From c81389741fea5fe666a99d458d9560d37a50c038 Mon Sep 17 00:00:00 2001 From: Jacob Trimble Date: Tue, 7 May 2019 13:34:28 -0700 Subject: [PATCH] Prefer const over let. A coming update to the Google eslint config will require using "const" over "let". This makes that one change to isolate the big changes. Change-Id: I7d0974c3ae15c53cc45a6b07bf9f6586e2d34aca --- .eslintrc.js | 1 + demo/asset_card.js | 2 +- demo/cast_receiver/receiver_app.js | 4 +- demo/common/asset.js | 10 +- demo/config.js | 4 +- demo/demo_utils.js | 24 +- demo/input.js | 2 +- demo/main.js | 16 +- demo/search.js | 6 +- lib/abr/ewma.js | 6 +- lib/abr/ewma_bandwidth_estimator.js | 4 +- lib/abr/simple_abr_manager.js | 20 +- lib/cast/cast_proxy.js | 56 ++-- lib/cast/cast_receiver.js | 107 +++---- lib/cast/cast_sender.js | 56 ++-- lib/cast/cast_utils.js | 8 +- lib/dash/content_protection.js | 10 +- lib/dash/dash_parser.js | 216 ++++++++------- lib/dash/mpd_utils.js | 66 ++--- lib/dash/segment_base.js | 51 ++-- lib/dash/segment_list.js | 28 +- lib/dash/segment_template.js | 80 +++--- lib/debug/asserts.js | 2 +- lib/debug/log.js | 4 +- lib/hls/hls_classes.js | 6 +- lib/hls/hls_parser.js | 203 +++++++------- lib/hls/hls_utils.js | 8 +- lib/hls/manifest_text_parser.js | 4 +- lib/media/drm_engine.js | 104 +++---- lib/media/gap_jumping_controller.js | 17 +- lib/media/manifest_parser.js | 16 +- lib/media/media_source_engine.js | 56 ++-- lib/media/mp4_segment_index_parser.js | 16 +- lib/media/playhead.js | 32 +-- lib/media/presentation_timeline.js | 12 +- lib/media/segment_index.js | 22 +- lib/media/streaming_engine.js | 182 ++++++------ lib/media/time_ranges_utils.js | 2 +- lib/media/transmuxer.js | 14 +- lib/media/webm_segment_index_parser.js | 54 ++-- lib/net/backoff.js | 6 +- lib/net/data_uri_plugin.js | 16 +- lib/net/http_fetch_plugin.js | 6 +- lib/net/http_plugin_utils.js | 4 +- lib/net/http_xhr_plugin.js | 14 +- lib/net/networking_engine.js | 32 +-- lib/offline/indexeddb/db_connection.js | 5 +- lib/offline/indexeddb/storage_mechanism.js | 10 +- lib/offline/indexeddb/v1_storage_cell.js | 32 +-- lib/offline/indexeddb/v2_storage_cell.js | 30 +- lib/offline/manifest_converter.js | 26 +- lib/offline/offline_scheme.js | 4 +- lib/offline/offline_uri.js | 10 +- lib/offline/storage.js | 30 +- lib/offline/stored_content_utils.js | 24 +- lib/offline/stream_bandwidth_estimator.js | 14 +- lib/player.js | 117 ++++---- lib/polyfill/fullscreen.js | 4 +- lib/polyfill/mathround.js | 4 +- lib/polyfill/mediasource.js | 52 ++-- lib/polyfill/patchedmediakeys_ms.js | 47 ++-- lib/polyfill/patchedmediakeys_webkit.js | 85 +++--- lib/polyfill/video_play_promise.js | 2 +- lib/polyfill/videoplaybackquality.js | 2 +- lib/polyfill/vttcue.js | 4 +- lib/text/mp4_vtt_parser.js | 26 +- lib/text/simple_text_displayer.js | 22 +- lib/text/text_engine.js | 12 +- lib/text/ttml_text_parser.js | 126 ++++----- lib/text/vtt_text_parser.js | 36 +-- lib/util/abortable_operation.js | 4 +- lib/util/array_utils.js | 4 +- lib/util/config_utils.js | 10 +- lib/util/data_view_reader.js | 16 +- lib/util/ebml_parser.js | 22 +- lib/util/error.js | 4 +- lib/util/event_manager.js | 8 +- lib/util/fake_event.js | 2 +- lib/util/fake_event_target.js | 2 +- lib/util/manifest_parser_utils.js | 2 +- lib/util/mp4_parser.js | 30 +- lib/util/multi_map.js | 10 +- lib/util/object_utils.js | 8 +- lib/util/operation_manager.js | 2 +- lib/util/pssh.js | 10 +- lib/util/stream_utils.js | 38 +-- lib/util/string_utils.js | 26 +- lib/util/text_parser.js | 6 +- lib/util/uint8array_utils.js | 12 +- lib/util/xml_utils.js | 42 +-- test/abr/simple_abr_manager_unit.js | 40 +-- test/assumptions/uint8_array_unit.js | 6 +- test/cast/cast_proxy_unit.js | 68 ++--- test/cast/cast_receiver_integration.js | 28 +- test/cast/cast_receiver_unit.js | 84 +++--- test/cast/cast_sender_unit.js | 84 +++--- test/cast/cast_utils_unit.js | 67 ++--- .../dash_parser_content_protection_unit.js | 133 ++++----- test/dash/dash_parser_live_unit.js | 185 +++++++------ test/dash/dash_parser_manifest_unit.js | 180 ++++++------ test/dash/dash_parser_segment_base_unit.js | 44 +-- test/dash/dash_parser_segment_list_unit.js | 52 ++-- .../dash/dash_parser_segment_template_unit.js | 80 +++--- test/dash/mpd_utils_unit.js | 184 +++++++------ test/hls/hls_live_unit.js | 95 +++---- test/hls/hls_parser_unit.js | 130 ++++----- test/hls/manifest_text_parser_unit.js | 16 +- test/media/drm_engine_integration.js | 29 +- test/media/drm_engine_unit.js | 260 +++++++++--------- test/media/media_source_engine_integration.js | 22 +- test/media/media_source_engine_unit.js | 100 +++---- test/media/mp4_segment_index_parser_unit.js | 12 +- test/media/playhead_unit.js | 8 +- test/media/presentation_timeline_unit.js | 60 ++-- test/media/segment_index_unit.js | 102 +++---- test/media/segment_reference_unit.js | 4 +- test/media/streaming_engine_integration.js | 36 +-- test/media/streaming_engine_unit.js | 107 +++---- test/media/time_ranges_utils_unit.js | 16 +- test/media/transmuxer_integration.js | 26 +- test/media/webm_segment_index_parser_unit.js | 16 +- test/net/data_uri_plugin_unit.js | 7 +- test/net/http_plugin_unit.js | 32 +-- test/net/networking_engine_unit.js | 170 ++++++------ test/offline/indexeddb_storage_unit.js | 12 +- test/offline/manifest_convert_unit.js | 62 ++--- test/offline/offline_integration.js | 22 +- test/offline/offline_manifest_parser_unit.js | 48 ++-- test/offline/offline_scheme_unit.js | 18 +- test/offline/offline_uri_unit.js | 20 +- test/offline/storage_unit.js | 146 +++++----- test/offline/v1_indexeddb_storage_unit.js | 60 ++-- test/player_external.js | 10 +- test/player_integration.js | 20 +- test/player_unit.js | 216 +++++++-------- test/test/boot.js | 8 +- test/test/util/dash_parser_util.js | 66 ++--- test/test/util/fake_media_source_engine.js | 26 +- test/test/util/indexeddb_utils.js | 14 +- test/test/util/jasmine_fetch.js | 42 +-- test/test/util/manifest_generator.js | 117 ++++---- test/test/util/manifest_parser_util.js | 16 +- test/test/util/offline_utils.js | 10 +- test/test/util/simple_fakes.js | 30 +- test/test/util/simple_idb.js | 18 +- test/test/util/stream_generator.js | 48 ++-- test/test/util/streaming_engine_util.js | 39 +-- test/test/util/test_scheme.js | 50 ++-- test/test/util/util.js | 40 +-- test/text/cue_integration.js | 6 +- test/text/mp4_ttml_parser_unit.js | 24 +- test/text/mp4_vtt_parser_unit.js | 42 +-- test/text/simple_text_displayer_unit.js | 24 +- test/text/text_engine_unit.js | 10 +- test/text/text_track_integration.js | 4 +- test/text/ttml_text_parser_unit.js | 18 +- test/text/vtt_text_parser_unit.js | 12 +- test/ui/ui_unit.js | 40 +-- test/util/abortable_operation_unit.js | 151 +++++----- test/util/data_view_reader_unit.js | 70 ++--- test/util/ebml_parser_unit.js | 105 +++---- test/util/event_manager_unit.js | 32 +-- test/util/fake_event_target_unit.js | 20 +- test/util/manifest_parser_utils_unit.js | 30 +- test/util/mp4_parser_unit.js | 48 ++-- test/util/object_utils_unit.js | 10 +- test/util/pssh_unit.js | 24 +- test/util/stream_utils_unit.js | 32 +-- test/util/string_utils_unit.js | 52 ++-- test/util/text_parser_unit.js | 50 ++-- test/util/xml_utils_unit.js | 60 ++-- ui/controls.js | 34 +-- ui/language_utils.js | 4 +- ui/overflow_menu.js | 2 +- ui/presentation_time.js | 16 +- ui/resolution_selection.js | 2 +- ui/ui_utils.js | 4 +- ui/volume_bar.js | 2 +- 178 files changed, 3602 insertions(+), 3558 deletions(-) diff --git a/.eslintrc.js b/.eslintrc.js index 4935633b62..3cc6f07225 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -63,6 +63,7 @@ module.exports = { "brace-style": ["error", "1tbs", { "allowSingleLine": true }], "key-spacing": ["error", {"beforeColon": false, "afterColon": true}], "no-multi-spaces": ["error", { "ignoreEOLComments": true }], + "prefer-const": ["error", {"ignoreReadBeforeAssign": true}], // }}} // "Possible error" rules in "eslint:recommended" that need options: {{{ diff --git a/demo/asset_card.js b/demo/asset_card.js index 4b8fa3b38e..cb0943d38d 100644 --- a/demo/asset_card.js +++ b/demo/asset_card.js @@ -128,7 +128,7 @@ class AssetCard { } } - for (let drm of asset.drm) { + for (const drm of asset.drm) { switch (drm) { case KeySystem.WIDEVINE: this.addFeatureIcon_('widevine', 'Widevine DRM'); diff --git a/demo/cast_receiver/receiver_app.js b/demo/cast_receiver/receiver_app.js index 166f1abd09..5216eaab60 100644 --- a/demo/cast_receiver/receiver_app.js +++ b/demo/cast_receiver/receiver_app.js @@ -63,13 +63,13 @@ ShakaReceiver.prototype.init = function() { shaka.polyfill.installAll(); /** @type {HTMLMediaElement} */ - let video = /** @type {HTMLMediaElement} */ + const video = /** @type {HTMLMediaElement} */ (document.getElementById('video')); goog.asserts.assert(video, 'Video element should be available!'); this.video_ = video; /** @type {!shaka.ui.Overlay} */ - let ui = this.video_['ui']; + const ui = this.video_['ui']; goog.asserts.assert(ui, 'UI should be available!'); // Make sure we don't show extra UI elements we don't need on the TV. diff --git a/demo/common/asset.js b/demo/common/asset.js index a5c88ba0aa..bcf503ce59 100644 --- a/demo/common/asset.js +++ b/demo/common/asset.js @@ -251,14 +251,14 @@ const ShakaDemoAssetInfo = class { // Construct a generic object with the values of this object, but with the // proper formatting. const raw = {}; - for (let key in this) { + for (const key in this) { const value = this[key]; if (value instanceof Map) { // The built-in JSON functions cannot convert Maps; this converts Maps // to objects. const replacement = {}; replacement['__type__'] = 'map'; - for (let entry of value.entries()) { + for (const entry of value.entries()) { replacement[entry[0]] = entry[1]; } raw[key] = replacement; @@ -317,7 +317,7 @@ const ShakaDemoAssetInfo = class { }); } if (this.extraConfig) { - for (let key in this.extraConfig) { + for (const key in this.extraConfig) { config[key] = this.extraConfig[key]; } } @@ -361,11 +361,11 @@ const ShakaDemoAssetInfo = class { static fromJSON(raw) { // This handles the special case for Maps in toJSON. const parsed = {}; - for (let key in raw) { + for (const key in raw) { const value = raw[key]; if (value && typeof value == 'object' && value['__type__'] == 'map') { const replacement = new Map(); - for (let key in value) { + for (const key in value) { if (key != '__type__') { replacement.set(key, value[key]); } diff --git a/demo/config.js b/demo/config.js index e9d8f126b7..a83bab2f8c 100644 --- a/demo/config.js +++ b/demo/config.js @@ -139,7 +139,7 @@ class ShakaDemoConfig { // All robustness fields of a given type are set at once. this.addDatalistInput_(name, robustnessSuggestions, (input) => { // Add in any common drmSystem not currently in advanced. - for (let drmSystem of commonDrmSystems) { + for (const drmSystem of commonDrmSystems) { if (!(drmSystem in advanced)) { advanced[commonDrmSystems] = { distinctiveIdentifierRequired: false, @@ -152,7 +152,7 @@ class ShakaDemoConfig { } } // Set the robustness. - for (let drmSystem in advanced) { + for (const drmSystem in advanced) { advanced[drmSystem][valueName] = input.value; } shakaDemoMain.configure('drm.advanced', advanced); diff --git a/demo/demo_utils.js b/demo/demo_utils.js index 5c946fb738..da70fe59b4 100644 --- a/demo/demo_utils.js +++ b/demo/demo_utils.js @@ -17,7 +17,7 @@ /** @namespace */ -let ShakaDemoUtils = {}; +const ShakaDemoUtils = {}; /** * Goes through the various values in shaka.extern.PlayerConfiguration, and @@ -37,8 +37,8 @@ ShakaDemoUtils.runThroughHashParams = (callback, config) => { // This exists for legacy reasons; the previous demo page had some hash values // set to names that did not match the names of their corresponding config // object name. - let overridden = []; - let configOverride = (hashName, configName) => { + const overridden = []; + const configOverride = (hashName, configName) => { overridden.push(configName); callback(hashName, configName); }; @@ -58,16 +58,16 @@ ShakaDemoUtils.runThroughHashParams = (callback, config) => { // This is to remove ambiguity in situations where there are two objects in // the config that share a key with the same name, without wasting space by // pointlessly adding namespace information to every value. - let added = []; - let collisions = []; - let findCollisions = (object) => { - for (let key in object) { + const added = []; + const collisions = []; + const findCollisions = (object) => { + for (const key in object) { if (added.includes(key) && !collisions.includes(key)) { collisions.push(key); } added.push(key); - let value = object[key]; + const value = object[key]; if (typeof value != 'number' && typeof value != 'string' && typeof value != 'boolean') { findCollisions(value); @@ -82,16 +82,16 @@ ShakaDemoUtils.runThroughHashParams = (callback, config) => { // discard any 'bufferBehind=' values from old hashes. // Now automatically do other config values. - let handleConfig = (object, accumulated) => { - for (let key in object) { + const handleConfig = (object, accumulated) => { + for (const key in object) { let hashName = key; - let configName = accumulated + key; + const configName = accumulated + key; if (overridden.includes(configName)) continue; if (collisions.includes(key)) { hashName = configName; } - let value = object[key]; + const value = object[key]; if (typeof value == 'number' || typeof value == 'string' || typeof value == 'boolean') { callback(hashName, configName); diff --git a/demo/input.js b/demo/input.js index 11aff232a8..82e8e7a599 100644 --- a/demo/input.js +++ b/demo/input.js @@ -114,7 +114,7 @@ class ShakaDemoSelectInput extends ShakaDemoInput { this.input_.classList.add('mdl-textfield__input'); this.extra_.classList.add('mdl-textfield__label'); this.extra_.setAttribute('for', this.input_.id); - for (let value of Object.keys(values)) { + for (const value of Object.keys(values)) { const option = document.createElement('option'); option.textContent = values[value]; option.value = value; diff --git a/demo/main.js b/demo/main.js index f706a71540..1dc4f27ea6 100644 --- a/demo/main.js +++ b/demo/main.js @@ -198,7 +198,7 @@ class ShakaDemoMain { const localization = this.controls_.getLocalization(); const UNKNOWN_LOCALES = shaka.ui.Localization.UNKNOWN_LOCALES; localization.addEventListener(UNKNOWN_LOCALES, (event) => { - for (let locale of event['locales']) { + for (const locale of event['locales']) { this.loadUILocale_(locale); } }); @@ -458,7 +458,7 @@ class ShakaDemoMain { } // Does the asset contain a playable mime type? - let mimeTypes = []; + const mimeTypes = []; if (asset.features.includes(shakaAssets.Feature.WEBM)) { mimeTypes.push('video/webm'); } @@ -516,7 +516,7 @@ class ShakaDemoMain { const obj = await response.json(); const map = new Map(); - for (let key in obj) { + for (const key in obj) { map.set(key, obj[key]); } @@ -873,7 +873,7 @@ class ShakaDemoMain { params.push('uilang=' + this.getUILocale()); const navButtons = document.getElementById('nav-button-container'); - for (let button of navButtons.childNodes) { + for (const button of navButtons.childNodes) { if (button.nodeType == Node.ELEMENT_NODE && button.classList.contains('mdl-button--accent')) { params.push('panel=' + button.textContent); @@ -980,12 +980,12 @@ class ShakaDemoMain { // Add a click listener to display this container, and hide the others. const switchPage = () => { // This element should be the selected one. - for (let child of navButtons.childNodes) { + for (const child of navButtons.childNodes) { if (child.nodeType == Node.ELEMENT_NODE) { child.classList.remove('mdl-button--accent'); } } - for (let child of contents.childNodes) { + for (const child of contents.childNodes) { if (child.nodeType == Node.ELEMENT_NODE) { this.hideNode_(child); } @@ -1023,7 +1023,7 @@ class ShakaDemoMain { setUpVersionString_() { const version = shaka.Player.version; let split = version.split('-'); - let inParen = []; + const inParen = []; // Separate out some special terms into parentheses after the rest of the // version, to make them stand out visually. @@ -1125,7 +1125,7 @@ class ShakaDemoMain { } -let shakaDemoMain = new ShakaDemoMain(); +const shakaDemoMain = new ShakaDemoMain(); /** diff --git a/demo/search.js b/demo/search.js index eaa18e31e4..a693eb2f9a 100644 --- a/demo/search.js +++ b/demo/search.js @@ -128,7 +128,7 @@ class ShakaDemoSearch { break; case ShakaDemoSearch.TermType.FEATURE: // Only this term should be in the desired features. - for (let term of others) { + for (const term of others) { const index = this.desiredFeatures_.indexOf( /** @type {shakaAssets.Feature} */ (term)); if (index != -1) { @@ -208,7 +208,7 @@ class ShakaDemoSearch { searchContainer.addRow(null, null); const nullOption = 'Unspecified'; const valuesObject = {}; - for (let term of choices) { + for (const term of choices) { if (type == 'DRM') { // The internal names of the keysystems aren't very readable, so use a // common name instead. @@ -304,7 +304,7 @@ class ShakaDemoSearch { if (this.desiredSource_ && asset.source != this.desiredSource_) { return false; } - for (let feature of this.desiredFeatures_) { + for (const feature of this.desiredFeatures_) { if (feature == shakaAssets.Feature.STORED) { if (!asset.isStored()) { return false; diff --git a/lib/abr/ewma.js b/lib/abr/ewma.js index 1928d1bfb2..bfd56aeec0 100644 --- a/lib/abr/ewma.js +++ b/lib/abr/ewma.js @@ -53,8 +53,8 @@ shaka.abr.Ewma = function(halfLife) { * @param {number} value */ shaka.abr.Ewma.prototype.sample = function(weight, value) { - let adjAlpha = Math.pow(this.alpha_, weight); - let newEstimate = value * (1 - adjAlpha) + adjAlpha * this.estimate_; + const adjAlpha = Math.pow(this.alpha_, weight); + const newEstimate = value * (1 - adjAlpha) + adjAlpha * this.estimate_; if (!isNaN(newEstimate)) { this.estimate_ = newEstimate; @@ -67,6 +67,6 @@ shaka.abr.Ewma.prototype.sample = function(weight, value) { * @return {number} */ shaka.abr.Ewma.prototype.getEstimate = function() { - let zeroFactor = 1 - Math.pow(this.alpha_, this.totalWeight_); + const zeroFactor = 1 - Math.pow(this.alpha_, this.totalWeight_); return this.estimate_ / zeroFactor; }; diff --git a/lib/abr/ewma_bandwidth_estimator.js b/lib/abr/ewma_bandwidth_estimator.js index d241812a11..b8b691b47f 100644 --- a/lib/abr/ewma_bandwidth_estimator.js +++ b/lib/abr/ewma_bandwidth_estimator.js @@ -89,8 +89,8 @@ shaka.abr.EwmaBandwidthEstimator.prototype.sample = function( return; } - let bandwidth = 8000 * numBytes / durationMs; - let weight = durationMs / 1000; + const bandwidth = 8000 * numBytes / durationMs; + const weight = durationMs / 1000; this.bytesSampled_ += numBytes; this.fast_.sample(weight, bandwidth); diff --git a/lib/abr/simple_abr_manager.js b/lib/abr/simple_abr_manager.js index 01eecd98e8..f28e7628d1 100644 --- a/lib/abr/simple_abr_manager.js +++ b/lib/abr/simple_abr_manager.js @@ -112,7 +112,7 @@ shaka.abr.SimpleAbrManager.prototype.chooseVariant = function() { // Get sorted Variants. let sortedVariants = SimpleAbrManager.filterAndSortVariants_( this.config_.restrictions, this.variants_); - let currentBandwidth = this.bandwidthEstimator_.getBandwidthEstimate( + const currentBandwidth = this.bandwidthEstimator_.getBandwidthEstimate( this.config_.defaultBandwidthEstimate); if (this.variants_.length && !sortedVariants.length) { @@ -131,12 +131,12 @@ shaka.abr.SimpleAbrManager.prototype.chooseVariant = function() { let chosen = sortedVariants[0] || null; for (let i = 0; i < sortedVariants.length; ++i) { - let variant = sortedVariants[i]; - let nextVariant = sortedVariants[i + 1] || {bandwidth: Infinity}; + const variant = sortedVariants[i]; + const nextVariant = sortedVariants[i + 1] || {bandwidth: Infinity}; - let minBandwidth = variant.bandwidth / + const minBandwidth = variant.bandwidth / this.config_.bandwidthDowngradeTarget; - let maxBandwidth = nextVariant.bandwidth / + const maxBandwidth = nextVariant.bandwidth / this.config_.bandwidthUpgradeTarget; shaka.log.v2('Bandwidth ranges:', (variant.bandwidth / 1e6).toFixed(3), @@ -238,18 +238,18 @@ shaka.abr.SimpleAbrManager.prototype.suggestStreams_ = function() { this.startupComplete_ = true; } else { // Check if we've left the switch interval. - let now = Date.now(); - let delta = now - this.lastTimeChosenMs_; + const now = Date.now(); + const delta = now - this.lastTimeChosenMs_; if (delta < this.config_.switchInterval * 1000) { shaka.log.v2('Still within switch interval...'); return; } } - let chosenVariant = this.chooseVariant(); - let bandwidthEstimate = this.bandwidthEstimator_.getBandwidthEstimate( + const chosenVariant = this.chooseVariant(); + const bandwidthEstimate = this.bandwidthEstimator_.getBandwidthEstimate( this.config_.defaultBandwidthEstimate); - let currentBandwidthKbps = Math.round(bandwidthEstimate / 1000.0); + const currentBandwidthKbps = Math.round(bandwidthEstimate / 1000.0); shaka.log.debug( 'Calling switch_(), bandwidth=' + currentBandwidthKbps + ' kbps'); diff --git a/lib/cast/cast_proxy.js b/lib/cast/cast_proxy.js index 82a1c777a7..2b51a867de 100644 --- a/lib/cast/cast_proxy.js +++ b/lib/cast/cast_proxy.js @@ -191,7 +191,7 @@ shaka.cast.CastProxy.prototype.receiverName = function() { * @export */ shaka.cast.CastProxy.prototype.cast = function() { - let initState = this.getInitState_(); + const initState = this.getInitState_(); // TODO: transfer manually-selected tracks? // TODO: transfer side-loaded text tracks? @@ -258,7 +258,7 @@ shaka.cast.CastProxy.prototype.init_ = function() { // We would like to use Proxy here, but it is not supported on IE11 or Safari. this.videoProxy_ = {}; - for (let k in this.localVideo_) { + for (const k in this.localVideo_) { Object.defineProperty(this.videoProxy_, k, { configurable: false, enumerable: true, @@ -268,7 +268,7 @@ shaka.cast.CastProxy.prototype.init_ = function() { } this.playerProxy_ = {}; - for (let k in /** @type {Object} */(this.localPlayer_)) { + for (const k in /** @type {Object} */(this.localPlayer_)) { Object.defineProperty(this.playerProxy_, k, { configurable: false, enumerable: true, @@ -292,7 +292,7 @@ shaka.cast.CastProxy.prototype.init_ = function() { * @private */ shaka.cast.CastProxy.prototype.getInitState_ = function() { - let initState = { + const initState = { 'video': {}, 'player': {}, 'playerAfterLoad': {}, @@ -314,17 +314,17 @@ shaka.cast.CastProxy.prototype.getInitState_ = function() { } shaka.cast.CastUtils.PlayerInitState.forEach(function(pair) { - let getter = pair[0]; - let setter = pair[1]; - let value = /** @type {Object} */(this.localPlayer_)[getter](); + const getter = pair[0]; + const setter = pair[1]; + const value = /** @type {Object} */(this.localPlayer_)[getter](); initState['player'][setter] = value; }.bind(this)); shaka.cast.CastUtils.PlayerInitAfterLoadState.forEach(function(pair) { - let getter = pair[0]; - let setter = pair[1]; - let value = /** @type {Object} */(this.localPlayer_)[getter](); + const getter = pair[0]; + const setter = pair[1]; + const value = /** @type {Object} */(this.localPlayer_)[getter](); initState['playerAfterLoad'][setter] = value; }.bind(this)); @@ -338,7 +338,7 @@ shaka.cast.CastProxy.prototype.getInitState_ = function() { * @private */ shaka.cast.CastProxy.prototype.onCastStatusChanged_ = function() { - let event = new shaka.util.FakeEvent('caststatuschanged'); + const event = new shaka.util.FakeEvent('caststatuschanged'); this.dispatchEvent(event); }; @@ -349,8 +349,8 @@ shaka.cast.CastProxy.prototype.onCastStatusChanged_ = function() { * @private */ shaka.cast.CastProxy.prototype.onFirstCastStateUpdate_ = function() { - let type = this.videoProxy_.paused ? 'pause' : 'play'; - let fakeEvent = new shaka.util.FakeEvent(type); + const type = this.videoProxy_.paused ? 'pause' : 'play'; + const fakeEvent = new shaka.util.FakeEvent(type); this.videoEventTarget_.dispatchEvent(fakeEvent); }; @@ -362,18 +362,18 @@ shaka.cast.CastProxy.prototype.onFirstCastStateUpdate_ = function() { shaka.cast.CastProxy.prototype.onResumeLocal_ = function() { // Transfer back the player state. shaka.cast.CastUtils.PlayerInitState.forEach(function(pair) { - let getter = pair[0]; - let setter = pair[1]; - let value = this.sender_.get('player', getter)(); + const getter = pair[0]; + const setter = pair[1]; + const value = this.sender_.get('player', getter)(); /** @type {Object} */(this.localPlayer_)[setter](value); }.bind(this)); // Get the most recent manifest URI and ended state. - let assetUri = this.sender_.get('player', 'getAssetUri')(); - let ended = this.sender_.get('video', 'ended'); + const assetUri = this.sender_.get('player', 'getAssetUri')(); + const ended = this.sender_.get('video', 'ended'); let manifestReady = Promise.resolve(); - let autoplay = this.localVideo_.autoplay; + const autoplay = this.localVideo_.autoplay; let startTime = null; @@ -391,7 +391,7 @@ shaka.cast.CastProxy.prototype.onResumeLocal_ = function() { } // Get the video state into a temp variable since we will apply it async. - let videoState = {}; + const videoState = {}; shaka.cast.CastUtils.VideoInitStateAttributes.forEach(function(name) { videoState[name] = this.sender_.get('video', name); }.bind(this)); @@ -408,9 +408,9 @@ shaka.cast.CastProxy.prototype.onResumeLocal_ = function() { }.bind(this)); shaka.cast.CastUtils.PlayerInitAfterLoadState.forEach(function(pair) { - let getter = pair[0]; - let setter = pair[1]; - let value = this.sender_.get('player', getter)(); + const getter = pair[0]; + const setter = pair[1]; + const value = this.sender_.get('player', getter)(); /** @type {Object} */(this.localPlayer_)[setter](value); }.bind(this)); @@ -424,7 +424,7 @@ shaka.cast.CastProxy.prototype.onResumeLocal_ = function() { // Pass any errors through to the app. goog.asserts.assert(error instanceof shaka.util.Error, 'Wrong error type!'); - let event = new shaka.util.FakeEvent('error', {'detail': error}); + const event = new shaka.util.FakeEvent('error', {'detail': error}); this.localPlayer_.dispatchEvent(event); }); }; @@ -448,7 +448,7 @@ shaka.cast.CastProxy.prototype.videoProxyGet_ = function(name) { // If we are casting, but the first update has not come in yet, use local // values, but not local methods. if (this.sender_.isCasting() && !this.sender_.hasRemoteProperties()) { - let value = this.localVideo_[name]; + const value = this.localVideo_[name]; if (typeof value != 'function') { return value; } @@ -496,7 +496,7 @@ shaka.cast.CastProxy.prototype.videoProxyLocalEvent_ = function(event) { // Convert this real Event into a FakeEvent for dispatch from our // FakeEventListener. - let fakeEvent = new shaka.util.FakeEvent(event.type, event); + const fakeEvent = new shaka.util.FakeEvent(event.type, event); this.videoEventTarget_.dispatchEvent(fakeEvent); }; @@ -566,7 +566,7 @@ shaka.cast.CastProxy.prototype.playerProxyGet_ = function(name) { // getters, but not local methods. if (this.sender_.isCasting() && !this.sender_.hasRemoteProperties()) { if (shaka.cast.CastUtils.PlayerGetterMethods[name]) { - let value = /** @type {Object} */(this.localPlayer_)[name]; + const value = /** @type {Object} */(this.localPlayer_)[name]; goog.asserts.assert(typeof value == 'function', 'only methods on Player'); return value.bind(this.localPlayer_); } @@ -574,7 +574,7 @@ shaka.cast.CastProxy.prototype.playerProxyGet_ = function(name) { // Use local getters and methods if we are not casting. if (!this.sender_.isCasting()) { - let value = /** @type {Object} */(this.localPlayer_)[name]; + const value = /** @type {Object} */(this.localPlayer_)[name]; goog.asserts.assert(typeof value == 'function', 'only methods on Player'); return value.bind(this.localPlayer_); } diff --git a/lib/cast/cast_receiver.js b/lib/cast/cast_receiver.js index c5eeb8f7f8..c7bb586aed 100644 --- a/lib/cast/cast_receiver.js +++ b/lib/cast/cast_receiver.js @@ -164,7 +164,7 @@ shaka.cast.CastReceiver.prototype.destroy = async function() { /** @private */ shaka.cast.CastReceiver.prototype.init_ = function() { - let manager = cast.receiver.CastReceiverManager.getInstance(); + const manager = cast.receiver.CastReceiverManager.getInstance(); manager.onSenderConnected = this.onSendersChanged_.bind(this); manager.onSenderDisconnected = this.onSendersChanged_.bind(this); manager.onSystemVolumeChanged = this.fakeVolumeChangeEvent_.bind(this); @@ -267,7 +267,7 @@ shaka.cast.CastReceiver.prototype.onSendersChanged_ = function() { // result in new data being loaded. this.initialStatusUpdatePending_ = true; - let manager = cast.receiver.CastReceiverManager.getInstance(); + const manager = cast.receiver.CastReceiverManager.getInstance(); this.isConnected_ = manager.getSenders().length != 0; this.onCastStatusChanged_(); }; @@ -287,7 +287,7 @@ shaka.cast.CastReceiver.prototype.onCastStatusChanged_ = function() { return; } - let event = new shaka.util.FakeEvent('caststatuschanged'); + const event = new shaka.util.FakeEvent('caststatuschanged'); this.dispatchEvent(event); // Send a media status message, with a media info message if appropriate. if (!this.maybeSendMediaInfoMessage_()) { @@ -305,8 +305,8 @@ shaka.cast.CastReceiver.prototype.onCastStatusChanged_ = function() { */ shaka.cast.CastReceiver.prototype.initState_ = function(initState, appData) { // Take on player state first. - for (let k in initState['player']) { - let v = initState['player'][k]; + for (const k in initState['player']) { + const v = initState['player'][k]; // All player state vars are setters to be called. /** @type {Object} */(this.player_)[k](v); } @@ -315,7 +315,7 @@ shaka.cast.CastReceiver.prototype.initState_ = function(initState, appData) { this.appDataCallback_(appData); let manifestReady = Promise.resolve(); - let autoplay = this.video_.autoplay; + const autoplay = this.video_.autoplay; // Now load the manifest, if present. if (initState['manifest']) { @@ -332,13 +332,13 @@ shaka.cast.CastReceiver.prototype.initState_ = function(initState, appData) { return; } - for (let k in initState['video']) { - let v = initState['video'][k]; + for (const k in initState['video']) { + const v = initState['video'][k]; this.video_[k] = v; } - for (let k in initState['playerAfterLoad']) { - let v = initState['playerAfterLoad'][k]; + for (const k in initState['playerAfterLoad']) { + const v = initState['playerAfterLoad'][k]; // All player state vars are setters to be called. /** @type {Object} */(this.player_)[k](v); } @@ -355,7 +355,7 @@ shaka.cast.CastReceiver.prototype.initState_ = function(initState, appData) { // Pass any errors through to the app. goog.asserts.assert(error instanceof shaka.util.Error, 'Wrong error type!'); - let event = new shaka.util.FakeEvent('error', {'detail': error}); + const event = new shaka.util.FakeEvent('error', {'detail': error}); this.player_.dispatchEvent(event); }); }; @@ -392,7 +392,7 @@ shaka.cast.CastReceiver.prototype.pollAttributes_ = function() { // polling too often. this.pollTimer_.tickAfter(/* seconds= */ 0.5); - let update = { + const update = { 'video': {}, 'player': {}, }; @@ -406,24 +406,25 @@ shaka.cast.CastReceiver.prototype.pollAttributes_ = function() { // updates every ~20 updates to account for dropped messages. if (this.player_.isLive()) { - for (let name in shaka.cast.CastUtils.PlayerGetterMethodsThatRequireLive) { - let frequency = + for (const name in + shaka.cast.CastUtils.PlayerGetterMethodsThatRequireLive) { + const frequency = shaka.cast.CastUtils.PlayerGetterMethodsThatRequireLive[name]; if (this.updateNumber_ % frequency == 0) { update['player'][name] = /** @type {Object} */ (this.player_)[name](); } } } - for (let name in shaka.cast.CastUtils.PlayerGetterMethods) { - let frequency = shaka.cast.CastUtils.PlayerGetterMethods[name]; + for (const name in shaka.cast.CastUtils.PlayerGetterMethods) { + const frequency = shaka.cast.CastUtils.PlayerGetterMethods[name]; if (this.updateNumber_ % frequency == 0) { update['player'][name] = /** @type {Object} */ (this.player_)[name](); } } // Volume attributes are tied to the system volume. - let manager = cast.receiver.CastReceiverManager.getInstance(); - let systemVolume = manager.getSystemVolume(); + const manager = cast.receiver.CastReceiverManager.getInstance(); + const systemVolume = manager.getSystemVolume(); if (systemVolume) { update['video']['volume'] = systemVolume.level; update['video']['muted'] = systemVolume.muted; @@ -468,7 +469,7 @@ shaka.cast.CastReceiver.prototype.maybeSendMediaInfoMessage_ = function() { * @private */ shaka.cast.CastReceiver.prototype.sendMediaInfoMessage_ = function() { - let media = { + const media = { 'contentId': this.player_.getAssetUri(), 'streamType': this.player_.isLive() ? 'LIVE' : 'BUFFERED', 'duration': this.video_.duration, @@ -488,8 +489,8 @@ shaka.cast.CastReceiver.prototype.sendMediaInfoMessage_ = function() { */ shaka.cast.CastReceiver.prototype.fakeVolumeChangeEvent_ = function() { // Volume attributes are tied to the system volume. - let manager = cast.receiver.CastReceiverManager.getInstance(); - let systemVolume = manager.getSystemVolume(); + const manager = cast.receiver.CastReceiverManager.getInstance(); + const systemVolume = manager.getSystemVolume(); goog.asserts.assert(systemVolume, 'System volume should not be null!'); if (systemVolume) { @@ -521,7 +522,7 @@ shaka.cast.CastReceiver.prototype.fakeVolumeChangeEvent_ = function() { * @private */ shaka.cast.CastReceiver.prototype.onShakaMessage_ = function(event) { - let message = shaka.cast.CastUtils.deserialize(event.data); + const message = shaka.cast.CastUtils.deserialize(event.data); shaka.log.debug('CastReceiver: message', message); switch (message['type']) { @@ -545,13 +546,13 @@ shaka.cast.CastReceiver.prototype.onShakaMessage_ = function(event) { this.appDataCallback_(message['appData']); break; case 'set': { - let targetName = message['targetName']; - let property = message['property']; - let value = message['value']; + const targetName = message['targetName']; + const property = message['property']; + const value = message['value']; if (targetName == 'video') { // Volume attributes must be rerouted to the system. - let manager = cast.receiver.CastReceiverManager.getInstance(); + const manager = cast.receiver.CastReceiverManager.getInstance(); if (property == 'volume') { manager.setSystemVolumeLevel(value); break; @@ -565,25 +566,25 @@ shaka.cast.CastReceiver.prototype.onShakaMessage_ = function(event) { break; } case 'call': { - let targetName = message['targetName']; - let methodName = message['methodName']; - let args = message['args']; - let target = this.targets_[targetName]; + const targetName = message['targetName']; + const methodName = message['methodName']; + const args = message['args']; + const target = this.targets_[targetName]; target[methodName].apply(target, args); break; } case 'asyncCall': { - let targetName = message['targetName']; - let methodName = message['methodName']; + const targetName = message['targetName']; + const methodName = message['methodName']; if (targetName == 'player' && methodName == 'load') { // Reset update message frequency values after a load. this.updateNumber_ = 0; this.startUpdatingUpdateNumber_ = false; } - let args = message['args']; - let id = message['id']; - let senderId = event.senderId; - let target = this.targets_[targetName]; + const args = message['args']; + const id = message['id']; + const senderId = event.senderId; + const target = this.targets_[targetName]; let p = target[methodName].apply(target, args); if (targetName == 'player' && methodName == 'load') { // Wait until the manifest has actually loaded to send another media @@ -607,7 +608,7 @@ shaka.cast.CastReceiver.prototype.onShakaMessage_ = function(event) { * @private */ shaka.cast.CastReceiver.prototype.onGenericMessage_ = function(event) { - let message = shaka.cast.CastUtils.deserialize(event.data); + const message = shaka.cast.CastUtils.deserialize(event.data); shaka.log.debug('CastReceiver: message', message); // TODO(ismena): error message on duplicate request id from the same sender switch (message['type']) { @@ -623,8 +624,8 @@ shaka.cast.CastReceiver.prototype.onGenericMessage_ = function(event) { this.sendMediaStatus_(0); break; case 'SEEK': { - let currentTime = message['currentTime']; - let resumeState = message['resumeState']; + const currentTime = message['currentTime']; + const resumeState = message['resumeState']; if (currentTime != null) { this.video_.currentTime = Number(currentTime); } @@ -656,11 +657,11 @@ shaka.cast.CastReceiver.prototype.onGenericMessage_ = function(event) { this.sendMediaStatus_(Number(message['requestId'])); break; case 'VOLUME': { - let volumeObject = message['volume']; - let level = volumeObject['level']; - let muted = volumeObject['muted']; - let oldVolumeLevel = this.video_.volume; - let oldVolumeMuted = this.video_.muted; + const volumeObject = message['volume']; + const level = volumeObject['level']; + const muted = volumeObject['muted']; + const oldVolumeLevel = this.video_.volume; + const oldVolumeMuted = this.video_.muted; if (level != null) { this.video_.volume = Number(level); } @@ -680,11 +681,11 @@ shaka.cast.CastReceiver.prototype.onGenericMessage_ = function(event) { this.startUpdatingUpdateNumber_ = false; this.initialStatusUpdatePending_ = false; // This already sends an update. - let mediaInfo = message['media']; - let contentId = mediaInfo['contentId']; - let currentTime = message['currentTime']; - let assetUri = this.contentIdCallback_(contentId); - let autoplay = message['autoplay'] || true; + const mediaInfo = message['media']; + const contentId = mediaInfo['contentId']; + const currentTime = message['currentTime']; + const assetUri = this.contentIdCallback_(contentId); + const autoplay = message['autoplay'] || true; if (autoplay) { this.video_.autoplay = true; } @@ -761,7 +762,7 @@ shaka.cast.CastReceiver.prototype.sendMessage_ = // Cuts log spam when debugging the receiver UI in Chrome. if (!this.isConnected_) return; - let serialized = shaka.cast.CastUtils.serialize(message); + const serialized = shaka.cast.CastUtils.serialize(message); if (senderId) { bus.getCastChannel(senderId).send(serialized); } else { @@ -775,7 +776,7 @@ shaka.cast.CastReceiver.prototype.sendMessage_ = * @private */ shaka.cast.CastReceiver.prototype.getPlayState_ = function() { - let playState = shaka.cast.CastReceiver.PLAY_STATE; + const playState = shaka.cast.CastReceiver.PLAY_STATE; if (this.isIdle_) { return playState.IDLE; } else if (this.player_.isBuffering()) { @@ -795,7 +796,7 @@ shaka.cast.CastReceiver.prototype.getPlayState_ = function() { */ shaka.cast.CastReceiver.prototype.sendMediaStatus_ = function(requestId, media) { - let mediaStatus = { + const mediaStatus = { // mediaSessionId is a unique ID for the playback of this specific session. // It's used to identify a specific instance of a playback. // We don't support multiple playbacks, so just return 0. @@ -825,7 +826,7 @@ shaka.cast.CastReceiver.prototype.sendMediaStatus_ = mediaStatus['media'] = media; } - let ret = { + const ret = { 'requestId': requestId, 'type': 'MEDIA_STATUS', 'status': [mediaStatus], diff --git a/lib/cast/cast_sender.js b/lib/cast/cast_sender.js index e87252a18a..d77d1d4d1a 100644 --- a/lib/cast/cast_sender.js +++ b/lib/cast/cast_sender.js @@ -198,8 +198,8 @@ shaka.cast.CastSender.prototype.init = function() { this.apiReady_ = true; this.statusChangeTimer_.tickNow(); - let sessionRequest = new chrome.cast.SessionRequest(this.receiverAppId_); - let apiConfig = new chrome.cast.ApiConfig(sessionRequest, + const sessionRequest = new chrome.cast.SessionRequest(this.receiverAppId_); + const apiConfig = new chrome.cast.ApiConfig(sessionRequest, this.onExistingSessionJoined_.bind(this), this.onReceiverStatusChanged_.bind(this), 'origin_scoped'); @@ -216,7 +216,7 @@ shaka.cast.CastSender.prototype.init = function() { this.statusChangeTimer_.tickAfter(/* seconds= */ 0.02); } - let oldSession = shaka.cast.CastSender.session_; + const oldSession = shaka.cast.CastSender.session_; if (oldSession && oldSession.status != chrome.cast.SessionStatus.STOPPED) { // The old session still exists, so re-use it. shaka.log.debug('CastSender: re-using existing connection'); @@ -287,7 +287,7 @@ shaka.cast.CastSender.prototype.showDisconnectDialog = function() { if (!this.isCasting_) { return; } - let initState = this.onInitStateRequired_(); + const initState = this.onInitStateRequired_(); chrome.cast.requestSession( this.onSessionInitiated_.bind(this, initState), @@ -329,7 +329,7 @@ shaka.cast.CastSender.prototype.get = function(targetName, property) { } } else if (targetName == 'player') { if (CastUtils.PlayerGetterMethodsThatRequireLive[property]) { - let isLive = this.get('player', 'isLive')(); + const isLive = this.get('player', 'isLive')(); goog.asserts.assert(isLive, property + ' should be called on a live stream!'); // If the property shouldn't exist, return a fake function so that the @@ -466,8 +466,8 @@ shaka.cast.CastSender.prototype.remoteAsyncCall_ = goog.asserts.assert(targetName == 'video' || targetName == 'player', 'Unexpected target name'); - let p = new shaka.util.PublicPromise(); - let id = this.nextAsyncCallId_.toString(); + const p = new shaka.util.PublicPromise(); + const id = this.nextAsyncCallId_.toString(); this.nextAsyncCallId_++; this.asyncCallPromises_[id] = p; @@ -489,7 +489,7 @@ shaka.cast.CastSender.prototype.remoteAsyncCall_ = shaka.cast.CastSender.prototype.onExistingSessionJoined_ = function(session) { shaka.log.debug('CastSender: onExistingSessionJoined'); - let initState = this.onInitStateRequired_(); + const initState = this.onInitStateRequired_(); this.castPromise_ = new shaka.util.PublicPromise(); this.hasJoinedExistingSession_ = true; @@ -529,7 +529,7 @@ shaka.cast.CastSender.prototype.onSessionCreated_ = function(session) { * @private */ shaka.cast.CastSender.prototype.removeListeners_ = function() { - let session = shaka.cast.CastSender.session_; + const session = shaka.cast.CastSender.session_; session.removeUpdateListener(this.onConnectionStatusChangedBound_); session.removeMessageListener(shaka.cast.CastUtils.SHAKA_MESSAGE_NAMESPACE, this.onMessageReceivedBound_); @@ -540,7 +540,7 @@ shaka.cast.CastSender.prototype.removeListeners_ = function() { * @private */ shaka.cast.CastSender.prototype.onConnectionStatusChanged_ = function() { - let connected = shaka.cast.CastSender.session_ ? + const connected = shaka.cast.CastSender.session_ ? shaka.cast.CastSender.session_.status == 'connected' : false; shaka.log.debug('CastSender: connection status', connected); @@ -549,7 +549,7 @@ shaka.cast.CastSender.prototype.onConnectionStatusChanged_ = function() { this.onResumeLocal_(); // Clear whatever we have cached. - for (let targetName in this.cachedProperties_) { + for (const targetName in this.cachedProperties_) { this.cachedProperties_[targetName] = {}; } @@ -569,8 +569,8 @@ shaka.cast.CastSender.prototype.onConnectionStatusChanged_ = function() { * @private */ shaka.cast.CastSender.prototype.rejectAllPromises_ = function() { - for (let id in this.asyncCallPromises_) { - let p = this.asyncCallPromises_[id]; + for (const id in this.asyncCallPromises_) { + const p = this.asyncCallPromises_[id]; delete this.asyncCallPromises_[id]; // Reject pending async operations as if they were interrupted. @@ -593,22 +593,22 @@ shaka.cast.CastSender.prototype.onMessageReceived_ = // Since this method is in the compiled library, make sure all messages passed // in here were created with quoted property names. - let message = shaka.cast.CastUtils.deserialize(serialized); + const message = shaka.cast.CastUtils.deserialize(serialized); shaka.log.v2('CastSender: message', message); switch (message['type']) { case 'event': { - let targetName = message['targetName']; - let event = message['event']; - let fakeEvent = new shaka.util.FakeEvent(event['type'], event); + const targetName = message['targetName']; + const event = message['event']; + const fakeEvent = new shaka.util.FakeEvent(event['type'], event); this.onRemoteEvent_(targetName, fakeEvent); break; } case 'update': { - let update = message['update']; - for (let targetName in update) { - let target = this.cachedProperties_[targetName] || {}; - for (let property in update[targetName]) { + const update = message['update']; + for (const targetName in update) { + const target = this.cachedProperties_[targetName] || {}; + for (const property in update[targetName]) { target[property] = update[targetName][property]; } } @@ -619,9 +619,9 @@ shaka.cast.CastSender.prototype.onMessageReceived_ = break; } case 'asyncComplete': { - let id = message['id']; - let error = message['error']; - let p = this.asyncCallPromises_[id]; + const id = message['id']; + const error = message['error']; + const p = this.asyncCallPromises_[id]; delete this.asyncCallPromises_[id]; goog.asserts.assert(p, 'Unexpected async id'); @@ -629,9 +629,9 @@ shaka.cast.CastSender.prototype.onMessageReceived_ = if (error) { // This is a hacky way to reconstruct the serialized error. - let reconstructedError = new shaka.util.Error( + const reconstructedError = new shaka.util.Error( error.severity, error.category, error.code); - for (let k in error) { + for (const k in error) { (/** @type {Object} */(reconstructedError))[k] = error[k]; } p.reject(reconstructedError); @@ -652,9 +652,9 @@ shaka.cast.CastSender.prototype.sendMessage_ = function(message) { // Since this method is in the compiled library, make sure all messages passed // in here were created with quoted property names. - let serialized = shaka.cast.CastUtils.serialize(message); + const serialized = shaka.cast.CastUtils.serialize(message); // TODO: have never seen this fail. When would it and how should we react? - let session = shaka.cast.CastSender.session_; + const session = shaka.cast.CastSender.session_; session.sendMessage(shaka.cast.CastUtils.SHAKA_MESSAGE_NAMESPACE, serialized, function() {}, // success callback diff --git a/lib/cast/cast_utils.js b/lib/cast/cast_utils.js index 251768235a..5f01036aef 100644 --- a/lib/cast/cast_utils.js +++ b/lib/cast/cast_utils.js @@ -266,9 +266,9 @@ shaka.cast.CastUtils.serialize = function(thing) { // and other complex objects they contain, so we strip these out. // Note that using Object.keys or JSON.stringify directly on the event // will not capture its properties. We must use a for loop. - let simpleEvent = {}; - for (let eventKey in value) { - let eventValue = value[eventKey]; + const simpleEvent = {}; + for (const eventKey in value) { + const eventValue = value[eventKey]; if (eventValue && typeof eventValue == 'object') { if (eventKey == 'detail') { // Keep the detail value, because it contains important information @@ -344,7 +344,7 @@ shaka.cast.CastUtils.deserialize = function(str) { * @private */ shaka.cast.CastUtils.unpackTimeRanges_ = function(ranges) { - let obj = { + const obj = { '__type__': 'TimeRanges', // a signal to deserialize 'length': ranges.length, 'start': [], diff --git a/lib/dash/content_protection.js b/lib/dash/content_protection.js index ea5c335e6a..22741f24b4 100644 --- a/lib/dash/content_protection.js +++ b/lib/dash/content_protection.js @@ -129,7 +129,7 @@ shaka.dash.ContentProtection.parseFromAdaptationSet = function( elems, callback, ignoreDrmInfo) { const ContentProtection = shaka.dash.ContentProtection; const ManifestParserUtils = shaka.util.ManifestParserUtils; - let parsed = ContentProtection.parseElements_(elems); + const parsed = ContentProtection.parseElements_(elems); /** @type {Array.} */ let defaultInit = null; /** @type {!Array.} */ @@ -224,14 +224,14 @@ shaka.dash.ContentProtection.parseFromAdaptationSet = function( shaka.dash.ContentProtection.parseFromRepresentation = function( elems, callback, context, ignoreDrmInfo) { const ContentProtection = shaka.dash.ContentProtection; - let repContext = ContentProtection.parseFromAdaptationSet( + const repContext = ContentProtection.parseFromAdaptationSet( elems, callback, ignoreDrmInfo); if (context.firstRepresentation) { - let asUnknown = context.drmInfos.length == 1 && + const asUnknown = context.drmInfos.length == 1 && !context.drmInfos[0].keySystem; - let asUnencrypted = context.drmInfos.length == 0; - let repUnencrypted = repContext.drmInfos.length == 0; + const asUnencrypted = context.drmInfos.length == 0; + const repUnencrypted = repContext.drmInfos.length == 0; // There are two cases where we need to replace the |drmInfos| in the // context with those in the Representation: diff --git a/lib/dash/dash_parser.js b/lib/dash/dash_parser.js index 4dcd3520e6..703a7c45c7 100644 --- a/lib/dash/dash_parser.js +++ b/lib/dash/dash_parser.js @@ -405,12 +405,12 @@ shaka.dash.DashParser.prototype.onExpirationUpdated = function( */ shaka.dash.DashParser.prototype.requestManifest_ = function() { const requestType = shaka.net.NetworkingEngine.RequestType.MANIFEST; - let request = shaka.net.NetworkingEngine.makeRequest( + const request = shaka.net.NetworkingEngine.makeRequest( this.manifestUris_, this.config_.retryParameters); - let networkingEngine = this.playerInterface_.networkingEngine; + const networkingEngine = this.playerInterface_.networkingEngine; const startTime = Date.now(); - let operation = networkingEngine.request(requestType, request); + const operation = networkingEngine.request(requestType, request); this.operationManager_.manage(operation); return operation.promise.then((response) => { @@ -455,7 +455,7 @@ shaka.dash.DashParser.prototype.parseManifest_ = const Error = shaka.util.Error; const MpdUtils = shaka.dash.MpdUtils; - let mpd = shaka.util.XmlUtils.parseXml(data, 'MPD'); + const mpd = shaka.util.XmlUtils.parseXml(data, 'MPD'); if (!mpd) { throw new Error( Error.Severity.CRITICAL, Error.Category.MANIFEST, @@ -463,8 +463,8 @@ shaka.dash.DashParser.prototype.parseManifest_ = } // Process the mpd to account for xlink connections. - let failGracefully = this.config_.dash.xlinkFailGracefully; - let xlinkOperation = MpdUtils.processXlinks( + const failGracefully = this.config_.dash.xlinkFailGracefully; + const xlinkOperation = MpdUtils.processXlinks( mpd, this.config_.retryParameters, failGracefully, finalManifestUri, this.playerInterface_.networkingEngine); this.operationManager_.manage(xlinkOperation); @@ -494,7 +494,7 @@ shaka.dash.DashParser.prototype.processManifest_ = /** @type {!Array.} */ let manifestBaseUris = [finalManifestUri]; /** @type {!Array.} */ - let locations = XmlUtils.findChildren(mpd, 'Location') + const locations = XmlUtils.findChildren(mpd, 'Location') .map(XmlUtils.getContents) .filter(Functional.isNotNull); if (locations.length > 0) { @@ -504,11 +504,11 @@ shaka.dash.DashParser.prototype.processManifest_ = manifestBaseUris = absoluteLocations; } - let uris = XmlUtils.findChildren(mpd, 'BaseURL').map(XmlUtils.getContents); - let baseUris = shaka.util.ManifestParserUtils.resolveUris( + const uris = XmlUtils.findChildren(mpd, 'BaseURL').map(XmlUtils.getContents); + const baseUris = shaka.util.ManifestParserUtils.resolveUris( manifestBaseUris, uris); - let ignoreMinBufferTime = this.config_.dash.ignoreMinBufferTime; + const ignoreMinBufferTime = this.config_.dash.ignoreMinBufferTime; let minBufferTime; if (!ignoreMinBufferTime) { minBufferTime = @@ -518,15 +518,15 @@ shaka.dash.DashParser.prototype.processManifest_ = this.updatePeriod_ = /** @type {number} */ (XmlUtils.parseAttr( mpd, 'minimumUpdatePeriod', XmlUtils.parseDuration, -1)); - let presentationStartTime = XmlUtils.parseAttr( + const presentationStartTime = XmlUtils.parseAttr( mpd, 'availabilityStartTime', XmlUtils.parseDate); let segmentAvailabilityDuration = XmlUtils.parseAttr( mpd, 'timeShiftBufferDepth', XmlUtils.parseDuration); - let suggestedPresentationDelay = XmlUtils.parseAttr( + const suggestedPresentationDelay = XmlUtils.parseAttr( mpd, 'suggestedPresentationDelay', XmlUtils.parseDuration); - let maxSegmentDuration = XmlUtils.parseAttr( + const maxSegmentDuration = XmlUtils.parseAttr( mpd, 'maxSegmentDuration', XmlUtils.parseDuration); - let mpdType = mpd.getAttribute('type') || 'static'; + const mpdType = mpd.getAttribute('type') || 'static'; /** @type {!shaka.media.PresentationTimeline} */ let presentationTimeline; @@ -543,10 +543,10 @@ shaka.dash.DashParser.prototype.processManifest_ = // or 10s (configurable) whichever is larger. This is fairly conservative. // Content providers should provide a suggestedPresentationDelay // whenever possible to optimize the live streaming experience. - let defaultPresentationDelay = Math.max( + const defaultPresentationDelay = Math.max( this.config_.dash.defaultPresentationDelay, minBufferTime * 1.5); - let presentationDelay = suggestedPresentationDelay != null ? + const presentationDelay = suggestedPresentationDelay != null ? suggestedPresentationDelay : defaultPresentationDelay; presentationTimeline = new shaka.media.PresentationTimeline( presentationStartTime, presentationDelay, @@ -554,7 +554,7 @@ shaka.dash.DashParser.prototype.processManifest_ = } /** @type {shaka.dash.DashParser.Context} */ - let context = { + const context = { // Don't base on updatePeriod_ since emsg boxes can cause manifest updates. dynamic: mpdType != 'static', presentationTimeline: presentationTimeline, @@ -566,9 +566,9 @@ shaka.dash.DashParser.prototype.processManifest_ = indexRangeWarningGiven: false, }; - let periodsAndDuration = this.parsePeriods_(context, baseUris, mpd); - let duration = periodsAndDuration.duration; - let periods = periodsAndDuration.periods; + const periodsAndDuration = this.parsePeriods_(context, baseUris, mpd); + const duration = periodsAndDuration.duration; + const periods = periodsAndDuration.periods; presentationTimeline.setStatic(mpdType == 'static'); if (mpdType == 'static' || !periodsAndDuration.durationDerivedFromPeriods) { @@ -576,7 +576,7 @@ shaka.dash.DashParser.prototype.processManifest_ = presentationTimeline.setDuration(duration || Infinity); } - let isLive = presentationTimeline.isLive(); + const isLive = presentationTimeline.isLive(); // If it's live, we check for an override. if (isLive && !isNaN(this.config_.availabilityWindowOverride)) { @@ -608,7 +608,7 @@ shaka.dash.DashParser.prototype.processManifest_ = // We only need to do clock sync when we're using presentation start time. // This condition also excludes VOD streams. if (presentationTimeline.usingPresentationStartTime()) { - let timingElements = XmlUtils.findChildren(mpd, 'UTCTiming'); + const timingElements = XmlUtils.findChildren(mpd, 'UTCTiming'); const offset = await this.parseUtcTiming_(baseUris, timingElements); // Detect calls to stop(). if (!this.playerInterface_) { @@ -637,17 +637,17 @@ shaka.dash.DashParser.prototype.processManifest_ = shaka.dash.DashParser.prototype.parsePeriods_ = function( context, baseUris, mpd) { const XmlUtils = shaka.util.XmlUtils; - let presentationDuration = XmlUtils.parseAttr( + const presentationDuration = XmlUtils.parseAttr( mpd, 'mediaPresentationDuration', XmlUtils.parseDuration); - let periods = []; + const periods = []; let prevEnd = 0; - let periodNodes = XmlUtils.findChildren(mpd, 'Period'); + const periodNodes = XmlUtils.findChildren(mpd, 'Period'); for (let i = 0; i < periodNodes.length; i++) { - let elem = periodNodes[i]; - let start = /** @type {number} */ ( + const elem = periodNodes[i]; + const start = /** @type {number} */ ( XmlUtils.parseAttr(elem, 'start', XmlUtils.parseDuration, prevEnd)); - let givenDuration = + const givenDuration = XmlUtils.parseAttr(elem, 'duration', XmlUtils.parseDuration); let periodDuration = null; @@ -655,8 +655,8 @@ shaka.dash.DashParser.prototype.parsePeriods_ = function( // "The difference between the start time of a Period and the start time // of the following Period is the duration of the media content // represented by this Period." - let nextPeriod = periodNodes[i + 1]; - let nextStart = + const nextPeriod = periodNodes[i + 1]; + const nextStart = XmlUtils.parseAttr(nextPeriod, 'start', XmlUtils.parseDuration); if (nextStart != null) { periodDuration = nextStart - start; @@ -668,7 +668,7 @@ shaka.dash.DashParser.prototype.parsePeriods_ = function( periodDuration = presentationDuration - start; } - let threshold = + const threshold = shaka.util.ManifestParserUtils.GAP_OVERLAP_TOLERANCE_SECONDS; if (periodDuration && givenDuration && Math.abs(periodDuration - givenDuration) > threshold) { @@ -682,19 +682,19 @@ shaka.dash.DashParser.prototype.parsePeriods_ = function( } // Parse child nodes. - let info = { + const info = { start: start, duration: periodDuration, node: elem, isLastPeriod: periodDuration == null || i == periodNodes.length - 1, }; - let period = this.parsePeriod_(context, baseUris, info); + const period = this.parsePeriod_(context, baseUris, info); periods.push(period); // If the period ID is new, add it to the list. This must be done for both // the initial manifest parse and for updates. // See https://github.com/google/shaka-player/issues/963 - let periodId = context.period.id; + const periodId = context.period.id; goog.asserts.assert(periodId, 'Period IDs should not be null!'); if (!this.periodIds_.includes(periodId)) { this.periodIds_.push(periodId); @@ -781,13 +781,14 @@ shaka.dash.DashParser.prototype.parsePeriod_ = function( context.period.id = '__shaka_period_' + periodInfo.start; } - let eventStreamNodes = XmlUtils.findChildren(periodInfo.node, 'EventStream'); + const eventStreamNodes = + XmlUtils.findChildren(periodInfo.node, 'EventStream'); eventStreamNodes.forEach( this.parseEventStream_.bind(this, periodInfo.start, periodInfo.duration)); - let adaptationSetNodes = + const adaptationSetNodes = XmlUtils.findChildren(periodInfo.node, 'AdaptationSet'); - let adaptationSets = adaptationSetNodes + const adaptationSets = adaptationSetNodes .map(this.parseAdaptationSet_.bind(this, context)) .filter(Functional.isNotNull); @@ -810,18 +811,18 @@ shaka.dash.DashParser.prototype.parsePeriod_ = function( } } - let normalAdaptationSets = adaptationSets + const normalAdaptationSets = adaptationSets .filter(function(as) { return !as.trickModeFor; }); - let trickModeAdaptationSets = adaptationSets + const trickModeAdaptationSets = adaptationSets .filter(function(as) { return as.trickModeFor; }); // Attach trick mode tracks to normal tracks. trickModeAdaptationSets.forEach(function(trickModeSet) { // There may be multiple trick mode streams, but we do not currently // support that. Just choose one. - let trickModeVideo = trickModeSet.streams[0]; - let targetId = trickModeSet.trickModeFor; + const trickModeVideo = trickModeSet.streams[0]; + const targetId = trickModeSet.trickModeFor; normalAdaptationSets.forEach(function(normalSet) { if (normalSet.id == targetId) { normalSet.streams.forEach(function(stream) { @@ -853,17 +854,17 @@ shaka.dash.DashParser.prototype.parsePeriod_ = function( // TODO: Limit number of combinations. Come up with a heuristic // to decide which audio tracks to combine with which video tracks. - let variants = []; + const variants = []; for (let i = 0; i < audioSets.length; i++) { for (let j = 0; j < videoSets.length; j++) { - let audioSet = audioSets[i]; - let videoSet = videoSets[j]; + const audioSet = audioSets[i]; + const videoSet = videoSets[j]; this.createVariants_(audioSet, videoSet, variants); } } - let textSets = this.getSetsOfType_(normalAdaptationSets, ContentType.TEXT); - let textStreams = []; + const textSets = this.getSetsOfType_(normalAdaptationSets, ContentType.TEXT); + const textStreams = []; for (let i = 0; i < textSets.length; i++) { textStreams.push.apply(textStreams, textSets[i].streams); } @@ -923,7 +924,7 @@ shaka.dash.DashParser.prototype.createVariants_ = // Audio+video variants const DrmEngine = shaka.media.DrmEngine; if (DrmEngine.areDrmCompatible(audio.drmInfos, video.drmInfos)) { - let drmInfos = DrmEngine.getCommonDrmInfos(audio.drmInfos, + const drmInfos = DrmEngine.getCommonDrmInfos(audio.drmInfos, video.drmInfos); for (let i = 0; i < audio.streams.length; i++) { @@ -949,7 +950,7 @@ shaka.dash.DashParser.prototype.createVariants_ = } } else { // Audio or video only variants - let set = audio || video; + const set = audio || video; for (let i = 0; i < set.streams.length; i++) { bandwidth = set.streams[i].bandwidth || 0; variant = { @@ -988,8 +989,8 @@ shaka.dash.DashParser.prototype.parseAdaptationSet_ = function(context, elem) { context.adaptationSet = this.createFrame_(elem, context.period, null); let main = false; - let roleElements = XmlUtils.findChildren(elem, 'Role'); - let roleValues = roleElements.map(function(role) { + const roleElements = XmlUtils.findChildren(elem, 'Role'); + const roleValues = roleElements.map(function(role) { return role.getAttribute('value'); }).filter(Functional.isNotNull); @@ -1002,12 +1003,12 @@ shaka.dash.DashParser.prototype.parseAdaptationSet_ = function(context, elem) { } for (let i = 0; i < roleElements.length; i++) { - let scheme = roleElements[i].getAttribute('schemeIdUri'); + const scheme = roleElements[i].getAttribute('schemeIdUri'); if (scheme == null || scheme == 'urn:mpeg:dash:role:2011') { // These only apply for the given scheme, but allow them to be specified // if there is no scheme specified. // See: DASH section 5.8.5.5 - let value = roleElements[i].getAttribute('value'); + const value = roleElements[i].getAttribute('value'); switch (value) { case 'main': main = true; @@ -1020,12 +1021,12 @@ shaka.dash.DashParser.prototype.parseAdaptationSet_ = function(context, elem) { } } - let essentialProperties = XmlUtils.findChildren(elem, 'EssentialProperty'); + const essentialProperties = XmlUtils.findChildren(elem, 'EssentialProperty'); // ID of real AdaptationSet if this is a trick mode set: let trickModeFor = null; let unrecognizedEssentialProperty = false; essentialProperties.forEach(function(prop) { - let schemeId = prop.getAttribute('schemeIdUri'); + const schemeId = prop.getAttribute('schemeIdUri'); if (schemeId == 'http://dashif.org/guidelines/trickmode') { trickModeFor = prop.getAttribute('value'); } else { @@ -1035,13 +1036,13 @@ shaka.dash.DashParser.prototype.parseAdaptationSet_ = function(context, elem) { const accessibilities = XmlUtils.findChildren(elem, 'Accessibility'); const LanguageUtils = shaka.util.LanguageUtils; - let closedCaptions = new Map(); + const closedCaptions = new Map(); for (const prop of accessibilities) { - let schemeId = prop.getAttribute('schemeIdUri'); + const schemeId = prop.getAttribute('schemeIdUri'); if (schemeId == 'urn:scte:dash:cc:cea-608:2015' || schemeId == 'urn:scte:dash:cc:cea-708:2015') { let channelId = 1; - let closedCaptionsValue = prop.getAttribute('value'); + const closedCaptionsValue = prop.getAttribute('value'); if (closedCaptionsValue != null) { closedCaptionsValue.split(';').forEach((captionStr) => { let channel; @@ -1088,20 +1089,21 @@ shaka.dash.DashParser.prototype.parseAdaptationSet_ = function(context, elem) { return null; } - let contentProtectionElems = XmlUtils.findChildren(elem, 'ContentProtection'); - let contentProtection = shaka.dash.ContentProtection.parseFromAdaptationSet( + const contentProtectionElems = + XmlUtils.findChildren(elem, 'ContentProtection'); + const contentProtection = shaka.dash.ContentProtection.parseFromAdaptationSet( contentProtectionElems, this.config_.dash.customScheme, this.config_.dash.ignoreDrmInfo); - let language = + const language = shaka.util.LanguageUtils.normalize(elem.getAttribute('lang') || 'und'); // This attribute is currently non-standard, but it is supported by Kaltura. - let label = elem.getAttribute('label'); + const label = elem.getAttribute('label'); // Parse Representations into Streams. - let representations = XmlUtils.findChildren(elem, 'Representation'); - let streams = representations + const representations = XmlUtils.findChildren(elem, 'Representation'); + const streams = representations .map(this.parseRepresentation_.bind(this, context, contentProtection, kind, language, label, main, roleValues, closedCaptions)) .filter(function(s) { return !!s; }); @@ -1124,8 +1126,8 @@ shaka.dash.DashParser.prototype.parseAdaptationSet_ = function(context, elem) { // necessary information. if (!context.adaptationSet.contentType || context.adaptationSet.contentType == ContentType.APPLICATION) { - let mimeType = streams[0].mimeType; - let codecs = streams[0].codecs; + const mimeType = streams[0].mimeType; + const codecs = streams[0].codecs; context.adaptationSet.contentType = shaka.dash.DashParser.guessContentType_(mimeType, codecs); @@ -1145,7 +1147,7 @@ shaka.dash.DashParser.prototype.parseAdaptationSet_ = function(context, elem) { }); }); - let repIds = representations + const repIds = representations .map(function(node) { return node.getAttribute('id'); }) .filter(shaka.util.Functional.isNotNull); @@ -1221,8 +1223,8 @@ shaka.dash.DashParser.prototype.parseRepresentation_ = function( goog.asserts.assert(isText, 'Must have Segment* with non-text streams.'); - let baseUris = context.representation.baseUris; - let duration = context.periodInfo.duration || 0; + const baseUris = context.representation.baseUris; + const duration = context.periodInfo.duration || 0; streamInfo = { createSegmentIndex: Promise.resolve.bind(Promise), findSegmentPosition: @@ -1257,8 +1259,9 @@ shaka.dash.DashParser.prototype.parseRepresentation_ = function( throw error; } - let contentProtectionElems = XmlUtils.findChildren(node, 'ContentProtection'); - let keyId = shaka.dash.ContentProtection.parseFromRepresentation( + const contentProtectionElems = + XmlUtils.findChildren(node, 'ContentProtection'); + const keyId = shaka.dash.ContentProtection.parseFromRepresentation( contentProtectionElems, this.config_.dash.customScheme, contentProtection, this.config_.dash.ignoreDrmInfo); @@ -1384,21 +1387,21 @@ shaka.dash.DashParser.prototype.createFrame_ = function( }); baseUris = baseUris || parent.baseUris; - let parseNumber = XmlUtils.parseNonNegativeInt; - let evalDivision = XmlUtils.evalDivision; - let uris = XmlUtils.findChildren(elem, 'BaseURL').map(XmlUtils.getContents); + const parseNumber = XmlUtils.parseNonNegativeInt; + const evalDivision = XmlUtils.evalDivision; + const uris = XmlUtils.findChildren(elem, 'BaseURL').map(XmlUtils.getContents); let contentType = elem.getAttribute('contentType') || parent.contentType; - let mimeType = elem.getAttribute('mimeType') || parent.mimeType; - let codecs = elem.getAttribute('codecs') || parent.codecs; - let frameRate = + const mimeType = elem.getAttribute('mimeType') || parent.mimeType; + const codecs = elem.getAttribute('codecs') || parent.codecs; + const frameRate = XmlUtils.parseAttr(elem, 'frameRate', evalDivision) || parent.frameRate; - let emsgSchemeIdUris = this.emsgSchemeIdUris_( + const emsgSchemeIdUris = this.emsgSchemeIdUris_( XmlUtils.findChildren(elem, 'InbandEventStream'), parent.emsgSchemeIdUris); - let audioChannelConfigs = + const audioChannelConfigs = XmlUtils.findChildren(elem, 'AudioChannelConfiguration'); - let numChannels = + const numChannels = this.parseAudioChannels_(audioChannelConfigs) || parent.numChannels; if (!contentType) { @@ -1438,9 +1441,9 @@ shaka.dash.DashParser.prototype.createFrame_ = function( */ shaka.dash.DashParser.prototype.emsgSchemeIdUris_ = function( inBandEventStreams, emsgSchemeIdUris) { - let schemeIdUris = emsgSchemeIdUris.slice(); - for (let event of inBandEventStreams) { - let schemeIdUri = event.getAttribute('schemeIdUri'); + const schemeIdUris = emsgSchemeIdUris.slice(); + for (const event of inBandEventStreams) { + const schemeIdUri = event.getAttribute('schemeIdUri'); if (!schemeIdUris.includes(schemeIdUri)) { schemeIdUris.push(schemeIdUri); } @@ -1457,12 +1460,12 @@ shaka.dash.DashParser.prototype.emsgSchemeIdUris_ = function( shaka.dash.DashParser.prototype.parseAudioChannels_ = function(audioChannelConfigs) { for (let i = 0; i < audioChannelConfigs.length; ++i) { - let elem = audioChannelConfigs[i]; + const elem = audioChannelConfigs[i]; - let scheme = elem.getAttribute('schemeIdUri'); + const scheme = elem.getAttribute('schemeIdUri'); if (!scheme) continue; - let value = elem.getAttribute('value'); + const value = elem.getAttribute('value'); if (!value) continue; switch (scheme) { @@ -1474,7 +1477,7 @@ shaka.dash.DashParser.prototype.parseAudioChannels_ = case 'urn:mpeg:dash:23003:3:audio_channel_configuration:2011': case 'urn:dts:dash:audio_channel_configuration:2012': { // As far as we can tell, this is a number of channels. - let intValue = parseInt(value, 10); + const intValue = parseInt(value, 10); if (!intValue) { // 0 or NaN shaka.log.warning('Channel parsing failure! ' + 'Ignoring scheme and value', scheme, value); @@ -1575,13 +1578,15 @@ shaka.dash.DashParser.prototype.verifyRepresentation_ = function(frame) { */ shaka.dash.DashParser.prototype.requestForTiming_ = function(baseUris, uri, method) { - let requestUris = shaka.util.ManifestParserUtils.resolveUris(baseUris, [uri]); - let request = shaka.net.NetworkingEngine.makeRequest( + const requestUris = + shaka.util.ManifestParserUtils.resolveUris(baseUris, [uri]); + const request = shaka.net.NetworkingEngine.makeRequest( requestUris, this.config_.retryParameters); request.method = method; const type = shaka.net.NetworkingEngine.RequestType.TIMING; - let operation = this.playerInterface_.networkingEngine.request(type, request); + const operation = + this.playerInterface_.networkingEngine.request(type, request); this.operationManager_.manage(operation); return operation.promise.then((response) => { @@ -1596,7 +1601,7 @@ shaka.dash.DashParser.prototype.requestForTiming_ = } else { text = shaka.util.StringUtils.fromUTF8(response.data); } - let date = Date.parse(text); + const date = Date.parse(text); if (isNaN(date)) { shaka.log.warning('Unable to parse date from UTC timing response'); return 0; @@ -1615,7 +1620,7 @@ shaka.dash.DashParser.prototype.requestForTiming_ = * @private */ shaka.dash.DashParser.prototype.parseUtcTiming_ = function(baseUris, elems) { - let schemesAndValues = elems.map(function(elem) { + const schemesAndValues = elems.map(function(elem) { return { scheme: elem.getAttribute('schemeIdUri'), value: elem.getAttribute('value'), @@ -1624,7 +1629,7 @@ shaka.dash.DashParser.prototype.parseUtcTiming_ = function(baseUris, elems) { // If there's nothing specified in the manifest, but we have a default from // the config, use that. - let clockSyncUri = this.config_.dash.clockSyncUri; + const clockSyncUri = this.config_.dash.clockSyncUri; if (!schemesAndValues.length && clockSyncUri) { schemesAndValues.push({ scheme: 'urn:mpeg:dash:utc:http-head:2014', @@ -1634,8 +1639,8 @@ shaka.dash.DashParser.prototype.parseUtcTiming_ = function(baseUris, elems) { const Functional = shaka.util.Functional; return Functional.createFallbackPromiseChain(schemesAndValues, function(sv) { - let scheme = sv.scheme; - let value = sv.value; + const scheme = sv.scheme; + const value = sv.value; switch (scheme) { // See DASH IOP Guidelines Section 4.7 // https://bit.ly/DashIop3-2 @@ -1650,7 +1655,7 @@ shaka.dash.DashParser.prototype.parseUtcTiming_ = function(baseUris, elems) { return this.requestForTiming_(baseUris, value, 'GET'); case 'urn:mpeg:dash:utc:direct:2014': case 'urn:mpeg:dash:utc:direct:2012': { - let date = Date.parse(value); + const date = Date.parse(value); return isNaN(date) ? 0 : (date - Date.now()); } @@ -1684,16 +1689,17 @@ shaka.dash.DashParser.prototype.parseUtcTiming_ = function(baseUris, elems) { shaka.dash.DashParser.prototype.parseEventStream_ = function( periodStart, periodDuration, elem) { const XmlUtils = shaka.util.XmlUtils; - let parseNumber = XmlUtils.parseNonNegativeInt; + const parseNumber = XmlUtils.parseNonNegativeInt; - let schemeIdUri = elem.getAttribute('schemeIdUri') || ''; - let value = elem.getAttribute('value') || ''; - let timescale = XmlUtils.parseAttr(elem, 'timescale', parseNumber) || 1; + const schemeIdUri = elem.getAttribute('schemeIdUri') || ''; + const value = elem.getAttribute('value') || ''; + const timescale = XmlUtils.parseAttr(elem, 'timescale', parseNumber) || 1; XmlUtils.findChildren(elem, 'Event').forEach(function(eventNode) { - let presentationTime = + const presentationTime = XmlUtils.parseAttr(eventNode, 'presentationTime', parseNumber) || 0; - let duration = XmlUtils.parseAttr(eventNode, 'duration', parseNumber) || 0; + const duration = + XmlUtils.parseAttr(eventNode, 'duration', parseNumber) || 0; let startTime = presentationTime / timescale + periodStart; let endTime = startTime + (duration / timescale); @@ -1705,7 +1711,7 @@ shaka.dash.DashParser.prototype.parseEventStream_ = function( } /** @type {shaka.extern.TimelineRegionInfo} */ - let region = { + const region = { schemeIdUri: schemeIdUri, value: value, startTime: startTime, @@ -1738,8 +1744,8 @@ shaka.dash.DashParser.prototype.requestInitSegment_ = function( endByte, this.config_.retryParameters); - let networkingEngine = this.playerInterface_.networkingEngine; - let operation = networkingEngine.request(requestType, request); + const networkingEngine = this.playerInterface_.networkingEngine; + const operation = networkingEngine.request(requestType, request); this.operationManager_.manage(operation); return operation.promise.then((response) => response.data); }; @@ -1754,7 +1760,7 @@ shaka.dash.DashParser.prototype.requestInitSegment_ = function( * @private */ shaka.dash.DashParser.guessContentType_ = function(mimeType, codecs) { - let fullMimeType = shaka.util.MimeUtils.getFullType(mimeType, codecs); + const fullMimeType = shaka.util.MimeUtils.getFullType(mimeType, codecs); if (shaka.text.TextEngine.isTypeSupported(fullMimeType)) { // If it's supported by TextEngine, it's definitely text. diff --git a/lib/dash/mpd_utils.js b/lib/dash/mpd_utils.js index b0848ebcfd..716f7165b2 100644 --- a/lib/dash/mpd_utils.js +++ b/lib/dash/mpd_utils.js @@ -104,7 +104,7 @@ shaka.dash.MpdUtils.XlinkNamespaceUri_ = 'http://www.w3.org/1999/xlink'; shaka.dash.MpdUtils.fillUriTemplate = function( uriTemplate, representationId, number, bandwidth, time) { /** @type {!Object.} */ - let valueTable = { + const valueTable = { 'RepresentationID': representationId, 'Number': number, 'Bandwidth': bandwidth, @@ -203,17 +203,17 @@ shaka.dash.MpdUtils.createTimeline = // Alias. const XmlUtils = shaka.util.XmlUtils; - let timePoints = XmlUtils.findChildren(segmentTimeline, 'S'); + const timePoints = XmlUtils.findChildren(segmentTimeline, 'S'); /** @type {!Array.} */ - let timeline = []; + const timeline = []; let lastEndTime = 0; for (let i = 0; i < timePoints.length; ++i) { - let timePoint = timePoints[i]; + const timePoint = timePoints[i]; let t = XmlUtils.parseAttr(timePoint, 't', XmlUtils.parseNonNegativeInt); - let d = XmlUtils.parseAttr(timePoint, 'd', XmlUtils.parseNonNegativeInt); - let r = XmlUtils.parseAttr(timePoint, 'r', XmlUtils.parseInt); + const d = XmlUtils.parseAttr(timePoint, 'd', XmlUtils.parseNonNegativeInt); + const r = XmlUtils.parseAttr(timePoint, 'r', XmlUtils.parseInt); // Adjust the start time to account for the presentation time offset. if (t != null) { @@ -233,8 +233,8 @@ shaka.dash.MpdUtils.createTimeline = let repeat = r || 0; if (repeat < 0) { if (i + 1 < timePoints.length) { - let nextTimePoint = timePoints[i + 1]; - let nextStartTime = XmlUtils.parseAttr( + const nextTimePoint = timePoints[i + 1]; + const nextStartTime = XmlUtils.parseAttr( nextTimePoint, 't', XmlUtils.parseNonNegativeInt); if (nextStartTime == null) { shaka.log.warning( @@ -284,7 +284,7 @@ shaka.dash.MpdUtils.createTimeline = // end of the last segment, but this would complicate the computation of // the $Time$ placeholder later on. if ((timeline.length > 0) && (startTime != lastEndTime)) { - let delta = startTime - lastEndTime; + const delta = startTime - lastEndTime; if (Math.abs(delta / timescale) >= shaka.util.ManifestParserUtils.GAP_OVERLAP_TOLERANCE_SECONDS) { @@ -298,8 +298,8 @@ shaka.dash.MpdUtils.createTimeline = } for (let j = 0; j <= repeat; ++j) { - let endTime = startTime + d; - let item = { + const endTime = startTime + d; + const item = { start: startTime / timescale, end: endTime / timescale, unscaledStart: startTime, @@ -330,21 +330,22 @@ shaka.dash.MpdUtils.parseSegmentInfo = function(context, callback) { const MpdUtils = shaka.dash.MpdUtils; const XmlUtils = shaka.util.XmlUtils; - let timescaleStr = MpdUtils.inheritAttribute(context, callback, 'timescale'); + const timescaleStr = + MpdUtils.inheritAttribute(context, callback, 'timescale'); let timescale = 1; if (timescaleStr) { timescale = XmlUtils.parsePositiveInt(timescaleStr) || 1; } - let durationStr = MpdUtils.inheritAttribute(context, callback, 'duration'); + const durationStr = MpdUtils.inheritAttribute(context, callback, 'duration'); let segmentDuration = XmlUtils.parsePositiveInt(durationStr || ''); if (segmentDuration) { segmentDuration /= timescale; } - let startNumberStr = + const startNumberStr = MpdUtils.inheritAttribute(context, callback, 'startNumber'); - let unscaledPresentationTimeOffset = + const unscaledPresentationTimeOffset = Number(MpdUtils.inheritAttribute(context, callback, 'presentationTimeOffset')) || 0; let startNumber = XmlUtils.parseNonNegativeInt(startNumberStr || ''); @@ -352,7 +353,7 @@ shaka.dash.MpdUtils.parseSegmentInfo = function(context, callback) { startNumber = 1; } - let timelineNode = + const timelineNode = MpdUtils.inheritChild(context, callback, 'SegmentTimeline'); /** @type {Array.} */ let timeline = null; @@ -362,7 +363,7 @@ shaka.dash.MpdUtils.parseSegmentInfo = function(context, callback) { context.periodInfo.duration || Infinity); } - let scaledPresentationTimeOffset = + const scaledPresentationTimeOffset = (unscaledPresentationTimeOffset / timescale) || 0; return { timescale: timescale, @@ -391,7 +392,7 @@ shaka.dash.MpdUtils.inheritAttribute = function(context, callback, attribute) { 'There must be at least one element of the given type'); /** @type {!Array.} */ - let nodes = [ + const nodes = [ callback(context.representation), callback(context.adaptationSet), callback(context.period), @@ -419,7 +420,7 @@ shaka.dash.MpdUtils.inheritChild = function(context, callback, child) { 'There must be at least one element of the given type'); /** @type {!Array.} */ - let nodes = [ + const nodes = [ callback(context.representation), callback(context.adaptationSet), callback(context.period), @@ -455,14 +456,14 @@ shaka.dash.MpdUtils.handleXlinkInElement_ = const ManifestParserUtils = shaka.util.ManifestParserUtils; const NS = MpdUtils.XlinkNamespaceUri_; - let xlinkHref = XmlUtils.getAttributeNS(element, NS, 'href'); - let xlinkActuate = + const xlinkHref = XmlUtils.getAttributeNS(element, NS, 'href'); + const xlinkActuate = XmlUtils.getAttributeNS(element, NS, 'actuate') || 'onRequest'; // Remove the xlink properties, so it won't download again // when re-processed. for (let i = 0; i < element.attributes.length; i++) { - let attribute = element.attributes[i]; + const attribute = element.attributes[i]; if (attribute.namespaceURI == NS) { element.removeAttributeNS(attribute.namespaceURI, attribute.localName); i -= 1; @@ -484,20 +485,20 @@ shaka.dash.MpdUtils.handleXlinkInElement_ = } // Resolve the xlink href, in case it's a relative URL. - let uris = ManifestParserUtils.resolveUris([baseUri], [xlinkHref]); + const uris = ManifestParserUtils.resolveUris([baseUri], [xlinkHref]); // Load in the linked elements. const requestType = shaka.net.NetworkingEngine.RequestType.MANIFEST; - let request = shaka.net.NetworkingEngine.makeRequest( + const request = shaka.net.NetworkingEngine.makeRequest( uris, retryParameters); - let requestOperation = networkingEngine.request(requestType, request); + const requestOperation = networkingEngine.request(requestType, request); // The interface is abstract, but we know it was implemented with the // more capable internal class. goog.asserts.assert(requestOperation instanceof shaka.util.AbortableOperation, 'Unexpected implementation of IAbortableOperation!'); // Satisfy the compiler with a cast. - let networkOperation = + const networkOperation = /** @type {!shaka.util.AbortableOperation.} */( requestOperation); @@ -505,7 +506,8 @@ shaka.dash.MpdUtils.handleXlinkInElement_ = return networkOperation.chain((response) => { // This only supports the case where the loaded xml has a single // top-level element. If there are multiple roots, it will be rejected. - let rootElem = shaka.util.XmlUtils.parseXml(response.data, element.tagName); + const rootElem = + shaka.util.XmlUtils.parseXml(response.data, element.tagName); if (!rootElem) { // It was not valid XML. return shaka.util.AbortableOperation.failed(new Error( @@ -523,15 +525,15 @@ shaka.dash.MpdUtils.handleXlinkInElement_ = // Move the children of the loaded xml into the current element. while (rootElem.childNodes.length) { - let child = rootElem.childNodes[0]; + const child = rootElem.childNodes[0]; rootElem.removeChild(child); element.appendChild(child); } // Move the attributes of the loaded xml into the current element. for (let i = 0; i < rootElem.attributes.length; i++) { - let attribute = rootElem.attributes[i].nodeName; - let attributeValue = rootElem.getAttribute(attribute); + const attribute = rootElem.attributes[i].nodeName; + const attributeValue = rootElem.getAttribute(attribute); element.setAttribute(attribute, attributeValue); } @@ -579,9 +581,9 @@ shaka.dash.MpdUtils.processXlinks = return handled; } - let childOperations = []; + const childOperations = []; for (let i = 0; i < element.childNodes.length; i++) { - let child = element.childNodes[i]; + const child = element.childNodes[i]; if (child instanceof Element) { const resolveToZeroString = 'urn:mpeg:dash:resolve-to-zero:2013'; if (XmlUtils.getAttributeNS(child, NS, 'href') == resolveToZeroString) { diff --git a/lib/dash/segment_base.js b/lib/dash/segment_base.js index dc4aff310b..d191f7b22c 100644 --- a/lib/dash/segment_base.js +++ b/lib/dash/segment_base.js @@ -47,14 +47,14 @@ shaka.dash.SegmentBase.createInitSegment = function(context, callback) { const XmlUtils = shaka.util.XmlUtils; const ManifestParserUtils = shaka.util.ManifestParserUtils; - let initialization = + const initialization = MpdUtils.inheritChild(context, callback, 'Initialization'); if (!initialization) { return null; } let resolvedUris = context.representation.baseUris; - let uri = initialization.getAttribute('sourceURL'); + const uri = initialization.getAttribute('sourceURL'); if (uri) { resolvedUris = ManifestParserUtils.resolveUris(context.representation.baseUris, [uri]); @@ -62,13 +62,14 @@ shaka.dash.SegmentBase.createInitSegment = function(context, callback) { let startByte = 0; let endByte = null; - let range = XmlUtils.parseAttr(initialization, 'range', XmlUtils.parseRange); + const range = + XmlUtils.parseAttr(initialization, 'range', XmlUtils.parseRange); if (range) { startByte = range.start; endByte = range.end; } - let getUris = function() { return resolvedUris; }; + const getUris = function() { return resolvedUris; }; return new shaka.media.InitSegmentReference(getUris, startByte, endByte); }; @@ -90,22 +91,22 @@ shaka.dash.SegmentBase.createStream = function(context, requestInitSegment) { const SegmentBase = shaka.dash.SegmentBase; const XmlUtils = shaka.util.XmlUtils; - let unscaledPresentationTimeOffset = Number(MpdUtils.inheritAttribute( + const unscaledPresentationTimeOffset = Number(MpdUtils.inheritAttribute( context, SegmentBase.fromInheritance_, 'presentationTimeOffset')) || 0; - let timescaleStr = MpdUtils.inheritAttribute( + const timescaleStr = MpdUtils.inheritAttribute( context, SegmentBase.fromInheritance_, 'timescale'); let timescale = 1; if (timescaleStr) { timescale = XmlUtils.parsePositiveInt(timescaleStr) || 1; } - let scaledPresentationTimeOffset = + const scaledPresentationTimeOffset = (unscaledPresentationTimeOffset / timescale) || 0; - let init = + const init = SegmentBase.createInitSegment(context, SegmentBase.fromInheritance_); - let index = SegmentBase.createSegmentIndex_( + const index = SegmentBase.createSegmentIndex_( context, requestInitSegment, init, scaledPresentationTimeOffset); return { @@ -134,16 +135,16 @@ shaka.dash.SegmentBase.createStream = function(context, requestInitSegment) { shaka.dash.SegmentBase.createSegmentIndexFromUris = function( context, requestInitSegment, init, uris, startByte, endByte, containerType, scaledPresentationTimeOffset) { - let presentationTimeline = context.presentationTimeline; - let fitLast = !context.dynamic || !context.periodInfo.isLastPeriod; - let periodStart = context.periodInfo.start; - let periodDuration = context.periodInfo.duration; + const presentationTimeline = context.presentationTimeline; + const fitLast = !context.dynamic || !context.periodInfo.isLastPeriod; + const periodStart = context.periodInfo.start; + const periodDuration = context.periodInfo.duration; // Create a local variable to bind to so we can set to null to help the GC. let localRequest = requestInitSegment; let segmentIndex = null; - let create = function() { - let async = [ + const create = function() { + const async = [ localRequest(uris, startByte, endByte), containerType == 'webm' ? localRequest(init.getUris(), init.startByte, init.endByte) : @@ -152,8 +153,8 @@ shaka.dash.SegmentBase.createSegmentIndexFromUris = function( localRequest = null; return Promise.all(async).then(function(results) { - let indexData = results[0]; - let initData = results[1] || null; + const indexData = results[0]; + const initData = results[1] || null; let references = null; if (containerType == 'mp4') { @@ -162,7 +163,7 @@ shaka.dash.SegmentBase.createSegmentIndexFromUris = function( indexData, startByte, uris, scaledPresentationTimeOffset); } else { goog.asserts.assert(initData, 'WebM requires init data'); - let parser = new shaka.media.WebmSegmentIndexParser(); + const parser = new shaka.media.WebmSegmentIndexParser(); references = parser.parse(indexData, initData, uris, scaledPresentationTimeOffset); } @@ -180,11 +181,11 @@ shaka.dash.SegmentBase.createSegmentIndexFromUris = function( } }); }; - let get = function(i) { + const get = function(i) { goog.asserts.assert(segmentIndex, 'Must call createSegmentIndex first'); return segmentIndex.get(i); }; - let find = function(t) { + const find = function(t) { goog.asserts.assert(segmentIndex, 'Must call createSegmentIndex first'); return segmentIndex.find(t); }; @@ -226,8 +227,8 @@ shaka.dash.SegmentBase.createSegmentIndex_ = function( const ManifestParserUtils = shaka.util.ManifestParserUtils; const ContentType = shaka.util.ManifestParserUtils.ContentType; - let contentType = context.representation.contentType; - let containerType = context.representation.mimeType.split('/')[1]; + const contentType = context.representation.contentType; + const containerType = context.representation.mimeType.split('/')[1]; if (contentType != ContentType.TEXT && containerType != 'mp4' && containerType != 'webm') { shaka.log.error( @@ -251,15 +252,15 @@ shaka.dash.SegmentBase.createSegmentIndex_ = function( shaka.util.Error.Code.DASH_WEBM_MISSING_INIT); } - let representationIndex = MpdUtils.inheritChild( + const representationIndex = MpdUtils.inheritChild( context, SegmentBase.fromInheritance_, 'RepresentationIndex'); - let indexRangeElem = MpdUtils.inheritAttribute( + const indexRangeElem = MpdUtils.inheritAttribute( context, SegmentBase.fromInheritance_, 'indexRange'); let indexUris = context.representation.baseUris; let indexRange = XmlUtils.parseRange(indexRangeElem || ''); if (representationIndex) { - let representationUri = representationIndex.getAttribute('sourceURL'); + const representationUri = representationIndex.getAttribute('sourceURL'); if (representationUri) { indexUris = ManifestParserUtils.resolveUris( context.representation.baseUris, [representationUri]); diff --git a/lib/dash/segment_list.js b/lib/dash/segment_list.js index aedd39c08d..31b4189280 100644 --- a/lib/dash/segment_list.js +++ b/lib/dash/segment_list.js @@ -47,9 +47,9 @@ shaka.dash.SegmentList.createStream = function(context, segmentIndexMap) { 'Should only be called with SegmentList'); const SegmentList = shaka.dash.SegmentList; - let init = shaka.dash.SegmentBase.createInitSegment( + const init = shaka.dash.SegmentBase.createInitSegment( context, SegmentList.fromInheritance_); - let info = SegmentList.parseSegmentListInfo_(context); + const info = SegmentList.parseSegmentListInfo_(context); SegmentList.checkSegmentListInfo_(context, info); @@ -62,13 +62,13 @@ shaka.dash.SegmentList.createStream = function(context, segmentIndexMap) { segmentIndex = segmentIndexMap[id]; } - let references = SegmentList.createSegmentReferences_( + const references = SegmentList.createSegmentReferences_( context.periodInfo.duration, info.startNumber, context.representation.baseUris, info); if (segmentIndex) { segmentIndex.merge(references); - let start = context.presentationTimeline.getSegmentAvailabilityStart(); + const start = context.presentationTimeline.getSegmentAvailabilityStart(); segmentIndex.evict(start - context.periodInfo.start); } else { context.presentationTimeline.notifySegments( @@ -161,8 +161,8 @@ shaka.dash.SegmentList.parseSegmentListInfo_ = function(context) { const SegmentList = shaka.dash.SegmentList; const MpdUtils = shaka.dash.MpdUtils; - let mediaSegments = SegmentList.parseMediaSegments_(context); - let segmentInfo = + const mediaSegments = SegmentList.parseMediaSegments_(context); + const segmentInfo = MpdUtils.parseSegmentInfo(context, SegmentList.fromInheritance_); let startNumber = segmentInfo.startNumber; @@ -264,14 +264,14 @@ shaka.dash.SegmentList.createSegmentReferences_ = function( } /** @type {!Array.} */ - let references = []; + const references = []; let prevEndTime = info.startTime; for (let i = 0; i < max; i++) { - let segment = info.mediaSegments[i]; - let mediaUri = ManifestParserUtils.resolveUris( + const segment = info.mediaSegments[i]; + const mediaUri = ManifestParserUtils.resolveUris( baseUris, [segment.mediaUri]); - let startTime = prevEndTime; + const startTime = prevEndTime; let endTime; if (info.segmentDuration != null) { @@ -288,7 +288,7 @@ shaka.dash.SegmentList.createSegmentReferences_ = function( endTime = startTime + periodDuration; } - let getUris = (function(uris) { return uris; }.bind(null, mediaUri)); + const getUris = (function(uris) { return uris; }.bind(null, mediaUri)); references.push( new shaka.media.SegmentReference( i + startNumber, startTime, endTime, getUris, segment.start, @@ -310,7 +310,7 @@ shaka.dash.SegmentList.createSegmentReferences_ = function( shaka.dash.SegmentList.parseMediaSegments_ = function(context) { const Functional = shaka.util.Functional; /** @type {!Array.} */ - let segmentLists = [ + const segmentLists = [ context.representation.segmentList, context.adaptationSet.segmentList, context.period.segmentList, @@ -332,8 +332,8 @@ shaka.dash.SegmentList.parseMediaSegments_ = function(context) { 'or SegmentTimeline, which must be accurate.'); } - let uri = urlNode.getAttribute('media'); - let range = XmlUtils.parseAttr( + const uri = urlNode.getAttribute('media'); + const range = XmlUtils.parseAttr( urlNode, 'mediaRange', XmlUtils.parseRange, {start: 0, end: null}); return {mediaUri: uri, start: range.start, end: range.end}; }); diff --git a/lib/dash/segment_template.js b/lib/dash/segment_template.js index d8288988ed..6420fa8f2e 100644 --- a/lib/dash/segment_template.js +++ b/lib/dash/segment_template.js @@ -50,8 +50,8 @@ shaka.dash.SegmentTemplate.createStream = function( 'Should only be called with SegmentTemplate'); const SegmentTemplate = shaka.dash.SegmentTemplate; - let init = SegmentTemplate.createInitSegment_(context); - let info = SegmentTemplate.parseSegmentTemplateInfo_(context); + const init = SegmentTemplate.createInitSegment_(context); + const info = SegmentTemplate.parseSegmentTemplateInfo_(context); SegmentTemplate.checkSegmentTemplateInfo_(context, info); @@ -78,23 +78,23 @@ shaka.dash.SegmentTemplate.createStream = function( segmentIndex = segmentIndexMap[id]; } - let references = SegmentTemplate.createFromTimeline_(context, info); + const references = SegmentTemplate.createFromTimeline_(context, info); // Don't fit live content, since it might receive more segments. // Unless that live content is multi-period; it's safe to fit every period // but the last one, since only the last period might receive new segments. - let shouldFit = !context.dynamic || !context.periodInfo.isLastPeriod; + const shouldFit = !context.dynamic || !context.periodInfo.isLastPeriod; if (segmentIndex) { if (shouldFit) { // Fit the new references before merging them, so that the merge // algorithm has a more accurate view of their start and end times. - let wrapper = new shaka.media.SegmentIndex(references); + const wrapper = new shaka.media.SegmentIndex(references); wrapper.fit(context.periodInfo.duration); } segmentIndex.merge(references); - let start = context.presentationTimeline.getSegmentAvailabilityStart(); + const start = context.presentationTimeline.getSegmentAvailabilityStart(); segmentIndex.evict(start - context.periodInfo.start); } else { context.presentationTimeline.notifySegments( @@ -182,12 +182,12 @@ shaka.dash.SegmentTemplate.fromInheritance_ = function(frame) { shaka.dash.SegmentTemplate.parseSegmentTemplateInfo_ = function(context) { const SegmentTemplate = shaka.dash.SegmentTemplate; const MpdUtils = shaka.dash.MpdUtils; - let segmentInfo = + const segmentInfo = MpdUtils.parseSegmentInfo(context, SegmentTemplate.fromInheritance_); - let media = MpdUtils.inheritAttribute( + const media = MpdUtils.inheritAttribute( context, SegmentTemplate.fromInheritance_, 'media'); - let index = MpdUtils.inheritAttribute( + const index = MpdUtils.inheritAttribute( context, SegmentTemplate.fromInheritance_, 'index'); return { @@ -274,7 +274,7 @@ shaka.dash.SegmentTemplate.createFromIndexTemplate_ = function( const ManifestParserUtils = shaka.util.ManifestParserUtils; // Determine the container type. - let containerType = context.representation.mimeType.split('/')[1]; + const containerType = context.representation.mimeType.split('/')[1]; if ((containerType != 'mp4') && (containerType != 'webm')) { shaka.log.error( 'SegmentTemplate specifies an unsupported container type.', @@ -298,11 +298,11 @@ shaka.dash.SegmentTemplate.createFromIndexTemplate_ = function( } goog.asserts.assert(info.indexTemplate, 'must be using index template'); - let filledTemplate = MpdUtils.fillUriTemplate( + const filledTemplate = MpdUtils.fillUriTemplate( info.indexTemplate, context.representation.id, null, context.bandwidth || null, null); - let resolvedUris = ManifestParserUtils.resolveUris( + const resolvedUris = ManifestParserUtils.resolveUris( context.representation.baseUris, [filledTemplate]); return shaka.dash.SegmentBase.createSegmentIndexFromUris( @@ -325,17 +325,17 @@ shaka.dash.SegmentTemplate.createFromDuration_ = function(context, info) { const MpdUtils = shaka.dash.MpdUtils; const ManifestParserUtils = shaka.util.ManifestParserUtils; - let periodDuration = context.periodInfo.duration; - let segmentDuration = info.segmentDuration; - let startNumber = info.startNumber; - let timescale = info.timescale; + const periodDuration = context.periodInfo.duration; + const segmentDuration = info.segmentDuration; + const startNumber = info.startNumber; + const timescale = info.timescale; - let template = info.mediaTemplate; - let bandwidth = context.bandwidth || null; - let id = context.representation.id; - let baseUris = context.representation.baseUris; + const template = info.mediaTemplate; + const bandwidth = context.bandwidth || null; + const id = context.representation.id; + const baseUris = context.representation.baseUris; - let find = function(periodTime) { + const find = function(periodTime) { if (periodTime < 0) { return null; } else if (periodDuration && periodTime >= periodDuration) { @@ -344,8 +344,8 @@ shaka.dash.SegmentTemplate.createFromDuration_ = function(context, info) { return Math.floor(periodTime / segmentDuration); }; - let get = function(position) { - let segmentStart = position * segmentDuration; + const get = function(position) { + const segmentStart = position * segmentDuration; // Cap the segment end at the period end, to avoid period transition issues // in StreamingEngine. let segmentEnd = segmentStart + segmentDuration; @@ -358,8 +358,8 @@ shaka.dash.SegmentTemplate.createFromDuration_ = function(context, info) { return null; } - let getUris = function() { - let mediaUri = MpdUtils.fillUriTemplate( + const getUris = function() { + const mediaUri = MpdUtils.fillUriTemplate( template, id, position + startNumber, bandwidth, segmentStart * timescale); return ManifestParserUtils.resolveUris(baseUris, [mediaUri]); @@ -392,22 +392,22 @@ shaka.dash.SegmentTemplate.createFromTimeline_ = function(context, info) { const ManifestParserUtils = shaka.util.ManifestParserUtils; /** @type {!Array.} */ - let references = []; + const references = []; for (let i = 0; i < info.timeline.length; i++) { - let start = info.timeline[i].start; - let unscaledStart = info.timeline[i].unscaledStart; - let end = info.timeline[i].end; + const start = info.timeline[i].start; + const unscaledStart = info.timeline[i].unscaledStart; + const end = info.timeline[i].end; // Note: i = k - 1, where k indicates the k'th segment listed in the MPD. // (See section 5.3.9.5.3 of the DASH spec.) - let segmentReplacement = i + info.startNumber; + const segmentReplacement = i + info.startNumber; // Consider the presentation time offset in segment uri computation - let timeReplacement = unscaledStart + + const timeReplacement = unscaledStart + info.unscaledPresentationTimeOffset; - let createUris = (function( + const createUris = (function( template, repId, bandwidth, baseUris, segmentId, time) { - let mediaUri = MpdUtils.fillUriTemplate( + const mediaUri = MpdUtils.fillUriTemplate( template, repId, segmentId, bandwidth, time); return ManifestParserUtils.resolveUris(baseUris, [mediaUri]) .map(function(g) { return g.toString(); }); @@ -435,20 +435,20 @@ shaka.dash.SegmentTemplate.createInitSegment_ = function(context) { const ManifestParserUtils = shaka.util.ManifestParserUtils; const SegmentTemplate = shaka.dash.SegmentTemplate; - let initialization = MpdUtils.inheritAttribute( + const initialization = MpdUtils.inheritAttribute( context, SegmentTemplate.fromInheritance_, 'initialization'); if (!initialization) { return null; } - let repId = context.representation.id; - let bandwidth = context.bandwidth || null; - let baseUris = context.representation.baseUris; - let getUris = function() { + const repId = context.representation.id; + const bandwidth = context.bandwidth || null; + const baseUris = context.representation.baseUris; + const getUris = function() { goog.asserts.assert(initialization, 'Should have returned earler'); - let filledTemplate = MpdUtils.fillUriTemplate( + const filledTemplate = MpdUtils.fillUriTemplate( initialization, repId, null, bandwidth, null); - let resolvedUris = ManifestParserUtils.resolveUris( + const resolvedUris = ManifestParserUtils.resolveUris( baseUris, [filledTemplate]); return resolvedUris; }; diff --git a/lib/debug/asserts.js b/lib/debug/asserts.js index 501054722f..5ea272365c 100644 --- a/lib/debug/asserts.js +++ b/lib/debug/asserts.js @@ -39,7 +39,7 @@ goog.asserts.assert = function() {}; /** @private */ goog.asserts.patchAssert_ = function() { - let assert = console.assert; + const assert = console.assert; if (!assert) { console.assert = function() {}; diff --git a/lib/debug/log.js b/lib/debug/log.js index 4af957f023..05e1e8466d 100644 --- a/lib/debug/log.js +++ b/lib/debug/log.js @@ -144,8 +144,8 @@ if (window.console && window.console.log.bind) { * @exportDoc */ shaka.log.setLevel = function(level) { - let nop = function() {}; - let log = shaka.log; + const nop = function() {}; + const log = shaka.log; const Level = shaka.log.Level; shaka.log.currentLevel = level; diff --git a/lib/hls/hls_classes.js b/lib/hls/hls_classes.js index 3596e06ce4..bcad30da04 100644 --- a/lib/hls/hls_classes.js +++ b/lib/hls/hls_classes.js @@ -105,7 +105,7 @@ shaka.hls.Tag.prototype.toString = function() { * @param {shaka.hls.Attribute} attr * @return {string} */ - let attrToStr = function(attr) { + const attrToStr = function(attr) { const isNumericAttr = !isNaN(Number(attr.value)); const value = (isNumericAttr ? attr.value : '"' + attr.value + '"'); @@ -170,7 +170,7 @@ shaka.hls.Tag.prototype.addAttribute = function(attribute) { * @return {?shaka.hls.Attribute} attribute */ shaka.hls.Tag.prototype.getAttribute = function(name) { - let attributes = this.attributes.filter(function(attr) { + const attributes = this.attributes.filter(function(attr) { return attr.name == name; }); @@ -195,7 +195,7 @@ shaka.hls.Tag.prototype.getAttribute = function(name) { * @return {?string} */ shaka.hls.Tag.prototype.getAttributeValue = function(name, defaultValue) { - let attribute = this.getAttribute(name); + const attribute = this.getAttribute(name); return attribute ? attribute.value : (defaultValue || null); }; diff --git a/lib/hls/hls_parser.js b/lib/hls/hls_parser.js index 853d9afa3f..9814ba394d 100644 --- a/lib/hls/hls_parser.js +++ b/lib/hls/hls_parser.js @@ -467,7 +467,7 @@ shaka.hls.HlsParser.prototype.parseManifest_ = async function(data) { segmentAvailabilityDuration); } - let rolloverSeconds = + const rolloverSeconds = shaka.hls.HlsParser.TS_ROLLOVER_ / shaka.hls.HlsParser.TS_TIMESCALE_; let offset = 0; while (maxFirstTimestamp >= rolloverSeconds) { @@ -531,15 +531,15 @@ shaka.hls.HlsParser.prototype.parseManifest_ = async function(data) { shaka.hls.HlsParser.prototype.createPeriod_ = async function(playlist) { const Utils = shaka.hls.Utils; const Functional = shaka.util.Functional; - let tags = playlist.tags; + const tags = playlist.tags; - let mediaTags = Utils.filterTagsByName(playlist.tags, 'EXT-X-MEDIA'); - let textStreamTags = mediaTags.filter(function(tag) { - let type = shaka.hls.HlsParser.getRequiredAttributeValue_(tag, 'TYPE'); + const mediaTags = Utils.filterTagsByName(playlist.tags, 'EXT-X-MEDIA'); + const textStreamTags = mediaTags.filter(function(tag) { + const type = shaka.hls.HlsParser.getRequiredAttributeValue_(tag, 'TYPE'); return type == 'SUBTITLES'; }.bind(this)); - let textStreamPromises = textStreamTags.map(function(tag) { + const textStreamPromises = textStreamTags.map(function(tag) { return this.createTextStream_(tag, playlist); }.bind(this)); @@ -554,8 +554,8 @@ shaka.hls.HlsParser.prototype.createPeriod_ = async function(playlist) { // Create Variants for every 'EXT-X-STREAM-INF' tag. Do this after text // streams have been created, so that we can push text codecs found on the // variant tag back into the created text streams. - let variantTags = Utils.filterTagsByName(tags, 'EXT-X-STREAM-INF'); - let variantsPromises = variantTags.map(function(tag) { + const variantTags = Utils.filterTagsByName(tags, 'EXT-X-STREAM-INF'); + const variantsPromises = variantTags.map(function(tag) { return this.createVariantsForTag_(tag, playlist); }.bind(this)); @@ -598,15 +598,15 @@ shaka.hls.HlsParser.prototype.createVariantsForTag_ = /** @type {!Array.} */ let codecs = shaka.hls.HlsParser.filterDuplicateCodecs_(codecsString.split(/\s*,\s*/)); - let resolutionAttr = tag.getAttribute('RESOLUTION'); + const resolutionAttr = tag.getAttribute('RESOLUTION'); let width = null; let height = null; - let frameRate = tag.getAttributeValue('FRAME-RATE'); - let bandwidth = + const frameRate = tag.getAttributeValue('FRAME-RATE'); + const bandwidth = Number(shaka.hls.HlsParser.getRequiredAttributeValue_(tag, 'BANDWIDTH')); if (resolutionAttr) { - let resBlocks = resolutionAttr.value.split('x'); + const resBlocks = resolutionAttr.value.split('x'); width = resBlocks[0]; height = resBlocks[1]; } @@ -632,8 +632,8 @@ shaka.hls.HlsParser.prototype.createVariantsForTag_ = return type == 'SUBTITLES' || uri != ''; }); - let audioGroupId = tag.getAttributeValue('AUDIO'); - let videoGroupId = tag.getAttributeValue('VIDEO'); + const audioGroupId = tag.getAttributeValue('AUDIO'); + const videoGroupId = tag.getAttributeValue('VIDEO'); goog.asserts.assert(audioGroupId == null || videoGroupId == null, 'Unexpected: both video and audio described by media tags!'); @@ -647,12 +647,12 @@ shaka.hls.HlsParser.prototype.createVariantsForTag_ = // There may be a codec string for the text stream. We should identify it, // add it to the appropriate stream, then strip it out of the variant to // avoid confusing our multiplex detection below. - let textCodecs = this.guessCodecsSafe_(ContentType.TEXT, codecs); + const textCodecs = this.guessCodecsSafe_(ContentType.TEXT, codecs); if (textCodecs) { // We found a text codec in the list, so look for an associated text stream. - let subGroupId = tag.getAttributeValue('SUBTITLES'); + const subGroupId = tag.getAttributeValue('SUBTITLES'); if (subGroupId) { - let textTags = Utils.findMediaTags(mediaTags, 'SUBTITLES', subGroupId); + const textTags = Utils.findMediaTags(mediaTags, 'SUBTITLES', subGroupId); goog.asserts.assert(textTags.length == 1, 'Exactly one text tag expected!'); if (textTags.length) { @@ -668,7 +668,7 @@ shaka.hls.HlsParser.prototype.createVariantsForTag_ = shaka.util.ArrayUtils.remove(codecs, textCodecs); } - let promises = mediaTags.map(function(tag) { + const promises = mediaTags.map(function(tag) { return this.createStreamInfoFromMediaTag_(tag, codecs); }.bind(this)); @@ -696,7 +696,7 @@ shaka.hls.HlsParser.prototype.createVariantsForTag_ = if (codecs.length == 1) { // There is only one codec, so it shouldn't be multiplexed. - let videoCodecs = this.guessCodecsSafe_(ContentType.VIDEO, codecs); + const videoCodecs = this.guessCodecsSafe_(ContentType.VIDEO, codecs); if (resolutionAttr || frameRate || videoCodecs) { // Assume video-only. shaka.log.debug('Guessing video-only.'); @@ -717,8 +717,9 @@ shaka.hls.HlsParser.prototype.createVariantsForTag_ = codecs = [codecs.join(',')]; } } else if (audioStreamInfos.length) { - let streamURI = shaka.hls.HlsParser.getRequiredAttributeValue_(tag, 'URI'); - let firstAudioStreamURI = audioStreamInfos[0].verbatimMediaPlaylistUri; + const streamURI = + shaka.hls.HlsParser.getRequiredAttributeValue_(tag, 'URI'); + const firstAudioStreamURI = audioStreamInfos[0].verbatimMediaPlaylistUri; if (streamURI == firstAudioStreamURI) { // The Microsoft HLS manifest generators will make audio-only variants // that link to their URI both directly and through an audio tag. @@ -918,7 +919,7 @@ shaka.hls.HlsParser.prototype.createTextStream_ = goog.asserts.assert(tag.name == 'EXT-X-MEDIA', 'Should only be called on media tags!'); - let type = shaka.hls.HlsParser.getRequiredAttributeValue_(tag, 'TYPE'); + const type = shaka.hls.HlsParser.getRequiredAttributeValue_(tag, 'TYPE'); goog.asserts.assert(type == 'SUBTITLES', 'Should only be called on tags with TYPE="SUBTITLES"!'); @@ -995,19 +996,19 @@ shaka.hls.HlsParser.prototype.createStreamInfoFromMediaTag_ = if (type == 'subtitles') type = ContentType.TEXT; const LanguageUtils = shaka.util.LanguageUtils; - let language = LanguageUtils.normalize(/** @type {string} */( + const language = LanguageUtils.normalize(/** @type {string} */( tag.getAttributeValue('LANGUAGE', 'und'))); const name = tag.getAttributeValue('NAME'); - let defaultAttr = tag.getAttribute('DEFAULT'); - let autoselectAttr = tag.getAttribute('AUTOSELECT'); + const defaultAttr = tag.getAttribute('DEFAULT'); + const autoselectAttr = tag.getAttribute('AUTOSELECT'); // TODO: Should we take into account some of the currently ignored attributes: // FORCED, INSTREAM-ID, CHARACTERISTICS, CHANNELS? // Attribute descriptions: https://bit.ly/2lpjOhj - let channelsAttribute = tag.getAttributeValue('CHANNELS'); - let channelsCount = type == 'audio' ? + const channelsAttribute = tag.getAttributeValue('CHANNELS'); + const channelsCount = type == 'audio' ? this.getChannelCount_(channelsAttribute) : null; - let primary = !!defaultAttr || !!autoselectAttr; + const primary = !!defaultAttr || !!autoselectAttr; const streamInfo = await this.createStreamInfo_( verbatimMediaPlaylistUri, allCodecs, type, language, primary, name, channelsCount, /* closedCaptions */ null); @@ -1037,8 +1038,8 @@ shaka.hls.HlsParser.prototype.createStreamInfoFromMediaTag_ = */ shaka.hls.HlsParser.prototype.getChannelCount_ = function(channels) { if (!channels) return null; - let channelcountstring = channels.split('/')[0]; - let count = parseInt(channelcountstring, 10); + const channelcountstring = channels.split('/')[0]; + const count = parseInt(channelcountstring, 10); return count; }; @@ -1137,7 +1138,7 @@ shaka.hls.HlsParser.prototype.createStreamInfo_ = async function( } /** @type {!Array.} */ - let drmTags = []; + const drmTags = []; playlist.segments.forEach(function(segment) { const segmentKeyTags = Utils.filterTagsByName(segment.tags, 'EXT-X-KEY'); @@ -1146,12 +1147,12 @@ shaka.hls.HlsParser.prototype.createStreamInfo_ = async function( let encrypted = false; /** @type {!Array.}*/ - let drmInfos = []; + const drmInfos = []; let keyId = null; // TODO: May still need changes to support key rotation. for (const drmTag of drmTags) { - let method = + const method = shaka.hls.HlsParser.getRequiredAttributeValue_(drmTag, 'METHOD'); if (method != 'NONE') { encrypted = true; @@ -1165,12 +1166,12 @@ shaka.hls.HlsParser.prototype.createStreamInfo_ = async function( return null; } - let keyFormat = + const keyFormat = shaka.hls.HlsParser.getRequiredAttributeValue_(drmTag, 'KEYFORMAT'); - let drmParser = + const drmParser = shaka.hls.HlsParser.KEYFORMATS_TO_DRM_PARSERS_[keyFormat]; - let drmInfo = drmParser ? drmParser(drmTag) : null; + const drmInfo = drmParser ? drmParser(drmTag) : null; if (drmInfo) { if (drmInfo.keyIds.length) { keyId = drmInfo.keyIds[0]; @@ -1201,18 +1202,18 @@ shaka.hls.HlsParser.prototype.createStreamInfo_ = async function( /** @type {string} */ const mimeType = mimeTypeArg; - let mediaSequenceTag = Utils.getFirstTagWithName(playlist.tags, + const mediaSequenceTag = Utils.getFirstTagWithName(playlist.tags, 'EXT-X-MEDIA-SEQUENCE'); - let startPosition = mediaSequenceTag ? Number(mediaSequenceTag.value) : 0; + const startPosition = mediaSequenceTag ? Number(mediaSequenceTag.value) : 0; const segments = await this.createSegments_( verbatimMediaPlaylistUri, playlist, startPosition, mimeType, codecs); - let minTimestamp = segments[0].startTime; - let lastEndTime = segments[segments.length - 1].endTime; - let duration = lastEndTime - minTimestamp; - let segmentIndex = new shaka.media.SegmentIndex(segments); + const minTimestamp = segments[0].startTime; + const lastEndTime = segments[segments.length - 1].endTime; + const duration = lastEndTime - minTimestamp; + const segmentIndex = new shaka.media.SegmentIndex(segments); const initSegmentReference = this.createInitSegmentReference_(playlist); @@ -1223,7 +1224,7 @@ shaka.hls.HlsParser.prototype.createStreamInfo_ = async function( /** @type {shaka.extern.Stream} */ - let stream = { + const stream = { id: this.globalId_++, originalId: name, createSegmentIndex: Promise.resolve.bind(Promise), @@ -1272,15 +1273,15 @@ shaka.hls.HlsParser.prototype.createStreamInfo_ = async function( shaka.hls.HlsParser.prototype.determinePresentationType_ = function(playlist) { const Utils = shaka.hls.Utils; const PresentationType = shaka.hls.HlsParser.PresentationType_; - let presentationTypeTag = Utils.getFirstTagWithName(playlist.tags, + const presentationTypeTag = Utils.getFirstTagWithName(playlist.tags, 'EXT-X-PLAYLIST-TYPE'); - let endListTag = Utils.getFirstTagWithName(playlist.tags, 'EXT-X-ENDLIST'); + const endListTag = Utils.getFirstTagWithName(playlist.tags, 'EXT-X-ENDLIST'); - let isVod = (presentationTypeTag && presentationTypeTag.value == 'VOD') || + const isVod = (presentationTypeTag && presentationTypeTag.value == 'VOD') || endListTag; - let isEvent = presentationTypeTag && presentationTypeTag.value == 'EVENT' && + const isEvent = presentationTypeTag && presentationTypeTag.value == 'EVENT' && !isVod; - let isLive = !isVod && !isEvent; + const isLive = !isVod && !isEvent; if (isVod) { this.setPresentationType_(PresentationType.VOD); @@ -1292,9 +1293,9 @@ shaka.hls.HlsParser.prototype.determinePresentationType_ = function(playlist) { this.setPresentationType_(PresentationType.EVENT); } - let targetDurationTag = this.getRequiredTag_(playlist.tags, + const targetDurationTag = this.getRequiredTag_(playlist.tags, 'EXT-X-TARGETDURATION'); - let targetDuration = Number(targetDurationTag.value); + const targetDuration = Number(targetDurationTag.value); // According to the HLS spec, updates should not happen more often than // once in targetDuration. It also requires us to only update the active @@ -1360,7 +1361,7 @@ shaka.hls.HlsParser.prototype.createPresentationTimeline_ = */ shaka.hls.HlsParser.prototype.createInitSegmentReference_ = function(playlist) { const Utils = shaka.hls.Utils; - let mapTags = Utils.filterTagsByName(playlist.tags, 'EXT-X-MAP'); + const mapTags = Utils.filterTagsByName(playlist.tags, 'EXT-X-MAP'); // TODO: Support multiple map tags? // For now, we don't support multiple map tags and will throw an error. if (!mapTags.length) { @@ -1373,7 +1374,7 @@ shaka.hls.HlsParser.prototype.createInitSegmentReference_ = function(playlist) { } // Map tag example: #EXT-X-MAP:URI="main.mp4",BYTERANGE="720@0" - let mapTag = mapTags[0]; + const mapTag = mapTags[0]; const verbatimInitSegmentUri = shaka.hls.HlsParser.getRequiredAttributeValue_(mapTag, 'URI'); const absoluteInitSegmentUri = @@ -1381,12 +1382,12 @@ shaka.hls.HlsParser.prototype.createInitSegmentReference_ = function(playlist) { let startByte = 0; let endByte = null; - let byterange = mapTag.getAttributeValue('BYTERANGE'); + const byterange = mapTag.getAttributeValue('BYTERANGE'); // If a BYTERANGE attribute is not specified, the segment consists // of the entire resource. if (byterange) { - let blocks = byterange.split('@'); - let byteLength = Number(blocks[0]); + const blocks = byterange.split('@'); + const byteLength = Number(blocks[0]); startByte = Number(blocks[1]); endByte = startByte + byteLength - 1; } @@ -1415,21 +1416,21 @@ shaka.hls.HlsParser.prototype.createSegmentReference_ = const tags = hlsSegment.tags; const absoluteSegmentUri = hlsSegment.absoluteUri; - let extinfTag = this.getRequiredTag_(tags, 'EXTINF'); + const extinfTag = this.getRequiredTag_(tags, 'EXTINF'); // The EXTINF tag format is '#EXTINF:,[]'. // We're interested in the duration part. - let extinfValues = extinfTag.value.split(','); - let duration = Number(extinfValues[0]); - let endTime = startTime + duration; + const extinfValues = extinfTag.value.split(','); + const duration = Number(extinfValues[0]); + const endTime = startTime + duration; let startByte = 0; let endByte = null; - let byterange = Utils.getFirstTagWithName(tags, 'EXT-X-BYTERANGE'); + const byterange = Utils.getFirstTagWithName(tags, 'EXT-X-BYTERANGE'); // If BYTERANGE is not specified, the segment consists of the entire resource. if (byterange) { - let blocks = byterange.value.split('@'); - let byteLength = Number(blocks[0]); + const blocks = byterange.value.split('@'); + const byteLength = Number(blocks[0]); if (blocks[1]) { startByte = Number(blocks[1]); } else { @@ -1501,12 +1502,12 @@ shaka.hls.HlsParser.prototype.createSegments_ = async function( shaka.log.debug('First segment', firstSegmentUri.split('/').pop(), 'starts at', firstStartTime); for (let i = 0; i < hlsSegments.length; ++i) { - let hlsSegment = hlsSegments[i]; - let previousReference = references[references.length - 1]; - let startTime = (i == 0) ? firstStartTime : previousReference.endTime; - let position = startPosition + i; + const hlsSegment = hlsSegments[i]; + const previousReference = references[references.length - 1]; + const startTime = (i == 0) ? firstStartTime : previousReference.endTime; + const position = startPosition + i; - let reference = this.createSegmentReference_( + const reference = this.createSegmentReference_( playlist, previousReference, hlsSegment, @@ -1736,7 +1737,7 @@ shaka.hls.HlsParser.prototype.getStartTimeFromMp4Segment_ = goog.asserts.assert( box.version == 0 || box.version == 1, 'TFDT version can only be 0 or 1'); - let baseTime = (box.version == 0) ? + const baseTime = (box.version == 0) ? box.reader.readUint32() : box.reader.readUint64(); startTime = baseTime / timescale; @@ -1763,7 +1764,7 @@ shaka.hls.HlsParser.prototype.getStartTimeFromMp4Segment_ = * @private */ shaka.hls.HlsParser.prototype.getStartTimeFromTsSegment_ = function(data) { - let reader = new shaka.util.DataViewReader( + const reader = new shaka.util.DataViewReader( new DataView(data), shaka.util.DataViewReader.Endianness.BIG_ENDIAN); const fail = function() { @@ -1807,12 +1808,12 @@ shaka.hls.HlsParser.prototype.getStartTimeFromTsSegment_ = function(data) { syncByte = reader.readUint8(); if (syncByte != 0x47) fail(); - let flagsAndPacketId = reader.readUint16(); - let hasPesPacket = flagsAndPacketId & 0x4000; + const flagsAndPacketId = reader.readUint16(); + const hasPesPacket = flagsAndPacketId & 0x4000; if (!hasPesPacket) fail(); - let flags = reader.readUint8(); - let adaptationFieldControl = (flags & 0x30) >> 4; + const flags = reader.readUint8(); + const adaptationFieldControl = (flags & 0x30) >> 4; if (adaptationFieldControl == 0 /* reserved */ || adaptationFieldControl == 2 /* adaptation field, no payload */) { fail(); @@ -1820,14 +1821,14 @@ shaka.hls.HlsParser.prototype.getStartTimeFromTsSegment_ = function(data) { if (adaptationFieldControl == 3) { // Skip over adaptation field. - let length = reader.readUint8(); + const length = reader.readUint8(); reader.skip(length); } // Now we come to the PES header (hopefully). // Format reference: https://bit.ly/TsPES - let startCode = reader.readUint32(); - let startCodePrefix = startCode >> 8; + const startCode = reader.readUint32(); + const startCodePrefix = startCode >> 8; if (startCodePrefix != 1) { // Not a PES packet yet. Skip this TS packet and try again. skipPacket(); @@ -1837,13 +1838,13 @@ shaka.hls.HlsParser.prototype.getStartTimeFromTsSegment_ = function(data) { // Skip the 16-bit PES length and the first 8 bits of the optional header. reader.skip(3); // The next 8 bits contain flags about DTS & PTS. - let ptsDtsIndicator = reader.readUint8() >> 6; + const ptsDtsIndicator = reader.readUint8() >> 6; if (ptsDtsIndicator == 0 /* no timestamp */ || ptsDtsIndicator == 1 /* forbidden */) { fail(); } - let pesHeaderLengthRemaining = reader.readUint8(); + const pesHeaderLengthRemaining = reader.readUint8(); if (pesHeaderLengthRemaining == 0) { fail(); } @@ -1854,15 +1855,15 @@ shaka.hls.HlsParser.prototype.getStartTimeFromTsSegment_ = function(data) { goog.asserts.assert(pesHeaderLengthRemaining == 10, 'Bad PES header?'); } - let pts0 = reader.readUint8(); - let pts1 = reader.readUint16(); - let pts2 = reader.readUint16(); + const pts0 = reader.readUint8(); + const pts1 = reader.readUint16(); + const pts2 = reader.readUint16(); // Reconstruct 33-bit PTS from the 5-byte, padded structure. - let ptsHigh3 = (pts0 & 0x0e) >> 1; - let ptsLow30 = ((pts1 & 0xfffe) << 14) | ((pts2 & 0xfffe) >> 1); + const ptsHigh3 = (pts0 & 0x0e) >> 1; + const ptsLow30 = ((pts1 & 0xfffe) << 14) | ((pts2 & 0xfffe) >> 1); // Reconstruct the PTS as a float. Avoid bitwise operations to combine // because bitwise ops treat the values as 32-bit ints. - let pts = ptsHigh3 * (1 << 30) + ptsLow30; + const pts = ptsHigh3 * (1 << 30) + ptsLow30; return pts / shaka.hls.HlsParser.TS_TIMESCALE_; } }; @@ -1880,14 +1881,14 @@ shaka.hls.HlsParser.prototype.getStartTimeFromTsSegment_ = function(data) { */ shaka.hls.HlsParser.prototype.getStartTimeFromTextSegment_ = function(mimeType, codecs, data) { - let fullMimeType = shaka.util.MimeUtils.getFullType(mimeType, codecs); + const fullMimeType = shaka.util.MimeUtils.getFullType(mimeType, codecs); if (!shaka.text.TextEngine.isTypeSupported(fullMimeType)) { // We won't be able to parse this, but it will be filtered out anyway. // So we don't have to care about the start time. return 0; } - let textEngine = new shaka.text.TextEngine(/* displayer */ null); + const textEngine = new shaka.text.TextEngine(/* displayer */ null); textEngine.initParser(fullMimeType); return textEngine.getStartTime(data); }; @@ -1933,7 +1934,7 @@ shaka.hls.HlsParser.filterDuplicateCodecs_ = function(codecs) { shaka.hls.HlsParser.prototype.guessCodecsSafe_ = function(contentType, codecs) { const ContentType = shaka.util.ManifestParserUtils.ContentType; const HlsParser = shaka.hls.HlsParser; - let formats = HlsParser.CODEC_REGEXPS_BY_CONTENT_TYPE_[contentType]; + const formats = HlsParser.CODEC_REGEXPS_BY_CONTENT_TYPE_[contentType]; for (let i = 0; i < formats.length; i++) { for (let j = 0; j < codecs.length; j++) { @@ -1967,7 +1968,7 @@ shaka.hls.HlsParser.prototype.guessCodecs_ = function(contentType, codecs) { return codecs[0]; } - let match = this.guessCodecsSafe_(contentType, codecs); + const match = this.guessCodecsSafe_(contentType, codecs); // A failure is specifically denoted by null; an empty string represents a // valid match of no codec. if (match != null) { @@ -2003,11 +2004,11 @@ shaka.hls.HlsParser.prototype.guessMimeType_ = 'Playlist should have segments!'); const firstSegmentUri = playlist.segments[0].absoluteUri; - let parsedUri = new goog.Uri(firstSegmentUri); - let extension = parsedUri.getPath().split('.').pop(); - let map = HlsParser.EXTENSION_MAP_BY_CONTENT_TYPE_[contentType]; + const parsedUri = new goog.Uri(firstSegmentUri); + const extension = parsedUri.getPath().split('.').pop(); + const map = HlsParser.EXTENSION_MAP_BY_CONTENT_TYPE_[contentType]; - let mimeType = map[extension]; + const mimeType = map[extension]; if (mimeType) { return mimeType; } @@ -2027,7 +2028,7 @@ shaka.hls.HlsParser.prototype.guessMimeType_ = // If unable to guess mime type, request a segment and try getting it // from the response. - let headRequest = shaka.net.NetworkingEngine.makeRequest( + const headRequest = shaka.net.NetworkingEngine.makeRequest( [firstSegmentUri], this.config_.retryParameters); headRequest.method = 'HEAD'; @@ -2060,7 +2061,7 @@ shaka.hls.HlsParser.prototype.guessMimeType_ = * @throws {shaka.util.Error} */ shaka.hls.HlsParser.getRequiredAttributeValue_ = function(tag, attributeName) { - let attribute = tag.getAttribute(attributeName); + const attribute = tag.getAttribute(attributeName); if (!attribute) { throw new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, @@ -2085,7 +2086,7 @@ shaka.hls.HlsParser.getRequiredAttributeValue_ = function(tag, attributeName) { */ shaka.hls.HlsParser.prototype.getRequiredTag_ = function(tags, tagName) { const Utils = shaka.hls.Utils; - let tag = Utils.getFirstTagWithName(tags, tagName); + const tag = Utils.getFirstTagWithName(tags, tagName); if (!tag) { throw new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, @@ -2251,7 +2252,7 @@ shaka.hls.HlsParser.DrmParser_; */ shaka.hls.HlsParser.widevineDrmParser_ = function(drmTag) { const HlsParser = shaka.hls.HlsParser; - let method = HlsParser.getRequiredAttributeValue_(drmTag, 'METHOD'); + const method = HlsParser.getRequiredAttributeValue_(drmTag, 'METHOD'); shaka.Deprecate.deprecateFeature( 2, 6, 'HLS SAMPLE-AES-CENC', @@ -2263,17 +2264,17 @@ shaka.hls.HlsParser.widevineDrmParser_ = function(drmTag) { return null; } - let uri = HlsParser.getRequiredAttributeValue_(drmTag, 'URI'); - let parsedData = shaka.net.DataUriPlugin.parse(uri); + const uri = HlsParser.getRequiredAttributeValue_(drmTag, 'URI'); + const parsedData = shaka.net.DataUriPlugin.parse(uri); // The data encoded in the URI is a PSSH box to be used as init data. - let pssh = new Uint8Array(parsedData.data); - let drmInfo = shaka.util.ManifestParserUtils.createDrmInfo( + const pssh = new Uint8Array(parsedData.data); + const drmInfo = shaka.util.ManifestParserUtils.createDrmInfo( 'com.widevine.alpha', [ {initDataType: 'cenc', initData: pssh}, ]); - let keyId = drmTag.getAttributeValue('KEYID'); + const keyId = drmTag.getAttributeValue('KEYID'); if (keyId) { // This value should begin with '0x': goog.asserts.assert(keyId.startsWith('0x'), 'Incorrect KEYID format!'); diff --git a/lib/hls/hls_utils.js b/lib/hls/hls_utils.js index d2cd196167..6cd28b73b5 100644 --- a/lib/hls/hls_utils.js +++ b/lib/hls/hls_utils.js @@ -40,7 +40,7 @@ shaka.hls.Utils.filterTagsByName = function(tags, name) { * @return {?shaka.hls.Tag} */ shaka.hls.Utils.getFirstTagWithName = function(tags, name) { - let tagsWithName = shaka.hls.Utils.filterTagsByName(tags, name); + const tagsWithName = shaka.hls.Utils.filterTagsByName(tags, name); if (!tagsWithName.length) return null; return tagsWithName[0]; @@ -56,8 +56,8 @@ shaka.hls.Utils.getFirstTagWithName = function(tags, name) { */ shaka.hls.Utils.findMediaTags = function(tags, type, groupId) { return tags.filter(function(tag) { - let typeAttr = tag.getAttribute('TYPE'); - let groupIdAttr = tag.getAttribute('GROUP-ID'); + const typeAttr = tag.getAttribute('TYPE'); + const groupIdAttr = tag.getAttribute('GROUP-ID'); return typeAttr.value == type && groupIdAttr.value == groupId; }); }; @@ -69,7 +69,7 @@ shaka.hls.Utils.findMediaTags = function(tags, type, groupId) { * @return {string} */ shaka.hls.Utils.constructAbsoluteUri = function(parentAbsoluteUri, uri) { - let uris = shaka.util.ManifestParserUtils.resolveUris( + const uris = shaka.util.ManifestParserUtils.resolveUris( [parentAbsoluteUri], [uri]); return uris[0]; diff --git a/lib/hls/manifest_text_parser.js b/lib/hls/manifest_text_parser.js index 1ad4f47f7f..34da8f4727 100644 --- a/lib/hls/manifest_text_parser.js +++ b/lib/hls/manifest_text_parser.js @@ -140,12 +140,12 @@ shaka.hls.ManifestTextParser.prototype.parsePlaylist = shaka.hls.ManifestTextParser.prototype.parseSegments_ = function(absoluteMediaPlaylistUri, lines, playlistTags) { /** @type {!Array.<shaka.hls.Segment>} */ - let segments = []; + const segments = []; /** @type {!Array.<shaka.hls.Tag>} */ let segmentTags = []; lines.forEach((line) => { if (/^(#EXT)/.test(line)) { - let tag = this.parseTag_(line); + const tag = this.parseTag_(line); if (shaka.hls.ManifestTextParser.MEDIA_PLAYLIST_TAGS.includes(tag.name)) { playlistTags.push(tag); } else { diff --git a/lib/media/drm_engine.js b/lib/media/drm_engine.js index 85fb1d8d4a..c1a29b8214 100644 --- a/lib/media/drm_engine.js +++ b/lib/media/drm_engine.js @@ -488,7 +488,7 @@ shaka.media.DrmEngine.prototype.attach = function(video) { exception.message)); }); - let setServerCertificate = this.setServerCertificate(); + const setServerCertificate = this.setServerCertificate(); return Promise.all([setMediaKeys, setServerCertificate]).then(() => { if (this.isDestroying_) { return Promise.reject(); } @@ -586,7 +586,7 @@ shaka.media.DrmEngine.prototype.removeSession = async function(sessionId) { */ shaka.media.DrmEngine.prototype.createOrLoad = function() { // Create temp sessions. - let initDatas = this.currentDrmInfo_ ? this.currentDrmInfo_.initData : []; + const initDatas = this.currentDrmInfo_ ? this.currentDrmInfo_.initData : []; initDatas.forEach((initDataOverride) => { return this.createTemporarySession_(initDataOverride.initDataType, initDataOverride.initData); @@ -857,7 +857,7 @@ shaka.media.DrmEngine.prototype.queryMediaKeys_ = function(configsByKeySystem) { } // Wait to reject this initial Promise until we have built the entire chain. - let instigator = new shaka.util.PublicPromise(); + const instigator = new shaka.util.PublicPromise(); let p = instigator; // Try key systems with configured license servers first. We only have to try @@ -867,7 +867,7 @@ shaka.media.DrmEngine.prototype.queryMediaKeys_ = function(configsByKeySystem) { // former takes precedence. [true, false].forEach(function(shouldHaveLicenseServer) { configsByKeySystem.forEach((config, keySystem) => { - let hasLicenseServer = config.drmInfos.some(function(info) { + const hasLicenseServer = config.drmInfos.some(function(info) { return !!info.licenseServerUri; }); if (hasLicenseServer != shouldHaveLicenseServer) return; @@ -966,13 +966,13 @@ shaka.media.DrmEngine.prototype.configureClearKey_ = function() { const StringUtils = shaka.util.StringUtils; const Uint8ArrayUtils = shaka.util.Uint8ArrayUtils; - let keys = []; - let keyIds = []; + const keys = []; + const keyIds = []; clearKeys.forEach((keyHex, keyIdHex) => { - let keyId = Uint8ArrayUtils.fromHex(keyIdHex); - let key = Uint8ArrayUtils.fromHex(keyHex); - let keyObj = { + const keyId = Uint8ArrayUtils.fromHex(keyIdHex); + const key = Uint8ArrayUtils.fromHex(keyHex); + const keyObj = { kty: 'oct', kid: Uint8ArrayUtils.toBase64(keyId, false), k: Uint8ArrayUtils.toBase64(key, false), @@ -982,15 +982,15 @@ shaka.media.DrmEngine.prototype.configureClearKey_ = function() { keyIds.push(keyObj.kid); }); - let jwkSet = {keys: keys}; - let license = JSON.stringify(jwkSet); + const jwkSet = {keys: keys}; + const license = JSON.stringify(jwkSet); // Use the keyids init data since is suggested by EME. // Suggestion: https://bit.ly/2JYcNTu // Format: https://www.w3.org/TR/eme-initdata-keyids/ - let initDataStr = JSON.stringify({'kids': keyIds}); - let initData = new Uint8Array(StringUtils.toUTF8(initDataStr)); - let initDatas = [{initData: initData, initDataType: 'keyids'}]; + const initDataStr = JSON.stringify({'kids': keyIds}); + const initData = new Uint8Array(StringUtils.toUTF8(initDataStr)); + const initDatas = [{initData: initData, initDataType: 'keyids'}]; return { keySystem: 'org.w3.clearkey', @@ -1017,7 +1017,7 @@ shaka.media.DrmEngine.prototype.loadOfflineSession_ = function(sessionId) { shaka.log.v1('Attempting to load an offline session', sessionId); session = this.mediaKeys_.createSession('persistent-license'); } catch (exception) { - let error = new shaka.util.Error( + const error = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.DRM, shaka.util.Error.Code.FAILED_TO_CREATE_SESSION, @@ -1168,7 +1168,7 @@ shaka.media.DrmEngine.prototype.delayLicenseRequest_ = function() { */ shaka.media.DrmEngine.prototype.sendLicenseRequest_ = function(event) { /** @type {!MediaKeySession} */ - let session = event.target; + const session = event.target; shaka.log.v2('Sending license request for session', session.sessionId); const metadata = this.activeSessions_.get(session); @@ -1181,7 +1181,7 @@ shaka.media.DrmEngine.prototype.sendLicenseRequest_ = function(event) { } const requestType = shaka.net.NetworkingEngine.RequestType.LICENSE; - let request = shaka.net.NetworkingEngine.makeRequest( + const request = shaka.net.NetworkingEngine.makeRequest( [url], this.config_.retryParameters); request.body = event.message; request.method = 'POST'; @@ -1206,7 +1206,7 @@ shaka.media.DrmEngine.prototype.sendLicenseRequest_ = function(event) { // Request succeeded, now pass the response to the CDM. return session.update(response.data).then(function() { - let event = new shaka.util.FakeEvent('drmsessionupdate'); + const event = new shaka.util.FakeEvent('drmsessionupdate'); this.playerInterface_.onEvent(event); if (metadata) { @@ -1234,7 +1234,7 @@ shaka.media.DrmEngine.prototype.sendLicenseRequest_ = function(event) { // Request failed! goog.asserts.assert(error instanceof shaka.util.Error, 'Wrong NetworkingEngine error type!'); - let shakaErr = new shaka.util.Error( + const shakaErr = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.DRM, shaka.util.Error.Code.LICENSE_REQUEST_FAILED, @@ -1248,7 +1248,7 @@ shaka.media.DrmEngine.prototype.sendLicenseRequest_ = function(event) { if (this.isDestroying_) { return; } // Session update failed! - let shakaErr = new shaka.util.Error( + const shakaErr = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.DRM, shaka.util.Error.Code.LICENSE_RESPONSE_REJECTED, @@ -1289,7 +1289,7 @@ shaka.media.DrmEngine.prototype.unpackPlayReadyRequest_ = function(request) { // </LicenseAcquisition> // </PlayReadyKeyMessage> - let xml = shaka.util.StringUtils.fromUTF16( + const xml = shaka.util.StringUtils.fromUTF16( request.body, true /* littleEndian */, true /* noThrow */); if (!xml.includes('PlayReadyKeyMessage')) { // This does not appear to be a wrapped message as on IE and Edge. Some @@ -1301,19 +1301,19 @@ shaka.media.DrmEngine.prototype.unpackPlayReadyRequest_ = function(request) { return; } shaka.log.debug('Unwrapping PlayReady request.'); - let dom = new DOMParser().parseFromString(xml, 'application/xml'); + const dom = new DOMParser().parseFromString(xml, 'application/xml'); // Set request headers. - let headers = dom.getElementsByTagName('HttpHeader'); + const headers = dom.getElementsByTagName('HttpHeader'); for (let i = 0; i < headers.length; ++i) { - let name = headers[i].querySelector('name'); - let value = headers[i].querySelector('value'); + const name = headers[i].querySelector('name'); + const value = headers[i].querySelector('value'); goog.asserts.assert(name && value, 'Malformed PlayReady headers!'); request.headers[name.textContent] = value.textContent; } // Unpack the base64-encoded challenge. - let challenge = dom.querySelector('Challenge'); + const challenge = dom.querySelector('Challenge'); goog.asserts.assert(challenge, 'Malformed PlayReady challenge!'); goog.asserts.assert(challenge.getAttribute('encoding') == 'base64encoded', 'Unexpected PlayReady challenge encoding!'); @@ -1398,7 +1398,7 @@ shaka.media.DrmEngine.prototype.onKeyStatusesChange_ = function(event) { shaka.log.v2('Key status changed for session', session.sessionId); const found = this.activeSessions_.get(session); - let keyStatusMap = session.keyStatuses; + const keyStatusMap = session.keyStatuses; let hasExpiredKeys = false; keyStatusMap.forEach(function(status, keyId) { @@ -1407,7 +1407,7 @@ shaka.media.DrmEngine.prototype.onKeyStatusesChange_ = function(event) { // EME spec. Given the back and forth in the spec, it may not be the only // one. Try to detect this and compensate: if (typeof keyId == 'string') { - let tmp = keyId; + const tmp = keyId; keyId = /** @type {ArrayBuffer} */(status); status = /** @type {string} */(tmp); } @@ -1425,10 +1425,10 @@ shaka.media.DrmEngine.prototype.onKeyStatusesChange_ = function(event) { keyId.byteLength == 16 && !shaka.util.Platform.isTizen()) { // Read out some fields in little-endian: - let dataView = new DataView(keyId); - let part0 = dataView.getUint32(0, true /* LE */); - let part1 = dataView.getUint16(4, true /* LE */); - let part2 = dataView.getUint16(6, true /* LE */); + const dataView = new DataView(keyId); + const part0 = dataView.getUint32(0, true /* LE */); + const part1 = dataView.getUint16(4, true /* LE */); + const part2 = dataView.getUint16(6, true /* LE */); // Write it back in big-endian: dataView.setUint32(0, part0, false /* BE */); dataView.setUint16(4, part1, false /* BE */); @@ -1461,7 +1461,7 @@ shaka.media.DrmEngine.prototype.onKeyStatusesChange_ = function(event) { hasExpiredKeys = true; } - let keyIdHex = shaka.util.Uint8ArrayUtils.toHex(new Uint8Array(keyId)); + const keyIdHex = shaka.util.Uint8ArrayUtils.toHex(new Uint8Array(keyId)); this.keyStatusByKeyId_.set(keyIdHex, status); }.bind(this)); @@ -1469,7 +1469,7 @@ shaka.media.DrmEngine.prototype.onKeyStatusesChange_ = function(event) { // If the session has expired, close it. // Some CDMs do not have sub-second time resolution, so the key status may // fire with hundreds of milliseconds left until the stated expiration time. - let msUntilExpiration = session.expiration - Date.now(); + const msUntilExpiration = session.expiration - Date.now(); if (msUntilExpiration < 0 || (hasExpiredKeys && msUntilExpiration < 1000)) { // If this is part of a remove(), we don't want to close the session until // the update is complete. Otherwise, we will orphan the session. @@ -1532,7 +1532,7 @@ shaka.media.DrmEngine.prototype.processKeyStatusChanges_ = function() { * @return {boolean} */ shaka.media.DrmEngine.isBrowserSupported = function() { - let basic = + const basic = !!window.MediaKeys && !!window.navigator && !!window.navigator.requestMediaKeySystemAccess && @@ -1552,7 +1552,7 @@ shaka.media.DrmEngine.probeSupport = function() { goog.asserts.assert(shaka.media.DrmEngine.isBrowserSupported(), 'Must have basic EME support'); - let testKeySystems = [ + const testKeySystems = [ 'org.w3.clearkey', 'com.widevine.alpha', 'com.microsoft.playready', @@ -1563,15 +1563,15 @@ shaka.media.DrmEngine.probeSupport = function() { 'com.adobe.primetime', ]; - let basicVideoCapabilities = [ + const basicVideoCapabilities = [ {contentType: 'video/mp4; codecs="avc1.42E01E"'}, {contentType: 'video/webm; codecs="vp8"'}, ]; - let basicConfig = { + const basicConfig = { videoCapabilities: basicVideoCapabilities, }; - let offlineConfig = { + const offlineConfig = { videoCapabilities: basicVideoCapabilities, persistentState: 'required', sessionTypes: ['persistent-license'], @@ -1593,7 +1593,7 @@ shaka.media.DrmEngine.probeSupport = function() { // assume no support for persistent-license. // TODO: Polyfill Edge to return known supported session types. // Edge bug: https://bit.ly/2IeKzho - let sessionTypes = access.getConfiguration().sessionTypes; + const sessionTypes = access.getConfiguration().sessionTypes; let persistentState = sessionTypes ? sessionTypes.includes('persistent-license') : false; @@ -1696,22 +1696,22 @@ shaka.media.DrmEngine.getCommonDrmInfos = function(drms1, drms2) { if (!drms1.length) return drms2; if (!drms2.length) return drms1; - let commonDrms = []; + const commonDrms = []; for (let i = 0; i < drms1.length; i++) { for (let j = 0; j < drms2.length; j++) { // This method is only called to compare drmInfos of a video and an audio // adaptations, so we shouldn't have to worry about checking robustness. if (drms1[i].keySystem == drms2[j].keySystem) { - let drm1 = drms1[i]; - let drm2 = drms2[j]; + const drm1 = drms1[i]; + const drm2 = drms2[j]; let initData = []; initData = initData.concat(drm1.initData || []); initData = initData.concat(drm2.initData || []); let keyIds = []; keyIds = keyIds.concat(drm1.keyIds); keyIds = keyIds.concat(drm2.keyIds); - let mergedDrm = { + const mergedDrm = { keySystem: drm1.keySystem, licenseServerUri: drm1.licenseServerUri || drm2.licenseServerUri, distinctiveIdentifierRequired: drm1.distinctiveIdentifierRequired || @@ -1742,7 +1742,7 @@ shaka.media.DrmEngine.getCommonDrmInfos = function(drms1, drms2) { */ shaka.media.DrmEngine.prototype.pollExpiration_ = function() { this.activeSessions_.forEach((metadata, session) => { - let oldTime = metadata.oldExpiration; + const oldTime = metadata.oldExpiration; let newTime = session.expiration; if (isNaN(newTime)) { newTime = Infinity; @@ -1809,16 +1809,16 @@ shaka.media.DrmEngine.replaceDrmInfo_ = function(variants, keySystems) { */ shaka.media.DrmEngine.createDrmInfoFor_ = function(keySystem, config) { /** @type {!Array.<string>} */ - let licenseServers = []; + const licenseServers = []; /** @type {!Array.<!Uint8Array>} */ - let serverCerts = []; + const serverCerts = []; /** @type {!Array.<!shaka.extern.InitDataOverride>} */ - let initDatas = []; + const initDatas = []; /** @type {!Array.<string>} */ - let keyIds = []; + const keyIds = []; shaka.media.DrmEngine.processDrmInfos_( config.drmInfos, licenseServers, serverCerts, initDatas, keyIds); @@ -1834,9 +1834,9 @@ shaka.media.DrmEngine.createDrmInfoFor_ = function(keySystem, config) { } // TODO: This only works when all DrmInfo have the same robustness. - let audioRobustness = + const audioRobustness = config.audioCapabilities ? config.audioCapabilities[0].robustness : ''; - let videoRobustness = + const videoRobustness = config.videoCapabilities ? config.videoCapabilities[0].robustness : ''; return { @@ -1868,7 +1868,7 @@ shaka.media.DrmEngine.processDrmInfos_ = function(drmInfos, licenseServers, serverCerts, initDatas, keyIds) { /** @type {function(shaka.extern.InitDataOverride, * shaka.extern.InitDataOverride):boolean} */ - let initDataOverrideEqual = (a, b) => { + const initDataOverrideEqual = (a, b) => { if (a.keyId && a.keyId == b.keyId) { // Two initDatas with the same keyId are considered to be the same, // unless that "same keyId" is null. diff --git a/lib/media/gap_jumping_controller.js b/lib/media/gap_jumping_controller.js index 178967a00c..36bc8255f3 100644 --- a/lib/media/gap_jumping_controller.js +++ b/lib/media/gap_jumping_controller.js @@ -181,10 +181,11 @@ shaka.media.GapJumpingController.prototype.onPollGapJump_ = function() { } const smallGapLimit = this.config_.smallGapLimit; - let currentTime = this.video_.currentTime; - let buffered = this.video_.buffered; + const currentTime = this.video_.currentTime; + const buffered = this.video_.buffered; - let gapIndex = shaka.media.TimeRangesUtils.getGapIndex(buffered, currentTime); + const gapIndex = + shaka.media.TimeRangesUtils.getGapIndex(buffered, currentTime); // The current time is unbuffered or is too far from a gap. if (gapIndex == null) { @@ -203,14 +204,14 @@ shaka.media.GapJumpingController.prototype.onPollGapJump_ = function() { // StreamingEngine can buffer past the seek end, but still don't allow seeking // past it. - let jumpTo = buffered.start(gapIndex); - let seekEnd = this.timeline_.getSeekRangeEnd(); + const jumpTo = buffered.start(gapIndex); + const seekEnd = this.timeline_.getSeekRangeEnd(); if (jumpTo >= seekEnd) { return; } - let jumpSize = jumpTo - currentTime; - let isGapSmall = jumpSize <= smallGapLimit; + const jumpSize = jumpTo - currentTime; + const isGapSmall = jumpSize <= smallGapLimit; let jumpLargeGap = false; // If we jump to exactly the gap start, we may detect a small gap due to @@ -224,7 +225,7 @@ shaka.media.GapJumpingController.prototype.onPollGapJump_ = function() { this.didFireLargeGap_ = true; // Event firing is synchronous. - let event = new shaka.util.FakeEvent( + const event = new shaka.util.FakeEvent( 'largegap', {'currentTime': currentTime, 'gapSize': jumpSize}); event.cancelable = true; this.onEvent_(event); diff --git a/lib/media/manifest_parser.js b/lib/media/manifest_parser.js index 12efaee91d..8692b7f354 100644 --- a/lib/media/manifest_parser.js +++ b/lib/media/manifest_parser.js @@ -83,15 +83,15 @@ shaka.media.ManifestParser.registerParserByMime = function( */ shaka.media.ManifestParser.probeSupport = function() { const ManifestParser = shaka.media.ManifestParser; - let support = {}; + const support = {}; // Make sure all registered parsers are shown, but only for MSE-enabled // platforms where our parsers matter. if (shaka.util.Platform.supportsMediaSource()) { - for (let type in ManifestParser.parsersByMime) { + for (const type in ManifestParser.parsersByMime) { support[type] = true; } - for (let type in ManifestParser.parsersByExtension) { + for (const type in ManifestParser.parsersByExtension) { support[type] = true; } } @@ -116,7 +116,7 @@ shaka.media.ManifestParser.probeSupport = function() { 'ism': 'application/vnd.ms-sstr+xml', }; - for (let type of testMimeTypes) { + for (const type of testMimeTypes) { // Only query our parsers for MSE-enabled platforms. Otherwise, query a // temporary media element for native support for these types. if (shaka.util.Platform.supportsMediaSource()) { @@ -126,7 +126,7 @@ shaka.media.ManifestParser.probeSupport = function() { } } - for (let extension in testExtensions) { + for (const extension in testExtensions) { // Only query our parsers for MSE-enabled platforms. Otherwise, query a // temporary media element for native support for these MIME type for the // extension. @@ -242,14 +242,14 @@ shaka.media.ManifestParser.getMimeType = async function( uri, netEngine, retryParams) { const type = shaka.net.NetworkingEngine.RequestType.MANIFEST; - let request = shaka.net.NetworkingEngine.makeRequest([uri], retryParams); + const request = shaka.net.NetworkingEngine.makeRequest([uri], retryParams); request.method = 'HEAD'; - let response = await netEngine.request(type, request).promise; + const response = await netEngine.request(type, request).promise; // https://bit.ly/2K9s9kf says this header should always be available, // but just to be safe: - let mimeType = response.headers['content-type']; + const mimeType = response.headers['content-type']; return mimeType ? mimeType.toLowerCase() : ''; }; diff --git a/lib/media/media_source_engine.js b/lib/media/media_source_engine.js index 71662a03b8..5d2ccb53d4 100644 --- a/lib/media/media_source_engine.js +++ b/lib/media/media_source_engine.js @@ -114,7 +114,7 @@ shaka.media.MediaSourceEngine.createObjectURL = window.URL.createObjectURL; * @return {!MediaSource} */ shaka.media.MediaSourceEngine.prototype.createMediaSource = function(p) { - let mediaSource = new MediaSource(); + const mediaSource = new MediaSource(); // Set up MediaSource on the video element. this.eventManager_.listenOnce(mediaSource, 'sourceopen', p.resolve); @@ -146,9 +146,9 @@ shaka.media.MediaSourceEngine.Operation; * @return {boolean} */ shaka.media.MediaSourceEngine.isStreamSupported = function(stream) { - let fullMimeType = shaka.util.MimeUtils.getFullType( + const fullMimeType = shaka.util.MimeUtils.getFullType( stream.mimeType, stream.codecs); - let extendedMimeType = shaka.util.MimeUtils.getExtendedType(stream); + const extendedMimeType = shaka.util.MimeUtils.getExtendedType(stream); return shaka.text.TextEngine.isTypeSupported(fullMimeType) || MediaSource.isTypeSupported(extendedMimeType) || shaka.media.Transmuxer.isSupported(fullMimeType, stream.type); @@ -197,8 +197,8 @@ shaka.media.MediaSourceEngine.probeSupport = function() { 'application/mp4; codecs="stpp"', ]; - let support = {}; - for (let type of testMimeTypes) { + const support = {}; + for (const type of testMimeTypes) { if (shaka.util.Platform.supportsMediaSource()) { // Our TextEngine is only effective for MSE platforms at the moment. if (shaka.text.TextEngine.isTypeSupported(type)) { @@ -224,12 +224,12 @@ shaka.media.MediaSourceEngine.prototype.destroy = function() { const Functional = shaka.util.Functional; this.destroyed_ = true; - let cleanup = []; + const cleanup = []; - for (let contentType in this.queues_) { + for (const contentType in this.queues_) { // Make a local copy of the queue and the first item. - let q = this.queues_[contentType]; - let inProgress = q[0]; + const q = this.queues_[contentType]; + const inProgress = q[0]; // Drop everything else out of the original queue. this.queues_[contentType] = q.slice(0, 1); @@ -253,7 +253,7 @@ shaka.media.MediaSourceEngine.prototype.destroy = function() { cleanup.push(this.textDisplayer_.destroy()); } - for (let contentType in this.transmuxers_) { + for (const contentType in this.transmuxers_) { cleanup.push(this.transmuxers_[contentType].destroy()); } @@ -277,7 +277,7 @@ shaka.media.MediaSourceEngine.prototype.destroy = function() { this.transmuxers_ = {}; this.captionParser_ = null; if (goog.DEBUG) { - for (let contentType in this.queues_) { + for (const contentType in this.queues_) { goog.asserts.assert( this.queues_[contentType].length == 0, contentType + ' queue should be empty after destroy!'); @@ -338,7 +338,7 @@ shaka.media.MediaSourceEngine.prototype.init = async function( mimeType = shaka.media.Transmuxer.convertTsCodecs(contentType, mimeType); } - let sourceBuffer = this.mediaSource_.addSourceBuffer(mimeType); + const sourceBuffer = this.mediaSource_.addSourceBuffer(mimeType); this.eventManager_.listen( sourceBuffer, 'error', this.onError_.bind(this, contentType)); @@ -419,7 +419,7 @@ shaka.media.MediaSourceEngine.prototype.isBuffered = function( if (contentType == ContentType.TEXT) { return this.textEngine_.isBuffered(time); } else { - let buffered = this.getBuffered_(contentType); + const buffered = this.getBuffered_(contentType); return shaka.media.TimeRangesUtils.isBuffered( buffered, time, smallGapLimit); } @@ -440,7 +440,7 @@ shaka.media.MediaSourceEngine.prototype.bufferedAheadOf = if (contentType == ContentType.TEXT) { return this.textEngine_.bufferedAheadOf(time); } else { - let buffered = this.getBuffered_(contentType); + const buffered = this.getBuffered_(contentType); return shaka.media.TimeRangesUtils.bufferedAheadOf(buffered, time); } }; @@ -792,8 +792,8 @@ shaka.media.MediaSourceEngine.prototype.remove_ = */ shaka.media.MediaSourceEngine.prototype.abort_ = function(contentType) { // Save the append window, which is reset on abort(). - let appendWindowStart = this.sourceBuffers_[contentType].appendWindowStart; - let appendWindowEnd = this.sourceBuffers_[contentType].appendWindowEnd; + const appendWindowStart = this.sourceBuffers_[contentType].appendWindowStart; + const appendWindowEnd = this.sourceBuffers_[contentType].appendWindowEnd; // This will not trigger an 'updateend' event, since nothing is happening. // This is only to reset MSE internals, not to abort an actual operation. @@ -879,11 +879,11 @@ shaka.media.MediaSourceEngine.prototype.setAppendWindow_ = */ shaka.media.MediaSourceEngine.prototype.onError_ = function(contentType, event) { - let operation = this.queues_[contentType][0]; + const operation = this.queues_[contentType][0]; goog.asserts.assert(operation, 'Spurious error event!'); goog.asserts.assert(!this.sourceBuffers_[contentType].updating, 'SourceBuffer should not be updating on error!'); - let code = this.video_.error ? this.video_.error.code : 0; + const code = this.video_.error ? this.video_.error.code : 0; operation.p.reject(new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.MEDIA, @@ -902,7 +902,7 @@ shaka.media.MediaSourceEngine.prototype.onError_ = * @private */ shaka.media.MediaSourceEngine.prototype.onUpdateEnd_ = function(contentType) { - let operation = this.queues_[contentType][0]; + const operation = this.queues_[contentType][0]; goog.asserts.assert(operation, 'Spurious updateend event!'); if (!operation) return; goog.asserts.assert(!this.sourceBuffers_[contentType].updating, @@ -924,7 +924,7 @@ shaka.media.MediaSourceEngine.prototype.enqueueOperation_ = function(contentType, start) { if (this.destroyed_) return Promise.reject(); - let operation = { + const operation = { start: start, p: new shaka.util.PublicPromise(), }; @@ -966,14 +966,14 @@ shaka.media.MediaSourceEngine.prototype.enqueueBlockingOperation_ = function(run) { if (this.destroyed_) return Promise.reject(); - let allWaiters = []; + const allWaiters = []; // Enqueue a 'wait' operation onto each queue. // This operation signals its readiness when it starts. // When all wait operations are ready, the real operation takes place. - for (let contentType in this.sourceBuffers_) { - let ready = new shaka.util.PublicPromise(); - let operation = { + for (const contentType in this.sourceBuffers_) { + const ready = new shaka.util.PublicPromise(); + const operation = { start: function(ready) { ready.resolve(); }.bind(null, ready), p: ready, }; @@ -991,7 +991,7 @@ shaka.media.MediaSourceEngine.prototype.enqueueBlockingOperation_ = return Promise.all(allWaiters).then(function() { if (goog.DEBUG) { // If we did it correctly, nothing is updating. - for (let contentType in this.sourceBuffers_) { + for (const contentType in this.sourceBuffers_) { goog.asserts.assert( this.sourceBuffers_[contentType].updating == false, 'SourceBuffers should not be updating after a blocking op!'); @@ -1011,7 +1011,7 @@ shaka.media.MediaSourceEngine.prototype.enqueueBlockingOperation_ = } // Unblock the queues. - for (let contentType in this.sourceBuffers_) { + for (const contentType in this.sourceBuffers_) { this.popFromQueue_(contentType); } @@ -1024,7 +1024,7 @@ shaka.media.MediaSourceEngine.prototype.enqueueBlockingOperation_ = // mode, we will maintain good hygiene and make sure the assert at the end // of destroy passes. In compiled mode, the queues are wiped in destroy. if (goog.DEBUG) { - for (let contentType in this.sourceBuffers_) { + for (const contentType in this.sourceBuffers_) { if (this.queues_[contentType].length) { goog.asserts.assert( this.queues_[contentType].length == 1, @@ -1050,7 +1050,7 @@ shaka.media.MediaSourceEngine.prototype.popFromQueue_ = function(contentType) { // Remove the in-progress operation, which is now complete. this.queues_[contentType].shift(); // Retrieve the next operation, if any, from the queue and start it. - let next = this.queues_[contentType][0]; + const next = this.queues_[contentType][0]; if (next) { try { next.start(); diff --git a/lib/media/mp4_segment_index_parser.js b/lib/media/mp4_segment_index_parser.js index e7b5893687..68ee0b9971 100644 --- a/lib/media/mp4_segment_index_parser.js +++ b/lib/media/mp4_segment_index_parser.js @@ -41,7 +41,7 @@ shaka.media.Mp4SegmentIndexParser = function( let references; - let parser = new shaka.util.Mp4Parser() + const parser = new shaka.util.Mp4Parser() .fullBox('sidx', function(box) { references = Mp4SegmentIndexParser.parseSIDX_( sidxOffset, @@ -86,13 +86,13 @@ shaka.media.Mp4SegmentIndexParser.parseSIDX_ = function( box.version != null, 'SIDX is a full box and should have a valid version.'); - let references = []; + const references = []; // Parse the SIDX structure. // Skip reference_ID (32 bits). box.reader.skip(4); - let timescale = box.reader.readUint32(); + const timescale = box.reader.readUint32(); if (timescale == 0) { shaka.log.error('Invalid timescale.'); @@ -117,7 +117,7 @@ shaka.media.Mp4SegmentIndexParser.parseSIDX_ = function( box.reader.skip(2); // Add references. - let referenceCount = box.reader.readUint16(); + const referenceCount = box.reader.readUint16(); // Substract the presentation time offset let unscaledStartTime = earliestPresentationTime; @@ -125,11 +125,11 @@ shaka.media.Mp4SegmentIndexParser.parseSIDX_ = function( for (let i = 0; i < referenceCount; i++) { // |chunk| is 1 bit for |referenceType|, and 31 bits for |referenceSize|. - let chunk = box.reader.readUint32(); - let referenceType = (chunk & 0x80000000) >>> 31; - let referenceSize = chunk & 0x7FFFFFFF; + const chunk = box.reader.readUint32(); + const referenceType = (chunk & 0x80000000) >>> 31; + const referenceSize = chunk & 0x7FFFFFFF; - let subsegmentDuration = box.reader.readUint32(); + const subsegmentDuration = box.reader.readUint32(); // Skipping 1 bit for |startsWithSap|, 3 bits for |sapType|, and 28 bits // for |sapDelta|. diff --git a/lib/media/playhead.js b/lib/media/playhead.js index 7d1c5d18b4..0b47595ebf 100644 --- a/lib/media/playhead.js +++ b/lib/media/playhead.js @@ -312,9 +312,9 @@ shaka.media.MediaSourcePlayhead = class { return; } - let currentTime = this.mediaElement_.currentTime; + const currentTime = this.mediaElement_.currentTime; let seekStart = this.timeline_.getSeekRangeStart(); - let seekEnd = this.timeline_.getSeekRangeEnd(); + const seekEnd = this.timeline_.getSeekRangeEnd(); if (seekEnd - seekStart < this.minSeekRange_) { seekStart = seekEnd - this.minSeekRange_; @@ -322,7 +322,7 @@ shaka.media.MediaSourcePlayhead = class { if (currentTime < seekStart) { // The seek range has moved past the playhead. Move ahead to catch up. - let targetTime = this.reposition_(currentTime); + const targetTime = this.reposition_(currentTime); shaka.log.info('Jumping forward ' + (targetTime - currentTime) + ' seconds to catch up with the seek range.'); this.mediaElement_.currentTime = targetTime; @@ -336,15 +336,15 @@ shaka.media.MediaSourcePlayhead = class { */ onSeeking_() { this.gapController_.onSeeking(); - let currentTime = this.videoWrapper_.getTime(); - let targetTime = this.reposition_(currentTime); + const currentTime = this.videoWrapper_.getTime(); + const targetTime = this.reposition_(currentTime); const gapLimit = shaka.media.GapJumpingController.BROWSER_GAP_TOLERANCE; if (Math.abs(targetTime - currentTime) > gapLimit) { // You can only seek like this every so often. This is to prevent an // infinite loop on systems where changing currentTime takes a significant // amount of time (e.g. Chromecast). - let time = new Date().getTime() / 1000; + const time = new Date().getTime() / 1000; if (!this.lastCorrectiveSeek_ || this.lastCorrectiveSeek_ < time - 1) { this.lastCorrectiveSeek_ = time; this.videoWrapper_.setTime(targetTime); @@ -367,7 +367,7 @@ shaka.media.MediaSourcePlayhead = class { * @private */ clampSeekToDuration_(time) { - let duration = this.timeline_.getDuration(); + const duration = this.timeline_.getDuration(); if (time >= duration) { goog.asserts.assert(this.config_.durationBackoff >= 0, 'Duration backoff must be non-negative!'); @@ -389,18 +389,18 @@ shaka.media.MediaSourcePlayhead = class { 'Cannot reposition playhead when it has beeen destroyed'); /** @type {function(number)} */ - let isBuffered = shaka.media.TimeRangesUtils.isBuffered.bind( + const isBuffered = shaka.media.TimeRangesUtils.isBuffered.bind( null, this.mediaElement_.buffered); - let rebufferingGoal = Math.max( + const rebufferingGoal = Math.max( this.minBufferTime_, this.config_.rebufferingGoal); const safeSeekOffset = this.config_.safeSeekOffset; let start = this.timeline_.getSeekRangeStart(); - let end = this.timeline_.getSeekRangeEnd(); - let duration = this.timeline_.getDuration(); + const end = this.timeline_.getSeekRangeEnd(); + const duration = this.timeline_.getDuration(); if (end - start < this.minSeekRange_) { start = end - this.minSeekRange_; @@ -410,14 +410,14 @@ shaka.media.MediaSourcePlayhead = class { // forward. This means we cannot seek to it since we will "fall" outside // the window while we buffer. So we define a "safe" region that is far // enough away. For VOD, |safe == start|. - let safe = this.timeline_.getSafeSeekRangeStart(rebufferingGoal); + const safe = this.timeline_.getSafeSeekRangeStart(rebufferingGoal); // These are the times to seek to rather than the exact destinations. When // we seek, we will get another event (after a slight delay) and these steps // will run again. So if we seeked directly to |start|, |start| would move // on the next call and we would loop forever. - let seekStart = this.timeline_.getSafeSeekRangeStart(safeSeekOffset); - let seekSafe = this.timeline_.getSafeSeekRangeStart( + const seekStart = this.timeline_.getSafeSeekRangeStart(safeSeekOffset); + const seekSafe = this.timeline_.getSafeSeekRangeStart( rebufferingGoal + safeSeekOffset); if (currentTime >= duration) { @@ -457,10 +457,10 @@ shaka.media.MediaSourcePlayhead = class { * @private */ clampTime_(time) { - let start = this.timeline_.getSeekRangeStart(); + const start = this.timeline_.getSeekRangeStart(); if (time < start) return start; - let end = this.timeline_.getSeekRangeEnd(); + const end = this.timeline_.getSeekRangeEnd(); if (time > end) return end; return time; diff --git a/lib/media/presentation_timeline.js b/lib/media/presentation_timeline.js index 669292d36a..381bb46559 100644 --- a/lib/media/presentation_timeline.js +++ b/lib/media/presentation_timeline.js @@ -241,7 +241,7 @@ shaka.media.PresentationTimeline.prototype.notifySegments = function( // Since we have explicit segment end times, calculate a presentation start // based on them. This start time accounts for drift. // Date.now() is in milliseconds, from which we compute "now" in seconds. - let now = (Date.now() + this.clockOffset_) / 1000.0; + const now = (Date.now() + this.clockOffset_) / 1000.0; this.presentationStartTime_ = now - this.maxSegmentEndTime_ - this.maxSegmentDuration_; } @@ -346,8 +346,8 @@ shaka.media.PresentationTimeline.prototype.getSegmentAvailabilityStart = return this.userSeekStart_; } - let end = this.getSegmentAvailabilityEnd(); - let start = end - this.segmentAvailabilityDuration_; + const end = this.getSegmentAvailabilityEnd(); + const start = end - this.segmentAvailabilityDuration_; return Math.max(this.userSeekStart_, start); }; @@ -437,8 +437,8 @@ shaka.media.PresentationTimeline.prototype.getSeekRangeStart = function() { * @export */ shaka.media.PresentationTimeline.prototype.getSeekRangeEnd = function() { - let useDelay = this.isLive() || this.isInProgress(); - let delay = useDelay ? this.presentationDelay_ : 0; + const useDelay = this.isLive() || this.isInProgress(); + const delay = useDelay ? this.presentationDelay_ : 0; return Math.max(0, this.getSegmentAvailabilityEnd() - delay); }; @@ -478,7 +478,7 @@ shaka.media.PresentationTimeline.prototype.getLiveEdge_ = function() { goog.asserts.assert(this.presentationStartTime_ != null, 'Cannot compute timeline live edge without start time'); // Date.now() is in milliseconds, from which we compute "now" in seconds. - let now = (Date.now() + this.clockOffset_) / 1000.0; + const now = (Date.now() + this.clockOffset_) / 1000.0; return Math.max( 0, now - this.maxSegmentDuration_ - this.presentationStartTime_); }; diff --git a/lib/media/segment_index.js b/lib/media/segment_index.js index ff7aca8ce8..17abcc782f 100644 --- a/lib/media/segment_index.js +++ b/lib/media/segment_index.js @@ -72,7 +72,7 @@ shaka.media.SegmentIndex.prototype.find = function(time) { // out either way. In both cases, references_.length is small enough that the // difference isn't huge. for (let i = this.references_.length - 1; i >= 0; --i) { - let r = this.references_[i]; + const r = this.references_[i]; // Note that a segment ends immediately before the end time. if ((time >= r.startTime) && (time < r.endTime)) { return r.position; @@ -99,7 +99,7 @@ shaka.media.SegmentIndex.prototype.get = function(position) { return null; } - let index = position - this.references_[0].position; + const index = position - this.references_[0].position; if (index < 0 || index >= this.references_.length) { return null; } @@ -143,8 +143,8 @@ shaka.media.SegmentIndex.prototype.merge = function(references) { let j = 0; while ((i < this.references_.length) && (j < references.length)) { - let r1 = this.references_[i]; - let r2 = references[j]; + const r1 = this.references_[i]; + const r2 = references[j]; if (r1.startTime < r2.startTime) { newReferences.push(r1); @@ -170,7 +170,7 @@ shaka.media.SegmentIndex.prototype.merge = function(references) { i == this.references_.length - 1 && j == references.length - 1, 'This should be an update of the last segment in a period'); - let r = new shaka.media.SegmentReference(r1.position, + const r = new shaka.media.SegmentReference(r1.position, r2.startTime, r2.endTime, r2.getUris, r2.startByte, r2.endByte); newReferences.push(r); } else { @@ -191,8 +191,8 @@ shaka.media.SegmentIndex.prototype.merge = function(references) { // The rest of these references may need to be renumbered. let nextPosition = newReferences[newReferences.length - 1].position + 1; while (j < references.length) { - let r = references[j++]; - let r2 = new shaka.media.SegmentReference(nextPosition++, + const r = references[j++]; + const r2 = new shaka.media.SegmentReference(nextPosition++, r.startTime, r.endTime, r.getUris, r.startByte, r.endByte); newReferences.push(r2); } @@ -259,7 +259,7 @@ shaka.media.SegmentIndex.prototype.fit = function(periodDuration) { // Trim out references we will never use. while (this.references_.length) { - let lastReference = this.references_[this.references_.length - 1]; + const lastReference = this.references_[this.references_.length - 1]; if (lastReference.startTime >= periodDuration) { this.references_.pop(); } else { @@ -267,7 +267,7 @@ shaka.media.SegmentIndex.prototype.fit = function(periodDuration) { } } while (this.references_.length) { - let firstReference = this.references_[0]; + const firstReference = this.references_[0]; if (firstReference.endTime <= 0) { this.references_.shift(); } else { @@ -280,7 +280,7 @@ shaka.media.SegmentIndex.prototype.fit = function(periodDuration) { } // Adjust the last SegmentReference. - let lastReference = this.references_[this.references_.length - 1]; + const lastReference = this.references_[this.references_.length - 1]; this.references_[this.references_.length - 1] = new shaka.media.SegmentReference( lastReference.position, @@ -303,7 +303,7 @@ if (goog.DEBUG) { shaka.media.SegmentIndex.assertCorrectReferences_ = function(references) { goog.asserts.assert(references.every(function(r2, i) { if (i == 0) return true; - let r1 = references[i - 1]; + const r1 = references[i - 1]; if (r2.position != r1.position + 1) return false; if (r1.startTime < r2.startTime) { return true; diff --git a/lib/media/streaming_engine.js b/lib/media/streaming_engine.js index 8a1e12b6ec..e9baaac7eb 100644 --- a/lib/media/streaming_engine.js +++ b/lib/media/streaming_engine.js @@ -376,7 +376,7 @@ shaka.media.StreamingEngine.prototype.configure = function(config) { // Create separate parameters for backoff during streaming failure. /** @type {shaka.extern.RetryParameters} */ - let failureRetryParams = { + const failureRetryParams = { // The term "attempts" includes the initial attempt, plus all retries. // In order to see a delay, there would have to be at least 2 attempts. maxAttempts: Math.max(config.retryParameters.maxAttempts, 2), @@ -388,7 +388,7 @@ shaka.media.StreamingEngine.prototype.configure = function(config) { // We don't want to ever run out of attempts. The application should be // allowed to retry streaming infinitely if it wishes. - let autoReset = true; + const autoReset = true; this.failureCallbackBackoff_ = new shaka.net.Backoff(failureRetryParams, autoReset); }; @@ -556,9 +556,9 @@ shaka.media.StreamingEngine.prototype.loadNewTextStream = async function( // The Sequence Id is to avoid that race condition. this.textStreamSequenceId_++; this.unloadingTextStream_ = false; - let currentSequenceId = this.textStreamSequenceId_; + const currentSequenceId = this.textStreamSequenceId_; - let mediaSourceEngine = this.playerInterface_.mediaSourceEngine; + const mediaSourceEngine = this.playerInterface_.mediaSourceEngine; const streamMap = new Map(); const streamSet = new Set(); @@ -614,22 +614,22 @@ shaka.media.StreamingEngine.prototype.setTrickPlay = function(on) { const mediaState = this.mediaStates_.get(ContentType.VIDEO); if (!mediaState) return; - let stream = mediaState.stream; + const stream = mediaState.stream; if (!stream) return; shaka.log.debug('setTrickPlay', on); if (on) { - let trickModeVideo = stream.trickModeVideo; + const trickModeVideo = stream.trickModeVideo; if (!trickModeVideo) return; // Can't engage trick play. - let normalVideo = mediaState.restoreStreamAfterTrickPlay; + const normalVideo = mediaState.restoreStreamAfterTrickPlay; if (normalVideo) return; // Already in trick play. shaka.log.debug('Engaging trick mode stream', trickModeVideo); this.switchInternal_(trickModeVideo, false, 0); mediaState.restoreStreamAfterTrickPlay = stream; } else { - let normalVideo = mediaState.restoreStreamAfterTrickPlay; + const normalVideo = mediaState.restoreStreamAfterTrickPlay; if (!normalVideo) return; shaka.log.debug('Restoring non-trick-mode stream', normalVideo); @@ -691,7 +691,7 @@ shaka.media.StreamingEngine.prototype.switchInternal_ = function( // If we are selecting a stream from a different Period, then we need to // handle a Period transition. Simply ignore the given stream, assuming that // Player will select the same track in onChooseStreams. - let periodIndex = this.findPeriodContainingStream_(stream); + const periodIndex = this.findPeriodContainingStream_(stream); if (clearBuffer && periodIndex != mediaState.needPeriodIndex) { shaka.log.debug('switch: switching to stream in another Period; clearing ' + 'buffer and changing Periods'); @@ -733,7 +733,7 @@ shaka.media.StreamingEngine.prototype.switchInternal_ = function( if (!canSwitchRecord || !canSwitchRecord.resolved) return; if (mediaState.stream == stream) { - let streamTag = shaka.media.StreamingEngine.logPrefix_(mediaState); + const streamTag = shaka.media.StreamingEngine.logPrefix_(mediaState); shaka.log.debug('switch: Stream ' + streamTag + ' already active'); return; } @@ -742,7 +742,7 @@ shaka.media.StreamingEngine.prototype.switchInternal_ = function( // Mime types are allowed to change for text streams. // Reinitialize the text parser, but only if we are going to fetch the init // segment again. - let fullMimeType = shaka.util.MimeUtils.getFullType( + const fullMimeType = shaka.util.MimeUtils.getFullType( stream.mimeType, stream.codecs); this.playerInterface_.mediaSourceEngine.reinitText(fullMimeType); } @@ -750,7 +750,7 @@ shaka.media.StreamingEngine.prototype.switchInternal_ = function( mediaState.stream = stream; mediaState.needInitSegment = true; - let streamTag = shaka.media.StreamingEngine.logPrefix_(mediaState); + const streamTag = shaka.media.StreamingEngine.logPrefix_(mediaState); shaka.log.debug('switch: switching to Stream ' + streamTag); if (this.shouldAbortCurrentRequest_(mediaState, periodIndex)) { @@ -980,8 +980,8 @@ shaka.media.StreamingEngine.prototype.initStreams_ = async function( } // Init MediaSourceEngine. - let mediaSourceEngine = this.playerInterface_.mediaSourceEngine; - let forceTransmuxTS = this.config_.forceTransmuxTS; + const mediaSourceEngine = this.playerInterface_.mediaSourceEngine; + const forceTransmuxTS = this.config_.forceTransmuxTS; await mediaSourceEngine.init(streamsByType, forceTransmuxTS); if (this.destroyed_) { return; } @@ -1165,7 +1165,7 @@ shaka.media.StreamingEngine.prototype.setupStreams_ = async function(streams) { * @private */ shaka.media.StreamingEngine.prototype.setDuration_ = function() { - let duration = this.manifest_.presentationTimeline.getDuration(); + const duration = this.manifest_.presentationTimeline.getDuration(); if (duration < Infinity) { this.playerInterface_.mediaSourceEngine.setDuration(duration); } else { @@ -1185,7 +1185,7 @@ shaka.media.StreamingEngine.prototype.setDuration_ = function() { shaka.media.StreamingEngine.prototype.onUpdate_ = function(mediaState) { if (this.destroyed_) return; - let logPrefix = shaka.media.StreamingEngine.logPrefix_(mediaState); + const logPrefix = shaka.media.StreamingEngine.logPrefix_(mediaState); // Sanity check. goog.asserts.assert( @@ -1212,7 +1212,7 @@ shaka.media.StreamingEngine.prototype.onUpdate_ = function(mediaState) { // Update the MediaState. try { - let delay = this.update_(mediaState); + const delay = this.update_(mediaState); if (delay != null) { this.scheduleUpdate_(mediaState, delay); mediaState.hasError = false; @@ -1244,7 +1244,7 @@ shaka.media.StreamingEngine.prototype.onUpdate_ = function(mediaState) { // forever at the end. We should only do this if the duration needs to // shrink. Growing it by less than 1ms can actually cause buffering on // replay, as in https://github.com/google/shaka-player/issues/979 - let duration = this.playerInterface_.mediaSourceEngine.getDuration(); + const duration = this.playerInterface_.mediaSourceEngine.getDuration(); if (duration < this.manifest_.presentationTimeline.getDuration()) { this.manifest_.presentationTimeline.setDuration(duration); } @@ -1281,22 +1281,23 @@ shaka.media.StreamingEngine.prototype.update_ = function(mediaState) { return null; } - let logPrefix = shaka.media.StreamingEngine.logPrefix_(mediaState); + const logPrefix = shaka.media.StreamingEngine.logPrefix_(mediaState); // Compute how far we've buffered ahead of the playhead. const presentationTime = this.playerInterface_.getPresentationTime(); // Get the next timestamp we need. - let timeNeeded = this.getTimeNeeded_(mediaState, presentationTime); + const timeNeeded = this.getTimeNeeded_(mediaState, presentationTime); shaka.log.v2(logPrefix, 'timeNeeded=' + timeNeeded); - let currentPeriodIndex = this.findPeriodContainingStream_(mediaState.stream); + const currentPeriodIndex = + this.findPeriodContainingStream_(mediaState.stream); const needPeriodIndex = this.findPeriodForTime_(timeNeeded); // Get the amount of content we have buffered, accounting for drift. This // is only used to determine if we have meet the buffering goal. This should // be the same method that PlayheadObserver uses. - let bufferedAhead = this.playerInterface_.mediaSourceEngine.bufferedAheadOf( + const bufferedAhead = this.playerInterface_.mediaSourceEngine.bufferedAheadOf( mediaState.type, presentationTime); shaka.log.v2(logPrefix, @@ -1304,12 +1305,12 @@ shaka.media.StreamingEngine.prototype.update_ = function(mediaState) { 'presentationTime=' + presentationTime, 'bufferedAhead=' + bufferedAhead); - let unscaledBufferingGoal = Math.max( + const unscaledBufferingGoal = Math.max( this.manifest_.minBufferTime || 0, this.config_.rebufferingGoal, this.config_.bufferingGoal); - let scaledBufferingGoal = unscaledBufferingGoal * this.bufferingGoalScale_; + const scaledBufferingGoal = unscaledBufferingGoal * this.bufferingGoalScale_; // Check if we've buffered to the end of the presentation. if (timeNeeded >= this.manifest_.presentationTimeline.getDuration()) { @@ -1357,9 +1358,9 @@ shaka.media.StreamingEngine.prototype.update_ = function(mediaState) { return 0.5; } - let bufferEnd = + const bufferEnd = this.playerInterface_.mediaSourceEngine.bufferEnd(mediaState.type); - let reference = this.getSegmentReferenceNeeded_( + const reference = this.getSegmentReferenceNeeded_( mediaState, presentationTime, bufferEnd, currentPeriodIndex); if (!reference) { // The segment could not be found, does not exist, or is not available. In @@ -1424,9 +1425,9 @@ shaka.media.StreamingEngine.prototype.getTimeNeeded_ = function( return Math.max(presentationTime, mediaState.resumeAt); } - let lastPeriodIndex = + const lastPeriodIndex = this.findPeriodContainingStream_(mediaState.lastStream); - let lastPeriod = this.manifest_.periods[lastPeriodIndex]; + const lastPeriod = this.manifest_.periods[lastPeriodIndex]; return lastPeriod.startTime + mediaState.lastSegmentReference.endTime; }; @@ -1445,12 +1446,12 @@ shaka.media.StreamingEngine.prototype.getTimeNeeded_ = function( */ shaka.media.StreamingEngine.prototype.getSegmentReferenceNeeded_ = function( mediaState, presentationTime, bufferEnd, currentPeriodIndex) { - let logPrefix = shaka.media.StreamingEngine.logPrefix_(mediaState); + const logPrefix = shaka.media.StreamingEngine.logPrefix_(mediaState); if (mediaState.lastSegmentReference && mediaState.stream == mediaState.lastStream) { // Something is buffered from the same Stream. - let position = mediaState.lastSegmentReference.position + 1; + const position = mediaState.lastSegmentReference.position + 1; shaka.log.v2(logPrefix, 'next position known:', 'position=' + position); return this.getSegmentReferenceIfAvailable_( @@ -1463,9 +1464,9 @@ shaka.media.StreamingEngine.prototype.getSegmentReferenceNeeded_ = function( // Something is buffered from another Stream. goog.asserts.assert(mediaState.lastStream, 'lastStream should not be null'); shaka.log.v1(logPrefix, 'next position unknown: another Stream buffered'); - let lastPeriodIndex = + const lastPeriodIndex = this.findPeriodContainingStream_(mediaState.lastStream); - let lastPeriod = this.manifest_.periods[lastPeriodIndex]; + const lastPeriod = this.manifest_.periods[lastPeriodIndex]; position = this.lookupSegmentPosition_( mediaState, lastPeriod.startTime + mediaState.lastSegmentReference.endTime, @@ -1491,7 +1492,7 @@ shaka.media.StreamingEngine.prototype.getSegmentReferenceNeeded_ = function( // unconditionally get the previous segment. If it turns out that there's // non-positive drift then we'll just end up buffering beind the playhead a // little more than we needed. - let optimalPosition = Math.max(0, position - 1); + const optimalPosition = Math.max(0, position - 1); reference = this.getSegmentReferenceIfAvailable_( mediaState, currentPeriodIndex, optimalPosition); } @@ -1513,16 +1514,16 @@ shaka.media.StreamingEngine.prototype.getSegmentReferenceNeeded_ = function( */ shaka.media.StreamingEngine.prototype.lookupSegmentPosition_ = function( mediaState, presentationTime, currentPeriodIndex) { - let logPrefix = shaka.media.StreamingEngine.logPrefix_(mediaState); - let currentPeriod = this.manifest_.periods[currentPeriodIndex]; + const logPrefix = shaka.media.StreamingEngine.logPrefix_(mediaState); + const currentPeriod = this.manifest_.periods[currentPeriodIndex]; shaka.log.debug(logPrefix, 'looking up segment:', 'presentationTime=' + presentationTime, 'currentPeriod.startTime=' + currentPeriod.startTime); - let lookupTime = Math.max(0, presentationTime - currentPeriod.startTime); - let position = mediaState.stream.findSegmentPosition(lookupTime); + const lookupTime = Math.max(0, presentationTime - currentPeriod.startTime); + const position = mediaState.stream.findSegmentPosition(lookupTime); if (position == null) { shaka.log.warning(logPrefix, @@ -1547,10 +1548,10 @@ shaka.media.StreamingEngine.prototype.lookupSegmentPosition_ = function( */ shaka.media.StreamingEngine.prototype.getSegmentReferenceIfAvailable_ = function(mediaState, currentPeriodIndex, position) { - let logPrefix = shaka.media.StreamingEngine.logPrefix_(mediaState); - let currentPeriod = this.manifest_.periods[currentPeriodIndex]; + const logPrefix = shaka.media.StreamingEngine.logPrefix_(mediaState); + const currentPeriod = this.manifest_.periods[currentPeriodIndex]; - let reference = mediaState.stream.getSegmentReference(position); + const reference = mediaState.stream.getSegmentReference(position); if (!reference) { shaka.log.v1(logPrefix, 'segment does not exist:', @@ -1559,9 +1560,9 @@ shaka.media.StreamingEngine.prototype.getSegmentReferenceIfAvailable_ = return null; } - let timeline = this.manifest_.presentationTimeline; - let availabilityStart = timeline.getSegmentAvailabilityStart(); - let availabilityEnd = timeline.getSegmentAvailabilityEnd(); + const timeline = this.manifest_.presentationTimeline; + const availabilityStart = timeline.getSegmentAvailabilityStart(); + const availabilityEnd = timeline.getSegmentAvailabilityEnd(); if ((currentPeriod.startTime + reference.endTime < availabilityStart) || (currentPeriod.startTime + reference.startTime > availabilityEnd)) { @@ -1610,11 +1611,11 @@ shaka.media.StreamingEngine.prototype.fetchAndAppend_ = function( // callbacks. Furthermore, switch() may be called at any time, so we should // also avoid using mediaState.stream or mediaState.needInitSegment in any // callbacks. - let stream = mediaState.stream; + const stream = mediaState.stream; // Compute the append window. - let duration = this.manifest_.presentationTimeline.getDuration(); - let followingPeriod = this.manifest_.periods[currentPeriodIndex + 1]; + const duration = this.manifest_.presentationTimeline.getDuration(); + const followingPeriod = this.manifest_.periods[currentPeriodIndex + 1]; // Rounding issues can cause us to remove the first frame of the Period, so // reduce the start time slightly. @@ -1628,7 +1629,7 @@ shaka.media.StreamingEngine.prototype.fetchAndAppend_ = function( reference.startTime <= appendWindowEnd, logPrefix + ' segment should start before append window end'); - let initSourceBuffer = this.initSourceBuffer_( + const initSourceBuffer = this.initSourceBuffer_( mediaState, currentPeriodIndex, appendWindowStart, appendWindowEnd); mediaState.performingUpdate = true; @@ -1638,7 +1639,7 @@ shaka.media.StreamingEngine.prototype.fetchAndAppend_ = function( mediaState.needInitSegment = false; shaka.log.v2(logPrefix, 'fetching segment'); - let fetchSegment = this.fetch_(mediaState, reference); + const fetchSegment = this.fetch_(mediaState, reference); Promise.all([initSourceBuffer, fetchSegment]).then(function(results) { @@ -1721,7 +1722,7 @@ shaka.media.StreamingEngine.prototype.retry = function() { } for (const mediaState of this.mediaStates_.values()) { - let logPrefix = shaka.media.StreamingEngine.logPrefix_(mediaState); + const logPrefix = shaka.media.StreamingEngine.logPrefix_(mediaState); if (mediaState.hasError) { shaka.log.info(logPrefix, 'Retrying after failure...'); mediaState.hasError = false; @@ -1742,7 +1743,7 @@ shaka.media.StreamingEngine.prototype.retry = function() { */ shaka.media.StreamingEngine.prototype.handleQuotaExceeded_ = function( mediaState, error) { - let logPrefix = shaka.media.StreamingEngine.logPrefix_(mediaState); + const logPrefix = shaka.media.StreamingEngine.logPrefix_(mediaState); // The segment cannot fit into the SourceBuffer. Ideally, MediaSource would // have evicted old data to accommodate the segment; however, it may have @@ -1758,14 +1759,14 @@ shaka.media.StreamingEngine.prototype.handleQuotaExceeded_ = function( // we don't reduce the buffering goals too quickly. const mediaStates = Array.from(this.mediaStates_.values()); - let waitingForAnotherStreamToRecover = mediaStates.some(function(ms) { + const waitingForAnotherStreamToRecover = mediaStates.some(function(ms) { return ms != mediaState && ms.recovering; }); if (!waitingForAnotherStreamToRecover) { // Reduction schedule: 80%, 60%, 40%, 20%, 16%, 12%, 8%, 4%, fail. // Note: percentages are used for comparisons to avoid rounding errors. - let percentBefore = Math.round(100 * this.bufferingGoalScale_); + const percentBefore = Math.round(100 * this.bufferingGoalScale_); if (percentBefore > 20) { this.bufferingGoalScale_ -= 0.2; } else if (percentBefore > 4) { @@ -1778,7 +1779,7 @@ shaka.media.StreamingEngine.prototype.handleQuotaExceeded_ = function( this.playerInterface_.onError(error); return; } - let percentAfter = Math.round(100 * this.bufferingGoalScale_); + const percentAfter = Math.round(100 * this.bufferingGoalScale_); shaka.log.warning( logPrefix, 'MediaSource threw QuotaExceededError:', @@ -1818,21 +1819,21 @@ shaka.media.StreamingEngine.prototype.initSourceBuffer_ = function( return Promise.resolve(); } - let logPrefix = shaka.media.StreamingEngine.logPrefix_(mediaState); - let currentPeriod = this.manifest_.periods[currentPeriodIndex]; + const logPrefix = shaka.media.StreamingEngine.logPrefix_(mediaState); + const currentPeriod = this.manifest_.periods[currentPeriodIndex]; // If we need an init segment then the Stream switched, so we've either // changed bitrates, Periods, or both. If we've changed Periods then we must // set a new timestamp offset and append window end. Note that by setting // these values here, we avoid having to co-ordinate ongoing updates, which // we would have to do if we instead set them in switch(). - let timestampOffset = + const timestampOffset = currentPeriod.startTime - mediaState.stream.presentationTimeOffset; shaka.log.v1(logPrefix, 'setting timestamp offset to ' + timestampOffset); shaka.log.v1(logPrefix, 'setting append window start to ' + appendWindowStart); shaka.log.v1(logPrefix, 'setting append window end to ' + appendWindowEnd); - let setStreamProperties = + const setStreamProperties = this.playerInterface_.mediaSourceEngine.setStreamProperties( mediaState.type, timestampOffset, appendWindowStart, appendWindowEnd); @@ -1843,9 +1844,9 @@ shaka.media.StreamingEngine.prototype.initSourceBuffer_ = function( shaka.log.v1(logPrefix, 'fetching init segment'); - let fetchInit = + const fetchInit = this.fetch_(mediaState, mediaState.stream.initSegmentReference); - let appendInit = fetchInit.then(function(initSegment) { + const appendInit = fetchInit.then(function(initSegment) { if (this.destroyed_) return; shaka.log.v1(logPrefix, 'appending init segment'); const hasClosedCaptions = mediaState.stream.closedCaptions && @@ -1876,7 +1877,7 @@ shaka.media.StreamingEngine.prototype.initSourceBuffer_ = function( */ shaka.media.StreamingEngine.prototype.append_ = function( mediaState, presentationTime, period, stream, reference, segment) { - let logPrefix = shaka.media.StreamingEngine.logPrefix_(mediaState); + const logPrefix = shaka.media.StreamingEngine.logPrefix_(mediaState); const hasClosedCaptions = stream.closedCaptions && stream.closedCaptions.size > 0; @@ -1925,17 +1926,17 @@ shaka.media.StreamingEngine.prototype.append_ = function( */ shaka.media.StreamingEngine.prototype.parseEMSG_ = function( period, reference, emsgSchemeIdUris, box) { - let schemeId = box.reader.readTerminatedString(); + const schemeId = box.reader.readTerminatedString(); // Read the rest of the data. - let value = box.reader.readTerminatedString(); - let timescale = box.reader.readUint32(); - let presentationTimeDelta = box.reader.readUint32(); - let eventDuration = box.reader.readUint32(); - let id = box.reader.readUint32(); - let messageData = box.reader.readBytes( + const value = box.reader.readTerminatedString(); + const timescale = box.reader.readUint32(); + const presentationTimeDelta = box.reader.readUint32(); + const eventDuration = box.reader.readUint32(); + const id = box.reader.readUint32(); + const messageData = box.reader.readBytes( box.reader.getLength() - box.reader.getPosition()); - let startTime = period.startTime + reference.startTime + + const startTime = period.startTime + reference.startTime + (presentationTimeDelta / timescale); // See DASH sec. 5.10.3.3.1 @@ -1948,7 +1949,7 @@ shaka.media.StreamingEngine.prototype.parseEMSG_ = function( this.playerInterface_.onManifestUpdate(); } else { /** @type {shaka.extern.EmsgInfo} */ - let emsg = { + const emsg = { startTime: startTime, endTime: startTime + (eventDuration / timescale), schemeIdUri: schemeId, @@ -1961,7 +1962,7 @@ shaka.media.StreamingEngine.prototype.parseEMSG_ = function( }; // Dispatch an event to notify the application about the emsg box. - let event = new shaka.util.FakeEvent('emsg', {'detail': emsg}); + const event = new shaka.util.FakeEvent('emsg', {'detail': emsg}); this.playerInterface_.onEvent(event); } } @@ -1978,16 +1979,16 @@ shaka.media.StreamingEngine.prototype.parseEMSG_ = function( */ shaka.media.StreamingEngine.prototype.evict_ = function( mediaState, presentationTime) { - let logPrefix = shaka.media.StreamingEngine.logPrefix_(mediaState); + const logPrefix = shaka.media.StreamingEngine.logPrefix_(mediaState); shaka.log.v2(logPrefix, 'checking buffer length'); // Use the max segment duration, if it is longer than the bufferBehind, to // avoid accidentally clearing too much data when dealing with a manifest // with a long keyframe interval. - let bufferBehind = Math.max(this.config_.bufferBehind, + const bufferBehind = Math.max(this.config_.bufferBehind, this.manifest_.presentationTimeline.getMaxSegmentDuration()); - let startTime = + const startTime = this.playerInterface_.mediaSourceEngine.bufferStart(mediaState.type); if (startTime == null) { shaka.log.v2(logPrefix, @@ -1996,9 +1997,9 @@ shaka.media.StreamingEngine.prototype.evict_ = function( 'bufferBehind=' + bufferBehind); return Promise.resolve(); } - let bufferedBehind = presentationTime - startTime; + const bufferedBehind = presentationTime - startTime; - let overflow = bufferedBehind - bufferBehind; + const overflow = bufferedBehind - bufferBehind; if (overflow <= 0) { shaka.log.v2(logPrefix, 'buffer behind okay:', @@ -2040,7 +2041,7 @@ shaka.media.StreamingEngine.prototype.handleStartup_ = function( return; } - let logPrefix = shaka.media.StreamingEngine.logPrefix_(mediaState); + const logPrefix = shaka.media.StreamingEngine.logPrefix_(mediaState); // If the only media state is text, then we may have loaded text before // any media content. Marking as complete early will break MediaSource. @@ -2064,7 +2065,7 @@ shaka.media.StreamingEngine.prototype.handleStartup_ = function( shaka.log.debug(logPrefix, 'startup complete'); // We must use |stream| because switch() may have been called. - let currentPeriodIndex = this.findPeriodContainingStream_(stream); + const currentPeriodIndex = this.findPeriodContainingStream_(stream); goog.asserts.assert( mediaStates.every(function(ms) { @@ -2110,15 +2111,16 @@ shaka.media.StreamingEngine.prototype.handleStartup_ = function( shaka.media.StreamingEngine.prototype.handlePeriodTransition_ = function( mediaState) { const Functional = shaka.util.Functional; - let logPrefix = shaka.media.StreamingEngine.logPrefix_(mediaState); + const logPrefix = shaka.media.StreamingEngine.logPrefix_(mediaState); const ContentType = shaka.util.ManifestParserUtils.ContentType; - let currentPeriodIndex = this.findPeriodContainingStream_(mediaState.stream); + const currentPeriodIndex = + this.findPeriodContainingStream_(mediaState.stream); if (mediaState.needPeriodIndex == currentPeriodIndex) { return; } - let needPeriodIndex = mediaState.needPeriodIndex; + const needPeriodIndex = mediaState.needPeriodIndex; const mediaStates = Array.from(this.mediaStates_.values()); @@ -2135,7 +2137,7 @@ shaka.media.StreamingEngine.prototype.handlePeriodTransition_ = function( 'All MediaStates should need the same Period or be performing updates.'); // Only call onChooseStreams() when all MediaStates need the same Period. - let needSamePeriod = mediaStates.every(function(ms) { + const needSamePeriod = mediaStates.every(function(ms) { return ms.needPeriodIndex == needPeriodIndex; }); if (!needSamePeriod) { @@ -2145,7 +2147,7 @@ shaka.media.StreamingEngine.prototype.handlePeriodTransition_ = function( } // Only call onChooseStreams() once per Period transition. - let allAreIdle = mediaStates.every(shaka.media.StreamingEngine.isIdle_); + const allAreIdle = mediaStates.every(shaka.media.StreamingEngine.isIdle_); if (!allAreIdle) { shaka.log.debug( logPrefix, @@ -2167,9 +2169,9 @@ shaka.media.StreamingEngine.prototype.handlePeriodTransition_ = function( // 2. All streams are still idle. // 3. The current stream is not in the needed Period (another transition // handled it). - let allReady = mediaStates.every(function(ms) { - let isIdle = shaka.media.StreamingEngine.isIdle_(ms); - let currentPeriodIndex = this.findPeriodContainingStream_(ms.stream); + const allReady = mediaStates.every(function(ms) { + const isIdle = shaka.media.StreamingEngine.isIdle_(ms); + const currentPeriodIndex = this.findPeriodContainingStream_(ms.stream); return isIdle && ms.needPeriodIndex == needPeriodIndex && currentPeriodIndex != needPeriodIndex; }.bind(this)); @@ -2180,10 +2182,10 @@ shaka.media.StreamingEngine.prototype.handlePeriodTransition_ = function( return; } - let needPeriod = this.manifest_.periods[needPeriodIndex]; + const needPeriod = this.manifest_.periods[needPeriodIndex]; shaka.log.v1(logPrefix, 'calling onChooseStreams()...'); - let chosenStreams = this.playerInterface_.onChooseStreams(needPeriod); + const chosenStreams = this.playerInterface_.onChooseStreams(needPeriod); /** @type {!Map.<!ContentType, shaka.extern.Stream>} */ const streamsByType = new Map(); @@ -2383,7 +2385,7 @@ shaka.media.StreamingEngine.prototype.fetch_ = function(mediaState, reference) { */ shaka.media.StreamingEngine.prototype.clearBuffer_ = async function(mediaState, flush, safeMargin) { - let logPrefix = shaka.media.StreamingEngine.logPrefix_(mediaState); + const logPrefix = shaka.media.StreamingEngine.logPrefix_(mediaState); goog.asserts.assert( !mediaState.performingUpdate && (mediaState.updateTimer == null), @@ -2398,7 +2400,7 @@ shaka.media.StreamingEngine.prototype.clearBuffer_ = let p; if (safeMargin) { const presentationTime = this.playerInterface_.getPresentationTime(); - let duration = this.playerInterface_.mediaSourceEngine.getDuration(); + const duration = this.playerInterface_.mediaSourceEngine.getDuration(); p = this.playerInterface_.mediaSourceEngine.remove( mediaState.type, presentationTime + safeMargin, duration); } else { @@ -2432,7 +2434,7 @@ shaka.media.StreamingEngine.prototype.clearBuffer_ = */ shaka.media.StreamingEngine.prototype.scheduleUpdate_ = function( mediaState, delay) { - let logPrefix = shaka.media.StreamingEngine.logPrefix_(mediaState); + const logPrefix = shaka.media.StreamingEngine.logPrefix_(mediaState); shaka.log.v2(logPrefix, 'updating in ' + delay + ' seconds'); goog.asserts.assert(mediaState.updateTimer == null, logPrefix + ' did not expect update to be scheduled'); diff --git a/lib/media/time_ranges_utils.js b/lib/media/time_ranges_utils.js index 7d99ccc936..61d4e3e972 100644 --- a/lib/media/time_ranges_utils.js +++ b/lib/media/time_ranges_utils.js @@ -156,7 +156,7 @@ shaka.media.TimeRangesUtils.getGapIndex = function(b, time) { */ shaka.media.TimeRangesUtils.getBufferedInfo = function(b) { if (!b) return []; - let ret = []; + const ret = []; for (let i = 0; i < b.length; i++) { ret.push({start: b.start(i), end: b.end(i)}); } diff --git a/lib/media/transmuxer.js b/lib/media/transmuxer.js index ce981bed8a..ad6f92da79 100644 --- a/lib/media/transmuxer.js +++ b/lib/media/transmuxer.js @@ -77,7 +77,7 @@ shaka.media.Transmuxer.isSupported = function(mimeType, contentType) { if (!window.muxjs || !shaka.media.Transmuxer.isTsContainer(mimeType)) { return false; } - let convertTsCodecs = shaka.media.Transmuxer.convertTsCodecs; + const convertTsCodecs = shaka.media.Transmuxer.convertTsCodecs; if (contentType) { return MediaSource.isTypeSupported(convertTsCodecs(contentType, mimeType)); } @@ -117,11 +117,11 @@ shaka.media.Transmuxer.convertTsCodecs = function(contentType, tsMimeType) { // 77 (main => 0x4d) // 100 (high => 0x64) // Reference: https://bit.ly/2K9JI3x - let match = /avc1\.(66|77|100)\.(\d+)/.exec(mp4MimeType); + const match = /avc1\.(66|77|100)\.(\d+)/.exec(mp4MimeType); if (match) { let newCodecString = 'avc1.'; - let profile = match[1]; + const profile = match[1]; if (profile == '66') { newCodecString += '4200'; } else if (profile == '77') { @@ -133,7 +133,7 @@ shaka.media.Transmuxer.convertTsCodecs = function(contentType, tsMimeType) { } // Convert the level to hex and append to the codec string. - let level = Number(match[2]); + const level = Number(match[2]); goog.asserts.assert(level < 256, 'Invalid legacy avc1 level number!'); newCodecString += (level >> 4).toString(16); @@ -160,7 +160,7 @@ shaka.media.Transmuxer.prototype.transmux = function(data) { this.transmuxedData_ = []; this.captions_ = []; - let dataArray = new Uint8Array(data); + const dataArray = new Uint8Array(data); this.muxTransmuxer_.push(dataArray); this.muxTransmuxer_.flush(); @@ -190,7 +190,7 @@ shaka.media.Transmuxer.prototype.transmux = function(data) { */ shaka.media.Transmuxer.prototype.onTransmuxed_ = function(segment) { this.captions_ = segment.captions; - let segmentWithInit = new Uint8Array(segment.data.byteLength + + const segmentWithInit = new Uint8Array(segment.data.byteLength + segment.initSegment.byteLength); segmentWithInit.set(segment.initSegment, 0); segmentWithInit.set(segment.data, segment.initSegment.byteLength); @@ -204,7 +204,7 @@ shaka.media.Transmuxer.prototype.onTransmuxed_ = function(segment) { * @private */ shaka.media.Transmuxer.prototype.onTransmuxDone_ = function() { - let output = { + const output = { data: shaka.util.Uint8ArrayUtils.concat.apply(null, this.transmuxedData_), captions: this.captions_, }; diff --git a/lib/media/webm_segment_index_parser.js b/lib/media/webm_segment_index_parser.js index abca95b520..7a5958dc9e 100644 --- a/lib/media/webm_segment_index_parser.js +++ b/lib/media/webm_segment_index_parser.js @@ -89,9 +89,9 @@ shaka.media.WebmSegmentIndexParser.CUE_CLUSTER_POSITION = 0xf1; */ shaka.media.WebmSegmentIndexParser.prototype.parse = function( cuesData, initData, uris, scaledPresentationTimeOffset) { - let tuple = this.parseWebmContainer_(initData); - let parser = new shaka.util.EbmlParser(new DataView(cuesData)); - let cuesElement = parser.parseElement(); + const tuple = this.parseWebmContainer_(initData); + const parser = new shaka.util.EbmlParser(new DataView(cuesData)); + const cuesElement = parser.parseElement(); if (cuesElement.id != shaka.media.WebmSegmentIndexParser.CUES_ID) { shaka.log.error('Not a Cues element.'); throw new shaka.util.Error( @@ -119,11 +119,11 @@ shaka.media.WebmSegmentIndexParser.prototype.parse = function( */ shaka.media.WebmSegmentIndexParser.prototype.parseWebmContainer_ = function( initData) { - let parser = new shaka.util.EbmlParser(new DataView(initData)); + const parser = new shaka.util.EbmlParser(new DataView(initData)); // Check that the WebM container data starts with the EBML header, but // skip its contents. - let ebmlElement = parser.parseElement(); + const ebmlElement = parser.parseElement(); if (ebmlElement.id != shaka.media.WebmSegmentIndexParser.EBML_ID) { shaka.log.error('Not an EBML element.'); throw new shaka.util.Error( @@ -132,7 +132,7 @@ shaka.media.WebmSegmentIndexParser.prototype.parseWebmContainer_ = function( shaka.util.Error.Code.WEBM_EBML_HEADER_ELEMENT_MISSING); } - let segmentElement = parser.parseElement(); + const segmentElement = parser.parseElement(); if (segmentElement.id != shaka.media.WebmSegmentIndexParser.SEGMENT_ID) { shaka.log.error('Not a Segment element.'); throw new shaka.util.Error( @@ -142,10 +142,10 @@ shaka.media.WebmSegmentIndexParser.prototype.parseWebmContainer_ = function( } // This value is used as the initial offset to the first referenced segment. - let segmentOffset = segmentElement.getOffset(); + const segmentOffset = segmentElement.getOffset(); // Parse the Segment element to get the segment info. - let segmentInfo = this.parseSegment_(segmentElement); + const segmentInfo = this.parseSegment_(segmentElement); return { segmentOffset: segmentOffset, timecodeScale: segmentInfo.timecodeScale, @@ -164,12 +164,12 @@ shaka.media.WebmSegmentIndexParser.prototype.parseWebmContainer_ = function( */ shaka.media.WebmSegmentIndexParser.prototype.parseSegment_ = function( segmentElement) { - let parser = segmentElement.createParser(); + const parser = segmentElement.createParser(); // Find the Info element. let infoElement = null; while (parser.hasMoreData()) { - let elem = parser.parseElement(); + const elem = parser.parseElement(); if (elem.id != shaka.media.WebmSegmentIndexParser.INFO_ID) { continue; } @@ -201,7 +201,7 @@ shaka.media.WebmSegmentIndexParser.prototype.parseSegment_ = function( */ shaka.media.WebmSegmentIndexParser.prototype.parseInfo_ = function( infoElement) { - let parser = infoElement.createParser(); + const parser = infoElement.createParser(); // The timecode scale factor in units of [nanoseconds / T], where [T] are the // units used to express all other time values in the WebM container. By @@ -211,7 +211,7 @@ shaka.media.WebmSegmentIndexParser.prototype.parseInfo_ = function( let durationScale = null; while (parser.hasMoreData()) { - let elem = parser.parseElement(); + const elem = parser.parseElement(); if (elem.id == shaka.media.WebmSegmentIndexParser.TIMECODE_SCALE_ID) { timecodeScaleNanoseconds = elem.getUint(); } else if (elem.id == shaka.media.WebmSegmentIndexParser.DURATION_ID) { @@ -226,9 +226,9 @@ shaka.media.WebmSegmentIndexParser.prototype.parseInfo_ = function( } // The timecode scale factor in units of [seconds / T]. - let timecodeScale = timecodeScaleNanoseconds / 1000000000; + const timecodeScale = timecodeScaleNanoseconds / 1000000000; // The duration is stored in units of [T] - let durationSeconds = durationScale * timecodeScale; + const durationSeconds = durationScale * timecodeScale; return {timecodeScale: timecodeScale, duration: durationSeconds}; }; @@ -249,28 +249,28 @@ shaka.media.WebmSegmentIndexParser.prototype.parseInfo_ = function( shaka.media.WebmSegmentIndexParser.prototype.parseCues_ = function( cuesElement, segmentOffset, timecodeScale, duration, uris, scaledPresentationTimeOffset) { - let references = []; - let getUris = function() { return uris; }; + const references = []; + const getUris = function() { return uris; }; - let parser = cuesElement.createParser(); + const parser = cuesElement.createParser(); let lastTime = null; let lastOffset = null; while (parser.hasMoreData()) { - let elem = parser.parseElement(); + const elem = parser.parseElement(); if (elem.id != shaka.media.WebmSegmentIndexParser.CUE_POINT_ID) { continue; } - let tuple = this.parseCuePoint_(elem); + const tuple = this.parseCuePoint_(elem); if (!tuple) { continue; } // Substract the presentation time offset from the unscaled time - let currentTime = timecodeScale * tuple.unscaledTime; - let currentOffset = segmentOffset + tuple.relativeOffset; + const currentTime = timecodeScale * tuple.unscaledTime; + const currentOffset = segmentOffset + tuple.relativeOffset; if (lastTime != null) { goog.asserts.assert(lastOffset != null, 'last offset cannot be null'); @@ -316,10 +316,10 @@ shaka.media.WebmSegmentIndexParser.prototype.parseCues_ = function( */ shaka.media.WebmSegmentIndexParser.prototype.parseCuePoint_ = function( cuePointElement) { - let parser = cuePointElement.createParser(); + const parser = cuePointElement.createParser(); // Parse CueTime element. - let cueTimeElement = parser.parseElement(); + const cueTimeElement = parser.parseElement(); if (cueTimeElement.id != shaka.media.WebmSegmentIndexParser.CUE_TIME_ID) { shaka.log.warning('Not a CueTime element.'); throw new shaka.util.Error( @@ -327,10 +327,10 @@ shaka.media.WebmSegmentIndexParser.prototype.parseCuePoint_ = function( shaka.util.Error.Category.MEDIA, shaka.util.Error.Code.WEBM_CUE_TIME_ELEMENT_MISSING); } - let unscaledTime = cueTimeElement.getUint(); + const unscaledTime = cueTimeElement.getUint(); // Parse CueTrackPositions element. - let cueTrackPositionsElement = parser.parseElement(); + const cueTrackPositionsElement = parser.parseElement(); if (cueTrackPositionsElement.id != shaka.media.WebmSegmentIndexParser.CUE_TRACK_POSITIONS_ID) { shaka.log.warning('Not a CueTrackPositions element.'); @@ -340,11 +340,11 @@ shaka.media.WebmSegmentIndexParser.prototype.parseCuePoint_ = function( shaka.util.Error.Code.WEBM_CUE_TRACK_POSITIONS_ELEMENT_MISSING); } - let cueTrackParser = cueTrackPositionsElement.createParser(); + const cueTrackParser = cueTrackPositionsElement.createParser(); let relativeOffset = 0; while (cueTrackParser.hasMoreData()) { - let elem = cueTrackParser.parseElement(); + const elem = cueTrackParser.parseElement(); if (elem.id != shaka.media.WebmSegmentIndexParser.CUE_CLUSTER_POSITION) { continue; } diff --git a/lib/net/backoff.js b/lib/net/backoff.js index 6bec8616c9..802d728812 100644 --- a/lib/net/backoff.js +++ b/lib/net/backoff.js @@ -37,7 +37,7 @@ shaka.net.Backoff = function(parameters, autoReset = false) { // Set defaults as we unpack these, so that individual app-level requests in // NetworkingEngine can be missing parameters. - let defaults = shaka.net.Backoff.defaultRetryParameters(); + const defaults = shaka.net.Backoff.defaultRetryParameters(); /** * @const @@ -162,10 +162,10 @@ shaka.net.Backoff.defaultRetryParameters = function() { */ shaka.net.Backoff.fuzz_ = function(value, fuzzFactor) { // A random number between -1 and +1. - let negToPosOne = (Math.random() * 2.0) - 1.0; + const negToPosOne = (Math.random() * 2.0) - 1.0; // A random number between -fuzzFactor and +fuzzFactor. - let negToPosFuzzFactor = negToPosOne * fuzzFactor; + const negToPosFuzzFactor = negToPosOne * fuzzFactor; // The original value, fuzzed by +/- fuzzFactor. return value * (1.0 + negToPosFuzzFactor); diff --git a/lib/net/data_uri_plugin.js b/lib/net/data_uri_plugin.js index 9814cfc71c..dcb7991e1e 100644 --- a/lib/net/data_uri_plugin.js +++ b/lib/net/data_uri_plugin.js @@ -37,10 +37,10 @@ goog.require('shaka.util.Uint8ArrayUtils'); */ shaka.net.DataUriPlugin = function(uri, request, requestType) { try { - let parsed = shaka.net.DataUriPlugin.parse(uri); + const parsed = shaka.net.DataUriPlugin.parse(uri); /** @type {shaka.extern.Response} */ - let response = { + const response = { uri: uri, data: parsed.data, headers: { @@ -61,7 +61,7 @@ shaka.net.DataUriPlugin = function(uri, request, requestType) { */ shaka.net.DataUriPlugin.parse = function(uri) { // Extract the scheme. - let parts = uri.split(':'); + const parts = uri.split(':'); if (parts.length < 2 || parts[0] != 'data') { shaka.log.error('Bad data URI, failed to parse scheme'); throw new shaka.util.Error( @@ -70,10 +70,10 @@ shaka.net.DataUriPlugin.parse = function(uri) { shaka.util.Error.Code.MALFORMED_DATA_URI, uri); } - let path = parts.slice(1).join(':'); + const path = parts.slice(1).join(':'); // Extract the encoding and MIME type (required but can be empty). - let infoAndData = path.split(','); + const infoAndData = path.split(','); if (infoAndData.length < 2) { shaka.log.error('Bad data URI, failed to extract encoding and MIME type'); throw new shaka.util.Error( @@ -82,11 +82,11 @@ shaka.net.DataUriPlugin.parse = function(uri) { shaka.util.Error.Code.MALFORMED_DATA_URI, uri); } - let info = infoAndData[0]; - let dataStr = window.decodeURIComponent(infoAndData.slice(1).join(',')); + const info = infoAndData[0]; + const dataStr = window.decodeURIComponent(infoAndData.slice(1).join(',')); // Extract the encoding (optional). - let typeAndEncoding = info.split(';'); + const typeAndEncoding = info.split(';'); let encoding = null; if (typeAndEncoding.length > 1) { encoding = typeAndEncoding[1]; diff --git a/lib/net/http_fetch_plugin.js b/lib/net/http_fetch_plugin.js index 837e74632d..5b701fdfdf 100644 --- a/lib/net/http_fetch_plugin.js +++ b/lib/net/http_fetch_plugin.js @@ -130,8 +130,8 @@ shaka.net.HttpFetchPlugin.request_ = async function( const contentLengthRaw = response.headers.get('Content-Length'); const contentLength = contentLengthRaw ? parseInt(contentLengthRaw, 10) : 0; - let start = (controller) => { - let push = async () => { + const start = (controller) => { + const push = async () => { let readObj; try { readObj = await reader.read(); @@ -146,7 +146,7 @@ shaka.net.HttpFetchPlugin.request_ = async function( loaded += readObj.value.byteLength; } - let currentTime = Date.now(); + const currentTime = Date.now(); // If the time between last time and this time we got progress event // is long enough, or if a whole segment is downloaded, call // progressUpdated(). diff --git a/lib/net/http_plugin_utils.js b/lib/net/http_plugin_utils.js index f6051718d7..fec6d56e01 100644 --- a/lib/net/http_plugin_utils.js +++ b/lib/net/http_plugin_utils.js @@ -46,7 +46,7 @@ shaka.net.HttpPluginUtils.makeResponse = uri = responseURL; } /** @type {shaka.extern.Response} */ - let response = { + const response = { uri: uri, data: data, headers: headers, @@ -60,7 +60,7 @@ shaka.net.HttpPluginUtils.makeResponse = } catch (exception) {} shaka.log.debug('HTTP error text:', responseText); - let severity = status == 401 || status == 403 ? + const severity = status == 401 || status == 403 ? shaka.util.Error.Severity.CRITICAL : shaka.util.Error.Severity.RECOVERABLE; throw new shaka.util.Error( diff --git a/lib/net/http_xhr_plugin.js b/lib/net/http_xhr_plugin.js index ae23507ce1..541e067dc9 100644 --- a/lib/net/http_xhr_plugin.js +++ b/lib/net/http_xhr_plugin.js @@ -36,14 +36,14 @@ goog.require('shaka.util.Error'); * @export */ shaka.net.HttpXHRPlugin = function(uri, request, requestType, progressUpdated) { - let xhr = new shaka.net.HttpXHRPlugin.Xhr_(); + const xhr = new shaka.net.HttpXHRPlugin.Xhr_(); // Last time stamp when we got a progress event. let lastTime = Date.now(); // Last number of bytes loaded, from progress event. let lastLoaded = 0; - let promise = new Promise(function(resolve, reject) { + const promise = new Promise(function(resolve, reject) { xhr.open(request.method, uri, true); xhr.responseType = 'arraybuffer'; xhr.timeout = request.retryParameters.timeout; @@ -57,7 +57,7 @@ shaka.net.HttpXHRPlugin = function(uri, request, requestType, progressUpdated) { uri, requestType)); }; xhr.onload = function(event) { - let target = event.target; + const target = event.target; goog.asserts.assert(target, 'XHR onload has no target!'); // Since IE and Edge incorrectly return the header with a leading new line // character ('\n'), we trim the header here. @@ -70,7 +70,7 @@ shaka.net.HttpXHRPlugin = function(uri, request, requestType, progressUpdated) { } try { - let response = shaka.net.HttpPluginUtils.makeResponse(headers, + const response = shaka.net.HttpPluginUtils.makeResponse(headers, target.response, target.status, uri, target.responseURL, requestType); resolve(response); @@ -95,7 +95,7 @@ shaka.net.HttpXHRPlugin = function(uri, request, requestType, progressUpdated) { uri, requestType)); }; xhr.onprogress = function(event) { - let currentTime = Date.now(); + const currentTime = Date.now(); // If the time between last time and this time we got progress event // is long enough, or if a whole segment is downloaded, call // progressUpdated(). @@ -108,10 +108,10 @@ shaka.net.HttpXHRPlugin = function(uri, request, requestType, progressUpdated) { } }; - for (let key in request.headers) { + for (const key in request.headers) { // The Fetch API automatically normalizes outgoing header keys to // lowercase. For consistency's sake, do it here too. - let lowercasedKey = key.toLowerCase(); + const lowercasedKey = key.toLowerCase(); xhr.setRequestHeader(lowercasedKey, request.headers[key]); } xhr.send(request.body); diff --git a/lib/net/networking_engine.js b/lib/net/networking_engine.js index e4e11fbab1..46658b2bd6 100644 --- a/lib/net/networking_engine.js +++ b/lib/net/networking_engine.js @@ -165,7 +165,7 @@ shaka.net.NetworkingEngine.registerScheme = 'explicit priority must be > 0'); priority = priority || shaka.net.NetworkingEngine.PluginPriority.APPLICATION; - let existing = shaka.net.NetworkingEngine.schemes_[scheme]; + const existing = shaka.net.NetworkingEngine.schemes_[scheme]; if (!existing || priority >= existing.priority) { shaka.net.NetworkingEngine.schemes_[scheme] = { priority: priority, @@ -307,7 +307,7 @@ shaka.net.NetworkingEngine.prototype.destroy = function() { * @export */ shaka.net.NetworkingEngine.prototype.request = function(type, request) { - let cloneObject = shaka.util.ObjectUtils.cloneObject; + const cloneObject = shaka.util.ObjectUtils.cloneObject; const numBytesRemainingObj = new shaka.net.NetworkingEngine.NumBytesRemainingClass(); @@ -341,15 +341,15 @@ shaka.net.NetworkingEngine.prototype.request = function(type, request) { request.uris = cloneObject(request.uris); // Apply the registered filters to the request. - let requestFilterOperation = this.filterRequest_(type, request); - let requestOperation = requestFilterOperation.chain( + const requestFilterOperation = this.filterRequest_(type, request); + const requestOperation = requestFilterOperation.chain( () => this.makeRequestWithRetry_(type, request, numBytesRemainingObj)); - let responseFilterOperation = requestOperation.chain( + const responseFilterOperation = requestOperation.chain( (responseAndGotProgress) => this.filterResponse_(type, responseAndGotProgress)); // Keep track of time spent in filters. - let requestFilterStartTime = Date.now(); + const requestFilterStartTime = Date.now(); let requestFilterMs = 0; requestFilterOperation.promise.then(() => { requestFilterMs = Date.now() - requestFilterStartTime; @@ -436,9 +436,9 @@ shaka.net.NetworkingEngine.prototype.filterRequest_ = function(type, request) { */ shaka.net.NetworkingEngine.prototype.makeRequestWithRetry_ = function(type, request, numBytesRemainingObj) { - let backoff = new shaka.net.Backoff( + const backoff = new shaka.net.Backoff( request.retryParameters, /* autoReset */ false); - let index = 0; + const index = 0; return this.send_(type, request, backoff, index, /* lastError */ null, numBytesRemainingObj); }; @@ -460,7 +460,7 @@ shaka.net.NetworkingEngine.prototype.makeRequestWithRetry_ = */ shaka.net.NetworkingEngine.prototype.send_ = function( type, request, backoff, index, lastError, numBytesRemainingObj) { - let uri = new goog.Uri(request.uris[index]); + const uri = new goog.Uri(request.uris[index]); let scheme = uri.getScheme(); // Whether it got a progress event. let gotProgress = false; @@ -477,8 +477,8 @@ shaka.net.NetworkingEngine.prototype.send_ = function( request.uris[index] = uri.toString(); } - let object = shaka.net.NetworkingEngine.schemes_[scheme]; - let plugin = object ? object.plugin : null; + const object = shaka.net.NetworkingEngine.schemes_[scheme]; + const plugin = object ? object.plugin : null; if (!plugin) { return shaka.util.AbortableOperation.failed( new shaka.util.Error( @@ -491,11 +491,11 @@ shaka.net.NetworkingEngine.prototype.send_ = function( // Every attempt must have an associated backoff.attempt() call so that the // accounting is correct. - let backoffOperation = + const backoffOperation = shaka.util.AbortableOperation.notAbortable(backoff.attempt()); let startTimeMs; - let sendOperation = backoffOperation.chain(() => { + const sendOperation = backoffOperation.chain(() => { if (this.destroyed_) { return shaka.util.AbortableOperation.aborted(); } @@ -518,7 +518,7 @@ shaka.net.NetworkingEngine.prototype.send_ = function( if (response.timeMs == undefined) { response.timeMs = Date.now() - startTimeMs; } - let responseAndGotProgress = { + const responseAndGotProgress = { response: response, gotProgress: gotProgress, }; @@ -538,12 +538,12 @@ shaka.net.NetworkingEngine.prototype.send_ = function( // Don't pass in a non-shaka error, even if one is somehow thrown; // instead, call the listener with a null error. const errorOrNull = error instanceof shaka.util.Error ? error : null; - let event = new shaka.util.FakeEvent('retry', {'error': errorOrNull}); + const event = new shaka.util.FakeEvent('retry', {'error': errorOrNull}); this.dispatchEvent(event); // Move to the next URI. index = (index + 1) % request.uris.length; - let shakaError = /** @type {shaka.util.Error} */(error); + const shakaError = /** @type {shaka.util.Error} */(error); return this.send_(type, request, backoff, index, shakaError); } diff --git a/lib/offline/indexeddb/db_connection.js b/lib/offline/indexeddb/db_connection.js index 843eb335ff..346e76f84b 100644 --- a/lib/offline/indexeddb/db_connection.js +++ b/lib/offline/indexeddb/db_connection.js @@ -74,8 +74,9 @@ shaka.offline.indexeddb.DBConnection = class { * @private */ startOperation_(store, type) { - let transaction = this.connection_.transaction([store], type); - let operation = new shaka.offline.indexeddb.DBOperation(transaction, store); + const transaction = this.connection_.transaction([store], type); + const operation = + new shaka.offline.indexeddb.DBOperation(transaction, store); this.pending_.push(operation); diff --git a/lib/offline/indexeddb/storage_mechanism.js b/lib/offline/indexeddb/storage_mechanism.js index fdc95281cc..8de681bfb2 100644 --- a/lib/offline/indexeddb/storage_mechanism.js +++ b/lib/offline/indexeddb/storage_mechanism.js @@ -60,10 +60,10 @@ shaka.offline.indexeddb.StorageMechanism = class { const name = shaka.offline.indexeddb.StorageMechanism.DB_NAME; const version = shaka.offline.indexeddb.StorageMechanism.VERSION; - let p = new shaka.util.PublicPromise(); - let open = window.indexedDB.open(name, version); + const p = new shaka.util.PublicPromise(); + const open = window.indexedDB.open(name, version); open.onsuccess = (event) => { - let db = event.target.result; + const db = event.target.result; this.db_ = db; this.v1_ = shaka.offline.indexeddb.StorageMechanism.createV1_(db); this.v2_ = shaka.offline.indexeddb.StorageMechanism.createV2_(db); @@ -260,9 +260,9 @@ shaka.offline.indexeddb.StorageMechanism = class { static deleteAll_() { const name = shaka.offline.indexeddb.StorageMechanism.DB_NAME; - let p = new shaka.util.PublicPromise(); + const p = new shaka.util.PublicPromise(); - let del = window.indexedDB.deleteDatabase(name); + const del = window.indexedDB.deleteDatabase(name); del.onblocked = (event) => { shaka.log.warning('Deleting', name, 'is being blocked'); }; diff --git a/lib/offline/indexeddb/v1_storage_cell.js b/lib/offline/indexeddb/v1_storage_cell.js index 4109a300dc..ffdc5e424f 100644 --- a/lib/offline/indexeddb/v1_storage_cell.js +++ b/lib/offline/indexeddb/v1_storage_cell.js @@ -94,15 +94,15 @@ shaka.offline.indexeddb.V1StorageCell = class { * @override */ updateManifestExpiration(key, newExpiration) { - let op = this.connection_.startReadWriteOperation(this.manifestStore_); - let store = op.store(); + const op = this.connection_.startReadWriteOperation(this.manifestStore_); + const store = op.store(); - let p = new shaka.util.PublicPromise(); + const p = new shaka.util.PublicPromise(); store.get(key).onsuccess = (event) => { // Make sure a defined value was found. Indexeddb treats "no value found" // as a success with an undefined result. - let manifest = event.target.result; + const manifest = event.target.result; // Indexeddb does not fail when you get a value that is not in the // database. It will return an undefined value. However, we expect @@ -190,8 +190,8 @@ shaka.offline.indexeddb.V1StorageCell = class { * @private */ remove_(storeName, keys, onRemove) { - let op = this.connection_.startReadWriteOperation(storeName); - let store = op.store(); + const op = this.connection_.startReadWriteOperation(storeName); + const store = op.store(); keys.forEach((key) => { store.delete(key).onsuccess = () => onRemove(key); @@ -208,17 +208,17 @@ shaka.offline.indexeddb.V1StorageCell = class { * @private */ get_(storeName, keys) { - let op = this.connection_.startReadOnlyOperation(storeName); - let store = op.store(); + const op = this.connection_.startReadOnlyOperation(storeName); + const store = op.store(); - let values = {}; - let missing = []; + const values = {}; + const missing = []; // Use a map to store the objects so that we can reorder the results to // match the order of |keys|. keys.forEach((key) => { store.get(key).onsuccess = (event) => { - let value = event.target.result; + const value = event.target.result; // Make sure a defined value was found. Indexeddb treats no-value found // as a success with an undefined result. if (value == undefined) { @@ -524,8 +524,8 @@ shaka.offline.indexeddb.V1StorageCell = class { // 3. Some streams' variant ids are null and other are non-null // Case 3 is invalid and should never happen in production. - let audio = period.streams.filter((s) => s.contentType == AUDIO); - let video = period.streams.filter((s) => s.contentType == VIDEO); + const audio = period.streams.filter((s) => s.contentType == AUDIO); + const video = period.streams.filter((s) => s.contentType == VIDEO); // Case 2 - There is nothing we need to do, so let's just get out of here. if (audio.every((s) => s.variantIds) && video.every((s) => s.variantIds)) { @@ -556,7 +556,7 @@ shaka.offline.indexeddb.V1StorageCell = class { // own variant. if (video.length && !audio.length) { shaka.log.debug('Found video-only content. Creating variants for video.'); - let variantId = nextId++; + const variantId = nextId++; video.forEach((s) => { s.variantIds.push(variantId); }); } @@ -564,7 +564,7 @@ shaka.offline.indexeddb.V1StorageCell = class { // own variant. if (!video.length && audio.length) { shaka.log.debug('Found audio-only content. Creating variants for audio.'); - let variantId = nextId++; + const variantId = nextId++; audio.forEach((s) => { s.variantIds.push(variantId); }); } @@ -573,7 +573,7 @@ shaka.offline.indexeddb.V1StorageCell = class { shaka.log.debug('Found audio-video content. Creating variants.'); audio.forEach((a) => { video.forEach((v) => { - let variantId = nextId++; + const variantId = nextId++; a.variantIds.push(variantId); v.variantIds.push(variantId); }); diff --git a/lib/offline/indexeddb/v2_storage_cell.js b/lib/offline/indexeddb/v2_storage_cell.js index 0b49427f22..b67b67795c 100644 --- a/lib/offline/indexeddb/v2_storage_cell.js +++ b/lib/offline/indexeddb/v2_storage_cell.js @@ -87,10 +87,10 @@ shaka.offline.indexeddb.V2StorageCell = class { * @override */ updateManifestExpiration(key, newExpiration) { - let op = this.connection_.startReadWriteOperation(this.manifestStore_); - let store = op.store(); + const op = this.connection_.startReadWriteOperation(this.manifestStore_); + const store = op.store(); store.get(key).onsuccess = (e) => { - let found = e.target.result; + const found = e.target.result; // If we can't find the value, then there is nothing for us to update. if (found) { found.expiration = newExpiration; @@ -149,19 +149,19 @@ shaka.offline.indexeddb.V2StorageCell = class { 'Cannot add new value to ' + storeName)); } - let op = this.connection_.startReadWriteOperation(storeName); - let store = op.store(); + const op = this.connection_.startReadWriteOperation(storeName); + const store = op.store(); /** @type {!Array.<number>} */ - let keys = []; + const keys = []; // Write each segment out. When each request completes, the key will // be in |event.target.result| as can be seen in // https://w3c.github.io/IndexedDB/#key-generator-construct. values.forEach((value) => { - let request = store.add(value); + const request = store.add(value); request.onsuccess = (event) => { - let key = event.target.result; + const key = event.target.result; keys.push(key); }; }); @@ -179,8 +179,8 @@ shaka.offline.indexeddb.V2StorageCell = class { * @private */ remove_(storeName, keys, onRemove) { - let op = this.connection_.startReadWriteOperation(storeName); - let store = op.store(); + const op = this.connection_.startReadWriteOperation(storeName); + const store = op.store(); keys.forEach((key) => { store.delete(key).onsuccess = () => onRemove(key); @@ -197,16 +197,16 @@ shaka.offline.indexeddb.V2StorageCell = class { * @private */ get_(storeName, keys) { - let op = this.connection_.startReadOnlyOperation(storeName); - let store = op.store(); + const op = this.connection_.startReadOnlyOperation(storeName); + const store = op.store(); - let values = {}; - let missing = []; + const values = {}; + const missing = []; // Use a map to store the objects so that we can reorder the results to // match the order of |keys|. keys.forEach((key) => { - let request = store.get(key); + const request = store.get(key); request.onsuccess = () => { // Make sure a defined value was found. Indexeddb treats no-value found // as a success with an undefined result. diff --git a/lib/offline/manifest_converter.js b/lib/offline/manifest_converter.js index bcbabfba03..2756357720 100644 --- a/lib/offline/manifest_converter.js +++ b/lib/offline/manifest_converter.js @@ -54,13 +54,13 @@ shaka.offline.ManifestConverter = class { * @return {shaka.extern.Manifest} */ fromManifestDB(manifestDB) { - let timeline = new shaka.media.PresentationTimeline(null, 0); + const timeline = new shaka.media.PresentationTimeline(null, 0); timeline.setDuration(manifestDB.duration); - let periods = manifestDB.periods.map((period) => + const periods = manifestDB.periods.map((period) => this.fromPeriodDB(period, timeline)); - let drmInfos = manifestDB.drmInfo ? [manifestDB.drmInfo] : []; + const drmInfos = manifestDB.drmInfo ? [manifestDB.drmInfo] : []; if (manifestDB.drmInfo) { periods.forEach((period) => { period.variants.forEach((variant) => { variant.drmInfos = drmInfos; }); @@ -84,21 +84,23 @@ shaka.offline.ManifestConverter = class { */ fromPeriodDB(period, timeline) { /** @type {!Array.<shaka.extern.StreamDB>} */ - let audioStreams = period.streams.filter((stream) => this.isAudio_(stream)); + const audioStreams = + period.streams.filter((stream) => this.isAudio_(stream)); /** @type {!Array.<shaka.extern.StreamDB>} */ - let videoStreams = period.streams.filter((stream) => this.isVideo_(stream)); + const videoStreams = + period.streams.filter((stream) => this.isVideo_(stream)); /** @type {!Map.<number, shaka.extern.Variant>} */ const variants = this.createVariants(audioStreams, videoStreams); /** @type {!Array.<shaka.extern.Stream>} */ - let textStreams = period.streams + const textStreams = period.streams .filter((stream) => this.isText_(stream)) .map((stream) => this.fromStreamDB_(stream)); period.streams.forEach((stream, i) => { /** @type {!Array.<!shaka.media.SegmentReference>} */ - let refs = stream.segments.map((segment, index) => { + const refs = stream.segments.map((segment, index) => { return this.fromSegmentDB_(index, segment); }); @@ -179,14 +181,14 @@ shaka.offline.ManifestConverter = class { */ fromStreamDB_(streamDB) { /** @type {!Array.<!shaka.media.SegmentReference>} */ - let segments = streamDB.segments.map((segment, index) => + const segments = streamDB.segments.map((segment, index) => this.fromSegmentDB_(index, segment)); /** @type {!shaka.media.SegmentIndex} */ - let segmentIndex = new shaka.media.SegmentIndex(segments); + const segmentIndex = new shaka.media.SegmentIndex(segments); /** @type {shaka.extern.Stream} */ - let stream = { + const stream = { id: streamDB.id, originalId: streamDB.originalId, createSegmentIndex: () => Promise.resolve(), @@ -230,7 +232,7 @@ shaka.offline.ManifestConverter = class { */ fromSegmentDB_(index, segmentDB) { /** @type {!shaka.offline.OfflineUri} */ - let uri = shaka.offline.OfflineUri.segment( + const uri = shaka.offline.OfflineUri.segment( this.mechanism_, this.cell_, segmentDB.dataKey); return new shaka.media.SegmentReference( @@ -249,7 +251,7 @@ shaka.offline.ManifestConverter = class { */ fromInitSegmentDB_(key) { /** @type {!shaka.offline.OfflineUri} */ - let uri = shaka.offline.OfflineUri.segment( + const uri = shaka.offline.OfflineUri.segment( this.mechanism_, this.cell_, key); return new shaka.media.InitSegmentReference( diff --git a/lib/offline/offline_scheme.js b/lib/offline/offline_scheme.js index b226f1b93a..b83a4806b5 100644 --- a/lib/offline/offline_scheme.js +++ b/lib/offline/offline_scheme.js @@ -35,7 +35,7 @@ goog.require('shaka.util.Error'); * @export */ shaka.offline.OfflineScheme = function(uri, request, requestType) { - let offlineUri = shaka.offline.OfflineUri.parse(uri); + const offlineUri = shaka.offline.OfflineUri.parse(uri); if (offlineUri && offlineUri.isManifest()) { return shaka.offline.OfflineScheme.getManifest_(uri); @@ -62,7 +62,7 @@ shaka.offline.OfflineScheme = function(uri, request, requestType) { */ shaka.offline.OfflineScheme.getManifest_ = function(uri) { /** @type {shaka.extern.Response} */ - let response = { + const response = { uri: uri, data: new ArrayBuffer(0), headers: {'content-type': 'application/x-offline-manifest'}, diff --git a/lib/offline/offline_uri.js b/lib/offline/offline_uri.js index 6459350fdc..83fb2b4fe3 100644 --- a/lib/offline/offline_uri.js +++ b/lib/offline/offline_uri.js @@ -89,19 +89,19 @@ shaka.offline.OfflineUri = class { * @return {?shaka.offline.OfflineUri} */ static parse(uri) { - let parts = /^offline:([a-z]+)\/([^/]+)\/([^/]+)\/([0-9]+)$/.exec(uri); + const parts = /^offline:([a-z]+)\/([^/]+)\/([^/]+)\/([0-9]+)$/.exec(uri); if (parts == null) { return null; } - let type = parts[1]; + const type = parts[1]; if (type != 'manifest' && type != 'segment') { return null; } - let mechanism = parts[2]; + const mechanism = parts[2]; if (!mechanism) { return null; } - let cell = parts[3]; + const cell = parts[3]; if (!cell) { return null; } - let key = Number(parts[4]); + const key = Number(parts[4]); if (type == null) { return null; } return new shaka.offline.OfflineUri(type, mechanism, cell, key); diff --git a/lib/offline/storage.js b/lib/offline/storage.js index 861ba67719..082b920952 100644 --- a/lib/offline/storage.js +++ b/lib/offline/storage.js @@ -207,7 +207,7 @@ shaka.offline.Storage.prototype.configure = function(config) { shaka.offline.Storage.prototype.getConfiguration = function() { goog.asserts.assert(this.config_, 'Config must not be null!'); - let ret = shaka.util.PlayerConfiguration.createDefault(); + const ret = shaka.util.PlayerConfiguration.createDefault(); shaka.util.PlayerConfiguration.mergeConfigObjects( ret, this.config_, shaka.util.PlayerConfiguration.createDefault()); return ret; @@ -339,7 +339,7 @@ shaka.offline.Storage.prototype.store_ = async function( /** @type {?shaka.media.DrmEngine} */ let drmEngine = null; /** @type {shaka.offline.StorageMuxer} */ - let muxer = new shaka.offline.StorageMuxer(); + const muxer = new shaka.offline.StorageMuxer(); /** @type {?shaka.offline.StorageCellHandle} */ let activeHandle = null; @@ -630,16 +630,16 @@ shaka.offline.Storage.prototype.removeFromDRM_ = async function( shaka.offline.Storage.prototype.removeFromStorage_ = function( storage, uri, manifest) { /** @type {!Array.<number>} */ - let segmentIds = shaka.offline.Storage.getAllSegmentIds_(manifest); + const segmentIds = shaka.offline.Storage.getAllSegmentIds_(manifest); // Count(segments) + Count(manifests) - let toRemove = segmentIds.length + 1; + const toRemove = segmentIds.length + 1; let removed = 0; - let pendingContent = shaka.offline.StoredContentUtils.fromManifestDB( + const pendingContent = shaka.offline.StoredContentUtils.fromManifestDB( uri, manifest); - let onRemove = (key) => { + const onRemove = (key) => { removed += 1; this.config_.offline.progressCallback(pendingContent, removed / toRemove); }; @@ -893,15 +893,15 @@ shaka.offline.Storage.prototype.createDrmEngine = async function( */ shaka.offline.Storage.prototype.createOfflineManifest_ = function( downloader, storage, drmEngine, manifest, originalManifestUri, metadata) { - let estimator = new shaka.offline.StreamBandwidthEstimator(); + const estimator = new shaka.offline.StreamBandwidthEstimator(); - let periods = manifest.periods.map((period) => { + const periods = manifest.periods.map((period) => { return this.createPeriod_( downloader, storage, estimator, drmEngine, manifest, period); }); - let drmInfo = drmEngine.getDrmInfo(); - let sessions = drmEngine.getSessionIds(); + const drmInfo = drmEngine.getDrmInfo(); + const sessions = drmEngine.getSessionIds(); if (drmInfo && this.config_.offline.usePersistentLicense) { if (!sessions.length) { @@ -993,7 +993,7 @@ shaka.offline.Storage.prototype.createPeriod_ = function( shaka.offline.Storage.prototype.createStream_ = function( downloader, storage, estimator, manifest, period, stream) { /** @type {shaka.extern.StreamDB} */ - let streamDb = { + const streamDb = { id: stream.id, originalId: stream.originalId, primary: stream.primary, @@ -1015,11 +1015,11 @@ shaka.offline.Storage.prototype.createStream_ = function( }; /** @type {number} */ - let startTime = + const startTime = manifest.presentationTimeline.getSegmentAvailabilityStart(); // Download each stream in parallel. - let downloadGroup = stream.id; + const downloadGroup = stream.id; shaka.offline.Storage.forEachSegment_(stream, startTime, (segment) => { const request = shaka.util.Networking.createSegmentRequest( @@ -1045,7 +1045,7 @@ shaka.offline.Storage.prototype.createStream_ = function( }); }); - let initSegment = stream.initSegmentReference; + const initSegment = stream.initSegmentReference; if (initSegment) { const request = shaka.util.Networking.createSegmentRequest( initSegment.getUris(), @@ -1149,7 +1149,7 @@ shaka.offline.Storage.prototype.startOperation_ = async function(action) { */ shaka.offline.Storage.getAllSegmentIds_ = function(manifest) { /** @type {!Array.<number>} */ - let ids = []; + const ids = []; // Get every segment for every stream in the manifest. manifest.periods.forEach(function(period) { diff --git a/lib/offline/stored_content_utils.js b/lib/offline/stored_content_utils.js index 0b16e60e55..196d5da38b 100644 --- a/lib/offline/stored_content_utils.js +++ b/lib/offline/stored_content_utils.js @@ -42,21 +42,21 @@ shaka.offline.StoredContentUtils = class { 'Cannot create stored content from manifest with no periods.'); /** @type {number} */ - let expiration = manifest.expiration == undefined ? + const expiration = manifest.expiration == undefined ? Infinity : manifest.expiration; /** @type {number} */ - let duration = manifest.presentationTimeline.getDuration(); + const duration = manifest.presentationTimeline.getDuration(); /** @type {shaka.extern.Period} */ - let firstPeriod = manifest.periods[0]; + const firstPeriod = manifest.periods[0]; /** @type {!Array.<shaka.extern.Track>} */ - let tracks = shaka.offline.StoredContentUtils.getTracks_(firstPeriod); + const tracks = shaka.offline.StoredContentUtils.getTracks_(firstPeriod); /** @type {shaka.extern.StoredContent} */ - let content = { + const content = { offlineUri: null, originalManifestUri: originalUri, duration: duration, @@ -80,26 +80,26 @@ shaka.offline.StoredContentUtils = class { manifestDB.periods.length, 'Cannot create stored content from manifestDB with no periods.'); - let converter = new shaka.offline.ManifestConverter( + const converter = new shaka.offline.ManifestConverter( offlineUri.mechanism(), offlineUri.cell()); /** @type {shaka.extern.PeriodDB} */ - let firstPeriodDB = manifestDB.periods[0]; + const firstPeriodDB = manifestDB.periods[0]; /** @type {!shaka.media.PresentationTimeline} */ - let timeline = new shaka.media.PresentationTimeline(null, 0); + const timeline = new shaka.media.PresentationTimeline(null, 0); /** @type {shaka.extern.Period} */ - let firstPeriod = converter.fromPeriodDB(firstPeriodDB, timeline); + const firstPeriod = converter.fromPeriodDB(firstPeriodDB, timeline); /** @type {!Object} */ - let metadata = manifestDB.appMetadata || {}; + const metadata = manifestDB.appMetadata || {}; /** @type {!Array.<shaka.extern.Track>} */ - let tracks = shaka.offline.StoredContentUtils.getTracks_(firstPeriod); + const tracks = shaka.offline.StoredContentUtils.getTracks_(firstPeriod); /** @type {shaka.extern.StoredContent} */ - let content = { + const content = { offlineUri: offlineUri.toString(), originalManifestUri: manifestDB.originalManifestUri, duration: manifestDB.duration, diff --git a/lib/offline/stream_bandwidth_estimator.js b/lib/offline/stream_bandwidth_estimator.js index 48a601193f..2df7a78d2b 100644 --- a/lib/offline/stream_bandwidth_estimator.js +++ b/lib/offline/stream_bandwidth_estimator.js @@ -44,18 +44,18 @@ shaka.offline.StreamBandwidthEstimator = class { // 2 - Only Video // 3 - Audio and Video - let audio = variant.audio; - let video = variant.video; + const audio = variant.audio; + const video = variant.video; // Case 1 if (audio && !video) { - let audioBitRate = audio.bandwidth || variant.bandwidth; + const audioBitRate = audio.bandwidth || variant.bandwidth; this.setBitrate_(audio.id, audioBitRate); } // Case 2 if (!audio && video) { - let videoBitRate = video.bandwidth || variant.bandwidth; + const videoBitRate = video.bandwidth || variant.bandwidth; this.setBitrate_(video.id, videoBitRate); } @@ -63,7 +63,7 @@ shaka.offline.StreamBandwidthEstimator = class { if (audio && video) { // Get the audio's bandwidth. If it is missing, default to our default // audio bandwidth. - let audioBitRate = + const audioBitRate = audio.bandwidth || shaka.offline.StreamBandwidthEstimator.DEFAULT_AUDIO_BITRATE_; @@ -111,7 +111,7 @@ shaka.offline.StreamBandwidthEstimator = class { * @return {number} */ getSegmentEstimate(id, segment) { - let duration = segment.endTime - segment.startTime; + const duration = segment.endTime - segment.startTime; return this.getEstimate_(id) * duration; } @@ -125,7 +125,7 @@ shaka.offline.StreamBandwidthEstimator = class { getInitSegmentEstimate(id) { // Assume that the init segment is worth approximately half a second of // content. - let duration = 0.5; + const duration = 0.5; return this.getEstimate_(id) * duration; } diff --git a/lib/player.js b/lib/player.js index 5d1c58454a..6956c572ef 100644 --- a/lib/player.js +++ b/lib/player.js @@ -737,16 +737,16 @@ shaka.Player.probeSupport = function() { goog.asserts.assert(shaka.Player.isBrowserSupported(), 'Must have basic support'); return shaka.media.DrmEngine.probeSupport().then(function(drm) { - let manifest = shaka.media.ManifestParser.probeSupport(); - let media = shaka.media.MediaSourceEngine.probeSupport(); - let ret = { + const manifest = shaka.media.ManifestParser.probeSupport(); + const media = shaka.media.MediaSourceEngine.probeSupport(); + const ret = { manifest: manifest, media: media, drm: drm, }; - let plugins = shaka.Player.supportPlugins_; - for (let name in plugins) { + const plugins = shaka.Player.supportPlugins_; + for (const name in plugins) { ret[name] = plugins[name](); } @@ -2043,7 +2043,7 @@ shaka.Player.prototype.chooseCodecsAndFilterManifest_ = function() { sum += variant.bandwidth || 0; ++num; }); - let averageBandwidth = sum / num; + const averageBandwidth = sum / num; shaka.log.debug('codecs', codecs, 'avg bandwidth', averageBandwidth); if (averageBandwidth < lowestAverageBandwidth) { @@ -2059,7 +2059,7 @@ shaka.Player.prototype.chooseCodecsAndFilterManifest_ = function() { // the most efficient variants possible. this.manifest_.periods.forEach(function(period) { period.variants = period.variants.filter(function(variant) { - let codecs = variantCodecs(variant); + const codecs = variantCodecs(variant); if (codecs == bestCodecs) return true; shaka.log.debug('Dropping Variant (better codec available)', variant); @@ -2280,7 +2280,7 @@ shaka.Player.prototype.createStreamingEngine = function() { 'Must not be destroyed'); /** @type {shaka.media.StreamingEngine.PlayerInterface} */ - let playerInterface = { + const playerInterface = { getPresentationTime: () => this.playhead_.getTime(), mediaSourceEngine: this.mediaSourceEngine_, netEngine: this.networkingEngine_, @@ -2327,7 +2327,7 @@ shaka.Player.prototype.configure = function(config, value) { goog.asserts.assert(typeof(config) == 'object', 'Should be an object!'); - let ret = shaka.util.PlayerConfiguration.mergeConfigObjects( + const ret = shaka.util.PlayerConfiguration.mergeConfigObjects( this.config_, config, this.defaultConfig_()); this.applyConfig_(); @@ -2347,17 +2347,17 @@ shaka.Player.prototype.configure = function(config, value) { * @private */ shaka.Player.prototype.convertToConfigObject_ = function(fieldName, value) { - let configObject = {}; + const configObject = {}; let last = configObject; let searchIndex = 0; let nameStart = 0; while (true) { // eslint-disable-line no-constant-condition - let idx = fieldName.indexOf('.', searchIndex); + const idx = fieldName.indexOf('.', searchIndex); if (idx < 0) { break; } if (idx == 0 || fieldName[idx - 1] != '\\') { - let part = fieldName.substring(nameStart, idx).replace(/\\\./g, '.'); + const part = fieldName.substring(nameStart, idx).replace(/\\\./g, '.'); last[part] = {}; last = last[part]; nameStart = idx + 1; @@ -2393,11 +2393,11 @@ shaka.Player.prototype.applyConfig_ = function() { } // If the stream we are playing is restricted, we need to switch. - let activeAudio = this.streamingEngine_.getBufferingAudio(); - let activeVideo = this.streamingEngine_.getBufferingVideo(); + const activeAudio = this.streamingEngine_.getBufferingAudio(); + const activeVideo = this.streamingEngine_.getBufferingVideo(); /** @type {shaka.extern.Period} */ - let period = this.getPresentationPeriod_(); - let activeVariant = shaka.util.StreamUtils.getVariantByStreams( + const period = this.getPresentationPeriod_(); + const activeVariant = shaka.util.StreamUtils.getVariantByStreams( activeAudio, activeVideo, period.variants); if (this.abrManager_ && activeVariant && activeVariant.allowedByApplication && @@ -2436,7 +2436,7 @@ shaka.Player.prototype.applyConfig_ = function() { shaka.Player.prototype.getConfiguration = function() { goog.asserts.assert(this.config_, 'Config must not be null!'); - let ret = this.defaultConfig_(); + const ret = this.defaultConfig_(); shaka.util.PlayerConfiguration.mergeConfigObjects( ret, this.config_, this.defaultConfig_()); return ret; @@ -3612,7 +3612,7 @@ shaka.Player.prototype.defaultConfig_ = function() { * @private */ shaka.Player.prototype.defaultStreamingFailureCallback_ = function(error) { - let retryErrorCodes = [ + const retryErrorCodes = [ shaka.util.Error.Code.BAD_HTTP_STATUS, shaka.util.Error.Code.HTTP_ERROR, shaka.util.Error.Code.TIMEOUT, @@ -3639,13 +3639,13 @@ shaka.Player.prototype.createTextStreamsForClosedCaptions_ = function(periods) { for (let periodIndex = 0; periodIndex < periods.length; periodIndex++) { const period = periods[periodIndex]; // A map of the closed captions id and the new dummy text stream. - let closedCaptionsMap = new Map(); - for (let variant of period.variants) { + const closedCaptionsMap = new Map(); + for (const variant of period.variants) { if (variant.video && variant.video.closedCaptions) { - let video = variant.video; + const video = variant.video; for (const id of video.closedCaptions.keys()) { if (!closedCaptionsMap.has(id)) { - let textStream = { + const textStream = { id: this.nextExternalStreamId_++, // A globally unique ID. originalId: id, // The CC ID string, like 'CC1', 'CC3', etc. createSegmentIndex: Promise.resolve.bind(Promise), @@ -3692,17 +3692,17 @@ shaka.Player.prototype.filterAllPeriods_ = function(periods) { const StreamUtils = shaka.util.StreamUtils; /** @type {?shaka.extern.Stream} */ - let activeAudio = + const activeAudio = this.streamingEngine_ ? this.streamingEngine_.getBufferingAudio() : null; /** @type {?shaka.extern.Stream} */ - let activeVideo = + const activeVideo = this.streamingEngine_ ? this.streamingEngine_.getBufferingVideo() : null; - let filterPeriod = StreamUtils.filterNewPeriod.bind( + const filterPeriod = StreamUtils.filterNewPeriod.bind( null, this.drmEngine_, activeAudio, activeVideo); periods.forEach(filterPeriod); - let validPeriodsCount = ArrayUtils.count(periods, function(period) { + const validPeriodsCount = ArrayUtils.count(periods, function(period) { return period.variants.some(StreamUtils.isPlayable); }); @@ -3723,7 +3723,7 @@ shaka.Player.prototype.filterAllPeriods_ = function(periods) { } periods.forEach(function(period) { - let tracksChanged = shaka.util.StreamUtils.applyRestrictions( + const tracksChanged = shaka.util.StreamUtils.applyRestrictions( period.variants, this.config_.restrictions, this.maxHwRes_); if (tracksChanged && this.streamingEngine_ && this.getPresentationPeriod_() == period) { @@ -3745,17 +3745,17 @@ shaka.Player.prototype.filterNewPeriod_ = function(period) { const StreamUtils = shaka.util.StreamUtils; /** @type {?shaka.extern.Stream} */ - let activeAudio = + const activeAudio = this.streamingEngine_ ? this.streamingEngine_.getBufferingAudio() : null; /** @type {?shaka.extern.Stream} */ - let activeVideo = + const activeVideo = this.streamingEngine_ ? this.streamingEngine_.getBufferingVideo() : null; StreamUtils.filterNewPeriod( this.drmEngine_, activeAudio, activeVideo, period); /** @type {!Array.<shaka.extern.Variant>} */ - let variants = period.variants; + const variants = period.variants; // Check for playable variants before restrictions, so that we can give a // special error when there were tracks but they were all filtered. @@ -3852,9 +3852,9 @@ shaka.Player.prototype.assertCorrectActiveStreams_ = function() { return; } - let activeAudio = this.streamingEngine_.getBufferingAudio(); - let activeVideo = this.streamingEngine_.getBufferingVideo(); - let activeText = this.streamingEngine_.getBufferingText(); + const activeAudio = this.streamingEngine_.getBufferingAudio(); + const activeVideo = this.streamingEngine_.getBufferingVideo(); + const activeText = this.streamingEngine_.getBufferingText(); // If we have deferred variants/text we want to compare against those rather // than what we are actually streaming. @@ -3894,27 +3894,27 @@ shaka.Player.prototype.assertCorrectActiveStreams_ = function() { */ shaka.Player.prototype.adjustStartTime_ = function(time) { /** @type {?shaka.extern.Stream} */ - let activeAudio = this.streamingEngine_.getBufferingAudio(); + const activeAudio = this.streamingEngine_.getBufferingAudio(); /** @type {?shaka.extern.Stream} */ - let activeVideo = this.streamingEngine_.getBufferingVideo(); + const activeVideo = this.streamingEngine_.getBufferingVideo(); /** @type {shaka.extern.Period} */ - let period = this.getPresentationPeriod_(); + const period = this.getPresentationPeriod_(); // This method is called after StreamingEngine.init resolves, which means that // all the active streams have had createSegmentIndex called. function getAdjustedTime(stream, time) { if (!stream) return null; - let idx = stream.findSegmentPosition(time - period.startTime); + const idx = stream.findSegmentPosition(time - period.startTime); if (idx == null) return null; - let ref = stream.getSegmentReference(idx); + const ref = stream.getSegmentReference(idx); if (!ref) return null; - let refTime = ref.startTime + period.startTime; + const refTime = ref.startTime + period.startTime; goog.asserts.assert(refTime <= time, 'Segment should start before time'); return refTime; } - let audioStartTime = getAdjustedTime(activeAudio, time); - let videoStartTime = getAdjustedTime(activeVideo, time); + const audioStartTime = getAdjustedTime(activeAudio, time); + const videoStartTime = getAdjustedTime(activeVideo, time); // If we have both video and audio times, pick the larger one. If we picked // the smaller one, that one will download an entire segment to buffer the @@ -3951,7 +3951,8 @@ shaka.Player.prototype.updateBufferState_ = function() { } // Surface the buffering event so that the app knows if/when we are buffering. - let event = new shaka.util.FakeEvent('buffering', {'buffering': isBuffering}); + const event = + new shaka.util.FakeEvent('buffering', {'buffering': isBuffering}); this.dispatchEvent(event); }; @@ -4437,7 +4438,7 @@ shaka.Player.prototype.onError_ = function(error) { // be safe to ignore. if (this.loadMode_ == shaka.Player.LoadMode.DESTROYED) { return; } - let event = new shaka.util.FakeEvent('error', {'detail': error}); + const event = new shaka.util.FakeEvent('error', {'detail': error}); this.dispatchEvent(event); if (event.defaultPrevented) { error.handled = true; @@ -4541,7 +4542,7 @@ shaka.Player.prototype.onKeyStatus_ = function(keyStatusMap) { const period = this.getPresentationPeriod_(); let tracksChanged = false; - let keyIds = Object.keys(keyStatusMap); + const keyIds = Object.keys(keyStatusMap); if (keyIds.length == 0) { shaka.log.warning( 'Got a key status event without any key statuses, so we don\'t know ' + @@ -4552,7 +4553,7 @@ shaka.Player.prototype.onKeyStatus_ = function(keyStatusMap) { // If EME is using a synthetic key ID, the only key ID is '00' (a single 0 // byte). In this case, it is only used to report global success/failure. // See note about old platforms in: https://bit.ly/2tpez5Z - let isGlobalStatus = keyIds.length == 1 && keyIds[0] == '00'; + const isGlobalStatus = keyIds.length == 1 && keyIds[0] == '00'; if (isGlobalStatus) { shaka.log.warning( @@ -4567,13 +4568,13 @@ shaka.Player.prototype.onKeyStatus_ = function(keyStatusMap) { const streams = shaka.util.StreamUtils.getVariantStreams(variant); streams.forEach(function(stream) { - let originalAllowed = variant.allowedByKeySystem; + const originalAllowed = variant.allowedByKeySystem; // Only update if we have a key ID for the stream. // If the key isn't present, then we don't have that key and the track // should be restricted. if (stream.keyId) { - let keyStatus = keyStatusMap[isGlobalStatus ? '00' : stream.keyId]; + const keyStatus = keyStatusMap[isGlobalStatus ? '00' : stream.keyId]; variant.allowedByKeySystem = !!keyStatus && !restrictedStatuses.includes(keyStatus); } @@ -4587,9 +4588,9 @@ shaka.Player.prototype.onKeyStatus_ = function(keyStatusMap) { // TODO: Get StreamingEngine to track variants and create // getBufferingVariant() - let activeAudio = this.streamingEngine_.getBufferingAudio(); - let activeVideo = this.streamingEngine_.getBufferingVideo(); - let activeVariant = shaka.util.StreamUtils.getVariantByStreams( + const activeAudio = this.streamingEngine_.getBufferingAudio(); + const activeVideo = this.streamingEngine_.getBufferingVideo(); + const activeVariant = shaka.util.StreamUtils.getVariantByStreams( activeAudio, activeVideo, period.variants); if (activeVariant && !activeVariant.allowedByKeySystem) { @@ -4615,7 +4616,7 @@ shaka.Player.prototype.onExpirationUpdated_ = function(keyId, expiration) { this.parser_.onExpirationUpdated(keyId, expiration); } - let event = new shaka.util.FakeEvent('expirationupdated'); + const event = new shaka.util.FakeEvent('expirationupdated'); this.dispatchEvent(event); }; @@ -4681,18 +4682,18 @@ shaka.Player.prototype.checkRestrictedVariants_ = function(variants) { let hasPlayable = false; let hasAppRestrict = false; - let missingKeys = []; - let badKeyStatuses = []; + const missingKeys = []; + const badKeyStatuses = []; - for (let variant of variants) { + for (const variant of variants) { // TODO: Combine with onKeyStatus_. - let streams = []; + const streams = []; if (variant.audio) streams.push(variant.audio); if (variant.video) streams.push(variant.video); - for (let stream of streams) { + for (const stream of streams) { if (stream.keyId) { - let keyStatus = keyStatusMap[isGlobalStatus ? '00' : stream.keyId]; + const keyStatus = keyStatusMap[isGlobalStatus ? '00' : stream.keyId]; if (!keyStatus) { if (!missingKeys.includes(stream.keyId)) { missingKeys.push(stream.keyId); @@ -4714,7 +4715,7 @@ shaka.Player.prototype.checkRestrictedVariants_ = function(variants) { if (!hasPlayable) { /** @type {shaka.extern.RestrictionInfo} */ - let data = { + const data = { hasAppRestrictions: hasAppRestrict, missingKeys: missingKeys, restrictedKeyStatuses: badKeyStatuses, diff --git a/lib/polyfill/fullscreen.js b/lib/polyfill/fullscreen.js index 7d37783ca4..64e1ae1ff6 100644 --- a/lib/polyfill/fullscreen.js +++ b/lib/polyfill/fullscreen.js @@ -69,7 +69,7 @@ shaka.polyfill.Fullscreen.install = function() { }); } - let proxy = shaka.polyfill.Fullscreen.proxyEvent_; + const proxy = shaka.polyfill.Fullscreen.proxyEvent_; document.addEventListener('webkitfullscreenchange', proxy); document.addEventListener('webkitfullscreenerror', proxy); document.addEventListener('mozfullscreenchange', proxy); @@ -85,7 +85,7 @@ shaka.polyfill.Fullscreen.install = function() { * @private */ shaka.polyfill.Fullscreen.proxyEvent_ = function(event) { - let eventType = event.type.replace(/^(webkit|moz|MS)/, '').toLowerCase(); + const eventType = event.type.replace(/^(webkit|moz|MS)/, '').toLowerCase(); let newEvent; // IE 11 does not have an Event constructor diff --git a/lib/polyfill/mathround.js b/lib/polyfill/mathround.js index cd2280005d..91fe3dce88 100644 --- a/lib/polyfill/mathround.js +++ b/lib/polyfill/mathround.js @@ -40,10 +40,10 @@ shaka.polyfill.MathRound.MAX_ACCURATE_INPUT_ = 0x10000000000000; shaka.polyfill.MathRound.install = function() { shaka.log.debug('mathRound.install'); - let testNumber = shaka.polyfill.MathRound.MAX_ACCURATE_INPUT_ + 1; + const testNumber = shaka.polyfill.MathRound.MAX_ACCURATE_INPUT_ + 1; if (Math.round(testNumber) != testNumber) { shaka.log.debug('polyfill Math.round'); - let originalMathRound = Math.round; + const originalMathRound = Math.round; Math.round = function(number) { let result = number; // Due to the precision of JavaScript numbers, the number must be integer. diff --git a/lib/polyfill/mediasource.js b/lib/polyfill/mediasource.js index 90338718d3..62eb1a0dcf 100644 --- a/lib/polyfill/mediasource.js +++ b/lib/polyfill/mediasource.js @@ -49,7 +49,7 @@ shaka.polyfill.MediaSource.install = function() { // Chromecast cannot make accurate determinations via isTypeSupported. shaka.polyfill.MediaSource.patchCastIsTypeSupported_(); } else if (shaka.util.Platform.isApple()) { - let version = navigator.appVersion; + const version = navigator.appVersion; // TS content is broken on Safari in general. // See https://github.com/google/shaka-player/issues/743 @@ -125,7 +125,7 @@ shaka.polyfill.MediaSource.blacklist_ = function() { shaka.polyfill.MediaSource.stubAbort_ = function() { const addSourceBuffer = MediaSource.prototype.addSourceBuffer; MediaSource.prototype.addSourceBuffer = function(...varArgs) { - let sourceBuffer = addSourceBuffer.apply(this, varArgs); + const sourceBuffer = addSourceBuffer.apply(this, varArgs); sourceBuffer.abort = function() {}; // Stub out for buggy implementations. return sourceBuffer; }; @@ -166,8 +166,8 @@ shaka.polyfill.MediaSource.patchEndOfStreamEvents_ = function() { // new duration will be. let newDuration = 0; for (let i = 0; i < this.sourceBuffers.length; ++i) { - let buffer = this.sourceBuffers[i]; - let bufferEnd = buffer.buffered.end(buffer.buffered.length - 1); + const buffer = this.sourceBuffers[i]; + const bufferEnd = buffer.buffered.end(buffer.buffered.length - 1); newDuration = Math.max(newDuration, bufferEnd); } @@ -177,7 +177,7 @@ shaka.polyfill.MediaSource.patchEndOfStreamEvents_ = function() { newDuration < this.duration) { this.ignoreUpdateEnd_ = true; for (let i = 0; i < this.sourceBuffers.length; ++i) { - let buffer = this.sourceBuffers[i]; + const buffer = this.sourceBuffers[i]; buffer.eventSuppressed_ = false; } } @@ -186,11 +186,11 @@ shaka.polyfill.MediaSource.patchEndOfStreamEvents_ = function() { }; let cleanUpHandlerInstalled = false; - let addSourceBuffer = MediaSource.prototype.addSourceBuffer; + const addSourceBuffer = MediaSource.prototype.addSourceBuffer; MediaSource.prototype.addSourceBuffer = function(...varArgs) { // After adding a new source buffer, add an event listener to allow us to // suppress events. - let sourceBuffer = addSourceBuffer.apply(this, varArgs); + const sourceBuffer = addSourceBuffer.apply(this, varArgs); sourceBuffer['mediaSource_'] = this; sourceBuffer.addEventListener('updateend', shaka.polyfill.MediaSource.ignoreUpdateEnd_, false); @@ -216,8 +216,8 @@ shaka.polyfill.MediaSource.patchEndOfStreamEvents_ = function() { * @private */ shaka.polyfill.MediaSource.ignoreUpdateEnd_ = function(event) { - let sourceBuffer = event.target; - let mediaSource = sourceBuffer['mediaSource_']; + const sourceBuffer = event.target; + const mediaSource = sourceBuffer['mediaSource_']; if (mediaSource.ignoreUpdateEnd_) { event.preventDefault(); @@ -226,7 +226,7 @@ shaka.polyfill.MediaSource.ignoreUpdateEnd_ = function(event) { sourceBuffer.eventSuppressed_ = true; for (let i = 0; i < mediaSource.sourceBuffers.length; ++i) { - let buffer = mediaSource.sourceBuffers[i]; + const buffer = mediaSource.sourceBuffers[i]; if (buffer.eventSuppressed_ == false) { // More events need to be suppressed. return; @@ -251,9 +251,9 @@ shaka.polyfill.MediaSource.ignoreUpdateEnd_ = function(event) { * @private */ shaka.polyfill.MediaSource.cleanUpListeners_ = function(event) { - let mediaSource = /** @type {!MediaSource} */ (event.target); + const mediaSource = /** @type {!MediaSource} */ (event.target); for (let i = 0; i < mediaSource.sourceBuffers.length; ++i) { - let buffer = mediaSource.sourceBuffers[i]; + const buffer = mediaSource.sourceBuffers[i]; buffer.removeEventListener('updateend', shaka.polyfill.MediaSource.ignoreUpdateEnd_, false); } @@ -273,9 +273,9 @@ shaka.polyfill.MediaSource.rejectTsContent_ = function() { MediaSource.isTypeSupported = function(mimeType) { // Parse the basic MIME type from its parameters. - let pieces = mimeType.split(/ *; */); - let basicMimeType = pieces[0]; - let container = basicMimeType.split('/')[1]; + const pieces = mimeType.split(/ *; */); + const basicMimeType = pieces[0]; + const container = basicMimeType.split('/')[1]; if (container == 'mp2t') { return false; @@ -314,24 +314,24 @@ shaka.polyfill.MediaSource.patchCastIsTypeSupported_ = function() { const originalIsTypeSupported = MediaSource.isTypeSupported; // Docs from Dolby detailing profile names: https://bit.ly/2T2wKbu - let dolbyVisionRegex = /^dv(?:h[e1]|a[v1])\./; + const dolbyVisionRegex = /^dv(?:h[e1]|a[v1])\./; MediaSource.isTypeSupported = function(mimeType) { // Parse the basic MIME type from its parameters. - let pieces = mimeType.split(/ *; */); - let basicMimeType = pieces[0]; + const pieces = mimeType.split(/ *; */); + const basicMimeType = pieces[0]; // Parse the parameters into key-value pairs. /** @type {Object.<string, string>} */ - let parameters = {}; + const parameters = {}; for (let i = 1; i < pieces.length; ++i) { - let kv = pieces[i].split('='); - let k = kv[0]; - let v = kv[1].replace(/"(.*)"/, '$1'); + const kv = pieces[i].split('='); + const k = kv[0]; + const v = kv[1].replace(/"(.*)"/, '$1'); parameters[k] = v; } - let codecs = parameters['codecs']; + const codecs = parameters['codecs']; if (!codecs) { return originalIsTypeSupported(mimeType); } @@ -339,7 +339,7 @@ shaka.polyfill.MediaSource.patchCastIsTypeSupported_ = function() { let isHDR = false; let isDolbyVision = false; - let codecList = codecs.split(',').filter(function(codec) { + const codecList = codecs.split(',').filter(function(codec) { if (dolbyVisionRegex.test(codec)) { isDolbyVision = true; } @@ -368,8 +368,8 @@ shaka.polyfill.MediaSource.patchCastIsTypeSupported_ = function() { // Reconstruct the MIME type, possibly with additional parameters. let extendedMimeType = basicMimeType; - for (let k in parameters) { - let v = parameters[k]; + for (const k in parameters) { + const v = parameters[k]; extendedMimeType += '; ' + k + '="' + v + '"'; } return cast.__platform__.canDisplayType(extendedMimeType); diff --git a/lib/polyfill/patchedmediakeys_ms.js b/lib/polyfill/patchedmediakeys_ms.js index 218838a08f..433487c6cb 100644 --- a/lib/polyfill/patchedmediakeys_ms.js +++ b/lib/polyfill/patchedmediakeys_ms.js @@ -89,7 +89,7 @@ shaka.polyfill.PatchedMediaKeysMs.requestMediaKeySystemAccess = // Alias. const PatchedMediaKeysMs = shaka.polyfill.PatchedMediaKeysMs; try { - let access = new PatchedMediaKeysMs.MediaKeySystemAccess( + const access = new PatchedMediaKeysMs.MediaKeySystemAccess( keySystem, supportedConfigurations); return Promise.resolve(/** @type {!MediaKeySystemAccess} */ (access)); } catch (exception) { @@ -118,16 +118,16 @@ shaka.polyfill.PatchedMediaKeysMs.MediaKeySystemAccess = /** @private {!MediaKeySystemConfiguration} */ this.configuration_; - let allowPersistentState = false; + const allowPersistentState = false; let success = false; for (let i = 0; i < supportedConfigurations.length; ++i) { - let cfg = supportedConfigurations[i]; + const cfg = supportedConfigurations[i]; // Create a new config object and start adding in the pieces which we // find support for. We will return this from getConfiguration() if asked. /** @type {!MediaKeySystemConfiguration} */ - let newCfg = { + const newCfg = { 'audioCapabilities': [], 'videoCapabilities': [], // It is technically against spec to return these as optional, but we @@ -146,10 +146,10 @@ shaka.polyfill.PatchedMediaKeysMs.MediaKeySystemAccess = let ranAnyTests = false; if (cfg.audioCapabilities) { for (let j = 0; j < cfg.audioCapabilities.length; ++j) { - let cap = cfg.audioCapabilities[j]; + const cap = cfg.audioCapabilities[j]; if (cap.contentType) { ranAnyTests = true; - let contentType = cap.contentType.split(';')[0]; + const contentType = cap.contentType.split(';')[0]; if (MSMediaKeys.isTypeSupported(this.keySystem, contentType)) { newCfg.audioCapabilities.push(cap); success = true; @@ -159,10 +159,10 @@ shaka.polyfill.PatchedMediaKeysMs.MediaKeySystemAccess = } if (cfg.videoCapabilities) { for (let j = 0; j < cfg.videoCapabilities.length; ++j) { - let cap = cfg.videoCapabilities[j]; + const cap = cfg.videoCapabilities[j]; if (cap.contentType) { ranAnyTests = true; - let contentType = cap.contentType.split(';')[0]; + const contentType = cap.contentType.split(';')[0]; if (MSMediaKeys.isTypeSupported(this.keySystem, contentType)) { newCfg.videoCapabilities.push(cap); success = true; @@ -193,7 +193,7 @@ shaka.polyfill.PatchedMediaKeysMs.MediaKeySystemAccess = // As per the spec, this should be a DOMException, but there is not a public // constructor for this. - let unsupportedKeySystemError = new Error('Unsupported keySystem'); + const unsupportedKeySystemError = new Error('Unsupported keySystem'); unsupportedKeySystemError.name = 'NotSupportedError'; unsupportedKeySystemError.code = DOMException.NOT_SUPPORTED_ERR; throw unsupportedKeySystemError; @@ -208,7 +208,7 @@ shaka.polyfill.PatchedMediaKeysMs.MediaKeySystemAccess.prototype. // Alias const PatchedMediaKeysMs = shaka.polyfill.PatchedMediaKeysMs; - let mediaKeys = new PatchedMediaKeysMs.MediaKeys(this.keySystem); + const mediaKeys = new PatchedMediaKeysMs.MediaKeys(this.keySystem); return Promise.resolve(/** @type {!MediaKeys} */ (mediaKeys)); }; @@ -237,10 +237,10 @@ shaka.polyfill.PatchedMediaKeysMs.setMediaKeys = function(mediaKeys) { // Alias const PatchedMediaKeysMs = shaka.polyfill.PatchedMediaKeysMs; - let newMediaKeys = + const newMediaKeys = /** @type {shaka.polyfill.PatchedMediaKeysMs.MediaKeys} */ ( mediaKeys); - let oldMediaKeys = + const oldMediaKeys = /** @type {shaka.polyfill.PatchedMediaKeysMs.MediaKeys} */ ( this.mediaKeys); @@ -337,7 +337,7 @@ shaka.polyfill.PatchedMediaKeysMs.MediaKeys.prototype. /** @type {shaka.util.EventManager.ListenerType} */ (PatchedMediaKeysMs.onMsNeedKey_)); - let self = this; + const self = this; function setMediaKeysDeferred() { media.msSetMediaKeys(self.nativeMediaKeys_); media.removeEventListener('loadedmetadata', setMediaKeysDeferred); @@ -526,7 +526,8 @@ shaka.polyfill.PatchedMediaKeysMs.onMsNeedKey_ = function(event) { // NOTE: Because "this" is a real EventTarget, on IE, the event we dispatch // here must also be a real Event. - let event2 = /** @type {!CustomEvent} */(document.createEvent('CustomEvent')); + const event2 = + /** @type {!CustomEvent} */ (document.createEvent('CustomEvent')); event2.initCustomEvent('encrypted', false, false, null); event2.initDataType = 'cenc'; event2.initData = PatchedMediaKeysMs.normaliseInitData_(event.initData); @@ -549,16 +550,16 @@ shaka.polyfill.PatchedMediaKeysMs.normaliseInitData_ = function(initData) { return initData; } - let pssh = new shaka.util.Pssh(initData); + const pssh = new shaka.util.Pssh(initData); // If there is only a single pssh, return the original array. if (pssh.dataBoundaries.length <= 1) { return initData; } - let unfilteredInitDatas = []; + const unfilteredInitDatas = []; for (let i = 0; i < pssh.dataBoundaries.length; i++) { - let currPssh = initData.subarray( + const currPssh = initData.subarray( pssh.dataBoundaries[i].start, pssh.dataBoundaries[i].end + 1); // End is exclusive, hence the +1. @@ -612,9 +613,9 @@ shaka.polyfill.PatchedMediaKeysMs.MediaKeySession.prototype. this.generateRequestPromise_ = null; } - let isNew = this.keyStatuses.getStatus() == undefined; + const isNew = this.keyStatuses.getStatus() == undefined; - let event2 = new shaka.util.FakeEvent('message', { + const event2 = new shaka.util.FakeEvent('message', { messageType: isNew ? 'license-request' : 'license-renewal', message: event.message.buffer, }); @@ -668,7 +669,7 @@ shaka.polyfill.PatchedMediaKeysMs.MediaKeySession.prototype. onMsKeyError_ = function(event) { shaka.log.debug('PatchedMediaKeysMs.onMsKeyError_', event); - let error = new Error('EME PatchedMediaKeysMs key error'); + const error = new Error('EME PatchedMediaKeysMs key error'); error.errorCode = this.nativeMediaKeySession_.error; if (this.generateRequestPromise_ != null) { @@ -709,7 +710,7 @@ shaka.polyfill.PatchedMediaKeysMs.MediaKeySession.prototype. shaka.polyfill.PatchedMediaKeysMs.MediaKeySession.prototype. updateKeyStatus_ = function(status) { this.keyStatuses.setStatus(status); - let event = new shaka.util.FakeEvent('keystatuseschange'); + const event = new shaka.util.FakeEvent('keystatuseschange'); this.dispatchEvent(event); }; @@ -767,7 +768,7 @@ shaka.polyfill.PatchedMediaKeysMs.MediaKeyStatusMap.prototype. shaka.polyfill.PatchedMediaKeysMs.MediaKeyStatusMap.prototype. forEach = function(fn) { if (this.status_) { - let fakeKeyId = + const fakeKeyId = shaka.polyfill.PatchedMediaKeysMs.MediaKeyStatusMap.KEY_ID_; fn(this.status_, fakeKeyId); } @@ -787,7 +788,7 @@ shaka.polyfill.PatchedMediaKeysMs.MediaKeyStatusMap.prototype. /** @override */ shaka.polyfill.PatchedMediaKeysMs.MediaKeyStatusMap.prototype. has = function(keyId) { - let fakeKeyId = + const fakeKeyId = shaka.polyfill.PatchedMediaKeysMs.MediaKeyStatusMap.KEY_ID_; if (this.status_ && shaka.util.Uint8ArrayUtils.equal( diff --git a/lib/polyfill/patchedmediakeys_webkit.js b/lib/polyfill/patchedmediakeys_webkit.js index a4815c6ab6..b01f94aa9c 100644 --- a/lib/polyfill/patchedmediakeys_webkit.js +++ b/lib/polyfill/patchedmediakeys_webkit.js @@ -99,7 +99,7 @@ shaka.polyfill.PatchedMediaKeysWebkit.install = function() { * @private */ shaka.polyfill.PatchedMediaKeysWebkit.prefixApi_ = function(api) { - let prefix = shaka.polyfill.PatchedMediaKeysWebkit.prefix_; + const prefix = shaka.polyfill.PatchedMediaKeysWebkit.prefix_; if (prefix) { return prefix + api.charAt(0).toUpperCase() + api.slice(1); } @@ -125,7 +125,7 @@ shaka.polyfill.PatchedMediaKeysWebkit.requestMediaKeySystemAccess = // Alias. const PatchedMediaKeysWebkit = shaka.polyfill.PatchedMediaKeysWebkit; try { - let access = new PatchedMediaKeysWebkit.MediaKeySystemAccess( + const access = new PatchedMediaKeysWebkit.MediaKeySystemAccess( keySystem, supportedConfigurations); return Promise.resolve(/** @type {!MediaKeySystemAccess} */ (access)); } catch (exception) { @@ -150,10 +150,10 @@ shaka.polyfill.PatchedMediaKeysWebkit.setMediaKeys = function(mediaKeys) { // Alias. const PatchedMediaKeysWebkit = shaka.polyfill.PatchedMediaKeysWebkit; - let newMediaKeys = + const newMediaKeys = /** @type {shaka.polyfill.PatchedMediaKeysWebkit.MediaKeys} */ ( mediaKeys); - let oldMediaKeys = + const oldMediaKeys = /** @type {shaka.polyfill.PatchedMediaKeysWebkit.MediaKeys} */ ( this.mediaKeys); @@ -189,8 +189,8 @@ shaka.polyfill.PatchedMediaKeysWebkit.setMediaKeys = function(mediaKeys) { * @private */ shaka.polyfill.PatchedMediaKeysWebkit.getVideoElement_ = function() { - let videos = document.getElementsByTagName('video'); - let tmpVideo = videos.length ? videos[0] : document.createElement('video'); + const videos = document.getElementsByTagName('video'); + const tmpVideo = videos.length ? videos[0] : document.createElement('video'); return /** @type {!HTMLVideoElement} */(tmpVideo); }; @@ -229,14 +229,14 @@ shaka.polyfill.PatchedMediaKeysWebkit.MediaKeySystemAccess = } let success = false; - let tmpVideo = shaka.polyfill.PatchedMediaKeysWebkit.getVideoElement_(); + const tmpVideo = shaka.polyfill.PatchedMediaKeysWebkit.getVideoElement_(); for (let i = 0; i < supportedConfigurations.length; ++i) { - let cfg = supportedConfigurations[i]; + const cfg = supportedConfigurations[i]; // Create a new config object and start adding in the pieces which we // find support for. We will return this from getConfiguration() if asked. /** @type {!MediaKeySystemConfiguration} */ - let newCfg = { + const newCfg = { 'audioCapabilities': [], 'videoCapabilities': [], // It is technically against spec to return these as optional, but we @@ -255,13 +255,13 @@ shaka.polyfill.PatchedMediaKeysWebkit.MediaKeySystemAccess = let ranAnyTests = false; if (cfg.audioCapabilities) { for (let j = 0; j < cfg.audioCapabilities.length; ++j) { - let cap = cfg.audioCapabilities[j]; + const cap = cfg.audioCapabilities[j]; if (cap.contentType) { ranAnyTests = true; // In Chrome <= 40, if you ask about Widevine-encrypted audio support, // you get a false-negative when you specify codec information. // Work around this by stripping codec info for audio types. - let contentType = cap.contentType.split(';')[0]; + const contentType = cap.contentType.split(';')[0]; if (tmpVideo.canPlayType(contentType, this.internalKeySystem_)) { newCfg.audioCapabilities.push(cap); success = true; @@ -271,7 +271,7 @@ shaka.polyfill.PatchedMediaKeysWebkit.MediaKeySystemAccess = } if (cfg.videoCapabilities) { for (let j = 0; j < cfg.videoCapabilities.length; ++j) { - let cap = cfg.videoCapabilities[j]; + const cap = cfg.videoCapabilities[j]; if (cap.contentType) { ranAnyTests = true; if (tmpVideo.canPlayType(cap.contentType, this.internalKeySystem_)) { @@ -307,7 +307,7 @@ shaka.polyfill.PatchedMediaKeysWebkit.MediaKeySystemAccess = if (keySystem == 'org.w3.clearkey' || keySystem == 'com.widevine.alpha') { message = 'None of the requested configurations were supported.'; } - let unsupportedError = new Error(message); + const unsupportedError = new Error(message); unsupportedError.name = 'NotSupportedError'; unsupportedError.code = DOMException.NOT_SUPPORTED_ERR; throw unsupportedError; @@ -322,7 +322,8 @@ shaka.polyfill.PatchedMediaKeysWebkit.MediaKeySystemAccess.prototype. // Alias. const PatchedMediaKeysWebkit = shaka.polyfill.PatchedMediaKeysWebkit; - let mediaKeys = new PatchedMediaKeysWebkit.MediaKeys(this.internalKeySystem_); + const mediaKeys = + new PatchedMediaKeysWebkit.MediaKeys(this.internalKeySystem_); return Promise.resolve(/** @type {!MediaKeys} */ (mediaKeys)); }; @@ -380,7 +381,7 @@ shaka.polyfill.PatchedMediaKeysWebkit.MediaKeys.prototype.setMedia = // Remove any old listeners. this.eventManager_.removeAll(); - let prefix = shaka.polyfill.PatchedMediaKeysWebkit.prefix_; + const prefix = shaka.polyfill.PatchedMediaKeysWebkit.prefix_; if (media) { // Intercept and translate these prefixed EME events. this.eventManager_.listen(media, prefix + 'needkey', @@ -418,11 +419,11 @@ shaka.polyfill.PatchedMediaKeysWebkit.MediaKeys.prototype.createSession = // Unprefixed EME allows for session creation without a video tag or src. // Prefixed EME requires both a valid HTMLMediaElement and a src. - let media = this.media_ || /** @type {!HTMLMediaElement} */( + const media = this.media_ || /** @type {!HTMLMediaElement} */( document.createElement('video')); if (!media.src) media.src = 'about:blank'; - let session = new PatchedMediaKeysWebkit.MediaKeySession( + const session = new PatchedMediaKeysWebkit.MediaKeySession( media, this.keySystem_, sessionType); this.newSessions_.push(session); return session; @@ -448,7 +449,7 @@ shaka.polyfill.PatchedMediaKeysWebkit.MediaKeys.prototype.onWebkitNeedKey_ = shaka.log.debug('PatchedMediaKeysWebkit.onWebkitNeedKey_', event); goog.asserts.assert(this.media_, 'media_ not set in onWebkitNeedKey_'); - let event2 = + const event2 = /** @type {!CustomEvent} */ (document.createEvent('CustomEvent')); event2.initCustomEvent('encrypted', false, false, null); @@ -468,15 +469,15 @@ shaka.polyfill.PatchedMediaKeysWebkit.MediaKeys.prototype.onWebkitKeyMessage_ = function(event) { shaka.log.debug('PatchedMediaKeysWebkit.onWebkitKeyMessage_', event); - let session = this.findSession_(event.sessionId); + const session = this.findSession_(event.sessionId); if (!session) { shaka.log.error('Session not found', event.sessionId); return; } - let isNew = session.keyStatuses.getStatus() == undefined; + const isNew = session.keyStatuses.getStatus() == undefined; - let event2 = new shaka.util.FakeEvent('message', { + const event2 = new shaka.util.FakeEvent('message', { messageType: isNew ? 'licenserequest' : 'licenserenewal', message: event.message, }); @@ -494,7 +495,7 @@ shaka.polyfill.PatchedMediaKeysWebkit.MediaKeys.prototype.onWebkitKeyAdded_ = function(event) { shaka.log.debug('PatchedMediaKeysWebkit.onWebkitKeyAdded_', event); - let session = this.findSession_(event.sessionId); + const session = this.findSession_(event.sessionId); goog.asserts.assert(session, 'unable to find session in onWebkitKeyAdded_'); if (session) { session.ready(); @@ -510,7 +511,7 @@ shaka.polyfill.PatchedMediaKeysWebkit.MediaKeys.prototype.onWebkitKeyError_ = function(event) { shaka.log.debug('PatchedMediaKeysWebkit.onWebkitKeyError_', event); - let session = this.findSession_(event.sessionId); + const session = this.findSession_(event.sessionId); goog.asserts.assert(session, 'unable to find session in onWebkitKeyError_'); if (session) { session.handleError(event); @@ -644,7 +645,7 @@ shaka.polyfill.PatchedMediaKeysWebkit.MediaKeySession.prototype.handleError = // This does not match the DOMException we get in current WD EME, but it will // at least provide some information which can be used to look into the // problem. - let error = new Error('EME v0.1b key error'); + const error = new Error('EME v0.1b key error'); error.errorCode = event.errorCode; error.errorCode.systemCode = event.systemCode; @@ -663,8 +664,8 @@ shaka.polyfill.PatchedMediaKeysWebkit.MediaKeySession.prototype.handleError = this.updatePromise_ = null; } else { // This mapping of key statuses is imperfect at best. - let code = event.errorCode.code; - let systemCode = event.systemCode; + const code = event.errorCode.code; + const systemCode = event.systemCode; if (code == MediaKeyError['MEDIA_KEYERR_OUTPUT']) { this.updateKeyStatus_('output-restricted'); } else if (systemCode == 1) { @@ -702,8 +703,8 @@ shaka.polyfill.PatchedMediaKeysWebkit.MediaKeySession.prototype.generate_ = if (!offlineSessionId) { // Persisting the initial license. // Prefix the init data with a tag to indicate persistence. - let prefix = StringUtils.toUTF8('PERSISTENT|'); - let result = new Uint8Array(prefix.byteLength + initData.byteLength); + const prefix = StringUtils.toUTF8('PERSISTENT|'); + const result = new Uint8Array(prefix.byteLength + initData.byteLength); result.set(new Uint8Array(prefix), 0); result.set(new Uint8Array(initData), prefix.byteLength); mangledInitData = result; @@ -741,8 +742,8 @@ shaka.polyfill.PatchedMediaKeysWebkit.MediaKeySession.prototype.generate_ = // most once. This situation should only occur when init data is available // ahead of the 'needkey' event. - let prefixApi = shaka.polyfill.PatchedMediaKeysWebkit.prefixApi_; - let generateKeyRequestName = prefixApi('generateKeyRequest'); + const prefixApi = shaka.polyfill.PatchedMediaKeysWebkit.prefixApi_; + const generateKeyRequestName = prefixApi('generateKeyRequest'); try { this.media_[generateKeyRequestName](this.keySystem_, mangledInitData); } catch (exception) { @@ -801,12 +802,12 @@ shaka.polyfill.PatchedMediaKeysWebkit.MediaKeySession.prototype.update_ = // extract the key and key ID. const StringUtils = shaka.util.StringUtils; const Uint8ArrayUtils = shaka.util.Uint8ArrayUtils; - let licenseString = StringUtils.fromUTF8(response); - let jwkSet = /** @type {JWKSet} */ (JSON.parse(licenseString)); - let kty = jwkSet.keys[0].kty; + const licenseString = StringUtils.fromUTF8(response); + const jwkSet = /** @type {JWKSet} */ (JSON.parse(licenseString)); + const kty = jwkSet.keys[0].kty; if (kty != 'oct') { // Reject the promise. - let error = new Error('Response is not a valid JSON Web Key Set.'); + const error = new Error('Response is not a valid JSON Web Key Set.'); this.updatePromise_.reject(error); this.updatePromise_ = null; } @@ -818,8 +819,8 @@ shaka.polyfill.PatchedMediaKeysWebkit.MediaKeySession.prototype.update_ = keyId = null; } - let prefixApi = shaka.polyfill.PatchedMediaKeysWebkit.prefixApi_; - let addKeyName = prefixApi('addKey'); + const prefixApi = shaka.polyfill.PatchedMediaKeysWebkit.prefixApi_; + const addKeyName = prefixApi('addKey'); try { this.media_[addKeyName](this.keySystem_, key, keyId, this.sessionId); } catch (exception) { @@ -839,7 +840,7 @@ shaka.polyfill.PatchedMediaKeysWebkit.MediaKeySession.prototype.update_ = shaka.polyfill.PatchedMediaKeysWebkit.MediaKeySession.prototype. updateKeyStatus_ = function(status) { this.keyStatuses.setStatus(status); - let event = new shaka.util.FakeEvent('keystatuseschange'); + const event = new shaka.util.FakeEvent('keystatuseschange'); this.dispatchEvent(event); }; @@ -870,7 +871,7 @@ shaka.polyfill.PatchedMediaKeysWebkit.MediaKeySession.prototype.update = shaka.log.debug('PatchedMediaKeysWebkit.MediaKeySession.update', response); goog.asserts.assert(this.sessionId, 'update without session ID'); - let nextUpdatePromise = new shaka.util.PublicPromise(); + const nextUpdatePromise = new shaka.util.PublicPromise(); this.update_(nextUpdatePromise, response); return nextUpdatePromise; }; @@ -897,8 +898,8 @@ shaka.polyfill.PatchedMediaKeysWebkit.MediaKeySession.prototype.close = // it to clean up resources in v0.1b. We still consider the session closed. // We can't let the exception propagate because MediaKeySession.close() // should not throw. - let prefixApi = shaka.polyfill.PatchedMediaKeysWebkit.prefixApi_; - let cancelKeyRequestName = prefixApi('cancelKeyRequest'); + const prefixApi = shaka.polyfill.PatchedMediaKeysWebkit.prefixApi_; + const cancelKeyRequestName = prefixApi('cancelKeyRequest'); try { this.media_[cancelKeyRequestName](this.keySystem_, this.sessionId); } catch (exception) {} @@ -976,7 +977,7 @@ shaka.polyfill.PatchedMediaKeysWebkit.MediaKeyStatusMap.prototype.getStatus = shaka.polyfill.PatchedMediaKeysWebkit.MediaKeyStatusMap.prototype.forEach = function(fn) { if (this.status_) { - let fakeKeyId = + const fakeKeyId = shaka.polyfill.PatchedMediaKeysWebkit.MediaKeyStatusMap.KEY_ID_; fn(this.status_, fakeKeyId); } @@ -996,7 +997,7 @@ shaka.polyfill.PatchedMediaKeysWebkit.MediaKeyStatusMap.prototype.get = /** @override */ shaka.polyfill.PatchedMediaKeysWebkit.MediaKeyStatusMap.prototype.has = function(keyId) { - let fakeKeyId = + const fakeKeyId = shaka.polyfill.PatchedMediaKeysWebkit.MediaKeyStatusMap.KEY_ID_; if (this.status_ && shaka.util.Uint8ArrayUtils.equal( diff --git a/lib/polyfill/video_play_promise.js b/lib/polyfill/video_play_promise.js index a7e1ade278..ab0258b5d2 100644 --- a/lib/polyfill/video_play_promise.js +++ b/lib/polyfill/video_play_promise.js @@ -37,7 +37,7 @@ shaka.polyfill.VideoPlayPromise.install = function() { if (window.HTMLMediaElement) { const originalPlay = HTMLMediaElement.prototype.play; HTMLMediaElement.prototype.play = function() { - let p = originalPlay.apply(this); + const p = originalPlay.apply(this); if (p) { // This browser is returning a Promise from play(). // If the play() call fails or is interrupted, the Promise will be diff --git a/lib/polyfill/videoplaybackquality.js b/lib/polyfill/videoplaybackquality.js index 40af3d303d..cbc694c9ba 100644 --- a/lib/polyfill/videoplaybackquality.js +++ b/lib/polyfill/videoplaybackquality.js @@ -38,7 +38,7 @@ shaka.polyfill.VideoPlaybackQuality.install = function() { return; } - let proto = HTMLVideoElement.prototype; + const proto = HTMLVideoElement.prototype; if (proto.getVideoPlaybackQuality) { // No polyfill needed. return; diff --git a/lib/polyfill/vttcue.js b/lib/polyfill/vttcue.js index d5bd4fd039..11f1050a1a 100644 --- a/lib/polyfill/vttcue.js +++ b/lib/polyfill/vttcue.js @@ -42,7 +42,7 @@ shaka.polyfill.VTTCue.install = function() { return; } - let constructorLength = TextTrackCue.length; + const constructorLength = TextTrackCue.length; if (constructorLength == 3) { shaka.log.info('Using VTTCue polyfill from 3 argument TextTrackCue.'); window.VTTCue = shaka.polyfill.VTTCue.from3ArgsTextTrackCue_; @@ -85,7 +85,7 @@ shaka.polyfill.VTTCue.from3ArgsTextTrackCue_ = function(startTime, endTime, */ shaka.polyfill.VTTCue.from6ArgsTextTrackCue_ = function(startTime, endTime, text) { - let id = startTime + '-' + endTime + '-' + text; + const id = startTime + '-' + endTime + '-' + text; // Quoting the access to the TextTrackCue object to satisfy the compiler. return new window['TextTrackCue'](id, startTime, endTime, text); }; diff --git a/lib/text/mp4_vtt_parser.js b/lib/text/mp4_vtt_parser.js index d67b7f6d41..b9621fe5a1 100644 --- a/lib/text/mp4_vtt_parser.js +++ b/lib/text/mp4_vtt_parser.js @@ -120,7 +120,7 @@ shaka.text.Mp4VttParser.prototype.parseMedia = function(data, time) { /** @type {Uint8Array} */ let rawPayload; /** @type {!Array.<shaka.text.Cue>} */ - let cues = []; + const cues = []; let sawTFDT = false; let sawTRUN = false; @@ -174,17 +174,17 @@ shaka.text.Mp4VttParser.prototype.parseMedia = function(data, time) { let currentTime = baseTime; - let dataView = new DataView( + const dataView = new DataView( rawPayload.buffer, rawPayload.byteOffset, rawPayload.byteLength); /** @type {!shaka.util.DataViewReader} */ - let reader = new shaka.util.DataViewReader( + const reader = new shaka.util.DataViewReader( dataView, shaka.util.DataViewReader.Endianness.BIG_ENDIAN); presentations.forEach((presentation) => { // If one presentation corresponds to multiple payloads, it is assumed // that all of those payloads have the same start time and duration. - let duration = presentation.duration || defaultDuration; - let startTime = presentation.timeOffset ? + const duration = presentation.duration || defaultDuration; + const startTime = presentation.timeOffset ? baseTime + presentation.timeOffset : currentTime; currentTime = startTime + (duration || 0); @@ -193,12 +193,12 @@ shaka.text.Mp4VttParser.prototype.parseMedia = function(data, time) { let totalSize = 0; do { // Read the payload size. - let payloadSize = reader.readUint32(); + const payloadSize = reader.readUint32(); totalSize += payloadSize; // Skip the type. - let payloadType = reader.readUint32(); - let payloadName = shaka.util.Mp4Parser.typeToString(payloadType); + const payloadType = reader.readUint32(); + const payloadName = shaka.util.Mp4Parser.typeToString(payloadType); // Read the data payload. /** @type {Uint8Array} */ @@ -301,7 +301,7 @@ shaka.text.Mp4VttParser.parseTFHD_ = function(flags, reader) { * @private */ shaka.text.Mp4VttParser.parseTRUN_ = function(version, flags, reader) { - let sampleCount = reader.readUint32(); + const sampleCount = reader.readUint32(); // Skip "data_offset" if present. if (flags & 0x000001) { reader.skip(4); } @@ -309,11 +309,11 @@ shaka.text.Mp4VttParser.parseTRUN_ = function(version, flags, reader) { // Skip "first_sample_flags" if present. if (flags & 0x000004) { reader.skip(4); } - let samples = []; + const samples = []; for (let sampleIndex = 0; sampleIndex < sampleCount; sampleIndex++) { /** @type {shaka.text.Mp4VttParser.TimeSegment} */ - let sample = { + const sample = { duration: null, sampleSize: null, timeOffset: null, @@ -396,7 +396,7 @@ shaka.text.Mp4VttParser.assembleCue_ = function(payload, settings, startTime, endTime) { - let cue = new shaka.text.Cue( + const cue = new shaka.text.Cue( startTime, endTime, payload); @@ -406,7 +406,7 @@ shaka.text.Mp4VttParser.assembleCue_ = function(payload, } if (settings) { - let parser = new shaka.util.TextParser(settings); + const parser = new shaka.util.TextParser(settings); let word = parser.readWord(); diff --git a/lib/text/simple_text_displayer.js b/lib/text/simple_text_displayer.js index 7633c31360..fd190a6498 100644 --- a/lib/text/simple_text_displayer.js +++ b/lib/text/simple_text_displayer.js @@ -48,7 +48,7 @@ shaka.text.SimpleTextDisplayer = function(video) { // If the video element has TextTracks, disable them. If we see one that // was created by a previous instance of Shaka Player, reuse it. for (let i = 0; i < video.textTracks.length; ++i) { - let track = video.textTracks[i]; + const track = video.textTracks[i]; track.mode = 'disabled'; if (track.label == shaka.text.SimpleTextDisplayer.TextTrackLabel_) { @@ -76,7 +76,7 @@ shaka.text.SimpleTextDisplayer.prototype.remove = function(start, end) { // Check that the displayer hasn't been destroyed. if (!this.textTrack_) return false; - let removeInRange = (cue) => { + const removeInRange = (cue) => { const inside = cue.startTime < end && cue.endTime > start; return inside; }; @@ -96,9 +96,9 @@ shaka.text.SimpleTextDisplayer.prototype.append = function(cues) { shaka.text.SimpleTextDisplayer.convertToTextTrackCue_; // Convert cues. - let textTrackCues = []; + const textTrackCues = []; for (let i = 0; i < cues.length; i++) { - let cue = convertToTextTrackCue(cues[i]); + const cue = convertToTextTrackCue(cues[i]); if (cue) { textTrackCues.push(cue); } @@ -107,7 +107,7 @@ shaka.text.SimpleTextDisplayer.prototype.append = function(cues) { // Sort the cues based on start/end times. Make a copy of the array so // we can get the index in the original ordering. Out of order cues are // rejected by IE/Edge. See https://bit.ly/2K9VX3s - let sortedCues = textTrackCues.slice().sort(function(a, b) { + const sortedCues = textTrackCues.slice().sort(function(a, b) { if (a.startTime != b.startTime) { return a.startTime - b.startTime; } else if (a.endTime != b.endTime) { @@ -133,7 +133,7 @@ shaka.text.SimpleTextDisplayer.prototype.append = function(cues) { */ shaka.text.SimpleTextDisplayer.prototype.destroy = function() { if (this.textTrack_) { - let removeIt = (cue) => true; + const removeIt = (cue) => true; shaka.text.SimpleTextDisplayer.removeWhere_(this.textTrack_, removeIt); } @@ -176,7 +176,7 @@ shaka.text.SimpleTextDisplayer.convertToTextTrackCue_ = function(shakaCue) { const Cue = shaka.text.Cue; /** @type {VTTCue} */ - let vttCue = new VTTCue(shakaCue.startTime, + const vttCue = new VTTCue(shakaCue.startTime, shakaCue.endTime, shakaCue.payload); @@ -240,8 +240,8 @@ shaka.text.SimpleTextDisplayer.removeWhere_ = function(track, predicate) { // If the track is already showing, then we should keep it as showing. But if // it something else, we will use hidden so that we don't "flash" cues on the // screen. - let oldState = track.mode; - let tempState = oldState == 'showing' ? 'showing' : 'hidden'; + const oldState = track.mode; + const tempState = oldState == 'showing' ? 'showing' : 'hidden'; track.mode = tempState; @@ -252,9 +252,9 @@ shaka.text.SimpleTextDisplayer.removeWhere_ = function(track, predicate) { // Go backward so that if a removal is done, it should not cause problems // with future indexing. In the case that the underlying implementation // returns a copy (and not a shared instance) cache a copy of the tracks. - let cues = track.cues; + const cues = track.cues; for (let i = cues.length - 1; i >= 0; i--) { - let cue = cues[i]; + const cue = cues[i]; if (cue && predicate(cue)) { track.removeCue(cue); } diff --git a/lib/text/text_engine.js b/lib/text/text_engine.js index 8d3e15995a..9bc3c4eb4a 100644 --- a/lib/text/text_engine.js +++ b/lib/text/text_engine.js @@ -135,7 +135,7 @@ shaka.text.TextEngine.prototype.initParser = function(mimeType) { return; } - let Factory = shaka.text.TextEngine.parserMap_[mimeType]; + const Factory = shaka.text.TextEngine.parserMap_[mimeType]; goog.asserts.assert( Factory, 'Text type negotiation should have happened already'); @@ -154,7 +154,7 @@ shaka.text.TextEngine.prototype.getStartTime = function(buffer) { goog.asserts.assert(this.parser_, 'The parser should already be initialized'); /** @type {shaka.extern.TextParser.TimeContext} **/ - let time = { + const time = { periodStart: 0, segmentStart: null, segmentEnd: 0, @@ -162,7 +162,7 @@ shaka.text.TextEngine.prototype.getStartTime = function(buffer) { // Parse the buffer and extract the first cue start time. try { - let allCues = this.parser_.parseMedia(new Uint8Array(buffer), time); + const allCues = this.parser_.parseMedia(new Uint8Array(buffer), time); return allCues[0].startTime; } catch (exception) { // This could be a failure from the parser itself (init segment required) @@ -197,15 +197,15 @@ shaka.text.TextEngine.prototype.appendBuffer = } /** @type {shaka.extern.TextParser.TimeContext} **/ - let time = { + const time = { periodStart: this.timestampOffset_, segmentStart: startTime, segmentEnd: endTime, }; // Parse the buffer and add the new cues. - let allCues = this.parser_.parseMedia(new Uint8Array(buffer), time); - let cuesToAppend = allCues.filter(function(cue) { + const allCues = this.parser_.parseMedia(new Uint8Array(buffer), time); + const cuesToAppend = allCues.filter(function(cue) { return cue.startTime >= this.appendWindowStart_ && cue.startTime < this.appendWindowEnd_; }.bind(this)); diff --git a/lib/text/ttml_text_parser.js b/lib/text/ttml_text_parser.js index 8864f1d7b3..afdcf26a44 100644 --- a/lib/text/ttml_text_parser.js +++ b/lib/text/ttml_text_parser.js @@ -60,9 +60,9 @@ shaka.text.TtmlTextParser.prototype.parseMedia = function(data, time) { const TtmlTextParser = shaka.text.TtmlTextParser; const XmlUtils = shaka.util.XmlUtils; const ttpNs = TtmlTextParser.parameterNs_; - let str = shaka.util.StringUtils.fromUTF8(data); - let ret = []; - let parser = new DOMParser(); + const str = shaka.util.StringUtils.fromUTF8(data); + const ret = []; + const parser = new DOMParser(); let xml = null; try { @@ -83,8 +83,8 @@ shaka.text.TtmlTextParser.prototype.parseMedia = function(data, time) { let tickRate = null; let spaceStyle = null; let extent = null; - let tts = xml.getElementsByTagName('tt'); - let tt = tts[0]; + const tts = xml.getElementsByTagName('tt'); + const tt = tts[0]; // TTML should always have tt element. if (!tt) { throw new shaka.util.Error( @@ -107,31 +107,31 @@ shaka.text.TtmlTextParser.prototype.parseMedia = function(data, time) { shaka.util.Error.Category.TEXT, shaka.util.Error.Code.INVALID_XML); } - let whitespaceTrim = spaceStyle == 'default'; + const whitespaceTrim = spaceStyle == 'default'; - let rateInfo = new TtmlTextParser.RateInfo_( + const rateInfo = new TtmlTextParser.RateInfo_( frameRate, subFrameRate, frameRateMultiplier, tickRate); const metadataElements = TtmlTextParser.getLeafNodes_( tt.getElementsByTagName('metadata')[0]); - let styles = TtmlTextParser.getLeafNodes_( + const styles = TtmlTextParser.getLeafNodes_( tt.getElementsByTagName('styling')[0]); - let regionElements = TtmlTextParser.getLeafNodes_( + const regionElements = TtmlTextParser.getLeafNodes_( tt.getElementsByTagName('layout')[0]); - let cueRegions = []; + const cueRegions = []; for (let i = 0; i < regionElements.length; i++) { - let cueRegion = TtmlTextParser.parseCueRegion_( + const cueRegion = TtmlTextParser.parseCueRegion_( regionElements[i], styles, extent); if (cueRegion) { cueRegions.push(cueRegion); } } - let textNodes = TtmlTextParser.getLeafNodes_( + const textNodes = TtmlTextParser.getLeafNodes_( tt.getElementsByTagName('body')[0]); for (let i = 0; i < textNodes.length; i++) { - let cue = TtmlTextParser.parseCue_(textNodes[i], + const cue = TtmlTextParser.parseCue_(textNodes[i], time.periodStart, rateInfo, metadataElements, @@ -264,18 +264,18 @@ shaka.text.TtmlTextParser.getLeafNodes_ = function(element) { return result; } - let childNodes = element.childNodes; + const childNodes = element.childNodes; for (let i = 0; i < childNodes.length; i++) { // Currently we don't support styles applicable to span // elements, so they are ignored. - let isSpanChildOfP = childNodes[i].nodeName == 'span' && + const isSpanChildOfP = childNodes[i].nodeName == 'span' && element.nodeName == 'p'; if (childNodes[i].nodeType == Node.ELEMENT_NODE && childNodes[i].nodeName != 'br' && !isSpanChildOfP) { // Get the leaves the child might contain. goog.asserts.assert(childNodes[i] instanceof Element, 'Node should be Element!'); - let leafChildren = shaka.text.TtmlTextParser.getLeafNodes_( + const leafChildren = shaka.text.TtmlTextParser.getLeafNodes_( /** @type {Element} */(childNodes[i])); goog.asserts.assert(leafChildren.length > 0, 'Only a null Element should return no leaves!'); @@ -299,7 +299,7 @@ shaka.text.TtmlTextParser.getLeafNodes_ = function(element) { * @private */ shaka.text.TtmlTextParser.addNewLines_ = function(element, whitespaceTrim) { - let childNodes = element.childNodes; + const childNodes = element.childNodes; for (let i = 0; i < childNodes.length; i++) { if (childNodes[i].nodeName == 'br' && i > 0) { @@ -352,9 +352,9 @@ shaka.text.TtmlTextParser.parseCue_ = function( cueElement.getAttribute('begin'), rateInfo); let end = shaka.text.TtmlTextParser.parseTime_( cueElement.getAttribute('end'), rateInfo); - let duration = shaka.text.TtmlTextParser.parseTime_( + const duration = shaka.text.TtmlTextParser.parseTime_( cueElement.getAttribute('dur'), rateInfo); - let payload = cueElement.textContent; + const payload = cueElement.textContent; if (end == null && duration != null) { end = start + duration; @@ -370,14 +370,14 @@ shaka.text.TtmlTextParser.parseCue_ = function( start += offset; end += offset; - let cue = new shaka.text.Cue(start, end, payload); + const cue = new shaka.text.Cue(start, end, payload); // Get other properties if available. - let regionElement = shaka.text.TtmlTextParser.getElementFromCollection_( + const regionElement = shaka.text.TtmlTextParser.getElementFromCollection_( cueElement, 'region', regionElements, /* prefix= */ ''); if (regionElement && regionElement.getAttribute('xml:id')) { - let regionId = regionElement.getAttribute('xml:id'); - let regionsWithId = cueRegions.filter(function(region) { + const regionId = regionElement.getAttribute('xml:id'); + const regionsWithId = cueRegions.filter(function(region) { return region.id == regionId; }); cue.region = regionsWithId[0]; @@ -408,8 +408,8 @@ shaka.text.TtmlTextParser.parseCue_ = function( shaka.text.TtmlTextParser.parseCueRegion_ = function(regionElement, styles, globalExtent) { const TtmlTextParser = shaka.text.TtmlTextParser; - let region = new shaka.text.CueRegion(); - let id = regionElement.getAttribute('xml:id'); + const region = new shaka.text.CueRegion(); + const id = regionElement.getAttribute('xml:id'); if (!id) { shaka.log.warning('TtmlTextParser parser encountered a region with ' + 'no id. Region will be ignored.'); @@ -427,7 +427,7 @@ shaka.text.TtmlTextParser.parseCueRegion_ = function(regionElement, styles, let results = null; let percentage = null; - let extent = TtmlTextParser.getStyleAttributeFromRegion_( + const extent = TtmlTextParser.getStyleAttributeFromRegion_( regionElement, styles, 'extent'); if (extent) { percentage = TtmlTextParser.percentValues_.exec(extent); @@ -453,7 +453,7 @@ shaka.text.TtmlTextParser.parseCueRegion_ = function(regionElement, styles, } } - let origin = TtmlTextParser.getStyleAttributeFromRegion_( + const origin = TtmlTextParser.getStyleAttributeFromRegion_( regionElement, styles, 'origin'); if (origin) { percentage = TtmlTextParser.percentValues_.exec(origin); @@ -493,7 +493,7 @@ shaka.text.TtmlTextParser.addStyle_ = function( const TtmlTextParser = shaka.text.TtmlTextParser; const Cue = shaka.text.Cue; - let direction = TtmlTextParser.getStyleAttribute_( + const direction = TtmlTextParser.getStyleAttribute_( cueElement, region, styles, 'direction'); if (direction == 'rtl') { cue.direction = Cue.direction.HORIZONTAL_RIGHT_TO_LEFT; @@ -504,7 +504,7 @@ shaka.text.TtmlTextParser.addStyle_ = function( // plus whether text is vertical or horizontal. // They should not contradict each other. If they do, we give // preference to writing mode. - let writingMode = TtmlTextParser.getStyleAttribute_( + const writingMode = TtmlTextParser.getStyleAttribute_( cueElement, region, styles, 'writingMode'); // Set cue's direction if the text is horizontal, and cue's writingMode if // it's vertical. @@ -518,7 +518,7 @@ shaka.text.TtmlTextParser.addStyle_ = function( cue.direction = Cue.direction.HORIZONTAL_LEFT_TO_RIGHT; } - let align = TtmlTextParser.getStyleAttribute_( + const align = TtmlTextParser.getStyleAttribute_( cueElement, region, styles, 'textAlign'); if (align) { cue.positionAlign = TtmlTextParser.textAlignToPositionAlign_[align]; @@ -531,7 +531,7 @@ shaka.text.TtmlTextParser.addStyle_ = function( cue.textAlign = Cue.textAlign[align.toUpperCase()]; } - let displayAlign = TtmlTextParser.getStyleAttribute_( + const displayAlign = TtmlTextParser.getStyleAttribute_( cueElement, region, styles, 'displayAlign'); if (displayAlign) { goog.asserts.assert(displayAlign.toUpperCase() in Cue.displayAlign, @@ -540,49 +540,49 @@ shaka.text.TtmlTextParser.addStyle_ = function( cue.displayAlign = Cue.displayAlign[displayAlign.toUpperCase()]; } - let color = TtmlTextParser.getStyleAttribute_( + const color = TtmlTextParser.getStyleAttribute_( cueElement, region, styles, 'color'); if (color) { cue.color = color; } - let backgroundColor = TtmlTextParser.getStyleAttribute_( + const backgroundColor = TtmlTextParser.getStyleAttribute_( cueElement, region, styles, 'backgroundColor'); if (backgroundColor) { cue.backgroundColor = backgroundColor; } - let fontFamily = TtmlTextParser.getStyleAttribute_( + const fontFamily = TtmlTextParser.getStyleAttribute_( cueElement, region, styles, 'fontFamily'); if (fontFamily) { cue.fontFamily = fontFamily; } - let fontWeight = TtmlTextParser.getStyleAttribute_( + const fontWeight = TtmlTextParser.getStyleAttribute_( cueElement, region, styles, 'fontWeight'); if (fontWeight && fontWeight == 'bold') { cue.fontWeight = Cue.fontWeight.BOLD; } - let wrapOption = TtmlTextParser.getStyleAttribute_( + const wrapOption = TtmlTextParser.getStyleAttribute_( cueElement, region, styles, 'wrapOption'); if (wrapOption && wrapOption == 'noWrap') { cue.wrapLine = false; } - let lineHeight = TtmlTextParser.getStyleAttribute_( + const lineHeight = TtmlTextParser.getStyleAttribute_( cueElement, region, styles, 'lineHeight'); if (lineHeight && lineHeight.match(TtmlTextParser.unitValues_)) { cue.lineHeight = lineHeight; } - let fontSize = TtmlTextParser.getStyleAttribute_( + const fontSize = TtmlTextParser.getStyleAttribute_( cueElement, region, styles, 'fontSize'); if (fontSize && fontSize.match(TtmlTextParser.unitValues_)) { cue.fontSize = fontSize; } - let fontStyle = TtmlTextParser.getStyleAttribute_( + const fontStyle = TtmlTextParser.getStyleAttribute_( cueElement, region, styles, 'fontStyle'); if (fontStyle) { goog.asserts.assert(fontStyle.toUpperCase() in Cue.fontStyle, @@ -606,13 +606,13 @@ shaka.text.TtmlTextParser.addStyle_ = function( // element's style or be inherited from elements' parent nodes. All of those // values should be applied as long as they don't contradict each other. If // they do, elements' own style gets preference. - let textDecorationRegion = TtmlTextParser.getStyleAttributeFromRegion_( + const textDecorationRegion = TtmlTextParser.getStyleAttributeFromRegion_( region, styles, 'textDecoration'); if (textDecorationRegion) { TtmlTextParser.addTextDecoration_(cue, textDecorationRegion); } - let textDecorationElement = TtmlTextParser.getStyleAttributeFromElement_( + const textDecorationElement = TtmlTextParser.getStyleAttributeFromElement_( cueElement, styles, 'textDecoration'); if (textDecorationElement) { TtmlTextParser.addTextDecoration_(cue, textDecorationElement); @@ -629,7 +629,7 @@ shaka.text.TtmlTextParser.addStyle_ = function( */ shaka.text.TtmlTextParser.addTextDecoration_ = function(cue, decoration) { const Cue = shaka.text.Cue; - let values = decoration.split(' '); + const values = decoration.split(' '); for (let i = 0; i < values.length; i++) { switch (values[i]) { case 'underline': @@ -686,7 +686,7 @@ shaka.text.TtmlTextParser.getStyleAttribute_ = function( // An attribute can be specified on region level or in a styling block // associated with the region or original element. const TtmlTextParser = shaka.text.TtmlTextParser; - let attr = TtmlTextParser.getStyleAttributeFromElement_( + const attr = TtmlTextParser.getStyleAttributeFromElement_( cueElement, styles, attribute); if (attr) { return attr; @@ -712,15 +712,15 @@ shaka.text.TtmlTextParser.getStyleAttributeFromRegion_ = function( const XmlUtils = shaka.util.XmlUtils; const ttsNs = shaka.text.TtmlTextParser.styleNs_; - let regionChildren = shaka.text.TtmlTextParser.getLeafNodes_(region); + const regionChildren = shaka.text.TtmlTextParser.getLeafNodes_(region); for (let i = 0; i < regionChildren.length; i++) { - let attr = XmlUtils.getAttributeNS(regionChildren[i], ttsNs, attribute); + const attr = XmlUtils.getAttributeNS(regionChildren[i], ttsNs, attribute); if (attr) { return attr; } } - let style = shaka.text.TtmlTextParser.getElementFromCollection_( + const style = shaka.text.TtmlTextParser.getElementFromCollection_( region, 'style', styles, /* prefix= */ ''); if (style) { return XmlUtils.getAttributeNS(style, ttsNs, attribute); @@ -744,9 +744,9 @@ shaka.text.TtmlTextParser.getStyleAttributeFromElement_ = function( const XmlUtils = shaka.util.XmlUtils; const ttsNs = shaka.text.TtmlTextParser.styleNs_; - let getElementFromCollection_ = + const getElementFromCollection_ = shaka.text.TtmlTextParser.getElementFromCollection_; - let style = getElementFromCollection_( + const style = getElementFromCollection_( cueElement, 'style', styles, /* prefix= */ ''); if (style) { return XmlUtils.getAttributeNS(style, ttsNs, attribute); @@ -772,7 +772,7 @@ shaka.text.TtmlTextParser.getElementFromCollection_ = function( return null; } let item = null; - let itemName = shaka.text.TtmlTextParser.getInheritedAttribute_( + const itemName = shaka.text.TtmlTextParser.getInheritedAttribute_( element, attributeName); if (itemName) { for (let i = 0; i < collection.length; i++) { @@ -806,7 +806,7 @@ shaka.text.TtmlTextParser.getInheritedAttribute_ = function( // Element.parentNode can lead to XMLDocument, which is not an Element and // has no getAttribute(). - let parentNode = element.parentNode; + const parentNode = element.parentNode; if (parentNode instanceof Element) { element = parentNode; } else { @@ -860,8 +860,8 @@ shaka.text.TtmlTextParser.parseTime_ = function(text, rateInfo) { */ shaka.text.TtmlTextParser.parseFramesTime_ = function(rateInfo, text) { // 75f or 75.5f - let results = shaka.text.TtmlTextParser.timeFramesFormat_.exec(text); - let frames = Number(results[1]); + const results = shaka.text.TtmlTextParser.timeFramesFormat_.exec(text); + const frames = Number(results[1]); return frames / rateInfo.frameRate; }; @@ -877,8 +877,8 @@ shaka.text.TtmlTextParser.parseFramesTime_ = function(rateInfo, text) { */ shaka.text.TtmlTextParser.parseTickTime_ = function(rateInfo, text) { // 50t or 50.5t - let results = shaka.text.TtmlTextParser.timeTickFormat_.exec(text); - let ticks = Number(results[1]); + const results = shaka.text.TtmlTextParser.timeTickFormat_.exec(text); + const ticks = Number(results[1]); return ticks / rateInfo.tickRate; }; @@ -895,13 +895,13 @@ shaka.text.TtmlTextParser.parseTickTime_ = function(rateInfo, text) { shaka.text.TtmlTextParser.parseColonTimeWithFrames_ = function( rateInfo, text) { // 01:02:43:07 ('07' is frames) or 01:02:43:07.1 (subframes) - let results = shaka.text.TtmlTextParser.timeColonFormatFrames_.exec(text); + const results = shaka.text.TtmlTextParser.timeColonFormatFrames_.exec(text); - let hours = Number(results[1]); - let minutes = Number(results[2]); + const hours = Number(results[1]); + const minutes = Number(results[2]); let seconds = Number(results[3]); let frames = Number(results[4]); - let subframes = Number(results[5]) || 0; + const subframes = Number(results[5]) || 0; frames += subframes / rateInfo.subFrameRate; seconds += frames / rateInfo.frameRate; @@ -920,16 +920,16 @@ shaka.text.TtmlTextParser.parseColonTimeWithFrames_ = function( * @private */ shaka.text.TtmlTextParser.parseTimeFromRegex_ = function(regex, text) { - let results = regex.exec(text); + const results = regex.exec(text); if (results == null || results[0] == '') { return null; } // This capture is optional, but will still be in the array as undefined, // in which case it is 0. - let hours = Number(results[1]) || 0; - let minutes = Number(results[2]) || 0; - let seconds = Number(results[3]) || 0; - let miliseconds = Number(results[4]) || 0; + const hours = Number(results[1]) || 0; + const minutes = Number(results[2]) || 0; + const seconds = Number(results[3]) || 0; + const miliseconds = Number(results[4]) || 0; return (miliseconds / 1000) + seconds + (minutes * 60) + (hours * 3600); }; diff --git a/lib/text/vtt_text_parser.js b/lib/text/vtt_text_parser.js index 3fb65c1a84..96eaba48ea 100644 --- a/lib/text/vtt_text_parser.js +++ b/lib/text/vtt_text_parser.js @@ -49,7 +49,7 @@ shaka.text.VttTextParser.prototype.parseMedia = function(data, time) { // Get the input as a string. Normalize newlines to \n. let str = shaka.util.StringUtils.fromUTF8(data); str = str.replace(/\r\n|\r(?=[^\n]|$)/gm, '\n'); - let blocks = str.split(/\n{2,}/m); + const blocks = str.split(/\n{2,}/m); if (!/^WEBVTT($|[ \t\n])/m.test(blocks[0])) { throw new shaka.util.Error( @@ -103,20 +103,20 @@ shaka.text.VttTextParser.prototype.parseMedia = function(data, time) { // Parse VTT regions. /* !Array.<!shaka.extern.CueRegion> */ - let regions = []; + const regions = []; let lines = blocks[0].split('\n'); for (let i = 1; i < lines.length; i++) { if (/^Region:/.test(lines[i])) { - let region = VttTextParser.parseRegion_(lines[i]); + const region = VttTextParser.parseRegion_(lines[i]); regions.push(region); } } // Parse cues. - let ret = []; + const ret = []; for (let i = 1; i < blocks.length; i++) { lines = blocks[i].split('\n'); - let cue = VttTextParser.parseCue_(lines, offset, regions); + const cue = VttTextParser.parseCue_(lines, offset, regions); if (cue) { ret.push(cue); } @@ -135,11 +135,11 @@ shaka.text.VttTextParser.prototype.parseMedia = function(data, time) { */ shaka.text.VttTextParser.parseRegion_ = function(text) { const VttTextParser = shaka.text.VttTextParser; - let parser = new shaka.util.TextParser(text); + const parser = new shaka.util.TextParser(text); // The region string looks like this: // Region: id=fred width=50% lines=3 regionanchor=0%,100% // viewportanchor=10%,90% scroll=up - let region = new shaka.text.CueRegion(); + const region = new shaka.text.CueRegion(); // Skip 'Region:' parser.readWord(); @@ -194,9 +194,9 @@ shaka.text.VttTextParser.parseCue_ = function(text, timeOffset, regions) { } // Parse the times. - let parser = new shaka.util.TextParser(text[0]); + const parser = new shaka.util.TextParser(text[0]); let start = VttTextParser.parseTime_(parser); - let expect = parser.readRegex(/[ \t]+-->[ \t]+/g); + const expect = parser.readRegex(/[ \t]+-->[ \t]+/g); let end = VttTextParser.parseTime_(parser); if (start == null || expect == null || end == null) { @@ -210,9 +210,9 @@ shaka.text.VttTextParser.parseCue_ = function(text, timeOffset, regions) { end += timeOffset; // Get the payload. - let payload = text.slice(1).join('\n').trim(); + const payload = text.slice(1).join('\n').trim(); - let cue = new shaka.text.Cue(start, end, payload); + const cue = new shaka.text.Cue(start, end, payload); // Parse optional settings. parser.skipWhitespace(); @@ -259,7 +259,7 @@ shaka.text.VttTextParser.parseCueSetting = function(cue, word, regions) { VttTextParser.setPositionAlign_(cue, results[2]); } } else if ((results = /^region:(.*)$/.exec(word))) { - let region = VttTextParser.getRegionById_(regions, results[1]); + const region = VttTextParser.getRegionById_(regions, results[1]); if (region) { cue.region = region; } @@ -279,7 +279,7 @@ shaka.text.VttTextParser.parseCueSetting = function(cue, word, regions) { * @private */ shaka.text.VttTextParser.getRegionById_ = function(regions, id) { - let regionsWithId = regions.filter(function(region) { + const regionsWithId = regions.filter(function(region) { return region.id == id; }); if (!regionsWithId.length) { @@ -426,16 +426,16 @@ shaka.text.VttTextParser.parsedLineValueAndInterpretation_ = */ shaka.text.VttTextParser.parseTime_ = function(parser) { // 00:00.000 or 00:00:00.000 or 0:00:00.000 - let results = parser.readRegex(/(?:(\d{1,}):)?(\d{2}):(\d{2})\.(\d{3})/g); + const results = parser.readRegex(/(?:(\d{1,}):)?(\d{2}):(\d{2})\.(\d{3})/g); if (results == null) { return null; } // This capture is optional, but will still be in the array as undefined, // in which case it is 0. - let hours = Number(results[1]) || 0; - let minutes = Number(results[2]); - let seconds = Number(results[3]); - let miliseconds = Number(results[4]); + const hours = Number(results[1]) || 0; + const minutes = Number(results[2]); + const seconds = Number(results[3]); + const miliseconds = Number(results[4]); if (minutes > 59 || seconds > 59) { return null; } diff --git a/lib/util/abortable_operation.js b/lib/util/abortable_operation.js index a1899c3aa8..e1d24000f5 100644 --- a/lib/util/abortable_operation.js +++ b/lib/util/abortable_operation.js @@ -161,7 +161,7 @@ shaka.util.AbortableOperation = class { * @export */ chain(onSuccess, onError) { - let newPromise = new shaka.util.PublicPromise(); + const newPromise = new shaka.util.PublicPromise(); // If called before "this" completes, just abort "this". let abort = () => { @@ -231,7 +231,7 @@ shaka.util.AbortableOperation = class { */ static wrapChainCallback_(callback, value, newPromise) { try { - let ret = callback(value); + const ret = callback(value); if (ret && ret.promise && ret.abort) { // This is an abortable operation, with its own abort() method. diff --git a/lib/util/array_utils.js b/lib/util/array_utils.js index 6d72463baa..3adbb1a62f 100644 --- a/lib/util/array_utils.js +++ b/lib/util/array_utils.js @@ -48,7 +48,7 @@ shaka.util.ArrayUtils.defaultEquals = function(a, b) { * @template T */ shaka.util.ArrayUtils.remove = function(array, element) { - let index = array.indexOf(element); + const index = array.indexOf(element); if (index > -1) { array.splice(index, 1); } @@ -90,7 +90,7 @@ shaka.util.ArrayUtils.hasSameElements = function(a, b, compareFn) { return false; } - let copy = b.slice(); + const copy = b.slice(); for (const item of a) { const idx = copy.findIndex((other) => compareFn(item, other)); if (idx == -1) { diff --git a/lib/util/config_utils.js b/lib/util/config_utils.js index edede9d2eb..7e704df75c 100644 --- a/lib/util/config_utils.js +++ b/lib/util/config_utils.js @@ -41,13 +41,13 @@ shaka.util.ConfigUtils.mergeConfigObjects = * @type {boolean} * If true, don't validate the keys in the next level. */ - let ignoreKeys = path in overrides; + const ignoreKeys = path in overrides; let isValid = true; - for (let k in source) { - let subPath = path + '.' + k; - let subTemplate = ignoreKeys ? overrides[path] : template[k]; + for (const k in source) { + const subPath = path + '.' + k; + const subTemplate = ignoreKeys ? overrides[path] : template[k]; // The order of these checks is important. if (!ignoreKeys && !(k in template)) { @@ -75,7 +75,7 @@ shaka.util.ConfigUtils.mergeConfigObjects = destination[k] = shaka.util.ObjectUtils.cloneObject(subTemplate); } - let subMergeValid = shaka.util.ConfigUtils.mergeConfigObjects( + const subMergeValid = shaka.util.ConfigUtils.mergeConfigObjects( destination[k], source[k], subTemplate, overrides, subPath); isValid = isValid && subMergeValid; } else if (typeof source[k] != typeof subTemplate || diff --git a/lib/util/data_view_reader.js b/lib/util/data_view_reader.js index ba2fbbd53f..75470f8c60 100644 --- a/lib/util/data_view_reader.js +++ b/lib/util/data_view_reader.js @@ -93,7 +93,7 @@ shaka.util.DataViewReader.prototype.getLength = function() { */ shaka.util.DataViewReader.prototype.readUint8 = function() { try { - let value = this.dataView_.getUint8(this.position_); + const value = this.dataView_.getUint8(this.position_); this.position_ += 1; return value; } catch (exception) { @@ -110,7 +110,7 @@ shaka.util.DataViewReader.prototype.readUint8 = function() { */ shaka.util.DataViewReader.prototype.readUint16 = function() { try { - let value = this.dataView_.getUint16(this.position_, this.littleEndian_); + const value = this.dataView_.getUint16(this.position_, this.littleEndian_); this.position_ += 2; return value; } catch (exception) { @@ -127,7 +127,7 @@ shaka.util.DataViewReader.prototype.readUint16 = function() { */ shaka.util.DataViewReader.prototype.readUint32 = function() { try { - let value = this.dataView_.getUint32(this.position_, this.littleEndian_); + const value = this.dataView_.getUint32(this.position_, this.littleEndian_); this.position_ += 4; return value; } catch (exception) { @@ -144,7 +144,7 @@ shaka.util.DataViewReader.prototype.readUint32 = function() { */ shaka.util.DataViewReader.prototype.readInt32 = function() { try { - let value = this.dataView_.getInt32(this.position_, this.littleEndian_); + const value = this.dataView_.getInt32(this.position_, this.littleEndian_); this.position_ += 4; return value; } catch (exception) { @@ -206,7 +206,7 @@ shaka.util.DataViewReader.prototype.readBytes = function(bytes) { this.throwOutOfBounds_(); } - let value = new Uint8Array( + const value = new Uint8Array( this.dataView_.buffer, this.dataView_.byteOffset + this.position_, bytes); this.position_ += bytes; return new Uint8Array(value); @@ -266,14 +266,14 @@ shaka.util.DataViewReader.prototype.seek = function(position) { * @export */ shaka.util.DataViewReader.prototype.readTerminatedString = function() { - let start = this.position_; + const start = this.position_; while (this.hasMoreData()) { - let value = this.dataView_.getUint8(this.position_); + const value = this.dataView_.getUint8(this.position_); if (value == 0) break; this.position_ += 1; } - let ret = new Uint8Array( + const ret = new Uint8Array( this.dataView_.buffer, this.dataView_.byteOffset + start, this.position_ - start); // Skip string termination. diff --git a/lib/util/ebml_parser.js b/lib/util/ebml_parser.js index 0f2592fcfb..36e8749587 100644 --- a/lib/util/ebml_parser.js +++ b/lib/util/ebml_parser.js @@ -75,10 +75,10 @@ shaka.util.EbmlParser.prototype.hasMoreData = function() { * @see http://matroska.org/technical/specs/rfc/index.html */ shaka.util.EbmlParser.prototype.parseElement = function() { - let id = this.parseId_(); + const id = this.parseId_(); // Parse the element's size. - let vint = this.parseVint_(); + const vint = this.parseVint_(); let size; if (shaka.util.EbmlParser.isDynamicSizeValue_(vint)) { // If this has an unknown size, assume that it takes up the rest of the @@ -92,12 +92,12 @@ shaka.util.EbmlParser.prototype.parseElement = function() { // parsing a "partial element". This may occur if for example we are // parsing the beginning of some WebM container data, but our buffer does // not contain the entire WebM container data. - let elementSize = + const elementSize = this.reader_.getPosition() + size <= this.dataView_.byteLength ? size : this.dataView_.byteLength - this.reader_.getPosition(); - let dataView = new DataView( + const dataView = new DataView( this.dataView_.buffer, this.dataView_.byteOffset + this.reader_.getPosition(), elementSize); @@ -115,7 +115,7 @@ shaka.util.EbmlParser.prototype.parseElement = function() { * @private */ shaka.util.EbmlParser.prototype.parseId_ = function() { - let vint = this.parseVint_(); + const vint = this.parseVint_(); if (vint.length > 7) { throw new shaka.util.Error( @@ -146,12 +146,12 @@ shaka.util.EbmlParser.prototype.parseId_ = function() { * @private */ shaka.util.EbmlParser.prototype.parseVint_ = function() { - let firstByte = this.reader_.readUint8(); + const firstByte = this.reader_.readUint8(); let numBytes; // Determine the byte width of the variable sized integer. for (numBytes = 1; numBytes <= 8; numBytes++) { - let mask = 0x1 << (8 - numBytes); + const mask = 0x1 << (8 - numBytes); if (firstByte & mask) { break; } @@ -164,7 +164,7 @@ shaka.util.EbmlParser.prototype.parseVint_ = function() { shaka.util.Error.Code.EBML_OVERFLOW); } - let vint = new Uint8Array(numBytes); + const vint = new Uint8Array(numBytes); vint[0] = firstByte; // Include the remaining bytes. @@ -203,7 +203,7 @@ shaka.util.EbmlParser.getVintValue_ = function(vint) { // Mask out the first few bits of |vint|'s first byte to get the most // significant bits of |vint|'s value. If |vint| is 8 bytes wide then |value| // will be set to 0. - let mask = 0x1 << (8 - vint.length); + const mask = 0x1 << (8 - vint.length); let value = vint[0] & (mask - 1); // Add the remaining bytes. @@ -225,7 +225,7 @@ shaka.util.EbmlParser.getVintValue_ = function(vint) { */ shaka.util.EbmlParser.isDynamicSizeValue_ = function(vint) { const EbmlParser = shaka.util.EbmlParser; - let uint8ArrayEqual = shaka.util.Uint8ArrayUtils.equal; + const uint8ArrayEqual = shaka.util.Uint8ArrayUtils.equal; for (let i = 0; i < EbmlParser.DYNAMIC_SIZES.length; i++) { if (uint8ArrayEqual(vint, EbmlParser.DYNAMIC_SIZES[i])) { @@ -295,7 +295,7 @@ shaka.util.EbmlElement.prototype.getUint = function() { let value = 0; for (let i = 0; i < this.dataView_.byteLength; i++) { - let chunk = this.dataView_.getUint8(i); + const chunk = this.dataView_.getUint8(i); value = (256 * value) + chunk; } diff --git a/lib/util/error.js b/lib/util/error.js index 0fcdbe181b..6dd3566ec2 100644 --- a/lib/util/error.js +++ b/lib/util/error.js @@ -64,12 +64,12 @@ shaka.util.Error = function(severity, category, code, ...varArgs) { let categoryName = 'UNKNOWN'; let codeName = 'UNKNOWN'; - for (let k in shaka.util.Error.Category) { + for (const k in shaka.util.Error.Category) { if (shaka.util.Error.Category[k] == this.category) { categoryName = k; } } - for (let k in shaka.util.Error.Code) { + for (const k in shaka.util.Error.Code) { if (shaka.util.Error.Code[k] == this.code) { codeName = k; } diff --git a/lib/util/event_manager.js b/lib/util/event_manager.js index 52babb3c60..92c62179e2 100644 --- a/lib/util/event_manager.js +++ b/lib/util/event_manager.js @@ -64,7 +64,7 @@ shaka.util.EventManager.prototype.release = function() { shaka.util.EventManager.prototype.listen = function(target, type, listener) { if (!this.bindingMap_) return; - let binding = new shaka.util.EventManager.Binding_(target, type, listener); + const binding = new shaka.util.EventManager.Binding_(target, type, listener); this.bindingMap_.push(type, binding); }; @@ -98,10 +98,10 @@ shaka.util.EventManager.prototype.listenOnce = shaka.util.EventManager.prototype.unlisten = function(target, type, listener) { if (!this.bindingMap_) return; - let list = this.bindingMap_.get(type) || []; + const list = this.bindingMap_.get(type) || []; for (let i = 0; i < list.length; ++i) { - let binding = list[i]; + const binding = list[i]; if (binding.target == target) { if (listener == binding.listener || !listener) { @@ -119,7 +119,7 @@ shaka.util.EventManager.prototype.unlisten = function(target, type, listener) { shaka.util.EventManager.prototype.removeAll = function() { if (!this.bindingMap_) return; - let list = this.bindingMap_.getAll(); + const list = this.bindingMap_.getAll(); for (let i = 0; i < list.length; ++i) { list[i].unlisten(); diff --git a/lib/util/fake_event.js b/lib/util/fake_event.js index c48949ff8f..07111e6b7a 100644 --- a/lib/util/fake_event.js +++ b/lib/util/fake_event.js @@ -29,7 +29,7 @@ goog.provide('shaka.util.FakeEvent'); */ shaka.util.FakeEvent = function(type, dict = {}) { // Take properties from dict if present. - for (let key in dict) { + for (const key in dict) { this[key] = dict[key]; } diff --git a/lib/util/fake_event_target.js b/lib/util/fake_event_target.js index 04ae35b9ae..37370595db 100644 --- a/lib/util/fake_event_target.js +++ b/lib/util/fake_event_target.js @@ -110,7 +110,7 @@ shaka.util.FakeEventTarget.prototype.dispatchEvent = function(event) { event.target = this.dispatchTarget; event.currentTarget = this.dispatchTarget; - let listener = listeners[i]; + const listener = listeners[i]; try { // Check for the |handleEvent| member to test if this is a // |EventListener| instance or a basic function. diff --git a/lib/util/manifest_parser_utils.js b/lib/util/manifest_parser_utils.js index e8359fe7db..bc9ad3e84b 100644 --- a/lib/util/manifest_parser_utils.js +++ b/lib/util/manifest_parser_utils.js @@ -41,7 +41,7 @@ shaka.util.ManifestParserUtils.resolveUris = function(baseUris, relativeUris) { return baseUris; } - let relativeAsGoog = + const relativeAsGoog = relativeUris.map(function(uri) { return new goog.Uri(uri); }); // Resolve each URI relative to each base URI, creating an Array of Arrays. // Then flatten the Arrays into a single Array. diff --git a/lib/util/mp4_parser.js b/lib/util/mp4_parser.js index 5219c61bd3..d58e198d9f 100644 --- a/lib/util/mp4_parser.js +++ b/lib/util/mp4_parser.js @@ -69,7 +69,7 @@ shaka.util.Mp4Parser.BoxType_ = { * @export */ shaka.util.Mp4Parser.prototype.box = function(type, definition) { - let typeCode = shaka.util.Mp4Parser.typeFromString_(type); + const typeCode = shaka.util.Mp4Parser.typeFromString_(type); this.headers_[typeCode] = shaka.util.Mp4Parser.BoxType_.BASIC_BOX; this.boxDefinitions_[typeCode] = definition; return this; @@ -85,7 +85,7 @@ shaka.util.Mp4Parser.prototype.box = function(type, definition) { * @export */ shaka.util.Mp4Parser.prototype.fullBox = function(type, definition) { - let typeCode = shaka.util.Mp4Parser.typeFromString_(type); + const typeCode = shaka.util.Mp4Parser.typeFromString_(type); this.headers_[typeCode] = shaka.util.Mp4Parser.BoxType_.FULL_BOX; this.boxDefinitions_[typeCode] = definition; return this; @@ -113,8 +113,8 @@ shaka.util.Mp4Parser.prototype.stop = function() { * @export */ shaka.util.Mp4Parser.prototype.parse = function(data, partialOkay) { - let wrapped = new Uint8Array(data); - let reader = new shaka.util.DataViewReader( + const wrapped = new Uint8Array(data); + const reader = new shaka.util.DataViewReader( new DataView(wrapped.buffer, wrapped.byteOffset, wrapped.byteLength), shaka.util.DataViewReader.Endianness.BIG_ENDIAN); @@ -138,11 +138,11 @@ shaka.util.Mp4Parser.prototype.parse = function(data, partialOkay) { */ shaka.util.Mp4Parser.prototype.parseNext = function(absStart, reader, partialOkay) { - let start = reader.getPosition(); + const start = reader.getPosition(); let size = reader.readUint32(); - let type = reader.readUint32(); - let name = shaka.util.Mp4Parser.typeToString(type); + const type = reader.readUint32(); + const name = shaka.util.Mp4Parser.typeToString(type); shaka.log.v2('Parsing MP4 box', name); switch (size) { @@ -154,14 +154,14 @@ shaka.util.Mp4Parser.prototype.parseNext = break; } - let boxDefinition = this.boxDefinitions_[type]; + const boxDefinition = this.boxDefinitions_[type]; if (boxDefinition) { let version = null; let flags = null; if (this.headers_[type] == shaka.util.Mp4Parser.BoxType_.FULL_BOX) { - let versionAndFlags = reader.readUint32(); + const versionAndFlags = reader.readUint32(); version = versionAndFlags >>> 24; flags = versionAndFlags & 0xFFFFFF; } @@ -173,16 +173,16 @@ shaka.util.Mp4Parser.prototype.parseNext = // For partial reads, truncate the payload if we must. end = reader.getLength(); } - let payloadSize = end - reader.getPosition(); - let payload = + const payloadSize = end - reader.getPosition(); + const payload = (payloadSize > 0) ? reader.readBytes(payloadSize) : new Uint8Array(0); - let payloadReader = new shaka.util.DataViewReader( + const payloadReader = new shaka.util.DataViewReader( new DataView(payload.buffer, payload.byteOffset, payload.byteLength), shaka.util.DataViewReader.Endianness.BIG_ENDIAN); /** @type {shaka.extern.ParsedBox} */ - let box = { + const box = { parser: this, partialOkay: partialOkay || false, version: version, @@ -248,7 +248,7 @@ shaka.util.Mp4Parser.sampleDescription = function(box) { */ shaka.util.Mp4Parser.allData = function(callback) { return function(box) { - let all = box.reader.getLength() - box.reader.getPosition(); + const all = box.reader.getLength() - box.reader.getPosition(); callback(box.reader.readBytes(all)); }; }; @@ -284,7 +284,7 @@ shaka.util.Mp4Parser.typeFromString_ = function(name) { * @export */ shaka.util.Mp4Parser.typeToString = function(type) { - let name = String.fromCharCode( + const name = String.fromCharCode( (type >> 24) & 0xff, (type >> 16) & 0xff, (type >> 8) & 0xff, diff --git a/lib/util/multi_map.js b/lib/util/multi_map.js index e74568a9bb..4be21dc68d 100644 --- a/lib/util/multi_map.js +++ b/lib/util/multi_map.js @@ -50,7 +50,7 @@ shaka.util.MultiMap.prototype.push = function(key, value) { * @return {Array.<T>} or null if no such key exists. */ shaka.util.MultiMap.prototype.get = function(key) { - let list = this.map_[key]; + const list = this.map_[key]; // slice() clones the list so that it and the map can each be modified // without affecting the other. return list ? list.slice() : null; @@ -62,8 +62,8 @@ shaka.util.MultiMap.prototype.get = function(key) { * @return {!Array.<T>} */ shaka.util.MultiMap.prototype.getAll = function() { - let list = []; - for (let key in this.map_) { + const list = []; + for (const key in this.map_) { list.push.apply(list, this.map_[key]); } return list; @@ -76,7 +76,7 @@ shaka.util.MultiMap.prototype.getAll = function() { * @param {T} value */ shaka.util.MultiMap.prototype.remove = function(key, value) { - let list = this.map_[key]; + const list = this.map_[key]; if (!list) return; for (let i = 0; i < list.length; ++i) { if (list[i] == value) { @@ -99,7 +99,7 @@ shaka.util.MultiMap.prototype.clear = function() { * @param {function(string, !Array.<T>)} callback */ shaka.util.MultiMap.prototype.forEach = function(callback) { - for (let key in this.map_) { + for (const key in this.map_) { callback(key, this.map_[key]); } }; diff --git a/lib/util/object_utils.js b/lib/util/object_utils.js index 2944d60adb..957d27c6e2 100644 --- a/lib/util/object_utils.js +++ b/lib/util/object_utils.js @@ -30,10 +30,10 @@ shaka.util.ObjectUtils = class { * @return {T} */ static cloneObject(arg) { - let seenObjects = new Set(); + const seenObjects = new Set(); // This recursively clones the value |val|, using the captured variable // |seenObjects| to track the objects we have already cloned. - let clone = function(val) { + const clone = function(val) { switch (typeof val) { case 'undefined': case 'boolean': @@ -65,9 +65,9 @@ shaka.util.ObjectUtils = class { } seenObjects.add(val); - let ret = isArray ? [] : {}; + const ret = isArray ? [] : {}; // Note |name| will equal a number for arrays. - for (let name in val) { + for (const name in val) { ret[name] = clone(val[name]); } diff --git a/lib/util/operation_manager.js b/lib/util/operation_manager.js index 96f541f886..a1d61a2728 100644 --- a/lib/util/operation_manager.js +++ b/lib/util/operation_manager.js @@ -46,7 +46,7 @@ shaka.util.OperationManager = class { /** @override */ destroy() { - let cleanup = []; + const cleanup = []; this.operations_.forEach((op) => { // Catch and ignore any failures. This silences error logs in the // JavaScript console about uncaught Promise failures. diff --git a/lib/util/pssh.js b/lib/util/pssh.js index b05da20b94..2da708564c 100644 --- a/lib/util/pssh.js +++ b/lib/util/pssh.js @@ -78,17 +78,17 @@ shaka.util.Pssh.prototype.parseBox_ = function(box) { return; } - let systemId = shaka.util.Uint8ArrayUtils.toHex(box.reader.readBytes(16)); - let keyIds = []; + const systemId = shaka.util.Uint8ArrayUtils.toHex(box.reader.readBytes(16)); + const keyIds = []; if (box.version > 0) { - let numKeyIds = box.reader.readUint32(); + const numKeyIds = box.reader.readUint32(); for (let i = 0; i < numKeyIds; ++i) { - let keyId = shaka.util.Uint8ArrayUtils.toHex(box.reader.readBytes(16)); + const keyId = shaka.util.Uint8ArrayUtils.toHex(box.reader.readBytes(16)); keyIds.push(keyId); } } - let dataSize = box.reader.readUint32(); + const dataSize = box.reader.readUint32(); box.reader.skip(dataSize); // Ignore the data section. // Now that everything has been succesfully parsed from this box, diff --git a/lib/util/stream_utils.js b/lib/util/stream_utils.js index e3338d5ee3..88e916f151 100644 --- a/lib/util/stream_utils.js +++ b/lib/util/stream_utils.js @@ -96,7 +96,7 @@ shaka.util.StreamUtils.applyRestrictions = let tracksChanged = false; variants.forEach((variant) => { - let originalAllowed = variant.allowedByApplication; + const originalAllowed = variant.allowedByApplication; variant.allowedByApplication = shaka.util.StreamUtils.meetsRestrictions( variant, restrictions, maxHwRes); @@ -183,9 +183,9 @@ shaka.util.StreamUtils.filterNewPeriod = function( // Filter text streams. period.textStreams = period.textStreams.filter(function(stream) { - let fullMimeType = shaka.util.MimeUtils.getFullType( + const fullMimeType = shaka.util.MimeUtils.getFullType( stream.mimeType, stream.codecs); - let keep = shaka.text.TextEngine.isTypeSupported(fullMimeType); + const keep = shaka.text.TextEngine.isTypeSupported(fullMimeType); if (!keep) { shaka.log.debug('Dropping text stream. Is not supported by the ' + @@ -227,33 +227,33 @@ shaka.util.StreamUtils.areStreamsCompatible_ = function(s0, s1) { */ shaka.util.StreamUtils.variantToTrack = function(variant) { /** @type {?shaka.extern.Stream} */ - let audio = variant.audio; + const audio = variant.audio; /** @type {?shaka.extern.Stream} */ - let video = variant.video; + const video = variant.video; /** @type {?string} */ - let audioCodec = audio ? audio.codecs : null; + const audioCodec = audio ? audio.codecs : null; /** @type {?string} */ - let videoCodec = video ? video.codecs : null; + const videoCodec = video ? video.codecs : null; /** @type {!Array.<string>} */ - let codecs = []; + const codecs = []; if (videoCodec) codecs.push(videoCodec); if (audioCodec) codecs.push(audioCodec); /** @type {!Array.<string>} */ - let mimeTypes = []; + const mimeTypes = []; if (video) mimeTypes.push(video.mimeType); if (audio) mimeTypes.push(audio.mimeType); /** @type {?string} */ - let mimeType = mimeTypes[0] || null; + const mimeType = mimeTypes[0] || null; /** @type {!Array.<string>} */ - let kinds = []; + const kinds = []; if (audio) kinds.push(audio.kind); if (video) kinds.push(video.kind); /** @type {?string} */ - let kind = kinds[0] || null; + const kind = kinds[0] || null; /** @type {!Set.<string>} */ const roles = new Set(); @@ -261,7 +261,7 @@ shaka.util.StreamUtils.variantToTrack = function(variant) { if (video) video.roles.forEach((role) => roles.add(role)); /** @type {shaka.extern.Track} */ - let track = { + const track = { id: variant.id, active: false, type: 'variant', @@ -319,7 +319,7 @@ shaka.util.StreamUtils.textStreamToTrack = function(stream) { const ContentType = shaka.util.ManifestParserUtils.ContentType; /** @type {shaka.extern.Track} */ - let track = { + const track = { id: stream.id, active: false, type: ContentType.TEXT, @@ -543,7 +543,7 @@ shaka.util.StreamUtils.filterStreamsByLanguageAndRole = function( // Start with the set of primary streams. /** @type {!Array.<!shaka.extern.Stream>} */ - let primary = streams.filter(function(stream) { + const primary = streams.filter(function(stream) { return stream.primary; }); @@ -553,7 +553,7 @@ shaka.util.StreamUtils.filterStreamsByLanguageAndRole = function( // Now reduce the set to one language. This covers both arbitrary language // choice and the reduction of the "primary" stream set to one language. - let firstLanguage = chosen.length ? chosen[0].language : ''; + const firstLanguage = chosen.length ? chosen[0].language : ''; chosen = chosen.filter(function(stream) { return stream.language == firstLanguage; }); @@ -577,7 +577,7 @@ shaka.util.StreamUtils.filterStreamsByLanguageAndRole = function( // Now refine the choice based on role preference. if (preferredRole) { - let roleMatches = shaka.util.StreamUtils.filterTextStreamsByRole_( + const roleMatches = shaka.util.StreamUtils.filterTextStreamsByRole_( chosen, preferredRole); if (roleMatches.length) { return roleMatches; @@ -586,7 +586,7 @@ shaka.util.StreamUtils.filterStreamsByLanguageAndRole = function( } } else { // Prefer text streams with no roles, if they exist. - let noRoleMatches = chosen.filter(function(stream) { + const noRoleMatches = chosen.filter(function(stream) { return stream.roles.length == 0; }); if (noRoleMatches.length) { @@ -598,7 +598,7 @@ shaka.util.StreamUtils.filterStreamsByLanguageAndRole = function( // Choose an arbitrary role, if there are any, and filter out any other roles. // This ensures we never adapt between roles. - let allRoles = chosen.map(function(stream) { + const allRoles = chosen.map(function(stream) { return stream.roles; }).reduce(shaka.util.Functional.collapseArrays, []); diff --git a/lib/util/string_utils.js b/lib/util/string_utils.js index 01a9618c50..187f47e9b2 100644 --- a/lib/util/string_utils.js +++ b/lib/util/string_utils.js @@ -46,12 +46,12 @@ shaka.util.StringUtils.fromUTF8 = function(data) { } // http://stackoverflow.com/a/13691499 - let utf8 = shaka.util.StringUtils.fromCharCode(uint8); + const utf8 = shaka.util.StringUtils.fromCharCode(uint8); // This converts each character in the string to an escape sequence. If the // character is in the ASCII range, it is not converted; otherwise it is // converted to a URI escape sequence. // Example: '\x67\x35\xe3\x82\xac' -> 'g#%E3%82%AC' - let escaped = escape(utf8); + const escaped = escape(utf8); // Decode the escaped sequence. This will interpret UTF-8 sequences into the // correct character. // Example: 'g#%E3%82%AC' -> 'g#€' @@ -95,15 +95,15 @@ shaka.util.StringUtils.fromUTF16 = function(data, littleEndian, noThrow) { // Have to create a new buffer because the argument may be a smaller // view on a larger ArrayBuffer. We cannot use an ArrayBufferView in // a DataView. - let temp = new Uint8Array(data.byteLength); + const temp = new Uint8Array(data.byteLength); temp.set(new Uint8Array(data)); buffer = temp.buffer; } // Use a DataView to ensure correct endianness. - let length = Math.floor(data.byteLength / 2); - let arr = new Uint16Array(length); - let dataView = new DataView(buffer); + const length = Math.floor(data.byteLength / 2); + const arr = new Uint16Array(length); + const dataView = new DataView(buffer); for (let i = 0; i < length; i++) { arr[i] = dataView.getUint16(i * 2, littleEndian); } @@ -123,7 +123,7 @@ shaka.util.StringUtils.fromUTF16 = function(data, littleEndian, noThrow) { shaka.util.StringUtils.fromBytesAutoDetect = function(data) { const StringUtils = shaka.util.StringUtils; - let uint8 = new Uint8Array(data); + const uint8 = new Uint8Array(data); if (uint8[0] == 0xef && uint8[1] == 0xbb && uint8[2] == 0xbf) { return StringUtils.fromUTF8(uint8); } else if (uint8[0] == 0xfe && uint8[1] == 0xff) { @@ -132,7 +132,7 @@ shaka.util.StringUtils.fromBytesAutoDetect = function(data) { return StringUtils.fromUTF16(uint8.subarray(2), true /* littleEndian */); } - let isAscii = (function(arr, i) { + const isAscii = (function(arr, i) { // arr[i] >= ' ' && arr[i] <= '~'; return arr.byteLength <= i || (arr[i] >= 0x20 && arr[i] <= 0x7e); }.bind(null, uint8)); @@ -166,15 +166,15 @@ shaka.util.StringUtils.toUTF8 = function(str) { // in the ASCII range, it is not converted; otherwise it will be converted to // a series of URI escape sequences according to UTF-8. // Example: 'g#€' -> 'g#%E3%82%AC' - let encoded = encodeURIComponent(str); + const encoded = encodeURIComponent(str); // Convert each escape sequence individually into a character. Each escape // sequence is interpreted as a code-point, so if an escape sequence happens // to be part of a multi-byte sequence, each byte will be converted to a // single character. // Example: 'g#%E3%82%AC' -> '\x67\x35\xe3\x82\xac' - let utf8 = unescape(encoded); + const utf8 = unescape(encoded); - let result = new Uint8Array(utf8.length); + const result = new Uint8Array(utf8.length); for (let i = 0; i < utf8.length; ++i) { result[i] = utf8.charCodeAt(i); } @@ -212,10 +212,10 @@ shaka.util.StringUtils.toUTF16 = function(str, littleEndian) { * @return {string} */ shaka.util.StringUtils.fromCharCode = function(array) { - let max = 16000; + const max = 16000; let ret = ''; for (let i = 0; i < array.length; i += max) { - let subArray = array.subarray(i, i + max); + const subArray = array.subarray(i, i + max); ret += String.fromCharCode.apply(null, subArray); } diff --git a/lib/util/text_parser.js b/lib/util/text_parser.js index 8ecfd22af5..e762e92d47 100644 --- a/lib/util/text_parser.js +++ b/lib/util/text_parser.js @@ -86,7 +86,7 @@ shaka.util.TextParser.prototype.skipWhitespace = function() { * @return {Array.<string>} */ shaka.util.TextParser.prototype.readRegex = function(regex) { - let index = this.indexOf_(regex); + const index = this.indexOf_(regex); if (this.atEnd() || index == null || index.position != this.position_) { return null; } @@ -110,7 +110,7 @@ shaka.util.TextParser.prototype.readRegexReturnCapture_ = function( return null; } - let ret = this.readRegex(regex); + const ret = this.readRegex(regex); if (!ret) { return null; } else { @@ -131,7 +131,7 @@ shaka.util.TextParser.prototype.indexOf_ = function(regex) { goog.asserts.assert(regex.global, 'global flag should be set'); regex.lastIndex = this.position_; - let results = regex.exec(this.data_); + const results = regex.exec(this.data_); if (results == null) { return null; } else { diff --git a/lib/util/uint8array_utils.js b/lib/util/uint8array_utils.js index c2a6795f44..640ebaab50 100644 --- a/lib/util/uint8array_utils.js +++ b/lib/util/uint8array_utils.js @@ -38,9 +38,9 @@ goog.require('shaka.util.StringUtils'); */ shaka.util.Uint8ArrayUtils.toBase64 = function(arr, padding) { // btoa expects a "raw string" where each character is interpreted as a byte. - let bytes = shaka.util.StringUtils.fromCharCode(arr); + const bytes = shaka.util.StringUtils.fromCharCode(arr); padding = (padding == undefined) ? true : padding; - let base64 = window.btoa(bytes).replace(/\+/g, '-').replace(/\//g, '_'); + const base64 = window.btoa(bytes).replace(/\+/g, '-').replace(/\//g, '_'); return padding ? base64 : base64.replace(/=*$/, ''); }; @@ -54,8 +54,8 @@ shaka.util.Uint8ArrayUtils.toBase64 = function(arr, padding) { */ shaka.util.Uint8ArrayUtils.fromBase64 = function(str) { // atob creates a "raw string" where each character is interpreted as a byte. - let bytes = window.atob(str.replace(/-/g, '+').replace(/_/g, '/')); - let result = new Uint8Array(bytes.length); + const bytes = window.atob(str.replace(/-/g, '+').replace(/_/g, '/')); + const result = new Uint8Array(bytes.length); for (let i = 0; i < bytes.length; ++i) { result[i] = bytes.charCodeAt(i); } @@ -70,7 +70,7 @@ shaka.util.Uint8ArrayUtils.fromBase64 = function(str) { * @export */ shaka.util.Uint8ArrayUtils.fromHex = function(str) { - let arr = new Uint8Array(str.length / 2); + const arr = new Uint8Array(str.length / 2); for (let i = 0; i < str.length; i += 2) { arr[i / 2] = window.parseInt(str.substr(i, 2), 16); } @@ -125,7 +125,7 @@ shaka.util.Uint8ArrayUtils.concat = function(...varArgs) { totalLength += varArgs[i].length; } - let result = new Uint8Array(totalLength); + const result = new Uint8Array(totalLength); let offset = 0; for (let i = 0; i < varArgs.length; ++i) { result.set(varArgs[i], offset); diff --git a/lib/util/xml_utils.js b/lib/util/xml_utils.js index bc671fde21..9ac86407da 100644 --- a/lib/util/xml_utils.js +++ b/lib/util/xml_utils.js @@ -36,7 +36,7 @@ goog.require('shaka.util.StringUtils'); * child XML element with the given tag name. */ shaka.util.XmlUtils.findChild = function(elem, name) { - let children = shaka.util.XmlUtils.findChildren(elem, name); + const children = shaka.util.XmlUtils.findChildren(elem, name); if (children.length != 1) { return null; } @@ -54,7 +54,7 @@ shaka.util.XmlUtils.findChild = function(elem, name) { * child XML element with the given tag name. */ shaka.util.XmlUtils.findChildNS = function(elem, ns, name) { - let children = shaka.util.XmlUtils.findChildrenNS(elem, ns, name); + const children = shaka.util.XmlUtils.findChildrenNS(elem, ns, name); if (children.length != 1) { return null; } @@ -110,7 +110,7 @@ shaka.util.XmlUtils.getAttributeNS = function(elem, ns, name) { * @return {?string} The text contents, or null if there are none. */ shaka.util.XmlUtils.getContents = function(elem) { - let isText = (child) => { + const isText = (child) => { return child.nodeType == Node.TEXT_NODE || child.nodeType == Node.CDATA_SECTION_NODE; }; @@ -139,7 +139,7 @@ shaka.util.XmlUtils.parseAttr = function( elem, name, parseFunction, defaultValue = null) { let parsedValue = null; - let value = elem.getAttribute(name); + const value = elem.getAttribute(name); if (value != null) { parsedValue = parseFunction(value); } @@ -166,7 +166,7 @@ shaka.util.XmlUtils.parseDate = function(dateString) { dateString += 'Z'; } - let result = Date.parse(dateString); + const result = Date.parse(dateString); return (!isNaN(result) ? Math.floor(result / 1000.0) : null); }; @@ -186,9 +186,9 @@ shaka.util.XmlUtils.parseDuration = function(durationString) { return null; } - let re = '^P(?:([0-9]*)Y)?(?:([0-9]*)M)?(?:([0-9]*)D)?' + + const re = '^P(?:([0-9]*)Y)?(?:([0-9]*)M)?(?:([0-9]*)D)?' + '(?:T(?:([0-9]*)H)?(?:([0-9]*)M)?(?:([0-9.]*)S)?)?$'; - let matches = new RegExp(re).exec(durationString); + const matches = new RegExp(re).exec(durationString); if (!matches) { shaka.log.warning('Invalid duration string:', durationString); @@ -196,15 +196,15 @@ shaka.util.XmlUtils.parseDuration = function(durationString) { } // Note: Number(null) == 0 but Number(undefined) == NaN. - let years = Number(matches[1] || null); - let months = Number(matches[2] || null); - let days = Number(matches[3] || null); - let hours = Number(matches[4] || null); - let minutes = Number(matches[5] || null); - let seconds = Number(matches[6] || null); + const years = Number(matches[1] || null); + const months = Number(matches[2] || null); + const days = Number(matches[3] || null); + const hours = Number(matches[4] || null); + const minutes = Number(matches[5] || null); + const seconds = Number(matches[6] || null); // Assume a year always has 365 days and a month always has 30 days. - let d = (60 * 60 * 24 * 365) * years + + const d = (60 * 60 * 24 * 365) * years + (60 * 60 * 24 * 30) * months + (60 * 60 * 24) * days + (60 * 60) * hours + @@ -221,18 +221,18 @@ shaka.util.XmlUtils.parseDuration = function(durationString) { * otherwise, return null. */ shaka.util.XmlUtils.parseRange = function(rangeString) { - let matches = /([0-9]+)-([0-9]+)/.exec(rangeString); + const matches = /([0-9]+)-([0-9]+)/.exec(rangeString); if (!matches) { return null; } - let start = Number(matches[1]); + const start = Number(matches[1]); if (!isFinite(start)) { return null; } - let end = Number(matches[2]); + const end = Number(matches[2]); if (!isFinite(end)) { return null; } @@ -247,7 +247,7 @@ shaka.util.XmlUtils.parseRange = function(rangeString) { * @return {?number} The parsed integer on success; otherwise, return null. */ shaka.util.XmlUtils.parseInt = function(intString) { - let n = Number(intString); + const n = Number(intString); return (n % 1 === 0) ? n : null; }; @@ -259,7 +259,7 @@ shaka.util.XmlUtils.parseInt = function(intString) { * return null. */ shaka.util.XmlUtils.parsePositiveInt = function(intString) { - let n = Number(intString); + const n = Number(intString); return (n % 1 === 0) && (n > 0) ? n : null; }; @@ -271,7 +271,7 @@ shaka.util.XmlUtils.parsePositiveInt = function(intString) { * return null. */ shaka.util.XmlUtils.parseNonNegativeInt = function(intString) { - let n = Number(intString); + const n = Number(intString); return (n % 1 === 0) && (n >= 0) ? n : null; }; @@ -283,7 +283,7 @@ shaka.util.XmlUtils.parseNonNegativeInt = function(intString) { * return null. May return -Infinity or Infinity. */ shaka.util.XmlUtils.parseFloat = function(floatString) { - let n = Number(floatString); + const n = Number(floatString); return !isNaN(n) ? n : null; }; diff --git a/test/abr/simple_abr_manager_unit.js b/test/abr/simple_abr_manager_unit.js index ce838c1fba..923cc67435 100644 --- a/test/abr/simple_abr_manager_unit.js +++ b/test/abr/simple_abr_manager_unit.js @@ -87,20 +87,20 @@ describe('SimpleAbrManager', function() { }); it('can choose audio and video Streams right away', function() { - let chosen = abrManager.chooseVariant(); + const chosen = abrManager.chooseVariant(); expect(chosen).not.toBe(null); }); it('uses custom default estimate', function() { config.defaultBandwidthEstimate = 3e6; abrManager.configure(config); - let chosen = abrManager.chooseVariant(); + const chosen = abrManager.chooseVariant(); expect(chosen.id).toBe(104); }); it('can handle empty variants', function() { abrManager.setVariants([]); - let chosen = abrManager.chooseVariant(); + const chosen = abrManager.chooseVariant(); expect(chosen).toEqual(null); }); @@ -114,7 +114,7 @@ describe('SimpleAbrManager', function() { .build(); abrManager.setVariants(manifest.periods[0].variants); - let chosen = abrManager.chooseVariant(); + const chosen = abrManager.chooseVariant(); expect(chosen).not.toBe(null); expect(chosen.audio).not.toBe(null); expect(chosen.video).toBe(null); @@ -130,7 +130,7 @@ describe('SimpleAbrManager', function() { .build(); abrManager.setVariants(manifest.periods[0].variants); - let chosen = abrManager.chooseVariant(); + const chosen = abrManager.chooseVariant(); expect(chosen).not.toBe(null); expect(chosen.audio).toBe(null); expect(chosen.video).not.toBe(null); @@ -139,11 +139,11 @@ describe('SimpleAbrManager', function() { [5e5, 6e5].forEach(function(bandwidth) { // Simulate some segments being downloaded just above the desired // bandwidth. - let bytesPerSecond = + const bytesPerSecond = sufficientBWMultiplier * bandwidth / 8.0; - let bandwidthKbps = bandwidth / 1000.0; - let description = + const bandwidthKbps = bandwidth / 1000.0; + const description = 'picks correct Variant at ' + bandwidthKbps + ' kbps'; it(description, function() { @@ -161,7 +161,7 @@ describe('SimpleAbrManager', function() { // Expect variants 2 to be chosen for bandwidth = 5e5 // and variant 5 - for bandwidth = 6e5 - let expectedVariant = (bandwidth == 6e5) ? variants[5] : variants[2]; + const expectedVariant = (bandwidth == 6e5) ? variants[5] : variants[2]; expect(switchCallback).toHaveBeenCalledWith(expectedVariant); }); @@ -171,8 +171,8 @@ describe('SimpleAbrManager', function() { // Makes sure bandwidth estimate doesn't get set to NaN // when a 0 duration segment is encountered. // https://github.com/google/shaka-player/issues/582 - let bandwidth = 5e5; - let bytesPerSecond = + const bandwidth = 5e5; + const bytesPerSecond = sufficientBWMultiplier * bandwidth / 8.0; abrManager.setVariants(variants); @@ -191,14 +191,14 @@ describe('SimpleAbrManager', function() { it('picks lowest variant when there is insufficient bandwidth', function() { - let bandwidth = 2e6; + const bandwidth = 2e6; abrManager.setVariants(variants); abrManager.chooseVariant(); // Simulate some segments being downloaded just above the desired // bandwidth. - let bytesPerSecond = + const bytesPerSecond = sufficientBWMultiplier * bandwidth / 8.0; abrManager.segmentDownloaded(1000, bytesPerSecond); @@ -211,14 +211,14 @@ describe('SimpleAbrManager', function() { abrManager.segmentDownloaded(1000, bytesPerSecond); // Expect variants 4 to be chosen - let expectedVariant = variants[4]; + const expectedVariant = variants[4]; expect(switchCallback).toHaveBeenCalledWith(expectedVariant); }); it('does not call switchCallback() if not enabled', function() { - let bandwidth = 5e5; - let bytesPerSecond = + const bandwidth = 5e5; + const bytesPerSecond = sufficientBWMultiplier * bandwidth / 8.0; abrManager.setVariants(variants); @@ -277,8 +277,8 @@ describe('SimpleAbrManager', function() { it('does not clear the buffer on upgrade', function() { // Simulate some segments being downloaded at a high rate, to trigger an // upgrade. - let bandwidth = 5e5; - let bytesPerSecond = + const bandwidth = 5e5; + const bytesPerSecond = sufficientBWMultiplier * bandwidth / 8.0; abrManager.setVariants(variants); @@ -301,8 +301,8 @@ describe('SimpleAbrManager', function() { it('does not clear the buffer on downgrade', function() { // Simulate some segments being downloaded at a low rate, to trigger a // downgrade. - let bandwidth = 5e5; - let bytesPerSecond = + const bandwidth = 5e5; + const bytesPerSecond = sufficientBWMultiplier * bandwidth / 8.0; // Set the default high so that the initial choice will be high-quality. diff --git a/test/assumptions/uint8_array_unit.js b/test/assumptions/uint8_array_unit.js index f2ec1f7456..8e1ba55fc8 100644 --- a/test/assumptions/uint8_array_unit.js +++ b/test/assumptions/uint8_array_unit.js @@ -17,9 +17,9 @@ describe('Uint8Array', function() { it('checks equality', function() { - let subject = new Uint8Array([0, 1, 2, 3]); - let same = new Uint8Array([0, 1, 2, 3]); - let different = new Uint8Array([4, 5, 6, 7]); + const subject = new Uint8Array([0, 1, 2, 3]); + const same = new Uint8Array([0, 1, 2, 3]); + const different = new Uint8Array([4, 5, 6, 7]); expect(subject).toBe(subject); expect(subject).toEqual(subject); diff --git a/test/cast/cast_proxy_unit.js b/test/cast/cast_proxy_unit.js index bbcfc1c04d..d7cba5db68 100644 --- a/test/cast/cast_proxy_unit.js +++ b/test/cast/cast_proxy_unit.js @@ -110,7 +110,7 @@ describe('CastProxy', function() { describe('setAppData', function() { it('delegates directly to the sender', function() { - let fakeAppData = {key: 'value'}; + const fakeAppData = {key: 'value'}; expect(mockSender.setAppData).not.toHaveBeenCalled(); proxy.setAppData(fakeAppData); expect(mockSender.setAppData).toHaveBeenCalledWith(fakeAppData); @@ -135,17 +135,17 @@ describe('CastProxy', function() { mockVideo.loop = true; mockVideo.playbackRate = 3; mockVideo.currentTime = 12; - let fakeConfig = {key: 'value'}; + const fakeConfig = {key: 'value'}; mockPlayer.getConfiguration.and.returnValue(fakeConfig); mockPlayer.isTextTrackVisible.and.returnValue(false); - let fakeManifestUri = 'foo://bar'; + const fakeManifestUri = 'foo://bar'; mockPlayer.getAssetUri.and.returnValue(fakeManifestUri); proxy.cast(); - let calls = mockSender.cast.calls; + const calls = mockSender.cast.calls; expect(calls.count()).toBe(1); if (calls.count()) { - let state = calls.argsFor(0)[0]; + const state = calls.argsFor(0)[0]; // Video state goes directly: expect(state.video.loop).toEqual(mockVideo.loop); expect(state.video.playbackRate).toEqual(mockVideo.playbackRate); @@ -164,16 +164,16 @@ describe('CastProxy', function() { mockVideo.currentTime = 12; proxy.cast(); - let calls = mockSender.cast.calls; + const calls = mockSender.cast.calls; expect(calls.count()).toBe(1); if (calls.count()) { - let state = calls.argsFor(0)[0]; + const state = calls.argsFor(0)[0]; expect(state.startTime).toBe(null); } }); it('unloads the local player after casting is complete', function(done) { - let p = new shaka.util.PublicPromise(); + const p = new shaka.util.PublicPromise(); mockSender.cast.and.returnValue(p); proxy.cast(); @@ -215,7 +215,7 @@ describe('CastProxy', function() { mockSender.hasRemoteProperties.and.returnValue(true); // Simulate remote values: - let cache = {video: { + const cache = {video: { currentTime: 24, paused: false, play: jasmine.createSpy('play'), @@ -247,7 +247,7 @@ describe('CastProxy', function() { mockSender.hasRemoteProperties.and.returnValue(false); // Simulate remote method: - let playSpy = jasmine.createSpy('play'); + const playSpy = jasmine.createSpy('play'); mockSender.get.and.callFake(function(targetName, property) { expect(targetName).toEqual('video'); expect(property).toEqual('play'); @@ -298,12 +298,12 @@ describe('CastProxy', function() { describe('local events', function() { it('forward to the proxy when we are playing back locally', function() { - let proxyListener = jasmine.createSpy('listener'); + const proxyListener = jasmine.createSpy('listener'); proxy.getVideo().addEventListener( 'timeupdate', Util.spyFunc(proxyListener)); expect(proxyListener).not.toHaveBeenCalled(); - let fakeEvent = new FakeEvent('timeupdate', {detail: 8675309}); + const fakeEvent = new FakeEvent('timeupdate', {detail: 8675309}); mockVideo.on['timeupdate'](fakeEvent); expect(proxyListener).toHaveBeenCalledWith(jasmine.objectContaining({ type: 'timeupdate', @@ -312,7 +312,7 @@ describe('CastProxy', function() { }); it('are ignored when we are casting', function() { - let proxyListener = jasmine.createSpy('listener'); + const proxyListener = jasmine.createSpy('listener'); proxy.getVideo().addEventListener( 'timeupdate', Util.spyFunc(proxyListener)); @@ -321,7 +321,7 @@ describe('CastProxy', function() { mockSender.hasRemoteProperties.and.returnValue(true); expect(proxyListener).not.toHaveBeenCalled(); - let fakeEvent = new FakeEvent('timeupdate', {detail: 8675309}); + const fakeEvent = new FakeEvent('timeupdate', {detail: 8675309}); mockVideo.on['timeupdate'](fakeEvent); expect(proxyListener).not.toHaveBeenCalled(); }); @@ -329,7 +329,7 @@ describe('CastProxy', function() { describe('remote events', function() { it('forward to the proxy when we are casting', function() { - let proxyListener = jasmine.createSpy('listener'); + const proxyListener = jasmine.createSpy('listener'); proxy.getVideo().addEventListener( 'timeupdate', Util.spyFunc(proxyListener)); @@ -338,7 +338,7 @@ describe('CastProxy', function() { mockSender.hasRemoteProperties.and.returnValue(true); expect(proxyListener).not.toHaveBeenCalled(); - let fakeEvent = new FakeEvent('timeupdate', {detail: 8675309}); + const fakeEvent = new FakeEvent('timeupdate', {detail: 8675309}); mockSender.onRemoteEvent('video', fakeEvent); expect(proxyListener).toHaveBeenCalledWith(jasmine.objectContaining({ type: 'timeupdate', @@ -351,7 +351,7 @@ describe('CastProxy', function() { describe('player proxy', function() { describe('get', function() { it('returns local values when we are playing back locally', function() { - let fakeConfig = {key: 'value'}; + const fakeConfig = {key: 'value'}; mockPlayer.getConfiguration.and.returnValue(fakeConfig); expect(proxy.getPlayer().getConfiguration()).toEqual(fakeConfig); @@ -364,7 +364,7 @@ describe('CastProxy', function() { it('returns cached remote values when we are casting', function() { // Local values that will be ignored: - let fakeConfig = {key: 'value'}; + const fakeConfig = {key: 'value'}; mockPlayer.getConfiguration.and.returnValue(fakeConfig); mockPlayer.isTextTrackVisible.and.returnValue(false); @@ -373,15 +373,15 @@ describe('CastProxy', function() { mockSender.hasRemoteProperties.and.returnValue(true); // Simulate remote values: - let fakeConfig2 = {key2: 'value2'}; - let cache = {player: { + const fakeConfig2 = {key2: 'value2'}; + const cache = {player: { getConfiguration: fakeConfig2, isTextTrackVisible: true, trickPlay: jasmine.createSpy('trickPlay'), }}; mockSender.get.and.callFake(function(targetName, property) { expect(targetName).toEqual('player'); - let value = cache.player[property]; + const value = cache.player[property]; // methods: if (typeof value == 'function') return value; // getters: @@ -400,7 +400,7 @@ describe('CastProxy', function() { }); it('returns local values when we have no remote values yet', function() { - let fakeConfig = {key: 'value'}; + const fakeConfig = {key: 'value'}; mockPlayer.getConfiguration.and.returnValue(fakeConfig); mockPlayer.isTextTrackVisible.and.returnValue(true); @@ -409,7 +409,7 @@ describe('CastProxy', function() { mockSender.hasRemoteProperties.and.returnValue(false); // Simulate remote method: - let trickPlaySpy = jasmine.createSpy('trickPlay'); + const trickPlaySpy = jasmine.createSpy('trickPlay'); mockSender.get.and.callFake(function(targetName, property) { expect(targetName).toEqual('player'); expect(property).toEqual('trickPlay'); @@ -444,12 +444,12 @@ describe('CastProxy', function() { describe('local events', function() { it('forward to the proxy when we are playing back locally', function() { - let proxyListener = jasmine.createSpy('listener'); + const proxyListener = jasmine.createSpy('listener'); proxy.getPlayer().addEventListener( 'buffering', Util.spyFunc(proxyListener)); expect(proxyListener).not.toHaveBeenCalled(); - let fakeEvent = new FakeEvent('buffering', {detail: 8675309}); + const fakeEvent = new FakeEvent('buffering', {detail: 8675309}); mockPlayer.listeners['buffering'](fakeEvent); expect(proxyListener).toHaveBeenCalledWith(jasmine.objectContaining({ type: 'buffering', @@ -458,7 +458,7 @@ describe('CastProxy', function() { }); it('are ignored when we are casting', function() { - let proxyListener = jasmine.createSpy('listener'); + const proxyListener = jasmine.createSpy('listener'); proxy.getPlayer().addEventListener( 'buffering', Util.spyFunc(proxyListener)); @@ -467,7 +467,7 @@ describe('CastProxy', function() { mockSender.hasRemoteProperties.and.returnValue(true); expect(proxyListener).not.toHaveBeenCalled(); - let fakeEvent = new FakeEvent('buffering', {detail: 8675309}); + const fakeEvent = new FakeEvent('buffering', {detail: 8675309}); mockPlayer.listeners['buffering'](fakeEvent); expect(proxyListener).not.toHaveBeenCalled(); }); @@ -475,7 +475,7 @@ describe('CastProxy', function() { describe('remote events', function() { it('forward to the proxy when we are casting', function() { - let proxyListener = jasmine.createSpy('listener'); + const proxyListener = jasmine.createSpy('listener'); proxy.getPlayer().addEventListener( 'buffering', Util.spyFunc(proxyListener)); @@ -484,7 +484,7 @@ describe('CastProxy', function() { mockSender.hasRemoteProperties.and.returnValue(true); expect(proxyListener).not.toHaveBeenCalled(); - let fakeEvent = new FakeEvent('buffering', {detail: 8675309}); + const fakeEvent = new FakeEvent('buffering', {detail: 8675309}); mockSender.onRemoteEvent('player', fakeEvent); expect(proxyListener).toHaveBeenCalledWith(jasmine.objectContaining({ type: 'buffering', @@ -496,7 +496,7 @@ describe('CastProxy', function() { describe('"caststatuschanged" event', function() { it('is triggered by the sender', function() { - let listener = jasmine.createSpy('listener'); + const listener = jasmine.createSpy('listener'); proxy.addEventListener('caststatuschanged', Util.spyFunc(listener)); expect(listener).not.toHaveBeenCalled(); mockSender.onCastStatusChanged(); @@ -509,7 +509,7 @@ describe('CastProxy', function() { describe('synthetic video events from onFirstCastStateUpdate', function() { it('sends a pause event if the video is paused', function() { mockVideo.paused = true; - let proxyListener = jasmine.createSpy('listener'); + const proxyListener = jasmine.createSpy('listener'); proxy.getVideo().addEventListener('pause', Util.spyFunc(proxyListener)); expect(proxyListener).not.toHaveBeenCalled(); mockSender.onFirstCastStateUpdate(); @@ -518,7 +518,7 @@ describe('CastProxy', function() { it('sends a play event if the video is playing', function() { mockVideo.paused = false; - let proxyListener = jasmine.createSpy('listener'); + const proxyListener = jasmine.createSpy('listener'); proxy.getVideo().addEventListener('play', Util.spyFunc(proxyListener)); expect(proxyListener).not.toHaveBeenCalled(); mockSender.onFirstCastStateUpdate(); @@ -635,7 +635,7 @@ describe('CastProxy', function() { it('triggers an "error" event if load fails', function(done) { cache.player.getAssetUri = 'foo://bar'; - let fakeError = new shaka.util.Error( + const fakeError = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.MANIFEST, shaka.util.Error.Code.UNABLE_TO_GUESS_MANIFEST_TYPE); @@ -713,7 +713,7 @@ describe('CastProxy', function() { } function createMockPlayer() { - let player = { + const player = { load: jasmine.createSpy('load'), unload: jasmine.createSpy('unload'), getNetworkingEngine: jasmine.createSpy('getNetworkingEngine'), diff --git a/test/cast/cast_receiver_integration.js b/test/cast/cast_receiver_integration.js index 790e1623da..07f92dd355 100644 --- a/test/cast/cast_receiver_integration.js +++ b/test/cast/cast_receiver_integration.js @@ -22,7 +22,7 @@ describe('CastReceiver', function() { const originalCast = window['cast']; const originalUserAgent = navigator.userAgent; - let eventManager = new shaka.util.EventManager(); + const eventManager = new shaka.util.EventManager(); let mockReceiverManager; let mockReceiverApi; @@ -58,7 +58,7 @@ describe('CastReceiver', function() { function checkAndRun(test, checkKeySystems) { const Platform = shaka.util.Platform; - let check = function(done) { + const check = function(done) { if (checkKeySystems && !support['com.widevine.alpha']) { pending('Skipping DrmEngine tests.'); } else if (Platform.isChromecast()) { @@ -88,7 +88,7 @@ describe('CastReceiver', function() { } beforeAll(function(done) { - let supportTest = shaka.media.DrmEngine.probeSupport() + const supportTest = shaka.media.DrmEngine.probeSupport() .then(function(result) { support = result; }) .catch(fail); @@ -113,7 +113,7 @@ describe('CastReceiver', function() { shaka.media.ManifestParser.registerParserByMime( 'application/x-test-manifest', shaka.test.TestScheme.ManifestParser); - let createManifests = shaka.test.TestScheme.createManifests(shaka, ''); + const createManifests = shaka.test.TestScheme.createManifests(shaka, ''); Promise.all([createManifests, supportTest]).then(done); }); @@ -121,7 +121,7 @@ describe('CastReceiver', function() { beforeEach(checkAndRun(() => { mockReceiverApi = createMockReceiverApi(); - let mockCanDisplayType = jasmine.createSpy('canDisplayType'); + const mockCanDisplayType = jasmine.createSpy('canDisplayType'); mockCanDisplayType.and.returnValue(true); // We're using quotes to access window.cast because the compiler @@ -288,13 +288,13 @@ describe('CastReceiver', function() { */ function waitForUpdateMessageWrapper(prototype, name, methodName) { pendingWaitWrapperCalls += 1; - let original = prototype[methodName]; + const original = prototype[methodName]; prototype[methodName] = /** @this {Object} @return {*} */ function() { pendingWaitWrapperCalls -= 1; shaka.log.debug( 'Waiting for update message before calling ' + name + '.' + methodName + '...'); - let originalArguments = arguments; + const originalArguments = arguments; return waitForUpdateMessage().then(function() { return original.apply(this, originalArguments); }.bind(this)); @@ -305,7 +305,7 @@ describe('CastReceiver', function() { } function addOnError(done) { - let onError = function(event) { + const onError = function(event) { fail(event.detail); done(); }; @@ -346,7 +346,7 @@ describe('CastReceiver', function() { } function createMockMessageBus() { - let bus = { + const bus = { messages: [], broadcast: jasmine.createSpy('CastMessageBus.broadcast'), getCastChannel: jasmine.createSpy('CastMessageBus.getCastChannel'), @@ -355,14 +355,14 @@ describe('CastReceiver', function() { bus.broadcast.and.callFake(function(message) { bus.messages.push(CastUtils.deserialize(message)); // Check to see if it's an update message. - let parsed = CastUtils.deserialize(message); + const parsed = CastUtils.deserialize(message); if (parsed.type == 'update' && messageWaitPromise) { shaka.log.debug('Received update message. Proceeding...'); messageWaitPromise.resolve(message); messageWaitPromise = null; } }); - let channel = { + const channel = { messages: [], send: function(message) { channel.messages.push(CastUtils.deserialize(message)); @@ -376,7 +376,7 @@ describe('CastReceiver', function() { * @param {number} num */ function fakeConnectedSenders(num) { - let senderArray = []; + const senderArray = []; while (num--) { senderArray.push('senderId'); } @@ -391,8 +391,8 @@ describe('CastReceiver', function() { * @param {string=} senderId */ function fakeIncomingMessage(message, bus, senderId) { - let serialized = CastUtils.serialize(message); - let messageEvent = { + const serialized = CastUtils.serialize(message); + const messageEvent = { senderId: senderId, data: serialized, }; diff --git a/test/cast/cast_receiver_unit.js b/test/cast/cast_receiver_unit.js index b649e50a1b..cdea73798a 100644 --- a/test/cast/cast_receiver_unit.js +++ b/test/cast/cast_receiver_unit.js @@ -50,7 +50,7 @@ describe('CastReceiver', function() { * @return {function(function())} */ function checkAndRun(test) { - let check = function(done) { + const check = function(done) { if (!isChromecast && !isChrome) { pending( 'Skipping CastReceiver tests for non-Chrome and non-Chromecast'); @@ -71,7 +71,7 @@ describe('CastReceiver', function() { // browsers our library supports. Because of this, CastReceiver tests will // only be run on Chrome and Chromecast. isChromecast = navigator.userAgent.includes('CrKey'); - let isEdge = navigator.userAgent.includes('Edge/'); + const isEdge = navigator.userAgent.includes('Edge/'); // Edge also has "Chrome/" in its user agent string. isChrome = navigator.userAgent.includes('Chrome/') && !isEdge; @@ -141,8 +141,8 @@ describe('CastReceiver', function() { it('limits streams to 1080p on Chromecast v1 and v2', checkAndRun(() => { // Simulate the canDisplayType reponse of Chromecast v1 or v2 mockCanDisplayType.and.callFake(function(type) { - let matches = /height=(\d+)/.exec(type); - let height = matches[1]; + const matches = /height=(\d+)/.exec(type); + const height = matches[1]; if (height && height > 1080) return false; return true; }); @@ -156,8 +156,8 @@ describe('CastReceiver', function() { it('limits streams to 4k on Chromecast Ultra', checkAndRun(() => { // Simulate the canDisplayType reponse of Chromecast Ultra mockCanDisplayType.and.callFake(function(type) { - let matches = /height=(\d+)/.exec(type); - let height = matches[1]; + const matches = /height=(\d+)/.exec(type); + const height = matches[1]; if (height && height > 2160) return false; return true; }); @@ -202,7 +202,7 @@ describe('CastReceiver', function() { }); it('triggers when senders connect or disconnect', checkAndRun((done) => { - let listener = jasmine.createSpy('listener'); + const listener = jasmine.createSpy('listener'); receiver.addEventListener('caststatuschanged', Util.spyFunc(listener)); shaka.test.Util.delay(0.2).then(function() { @@ -220,13 +220,13 @@ describe('CastReceiver', function() { })); it('triggers when idle state changes', checkAndRun((done) => { - let listener = jasmine.createSpy('listener'); + const listener = jasmine.createSpy('listener'); receiver.addEventListener('caststatuschanged', Util.spyFunc(listener)); - let fakeLoadingEvent = {type: 'loading'}; - let fakeUnloadingEvent = {type: 'unloading'}; - let fakeEndedEvent = {type: 'ended'}; - let fakePlayingEvent = {type: 'playing'}; + const fakeLoadingEvent = {type: 'loading'}; + const fakeUnloadingEvent = {type: 'unloading'}; + const fakeEndedEvent = {type: 'ended'}; + const fakePlayingEvent = {type: 'playing'}; shaka.test.Util.delay(0.2).then(function() { expect(listener).not.toHaveBeenCalled(); @@ -274,7 +274,7 @@ describe('CastReceiver', function() { // No messages yet. expect(mockShakaMessageBus.messages).toEqual([]); - let fakeEvent = {type: 'timeupdate'}; + const fakeEvent = {type: 'timeupdate'}; mockVideo.on['timeupdate'](fakeEvent); // There are now "update" and "event" messages, in that order. @@ -294,9 +294,9 @@ describe('CastReceiver', function() { describe('"init" message', function() { /** @const */ - let fakeConfig = {key: 'value'}; + const fakeConfig = {key: 'value'}; /** @const */ - let fakeAppData = {myFakeAppData: 1234}; + const fakeAppData = {myFakeAppData: 1234}; let fakeInitState; beforeEach(function() { @@ -348,7 +348,7 @@ describe('CastReceiver', function() { })); it('starts polling', checkAndRun(() => { - let fakeConfig = {key: 'value'}; + const fakeConfig = {key: 'value'}; mockPlayer.getConfiguration.and.returnValue(fakeConfig); fakeConnectedSenders(1); @@ -463,13 +463,13 @@ describe('CastReceiver', function() { it('triggers an "error" event if load fails', checkAndRun((done) => { fakeInitState.manifest = 'foo://bar'; - let fakeError = new shaka.util.Error( + const fakeError = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.MANIFEST, shaka.util.Error.Code.UNABLE_TO_GUESS_MANIFEST_TYPE); mockPlayer.load.and.returnValue(Promise.reject(fakeError)); - let listener = jasmine.createSpy('listener'); + const listener = jasmine.createSpy('listener'); mockPlayer.addEventListener('error', listener); expect(listener).not.toHaveBeenCalled(); @@ -496,7 +496,7 @@ describe('CastReceiver', function() { it('triggers the app data callback', checkAndRun(() => { expect(mockAppDataCallback).not.toHaveBeenCalled(); - let fakeAppData = {myFakeAppData: 1234}; + const fakeAppData = {myFakeAppData: 1234}; fakeIncomingMessage({ type: 'appData', appData: fakeAppData, @@ -589,9 +589,9 @@ describe('CastReceiver', function() { describe('"asyncCall" message', function() { /** @const */ - let fakeSenderId = 'senderId'; + const fakeSenderId = 'senderId'; /** @const */ - let fakeCallId = '5'; + const fakeCallId = '5'; /** @type {!shaka.util.PublicPromise} */ let p; @@ -630,7 +630,7 @@ describe('CastReceiver', function() { expect(mockShakaMessageBus.broadcast).not.toHaveBeenCalled(); expect(mockShakaMessageBus.getCastChannel).toHaveBeenCalledWith( fakeSenderId); - let senderChannel = mockShakaMessageBus.getCastChannel(); + const senderChannel = mockShakaMessageBus.getCastChannel(); expect(senderChannel.messages).toEqual([{ type: 'asyncComplete', id: fakeCallId, @@ -644,7 +644,7 @@ describe('CastReceiver', function() { expect(mockShakaMessageBus.broadcast).not.toHaveBeenCalled(); expect(mockShakaMessageBus.getCastChannel).not.toHaveBeenCalled(); - let fakeError = new shaka.util.Error( + const fakeError = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.MANIFEST, shaka.util.Error.Code.UNABLE_TO_GUESS_MANIFEST_TYPE); @@ -655,14 +655,14 @@ describe('CastReceiver', function() { expect(mockShakaMessageBus.broadcast).not.toHaveBeenCalled(); expect(mockShakaMessageBus.getCastChannel).toHaveBeenCalledWith( fakeSenderId); - let senderChannel = mockShakaMessageBus.getCastChannel(); + const senderChannel = mockShakaMessageBus.getCastChannel(); expect(senderChannel.messages).toEqual([{ type: 'asyncComplete', id: fakeCallId, error: jasmine.any(Object), }]); if (senderChannel.messages.length) { - let error = senderChannel.messages[0].error; + const error = senderChannel.messages[0].error; shaka.test.Util.expectToEqualError(fakeError, error); } }).catch(fail).then(done); @@ -741,7 +741,7 @@ describe('CastReceiver', function() { }; return Promise.resolve(); }; - let message = { + const message = { // Arbitrary number 'requestId': 0, 'type': 'LOAD', @@ -792,7 +792,7 @@ describe('CastReceiver', function() { }); it('get status', checkAndRun(() => { - let message = { + const message = { // Arbitrary number 'requestId': 0, 'type': 'GET_STATUS', @@ -805,7 +805,7 @@ describe('CastReceiver', function() { })); it('play', checkAndRun(() => { - let message = { + const message = { // Arbitrary number 'requestId': 0, 'type': 'PLAY', @@ -816,7 +816,7 @@ describe('CastReceiver', function() { })); it('pause', checkAndRun(() => { - let message = { + const message = { // Arbitrary number 'requestId': 0, 'type': 'PAUSE', @@ -827,7 +827,7 @@ describe('CastReceiver', function() { })); it('seek', checkAndRun(() => { - let message = { + const message = { // Arbitrary number 'requestId': 0, 'type': 'SEEK', @@ -841,7 +841,7 @@ describe('CastReceiver', function() { })); it('stop', checkAndRun(() => { - let message = { + const message = { // Arbitrary number 'requestId': 0, 'type': 'STOP', @@ -852,7 +852,7 @@ describe('CastReceiver', function() { })); it('volume', checkAndRun(() => { - let message = { + const message = { // Arbitrary number 'requestId': 0, 'type': 'VOLUME', @@ -868,7 +868,7 @@ describe('CastReceiver', function() { })); it('load', checkAndRun(() => { - let message = { + const message = { // Arbitrary number 'requestId': 0, 'type': 'LOAD', @@ -886,7 +886,7 @@ describe('CastReceiver', function() { })); it('dispatches error on unrecognized request type', checkAndRun(() => { - let message = { + const message = { // Arbitrary number 'requestId': 0, 'type': 'UNKNOWN_TYPE', @@ -976,7 +976,7 @@ describe('CastReceiver', function() { } function createMockMessageBus() { - let bus = { + const bus = { messages: [], broadcast: jasmine.createSpy('CastMessageBus.broadcast'), getCastChannel: jasmine.createSpy('CastMessageBus.getCastChannel'), @@ -985,7 +985,7 @@ describe('CastReceiver', function() { bus.broadcast.and.callFake(function(message) { bus.messages.push(CastUtils.deserialize(message)); }); - let channel = { + const channel = { messages: [], send: function(message) { channel.messages.push(CastUtils.deserialize(message)); @@ -996,7 +996,7 @@ describe('CastReceiver', function() { } function createMockPlayer() { - let player = { + const player = { destroy: jasmine.createSpy('destroy').and.returnValue(Promise.resolve()), setMaxHardwareResolution: jasmine.createSpy('setMaxHardwareResolution'), @@ -1014,10 +1014,10 @@ describe('CastReceiver', function() { CastUtils.PlayerVoidMethods.forEach(function(name) { player[name] = jasmine.createSpy(name); }); - for (let name in CastUtils.PlayerGetterMethods) { + for (const name in CastUtils.PlayerGetterMethods) { player[name] = jasmine.createSpy(name); } - for (let name in CastUtils.PlayerGetterMethodsThatRequireLive) { + for (const name in CastUtils.PlayerGetterMethodsThatRequireLive) { player[name] = jasmine.createSpy(name); } CastUtils.PlayerPromiseMethods.forEach(function(name) { @@ -1031,7 +1031,7 @@ describe('CastReceiver', function() { * @param {number} num */ function fakeConnectedSenders(num) { - let senderArray = []; + const senderArray = []; while (num--) { senderArray.push('senderId'); } @@ -1046,8 +1046,8 @@ describe('CastReceiver', function() { * @param {string=} senderId */ function fakeIncomingMessage(message, bus, senderId) { - let serialized = CastUtils.serialize(message); - let messageEvent = { + const serialized = CastUtils.serialize(message); + const messageEvent = { senderId: senderId, data: serialized, }; diff --git a/test/cast/cast_sender_unit.js b/test/cast/cast_sender_unit.js index 740c0ab273..3a6c45743e 100644 --- a/test/cast/cast_sender_unit.js +++ b/test/cast/cast_sender_unit.js @@ -22,8 +22,8 @@ describe('CastSender', function() { const originalChrome = window['chrome']; - let fakeAppId = 'asdf'; - let fakeInitState = { + const fakeAppId = 'asdf'; + const fakeInitState = { manifest: null, player: null, startTime: null, @@ -171,7 +171,7 @@ describe('CastSender', function() { fakeReceiverAvailability(true); expect(sender.hasReceivers()).toBe(true); - let p = sender.cast(fakeInitState); + const p = sender.cast(fakeInitState); fakeSessionConnection(); p.then(function() { @@ -187,7 +187,7 @@ describe('CastSender', function() { // The library is not loaded yet during describe(), so we can't refer to // Shaka error codes by name here. Instead, we use the numeric value and // put the name in a comment. - let connectionFailures = [ + const connectionFailures = [ { condition: 'canceled by the user', castErrorCode: 'cancel', @@ -215,7 +215,7 @@ describe('CastSender', function() { sender.init(); fakeReceiverAvailability(true); - let p = sender.cast(fakeInitState); + const p = sender.cast(fakeInitState); fakeSessionConnectionFailure(metadata.castErrorCode); p.then(fail).catch(function(error) { @@ -229,7 +229,7 @@ describe('CastSender', function() { sender.init(); fakeReceiverAvailability(true); - let p = sender.cast(fakeInitState); + const p = sender.cast(fakeInitState); fakeSessionConnection(); p.catch(fail).then(function() { @@ -244,9 +244,9 @@ describe('CastSender', function() { it('re-uses old sessions', function(done) { sender.init(); fakeReceiverAvailability(true); - let p = sender.cast(fakeInitState); + const p = sender.cast(fakeInitState); fakeSessionConnection(); - let oldMockSession = mockSession; + const oldMockSession = mockSession; p.then(function() { return sender.destroy(); }).then(function() { @@ -282,7 +282,7 @@ describe('CastSender', function() { it('doesn\'t re-use stopped sessions', function(done) { sender.init(); fakeReceiverAvailability(true); - let p = sender.cast(fakeInitState); + const p = sender.cast(fakeInitState); fakeSessionConnection(); p.then(function() { return sender.destroy(); @@ -319,7 +319,7 @@ describe('CastSender', function() { }); describe('setAppData', function() { - let fakeAppData = { + const fakeAppData = { myKey1: 'myValue1', myKey2: 'myValue2', }; @@ -431,7 +431,7 @@ describe('CastSender', function() { sender.init(); fakeReceiverAvailability(true); sender.cast(fakeInitState).then(function() { - let fakeEvent = { + const fakeEvent = { type: 'eventName', detail: {key1: 'value1'}, }; @@ -493,7 +493,7 @@ describe('CastSender', function() { sender.init(); fakeReceiverAvailability(true); sender.cast(fakeInitState).then(function() { - let update = { + const update = { video: { currentTime: 12, paused: false, @@ -535,8 +535,8 @@ describe('CastSender', function() { sender.init(); fakeReceiverAvailability(true); sender.cast(fakeInitState).then(function() { - let method = sender.get('video', 'play'); - let retval = method(123, 'abc'); + const method = sender.get('video', 'play'); + const retval = method(123, 'abc'); expect(retval).toBe(undefined); expect(mockSession.messages).toContain(jasmine.objectContaining({ @@ -563,13 +563,13 @@ describe('CastSender', function() { }); it('return Promises', function() { - let p = method(); + const p = method(); expect(p).toEqual(jasmine.any(Promise)); p.catch(function() {}); // silence logs about uncaught rejections }); it('trigger "asyncCall" messages', function() { - let p = method(123, 'abc'); + const p = method(123, 'abc'); p.catch(function() {}); // silence logs about uncaught rejections expect(mockSession.messages).toContain(jasmine.objectContaining({ @@ -582,12 +582,12 @@ describe('CastSender', function() { }); it('resolve when "asyncComplete" messages are received', function(done) { - let p = new shaka.test.StatusPromise(method(123, 'abc')); + const p = new shaka.test.StatusPromise(method(123, 'abc')); // Wait a tick for the Promise status to be set. Util.delay(0.1).then(function() { expect(p.status).toBe('pending'); - let id = mockSession.messages[mockSession.messages.length - 1].id; + const id = mockSession.messages[mockSession.messages.length - 1].id; fakeSessionMessage({ type: 'asyncComplete', id: id, @@ -602,17 +602,17 @@ describe('CastSender', function() { }); it('reject when "asyncComplete" messages have an error', function(done) { - let originalError = new shaka.util.Error( + const originalError = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.MANIFEST, shaka.util.Error.Code.UNABLE_TO_GUESS_MANIFEST_TYPE, 'foo://bar'); - let p = new shaka.test.StatusPromise(method(123, 'abc')); + const p = new shaka.test.StatusPromise(method(123, 'abc')); // Wait a tick for the Promise status to be set. Util.delay(0.1).then(function() { expect(p.status).toBe('pending'); - let id = mockSession.messages[mockSession.messages.length - 1].id; + const id = mockSession.messages[mockSession.messages.length - 1].id; fakeSessionMessage({ type: 'asyncComplete', id: id, @@ -630,7 +630,7 @@ describe('CastSender', function() { }); it('reject when disconnected remotely', function(done) { - let p = new shaka.test.StatusPromise(method(123, 'abc')); + const p = new shaka.test.StatusPromise(method(123, 'abc')); // Wait a tick for the Promise status to be set. Util.delay(0.1).then(function() { @@ -657,7 +657,7 @@ describe('CastSender', function() { sender.init(); fakeReceiverAvailability(true); sender.cast(fakeInitState).then(function() { - let update = { + const update = { video: {muted: false}, }; fakeSessionMessage({ @@ -727,8 +727,8 @@ describe('CastSender', function() { expect(mockSession.removeUpdateListener).not.toHaveBeenCalled(); expect(mockSession.removeMessageListener).not.toHaveBeenCalled(); - let method = sender.get('player', 'load'); - let p = new shaka.test.StatusPromise(method()); + const method = sender.get('player', 'load'); + const p = new shaka.test.StatusPromise(method()); // Wait a tick for the Promise status to be set. return Util.delay(0.1).then(function() { @@ -765,8 +765,8 @@ describe('CastSender', function() { expect(mockSession.removeUpdateListener).not.toHaveBeenCalled(); expect(mockSession.removeMessageListener).not.toHaveBeenCalled(); - let method = sender.get('player', 'load'); - let p = new shaka.test.StatusPromise(method()); + const method = sender.get('player', 'load'); + const p = new shaka.test.StatusPromise(method()); // Wait a tick for the Promise status to be set. return Util.delay(0.1).then(function() { @@ -805,7 +805,7 @@ describe('CastSender', function() { } function createMockCastSession() { - let session = { + const session = { messages: [], status: 'connected', receiver: {friendlyName: 'SomeDevice'}, @@ -830,19 +830,19 @@ describe('CastSender', function() { * @param {boolean} yes If true, simulate receivers being available. */ function fakeReceiverAvailability(yes) { - let calls = mockCastApi.ApiConfig.calls; + const calls = mockCastApi.ApiConfig.calls; expect(calls.count()).toEqual(1); if (calls.count()) { - let onReceiverStatusChanged = calls.argsFor(0)[2]; + const onReceiverStatusChanged = calls.argsFor(0)[2]; onReceiverStatusChanged(yes ? 'available' : 'unavailable'); } } function fakeSessionConnection() { - let calls = mockCastApi.requestSession.calls; + const calls = mockCastApi.requestSession.calls; expect(calls.count()).toEqual(1); if (calls.count()) { - let onSessionInitiated = calls.argsFor(0)[0]; + const onSessionInitiated = calls.argsFor(0)[0]; mockSession = createMockCastSession(); onSessionInitiated(mockSession); } @@ -852,10 +852,10 @@ describe('CastSender', function() { * @param {string} code */ function fakeSessionConnectionFailure(code) { - let calls = mockCastApi.requestSession.calls; + const calls = mockCastApi.requestSession.calls; expect(calls.count()).toEqual(1); if (calls.count()) { - let onSessionError = calls.argsFor(0)[1]; + const onSessionError = calls.argsFor(0)[1]; onSessionError({code: code}); } } @@ -864,31 +864,31 @@ describe('CastSender', function() { * @param {?} message */ function fakeSessionMessage(message) { - let calls = mockSession.addMessageListener.calls; + const calls = mockSession.addMessageListener.calls; expect(calls.count()).toEqual(1); if (calls.count()) { - let namespace = calls.argsFor(0)[0]; - let listener = calls.argsFor(0)[1]; - let serialized = CastUtils.serialize(message); + const namespace = calls.argsFor(0)[0]; + const listener = calls.argsFor(0)[1]; + const serialized = CastUtils.serialize(message); listener(namespace, serialized); } } function fakeRemoteDisconnect() { mockSession.status = 'disconnected'; - let calls = mockSession.addUpdateListener.calls; + const calls = mockSession.addUpdateListener.calls; expect(calls.count()).toEqual(1); if (calls.count()) { - let onConnectionStatus = calls.argsFor(0)[0]; + const onConnectionStatus = calls.argsFor(0)[0]; onConnectionStatus(); } } function fakeJoinExistingSession() { - let calls = mockCastApi.ApiConfig.calls; + const calls = mockCastApi.ApiConfig.calls; expect(calls.count()).toEqual(1); if (calls.count()) { - let onJoinExistingSession = calls.argsFor(0)[1]; + const onJoinExistingSession = calls.argsFor(0)[1]; mockSession = createMockCastSession(); onJoinExistingSession(mockSession); } diff --git a/test/cast/cast_utils_unit.js b/test/cast/cast_utils_unit.js index b7de28490c..e787072544 100644 --- a/test/cast/cast_utils_unit.js +++ b/test/cast/cast_utils_unit.js @@ -20,7 +20,7 @@ describe('CastUtils', function() { const FakeEvent = shaka.util.FakeEvent; it('includes every Player member', function() { - let ignoredMembers = [ + const ignoredMembers = [ 'constructor', // JavaScript added field 'getSharedConfiguration', // Handled specially 'getNetworkingEngine', // Handled specially @@ -42,15 +42,15 @@ describe('CastUtils', function() { 'createStreamingEngine', ]; - let castMembers = CastUtils.PlayerVoidMethods + const castMembers = CastUtils.PlayerVoidMethods .concat(CastUtils.PlayerPromiseMethods); - for (let name in CastUtils.PlayerGetterMethods) { + for (const name in CastUtils.PlayerGetterMethods) { castMembers.push(name); } - for (let name in CastUtils.PlayerGetterMethodsThatRequireLive) { + for (const name in CastUtils.PlayerGetterMethodsThatRequireLive) { castMembers.push(name); } - let playerMembers = Object.keys(shaka.Player.prototype).filter( + const playerMembers = Object.keys(shaka.Player.prototype).filter( function(name) { // Private members end with _. return !ignoredMembers.includes(name) && !name.endsWith('_'); @@ -58,10 +58,10 @@ describe('CastUtils', function() { // To make debugging easier, don't check that they are equal; instead check // that neither has any extra entries. - let extraCastMembers = castMembers.filter(function(name) { + const extraCastMembers = castMembers.filter(function(name) { return !playerMembers.includes(name); }); - let extraPlayerMembers = playerMembers.filter(function(name) { + const extraPlayerMembers = playerMembers.filter(function(name) { return !castMembers.includes(name); }); expect(extraCastMembers).toEqual([]); @@ -70,7 +70,7 @@ describe('CastUtils', function() { describe('serialize/deserialize', function() { it('transfers infinite values and NaN', function() { - let orig = { + const orig = { 'nan': NaN, 'positive_infinity': Infinity, 'negative_infinity': -Infinity, @@ -81,89 +81,89 @@ describe('CastUtils', function() { 'string': 'a string', }; - let serialized = CastUtils.serialize(orig); + const serialized = CastUtils.serialize(orig); // The object is turned into a string. expect(typeof serialized).toBe('string'); // The deserialized object matches the original. - let deserialized = CastUtils.deserialize(serialized); - for (let k in orig) { + const deserialized = CastUtils.deserialize(serialized); + for (const k in orig) { expect(deserialized[k]).toEqual(orig[k]); } }); it('transfers real Events', function() { // new Event() is not usable on IE11: - let event = + const event = /** @type {!CustomEvent} */ (document.createEvent('CustomEvent')); event.initCustomEvent('myEventType', false, false, null); // Properties that can definitely be transferred. - let nativeProperties = [ + const nativeProperties = [ 'bubbles', 'type', 'cancelable', 'defaultPrevented', ]; - let extraProperties = { + const extraProperties = { 'key': 'value', 'true': true, 'one': 1, }; - for (let k in extraProperties) { + for (const k in extraProperties) { event[k] = extraProperties[k]; } // The event is turned into a string. - let serialized = CastUtils.serialize(event); + const serialized = CastUtils.serialize(event); expect(typeof serialized).toBe('string'); // The string is turned back into an object. - let deserialized = CastUtils.deserialize(serialized); + const deserialized = CastUtils.deserialize(serialized); expect(typeof deserialized).toBe('object'); // The object can be used to construct a FakeEvent. - let fakeEvent = new FakeEvent(deserialized['type'], deserialized); + const fakeEvent = new FakeEvent(deserialized['type'], deserialized); // The fake event has the same type and properties as the original. nativeProperties.forEach(function(k) { expect(fakeEvent[k]).toEqual(event[k]); }); - for (let k in extraProperties) { + for (const k in extraProperties) { expect(fakeEvent[k]).toEqual(event[k]); } }); it('transfers dispatched FakeEvents', function(done) { - let event = new FakeEvent('custom'); + const event = new FakeEvent('custom'); // Properties that can definitely be transferred. - let nativeProperties = [ + const nativeProperties = [ 'bubbles', 'type', 'cancelable', 'defaultPrevented', ]; - let extraProperties = { + const extraProperties = { 'key': 'value', 'true': true, 'one': 1, }; - for (let k in extraProperties) { + for (const k in extraProperties) { event[k] = extraProperties[k]; } - let target = new shaka.util.FakeEventTarget(); + const target = new shaka.util.FakeEventTarget(); target.addEventListener(event.type, function() { try { // The event is turned into a string. - let serialized = CastUtils.serialize(event); + const serialized = CastUtils.serialize(event); expect(typeof serialized).toBe('string'); // The string is turned back into an object. - let deserialized = CastUtils.deserialize(serialized); + const deserialized = CastUtils.deserialize(serialized); expect(typeof deserialized).toBe('object'); // The deserialized event has the same type and properties as the @@ -171,7 +171,7 @@ describe('CastUtils', function() { nativeProperties.forEach(function(k) { expect(deserialized[k]).toEqual(event[k]); }); - for (let k in extraProperties) { + for (const k in extraProperties) { expect(deserialized[k]).toEqual(event[k]); } } catch (exception) { @@ -198,12 +198,13 @@ describe('CastUtils', function() { beforeEach(function(done) { // The TimeRanges constructor cannot be used directly, so we load a clip // to get ranges to use. - let fakeVideoStream = { + const fakeVideoStream = { mimeType: 'video/mp4', codecs: 'avc1.42c01e', }; - let initSegmentUrl = '/base/test/test/assets/sintel-video-init.mp4'; - let videoSegmentUrl = '/base/test/test/assets/sintel-video-segment.mp4'; + const initSegmentUrl = '/base/test/test/assets/sintel-video-init.mp4'; + const videoSegmentUrl = + '/base/test/test/assets/sintel-video-segment.mp4'; // Wait for the media source to be open. eventManager = new shaka.util.EventManager(); @@ -252,17 +253,17 @@ describe('CastUtils', function() { }); quarantinedIt('deserialize into equivalent objects', function() { - let buffered = video.buffered; + const buffered = video.buffered; // The test is less interesting if the ranges are empty. expect(buffered.length).toBeGreaterThan(0); // The TimeRanges object is turned into a string. - let serialized = CastUtils.serialize(buffered); + const serialized = CastUtils.serialize(buffered); expect(typeof serialized).toBe('string'); // Expect the deserialized version to look like the original. - let deserialized = CastUtils.deserialize(serialized); + const deserialized = CastUtils.deserialize(serialized); expect(deserialized.length).toEqual(buffered.length); expect(deserialized.start).toEqual(jasmine.any(Function)); expect(deserialized.end).toEqual(jasmine.any(Function)); diff --git a/test/dash/dash_parser_content_protection_unit.js b/test/dash/dash_parser_content_protection_unit.js index 836881afbc..5590c3b57d 100644 --- a/test/dash/dash_parser_content_protection_unit.js +++ b/test/dash/dash_parser_content_protection_unit.js @@ -31,9 +31,9 @@ describe('DashParser ContentProtection', function() { */ function testDashParser(manifestText, expected, callback, ignoreDrmInfo = false) { - let netEngine = new shaka.test.FakeNetworkingEngine(); + const netEngine = new shaka.test.FakeNetworkingEngine(); netEngine.setDefaultText(manifestText); - let dashParser = new shaka.dash.DashParser(); + const dashParser = new shaka.dash.DashParser(); const config = shaka.util.PlayerConfiguration.createDefault().manifest; config.dash.ignoreDrmInfo = ignoreDrmInfo; @@ -42,7 +42,7 @@ describe('DashParser ContentProtection', function() { } dashParser.configure(config); - let playerEvents = { + const playerEvents = { networkingEngine: netEngine, filterNewPeriod: function() {}, filterAllPeriods: function() {}, @@ -66,7 +66,7 @@ describe('DashParser ContentProtection', function() { */ function buildManifestText( adaptationSetLines, representation1Lines, representation2Lines) { - let template = [ + const template = [ '<MPD xmlns="urn:mpeg:DASH:schema:MPD:2011"', ' xmlns:cenc="urn:mpeg:cenc:2013">', ' <Period duration="PT30S">', @@ -103,9 +103,9 @@ describe('DashParser ContentProtection', function() { keyIds = drmInfos[0].sample.keyIds; } - let variants = []; + const variants = []; for (let i = 0; i < numVariants; i++) { - let variant = jasmine.objectContaining({ + const variant = jasmine.objectContaining({ drmInfos: drmInfos, video: jasmine.objectContaining({ keyId: keyIds[i] || null, @@ -135,22 +135,23 @@ describe('DashParser ContentProtection', function() { */ function buildDrmInfo(keySystem, keyIds = [], base64Psshs = [], initDataKeyIds) { - let initData = base64Psshs.map(function(base64, index) { + const initData = base64Psshs.map(function(base64, index) { /** @type {shaka.extern.InitDataOverride} */ - let initData = { + const initData = { initDataType: 'cenc', initData: shaka.util.Uint8ArrayUtils.fromBase64(base64), keyId: initDataKeyIds ? initDataKeyIds[index] : null, }; return initData; }); - let containing = {keySystem: keySystem, initData: initData, keyIds: keyIds}; + const containing = + {keySystem: keySystem, initData: initData, keyIds: keyIds}; return jasmine.objectContaining(containing); } it('handles clear content', async () => { - let source = buildManifestText([], [], []); - let expected = buildExpectedManifest([]); + const source = buildManifestText([], [], []); + const expected = buildExpectedManifest([]); await testDashParser(source, expected); }); @@ -162,15 +163,15 @@ describe('DashParser ContentProtection', function() { */ function testKeySystemMappings(name, uuids, keySystems) { it(name, async () => { - let adaptationSetLines = uuids.map(function(uri) { + const adaptationSetLines = uuids.map(function(uri) { return sprintf('<ContentProtection schemeIdUri="urn:uuid:%s" />', uri); }); - let source = buildManifestText(adaptationSetLines, [], []); - let drmInfos = keySystems.map(function(keySystem) { + const source = buildManifestText(adaptationSetLines, [], []); + const drmInfos = keySystems.map(function(keySystem) { return buildDrmInfo(keySystem); }); - let expected = buildExpectedManifest(drmInfos); + const expected = buildExpectedManifest(drmInfos); await testDashParser(source, expected); }); } @@ -204,7 +205,7 @@ describe('DashParser ContentProtection', function() { }); it('inherits key IDs from AdaptationSet to Representation', async () => { - let source = buildManifestText([ + const source = buildManifestText([ // AdaptationSet lines '<ContentProtection', ' schemeIdUri="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed" />', @@ -212,7 +213,7 @@ describe('DashParser ContentProtection', function() { ' schemeIdUri="urn:mpeg:dash:mp4protection:2011" value="cenc"', ' cenc:default_KID="DEADBEEF-FEED-BAAD-F00D-000008675309" />', ], [], []); - let expected = buildExpectedManifest([ + const expected = buildExpectedManifest([ buildDrmInfo('com.widevine.alpha', [ // Representation 1 key ID 'deadbeeffeedbaadf00d000008675309', @@ -224,7 +225,7 @@ describe('DashParser ContentProtection', function() { }); it('sets key IDs for the init data', async () => { - let source = buildManifestText([ + const source = buildManifestText([ // AdaptationSet lines ], [ // Representation 1 lines @@ -236,7 +237,7 @@ describe('DashParser ContentProtection', function() { '</ContentProtection>', ], []); - let expected = buildExpectedManifest([ + const expected = buildExpectedManifest([ buildDrmInfo('com.widevine.alpha', ['deadbeeffeedbaadf00d000008675309'], // key Id ['bm8gaHVtYW4gY2FuIHJlYWQgYmFzZTY0IGRpcmVjdGx5'], // initData @@ -246,7 +247,7 @@ describe('DashParser ContentProtection', function() { }); it('lets Representations override key IDs', async () => { - let source = buildManifestText([ + const source = buildManifestText([ // AdaptationSet lines '<ContentProtection', ' schemeIdUri="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed" />', @@ -264,7 +265,7 @@ describe('DashParser ContentProtection', function() { ' schemeIdUri="urn:mpeg:dash:mp4protection:2011" value="cenc"', ' cenc:default_KID="BAADF00D-FEED-DEAF-BEEF-018006492568" />', ]); - let expected = buildExpectedManifest([ + const expected = buildExpectedManifest([ buildDrmInfo('com.widevine.alpha', [ // Representation 1 key ID 'baadf00dfeeddeafbeef000004390116', @@ -276,7 +277,7 @@ describe('DashParser ContentProtection', function() { }); it('extracts embedded PSSHs', async () => { - let source = buildManifestText([ + const source = buildManifestText([ // AdaptationSet lines '<ContentProtection', ' schemeIdUri="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed">', @@ -287,7 +288,7 @@ describe('DashParser ContentProtection', function() { ' <cenc:pssh>bm8gaHVtYW4gY2FuIHJlYWQgYmFzZTY0IGRpcmVjdGx5</cenc:pssh>', '</ContentProtection>', ], [], []); - let expected = buildExpectedManifest([ + const expected = buildExpectedManifest([ buildDrmInfo('com.widevine.alpha', [], [ 'ZmFrZSBXaWRldmluZSBQU1NI', ]), @@ -299,12 +300,12 @@ describe('DashParser ContentProtection', function() { }); it('assumes all known key systems for generic CENC', async () => { - let source = buildManifestText([ + const source = buildManifestText([ // AdaptationSet lines '<ContentProtection', ' schemeIdUri="urn:mpeg:dash:mp4protection:2011" value="cenc" />', ], [], []); - let expected = buildExpectedManifest( + const expected = buildExpectedManifest( // The order does not matter here, so use arrayContaining. /** @type {!Array.<!Object>} */(jasmine.arrayContaining([ buildDrmInfo('com.widevine.alpha'), @@ -315,7 +316,7 @@ describe('DashParser ContentProtection', function() { }); it('assumes all known key systems when ignoreDrmInfo is set', async () => { - let source = buildManifestText([ + const source = buildManifestText([ // AdaptationSet lines '<ContentProtection', ' schemeIdUri="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed">', @@ -328,7 +329,7 @@ describe('DashParser ContentProtection', function() { ], [], []); - let expected = buildExpectedManifest( + const expected = buildExpectedManifest( // The order does not matter here, so use arrayContaining. // NOTE: the buildDrmInfo calls here specify no init data /** @type {!Array.<!Object>} */(jasmine.arrayContaining([ @@ -341,7 +342,7 @@ describe('DashParser ContentProtection', function() { }); it('parses key IDs when ignoreDrmInfo flag is set', async () => { - let source = buildManifestText([ + const source = buildManifestText([ // AdaptationSet lines '<ContentProtection', ' schemeIdUri="urn:uuid:9a04f079-9840-4286-ab92-e65be0885f95"', @@ -350,14 +351,14 @@ describe('DashParser ContentProtection', function() { ' schemeIdUri="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"', ' cenc:default_KID="DEADBEEF-FEED-BAAD-F00D-000008675309" />', ], [], []); - let keyIds = [ + const keyIds = [ // Representation 1 key ID 'deadbeeffeedbaadf00d000008675309', // Representation 2 key ID 'deadbeeffeedbaadf00d000008675309', ]; - let expected = buildExpectedManifest( + const expected = buildExpectedManifest( [ buildDrmInfo('com.widevine.alpha', keyIds), buildDrmInfo('com.microsoft.playready', keyIds), @@ -368,7 +369,7 @@ describe('DashParser ContentProtection', function() { }); it('inherits PSSH from generic CENC into all key systems', async () => { - let source = buildManifestText([ + const source = buildManifestText([ // AdaptationSet lines '<ContentProtection', ' schemeIdUri="urn:mpeg:dash:mp4protection:2011" value="cenc">', @@ -379,7 +380,7 @@ describe('DashParser ContentProtection', function() { '<ContentProtection', ' schemeIdUri="urn:uuid:9a04f079-9840-4286-ab92-e65be0885f95" />', ], [], []); - let expected = buildExpectedManifest([ + const expected = buildExpectedManifest([ buildDrmInfo('com.widevine.alpha', [], [ 'b25lIGhlYWRlciB0byBydWxlIHRoZW0gYWxs', ]), @@ -391,7 +392,7 @@ describe('DashParser ContentProtection', function() { }); it('lets key systems override generic PSSH', async () => { - let source = buildManifestText([ + const source = buildManifestText([ // AdaptationSet lines '<ContentProtection', ' schemeIdUri="urn:mpeg:dash:mp4protection:2011" value="cenc">', @@ -406,7 +407,7 @@ describe('DashParser ContentProtection', function() { '<ContentProtection', ' schemeIdUri="urn:uuid:9a04f079-9840-4286-ab92-e65be0885f95" />', ], [], []); - let expected = buildExpectedManifest([ + const expected = buildExpectedManifest([ buildDrmInfo('com.widevine.alpha', [], [ 'VGltZSBpcyBhbiBpbGx1c2lvbi4gTHVuY2h0aW1lIGRvdWJseSBzby4=', ]), @@ -418,7 +419,7 @@ describe('DashParser ContentProtection', function() { }); it('ignores custom or unknown schemes', async () => { - let source = buildManifestText([ + const source = buildManifestText([ // AdaptationSet lines '<ContentProtection', ' schemeIdUri="urn:uuid:feedbaad-f00d-2bee-baad-d00d00000000" />', @@ -427,14 +428,14 @@ describe('DashParser ContentProtection', function() { '<ContentProtection', ' schemeIdUri="http://example.com/drm" />', ], [], []); - let expected = buildExpectedManifest([ + const expected = buildExpectedManifest([ buildDrmInfo('com.widevine.alpha'), ]); await testDashParser(source, expected); }); it('invokes a callback for unknown schemes', async () => { - let source = buildManifestText([ + const source = buildManifestText([ // AdaptationSet lines '<ContentProtection', ' schemeIdUri="urn:uuid:feedbaad-f00d-2bee-baad-d00d00000000" />', @@ -448,8 +449,8 @@ describe('DashParser ContentProtection', function() { * @param {!Element} contentProtection * @return {Array.<shaka.extern.DrmInfo>} */ - let callback = function(contentProtection) { - let schemeIdUri = contentProtection.getAttribute('schemeIdUri'); + const callback = function(contentProtection) { + const schemeIdUri = contentProtection.getAttribute('schemeIdUri'); if (schemeIdUri == 'urn:uuid:feedbaad-f00d-2bee-baad-d00d00000000') { return [{ keySystem: 'com.custom.baadd00d', @@ -479,7 +480,7 @@ describe('DashParser ContentProtection', function() { } }; - let expected = buildExpectedManifest([ + const expected = buildExpectedManifest([ buildDrmInfo('com.custom.baadd00d'), buildDrmInfo('com.widevine.alpha'), buildDrmInfo('com.example.drm'), @@ -489,7 +490,7 @@ describe('DashParser ContentProtection', function() { }); it('inserts a placeholder for unrecognized schemes', async () => { - let source = buildManifestText([ + const source = buildManifestText([ // AdaptationSet lines '<ContentProtection', ' schemeIdUri="urn:uuid:feedbaad-f00d-2bee-baad-d00d00000000" />', @@ -499,7 +500,7 @@ describe('DashParser ContentProtection', function() { ' schemeIdUri="urn:mpeg:dash:mp4protection:2011" value="cenc"', ' cenc:default_KID="DEADBEEF-FEED-BAAD-F00D-000008675309" />', ], [], []); - let expected = buildExpectedManifest([ + const expected = buildExpectedManifest([ buildDrmInfo('', // placeholder: only unrecognized schemes found [ // Representation 1 key ID @@ -512,7 +513,7 @@ describe('DashParser ContentProtection', function() { }); it('can specify ContentProtection in Representation only', async () => { - let source = buildManifestText([ + const source = buildManifestText([ // AdaptationSet lines ], [ // Representation 1 lines @@ -523,13 +524,13 @@ describe('DashParser ContentProtection', function() { '<ContentProtection', ' schemeIdUri="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed" />', ]); - let expected = buildExpectedManifest( + const expected = buildExpectedManifest( [buildDrmInfo('com.widevine.alpha')]); await testDashParser(source, expected); }); it('only keeps key systems common to all Representations', async () => { - let source = buildManifestText([ + const source = buildManifestText([ // AdaptationSet lines ], [ // Representation 1 lines @@ -542,13 +543,13 @@ describe('DashParser ContentProtection', function() { '<ContentProtection', ' schemeIdUri="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed" />', ]); - let expected = buildExpectedManifest( + const expected = buildExpectedManifest( [buildDrmInfo('com.widevine.alpha')]); await testDashParser(source, expected); }); it('still keeps per-Representation key IDs when merging', async () => { - let source = buildManifestText([ + const source = buildManifestText([ // AdaptationSet lines ], [ // Representation 1 lines @@ -565,7 +566,7 @@ describe('DashParser ContentProtection', function() { ' schemeIdUri="urn:mpeg:dash:mp4protection:2011" value="cenc"', ' cenc:default_KID="BAADF00D-FEED-DEAF-BEEF-000004390116" />', ]); - let expected = buildExpectedManifest([ + const expected = buildExpectedManifest([ buildDrmInfo('com.widevine.alpha', [ // Representation 1 key ID 'deadbeeffeedbaadf00d000008675309', @@ -577,7 +578,7 @@ describe('DashParser ContentProtection', function() { }); it('parses key IDs from non-cenc in Representation', async () => { - let source = buildManifestText([ + const source = buildManifestText([ // AdaptationSet lines ], [ // Representation 1 lines @@ -596,13 +597,13 @@ describe('DashParser ContentProtection', function() { ' schemeIdUri="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"', ' cenc:default_KID="BAADF00D-FEED-DEAF-BEEF-000004390116" />', ]); - let keyIds = [ + const keyIds = [ // Representation 1 key ID 'deadbeeffeedbaadf00d000008675309', // Representation 2 key ID 'baadf00dfeeddeafbeef000004390116', ]; - let expected = buildExpectedManifest( + const expected = buildExpectedManifest( [ buildDrmInfo('com.microsoft.playready', keyIds), buildDrmInfo('com.widevine.alpha', keyIds), @@ -611,7 +612,7 @@ describe('DashParser ContentProtection', function() { }); it('parses key IDs from non-cenc in AdaptationSet', async () => { - let source = buildManifestText([ + const source = buildManifestText([ // AdaptationSet lines '<ContentProtection', ' schemeIdUri="urn:uuid:9a04f079-9840-4286-ab92-e65be0885f95"', @@ -620,13 +621,13 @@ describe('DashParser ContentProtection', function() { ' schemeIdUri="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"', ' cenc:default_KID="DEADBEEF-FEED-BAAD-F00D-000008675309" />', ], [], []); - let keyIds = [ + const keyIds = [ // Representation 1 key ID 'deadbeeffeedbaadf00d000008675309', // Representation 2 key ID 'deadbeeffeedbaadf00d000008675309', ]; - let expected = buildExpectedManifest( + const expected = buildExpectedManifest( [ buildDrmInfo('com.microsoft.playready', keyIds), buildDrmInfo('com.widevine.alpha', keyIds), @@ -635,19 +636,19 @@ describe('DashParser ContentProtection', function() { }); it('ignores elements missing @schemeIdUri', async () => { - let source = buildManifestText([ + const source = buildManifestText([ // AdaptationSet lines '<ContentProtection />', '<ContentProtection', ' schemeIdUri="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed" />', ], [], []); - let expected = buildExpectedManifest( + const expected = buildExpectedManifest( [buildDrmInfo('com.widevine.alpha')]); await testDashParser(source, expected); }); it('handles non-default namespace names', async () => { - let source = [ + const source = [ '<MPD xmlns="urn:mpeg:DASH:schema:MPD:2011"', ' xmlns:foo="urn:mpeg:cenc:2013">', ' <Period duration="PT30S">', @@ -663,13 +664,13 @@ describe('DashParser ContentProtection', function() { ' </Period>', '</MPD>', ].join('\n'); - let expected = buildExpectedManifest([buildDrmInfo( + const expected = buildExpectedManifest([buildDrmInfo( 'com.widevine.alpha', [], ['b25lIGhlYWRlciB0byBydWxlIHRoZW0gYWxs'])]); await testDashParser(source, expected); }); it('fails for no schemes common', async () => { - let source = buildManifestText([ + const source = buildManifestText([ // AdaptationSet lines ], [ // Representation 1 lines @@ -680,7 +681,7 @@ describe('DashParser ContentProtection', function() { '<ContentProtection', ' schemeIdUri="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed" />', ]); - let expected = new shaka.util.Error( + const expected = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.MANIFEST, shaka.util.Error.Code.DASH_NO_COMMON_KEY_SYSTEM); @@ -688,14 +689,14 @@ describe('DashParser ContentProtection', function() { }); it('fails for invalid PSSH encoding', async () => { - let source = buildManifestText([ + const source = buildManifestText([ // AdaptationSet lines '<ContentProtection', ' schemeIdUri="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed">', ' <cenc:pssh>foobar!</cenc:pssh>', '</ContentProtection>', ], [], []); - let expected = new shaka.util.Error( + const expected = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.MANIFEST, shaka.util.Error.Code.DASH_PSSH_BAD_ENCODING); @@ -703,7 +704,7 @@ describe('DashParser ContentProtection', function() { }); it('fails for conflicting default key IDs', async () => { - let source = buildManifestText([ + const source = buildManifestText([ // AdaptationSet lines '<ContentProtection', ' schemeIdUri="urn:uuid:9a04f079-9840-4286-ab92-e65be0885f95"', @@ -712,7 +713,7 @@ describe('DashParser ContentProtection', function() { ' schemeIdUri="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"', ' cenc:default_KID="BAADF00D-FEED-DEAF-BEEF-000004390116" />', ], [], []); - let expected = new shaka.util.Error( + const expected = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.MANIFEST, shaka.util.Error.Code.DASH_CONFLICTING_KEY_IDS); @@ -720,7 +721,7 @@ describe('DashParser ContentProtection', function() { }); it('fails for multiple key IDs', async () => { - let source = buildManifestText([ + const source = buildManifestText([ // AdaptationSet lines '<ContentProtection', ' schemeIdUri="urn:mpeg:dash:mp4protection:2011" value="cenc"', @@ -728,7 +729,7 @@ describe('DashParser ContentProtection', function() { '<ContentProtection', ' schemeIdUri="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed" />', ], [], []); - let expected = new shaka.util.Error( + const expected = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.MANIFEST, shaka.util.Error.Code.DASH_MULTIPLE_KEY_IDS_NOT_SUPPORTED); diff --git a/test/dash/dash_parser_live_unit.js b/test/dash/dash_parser_live_unit.js index ad3e4a6003..72bdff99be 100644 --- a/test/dash/dash_parser_live_unit.js +++ b/test/dash/dash_parser_live_unit.js @@ -86,11 +86,11 @@ describe('DashParser Live', function() { * @return {string} */ function makeSimpleLiveManifestText(lines, updateTime, duration) { - let updateAttr = updateTime != null ? + const updateAttr = updateTime != null ? 'minimumUpdatePeriod="PT' + updateTime + 'S"' : ''; - let durationAttr = duration != undefined ? + const durationAttr = duration != undefined ? 'duration="PT' + duration + 'S"' : ''; - let template = [ + const template = [ '<MPD type="dynamic" %(updateAttr)s', ' availabilityStartTime="1970-01-01T00:00:00Z">', ' <Period id="1" %(durationAttr)s>', @@ -103,7 +103,7 @@ describe('DashParser Live', function() { ' </Period>', '</MPD>', ].join('\n'); - let text = sprintf(template, { + const text = sprintf(template, { updateAttr: updateAttr, durationAttr: durationAttr, contents: lines.join('\n'), @@ -139,13 +139,14 @@ describe('DashParser Live', function() { */ function testBasicUpdate( done, firstLines, firstReferences, secondLines, secondReferences) { - let firstManifest = makeSimpleLiveManifestText(firstLines, updateTime); - let secondManifest = makeSimpleLiveManifestText(secondLines, updateTime); + const firstManifest = makeSimpleLiveManifestText(firstLines, updateTime); + const secondManifest = + makeSimpleLiveManifestText(secondLines, updateTime); fakeNetEngine.setResponseText('dummy://foo', firstManifest); parser.start('dummy://foo', playerInterface) .then(function(manifest) { - let stream = manifest.periods[0].variants[0].video; + const stream = manifest.periods[0].variants[0].video; ManifestParser.verifySegmentIndex(stream, firstReferences); expect(manifest.periods.length).toBe(1); @@ -170,7 +171,7 @@ describe('DashParser Live', function() { }); it('evicts old references for single-period live stream', function(done) { - let template = [ + const template = [ '<MPD type="dynamic" minimumUpdatePeriod="PT%(updateTime)dS"', ' timeShiftBufferDepth="PT30S"', ' suggestedPresentationDelay="PT5S"', @@ -185,7 +186,7 @@ describe('DashParser Live', function() { ' </Period>', '</MPD>', ].join('\n'); - let text = sprintf( + const text = sprintf( template, {updateTime: updateTime, contents: basicLines.join('\n')}); fakeNetEngine.setResponseText('dummy://foo', text); @@ -193,7 +194,7 @@ describe('DashParser Live', function() { parser.start('dummy://foo', playerInterface) .then(function(manifest) { expect(manifest).toBeTruthy(); - let stream = manifest.periods[0].variants[0].video; + const stream = manifest.periods[0].variants[0].video; expect(stream).toBeTruthy(); expect(stream.findSegmentPosition).toBeTruthy(); @@ -215,7 +216,7 @@ describe('DashParser Live', function() { }); it('evicts old references for multi-period live stream', function(done) { - let template = [ + const template = [ '<MPD type="dynamic" minimumUpdatePeriod="PT%(updateTime)dS"', ' timeShiftBufferDepth="PT60S"', ' suggestedPresentationDelay="PT5S"', @@ -240,21 +241,23 @@ describe('DashParser Live', function() { ].join('\n'); // Set the period start to the sum of the durations of the references // in the previous period. - let durs = basicRefs.map(function(r) { return r.endTime - r.startTime; }); - let pStart = durs.reduce(function(p, d) { return p + d; }, 0); - let args = { + const durs = basicRefs.map(function(r) { + return r.endTime - r.startTime; + }); + const pStart = durs.reduce(function(p, d) { return p + d; }, 0); + const args = { updateTime: updateTime, pStart: pStart, contents: basicLines.join('\n'), }; - let text = sprintf(template, args); + const text = sprintf(template, args); fakeNetEngine.setResponseText('dummy://foo', text); Date.now = function() { return 0; }; parser.start('dummy://foo', playerInterface) .then(function(manifest) { - let stream1 = manifest.periods[0].variants[0].video; - let stream2 = manifest.periods[1].variants[0].video; + const stream1 = manifest.periods[0].variants[0].video; + const stream2 = manifest.periods[1].variants[0].video; ManifestParser.verifySegmentIndex(stream1, basicRefs); ManifestParser.verifySegmentIndex(stream2, basicRefs); @@ -279,7 +282,7 @@ describe('DashParser Live', function() { }); it('sets infinite duration for single-period live streams', function(done) { - let template = [ + const template = [ '<MPD type="dynamic" minimumUpdatePeriod="PT%(updateTime)dS"', ' timeShiftBufferDepth="PT1S"', ' suggestedPresentationDelay="PT5S"', @@ -294,7 +297,7 @@ describe('DashParser Live', function() { ' </Period>', '</MPD>', ].join('\n'); - let text = sprintf( + const text = sprintf( template, {updateTime: updateTime, contents: basicLines.join('\n')}); fakeNetEngine.setResponseText('dummy://foo', text); @@ -302,14 +305,14 @@ describe('DashParser Live', function() { parser.start('dummy://foo', playerInterface) .then(function(manifest) { expect(manifest.periods.length).toBe(1); - let timeline = manifest.presentationTimeline; + const timeline = manifest.presentationTimeline; expect(timeline.getDuration()).toBe(Infinity); }).catch(fail).then(done); PromiseMock.flush(); }); it('sets infinite duration for multi-period live streams', function(done) { - let template = [ + const template = [ '<MPD type="dynamic" minimumUpdatePeriod="PT%(updateTime)dS"', ' timeShiftBufferDepth="PT1S"', ' suggestedPresentationDelay="PT5S"', @@ -332,7 +335,7 @@ describe('DashParser Live', function() { ' </Period>', '</MPD>', ].join('\n'); - let text = sprintf( + const text = sprintf( template, {updateTime: updateTime, contents: basicLines.join('\n')}); fakeNetEngine.setResponseText('dummy://foo', text); @@ -341,7 +344,7 @@ describe('DashParser Live', function() { .then(function(manifest) { expect(manifest.periods.length).toBe(2); expect(manifest.periods[1].startTime).toBe(60); - let timeline = manifest.presentationTimeline; + const timeline = manifest.presentationTimeline; expect(timeline.getDuration()).toBe(Infinity); }).catch(fail).then(done); PromiseMock.flush(); @@ -349,10 +352,10 @@ describe('DashParser Live', function() { } it('can add Periods', function(done) { - let lines = [ + const lines = [ '<SegmentTemplate startNumber="1" media="s$Number$.mp4" duration="2" />', ]; - let template = [ + const template = [ '<MPD type="dynamic" availabilityStartTime="1970-01-01T00:00:00Z"', ' suggestedPresentationDelay="PT5S"', ' minimumUpdatePeriod="PT%(updateTime)dS">', @@ -366,14 +369,14 @@ describe('DashParser Live', function() { ' </Period>', '</MPD>', ].join('\n'); - let secondManifest = + const secondManifest = sprintf(template, {updateTime: updateTime, contents: lines.join('\n')}); - let firstManifest = makeSimpleLiveManifestText(lines, updateTime); + const firstManifest = makeSimpleLiveManifestText(lines, updateTime); - let filterNewPeriod = jasmine.createSpy('filterNewPeriod'); + const filterNewPeriod = jasmine.createSpy('filterNewPeriod'); playerInterface.filterNewPeriod = Util.spyFunc(filterNewPeriod); - let filterAllPeriods = jasmine.createSpy('filterAllPeriods'); + const filterAllPeriods = jasmine.createSpy('filterAllPeriods'); playerInterface.filterAllPeriods = Util.spyFunc(filterAllPeriods); fakeNetEngine.setResponseText('dummy://foo', firstManifest); @@ -397,7 +400,7 @@ describe('DashParser Live', function() { }); it('uses redirect URL for manifest BaseURL and updates', function(done) { - let template = [ + const template = [ '<MPD type="dynamic" availabilityStartTime="1970-01-01T00:00:00Z"', ' suggestedPresentationDelay="PT5S"', ' minimumUpdatePeriod="PT%(updateTime)dS">', @@ -416,9 +419,9 @@ describe('DashParser Live', function() { ' </Period>', '</MPD>', ].join('\n'); - let manifestText = sprintf(template, {updateTime: updateTime}); - let manifestData = shaka.util.StringUtils.toUTF8(manifestText); - let redirectedUri = 'http://redirected.com/'; + const manifestText = sprintf(template, {updateTime: updateTime}); + const manifestData = shaka.util.StringUtils.toUTF8(manifestText); + const redirectedUri = 'http://redirected.com/'; // The initial manifest request will be redirected. fakeNetEngine.request.and.returnValue( @@ -432,24 +435,24 @@ describe('DashParser Live', function() { // The manifest request was made to the original URL. // But includes a redirect expect(fakeNetEngine.request.calls.count()).toBe(1); - let netRequest = fakeNetEngine.request.calls.argsFor(0)[1]; + const netRequest = fakeNetEngine.request.calls.argsFor(0)[1]; expect(netRequest.uris).toEqual([redirectedUri, originalUri]); // Since the manifest request was redirected, the segment refers to // the redirected base. - let stream = manifest.periods[0].variants[0].video; - let segmentUri = stream.getSegmentReference(1).getUris()[0]; + const stream = manifest.periods[0].variants[0].video; + const segmentUri = stream.getSegmentReference(1).getUris()[0]; expect(segmentUri).toBe(redirectedUri + 's1.mp4'); }).catch(fail).then(done); PromiseMock.flush(); }); it('calls the error callback if an update fails', function(done) { - let lines = [ + const lines = [ '<SegmentTemplate startNumber="1" media="s$Number$.mp4" duration="2" />', ]; - let manifest = makeSimpleLiveManifestText(lines, updateTime); - let onError = jasmine.createSpy('onError'); + const manifest = makeSimpleLiveManifestText(lines, updateTime); + const onError = jasmine.createSpy('onError'); playerInterface.onError = Util.spyFunc(onError); fakeNetEngine.setResponseText('dummy://foo', manifest); @@ -457,11 +460,11 @@ describe('DashParser Live', function() { .then(function(manifest) { expect(fakeNetEngine.request.calls.count()).toBe(1); - let error = new shaka.util.Error( + const error = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.NETWORK, shaka.util.Error.Code.BAD_HTTP_STATUS); - let operation = shaka.util.AbortableOperation.failed(error); + const operation = shaka.util.AbortableOperation.failed(error); fakeNetEngine.request.and.returnValue(operation); delayForUpdatePeriod(); @@ -471,11 +474,11 @@ describe('DashParser Live', function() { }); it('uses @minimumUpdatePeriod', function(done) { - let lines = [ + const lines = [ '<SegmentTemplate startNumber="1" media="s$Number$.mp4" duration="2" />', ]; // updateTime parameter sets @minimumUpdatePeriod in the manifest. - let manifest = makeSimpleLiveManifestText(lines, updateTime); + const manifest = makeSimpleLiveManifestText(lines, updateTime); fakeNetEngine.setResponseText('dummy://foo', manifest); parser.start('dummy://foo', playerInterface) @@ -483,8 +486,8 @@ describe('DashParser Live', function() { expect(fakeNetEngine.request.calls.count()).toBe(1); expect(manifest).toBeTruthy(); - let partialTime = updateTime * 1000 * 3 / 4; - let remainingTime = updateTime * 1000 - partialTime; + const partialTime = updateTime * 1000 * 3 / 4; + const remainingTime = updateTime * 1000 - partialTime; jasmine.clock().tick(partialTime); PromiseMock.flush(); @@ -500,11 +503,11 @@ describe('DashParser Live', function() { }); it('still updates when @minimumUpdatePeriod is zero', function(done) { - let lines = [ + const lines = [ '<SegmentTemplate startNumber="1" media="s$Number$.mp4" duration="2" />', ]; // updateTime parameter sets @minimumUpdatePeriod in the manifest. - let manifest = makeSimpleLiveManifestText(lines, /* updateTime */ 0); + const manifest = makeSimpleLiveManifestText(lines, /* updateTime */ 0); fakeNetEngine.setResponseText('dummy://foo', manifest); parser.start('dummy://foo', playerInterface) @@ -512,7 +515,7 @@ describe('DashParser Live', function() { expect(manifest).toBeTruthy(); fakeNetEngine.request.calls.reset(); - let waitTimeMs = shaka.dash.DashParser['MIN_UPDATE_PERIOD_'] * 1000; + const waitTimeMs = shaka.dash.DashParser['MIN_UPDATE_PERIOD_'] * 1000; jasmine.clock().tick(waitTimeMs); PromiseMock.flush(); @@ -523,11 +526,11 @@ describe('DashParser Live', function() { }); it('does not update when @minimumUpdatePeriod is missing', function(done) { - let lines = [ + const lines = [ '<SegmentTemplate startNumber="1" media="s$Number$.mp4" duration="2" />', ]; // updateTime parameter sets @minimumUpdatePeriod in the manifest. - let manifest = makeSimpleLiveManifestText(lines, /* updateTime */ null); + const manifest = makeSimpleLiveManifestText(lines, /* updateTime */ null); fakeNetEngine.setResponseText('dummy://foo', manifest); parser.start('dummy://foo', playerInterface) @@ -535,7 +538,7 @@ describe('DashParser Live', function() { expect(manifest).toBeTruthy(); fakeNetEngine.request.calls.reset(); - let waitTimeMs = shaka.dash.DashParser['MIN_UPDATE_PERIOD_'] * 1000; + const waitTimeMs = shaka.dash.DashParser['MIN_UPDATE_PERIOD_'] * 1000; jasmine.clock().tick(waitTimeMs * 2); PromiseMock.flush(); @@ -597,7 +600,7 @@ describe('DashParser Live', function() { }); it('uses Mpd.Location', function(done) { - let manifestText = [ + const manifestText = [ '<MPD type="dynamic" availabilityStartTime="1970-01-01T00:00:00Z"', ' suggestedPresentationDelay="PT5S"', ' minimumUpdatePeriod="PT' + updateTime + 'S">', @@ -629,7 +632,7 @@ describe('DashParser Live', function() { expect(type).toBe(manifestRequest); expect(request.uris).toEqual( ['http://foobar', 'http://foobar2', 'dummy://foo/foobar3']); - let data = shaka.util.StringUtils.toUTF8(manifestText); + const data = shaka.util.StringUtils.toUTF8(manifestText); return shaka.util.AbortableOperation.completed( {uri: request.uris[0], data: data, headers: {}}); }); @@ -641,7 +644,7 @@ describe('DashParser Live', function() { }); it('uses @suggestedPresentationDelay', function(done) { - let manifest = [ + const manifest = [ '<MPD type="dynamic" suggestedPresentationDelay="PT60S"', ' minimumUpdatePeriod="PT5S"', ' timeShiftBufferDepth="PT2M"', @@ -663,7 +666,7 @@ describe('DashParser Live', function() { parser.start('dummy://foo', playerInterface) .then(function(manifest) { expect(manifest).toBeTruthy(); - let timeline = manifest.presentationTimeline; + const timeline = manifest.presentationTimeline; expect(timeline).toBeTruthy(); // We are 5 minutes into the presentation, with a @@ -680,7 +683,7 @@ describe('DashParser Live', function() { describe('availabilityWindowOverride', function() { it('overrides @timeShiftBufferDepth', function(done) { - let manifest = [ + const manifest = [ '<MPD type="dynamic" suggestedPresentationDelay="PT60S"', ' minimumUpdatePeriod="PT5S"', ' timeShiftBufferDepth="PT2M"', @@ -706,13 +709,13 @@ describe('DashParser Live', function() { parser.start('dummy://foo', playerInterface) .then(function(manifest) { expect(manifest).toBeTruthy(); - let timeline = manifest.presentationTimeline; + const timeline = manifest.presentationTimeline; expect(timeline).toBeTruthy(); // The parser was configured to have a manifest availability window // of 4 minutes. - let end = timeline.getSegmentAvailabilityEnd(); - let start = timeline.getSegmentAvailabilityStart(); + const end = timeline.getSegmentAvailabilityEnd(); + const start = timeline.getSegmentAvailabilityStart(); expect(end - start).toEqual(4 * 60); }).catch(fail).then(done); PromiseMock.flush(); @@ -721,7 +724,7 @@ describe('DashParser Live', function() { describe('maxSegmentDuration', function() { it('uses @maxSegmentDuration', function(done) { - let manifest = [ + const manifest = [ '<MPD type="dynamic" suggestedPresentationDelay="PT0S"', ' minimumUpdatePeriod="PT5S"', ' timeShiftBufferDepth="PT2M"', @@ -743,7 +746,7 @@ describe('DashParser Live', function() { parser.start('dummy://foo', playerInterface) .then(function(manifest) { expect(manifest).toBeTruthy(); - let timeline = manifest.presentationTimeline; + const timeline = manifest.presentationTimeline; expect(timeline).toBeTruthy(); expect(timeline.getMaxSegmentDuration()).toBe(15); }).catch(fail).then(done); @@ -751,7 +754,7 @@ describe('DashParser Live', function() { }); it('derived from SegmentTemplate w/ SegmentTimeline', function(done) { - let lines = [ + const lines = [ '<SegmentTemplate media="s$Number$.mp4">', ' <SegmentTimeline>', ' <S t="0" d="7" />', @@ -764,14 +767,14 @@ describe('DashParser Live', function() { }); it('derived from SegmentTemplate w/ @duration', function(done) { - let lines = [ + const lines = [ '<SegmentTemplate media="s$Number$.mp4" duration="8" />', ]; testDerived(lines, done); }); it('derived from SegmentList', function(done) { - let lines = [ + const lines = [ '<SegmentList duration="8">', ' <SegmentURL media="s1.mp4" />', ' <SegmentURL media="s2.mp4" />', @@ -781,7 +784,7 @@ describe('DashParser Live', function() { }); it('derived from SegmentList w/ SegmentTimeline', function(done) { - let lines = [ + const lines = [ '<SegmentList duration="8">', ' <SegmentTimeline>', ' <S t="0" d="5" />', @@ -796,7 +799,7 @@ describe('DashParser Live', function() { }); function testDerived(lines, done) { - let template = [ + const template = [ '<MPD type="dynamic" suggestedPresentationDelay="PT0S"', ' minimumUpdatePeriod="PT5S"', ' timeShiftBufferDepth="PT2M"', @@ -811,14 +814,14 @@ describe('DashParser Live', function() { ' </Period>', '</MPD>', ].join('\n'); - let manifest = sprintf(template, {contents: lines.join('\n')}); + const manifest = sprintf(template, {contents: lines.join('\n')}); fakeNetEngine.setResponseText('dummy://foo', manifest); Date.now = function() { return 600000; /* 10 minutes */ }; parser.start('dummy://foo', playerInterface) .then(function(manifest) { expect(manifest).toBeTruthy(); - let timeline = manifest.presentationTimeline; + const timeline = manifest.presentationTimeline; expect(timeline).toBeTruthy(); // NOTE: the largest segment is 8 seconds long in each test. @@ -835,7 +838,7 @@ describe('DashParser Live', function() { const dateUri = 'http://foo.bar/date'; beforeEach(function() { - let manifest = [ + const manifest = [ '<MPD type="dynamic" availabilityStartTime="1970-01-01T00:00:00Z"', ' minimumUpdatePeriod="PT' + updateTime + 'S">', ' <UTCTiming schemeIdUri="urn:mpeg:dash:utc:http-xsdate:2014"', @@ -895,7 +898,7 @@ describe('DashParser Live', function() { expect(manifest).toBeTruthy(); fakeNetEngine.expectRequest(manifestUri, manifestRequestType); fakeNetEngine.request.calls.reset(); - let delay = fakeNetEngine.delayNextRequest(); + const delay = fakeNetEngine.delayNextRequest(); delayForUpdatePeriod(); // The request was made but should not be resolved yet. @@ -950,7 +953,7 @@ describe('DashParser Live', function() { }); describe('SegmentTemplate w/ SegmentTimeline', function() { - let basicLines = [ + const basicLines = [ '<SegmentTemplate startNumber="1" media="s$Number$.mp4">', ' <SegmentTimeline>', ' <S d="10" t="0" />', @@ -959,12 +962,12 @@ describe('DashParser Live', function() { ' </SegmentTimeline>', '</SegmentTemplate>', ]; - let basicRefs = [ + const basicRefs = [ shaka.test.ManifestParser.makeReference('s1.mp4', 1, 0, 10, originalUri), shaka.test.ManifestParser.makeReference('s2.mp4', 2, 10, 15, originalUri), shaka.test.ManifestParser.makeReference('s3.mp4', 3, 15, 30, originalUri), ]; - let updateLines = [ + const updateLines = [ '<SegmentTemplate startNumber="1" media="s$Number$.mp4">', ' <SegmentTimeline>', ' <S d="10" t="0" />', @@ -974,13 +977,13 @@ describe('DashParser Live', function() { ' </SegmentTimeline>', '</SegmentTemplate>', ]; - let updateRefs = [ + const updateRefs = [ shaka.test.ManifestParser.makeReference('s1.mp4', 1, 0, 10, originalUri), shaka.test.ManifestParser.makeReference('s2.mp4', 2, 10, 15, originalUri), shaka.test.ManifestParser.makeReference('s3.mp4', 3, 15, 30, originalUri), shaka.test.ManifestParser.makeReference('s4.mp4', 4, 30, 40, originalUri), ]; - let partialUpdateLines = [ + const partialUpdateLines = [ '<SegmentTemplate startNumber="3" media="s$Number$.mp4">', ' <SegmentTimeline>', ' <S d="15" t="15" />', @@ -994,7 +997,7 @@ describe('DashParser Live', function() { }); describe('SegmentList w/ SegmentTimeline', function() { - let basicLines = [ + const basicLines = [ '<SegmentList>', ' <SegmentURL media="s1.mp4" />', ' <SegmentURL media="s2.mp4" />', @@ -1006,12 +1009,12 @@ describe('DashParser Live', function() { ' </SegmentTimeline>', '</SegmentList>', ]; - let basicRefs = [ + const basicRefs = [ shaka.test.ManifestParser.makeReference('s1.mp4', 1, 0, 10, originalUri), shaka.test.ManifestParser.makeReference('s2.mp4', 2, 10, 15, originalUri), shaka.test.ManifestParser.makeReference('s3.mp4', 3, 15, 30, originalUri), ]; - let updateLines = [ + const updateLines = [ '<SegmentList>', ' <SegmentURL media="s1.mp4" />', ' <SegmentURL media="s2.mp4" />', @@ -1025,13 +1028,13 @@ describe('DashParser Live', function() { ' </SegmentTimeline>', '</SegmentList>', ]; - let updateRefs = [ + const updateRefs = [ shaka.test.ManifestParser.makeReference('s1.mp4', 1, 0, 10, originalUri), shaka.test.ManifestParser.makeReference('s2.mp4', 2, 10, 15, originalUri), shaka.test.ManifestParser.makeReference('s3.mp4', 3, 15, 30, originalUri), shaka.test.ManifestParser.makeReference('s4.mp4', 4, 30, 40, originalUri), ]; - let partialUpdateLines = [ + const partialUpdateLines = [ '<SegmentList startNumber="3">', ' <SegmentURL media="s3.mp4" />', ' <SegmentURL media="s4.mp4" />', @@ -1047,19 +1050,19 @@ describe('DashParser Live', function() { }); describe('SegmentList w/ @duration', function() { - let basicLines = [ + const basicLines = [ '<SegmentList duration="10">', ' <SegmentURL media="s1.mp4" />', ' <SegmentURL media="s2.mp4" />', ' <SegmentURL media="s3.mp4" />', '</SegmentList>', ]; - let basicRefs = [ + const basicRefs = [ shaka.test.ManifestParser.makeReference('s1.mp4', 1, 0, 10, originalUri), shaka.test.ManifestParser.makeReference('s2.mp4', 2, 10, 20, originalUri), shaka.test.ManifestParser.makeReference('s3.mp4', 3, 20, 30, originalUri), ]; - let updateLines = [ + const updateLines = [ '<SegmentList duration="10">', ' <SegmentURL media="s1.mp4" />', ' <SegmentURL media="s2.mp4" />', @@ -1067,13 +1070,13 @@ describe('DashParser Live', function() { ' <SegmentURL media="s4.mp4" />', '</SegmentList>', ]; - let updateRefs = [ + const updateRefs = [ shaka.test.ManifestParser.makeReference('s1.mp4', 1, 0, 10, originalUri), shaka.test.ManifestParser.makeReference('s2.mp4', 2, 10, 20, originalUri), shaka.test.ManifestParser.makeReference('s3.mp4', 3, 20, 30, originalUri), shaka.test.ManifestParser.makeReference('s4.mp4', 4, 30, 40, originalUri), ]; - let partialUpdateLines = [ + const partialUpdateLines = [ '<SegmentList startNumber="3" duration="10">', ' <SegmentURL media="s3.mp4" />', ' <SegmentURL media="s4.mp4" />', @@ -1085,21 +1088,21 @@ describe('DashParser Live', function() { }); describe('SegmentTemplate w/ duration', function() { - let templateLines = [ + const templateLines = [ '<SegmentTemplate startNumber="1" media="s$Number$.mp4" duration="2" />', ]; it('produces sane references without assertions', function(done) { - let manifest = makeSimpleLiveManifestText(templateLines, updateTime); + const manifest = makeSimpleLiveManifestText(templateLines, updateTime); fakeNetEngine.setResponseText('dummy://foo', manifest); parser.start('dummy://foo', playerInterface).then(function(manifest) { expect(manifest.periods.length).toBe(1); - let stream = manifest.periods[0].variants[0].video; + const stream = manifest.periods[0].variants[0].video; // In https://github.com/google/shaka-player/issues/1204, this // failed an assertion and returned endTime == 0. - let ref = stream.getSegmentReference(1); + const ref = stream.getSegmentReference(1); expect(ref.endTime).toBeGreaterThan(0); }).catch(fail).then(done); PromiseMock.flush(); @@ -1163,7 +1166,7 @@ describe('DashParser Live', function() { }); it('will add timeline regions on manifest update', function(done) { - let newManifest = [ + const newManifest = [ '<MPD type="dynamic" minimumUpdatePeriod="PT' + updateTime + 'S"', ' availabilityStartTime="1970-01-01T00:00:00Z">', ' <Period id="1" duration="PT30S">', @@ -1196,7 +1199,7 @@ describe('DashParser Live', function() { }); it('will not let an event exceed the Period duration', function(done) { - let newManifest = [ + const newManifest = [ '<MPD>', ' <Period id="1" duration="PT30S">', ' <EventStream schemeIdUri="http://example.com" timescale="1">', diff --git a/test/dash/dash_parser_manifest_unit.js b/test/dash/dash_parser_manifest_unit.js index 35a772112e..83b07813b1 100644 --- a/test/dash/dash_parser_manifest_unit.js +++ b/test/dash/dash_parser_manifest_unit.js @@ -69,12 +69,12 @@ describe('DashParser Manifest', function() { */ async function testDashParser(manifestText) { fakeNetEngine.setResponseText('dummy://foo', manifestText); - let actual = await parser.start('dummy://foo', playerInterface); + const actual = await parser.start('dummy://foo', playerInterface); expect(actual).toEqual(expected); } it('with SegmentBase', async () => { - let source = makeTestManifest([ + const source = makeTestManifest([ ' <SegmentBase indexRange="100-200" timescale="9000">', ' <Initialization sourceURL="init.mp4" range="201-300" />', ' </SegmentBase>', @@ -83,7 +83,7 @@ describe('DashParser Manifest', function() { }); it('with SegmentList', async () => { - let source = makeTestManifest([ + const source = makeTestManifest([ ' <SegmentList startNumber="1" duration="10">', ' <Initialization sourceURL="init.mp4" range="201-300" />', ' <SegmentURL media="s1.mp4" />', @@ -93,7 +93,7 @@ describe('DashParser Manifest', function() { }); it('with SegmentTemplate', async () => { - let source = makeTestManifest([ + const source = makeTestManifest([ ' <SegmentTemplate startNumber="1" media="l-$Number$.mp4"', ' initialization="init.mp4">', ' <Initialization sourceURL="init.mp4" range="201-300" />', @@ -182,7 +182,7 @@ describe('DashParser Manifest', function() { }); it('skips any periods after one without duration', async () => { - let periodContents = [ + const periodContents = [ ' <AdaptationSet mimeType="video/mp4" lang="en" group="1">', ' <Representation bandwidth="100">', ' <SegmentBase presentationTimeOffset="1" indexRange="100-200">', @@ -191,7 +191,7 @@ describe('DashParser Manifest', function() { ' </Representation>', ' </AdaptationSet>', ].join('\n'); - let template = [ + const template = [ '<MPD mediaPresentationDuration="PT75S">', ' <Period id="1">', '%(periodContents)s', @@ -201,15 +201,15 @@ describe('DashParser Manifest', function() { ' </Period>', '</MPD>', ].join('\n'); - let source = sprintf(template, {periodContents: periodContents}); + const source = sprintf(template, {periodContents: periodContents}); fakeNetEngine.setResponseText('dummy://foo', source); - let manifest = await parser.start('dummy://foo', playerInterface); + const manifest = await parser.start('dummy://foo', playerInterface); expect(manifest.periods.length).toBe(1); }); it('calculates Period times when missing', async () => { - let periodContents = [ + const periodContents = [ ' <AdaptationSet mimeType="video/mp4" lang="en" group="1">', ' <Representation bandwidth="100">', ' <SegmentBase presentationTimeOffset="1" indexRange="100-200">', @@ -218,7 +218,7 @@ describe('DashParser Manifest', function() { ' </Representation>', ' </AdaptationSet>', ].join('\n'); - let template = [ + const template = [ '<MPD mediaPresentationDuration="PT75S">', ' <Period id="1" start="PT10S">', '%(periodContents)s', @@ -231,10 +231,10 @@ describe('DashParser Manifest', function() { ' </Period>', '</MPD>', ].join('\n'); - let source = sprintf(template, {periodContents: periodContents}); + const source = sprintf(template, {periodContents: periodContents}); fakeNetEngine.setResponseText('dummy://foo', source); - let manifest = await parser.start('dummy://foo', playerInterface); + const manifest = await parser.start('dummy://foo', playerInterface); expect(manifest.periods.length).toBe(3); expect(manifest.periods[0].startTime).toBe(10); expect(manifest.periods[1].startTime).toBe(20); @@ -242,7 +242,7 @@ describe('DashParser Manifest', function() { }); it('defaults to SegmentBase with multiple Segment*', async () => { - let source = Dash.makeSimpleManifestText([ + const source = Dash.makeSimpleManifestText([ '<SegmentBase presentationTimeOffset="1" indexRange="100-200">', ' <Initialization sourceURL="init.mp4" range="201-300" />', '</SegmentBase>', @@ -253,13 +253,13 @@ describe('DashParser Manifest', function() { ]); fakeNetEngine.setResponseText('dummy://foo', source); - let manifest = await parser.start('dummy://foo', playerInterface); - let stream = manifest.periods[0].variants[0].video; + const manifest = await parser.start('dummy://foo', playerInterface); + const stream = manifest.periods[0].variants[0].video; expect(stream.presentationTimeOffset).toBe(1); }); it('defaults to SegmentList with SegmentTemplate', async () => { - let source = Dash.makeSimpleManifestText([ + const source = Dash.makeSimpleManifestText([ '<SegmentList presentationTimeOffset="2" duration="10">', ' <Initialization sourceURL="init.mp4" range="201-300" />', ' <SegmentURL media="s1.mp4" />', @@ -274,13 +274,13 @@ describe('DashParser Manifest', function() { ]); fakeNetEngine.setResponseText('dummy://foo', source); - let manifest = await parser.start('dummy://foo', playerInterface); - let stream = manifest.periods[0].variants[0].video; + const manifest = await parser.start('dummy://foo', playerInterface); + const stream = manifest.periods[0].variants[0].video; expect(stream.presentationTimeOffset).toBe(2); }); it('generates a correct index for non-segmented text', async () => { - let source = [ + const source = [ '<MPD mediaPresentationDuration="PT30S">', ' <Period>', ' <AdaptationSet mimeType="video/mp4">', @@ -299,8 +299,8 @@ describe('DashParser Manifest', function() { fakeNetEngine.setResponseText('dummy://foo', source); - let manifest = await parser.start('dummy://foo', playerInterface); - let stream = manifest.periods[0].textStreams[0]; + const manifest = await parser.start('dummy://foo', playerInterface); + const stream = manifest.periods[0].textStreams[0]; await stream.createSegmentIndex(); expect(stream.initSegmentReference).toBe(null); expect(stream.findSegmentPosition(0)).toBe(1); @@ -408,7 +408,7 @@ describe('DashParser Manifest', function() { }); it('correctly parses UTF-8', async () => { - let source = [ + const source = [ '<MPD>', ' <Period duration="PT30M">', ' <AdaptationSet mimeType="audio/mp4" lang="\u2603">', @@ -424,9 +424,9 @@ describe('DashParser Manifest', function() { fakeNetEngine.setResponseText('dummy://foo', source); - let manifest = await parser.start('dummy://foo', playerInterface); - let variant = manifest.periods[0].variants[0]; - let stream = manifest.periods[0].variants[0].audio; + const manifest = await parser.start('dummy://foo', playerInterface); + const variant = manifest.periods[0].variants[0]; + const stream = manifest.periods[0].variants[0].audio; expect(stream.initSegmentReference.getUris()[0]) .toBe('http://example.com/%C8%A7.mp4'); expect(variant.language).toBe('\u2603'); @@ -448,7 +448,7 @@ describe('DashParser Manifest', function() { * @return {string} */ function makeManifest(lines) { - let template = [ + const template = [ '<MPD type="dynamic"', ' availabilityStartTime="1970-01-01T00:00:00Z"', ' timeShiftBufferDepth="PT60S"', @@ -473,7 +473,7 @@ describe('DashParser Manifest', function() { * @return {!Promise} */ async function runTest(expectedTime) { - let manifest = await parser.start( + const manifest = await parser.start( 'http://foo.bar/manifest', playerInterface); expect(manifest.presentationTimeline).toBeTruthy(); expect(manifest.presentationTimeline.getSegmentAvailabilityEnd()) @@ -481,7 +481,7 @@ describe('DashParser Manifest', function() { } it('with direct', async () => { - let source = makeManifest([ + const source = makeManifest([ '<UTCTiming schemeIdUri="urn:mpeg:dash:utc:direct:2014"', ' value="1970-01-01T00:00:30Z" />', ]); @@ -491,7 +491,7 @@ describe('DashParser Manifest', function() { }); it('does not produce errors', async () => { - let source = makeManifest([ + const source = makeManifest([ '<UTCTiming schemeIdUri="unknown scheme" value="foobar" />', ]); @@ -500,7 +500,7 @@ describe('DashParser Manifest', function() { }); it('tries multiple sources', async () => { - let source = makeManifest([ + const source = makeManifest([ '<UTCTiming schemeIdUri="unknown scheme" value="foobar" />', '<UTCTiming schemeIdUri="urn:mpeg:dash:utc:direct:2014"', ' value="1970-01-01T00:00:55Z" />', @@ -511,14 +511,14 @@ describe('DashParser Manifest', function() { }); it('with HEAD', async () => { - let source = makeManifest([ + const source = makeManifest([ '<UTCTiming schemeIdUri="urn:mpeg:dash:utc:http-head:2014"', ' value="http://foo.bar/date" />', ]); fakeNetEngine.request.and.callFake(function(type, request) { if (request.uris[0] == 'http://foo.bar/manifest') { - let data = shaka.util.StringUtils.toUTF8(source); + const data = shaka.util.StringUtils.toUTF8(source); return shaka.util.AbortableOperation.completed({ data: data, headers: {}, @@ -537,7 +537,7 @@ describe('DashParser Manifest', function() { }); it('with xsdate', async () => { - let source = makeManifest([ + const source = makeManifest([ '<UTCTiming schemeIdUri="urn:mpeg:dash:utc:http-xsdate:2014"', ' value="http://foo.bar/date" />', ]); @@ -549,7 +549,7 @@ describe('DashParser Manifest', function() { }); it('with relative paths', async () => { - let source = makeManifest([ + const source = makeManifest([ '<UTCTiming schemeIdUri="urn:mpeg:dash:utc:http-xsdate:2014"', ' value="/date" />', ]); @@ -561,7 +561,7 @@ describe('DashParser Manifest', function() { }); it('with paths relative to BaseURLs', async () => { - let source = makeManifest([ + const source = makeManifest([ '<BaseURL>http://example.com</BaseURL>', '<UTCTiming schemeIdUri="urn:mpeg:dash:utc:http-xsdate:2014"', ' value="/date" />', @@ -575,7 +575,7 @@ describe('DashParser Manifest', function() { }); it('handles missing Segment* elements', async () => { - let source = [ + const source = [ '<MPD minBufferTime="PT75S">', ' <Period id="1" duration="PT30S">', ' <AdaptationSet mimeType="video/mp4" lang="en" group="1">', @@ -590,16 +590,16 @@ describe('DashParser Manifest', function() { fakeNetEngine.setResponseText('dummy://foo', source); - let manifest = await parser.start('dummy://foo', playerInterface); + const manifest = await parser.start('dummy://foo', playerInterface); // First Representation should be dropped. - let period = manifest.periods[0]; + const period = manifest.periods[0]; expect(period.variants.length).toBe(1); expect(period.variants[0].bandwidth).toBe(200); }); describe('allows missing Segment* elements for text', function() { it('specified via AdaptationSet@contentType', async () => { - let source = [ + const source = [ '<MPD minBufferTime="PT75S">', ' <Period id="1" duration="PT30S">', ' <AdaptationSet mimeType="video/mp4">', @@ -616,12 +616,12 @@ describe('DashParser Manifest', function() { fakeNetEngine.setResponseText('dummy://foo', source); - let manifest = await parser.start('dummy://foo', playerInterface); + const manifest = await parser.start('dummy://foo', playerInterface); expect(manifest.periods[0].textStreams.length).toBe(1); }); it('specified via AdaptationSet@mimeType', async () => { - let source = [ + const source = [ '<MPD minBufferTime="PT75S">', ' <Period id="1" duration="PT30S">', ' <AdaptationSet mimeType="video/mp4">', @@ -638,12 +638,12 @@ describe('DashParser Manifest', function() { fakeNetEngine.setResponseText('dummy://foo', source); - let manifest = await parser.start('dummy://foo', playerInterface); + const manifest = await parser.start('dummy://foo', playerInterface); expect(manifest.periods[0].textStreams.length).toBe(1); }); it('specified via Representation@mimeType', async () => { - let source = [ + const source = [ '<MPD minBufferTime="PT75S">', ' <Period id="1" duration="PT30S">', ' <AdaptationSet mimeType="video/mp4">', @@ -660,15 +660,15 @@ describe('DashParser Manifest', function() { fakeNetEngine.setResponseText('dummy://foo', source); - let manifest = await parser.start('dummy://foo', playerInterface); + const manifest = await parser.start('dummy://foo', playerInterface); expect(manifest.periods[0].textStreams.length).toBe(1); }); }); describe('fails for', function() { it('invalid XML', async () => { - let source = '<not XML'; - let error = new shaka.util.Error( + const source = '<not XML'; + const error = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.MANIFEST, shaka.util.Error.Code.DASH_INVALID_XML, @@ -677,7 +677,7 @@ describe('DashParser Manifest', function() { }); it('XML with inner errors', async () => { - let source = [ + const source = [ '<MPD minBufferTime="PT75S">', ' <Period id="1" duration="PT30S">', ' <AdaptationSet mimeType="video/mp4">', @@ -688,7 +688,7 @@ describe('DashParser Manifest', function() { ' </Period>', '</MPD>', ].join('\n'); - let error = new shaka.util.Error( + const error = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.MANIFEST, shaka.util.Error.Code.DASH_INVALID_XML, @@ -697,7 +697,7 @@ describe('DashParser Manifest', function() { }); it('xlink problems when xlinkFailGracefully is false', async () => { - let source = [ + const source = [ '<MPD minBufferTime="PT75S" xmlns="urn:mpeg:dash:schema:mpd:2011" ' + 'xmlns:xlink="http://www.w3.org/1999/xlink">', ' <Period id="1" duration="PT30S">', @@ -710,7 +710,7 @@ describe('DashParser Manifest', function() { ' </Period>', '</MPD>', ].join('\n'); - let error = new shaka.util.Error( + const error = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.MANIFEST, shaka.util.Error.Code.DASH_UNSUPPORTED_XLINK_ACTUATE); @@ -718,7 +718,7 @@ describe('DashParser Manifest', function() { }); it('failed network requests', async () => { - let expectedError = new shaka.util.Error( + const expectedError = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.NETWORK, shaka.util.Error.Code.BAD_HTTP_STATUS); @@ -734,8 +734,8 @@ describe('DashParser Manifest', function() { }); it('missing MPD element', async () => { - let source = '<XML></XML>'; - let error = new shaka.util.Error( + const source = '<XML></XML>'; + const error = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.MANIFEST, shaka.util.Error.Code.DASH_INVALID_XML, @@ -744,14 +744,14 @@ describe('DashParser Manifest', function() { }); it('empty AdaptationSet', async () => { - let source = [ + const source = [ '<MPD minBufferTime="PT75S">', ' <Period id="1" duration="PT30S">', ' <AdaptationSet mimeType="video/mp4" lang="en" group="1" />', ' </Period>', '</MPD>', ].join('\n'); - let error = new shaka.util.Error( + const error = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.MANIFEST, shaka.util.Error.Code.DASH_EMPTY_ADAPTATION_SET); @@ -759,12 +759,12 @@ describe('DashParser Manifest', function() { }); it('empty Period', async () => { - let source = [ + const source = [ '<MPD minBufferTime="PT75S">', ' <Period id="1" duration="PT30S" />', '</MPD>', ].join('\n'); - let error = new shaka.util.Error( + const error = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.MANIFEST, shaka.util.Error.Code.DASH_EMPTY_PERIOD); @@ -772,7 +772,7 @@ describe('DashParser Manifest', function() { }); it('duplicate Representation ids with live', async () => { - let source = [ + const source = [ '<MPD minBufferTime="PT75S" type="dynamic">', ' <Period id="1" duration="PT30S">', ' <AdaptationSet mimeType="video/mp4">', @@ -788,7 +788,7 @@ describe('DashParser Manifest', function() { ' </Period>', '</MPD>', ].join('\n'); - let error = new shaka.util.Error( + const error = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.MANIFEST, shaka.util.Error.Code.DASH_DUPLICATE_REPRESENTATION_ID); @@ -797,7 +797,7 @@ describe('DashParser Manifest', function() { }); it('parses trickmode tracks', async () => { - let manifestText = [ + const manifestText = [ '<MPD minBufferTime="PT75S">', ' <Period id="1" duration="PT30S">', ' <AdaptationSet id="1" mimeType="video/mp4">', @@ -817,13 +817,13 @@ describe('DashParser Manifest', function() { ].join('\n'); fakeNetEngine.setResponseText('dummy://foo', manifestText); - let manifest = await parser.start('dummy://foo', playerInterface); + const manifest = await parser.start('dummy://foo', playerInterface); expect(manifest.periods.length).toBe(1); expect(manifest.periods[0].variants.length).toBe(1); expect(manifest.periods[0].textStreams.length).toBe(0); - let variant = manifest.periods[0].variants[0]; - let trickModeVideo = variant && variant.video && + const variant = manifest.periods[0].variants[0]; + const trickModeVideo = variant && variant.video && variant.video.trickModeVideo; expect(trickModeVideo).toEqual(jasmine.objectContaining({ id: 2, @@ -832,7 +832,7 @@ describe('DashParser Manifest', function() { }); it('skips unrecognized EssentialProperty elements', async () => { - let manifestText = [ + const manifestText = [ '<MPD minBufferTime="PT75S">', ' <Period id="1" duration="PT30S">', ' <AdaptationSet id="1" mimeType="video/mp4">', @@ -851,7 +851,7 @@ describe('DashParser Manifest', function() { ].join('\n'); fakeNetEngine.setResponseText('dummy://foo', manifestText); - let manifest = await parser.start('dummy://foo', playerInterface); + const manifest = await parser.start('dummy://foo', playerInterface); expect(manifest.periods.length).toBe(1); // The bogus EssentialProperty did not result in a variant. @@ -859,8 +859,8 @@ describe('DashParser Manifest', function() { expect(manifest.periods[0].textStreams.length).toBe(0); // The bogus EssentialProperty did not result in a trick mode track. - let variant = manifest.periods[0].variants[0]; - let trickModeVideo = variant && variant.video && + const variant = manifest.periods[0].variants[0]; + const trickModeVideo = variant && variant.video && variant.video.trickModeVideo; expect(trickModeVideo).toBe(null); }); @@ -868,7 +868,7 @@ describe('DashParser Manifest', function() { it('sets contentType to text for embedded text mime types', async () => { // One MIME type for embedded TTML, one for embedded WebVTT. // One MIME type specified on AdaptationSet, on one Representation. - let manifestText = [ + const manifestText = [ '<MPD minBufferTime="PT75S">', ' <Period id="1" duration="PT30S">', ' <AdaptationSet mimeType="video/mp4">', @@ -891,7 +891,7 @@ describe('DashParser Manifest', function() { ].join('\n'); fakeNetEngine.setResponseText('dummy://foo', manifestText); - let manifest = await parser.start('dummy://foo', playerInterface); + const manifest = await parser.start('dummy://foo', playerInterface); expect(manifest.periods.length).toBe(1); expect(manifest.periods[0].textStreams.length).toBe(2); // At one time, these came out as 'application' rather than 'text'. @@ -902,7 +902,7 @@ describe('DashParser Manifest', function() { it('handles text with mime and codecs on different levels', async () => { // Regression test for #875 - let manifestText = [ + const manifestText = [ '<MPD minBufferTime="PT75S">', ' <Period id="1" duration="PT30S">', ' <AdaptationSet mimeType="video/mp4">', @@ -920,7 +920,7 @@ describe('DashParser Manifest', function() { ].join('\n'); fakeNetEngine.setResponseText('dummy://foo', manifestText); - let manifest = await parser.start('dummy://foo', playerInterface); + const manifest = await parser.start('dummy://foo', playerInterface); expect(manifest.periods.length).toBe(1); // In #875, this was an empty list. @@ -932,7 +932,7 @@ describe('DashParser Manifest', function() { }); it('ignores duplicate Representation IDs for VOD', async () => { - let source = [ + const source = [ '<MPD minBufferTime="PT75S">', ' <Period id="1" duration="PT30S">', ' <AdaptationSet mimeType="video/mp4">', @@ -963,12 +963,12 @@ describe('DashParser Manifest', function() { // This test proves that duplicate Representation IDs are allowed for VOD // and that error doesn't occur. fakeNetEngine.setResponseText('dummy://foo', source); - let manifest = await parser.start('dummy://foo', playerInterface); + const manifest = await parser.start('dummy://foo', playerInterface); expect(manifest.periods.length).toBe(1); expect(manifest.periods[0].variants.length).toBe(2); - let variant1 = manifest.periods[0].variants[0]; - let variant2 = manifest.periods[0].variants[1]; + const variant1 = manifest.periods[0].variants[0]; + const variant2 = manifest.periods[0].variants[1]; expect(variant1.video).toBeTruthy(); expect(variant2.video).toBeTruthy(); expect(variant1.video.getSegmentReference(1).getUris()) @@ -979,7 +979,7 @@ describe('DashParser Manifest', function() { it('handles bandwidth of 0 or missing', async () => { // Regression test for https://github.com/google/shaka-player/issues/938 - let source = [ + const source = [ '<MPD minBufferTime="PT75S">', ' <Period id="1" duration="PT30S">', ' <AdaptationSet mimeType="video/mp4">', @@ -1000,15 +1000,15 @@ describe('DashParser Manifest', function() { ].join('\n'); fakeNetEngine.setResponseText('dummy://foo', source); - let manifest = await parser.start('dummy://foo', playerInterface); + const manifest = await parser.start('dummy://foo', playerInterface); expect(manifest.periods.length).toBe(1); expect(manifest.periods[0].variants.length).toBe(2); - let variant1 = manifest.periods[0].variants[0]; + const variant1 = manifest.periods[0].variants[0]; expect(isNaN(variant1.bandwidth)).toBe(false); expect(variant1.bandwidth).toBeGreaterThan(0); - let variant2 = manifest.periods[0].variants[1]; + const variant2 = manifest.periods[0].variants[1]; expect(isNaN(variant2.bandwidth)).toBe(false); expect(variant2.bandwidth).toBeGreaterThan(0); }); @@ -1022,21 +1022,21 @@ describe('DashParser Manifest', function() { * @return {!Promise} */ function testAudioChannelConfiguration(expectedNumChannels, schemeMap) { - let header = [ + const header = [ '<MPD minBufferTime="PT75S">', ' <Period id="1" duration="PT30S">', ' <AdaptationSet mimeType="audio/mp4">', ' <Representation id="1" bandwidth="1">', ].join('\n'); - let configs = []; - for (let scheme in schemeMap) { - let value = schemeMap[scheme]; + const configs = []; + for (const scheme in schemeMap) { + const value = schemeMap[scheme]; configs.push('<AudioChannelConfiguration schemeIdUri="' + scheme + '" value="' + value + '" />'); } - let footer = [ + const footer = [ ' <SegmentTemplate media="1-$Number$.mp4" duration="1" />', ' </Representation>', ' </AdaptationSet>', @@ -1044,7 +1044,7 @@ describe('DashParser Manifest', function() { '</MPD>', ].join('\n'); - let source = header + configs.join('\n') + footer; + const source = header + configs.join('\n') + footer; // Create a fresh parser, to avoid issues when we chain multiple tests // together. @@ -1056,7 +1056,7 @@ describe('DashParser Manifest', function() { expect(manifest.periods.length).toBe(1); expect(manifest.periods[0].variants.length).toBe(1); - let variant = manifest.periods[0].variants[0]; + const variant = manifest.periods[0].variants[0]; expect(variant.audio.channelsCount).toEqual(expectedNumChannels); }).catch(fail); } @@ -1113,7 +1113,7 @@ describe('DashParser Manifest', function() { }); it('does not fail on AdaptationSets without segment info', async () => { - let manifestText = [ + const manifestText = [ '<MPD minBufferTime="PT75S">', ' <Period id="1" duration="PT30S">', ' <AdaptationSet id="1" contentType="text">', @@ -1135,7 +1135,7 @@ describe('DashParser Manifest', function() { }); it('exposes Representation IDs', async () => { - let manifestText = [ + const manifestText = [ '<MPD minBufferTime="PT75S">', ' <Period id="1" duration="PT30S">', ' <AdaptationSet id="1" contentType="text">', @@ -1169,7 +1169,7 @@ describe('DashParser Manifest', function() { }); it('override manifest value if ignoreMinBufferTime is true', async () => { - let manifestText = [ + const manifestText = [ '<MPD minBufferTime="PT75S">', ' <Period id="1" duration="PT30S">', ' <AdaptationSet id="1" mimeType="video/mp4">', @@ -1193,7 +1193,7 @@ describe('DashParser Manifest', function() { }); it('get manifest value if ignoreMinBufferTime is false', async () => { - let manifestText = [ + const manifestText = [ '<MPD minBufferTime="PT75S">', ' <Period id="1" duration="PT30S">', ' <AdaptationSet id="1" mimeType="video/mp4">', diff --git a/test/dash/dash_parser_segment_base_unit.js b/test/dash/dash_parser_segment_base_unit.js index 69fb04d13b..55447a13da 100644 --- a/test/dash/dash_parser_segment_base_unit.js +++ b/test/dash/dash_parser_segment_base_unit.js @@ -48,7 +48,7 @@ describe('DashParser SegmentBase', function() { }); it('requests init data for WebM', async () => { - let source = [ + const source = [ '<MPD mediaPresentationDuration="PT75S">', ' <Period>', ' <AdaptationSet mimeType="video/webm">', @@ -68,7 +68,7 @@ describe('DashParser SegmentBase', function() { .setResponseText('http://example.com', '') .setResponseText('http://example.com/init.webm', ''); - let manifest = await parser.start('dummy://foo', playerInterface); + const manifest = await parser.start('dummy://foo', playerInterface); expect(manifest).toEqual(Dash.makeManifestFromInit('init.webm', 201, 300)); await Dash.callCreateSegmentIndex(manifest); @@ -78,7 +78,7 @@ describe('DashParser SegmentBase', function() { }); it('inherits from Period', async () => { - let source = [ + const source = [ '<MPD mediaPresentationDuration="PT75S">', ' <Period>', ' <BaseURL>http://example.com</BaseURL>', @@ -96,7 +96,7 @@ describe('DashParser SegmentBase', function() { .setResponseText('dummy://foo', source) .setResponseText('http://example.com', ''); - let manifest = await parser.start('dummy://foo', playerInterface); + const manifest = await parser.start('dummy://foo', playerInterface); expect(manifest).toEqual(Dash.makeManifestFromInit('init.mp4', 201, 300)); await Dash.callCreateSegmentIndex(manifest); @@ -105,7 +105,7 @@ describe('DashParser SegmentBase', function() { }); it('inherits from AdaptationSet', async () => { - let source = [ + const source = [ '<MPD mediaPresentationDuration="PT75S">', ' <Period>', ' <AdaptationSet mimeType="video/mp4">', @@ -123,7 +123,7 @@ describe('DashParser SegmentBase', function() { .setResponseText('dummy://foo', source) .setResponseText('http://example.com', ''); - let manifest = await parser.start('dummy://foo', playerInterface); + const manifest = await parser.start('dummy://foo', playerInterface); expect(manifest).toEqual(Dash.makeManifestFromInit('init.mp4', 201, 300)); await Dash.callCreateSegmentIndex(manifest); @@ -132,7 +132,7 @@ describe('DashParser SegmentBase', function() { }); it('does not require sourceURL in Initialization', async () => { - let source = [ + const source = [ '<MPD mediaPresentationDuration="PT75S">', ' <Period>', ' <AdaptationSet mimeType="video/mp4">', @@ -151,7 +151,7 @@ describe('DashParser SegmentBase', function() { .setResponseText('dummy://foo', source) .setResponseText('http://example.com/stream.mp4', ''); - let manifest = await parser.start('dummy://foo', playerInterface); + const manifest = await parser.start('dummy://foo', playerInterface); expect(manifest).toEqual(Dash.makeManifestFromInit('stream.mp4', 201, 300)); await Dash.callCreateSegmentIndex(manifest); @@ -160,7 +160,7 @@ describe('DashParser SegmentBase', function() { }); it('merges across levels', async () => { - let source = [ + const source = [ '<MPD mediaPresentationDuration="PT75S">', ' <Period>', ' <BaseURL>http://example.com</BaseURL>', @@ -185,7 +185,7 @@ describe('DashParser SegmentBase', function() { .setResponseText('dummy://foo', source) .setResponseText('http://example.com/index.mp4', ''); - let manifest = await parser.start('dummy://foo', playerInterface); + const manifest = await parser.start('dummy://foo', playerInterface); expect(manifest).toEqual( Dash.makeManifestFromInit('init.mp4', 201, 300, 10)); await Dash.callCreateSegmentIndex(manifest); @@ -195,7 +195,7 @@ describe('DashParser SegmentBase', function() { }); it('merges and overrides across levels', async () => { - let source = [ + const source = [ '<MPD mediaPresentationDuration="PT75S">', ' <Period>', ' <BaseURL>http://example.com</BaseURL>', @@ -219,7 +219,7 @@ describe('DashParser SegmentBase', function() { .setResponseText('dummy://foo', source) .setResponseText('http://example.com', ''); - let manifest = await parser.start('dummy://foo', playerInterface); + const manifest = await parser.start('dummy://foo', playerInterface); expect(manifest).toEqual( Dash.makeManifestFromInit('special.mp4', 0, null, 20)); await Dash.callCreateSegmentIndex(manifest); @@ -229,7 +229,7 @@ describe('DashParser SegmentBase', function() { }); it('does not assume the same timescale as media', async () => { - let source = [ + const source = [ '<MPD mediaPresentationDuration="PT75S">', ' <Period>', ' <AdaptationSet mimeType="video/mp4">', @@ -248,18 +248,18 @@ describe('DashParser SegmentBase', function() { .setResponseText('dummy://foo', source) .setResponseValue('http://example.com/index.mp4', indexSegment); - let manifest = await parser.start('dummy://foo', playerInterface); - let video = manifest.periods[0].variants[0].video; + const manifest = await parser.start('dummy://foo', playerInterface); + const video = manifest.periods[0].variants[0].video; await video.createSegmentIndex(); // real data, should succeed - let reference = video.getSegmentReference(0); + const reference = video.getSegmentReference(0); expect(reference.startTime).toEqual(-2); expect(reference.endTime).toEqual(10); // would be 12 without PTO }); describe('fails for', function() { it('unsupported container', async () => { - let source = [ + const source = [ '<MPD mediaPresentationDuration="PT75S">', ' <Period>', ' <BaseURL>http://example.com</BaseURL>', @@ -271,7 +271,7 @@ describe('DashParser SegmentBase', function() { ' </Period>', '</MPD>', ].join('\n'); - let error = new shaka.util.Error( + const error = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.MANIFEST, shaka.util.Error.Code.DASH_UNSUPPORTED_CONTAINER); @@ -279,7 +279,7 @@ describe('DashParser SegmentBase', function() { }); it('missing init segment for WebM', async () => { - let source = [ + const source = [ '<MPD mediaPresentationDuration="PT75S">', ' <Period>', ' <BaseURL>http://example.com</BaseURL>', @@ -291,7 +291,7 @@ describe('DashParser SegmentBase', function() { ' </Period>', '</MPD>', ].join('\n'); - let error = new shaka.util.Error( + const error = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.MANIFEST, shaka.util.Error.Code.DASH_WEBM_MISSING_INIT); @@ -299,7 +299,7 @@ describe('DashParser SegmentBase', function() { }); it('no @indexRange nor RepresentationIndex', async () => { - let source = [ + const source = [ '<MPD mediaPresentationDuration="PT75S">', ' <Period>', ' <BaseURL>http://example.com</BaseURL>', @@ -313,7 +313,7 @@ describe('DashParser SegmentBase', function() { ' </Period>', '</MPD>', ].join('\n'); - let error = new shaka.util.Error( + const error = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.MANIFEST, shaka.util.Error.Code.DASH_NO_SEGMENT_INFO); diff --git a/test/dash/dash_parser_segment_list_unit.js b/test/dash/dash_parser_segment_list_unit.js index 0a1f75923a..0ab632743e 100644 --- a/test/dash/dash_parser_segment_list_unit.js +++ b/test/dash/dash_parser_segment_list_unit.js @@ -29,7 +29,7 @@ describe('DashParser SegmentList', function() { ]); it('truncates segments when lengths don\'t match', async () => { - let source = Dash.makeSimpleManifestText([ + const source = Dash.makeSimpleManifestText([ '<SegmentList>', ' <SegmentURL media="s1.mp4" />', ' <SegmentURL media="s2.mp4" />', @@ -42,7 +42,7 @@ describe('DashParser SegmentList', function() { ' </SegmentTimeline>', '</SegmentList>', ], 65 /* duration */); - let references = [ + const references = [ ManifestParser.makeReference('s1.mp4', 1, 50, 60, baseUri), ManifestParser.makeReference('s2.mp4', 2, 60, 65, baseUri), ]; @@ -50,19 +50,19 @@ describe('DashParser SegmentList', function() { }); it('supports single segment', async () => { - let source = Dash.makeSimpleManifestText([ + const source = Dash.makeSimpleManifestText([ '<SegmentList>', ' <SegmentURL media="s1.mp4" />', '</SegmentList>', ], 30 /* duration */); - let references = [ManifestParser.makeReference('s1.mp4', 1, + const references = [ManifestParser.makeReference('s1.mp4', 1, 0, 30, baseUri)]; await Dash.testSegmentIndex(source, references); }); describe('duration', function() { it('basic support', async () => { - let source = Dash.makeSimpleManifestText([ + const source = Dash.makeSimpleManifestText([ '<SegmentList startNumber="1" duration="10">', ' <SegmentURL media="s1.mp4" />', ' <SegmentURL media="s2.mp4" />', @@ -70,7 +70,7 @@ describe('DashParser SegmentList', function() { ' <SegmentURL media="s4.mp4" />', '</SegmentList>', ]); - let references = [ + const references = [ ManifestParser.makeReference('s1.mp4', 1, 0, 10, baseUri), ManifestParser.makeReference('s2.mp4', 2, 10, 20, baseUri), ManifestParser.makeReference('s3.mp4', 3, 20, 30, baseUri), @@ -80,7 +80,7 @@ describe('DashParser SegmentList', function() { }); it('uses @startNumber correctly', async () => { - let source = Dash.makeSimpleManifestText([ + const source = Dash.makeSimpleManifestText([ '<SegmentList startNumber="5" duration="10">', ' <SegmentURL media="s1.mp4" />', ' <SegmentURL media="s2.mp4" />', @@ -88,7 +88,7 @@ describe('DashParser SegmentList', function() { ' <SegmentURL media="s4.mp4" />', '</SegmentList>', ]); - let references = [ + const references = [ ManifestParser.makeReference('s1.mp4', 5, 40, 50, baseUri), ManifestParser.makeReference('s2.mp4', 6, 50, 60, baseUri), ManifestParser.makeReference('s3.mp4', 7, 60, 70, baseUri), @@ -98,13 +98,13 @@ describe('DashParser SegmentList', function() { }); it('supports @startNumber=0', async () => { - let source = Dash.makeSimpleManifestText([ + const source = Dash.makeSimpleManifestText([ '<SegmentList startNumber="0" duration="10">', ' <SegmentURL media="s1.mp4" />', ' <SegmentURL media="s2.mp4" />', '</SegmentList>', ]); - let references = [ + const references = [ ManifestParser.makeReference('s1.mp4', 1, 0, 10, baseUri), ManifestParser.makeReference('s2.mp4', 2, 10, 20, baseUri), ]; @@ -112,7 +112,7 @@ describe('DashParser SegmentList', function() { }); it('supports @timescale', async () => { - let source = Dash.makeSimpleManifestText([ + const source = Dash.makeSimpleManifestText([ '<SegmentList startNumber="1" timescale="9000" duration="18000">', ' <SegmentURL media="s1.mp4" />', ' <SegmentURL media="s2.mp4" />', @@ -120,7 +120,7 @@ describe('DashParser SegmentList', function() { ' <SegmentURL media="s4.mp4" />', '</SegmentList>', ]); - let references = [ + const references = [ ManifestParser.makeReference('s1.mp4', 1, 0, 2, baseUri), ManifestParser.makeReference('s2.mp4', 2, 2, 4, baseUri), ManifestParser.makeReference('s3.mp4', 3, 4, 6, baseUri), @@ -132,14 +132,14 @@ describe('DashParser SegmentList', function() { describe('rejects streams with', function() { it('no @duration or SegmentTimeline', async () => { - let source = Dash.makeSimpleManifestText([ + const source = Dash.makeSimpleManifestText([ '<SegmentList>', ' <SegmentURL media="s1.mp4" />', ' <SegmentURL media="s2.mp4" />', ' <SegmentURL media="s3.mp4" />', '</SegmentList>', ]); - let error = new shaka.util.Error( + const error = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.MANIFEST, shaka.util.Error.Code.DASH_NO_SEGMENT_INFO); @@ -147,12 +147,12 @@ describe('DashParser SegmentList', function() { }); it('one segment and no durations', async () => { - let source = Dash.makeSimpleManifestText([ + const source = Dash.makeSimpleManifestText([ '<SegmentList>', ' <SegmentURL media="s1.mp4" />', '</SegmentList>', ]); - let error = new shaka.util.Error( + const error = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.MANIFEST, shaka.util.Error.Code.DASH_NO_SEGMENT_INFO); @@ -160,14 +160,14 @@ describe('DashParser SegmentList', function() { }); it('empty SegmentTimeline', async () => { - let source = Dash.makeSimpleManifestText([ + const source = Dash.makeSimpleManifestText([ '<SegmentList>', ' <SegmentURL media="s1.mp4" />', ' <SegmentTimeline>', ' </SegmentTimeline>', '</SegmentList>', ]); - let error = new shaka.util.Error( + const error = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.MANIFEST, shaka.util.Error.Code.DASH_NO_SEGMENT_INFO); @@ -177,7 +177,7 @@ describe('DashParser SegmentList', function() { describe('inherits', function() { it('attributes', async () => { - let source = [ + const source = [ '<MPD mediaPresentationDuration="PT200S">', ' <Period>', ' <SegmentList startNumber="40" />', @@ -196,7 +196,7 @@ describe('DashParser SegmentList', function() { ' </Period>', '</MPD>', ].join('\n'); - let references = [ + const references = [ ManifestParser.makeReference('s1.mp4', 1, 0, 50, baseUri), ManifestParser.makeReference('s2.mp4', 2, 50, 100, baseUri), ManifestParser.makeReference('s3.mp4', 3, 100, 150, baseUri), @@ -206,7 +206,7 @@ describe('DashParser SegmentList', function() { }); it('SegmentTimeline', async () => { - let source = [ + const source = [ '<MPD mediaPresentationDuration="PT73S">', ' <Period>', ' <SegmentList>', @@ -229,7 +229,7 @@ describe('DashParser SegmentList', function() { ' </Period>', '</MPD>', ].join('\n'); - let references = [ + const references = [ ManifestParser.makeReference('s1.mp4', 1, 50, 60, baseUri), ManifestParser.makeReference('s2.mp4', 2, 60, 65, baseUri), ManifestParser.makeReference('s3.mp4', 3, 65, 73, baseUri), @@ -238,7 +238,7 @@ describe('DashParser SegmentList', function() { }); it('SegmentURL', async () => { - let source = [ + const source = [ '<MPD mediaPresentationDuration="PT73S">', ' <Period>', ' <SegmentList>', @@ -261,7 +261,7 @@ describe('DashParser SegmentList', function() { ' </Period>', '</MPD>', ].join('\n'); - let references = [ + const references = [ ManifestParser.makeReference('s1.mp4', 1, 50, 60, baseUri), ManifestParser.makeReference('s2.mp4', 2, 60, 65, baseUri), ManifestParser.makeReference('s3.mp4', 3, 65, 73, baseUri), @@ -272,7 +272,7 @@ describe('DashParser SegmentList', function() { describe('Segment start', function() { it('shoud be adjusted with presentationTimeOffset', async () => { - let source = [ + const source = [ '<MPD mediaPresentationDuration="PT70S">', ' <Period>', ' <SegmentList>', @@ -297,7 +297,7 @@ describe('DashParser SegmentList', function() { ' </Period>', '</MPD>', ].join('\n'); - let references = [ + const references = [ ManifestParser.makeReference('s1.mp4', 1, 40, 50, baseUri), ManifestParser.makeReference('s2.mp4', 2, 50, 55, baseUri), ManifestParser.makeReference('s3.mp4', 3, 55, 63, baseUri), diff --git a/test/dash/dash_parser_segment_template_unit.js b/test/dash/dash_parser_segment_template_unit.js index 4412cd3bb0..095b610027 100644 --- a/test/dash/dash_parser_segment_template_unit.js +++ b/test/dash/dash_parser_segment_template_unit.js @@ -46,11 +46,11 @@ describe('DashParser SegmentTemplate', function() { describe('duration', function() { it('basic support', async () => { - let source = Dash.makeSimpleManifestText([ + const source = Dash.makeSimpleManifestText([ '<SegmentTemplate startNumber="1" media="s$Number$.mp4"', ' duration="10" />', ], 60 /* duration */); - let references = [ + const references = [ ManifestParser.makeReference('s1.mp4', 0, 0, 10, baseUri), ManifestParser.makeReference('s2.mp4', 1, 10, 20, baseUri), ManifestParser.makeReference('s3.mp4', 2, 20, 30, baseUri), @@ -62,11 +62,11 @@ describe('DashParser SegmentTemplate', function() { }); it('with @startNumber > 1', async () => { - let source = Dash.makeSimpleManifestText([ + const source = Dash.makeSimpleManifestText([ '<SegmentTemplate startNumber="10" media="s$Number$.mp4"', ' duration="10" />', ], 30 /* duration */); - let references = [ + const references = [ ManifestParser.makeReference('s10.mp4', 0, 0, 10, baseUri), ManifestParser.makeReference('s11.mp4', 1, 10, 20, baseUri), ManifestParser.makeReference('s12.mp4', 2, 20, 30, baseUri), @@ -75,7 +75,7 @@ describe('DashParser SegmentTemplate', function() { }); it('honors presentationTimeOffset', function(done) { - let source = Dash.makeSimpleManifestText([ + const source = Dash.makeSimpleManifestText([ '<SegmentTemplate media="s$Number$.mp4" duration="10"', ' presentationTimeOffset="50" />', ], 30 /* duration */); @@ -86,7 +86,7 @@ describe('DashParser SegmentTemplate', function() { expect(manifest.periods.length).toBe(1); expect(manifest.periods[0].variants.length).toBe(1); - let stream = manifest.periods[0].variants[0].video; + const stream = manifest.periods[0].variants[0].video; expect(stream).toBeTruthy(); expect(stream.presentationTimeOffset).toBe(50); expect(stream.getSegmentReference(0)).toEqual( @@ -98,20 +98,20 @@ describe('DashParser SegmentTemplate', function() { }); it('handles segments larger than the period', async () => { - let source = Dash.makeSimpleManifestText([ + const source = Dash.makeSimpleManifestText([ '<SegmentTemplate media="s$Number$.mp4" duration="60" />', ], 30 /* duration */); // The first segment is number 1 and position 0. // Although the segment is 60 seconds long, it is clipped to the period // duration of 30 seconds. - let references = [ + const references = [ ManifestParser.makeReference('s1.mp4', 0, 0, 30, baseUri), ]; await Dash.testSegmentIndex(source, references); }); it('presentation start is parsed correctly', function(done) { - let source = Dash.makeSimpleManifestText([ + const source = Dash.makeSimpleManifestText([ '<SegmentTemplate media="s$Number$.mp4" duration="60" />', ], 30 /* duration */, /* startTime */ 30); @@ -126,7 +126,7 @@ describe('DashParser SegmentTemplate', function() { describe('index', function() { it('basic support', async () => { - let source = Dash.makeSimpleManifestText([ + const source = Dash.makeSimpleManifestText([ '<SegmentTemplate startNumber="1" index="index-$Bandwidth$.mp4"', ' initialization="init-$Bandwidth$.mp4" />', ]); @@ -135,7 +135,7 @@ describe('DashParser SegmentTemplate', function() { .setResponseText('dummy://foo', source) .setResponseText('http://example.com/index-500.mp4', ''); - let manifest = await parser.start('dummy://foo', playerInterface); + const manifest = await parser.start('dummy://foo', playerInterface); expect(manifest).toEqual( Dash.makeManifestFromInit('init-500.mp4', 0, null)); await Dash.callCreateSegmentIndex(manifest); @@ -146,7 +146,7 @@ describe('DashParser SegmentTemplate', function() { }); it('defaults to index with multiple segment sources', async () => { - let source = Dash.makeSimpleManifestText([ + const source = Dash.makeSimpleManifestText([ '<SegmentTemplate startNumber="1" index="index-$Bandwidth$.mp4"', ' initialization="init-$Bandwidth$.mp4">', ' <SegmentTimeline>', @@ -159,7 +159,7 @@ describe('DashParser SegmentTemplate', function() { .setResponseText('dummy://foo', source) .setResponseText('http://example.com/index-500.mp4', ''); - let manifest = await parser.start('dummy://foo', playerInterface); + const manifest = await parser.start('dummy://foo', playerInterface); expect(manifest).toEqual( Dash.makeManifestFromInit('init-500.mp4', 0, null)); await Dash.callCreateSegmentIndex(manifest); @@ -170,7 +170,7 @@ describe('DashParser SegmentTemplate', function() { }); it('requests init data for WebM', async () => { - let source = [ + const source = [ '<MPD mediaPresentationDuration="PT75S">', ' <Period>', ' <BaseURL>http://example.com</BaseURL>', @@ -190,7 +190,7 @@ describe('DashParser SegmentTemplate', function() { .setResponseText('http://example.com/index-500.webm', '') .setResponseText('http://example.com/init-500.webm', ''); - let manifest = await parser.start('dummy://foo', playerInterface); + const manifest = await parser.start('dummy://foo', playerInterface); expect(manifest).toEqual( Dash.makeManifestFromInit('init-500.webm', 0, null)); await Dash.callCreateSegmentIndex(manifest); @@ -203,7 +203,7 @@ describe('DashParser SegmentTemplate', function() { }); it('inherits from Period', async () => { - let source = [ + const source = [ '<MPD mediaPresentationDuration="PT75S">', ' <Period>', ' <BaseURL>http://example.com</BaseURL>', @@ -220,7 +220,7 @@ describe('DashParser SegmentTemplate', function() { .setResponseText('dummy://foo', source) .setResponseText('http://example.com/index-500.mp4', ''); - let manifest = await parser.start('dummy://foo', playerInterface); + const manifest = await parser.start('dummy://foo', playerInterface); expect(manifest).toEqual( Dash.makeManifestFromInit('init-500.mp4', 0, null)); await Dash.callCreateSegmentIndex(manifest); @@ -231,7 +231,7 @@ describe('DashParser SegmentTemplate', function() { }); it('inherits from AdaptationSet', async () => { - let source = [ + const source = [ '<MPD mediaPresentationDuration="PT75S">', ' <Period>', ' <AdaptationSet mimeType="video/mp4">', @@ -248,7 +248,7 @@ describe('DashParser SegmentTemplate', function() { .setResponseText('dummy://foo', source) .setResponseText('http://example.com/index-500.mp4', ''); - let manifest = await parser.start('dummy://foo', playerInterface); + const manifest = await parser.start('dummy://foo', playerInterface); expect(manifest).toEqual( Dash.makeManifestFromInit('init-500.mp4', 0, null)); await Dash.callCreateSegmentIndex(manifest); @@ -261,7 +261,7 @@ describe('DashParser SegmentTemplate', function() { describe('media template', function() { it('defaults to timeline when also has duration', async () => { - let source = Dash.makeSimpleManifestText([ + const source = Dash.makeSimpleManifestText([ '<SegmentTemplate startNumber="0" duration="10"', ' media="$Number$-$Time$-$Bandwidth$.mp4">', ' <SegmentTimeline>', @@ -269,7 +269,7 @@ describe('DashParser SegmentTemplate', function() { ' </SegmentTimeline>', '</SegmentTemplate>', ], 45 /* duration */); - let references = [ + const references = [ ManifestParser.makeReference('0-0-500.mp4', 0, 0, 15, baseUri), ManifestParser.makeReference('1-15-500.mp4', 1, 15, 30, baseUri), ManifestParser.makeReference('2-30-500.mp4', 2, 30, 45, baseUri), @@ -278,11 +278,11 @@ describe('DashParser SegmentTemplate', function() { }); it('with @startnumber = 0', async () => { - let source = Dash.makeSimpleManifestText([ + const source = Dash.makeSimpleManifestText([ '<SegmentTemplate startNumber="0" duration="10"', ' media="$Number$-$Time$-$Bandwidth$.mp4" />', ], 30 /* duration */); - let references = [ + const references = [ ManifestParser.makeReference('0-0-500.mp4', 0, 0, 10, baseUri), ManifestParser.makeReference('1-10-500.mp4', 1, 10, 20, baseUri), ManifestParser.makeReference('2-20-500.mp4', 2, 20, 30, baseUri), @@ -291,11 +291,11 @@ describe('DashParser SegmentTemplate', function() { }); it('with @startNumber = 1', async () => { - let source = Dash.makeSimpleManifestText([ + const source = Dash.makeSimpleManifestText([ '<SegmentTemplate startNumber="1" duration="10"', ' media="$Number$-$Time$-$Bandwidth$.mp4" />', ], 30 /* duration */); - let references = [ + const references = [ ManifestParser.makeReference('1-0-500.mp4', 0, 0, 10, baseUri), ManifestParser.makeReference('2-10-500.mp4', 1, 10, 20, baseUri), ManifestParser.makeReference('3-20-500.mp4', 2, 20, 30, baseUri), @@ -304,11 +304,11 @@ describe('DashParser SegmentTemplate', function() { }); it('with @startNumber > 1', async () => { - let source = Dash.makeSimpleManifestText([ + const source = Dash.makeSimpleManifestText([ '<SegmentTemplate startNumber="10" duration="10"', ' media="$Number$-$Time$-$Bandwidth$.mp4" />', ], 30 /* duration */); - let references = [ + const references = [ ManifestParser.makeReference('10-0-500.mp4', 0, 0, 10, baseUri), ManifestParser.makeReference('11-10-500.mp4', 1, 10, 20, baseUri), ManifestParser.makeReference('12-20-500.mp4', 2, 20, 30, baseUri), @@ -317,11 +317,11 @@ describe('DashParser SegmentTemplate', function() { }); it('with @timescale > 1', async () => { - let source = Dash.makeSimpleManifestText([ + const source = Dash.makeSimpleManifestText([ '<SegmentTemplate startNumber="1" timescale="9000" duration="9000"', ' media="$Number$-$Time$-$Bandwidth$.mp4" />', ], 3 /* duration */); - let references = [ + const references = [ ManifestParser.makeReference('1-0-500.mp4', 0, 0, 1, baseUri), ManifestParser.makeReference('2-9000-500.mp4', 1, 1, 2, baseUri), ManifestParser.makeReference('3-18000-500.mp4', 2, 2, 3, baseUri), @@ -330,7 +330,7 @@ describe('DashParser SegmentTemplate', function() { }); it('across representations', async () => { - let source = [ + const source = [ '<MPD>', ' <Period duration="PT60S">', ' <AdaptationSet mimeType="video/webm">', @@ -346,10 +346,10 @@ describe('DashParser SegmentTemplate', function() { ].join('\n'); fakeNetEngine.setResponseText('dummy://foo', source); - let actual = await parser.start('dummy://foo', playerInterface); + const actual = await parser.start('dummy://foo', playerInterface); expect(actual).toBeTruthy(); - let variants = actual.periods[0].variants; + const variants = actual.periods[0].variants; expect(variants.length).toBe(3); expect(variants[0].video.findSegmentPosition(0)).toBe(0); @@ -375,7 +375,7 @@ describe('DashParser SegmentTemplate', function() { describe('rejects streams with', function() { it('bad container type', async () => { - let source = [ + const source = [ '<MPD mediaPresentationDuration="PT75S">', ' <Period>', ' <BaseURL>http://example.com</BaseURL>', @@ -389,7 +389,7 @@ describe('DashParser SegmentTemplate', function() { ' </Period>', '</MPD>', ].join('\n'); - let error = new shaka.util.Error( + const error = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.MANIFEST, shaka.util.Error.Code.DASH_UNSUPPORTED_CONTAINER); @@ -397,7 +397,7 @@ describe('DashParser SegmentTemplate', function() { }); it('no init data with webm', async () => { - let source = [ + const source = [ '<MPD>', ' <Period duration="PT30S">', ' <BaseURL>http://example.com</BaseURL>', @@ -410,7 +410,7 @@ describe('DashParser SegmentTemplate', function() { ' </Period>', '</MPD>', ].join('\n'); - let error = new shaka.util.Error( + const error = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.MANIFEST, shaka.util.Error.Code.DASH_WEBM_MISSING_INIT); @@ -418,10 +418,10 @@ describe('DashParser SegmentTemplate', function() { }); it('not enough segment info', async () => { - let source = Dash.makeSimpleManifestText([ + const source = Dash.makeSimpleManifestText([ '<SegmentTemplate startNumber="1" />', ]); - let error = new shaka.util.Error( + const error = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.MANIFEST, shaka.util.Error.Code.DASH_NO_SEGMENT_INFO); @@ -429,14 +429,14 @@ describe('DashParser SegmentTemplate', function() { }); it('no media template', async () => { - let source = Dash.makeSimpleManifestText([ + const source = Dash.makeSimpleManifestText([ '<SegmentTemplate startNumber="1">', ' <SegmentTimeline>', ' <S d="10" />', ' </SegmentTimeline>', '</SegmentTemplate>', ]); - let error = new shaka.util.Error( + const error = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.MANIFEST, shaka.util.Error.Code.DASH_NO_SEGMENT_INFO); diff --git a/test/dash/mpd_utils_unit.js b/test/dash/mpd_utils_unit.js index 2a798ce869..d46b76bc17 100644 --- a/test/dash/mpd_utils_unit.js +++ b/test/dash/mpd_utils_unit.js @@ -163,12 +163,12 @@ describe('MpdUtils', function() { describe('createTimeline', function() { it('works in normal case', function() { - let timePoints = [ + const timePoints = [ createTimePoint(0, 10, 0), createTimePoint(10, 10, 0), createTimePoint(20, 10, 0), ]; - let result = [ + const result = [ {start: 0, end: 10}, {start: 10, end: 20}, {start: 20, end: 30}, @@ -177,12 +177,12 @@ describe('MpdUtils', function() { }); it('handles null start time', function() { - let timePoints = [ + const timePoints = [ createTimePoint(0, 10, 0), createTimePoint(null, 10, 0), createTimePoint(null, 10, 0), ]; - let result = [ + const result = [ {start: 0, end: 10}, {start: 10, end: 20}, {start: 20, end: 30}, @@ -191,11 +191,11 @@ describe('MpdUtils', function() { }); it('handles gaps', function() { - let timePoints = [ + const timePoints = [ createTimePoint(0, 10, 0), createTimePoint(15, 10, 0), ]; - let result = [ + const result = [ {start: 0, end: 15}, {start: 15, end: 25}, ]; @@ -203,11 +203,11 @@ describe('MpdUtils', function() { }); it('handles overlap', function() { - let timePoints = [ + const timePoints = [ createTimePoint(0, 15, 0), createTimePoint(10, 10, 0), ]; - let result = [ + const result = [ {start: 0, end: 10}, {start: 10, end: 20}, ]; @@ -215,11 +215,11 @@ describe('MpdUtils', function() { }); it('handles repetitions', function() { - let timePoints = [ + const timePoints = [ createTimePoint(0, 10, 5), createTimePoint(60, 10, 0), ]; - let result = [ + const result = [ {start: 0, end: 10}, {start: 10, end: 20}, {start: 20, end: 30}, @@ -232,12 +232,12 @@ describe('MpdUtils', function() { }); it('handles null repeat', function() { - let timePoints = [ + const timePoints = [ createTimePoint(0, 10, 0), createTimePoint(10, 10, null), createTimePoint(20, 10, 0), ]; - let result = [ + const result = [ {start: 0, end: 10}, {start: 10, end: 20}, {start: 20, end: 30}, @@ -246,11 +246,11 @@ describe('MpdUtils', function() { }); it('handles repetitions with gap', function() { - let timePoints = [ + const timePoints = [ createTimePoint(0, 10, 2), createTimePoint(35, 10, 0), ]; - let result = [ + const result = [ {start: 0, end: 10}, {start: 10, end: 20}, {start: 20, end: 35}, @@ -260,12 +260,12 @@ describe('MpdUtils', function() { }); it('handles negative repetitions', function() { - let timePoints = [ + const timePoints = [ createTimePoint(0, 10, 0), createTimePoint(10, 10, -1), createTimePoint(40, 10, 0), ]; - let result = [ + const result = [ {start: 0, end: 10}, {start: 10, end: 20}, {start: 20, end: 30}, @@ -276,12 +276,12 @@ describe('MpdUtils', function() { }); it('handles negative repetitions with uneven border', function() { - let timePoints = [ + const timePoints = [ createTimePoint(0, 10, 0), createTimePoint(10, 10, -1), createTimePoint(45, 5, 0), ]; - let result = [ + const result = [ {start: 0, end: 10}, {start: 10, end: 20}, {start: 20, end: 30}, @@ -293,35 +293,35 @@ describe('MpdUtils', function() { }); it('handles negative repetitions w/ bad next start time', function() { - let timePoints = [ + const timePoints = [ createTimePoint(0, 10, 0), createTimePoint(10, 10, -1), createTimePoint(5, 10, 0), ]; - let result = [ + const result = [ {start: 0, end: 10}, ]; checkTimePoints(timePoints, result, 1, 0, Infinity); }); it('handles negative repetitions w/ null next start time', function() { - let timePoints = [ + const timePoints = [ createTimePoint(0, 10, 0), createTimePoint(10, 10, -1), createTimePoint(null, 10, 0), ]; - let result = [ + const result = [ {start: 0, end: 10}, ]; checkTimePoints(timePoints, result, 1, 0, Infinity); }); it('handles negative repetitions at end', function() { - let timePoints = [ + const timePoints = [ createTimePoint(0, 10, 0), createTimePoint(10, 5, -1), ]; - let result = [ + const result = [ {start: 0, end: 10}, {start: 10, end: 15}, {start: 15, end: 20}, @@ -331,23 +331,23 @@ describe('MpdUtils', function() { }); it('handles negative repetitions at end w/o Period length', function() { - let timePoints = [ + const timePoints = [ createTimePoint(0, 10, 0), createTimePoint(10, 5, -1), ]; - let result = [ + const result = [ {start: 0, end: 10}, ]; checkTimePoints(timePoints, result, 1, 0, Infinity); }); it('handles negative repetitions at end w/ bad Period length', function() { - let timePoints = [ + const timePoints = [ createTimePoint(0, 10, 0), createTimePoint(10, 10, 0), createTimePoint(25, 5, -1), ]; - let result = [ + const result = [ {start: 0, end: 10}, {start: 10, end: 20}, ]; @@ -355,14 +355,14 @@ describe('MpdUtils', function() { }); it('ignores elements after null duration', function() { - let timePoints = [ + const timePoints = [ createTimePoint(0, 10, 0), createTimePoint(10, 10, 0), createTimePoint(20, null, 0), createTimePoint(30, 10, 0), createTimePoint(40, 10, 0), ]; - let result = [ + const result = [ {start: 0, end: 10}, {start: 10, end: 20}, ]; @@ -370,13 +370,13 @@ describe('MpdUtils', function() { }); it('adjust start with presentationTimeOffset', function() { - let timePoints = [ + const timePoints = [ createTimePoint(10, 10, 0), createTimePoint(20, 10, 0), createTimePoint(30, 10, 0), createTimePoint(40, 10, 0), ]; - let result = [ + const result = [ {start: 0, end: 10}, {start: 10, end: 20}, {start: 20, end: 30}, @@ -410,9 +410,9 @@ describe('MpdUtils', function() { function checkTimePoints(points, expected, timescale, presentationTimeOffset, periodDuration) { // Construct a SegmentTimeline Node object. - let xmlLines = ['<?xml version="1.0"?>', '<SegmentTimeline>']; + const xmlLines = ['<?xml version="1.0"?>', '<SegmentTimeline>']; for (let i = 0; i < points.length; i++) { - let p = points[i]; + const p = points[i]; xmlLines.push('<S' + (p.t != null ? ' t="' + p.t + '"' : '') + (p.d != null ? ' d="' + p.d + '"' : '') + @@ -420,12 +420,13 @@ describe('MpdUtils', function() { ' />'); } xmlLines.push('</SegmentTimeline>'); - let parser = new DOMParser(); - let xml = parser.parseFromString(xmlLines.join('\n'), 'application/xml'); - let segmentTimeline = xml.documentElement; + const parser = new DOMParser(); + const xml = + parser.parseFromString(xmlLines.join('\n'), 'application/xml'); + const segmentTimeline = xml.documentElement; console.assert(segmentTimeline); - let timeline = MpdUtils.createTimeline( + const timeline = MpdUtils.createTimeline( segmentTimeline, timescale, presentationTimeOffset, periodDuration); expect(timeline).toBeTruthy(); @@ -457,10 +458,10 @@ describe('MpdUtils', function() { }); it('will replace elements and children', async () => { - let baseXMLString = inBaseContainer( + const baseXMLString = inBaseContainer( '<ToReplace xlink:href="https://xlink1" xlink:actuate="onLoad" />'); - let xlinkXMLString = '<ToReplace variable="1"><Contents /></ToReplace>'; - let desiredXMLString = inBaseContainer( + const xlinkXMLString = '<ToReplace variable="1"><Contents /></ToReplace>'; + const desiredXMLString = inBaseContainer( '<ToReplace variable="1"><Contents /></ToReplace>'); fakeNetEngine.setResponseText('https://xlink1', xlinkXMLString); @@ -468,11 +469,11 @@ describe('MpdUtils', function() { }); it('preserves non-xlink attributes', async () => { - let baseXMLString = inBaseContainer( + const baseXMLString = inBaseContainer( '<ToReplace otherVariable="q" xlink:href="https://xlink1" ' + 'xlink:actuate="onLoad" />'); - let xlinkXMLString = '<ToReplace variable="1"><Contents /></ToReplace>'; - let desiredXMLString = inBaseContainer( + const xlinkXMLString = '<ToReplace variable="1"><Contents /></ToReplace>'; + const desiredXMLString = inBaseContainer( '<ToReplace otherVariable="q" variable="1"><Contents /></ToReplace>'); fakeNetEngine.setResponseText('https://xlink1', xlinkXMLString); @@ -480,11 +481,11 @@ describe('MpdUtils', function() { }); it('preserves text', async () => { - let baseXMLString = inBaseContainer( + const baseXMLString = inBaseContainer( '<ToReplace xlink:href="https://xlink1" xlink:actuate="onLoad" />'); - let xlinkXMLString = + const xlinkXMLString = '<ToReplace variable="1">TEXT CONTAINED WITHIN</ToReplace>'; - let desiredXMLString = inBaseContainer( + const desiredXMLString = inBaseContainer( '<ToReplace variable="1">TEXT CONTAINED WITHIN</ToReplace>'); fakeNetEngine.setResponseText('https://xlink1', xlinkXMLString); @@ -492,13 +493,14 @@ describe('MpdUtils', function() { }); it('supports multiple replacements', async () => { - let baseXMLString = inBaseContainer( + const baseXMLString = inBaseContainer( '<ToReplace xlink:href="https://xlink1" xlink:actuate="onLoad" />', '<ToReplace xlink:href="https://xlink2" xlink:actuate="onLoad" />'); - let xlinkXMLString1 = makeRecursiveXMLString(1, 'https://xlink3'); - let xlinkXMLString2 = '<ToReplace variable="2"><Contents /></ToReplace>'; - let xlinkXMLString3 = '<ToReplace otherVariable="blue" />'; - let desiredXMLString = inBaseContainer( + const xlinkXMLString1 = makeRecursiveXMLString(1, 'https://xlink3'); + const xlinkXMLString2 = + '<ToReplace variable="2"><Contents /></ToReplace>'; + const xlinkXMLString3 = '<ToReplace otherVariable="blue" />'; + const desiredXMLString = inBaseContainer( '<ToReplace xmlns="urn:mpeg:dash:schema:mpd:2011" ' + 'xmlns:xlink="http://www.w3.org/1999/xlink" variable="1">' + '<ToReplace otherVariable="blue" /></ToReplace>', @@ -512,11 +514,11 @@ describe('MpdUtils', function() { }); it('fails if loaded file is invalid xml', async () => { - let baseXMLString = inBaseContainer( + const baseXMLString = inBaseContainer( '<ToReplace xlink:href="https://xlink1" xlink:actuate="onLoad" />'); // Note this does not have a close angle bracket. - let xlinkXMLString = '<ToReplace></ToReplace'; - let expectedError = new shaka.util.Error( + const xlinkXMLString = '<ToReplace></ToReplace'; + const expectedError = new shaka.util.Error( Error.Severity.CRITICAL, Error.Category.MANIFEST, Error.Code.DASH_INVALID_XML, 'https://xlink1'); @@ -525,7 +527,7 @@ describe('MpdUtils', function() { }); it('fails if it recurses too many times', async () => { - let baseXMLString = inBaseContainer( + const baseXMLString = inBaseContainer( '<ToReplace xlink:href="https://xlink1" xlink:actuate="onLoad" />'); // Create a large but finite number of links, so this won't // infinitely recurse if there isn't a depth limit. @@ -535,7 +537,7 @@ describe('MpdUtils', function() { fakeNetEngine.setResponseText(key, value); } - let expectedError = new shaka.util.Error( + const expectedError = new shaka.util.Error( Error.Severity.CRITICAL, Error.Category.MANIFEST, Error.Code.DASH_XLINK_DEPTH_LIMIT); @@ -543,11 +545,11 @@ describe('MpdUtils', function() { }); it('preserves url parameters', async () => { - let baseXMLString = inBaseContainer( + const baseXMLString = inBaseContainer( '<ToReplace xlink:href="https://xlink1?parameter" ' + 'xlink:actuate="onLoad" />'); - let xlinkXMLString = '<ToReplace variable="1"><Contents /></ToReplace>'; - let desiredXMLString = inBaseContainer( + const xlinkXMLString = '<ToReplace variable="1"><Contents /></ToReplace>'; + const desiredXMLString = inBaseContainer( '<ToReplace variable="1"><Contents /></ToReplace>'); fakeNetEngine.setResponseText( @@ -556,11 +558,11 @@ describe('MpdUtils', function() { }); it('replaces existing contents', async () => { - let baseXMLString = inBaseContainer( + const baseXMLString = inBaseContainer( '<ToReplace xlink:href="https://xlink1" xlink:actuate="onLoad">' + '<Unwanted /></ToReplace>'); - let xlinkXMLString = '<ToReplace variable="1"><Contents /></ToReplace>'; - let desiredXMLString = inBaseContainer( + const xlinkXMLString = '<ToReplace variable="1"><Contents /></ToReplace>'; + const desiredXMLString = inBaseContainer( '<ToReplace variable="1"><Contents /></ToReplace>'); fakeNetEngine.setResponseText('https://xlink1', xlinkXMLString); @@ -568,21 +570,21 @@ describe('MpdUtils', function() { }); it('handles relative links', async () => { - let baseXMLString = inBaseContainer( + const baseXMLString = inBaseContainer( '<ToReplace xlink:href="xlink1" xlink:actuate="onLoad" />', '<ToReplace xlink:href="xlink2" xlink:actuate="onLoad" />'); - let xlinkXMLString1 = // This is loaded relative to base. + const xlinkXMLString1 = // This is loaded relative to base. makeRecursiveXMLString(1, 'xlink3'); - let xlinkXMLString2 = // This is loaded relative to base. + const xlinkXMLString2 = // This is loaded relative to base. '<ToReplace variable="2"><Contents /></ToReplace>'; - let xlinkXMLString3 = // This is loaded relative to string1. + const xlinkXMLString3 = // This is loaded relative to string1. '<ToReplace variable="3" />'; fakeNetEngine .setResponseText('https://base/xlink1', xlinkXMLString1) .setResponseText('https://base/xlink2', xlinkXMLString2) .setResponseText('https://base/xlink3', xlinkXMLString3); - let desiredXMLString = inBaseContainer( + const desiredXMLString = inBaseContainer( '<ToReplace xmlns="urn:mpeg:dash:schema:mpd:2011" ' + 'xmlns:xlink="http://www.w3.org/1999/xlink" variable="1">' + '<ToReplace variable="3" /></ToReplace>', @@ -592,11 +594,11 @@ describe('MpdUtils', function() { }); it('fails for actuate=onRequest', async () => { - let baseXMLString = inBaseContainer( + const baseXMLString = inBaseContainer( '<ToReplace xlink:href="https://xlink1" ' + 'xlink:actuate="onRequest" />'); - let xlinkXMLString = '<ToReplace variable="1"><Contents /></ToReplace>'; - let expectedError = new shaka.util.Error( + const xlinkXMLString = '<ToReplace variable="1"><Contents /></ToReplace>'; + const expectedError = new shaka.util.Error( Error.Severity.CRITICAL, Error.Category.MANIFEST, Error.Code.DASH_UNSUPPORTED_XLINK_ACTUATE); @@ -605,10 +607,10 @@ describe('MpdUtils', function() { }); it('fails for no actuate', async () => { - let baseXMLString = inBaseContainer( + const baseXMLString = inBaseContainer( '<ToReplace xlink:href="https://xlink1" />'); - let xlinkXMLString = '<ToReplace variable="1"><Contents /></ToReplace>'; - let expectedError = new shaka.util.Error( + const xlinkXMLString = '<ToReplace variable="1"><Contents /></ToReplace>'; + const expectedError = new shaka.util.Error( Error.Severity.CRITICAL, Error.Category.MANIFEST, Error.Code.DASH_UNSUPPORTED_XLINK_ACTUATE); @@ -617,17 +619,17 @@ describe('MpdUtils', function() { }); it('removes elements with resolve-to-zero', async () => { - let baseXMLString = inBaseContainer( + const baseXMLString = inBaseContainer( '<ToReplace xlink:href="urn:mpeg:dash:resolve-to-zero:2013" />'); - let desiredXMLString = inBaseContainer(); + const desiredXMLString = inBaseContainer(); await testSucceeds(baseXMLString, desiredXMLString, 0); }); it('needs the top-level to match the link\'s tagName', async () => { - let baseXMLString = inBaseContainer( + const baseXMLString = inBaseContainer( '<ToReplace xlink:href="https://xlink1" xlink:actuate="onLoad" />'); - let xlinkXMLString = '<BadTagName</BadTagName>'; + const xlinkXMLString = '<BadTagName</BadTagName>'; fakeNetEngine.setResponseText('https://xlink1', xlinkXMLString); await testFails(baseXMLString, null, 1); @@ -635,12 +637,12 @@ describe('MpdUtils', function() { it('doesn\'t error when set to fail gracefully', async () => { failGracefully = true; - let baseXMLString = inBaseContainer( + const baseXMLString = inBaseContainer( '<ToReplace xlink:href="https://xlink1" xlink:actuate="onLoad">' + '<DefaultContents />' + '</ToReplace>'); - let xlinkXMLString = '<BadTagName</BadTagName>'; - let desiredXMLString = inBaseContainer( + const xlinkXMLString = '<BadTagName</BadTagName>'; + const desiredXMLString = inBaseContainer( '<ToReplace><DefaultContents /></ToReplace>'); fakeNetEngine.setResponseText('https://xlink1', xlinkXMLString); @@ -648,7 +650,7 @@ describe('MpdUtils', function() { }); it('interrupts requests on abort', function(done) { - let baseXMLString = inBaseContainer( + const baseXMLString = inBaseContainer( '<ToReplace xlink:href="https://xlink1" xlink:actuate="onLoad" />'); // Create a few links. This is few enough that it would succeed if we // didn't abort it. @@ -658,11 +660,11 @@ describe('MpdUtils', function() { fakeNetEngine.setResponseText(key, value); } - let continuePromise = fakeNetEngine.delayNextRequest(); + const continuePromise = fakeNetEngine.delayNextRequest(); - let xml = parser.parseFromString(baseXMLString, 'text/xml') + const xml = parser.parseFromString(baseXMLString, 'text/xml') .documentElement; - let operation = MpdUtils.processXlinks( + const operation = MpdUtils.processXlinks( xml, retry, failGracefully, 'https://base', fakeNetEngine); shaka.test.Util.delay(0.1).then(() => { @@ -689,7 +691,7 @@ describe('MpdUtils', function() { }); it('ignores SegmentTimeline children', async () => { - let baseXMLString = inBaseContainer( + const baseXMLString = inBaseContainer( '<SegmentTimeline>' + ' <ToReplace xlink:href="https://xlink1" ' + ' xlink:actuate="onRequest" />' + @@ -699,9 +701,9 @@ describe('MpdUtils', function() { async function testSucceeds( baseXMLString, desiredXMLString, desiredNetCalls) { - let desiredXML = parser.parseFromString(desiredXMLString, 'text/xml') + const desiredXML = parser.parseFromString(desiredXMLString, 'text/xml') .documentElement; - let finalXML = await testRequest(baseXMLString); + const finalXML = await testRequest(baseXMLString); expect(fakeNetEngine.request).toHaveBeenCalledTimes(desiredNetCalls); expect(finalXML).toEqualElement(desiredXML); } @@ -725,7 +727,7 @@ describe('MpdUtils', function() { * @private */ function makeRecursiveXMLString(variable, link) { - let format = + const format = '<ToReplace xmlns="urn:mpeg:dash:schema:mpd:2011" ' + 'xmlns:xlink="http://www.w3.org/1999/xlink" variable="%(let)s">' + '<ToReplace xlink:href="%(link)s" xlink:actuate="onLoad" />' + @@ -740,7 +742,7 @@ describe('MpdUtils', function() { * @private */ function inBaseContainer(toReplaceOne = '', toReplaceTwo = '') { - let format = + const format = '<Container xmlns="urn:mpeg:dash:schema:mpd:2011" ' + 'xmlns:xlink="http://www.w3.org/1999/xlink">' + '<Thing>' + @@ -754,7 +756,7 @@ describe('MpdUtils', function() { } function testRequest(baseXMLString) { - let xml = parser.parseFromString(baseXMLString, 'text/xml') + const xml = parser.parseFromString(baseXMLString, 'text/xml') .documentElement; return MpdUtils.processXlinks(xml, retry, failGracefully, 'https://base', fakeNetEngine).promise; diff --git a/test/hls/hls_live_unit.js b/test/hls/hls_live_unit.js index bb24ac5901..3c644d2fe6 100644 --- a/test/hls/hls_live_unit.js +++ b/test/hls/hls_live_unit.js @@ -165,10 +165,10 @@ describe('HlsParser live', function() { parser.start('test:/master', playerInterface) .then(function(manifest) { - let variants = manifest.periods[0].variants; + const variants = manifest.periods[0].variants; for (let i = 0; i < variants.length; i++) { - let video = variants[i].video; - let audio = variants[i].audio; + const video = variants[i].video; + const audio = variants[i].audio; ManifestParser.verifySegmentIndex(video, initialReferences); if (audio) { ManifestParser.verifySegmentIndex(audio, initialReferences); @@ -184,8 +184,8 @@ describe('HlsParser live', function() { delayForUpdatePeriod(); for (let i = 0; i < variants.length; i++) { - let video = variants[i].video; - let audio = variants[i].audio; + const video = variants[i].video; + const audio = variants[i].audio; ManifestParser.verifySegmentIndex(video, updatedReferences); if (audio) { ManifestParser.verifySegmentIndex(audio, updatedReferences); @@ -246,9 +246,9 @@ describe('HlsParser live', function() { }); it('adds new segments when they appear', function(done) { - let ref1 = ManifestParser.makeReference('test:/main.mp4', + const ref1 = ManifestParser.makeReference('test:/main.mp4', 0, 2, 4); - let ref2 = ManifestParser.makeReference('test:/main2.mp4', + const ref2 = ManifestParser.makeReference('test:/main2.mp4', 1, 4, 6); testUpdate(done, master, media, [ref1], @@ -262,10 +262,10 @@ describe('HlsParser live', function() { 'video2', ].join(''); - let masterWithTwoVariants = master + secondVariant; - let ref1 = ManifestParser.makeReference('test:/main.mp4', + const masterWithTwoVariants = master + secondVariant; + const ref1 = ManifestParser.makeReference('test:/main.mp4', 0, 2, 4); - let ref2 = ManifestParser.makeReference('test:/main2.mp4', + const ref2 = ManifestParser.makeReference('test:/main2.mp4', 1, 4, 6); testUpdate(done, masterWithTwoVariants, media, [ref1], @@ -278,10 +278,10 @@ describe('HlsParser live', function() { 'URI="audio"\n', ].join(''); - let masterWithAudio = master + audio; - let ref1 = ManifestParser.makeReference('test:/main.mp4', + const masterWithAudio = master + audio; + const ref1 = ManifestParser.makeReference('test:/main.mp4', 0, 2, 4); - let ref2 = ManifestParser.makeReference('test:/main2.mp4', + const ref2 = ManifestParser.makeReference('test:/main2.mp4', 1, 4, 6); testUpdate(done, masterWithAudio, media, [ref1], @@ -299,13 +299,13 @@ describe('HlsParser live', function() { 'main3.mp4\n', ].join(''); - let updatedMedia1 = media + newSegment1; - let updatedMedia2 = updatedMedia1 + newSegment2; - let ref1 = ManifestParser.makeReference('test:/main.mp4', + const updatedMedia1 = media + newSegment1; + const updatedMedia2 = updatedMedia1 + newSegment2; + const ref1 = ManifestParser.makeReference('test:/main.mp4', 0, 2, 4); - let ref2 = ManifestParser.makeReference('test:/main2.mp4', + const ref2 = ManifestParser.makeReference('test:/main2.mp4', 1, 4, 6); - let ref3 = ManifestParser.makeReference('test:/main3.mp4', + const ref3 = ManifestParser.makeReference('test:/main3.mp4', 2, 6, 8); fakeNetEngine @@ -316,7 +316,7 @@ describe('HlsParser live', function() { parser.start('test:/master', playerInterface) .then(function(manifest) { - let video = manifest.periods[0].variants[0].video; + const video = manifest.periods[0].variants[0].video; ManifestParser.verifySegmentIndex(video, [ref1]); fakeNetEngine @@ -463,9 +463,9 @@ describe('HlsParser live', function() { .setResponseValue('test:/init.mp4', initSegmentData) .setResponseValue('test:/main.mp4', segmentData); - let manifest = await parser.start('test:/master', playerInterface); + const manifest = await parser.start('test:/master', playerInterface); expect(manifest).toBeTruthy(); - let timeline = manifest.presentationTimeline; + const timeline = manifest.presentationTimeline; expect(timeline).toBeTruthy(); const start = timeline.getSegmentAvailabilityStart(); @@ -518,12 +518,12 @@ describe('HlsParser live', function() { .setResponseText('test:/main.vtt', vtt); parser.start('test:/master', playerInterface).then(function(manifest) { - let textStream = manifest.periods[0].textStreams[0]; + const textStream = manifest.periods[0].textStreams[0]; let ref = textStream.getSegmentReference(0); expect(ref).not.toBe(null); expect(ref.startTime).not.toBeLessThan(rolloverOffset); - let videoStream = manifest.periods[0].variants[0].video; + const videoStream = manifest.periods[0].variants[0].video; ref = videoStream.getSegmentReference(0); expect(ref).not.toBe(null); expect(ref.startTime).not.toBeLessThan(rolloverOffset); @@ -543,9 +543,9 @@ describe('HlsParser live', function() { }); it('adds new segments when they appear', function(done) { - let ref1 = ManifestParser.makeReference('test:/main.mp4', + const ref1 = ManifestParser.makeReference('test:/main.mp4', 0, 2, 4); - let ref2 = ManifestParser.makeReference('test:/main2.mp4', + const ref2 = ManifestParser.makeReference('test:/main2.mp4', 1, 4, 6); testUpdate(done, master, media, [ref1], @@ -553,9 +553,9 @@ describe('HlsParser live', function() { }); it('evicts removed segments', function(done) { - let ref1 = ManifestParser.makeReference('test:/main.mp4', + const ref1 = ManifestParser.makeReference('test:/main.mp4', 0, 2, 4); - let ref2 = ManifestParser.makeReference('test:/main2.mp4', + const ref2 = ManifestParser.makeReference('test:/main2.mp4', 1, 4, 6); testUpdate(done, master, mediaWithAdditionalSegment, [ref1, ref2], @@ -563,13 +563,13 @@ describe('HlsParser live', function() { }); it('handles updates with redirects', function(done) { - let oldRef1 = ManifestParser.makeReference('test:/main.mp4', + const oldRef1 = ManifestParser.makeReference('test:/main.mp4', 0, 2, 4); - let newRef1 = ManifestParser.makeReference('test:/redirected/main.mp4', - 0, 2, 4); - let newRef2 = ManifestParser.makeReference('test:/redirected/main2.mp4', - 1, 4, 6); + const newRef1 = + ManifestParser.makeReference('test:/redirected/main.mp4', 0, 2, 4); + const newRef2 = + ManifestParser.makeReference('test:/redirected/main2.mp4', 1, 4, 6); let playlistFetchCount = 0; @@ -595,12 +595,12 @@ describe('HlsParser live', function() { .setResponseValue('test:/init.mp4', initSegmentData) .setResponseValue('test:/main.mp4', segmentData); - let ref = ManifestParser.makeReference( + const ref = ManifestParser.makeReference( 'test:/main.mp4', 0, segmentDataStartTime, segmentDataStartTime + 2); parser.start('test:/master', playerInterface).then(function(manifest) { - let video = manifest.periods[0].variants[0].video; + const video = manifest.periods[0].variants[0].video; ManifestParser.verifySegmentIndex(video, [ref]); // In live content, we do not set presentationTimeOffset. @@ -616,16 +616,16 @@ describe('HlsParser live', function() { .setResponseValue('test:/init.mp4', initSegmentData) .setResponseValue('test:/main.mp4', segmentData); - let ref1 = ManifestParser.makeReference( + const ref1 = ManifestParser.makeReference( 'test:/main.mp4', 0, segmentDataStartTime, segmentDataStartTime + 2); - let ref2 = ManifestParser.makeReference( + const ref2 = ManifestParser.makeReference( 'test:/main2.mp4', 1, segmentDataStartTime + 2, segmentDataStartTime + 4); parser.start('test:/master', playerInterface).then(function(manifest) { - let video = manifest.periods[0].variants[0].video; + const video = manifest.periods[0].variants[0].video; ManifestParser.verifySegmentIndex(video, [ref1, ref2]); fakeNetEngine @@ -652,19 +652,20 @@ describe('HlsParser live', function() { }); it('parses start time from ts segments', function(done) { - let tsMediaPlaylist = mediaWithRemovedSegment.replace(/\.mp4/g, '.ts'); + const tsMediaPlaylist = + mediaWithRemovedSegment.replace(/\.mp4/g, '.ts'); fakeNetEngine .setResponseText('test:/master', master) .setResponseText('test:/video', tsMediaPlaylist) .setResponseValue('test:/main2.ts', tsSegmentData); - let ref = ManifestParser.makeReference( + const ref = ManifestParser.makeReference( 'test:/main2.ts', 1, segmentDataStartTime, segmentDataStartTime + 2); parser.start('test:/master', playerInterface).then(function(manifest) { - let video = manifest.periods[0].variants[0].video; + const video = manifest.periods[0].variants[0].video; ManifestParser.verifySegmentIndex(video, [ref]); // In live content, we do not set presentationTimeOffset. expect(video.presentationTimeOffset).toEqual(0); @@ -675,7 +676,7 @@ describe('HlsParser live', function() { it('gets start time of segments with byte range', function(done) { // Nit: this value is an implementation detail of the fix for #1106 - let partialEndByte = expectedStartByte + 2048 - 1; + const partialEndByte = expectedStartByte + 2048 - 1; fakeNetEngine .setResponseText('test:/master', master) @@ -683,7 +684,7 @@ describe('HlsParser live', function() { .setResponseValue('test:/init.mp4', initSegmentData) .setResponseValue('test:/main.mp4', segmentData); - let ref = ManifestParser.makeReference( + const ref = ManifestParser.makeReference( 'test:/main.mp4' /* uri */, 0 /* position */, segmentDataStartTime /* start */, @@ -693,7 +694,7 @@ describe('HlsParser live', function() { expectedEndByte); // Complete segment reference parser.start('test:/master', playerInterface).then(function(manifest) { - let video = manifest.periods[0].variants[0].video; + const video = manifest.periods[0].variants[0].video; ManifestParser.verifySegmentIndex(video, [ref]); // There should have been a range request for this segment to get the @@ -761,18 +762,18 @@ describe('HlsParser live', function() { .setResponseText('test:/main1.vtt', vtt1); - let baseTime = 95443 + rolloverOffset; - let ref1 = ManifestParser.makeReference('test:/main1.vtt', + const baseTime = 95443 + rolloverOffset; + const ref1 = ManifestParser.makeReference('test:/main1.vtt', /* position */ 0, /* startTime */ baseTime, /* endTime */ baseTime + 2); - let ref2 = ManifestParser.makeReference('test:/main2.vtt', + const ref2 = ManifestParser.makeReference('test:/main2.vtt', /* position */ 1, /* startTime */ baseTime + 2, /* endTime */ baseTime + 4); parser.start('test:/master', playerInterface).then(function(manifest) { - let text = manifest.periods[0].textStreams[0]; + const text = manifest.periods[0].textStreams[0]; ManifestParser.verifySegmentIndex(text, [ref1]); // Change the entries that are affected by the roll over. diff --git a/test/hls/hls_parser_unit.js b/test/hls/hls_parser_unit.js index 5eaed7934d..a0d3424ec2 100644 --- a/test/hls/hls_parser_unit.js +++ b/test/hls/hls_parser_unit.js @@ -116,7 +116,7 @@ describe('HlsParser', function() { .setResponseValue('test:/main.test', segmentData) .setResponseValue('test:/selfInit.mp4', selfInitializingSegmentData); - let actual = await parser.start('test:/master', playerInterface); + const actual = await parser.start('test:/master', playerInterface); expect(actual).toEqual(manifest); return actual; } @@ -200,14 +200,14 @@ describe('HlsParser', function() { }); it('ignores duplicate CODECS', async function() { - let master = [ + const master = [ '#EXTM3U\n', '#EXT-X-STREAM-INF:BANDWIDTH=200,CODECS="avc1.4d001e,avc1.42000d",', 'RESOLUTION=960x540,FRAME-RATE=60\n', 'video', ].join(''); - let media = [ + const media = [ '#EXTM3U\n', '#EXT-X-PLAYLIST-TYPE:VOD\n', '#EXT-X-MAP:URI="init.mp4",BYTERANGE="616@0"\n', @@ -216,7 +216,7 @@ describe('HlsParser', function() { 'main.mp4', ].join(''); - let manifest = new shaka.test.ManifestGenerator() + const manifest = new shaka.test.ManifestGenerator() .anyTimeline() .addPeriod(0) .addPartialVariant() @@ -228,14 +228,14 @@ describe('HlsParser', function() { }); it('parses video-only variant', async function() { - let master = [ + const master = [ '#EXTM3U\n', '#EXT-X-STREAM-INF:BANDWIDTH=200,CODECS="avc1",', 'RESOLUTION=960x540,FRAME-RATE=60\n', 'video', ].join(''); - let media = [ + const media = [ '#EXTM3U\n', '#EXT-X-PLAYLIST-TYPE:VOD\n', '#EXT-X-MAP:URI="init.mp4",BYTERANGE="616@0"\n', @@ -244,7 +244,7 @@ describe('HlsParser', function() { 'main.mp4', ].join(''); - let manifest = new shaka.test.ManifestGenerator() + const manifest = new shaka.test.ManifestGenerator() .anyTimeline() .addPeriod(0) .addPartialVariant() @@ -271,7 +271,7 @@ describe('HlsParser', function() { 'main.mp4', ].join(''); - let manifest = new shaka.test.ManifestGenerator() + const manifest = new shaka.test.ManifestGenerator() .anyTimeline() .addPeriod(0) .addPartialVariant() @@ -298,7 +298,7 @@ describe('HlsParser', function() { 'main.mp4', ].join(''); - let manifest = new shaka.test.ManifestGenerator() + const manifest = new shaka.test.ManifestGenerator() .anyTimeline() .addPeriod(0) .addPartialVariant() @@ -328,7 +328,7 @@ describe('HlsParser', function() { 'main.mp4', ].join(''); - let manifest = new shaka.test.ManifestGenerator() + const manifest = new shaka.test.ManifestGenerator() .anyTimeline() .addPeriod(0) .addPartialVariant() @@ -429,7 +429,7 @@ describe('HlsParser', function() { 'main.mp4', ].join(''); - let manifest = new shaka.test.ManifestGenerator() + const manifest = new shaka.test.ManifestGenerator() .anyTimeline() .addPeriod(0) .addPartialVariant() @@ -478,8 +478,8 @@ describe('HlsParser', function() { .setResponseValue('test:/init.mp4', initSegmentData) .setResponseValue('test:/main.mp4', segmentData); - let manifest = await parser.start('test:/master', playerInterface); - let presentationTimeline = manifest.presentationTimeline; + const manifest = await parser.start('test:/master', playerInterface); + const presentationTimeline = manifest.presentationTimeline; const stream = manifest.periods[0].variants[0].video; // baseMediaDecodeTime (655360) / timescale (1000) expect(stream.presentationTimeOffset).toBe(655.36); @@ -507,7 +507,7 @@ describe('HlsParser', function() { 'main.mp4', ].join(''); - let manifest = new shaka.test.ManifestGenerator() + const manifest = new shaka.test.ManifestGenerator() .anyTimeline() .addPeriod(0) .addPartialVariant() @@ -535,7 +535,7 @@ describe('HlsParser', function() { 'main.mp4', ].join(''); - let manifest = new shaka.test.ManifestGenerator() + const manifest = new shaka.test.ManifestGenerator() .anyTimeline() .addPeriod(0) .addPartialVariant() @@ -565,7 +565,7 @@ describe('HlsParser', function() { 'main.mp4', ].join(''); - let manifest = new shaka.test.ManifestGenerator() + const manifest = new shaka.test.ManifestGenerator() .anyTimeline() .addPeriod(0) .addPartialVariant() @@ -596,7 +596,7 @@ describe('HlsParser', function() { 'main.mp4', ].join(''); - let manifest = new shaka.test.ManifestGenerator() + const manifest = new shaka.test.ManifestGenerator() .anyTimeline() .addPeriod(0) .addPartialVariant() @@ -625,7 +625,7 @@ describe('HlsParser', function() { 'main.mp4', ].join(''); - let manifest = new shaka.test.ManifestGenerator() + const manifest = new shaka.test.ManifestGenerator() .anyTimeline() .addPeriod(0) .addPartialVariant() @@ -660,7 +660,7 @@ describe('HlsParser', function() { 'main.mp4', ].join(''); - let manifest = new shaka.test.ManifestGenerator() + const manifest = new shaka.test.ManifestGenerator() .anyTimeline() .addPeriod(0) .addPartialVariant() @@ -701,7 +701,7 @@ describe('HlsParser', function() { 'main.mp4', ].join(''); - let manifest = new shaka.test.ManifestGenerator() + const manifest = new shaka.test.ManifestGenerator() .anyTimeline() .addPeriod(0) .addPartialVariant() @@ -743,7 +743,7 @@ describe('HlsParser', function() { .setResponseValue('test:/init.mp4', initSegmentData) .setResponseValue('test:/main.mp4', segmentData); - let filterAllPeriods = jasmine.createSpy('filterAllPeriods'); + const filterAllPeriods = jasmine.createSpy('filterAllPeriods'); playerInterface.filterAllPeriods = Util.spyFunc(filterAllPeriods); parser.start('test:/master', playerInterface) @@ -769,7 +769,7 @@ describe('HlsParser', function() { 'main.test', ].join(''); - let manifest = new shaka.test.ManifestGenerator() + const manifest = new shaka.test.ManifestGenerator() .anyTimeline() .addPeriod(0) .addPartialVariant() @@ -820,7 +820,7 @@ describe('HlsParser', function() { 'main.vtt', ].join(''); - let manifest = new shaka.test.ManifestGenerator() + const manifest = new shaka.test.ManifestGenerator() .anyTimeline() .addPeriod(0) .addPartialVariant() @@ -848,7 +848,7 @@ describe('HlsParser', function() { .setResponseValue('test:/init.mp4', initSegmentData) .setResponseValue('test:/main.mp4', segmentData); - let actual = await parser.start('test:/master', playerInterface); + const actual = await parser.start('test:/master', playerInterface); expect(actual).toEqual(manifest); }); @@ -883,7 +883,7 @@ describe('HlsParser', function() { 'main.vtt', ].join(''); - let manifest = new shaka.test.ManifestGenerator() + const manifest = new shaka.test.ManifestGenerator() .anyTimeline() .addPeriod(0) .addPartialVariant() @@ -907,7 +907,7 @@ describe('HlsParser', function() { .setResponseValue('test:/init.mp4', initSegmentData) .setResponseValue('test:/main.mp4', segmentData); - let actual = await parser.start('test:/master', playerInterface); + const actual = await parser.start('test:/master', playerInterface); expect(actual).toEqual(manifest); }); @@ -962,13 +962,13 @@ describe('HlsParser', function() { .setResponseValue('test:/init.mp4', initSegmentData) .setResponseValue('test:/main.mp4', segmentData); - let actual = await parser.start('test:/master', playerInterface); + const actual = await parser.start('test:/master', playerInterface); // Duration should be the minimum of the streams, but ignore the text // stream. - let timeline = actual.presentationTimeline; + const timeline = actual.presentationTimeline; expect(timeline.getDuration()).toBe(10); - let period = actual.periods[0]; + const period = actual.periods[0]; expect(period.textStreams.length).toBe(1); expect(period.variants.length).toBe(1); expect(period.variants[0].audio).toBeTruthy(); @@ -994,7 +994,7 @@ describe('HlsParser', function() { 'main.mp4', ].join(''); - let manifest = new shaka.test.ManifestGenerator() + const manifest = new shaka.test.ManifestGenerator() .anyTimeline() .addPeriod(0) .addPartialVariant() @@ -1012,7 +1012,7 @@ describe('HlsParser', function() { .setResponseValue('test:/init.mp4', initSegmentData) .setResponseValue('test:/main.mp4', segmentData); - let actual = await parser.start('test:/master', playerInterface); + const actual = await parser.start('test:/master', playerInterface); expect(actual).toEqual(manifest); }); @@ -1043,7 +1043,7 @@ describe('HlsParser', function() { 'main.foo', ].join(''); - let manifest = new shaka.test.ManifestGenerator() + const manifest = new shaka.test.ManifestGenerator() .anyTimeline() .addPeriod(0) .addPartialVariant() @@ -1061,7 +1061,7 @@ describe('HlsParser', function() { .setResponseValue('test:/init.mp4', initSegmentData) .setResponseValue('test:/main.mp4', segmentData); - let actual = await parser.start('test:/master', playerInterface); + const actual = await parser.start('test:/master', playerInterface); expect(actual).toEqual(manifest); }); @@ -1084,7 +1084,7 @@ describe('HlsParser', function() { 'main.mp4', ].join(''); - let manifest = new shaka.test.ManifestGenerator() + const manifest = new shaka.test.ManifestGenerator() .anyTimeline() .addPeriod(jasmine.any(Number)) .addPartialVariant() @@ -1125,7 +1125,7 @@ describe('HlsParser', function() { 'main.mp4', ].join(''); - let manifest = new shaka.test.ManifestGenerator() + const manifest = new shaka.test.ManifestGenerator() .anyTimeline() .addPeriod(0) .addPartialVariant() @@ -1167,18 +1167,18 @@ describe('HlsParser', function() { parser.start('test:/host/master.m3u8', playerInterface) .then(function(actual) { - let video = actual.periods[0].variants[0].video; - let audio = actual.periods[0].variants[0].audio; + const video = actual.periods[0].variants[0].video; + const audio = actual.periods[0].variants[0].audio; - let videoPosition = video.findSegmentPosition(0); - let audioPosition = audio.findSegmentPosition(0); + const videoPosition = video.findSegmentPosition(0); + const audioPosition = audio.findSegmentPosition(0); goog.asserts.assert(videoPosition != null, 'Cannot find first video segment'); goog.asserts.assert(audioPosition != null, 'Cannot find first audio segment'); - let videoReference = video.getSegmentReference(videoPosition); - let audioReference = audio.getSegmentReference(audioPosition); + const videoReference = video.getSegmentReference(videoPosition); + const audioReference = audio.getSegmentReference(audioPosition); expect(videoReference).not.toBe(null); expect(audioReference).not.toBe(null); if (videoReference) { @@ -1210,7 +1210,7 @@ describe('HlsParser', function() { 'selfInit.mp4', ].join(''); - let manifest = new shaka.test.ManifestGenerator() + const manifest = new shaka.test.ManifestGenerator() .anyTimeline() .addPeriod(0) .addPartialVariant() @@ -1260,7 +1260,7 @@ describe('HlsParser', function() { 'main.mp4', ].join(''); - let manifest = new shaka.test.ManifestGenerator() + const manifest = new shaka.test.ManifestGenerator() .anyTimeline() .addPeriod(0) .addPartialVariant() @@ -1283,7 +1283,7 @@ describe('HlsParser', function() { .setResponseValue('test:/main.test', segmentData) .setResponseValue('test:/selfInit.mp4', selfInitializingSegmentData); - let actual = await parser.start('test:/master', playerInterface); + const actual = await parser.start('test:/master', playerInterface); expect(actual).toEqual(manifest); return actual; }); @@ -1313,7 +1313,7 @@ describe('HlsParser', function() { 'main.mp4', ].join(''); - let manifest = new shaka.test.ManifestGenerator() + const manifest = new shaka.test.ManifestGenerator() .anyTimeline() .addPeriod(0) .addPartialVariant() @@ -1627,7 +1627,7 @@ describe('HlsParser', function() { .setResponseValue('test:/init.mp4', initSegmentData) .setResponseValue('test:/main.mp4', segmentData); - let ref = ManifestParser.makeReference( + const ref = ManifestParser.makeReference( 'test:/main.mp4' /* uri */, 0 /* position */, 0 /* startTime */, @@ -1636,8 +1636,8 @@ describe('HlsParser', function() { expectedStartByte, expectedEndByte); - let manifest = await parser.start('test:/master', playerInterface); - let video = manifest.periods[0].variants[0].video; + const manifest = await parser.start('test:/master', playerInterface); + const video = manifest.periods[0].variants[0].video; ManifestParser.verifySegmentIndex(video, [ref]); // Make sure the segment data was fetched with the correct byte @@ -1653,14 +1653,14 @@ describe('HlsParser', function() { }); it('parses start time from ts segments', async () => { - let tsMediaPlaylist = media.replace(/\.mp4/g, '.ts'); + const tsMediaPlaylist = media.replace(/\.mp4/g, '.ts'); fakeNetEngine .setResponseText('test:/master', master) .setResponseText('test:/video', tsMediaPlaylist) .setResponseValue('test:/main.ts', tsSegmentData); - let ref = ManifestParser.makeReference( + const ref = ManifestParser.makeReference( 'test:/main.ts' /* uri */, 0 /* position */, 0 /* startTime */, @@ -1669,8 +1669,8 @@ describe('HlsParser', function() { expectedStartByte, expectedEndByte); - let manifest = await parser.start('test:/master', playerInterface); - let video = manifest.periods[0].variants[0].video; + const manifest = await parser.start('test:/master', playerInterface); + const video = manifest.periods[0].variants[0].video; ManifestParser.verifySegmentIndex(video, [ref]); // Make sure the segment data was fetched with the correct byte @@ -1734,10 +1734,10 @@ describe('HlsParser', function() { .setResponseValue('test:/init.mp4', initSegmentData) .setResponseValue('test:/main.mp4', segmentData); - let manifest = await parser.start('test:/master', playerInterface); - let presentationTimeline = manifest.presentationTimeline; - let video = manifest.periods[0].variants[0].video; - let ref = video.getSegmentReference(0); + const manifest = await parser.start('test:/master', playerInterface); + const presentationTimeline = manifest.presentationTimeline; + const video = manifest.periods[0].variants[0].video; + const ref = video.getSegmentReference(0); expect(video.getSegmentReference(1)).toBe(null); // No more references. expect(video.presentationTimeOffset).toEqual(segmentDataStartTime); @@ -1771,7 +1771,7 @@ describe('HlsParser', function() { .setResponseValue('test:/init.mp4', initSegmentData) .setResponseValue('test:/main.mp4', segmentData); - let manifest = await parser.start('test:/master', playerInterface); + const manifest = await parser.start('test:/master', playerInterface); expect(manifest.presentationTimeline.isLive()).toBe(false); }); @@ -1798,7 +1798,7 @@ describe('HlsParser', function() { .setResponseValue('test:/init.mp4', initSegmentData) .setResponseValue('test:/main.mp4', segmentData); - let manifest = await parser.start('test:/master', playerInterface); + const manifest = await parser.start('test:/master', playerInterface); expect(manifest.presentationTimeline.isLive()).toBe(false); }); @@ -1825,8 +1825,8 @@ describe('HlsParser', function() { .setResponseValue('test:/init.mp4', initSegmentData) .setResponseValue('test:/main.mp4', segmentData); - let manifest = await parser.start('test:/master', playerInterface); - let video = manifest.periods[0].variants[0].video; + const manifest = await parser.start('test:/master', playerInterface); + const video = manifest.periods[0].variants[0].video; expect(video.mimeType).toBe('video/mp4'); }); @@ -1853,8 +1853,8 @@ describe('HlsParser', function() { .setResponseValue('test:/init.mp4', initSegmentData) .setResponseValue('test:/main.mp4?foo=bar', segmentData); - let manifest = await parser.start('test:/master', playerInterface); - let video = manifest.periods[0].variants[0].video; + const manifest = await parser.start('test:/master', playerInterface); + const video = manifest.periods[0].variants[0].video; expect(video.mimeType).toBe('video/mp4'); }); @@ -1888,10 +1888,10 @@ describe('HlsParser', function() { .setResponseValue('test:/init.mp4', initSegmentData) .setResponseValue('test:/main.mp4', segmentData); - let manifest = await parser.start('test:/master', playerInterface); + const manifest = await parser.start('test:/master', playerInterface); expect(manifest.periods[0].variants.length).toBe(2); - let audio0 = manifest.periods[0].variants[0].audio; - let audio1 = manifest.periods[0].variants[1].audio; + const audio0 = manifest.periods[0].variants[0].audio; + const audio1 = manifest.periods[0].variants[1].audio; // These should be the exact same memory address, not merely equal. // Otherwise, the parser will only be replacing one of the SegmentIndexes // on update, which will lead to live streaming issues. diff --git a/test/hls/manifest_text_parser_unit.js b/test/hls/manifest_text_parser_unit.js index 115b8dfb71..802f0af803 100644 --- a/test/hls/manifest_text_parser_unit.js +++ b/test/hls/manifest_text_parser_unit.js @@ -101,8 +101,8 @@ describe('ManifestTextParser', function() { * @param {shaka.util.Error.Code} code */ function verifyError(string, code) { - let data = shaka.util.StringUtils.toUTF8(string); - let error = new shaka.util.Error( + const data = shaka.util.StringUtils.toUTF8(string); + const error = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.MANIFEST, code); @@ -260,12 +260,12 @@ describe('ManifestTextParser', function() { }); it('rejects invalid tags', function() { - let error = new shaka.util.Error( + const error = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.MANIFEST, shaka.util.Error.Code.INVALID_HLS_TAG, 'invalid tag'); - let text = shaka.util.StringUtils.toUTF8('#EXTM3U\ninvalid tag'); + const text = shaka.util.StringUtils.toUTF8('#EXTM3U\ninvalid tag'); try { parser.parsePlaylist(text, /* uri */ ''); fail('Invalid HLS tags should not be supported!'); @@ -278,25 +278,25 @@ describe('ManifestTextParser', function() { describe('tag.toString', function() { it('recreates valid tag with attributes', function() { const text = '#EXT-X-MEDIA:CODECS="avc1.64002a,mp4a.40.2",AUDIO="a1,a2"'; - let tag = shaka.hls.ManifestTextParser.parseTag(0, text); + const tag = shaka.hls.ManifestTextParser.parseTag(0, text); expect(text).toEqual(tag.toString()); }); it('recreates valid tag with value', function() { const text = '#EXT-X-PLAYLIST-TYPE:VOD'; - let tag = shaka.hls.ManifestTextParser.parseTag(0, text); + const tag = shaka.hls.ManifestTextParser.parseTag(0, text); expect(text).toEqual(tag.toString()); }); it('recreates valid tag with no value', function() { const text = '#EXTM3U'; - let tag = shaka.hls.ManifestTextParser.parseTag(0, text); + const tag = shaka.hls.ManifestTextParser.parseTag(0, text); expect(text).toEqual(tag.toString()); }); it('recreates valid tag with both value and attributes', function() { const text = '#EXTINF:5.99467,pid=180'; - let tag = shaka.hls.ManifestTextParser.parseTag(0, text); + const tag = shaka.hls.ManifestTextParser.parseTag(0, text); expect(text).toEqual(tag.toString()); }); }); diff --git a/test/media/drm_engine_integration.js b/test/media/drm_engine_integration.js index b5c3557bfe..b576f55a08 100644 --- a/test/media/drm_engine_integration.js +++ b/test/media/drm_engine_integration.js @@ -61,14 +61,14 @@ describe('DrmEngine', function() { let audioSegment; beforeAll(async () => { - let supportTest = shaka.media.DrmEngine.probeSupport() + const supportTest = shaka.media.DrmEngine.probeSupport() .then(function(result) { support = result; }) .catch(fail); video = shaka.util.Dom.createVideoElement(); document.body.appendChild(video); - let responses = await Promise.all([ + const responses = await Promise.all([ supportTest, shaka.test.Util.fetch(videoInitSegmentUri), shaka.test.Util.fetch(videoSegmentUri), @@ -100,7 +100,7 @@ describe('DrmEngine', function() { ].join(''); }); - let playerInterface = { + const playerInterface = { netEngine: networkingEngine, onError: shaka.test.Util.spyFunc(onErrorSpy), onKeyStatus: shaka.test.Util.spyFunc(onKeyStatusSpy), @@ -125,8 +125,8 @@ describe('DrmEngine', function() { .addAudio(2).mime('audio/mp4', 'mp4a.40.2').encrypted(true) .build(); - let videoStream = manifest.periods[0].variants[0].video; - let audioStream = manifest.periods[0].variants[0].audio; + const videoStream = manifest.periods[0].variants[0].video; + const audioStream = manifest.periods[0].variants[0].audio; eventManager = new shaka.util.EventManager(); @@ -159,10 +159,11 @@ describe('DrmEngine', function() { // The error callback should not be invoked. onErrorSpy.and.callFake(fail); - let originalRequest = networkingEngine.request.bind(networkingEngine); + const originalRequest = + networkingEngine.request.bind(networkingEngine); let requestComplete; - let requestSpy = jasmine.createSpy('request'); - let requestMade = new shaka.util.PublicPromise(); + const requestSpy = jasmine.createSpy('request'); + const requestMade = new shaka.util.PublicPromise(); requestSpy.and.callFake(function() { requestMade.resolve(); requestComplete = originalRequest.apply(null, arguments); @@ -170,7 +171,7 @@ describe('DrmEngine', function() { }); networkingEngine.request = shaka.test.Util.spyFunc(requestSpy); - let encryptedEventSeen = new shaka.util.PublicPromise(); + const encryptedEventSeen = new shaka.util.PublicPromise(); eventManager.listen(video, 'encrypted', function() { encryptedEventSeen.resolve(); }); @@ -185,7 +186,7 @@ describe('DrmEngine', function() { } }); - let keyStatusEventSeen = new shaka.util.PublicPromise(); + const keyStatusEventSeen = new shaka.util.PublicPromise(); onKeyStatusSpy.and.callFake(function() { keyStatusEventSeen.resolve(); }); @@ -223,14 +224,14 @@ describe('DrmEngine', function() { }).then(function() { // Some platforms (notably 2017 Tizen TVs) do not fire key status // events. - let keyStatusTimeout = shaka.test.Util.delay(5); + const keyStatusTimeout = shaka.test.Util.delay(5); return Promise.race([keyStatusTimeout, keyStatusEventSeen]); }).then(function() { - let call = onKeyStatusSpy.calls.mostRecent(); + const call = onKeyStatusSpy.calls.mostRecent(); if (call) { - let map = /** @type {!Object} */ (call.args[0]); + const map = /** @type {!Object} */ (call.args[0]); expect(Object.keys(map).length).not.toBe(0); - for (let k in map) { + for (const k in map) { expect(map[k]).toBe('usable'); } } diff --git a/test/media/drm_engine_unit.js b/test/media/drm_engine_unit.js index de9e8a393d..373fcc2705 100644 --- a/test/media/drm_engine_unit.js +++ b/test/media/drm_engine_unit.js @@ -106,7 +106,7 @@ describe('DrmEngine', function() { mockMediaKeys = createMockMediaKeys(); mockMediaKeys.createSession.and.callFake(function() { - let index = mockMediaKeys.createSession.calls.count() - 1; + const index = mockMediaKeys.createSession.calls.count() - 1; return [session1, session2, session3][index]; }); mockMediaKeys.setServerCertificate.and.returnValue(Promise.resolve()); @@ -116,7 +116,7 @@ describe('DrmEngine', function() { license = (new Uint8Array(0)).buffer; fakeNetEngine.setResponseValue('http://abc.drm/license', license); - let playerInterface = { + const playerInterface = { netEngine: fakeNetEngine, onError: shaka.test.Util.spyFunc(onErrorSpy), onKeyStatus: shaka.test.Util.spyFunc(onKeyStatusSpy), @@ -190,7 +190,7 @@ describe('DrmEngine', function() { expect(requestMediaKeySystemAccessSpy.calls.count()).toBe(2); // These should be in the same order as the key systems appear in the // manifest. - let calls = requestMediaKeySystemAccessSpy.calls; + const calls = requestMediaKeySystemAccessSpy.calls; expect(calls.argsFor(0)[0]).toBe('drm.abc'); expect(calls.argsFor(1)[0]).toBe('drm.def'); } @@ -215,7 +215,7 @@ describe('DrmEngine', function() { expect(requestMediaKeySystemAccessSpy.calls.count()).toBe(2); // Although drm.def appears second in the manifest, it is queried first // because it has a server configured. - let calls = requestMediaKeySystemAccessSpy.calls; + const calls = requestMediaKeySystemAccessSpy.calls; expect(calls.argsFor(0)[0]).toBe('drm.def'); expect(calls.argsFor(1)[0]).toBe('drm.abc'); } @@ -660,7 +660,7 @@ describe('DrmEngine', function() { }); it('sets server certificate if present in config', async () => { - let cert = new Uint8Array(1); + const cert = new Uint8Array(1); config.advanced['drm.abc'] = createAdvancedConfig(cert); drmEngine.configure(config); @@ -669,8 +669,8 @@ describe('DrmEngine', function() { }); it('prefers server certificate from DrmInfo', async () => { - let cert1 = new Uint8Array(5); - let cert2 = new Uint8Array(1); + const cert1 = new Uint8Array(5); + const cert2 = new Uint8Array(1); manifest.periods[0].variants[0].drmInfos[0].serverCertificate = cert1; config.advanced['drm.abc'] = createAdvancedConfig(cert2); @@ -687,9 +687,9 @@ describe('DrmEngine', function() { it('creates sessions for init data overrides', function(done) { // Set up init data overrides in the manifest: - let initData1 = new Uint8Array(5); - let initData2 = new Uint8Array(0); - let initData3 = new Uint8Array(10); + const initData1 = new Uint8Array(5); + const initData2 = new Uint8Array(0); + const initData3 = new Uint8Array(10); manifest.periods[0].variants[0].drmInfos[0].initData = [ {initData: initData1, initDataType: 'cenc', keyId: null}, {initData: initData2, initDataType: 'webm', keyId: null}, @@ -714,9 +714,9 @@ describe('DrmEngine', function() { // The third initData has a different initData from the first, // but the same keyId. // Both should be discarded as duplicates. - let initData1 = new Uint8Array(1); - let initData2 = new Uint8Array(1); - let initData3 = new Uint8Array(10); + const initData1 = new Uint8Array(1); + const initData2 = new Uint8Array(1); + const initData3 = new Uint8Array(10); manifest.periods[0].variants[0].drmInfos[0].initData = [ {initData: initData1, initDataType: 'cenc', keyId: 'abc'}, {initData: initData2, initDataType: 'cenc', keyId: 'def'}, @@ -744,14 +744,14 @@ describe('DrmEngine', function() { }; drmEngine.configure(config); - let session = createMockSession(); + const session = createMockSession(); mockMediaKeys.createSession.and.callFake(function() { expect(mockMediaKeys.createSession.calls.count()).toBe(1); return session; }); await initAndAttach(); - let Uint8ArrayUtils = shaka.util.Uint8ArrayUtils; + const Uint8ArrayUtils = shaka.util.Uint8ArrayUtils; expect(manifest.periods[0].variants[0].drmInfos.length).toBe(1); expect(manifest.periods[0].variants[0].drmInfos[0].keySystem). @@ -760,11 +760,11 @@ describe('DrmEngine', function() { expect(session.generateRequest). toHaveBeenCalledWith('keyids', jasmine.any(ArrayBuffer)); - let initData = JSON.parse(shaka.util.StringUtils.fromUTF8( + const initData = JSON.parse(shaka.util.StringUtils.fromUTF8( session.generateRequest.calls.argsFor(0)[1])); - let keyId1 = Uint8ArrayUtils.toHex( + const keyId1 = Uint8ArrayUtils.toHex( Uint8ArrayUtils.fromBase64(initData.kids[0])); - let keyId2 = Uint8ArrayUtils.toHex( + const keyId2 = Uint8ArrayUtils.toHex( Uint8ArrayUtils.fromBase64(initData.kids[1])); expect(keyId1).toBe('deadbeefdeadbeefdeadbeefdeadbeef'); expect(keyId2).toBe('02030507011013017019023029031037'); @@ -789,7 +789,7 @@ describe('DrmEngine', function() { }); it('fails with an error if setServerCertificate fails', async () => { - let cert = new Uint8Array(1); + const cert = new Uint8Array(1); config.advanced['drm.abc'] = createAdvancedConfig(cert); drmEngine.configure(config); @@ -813,13 +813,13 @@ describe('DrmEngine', function() { it('dispatches an error if generateRequest fails', async () => { // Set up an init data override in the manifest to get an immediate call // to generateRequest: - let initData1 = new Uint8Array(5); + const initData1 = new Uint8Array(5); manifest.periods[0].variants[0].drmInfos[0].initData = [ {initData: initData1, initDataType: 'cenc', keyId: null}, ]; // Fail generateRequest. - let session1 = createMockSession(); + const session1 = createMockSession(); const nativeError = {message: 'whoops!'}; session1.generateRequest.and.returnValue(Promise.reject(nativeError)); mockMediaKeys.createSession.and.returnValue(session1); @@ -827,7 +827,7 @@ describe('DrmEngine', function() { onErrorSpy.and.stub(); await initAndAttach(); expect(onErrorSpy).toHaveBeenCalled(); - let error = onErrorSpy.calls.argsFor(0)[0]; + const error = onErrorSpy.calls.argsFor(0)[0]; shaka.test.Util.expectToEqualError(error, new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.DRM, @@ -846,8 +846,8 @@ describe('DrmEngine', function() { it('triggers the creation of a session', async () => { await initAndAttach(); - let initData1 = new Uint8Array(1); - let initData2 = new Uint8Array(2); + const initData1 = new Uint8Array(1); + const initData2 = new Uint8Array(2); mockVideo.on['encrypted']( {initDataType: 'webm', initData: initData1, keyId: null}); @@ -863,8 +863,8 @@ describe('DrmEngine', function() { it('suppresses duplicate initDatas', async () => { await initAndAttach(); - let initData1 = new Uint8Array(1); - let initData2 = new Uint8Array(1); // identical to initData1 + const initData1 = new Uint8Array(1); + const initData2 = new Uint8Array(1); // identical to initData1 mockVideo.on['encrypted']( {initDataType: 'webm', initData: initData1, keyId: null}); @@ -894,12 +894,12 @@ describe('DrmEngine', function() { onErrorSpy.and.stub(); await initAndAttach(); - let initData1 = new Uint8Array(1); + const initData1 = new Uint8Array(1); mockVideo.on['encrypted']( {initDataType: 'webm', initData: initData1, keyId: null}); expect(onErrorSpy).toHaveBeenCalled(); - let error = onErrorSpy.calls.argsFor(0)[0]; + const error = onErrorSpy.calls.argsFor(0)[0]; shaka.test.Util.expectToEqualError(error, new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.DRM, @@ -915,12 +915,12 @@ describe('DrmEngine', function() { onErrorSpy.and.stub(); await initAndAttach(); - let initData1 = new Uint8Array(1); + const initData1 = new Uint8Array(1); mockVideo.on['encrypted']( {initDataType: 'webm', initData: initData1, keyId: null}); expect(onErrorSpy).toHaveBeenCalled(); - let error = onErrorSpy.calls.argsFor(0)[0]; + const error = onErrorSpy.calls.argsFor(0)[0]; shaka.test.Util.expectToEqualError(error, new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.DRM, @@ -931,7 +931,7 @@ describe('DrmEngine', function() { describe('message', function() { it('is listened for', async () => { await initAndAttach(); - let initData = new Uint8Array(0); + const initData = new Uint8Array(0); mockVideo.on['encrypted']( {initDataType: 'webm', initData: initData, keyId: null}); @@ -972,25 +972,25 @@ describe('DrmEngine', function() { onErrorSpy.and.stub(); await initAndAttach(); - let initData = new Uint8Array(0); + const initData = new Uint8Array(0); mockVideo.on['encrypted']( {initDataType: 'webm', initData: initData, keyId: null}); // Simulate a permission error from the web server. - let netError = new shaka.util.Error( + const netError = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.NETWORK, shaka.util.Error.Code.BAD_HTTP_STATUS, 'http://abc.drm/license', 403); - let operation = shaka.util.AbortableOperation.failed(netError); + const operation = shaka.util.AbortableOperation.failed(netError); fakeNetEngine.request.and.returnValue(operation); - let message = new Uint8Array(0); + const message = new Uint8Array(0); session1.on['message']({target: session1, message: message}); await shaka.test.Util.delay(0.5); expect(onErrorSpy).toHaveBeenCalled(); - let error = onErrorSpy.calls.argsFor(0)[0]; + const error = onErrorSpy.calls.argsFor(0)[0]; shaka.test.Util.expectToEqualError(error, new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.DRM, @@ -1010,13 +1010,13 @@ describe('DrmEngine', function() { async function sendMessageTest( expectedUrl, messageType = 'license-request') { await initAndAttach(); - let initData = new Uint8Array(0); + const initData = new Uint8Array(0); mockVideo.on['encrypted']( {initDataType: 'webm', initData: initData, keyId: null}); - let operation = shaka.util.AbortableOperation.completed({}); + const operation = shaka.util.AbortableOperation.completed({}); fakeNetEngine.request.and.returnValue(operation); - let message = new Uint8Array(0); + const message = new Uint8Array(0); session1.on['message']( {target: session1, message: message, messageType: messageType}); @@ -1034,7 +1034,7 @@ describe('DrmEngine', function() { describe('keystatuseschange', function() { it('is listened for', async () => { await initAndAttach(); - let initData = new Uint8Array(0); + const initData = new Uint8Array(0); mockVideo.on['encrypted']( {initDataType: 'webm', initData: initData, keyId: null}); @@ -1044,14 +1044,14 @@ describe('DrmEngine', function() { it('triggers callback', function(done) { initAndAttach().then(function() { - let initData = new Uint8Array(0); + const initData = new Uint8Array(0); mockVideo.on['encrypted']( {initDataType: 'webm', initData: initData, keyId: null}); - let keyId1 = (new Uint8Array(1)).buffer; - let keyId2 = (new Uint8Array(2)).buffer; - let status1 = 'usable'; - let status2 = 'expired'; + const keyId1 = (new Uint8Array(1)).buffer; + const keyId2 = (new Uint8Array(2)).buffer; + const status1 = 'usable'; + const status2 = 'expired'; session1.keyStatuses.forEach.and.callFake(function(callback) { callback(keyId1, status1); callback(keyId2, status2); @@ -1073,14 +1073,14 @@ describe('DrmEngine', function() { it('does not update public key statuses before callback', async () => { await initAndAttach(); - let initData = new Uint8Array(0); + const initData = new Uint8Array(0); mockVideo.on['encrypted']( {initDataType: 'webm', initData: initData, keyId: null}); - let keyId1 = (new Uint8Array(1)).buffer; - let keyId2 = (new Uint8Array(2)).buffer; - let status1 = 'usable'; - let status2 = 'expired'; + const keyId1 = (new Uint8Array(1)).buffer; + const keyId2 = (new Uint8Array(2)).buffer; + const status1 = 'usable'; + const status2 = 'expired'; session1.keyStatuses.forEach.and.callFake(function(callback) { callback(keyId1, status1); callback(keyId2, status2); @@ -1111,15 +1111,15 @@ describe('DrmEngine', function() { it('does not invoke callback until all sessions are loaded', async () => { // Set up init data overrides in the manifest so that we get multiple // sessions. - let initData1 = new Uint8Array(10); - let initData2 = new Uint8Array(11); + const initData1 = new Uint8Array(10); + const initData2 = new Uint8Array(11); manifest.periods[0].variants[0].drmInfos[0].initData = [ {initData: initData1, initDataType: 'cenc', keyId: null}, {initData: initData2, initDataType: 'cenc', keyId: null}, ]; - let keyId1 = (new Uint8Array(1)).buffer; - let keyId2 = (new Uint8Array(2)).buffer; + const keyId1 = (new Uint8Array(1)).buffer; + const keyId2 = (new Uint8Array(2)).buffer; session1.keyStatuses.forEach.and.callFake(function(callback) { callback(keyId1, 'usable'); }); @@ -1149,12 +1149,12 @@ describe('DrmEngine', function() { initAndAttach().then(function() { expect(onErrorSpy).not.toHaveBeenCalled(); - let initData = new Uint8Array(0); + const initData = new Uint8Array(0); mockVideo.on['encrypted']( {initDataType: 'webm', initData: initData, keyId: null}); - let keyId1 = (new Uint8Array(1)).buffer; - let keyId2 = (new Uint8Array(2)).buffer; + const keyId1 = (new Uint8Array(1)).buffer; + const keyId2 = (new Uint8Array(2)).buffer; // Expire one key. session1.keyStatuses.forEach.and.callFake(function(callback) { @@ -1177,7 +1177,7 @@ describe('DrmEngine', function() { expect(onErrorSpy).toHaveBeenCalled(); // There should be exactly one error. expect(onErrorSpy.calls.count()).toEqual(1); - let error = onErrorSpy.calls.argsFor(0)[0]; + const error = onErrorSpy.calls.argsFor(0)[0]; shaka.test.Util.expectToEqualError(error, new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.DRM, @@ -1198,12 +1198,12 @@ describe('DrmEngine', function() { initAndAttach().then(function() { expect(onErrorSpy).not.toHaveBeenCalled(); - let initData = new Uint8Array(0); + const initData = new Uint8Array(0); mockVideo.on['encrypted']( {initDataType: 'webm', initData: initData, keyId: null}); - let keyId1 = (new Uint8Array(1)).buffer; - let keyId2 = (new Uint8Array(2)).buffer; + const keyId1 = (new Uint8Array(1)).buffer; + const keyId2 = (new Uint8Array(2)).buffer; // Expire both keys at once. session1.keyStatuses.forEach.and.callFake(function(callback) { @@ -1216,7 +1216,7 @@ describe('DrmEngine', function() { expect(onErrorSpy).toHaveBeenCalled(); // There should be exactly one error. expect(onErrorSpy.calls.count()).toEqual(1); - let error = onErrorSpy.calls.argsFor(0)[0]; + const error = onErrorSpy.calls.argsFor(0)[0]; shaka.test.Util.expectToEqualError(error, new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.DRM, @@ -1242,15 +1242,15 @@ describe('DrmEngine', function() { describe('update', function() { it('receives a license', async () => { - let license = (new Uint8Array(0)).buffer; + const license = (new Uint8Array(0)).buffer; await initAndAttach(); - let initData = new Uint8Array(0); + const initData = new Uint8Array(0); mockVideo.on['encrypted']( {initDataType: 'webm', initData: initData, keyId: null}); fakeNetEngine.setResponseValue('http://abc.drm/license', license); - let message = new Uint8Array(0); + const message = new Uint8Array(0); session1.on['message']({target: session1, message: message}); session1.update.and.returnValue(Promise.resolve()); @@ -1279,16 +1279,16 @@ describe('DrmEngine', function() { }); await initAndAttach(); - let message = new Uint8Array(0); + const message = new Uint8Array(0); session1.on['message']({target: session1, message: message}); session1.update.and.returnValue(Promise.resolve()); await shaka.test.Util.delay(0.5); expect(session1.update.calls.count()).toBe(1); - let licenseBuffer = session1.update.calls.argsFor(0)[0]; - let licenseJson = + const licenseBuffer = session1.update.calls.argsFor(0)[0]; + const licenseJson = shaka.util.StringUtils.fromBytesAutoDetect(licenseBuffer); - let license = JSON.parse(licenseJson); + const license = JSON.parse(licenseJson); expect(license).toEqual({ keys: [ {kid: '3q2-796tvu_erb7v3q2-7w', @@ -1301,10 +1301,10 @@ describe('DrmEngine', function() { it('publishes an event if update succeeds', async () => { await initAndAttach(); - let initData = new Uint8Array(1); + const initData = new Uint8Array(1); mockVideo.on['encrypted']( {initDataType: 'webm', initData: initData, keyId: null}); - let message = new Uint8Array(0); + const message = new Uint8Array(0); session1.on['message']({target: session1, message: message}); session1.update.and.returnValue(Promise.resolve()); @@ -1316,21 +1316,21 @@ describe('DrmEngine', function() { it('dispatches an error if update fails', async () => { onErrorSpy.and.stub(); - let license = (new Uint8Array(0)).buffer; + const license = (new Uint8Array(0)).buffer; await initAndAttach(); - let initData = new Uint8Array(0); + const initData = new Uint8Array(0); mockVideo.on['encrypted']( {initDataType: 'webm', initData: initData, keyId: null}); fakeNetEngine.setResponseValue('http://abc.drm/license', license); - let message = new Uint8Array(0); + const message = new Uint8Array(0); session1.on['message']({target: session1, message: message}); session1.update.and.throwError('whoops!'); await shaka.test.Util.delay(0.5); expect(onErrorSpy).toHaveBeenCalled(); - let error = onErrorSpy.calls.argsFor(0)[0]; + const error = onErrorSpy.calls.argsFor(0)[0]; shaka.test.Util.expectToEqualError(error, new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.DRM, @@ -1342,14 +1342,14 @@ describe('DrmEngine', function() { describe('destroy', function() { it('tears down MediaKeys and active sessions', async () => { await initAndAttach(); - let initData1 = new Uint8Array(1); - let initData2 = new Uint8Array(2); + const initData1 = new Uint8Array(1); + const initData2 = new Uint8Array(2); mockVideo.on['encrypted']( {initDataType: 'webm', initData: initData1, keyId: null}); mockVideo.on['encrypted']( {initDataType: 'webm', initData: initData2, keyId: null}); - let message = new Uint8Array(0); + const message = new Uint8Array(0); session1.on['message']({target: session1, message: message}); session1.update.and.returnValue(Promise.resolve()); session2.on['message']({target: session2, message: message}); @@ -1365,14 +1365,14 @@ describe('DrmEngine', function() { it('swallows errors when closing sessions', async () => { await initAndAttach(); - let initData1 = new Uint8Array(1); - let initData2 = new Uint8Array(2); + const initData1 = new Uint8Array(1); + const initData2 = new Uint8Array(2); mockVideo.on['encrypted']( {initDataType: 'webm', initData: initData1, keyId: null}); mockVideo.on['encrypted']( {initDataType: 'webm', initData: initData2, keyId: null}); - let message = new Uint8Array(0); + const message = new Uint8Array(0); session1.on['message']({target: session1, message: message}); session1.update.and.returnValue(Promise.resolve()); session2.on['message']({target: session2, message: message}); @@ -1386,14 +1386,14 @@ describe('DrmEngine', function() { it('swallows errors when clearing MediaKeys', async () => { await initAndAttach(); - let initData1 = new Uint8Array(1); - let initData2 = new Uint8Array(2); + const initData1 = new Uint8Array(1); + const initData2 = new Uint8Array(2); mockVideo.on['encrypted']( {initDataType: 'webm', initData: initData1, keyId: null}); mockVideo.on['encrypted']( {initDataType: 'webm', initData: initData2, keyId: null}); - let message = new Uint8Array(0); + const message = new Uint8Array(0); session1.on['message']({target: session1, message: message}); session1.update.and.returnValue(Promise.resolve()); session2.on['message']({target: session2, message: message}); @@ -1474,7 +1474,7 @@ describe('DrmEngine', function() { it('interrupts failed calls to setMediaKeys', function(done) { // Hold setMediaKeys: - let p1 = new shaka.util.PublicPromise(); + const p1 = new shaka.util.PublicPromise(); mockVideo.setMediaKeys.and.returnValue(p1); // This chain should still return "success" when DrmEngine is destroyed. @@ -1484,7 +1484,7 @@ describe('DrmEngine', function() { // We are now blocked on setMediaKeys: expect(mockVideo.setMediaKeys.calls.count()).toBe(1); // DrmEngine.destroy also calls setMediaKeys. - let p2 = new shaka.util.PublicPromise(); + const p2 = new shaka.util.PublicPromise(); mockVideo.setMediaKeys.and.returnValue(p2); // Set timeouts to complete these calls. shaka.test.Util.delay(0.5).then(p1.reject.bind(p1)); // Failure @@ -1495,7 +1495,7 @@ describe('DrmEngine', function() { it('interrupts successful calls to setMediaKeys', function(done) { // Hold setMediaKeys: - let p1 = new shaka.util.PublicPromise(); + const p1 = new shaka.util.PublicPromise(); mockVideo.setMediaKeys.and.returnValue(p1); // This chain should still return "success" when DrmEngine is destroyed. @@ -1505,7 +1505,7 @@ describe('DrmEngine', function() { // We are now blocked on setMediaKeys: expect(mockVideo.setMediaKeys.calls.count()).toBe(1); // DrmEngine.destroy also calls setMediaKeys. - let p2 = new shaka.util.PublicPromise(); + const p2 = new shaka.util.PublicPromise(); mockVideo.setMediaKeys.and.returnValue(p2); // Set timeouts to complete these calls. shaka.test.Util.delay(0.5).then(p1.resolve.bind(p1)); // Success @@ -1518,12 +1518,12 @@ describe('DrmEngine', function() { }); it('interrupts failed calls to setServerCertificate', function(done) { - let cert = new Uint8Array(1); + const cert = new Uint8Array(1); config.advanced['drm.abc'] = createAdvancedConfig(cert); drmEngine.configure(config); // Hold setServerCertificate: - let p = new shaka.util.PublicPromise(); + const p = new shaka.util.PublicPromise(); mockMediaKeys.setServerCertificate.and.returnValue(p); // This chain should still return "success" when DrmEngine is destroyed. @@ -1540,12 +1540,12 @@ describe('DrmEngine', function() { }); it('interrupts successful calls to setServerCertificate', function(done) { - let cert = new Uint8Array(1); + const cert = new Uint8Array(1); config.advanced['drm.abc'] = createAdvancedConfig(cert); drmEngine.configure(config); // Hold setServerCertificate: - let p = new shaka.util.PublicPromise(); + const p = new shaka.util.PublicPromise(); mockMediaKeys.setServerCertificate.and.returnValue(p); // This chain should still return "success" when DrmEngine is destroyed. @@ -1565,11 +1565,11 @@ describe('DrmEngine', function() { }); it('does not trigger errors if it fails generateRequest', function(done) { - let p = new shaka.util.PublicPromise(); + const p = new shaka.util.PublicPromise(); session1.generateRequest.and.returnValue(p); initAndAttach().then(function() { - let initData1 = new Uint8Array(1); + const initData1 = new Uint8Array(1); mockVideo.on['encrypted']( {initDataType: 'webm', initData: initData1, keyId: null}); @@ -1584,16 +1584,16 @@ describe('DrmEngine', function() { }); it('interrupts successful license requests', function(done) { - let p = new shaka.util.PublicPromise(); - let operation = shaka.util.AbortableOperation.notAbortable(p); + const p = new shaka.util.PublicPromise(); + const operation = shaka.util.AbortableOperation.notAbortable(p); fakeNetEngine.request.and.returnValue(operation); initAndAttach().then(function() { - let initData1 = new Uint8Array(1); + const initData1 = new Uint8Array(1); mockVideo.on['encrypted']( {initDataType: 'webm', initData: initData1, keyId: null}); - let message = new Uint8Array(0); + const message = new Uint8Array(0); session1.on['message']({target: session1, message: message}); session1.update.and.returnValue(Promise.resolve()); @@ -1615,16 +1615,16 @@ describe('DrmEngine', function() { }); it('interrupts failed license requests', function(done) { - let p = new shaka.util.PublicPromise(); - let operation = shaka.util.AbortableOperation.notAbortable(p); + const p = new shaka.util.PublicPromise(); + const operation = shaka.util.AbortableOperation.notAbortable(p); fakeNetEngine.request.and.returnValue(operation); initAndAttach().then(function() { - let initData1 = new Uint8Array(1); + const initData1 = new Uint8Array(1); mockVideo.on['encrypted']( {initDataType: 'webm', initData: initData1, keyId: null}); - let message = new Uint8Array(0); + const message = new Uint8Array(0); session1.on['message']({target: session1, message: message}); session1.update.and.returnValue(Promise.resolve()); @@ -1643,15 +1643,15 @@ describe('DrmEngine', function() { }); it('does not trigger errors if it fails update', function(done) { - let p = new shaka.util.PublicPromise(); + const p = new shaka.util.PublicPromise(); session1.update.and.returnValue(p); initAndAttach().then(function() { - let initData1 = new Uint8Array(1); + const initData1 = new Uint8Array(1); mockVideo.on['encrypted']( {initDataType: 'webm', initData: initData1, keyId: null}); - let message = new Uint8Array(0); + const message = new Uint8Array(0); session1.on['message']({target: session1, message: message}); return shaka.test.Util.delay(0.1); @@ -1684,8 +1684,8 @@ describe('DrmEngine', function() { session1.close.and.returnValue(rejected); session2.close.and.returnValue(rejected); - let initData1 = new Uint8Array(1); - let initData2 = new Uint8Array(2); + const initData1 = new Uint8Array(1); + const initData2 = new Uint8Array(2); mockVideo.on['encrypted']( {initDataType: 'webm', initData: initData1, keyId: null}); mockVideo.on['encrypted']( @@ -1693,7 +1693,7 @@ describe('DrmEngine', function() { // Still resolve these since we are mocking close and closed. This // ensures DrmEngine is in the correct state. - let message = new Uint8Array(0); + const message = new Uint8Array(0); session1.on['message']({target: session1, message: message}); session1.update.and.returnValue(Promise.resolve()); session2.on['message']({target: session2, message: message}); @@ -1734,7 +1734,7 @@ describe('DrmEngine', function() { const variants = Periods.getAllVariantsFrom(manifest.periods); await drmEngine.initForPlayback(variants, manifest.offlineSessionIds); expect(drmEngine.initialized()).toBe(true); - let drmInfo = drmEngine.getDrmInfo(); + const drmInfo = drmEngine.getDrmInfo(); expect(drmInfo).toEqual({ keySystem: 'drm.abc', licenseServerUri: 'http://abc.drm/license', @@ -1751,7 +1751,7 @@ describe('DrmEngine', function() { describe('getCommonDrmInfos', function() { it('returns one array if the other is empty', () => { - let drmInfo = { + const drmInfo = { keySystem: 'drm.abc', licenseServerUri: 'http://abc.drm/license', distinctiveIdentifierRequired: true, @@ -1762,15 +1762,17 @@ describe('DrmEngine', function() { initData: [], keyIds: ['deadbeefdeadbeefdeadbeefdeadbeef'], }; - let returnedOne = shaka.media.DrmEngine.getCommonDrmInfos([drmInfo], []); - let returnedTwo = shaka.media.DrmEngine.getCommonDrmInfos([], [drmInfo]); + const returnedOne = + shaka.media.DrmEngine.getCommonDrmInfos([drmInfo], []); + const returnedTwo = + shaka.media.DrmEngine.getCommonDrmInfos([], [drmInfo]); expect(returnedOne).toEqual([drmInfo]); expect(returnedTwo).toEqual([drmInfo]); }); it('merges drmInfos if two exist', () => { - let serverCert = new Uint8Array(0); - let drmInfoVideo = { + const serverCert = new Uint8Array(0); + const drmInfoVideo = { keySystem: 'drm.abc', licenseServerUri: 'http://abc.drm/license', distinctiveIdentifierRequired: false, @@ -1780,7 +1782,7 @@ describe('DrmEngine', function() { initData: ['blah'], keyIds: ['deadbeefdeadbeefdeadbeefdeadbeef'], }; - let drmInfoAudio = { + const drmInfoAudio = { keySystem: 'drm.abc', licenseServerUri: undefined, distinctiveIdentifierRequired: true, @@ -1790,7 +1792,7 @@ describe('DrmEngine', function() { initData: ['init data'], keyIds: ['eadbeefdeadbeefdeadbeefdeadbeefd'], }; - let drmInfoDesired = { + const drmInfoDesired = { keySystem: 'drm.abc', licenseServerUri: 'http://abc.drm/license', distinctiveIdentifierRequired: true, @@ -1802,7 +1804,7 @@ describe('DrmEngine', function() { keyIds: ['deadbeefdeadbeefdeadbeefdeadbeef', 'eadbeefdeadbeefdeadbeefdeadbeefd'], }; - let returned = shaka.media.DrmEngine.getCommonDrmInfos([drmInfoVideo], + const returned = shaka.media.DrmEngine.getCommonDrmInfos([drmInfoVideo], [drmInfoAudio]); expect(returned).toEqual([drmInfoDesired]); }); @@ -1815,13 +1817,13 @@ describe('DrmEngine', function() { mockVideo.paused = true; await initAndAttach(); - let initData = new Uint8Array(0); + const initData = new Uint8Array(0); mockVideo.on['encrypted']( {initDataType: 'webm', initData: initData, keyId: null}); - let operation = shaka.util.AbortableOperation.completed({}); + const operation = shaka.util.AbortableOperation.completed({}); fakeNetEngine.request.and.returnValue(operation); - let message = new Uint8Array(0); + const message = new Uint8Array(0); session1.on['message']({target: session1, message: message}); expect(fakeNetEngine.request).not.toHaveBeenCalled(); @@ -1843,13 +1845,13 @@ describe('DrmEngine', function() { mockVideo.paused = true; await initAndAttach(); - let initData = new Uint8Array(0); + const initData = new Uint8Array(0); mockVideo.on['encrypted']( {initDataType: 'webm', initData: initData, keyId: null}); - let operation = shaka.util.AbortableOperation.completed({}); + const operation = shaka.util.AbortableOperation.completed({}); fakeNetEngine.request.and.returnValue(operation); - let message = new Uint8Array(0); + const message = new Uint8Array(0); session1.on['message']({target: session1, message: message}); expect(fakeNetEngine.request).not.toHaveBeenCalled(); @@ -1911,8 +1913,8 @@ describe('DrmEngine', function() { }); it('is rejected when network request fails', async () => { - let p = fakeNetEngine.delayNextRequest(); - let networkError = new shaka.util.Error( + const p = fakeNetEngine.delayNextRequest(); + const networkError = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.NETWORK, shaka.util.Error.Code.BAD_HTTP_STATUS); @@ -1967,8 +1969,8 @@ describe('DrmEngine', function() { session1.expiration = NaN; await initAndAttach(); - let initData = new Uint8Array(0); - let message = new Uint8Array(0); + const initData = new Uint8Array(0); + const message = new Uint8Array(0); mockVideo.on['encrypted']( {initDataType: 'webm', initData: initData, keyId: null}); session1.on['message']({target: session1, message: message}); @@ -2022,7 +2024,7 @@ describe('DrmEngine', function() { } function createMockMediaKeySystemAccess() { - let mksa = { + const mksa = { keySystem: '', getConfiguration: jasmine.createSpy('getConfiguration'), createMediaKeys: jasmine.createSpy('createMediaKeys'), @@ -2047,7 +2049,7 @@ describe('DrmEngine', function() { } function createMockSession() { - let session = { + const session = { expiration: NaN, closed: Promise.resolve(), keyStatuses: { diff --git a/test/media/media_source_engine_integration.js b/test/media/media_source_engine_integration.js index ee63936bd9..9d2f9756da 100644 --- a/test/media/media_source_engine_integration.js +++ b/test/media/media_source_engine_integration.js @@ -71,13 +71,13 @@ describe('MediaSourceEngine', function() { }); function appendInit(type) { - let segment = generators[type].getInitSegment(Date.now() / 1000); + const segment = generators[type].getInitSegment(Date.now() / 1000); return mediaSourceEngine.appendBuffer( type, segment, null, null, /* hasClosedCaptions */ false); } function append(type, segmentNumber) { - let segment = generators[type]. + const segment = generators[type]. getSegment(segmentNumber, 0, Date.now() / 1000); return mediaSourceEngine.appendBuffer( type, segment, null, null, /* hasClosedCaptions */ false); @@ -86,7 +86,7 @@ describe('MediaSourceEngine', function() { // The start time and end time should be null for init segment with closed // captions. function appendInitWithClosedCaptions(type) { - let segment = generators[type].getInitSegment(Date.now() / 1000); + const segment = generators[type].getInitSegment(Date.now() / 1000); return mediaSourceEngine.appendBuffer(type, segment, /* startTime */ null, /* endTime */ null, /* hasClosedCaptions */ true); } @@ -94,7 +94,7 @@ describe('MediaSourceEngine', function() { // The start time and end time should be valid for the segments with closed // captions. function appendWithClosedCaptions(type, segmentNumber) { - let segment = generators[type]. + const segment = generators[type]. getSegment(segmentNumber, 0, Date.now() / 1000); return mediaSourceEngine.appendBuffer(type, segment, /* startTime */ 0, /* endTime */ 2, /* hasClosedCaptions */ true); @@ -109,8 +109,8 @@ describe('MediaSourceEngine', function() { } function remove(type, segmentNumber) { - let start = (segmentNumber - 1) * metadata[type].segmentDuration; - let end = segmentNumber * metadata[type].segmentDuration; + const start = (segmentNumber - 1) * metadata[type].segmentDuration; + const end = segmentNumber * metadata[type].segmentDuration; return mediaSourceEngine.remove(type, start, end); } @@ -194,11 +194,11 @@ describe('MediaSourceEngine', function() { }); it('queues operations', function(done) { - let resolutionOrder = []; - let requests = []; + const resolutionOrder = []; + const requests = []; function checkOrder(p) { - let nextIndex = requests.length; + const nextIndex = requests.length; requests.push(p); p.then(function() { resolutionOrder.push(nextIndex); }); } @@ -244,7 +244,7 @@ describe('MediaSourceEngine', function() { await mediaSourceEngine.init(initObject, false); await mediaSourceEngine.setDuration(presentationDuration); - let audioStreaming = appendInit(ContentType.AUDIO).then(() => { + const audioStreaming = appendInit(ContentType.AUDIO).then(() => { return append(ContentType.AUDIO, 1); }).then(() => { expect(buffered(ContentType.AUDIO, 0)).toBeCloseTo(10, 1); @@ -265,7 +265,7 @@ describe('MediaSourceEngine', function() { expect(buffered(ContentType.AUDIO, 0)).toBeCloseTo(60, 1); }); - let videoStreaming = appendInit(ContentType.VIDEO).then(() => { + const videoStreaming = appendInit(ContentType.VIDEO).then(() => { return append(ContentType.VIDEO, 1); }).then(() => { expect(buffered(ContentType.VIDEO, 0)).toBeCloseTo(10); diff --git a/test/media/media_source_engine_unit.js b/test/media/media_source_engine_unit.js index 6d85acba59..ea23bc167e 100644 --- a/test/media/media_source_engine_unit.js +++ b/test/media/media_source_engine_unit.js @@ -89,7 +89,7 @@ describe('MediaSourceEngine', function() { // fail assertions based on browser support for types. Pretend that all // video and audio types are supported. window.MediaSource.isTypeSupported = function(mimeType) { - let type = mimeType.split('/')[0]; + const type = mimeType.split('/')[0]; return type == 'video' || type == 'audio'; }; @@ -112,7 +112,7 @@ describe('MediaSourceEngine', function() { videoSourceBuffer = createMockSourceBuffer(); mockMediaSource = createMockMediaSource(); mockMediaSource.addSourceBuffer.and.callFake(function(mimeType) { - let type = mimeType.split('/')[0]; + const type = mimeType.split('/')[0]; return type == 'audio' ? audioSourceBuffer : videoSourceBuffer; }); @@ -180,9 +180,10 @@ describe('MediaSourceEngine', function() { shaka.media.MediaSourceEngine.createObjectURL = Util.spyFunc(createObjectURLSpy); - let mediaSourceSpy = jasmine.createSpy('MediaSource').and.callFake(() => { - return mockMediaSource; - }); + const mediaSourceSpy = + jasmine.createSpy('MediaSource').and.callFake(() => { + return mockMediaSource; + }); window.MediaSource = Util.spyFunc(mediaSourceSpy); await mediaSourceEngine.destroy(); @@ -340,7 +341,7 @@ describe('MediaSourceEngine', function() { it('appends the given data', async () => { /** @type {!shaka.test.StatusPromise} */ - let p = new shaka.test.StatusPromise(mediaSourceEngine.appendBuffer( + const p = new shaka.test.StatusPromise(mediaSourceEngine.appendBuffer( ContentType.AUDIO, buffer, null, null, /* hasClosedCaptions */ false)); expect(audioSourceBuffer.appendBuffer).toHaveBeenCalledWith(buffer); @@ -365,7 +366,7 @@ describe('MediaSourceEngine', function() { }); it('rejects promise when op. throws QuotaExceededError', async () => { - let fakeDOMException = {name: 'QuotaExceededError'}; + const fakeDOMException = {name: 'QuotaExceededError'}; audioSourceBuffer.appendBuffer.and.callFake(function() { throw fakeDOMException; }); @@ -400,11 +401,11 @@ describe('MediaSourceEngine', function() { it('queues operations on a single SourceBuffer', async () => { /** @type {!shaka.test.StatusPromise} */ - let p1 = new shaka.test.StatusPromise(mediaSourceEngine.appendBuffer( + const p1 = new shaka.test.StatusPromise(mediaSourceEngine.appendBuffer( ContentType.AUDIO, buffer, null, null, /* hasClosedCaptions */ false)); /** @type {!shaka.test.StatusPromise} */ - let p2 = new shaka.test.StatusPromise(mediaSourceEngine.appendBuffer( + const p2 = new shaka.test.StatusPromise(mediaSourceEngine.appendBuffer( ContentType.AUDIO, buffer2, null, null, /* hasClosedCaptions */ false)); @@ -423,15 +424,15 @@ describe('MediaSourceEngine', function() { it('queues operations independently for different types', async () => { /** @type {!shaka.test.StatusPromise} */ - let p1 = new shaka.test.StatusPromise(mediaSourceEngine.appendBuffer( + const p1 = new shaka.test.StatusPromise(mediaSourceEngine.appendBuffer( ContentType.AUDIO, buffer, null, null, /* hasClosedCaptions */ false)); /** @type {!shaka.test.StatusPromise} */ - let p2 = new shaka.test.StatusPromise(mediaSourceEngine.appendBuffer( + const p2 = new shaka.test.StatusPromise(mediaSourceEngine.appendBuffer( ContentType.AUDIO, buffer2, null, null, /* hasClosedCaptions */ false)); /** @type {!shaka.test.StatusPromise} */ - let p3 = new shaka.test.StatusPromise(mediaSourceEngine.appendBuffer( + const p3 = new shaka.test.StatusPromise(mediaSourceEngine.appendBuffer( ContentType.VIDEO, buffer3, null, null, /* hasClosedCaptions */ false)); @@ -467,15 +468,15 @@ describe('MediaSourceEngine', function() { }); /** @type {!shaka.test.StatusPromise} */ - let p1 = new shaka.test.StatusPromise(mediaSourceEngine.appendBuffer( + const p1 = new shaka.test.StatusPromise(mediaSourceEngine.appendBuffer( ContentType.AUDIO, buffer, null, null, /* hasClosedCaptions */ false)); /** @type {!shaka.test.StatusPromise} */ - let p2 = new shaka.test.StatusPromise(mediaSourceEngine.appendBuffer( + const p2 = new shaka.test.StatusPromise(mediaSourceEngine.appendBuffer( ContentType.AUDIO, buffer2, null, null, /* hasClosedCaptions */ false)); /** @type {!shaka.test.StatusPromise} */ - let p3 = new shaka.test.StatusPromise(mediaSourceEngine.appendBuffer( + const p3 = new shaka.test.StatusPromise(mediaSourceEngine.appendBuffer( ContentType.AUDIO, buffer3, null, null, /* hasClosedCaptions */ false)); @@ -489,7 +490,7 @@ describe('MediaSourceEngine', function() { }); it('forwards to TextEngine', async () => { - let data = new ArrayBuffer(0); + const data = new ArrayBuffer(0); expect(mockTextEngine.appendBuffer).not.toHaveBeenCalled(); await mediaSourceEngine.appendBuffer( ContentType.TEXT, data, 0, 10, /* hasClosedCaptions */ false); @@ -654,10 +655,10 @@ describe('MediaSourceEngine', function() { it('queues operations on a single SourceBuffer', async () => { /** @type {!shaka.test.StatusPromise} */ - let p1 = new shaka.test.StatusPromise( + const p1 = new shaka.test.StatusPromise( mediaSourceEngine.remove(ContentType.AUDIO, 1, 5)); /** @type {!shaka.test.StatusPromise} */ - let p2 = new shaka.test.StatusPromise( + const p2 = new shaka.test.StatusPromise( mediaSourceEngine.remove(ContentType.AUDIO, 6, 10)); expect(audioSourceBuffer.remove).toHaveBeenCalledWith(1, 5); @@ -675,13 +676,13 @@ describe('MediaSourceEngine', function() { it('queues operations independently for different types', async () => { /** @type {!shaka.test.StatusPromise} */ - let p1 = new shaka.test.StatusPromise( + const p1 = new shaka.test.StatusPromise( mediaSourceEngine.remove(ContentType.AUDIO, 1, 5)); /** @type {!shaka.test.StatusPromise} */ - let p2 = new shaka.test.StatusPromise( + const p2 = new shaka.test.StatusPromise( mediaSourceEngine.remove(ContentType.AUDIO, 6, 10)); /** @type {!shaka.test.StatusPromise} */ - let p3 = new shaka.test.StatusPromise( + const p3 = new shaka.test.StatusPromise( mediaSourceEngine.remove(ContentType.VIDEO, 3, 8)); expect(audioSourceBuffer.remove).toHaveBeenCalledWith(1, 5); @@ -715,13 +716,13 @@ describe('MediaSourceEngine', function() { }); /** @type {!shaka.test.StatusPromise} */ - let p1 = new shaka.test.StatusPromise( + const p1 = new shaka.test.StatusPromise( mediaSourceEngine.remove(ContentType.AUDIO, 1, 2)); /** @type {!shaka.test.StatusPromise} */ - let p2 = new shaka.test.StatusPromise( + const p2 = new shaka.test.StatusPromise( mediaSourceEngine.remove(ContentType.AUDIO, 2, 3)); /** @type {!shaka.test.StatusPromise} */ - let p3 = new shaka.test.StatusPromise( + const p3 = new shaka.test.StatusPromise( mediaSourceEngine.remove(ContentType.AUDIO, 3, 4)); await Util.delay(0.1); @@ -825,15 +826,15 @@ describe('MediaSourceEngine', function() { it('waits for all previous operations to complete', async () => { /** @type {!shaka.test.StatusPromise} */ - let p1 = new shaka.test.StatusPromise(mediaSourceEngine.appendBuffer( + const p1 = new shaka.test.StatusPromise(mediaSourceEngine.appendBuffer( ContentType.AUDIO, buffer, null, null, /* hasClosedCaptions */ false)); /** @type {!shaka.test.StatusPromise} */ - let p2 = new shaka.test.StatusPromise(mediaSourceEngine.appendBuffer( + const p2 = new shaka.test.StatusPromise(mediaSourceEngine.appendBuffer( ContentType.VIDEO, buffer, null, null, /* hasClosedCaptions */ false)); /** @type {!shaka.test.StatusPromise} */ - let p3 = new shaka.test.StatusPromise(mediaSourceEngine.endOfStream()); + const p3 = new shaka.test.StatusPromise(mediaSourceEngine.endOfStream()); expect(mockMediaSource.endOfStream).not.toHaveBeenCalled(); expect(p1.status).toBe('pending'); @@ -852,7 +853,7 @@ describe('MediaSourceEngine', function() { it('makes subsequent operations wait', async () => { /** @type {!Promise} */ - let p1 = mediaSourceEngine.endOfStream(); + const p1 = mediaSourceEngine.endOfStream(); mediaSourceEngine.appendBuffer(ContentType.AUDIO, buffer, null, null, /* hasClosedCaptions */ false); mediaSourceEngine.appendBuffer(ContentType.VIDEO, buffer, null, null, @@ -884,7 +885,7 @@ describe('MediaSourceEngine', function() { it('runs subsequent operations if this operation throws', async () => { mockMediaSource.endOfStream.and.throwError(new Error()); /** @type {!Promise} */ - let p1 = mediaSourceEngine.endOfStream(); + const p1 = mediaSourceEngine.endOfStream(); mediaSourceEngine.appendBuffer(ContentType.AUDIO, buffer, null, null, /* hasClosedCaptions */ false); @@ -920,15 +921,16 @@ describe('MediaSourceEngine', function() { it('waits for all previous operations to complete', async () => { /** @type {!shaka.test.StatusPromise} */ - let p1 = new shaka.test.StatusPromise(mediaSourceEngine.appendBuffer( + const p1 = new shaka.test.StatusPromise(mediaSourceEngine.appendBuffer( ContentType.AUDIO, buffer, null, null, /* hasClosedCaptions */ false)); /** @type {!shaka.test.StatusPromise} */ - let p2 = new shaka.test.StatusPromise(mediaSourceEngine.appendBuffer( + const p2 = new shaka.test.StatusPromise(mediaSourceEngine.appendBuffer( ContentType.VIDEO, buffer, null, null, /* hasClosedCaptions */ false)); /** @type {!shaka.test.StatusPromise} */ - let p3 = new shaka.test.StatusPromise(mediaSourceEngine.setDuration(100)); + const p3 = + new shaka.test.StatusPromise(mediaSourceEngine.setDuration(100)); expect(mockMediaSource.durationSetter_).not.toHaveBeenCalled(); expect(p1.status).toBe('pending'); @@ -947,7 +949,7 @@ describe('MediaSourceEngine', function() { it('makes subsequent operations wait', async () => { /** @type {!Promise} */ - let p1 = mediaSourceEngine.setDuration(100); + const p1 = mediaSourceEngine.setDuration(100); mediaSourceEngine.appendBuffer(ContentType.AUDIO, buffer, null, null, /* hasClosedCaptions */ false); mediaSourceEngine.appendBuffer(ContentType.VIDEO, buffer, null, null, @@ -980,7 +982,7 @@ describe('MediaSourceEngine', function() { it('runs subsequent operations if this operation throws', async () => { mockMediaSource.durationSetter_.and.throwError(new Error()); /** @type {!Promise} */ - let p1 = mediaSourceEngine.setDuration(100); + const p1 = mediaSourceEngine.setDuration(100); mediaSourceEngine.appendBuffer(ContentType.AUDIO, buffer, null, null, /* hasClosedCaptions */ false); @@ -1015,7 +1017,7 @@ describe('MediaSourceEngine', function() { /* hasClosedCaptions */ false); /** @type {!shaka.test.StatusPromise} */ - let p = new shaka.test.StatusPromise(mediaSourceEngine.destroy()); + const p = new shaka.test.StatusPromise(mediaSourceEngine.destroy()); expect(p.status).toBe('pending'); await Util.delay(0.1); @@ -1030,11 +1032,11 @@ describe('MediaSourceEngine', function() { it('resolves even when a pending operation fails', async () => { /** @type {!shaka.test.StatusPromise} */ - let p1 = new shaka.test.StatusPromise(mediaSourceEngine.appendBuffer( + const p1 = new shaka.test.StatusPromise(mediaSourceEngine.appendBuffer( ContentType.AUDIO, buffer, null, null, /* hasClosedCaptions */ false)); /** @type {!shaka.test.StatusPromise} */ - let p2 = new shaka.test.StatusPromise(mediaSourceEngine.destroy()); + const p2 = new shaka.test.StatusPromise(mediaSourceEngine.destroy()); audioSourceBuffer.error(); audioSourceBuffer.updateend(); @@ -1045,9 +1047,9 @@ describe('MediaSourceEngine', function() { it('waits for blocking operations to complete', async () => { /** @type {!shaka.test.StatusPromise} */ - let p1 = new shaka.test.StatusPromise(mediaSourceEngine.endOfStream()); + const p1 = new shaka.test.StatusPromise(mediaSourceEngine.endOfStream()); /** @type {!shaka.test.StatusPromise} */ - let p2 = new shaka.test.StatusPromise(mediaSourceEngine.destroy()); + const p2 = new shaka.test.StatusPromise(mediaSourceEngine.destroy()); expect(p1.status).toBe('pending'); expect(p2.status).toBe('pending'); @@ -1061,7 +1063,7 @@ describe('MediaSourceEngine', function() { mediaSourceEngine.appendBuffer( ContentType.AUDIO, buffer, null, null, /* hasClosedCaptions */ false); /** @type {!shaka.test.StatusPromise} */ - let rejected = + const rejected = new shaka.test.StatusPromise(mediaSourceEngine.appendBuffer( ContentType.AUDIO, buffer2, null, null, /* hasClosedCaptions */ false)); @@ -1070,7 +1072,7 @@ describe('MediaSourceEngine', function() { expect(audioSourceBuffer.appendBuffer).not.toHaveBeenCalledWith(buffer2); /** @type {!shaka.test.StatusPromise} */ - let p = new shaka.test.StatusPromise(mediaSourceEngine.destroy()); + const p = new shaka.test.StatusPromise(mediaSourceEngine.destroy()); expect(p.status).toBe('pending'); await Util.delay(0.1); @@ -1086,13 +1088,13 @@ describe('MediaSourceEngine', function() { it('cancels blocking operations that have not yet started', async () => { /** @type {!shaka.test.StatusPromise} */ - let p1 = new shaka.test.StatusPromise(mediaSourceEngine.appendBuffer( + const p1 = new shaka.test.StatusPromise(mediaSourceEngine.appendBuffer( ContentType.AUDIO, buffer, null, null, /* hasClosedCaptions */ false)); /** @type {!shaka.test.StatusPromise} */ - let p2 = new shaka.test.StatusPromise(mediaSourceEngine.endOfStream()); + const p2 = new shaka.test.StatusPromise(mediaSourceEngine.endOfStream()); /** @type {!shaka.test.StatusPromise} */ - let p3 = new shaka.test.StatusPromise(mediaSourceEngine.destroy()); + const p3 = new shaka.test.StatusPromise(mediaSourceEngine.destroy()); expect(p1.status).toBe('pending'); expect(p2.status).toBe('pending'); @@ -1106,9 +1108,9 @@ describe('MediaSourceEngine', function() { }); it('prevents new operations from being added', async () => { - let p = mediaSourceEngine.destroy(); + const p = mediaSourceEngine.destroy(); /** @type {!shaka.test.StatusPromise} */ - let rejected = + const rejected = new shaka.test.StatusPromise(mediaSourceEngine.appendBuffer( ContentType.AUDIO, buffer, null, null, /* hasClosedCaptions */ false)); @@ -1139,7 +1141,7 @@ describe('MediaSourceEngine', function() { }); function createMockMediaSource() { - let mediaSource = { + const mediaSource = { readyState: 'open', addSourceBuffer: jasmine.createSpy('addSourceBuffer'), endOfStream: jasmine.createSpy('endOfStream'), @@ -1176,7 +1178,7 @@ describe('MediaSourceEngine', function() { } function createMockTextEngineCtor() { - let ctor = jasmine.createSpy('TextEngine'); + const ctor = jasmine.createSpy('TextEngine'); ctor.isTypeSupported = function() { return true; }; ctor.and.callFake(function() { expect(mockTextEngine).toBeFalsy(); @@ -1186,7 +1188,7 @@ describe('MediaSourceEngine', function() { 'appendCues', 'storeAndAppendClosedCaptions', ]); - let resolve = Promise.resolve.bind(Promise); + const resolve = Promise.resolve.bind(Promise); mockTextEngine.destroy.and.callFake(resolve); mockTextEngine.appendBuffer.and.callFake(resolve); mockTextEngine.remove.and.callFake(resolve); diff --git a/test/media/mp4_segment_index_parser_unit.js b/test/media/mp4_segment_index_parser_unit.js index b82d7d4567..3b120b2624 100644 --- a/test/media/mp4_segment_index_parser_unit.js +++ b/test/media/mp4_segment_index_parser_unit.js @@ -23,7 +23,7 @@ describe('Mp4SegmentIndexParser', function() { let mediaSegment; beforeAll(async () => { - let responses = await Promise.all([ + const responses = await Promise.all([ shaka.test.Util.fetch(indexSegmentUri), shaka.test.Util.fetch(mediaSegmentUri), ]); @@ -32,7 +32,7 @@ describe('Mp4SegmentIndexParser', function() { }); it('rejects a non-index segment ', function() { - let error = new shaka.util.Error( + const error = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.MEDIA, shaka.util.Error.Code.MP4_SIDX_WRONG_BOX_TYPE); @@ -47,8 +47,8 @@ describe('Mp4SegmentIndexParser', function() { it('parses index segment ', function() { // eslint-disable-next-line new-cap - let result = shaka.media.Mp4SegmentIndexParser(indexSegment, 0, [], 0); - let references = + const result = shaka.media.Mp4SegmentIndexParser(indexSegment, 0, [], 0); + const references = [ {startTime: 0, endTime: 12, startByte: 92, endByte: 194960}, {startTime: 12, endTime: 24, startByte: 194961, endByte: 294059}, @@ -70,8 +70,8 @@ describe('Mp4SegmentIndexParser', function() { it('takes a scaled presentationTimeOffset in seconds', function() { // eslint-disable-next-line new-cap - let result = shaka.media.Mp4SegmentIndexParser(indexSegment, 0, [], 2); - let references = + const result = shaka.media.Mp4SegmentIndexParser(indexSegment, 0, [], 2); + const references = [ {startTime: -2, endTime: 10}, {startTime: 10, endTime: 22}, diff --git a/test/media/playhead_unit.js b/test/media/playhead_unit.js index c42c25c048..e24f6456d7 100644 --- a/test/media/playhead_unit.js +++ b/test/media/playhead_unit.js @@ -161,9 +161,9 @@ describe('Playhead', function() { }); function setMockDate(seconds) { - let minutes = Math.floor(seconds / 60); + const minutes = Math.floor(seconds / 60); seconds = seconds % 60; - let mockDate = new Date(2013, 9, 23, 7, minutes, seconds); + const mockDate = new Date(2013, 9, 23, 7, minutes, seconds); jasmine.clock().mockDate(mockDate); } @@ -1146,7 +1146,7 @@ describe('Playhead', function() { }); // with unbuffered seeks it('doesn\'t gap jump if the seeking event is late', function() { - let buffered = [{start: 10, end: 20}]; + const buffered = [{start: 10, end: 20}]; video.buffered = createFakeBuffered(buffered); video.currentTime = 12; video.readyState = HTMLMediaElement.HAVE_ENOUGH_DATA; @@ -1181,7 +1181,7 @@ describe('Playhead', function() { // If the browser sets the time to slightly before where we seek to, we // shouldn't get stuck in an infinite loop trying to jump the tiny gap. // https://github.com/google/shaka-player/issues/1309 - let buffered = [{start: 10, end: 20}]; + const buffered = [{start: 10, end: 20}]; video.buffered = createFakeBuffered(buffered); video.readyState = HTMLMediaElement.HAVE_METADATA; diff --git a/test/media/presentation_timeline_unit.js b/test/media/presentation_timeline_unit.js index fe133b2b3c..d4d2a905c7 100644 --- a/test/media/presentation_timeline_unit.js +++ b/test/media/presentation_timeline_unit.js @@ -59,7 +59,7 @@ describe('PresentationTimeline', function() { clockOffset, presentationDelay, autoCorrectDrift = true) { - let timeline = new shaka.media.PresentationTimeline( + const timeline = new shaka.media.PresentationTimeline( presentationStartTime, presentationDelay, autoCorrectDrift); timeline.setStatic(isStatic); timeline.setDuration(duration || Infinity); @@ -77,7 +77,7 @@ describe('PresentationTimeline', function() { * @return {shaka.media.PresentationTimeline} */ function makeVodTimeline(duration) { - let timeline = makePresentationTimeline( + const timeline = makePresentationTimeline( /* static */ true, duration, /* start time */ null, /* availability */ Infinity, /* max seg dur */ 10, /* clock offset */ 0, /* presentation delay */ 0); @@ -94,8 +94,8 @@ describe('PresentationTimeline', function() { * @return {shaka.media.PresentationTimeline} */ function makeIprTimeline(duration, delay) { - let now = Date.now() / 1000; - let timeline = makePresentationTimeline( + const now = Date.now() / 1000; + const timeline = makePresentationTimeline( /* static */ false, duration, /* start time */ now, /* availability */ Infinity, /* max seg dur */ 10, /* clock offset */ 0, delay || 0); @@ -113,8 +113,8 @@ describe('PresentationTimeline', function() { * @return {shaka.media.PresentationTimeline} */ function makeLiveTimeline(availability, delay, autoCorrectDrift = true) { - let now = Date.now() / 1000; - let timeline = makePresentationTimeline( + const now = Date.now() / 1000; + const timeline = makePresentationTimeline( /* static */ false, /* duration */ Infinity, /* start time */ now, availability, /* max seg dur */ 10, /* clock offset */ 0, delay || 0, autoCorrectDrift); @@ -143,8 +143,8 @@ describe('PresentationTimeline', function() { describe('getSegmentAvailabilityStart', function() { it('returns 0 for VOD and IPR', function() { - let timeline1 = makeVodTimeline(/* duration */ 60); - let timeline2 = makeIprTimeline(/* duration */ 60); + const timeline1 = makeVodTimeline(/* duration */ 60); + const timeline2 = makeIprTimeline(/* duration */ 60); setElapsed(0); expect(timeline1.getSegmentAvailabilityStart()).toBe(0); @@ -156,7 +156,7 @@ describe('PresentationTimeline', function() { }); it('calculates time for live with finite availability', function() { - let timeline = makeLiveTimeline(/* availability */ 20); + const timeline = makeLiveTimeline(/* availability */ 20); setElapsed(0); expect(timeline.getSegmentAvailabilityStart()).toBe(0); @@ -181,7 +181,7 @@ describe('PresentationTimeline', function() { }); it('calculates time for live with infinite availability', function() { - let timeline = makeLiveTimeline(/* availability */ Infinity); + const timeline = makeLiveTimeline(/* availability */ Infinity); setElapsed(0); expect(timeline.getSegmentAvailabilityStart()).toBe(0); @@ -197,7 +197,7 @@ describe('PresentationTimeline', function() { }); it('calculates time based on segment times when available', () => { - let timeline = makeLiveTimeline(/* availability */ 20); + const timeline = makeLiveTimeline(/* availability */ 20); const ref1 = makeSegmentReference(0, 10); const ref2 = makeSegmentReference(10, 20); @@ -237,7 +237,7 @@ describe('PresentationTimeline', function() { describe('getSegmentAvailabilityEnd', function() { it('returns duration for VOD', function() { - let timeline = makeVodTimeline(/* duration */ 60); + const timeline = makeVodTimeline(/* duration */ 60); setElapsed(0); expect(timeline.getSegmentAvailabilityEnd()).toBe(60); @@ -247,7 +247,7 @@ describe('PresentationTimeline', function() { }); it('calculates time for IPR', function() { - let timeline = makeIprTimeline(/* duration */ 60); + const timeline = makeIprTimeline(/* duration */ 60); setElapsed(0); expect(timeline.getSegmentAvailabilityEnd()).toBe(0); @@ -269,8 +269,8 @@ describe('PresentationTimeline', function() { }); it('calculates time for live', function() { - let timeline1 = makeLiveTimeline(/* availability */ 20); - let timeline2 = makeLiveTimeline(/* availability */ Infinity); + const timeline1 = makeLiveTimeline(/* availability */ 20); + const timeline2 = makeLiveTimeline(/* availability */ Infinity); setElapsed(0); expect(timeline1.getSegmentAvailabilityEnd()).toBe(0); @@ -298,7 +298,7 @@ describe('PresentationTimeline', function() { }); it('calculates time based on segment times when available', () => { - let timeline = makeLiveTimeline(/* availability */ 20); + const timeline = makeLiveTimeline(/* availability */ 20); const ref1 = makeSegmentReference(0, 10); const ref2 = makeSegmentReference(10, 20); @@ -321,10 +321,10 @@ describe('PresentationTimeline', function() { describe('getDuration', function() { it('returns the timeline duration', function() { setElapsed(0); - let timeline1 = makeVodTimeline(/* duration */ 60); - let timeline2 = makeIprTimeline(/* duration */ 60); - let timeline3 = makeLiveTimeline(/* availability */ 20); - let timeline4 = makeLiveTimeline(/* availability */ Infinity); + const timeline1 = makeVodTimeline(/* duration */ 60); + const timeline2 = makeIprTimeline(/* duration */ 60); + const timeline3 = makeLiveTimeline(/* availability */ 20); + const timeline4 = makeLiveTimeline(/* availability */ Infinity); expect(timeline1.getDuration()).toBe(60); expect(timeline2.getDuration()).toBe(60); expect(timeline3.getDuration()).toBe(Infinity); @@ -335,7 +335,7 @@ describe('PresentationTimeline', function() { describe('setDuration', function() { it('affects availability end for VOD', function() { setElapsed(0); - let timeline = makeVodTimeline(/* duration */ 60); + const timeline = makeVodTimeline(/* duration */ 60); expect(timeline.getSegmentAvailabilityEnd()).toBe(60); timeline.setDuration(90); @@ -343,7 +343,7 @@ describe('PresentationTimeline', function() { }); it('affects availability end for IPR', function() { - let timeline = makeIprTimeline(/* duration */ 60); + const timeline = makeIprTimeline(/* duration */ 60); setElapsed(85); expect(timeline.getSegmentAvailabilityEnd()).toBe(60); @@ -355,7 +355,7 @@ describe('PresentationTimeline', function() { describe('clockOffset', function() { it('offsets availability calculations', function() { - let timeline = makeLiveTimeline(/* availability */ 10); + const timeline = makeLiveTimeline(/* availability */ 10); setElapsed(11); expect(timeline.getSegmentAvailabilityEnd()).toBe(1); @@ -366,14 +366,14 @@ describe('PresentationTimeline', function() { describe('getSafeSeekRangeStart', function() { it('ignores offset for VOD', function() { - let timeline = makeVodTimeline(/* duration */ 60); + const timeline = makeVodTimeline(/* duration */ 60); expect(timeline.getSafeSeekRangeStart(0)).toBe(0); expect(timeline.getSafeSeekRangeStart(10)).toBe(0); expect(timeline.getSafeSeekRangeStart(25)).toBe(0); }); it('offsets from live edge', function() { - let timeline = makeLiveTimeline(/* availability */ 60, /* delay */ 0); + const timeline = makeLiveTimeline(/* availability */ 60, /* delay */ 0); setElapsed(120); // now (120) - availability (60) - segment size (10) = 50 @@ -384,7 +384,7 @@ describe('PresentationTimeline', function() { }); it('clamps to end', function() { - let timeline = makeLiveTimeline(/* availability */ 60, /* delay */ 0); + const timeline = makeLiveTimeline(/* availability */ 60, /* delay */ 0); setElapsed(120); expect(timeline.getSegmentAvailabilityEnd()).toBe(110); @@ -394,7 +394,7 @@ describe('PresentationTimeline', function() { }); it('will return 0 if safe', function() { - let timeline = makeLiveTimeline(/* availability */ 60, /* delay */ 0); + const timeline = makeLiveTimeline(/* availability */ 60, /* delay */ 0); setElapsed(50); // now (50) - availability (60) - segment size (10) = -20 @@ -405,7 +405,7 @@ describe('PresentationTimeline', function() { it('adjusts segment times to the presentation timeline', () => { // All of these segments fit in the availability window. - let timeline = makeLiveTimeline(/* availability */ 100); + const timeline = makeLiveTimeline(/* availability */ 100); // A reference from 30-40, + period start 0 timeline.notifySegments([makeSegmentReference(30, 40)], @@ -422,8 +422,8 @@ describe('PresentationTimeline', function() { describe('getSeekRangeEnd', function() { it('accounts for delay for live and IPR', function() { - let timeline1 = makeIprTimeline(/* duration */ 60, /* delay */ 7); - let timeline2 = makeLiveTimeline(/* duration */ 60, /* delay */ 7); + const timeline1 = makeIprTimeline(/* duration */ 60, /* delay */ 7); + const timeline2 = makeLiveTimeline(/* duration */ 60, /* delay */ 7); setElapsed(11); expect(timeline1.getSeekRangeEnd()).toBe(0); diff --git a/test/media/segment_index_unit.js b/test/media/segment_index_unit.js index a266f7fa98..bc2e092ce9 100644 --- a/test/media/segment_index_unit.js +++ b/test/media/segment_index_unit.js @@ -38,59 +38,59 @@ describe('SegmentIndex', /** @suppress {accessControls} */ function() { index = new shaka.media.SegmentIndex([actual1, actual2, actual3]); pos1 = index.find(5); pos2 = index.find(15); - let pos3 = index.find(25); + const pos3 = index.find(25); expect(pos1).toBe(actual1.position); expect(pos2).toBe(actual2.position); expect(pos3).toBe(actual3.position); }); it('works if time == first start time', function() { - let actual = makeReference(1, 10, 20, uri(10)); - let index = new shaka.media.SegmentIndex([actual]); + const actual = makeReference(1, 10, 20, uri(10)); + const index = new shaka.media.SegmentIndex([actual]); - let pos = index.find(10); + const pos = index.find(10); expect(pos).toBe(actual.position); }); it('works with two references if time == second start time', function() { - let actual1 = makeReference(1, 10, 20, uri(10)); - let actual2 = makeReference(2, 20, 30, uri(20)); - let index = new shaka.media.SegmentIndex([actual1, actual2]); + const actual1 = makeReference(1, 10, 20, uri(10)); + const actual2 = makeReference(2, 20, 30, uri(20)); + const index = new shaka.media.SegmentIndex([actual1, actual2]); - let pos = index.find(20); + const pos = index.find(20); expect(pos).toBe(actual2.position); }); it('returns the first segment if time < first start time', function() { - let actual = makeReference(1, 10, 20, uri(10)); - let index = new shaka.media.SegmentIndex([actual]); + const actual = makeReference(1, 10, 20, uri(10)); + const index = new shaka.media.SegmentIndex([actual]); - let pos = index.find(5); + const pos = index.find(5); expect(pos).toBe(actual.position); }); it('returns null if time == last end time', function() { - let actual = makeReference(1, 10, 20, uri(10)); - let index = new shaka.media.SegmentIndex([actual]); + const actual = makeReference(1, 10, 20, uri(10)); + const index = new shaka.media.SegmentIndex([actual]); - let pos = index.find(20); + const pos = index.find(20); expect(pos).toBeNull(); }); it('returns null if time > last end time', function() { - let actual = makeReference(1, 10, 20, uri(10)); - let index = new shaka.media.SegmentIndex([actual]); + const actual = makeReference(1, 10, 20, uri(10)); + const index = new shaka.media.SegmentIndex([actual]); - let pos = index.find(21); + const pos = index.find(21); expect(pos).toBeNull(); }); it('returns null if time is within a gap', function() { - let actual1 = makeReference(1, 10, 20, uri(10)); - let actual2 = makeReference(2, 25, 30, uri(25)); - let index = new shaka.media.SegmentIndex([actual1, actual2]); + const actual1 = makeReference(1, 10, 20, uri(10)); + const actual2 = makeReference(2, 25, 30, uri(25)); + const index = new shaka.media.SegmentIndex([actual1, actual2]); - let pos = index.find(23); + const pos = index.find(23); expect(pos).toBeNull(); }); }); @@ -132,20 +132,20 @@ describe('SegmentIndex', /** @suppress {accessControls} */ function() { }); it('returns null with zero references', function() { - let index = new shaka.media.SegmentIndex([]); + const index = new shaka.media.SegmentIndex([]); expect(index.get(0)).toBeNull(); }); it('returns null if position < 0', function() { - let index = new shaka.media.SegmentIndex([actual1, actual2, actual3]); + const index = new shaka.media.SegmentIndex([actual1, actual2, actual3]); expect(index.get(-1)).toBeNull(); }); it('returns null for unknown positions', function() { - let index1 = new shaka.media.SegmentIndex([actual1, actual2, actual3]); + const index1 = new shaka.media.SegmentIndex([actual1, actual2, actual3]); expect(index1.get(3)).toBeNull(); - let index2 = new shaka.media.SegmentIndex([actual2, actual3]); + const index2 = new shaka.media.SegmentIndex([actual2, actual3]); expect(index2.get(0)).toBeNull(); }); }); @@ -153,18 +153,18 @@ describe('SegmentIndex', /** @suppress {accessControls} */ function() { describe('fit', function() { it('drops references which are outside the period bounds', function() { // These negative numbers can occur due to presentationTimeOffset in DASH. - let references = [ + const references = [ makeReference(0, -10, -3, uri(0)), makeReference(1, -3, 4, uri(1)), makeReference(2, 4, 11, uri(2)), makeReference(3, 11, 18, uri(3)), makeReference(4, 18, 25, uri(4)), ]; - let index = new shaka.media.SegmentIndex(references); + const index = new shaka.media.SegmentIndex(references); expect(index.references_).toEqual(references); index.fit(/* periodDuration */ 15); - let newReferences = [ + const newReferences = [ /* ref 0 dropped because it ends before the period starts */ makeReference(1, -3, 4, uri(1)), makeReference(2, 4, 11, uri(2)), @@ -177,15 +177,15 @@ describe('SegmentIndex', /** @suppress {accessControls} */ function() { it('drops references which end exactly at zero', function() { // The end time is meant to be exclusive, so segments ending at zero // (after PTO adjustments) should be dropped. - let references = [ + const references = [ makeReference(0, -10, 0, uri(0)), makeReference(1, 0, 10, uri(1)), ]; - let index = new shaka.media.SegmentIndex(references); + const index = new shaka.media.SegmentIndex(references); expect(index.references_).toEqual(references); index.fit(/* periodDuration */ 10); - let newReferences = [ + const newReferences = [ /* ref 0 dropped because it ends before the period starts (at 0) */ makeReference(1, 0, 10, uri(1)), ]; @@ -195,9 +195,9 @@ describe('SegmentIndex', /** @suppress {accessControls} */ function() { describe('merge', function() { it('three references into zero references', function() { - let index1 = new shaka.media.SegmentIndex([]); + const index1 = new shaka.media.SegmentIndex([]); - let references2 = [actual1, actual2, actual3]; + const references2 = [actual1, actual2, actual3]; index1.merge(references2); expect(index1.references_.length).toBe(3); @@ -205,8 +205,8 @@ describe('SegmentIndex', /** @suppress {accessControls} */ function() { }); it('zero references into three references', function() { - let references1 = [actual1, actual2, actual3]; - let index1 = new shaka.media.SegmentIndex(references1); + const references1 = [actual1, actual2, actual3]; + const index1 = new shaka.media.SegmentIndex(references1); index1.merge([]); expect(index1.references_.length).toBe(3); @@ -214,10 +214,10 @@ describe('SegmentIndex', /** @suppress {accessControls} */ function() { }); it('one reference into one reference at end', function() { - let references1 = [makeReference(1, 10, 20, uri(10))]; - let index1 = new shaka.media.SegmentIndex(references1); + const references1 = [makeReference(1, 10, 20, uri(10))]; + const index1 = new shaka.media.SegmentIndex(references1); - let references2 = [makeReference(2, 20, 30, uri(20))]; + const references2 = [makeReference(2, 20, 30, uri(20))]; index1.merge(references2); expect(index1.references_.length).toBe(2); @@ -226,13 +226,13 @@ describe('SegmentIndex', /** @suppress {accessControls} */ function() { }); it('one reference into two references at end', function() { - let references1 = [ + const references1 = [ makeReference(1, 10, 20, uri(10)), makeReference(2, 20, 30, uri(20)), ]; - let index1 = new shaka.media.SegmentIndex(references1); + const index1 = new shaka.media.SegmentIndex(references1); - let references2 = [makeReference(3, 30, 40, uri(30))]; + const references2 = [makeReference(3, 30, 40, uri(30))]; index1.merge(references2); expect(index1.references_.length).toBe(3); @@ -242,10 +242,10 @@ describe('SegmentIndex', /** @suppress {accessControls} */ function() { }); it('two references into one reference at end', function() { - let references1 = [makeReference(2, 20, 30, uri(20))]; - let index1 = new shaka.media.SegmentIndex(references1); + const references1 = [makeReference(2, 20, 30, uri(20))]; + const index1 = new shaka.media.SegmentIndex(references1); - let references2 = [ + const references2 = [ makeReference(3, 30, 40, uri(30)), makeReference(4, 40, 50, uri(40)), ]; @@ -258,17 +258,17 @@ describe('SegmentIndex', /** @suppress {accessControls} */ function() { }); it('last live stream reference when period change', function() { - let references1 = [ + const references1 = [ makeReference(1, 10, 20, uri(10)), makeReference(2, 20, 30, uri(20)), makeReference(3, 30, 49.887, uri(30)), ]; - let index1 = new shaka.media.SegmentIndex(references1); + const index1 = new shaka.media.SegmentIndex(references1); // When the period is changed, fit() will expand last segment to the start // of the next the period. This simulates an update in which fit() has // done that. - let references2 = [ + const references2 = [ makeReference(2, 20, 30, uri(20)), makeReference(3, 30, 50, uri(30)), ]; @@ -284,20 +284,20 @@ describe('SegmentIndex', /** @suppress {accessControls} */ function() { // position numbers. // https://github.com/google/shaka-player/pull/838 it('last live stream reference with corrected position', function() { - let references1 = [ + const references1 = [ makeReference(1, 10, 20, uri(10)), makeReference(2, 20, 30, uri(20)), makeReference(3, 30, 49.887, uri(30)), ]; - let index1 = new shaka.media.SegmentIndex(references1); + const index1 = new shaka.media.SegmentIndex(references1); // segment position always start from 1 for time-based segment templates - let references2 = [ + const references2 = [ makeReference(1, 20, 30, uri(20)), makeReference(2, 30, 50, uri(30)), ]; - let lastReference = makeReference(3, 30, 50, uri(30)); + const lastReference = makeReference(3, 30, 50, uri(30)); index1.merge(references2); expect(index1.references_.length).toBe(3); diff --git a/test/media/segment_reference_unit.js b/test/media/segment_reference_unit.js index 0fbb2896a4..ebf841b261 100644 --- a/test/media/segment_reference_unit.js +++ b/test/media/segment_reference_unit.js @@ -17,7 +17,7 @@ describe('SegmentReference', function() { it('returns in getters values from constructor parameters', function() { - let reference = new shaka.media.SegmentReference(1, 2, 3, + const reference = new shaka.media.SegmentReference(1, 2, 3, function() { return ['x', 'y']; }, 4, 5); expect(reference.getPosition()).toBe(1); @@ -31,7 +31,7 @@ describe('SegmentReference', function() { describe('InitSegmentReference', function() { it('returns in getters values from constructor parameters', function() { - let reference = new shaka.media.InitSegmentReference( + const reference = new shaka.media.InitSegmentReference( function() { return ['x', 'y']; }, 4, 5); expect(reference.createUris()).toEqual(['x', 'y']); diff --git a/test/media/streaming_engine_integration.js b/test/media/streaming_engine_integration.js index c868aa2a8f..14de3b165a 100644 --- a/test/media/streaming_engine_integration.js +++ b/test/media/streaming_engine_integration.js @@ -168,7 +168,7 @@ describe('StreamingEngine', () => { } function createVodStreamGenerator(metadata, type) { - let generator = new shaka.test.Mp4VodStreamGenerator( + const generator = new shaka.test.Mp4VodStreamGenerator( metadata.initSegmentUri, metadata.mdhdOffset, metadata.segmentUri, @@ -182,8 +182,8 @@ describe('StreamingEngine', () => { function createLiveStreamGenerator(metadata, type, timeShiftBufferDepth) { // Set the generator's AST to 295 seconds in the past so the // StreamingEngine begins streaming close to the end of the first Period. - let now = Date.now() / 1000; - let generator = new shaka.test.Mp4LiveStreamGenerator( + const now = Date.now() / 1000; + const generator = new shaka.test.Mp4LiveStreamGenerator( metadata.initSegmentUri, metadata.mdhdOffset, metadata.segmentUri, @@ -199,13 +199,13 @@ describe('StreamingEngine', () => { function setupNetworkingEngine(firstPeriodStartTime, secondPeriodStartTime, presentationDuration, segmentDurations) { - let periodStartTimes = [firstPeriodStartTime, secondPeriodStartTime]; + const periodStartTimes = [firstPeriodStartTime, secondPeriodStartTime]; - let boundsCheckPosition = + const boundsCheckPosition = shaka.test.StreamingEngineUtil.boundsCheckPosition.bind( null, periodStartTimes, presentationDuration, segmentDurations); - let getNumSegments = + const getNumSegments = shaka.test.StreamingEngineUtil.getNumSegments.bind( null, periodStartTimes, presentationDuration, segmentDurations); @@ -215,8 +215,8 @@ describe('StreamingEngine', () => { // Init segment generator: function(type, periodNumber) { expect(periodNumber).toBeLessThan(periodStartTimes.length + 1); - let wallClockTime = Date.now() / 1000; - let segment = generators[type].getInitSegment(wallClockTime); + const wallClockTime = Date.now() / 1000; + const segment = generators[type].getInitSegment(wallClockTime); expect(segment).not.toBeNull(); return segment; }, @@ -232,9 +232,9 @@ describe('StreamingEngine', () => { numPriorSegments += getNumSegments(type, n); } - let wallClockTime = Date.now() / 1000; + const wallClockTime = Date.now() / 1000; - let segment = generators[type].getSegment( + const segment = generators[type].getSegment( position, numPriorSegments, wallClockTime); expect(segment).not.toBeNull(); return segment; @@ -243,7 +243,7 @@ describe('StreamingEngine', () => { function setupPlayhead() { onBuffering = jasmine.createSpy('onBuffering'); - let onSeek = () => { streamingEngine.seeked(); }; + const onSeek = () => { streamingEngine.seeked(); }; playhead = new shaka.media.MediaSourcePlayhead( /** @type {!HTMLVideoElement} */(video), manifest, @@ -280,7 +280,7 @@ describe('StreamingEngine', () => { } function createStreamingEngine() { - let playerInterface = { + const playerInterface = { getPresentationTime: () => playhead.getTime(), mediaSourceEngine: mediaSourceEngine, netEngine: /** @type {!shaka.net.NetworkingEngine} */(netEngine), @@ -599,8 +599,8 @@ describe('StreamingEngine', () => { * @return {!shaka.media.SegmentIndex} */ function createIndex(type) { - let d = metadata[type].segmentDuration; - let refs = []; + const d = metadata[type].segmentDuration; + const refs = []; let i = 1; let time = gapAtStart; while (time < 30) { @@ -611,7 +611,7 @@ describe('StreamingEngine', () => { end += d; } - let getUris = (function(i) { + const getUris = (function(i) { // The times in the media are based on the URL; so to drop a // segment, we change the URL. if (i >= 2 && dropSegment) i++; @@ -627,14 +627,14 @@ describe('StreamingEngine', () => { } function createInit(type) { - let getUris = () => { + const getUris = () => { return ['1_' + type + '_init']; }; return new shaka.media.InitSegmentReference(getUris, 0, null); } - let videoIndex = createIndex('video'); - let audioIndex = createIndex('audio'); + const videoIndex = createIndex('video'); + const audioIndex = createIndex('audio'); return { presentationTimeline: timeline, offlineSessionIds: [], diff --git a/test/media/streaming_engine_unit.js b/test/media/streaming_engine_unit.js index fbfcfedda0..bfcf4dda4a 100644 --- a/test/media/streaming_engine_unit.js +++ b/test/media/streaming_engine_unit.js @@ -27,12 +27,12 @@ describe('StreamingEngine', function() { * @type {!Object.<shaka.util.ManifestParserUtils.ContentType, * !Array.<number>>} */ - let initSegmentRanges = {}; + const initSegmentRanges = {}; initSegmentRanges[ContentType.AUDIO] = [100, 1000]; initSegmentRanges[ContentType.VIDEO] = [200, 2000]; /** @type {!Object.<shaka.util.ManifestParserUtils.ContentType, number>} */ - let segmentSizes = {}; + const segmentSizes = {}; segmentSizes[ContentType.AUDIO] = 1000; segmentSizes[ContentType.VIDEO] = 10000; segmentSizes[ContentType.TEXT] = 500; @@ -118,9 +118,9 @@ describe('StreamingEngine', function() { // All media segments are (by default) 10 seconds long. // Create SegmentData map for FakeMediaSourceEngine. - let initSegmentSizeAudio = initSegmentRanges[ContentType.AUDIO][1] - + const initSegmentSizeAudio = initSegmentRanges[ContentType.AUDIO][1] - initSegmentRanges[ContentType.AUDIO][0] + 1; - let initSegmentSizeVideo = initSegmentRanges[ContentType.VIDEO][1] - + const initSegmentSizeVideo = initSegmentRanges[ContentType.VIDEO][1] - initSegmentRanges[ContentType.VIDEO][0] + 1; function makeBuffer(size) { return new ArrayBuffer(size); } @@ -219,9 +219,9 @@ describe('StreamingEngine', function() { // to t=120 (segment 13). // Create SegmentData map for FakeMediaSourceEngine. - let initSegmentSizeAudio = initSegmentRanges[ContentType.AUDIO][1] - + const initSegmentSizeAudio = initSegmentRanges[ContentType.AUDIO][1] - initSegmentRanges[ContentType.AUDIO][0] + 1; - let initSegmentSizeVideo = initSegmentRanges[ContentType.VIDEO][1] - + const initSegmentSizeVideo = initSegmentRanges[ContentType.VIDEO][1] - initSegmentRanges[ContentType.VIDEO][0] + 1; function makeBuffer(size) { return new ArrayBuffer(size); } @@ -253,7 +253,7 @@ describe('StreamingEngine', function() { }, }; - let segmentsInFirstPeriod = 12; + const segmentsInFirstPeriod = 12; for (let i = 0; i < segmentsInFirstPeriod; ++i) { segmentData[ContentType.AUDIO].segments.push( makeBuffer(segmentSizes[ContentType.AUDIO])); @@ -271,7 +271,7 @@ describe('StreamingEngine', function() { segmentData[ContentType.TEXT].segmentPeriodTimes.push(0); } - let segmentsInSecondPeriod = 2; + const segmentsInSecondPeriod = 2; for (let i = 0; i < segmentsInSecondPeriod; ++i) { segmentData[ContentType.AUDIO].segments.push( makeBuffer(segmentSizes[ContentType.AUDIO])); @@ -327,14 +327,15 @@ describe('StreamingEngine', function() { expect(position).toBeGreaterThan(0); expect((periodNumber == 1 && position <= segmentsInFirstPeriod) || (periodNumber == 2 && position <= segmentsInSecondPeriod)); - let i = (segmentsInFirstPeriod * (periodNumber - 1)) + (position - 1); + const i = + (segmentsInFirstPeriod * (periodNumber - 1)) + (position - 1); return segmentData[type].segments[i]; }); } function setupManifest( firstPeriodStartTime, secondPeriodStartTime, presentationDuration) { - let segmentDurations = { + const segmentDurations = { audio: segmentData[ContentType.AUDIO].segmentDuration, video: segmentData[ContentType.VIDEO].segmentDuration, text: segmentData[ContentType.TEXT].segmentDuration, @@ -399,7 +400,7 @@ describe('StreamingEngine', function() { alternateVideoStream1.createSegmentIndex.and.returnValue(Promise.resolve()); alternateVideoStream1.findSegmentPosition.and.returnValue(null); alternateVideoStream1.getSegmentReference.and.returnValue(null); - let variant = { + const variant = { audio: null, video: /** @type {shaka.extern.Stream} */ (alternateVideoStream1), id: 0, @@ -442,7 +443,7 @@ describe('StreamingEngine', function() { config.bufferBehind = Infinity; } - let playerInterface = { + const playerInterface = { getPresentationTime: () => presentationTimeInSeconds, mediaSourceEngine: mediaSourceEngine, netEngine: /** @type {!shaka.net.NetworkingEngine} */(netEngine), @@ -794,7 +795,7 @@ describe('StreamingEngine', function() { }); it('plays when a small gap is present at the beginning', function() { - let drift = 0.050; // 50 ms + const drift = 0.050; // 50 ms setupVod(); mediaSourceEngine = @@ -818,7 +819,7 @@ describe('StreamingEngine', function() { onStartupComplete.and.callFake(setupFakeGetTime.bind(null, 0)); onChooseStreams.and.callFake(function(period) { - let chosen = defaultOnChooseStreams(period); + const chosen = defaultOnChooseStreams(period); if (period == manifest.periods[0]) { chosen.text = null; } @@ -844,7 +845,7 @@ describe('StreamingEngine', function() { // For the first update, indicate the segment isn't available. This should // not cause us to fallback to the Playhead time to determine which segment // to start streaming. - let oldGet = textStream2.getSegmentReference; + const oldGet = textStream2.getSegmentReference; textStream2.getSegmentReference = function(idx) { if (idx == 1) { textStream2.getSegmentReference = oldGet; @@ -858,7 +859,7 @@ describe('StreamingEngine', function() { onStartupComplete.and.callFake(setupFakeGetTime.bind(null, 0)); onChooseStreams.and.callFake(function(period) { - let chosen = defaultOnChooseStreams(period); + const chosen = defaultOnChooseStreams(period); if (period == manifest.periods[0]) { chosen.text = null; } @@ -911,7 +912,7 @@ describe('StreamingEngine', function() { onStartupComplete.and.callFake(setupFakeGetTime.bind(null, 0)); onChooseStreams.and.callFake(function(period) { - let chosen = defaultOnChooseStreams(period); + const chosen = defaultOnChooseStreams(period); if (period == manifest.periods[1]) { chosen.text = null; } @@ -994,7 +995,7 @@ describe('StreamingEngine', function() { // The second Period starts at 20, so we should set the appendWindowStart to // 20, but reduced by a small fudge factor. - let lt20 = { + const lt20 = { asymmetricMatch: function(val) { return val >= 19.9 && val < 20; }, @@ -1081,8 +1082,8 @@ describe('StreamingEngine', function() { // Just return any old ArrayBuffer for any requested segment. netEngine = { request: function(requestType, request) { - let buffer = new ArrayBuffer(0); - let response = {uri: request.uris[0], data: buffer, headers: {}}; + const buffer = new ArrayBuffer(0); + const response = {uri: request.uris[0], data: buffer, headers: {}}; return shaka.util.AbortableOperation.completed(response); }, }; @@ -1096,7 +1097,7 @@ describe('StreamingEngine', function() { mediaSourceEngine.setStreamProperties.and.returnValue(Promise.resolve()); mediaSourceEngine.remove.and.returnValue(Promise.resolve()); - let bufferEnd = {audio: 0, video: 0, text: 0}; + const bufferEnd = {audio: 0, video: 0, text: 0}; mediaSourceEngine.appendBuffer.and.callFake( function(type, data, start, end) { bufferEnd[type] = end; @@ -1764,7 +1765,7 @@ describe('StreamingEngine', function() { // Eventually StreamingEngine should request the first segment (since // it needs the second segment) of the second Period when it becomes // available. - let originalAppendBuffer = + const originalAppendBuffer = shaka.test.FakeMediaSourceEngine.prototype.appendBufferImpl; mediaSourceEngine.appendBuffer.and.callFake( function(type, data, startTime, endTime) { @@ -1772,7 +1773,7 @@ describe('StreamingEngine', function() { expect(timeline.getSegmentAvailabilityStart()).toBe(100); expect(timeline.getSegmentAvailabilityEnd()).toBe(120); playing = true; - let p = originalAppendBuffer.call( + const p = originalAppendBuffer.call( mediaSourceEngine, type, data, startTime, endTime); mediaSourceEngine.appendBuffer.and.callFake(originalAppendBuffer); return p; @@ -1817,7 +1818,7 @@ describe('StreamingEngine', function() { videoStream1.createSegmentIndex.and.returnValue( Promise.reject('FAKE_ERROR')); - let onInitError = jasmine.createSpy('onInitError'); + const onInitError = jasmine.createSpy('onInitError'); onInitError.and.callFake(function(error) { expect(onInitialStreamsSetup).not.toHaveBeenCalled(); expect(onStartupComplete).not.toHaveBeenCalled(); @@ -1851,7 +1852,7 @@ describe('StreamingEngine', function() { }); it('from failed init segment append during startup', function() { - let expectedError = new shaka.util.Error( + const expectedError = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.MEDIA, shaka.util.Error.Code.MEDIA_SOURCE_OPERATION_FAILED); @@ -1865,9 +1866,9 @@ describe('StreamingEngine', function() { onChooseStreams.and.callFake(function(period) { expect(period).toBe(manifest.periods[0]); - let streamsByType = defaultOnChooseStreams(period); + const streamsByType = defaultOnChooseStreams(period); - let originalAppendBuffer = + const originalAppendBuffer = shaka.test.FakeMediaSourceEngine.prototype.appendBufferImpl; mediaSourceEngine.appendBuffer.and.callFake( function(type, data, startTime, endTime) { @@ -1890,7 +1891,7 @@ describe('StreamingEngine', function() { }); it('from failed media segment append during startup', function() { - let expectedError = new shaka.util.Error( + const expectedError = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.MEDIA, shaka.util.Error.Code.MEDIA_SOURCE_OPERATION_FAILED); @@ -1904,9 +1905,9 @@ describe('StreamingEngine', function() { onChooseStreams.and.callFake(function(period) { expect(period).toBe(manifest.periods[0]); - let streamsByType = defaultOnChooseStreams(period); + const streamsByType = defaultOnChooseStreams(period); - let originalAppendBuffer = + const originalAppendBuffer = shaka.test.FakeMediaSourceEngine.prototype.appendBufferImpl; mediaSourceEngine.appendBuffer.and.callFake( function(type, data, startTime, endTime) { @@ -1932,8 +1933,8 @@ describe('StreamingEngine', function() { describe('handles network errors', function() { it('ignores text stream failures if configured to', function() { setupVod(); - let textUri = '1_text_1'; - let originalNetEngine = netEngine; + const textUri = '1_text_1'; + const originalNetEngine = netEngine; netEngine = { request: jasmine.createSpy('request'), }; @@ -1968,7 +1969,7 @@ describe('StreamingEngine', function() { setupLive(); // Wrap the NetworkingEngine to cause errors. - let targetUri = '1_audio_init'; + const targetUri = '1_audio_init'; failFirstRequestForTarget(netEngine, targetUri, shaka.util.Error.Code.BAD_HTTP_STATUS); @@ -2003,7 +2004,7 @@ describe('StreamingEngine', function() { setupLive(); // Wrap the NetworkingEngine to cause errors. - let targetUri = '1_audio_init'; + const targetUri = '1_audio_init'; failFirstRequestForTarget(netEngine, targetUri, shaka.util.Error.Code.BAD_HTTP_STATUS); @@ -2038,7 +2039,7 @@ describe('StreamingEngine', function() { setupLive(); // Wrap the NetworkingEngine to cause errors. - let targetUri = '1_audio_init'; + const targetUri = '1_audio_init'; failFirstRequestForTarget(netEngine, targetUri, shaka.util.Error.Code.BAD_HTTP_STATUS); @@ -2072,7 +2073,7 @@ describe('StreamingEngine', function() { setupLive(); // Wrap the NetworkingEngine to cause errors. - let targetUri = '1_audio_init'; + const targetUri = '1_audio_init'; failFirstRequestForTarget(netEngine, targetUri, shaka.util.Error.Code.BAD_HTTP_STATUS); @@ -2080,7 +2081,7 @@ describe('StreamingEngine', function() { // Configure with a failure callback that records the callback time. let callbackTime = null; - let failureCallback = jasmine.createSpy('failureCallback'); + const failureCallback = jasmine.createSpy('failureCallback'); failureCallback.and.callFake(function() { callbackTime = Date.now(); }); const config = shaka.util.PlayerConfiguration.createDefault().streaming; @@ -2100,7 +2101,7 @@ describe('StreamingEngine', function() { onChooseStreams.and.callFake(defaultOnChooseStreams.bind(null)); streamingEngine.start(); - let startTime = Date.now(); + const startTime = Date.now(); runTest(); expect(failureCallback).toHaveBeenCalled(); expect(callbackTime - startTime).toEqual(10000); // baseDelay == 10000 @@ -2112,8 +2113,8 @@ describe('StreamingEngine', function() { setupVod(); // Wrap the NetworkingEngine to cause errors. - let targetUri = '1_audio_init'; - let originalNetEngineRequest = netEngine.request; + const targetUri = '1_audio_init'; + const originalNetEngineRequest = netEngine.request; failFirstRequestForTarget(netEngine, targetUri, shaka.util.Error.Code.BAD_HTTP_STATUS); @@ -2150,7 +2151,7 @@ describe('StreamingEngine', function() { it('does not resume streaming after quota error', function() { setupVod(); - let appendBufferSpy = jasmine.createSpy('appendBuffer'); + const appendBufferSpy = jasmine.createSpy('appendBuffer'); // Throw QuotaExceededError on every segment to quickly trigger the quota // error. appendBufferSpy.and.callFake(function(type, data, startTime, endTime) { @@ -2245,7 +2246,7 @@ describe('StreamingEngine', function() { onStartupComplete.and.callFake(setupFakeGetTime.bind(null, 0)); - let originalRemove = + const originalRemove = shaka.test.FakeMediaSourceEngine.prototype.removeImpl .bind(mediaSourceEngine); @@ -2352,16 +2353,16 @@ describe('StreamingEngine', function() { onStartupComplete.and.callFake(setupFakeGetTime.bind(null, 0)); - let originalAppendBuffer = + const originalAppendBuffer = shaka.test.FakeMediaSourceEngine.prototype.appendBufferImpl; - let appendBufferSpy = jasmine.createSpy('appendBuffer'); + const appendBufferSpy = jasmine.createSpy('appendBuffer'); mediaSourceEngine.appendBuffer = appendBufferSpy; // Throw two QuotaExceededErrors at different times. let numErrorsThrown = 0; appendBufferSpy.and.callFake( function(type, data, startTime, endTime) { - let throwError = (numErrorsThrown == 0 && startTime == 10) || + const throwError = (numErrorsThrown == 0 && startTime == 10) || (numErrorsThrown == 1 && startTime == 20); if (throwError) { numErrorsThrown++; @@ -2371,7 +2372,7 @@ describe('StreamingEngine', function() { shaka.util.Error.Code.QUOTA_EXCEEDED_ERROR, type); } else { - let p = originalAppendBuffer.call( + const p = originalAppendBuffer.call( mediaSourceEngine, type, data, startTime, endTime); return p; } @@ -2412,9 +2413,9 @@ describe('StreamingEngine', function() { onStartupComplete.and.callFake(setupFakeGetTime.bind(null, 0)); - let originalAppendBuffer = + const originalAppendBuffer = shaka.test.FakeMediaSourceEngine.prototype.appendBufferImpl; - let appendBufferSpy = jasmine.createSpy('appendBuffer'); + const appendBufferSpy = jasmine.createSpy('appendBuffer'); mediaSourceEngine.appendBuffer = appendBufferSpy; // Throw QuotaExceededError multiple times after at least one segment of @@ -2428,7 +2429,7 @@ describe('StreamingEngine', function() { shaka.util.Error.Code.QUOTA_EXCEEDED_ERROR, type); } else { - let p = originalAppendBuffer.call( + const p = originalAppendBuffer.call( mediaSourceEngine, type, data, startTime, endTime); return p; } @@ -2447,7 +2448,7 @@ describe('StreamingEngine', function() { // Stop the playhead after 10 seconds since will not append any // segments after this time. - let stopPlayhead = () => { playing = presentationTimeInSeconds < 10; }; + const stopPlayhead = () => { playing = presentationTimeInSeconds < 10; }; runTest(stopPlayhead); expect(onError).toHaveBeenCalled(); @@ -2707,7 +2708,7 @@ describe('StreamingEngine', function() { expect(onEvent).toHaveBeenCalledTimes(1); - let event = onEvent.calls.argsFor(0)[0]; + const event = onEvent.calls.argsFor(0)[0]; expect(event.detail).toEqual(emsgObj); }); @@ -3084,14 +3085,14 @@ describe('StreamingEngine', function() { * @param {shaka.util.Error.Code} errorCode */ function failFirstRequestForTarget(netEngine, targetUri, errorCode) { - let originalNetEngineRequest = netEngine.request.bind(netEngine); + const originalNetEngineRequest = netEngine.request.bind(netEngine); netEngine.attempts = 0; netEngine.request = jasmine.createSpy('request').and.callFake( function(requestType, request) { if (request.uris[0] == targetUri) { if (++netEngine.attempts == 1) { - let data = [targetUri]; + const data = [targetUri]; if (errorCode == shaka.util.Error.Code.BAD_HTTP_STATUS) { data.push(404); diff --git a/test/media/time_ranges_utils_unit.js b/test/media/time_ranges_utils_unit.js index c906bf791f..76c1f736ea 100644 --- a/test/media/time_ranges_utils_unit.js +++ b/test/media/time_ranges_utils_unit.js @@ -24,17 +24,17 @@ describe('TimeRangesUtils', function() { }); it('still works with nothing buffered', function() { - let b = createFakeBuffered([]); + const b = createFakeBuffered([]); expect(TimeRangesUtils.isBuffered(b, 10)).toBe(false); }); it('returns buffered when inside a single range', function() { - let b = createFakeBuffered([{start: 10, end: 20}]); + const b = createFakeBuffered([{start: 10, end: 20}]); expect(TimeRangesUtils.isBuffered(b, 13)).toBe(true); }); it('returns buffered when having a small gap', function() { - let b = createFakeBuffered([{start: 10, end: 20}]); + const b = createFakeBuffered([{start: 10, end: 20}]); expect(TimeRangesUtils.isBuffered(b, 9, 1)).toBe(true); }); @@ -53,7 +53,7 @@ describe('TimeRangesUtils', function() { */ function defineTest(name, data) { it(name, function() { - let b = createFakeBuffered( + const b = createFakeBuffered( [{start: 10, end: 20}, {start: 30, end: 40}, {start: 50, end: 60}]); expect(TimeRangesUtils.isBuffered(b, data.time)).toBe(data.expected); }); @@ -66,7 +66,7 @@ describe('TimeRangesUtils', function() { }); it('still works when nothing is buffered', function() { - let b = createFakeBuffered([]); + const b = createFakeBuffered([]); expect(TimeRangesUtils.bufferedAheadOf(b, 10)).toBe(0); }); @@ -89,7 +89,7 @@ describe('TimeRangesUtils', function() { */ function defineTest(name, data) { it(name, function() { - let b = createFakeBuffered( + const b = createFakeBuffered( [{start: 10, end: 20}, {start: 30, end: 40}, {start: 50, end: 60}]); expect(TimeRangesUtils.bufferedAheadOf( b, data.time)).toBe(data.expected); @@ -103,7 +103,7 @@ describe('TimeRangesUtils', function() { }); it('still works whith nothing buffered', function() { - let b = createFakeBuffered([]); + const b = createFakeBuffered([]); expect(TimeRangesUtils.getGapIndex(b, 10)).toBe(null); }); @@ -129,7 +129,7 @@ describe('TimeRangesUtils', function() { */ function defineTest(name, data) { it(name, function() { - let b = createFakeBuffered( + const b = createFakeBuffered( [{start: 10, end: 20}, {start: 30, end: 40}, {start: 50, end: 60}]); expect(TimeRangesUtils.getGapIndex(b, data.time)).toBe(data.expected); }); diff --git a/test/media/transmuxer_integration.js b/test/media/transmuxer_integration.js index 20dfb8227d..c852c3c4c1 100644 --- a/test/media/transmuxer_integration.js +++ b/test/media/transmuxer_integration.js @@ -35,7 +35,7 @@ describe('Transmuxer', function() { beforeAll(async () => { - let responses = await Promise.all([ + const responses = await Promise.all([ shaka.test.Util.fetch(videoSegmentUri), shaka.test.Util.fetch(audioSegmentUri), ]); @@ -53,7 +53,7 @@ describe('Transmuxer', function() { }); describe('isSupported', function() { - let isSupported = shaka.media.Transmuxer.isSupported; + const isSupported = shaka.media.Transmuxer.isSupported; it('returns whether the content type is supported', function() { expect(isSupported(mp4MimeType, ContentType.VIDEO)).toBeFalsy(); expect(isSupported(transportStreamVideoMimeType, ContentType.VIDEO)) @@ -62,15 +62,15 @@ describe('Transmuxer', function() { }); describe('convertTsCodecs', function() { - let convertTsCodecs = shaka.media.Transmuxer.convertTsCodecs; + const convertTsCodecs = shaka.media.Transmuxer.convertTsCodecs; it('returns converted codecs', function() { - let convertedVideoCodecs = + const convertedVideoCodecs = convertTsCodecs(ContentType.VIDEO, transportStreamVideoMimeType); - let convertedAudioCodecs = + const convertedAudioCodecs = convertTsCodecs(ContentType.AUDIO, transportStreamAudioMimeType); - let expectedVideoCodecs = 'video/mp4; codecs="avc1.42E01E"'; - let expectedAudioCodecs = 'audio/mp4; codecs="mp4a.40.2"'; + const expectedVideoCodecs = 'video/mp4; codecs="avc1.42E01E"'; + const expectedAudioCodecs = 'audio/mp4; codecs="mp4a.40.2"'; expect(convertedVideoCodecs).toEqual(expectedVideoCodecs); expect(convertedAudioCodecs).toEqual(expectedAudioCodecs); }); @@ -92,7 +92,7 @@ describe('Transmuxer', function() { it('transmux video from TS to MP4', async () => { let sawMDAT = false; - let transmuxedData = await transmuxer.transmux(videoSegment); + const transmuxedData = await transmuxer.transmux(videoSegment); expect(transmuxedData.data).toEqual(jasmine.any(Uint8Array)); expect(transmuxedData.data.length).toBeGreaterThan(0); expect(transmuxedData.captions).toEqual(jasmine.any(Array)); @@ -107,7 +107,7 @@ describe('Transmuxer', function() { it('transmux audio from TS to MP4', async () => { let sawMDAT = false; - let transmuxedData = await transmuxer.transmux(audioSegment); + const transmuxedData = await transmuxer.transmux(audioSegment); expect(transmuxedData.data).toEqual(jasmine.any(Uint8Array)); expect(transmuxedData.data.length).toBeGreaterThan(0); expect(transmuxedData.captions).toEqual(jasmine.any(Array)); @@ -122,7 +122,7 @@ describe('Transmuxer', function() { it('transmux empty video from TS to MP4', async () => { let sawMDAT = false; - let transmuxedData = await transmuxer.transmux(emptySegment); + const transmuxedData = await transmuxer.transmux(emptySegment); expect(transmuxedData.data).toEqual(jasmine.any(Uint8Array)); expect(transmuxedData.data.length).toBeGreaterThan(0); expect(transmuxedData.captions).toEqual(jasmine.any(Array)); @@ -136,11 +136,11 @@ describe('Transmuxer', function() { it('passes through true timestamps', async () => { let parsed = false; - let expectedMp4Timestamp = 5166000; // in timescale units + const expectedMp4Timestamp = 5166000; // in timescale units let mp4Timestamp; - let transmuxedData = await transmuxer.transmux(videoSegment); - let Mp4Parser = shaka.util.Mp4Parser; + const transmuxedData = await transmuxer.transmux(videoSegment); + const Mp4Parser = shaka.util.Mp4Parser; new Mp4Parser() .box('moof', Mp4Parser.children) diff --git a/test/media/webm_segment_index_parser_unit.js b/test/media/webm_segment_index_parser_unit.js index 0fbf8988b2..9c13f76012 100644 --- a/test/media/webm_segment_index_parser_unit.js +++ b/test/media/webm_segment_index_parser_unit.js @@ -21,10 +21,10 @@ describe('WebmSegmentIndexParser', function() { let indexSegment; let initSegment; - let parser = new shaka.media.WebmSegmentIndexParser(); + const parser = new shaka.media.WebmSegmentIndexParser(); beforeAll(async () => { - let responses = await Promise.all([ + const responses = await Promise.all([ shaka.test.Util.fetch(indexSegmentUri), shaka.test.Util.fetch(initSegmentUri), ]); @@ -33,7 +33,7 @@ describe('WebmSegmentIndexParser', function() { }); it('rejects a non-index segment ', function() { - let error = new shaka.util.Error( + const error = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.MEDIA, shaka.util.Error.Code.WEBM_CUES_ELEMENT_MISSING); @@ -46,7 +46,7 @@ describe('WebmSegmentIndexParser', function() { }); it('rejects an invalid init segment ', function() { - let error = new shaka.util.Error( + const error = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.MEDIA, shaka.util.Error.Code.WEBM_EBML_HEADER_ELEMENT_MISSING); @@ -59,8 +59,8 @@ describe('WebmSegmentIndexParser', function() { }); it('parses index segment ', function() { - let result = parser.parse(indexSegment, initSegment, [], 0); - let references = + const result = parser.parse(indexSegment, initSegment, [], 0); + const references = [ {startTime: 0, endTime: 12, startByte: 281, endByte: 95911}, {startTime: 12, endTime: 24, startByte: 95912, endByte: 209663}, @@ -81,8 +81,8 @@ describe('WebmSegmentIndexParser', function() { }); it('takes a scaled presentationTimeOffset in seconds', function() { - let result = parser.parse(indexSegment, initSegment, [], 2); - let references = + const result = parser.parse(indexSegment, initSegment, [], 2); + const references = [ {startTime: -2, endTime: 10}, {startTime: 10, endTime: 22}, diff --git a/test/net/data_uri_plugin_unit.js b/test/net/data_uri_plugin_unit.js index b12a4b74a8..6c072e7083 100644 --- a/test/net/data_uri_plugin_unit.js +++ b/test/net/data_uri_plugin_unit.js @@ -65,7 +65,7 @@ describe('DataUriPlugin', function() { }); function testSucceeds(uri, contentType, text, done) { - let request = + const request = shaka.net.NetworkingEngine.makeRequest([uri], retryParameters); // eslint-disable-next-line new-cap shaka.net.DataUriPlugin(uri, request).promise @@ -74,7 +74,8 @@ describe('DataUriPlugin', function() { expect(response.uri).toBe(uri); expect(response.data).toBeTruthy(); expect(response.headers['content-type']).toBe(contentType); - let data = shaka.util.StringUtils.fromBytesAutoDetect(response.data); + const data = + shaka.util.StringUtils.fromBytesAutoDetect(response.data); expect(data).toBe(text); }) .catch(fail) @@ -82,7 +83,7 @@ describe('DataUriPlugin', function() { } function testFails(uri, done, code) { - let request = + const request = shaka.net.NetworkingEngine.makeRequest([uri], retryParameters); // eslint-disable-next-line new-cap shaka.net.DataUriPlugin(uri, request).promise diff --git a/test/net/http_plugin_unit.js b/test/net/http_plugin_unit.js index c406f9e353..b29d01bf74 100644 --- a/test/net/http_plugin_unit.js +++ b/test/net/http_plugin_unit.js @@ -39,7 +39,7 @@ function httpPluginTests(usingFetch) { // Install the mock only briefly in the global namespace, to get a handle // to the mocked fetch implementation. jasmine.Fetch.install(); - let MockFetch = window.fetch; + const MockFetch = window.fetch; const MockAbortController = window.AbortController; const MockReadableStream = window.ReadableStream; const MockHeaders = window.Headers; @@ -163,7 +163,7 @@ function httpPluginTests(usingFetch) { }); it('sets the correct fields', function(done) { - let request = shaka.net.NetworkingEngine.makeRequest( + const request = shaka.net.NetworkingEngine.makeRequest( ['https://foo.bar/'], retryParameters); request.allowCrossSiteCredentials = true; request.method = 'POST'; @@ -171,7 +171,7 @@ function httpPluginTests(usingFetch) { plugin(request.uris[0], request, requestType).promise .then(function() { - let actual = mostRecentRequest(); + const actual = mostRecentRequest(); expect(actual).toBeTruthy(); expect(actual.url).toBe(request.uris[0]); expect(actual.method).toBe(request.method); @@ -188,14 +188,14 @@ function httpPluginTests(usingFetch) { // Regression test for an issue with Edge, where Fetch fails if the body // is set to null but succeeds on undefined. it('sets a request\'s null body to undefined', function(done) { - let request = shaka.net.NetworkingEngine.makeRequest( + const request = shaka.net.NetworkingEngine.makeRequest( ['https://foo.bar/'], retryParameters); request.body = null; request.method = 'GET'; plugin(request.uris[0], request, requestType).promise .then(function() { - let actual = jasmine.Fetch.requests.mostRecent(); + const actual = jasmine.Fetch.requests.mostRecent(); expect(actual).toBeTruthy(); expect(actual.body).toBeUndefined(); }) @@ -265,7 +265,7 @@ function httpPluginTests(usingFetch) { }); it('detects cache headers', function(done) { - let request = shaka.net.NetworkingEngine.makeRequest( + const request = shaka.net.NetworkingEngine.makeRequest( ['https://foo.bar/cache'], retryParameters); plugin(request.uris[0], request, requestType).promise .catch(fail) @@ -280,14 +280,14 @@ function httpPluginTests(usingFetch) { it('aborts the request when the operation is aborted', function(done) { let abortPromise; let requestPromise; - let oldXHRMock = shaka.net.HttpXHRPlugin['Xhr_']; + const oldXHRMock = shaka.net.HttpXHRPlugin['Xhr_']; if (usingFetch) { - let request = shaka.net.NetworkingEngine.makeRequest( + const request = shaka.net.NetworkingEngine.makeRequest( ['https://foo.bar/timeout'], retryParameters); - let operation = plugin(request.uris[0], request, requestType); + const operation = plugin(request.uris[0], request, requestType); /** @type {jasmine.Fetch.RequestStub} */ - let actual = jasmine.Fetch.requests.mostRecent(); + const actual = jasmine.Fetch.requests.mostRecent(); requestPromise = operation.promise; @@ -304,7 +304,7 @@ function httpPluginTests(usingFetch) { // actually insert a call to abort in the middle. // Instead, install a very elementary mock. /** @constructor */ - let NewXHRMock = function() { + const NewXHRMock = function() { this.abort = shaka.test.Util.spyFunc(jasmine.createSpy('abort')); this.open = shaka.test.Util.spyFunc(jasmine.createSpy('open')); @@ -324,7 +324,7 @@ function httpPluginTests(usingFetch) { }; shaka.net.HttpXHRPlugin['Xhr_'] = NewXHRMock; - let request = shaka.net.NetworkingEngine.makeRequest( + const request = shaka.net.NetworkingEngine.makeRequest( ['https://foo.bar/'], retryParameters); operation = plugin(request.uris[0], request, requestType); requestPromise = operation.promise; @@ -357,7 +357,7 @@ function httpPluginTests(usingFetch) { * @param {string=} overrideUri */ function testSucceeds(uri, done, overrideUri) { - let request = shaka.net.NetworkingEngine.makeRequest( + const request = shaka.net.NetworkingEngine.makeRequest( [uri], retryParameters); plugin(uri, request, requestType).promise .catch(fail) @@ -383,7 +383,7 @@ function httpPluginTests(usingFetch) { * @param {Array<*>=} errorData */ function testFails(uri, done, severity, code, errorData) { - let request = shaka.net.NetworkingEngine.makeRequest( + const request = shaka.net.NetworkingEngine.makeRequest( [uri], retryParameters); plugin(uri, request, requestType).promise .then(fail) @@ -412,7 +412,7 @@ function httpPluginTests(usingFetch) { * @param {string=} overrideUri */ function testSucceedsWithEmptyLine(uri, done, overrideUri) { - let request = shaka.net.NetworkingEngine.makeRequest( + const request = shaka.net.NetworkingEngine.makeRequest( [uri], retryParameters); plugin(uri, request, requestType).promise .catch(fail) @@ -434,7 +434,7 @@ function httpPluginTests(usingFetch) { */ function mostRecentRequest() { if (usingFetch) { - let mostRecent = jasmine.Fetch.requests.mostRecent(); + const mostRecent = jasmine.Fetch.requests.mostRecent(); if (mostRecent) { // Convert from jasmine.Fetch.RequestStub to jasmine.Ajax.RequestStub return /** @type {jasmine.Ajax.RequestStub} */({ diff --git a/test/net/networking_engine_unit.js b/test/net/networking_engine_unit.js index 0f1c992990..e274992b93 100644 --- a/test/net/networking_engine_unit.js +++ b/test/net/networking_engine_unit.js @@ -79,7 +79,7 @@ describe('NetworkingEngine', /** @suppress {accessControls} */ function() { describe('retry', function() { it('will retry', function(done) { - let request = createRequest('reject://foo', { + const request = createRequest('reject://foo', { maxAttempts: 2, baseDelay: 0, backoffFactor: 0, @@ -102,7 +102,7 @@ describe('NetworkingEngine', /** @suppress {accessControls} */ function() { }); it('will retry twice', function(done) { - let request = createRequest('reject://foo', { + const request = createRequest('reject://foo', { maxAttempts: 3, baseDelay: 0, backoffFactor: 0, @@ -125,7 +125,7 @@ describe('NetworkingEngine', /** @suppress {accessControls} */ function() { }); it('will fail overall', function(done) { - let request = createRequest('reject://foo', { + const request = createRequest('reject://foo', { maxAttempts: 3, baseDelay: 0, backoffFactor: 0, @@ -226,7 +226,7 @@ describe('NetworkingEngine', /** @suppress {accessControls} */ function() { }); // describe('backoff') it('uses multiple URIs', function(done) { - let request = createRequest('', { + const request = createRequest('', { maxAttempts: 3, baseDelay: 0, backoffFactor: 0, @@ -244,7 +244,7 @@ describe('NetworkingEngine', /** @suppress {accessControls} */ function() { }); it('won\'t retry for CRITICAL error', function(done) { - let request = createRequest('reject://foo', { + const request = createRequest('reject://foo', { maxAttempts: 5, baseDelay: 0, backoffFactor: 0, @@ -277,12 +277,12 @@ describe('NetworkingEngine', /** @suppress {accessControls} */ function() { }); it('uses registered scheme plugins in order of priority', function(done) { - let applicationResolveScheme = + const applicationResolveScheme = makeResolveScheme('application resolve scheme'); shaka.net.NetworkingEngine.registerScheme( 'resolve', Util.spyFunc(applicationResolveScheme), shaka.net.NetworkingEngine.PluginPriority.APPLICATION); - let preferredResolveScheme = + const preferredResolveScheme = makeResolveScheme('preferred resolve scheme'); shaka.net.NetworkingEngine.registerScheme( 'resolve', Util.spyFunc(preferredResolveScheme), @@ -292,7 +292,7 @@ describe('NetworkingEngine', /** @suppress {accessControls} */ function() { }); it('uses newest scheme plugin in case of tie in priority', function(done) { - let secondResolveScheme = makeResolveScheme('second resolve scheme'); + const secondResolveScheme = makeResolveScheme('second resolve scheme'); shaka.net.NetworkingEngine.registerScheme( 'resolve', Util.spyFunc(secondResolveScheme), shaka.net.NetworkingEngine.PluginPriority.FALLBACK); @@ -301,10 +301,10 @@ describe('NetworkingEngine', /** @suppress {accessControls} */ function() { }); it('defaults new scheme plugins to application priority', function(done) { - let secondResolveScheme = makeResolveScheme('second resolve scheme'); + const secondResolveScheme = makeResolveScheme('second resolve scheme'); shaka.net.NetworkingEngine.registerScheme( 'resolve', Util.spyFunc(secondResolveScheme)); - let preferredResolveScheme = + const preferredResolveScheme = makeResolveScheme('preferred resolve scheme'); shaka.net.NetworkingEngine.registerScheme( 'resolve', Util.spyFunc(preferredResolveScheme), @@ -323,7 +323,7 @@ describe('NetworkingEngine', /** @suppress {accessControls} */ function() { }); it('unregister removes all plugins for scheme at once', function(done) { - let preferredResolveScheme = + const preferredResolveScheme = makeResolveScheme('preferred resolve scheme'); shaka.net.NetworkingEngine.registerScheme( 'resolve', Util.spyFunc(preferredResolveScheme), @@ -361,7 +361,7 @@ describe('NetworkingEngine', /** @suppress {accessControls} */ function() { }); it('passes correct arguments to plugin', function(done) { - let request = createRequest('resolve://foo'); + const request = createRequest('resolve://foo'); request.method = 'POST'; resolveScheme.and.callFake( @@ -387,7 +387,7 @@ describe('NetworkingEngine', /** @suppress {accessControls} */ function() { }); it('fills in defaults for partial request objects', function(done) { - let originalRequest = /** @type {shaka.extern.Request} */ ({ + const originalRequest = /** @type {shaka.extern.Request} */ ({ uris: ['resolve://foo'], }); @@ -436,7 +436,7 @@ describe('NetworkingEngine', /** @suppress {accessControls} */ function() { }); it('is given correct arguments', function(done) { - let request = createRequest('resolve://foo'); + const request = createRequest('resolve://foo'); networkingEngine.request(requestType, request).promise .catch(fail) .then(function() { @@ -448,15 +448,15 @@ describe('NetworkingEngine', /** @suppress {accessControls} */ function() { }); it('waits for asynchronous filters', function(done) { - let responseFilter = jasmine.createSpy('response filter'); + const responseFilter = jasmine.createSpy('response filter'); networkingEngine.registerResponseFilter(Util.spyFunc(responseFilter)); - let p = new shaka.util.PublicPromise(); - let p2 = new shaka.util.PublicPromise(); + const p = new shaka.util.PublicPromise(); + const p2 = new shaka.util.PublicPromise(); filter.and.returnValue(p); responseFilter.and.returnValue(p2); - let request = createRequest('resolve://foo'); - let r = new StatusPromise( + const request = createRequest('resolve://foo'); + const r = new StatusPromise( networkingEngine.request(requestType, request).promise); Util.delay(0.1).then(function() { @@ -481,7 +481,7 @@ describe('NetworkingEngine', /** @suppress {accessControls} */ function() { }); it('turns errors into shaka errors', function(done) { - let fakeError = 'fake error'; + const fakeError = 'fake error'; filter.and.callFake(function() { throw fakeError; }); @@ -510,7 +510,7 @@ describe('NetworkingEngine', /** @suppress {accessControls} */ function() { }); it('applies request filters sequentially', function(done) { - let secondFilter = jasmine.createSpy('second request filter'); + const secondFilter = jasmine.createSpy('second request filter'); networkingEngine.registerRequestFilter(Util.spyFunc(secondFilter)); let order = 0; @@ -530,7 +530,7 @@ describe('NetworkingEngine', /** @suppress {accessControls} */ function() { }); it('can modify requests asynchronously', function(done) { - let p = new shaka.util.PublicPromise(); + const p = new shaka.util.PublicPromise(); filter.and.callFake(function(type, request) { return p.then(function() { request.uris = ['resolve://foo']; @@ -572,7 +572,7 @@ describe('NetworkingEngine', /** @suppress {accessControls} */ function() { }); it('if rejects will stop requests', function(done) { - let request = createRequest('resolve://foo', { + const request = createRequest('resolve://foo', { maxAttempts: 3, baseDelay: 0, backoffFactor: 0, @@ -590,7 +590,7 @@ describe('NetworkingEngine', /** @suppress {accessControls} */ function() { }); it('if throws will stop requests', function(done) { - let request = createRequest('resolve://foo', { + const request = createRequest('resolve://foo', { maxAttempts: 3, baseDelay: 0, backoffFactor: 0, @@ -608,7 +608,7 @@ describe('NetworkingEngine', /** @suppress {accessControls} */ function() { }); it('causes no errors to remove an unused filter', function() { - let unusedFilter = jasmine.createSpy('unused filter'); + const unusedFilter = jasmine.createSpy('unused filter'); networkingEngine.unregisterRequestFilter(Util.spyFunc(unusedFilter)); }); }); // describe('request filter') @@ -648,7 +648,7 @@ describe('NetworkingEngine', /** @suppress {accessControls} */ function() { }); it('is given correct arguments', function(done) { - let request = createRequest('resolve://foo'); + const request = createRequest('resolve://foo'); networkingEngine.request(requestType, request) .promise .catch(fail) @@ -693,7 +693,7 @@ describe('NetworkingEngine', /** @suppress {accessControls} */ function() { }); it('applies response filters sequentially', function(done) { - let secondFilter = jasmine.createSpy('second response filter'); + const secondFilter = jasmine.createSpy('second response filter'); networkingEngine.registerResponseFilter(Util.spyFunc(secondFilter)); let order = 0; @@ -713,7 +713,7 @@ describe('NetworkingEngine', /** @suppress {accessControls} */ function() { }); it('turns errors into shaka errors', function(done) { - let fakeError = 'fake error'; + const fakeError = 'fake error'; filter.and.callFake(function() { throw fakeError; }); @@ -728,7 +728,7 @@ describe('NetworkingEngine', /** @suppress {accessControls} */ function() { }); it('can modify responses asynchronously', function(done) { - let p = new shaka.util.PublicPromise(); + const p = new shaka.util.PublicPromise(); filter.and.callFake(function(type, response) { return p.then(function() { expect(response.headers).toBeTruthy(); @@ -737,8 +737,8 @@ describe('NetworkingEngine', /** @suppress {accessControls} */ function() { }); }); - let request = createRequest('resolve://foo'); - let r = new StatusPromise(networkingEngine.request(requestType, request) + const request = createRequest('resolve://foo'); + const r = new StatusPromise(networkingEngine.request(requestType, request) .promise .catch(fail) .then(function(response) { @@ -766,21 +766,21 @@ describe('NetworkingEngine', /** @suppress {accessControls} */ function() { }); it('causes no errors to remove an unused filter', function() { - let unusedFilter = jasmine.createSpy('unused filter'); + const unusedFilter = jasmine.createSpy('unused filter'); networkingEngine.unregisterResponseFilter(Util.spyFunc(unusedFilter)); }); }); // describe('response filter') describe('destroy', function() { it('waits for all operations to complete', function(done) { - let request = createRequest('resolve://foo'); - let p = new shaka.util.PublicPromise(); + const request = createRequest('resolve://foo'); + const p = new shaka.util.PublicPromise(); resolveScheme.and.returnValue( shaka.util.AbortableOperation.notAbortable(p)); - let r1 = new StatusPromise( + const r1 = new StatusPromise( networkingEngine.request(requestType, request).promise); - let r2 = new StatusPromise( + const r2 = new StatusPromise( networkingEngine.request(requestType, request).promise); expect(r1.status).toBe('pending'); @@ -808,19 +808,19 @@ describe('NetworkingEngine', /** @suppress {accessControls} */ function() { }); it('causes requests to reject if called while filtering', function(done) { - let filter = jasmine.createSpy('request filter'); + const filter = jasmine.createSpy('request filter'); networkingEngine.registerRequestFilter(Util.spyFunc(filter)); - let p = new shaka.util.PublicPromise(); + const p = new shaka.util.PublicPromise(); filter.and.returnValue(p); - let request = createRequest('resolve://foo', { + const request = createRequest('resolve://foo', { maxAttempts: 1, baseDelay: 0, backoffFactor: 0, fuzzFactor: 0, timeout: 0, }); - let r = new StatusPromise( + const r = new StatusPromise( networkingEngine.request(requestType, request).promise); /** @type {!shaka.test.StatusPromise} */ @@ -841,14 +841,14 @@ describe('NetworkingEngine', /** @suppress {accessControls} */ function() { }); it('resolves even when a request fails', function(done) { - let request = createRequest('reject://foo'); - let p = new shaka.util.PublicPromise(); + const request = createRequest('reject://foo'); + const p = new shaka.util.PublicPromise(); rejectScheme.and.returnValue( shaka.util.AbortableOperation.notAbortable(p)); - let r1 = new StatusPromise( + const r1 = new StatusPromise( networkingEngine.request(requestType, request).promise); - let r2 = new StatusPromise( + const r2 = new StatusPromise( networkingEngine.request(requestType, request).promise); expect(r1.status).toBe('pending'); @@ -875,12 +875,12 @@ describe('NetworkingEngine', /** @suppress {accessControls} */ function() { }); it('prevents new requests', function(done) { - let request = createRequest('resolve://foo'); + const request = createRequest('resolve://foo'); - let d = new StatusPromise(networkingEngine.destroy()); + const d = new StatusPromise(networkingEngine.destroy()); expect(d.status).toBe('pending'); - let r = new StatusPromise( + const r = new StatusPromise( networkingEngine.request(requestType, request).promise); Util.delay(0.1).then(() => { @@ -894,7 +894,7 @@ describe('NetworkingEngine', /** @suppress {accessControls} */ function() { }); it('does not allow further retries', function(done) { - let request = createRequest('reject://foo', { + const request = createRequest('reject://foo', { maxAttempts: 3, baseDelay: 0, backoffFactor: 0, @@ -902,8 +902,8 @@ describe('NetworkingEngine', /** @suppress {accessControls} */ function() { timeout: 0, }); - let p1 = new shaka.util.PublicPromise(); - let p2 = new shaka.util.PublicPromise(); + const p1 = new shaka.util.PublicPromise(); + const p2 = new shaka.util.PublicPromise(); rejectScheme.and.callFake(function() { // Return p1 the first time, then p2 the second time. return (rejectScheme.calls.count() == 1) ? @@ -911,7 +911,7 @@ describe('NetworkingEngine', /** @suppress {accessControls} */ function() { shaka.util.AbortableOperation.notAbortable(p2); }); - let r = new StatusPromise( + const r = new StatusPromise( networkingEngine.request(requestType, request).promise); /** @type {shaka.test.StatusPromise} */ let d; @@ -943,7 +943,7 @@ describe('NetworkingEngine', /** @suppress {accessControls} */ function() { }); // describe('destroy') it('ignores cache hits', function(done) { - let onSegmentDownloaded = jasmine.createSpy('onSegmentDownloaded'); + const onSegmentDownloaded = jasmine.createSpy('onSegmentDownloaded'); networkingEngine = new shaka.net.NetworkingEngine(Util.spyFunc(onSegmentDownloaded)); @@ -986,15 +986,15 @@ describe('NetworkingEngine', /** @suppress {accessControls} */ function() { }); it('is called on recoverable error', async () => { - let error1 = new shaka.util.Error( + const error1 = new shaka.util.Error( shaka.util.Error.Severity.RECOVERABLE, shaka.util.Error.Category.NETWORK, shaka.util.Error.Code.HTTP_ERROR); - let error2 = new shaka.util.Error( + const error2 = new shaka.util.Error( shaka.util.Error.Severity.RECOVERABLE, shaka.util.Error.Category.NETWORK, shaka.util.Error.Code.BAD_HTTP_STATUS); - let resolve = createResponse(); + const resolve = createResponse(); rejectScheme.and.callFake(() => { switch (rejectScheme.calls.count()) { case 1: return shaka.util.AbortableOperation.failed(error1); @@ -1038,21 +1038,21 @@ describe('NetworkingEngine', /** @suppress {accessControls} */ function() { }); it('interrupts request filters', function(done) { - let filter1Promise = new shaka.util.PublicPromise(); - let filter1Spy = jasmine.createSpy('filter 1') + const filter1Promise = new shaka.util.PublicPromise(); + const filter1Spy = jasmine.createSpy('filter 1') .and.returnValue(filter1Promise); - let filter1 = Util.spyFunc(filter1Spy); + const filter1 = Util.spyFunc(filter1Spy); networkingEngine.registerRequestFilter(filter1); - let filter2Promise = new shaka.util.PublicPromise(); - let filter2Spy = jasmine.createSpy('filter 2') + const filter2Promise = new shaka.util.PublicPromise(); + const filter2Spy = jasmine.createSpy('filter 2') .and.returnValue(filter2Promise); - let filter2 = Util.spyFunc(filter2Spy); + const filter2 = Util.spyFunc(filter2Spy); networkingEngine.registerRequestFilter(filter2); - let request = createRequest('resolve://foo'); - let operation = networkingEngine.request(requestType, request); - let r = new StatusPromise(operation.promise); + const request = createRequest('resolve://foo'); + const operation = networkingEngine.request(requestType, request); + const r = new StatusPromise(operation.promise); Util.delay(0.1).then(() => { // The first filter has been called, but not the second, and not the @@ -1083,17 +1083,17 @@ describe('NetworkingEngine', /** @suppress {accessControls} */ function() { }); it('interrupts scheme plugins', function(done) { - let p = new shaka.util.PublicPromise(); - let abortSpy = jasmine.createSpy('abort'); - let abort = Util.spyFunc(abortSpy); + const p = new shaka.util.PublicPromise(); + const abortSpy = jasmine.createSpy('abort'); + const abort = Util.spyFunc(abortSpy); resolveScheme.and.returnValue( new shaka.util.AbortableOperation(p, abort)); expect(resolveScheme).not.toHaveBeenCalled(); - let request = createRequest('resolve://foo'); - let operation = networkingEngine.request(requestType, request); - let r = new StatusPromise(operation.promise); + const request = createRequest('resolve://foo'); + const operation = networkingEngine.request(requestType, request); + const r = new StatusPromise(operation.promise); Util.delay(0.1).then(() => { // A request has been made, but not completed yet. @@ -1115,21 +1115,21 @@ describe('NetworkingEngine', /** @suppress {accessControls} */ function() { }); it('interrupts response filters', function(done) { - let filter1Promise = new shaka.util.PublicPromise(); - let filter1Spy = jasmine.createSpy('filter 1') + const filter1Promise = new shaka.util.PublicPromise(); + const filter1Spy = jasmine.createSpy('filter 1') .and.returnValue(filter1Promise); - let filter1 = Util.spyFunc(filter1Spy); + const filter1 = Util.spyFunc(filter1Spy); networkingEngine.registerResponseFilter(filter1); - let filter2Promise = new shaka.util.PublicPromise(); - let filter2Spy = jasmine.createSpy('filter 2') + const filter2Promise = new shaka.util.PublicPromise(); + const filter2Spy = jasmine.createSpy('filter 2') .and.returnValue(filter2Promise); - let filter2 = Util.spyFunc(filter2Spy); + const filter2 = Util.spyFunc(filter2Spy); networkingEngine.registerResponseFilter(filter2); - let request = createRequest('resolve://foo'); - let operation = networkingEngine.request(requestType, request); - let r = new StatusPromise(operation.promise); + const request = createRequest('resolve://foo'); + const operation = networkingEngine.request(requestType, request); + const r = new StatusPromise(operation.promise); Util.delay(0.1).then(() => { // The scheme plugin has been called, and the first filter has been @@ -1159,17 +1159,17 @@ describe('NetworkingEngine', /** @suppress {accessControls} */ function() { }); it('is called by destroy', function(done) { - let p = new shaka.util.PublicPromise(); - let abortSpy = jasmine.createSpy('abort'); - let abort = Util.spyFunc(abortSpy); + const p = new shaka.util.PublicPromise(); + const abortSpy = jasmine.createSpy('abort'); + const abort = Util.spyFunc(abortSpy); resolveScheme.and.returnValue( new shaka.util.AbortableOperation(p, abort)); expect(resolveScheme).not.toHaveBeenCalled(); - let request = createRequest('resolve://foo'); - let operation = networkingEngine.request(requestType, request); - let r = new StatusPromise(operation.promise); + const request = createRequest('resolve://foo'); + const operation = networkingEngine.request(requestType, request); + const r = new StatusPromise(operation.promise); Util.delay(0.1).then(() => { // A request has been made, but not completed yet. diff --git a/test/offline/indexeddb_storage_unit.js b/test/offline/indexeddb_storage_unit.js index 59af688001..2b0f3b79d8 100644 --- a/test/offline/indexeddb_storage_unit.js +++ b/test/offline/indexeddb_storage_unit.js @@ -52,7 +52,7 @@ describe('IndexeddbStorageCell', function() { let cell; /** @type {!Array.<shaka.extern.SegmentDataDB>} */ - let segments = [ + const segments = [ OfflineUtils.createSegmentData([0]), OfflineUtils.createSegmentData([0, 1]), OfflineUtils.createSegmentData([0, 1, 2]), @@ -95,7 +95,7 @@ describe('IndexeddbStorageCell', function() { let cell; /** @type {!Array.<shaka.extern.ManifestDB>} */ - let manifests = [ + const manifests = [ OfflineUtils.createManifest('original-uri-1'), OfflineUtils.createManifest('original-uri-2'), OfflineUtils.createManifest('original-uri-3'), @@ -138,7 +138,7 @@ describe('IndexeddbStorageCell', function() { let cell; /** @type {!Array.<shaka.extern.ManifestDB>} */ - let manifests = [ + const manifests = [ OfflineUtils.createManifest('original-uri-1'), OfflineUtils.createManifest('original-uri-2'), OfflineUtils.createManifest('original-uri-3'), @@ -162,7 +162,7 @@ describe('IndexeddbStorageCell', function() { }).then((found) => { expect(found).toBeTruthy(); - let actual = keys.map((key) => found.get(key)); + const actual = keys.map((key) => found.get(key)); expect(actual[0]).toEqual(manifests[0]); expect(actual[1]).toEqual(manifests[1]); expect(actual[2]).toEqual(manifests[2]); @@ -174,7 +174,7 @@ describe('IndexeddbStorageCell', function() { let cell; /** @type {shaka.extern.ManifestDB} */ - let originalManifest = OfflineUtils.createManifest('original'); + const originalManifest = OfflineUtils.createManifest('original'); originalManifest.expiration = 1000; /** @type {number} */ @@ -233,7 +233,7 @@ describe('IndexeddbStorageCell', function() { * @return {shaka.extern.StorageCell} */ function makeCell(connection) { - let cell = new shaka.offline.indexeddb.V2StorageCell( + const cell = new shaka.offline.indexeddb.V2StorageCell( connection, segmentStore, manifestStore, diff --git a/test/offline/manifest_convert_unit.js b/test/offline/manifest_convert_unit.js index bcd4d40a38..db7d8005ab 100644 --- a/test/offline/manifest_convert_unit.js +++ b/test/offline/manifest_convert_unit.js @@ -22,12 +22,12 @@ describe('ManifestConverter', function() { it('will create variants with variant ids', function() { /** @type {!Array.<shaka.extern.StreamDB>} */ - let audios = [ + const audios = [ createStreamDB(0, audioType, [0]), createStreamDB(1, audioType, [1]), ]; /** @type {!Array.<shaka.extern.StreamDB>} */ - let videos = [ + const videos = [ createStreamDB(2, videoType, [0]), createStreamDB(3, videoType, [1]), ]; @@ -47,12 +47,12 @@ describe('ManifestConverter', function() { it('will create variants when there is only audio', function() { /** @type {!Array.<shaka.extern.StreamDB>} */ - let audios = [ + const audios = [ createStreamDB(0, audioType, [0]), createStreamDB(1, audioType, [1]), ]; /** @type {!Array.<shaka.extern.StreamDB>} */ - let videos = []; + const videos = []; /** @type {!Map.<number, shaka.extern.Variant>} */ const variants = createConverter().createVariants(audios, videos); @@ -61,9 +61,9 @@ describe('ManifestConverter', function() { it('will create variants when there is only video', function() { /** @type {!Array.<shaka.extern.StreamDB>} */ - let audios = []; + const audios = []; /** @type {!Array.<shaka.extern.StreamDB>} */ - let videos = [ + const videos = [ createStreamDB(2, videoType, [0]), createStreamDB(3, videoType, [1]), ]; @@ -77,20 +77,20 @@ describe('ManifestConverter', function() { describe('fromPeriodDB', function() { it('will reconstruct Periods correctly', function() { /** @type {shaka.extern.PeriodDB} */ - let periodDb = { + const periodDb = { startTime: 60, streams: [createVideoStreamDB(1, [0]), createAudioStreamDB(2, [0])], }; - let timeline = createTimeline(); + const timeline = createTimeline(); - let period = createConverter().fromPeriodDB(periodDb, timeline); + const period = createConverter().fromPeriodDB(periodDb, timeline); expect(period).toBeTruthy(); expect(period.startTime).toBe(periodDb.startTime); expect(period.textStreams).toEqual([]); expect(period.variants.length).toBe(1); - let variant = period.variants[0]; + const variant = period.variants[0]; expect(variant.id).toEqual(jasmine.any(Number)); expect(variant.language).toBe(periodDb.streams[1].language); expect(variant.primary).toBe(false); @@ -104,14 +104,14 @@ describe('ManifestConverter', function() { it('supports video-only content', function() { /** @type {shaka.extern.PeriodDB} */ - let periodDb = { + const periodDb = { startTime: 60, streams: [createVideoStreamDB(1, [0]), createVideoStreamDB(2, [1])], }; - let timeline = createTimeline(); + const timeline = createTimeline(); - let period = createConverter().fromPeriodDB(periodDb, timeline); + const period = createConverter().fromPeriodDB(periodDb, timeline); expect(period).toBeTruthy(); expect(period.variants.length).toBe(2); expect(period.variants[0].audio).toBe(null); @@ -120,14 +120,14 @@ describe('ManifestConverter', function() { it('supports audio-only content', function() { /** @type {shaka.extern.PeriodDB} */ - let periodDb = { + const periodDb = { startTime: 60, streams: [createAudioStreamDB(1, [0]), createAudioStreamDB(2, [1])], }; - let timeline = createTimeline(); + const timeline = createTimeline(); - let period = createConverter().fromPeriodDB(periodDb, timeline); + const period = createConverter().fromPeriodDB(periodDb, timeline); expect(period).toBeTruthy(); expect(period.variants.length).toBe(2); expect(period.variants[0].audio).toBeTruthy(); @@ -136,7 +136,7 @@ describe('ManifestConverter', function() { it('supports text streams', function() { /** @type {shaka.extern.PeriodDB} */ - let periodDb = { + const periodDb = { startTime: 60, streams: [ createVideoStreamDB(1, [0]), @@ -144,9 +144,9 @@ describe('ManifestConverter', function() { ], }; - let timeline = createTimeline(); + const timeline = createTimeline(); - let period = createConverter().fromPeriodDB(periodDb, timeline); + const period = createConverter().fromPeriodDB(periodDb, timeline); expect(period).toBeTruthy(); expect(period.variants.length).toBe(1); expect(period.textStreams.length).toBe(1); @@ -165,7 +165,7 @@ describe('ManifestConverter', function() { const variant3 = 2; /** @type {shaka.extern.PeriodDB} */ - let periodDb = { + const periodDb = { startTime: 60, streams: [ // Audio @@ -178,10 +178,10 @@ describe('ManifestConverter', function() { ], }; - let timeline = createTimeline(); + const timeline = createTimeline(); /** @type {shaka.extern.Period} */ - let period = createConverter().fromPeriodDB(periodDb, timeline); + const period = createConverter().fromPeriodDB(periodDb, timeline); expect(period).toBeTruthy(); expect(period.variants.length).toBe(3); @@ -213,7 +213,7 @@ describe('ManifestConverter', function() { */ function createStreamDB(id, type, variants) { /** @type {shaka.extern.StreamDB} */ - let streamDB = { + const streamDB = { id: id, originalId: id.toString(), primary: false, @@ -243,7 +243,7 @@ describe('ManifestConverter', function() { */ function createSegmentDB(startTime, endTime, dataKey) { /** @type {shaka.extern.SegmentDB} */ - let segment = { + const segment = { startTime: startTime, endTime: endTime, dataKey: dataKey, @@ -387,7 +387,7 @@ describe('ManifestConverter', function() { return; } - let expectedStream = { + const expectedStream = { id: jasmine.any(Number), originalId: jasmine.any(String), createSegmentIndex: jasmine.any(Function), @@ -421,14 +421,14 @@ describe('ManifestConverter', function() { // Assume that we don't have to call createSegmentIndex. streamDb.segments.forEach(function(segmentDb, i) { - let uri = shaka.offline.OfflineUri.segment( + const uri = shaka.offline.OfflineUri.segment( 'mechanism', 'cell', segmentDb.dataKey); expect(stream.findSegmentPosition(segmentDb.startTime)).toBe(i); expect(stream.findSegmentPosition(segmentDb.endTime - 0.1)).toBe(i); /** @type {shaka.media.SegmentReference} */ - let segment = stream.getSegmentReference(i); + const segment = stream.getSegmentReference(i); expect(segment).toBeTruthy(); expect(segment.position).toBe(i); expect(segment.startTime).toBe(segmentDb.startTime); @@ -451,14 +451,14 @@ describe('ManifestConverter', function() { variants.forEach(function(variant) { /** @type {?shaka.extern.Stream} */ - let audio = variant.audio; + const audio = variant.audio; /** @type {?shaka.extern.Stream} */ - let video = variant.video; + const video = variant.video; /** @type {boolean } */ - let audioMatch = audio ? audioId == audio.id : audioId == null; + const audioMatch = audio ? audioId == audio.id : audioId == null; /** @type {boolean } */ - let videoMatch = video ? videoId == video.id : videoId == null; + const videoMatch = video ? videoId == video.id : videoId == null; if (audioMatch && videoMatch) { found = variant; diff --git a/test/offline/offline_integration.js b/test/offline/offline_integration.js index 8e14057e2b..54119ffea0 100644 --- a/test/offline/offline_integration.js +++ b/test/offline/offline_integration.js @@ -70,10 +70,10 @@ describe('Offline', () => { return; } - let content = await storage.store('test:sintel'); + const content = await storage.store('test:sintel'); expect(content).toBeTruthy(); - let contentUri = content.offlineUri; + const contentUri = content.offlineUri; goog.asserts.assert( contentUri, 'Stored content should have an offline uri.'); @@ -94,8 +94,8 @@ describe('Offline', () => { return; } - let support = await shaka.Player.probeSupport(); - let widevineSupport = support.drm['com.widevine.alpha']; + const support = await shaka.Player.probeSupport(); + const widevineSupport = support.drm['com.widevine.alpha']; if (!widevineSupport || !widevineSupport.persistentState) { pending('Widevine persistent licenses are not supported'); @@ -105,7 +105,7 @@ describe('Offline', () => { shaka.test.TestScheme.setupPlayer(player, 'sintel-enc'); storage.configure({usePersistentLicense: true}); - let content = await storage.store('test:sintel-enc'); + const content = await storage.store('test:sintel-enc'); // Work around http://crbug.com/887535 in which load cannot happen right // after close. Experimentally, we seem to need a ~1s delay, so we're @@ -114,7 +114,7 @@ describe('Offline', () => { // TODO: Remove when Chrome is fixed await shaka.test.Util.delay(3); - let contentUri = content.offlineUri; + const contentUri = content.offlineUri; goog.asserts.assert( contentUri, 'Stored content should have an offline uri.'); @@ -134,9 +134,9 @@ describe('Offline', () => { return; } - let support = await shaka.Player.probeSupport(); - let widevineSupport = support.drm['com.widevine.alpha']; - let playreadySupport = support.drm['com.microsoft.playready']; + const support = await shaka.Player.probeSupport(); + const widevineSupport = support.drm['com.widevine.alpha']; + const playreadySupport = support.drm['com.microsoft.playready']; if (!(widevineSupport || playreadySupport)) { pending('Widevine and PlayReady are not supported'); @@ -149,9 +149,9 @@ describe('Offline', () => { shaka.test.TestScheme.setupPlayer(player, 'multidrm_no_init_data'); storage.configure({usePersistentLicense: false}); - let content = await storage.store('test:multidrm_no_init_data'); + const content = await storage.store('test:multidrm_no_init_data'); - let contentUri = content.offlineUri; + const contentUri = content.offlineUri; goog.asserts.assert( contentUri, 'Stored content should have an offline uri.'); diff --git a/test/offline/offline_manifest_parser_unit.js b/test/offline/offline_manifest_parser_unit.js index 2cff425b26..cd598cb29e 100644 --- a/test/offline/offline_manifest_parser_unit.js +++ b/test/offline/offline_manifest_parser_unit.js @@ -40,7 +40,7 @@ describe('OfflineManifestParser', function() { })); it('returns manifest from storage', checkAndRun(async function() { - let inputManifest = makeManifest(); + const inputManifest = makeManifest(); /** @type {!shaka.offline.OfflineUri} */ let uri; @@ -50,8 +50,8 @@ describe('OfflineManifestParser', function() { try { await muxer.init(); - let handle = await muxer.getActive(); - let keys = await handle.cell.addManifests([inputManifest]); + const handle = await muxer.getActive(); + const keys = await handle.cell.addManifests([inputManifest]); uri = shaka.offline.OfflineUri.manifest( handle.path.mechanism, handle.path.cell, keys[0]); @@ -59,14 +59,14 @@ describe('OfflineManifestParser', function() { await muxer.destroy(); } - let outputManifest = await parser.start(uri.toString(), playerInterface); + const outputManifest = await parser.start(uri.toString(), playerInterface); expect(outputManifest).toBeTruthy(); })); it('updates expiration', checkAndRun(async function() { const newExpiration = 1000; - let inputManifest = makeManifest(); + const inputManifest = makeManifest(); // Make sure that the expiration is different from the new expiration // so that when we check that they are the same later, it actually // means that it changed. @@ -77,17 +77,17 @@ describe('OfflineManifestParser', function() { try { await muxer.init(); - let handle = await muxer.getActive(); - let keys = await handle.cell.addManifests([inputManifest]); + const handle = await muxer.getActive(); + const keys = await handle.cell.addManifests([inputManifest]); /** @type {!shaka.offline.OfflineUri} */ - let uri = shaka.offline.OfflineUri.manifest( + const uri = shaka.offline.OfflineUri.manifest( handle.path.mechanism, handle.path.cell, keys[0]); await parser.start(uri.toString(), playerInterface); await parser.onExpirationUpdated(sessionId, newExpiration); - let found = await handle.cell.getManifests(keys); + const found = await handle.cell.getManifests(keys); expect(found[0].expiration).toBe(newExpiration); } finally { await muxer.destroy(); @@ -95,7 +95,7 @@ describe('OfflineManifestParser', function() { })); it('fails if manifest was not found', checkAndRun(async function() { - let inputManifest = makeManifest(); + const inputManifest = makeManifest(); /** @type {!shaka.offline.OfflineUri} */ let uri; @@ -105,8 +105,8 @@ describe('OfflineManifestParser', function() { try { await muxer.init(); - let handle = await muxer.getActive(); - let keys = await handle.cell.addManifests([inputManifest]); + const handle = await muxer.getActive(); + const keys = await handle.cell.addManifests([inputManifest]); uri = shaka.offline.OfflineUri.manifest( handle.path.mechanism, handle.path.cell, keys[0]); @@ -140,16 +140,16 @@ describe('OfflineManifestParser', function() { checkAndRun(async function() { const newExpiration = 1000; - let inputManifest = makeManifest(); + const inputManifest = makeManifest(); /** @type {!shaka.offline.StorageMuxer} */ const muxer = new shaka.offline.StorageMuxer(); try { await muxer.init(); - let handle = await muxer.getActive(); - let keys = await handle.cell.addManifests([inputManifest]); + const handle = await muxer.getActive(); + const keys = await handle.cell.addManifests([inputManifest]); - let uri = shaka.offline.OfflineUri.manifest( + const uri = shaka.offline.OfflineUri.manifest( handle.path.mechanism, handle.path.cell, keys[0]); await parser.start(uri.toString(), playerInterface); @@ -169,8 +169,8 @@ describe('OfflineManifestParser', function() { const wrongSession = 'this-session-wont-be-found'; const newExpiration = 1000; - let inputManifest = makeManifest(); - let oldExpiration = inputManifest.expiration; + const inputManifest = makeManifest(); + const oldExpiration = inputManifest.expiration; // Make sure that the expirations are not the same. expect(oldExpiration).not.toBe(newExpiration); @@ -180,17 +180,17 @@ describe('OfflineManifestParser', function() { try { await muxer.init(); - let handle = await muxer.getActive(); - let keys = await handle.cell.addManifests([inputManifest]); + const handle = await muxer.getActive(); + const keys = await handle.cell.addManifests([inputManifest]); - let uri = shaka.offline.OfflineUri.manifest( + const uri = shaka.offline.OfflineUri.manifest( handle.path.mechanism, handle.path.cell, keys[0]); await parser.start(uri.toString(), playerInterface); await parser.onExpirationUpdated(wrongSession, newExpiration); // Make sure that the expiration was not updated. - let found = await handle.cell.getManifests(keys); + const found = await handle.cell.getManifests(keys); expect(found[0].expiration).toBe(oldExpiration); } finally { await muxer.destroy(); @@ -205,7 +205,7 @@ describe('OfflineManifestParser', function() { const seconds = 1.0; /** @type {shaka.extern.ManifestDB} */ - let manifest = { + const manifest = { originalManifestUri: '', duration: 600 * seconds, size: 100 * mb, @@ -241,7 +241,7 @@ describe('OfflineManifestParser', function() { */ function checkAndRun(test) { return async () => { - let hasSupport = shaka.offline.StorageMuxer.support(); + const hasSupport = shaka.offline.StorageMuxer.support(); if (hasSupport) { await test(); } else { diff --git a/test/offline/offline_scheme_unit.js b/test/offline/offline_scheme_unit.js index 64996ec8ee..408102c753 100644 --- a/test/offline/offline_scheme_unit.js +++ b/test/offline/offline_scheme_unit.js @@ -35,7 +35,7 @@ describe('OfflineScheme', function() { 'mechanism', 'cell', 1024); // eslint-disable-next-line new-cap - let response = await shaka.offline.OfflineScheme( + const response = await shaka.offline.OfflineScheme( uri.toString(), request).promise; expect(response).toBeTruthy(); @@ -55,8 +55,8 @@ describe('OfflineScheme', function() { try { await muxer.init(); - let handle = await muxer.getActive(); - let keys = await handle.cell.addSegments([segment]); + const handle = await muxer.getActive(); + const keys = await handle.cell.addSegments([segment]); uri = shaka.offline.OfflineUri.segment( handle.path.mechanism, handle.path.cell, keys[0]); } finally { @@ -64,7 +64,7 @@ describe('OfflineScheme', function() { } // eslint-disable-next-line new-cap - let response = await shaka.offline.OfflineScheme( + const response = await shaka.offline.OfflineScheme( uri.toString(), request).promise; expect(response).toBeTruthy(); @@ -82,7 +82,7 @@ describe('OfflineScheme', function() { try { await muxer.init(); - let handle = await muxer.getActive(); + const handle = await muxer.getActive(); // Create a bad uri by using the mechanism and cell of the active cell // but use a key that is not in use. @@ -119,8 +119,8 @@ describe('OfflineScheme', function() { * @return {shaka.extern.Request} */ function createRequest() { - let retry = shaka.net.NetworkingEngine.defaultRetryParameters(); - let request = shaka.net.NetworkingEngine.makeRequest([], retry); + const retry = shaka.net.NetworkingEngine.defaultRetryParameters(); + const request = shaka.net.NetworkingEngine.makeRequest([], retry); return request; } @@ -131,7 +131,7 @@ describe('OfflineScheme', function() { function createSegment() { const dataLength = 12; - let segment = { + const segment = { data: new ArrayBuffer(dataLength), }; @@ -161,7 +161,7 @@ describe('OfflineScheme', function() { */ function checkAndRun(test) { return async () => { - let hasSupport = shaka.offline.StorageMuxer.support(); + const hasSupport = shaka.offline.StorageMuxer.support(); if (hasSupport) { await test(); } else { diff --git a/test/offline/offline_uri_unit.js b/test/offline/offline_uri_unit.js index acd01913cc..6a3c8a4c68 100644 --- a/test/offline/offline_uri_unit.js +++ b/test/offline/offline_uri_unit.js @@ -20,34 +20,34 @@ describe('OfflineUri', function() { it('creates uri from manifest id', function() { /** @type {number} */ - let id = 123; + const id = 123; /** @type {string} */ - let uri = OfflineUri.manifest('mech', 'cell', id).toString(); + const uri = OfflineUri.manifest('mech', 'cell', id).toString(); expect(uri).toBe('offline:manifest/mech/cell/123'); }); it('creates uri from segment id', function() { /** @type {number} */ - let id = 123; + const id = 123; /** @type {string} */ - let uri = OfflineUri.segment('mech', 'cell', id).toString(); + const uri = OfflineUri.segment('mech', 'cell', id).toString(); expect(uri).toBe('offline:segment/mech/cell/123'); }); it('creates null from invalid uri', function() { /** @type {string} */ - let uri = 'invalid-uri'; - let parsed = OfflineUri.parse(uri); + const uri = 'invalid-uri'; + const parsed = OfflineUri.parse(uri); expect(parsed).toBeNull(); }); it('parse manifest uri', function() { /** @type {string} */ - let uri = 'offline:manifest/mech/cell/123'; - let parsed = OfflineUri.parse(uri); + const uri = 'offline:manifest/mech/cell/123'; + const parsed = OfflineUri.parse(uri); expect(parsed).toBeTruthy(); expect(parsed.isManifest()).toBeTruthy(); @@ -58,8 +58,8 @@ describe('OfflineUri', function() { it('parse segment uri', function() { /** @type {string} */ - let uri = 'offline:segment/mech/cell/123'; - let parsed = OfflineUri.parse(uri); + const uri = 'offline:segment/mech/cell/123'; + const parsed = OfflineUri.parse(uri); expect(parsed).toBeTruthy(); expect(parsed.isSegment()).toBeTruthy(); diff --git a/test/offline/storage_unit.js b/test/offline/storage_unit.js index 196866c85d..7ae7e5dbe5 100644 --- a/test/offline/storage_unit.js +++ b/test/offline/storage_unit.js @@ -71,7 +71,7 @@ describe('Storage', function() { // Make sure that the content can be found. await withStorage(async (storage) => { - let content = await storage.list(); + const content = await storage.list(); expect(content).toBeTruthy(); expect(content.length).toBe(1); }); @@ -81,7 +81,7 @@ describe('Storage', function() { // Make sure that all content that was previously found is no gone. await withStorage(async (storage) => { - let content = await storage.list(); + const content = await storage.list(); expect(content).toBeTruthy(); expect(content.length).toBe(0); }); @@ -135,15 +135,15 @@ describe('Storage', function() { // PART 1 - Download and store content that has a persistent license // associated with it. - let stored = await storage.store( + const stored = await storage.store( 'test:sintel-enc', noMetadata, TestManifestParser); expect(stored.offlineUri).toBeTruthy(); /** @type {shaka.offline.OfflineUri} */ - let uri = shaka.offline.OfflineUri.parse(stored.offlineUri); + const uri = shaka.offline.OfflineUri.parse(stored.offlineUri); goog.asserts.assert(uri, 'Stored offline uri should be non-null'); - let manifest = await getStoredManifest(uri); + const manifest = await getStoredManifest(uri); expect(manifest.offlineSessionIds).toBeTruthy(); expect(manifest.offlineSessionIds.length).toBeTruthy(); @@ -157,7 +157,7 @@ describe('Storage', function() { // PART 2 - Check that the licences are stored. await withDrm(player, manifest, (drm) => { return Promise.all(manifest.offlineSessionIds.map(async (session) => { - let foundSession = await loadOfflineSession(drm, session); + const foundSession = await loadOfflineSession(drm, session); expect(foundSession).toBeTruthy(); })); }); @@ -177,7 +177,7 @@ describe('Storage', function() { try { await withDrm(player, manifest, (drm) => { return Promise.all(manifest.offlineSessionIds.map(async (session) => { - let notFoundSession = await loadOfflineSession(drm, session); + const notFoundSession = await loadOfflineSession(drm, session); // TODO: This is failing. The session is actually found, possibly // due to http://crbug.com/690583, but this is unclear. expect(notFoundSession).toBeFalsy(); @@ -292,7 +292,8 @@ describe('Storage', function() { variantTrack(5, 1080, englishUS, 4 * kbps), ]; - let selected = PlayerConfiguration.defaultTrackSelect(tracks, englishUS); + const selected = + PlayerConfiguration.defaultTrackSelect(tracks, englishUS); expect(selected).toBeTruthy(); expect(selected.length).toBe(1); expect(selected[0]).toBeTruthy(); @@ -307,7 +308,8 @@ describe('Storage', function() { textTrack(1, frenchCanadian), ]; - let selected = PlayerConfiguration.defaultTrackSelect(tracks, englishUS); + const selected = + PlayerConfiguration.defaultTrackSelect(tracks, englishUS); expect(selected).toBeTruthy(); expect(selected.length).toBe(2); tracks.forEach((track) => { @@ -323,7 +325,8 @@ describe('Storage', function() { variantTrack(2, 480, 'eng-ca', 1 * kbps), ]; - let selected = PlayerConfiguration.defaultTrackSelect(tracks, 'eng-us'); + const selected = + PlayerConfiguration.defaultTrackSelect(tracks, 'eng-us'); expect(selected).toBeTruthy(); expect(selected.length).toBe(1); expect(selected[0]).toBeTruthy(); @@ -338,7 +341,7 @@ describe('Storage', function() { variantTrack(3, 480, 'eng', 1 * kbps), ]; - let selected = PlayerConfiguration.defaultTrackSelect(tracks, 'eng'); + const selected = PlayerConfiguration.defaultTrackSelect(tracks, 'eng'); expect(selected).toBeTruthy(); expect(selected.length).toBe(1); expect(selected[0]).toBeTruthy(); @@ -352,7 +355,7 @@ describe('Storage', function() { variantTrack(2, 480, 'eng-ca', 1 * kbps), ]; - let selected = PlayerConfiguration.defaultTrackSelect(tracks, 'fr'); + const selected = PlayerConfiguration.defaultTrackSelect(tracks, 'fr'); expect(selected).toBeTruthy(); expect(selected.length).toBe(1); expect(selected[0]).toBeTruthy(); @@ -366,7 +369,8 @@ describe('Storage', function() { variantTrack(2, 480, 'eng-ca', 1 * kbps), ]; - let selected = PlayerConfiguration.defaultTrackSelect(tracks, 'fr-uk'); + const selected = + PlayerConfiguration.defaultTrackSelect(tracks, 'fr-uk'); expect(selected).toBeTruthy(); expect(selected.length).toBe(1); expect(selected[0]).toBeTruthy(); @@ -382,7 +386,7 @@ describe('Storage', function() { tracks[0].primary = true; - let selected = PlayerConfiguration.defaultTrackSelect(tracks, 'de'); + const selected = PlayerConfiguration.defaultTrackSelect(tracks, 'de'); expect(selected).toBeTruthy(); expect(selected.length).toBe(1); expect(selected[0]).toBeTruthy(); @@ -733,10 +737,10 @@ describe('Storage', function() { await storage.store(manifestUris[1], noMetadata, FakeManifestParser); await storage.store(manifestUris[2], noMetadata, FakeManifestParser); - let content = await storage.list(); + const content = await storage.list(); expect(content).toBeTruthy(); - let originalUris = content.map((c) => c.originalManifestUri); + const originalUris = content.map((c) => c.originalManifestUri); expect(originalUris).toBeTruthy(); expect(originalUris.length).toBe(3); @@ -748,8 +752,8 @@ describe('Storage', function() { it('only stores chosen tracks', checkAndRun(async function() { // Change storage to only store one track so that it will be easy // for use to ensure that only the one track was stored. - let selectTrack = (tracks) => { - let selected = tracks.filter((t) => t.language == frenchCanadian); + const selectTrack = (tracks) => { + const selected = tracks.filter((t) => t.language == frenchCanadian); expect(selected.length).toBe(1); return selected; }; @@ -761,7 +765,7 @@ describe('Storage', function() { // Stored content should reflect the tracks in the first period, so we // should only find track there. - let stored = await storage.store( + const stored = await storage.store( manifestWithPerStreamBandwidthUri, noMetadata, FakeManifestParser); expect(stored).toBeTruthy(); expect(stored.tracks).toBeTruthy(); @@ -771,7 +775,7 @@ describe('Storage', function() { // Pull the manifest out of storage so that we can ensure that it only // has one variant. /** @type {shaka.offline.OfflineUri} */ - let uri = shaka.offline.OfflineUri.parse(stored.offlineUri); + const uri = shaka.offline.OfflineUri.parse(stored.offlineUri); expect(uri).toBeTruthy(); /** @type {!shaka.offline.StorageMuxer} */ @@ -779,23 +783,23 @@ describe('Storage', function() { try { await muxer.init(); - let cell = await muxer.getCell(uri.mechanism(), uri.cell()); - let manifests = await cell.getManifests([uri.key()]); + const cell = await muxer.getCell(uri.mechanism(), uri.cell()); + const manifests = await cell.getManifests([uri.key()]); expect(manifests).toBeTruthy(); expect(manifests.length).toBe(1); - let manifest = manifests[0]; + const manifest = manifests[0]; expect(manifest).toBeTruthy(); expect(manifest.periods).toBeTruthy(); expect(manifest.periods.length).toBe(1); - let period = manifest.periods[0]; + const period = manifest.periods[0]; expect(period).toBeTruthy(); expect(period.streams).toBeTruthy(); // There should be 2 streams, an audio and a video stream. expect(period.streams.length).toBe(2); - let audio = period.streams.filter((s) => s.contentType == 'audio')[0]; + const audio = period.streams.filter((s) => s.contentType == 'audio')[0]; expect(audio).toBeTruthy(); expect(audio.language).toBe(frenchCanadian); } finally { @@ -811,7 +815,7 @@ describe('Storage', function() { // TODO(vaage): Is there a way we can set the session ids without needing // to overload an internal call in storage. - let drm = new shaka.test.FakeDrmEngine(); + const drm = new shaka.test.FakeDrmEngine(); drm.setDrmInfo(drmInfo); drm.setSessionIds([session1, session2]); drm.getExpiration.and.returnValue(expiration); @@ -821,10 +825,10 @@ describe('Storage', function() { drm, makeManifestWithPerStreamBandwidth()); - let stored = await storage.store(manifestWithPerStreamBandwidthUri); + const stored = await storage.store(manifestWithPerStreamBandwidthUri); /** @type {shaka.offline.OfflineUri} */ - let uri = shaka.offline.OfflineUri.parse(stored.offlineUri); + const uri = shaka.offline.OfflineUri.parse(stored.offlineUri); expect(uri).toBeTruthy(); /** @type {!shaka.offline.StorageMuxer} */ @@ -832,9 +836,9 @@ describe('Storage', function() { try { await muxer.init(); - let cell = await muxer.getCell(uri.mechanism(), uri.cell()); - let manifests = await cell.getManifests([uri.key()]); - let manifest = manifests[0]; + const cell = await muxer.getCell(uri.mechanism(), uri.cell()); + const manifests = await cell.getManifests([uri.key()]); + const manifest = manifests[0]; expect(manifest).toBeTruthy(); expect(manifest.drmInfo).toEqual(drmInfo); @@ -860,7 +864,7 @@ describe('Storage', function() { // TODO(vaage): Is there a way we can set the session ids without // needing to overload an internal call in storage. - let drm = new shaka.test.FakeDrmEngine(); + const drm = new shaka.test.FakeDrmEngine(); drm.setDrmInfo(drmInfo); drm.setSessionIds([session1, session2]); @@ -872,10 +876,10 @@ describe('Storage', function() { usePersistentLicense: false, }); - let stored = await storage.store(manifestWithPerStreamBandwidthUri); + const stored = await storage.store(manifestWithPerStreamBandwidthUri); /** @type {shaka.offline.OfflineUri} */ - let uri = shaka.offline.OfflineUri.parse(stored.offlineUri); + const uri = shaka.offline.OfflineUri.parse(stored.offlineUri); expect(uri).toBeTruthy(); /** @type {!shaka.offline.StorageMuxer} */ @@ -883,9 +887,9 @@ describe('Storage', function() { try { await muxer.init(); - let cell = await muxer.getCell(uri.mechanism(), uri.cell()); - let manifests = await cell.getManifests([uri.key()]); - let manifest = manifests[0]; + const cell = await muxer.getCell(uri.mechanism(), uri.cell()); + const manifests = await cell.getManifests([uri.key()]); + const manifest = manifests[0]; expect(manifest).toBeTruthy(); expect(manifest.drmInfo).toEqual(drmInfo); @@ -906,9 +910,9 @@ describe('Storage', function() { checkAndRun(async function() { // Block the network so that we won't finish the first store command. /** @type {!shaka.util.PublicPromise} */ - let hangingPromise = netEngine.delayNextRequest(); + const hangingPromise = netEngine.delayNextRequest(); /** @type {!Promise} */ - let storePromise = storage.store( + const storePromise = storage.store( manifestWithPerStreamBandwidthUri, noMetadata, FakeManifestParser); @@ -949,7 +953,7 @@ describe('Storage', function() { // TODO(vaage): Is there a way we can set the session ids without // needing to overload an internal call in storage. - let drm = new shaka.test.FakeDrmEngine(); + const drm = new shaka.test.FakeDrmEngine(); drm.setDrmInfo(drmInfo); drm.setSessionIds(noSessions); @@ -1034,12 +1038,12 @@ describe('Storage', function() { checkAndRun(async function() { // Store a piece of content, but then change the uri slightly so that // it won't be found when we try to remove it (with the wrong uri). - let stored = await storage.store( + const stored = await storage.store( manifestWithPerStreamBandwidthUri, noMetadata, FakeManifestParser); - let storedUri = shaka.offline.OfflineUri.parse(stored.offlineUri); - let missingManifestUri = shaka.offline.OfflineUri.manifest( + const storedUri = shaka.offline.OfflineUri.parse(stored.offlineUri); + const missingManifestUri = shaka.offline.OfflineUri.manifest( storedUri.mechanism(), storedUri.cell(), storedUri.key() + 1); try { @@ -1051,18 +1055,18 @@ describe('Storage', function() { })); it('removes manifest', checkAndRun(async function() { - let stored = await storage.store( + const stored = await storage.store( manifestWithPerStreamBandwidthUri, noMetadata, FakeManifestParser); await storage.remove(stored.offlineUri); })); it('removes manifest with missing segments', checkAndRun(async function() { - let stored = await storage.store( + const stored = await storage.store( manifestWithPerStreamBandwidthUri, noMetadata, FakeManifestParser); /** @type {shaka.offline.OfflineUri} */ - let uri = shaka.offline.OfflineUri.parse(stored.offlineUri); + const uri = shaka.offline.OfflineUri.parse(stored.offlineUri); expect(uri).toBeTruthy(); /** @type {!shaka.offline.StorageMuxer} */ @@ -1070,19 +1074,19 @@ describe('Storage', function() { try { await muxer.init(); - let cell = await muxer.getCell(uri.mechanism(), uri.cell()); - let manifests = await cell.getManifests([uri.key()]); - let manifest = manifests[0]; + const cell = await muxer.getCell(uri.mechanism(), uri.cell()); + const manifests = await cell.getManifests([uri.key()]); + const manifest = manifests[0]; // Get the stream from the manifest. The segment count is based on how // we created manifest in the "make*Manifest" functions. - let stream = manifest.periods[0].streams[0]; + const stream = manifest.periods[0].streams[0]; expect(stream).toBeTruthy(); expect(stream.segments.length).toBe(4); // Remove all the segments so that all segments will be missing. // There should be way more than one segment. - let keys = stream.segments.map((segment) => segment.dataKey); + const keys = stream.segments.map((segment) => segment.dataKey); expect(keys.length).toBeGreaterThan(0); const noop = () => {}; @@ -1095,14 +1099,14 @@ describe('Storage', function() { })); it('tracks progress on remove', checkAndRun(async function() { - let selectOneTrack = (tracks) => { - let allVariants = tracks.filter((t) => { + const selectOneTrack = (tracks) => { + const allVariants = tracks.filter((t) => { return t.type == 'variant'; }); expect(allVariants).toBeTruthy(); expect(allVariants.length).toBeGreaterThan(0); - let frenchVariants = allVariants.filter((t) => { + const frenchVariants = allVariants.filter((t) => { return t.language == frenchCanadian; }); expect(frenchVariants).toBeTruthy(); @@ -1118,7 +1122,7 @@ describe('Storage', function() { trackSelectionCallback: selectOneTrack, }, }); - let content = await storage.store( + const content = await storage.store( manifestWithPerStreamBandwidthUri, noMetadata, FakeManifestParser); @@ -1126,11 +1130,11 @@ describe('Storage', function() { /** * @type {!Array.<number>} */ - let progressSteps = [ + const progressSteps = [ 0.111, 0.222, 0.333, 0.444, 0.555, 0.666, 0.777, 0.888, 1.0, ]; - let progressCallback = (content, progress) => { + const progressCallback = (content, progress) => { expect(progress).toBeCloseTo(progressSteps.shift()); }; @@ -1249,7 +1253,7 @@ describe('Storage', function() { function makeManifestWithPerStreamBandwidth() { const SegmentReference = shaka.media.SegmentReference; - let manifest = new shaka.test.ManifestGenerator() + const manifest = new shaka.test.ManifestGenerator() .setPresentationDuration(20) .addPeriod(0) .addVariant(0).language(englishUS).bandwidth(13 * kbps) @@ -1263,7 +1267,7 @@ describe('Storage', function() { getAllStreams(manifest).forEach((stream) => { // Make a new copy each time as the segment index can modify // each reference. - let refs = [ + const refs = [ new SegmentReference(0, 0, 1, uris(segment1Uri), 0, null), new SegmentReference(1, 1, 2, uris(segment2Uri), 0, null), new SegmentReference(2, 2, 3, uris(segment3Uri), 0, null), @@ -1280,7 +1284,7 @@ describe('Storage', function() { * @return {shaka.extern.Manifest} */ function makeManifestWithoutPerStreamBandwidth() { - let manifest = makeManifestWithPerStreamBandwidth(); + const manifest = makeManifestWithPerStreamBandwidth(); // Remove the per stream bandwidth. getAllStreams(manifest).forEach((stream) => { @@ -1296,10 +1300,10 @@ describe('Storage', function() { function makeManifestWithNonZeroStart() { const SegmentReference = shaka.media.SegmentReference; - let manifest = makeManifestWithPerStreamBandwidth(); + const manifest = makeManifestWithPerStreamBandwidth(); getAllStreams(manifest).forEach((stream) => { - let refs = [ + const refs = [ new SegmentReference(0, 10, 11, uris(segment1Uri), 0, null), new SegmentReference(1, 11, 12, uris(segment2Uri), 0, null), new SegmentReference(2, 12, 13, uris(segment3Uri), 0, null), @@ -1316,7 +1320,7 @@ describe('Storage', function() { * @return {shaka.extern.Manifest} */ function makeManifestWithLiveTimeline() { - let manifest = makeManifestWithPerStreamBandwidth(); + const manifest = makeManifestWithPerStreamBandwidth(); manifest.presentationTimeline.setDuration(Infinity); manifest.presentationTimeline.setStatic(false); return manifest; @@ -1327,7 +1331,7 @@ describe('Storage', function() { * @return {!Array.<shaka.extern.Stream>} */ function getAllStreams(manifest) { - let streams = []; + const streams = []; manifest.periods.forEach((period) => { period.variants.forEach((variant) => { @@ -1347,7 +1351,7 @@ describe('Storage', function() { * @param {!Array.<shaka.media.SegmentReference>} segments */ function overrideSegmentIndex(stream, segments) { - let index = new shaka.media.SegmentIndex(segments); + const index = new shaka.media.SegmentIndex(segments); stream.findSegmentPosition = (time) => index.find(time); stream.getSegmentReference = (time) => index.get(time); } @@ -1386,7 +1390,7 @@ describe('Storage', function() { * @return {shaka.extern.DrmInfo} */ function makeDrmInfo() { - let drmInfo = { + const drmInfo = { keySystem: 'com.example.abc', licenseServerUri: 'http://example.com', persistentStateRequired: true, @@ -1403,7 +1407,7 @@ describe('Storage', function() { // TODO(vaage): Replace this with |shaka.test.FakeManifestParser| /** @implements {shaka.extern.ManifestParser} */ - let FakeManifestParser = class { + const FakeManifestParser = class { constructor() { this.map_ = {}; this.map_[manifestWithPerStreamBandwidthUri] = @@ -1516,7 +1520,7 @@ describe('Storage', function() { */ function checkAndRun(test) { return async () => { - let hasSupport = shaka.offline.Storage.support(); + const hasSupport = shaka.offline.Storage.support(); if (hasSupport) { await test(); } else { @@ -1534,10 +1538,10 @@ describe('Storage', function() { */ function drmCheckAndRun(test) { return async () => { - let support = await shaka.Player.probeSupport(); + const support = await shaka.Player.probeSupport(); - let widevineSupport = support.drm['com.widevine.alpha']; - let storageSupport = shaka.offline.Storage.support(); + const widevineSupport = support.drm['com.widevine.alpha']; + const storageSupport = shaka.offline.Storage.support(); if (!widevineSupport) { pending('Widevine is not supported on this platform'); diff --git a/test/offline/v1_indexeddb_storage_unit.js b/test/offline/v1_indexeddb_storage_unit.js index 6b74353bcf..24a4419d3d 100644 --- a/test/offline/v1_indexeddb_storage_unit.js +++ b/test/offline/v1_indexeddb_storage_unit.js @@ -33,7 +33,7 @@ describe('V1IndexeddbStorageCell', function() { let connections = []; beforeAll(async function() { - let data = await shaka.test.Util.fetch(dbImagePath); + const data = await shaka.test.Util.fetch(dbImagePath); dbImageAsString = shaka.util.StringUtils.fromUTF8(data); }); @@ -55,12 +55,12 @@ describe('V1IndexeddbStorageCell', function() { const expectedErrorCode = shaka.util.Error.Code.NEW_KEY_OPERATION_NOT_SUPPORTED; - let connection = await makeConnection(); - let cell = makeCell(connection); + const connection = await makeConnection(); + const cell = makeCell(connection); // There should be one manifest. - let manifests = await cell.getAllManifests(); - let manifest = manifests.get(0); + const manifests = await cell.getAllManifests(); + const manifest = manifests.get(0); expect(manifest).toBeTruthy(); // Make sure that the request fails. @@ -76,11 +76,11 @@ describe('V1IndexeddbStorageCell', function() { const expectedErrorCode = shaka.util.Error.Code.NEW_KEY_OPERATION_NOT_SUPPORTED; - let connection = await makeConnection(); - let cell = makeCell(connection); + const connection = await makeConnection(); + const cell = makeCell(connection); // Update the key to what should be a free key. - let segment = {data: new ArrayBuffer(16)}; + const segment = {data: new ArrayBuffer(16)}; // Make sure that the request fails. try { @@ -92,30 +92,30 @@ describe('V1IndexeddbStorageCell', function() { })); it('can get all manifests', checkAndRun(async function() { - let connection = await makeConnection(); - let cell = makeCell(connection); + const connection = await makeConnection(); + const cell = makeCell(connection); // There should be one manifest. - let map = await cell.getAllManifests(); + const map = await cell.getAllManifests(); expect(map).toBeTruthy(); expect(map.size).toBe(1); expect(map.get(0)).toBeTruthy(); })); it('can get manifest and all segments', checkAndRun(async function() { - let connection = await makeConnection(); - let cell = makeCell(connection); + const connection = await makeConnection(); + const cell = makeCell(connection); // There should be one manifest. - let manifests = await cell.getManifests([0]); - let manifest = manifests[0]; + const manifests = await cell.getManifests([0]); + const manifest = manifests[0]; expect(manifest).toBeTruthy(); // Collect all the keys for each segment. - let dataKeys = getAllSegmentKeys(manifest); + const dataKeys = getAllSegmentKeys(manifest); // Check that each segment was successfully retrieved. - let segmentData = await cell.getSegments(dataKeys); + const segmentData = await cell.getSegments(dataKeys); expect(segmentData).toBeTruthy(); expect(segmentData.length).toBe(6); segmentData.forEach((segment) => { @@ -129,25 +129,25 @@ describe('V1IndexeddbStorageCell', function() { const oldExpiration = Infinity; const newExpiration = 1000; - let connection = await makeConnection(); - let cell = makeCell(connection); + const connection = await makeConnection(); + const cell = makeCell(connection); - let original = await cell.getManifests([manifestKey]); + const original = await cell.getManifests([manifestKey]); expect(original).toBeTruthy(); expect(original[0]).toBeTruthy(); expect(original[0].expiration).toBe(oldExpiration); await cell.updateManifestExpiration(manifestKey, newExpiration); - let updated = await cell.getManifests([manifestKey]); + const updated = await cell.getManifests([manifestKey]); expect(updated).toBeTruthy(); expect(updated[0]).toBeTruthy(); expect(updated[0].expiration).toBe(newExpiration); })); it('can remove manifests and segments', checkAndRun(async function() { - let connection = await makeConnection(); - let cell = makeCell(connection); + const connection = await makeConnection(); + const cell = makeCell(connection); /** @type {!Array.<number>} */ const manifestKeys = []; @@ -171,7 +171,7 @@ describe('V1IndexeddbStorageCell', function() { await cell.removeManifests(manifestKeys, noop); await cell.removeSegments(segmentKeys, noop); - let checkMissingSegment = async (key) => { + const checkMissingSegment = async (key) => { try { await cell.getSegments([key]); fail(); @@ -180,7 +180,7 @@ describe('V1IndexeddbStorageCell', function() { } }; - let checkMissingManifest = async (key) => { + const checkMissingManifest = async (key) => { try { await cell.getManifests([key]); fail(); @@ -191,10 +191,10 @@ describe('V1IndexeddbStorageCell', function() { // Need to check each key on its own to ensure that each key is missing // and not just one of the keys is missing. - let checkMissingSegments = (keys) => { + const checkMissingSegments = (keys) => { return Promise.all(keys.map((key) => checkMissingSegment(key))); }; - let checkMissingManifests = (keys) => { + const checkMissingManifests = (keys) => { return Promise.all(keys.map((key) => checkMissingManifest(key))); }; @@ -209,7 +209,7 @@ describe('V1IndexeddbStorageCell', function() { * @return {!Array.<number>} */ function getAllSegmentKeys(manifest) { - let keys = []; + const keys = []; manifest.periods.forEach((period) => { period.streams.forEach((stream) => { @@ -235,7 +235,7 @@ describe('V1IndexeddbStorageCell', function() { await CannedIDB.restoreJSON(dbName, dbImageAsString, startFromScratch); // Track the connection so that we can close it when the test is over. - let connection = await shaka.test.IndexedDBUtils.open(dbName); + const connection = await shaka.test.IndexedDBUtils.open(dbName); connections.push(connection); return connection; } @@ -245,7 +245,7 @@ describe('V1IndexeddbStorageCell', function() { * @return {shaka.extern.StorageCell} */ function makeCell(connection) { - let cell = new shaka.offline.indexeddb.V1StorageCell( + const cell = new shaka.offline.indexeddb.V1StorageCell( connection, segmentStore, manifestStore); diff --git a/test/player_external.js b/test/player_external.js index 9304b29559..4e53ab253d 100644 --- a/test/player_external.js +++ b/test/player_external.js @@ -84,10 +84,10 @@ describe('Player', () => { function createAssetTest(asset) { if (asset.disabled) return; - let testName = + const testName = asset.source + ' / ' + asset.name + ' : ' + asset.manifestUri; - let wit = asset.focus ? fit : it; + const wit = asset.focus ? fit : it; wit(testName, async () => { if (asset.drm.length && !asset.drm.some((keySystem) => support.drm[keySystem])) { @@ -95,7 +95,7 @@ describe('Player', () => { } if (asset.features) { - let mimeTypes = []; + const mimeTypes = []; if (asset.features.includes(Feature.WEBM)) { mimeTypes.push('video/webm'); } @@ -218,7 +218,7 @@ describe('Player', () => { /* manifestUri= */ testCustomAsset, /* source= */ shakaAssets.Source.CUSTOM); if (keySystems.length) { - for (let keySystem of keySystems) { + for (const keySystem of keySystems) { asset.addKeySystem(/** @type {!shakaAssets.KeySystem} */ (keySystem)); const licenseServer = licenseServers[keySystem]; if (licenseServer) { @@ -260,7 +260,7 @@ describe('Player', () => { // Add these to the existing headers. Do not clobber them! // For PlayReady, there will already be headers in the request. - for (let k in headers) { + for (const k in headers) { request.headers[k] = headers[k]; } } diff --git a/test/player_integration.js b/test/player_integration.js index 314ae8ce59..bfea0a4200 100644 --- a/test/player_integration.js +++ b/test/player_integration.js @@ -84,8 +84,8 @@ describe('Player', function() { video.play(); await waitUntilPlayheadReaches(eventManager, video, 1, 10); - let stats = player.getStats(); - let expected = { + const stats = player.getStats(); + const expected = { width: jasmine.any(Number), height: jasmine.any(Number), streamBandwidth: jasmine.any(Number), @@ -130,7 +130,7 @@ describe('Player', function() { // This TextTrack was created as part of load() when we set up the // TextDisplayer. - let textTrack = video.textTracks[0]; + const textTrack = video.textTracks[0]; expect(textTrack).not.toBe(null); if (textTrack) { @@ -258,13 +258,13 @@ describe('Player', function() { // For some reason, using path-absolute URLs (i.e. without the hostname) // like this doesn't work on Safari. So manually resolve the URL. - let locationUri = new goog.Uri(location.href); - let partialUri = new goog.Uri('/base/test/test/assets/text-clip.vtt'); - let absoluteUri = locationUri.resolve(partialUri); + const locationUri = new goog.Uri(location.href); + const partialUri = new goog.Uri('/base/test/test/assets/text-clip.vtt'); + const absoluteUri = locationUri.resolve(partialUri); await player.addTextTrack(absoluteUri.toString(), 'en', 'subtitles', 'text/vtt'); - let textTracks = player.getTextTracks(); + const textTracks = player.getTextTracks(); expect(textTracks).toBeTruthy(); expect(textTracks.length).toBe(1); @@ -294,7 +294,7 @@ describe('Player', function() { expect(video.currentTime).toBeLessThan(9); // The two periods might not be in a single contiguous buffer, so don't // check end(0). Gap-jumping will deal with any discontinuities. - let bufferEnd = video.buffered.end(video.buffered.length - 1); + const bufferEnd = video.buffered.end(video.buffered.length - 1); expect(bufferEnd).toBeGreaterThan(11); // Change to a different language; this should clear the buffers and @@ -313,7 +313,7 @@ describe('Player', function() { * @return {string} */ function getActiveLanguage() { - let tracks = player.getVariantTracks().filter(function(t) { + const tracks = player.getVariantTracks().filter(function(t) { return t.active; }); expect(tracks.length).toBeGreaterThan(0); @@ -359,7 +359,7 @@ describe('Player', function() { // properly exported from the player. it('exports language and roles fields', async () => { await player.load('test:sintel_compiled'); - let languagesAndRoles = player.getTextLanguagesAndRoles(); + const languagesAndRoles = player.getTextLanguagesAndRoles(); expect(languagesAndRoles.length).toBeTruthy(); languagesAndRoles.forEach((languageAndRole) => { expect(languageAndRole.language).not.toBeUndefined(); diff --git a/test/player_unit.js b/test/player_unit.js index f901f1d898..0cc6ae8f0b 100644 --- a/test/player_unit.js +++ b/test/player_unit.js @@ -80,7 +80,7 @@ describe('Player', function() { // fail assertions based on browser support for types. Pretend that all // video and audio types are supported. window.MediaSource.isTypeSupported = function(mimeType) { - let type = mimeType.split('/')[0]; + const type = mimeType.split('/')[0]; return type == 'video' || type == 'audio'; }; @@ -161,8 +161,8 @@ describe('Player', function() { describe('destroy', function() { it('cleans up all dependencies', async () => { goog.asserts.assert(manifest, 'Manifest should be non-null'); - let parser = new shaka.test.FakeManifestParser(manifest); - let factory = function() { return parser; }; + const parser = new shaka.test.FakeManifestParser(manifest); + const factory = function() { return parser; }; await player.load(fakeManifestUri, 0, factory); await player.destroy(); @@ -177,8 +177,8 @@ describe('Player', function() { it('destroys mediaSourceEngine before drmEngine', async () => { goog.asserts.assert(manifest, 'Manifest should be non-null'); - let parser = new shaka.test.FakeManifestParser(manifest); - let factory = function() { return parser; }; + const parser = new shaka.test.FakeManifestParser(manifest); + const factory = function() { return parser; }; mediaSourceEngine.destroy.and.callFake(() => { expect(drmEngine.destroy).not.toHaveBeenCalled(); @@ -197,14 +197,14 @@ describe('Player', function() { // TODO(vaage): Re-enable once the parser is integrated into the load graph // better. xit('destroys parser first when interrupting load', function(done) { - let p = shaka.test.Util.delay(0.3); - let parser = new shaka.test.FakeManifestParser(manifest); + const p = shaka.test.Util.delay(0.3); + const parser = new shaka.test.FakeManifestParser(manifest); parser.start.and.returnValue(p); parser.stop.and.callFake(function() { expect(abrManager.stop).not.toHaveBeenCalled(); expect(networkingEngine.destroy).not.toHaveBeenCalled(); }); - let factory = function() { return parser; }; + const factory = function() { return parser; }; player.load(fakeManifestUri, 0, factory).then(fail).catch(() => {}); shaka.test.Util.delay(0.1).then(function() { @@ -344,9 +344,9 @@ describe('Player', function() { describe('getConfiguration', function() { it('returns a copy of the configuration', function() { - let config1 = player.getConfiguration(); + const config1 = player.getConfiguration(); config1.streaming.bufferBehind = -99; - let config2 = player.getConfiguration(); + const config2 = player.getConfiguration(); expect(config1.streaming.bufferBehind).not.toEqual( config2.streaming.bufferBehind); }); @@ -354,7 +354,7 @@ describe('Player', function() { describe('configure', function() { it('overwrites defaults', function() { - let defaultConfig = player.getConfiguration(); + const defaultConfig = player.getConfiguration(); // Make sure the default differs from our test value: expect(defaultConfig.drm.retryParameters.backoffFactor).not.toBe(5); expect(defaultConfig.manifest.retryParameters.backoffFactor).not.toBe(5); @@ -365,7 +365,7 @@ describe('Player', function() { }, }); - let newConfig = player.getConfiguration(); + const newConfig = player.getConfiguration(); // Make sure we changed the backoff for DRM, but not for manifests: expect(newConfig.drm.retryParameters.backoffFactor).toBe(5); expect(newConfig.manifest.retryParameters.backoffFactor).not.toBe(5); @@ -400,7 +400,7 @@ describe('Player', function() { it('restricts the types of config values', function() { logErrorSpy.and.stub(); - let defaultConfig = player.getConfiguration(); + const defaultConfig = player.getConfiguration(); // Try a bogus bufferBehind (string instead of number) player.configure({ @@ -468,7 +468,7 @@ describe('Player', function() { 'ks1': jasmine.objectContaining({distinctiveIdentifierRequired: true}), }); expect(logErrorSpy).not.toHaveBeenCalled(); - let lastGoodConfig = newConfig; + const lastGoodConfig = newConfig; // Try an invalid advanced config key. player.configure({ @@ -515,9 +515,9 @@ describe('Player', function() { }); it('checks the number of arguments to functions', function() { - let goodCustomScheme = function(node) {}; - let badCustomScheme1 = function() {}; // too few args - let badCustomScheme2 = function(x, y) {}; // too many args + const goodCustomScheme = function(node) {}; + const badCustomScheme1 = function() {}; // too few args + const badCustomScheme2 = function(x, y) {}; // too many args // Takes good callback. player.configure({ @@ -628,7 +628,7 @@ describe('Player', function() { it('configures play and seek range for VOD', async () => { player.configure({playRangeStart: 5, playRangeEnd: 10}); - let timeline = new shaka.media.PresentationTimeline(300, 0); + const timeline = new shaka.media.PresentationTimeline(300, 0); timeline.setStatic(true); manifest = new shaka.test.ManifestGenerator() .setTimeline(timeline) @@ -637,19 +637,19 @@ describe('Player', function() { .addVideo(1) .build(); goog.asserts.assert(manifest, 'manifest must be non-null'); - let parser = new shaka.test.FakeManifestParser(manifest); - let factory = function() { return parser; }; + const parser = new shaka.test.FakeManifestParser(manifest); + const factory = function() { return parser; }; await player.load(fakeManifestUri, 0, factory); - let seekRange = player.seekRange(); + const seekRange = player.seekRange(); expect(seekRange.start).toBe(5); expect(seekRange.end).toBe(10); }); it('does not switch for plain configuration changes', async () => { - let parser = new shaka.test.FakeManifestParser(manifest); - let factory = function() { return parser; }; + const parser = new shaka.test.FakeManifestParser(manifest); + const factory = function() { return parser; }; - let switchVariantSpy = spyOn(player, 'switchVariant_'); + const switchVariantSpy = spyOn(player, 'switchVariant_'); await player.load(fakeManifestUri, 0, factory); @@ -663,10 +663,10 @@ describe('Player', function() { }); it('accepts parameters in a (fieldName, value) format', function() { - let oldConfig = player.getConfiguration(); - let oldDelayLicense = oldConfig.drm.delayLicenseRequestUntilPlayed; - let oldSwitchInterval = oldConfig.abr.switchInterval; - let oldPreferredLang = oldConfig.preferredAudioLanguage; + const oldConfig = player.getConfiguration(); + const oldDelayLicense = oldConfig.drm.delayLicenseRequestUntilPlayed; + const oldSwitchInterval = oldConfig.abr.switchInterval; + const oldPreferredLang = oldConfig.preferredAudioLanguage; expect(oldDelayLicense).toBe(false); expect(oldSwitchInterval).toBe(8); @@ -676,10 +676,10 @@ describe('Player', function() { player.configure('abr.switchInterval', 10); player.configure('preferredAudioLanguage', 'fr'); - let newConfig = player.getConfiguration(); - let newDelayLicense = newConfig.drm.delayLicenseRequestUntilPlayed; - let newSwitchInterval = newConfig.abr.switchInterval; - let newPreferredLang = newConfig.preferredAudioLanguage; + const newConfig = player.getConfiguration(); + const newDelayLicense = newConfig.drm.delayLicenseRequestUntilPlayed; + const newSwitchInterval = newConfig.abr.switchInterval; + const newPreferredLang = newConfig.preferredAudioLanguage; expect(newDelayLicense).toBe(true); expect(newSwitchInterval).toBe(10); @@ -718,13 +718,13 @@ describe('Player', function() { it('still sets other fields when there are errors', function() { logErrorSpy.and.stub(); - let changes = { + const changes = { manifest: {foobar: false}, streaming: {bufferBehind: 77}, }; expect(player.configure(changes)).toBe(false); - let newConfig = player.getConfiguration(); + const newConfig = player.getConfiguration(); expect(newConfig.streaming.bufferBehind).toEqual(77); }); @@ -886,14 +886,14 @@ describe('Player', function() { .addVideo(8) .build(); - let variantTracks1 = [ + const variantTracks1 = [ jasmine.objectContaining({ id: 11, active: true, type: 'variant', }), ]; - let variantTracks2 = [ + const variantTracks2 = [ jasmine.objectContaining({ id: 22, active: false, @@ -901,18 +901,18 @@ describe('Player', function() { }), ]; - let parser = new shaka.test.FakeManifestParser(manifest); - let parserFactory = function() { return parser; }; + const parser = new shaka.test.FakeManifestParser(manifest); + const parserFactory = function() { return parser; }; player.load(fakeManifestUri, 0, parserFactory).catch(fail).then(() => { // Check the first period's variant tracks. - let actualVariantTracks1 = player.getVariantTracks(); + const actualVariantTracks1 = player.getVariantTracks(); expect(actualVariantTracks1).toEqual(variantTracks1); // Check the second period's variant tracks. playhead.getTime.and.callFake(function() { return 100; }); - let actualVariantTracks2 = player.getVariantTracks(); + const actualVariantTracks2 = player.getVariantTracks(); expect(actualVariantTracks2).toEqual(variantTracks2); }).then(done); }); @@ -1312,8 +1312,8 @@ describe('Player', function() { ]; goog.asserts.assert(manifest, 'manifest must be non-null'); - let parser = new shaka.test.FakeManifestParser(manifest); - let parserFactory = function() { return parser; }; + const parser = new shaka.test.FakeManifestParser(manifest); + const parserFactory = function() { return parser; }; // Language/channel prefs must be set before load. Used in // select*Language() tests. @@ -1334,8 +1334,8 @@ describe('Player', function() { }); it('returns empty arrays before tracks can be determined', async () => { - let parser = new shaka.test.FakeManifestParser(manifest); - let parserFactory = function() { return parser; }; + const parser = new shaka.test.FakeManifestParser(manifest); + const parserFactory = function() { return parser; }; parser.start.and.callFake(function(manifestUri, playerInterface) { // The player does not yet have a manifest. expect(player.getVariantTracks()).toEqual([]); @@ -1703,8 +1703,8 @@ describe('Player', function() { expect(player.isTextTrackVisible()).toBe(false); - let parser = new shaka.test.FakeManifestParser(manifest); - let factory = function() { return parser; }; + const parser = new shaka.test.FakeManifestParser(manifest); + const factory = function() { return parser; }; await player.load(fakeManifestUri, 0, factory); // Text was turned on during startup. @@ -1734,15 +1734,15 @@ describe('Player', function() { preferredAudioLanguage: undefined, }); - let parser = new shaka.test.FakeManifestParser(manifest); - let parserFactory = function() { return parser; }; + const parser = new shaka.test.FakeManifestParser(manifest); + const parserFactory = function() { return parser; }; await player.load(fakeManifestUri, 0, parserFactory); expect(abrManager.setVariants).toHaveBeenCalled(); // If we have chosen any arbitrary language, setVariants is provided // with exactly one variant. - let variants = abrManager.setVariants.calls.argsFor(0)[0]; + const variants = abrManager.setVariants.calls.argsFor(0)[0]; expect(variants.length).toBe(1); }); @@ -1753,10 +1753,10 @@ describe('Player', function() { * @return {!Promise} */ function runTest(languages, preference, expectedIndex) { - let generator = new shaka.test.ManifestGenerator().addPeriod(0); + const generator = new shaka.test.ManifestGenerator().addPeriod(0); for (let i = 0; i < languages.length; i++) { - let lang = languages[i]; + const lang = languages[i]; if (lang.charAt(0) == '*') { generator .addVariant(i) @@ -1775,8 +1775,8 @@ describe('Player', function() { preferredAudioLanguage: preference, }); - let parser = new shaka.test.FakeManifestParser(manifest); - let factory = function() { return parser; }; + const parser = new shaka.test.FakeManifestParser(manifest); + const factory = function() { return parser; }; return player.load(fakeManifestUri, 0, factory).then(function() { expect(getActiveVariantTrack().id).toBe(expectedIndex); }); @@ -1815,8 +1815,8 @@ describe('Player', function() { .addExistingStream(3) // video .build(); - let parser = new shaka.test.FakeManifestParser(manifest); - let parserFactory = function() { return parser; }; + const parser = new shaka.test.FakeManifestParser(manifest); + const parserFactory = function() { return parser; }; await player.load(fakeManifestUri, 0, parserFactory); // Initialize the fake streams. @@ -1829,12 +1829,12 @@ describe('Player', function() { it('tracks estimated bandwidth', function() { abrManager.getBandwidthEstimate.and.returnValue(25); - let stats = player.getStats(); + const stats = player.getStats(); expect(stats.estimatedBandwidth).toBe(25); }); it('tracks info about current stream', function() { - let stats = player.getStats(); + const stats = player.getStats(); // Should have chosen the first of each type of stream. expect(stats.width).toBe(100); expect(stats.height).toBe(200); @@ -1901,7 +1901,7 @@ describe('Player', function() { forceBufferingTo(false); jasmine.clock().tick(1000); - let stats = player.getStats(); + const stats = player.getStats(); expect(stats.playTime).toBeCloseTo(4); expect(stats.bufferingTime).toBeCloseTo(14); }); @@ -1932,7 +1932,7 @@ describe('Player', function() { }); it('includes adaptation choices', function() { - let variant = manifest.periods[0].variants[3]; + const variant = manifest.periods[0].variants[3]; switch_(variant); checkHistory(jasmine.arrayContaining([ @@ -1951,7 +1951,7 @@ describe('Player', function() { * @param {!Array.<shaka.extern.TrackChoice>} additional */ function checkHistory(additional) { - let prefix = { + const prefix = { timestamp: jasmine.any(Number), id: 0, type: 'variant', @@ -1959,7 +1959,7 @@ describe('Player', function() { bandwidth: 200, }; - let switchHistory = player.getStats().switchHistory; + const switchHistory = player.getStats().switchHistory; expect(switchHistory[0]).toEqual(prefix); expect(switchHistory.slice(1)).toEqual(additional); @@ -2108,8 +2108,8 @@ describe('Player', function() { .addVariant(0) .addVideo(0).mime('video/mp4', 'good') .build(); - let parser = new shaka.test.FakeManifestParser(manifest); - let factory = function() { return parser; }; + const parser = new shaka.test.FakeManifestParser(manifest); + const factory = function() { return parser; }; await player.load(fakeManifestUri, 0, factory); }); @@ -2122,8 +2122,8 @@ describe('Player', function() { .addVariant(1) .addVideo(1).mime('video/mp4', 'good') .build(); - let parser = new shaka.test.FakeManifestParser(manifest); - let factory = function() { return parser; }; + const parser = new shaka.test.FakeManifestParser(manifest); + const factory = function() { return parser; }; await player.load(fakeManifestUri, 0, factory); }); @@ -2136,8 +2136,8 @@ describe('Player', function() { .addVariant(1).bandwidth(500) .addVideo(1).mime('video/mp4', 'bad') .build(); - let parser = new shaka.test.FakeManifestParser(manifest); - let factory = function() { return parser; }; + const parser = new shaka.test.FakeManifestParser(manifest); + const factory = function() { return parser; }; try { await player.load(fakeManifestUri, 0, factory); fail(); @@ -2158,8 +2158,8 @@ describe('Player', function() { .addVariant(0).bandwidth(500) .addVideo(0).mime('video/mp4', 'bad') .build(); - let parser = new shaka.test.FakeManifestParser(manifest); - let factory = function() { return parser; }; + const parser = new shaka.test.FakeManifestParser(manifest); + const factory = function() { return parser; }; try { await player.load(fakeManifestUri, 0, factory); fail(); @@ -2186,8 +2186,8 @@ describe('Player', function() { .addVideo(2).mime('video/mp4', 'bad') .build(); - let parser = new shaka.test.FakeManifestParser(manifest); - let factory = function() { return parser; }; + const parser = new shaka.test.FakeManifestParser(manifest); + const factory = function() { return parser; }; try { await player.load(fakeManifestUri, 0, factory); fail(); @@ -2209,10 +2209,10 @@ describe('Player', function() { .addVariant(1).bandwidth(500) .addVideo(1).mime('video/mp4', 'good') .build(); - let parser = new shaka.test.FakeManifestParser(manifest); - let factory = function() { return parser; }; + const parser = new shaka.test.FakeManifestParser(manifest); + const factory = function() { return parser; }; player.load(fakeManifestUri, 0, factory).catch(fail).then(function() { - let manifest2 = new shaka.test.ManifestGenerator() + const manifest2 = new shaka.test.ManifestGenerator() .addPeriod(0) .addVariant(0).bandwidth(500) .addVideo(0).mime('video/mp4', 'bad') @@ -2393,7 +2393,7 @@ describe('Player', function() { onKeyStatus({'abc': 'output-restricted'}); - let tracks = player.getVariantTracks(); + const tracks = player.getVariantTracks(); expect(tracks.length).toBe(1); expect(tracks[0].id).toBe(1); }); @@ -2412,7 +2412,7 @@ describe('Player', function() { onKeyStatus({'abc': 'internal-error'}); - let tracks = player.getVariantTracks(); + const tracks = player.getVariantTracks(); expect(tracks.length).toBe(1); expect(tracks[0].id).toBe(1); }); @@ -2432,7 +2432,7 @@ describe('Player', function() { // We have some key statuses, but not for the key IDs we know. onKeyStatus({'foo': 'usable'}); - let tracks = player.getVariantTracks(); + const tracks = player.getVariantTracks(); expect(tracks.length).toBe(1); expect(tracks[0].id).toBe(2); }); @@ -2453,7 +2453,7 @@ describe('Player', function() { // when using PlayReady. See #1070. onKeyStatus({}); - let tracks = player.getVariantTracks(); + const tracks = player.getVariantTracks(); expect(tracks.length).toBe(2); }); @@ -2493,7 +2493,7 @@ describe('Player', function() { // A synthetic key status contains a single key status with key '00'. onKeyStatus({'00': 'internal-error'}); - let tracks = player.getVariantTracks(); + const tracks = player.getVariantTracks(); expect(tracks.length).toBe(1); expect(tracks[0].id).toBe(4); }); @@ -2519,7 +2519,7 @@ describe('Player', function() { }); await setupPlayer(); - let tracks = player.getVariantTracks(); + const tracks = player.getVariantTracks(); expect(tracks.length).toBe(1); expect(tracks[0].id).toBe(1); }); @@ -2540,7 +2540,7 @@ describe('Player', function() { player.configure({restrictions: {minBandwidth: 100, maxBandwidth: 1000}}); - let tracks = player.getVariantTracks(); + const tracks = player.getVariantTracks(); expect(tracks.length).toBe(1); expect(tracks[0].id).toBe(2); }); @@ -2561,7 +2561,7 @@ describe('Player', function() { player.configure({restrictions: {minPixels: 100, maxPixels: 800 * 800}}); - let tracks = player.getVariantTracks(); + const tracks = player.getVariantTracks(); expect(tracks.length).toBe(1); expect(tracks[0].id).toBe(2); }); @@ -2582,7 +2582,7 @@ describe('Player', function() { player.configure({restrictions: {minWidth: 100, maxWidth: 1000}}); - let tracks = player.getVariantTracks(); + const tracks = player.getVariantTracks(); expect(tracks.length).toBe(1); expect(tracks[0].id).toBe(2); }); @@ -2603,7 +2603,7 @@ describe('Player', function() { player.configure({restrictions: {minHeight: 100, maxHeight: 1000}}); - let tracks = player.getVariantTracks(); + const tracks = player.getVariantTracks(); expect(tracks.length).toBe(1); expect(tracks[0].id).toBe(2); }); @@ -2624,7 +2624,7 @@ describe('Player', function() { player.configure({restrictions: {minHeight: 100, maxHeight: 1000}}); - let tracks = player.getVariantTracks(); + const tracks = player.getVariantTracks(); expect(tracks.length).toBe(1); expect(tracks[0].id).toBe(1); }); @@ -2644,7 +2644,7 @@ describe('Player', function() { expect(player.getVariantTracks().length).toBe(3); onError.and.callFake(function(e) { - let error = e.detail; + const error = e.detail; shaka.test.Util.expectToEqualError( error, new shaka.util.Error( @@ -2682,7 +2682,7 @@ describe('Player', function() { await setupPlayer(); expect(abrManager.setVariants).toHaveBeenCalled(); - let variants = abrManager.setVariants.calls.argsFor(0)[0]; + const variants = abrManager.setVariants.calls.argsFor(0)[0]; // We've already chosen codecs, so only 3 tracks should remain. expect(variants.length).toBe(3); // They should be the low-bandwidth ones. @@ -2700,7 +2700,7 @@ describe('Player', function() { .addVideo(3) .build(); - let abrManager = new shaka.test.FakeAbrManager(); + const abrManager = new shaka.test.FakeAbrManager(); player.configure({abrFactory: function() { return abrManager; }}); setupPlayer().then(function() { expect(player.getVariantTracks().length).toBe(2); @@ -2710,7 +2710,7 @@ describe('Player', function() { onKeyStatus({'foo': 'usable'}); expect(abrManager.setVariants).toHaveBeenCalled(); - let variants = abrManager.setVariants.calls.argsFor(0)[0]; + const variants = abrManager.setVariants.calls.argsFor(0)[0]; expect(variants.length).toBe(1); expect(variants[0].id).toBe(2); }).catch(fail).then(done); @@ -2744,8 +2744,8 @@ describe('Player', function() { * @return {!Promise} */ function setupPlayer() { - let parser = new shaka.test.FakeManifestParser(manifest); - let parserFactory = function() { return parser; }; + const parser = new shaka.test.FakeManifestParser(manifest); + const parserFactory = function() { return parser; }; return player.load(fakeManifestUri, 0, parserFactory).then(function() { // Initialize the fake streams. streamingEngine.onCanSwitch(); @@ -2755,7 +2755,7 @@ describe('Player', function() { describe('getPlayheadTimeAsDate()', function() { beforeEach(async () => { - let timeline = new shaka.media.PresentationTimeline(300, 0); + const timeline = new shaka.media.PresentationTimeline(300, 0); timeline.setStatic(false); manifest = new shaka.test.ManifestGenerator() .setTimeline(timeline) @@ -2764,21 +2764,21 @@ describe('Player', function() { .addVideo(1) .build(); goog.asserts.assert(manifest, 'manifest must be non-null'); - let parser = new shaka.test.FakeManifestParser(manifest); - let factory = function() { return parser; }; + const parser = new shaka.test.FakeManifestParser(manifest); + const factory = function() { return parser; }; await player.load(fakeManifestUri, 0, factory); }); it('gets current wall clock time in UTC', function() { - let liveTimeUtc = player.getPlayheadTimeAsDate(); + const liveTimeUtc = player.getPlayheadTimeAsDate(); expect(liveTimeUtc).toEqual(new Date(320000)); }); }); it('rejects empty manifests', function(done) { manifest = new shaka.test.ManifestGenerator().build(); - let emptyParser = new shaka.test.FakeManifestParser(manifest); - let emptyFactory = function() { return emptyParser; }; + const emptyParser = new shaka.test.FakeManifestParser(manifest); + const emptyFactory = function() { return emptyParser; }; player.load(fakeManifestUri, 0, emptyFactory).then(fail).catch((error) => { shaka.test.Util.expectToEqualError( @@ -2809,8 +2809,8 @@ describe('Player', function() { .addExistingStream(9) // audio .build(); - let parser = new shaka.test.FakeManifestParser(manifest); - let parserFactory = function() { return parser; }; + const parser = new shaka.test.FakeManifestParser(manifest); + const parserFactory = function() { return parser; }; await player.load(fakeManifestUri, 0, parserFactory); streamingEngine.onCanSwitch(); @@ -2836,7 +2836,7 @@ describe('Player', function() { it('detects audio-only content', async () => { // This factory recreates the parser each time, so updates to |manifest| // affect the next load() call. - let parserFactory = function() { + const parserFactory = function() { return new shaka.test.FakeManifestParser(manifest); }; @@ -2890,8 +2890,8 @@ describe('Player', function() { .addVideo(2).mime('video/mp4', 'good') .build(); - let parser = new shaka.test.FakeManifestParser(manifest); - let parserFactory = function() { return parser; }; + const parser = new shaka.test.FakeManifestParser(manifest); + const parserFactory = function() { return parser; }; // Before the fix, load() would fail assertions and throw errors. await player.load(fakeManifestUri, 0, parserFactory); @@ -2904,7 +2904,7 @@ describe('Player', function() { // default is the live edge. // Create a live timeline and manifest. - let timeline = new shaka.media.PresentationTimeline(300, 0); + const timeline = new shaka.media.PresentationTimeline(300, 0); timeline.setStatic(false); manifest = new shaka.test.ManifestGenerator() @@ -2914,8 +2914,8 @@ describe('Player', function() { .addVideo(1) .build(); - let parser = new shaka.test.FakeManifestParser(manifest); - let parserFactory = function() { return parser; }; + const parser = new shaka.test.FakeManifestParser(manifest); + const parserFactory = function() { return parser; }; // To ensure that Playhead is correctly created, we must use the original // playhead injector. To inspect the real Playhead instance, though, we @@ -2947,7 +2947,7 @@ describe('Player', function() { describe('language methods', function() { let videoOnlyManifest; - let parserFactory = function() { + const parserFactory = function() { return new shaka.test.FakeManifestParser(manifest); }; @@ -3065,7 +3065,7 @@ describe('Player', function() { * @return {shaka.extern.Track} */ function getActiveVariantTrack() { - let activeTracks = player.getVariantTracks().filter(function(track) { + const activeTracks = player.getVariantTracks().filter(function(track) { return track.active; }); @@ -3078,7 +3078,7 @@ describe('Player', function() { * @return {shaka.extern.Track} */ function getActiveTextTrack() { - let activeTracks = player.getTextTracks().filter(function(track) { + const activeTracks = player.getTextTracks().filter(function(track) { return track.active; }); diff --git a/test/test/boot.js b/test/test/boot.js index b0ca5a11d0..abb3e7b473 100644 --- a/test/test/boot.js +++ b/test/test/boot.js @@ -33,7 +33,7 @@ function getClientArg(name) { // Executed before test utilities and tests are loaded, but after Shaka Player // is loaded in uncompiled mode. (function() { - let realAssert = console.assert.bind(console); + const realAssert = console.assert.bind(console); /** * A version of assert() which hooks into jasmine and converts all failed @@ -72,7 +72,7 @@ function getClientArg(name) { }); // Use a RegExp if --specFilter is set, else empty string will match all. - let specFilterRegExp = new RegExp(getClientArg('specFilter') || ''); + const specFilterRegExp = new RegExp(getClientArg('specFilter') || ''); /** * A filter over all Jasmine specs. @@ -105,7 +105,7 @@ function getClientArg(name) { // Set the default timeout to 120s for all asynchronous tests. jasmine.DEFAULT_TIMEOUT_INTERVAL = 120 * 1000; - let logLevel = getClientArg('logLevel'); + const logLevel = getClientArg('logLevel'); if (logLevel) { shaka.log.setLevel(Number(logLevel)); } else { @@ -116,7 +116,7 @@ function getClientArg(name) { if (getClientArg('random')) { jasmine.getEnv().randomizeTests(true); - let seed = getClientArg('seed'); + const seed = getClientArg('seed'); if (seed) { jasmine.getEnv().seed(seed.toString()); } diff --git a/test/test/util/dash_parser_util.js b/test/test/util/dash_parser_util.js index eccef6e73b..8da5465cc1 100644 --- a/test/test/util/dash_parser_util.js +++ b/test/test/util/dash_parser_util.js @@ -38,13 +38,13 @@ shaka.test.Dash.makeDashParser = function() { * @return {!Promise} */ shaka.test.Dash.testSegmentIndex = async function(manifestText, references) { - let buffer = shaka.util.StringUtils.toUTF8(manifestText); - let dashParser = shaka.test.Dash.makeDashParser(); + const buffer = shaka.util.StringUtils.toUTF8(manifestText); + const dashParser = shaka.test.Dash.makeDashParser(); const networkingEngine = new shaka.test.FakeNetworkingEngine() .setResponseValue('dummy://foo', buffer); - let playerInterface = { + const playerInterface = { networkingEngine: networkingEngine, filterNewPeriod: function() {}, filterAllPeriods: function() {}, @@ -52,8 +52,8 @@ shaka.test.Dash.testSegmentIndex = async function(manifestText, references) { onEvent: fail, onError: fail, }; - let manifest = await dashParser.start('dummy://foo', playerInterface); - let stream = manifest.periods[0].variants[0].video; + const manifest = await dashParser.start('dummy://foo', playerInterface); + const stream = manifest.periods[0].variants[0].video; shaka.test.ManifestParser.verifySegmentIndex(stream, references); }; @@ -66,13 +66,13 @@ shaka.test.Dash.testSegmentIndex = async function(manifestText, references) { * @return {!Promise} */ shaka.test.Dash.testFails = async function(manifestText, expectedError) { - let manifestData = shaka.util.StringUtils.toUTF8(manifestText); - let dashParser = shaka.test.Dash.makeDashParser(); + const manifestData = shaka.util.StringUtils.toUTF8(manifestText); + const dashParser = shaka.test.Dash.makeDashParser(); const networkingEngine = new shaka.test.FakeNetworkingEngine() .setResponseValue('dummy://foo', manifestData); - let playerInterface = { + const playerInterface = { networkingEngine: networkingEngine, filterNewPeriod: function() {}, filterAllPeriods: function() {}, @@ -109,14 +109,14 @@ shaka.test.Dash.makeSimpleManifestText = periodAttr += ' start="PT' + startTime + 'S"'; } - let start = [ + const start = [ '<MPD ' + mpdAttr + '>', ' <Period ' + periodAttr + '>', ' <AdaptationSet mimeType="video/mp4">', ' <Representation bandwidth="500">', ' <BaseURL>http://example.com</BaseURL>', ]; - let end = [ + const end = [ ' </Representation>', ' </AdaptationSet>', ' </Period>', @@ -179,7 +179,7 @@ shaka.test.Dash.makeManifestFromInit = function( * @return {!Promise} */ shaka.test.Dash.callCreateSegmentIndex = function(manifest) { - let stream = manifest.periods[0].variants[0].video; + const stream = manifest.periods[0].variants[0].video; return stream.createSegmentIndex().then(fail).catch(function() {}); }; @@ -197,7 +197,7 @@ shaka.test.Dash.makeTimelineTests = function(type, extraAttrs, extraChildren) { describe('SegmentTimeline', function() { const Dash = shaka.test.Dash; const ManifestParser = shaka.test.ManifestParser; - let baseUri = 'http://example.com/'; + const baseUri = 'http://example.com/'; /** * @param {!Array.<string>} timeline @@ -207,16 +207,16 @@ shaka.test.Dash.makeTimelineTests = function(type, extraAttrs, extraChildren) { * @return {string} */ function makeManifestText(timeline, testAttrs, dur, startTime) { - let start = '<' + type + ' ' + extraAttrs + ' ' + testAttrs + '>'; - let end = '</' + type + '>'; - let lines = [].concat(start, extraChildren, timeline, end); + const start = '<' + type + ' ' + extraAttrs + ' ' + testAttrs + '>'; + const end = '</' + type + '>'; + const lines = [].concat(start, extraChildren, timeline, end); return Dash.makeSimpleManifestText(lines, dur, startTime); } // All tests should have 5 segments and have the relative URIs: // s1.mp4 s2.mp4 s3.mp4 s4.mp4 s5.mp4 it('basic support', async () => { - let timeline = [ + const timeline = [ '<SegmentTimeline>', ' <S d="12" t="34" />', ' <S d="21" />', @@ -225,8 +225,8 @@ shaka.test.Dash.makeTimelineTests = function(type, extraAttrs, extraChildren) { ' <S d="10" />', '</SegmentTimeline>', ]; - let source = makeManifestText(timeline, ''); - let references = [ + const source = makeManifestText(timeline, ''); + const references = [ ManifestParser.makeReference('s1.mp4', 1, 34, 46, baseUri), ManifestParser.makeReference('s2.mp4', 2, 46, 67, baseUri), ManifestParser.makeReference('s3.mp4', 3, 67, 111, baseUri), @@ -237,15 +237,15 @@ shaka.test.Dash.makeTimelineTests = function(type, extraAttrs, extraChildren) { }); it('supports repetitions', async () => { - let timeline = [ + const timeline = [ '<SegmentTimeline>', ' <S d="12" t="34" />', ' <S d="10" r="2" />', ' <S d="44" />', '</SegmentTimeline>', ]; - let source = makeManifestText(timeline, ''); - let references = [ + const source = makeManifestText(timeline, ''); + const references = [ ManifestParser.makeReference('s1.mp4', 1, 34, 46, baseUri), ManifestParser.makeReference('s2.mp4', 2, 46, 56, baseUri), ManifestParser.makeReference('s3.mp4', 3, 56, 66, baseUri), @@ -256,7 +256,7 @@ shaka.test.Dash.makeTimelineTests = function(type, extraAttrs, extraChildren) { }); it('supports negative repetitions', async () => { - let timeline = [ + const timeline = [ '<SegmentTimeline>', ' <S d="8" t="22" />', ' <S d="10" r="-1" />', @@ -264,8 +264,8 @@ shaka.test.Dash.makeTimelineTests = function(type, extraAttrs, extraChildren) { ' <S d="10" />', '</SegmentTimeline>', ]; - let source = makeManifestText(timeline, ''); - let references = [ + const source = makeManifestText(timeline, ''); + const references = [ ManifestParser.makeReference('s1.mp4', 1, 22, 30, baseUri), ManifestParser.makeReference('s2.mp4', 2, 30, 40, baseUri), ManifestParser.makeReference('s3.mp4', 3, 40, 50, baseUri), @@ -276,14 +276,14 @@ shaka.test.Dash.makeTimelineTests = function(type, extraAttrs, extraChildren) { }); it('supports negative repetitions at end', async () => { - let timeline = [ + const timeline = [ '<SegmentTimeline>', ' <S d="5" t="5" />', ' <S d="10" r="-1" />', '</SegmentTimeline>', ]; - let source = makeManifestText(timeline, '', 50 /* duration */); - let references = [ + const source = makeManifestText(timeline, '', 50 /* duration */); + const references = [ ManifestParser.makeReference('s1.mp4', 1, 5, 10, baseUri), ManifestParser.makeReference('s2.mp4', 2, 10, 20, baseUri), ManifestParser.makeReference('s3.mp4', 3, 20, 30, baseUri), @@ -294,14 +294,14 @@ shaka.test.Dash.makeTimelineTests = function(type, extraAttrs, extraChildren) { }); it('gives times relative to period', async () => { - let timeline = [ + const timeline = [ '<SegmentTimeline>', ' <S t="0" d="10" r="-1" />', '</SegmentTimeline>', ]; - let source = + const source = makeManifestText(timeline, '', 50 /* duration */, 30 /* start */); - let references = [ + const references = [ ManifestParser.makeReference('s1.mp4', 1, 0, 10, baseUri), ManifestParser.makeReference('s2.mp4', 2, 10, 20, baseUri), ManifestParser.makeReference('s3.mp4', 3, 20, 30, baseUri), @@ -312,7 +312,7 @@ shaka.test.Dash.makeTimelineTests = function(type, extraAttrs, extraChildren) { }); it('supports @timescale', async () => { - let timeline = [ + const timeline = [ '<SegmentTimeline>', ' <S d="4500" t="18000" />', ' <S d="9000" />', @@ -321,8 +321,8 @@ shaka.test.Dash.makeTimelineTests = function(type, extraAttrs, extraChildren) { ' <S d="9000" />', '</SegmentTimeline>', ]; - let source = makeManifestText(timeline, 'timescale="9000"'); - let references = [ + const source = makeManifestText(timeline, 'timescale="9000"'); + const references = [ ManifestParser.makeReference('s1.mp4', 1, 2, 2.5, baseUri), ManifestParser.makeReference('s2.mp4', 2, 2.5, 3.5, baseUri), ManifestParser.makeReference('s3.mp4', 3, 3.5, 7, baseUri), diff --git a/test/test/util/fake_media_source_engine.js b/test/test/util/fake_media_source_engine.js index 2d08f3ad49..2844dc0a86 100644 --- a/test/test/util/fake_media_source_engine.js +++ b/test/test/util/fake_media_source_engine.js @@ -52,8 +52,8 @@ shaka.test.FakeMediaSourceEngine = function(segmentData, drift) { /** @private {number} */ this.duration_ = Infinity; - for (let type in segmentData) { - let data = segmentData[type]; + for (const type in segmentData) { + const data = segmentData[type]; this.initSegments[type] = []; for (let i = 0; i < data.initSegments.length; ++i) { @@ -169,7 +169,7 @@ shaka.test.FakeMediaSourceEngine.SegmentData; shaka.test.FakeMediaSourceEngine.prototype.bufferStartImpl_ = function(type) { if (this.segments[type] === undefined) throw new Error('unexpected type'); - let first = this.segments[type].indexOf(true); + const first = this.segments[type].indexOf(true); if (first < 0) { return null; } @@ -186,7 +186,7 @@ shaka.test.FakeMediaSourceEngine.prototype.bufferStartImpl_ = function(type) { shaka.test.FakeMediaSourceEngine.prototype.bufferEndImpl_ = function(type) { if (this.segments[type] === undefined) throw new Error('unexpected type'); - let last = this.segments[type].lastIndexOf(true); + const last = this.segments[type].lastIndexOf(true); if (last < 0) { return null; } @@ -205,8 +205,8 @@ shaka.test.FakeMediaSourceEngine.prototype.isBufferedImpl_ = function(type, time) { if (this.segments[type] === undefined) throw new Error('unexpected type'); - let first = this.segments[type].indexOf(true); - let last = this.segments[type].lastIndexOf(true); + const first = this.segments[type].indexOf(true); + const last = this.segments[type].lastIndexOf(true); if (first < 0 || last < 0) { return false; } @@ -225,7 +225,7 @@ shaka.test.FakeMediaSourceEngine.prototype.bufferedAheadOfImpl = function( if (this.segments[type] === undefined) throw new Error('unexpected type'); const ContentType = shaka.util.ManifestParserUtils.ContentType; - let hasSegment = (function(i) { + const hasSegment = (function(i) { return this.segments[type][i] || (type === ContentType.VIDEO && this.segments['trickvideo'] && this.segments['trickvideo'][i]); @@ -233,7 +233,7 @@ shaka.test.FakeMediaSourceEngine.prototype.bufferedAheadOfImpl = function( // Note: |start| may equal the end of the last segment, so |first| // may equal segments[type].length - let first = this.toIndex_(type, start); + const first = this.toIndex_(type, start); if (!hasSegment(first)) { return 0; } // Unbuffered. @@ -260,7 +260,7 @@ shaka.test.FakeMediaSourceEngine.prototype.appendBufferImpl = function( if (this.segments[type] === undefined) throw new Error('unexpected type'); // Remains 'video' even when we detect a 'trickvideo' segment. - let originalType = type; + const originalType = type; const ContentType = shaka.util.ManifestParserUtils.ContentType; // Set init segment. @@ -311,9 +311,9 @@ shaka.test.FakeMediaSourceEngine.prototype.appendBufferImpl = function( expect(endTime).toBe(expectedEndTime); // Verify that the segment is aligned. - let start = this.segmentData[type].segmentStartTimes[i] + + const start = this.segmentData[type].segmentStartTimes[i] + this.timestampOffsets_[originalType]; - let expectedStart = i * this.segmentData[type].segmentDuration; + const expectedStart = i * this.segmentData[type].segmentDuration; expect(start).toBe(expectedStart); this.segments[type][i] = true; @@ -331,13 +331,13 @@ shaka.test.FakeMediaSourceEngine.prototype.removeImpl = function(type, start, end) { if (this.segments[type] === undefined) throw new Error('unexpected type'); - let first = this.toIndex_(type, start); + const first = this.toIndex_(type, start); if (first < 0 || first >= this.segments[type].length) { throw new Error('unexpected start'); } // Note: |end| is exclusive. - let last = this.toIndex_(type, end - 0.000001); + const last = this.toIndex_(type, end - 0.000001); if (last < 0) { throw new Error('unexpected end'); } diff --git a/test/test/util/indexeddb_utils.js b/test/test/util/indexeddb_utils.js index 7f9c387cdf..062c150eb0 100644 --- a/test/test/util/indexeddb_utils.js +++ b/test/test/util/indexeddb_utils.js @@ -63,9 +63,9 @@ shaka.test.IndexedDBUtils.makeConnection = function(name, version, upgrade) { */ shaka.test.IndexedDBUtils.deleteDB = function(name) { /** @type {!shaka.util.PublicPromise} */ - let p = new shaka.util.PublicPromise(); + const p = new shaka.util.PublicPromise(); - let goaway = window.indexedDB.deleteDatabase(name); + const goaway = window.indexedDB.deleteDatabase(name); goaway.onsuccess = (e) => { p.resolve(); }; goaway.onerror = (e) => { p.reject(); }; @@ -85,9 +85,9 @@ shaka.test.IndexedDBUtils.dbOpenNew_ = function(name, version, upgrade) { let upgraded = false; /** @type {!shaka.util.PublicPromise} */ - let p = new shaka.util.PublicPromise(); + const p = new shaka.util.PublicPromise(); - let open = window.indexedDB.open(name, version); + const open = window.indexedDB.open(name, version); open.onerror = (e) => { p.reject(); }; open.onsuccess = (e) => { // Make sure that the database actually upgraded when connecting or else @@ -118,9 +118,9 @@ shaka.test.IndexedDBUtils.dbOpenNew_ = function(name, version, upgrade) { */ shaka.test.IndexedDBUtils.open = function(name) { /** @type {!shaka.util.PublicPromise} */ - let p = new shaka.util.PublicPromise(); + const p = new shaka.util.PublicPromise(); - let open = window.indexedDB.open(name); + const open = window.indexedDB.open(name); open.onerror = (e) => { p.reject(); }; open.onsuccess = (e) => { p.resolve(open.result); }; @@ -135,7 +135,7 @@ shaka.test.IndexedDBUtils.open = function(name) { */ shaka.test.IndexedDBUtils.wait_ = function(ms) { /** @type {!shaka.util.PublicPromise} */ - let p = new shaka.util.PublicPromise(); + const p = new shaka.util.PublicPromise(); setTimeout(() => p.resolve(), ms); return p; }; diff --git a/test/test/util/jasmine_fetch.js b/test/test/util/jasmine_fetch.js index e020a49b11..00da350205 100644 --- a/test/test/util/jasmine_fetch.js +++ b/test/test/util/jasmine_fetch.js @@ -68,7 +68,7 @@ jasmine.Fetch.install = function() { window.fetch = function(input, init) { // TODO: this does not support input in Request form - let url = /** @type {string} */ (input); + const url = /** @type {string} */ (input); return jasmine.Fetch.impl_(url, init || null); }; }; @@ -81,7 +81,7 @@ jasmine.Fetch.install = function() { jasmine.Fetch.makeAbortError_ = function() { // As per the spec, this should be a DOMException, but // there is not a public constructor for this - let exception = new Error('The operation was aborted. '); + const exception = new Error('The operation was aborted. '); exception.name = 'AbortError'; exception.code = 20; return exception; @@ -100,13 +100,13 @@ jasmine.Fetch.impl_ = function(url, init) { return Promise.reject(jasmine.Fetch.makeAbortError_()); } - let headers = {}; - let initHeaders = new jasmine.Fetch.Headers(init.headers); + const headers = {}; + const initHeaders = new jasmine.Fetch.Headers(init.headers); initHeaders.forEach(function(value, key) { headers[key] = value; }); - let newStub = /** @type {jasmine.Fetch.RequestStub} */({ + const newStub = /** @type {jasmine.Fetch.RequestStub} */({ url: url, query: null, data: null, @@ -118,27 +118,27 @@ jasmine.Fetch.impl_ = function(url, init) { }); jasmine.Fetch.container_.lastFetchRequestStub = newStub; - let stubbed = jasmine.Fetch.container_.stubbedRequests[url]; + const stubbed = jasmine.Fetch.container_.stubbedRequests[url]; if (stubbed.callFunc) { - let callFunc = stubbed.callFunc; + const callFunc = stubbed.callFunc; stubbed.callFunc = undefined; callFunc(stubbed, self); // Call fetch again, in case callFunc changed the stub's action. return jasmine.Fetch.impl_(url, init); } else if (stubbed.response) { - let responseHeaders = new jasmine.Fetch.Headers(); - for (let key in stubbed.response.responseHeaders) { + const responseHeaders = new jasmine.Fetch.Headers(); + for (const key in stubbed.response.responseHeaders) { responseHeaders.append(key, stubbed.response.responseHeaders[key]); } - let body = { + const body = { getReader: () => { - let sequence = [{ + const sequence = [{ done: false, value: {byteLength: 100}, }, { done: true, value: null, }]; - let read = () => { + const read = () => { return Promise.resolve(sequence.shift()); }; return {read: read}; @@ -148,7 +148,7 @@ jasmine.Fetch.impl_ = function(url, init) { // This creates an anonymous object instead of using the // built-in response constructor, because the fetch API // does not include a very good constructor for Response. - let response = /** @type {!Response} */ ({ + const response = /** @type {!Response} */ ({ status: stubbed.response.status, body: body, headers: responseHeaders, @@ -166,7 +166,7 @@ jasmine.Fetch.impl_ = function(url, init) { // Fetch does not time out yet, so just return a promise that rejects when // the user aborts. return new Promise(function(resolve, reject) { - let interval = setInterval(function() { + const interval = setInterval(function() { if (init['signal'] && init['signal']()) { // TODO: This assumes that this request is still the most recent. // If you have multiple requests at once, this could be incorrect. @@ -215,7 +215,7 @@ jasmine.Fetch.AbortController = function() { */ jasmine.Fetch.ReadableStream = function(underlyingSource) { const noop = () => {}; - let controller = { + const controller = { close: noop, enqueue: noop, }; @@ -234,7 +234,7 @@ jasmine.Fetch.Response = function() { this.body = latest.body; this.headers = latest.headers; this.url = latest.url; - let arrayBuffer = latest.arrayBuffer; + const arrayBuffer = latest.arrayBuffer; this.arrayBuffer = () => arrayBuffer; }; @@ -280,7 +280,7 @@ jasmine.Fetch.Headers = function(headers) { */ jasmine.Fetch.Headers.prototype.append = function(name, value) { // Normalize name before setting. - let normalized = name.toLowerCase(); + const normalized = name.toLowerCase(); this.contents[normalized] = value; }; @@ -289,9 +289,9 @@ jasmine.Fetch.Headers.prototype.append = function(name, value) { * @param {Function} apply */ jasmine.Fetch.Headers.prototype.forEach = function(apply) { - let contentsNames = Object.getOwnPropertyNames(this.contents); + const contentsNames = Object.getOwnPropertyNames(this.contents); for (let i = 0; i < contentsNames.length; i++) { - let contentsName = contentsNames[i]; + const contentsName = contentsNames[i]; apply(this.get(contentsName), contentsName, this); } }; @@ -301,7 +301,7 @@ jasmine.Fetch.Headers.prototype.forEach = function(apply) { * @return {Object} */ jasmine.Fetch.Headers.prototype.keys = function() { - let contentsNames = Object.getOwnPropertyNames(this.contents); + const contentsNames = Object.getOwnPropertyNames(this.contents); let index = 0; return { next: function() { @@ -332,7 +332,7 @@ jasmine.Fetch.Headers.prototype.get = function(header) { * @return {jasmine.Fetch.RequestStub} */ jasmine.Fetch.stubRequest = function(url) { - let stub = new jasmine.Fetch.RequestStub(url); + const stub = new jasmine.Fetch.RequestStub(url); jasmine.Fetch.container_.stubbedRequests[url] = stub; return stub; }; diff --git a/test/test/util/manifest_generator.js b/test/test/util/manifest_generator.js index 1c8c57d514..02f5e44387 100644 --- a/test/test/util/manifest_generator.js +++ b/test/test/util/manifest_generator.js @@ -32,7 +32,7 @@ shaka.test.ManifestGenerator = function(shaka) { /** @private {?} */ this.shaka_ = shaka || window['shaka']; - let timeline = new this.shaka_.media.PresentationTimeline(0, 0); + const timeline = new this.shaka_.media.PresentationTimeline(0, 0); timeline.setSegmentAvailabilityDuration(Infinity); timeline.notifyMaxSegmentDuration(10); @@ -134,8 +134,8 @@ shaka.test.ManifestGenerator.prototype.addPeriod = function(startTime) { * @return {!shaka.test.ManifestGenerator} */ shaka.test.ManifestGenerator.prototype.addVariant = function(id) { - let period = this.currentPeriod_(); - let variant = { + const period = this.currentPeriod_(); + const variant = { id: id, language: 'und', bandwidth: 0, @@ -162,9 +162,9 @@ shaka.test.ManifestGenerator.prototype.addVariant = function(id) { * @return {!shaka.test.ManifestGenerator} */ shaka.test.ManifestGenerator.prototype.addPartialVariant = function(id) { - let period = this.currentPeriod_(); + const period = this.currentPeriod_(); - let variant = /** @type {shaka.extern.Variant} */ ({ + const variant = /** @type {shaka.extern.Variant} */ ({ audio: null, video: null, }); @@ -221,7 +221,7 @@ shaka.test.ManifestGenerator.prototype.bandwidth = function(bandwidth) { * @return {!shaka.test.ManifestGenerator} */ shaka.test.ManifestGenerator.prototype.disallowByApplication = function() { - let variant = this.currentVariant_(); + const variant = this.currentVariant_(); variant.allowedByApplication = false; return this; }; @@ -233,7 +233,7 @@ shaka.test.ManifestGenerator.prototype.disallowByApplication = function() { * @return {!shaka.test.ManifestGenerator} */ shaka.test.ManifestGenerator.prototype.disallowByKeySystem = function() { - let variant = this.currentVariant_(); + const variant = this.currentVariant_(); variant.allowedByKeySystem = false; return this; }; @@ -248,7 +248,7 @@ shaka.test.ManifestGenerator.prototype.disallowByKeySystem = function() { * @return {!shaka.test.ManifestGenerator} */ shaka.test.ManifestGenerator.prototype.addDrmInfo = function(keySystem) { - let variant = this.currentVariant_(); + const variant = this.currentVariant_(); if (!variant.drmInfos) { variant.drmInfos = []; } @@ -274,7 +274,7 @@ shaka.test.ManifestGenerator.prototype.addDrmInfo = function(keySystem) { * @return {!shaka.test.ManifestGenerator} */ shaka.test.ManifestGenerator.prototype.licenseServerUri = function(uri) { - let drmInfo = this.currentDrmInfo_(); + const drmInfo = this.currentDrmInfo_(); drmInfo.licenseServerUri = uri; return this; }; @@ -287,7 +287,7 @@ shaka.test.ManifestGenerator.prototype.licenseServerUri = function(uri) { */ shaka.test.ManifestGenerator.prototype.distinctiveIdentifierRequired = function() { - let drmInfo = this.currentDrmInfo_(); + const drmInfo = this.currentDrmInfo_(); drmInfo.distinctiveIdentifierRequired = true; return this; }; @@ -299,7 +299,7 @@ shaka.test.ManifestGenerator.prototype.distinctiveIdentifierRequired = * @return {!shaka.test.ManifestGenerator} */ shaka.test.ManifestGenerator.prototype.persistentStateRequired = function() { - let drmInfo = this.currentDrmInfo_(); + const drmInfo = this.currentDrmInfo_(); drmInfo.persistentStateRequired = true; return this; }; @@ -312,7 +312,7 @@ shaka.test.ManifestGenerator.prototype.persistentStateRequired = function() { * @return {!shaka.test.ManifestGenerator} */ shaka.test.ManifestGenerator.prototype.audioRobustness = function(robustness) { - let drmInfo = this.currentDrmInfo_(); + const drmInfo = this.currentDrmInfo_(); drmInfo.audioRobustness = robustness; return this; }; @@ -325,7 +325,7 @@ shaka.test.ManifestGenerator.prototype.audioRobustness = function(robustness) { * @return {!shaka.test.ManifestGenerator} */ shaka.test.ManifestGenerator.prototype.videoRobustness = function(robustness) { - let drmInfo = this.currentDrmInfo_(); + const drmInfo = this.currentDrmInfo_(); drmInfo.videoRobustness = robustness; return this; }; @@ -339,7 +339,7 @@ shaka.test.ManifestGenerator.prototype.videoRobustness = function(robustness) { * @return {!shaka.test.ManifestGenerator} */ shaka.test.ManifestGenerator.prototype.addInitData = function(type, buffer) { - let drmInfo = this.currentDrmInfo_(); + const drmInfo = this.currentDrmInfo_(); if (!drmInfo.initData) { drmInfo.initData = []; } @@ -355,12 +355,12 @@ shaka.test.ManifestGenerator.prototype.addInitData = function(type, buffer) { * @return {!shaka.test.ManifestGenerator} */ shaka.test.ManifestGenerator.prototype.addCencInitData = function(base64) { - let drmInfo = this.currentDrmInfo_(); + const drmInfo = this.currentDrmInfo_(); if (!drmInfo.initData) { drmInfo.initData = []; } - let buffer = shaka.util.Uint8ArrayUtils.fromBase64(base64); + const buffer = shaka.util.Uint8ArrayUtils.fromBase64(base64); drmInfo.initData.push({initData: buffer, initDataType: 'cenc'}); return this; }; @@ -378,7 +378,7 @@ shaka.test.ManifestGenerator.prototype.addVideo = function(id) { goog.asserts.assert(!this.isIdUsed_(id), 'Streams should have unique ids!'); const ContentType = shaka.util.ManifestParserUtils.ContentType; - let stream = this.createStream_(id, ContentType.VIDEO, 'und'); + const stream = this.createStream_(id, ContentType.VIDEO, 'und'); this.currentVariant_().video = stream; this.lastStreamAdded_ = stream; @@ -398,8 +398,8 @@ shaka.test.ManifestGenerator.prototype.addAudio = function(id) { goog.asserts.assert(!this.isIdUsed_(id), 'Streams should have unique ids!'); const ContentType = shaka.util.ManifestParserUtils.ContentType; - let variant = this.currentVariant_(); - let stream = this.createStream_(id, ContentType.AUDIO, variant.language); + const variant = this.currentVariant_(); + const stream = this.createStream_(id, ContentType.AUDIO, variant.language); variant.audio = stream; this.lastStreamAdded_ = stream; @@ -419,7 +419,7 @@ shaka.test.ManifestGenerator.prototype.addTextStream = function(id) { goog.asserts.assert(!this.isIdUsed_(id), 'Streams should have unique ids!'); const ContentType = shaka.util.ManifestParserUtils.ContentType; - let stream = this.createStream_(id, ContentType.TEXT, 'und'); + const stream = this.createStream_(id, ContentType.TEXT, 'und'); this.currentPeriod_().textStreams.push(stream); this.lastObjectAdded_ = stream; @@ -437,10 +437,10 @@ shaka.test.ManifestGenerator.prototype.addTextStream = function(id) { */ shaka.test.ManifestGenerator.prototype.addExistingStream = function(id) { const realObj_ = shaka.test.ManifestGenerator.realObj_; - let period = this.currentPeriod_(); + const period = this.currentPeriod_(); let found = false; for (let i = 0; i < period.variants.length; i++) { - let variant = realObj_(period.variants[i]); + const variant = realObj_(period.variants[i]); if (variant.audio && realObj_(variant.audio).id == id) { this.currentVariant_().audio = variant.audio; found = true; @@ -474,20 +474,20 @@ shaka.test.ManifestGenerator.prototype.addExistingStream = function(id) { shaka.test.ManifestGenerator.prototype.addPartialStream = function(type, id) { const ContentType = shaka.util.ManifestParserUtils.ContentType; - let stream = /** @type {shaka.extern.Stream} */ ({type: type}); + const stream = /** @type {shaka.extern.Stream} */ ({type: type}); if (id != null) { stream.id = id; } this.lastObjectAdded_ = stream; this.lastStreamAdded_ = stream; - let streamObj = + const streamObj = /** @type {shaka.extern.Stream} */ (jasmine.objectContaining(stream)); if (type == ContentType.TEXT) { - let period = this.currentPeriod_(); + const period = this.currentPeriod_(); period.textStreams.push(streamObj); } else { - let variant = this.currentVariant_(); + const variant = this.currentVariant_(); if (type == ContentType.AUDIO) { variant.audio = streamObj; } else { @@ -527,14 +527,15 @@ shaka.test.ManifestGenerator.prototype.createStream_ = defaultMimeType = 'text/vtt'; } - let create = jasmine.createSpy('createSegmentIndex').and.callFake(function() { - return Promise.resolve(); - }); - let find = jasmine.createSpy('findSegmentPosition').and.returnValue(null); - let get = jasmine.createSpy('getSegmentReference').and.returnValue(null); + const create = + jasmine.createSpy('createSegmentIndex').and.callFake(function() { + return Promise.resolve(); + }); + const find = jasmine.createSpy('findSegmentPosition').and.returnValue(null); + const get = jasmine.createSpy('getSegmentReference').and.returnValue(null); /** @type {shaka.extern.Stream} */ - let stream = { + const stream = { id: id, originalId: null, createSegmentIndex: shaka.test.Util.spyFunc(create), @@ -576,9 +577,9 @@ shaka.test.ManifestGenerator.prototype.createStream_ = */ shaka.test.ManifestGenerator.prototype.useSegmentTemplate = function( template, segmentDuration, segmentSize = null) { - let stream = this.currentStream_(); - let totalDuration = this.manifest_.presentationTimeline.getDuration(); - let segmentCount = totalDuration / segmentDuration; + const stream = this.currentStream_(); + const totalDuration = this.manifest_.presentationTimeline.getDuration(); + const segmentCount = totalDuration / segmentDuration; stream.createSegmentIndex = function() { return Promise.resolve(); }; stream.findSegmentPosition = function(time) { return Math.floor(time / segmentDuration); @@ -587,9 +588,9 @@ shaka.test.ManifestGenerator.prototype.useSegmentTemplate = function( if (index < 0 || index >= segmentCount) { return null; } - let getUris = function() { return [sprintf(template, index)]; }; - let start = index * segmentDuration; - let end = Math.min(totalDuration, (index + 1) * segmentDuration); + const getUris = function() { return [sprintf(template, index)]; }; + const start = index * segmentDuration; + const end = Math.min(totalDuration, (index + 1) * segmentDuration); return new this.shaka_.media.SegmentReference( index, start, end, getUris, 0, segmentSize); }.bind(this)); @@ -605,9 +606,9 @@ shaka.test.ManifestGenerator.prototype.useSegmentTemplate = function( * @return {!shaka.test.ManifestGenerator} */ shaka.test.ManifestGenerator.prototype.textStream = function(uri) { - let stream = this.currentStream_(); - let duration = this.manifest_.presentationTimeline.getDuration(); - let getUris = function() { return [uri]; }; + const stream = this.currentStream_(); + const duration = this.manifest_.presentationTimeline.getDuration(); + const getUris = function() { return [uri]; }; stream.createSegmentIndex = function() { return Promise.resolve(); }; stream.findSegmentPosition = function(time) { @@ -615,7 +616,7 @@ shaka.test.ManifestGenerator.prototype.textStream = function(uri) { }; stream.getSegmentReference = (function(position) { if (position != 1) return null; - let startTime = 0; + const startTime = 0; return new this.shaka_.media.SegmentReference( position, startTime, duration, getUris, 0, null); }.bind(this)); @@ -642,7 +643,7 @@ shaka.test.ManifestGenerator.prototype.delayCreateSegmentIndex = function() { * @return {!shaka.test.ManifestGenerator} */ shaka.test.ManifestGenerator.prototype.anyInitSegment = function() { - let stream = this.currentStream_(); + const stream = this.currentStream_(); stream.initSegmentReference = /** @type {shaka.media.InitSegmentReference} */ ( jasmine.any(this.shaka_.media.InitSegmentReference)); @@ -656,7 +657,7 @@ shaka.test.ManifestGenerator.prototype.anyInitSegment = function() { * @return {!shaka.test.ManifestGenerator} */ shaka.test.ManifestGenerator.prototype.nullInitSegment = function() { - let stream = this.currentStream_(); + const stream = this.currentStream_(); stream.initSegmentReference = null; return this; }; @@ -672,8 +673,8 @@ shaka.test.ManifestGenerator.prototype.nullInitSegment = function() { */ shaka.test.ManifestGenerator.prototype.initSegmentReference = function( uris, startByte, endByte) { - let stream = this.currentStream_(); - let getUris = function() { return uris; }; + const stream = this.currentStream_(); + const getUris = function() { return uris; }; stream.initSegmentReference = new this.shaka_.media.InitSegmentReference(getUris, startByte, endByte); return this; @@ -687,7 +688,7 @@ shaka.test.ManifestGenerator.prototype.initSegmentReference = function( * @return {!shaka.test.ManifestGenerator} */ shaka.test.ManifestGenerator.prototype.presentationTimeOffset = function(pto) { - let stream = this.currentStream_(); + const stream = this.currentStream_(); stream.presentationTimeOffset = pto; return this; }; @@ -701,7 +702,7 @@ shaka.test.ManifestGenerator.prototype.presentationTimeOffset = function(pto) { * @return {!shaka.test.ManifestGenerator} */ shaka.test.ManifestGenerator.prototype.mime = function(mime, codecs) { - let stream = this.currentStream_(); + const stream = this.currentStream_(); stream.mimeType = mime; stream.codecs = codecs || ''; return this; @@ -729,7 +730,7 @@ shaka.test.ManifestGenerator.prototype.closedCaptions = * @return {!shaka.test.ManifestGenerator} */ shaka.test.ManifestGenerator.prototype.frameRate = function(frameRate) { - let stream = this.currentStream_(); + const stream = this.currentStream_(); stream.frameRate = frameRate; return this; }; @@ -743,7 +744,7 @@ shaka.test.ManifestGenerator.prototype.frameRate = function(frameRate) { * @return {!shaka.test.ManifestGenerator} */ shaka.test.ManifestGenerator.prototype.size = function(width, height) { - let stream = this.currentStream_(); + const stream = this.currentStream_(); stream.width = width; stream.height = height; return this; @@ -757,7 +758,7 @@ shaka.test.ManifestGenerator.prototype.size = function(width, height) { * @return {!shaka.test.ManifestGenerator} */ shaka.test.ManifestGenerator.prototype.kind = function(kind) { - let stream = this.currentStream_(); + const stream = this.currentStream_(); stream.kind = kind; return this; }; @@ -770,7 +771,7 @@ shaka.test.ManifestGenerator.prototype.kind = function(kind) { * @return {!shaka.test.ManifestGenerator} */ shaka.test.ManifestGenerator.prototype.encrypted = function(encrypted) { - let stream = this.currentStream_(); + const stream = this.currentStream_(); stream.encrypted = encrypted; return this; }; @@ -783,7 +784,7 @@ shaka.test.ManifestGenerator.prototype.encrypted = function(encrypted) { * @return {!shaka.test.ManifestGenerator} */ shaka.test.ManifestGenerator.prototype.keyId = function(keyId) { - let stream = this.currentStream_(); + const stream = this.currentStream_(); stream.keyId = keyId; return this; }; @@ -807,7 +808,7 @@ shaka.test.ManifestGenerator.prototype.label = function(label) { * @return {!shaka.test.ManifestGenerator} */ shaka.test.ManifestGenerator.prototype.roles = function(roles) { - let stream = this.currentStream_(); + const stream = this.currentStream_(); stream.roles = roles; return this; }; @@ -819,7 +820,7 @@ shaka.test.ManifestGenerator.prototype.roles = function(roles) { * @return {!shaka.test.ManifestGenerator} */ shaka.test.ManifestGenerator.prototype.channelsCount = function(count) { - let stream = this.currentStream_(); + const stream = this.currentStream_(); stream.channelsCount = count; return this; }; @@ -832,7 +833,7 @@ shaka.test.ManifestGenerator.prototype.channelsCount = function(count) { * @return {!shaka.test.ManifestGenerator} */ shaka.test.ManifestGenerator.prototype.originalId = function(originalId) { - let stream = this.currentStream_(); + const stream = this.currentStream_(); stream.originalId = originalId; return this; }; @@ -859,7 +860,7 @@ shaka.test.ManifestGenerator.prototype.currentPeriod_ = function() { */ shaka.test.ManifestGenerator.prototype.currentVariant_ = function() { const realObj_ = shaka.test.ManifestGenerator.realObj_; - let period = this.currentPeriod_(); + const period = this.currentPeriod_(); goog.asserts.assert(period.variants.length > 0, 'Must call addVariant() at least once.'); return realObj_(period.variants[period.variants.length - 1]); @@ -886,7 +887,7 @@ shaka.test.ManifestGenerator.prototype.currentStreamOrVariant_ = function() { */ shaka.test.ManifestGenerator.prototype.currentDrmInfo_ = function() { const realObj_ = shaka.test.ManifestGenerator.realObj_; - let variant = this.currentVariant_(); + const variant = this.currentVariant_(); goog.asserts.assert(variant.drmInfos.length > 0, 'Must call addDrmInfo() at least once.'); return realObj_(variant.drmInfos[variant.drmInfos.length - 1]); diff --git a/test/test/util/manifest_parser_util.js b/test/test/util/manifest_parser_util.js index 6f54dd3bec..dc7fdaad5e 100644 --- a/test/test/util/manifest_parser_util.js +++ b/test/test/util/manifest_parser_util.js @@ -39,12 +39,12 @@ shaka.test.ManifestParser.verifySegmentIndex = function(stream, references) { expect(stream.findSegmentPosition(0)).toBe(references[0].position); for (let i = 0; i < references.length; i++) { - let expectedRef = references[i]; + const expectedRef = references[i]; // Don't query negative times. Query 0 instead. - let startTime = Math.max(0, expectedRef.startTime); - let position = stream.findSegmentPosition(startTime); + const startTime = Math.max(0, expectedRef.startTime); + const position = stream.findSegmentPosition(startTime); expect(position).not.toBe(null); - let actualRef = + const actualRef = stream.getSegmentReference(/** @type {number} */ (position)); // NOTE: A custom matcher for SegmentReferences is installed, so this checks // the URIs as well. @@ -52,11 +52,11 @@ shaka.test.ManifestParser.verifySegmentIndex = function(stream, references) { } // Make sure that the references stop at the end. - let lastExpectedReference = references[references.length - 1]; - let positionAfterEnd = + const lastExpectedReference = references[references.length - 1]; + const positionAfterEnd = stream.findSegmentPosition(lastExpectedReference.endTime); expect(positionAfterEnd).toBe(null); - let referencePastEnd = + const referencePastEnd = stream.getSegmentReference(lastExpectedReference.position + 1); expect(referencePastEnd).toBe(null); }; @@ -77,7 +77,7 @@ shaka.test.ManifestParser.verifySegmentIndex = function(stream, references) { shaka.test.ManifestParser.makeReference = function(uri, position, start, end, baseUri = '', startByte = 0, endByte = null) { - let getUris = function() { return [baseUri + uri]; }; + const getUris = function() { return [baseUri + uri]; }; return new shaka.media.SegmentReference( position, start, end, getUris, startByte, endByte); }; diff --git a/test/test/util/offline_utils.js b/test/test/util/offline_utils.js index 77b35c158c..f3d689be19 100644 --- a/test/test/util/offline_utils.js +++ b/test/test/util/offline_utils.js @@ -71,7 +71,7 @@ shaka.test.OfflineUtils.createStream = function(id, type) { */ shaka.test.OfflineUtils.createSegmentData = function(data) { /** @type {Uint8Array} */ - let array = new Uint8Array(data); + const array = new Uint8Array(data); return { data: array.buffer, @@ -85,13 +85,13 @@ shaka.test.OfflineUtils.createSegmentData = function(data) { */ shaka.test.OfflineUtils.expectSegmentsToContain = function(segments, expected) { - let actualData = segments.map(function(segment) { + const actualData = segments.map(function(segment) { expect(segment.data).toBeTruthy(); return new Uint8Array(segment.data); }); expect(expected.data).toBeTruthy(); - let expectedData = new Uint8Array(expected.data); + const expectedData = new Uint8Array(expected.data); expect(actualData).toContain(expectedData); }; @@ -105,8 +105,8 @@ shaka.test.OfflineUtils.expectSegmentToEqual = function(actual, expected) { expect(actual.data).toBeTruthy(); expect(expected.data).toBeTruthy(); - let actualData = new Uint8Array(actual.data); - let expectedData = new Uint8Array(expected.data); + const actualData = new Uint8Array(actual.data); + const expectedData = new Uint8Array(expected.data); expect(actualData).toEqual(expectedData); }; diff --git a/test/test/util/simple_fakes.js b/test/test/util/simple_fakes.js index d89cb21aa5..765144de5b 100644 --- a/test/test/util/simple_fakes.js +++ b/test/test/util/simple_fakes.js @@ -43,7 +43,7 @@ goog.provide('shaka.test.FakeVideo'); * @return {!Object} */ shaka.test.FakeAbrManager = function() { - let ret = jasmine.createSpyObj('FakeAbrManager', [ + const ret = jasmine.createSpyObj('FakeAbrManager', [ 'stop', 'init', 'enable', 'disable', 'segmentDownloaded', 'getBandwidthEstimate', 'chooseVariant', 'setVariants', 'configure', ]); @@ -123,13 +123,13 @@ shaka.test.FakeAbrManager.prototype.configure; * @return {!Object} */ shaka.test.FakeStreamingEngine = function(onChooseStreams, onCanSwitch) { - let resolve = Promise.resolve.bind(Promise); + const resolve = Promise.resolve.bind(Promise); let activeAudio = null; let activeVideo = null; let activeText = null; - let ret = jasmine.createSpyObj('fakeStreamingEngine', [ + const ret = jasmine.createSpyObj('fakeStreamingEngine', [ 'destroy', 'configure', 'start', 'getBufferingPeriod', 'getBufferingAudio', 'getBufferingVideo', 'getBufferingText', 'loadNewTextStream', 'switchVariant', 'switchTextStream', 'seeked', @@ -148,7 +148,7 @@ shaka.test.FakeStreamingEngine = function(onChooseStreams, onCanSwitch) { activeText = null; }); ret.start.and.callFake(function() { - let chosen = onChooseStreams(); + const chosen = onChooseStreams(); return Promise.resolve().then(function() { if (chosen.variant && chosen.variant.audio) { activeAudio = chosen.variant.audio; @@ -204,7 +204,7 @@ shaka.test.FakeStreamingEngine.prototype.onCanSwitch; * @return {!Object} */ shaka.test.FakeManifestParser = function(manifest) { - let ret = jasmine.createSpyObj('FakeManifestParser', [ + const ret = jasmine.createSpyObj('FakeManifestParser', [ 'start', 'stop', 'configure', 'update', 'onExpirationUpdated', ]); ret.start.and.callFake(function(manifestUri, playerInterface) { @@ -252,7 +252,7 @@ shaka.test.FakeManifestParser.prototype.playerInterface; * @return {!Object} */ shaka.test.FakeVideo = function(currentTime) { - let video = { + const video = { currentTime: currentTime || 0, readyState: 0, playbackRate: 1, @@ -281,7 +281,7 @@ shaka.test.FakeVideo = function(currentTime) { }; video.setMediaKeys.and.returnValue(Promise.resolve()); video.addTextTrack.and.callFake(function(kind, id) { - let track = new shaka.test.FakeTextTrack(); + const track = new shaka.test.FakeTextTrack(); video.textTracks.push(track); return track; }); @@ -335,11 +335,11 @@ function createFakeBuffered(ranges) { * @return {!Object} */ shaka.test.FakePresentationTimeline = function() { - let getStart = jasmine.createSpy('getSeekRangeStart'); - let getEnd = jasmine.createSpy('getSeekRangeEnd'); - let getSafeStart = jasmine.createSpy('getSafeSeekRangeStart'); + const getStart = jasmine.createSpy('getSeekRangeStart'); + const getEnd = jasmine.createSpy('getSeekRangeEnd'); + const getSafeStart = jasmine.createSpy('getSafeSeekRangeStart'); getSafeStart.and.callFake(function(delay) { - let end = shaka.test.Util.invokeSpy(getEnd); + const end = shaka.test.Util.invokeSpy(getEnd); return Math.min(shaka.test.Util.invokeSpy(getStart) + delay, end); }); @@ -517,7 +517,7 @@ shaka.test.FakePlayheadObserver.prototype.addTimelineRegion; * @return {!Object} */ shaka.test.FakeTextTrack = function() { - let track = { + const track = { addCue: jasmine.createSpy('addCue'), removeCue: jasmine.createSpy('removeCue'), cues: [], @@ -526,7 +526,7 @@ shaka.test.FakeTextTrack = function() { track.cues.push(cue); }); track.removeCue.and.callFake(function(cue) { - let idx = track.cues.indexOf(cue); + const idx = track.cues.indexOf(cue); expect(idx).not.toBeLessThan(0); track.cues.splice(idx, 1); }); @@ -589,11 +589,11 @@ shaka.test.FakeClosedCaptionParser = class { * @return {!Object} */ shaka.test.FakeTransmuxer = function() { - let output = { + const output = { data: new Uint8Array(), captions: [], }; - let transmuxer = { + const transmuxer = { destroy: jasmine.createSpy('destroy').and.returnValue(Promise.resolve()), transmux: jasmine.createSpy('transmux').and .returnValue(Promise.resolve(output)), diff --git a/test/test/util/simple_idb.js b/test/test/util/simple_idb.js index 6f96627a12..59dec0ae69 100644 --- a/test/test/util/simple_idb.js +++ b/test/test/util/simple_idb.js @@ -44,9 +44,9 @@ shaka.test.SimpleIDB = class { * @return {!Promise<number>} */ add(store, value) { - let promise = new shaka.util.PublicPromise(); + const promise = new shaka.util.PublicPromise(); - let transaction = this.db_.transaction([store], 'readwrite'); + const transaction = this.db_.transaction([store], 'readwrite'); transaction.oncomplete = () => promise.resolve(); transaction.onerror = () => { promise.reject('Error adding ' + value + ' to ' + store); @@ -75,26 +75,26 @@ shaka.test.SimpleIDB = class { let upgraded = false; - let wait = () => { + const wait = () => { const wait = 1000; // 1 second return new Promise((resolve) => setTimeout(resolve, wait)); }; - let tryOpen = () => { + const tryOpen = () => { /** @type {!shaka.util.PublicPromise} */ - let promise = new shaka.util.PublicPromise(); + const promise = new shaka.util.PublicPromise(); - let request = window.indexedDB.open(name, version); + const request = window.indexedDB.open(name, version); request.onerror = () => promise.reject(); request.onupgradeneeded = (e) => { - let db = e.target.transaction.db; + const db = e.target.transaction.db; stores.forEach((store) => db.createObjectStore(store, settings)); upgraded = true; }; request.onsuccess = (e) => { - let db = e.target.result; - let simple = new shaka.test.SimpleIDB(db); + const db = e.target.result; + const simple = new shaka.test.SimpleIDB(db); promise.resolve(simple); }; diff --git a/test/test/util/stream_generator.js b/test/test/util/stream_generator.js index 746cf24ed5..6c673682ef 100644 --- a/test/test/util/stream_generator.js +++ b/test/test/util/stream_generator.js @@ -180,7 +180,7 @@ shaka.test.Mp4VodStreamGenerator = function( /** @override */ shaka.test.Mp4VodStreamGenerator.prototype.init = function() { - let async = [ + const async = [ shaka.test.Util.fetch(this.initSegmentUri_), shaka.test.Util.fetch(this.segmentTemplateUri_), ]; @@ -218,9 +218,9 @@ shaka.test.Mp4VodStreamGenerator.prototype.getSegment = function( goog.asserts.assert((position % 1 === 0) && (position >= 1), 'segment number must be an integer >= 1'); - let segmentStartTime = (position - 1) * this.segmentDuration_; + const segmentStartTime = (position - 1) * this.segmentDuration_; - let mediaTimestamp = segmentStartTime + this.presentationTimeOffset_; + const mediaTimestamp = segmentStartTime + this.presentationTimeOffset_; return shaka.test.StreamGenerator.setBaseMediaDecodeTime_( this.segmentTemplate_, this.tfdtOffset_, mediaTimestamp, this.timescale_); @@ -317,7 +317,7 @@ shaka.test.Mp4LiveStreamGenerator = function( /** @override */ shaka.test.Mp4LiveStreamGenerator.prototype.init = function() { - let async = [ + const async = [ shaka.test.Util.fetch(this.initSegmentUri_), shaka.test.Util.fetch(this.segmentTemplateUri_), ]; @@ -356,15 +356,15 @@ shaka.test.Mp4LiveStreamGenerator.prototype.getSegment = function( goog.asserts.assert((position % 1 === 0) && (position >= 1), 'segment number must be an integer >= 1'); - let segmentStartTime = (position - 1) * this.segmentDuration_; + const segmentStartTime = (position - 1) * this.segmentDuration_; // Compute the segment's availability start time and end time. // (See section 5.3.9.5.3 of the DASH spec.) - let segmentAvailabilityStartTime = this.availabilityStartTime_ + + const segmentAvailabilityStartTime = this.availabilityStartTime_ + segmentStartTime + (segmentOffset * this.segmentDuration_) + this.segmentDuration_; - let segmentAvailabiltyEndTime = segmentAvailabilityStartTime + + const segmentAvailabiltyEndTime = segmentAvailabilityStartTime + this.segmentDuration_ + this.timeShiftBufferDepth_; @@ -386,9 +386,9 @@ shaka.test.Mp4LiveStreamGenerator.prototype.getSegment = function( // |availabilityStartTime| may be less than |broadcastStartTime| to align the // stream if the Period's first segment's first timestamp does not equal 0. - let artificialPresentationTimeOffset = + const artificialPresentationTimeOffset = this.broadcastStartTime_ - this.availabilityStartTime_; - let mediaTimestamp = segmentStartTime + + const mediaTimestamp = segmentStartTime + this.presentationTimeOffset_ + artificialPresentationTimeOffset; @@ -411,24 +411,24 @@ shaka.test.Mp4LiveStreamGenerator.prototype.getSegment = function( */ shaka.test.StreamGenerator.getTimescale_ = function( initSegment, mdhdOffset) { - let dataView = new DataView(initSegment); - let reader = new shaka.util.DataViewReader( + const dataView = new DataView(initSegment); + const reader = new shaka.util.DataViewReader( dataView, shaka.util.DataViewReader.Endianness.BIG_ENDIAN); reader.skip(mdhdOffset); - let size = reader.readUint32(); - let type = reader.readUint32(); + const size = reader.readUint32(); + const type = reader.readUint32(); goog.asserts.assert( type == 0x6d646864 /* mdhd */, 'initSegment does not contain an mdhd box at the specified offset.'); - let largesizePresent = size == 1; + const largesizePresent = size == 1; if (largesizePresent) { shaka.log.v2('\'largesize\' field is present.'); reader.skip(8); // Skip 'largesize' field. } - let version = reader.readUint8(); + const version = reader.readUint8(); reader.skip(3); // Skip 'flags' field. // Skip 'creation_time' and 'modification_time' fields. @@ -440,7 +440,7 @@ shaka.test.StreamGenerator.getTimescale_ = function( reader.skip(16); } - let timescale = reader.readUint32(); + const timescale = reader.readUint32(); return timescale; }; @@ -467,30 +467,30 @@ shaka.test.StreamGenerator.setBaseMediaDecodeTime_ = function( // NOTE from Microsoft on the lack of ArrayBuffer.prototype.slice in IE11: // "At this time we do not plan to fix this issue." ~ https://bit.ly/2ywEkpQ // This is the best replacement for segment.slice(0) I could come up with: - let buffer = new ArrayBuffer(segment.byteLength); + const buffer = new ArrayBuffer(segment.byteLength); (new Uint8Array(buffer)).set(new Uint8Array(segment)); - let dataView = new DataView(buffer); - let reader = new shaka.util.DataViewReader( + const dataView = new DataView(buffer); + const reader = new shaka.util.DataViewReader( dataView, shaka.util.DataViewReader.Endianness.BIG_ENDIAN); reader.skip(tfdtOffset); - let size = reader.readUint32(); - let type = reader.readUint32(); + const size = reader.readUint32(); + const type = reader.readUint32(); goog.asserts.assert( type == 0x74666474 /* tfdt */, 'segment does not contain a tfdt box at the specified offset.'); - let largesizePresent = size == 1; + const largesizePresent = size == 1; if (largesizePresent) { shaka.log.v2('\'largesize\' field is present.'); reader.skip(8); // Skip 'largesize' field. } - let version = reader.readUint8(); + const version = reader.readUint8(); reader.skip(3); // Skip 'flags' field. - let pos = reader.getPosition(); + const pos = reader.getPosition(); if (version == 0) { shaka.log.v2('tfdt box is version 0.'); dataView.setUint32(pos, baseMediaDecodeTime * timescale); diff --git a/test/test/util/streaming_engine_util.js b/test/test/util/streaming_engine_util.js index bbf8d9ded4..d9a2dc4276 100644 --- a/test/test/util/streaming_engine_util.js +++ b/test/test/util/streaming_engine_util.js @@ -40,7 +40,7 @@ goog.provide('shaka.test.StreamingEngineUtil'); */ shaka.test.StreamingEngineUtil.createFakeNetworkingEngine = function( getInitSegment, getSegment) { - let netEngine = { + const netEngine = { request: jasmine.createSpy('request'), delays: { // Artificial delays per content type, in seconds. audio: 0, @@ -53,21 +53,21 @@ shaka.test.StreamingEngineUtil.createFakeNetworkingEngine = function( expect(requestType).toBeTruthy(); expect(request.uris.length).toBe(1); - let parts = request.uris[0].split('_'); + const parts = request.uris[0].split('_'); expect(parts.length).toBe(3); - let periodNumber = Number(parts[0]); + const periodNumber = Number(parts[0]); expect(periodNumber).not.toBeNaN(); expect(periodNumber).toBeGreaterThan(0); expect(Math.floor(periodNumber)).toEqual(periodNumber); - let contentType = parts[1]; + const contentType = parts[1]; let buffer; if (parts[2] == 'init') { buffer = getInitSegment(contentType, periodNumber); } else { - let position = Number(parts[2]); + const position = Number(parts[2]); expect(position).not.toBeNaN(); expect(position).toBeGreaterThan(0); expect(Math.floor(position)).toEqual(position); @@ -123,7 +123,7 @@ shaka.test.StreamingEngineUtil.createFakeNetworkingEngine = function( shaka.test.StreamingEngineUtil.createFakePresentationTimeline = function( segmentAvailabilityStart, segmentAvailabilityEnd, presentationDuration, maxSegmentDuration, isLive) { - let timeline = { + const timeline = { getDuration: jasmine.createSpy('getDuration'), setDuration: jasmine.createSpy('setDuration'), getMaxSegmentDuration: jasmine.createSpy('getMaxSegmentDuration'), @@ -198,7 +198,7 @@ shaka.test.StreamingEngineUtil.createFakePresentationTimeline = function( */ shaka.test.StreamingEngineUtil.createManifest = function( periodStartTimes, presentationDuration, segmentDurations) { - let boundsCheckPosition = + const boundsCheckPosition = shaka.test.StreamingEngineUtil.boundsCheckPosition.bind( null, periodStartTimes, presentationDuration, segmentDurations); @@ -210,7 +210,7 @@ shaka.test.StreamingEngineUtil.createManifest = function( */ function find(type, periodNumber, time) { // Note: |time| is relative to a Period's start time. - let position = Math.floor(time / segmentDurations[type]) + 1; + const position = Math.floor(time / segmentDurations[type]) + 1; return boundsCheckPosition(type, periodNumber, position); } @@ -225,15 +225,15 @@ shaka.test.StreamingEngineUtil.createManifest = function( return null; } - let d = segmentDurations[type]; - let getUris = function() { + const d = segmentDurations[type]; + const getUris = function() { return ['' + periodNumber + '_' + type + '_' + position]; }; return new shaka.media.SegmentReference( position, (position - 1) * d, position * d, getUris, 0, null); } - let manifest = { + const manifest = { presentationTimeline: undefined, // Should be set externally. minBufferTime: undefined, // Should be set externally. periods: [], @@ -242,17 +242,18 @@ shaka.test.StreamingEngineUtil.createManifest = function( // Populate the Manifest. let id = 0; for (let i = 0; i < periodStartTimes.length; ++i) { - let period = { + const period = { startTime: periodStartTimes[i], variants: [], textStreams: [], }; - let variant = {}; + const variant = {}; let trickModeVideo; - for (let type in segmentDurations) { - let stream = shaka.test.StreamingEngineUtil.createMockStream(type, id++); + for (const type in segmentDurations) { + const stream = + shaka.test.StreamingEngineUtil.createMockStream(type, id++); stream.createSegmentIndex.and.returnValue(Promise.resolve()); stream.findSegmentPosition.and.callFake(find.bind(null, type, i + 1)); stream.getSegmentReference.and.callFake(get.bind(null, type, i + 1)); @@ -289,7 +290,7 @@ shaka.test.StreamingEngineUtil.createManifest = function( shaka.test.StreamingEngineUtil.boundsCheckPosition = function( periodStartTimes, presentationDuration, segmentDurations, type, periodNumber, position) { - let numSegments = shaka.test.StreamingEngineUtil.getNumSegments( + const numSegments = shaka.test.StreamingEngineUtil.getNumSegments( periodStartTimes, presentationDuration, segmentDurations, type, periodNumber); return position >= 1 && position <= numSegments ? position : null; @@ -307,11 +308,11 @@ shaka.test.StreamingEngineUtil.boundsCheckPosition = function( shaka.test.StreamingEngineUtil.getNumSegments = function( periodStartTimes, presentationDuration, segmentDurations, type, periodNumber) { - let periodIndex = periodNumber - 1; - let nextStartTime = periodIndex < periodStartTimes.length - 1 ? + const periodIndex = periodNumber - 1; + const nextStartTime = periodIndex < periodStartTimes.length - 1 ? periodStartTimes[periodIndex + 1] : presentationDuration; - let periodDuration = nextStartTime - periodStartTimes[periodIndex]; + const periodDuration = nextStartTime - periodStartTimes[periodIndex]; return Math.ceil(periodDuration / segmentDurations[type]); }; diff --git a/test/test/util/test_scheme.js b/test/test/util/test_scheme.js index c003ab204c..88f9e9e879 100644 --- a/test/test/util/test_scheme.js +++ b/test/test/util/test_scheme.js @@ -28,10 +28,10 @@ goog.provide('shaka.test.TestScheme'); * @return {!shaka.extern.IAbortableOperation.<shaka.extern.Response>} */ shaka.test.TestScheme = function(uri, request, requestType) { - let manifestParts = /^test:([^/]+)$/.exec(uri); + const manifestParts = /^test:([^/]+)$/.exec(uri); if (manifestParts) { /** @type {shaka.extern.Response} */ - let response = { + const response = { uri: uri, data: new ArrayBuffer(0), headers: {'content-type': 'application/x-test-manifest'}, @@ -39,29 +39,29 @@ shaka.test.TestScheme = function(uri, request, requestType) { return shaka.util.AbortableOperation.completed(response); } - let malformed = new shaka.util.Error( + const malformed = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.NETWORK, shaka.util.Error.Code.MALFORMED_TEST_URI); - let re = /^test:([^/]+)\/(video|audio)\/(init|[0-9]+)$/; - let segmentParts = re.exec(uri); + const re = /^test:([^/]+)\/(video|audio)\/(init|[0-9]+)$/; + const segmentParts = re.exec(uri); if (!segmentParts) { // Use expect so the URI is printed on errors. expect(uri).toMatch(re); return shaka.util.AbortableOperation.failed(malformed); } - let name = segmentParts[1]; - let type = segmentParts[2]; + const name = segmentParts[1]; + const type = segmentParts[2]; - let generators = shaka.test.TestScheme.GENERATORS[name]; + const generators = shaka.test.TestScheme.GENERATORS[name]; expect(generators).toBeTruthy(); if (!generators) { return shaka.util.AbortableOperation.failed(malformed); } - let generator = generators[type]; + const generator = generators[type]; expect(generator).toBeTruthy(); if (!generator) { return shaka.util.AbortableOperation.failed(malformed); @@ -71,12 +71,12 @@ shaka.test.TestScheme = function(uri, request, requestType) { if (segmentParts[3] === 'init') { responseData = generator.getInitSegment(0); } else { - let index = Number(segmentParts[3]); + const index = Number(segmentParts[3]); responseData = generator.getSegment(index + 1, 0, 0); } /** @type {shaka.extern.Response} */ - let ret = {uri: uri, data: responseData, headers: {}}; + const ret = {uri: uri, data: responseData, headers: {}}; return shaka.util.AbortableOperation.completed(ret); }; @@ -361,22 +361,22 @@ shaka.test.TestScheme.DATA = { * @param {string} name */ shaka.test.TestScheme.setupPlayer = function(player, name) { - let asset = shaka.test.TestScheme.DATA[name]; + const asset = shaka.test.TestScheme.DATA[name]; goog.asserts.assert(asset, 'Unknown asset'); if (!asset) return; if (asset.licenseRequestHeaders) { - let netEngine = player.getNetworkingEngine(); + const netEngine = player.getNetworkingEngine(); netEngine.registerRequestFilter( function(type, request) { if (type != shaka.net.NetworkingEngine.RequestType.LICENSE) return; - for (let header in asset.licenseRequestHeaders) { + for (const header in asset.licenseRequestHeaders) { request.headers[header] = asset.licenseRequestHeaders[header]; } }); } if (asset.licenseServers) { - let config = {drm: {servers: asset.licenseServers}}; + const config = {drm: {servers: asset.licenseServers}}; player.configure(config); } }; @@ -390,7 +390,7 @@ shaka.test.TestScheme.setupPlayer = function(player, name) { */ shaka.test.TestScheme.createManifests = function(shaka, suffix) { /** @type {?} */ - let windowShaka = window['shaka']; + const windowShaka = window['shaka']; /** * @param {Object} metadata @@ -434,7 +434,7 @@ shaka.test.TestScheme.createManifests = function(shaka, suffix) { } if (data.licenseServers) { - for (let keySystem in data.licenseServers) { + for (const keySystem in data.licenseServers) { manifestGenerator.addDrmInfo(keySystem) .licenseServerUri(data.licenseServers[keySystem]); if (data[contentType].initData) { @@ -456,25 +456,25 @@ shaka.test.TestScheme.createManifests = function(shaka, suffix) { return locationUri.resolve(partialUri).toString(); } - let async = []; + const async = []; // Include 'window' to use uncompiled version version of the library. const DATA = windowShaka.test.TestScheme.DATA; const GENERATORS = windowShaka.test.TestScheme.GENERATORS; const MANIFESTS = windowShaka.test.TestScheme.MANIFESTS; const ContentType = windowShaka.util.ManifestParserUtils.ContentType; - for (let name in DATA) { + for (const name in DATA) { GENERATORS[name + suffix] = GENERATORS[name + suffix] || {}; - let data = DATA[name]; + const data = DATA[name]; [ContentType.VIDEO, ContentType.AUDIO].forEach(function(type) { if (data[type]) { - let streamGen = createStreamGenerator(data[type]); + const streamGen = createStreamGenerator(data[type]); GENERATORS[name + suffix][type] = streamGen; async.push(streamGen.init()); } }); - let gen = new windowShaka.test.ManifestGenerator(shaka) + const gen = new windowShaka.test.ManifestGenerator(shaka) .setPresentationDuration(data.duration) .addPeriod(/* startTime= */ 0) .addVariant(0); @@ -592,15 +592,15 @@ shaka.test.TestScheme.ManifestParser.prototype.configure = function(config) {}; /** @override */ shaka.test.TestScheme.ManifestParser.prototype.start = function(uri, playerInterface) { - let re = /^test:([^/]+)$/; - let manifestParts = re.exec(uri); + const re = /^test:([^/]+)$/; + const manifestParts = re.exec(uri); if (!manifestParts) { // Use expect so the URI is printed on errors. expect(uri).toMatch(re); return Promise.reject(); } - let manifest = shaka.test.TestScheme.MANIFESTS[manifestParts[1]]; + const manifest = shaka.test.TestScheme.MANIFESTS[manifestParts[1]]; expect(manifest).toBeTruthy(); if (!manifest) return Promise.reject(); diff --git a/test/test/util/util.js b/test/test/util/util.js index 7bec44af1a..9b8688707e 100644 --- a/test/test/util/util.js +++ b/test/test/util/util.js @@ -79,7 +79,7 @@ shaka.test.Util.fakeEventLoop = function(duration, onTick) { */ shaka.test.Util.delay = function(seconds, realSetTimeout) { return new Promise(function(resolve, reject) { - let timeout = realSetTimeout || setTimeout; + const timeout = realSetTimeout || setTimeout; timeout(function() { resolve(); // Play nicely with PromiseMock by flushing automatically. @@ -113,8 +113,8 @@ shaka.test.Util.expectToEqualError = function(actual, expected) { * @private */ shaka.test.Util.expectToEqualElementCompare_ = function(actual, expected) { - let diff = shaka.test.Util.expectToEqualElementRecursive_(actual, expected); - let result = {}; + const diff = shaka.test.Util.expectToEqualElementRecursive_(actual, expected); + const result = {}; result.pass = diff == null; if (result.pass) { result.message = 'Expected ' + actual.innerHTML + ' not to match '; @@ -134,7 +134,7 @@ shaka.test.Util.expectToEqualElementCompare_ = function(actual, expected) { * @private */ shaka.test.Util.expectToEqualElementRecursive_ = function(actual, expected) { - let prospectiveDiff = 'The difference was in ' + + const prospectiveDiff = 'The difference was in ' + (actual.outerHTML || actual.textContent) + ' vs ' + (expected['outerHTML'] || expected.textContent) + ': '; @@ -155,12 +155,12 @@ shaka.test.Util.expectToEqualElementRecursive_ = function(actual, expected) { return prospectiveDiff + 'Different attribute list length.'; } for (let i = 0; i < actual.attributes.length; i++) { - let aAttrib = actual.attributes[i].nodeName; - let aAttribVal = actual.getAttribute(aAttrib); - let eAttrib = expected.attributes[i].nodeName; - let eAttribVal = expected.getAttribute(eAttrib); + const aAttrib = actual.attributes[i].nodeName; + const aAttribVal = actual.getAttribute(aAttrib); + const eAttrib = expected.attributes[i].nodeName; + const eAttribVal = expected.getAttribute(eAttrib); if (aAttrib != eAttrib || aAttribVal != eAttribVal) { - let diffNote = + const diffNote = aAttrib + '=' + aAttribVal + ' vs ' + eAttrib + '=' + eAttribVal; return prospectiveDiff + 'Attribute #' + i + ' was different (' + diffNote + ').'; @@ -171,9 +171,9 @@ shaka.test.Util.expectToEqualElementRecursive_ = function(actual, expected) { return prospectiveDiff + 'Different child node list length.'; } for (let i = 0; i < actual.childNodes.length; i++) { - let aNode = actual.childNodes[i]; - let eNode = expected.childNodes[i]; - let diff = shaka.test.Util.expectToEqualElementRecursive_(aNode, eNode); + const aNode = actual.childNodes[i]; + const eNode = expected.childNodes[i]; + const diff = shaka.test.Util.expectToEqualElementRecursive_(aNode, eNode); if (diff) { return diff; } @@ -191,13 +191,13 @@ shaka.test.Util.expectToEqualElementRecursive_ = function(actual, expected) { * @return {boolean|undefined} */ shaka.test.Util.compareReferences = function(first, second) { - let isSegment = first instanceof shaka.media.SegmentReference && + const isSegment = first instanceof shaka.media.SegmentReference && second instanceof shaka.media.SegmentReference; - let isInit = first instanceof shaka.media.InitSegmentReference && + const isInit = first instanceof shaka.media.InitSegmentReference && second instanceof shaka.media.InitSegmentReference; if (isSegment || isInit) { - let a = first.getUris(); - let b = second.getUris(); + const a = first.getUris(); + const b = second.getUris(); if (typeof a !== 'object' || typeof b !== 'object' || typeof a.length != 'number' || typeof b.length !== 'number') { return false; @@ -229,7 +229,7 @@ shaka.test.Util.compareReferences = function(first, second) { */ shaka.test.Util.fetch = function(uri) { return new Promise(function(resolve, reject) { - let xhr = new XMLHttpRequest(); + const xhr = new XMLHttpRequest(); xhr.open('GET', uri, true /* asynchronous */); xhr.responseType = 'arraybuffer'; @@ -259,7 +259,7 @@ shaka.test.Util.fetch = function(uri) { * @param {!Object} obj */ shaka.test.Util.makeMockObjectStrict = function(obj) { - for (let name in obj) { + for (const name in obj) { obj[name].and.throwError(new Error(name)); } }; @@ -352,7 +352,7 @@ shaka.test.Util.cleanupUI = async function() { document.querySelectorAll('[data-shaka-player-container]'); const destroys = []; - for (let container of containers) { + for (const container of containers) { const ui = /** @type {shaka.ui.Overlay} */(container['ui']); // Destroying the UI destroys the controls and player inside. @@ -361,7 +361,7 @@ shaka.test.Util.cleanupUI = async function() { await Promise.all(destroys); // Now remove all the containers from the DOM. - for (let container of containers) { + for (const container of containers) { container.parentElement.removeChild(container); } }; diff --git a/test/text/cue_integration.js b/test/text/cue_integration.js index 2fd3b3d552..a5636f4369 100644 --- a/test/text/cue_integration.js +++ b/test/text/cue_integration.js @@ -26,7 +26,7 @@ describe('Cue', function() { it('handles offsets', function() { // Offsets must be handled early. // See issue #502 - let cues = parseVtt( + const cues = parseVtt( 'WEBVTT\n\n' + '00:00:20.000 --> 00:00:40.000\n' + 'Test', @@ -40,7 +40,7 @@ describe('Cue', function() { // To simplify refactoring, we are no longer checking for VTTCue before // setting properties that only exist on VTTCue. So we want to ensure that // errors are not thrown when the extra settings are assigned. - let cues = parseVtt( + const cues = parseVtt( 'WEBVTT\n\n' + 'ID1\n' + '00:00:20.000 --> 00:00:40.000 align:middle size:56% vertical:lr\n' + @@ -55,7 +55,7 @@ describe('Cue', function() { * @return {!Array.<!shaka.extern.Cue>} */ function parseVtt(text, time) { - let data = new Uint8Array(shaka.util.StringUtils.toUTF8(text)); + const data = new Uint8Array(shaka.util.StringUtils.toUTF8(text)); return new shaka.text.VttTextParser().parseMedia(data, time); } }); diff --git a/test/text/mp4_ttml_parser_unit.js b/test/text/mp4_ttml_parser_unit.js index 3955c67889..300f2734e0 100644 --- a/test/text/mp4_ttml_parser_unit.js +++ b/test/text/mp4_ttml_parser_unit.js @@ -50,32 +50,32 @@ describe('Mp4TtmlParser', function() { }); it('parses media segment', function() { - let parser = new shaka.text.Mp4TtmlParser(); + const parser = new shaka.text.Mp4TtmlParser(); parser.parseInit(ttmlInitSegment); - let time = {periodStart: 0, segmentStart: 0, segmentEnd: 0}; - let ret = parser.parseMedia(ttmlSegment, time); + const time = {periodStart: 0, segmentStart: 0, segmentEnd: 0}; + const ret = parser.parseMedia(ttmlSegment, time); expect(ret.length).toBe(10); }); it('handles media segments with multiple mdats', function() { - let parser = new shaka.text.Mp4TtmlParser(); + const parser = new shaka.text.Mp4TtmlParser(); parser.parseInit(ttmlInitSegment); - let time = {periodStart: 0, segmentStart: 0, segmentEnd: 0}; - let ret = parser.parseMedia(ttmlSegmentMultipleMDAT, time); + const time = {periodStart: 0, segmentStart: 0, segmentEnd: 0}; + const ret = parser.parseMedia(ttmlSegmentMultipleMDAT, time); expect(ret.length).toBe(20); }); it('accounts for offset', function() { - let time1 = {periodStart: 0, segmentStart: 0, segmentEnd: 0}; - let time2 = {periodStart: 7, segmentStart: 0, segmentEnd: 0}; + const time1 = {periodStart: 0, segmentStart: 0, segmentEnd: 0}; + const time2 = {periodStart: 7, segmentStart: 0, segmentEnd: 0}; - let parser = new shaka.text.Mp4TtmlParser(); + const parser = new shaka.text.Mp4TtmlParser(); parser.parseInit(ttmlInitSegment); - let ret1 = parser.parseMedia(ttmlSegment, time1); + const ret1 = parser.parseMedia(ttmlSegment, time1); expect(ret1.length).toBeGreaterThan(0); - let ret2 = parser.parseMedia(ttmlSegment, time2); + const ret2 = parser.parseMedia(ttmlSegment, time2); expect(ret2.length).toBeGreaterThan(0); expect(ret2[0].startTime).toEqual(ret1[0].startTime + 7); @@ -83,7 +83,7 @@ describe('Mp4TtmlParser', function() { }); it('rejects init segment with no ttml', function() { - let error = new shaka.util.Error( + const error = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.TEXT, shaka.util.Error.Code.INVALID_MP4_TTML); diff --git a/test/text/mp4_vtt_parser_unit.js b/test/text/mp4_vtt_parser_unit.js index 7946a29144..03d389fa1b 100644 --- a/test/text/mp4_vtt_parser_unit.js +++ b/test/text/mp4_vtt_parser_unit.js @@ -61,7 +61,7 @@ describe('Mp4VttParser', function() { }); it('parses media segment', function() { - let cues = [ + const cues = [ { start: 111.8, end: 115.8, @@ -75,15 +75,15 @@ describe('Mp4VttParser', function() { }, ]; - let parser = new shaka.text.Mp4VttParser(); + const parser = new shaka.text.Mp4VttParser(); parser.parseInit(vttInitSegment); - let time = {periodStart: 0, segmentStart: 0, segmentEnd: 0}; - let result = parser.parseMedia(vttSegment, time); + const time = {periodStart: 0, segmentStart: 0, segmentEnd: 0}; + const result = parser.parseMedia(vttSegment, time); verifyHelper(cues, result); }); it('plays multiple payloads at one time if specified by size', () => { - let cues = [ + const cues = [ { start: 110, end: 113, @@ -103,16 +103,16 @@ describe('Mp4VttParser', function() { }, ]; - let parser = new shaka.text.Mp4VttParser(); + const parser = new shaka.text.Mp4VttParser(); parser.parseInit(vttInitSegment); - let time = {periodStart: 0, segmentStart: 0, segmentEnd: 0}; - let result = parser.parseMedia(vttSegmentMultiPayload, time); + const time = {periodStart: 0, segmentStart: 0, segmentEnd: 0}; + const result = parser.parseMedia(vttSegmentMultiPayload, time); verifyHelper(cues, result); }); it('parses media segment containing settings', function() { const Cue = shaka.text.Cue; - let cues = [ + const cues = [ { start: 111.8, end: 115.8, @@ -131,16 +131,16 @@ describe('Mp4VttParser', function() { }, ]; - let parser = new shaka.text.Mp4VttParser(); + const parser = new shaka.text.Mp4VttParser(); parser.parseInit(vttInitSegment); - let time = {periodStart: 0, segmentStart: 0, segmentEnd: 0}; - let result = parser.parseMedia(vttSegSettings, time); + const time = {periodStart: 0, segmentStart: 0, segmentEnd: 0}; + const result = parser.parseMedia(vttSegSettings, time); verifyHelper(cues, result); }); it('parses media segments without a sample duration', function() { // Regression test for https://github.com/google/shaka-player/issues/919 - let cues = [ + const cues = [ {start: 10, end: 11, payload: 'cue 10'}, {start: 11, end: 12, payload: 'cue 11'}, {start: 12, end: 13, payload: 'cue 12'}, @@ -153,15 +153,15 @@ describe('Mp4VttParser', function() { {start: 19, end: 20, payload: 'cue 19'}, ]; - let parser = new shaka.text.Mp4VttParser(); + const parser = new shaka.text.Mp4VttParser(); parser.parseInit(vttInitSegment); - let time = {periodStart: 0, segmentStart: 0, segmentEnd: 0}; - let result = parser.parseMedia(vttSegNoDuration, time); + const time = {periodStart: 0, segmentStart: 0, segmentEnd: 0}; + const result = parser.parseMedia(vttSegNoDuration, time); verifyHelper(cues, result); }); it('accounts for offset', function() { - let cues = [ + const cues = [ { start: 121.8, end: 125.8, @@ -175,15 +175,15 @@ describe('Mp4VttParser', function() { }, ]; - let parser = new shaka.text.Mp4VttParser(); + const parser = new shaka.text.Mp4VttParser(); parser.parseInit(vttInitSegment); - let time = {periodStart: 10, segmentStart: 0, segmentEnd: 0}; - let result = parser.parseMedia(vttSegment, time); + const time = {periodStart: 10, segmentStart: 0, segmentEnd: 0}; + const result = parser.parseMedia(vttSegment, time); verifyHelper(cues, result); }); it('rejects init segment with no vtt', function() { - let error = new shaka.util.Error( + const error = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.TEXT, shaka.util.Error.Code.INVALID_MP4_VTT); diff --git a/test/text/simple_text_displayer_unit.js b/test/text/simple_text_displayer_unit.js index 78fcb13773..0d037c0aef 100644 --- a/test/text/simple_text_displayer_unit.js +++ b/test/text/simple_text_displayer_unit.js @@ -88,9 +88,9 @@ describe('SimpleTextDisplayer', function() { describe('remove', function() { it('removes cues which overlap the range', function() { - let cue1 = new shaka.text.Cue(0, 1, 'Test'); - let cue2 = new shaka.text.Cue(1, 2, 'Test'); - let cue3 = new shaka.text.Cue(2, 3, 'Test'); + const cue1 = new shaka.text.Cue(0, 1, 'Test'); + const cue2 = new shaka.text.Cue(1, 2, 'Test'); + const cue3 = new shaka.text.Cue(2, 3, 'Test'); displayer.append([cue1, cue2, cue3]); displayer.remove(0, 1); @@ -132,7 +132,7 @@ describe('SimpleTextDisplayer', function() { new shaka.text.Cue(20, 40, 'Test'), ]); - let cue1 = new shaka.text.Cue(20, 40, 'Test'); + const cue1 = new shaka.text.Cue(20, 40, 'Test'); cue1.positionAlign = Cue.positionAlign.LEFT; cue1.lineAlign = Cue.lineAlign.START; cue1.size = 80; @@ -159,7 +159,7 @@ describe('SimpleTextDisplayer', function() { }, ], [cue1]); - let cue2 = new shaka.text.Cue(30, 50, 'Test'); + const cue2 = new shaka.text.Cue(30, 50, 'Test'); cue2.positionAlign = Cue.positionAlign.RIGHT; cue2.lineAlign = Cue.lineAlign.END; cue2.textAlign = Cue.textAlign.RIGHT; @@ -182,7 +182,7 @@ describe('SimpleTextDisplayer', function() { }, ], [cue2]); - let cue3 = new shaka.text.Cue(40, 60, 'Test'); + const cue3 = new shaka.text.Cue(40, 60, 'Test'); cue3.positionAlign = Cue.positionAlign.CENTER; cue3.lineAlign = Cue.lineAlign.CENTER; cue3.textAlign = Cue.textAlign.START; @@ -201,7 +201,7 @@ describe('SimpleTextDisplayer', function() { }, ], [cue3]); - let cue4 = new shaka.text.Cue(40, 60, 'Test'); + const cue4 = new shaka.text.Cue(40, 60, 'Test'); cue4.line = null; cue4.position = null; @@ -218,7 +218,7 @@ describe('SimpleTextDisplayer', function() { }, ], [cue4]); - let cue5 = new shaka.text.Cue(40, 60, 'Test'); + const cue5 = new shaka.text.Cue(40, 60, 'Test'); cue5.line = 0; cue5.position = 0; @@ -255,7 +255,7 @@ describe('SimpleTextDisplayer', function() { } window.VTTCue = /** @type {?} */(FakeVTTCueWithoutAlignCenter); - let cue1 = new shaka.text.Cue(20, 40, 'Test'); + const cue1 = new shaka.text.Cue(20, 40, 'Test'); cue1.textAlign = Cue.textAlign.CENTER; verifyHelper( @@ -271,8 +271,8 @@ describe('SimpleTextDisplayer', function() { }); it('ignores cues with startTime >= endTime', function() { - let cue1 = new shaka.text.Cue(60, 40, 'Test'); - let cue2 = new shaka.text.Cue(40, 40, 'Test'); + const cue1 = new shaka.text.Cue(60, 40, 'Test'); + const cue2 = new shaka.text.Cue(40, 40, 'Test'); displayer.append([cue1, cue2]); expect(mockTrack.addCue).not.toHaveBeenCalled(); }); @@ -289,7 +289,7 @@ describe('SimpleTextDisplayer', function() { function verifyHelper(vttCues, shakaCues) { mockTrack.addCue.calls.reset(); displayer.append(shakaCues); - let result = mockTrack.addCue.calls.allArgs().reduce( + const result = mockTrack.addCue.calls.allArgs().reduce( shaka.util.Functional.collapseArrays, []); expect(result).toBeTruthy(); expect(result.length).toBe(vttCues.length); diff --git a/test/text/text_engine_unit.js b/test/text/text_engine_unit.js index 30ff6fa3ab..88f737592f 100644 --- a/test/text/text_engine_unit.js +++ b/test/text/text_engine_unit.js @@ -91,10 +91,10 @@ describe('TextEngine', function() { }); it('calls displayer.append()', async () => { - let cue1 = createFakeCue(1, 2); - let cue2 = createFakeCue(2, 3); - let cue3 = createFakeCue(3, 4); - let cue4 = createFakeCue(4, 5); + const cue1 = createFakeCue(1, 2); + const cue2 = createFakeCue(2, 3); + const cue3 = createFakeCue(3, 4); + const cue4 = createFakeCue(4, 5); mockParseMedia.and.returnValue([cue1, cue2]); await textEngine.appendBuffer(dummyData, 0, 3); @@ -249,7 +249,7 @@ describe('TextEngine', function() { it('works asynchronously', function(done) { textEngine.appendBuffer(dummyData, 0, 3).then(function() { - let p = textEngine.remove(0, 1); + const p = textEngine.remove(0, 1); expect(mockDisplayer.removeSpy).not.toHaveBeenCalled(); return p; }).catch(fail).then(done); diff --git a/test/text/text_track_integration.js b/test/text/text_track_integration.js index e40804ec09..e26d6a4911 100644 --- a/test/text/text_track_integration.js +++ b/test/text/text_track_integration.js @@ -89,7 +89,7 @@ describe('TextTrackIntegration', function() { describe('addCue', function() { - let cues = [ + const cues = [ new VTTCue(0, 1000, 'Cue 1 message'), new VTTCue(2000, 3000, 'Cue 2 message'), ]; @@ -129,7 +129,7 @@ describe('TextTrackIntegration', function() { }); describe('removeCue', function() { - let cues = [ + const cues = [ new VTTCue(0, 1000, 'Cue 1 message'), new VTTCue(2000, 3000, 'Cue 2 message'), ]; diff --git a/test/text/ttml_text_parser_unit.js b/test/text/ttml_text_parser_unit.js index 38254a2cb2..f4f386c1b6 100644 --- a/test/text/ttml_text_parser_unit.js +++ b/test/text/ttml_text_parser_unit.js @@ -33,7 +33,7 @@ describe('TtmlTextParser', function() { }); it('supports xml:space', function() { - let ttBody = '\n' + + const ttBody = '\n' + ' <body>\n' + ' <p begin="01:02.03" end="01:02.05">\n' + ' <span> A B C </span>\n' + @@ -797,9 +797,9 @@ describe('TtmlTextParser', function() { * @param {shaka.extern.TextParser.TimeContext} time */ function verifyHelper(cues, text, time) { - let data = new Uint8Array(shaka.util.StringUtils.toUTF8(text)); - let result = new shaka.text.TtmlTextParser().parseMedia(data, time); - let properties = ['textAlign', 'lineAlign', 'positionAlign', 'size', + const data = new Uint8Array(shaka.util.StringUtils.toUTF8(text)); + const result = new shaka.text.TtmlTextParser().parseMedia(data, time); + const properties = ['textAlign', 'lineAlign', 'positionAlign', 'size', 'line', 'position', 'direction', 'color', 'writingMode', 'backgroundColor', 'fontWeight', 'fontFamily', 'wrapLine', 'lineHeight', 'fontStyle', 'fontSize']; @@ -815,7 +815,7 @@ describe('TtmlTextParser', function() { } for (let j = 0; j < properties.length; j++) { - let property = properties[j]; + const property = properties[j]; if (property in cues[i]) { expect(result[i][property]).toEqual(cues[i][property]); } @@ -836,14 +836,14 @@ describe('TtmlTextParser', function() { * @param {shaka.extern.CueRegion} actual */ function verifyRegion(expected, actual) { - let properties = ['id', 'viewportAnchorX', 'viewportAnchorY', + const properties = ['id', 'viewportAnchorX', 'viewportAnchorY', 'regionAnchorX', 'regionAnchorY', 'width', 'height', 'heightUnits', 'widthUnits', 'viewportAnchorUnits', 'scroll']; expect(actual).toBeTruthy(); for (let i = 0; i < properties.length; i++) { - let property = properties[i]; + const property = properties[i]; if (property in expected) { expect(actual[property]).toEqual(expected[property]); } @@ -856,10 +856,10 @@ describe('TtmlTextParser', function() { * @param {string} text */ function errorHelper(code, text) { - let error = new shaka.util.Error( + const error = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.TEXT, code); - let data = shaka.util.StringUtils.toUTF8(text); + const data = shaka.util.StringUtils.toUTF8(text); try { new shaka.text.TtmlTextParser().parseMedia( new Uint8Array(data), diff --git a/test/text/vtt_text_parser_unit.js b/test/text/vtt_text_parser_unit.js index f8525491c9..0f3dd0616d 100644 --- a/test/text/vtt_text_parser_unit.js +++ b/test/text/vtt_text_parser_unit.js @@ -594,9 +594,9 @@ describe('VttTextParser', function() { * @param {shaka.extern.TextParser.TimeContext} time */ function verifyHelper(cues, text, time) { - let data = new Uint8Array(shaka.util.StringUtils.toUTF8(text)); + const data = new Uint8Array(shaka.util.StringUtils.toUTF8(text)); - let result = new shaka.text.VttTextParser().parseMedia(data, time); + const result = new shaka.text.VttTextParser().parseMedia(data, time); expect(result).toBeTruthy(); expect(result.length).toBe(cues.length); for (let i = 0; i < cues.length; i++) { @@ -634,14 +634,14 @@ describe('VttTextParser', function() { * @param {shaka.extern.CueRegion} actual */ function verifyRegion(expected, actual) { - let properties = ['id', 'viewportAnchorX', 'viewportAnchorY', + const properties = ['id', 'viewportAnchorX', 'viewportAnchorY', 'regionAnchorX', 'regionAnchorY', 'width', 'height', 'heightUnits', 'widthUnits', 'viewportAnchorUnits', 'scroll']; expect(actual).toBeTruthy(); for (let i = 0; i < properties.length; i++) { - let property = properties[i]; + const property = properties[i]; if (property in expected) { expect(actual[property]).toEqual(expected[property]); } @@ -654,10 +654,10 @@ describe('VttTextParser', function() { * @param {shaka.extern.TextParser.TimeContext} time */ function errorHelper(code, text, time) { - let error = new shaka.util.Error( + const error = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.TEXT, code); - let data = new Uint8Array(shaka.util.StringUtils.toUTF8(text)); + const data = new Uint8Array(shaka.util.StringUtils.toUTF8(text)); try { new shaka.text.VttTextParser().parseMedia(data, time); fail('Invalid WebVTT file supported'); diff --git a/test/ui/ui_unit.js b/test/ui/ui_unit.js index 48c736f4f5..3bde2a8530 100644 --- a/test/ui/ui_unit.js +++ b/test/ui/ui_unit.js @@ -118,14 +118,14 @@ describe('UI', function() { describe('set up with several videos', function() { /** @type {!Array.<!HTMLVideoElement>} */ - let videos = []; + const videos = []; beforeEach(() => { // Four is just a random number I (ismena) came up with to test a // multi-video use case. It could be replaces with any other // (reasonable) number. for (let i = 0; i < 4; i++) { - let video = /** @type {!HTMLVideoElement} */ + const video = /** @type {!HTMLVideoElement} */ (document.createElement('video')); document.body.appendChild(video); @@ -187,22 +187,22 @@ describe('UI', function() { beforeEach(function() { createUIThroughAPI(videoContainer, video); - let controlsContainers = + const controlsContainers = videoContainer.getElementsByClassName('shaka-controls-container'); expect(controlsContainers.length).toBe(1); controlsContainer = /** @type {!HTMLElement} */ (controlsContainers[0]); }); it('stay visible if overflow menuButton is open', function() { - let overflowMenus = + const overflowMenus = videoContainer.getElementsByClassName('shaka-overflow-menu'); expect(overflowMenus.length).toBe(1); - let overflowMenu = /** @type {!HTMLElement} */ (overflowMenus[0]); + const overflowMenu = /** @type {!HTMLElement} */ (overflowMenus[0]); - let overflowMenuButtons = + const overflowMenuButtons = videoContainer.getElementsByClassName('shaka-overflow-menu-button'); expect(overflowMenuButtons.length).toBe(1); - let overflowMenuButton = overflowMenuButtons[0]; + const overflowMenuButton = overflowMenuButtons[0]; overflowMenuButton.click(); expect(overflowMenu.style.display).not.toEqual('none'); @@ -215,14 +215,14 @@ describe('UI', function() { let overflowMenu; beforeEach(function() { - let config = { + const config = { controlPanelElements: [ 'overflow_menu', ], }; createUIThroughAPI(videoContainer, video, config); - let overflowMenus = + const overflowMenus = videoContainer.getElementsByClassName('shaka-overflow-menu'); expect(overflowMenus.length).toBe(1); overflowMenu = /** @type {!HTMLElement} */ (overflowMenus[0]); @@ -239,10 +239,10 @@ describe('UI', function() { let display = window.getComputedStyle(overflowMenu, null).display; expect(display).toEqual('none'); - let overflowMenuButtons = + const overflowMenuButtons = videoContainer.getElementsByClassName('shaka-overflow-menu-button'); expect(overflowMenuButtons.length).toBe(1); - let overflowMenuButton = overflowMenuButtons[0]; + const overflowMenuButton = overflowMenuButtons[0]; overflowMenuButton.click(); display = overflowMenu.style.display; @@ -277,7 +277,7 @@ describe('UI', function() { }); it('is accessible', function() { - for (let button of overflowMenu.childNodes) { + for (const button of overflowMenu.childNodes) { expect(/** @type {!HTMLElement} */ (button) .hasAttribute('aria-label')).toBe(true); } @@ -291,7 +291,7 @@ describe('UI', function() { it('has default elements', function() { createUIThroughAPI(videoContainer, video); - let controlsButtonPanels = videoContainer.getElementsByClassName( + const controlsButtonPanels = videoContainer.getElementsByClassName( 'shaka-controls-button-panel'); expect(controlsButtonPanels.length).toBe(1); @@ -346,7 +346,7 @@ describe('UI', function() { let resolutionsMenu; beforeEach(function() { - let config = { + const config = { controlPanelElements: [ 'overflow_menu', ], @@ -356,7 +356,7 @@ describe('UI', function() { }; createUIThroughAPI(videoContainer, video, config); - let resolutionsMenus = + const resolutionsMenus = videoContainer.getElementsByClassName('shaka-resolutions'); expect(resolutionsMenus.length).toBe(1); resolutionsMenu = /** @type {!HTMLElement} */ (resolutionsMenus[0]); @@ -366,10 +366,10 @@ describe('UI', function() { let display = window.getComputedStyle(resolutionsMenu, null).display; expect(display).toEqual('none'); - let resolutionButtons = + const resolutionButtons = videoContainer.getElementsByClassName('shaka-resolution-button'); expect(resolutionButtons.length).toBe(1); - let resolutionButton = resolutionButtons[0]; + const resolutionButton = resolutionButtons[0]; resolutionButton.click(); display = resolutionsMenu.style.display; @@ -503,13 +503,13 @@ describe('UI', function() { 'fullscreen']}; createUIThroughAPI(container, video, config); - let controlsButtonPanels = + const controlsButtonPanels = container.getElementsByClassName('shaka-controls-button-panel'); expect(controlsButtonPanels.length).toBe(1); - let controlsButtonPanel = + const controlsButtonPanel = /** @type {!HTMLElement} */ (controlsButtonPanels[0]); - let buttons = controlsButtonPanel.childNodes; + const buttons = controlsButtonPanel.childNodes; expect(buttons.length).toBe(3); expect( /** @type {!HTMLElement} */ (buttons[0]).className) diff --git a/test/util/abortable_operation_unit.js b/test/util/abortable_operation_unit.js index 94171fe217..d42c7887a3 100644 --- a/test/util/abortable_operation_unit.js +++ b/test/util/abortable_operation_unit.js @@ -18,10 +18,10 @@ describe('AbortableOperation', function() { describe('promise', function() { it('is resolved by the constructor argument', function(done) { - let promise = new shaka.util.PublicPromise(); - let abort = () => Promise.resolve(); + const promise = new shaka.util.PublicPromise(); + const abort = () => Promise.resolve(); - let operation = new shaka.util.AbortableOperation(promise, abort); + const operation = new shaka.util.AbortableOperation(promise, abort); promise.resolve(100); operation.promise.catch(fail).then((value) => { @@ -33,23 +33,24 @@ describe('AbortableOperation', function() { describe('abort', function() { it('calls the abort argument from the constructor', function() { - let promise = Promise.resolve(); - let abort = jasmine.createSpy('abort').and.returnValue(Promise.resolve()); + const promise = Promise.resolve(); + const abort = + jasmine.createSpy('abort').and.returnValue(Promise.resolve()); - let operation = new shaka.util.AbortableOperation( + const operation = new shaka.util.AbortableOperation( promise, shaka.test.Util.spyFunc(abort)); operation.abort(); expect(abort).toHaveBeenCalled(); }); it('is resolved when the underlying abort() is resolved', function(done) { - let p = new shaka.util.PublicPromise(); - let abort = jasmine.createSpy('abort').and.returnValue(p); + const p = new shaka.util.PublicPromise(); + const abort = jasmine.createSpy('abort').and.returnValue(p); - let operation = new shaka.util.AbortableOperation( + const operation = new shaka.util.AbortableOperation( new shaka.util.PublicPromise(), shaka.test.Util.spyFunc(abort)); - let abortComplete = jasmine.createSpy('abort complete'); + const abortComplete = jasmine.createSpy('abort complete'); operation.abort() .catch(fail).then(shaka.test.Util.spyFunc(abortComplete)); @@ -69,12 +70,12 @@ describe('AbortableOperation', function() { describe('failed', function() { it('creates a failed operation with the given error', function(done) { - let error = new shaka.util.Error( + const error = new shaka.util.Error( shaka.util.Error.Severity.RECOVERABLE, shaka.util.Error.Category.NETWORK, shaka.util.Error.Code.MALFORMED_DATA_URI); - let operation = shaka.util.AbortableOperation.failed(error); + const operation = shaka.util.AbortableOperation.failed(error); operation.promise.then(fail).catch((e) => { shaka.test.Util.expectToEqualError(e, error); }).then(done); @@ -83,12 +84,12 @@ describe('AbortableOperation', function() { describe('aborted', function() { it('creates a failed operation with OPERATION_ABORTED', function(done) { - let error = new shaka.util.Error( + const error = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.PLAYER, shaka.util.Error.Code.OPERATION_ABORTED); - let operation = shaka.util.AbortableOperation.aborted(); + const operation = shaka.util.AbortableOperation.aborted(); operation.promise.then(fail).catch((e) => { shaka.test.Util.expectToEqualError(e, error); }).then(done); @@ -97,7 +98,7 @@ describe('AbortableOperation', function() { describe('completed', function() { it('creates a completed operation with the given value', function(done) { - let operation = shaka.util.AbortableOperation.completed(100); + const operation = shaka.util.AbortableOperation.completed(100); operation.promise.catch(fail).then((value) => { expect(value).toEqual(100); done(); @@ -107,8 +108,8 @@ describe('AbortableOperation', function() { describe('notAbortable', function() { it('creates an operation from the given promise', function(done) { - let promise = new shaka.util.PublicPromise(); - let operation = shaka.util.AbortableOperation.notAbortable(promise); + const promise = new shaka.util.PublicPromise(); + const operation = shaka.util.AbortableOperation.notAbortable(promise); let isAborted = false; operation.abort().then(() => { @@ -141,21 +142,21 @@ describe('AbortableOperation', function() { describe('all', function() { it('creates a successful operation when all succeed', function(done) { - let p1 = new shaka.util.PublicPromise(); - let op1 = shaka.util.AbortableOperation.notAbortable(p1); + const p1 = new shaka.util.PublicPromise(); + const op1 = shaka.util.AbortableOperation.notAbortable(p1); - let p2 = new shaka.util.PublicPromise(); - let op2 = shaka.util.AbortableOperation.notAbortable(p2); + const p2 = new shaka.util.PublicPromise(); + const op2 = shaka.util.AbortableOperation.notAbortable(p2); - let p3 = new shaka.util.PublicPromise(); - let op3 = shaka.util.AbortableOperation.notAbortable(p3); + const p3 = new shaka.util.PublicPromise(); + const op3 = shaka.util.AbortableOperation.notAbortable(p3); - let all = shaka.util.AbortableOperation.all([op1, op2, op3]); + const all = shaka.util.AbortableOperation.all([op1, op2, op3]); - let onSuccessSpy = jasmine.createSpy('onSuccess'); - let onSuccess = shaka.test.Util.spyFunc(onSuccessSpy); - let onErrorSpy = jasmine.createSpy('onError'); - let onError = shaka.test.Util.spyFunc(onErrorSpy); + const onSuccessSpy = jasmine.createSpy('onSuccess'); + const onSuccess = shaka.test.Util.spyFunc(onSuccessSpy); + const onErrorSpy = jasmine.createSpy('onError'); + const onError = shaka.test.Util.spyFunc(onErrorSpy); all.promise.then(onSuccess, onError).catch(fail); @@ -181,21 +182,21 @@ describe('AbortableOperation', function() { }); it('creates a failed operation when any fail', function(done) { - let p1 = new shaka.util.PublicPromise(); - let op1 = shaka.util.AbortableOperation.notAbortable(p1); + const p1 = new shaka.util.PublicPromise(); + const op1 = shaka.util.AbortableOperation.notAbortable(p1); - let p2 = new shaka.util.PublicPromise(); - let op2 = shaka.util.AbortableOperation.notAbortable(p2); + const p2 = new shaka.util.PublicPromise(); + const op2 = shaka.util.AbortableOperation.notAbortable(p2); - let p3 = new shaka.util.PublicPromise(); - let op3 = shaka.util.AbortableOperation.notAbortable(p3); + const p3 = new shaka.util.PublicPromise(); + const op3 = shaka.util.AbortableOperation.notAbortable(p3); - let all = shaka.util.AbortableOperation.all([op1, op2, op3]); + const all = shaka.util.AbortableOperation.all([op1, op2, op3]); - let onSuccessSpy = jasmine.createSpy('onSuccess'); - let onSuccess = shaka.test.Util.spyFunc(onSuccessSpy); - let onErrorSpy = jasmine.createSpy('onError'); - let onError = shaka.test.Util.spyFunc(onErrorSpy); + const onSuccessSpy = jasmine.createSpy('onSuccess'); + const onSuccess = shaka.test.Util.spyFunc(onSuccessSpy); + const onErrorSpy = jasmine.createSpy('onError'); + const onError = shaka.test.Util.spyFunc(onErrorSpy); all.promise.then(onSuccess, onError).catch(fail); @@ -216,30 +217,30 @@ describe('AbortableOperation', function() { }); it('aborts all operations on abort', function(done) { - let p1 = new shaka.util.PublicPromise(); - let abort1Spy = jasmine.createSpy('abort1') + const p1 = new shaka.util.PublicPromise(); + const abort1Spy = jasmine.createSpy('abort1') .and.callFake(() => p1.reject()); - let abort1 = shaka.test.Util.spyFunc(abort1Spy); - let op1 = new shaka.util.AbortableOperation(p1, abort1); + const abort1 = shaka.test.Util.spyFunc(abort1Spy); + const op1 = new shaka.util.AbortableOperation(p1, abort1); - let p2 = new shaka.util.PublicPromise(); - let abort2Spy = jasmine.createSpy('abort2') + const p2 = new shaka.util.PublicPromise(); + const abort2Spy = jasmine.createSpy('abort2') .and.callFake(() => p2.reject()); - let abort2 = shaka.test.Util.spyFunc(abort2Spy); - let op2 = new shaka.util.AbortableOperation(p2, abort2); + const abort2 = shaka.test.Util.spyFunc(abort2Spy); + const op2 = new shaka.util.AbortableOperation(p2, abort2); - let p3 = new shaka.util.PublicPromise(); - let abort3Spy = jasmine.createSpy('abort3') + const p3 = new shaka.util.PublicPromise(); + const abort3Spy = jasmine.createSpy('abort3') .and.callFake(() => p3.reject()); - let abort3 = shaka.test.Util.spyFunc(abort3Spy); - let op3 = new shaka.util.AbortableOperation(p3, abort3); + const abort3 = shaka.test.Util.spyFunc(abort3Spy); + const op3 = new shaka.util.AbortableOperation(p3, abort3); - let all = shaka.util.AbortableOperation.all([op1, op2, op3]); + const all = shaka.util.AbortableOperation.all([op1, op2, op3]); - let onSuccessSpy = jasmine.createSpy('onSuccess'); - let onSuccess = shaka.test.Util.spyFunc(onSuccessSpy); - let onErrorSpy = jasmine.createSpy('onError'); - let onError = shaka.test.Util.spyFunc(onErrorSpy); + const onSuccessSpy = jasmine.createSpy('onSuccess'); + const onSuccess = shaka.test.Util.spyFunc(onSuccessSpy); + const onErrorSpy = jasmine.createSpy('onError'); + const onError = shaka.test.Util.spyFunc(onErrorSpy); all.promise.then(onSuccess, onError).catch(fail); @@ -267,7 +268,7 @@ describe('AbortableOperation', function() { describe('finally', function() { it('executes after the operation is successful', function(done) { let isDone = false; - let promise = new shaka.util.PublicPromise(); + const promise = new shaka.util.PublicPromise(); shaka.util.AbortableOperation.notAbortable(promise).finally((ok) => { expect(ok).toBe(true); @@ -286,7 +287,7 @@ describe('AbortableOperation', function() { it('executes after the operation fails', function(done) { let isDone = false; - let promise = new shaka.util.PublicPromise(); + const promise = new shaka.util.PublicPromise(); shaka.util.AbortableOperation.notAbortable(promise).finally((ok) => { expect(ok).toBe(false); @@ -305,8 +306,8 @@ describe('AbortableOperation', function() { it('executes after the chain is successful', function(done) { let isDone = false; - let promise1 = new shaka.util.PublicPromise(); - let promise2 = new shaka.util.PublicPromise(); + const promise1 = new shaka.util.PublicPromise(); + const promise2 = new shaka.util.PublicPromise(); shaka.util.AbortableOperation.notAbortable(promise1).chain(() => { return shaka.util.AbortableOperation.notAbortable(promise2); @@ -331,8 +332,8 @@ describe('AbortableOperation', function() { it('executes after the chain fails', function(done) { let isDone = false; - let promise1 = new shaka.util.PublicPromise(); - let promise2 = new shaka.util.PublicPromise(); + const promise1 = new shaka.util.PublicPromise(); + const promise2 = new shaka.util.PublicPromise(); shaka.util.AbortableOperation.notAbortable(promise1).chain(() => { return shaka.util.AbortableOperation.notAbortable(promise2); @@ -374,7 +375,7 @@ describe('AbortableOperation', function() { describe('chain', function() { it('passes the value to the next operation on success', function(done) { - let values = []; + const values = []; shaka.util.AbortableOperation.completed(100).chain((value) => { values.push(value); @@ -411,7 +412,7 @@ describe('AbortableOperation', function() { }); it('skips the onSuccess callbacks on error', function(done) { - let error = new shaka.util.Error( + const error = new shaka.util.Error( shaka.util.Error.Severity.RECOVERABLE, shaka.util.Error.Category.NETWORK, shaka.util.Error.Code.MALFORMED_DATA_URI); @@ -431,15 +432,15 @@ describe('AbortableOperation', function() { }); it('can fall back to other operations in onError callback', function(done) { - let error1 = new shaka.util.Error( + const error1 = new shaka.util.Error( shaka.util.Error.Severity.RECOVERABLE, shaka.util.Error.Category.NETWORK, shaka.util.Error.Code.MALFORMED_DATA_URI); - let error2 = new shaka.util.Error( + const error2 = new shaka.util.Error( shaka.util.Error.Severity.RECOVERABLE, shaka.util.Error.Category.TEXT, shaka.util.Error.Code.INVALID_XML); - let error3 = new shaka.util.Error( + const error3 = new shaka.util.Error( shaka.util.Error.Severity.RECOVERABLE, shaka.util.Error.Category.MEDIA, shaka.util.Error.Code.EBML_BAD_FLOATING_POINT_SIZE); @@ -462,11 +463,11 @@ describe('AbortableOperation', function() { }); it('fails when an error is thrown', function(done) { - let error1 = new shaka.util.Error( + const error1 = new shaka.util.Error( shaka.util.Error.Severity.RECOVERABLE, shaka.util.Error.Category.NETWORK, shaka.util.Error.Code.MALFORMED_DATA_URI); - let error2 = new shaka.util.Error( + const error2 = new shaka.util.Error( shaka.util.Error.Severity.RECOVERABLE, shaka.util.Error.Category.TEXT, shaka.util.Error.Code.INVALID_XML); @@ -485,7 +486,7 @@ describe('AbortableOperation', function() { }); it('goes to success state when onError returns undefined', function(done) { - let error = new shaka.util.Error( + const error = new shaka.util.Error( shaka.util.Error.Severity.RECOVERABLE, shaka.util.Error.Category.NETWORK, shaka.util.Error.Code.MALFORMED_DATA_URI); @@ -502,7 +503,7 @@ describe('AbortableOperation', function() { }); it('does not need return when onSuccess omitted', function(done) { - let operation = shaka.util.AbortableOperation.completed(100); + const operation = shaka.util.AbortableOperation.completed(100); operation.chain(undefined, fail).chain(undefined, fail).chain((value) => { expect(value).toEqual(100); }).finally((ok) => { @@ -512,12 +513,12 @@ describe('AbortableOperation', function() { }); it('does not need rethrow when onError omitted', function(done) { - let error = new shaka.util.Error( + const error = new shaka.util.Error( shaka.util.Error.Severity.RECOVERABLE, shaka.util.Error.Category.NETWORK, shaka.util.Error.Code.MALFORMED_DATA_URI); - let operation = shaka.util.AbortableOperation.failed(error); + const operation = shaka.util.AbortableOperation.failed(error); operation.chain(fail).chain(fail).chain(fail).chain(fail, (e) => { shaka.test.Util.expectToEqualError(e, error); }).finally((ok) => { @@ -531,7 +532,7 @@ describe('AbortableOperation', function() { // sometimes unbind an abort method from an earlier stage of the chain. // Make sure this doesn't happen. let innerOperation; - let p = new shaka.util.PublicPromise(); + const p = new shaka.util.PublicPromise(); let abortCalled = false; /** @@ -543,7 +544,7 @@ describe('AbortableOperation', function() { * called with the "this" of the test itself, regardless of what the * library is doing. */ - let abort = function() { + const abort = function() { expect(this).toBe(innerOperation); abortCalled = true; return Promise.resolve(); diff --git a/test/util/data_view_reader_unit.js b/test/util/data_view_reader_unit.js index 50732a6323..27a23460f0 100644 --- a/test/util/data_view_reader_unit.js +++ b/test/util/data_view_reader_unit.js @@ -52,130 +52,130 @@ describe('DataViewReader', function() { }); it('reads a uint8 in big endian', function() { - let value1 = bigEndianReader.readUint8(); + const value1 = bigEndianReader.readUint8(); expect(value1).toBe(0x00); - let value2 = bigEndianReader.readUint8(); + const value2 = bigEndianReader.readUint8(); expect(value2).toBe(0x01); - let value3 = bigEndianReader2.readUint8(); + const value3 = bigEndianReader2.readUint8(); expect(value3).toBe(0xde); - let value4 = bigEndianReader2.readUint8(); + const value4 = bigEndianReader2.readUint8(); expect(value4).toBe(0xad); }); it('reads a uint16 in big endian', function() { - let value1 = bigEndianReader.readUint16(); + const value1 = bigEndianReader.readUint16(); expect(value1).toBe(0x0001); - let value2 = bigEndianReader.readUint16(); + const value2 = bigEndianReader.readUint16(); expect(value2).toBe(0x0203); - let value3 = bigEndianReader2.readUint16(); + const value3 = bigEndianReader2.readUint16(); expect(value3).toBe(0xdead); - let value4 = bigEndianReader2.readUint16(); + const value4 = bigEndianReader2.readUint16(); expect(value4).toBe(0xbeef); }); it('reads a uint32 in big endian', function() { - let value1 = bigEndianReader.readUint32(); + const value1 = bigEndianReader.readUint32(); expect(value1).toBe(0x00010203); - let value2 = bigEndianReader.readUint32(); + const value2 = bigEndianReader.readUint32(); expect(value2).toBe(0x04050607); - let value3 = bigEndianReader2.readUint32(); + const value3 = bigEndianReader2.readUint32(); expect(value3).toBe(0xdeadbeef); - let value4 = bigEndianReader2.readUint32(); + const value4 = bigEndianReader2.readUint32(); expect(value4).toBe(0xffff0100); }); it('reads an int32 in big endian', function() { - let value1 = bigEndianReader.readInt32(); + const value1 = bigEndianReader.readInt32(); expect(value1).toBe(66051); - let value2 = bigEndianReader.readInt32(); + const value2 = bigEndianReader.readInt32(); expect(value2).toBe(67438087); - let value3 = bigEndianReader2.readInt32(); + const value3 = bigEndianReader2.readInt32(); expect(value3).toBe(-559038737); - let value4 = bigEndianReader2.readInt32(); + const value4 = bigEndianReader2.readInt32(); expect(value4).toBe(-65280); }); it('reads a uint64 in big endian', function() { - let value = bigEndianReader.readUint64(); + const value = bigEndianReader.readUint64(); expect(value).toBe(0x0001020304050607); }); it('reads a uint8 in little endian', function() { - let value1 = littleEndianReader.readUint8(); + const value1 = littleEndianReader.readUint8(); expect(value1).toBe(0x00); - let value2 = littleEndianReader.readUint8(); + const value2 = littleEndianReader.readUint8(); expect(value2).toBe(0x01); - let value3 = littleEndianReader2.readUint8(); + const value3 = littleEndianReader2.readUint8(); expect(value3).toBe(0xde); - let value4 = littleEndianReader2.readUint8(); + const value4 = littleEndianReader2.readUint8(); expect(value4).toBe(0xad); }); it('reads a uint16 in little endian', function() { - let value1 = littleEndianReader.readUint16(); + const value1 = littleEndianReader.readUint16(); expect(value1).toBe(0x0100); - let value2 = littleEndianReader.readUint16(); + const value2 = littleEndianReader.readUint16(); expect(value2).toBe(0x0302); - let value3 = littleEndianReader2.readUint16(); + const value3 = littleEndianReader2.readUint16(); expect(value3).toBe(0xadde); - let value4 = littleEndianReader2.readUint16(); + const value4 = littleEndianReader2.readUint16(); expect(value4).toBe(0xefbe); }); it('reads a uint32 in little endian', function() { - let value1 = littleEndianReader.readUint32(); + const value1 = littleEndianReader.readUint32(); expect(value1).toBe(0x03020100); - let value2 = littleEndianReader.readUint32(); + const value2 = littleEndianReader.readUint32(); expect(value2).toBe(0x07060504); - let value3 = littleEndianReader2.readUint32(); + const value3 = littleEndianReader2.readUint32(); expect(value3).toBe(0xefbeadde); - let value4 = littleEndianReader2.readUint32(); + const value4 = littleEndianReader2.readUint32(); expect(value4).toBe(0x0001ffff); }); it('reads an int32 in little endian', function() { - let value1 = littleEndianReader.readInt32(); + const value1 = littleEndianReader.readInt32(); expect(value1).toBe(50462976); - let value2 = littleEndianReader.readInt32(); + const value2 = littleEndianReader.readInt32(); expect(value2).toBe(117835012); - let value3 = littleEndianReader2.readInt32(); + const value3 = littleEndianReader2.readInt32(); expect(value3).toBe(-272716322); - let value4 = littleEndianReader2.readInt32(); + const value4 = littleEndianReader2.readInt32(); expect(value4).toBe(131071); }); it('reads a uint64 in little endian', function() { - let value = littleEndianReader2.readUint64(); + const value = littleEndianReader2.readUint64(); expect(value).toBe(0x0001ffffefbeadde); }); it('skips bytes', function() { bigEndianReader.skip(1); - let value = bigEndianReader.readUint8(); + const value = bigEndianReader.readUint8(); expect(value).toBe(0x01); }); diff --git a/test/util/ebml_parser_unit.js b/test/util/ebml_parser_unit.js index edfc73b005..2e61b1db86 100644 --- a/test/util/ebml_parser_unit.js +++ b/test/util/ebml_parser_unit.js @@ -22,10 +22,10 @@ describe('EbmlParser', /** @suppress {accessControls} */ function() { // Set ID to 0x1. // Set size to 4 bytes. // Set the data to [0x01, 0x02, 0x03, 0x04]. - let data = new Uint8Array([0x81, 0x84, 0x01, 0x02, 0x03, 0x04]); - let parser = new shaka.util.EbmlParser(new DataView(data.buffer)); + const data = new Uint8Array([0x81, 0x84, 0x01, 0x02, 0x03, 0x04]); + const parser = new shaka.util.EbmlParser(new DataView(data.buffer)); - let elem = parser.parseElement(); + const elem = parser.parseElement(); expect(elem.id).toBe(0x81); expect(elem.dataView_.byteLength).toBe(4); expect(elem.dataView_.getUint8(0)).toBe(0x01); @@ -43,11 +43,11 @@ describe('EbmlParser', /** @suppress {accessControls} */ function() { // Set ID to 0x2. // Set size to 4 bytes. // Set the data to [0x09, 0x08, 0x07, 0x06]. - let data = new Uint8Array([0x81, 0x84, 0x01, 0x02, 0x03, 0x04, 0x82, 0x84, + const data = new Uint8Array([0x81, 0x84, 0x01, 0x02, 0x03, 0x04, 0x82, 0x84, 0x09, 0x08, 0x07, 0x06]); - let parser = new shaka.util.EbmlParser(new DataView(data.buffer)); + const parser = new shaka.util.EbmlParser(new DataView(data.buffer)); - let elem1 = parser.parseElement(); + const elem1 = parser.parseElement(); expect(elem1.id).toBe(0x81); expect(elem1.dataView_.byteLength).toBe(4); expect(elem1.dataView_.getUint8(0)).toBe(0x01); @@ -55,7 +55,7 @@ describe('EbmlParser', /** @suppress {accessControls} */ function() { expect(elem1.dataView_.getUint8(2)).toBe(0x03); expect(elem1.dataView_.getUint8(3)).toBe(0x04); - let elem2 = parser.parseElement(); + const elem2 = parser.parseElement(); expect(elem2.id).toBe(0x82); expect(elem2.dataView_.byteLength).toBe(4); expect(elem2.dataView_.getUint8(0)).toBe(0x09); @@ -69,9 +69,9 @@ describe('EbmlParser', /** @suppress {accessControls} */ function() { // Set size to a dynamic size value. // The size should be 5 bytes. // Set the data to [0xaa, 0xbb, 0xcc, 0xdd, 0xee]. - let data = new Uint8Array([0x81, 0xff, 0xaa, 0xbb, 0xcc, 0xdd, 0xee]); - let parser = new shaka.util.EbmlParser(new DataView(data.buffer)); - let element = parser.parseElement(); + const data = new Uint8Array([0x81, 0xff, 0xaa, 0xbb, 0xcc, 0xdd, 0xee]); + const parser = new shaka.util.EbmlParser(new DataView(data.buffer)); + const element = parser.parseElement(); expect(element).toBeTruthy(); expect(element.dataView_.byteLength).toBe(5); @@ -79,13 +79,13 @@ describe('EbmlParser', /** @suppress {accessControls} */ function() { it('parses a 1 byte vint', function() { // 7-bit value: 1|100 0001 - let data = new Uint8Array([0xc1]); + const data = new Uint8Array([0xc1]); // Extract the variable sized integer from |data|. Note that since // |data| contains exactly one variable sized integer, |vint| should be // identical to |data|. - let parser = new shaka.util.EbmlParser(new DataView(data.buffer)); - let vint = parser.parseVint_(); + const parser = new shaka.util.EbmlParser(new DataView(data.buffer)); + const vint = parser.parseVint_(); expect(shaka.util.EbmlParser.getVintValue_(data)).toBe(0x41); expect(shaka.util.EbmlParser.getVintValue_(vint)).toBe(0x41); @@ -93,10 +93,10 @@ describe('EbmlParser', /** @suppress {accessControls} */ function() { it('parses a 2 byte vint', function() { // 14-bit: 01|10 0001, 0001 1001 - let data = new Uint8Array([0x61, 0x19]); + const data = new Uint8Array([0x61, 0x19]); - let parser = new shaka.util.EbmlParser(new DataView(data.buffer)); - let vint = parser.parseVint_(); + const parser = new shaka.util.EbmlParser(new DataView(data.buffer)); + const vint = parser.parseVint_(); expect(shaka.util.EbmlParser.getVintValue_(data)).toBe(0x2119); expect(shaka.util.EbmlParser.getVintValue_(vint)).toBe(0x2119); @@ -104,10 +104,10 @@ describe('EbmlParser', /** @suppress {accessControls} */ function() { it('parses a 3 byte vint', function() { // 21-bit: 001|1 0001, 0010 0001, 0001 0011 - let data = new Uint8Array([0x31, 0x21, 0x13]); + const data = new Uint8Array([0x31, 0x21, 0x13]); - let parser = new shaka.util.EbmlParser(new DataView(data.buffer)); - let vint = parser.parseVint_(); + const parser = new shaka.util.EbmlParser(new DataView(data.buffer)); + const vint = parser.parseVint_(); expect(shaka.util.EbmlParser.getVintValue_(data)).toBe(0x112113); expect(shaka.util.EbmlParser.getVintValue_(vint)).toBe(0x112113); @@ -115,10 +115,10 @@ describe('EbmlParser', /** @suppress {accessControls} */ function() { it('parses a 4 byte vint', function() { // 28-bit: 0001 | 1000, 0001 0001, 0001 0001, 0001 0101 - let data = new Uint8Array([0x18, 0x11, 0x11, 0x15]); + const data = new Uint8Array([0x18, 0x11, 0x11, 0x15]); - let parser = new shaka.util.EbmlParser(new DataView(data.buffer)); - let vint = parser.parseVint_(); + const parser = new shaka.util.EbmlParser(new DataView(data.buffer)); + const vint = parser.parseVint_(); expect(shaka.util.EbmlParser.getVintValue_(data)).toBe(0x8111115); expect(shaka.util.EbmlParser.getVintValue_(vint)).toBe(0x8111115); @@ -126,10 +126,10 @@ describe('EbmlParser', /** @suppress {accessControls} */ function() { it('parses a 5 byte vint', function() { // 35-bit: 0000 1|100, 0001 0001, 0001 0001, 0001 0001, 0001 1001 - let data = new Uint8Array([0x0c, 0x11, 0x11, 0x11, 0x19]); + const data = new Uint8Array([0x0c, 0x11, 0x11, 0x11, 0x19]); - let parser = new shaka.util.EbmlParser(new DataView(data.buffer)); - let vint = parser.parseVint_(); + const parser = new shaka.util.EbmlParser(new DataView(data.buffer)); + const vint = parser.parseVint_(); expect(shaka.util.EbmlParser.getVintValue_(data)).toBe(0x411111119); expect(shaka.util.EbmlParser.getVintValue_(vint)).toBe(0x411111119); @@ -138,10 +138,10 @@ describe('EbmlParser', /** @suppress {accessControls} */ function() { it('parses a 6 byte vint', function() { // 42-bit: 0000 01|10, 0001 0010, 0001 0001, 0001 0001, 0001 0001, // 0001 1000 - let data = new Uint8Array([0x06, 0x12, 0x11, 0x11, 0x11, 0x18]); + const data = new Uint8Array([0x06, 0x12, 0x11, 0x11, 0x11, 0x18]); - let parser = new shaka.util.EbmlParser(new DataView(data.buffer)); - let vint = parser.parseVint_(); + const parser = new shaka.util.EbmlParser(new DataView(data.buffer)); + const vint = parser.parseVint_(); expect(shaka.util.EbmlParser.getVintValue_(data)).toBe(0x21211111118); expect(shaka.util.EbmlParser.getVintValue_(vint)).toBe(0x21211111118); @@ -150,10 +150,10 @@ describe('EbmlParser', /** @suppress {accessControls} */ function() { it('parses a 7 byte vint', function() { // 49-bit: 0000 001|1, 0001 0010, 0001 0001, 0001 0001, 0001 0001, // 0001 0001, 1001 0001 - let data = new Uint8Array([0x03, 0x12, 0x11, 0x11, 0x11, 0x11, 0x91]); + const data = new Uint8Array([0x03, 0x12, 0x11, 0x11, 0x11, 0x11, 0x91]); - let parser = new shaka.util.EbmlParser(new DataView(data.buffer)); - let vint = parser.parseVint_(); + const parser = new shaka.util.EbmlParser(new DataView(data.buffer)); + const vint = parser.parseVint_(); expect(shaka.util.EbmlParser.getVintValue_(data)).toBe(0x1121111111191); expect(shaka.util.EbmlParser.getVintValue_(vint)).toBe(0x1121111111191); @@ -162,10 +162,11 @@ describe('EbmlParser', /** @suppress {accessControls} */ function() { it('parses a 8 byte vint', function() { // 56-bit: 0000 0001 | 0001 0010, 0001 0100, 0001 1000, 0001 0001, // 0001 0001, 0001 1001, 0011 0001 - let data = new Uint8Array([0x01, 0x12, 0x14, 0x18, 0x11, 0x11, 0x19, 0x31]); + const data = + new Uint8Array([0x01, 0x12, 0x14, 0x18, 0x11, 0x11, 0x19, 0x31]); - let parser = new shaka.util.EbmlParser(new DataView(data.buffer)); - let vint = parser.parseVint_(); + const parser = new shaka.util.EbmlParser(new DataView(data.buffer)); + const vint = parser.parseVint_(); expect(shaka.util.EbmlParser.getVintValue_(data)).toBe(0x12141811111931); expect(shaka.util.EbmlParser.getVintValue_(vint)).toBe(0x12141811111931); @@ -178,9 +179,9 @@ describe('EbmlParser', /** @suppress {accessControls} */ function() { // 63-bit: 0000 0000, 1|000 0001, 0001 0001, 0001 0001, 0001 0001, // 0001 0001, 0001 0001, 0001 0001, // 0001 0001 - let data = new Uint8Array( + const data = new Uint8Array( [0x00, 0x81, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11]); - let parser = new shaka.util.EbmlParser(new DataView(data.buffer)); + const parser = new shaka.util.EbmlParser(new DataView(data.buffer)); parser.parseVint_(); } catch (e) { exception = e; @@ -197,7 +198,7 @@ describe('EbmlParser', /** @suppress {accessControls} */ function() { try { // 56-bit: 0000 0001 | 1000 0001, 0001 0001, 0001 0001, 0001 0001, // 0001 0001, 0001 0001, 0001 0001 - let data = new Uint8Array( + const data = new Uint8Array( [0x01, 0x81, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11]); shaka.util.EbmlParser.getVintValue_(data); } catch (e) { @@ -213,7 +214,7 @@ describe('EbmlParser', /** @suppress {accessControls} */ function() { try { // 56-bit: 0000 0001 | 0100 0001, 0001 0001, 0001 0001, 0001 0001, // 0001 0001, 0001 0001, 0001 0001 - let data = new Uint8Array( + const data = new Uint8Array( [0x01, 0x41, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11]); shaka.util.EbmlParser.getVintValue_(data); } catch (e) { @@ -229,7 +230,7 @@ describe('EbmlParser', /** @suppress {accessControls} */ function() { try { // 56-bit: 0000 0001 | 0010 0001, 0001 0001, 0001 0001, 0001 0001, // 0001 0001, 0001 0001, 0001 0001 - let data = new Uint8Array( + const data = new Uint8Array( [0x01, 0x21, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11]); shaka.util.EbmlParser.getVintValue_(data); } catch (e) { @@ -243,8 +244,8 @@ describe('EbmlParser', /** @suppress {accessControls} */ function() { it('detects the end of input while reading a vint', function() { // 14-bit: 01|10 0001, 0001 0001 - let data = new Uint8Array([0x61]); - let parser = new shaka.util.EbmlParser(new DataView(data.buffer)); + const data = new Uint8Array([0x61]); + const parser = new shaka.util.EbmlParser(new DataView(data.buffer)); let exception = null; @@ -263,10 +264,10 @@ describe('EbmlParser', /** @suppress {accessControls} */ function() { // Set ID to 0x1. // Set size to 4 bytes. // Set the data to [0x01, 0x02, 0x03, 0x04]. - let data = new Uint8Array([0x81, 0x84, 0x01, 0x02, 0x03, 0x04]); - let parser = new shaka.util.EbmlParser(new DataView(data.buffer)); + const data = new Uint8Array([0x81, 0x84, 0x01, 0x02, 0x03, 0x04]); + const parser = new shaka.util.EbmlParser(new DataView(data.buffer)); - let elem = parser.parseElement(); + const elem = parser.parseElement(); expect(elem.id).toBe(0x81); expect(elem.getUint()).toBe(0x01020304); }); @@ -275,11 +276,11 @@ describe('EbmlParser', /** @suppress {accessControls} */ function() { // Set ID to 0x1. // Set size to 9 bytes. // Set the data to [0x01, 0x02, 0x03, ..., 0x09]. - let data = new Uint8Array( + const data = new Uint8Array( [0x81, 0x89, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09]); - let parser = new shaka.util.EbmlParser(new DataView(data.buffer)); + const parser = new shaka.util.EbmlParser(new DataView(data.buffer)); - let elem = parser.parseElement(); + const elem = parser.parseElement(); expect(elem.id).toBe(0x81); let exception = null; @@ -299,11 +300,11 @@ describe('EbmlParser', /** @suppress {accessControls} */ function() { // Set ID to 0x1. // Set size to 8 bytes. // Set the data to [0x2f, 0xff, 0xff, ..., 0xff]. - let data = new Uint8Array( + const data = new Uint8Array( [0x81, 0x88, 0x2f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]); - let parser = new shaka.util.EbmlParser(new DataView(data.buffer)); + const parser = new shaka.util.EbmlParser(new DataView(data.buffer)); - let elem = parser.parseElement(); + const elem = parser.parseElement(); expect(elem.id).toBe(0x81); let exception = null; @@ -320,7 +321,7 @@ describe('EbmlParser', /** @suppress {accessControls} */ function() { }); it('recognizes dynamic-sized values', function() { - let dynamicSizes = [ + const dynamicSizes = [ new Uint8Array([0xff]), new Uint8Array([0x7f, 0xff]), new Uint8Array([0x3f, 0xff, 0xff]), @@ -331,7 +332,7 @@ describe('EbmlParser', /** @suppress {accessControls} */ function() { new Uint8Array([0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]), ]; - let isDynamicSizeValue_ = shaka.util.EbmlParser.isDynamicSizeValue_; + const isDynamicSizeValue_ = shaka.util.EbmlParser.isDynamicSizeValue_; expect(isDynamicSizeValue_(dynamicSizes[0])).toBe(true); expect(isDynamicSizeValue_(dynamicSizes[1])).toBe(true); diff --git a/test/util/event_manager_unit.js b/test/util/event_manager_unit.js index 99c23ea07e..a37bf6f23c 100644 --- a/test/util/event_manager_unit.js +++ b/test/util/event_manager_unit.js @@ -47,7 +47,7 @@ describe('EventManager', function() { describe('listen', () => { it('listens for an event', function() { - let listener = jasmine.createSpy('listener'); + const listener = jasmine.createSpy('listener'); eventManager.listen(target1, 'eventtype1', Util.spyFunc(listener)); target1.dispatchEvent(event1); @@ -56,8 +56,8 @@ describe('EventManager', function() { }); it('listens for an event from mutiple targets', function() { - let listener1 = jasmine.createSpy('listener1'); - let listener2 = jasmine.createSpy('listener2'); + const listener1 = jasmine.createSpy('listener1'); + const listener2 = jasmine.createSpy('listener2'); eventManager.listen(target1, 'eventtype1', Util.spyFunc(listener1)); eventManager.listen(target2, 'eventtype1', Util.spyFunc(listener2)); @@ -70,8 +70,8 @@ describe('EventManager', function() { }); it('listens for multiple events', function() { - let listener1 = jasmine.createSpy('listener1'); - let listener2 = jasmine.createSpy('listener2'); + const listener1 = jasmine.createSpy('listener1'); + const listener2 = jasmine.createSpy('listener2'); eventManager.listen(target1, 'eventtype1', Util.spyFunc(listener1)); eventManager.listen(target1, 'eventtype2', Util.spyFunc(listener2)); @@ -84,8 +84,8 @@ describe('EventManager', function() { }); it('listens for multiple events from mutiple targets', function() { - let listener1 = jasmine.createSpy('listener1'); - let listener2 = jasmine.createSpy('listener2'); + const listener1 = jasmine.createSpy('listener1'); + const listener2 = jasmine.createSpy('listener2'); eventManager.listen(target1, 'eventtype1', Util.spyFunc(listener1)); eventManager.listen(target2, 'eventtype2', Util.spyFunc(listener2)); @@ -98,8 +98,8 @@ describe('EventManager', function() { }); it('listens for an event with multiple listeners', function() { - let listener1 = jasmine.createSpy('listener1'); - let listener2 = jasmine.createSpy('listener2'); + const listener1 = jasmine.createSpy('listener1'); + const listener2 = jasmine.createSpy('listener2'); eventManager.listen(target1, 'eventtype1', Util.spyFunc(listener1)); eventManager.listen(target1, 'eventtype1', Util.spyFunc(listener2)); @@ -141,7 +141,7 @@ describe('EventManager', function() { describe('unlisten', () => { it('stops listening to an event', function() { - let listener = jasmine.createSpy('listener'); + const listener = jasmine.createSpy('listener'); eventManager.listen(target1, 'eventtype1', Util.spyFunc(listener)); eventManager.unlisten(target1, 'eventtype1'); @@ -152,8 +152,8 @@ describe('EventManager', function() { }); it('ignores other targets when removing listeners', function() { - let listener1 = jasmine.createSpy('listener1'); - let listener2 = jasmine.createSpy('listener2'); + const listener1 = jasmine.createSpy('listener1'); + const listener2 = jasmine.createSpy('listener2'); eventManager.listen(target1, 'eventtype1', Util.spyFunc(listener1)); eventManager.listen(target2, 'eventtype1', Util.spyFunc(listener2)); @@ -167,8 +167,8 @@ describe('EventManager', function() { describe('removeAll', () => { it('stops listening to multiple events', function() { - let listener1 = jasmine.createSpy('listener1'); - let listener2 = jasmine.createSpy('listener2'); + const listener1 = jasmine.createSpy('listener1'); + const listener2 = jasmine.createSpy('listener2'); eventManager.listen(target1, 'eventtype1', Util.spyFunc(listener1)); eventManager.listen(target1, 'eventtype2', Util.spyFunc(listener2)); @@ -183,8 +183,8 @@ describe('EventManager', function() { }); it('stops listening for an event with multiple listeners', function() { - let listener1 = jasmine.createSpy('listener1'); - let listener2 = jasmine.createSpy('listener2'); + const listener1 = jasmine.createSpy('listener1'); + const listener2 = jasmine.createSpy('listener2'); eventManager.listen(target1, 'eventtype1', Util.spyFunc(listener1)); eventManager.listen(target1, 'eventtype1', Util.spyFunc(listener2)); diff --git a/test/util/fake_event_target_unit.js b/test/util/fake_event_target_unit.js index b6f39d7ffc..528eb99dbc 100644 --- a/test/util/fake_event_target_unit.js +++ b/test/util/fake_event_target_unit.js @@ -50,8 +50,8 @@ describe('FakeEventTarget', function() { }); it('calls all event listeners', function(done) { - let listener1 = jasmine.createSpy('listener1'); - let listener2 = jasmine.createSpy('listener2'); + const listener1 = jasmine.createSpy('listener1'); + const listener2 = jasmine.createSpy('listener2'); target.addEventListener('event', Util.spyFunc(listener1)); target.addEventListener('event', Util.spyFunc(listener2)); @@ -66,8 +66,8 @@ describe('FakeEventTarget', function() { }); it('stops processing on stopImmediatePropagation', function(done) { - let listener1 = jasmine.createSpy('listener1'); - let listener2 = jasmine.createSpy('listener2'); + const listener1 = jasmine.createSpy('listener1'); + const listener2 = jasmine.createSpy('listener2'); target.addEventListener('event', Util.spyFunc(listener1)); target.addEventListener('event', Util.spyFunc(listener2)); @@ -86,8 +86,8 @@ describe('FakeEventTarget', function() { }); it('catches exceptions thrown from listeners', function(done) { - let listener1 = jasmine.createSpy('listener1'); - let listener2 = jasmine.createSpy('listener2'); + const listener1 = jasmine.createSpy('listener1'); + const listener2 = jasmine.createSpy('listener2'); target.addEventListener('event', Util.spyFunc(listener1)); target.addEventListener('event', Util.spyFunc(listener2)); @@ -106,14 +106,14 @@ describe('FakeEventTarget', function() { }); it('allows events to be re-dispatched', function(done) { - let listener1 = jasmine.createSpy('listener1'); - let listener2 = jasmine.createSpy('listener2'); + const listener1 = jasmine.createSpy('listener1'); + const listener2 = jasmine.createSpy('listener2'); target.addEventListener('event', Util.spyFunc(listener1)); target.addEventListener('event', Util.spyFunc(listener2)); - let target2 = new shaka.util.FakeEventTarget(); - let target2Listener = jasmine.createSpy('target2Listener'); + const target2 = new shaka.util.FakeEventTarget(); + const target2Listener = jasmine.createSpy('target2Listener'); target2.addEventListener('event', Util.spyFunc(target2Listener)); diff --git a/test/util/manifest_parser_utils_unit.js b/test/util/manifest_parser_utils_unit.js index 53c66f2464..98b5dfaecc 100644 --- a/test/util/manifest_parser_utils_unit.js +++ b/test/util/manifest_parser_utils_unit.js @@ -20,46 +20,46 @@ describe('ManifestParserUtils', function() { describe('resolveUris', function() { it('resolves relative URIs', function() { - let base = ['http://example.com/']; - let relative = ['page.html']; - let expected = ['http://example.com/page.html']; - let actual = ManifestParserUtils.resolveUris(base, relative); + const base = ['http://example.com/']; + const relative = ['page.html']; + const expected = ['http://example.com/page.html']; + const actual = ManifestParserUtils.resolveUris(base, relative); expect(actual).toEqual(expected); }); it('resolves URIs multiplicatively', function() { - let base = ['http://example.com/', 'http://example.org']; - let relative = ['page.html', 'site.css']; - let expected = [ + const base = ['http://example.com/', 'http://example.org']; + const relative = ['page.html', 'site.css']; + const expected = [ 'http://example.com/page.html', 'http://example.com/site.css', 'http://example.org/page.html', 'http://example.org/site.css', ]; - let actual = ManifestParserUtils.resolveUris(base, relative); + const actual = ManifestParserUtils.resolveUris(base, relative); expect(actual).toEqual(expected); }); it('returns base if no relative URIs', function() { - let base = ['http://example.com']; - let relative = []; - let actual = ManifestParserUtils.resolveUris(base, relative); + const base = ['http://example.com']; + const relative = []; + const actual = ManifestParserUtils.resolveUris(base, relative); expect(actual).toEqual(base); }); it('handles manifest file as base URI', function() { - let base = [ + const base = [ 'http://example.com/manifest.mpd', 'http://example.org/path/to/manifest.mpd', ]; - let relative = ['segment.mp4', 'other/location/segment.webm']; - let expected = [ + const relative = ['segment.mp4', 'other/location/segment.webm']; + const expected = [ 'http://example.com/segment.mp4', 'http://example.com/other/location/segment.webm', 'http://example.org/path/to/segment.mp4', 'http://example.org/path/to/other/location/segment.webm', ]; - let actual = ManifestParserUtils.resolveUris(base, relative); + const actual = ManifestParserUtils.resolveUris(base, relative); expect(actual).toEqual(expected); }); }); diff --git a/test/util/mp4_parser_unit.js b/test/util/mp4_parser_unit.js index 6dc42c7c85..809fad93d7 100644 --- a/test/util/mp4_parser_unit.js +++ b/test/util/mp4_parser_unit.js @@ -115,7 +115,7 @@ describe('Mp4Parser', function() { describe('headerDefinitions', function() { it('reads box header', function() { - let callback = jasmine.createSpy('parser callback').and.callFake( + const callback = jasmine.createSpy('parser callback').and.callFake( function(box) { expect(box.size).toEqual(12); expect(box.version).toEqual(null); @@ -129,7 +129,7 @@ describe('Mp4Parser', function() { }); it('reads full box header', function() { - let callback = jasmine.createSpy('parser callback').and.callFake( + const callback = jasmine.createSpy('parser callback').and.callFake( function(box) { expect(box.size).toEqual(16); expect(box.version).toEqual(1); @@ -145,17 +145,17 @@ describe('Mp4Parser', function() { describe('boxDefinitions', function() { it('reads children definition', function() { - let parentBox = jasmine.createSpy('parent box').and.callFake( + const parentBox = jasmine.createSpy('parent box').and.callFake( shaka.util.Mp4Parser.children); - let childBox1 = jasmine.createSpy('child box 1').and.callFake( + const childBox1 = jasmine.createSpy('child box 1').and.callFake( function(box) { expect(box.size).toEqual(12); expect(box.version).toEqual(null); expect(box.flags).toEqual(null); }); - let childBox2 = jasmine.createSpy('child box 2').and.callFake( + const childBox2 = jasmine.createSpy('child box 2').and.callFake( function(box) { expect(box.size).toEqual(12); expect(box.version).toEqual(null); @@ -173,15 +173,15 @@ describe('Mp4Parser', function() { }); it('stops reading children when asked to', function() { - let parentBox = jasmine.createSpy('parent box').and.callFake( + const parentBox = jasmine.createSpy('parent box').and.callFake( shaka.util.Mp4Parser.children); - let childBox1 = jasmine.createSpy('child box 1').and.callFake( + const childBox1 = jasmine.createSpy('child box 1').and.callFake( function(box) { box.parser.stop(); }); - let childBox2 = jasmine.createSpy('child box 2'); + const childBox2 = jasmine.createSpy('child box 2'); new shaka.util.Mp4Parser() .box('b003', Util.spyFunc(parentBox)) @@ -210,10 +210,10 @@ describe('Mp4Parser', function() { }); it('reads sample description definition', function() { - let parentBox = jasmine.createSpy('parent box').and.callFake( + const parentBox = jasmine.createSpy('parent box').and.callFake( shaka.util.Mp4Parser.sampleDescription); - let childBox1 = jasmine.createSpy('child box 1'); - let childBox2 = jasmine.createSpy('child box 2'); + const childBox1 = jasmine.createSpy('child box 1'); + const childBox2 = jasmine.createSpy('child box 2'); new shaka.util.Mp4Parser() .box('b003', Util.spyFunc(parentBox)) @@ -226,13 +226,13 @@ describe('Mp4Parser', function() { }); it('stops reading sample description when asked to', function() { - let parentBox = jasmine.createSpy('parent box').and.callFake( + const parentBox = jasmine.createSpy('parent box').and.callFake( shaka.util.Mp4Parser.sampleDescription); - let childBox1 = jasmine.createSpy('child box 1').and.callFake( + const childBox1 = jasmine.createSpy('child box 1').and.callFake( function(box) { box.parser.stop(); }); - let childBox2 = jasmine.createSpy('child box 2'); + const childBox2 = jasmine.createSpy('child box 2'); new shaka.util.Mp4Parser() .box('b003', Util.spyFunc(parentBox)) @@ -247,9 +247,9 @@ describe('Mp4Parser', function() { describe('parsing', function() { it('finds all top level boxes', function() { - let box1 = jasmine.createSpy('box 1'); - let box2 = jasmine.createSpy('box 2'); - let box3 = jasmine.createSpy('box 3'); + const box1 = jasmine.createSpy('box 1'); + const box2 = jasmine.createSpy('box 2'); + const box3 = jasmine.createSpy('box 3'); new shaka.util.Mp4Parser() .box('b001', Util.spyFunc(box1)) @@ -265,8 +265,8 @@ describe('Mp4Parser', function() { // By leaving a single box undefined, it should not interfere // with the other boxes (on the same level) from being read. - let box1 = jasmine.createSpy('box 1'); - let box3 = jasmine.createSpy('box 3'); + const box1 = jasmine.createSpy('box 1'); + const box3 = jasmine.createSpy('box 3'); new shaka.util.Mp4Parser() .box('b001', Util.spyFunc(box1)) @@ -277,9 +277,9 @@ describe('Mp4Parser', function() { }); it('does not parse child boxes with undefined parent box', function() { - let box1 = jasmine.createSpy('box 1'); - let box2Child = jasmine.createSpy('box 2 child'); - let box3 = jasmine.createSpy('box 3'); + const box1 = jasmine.createSpy('box 1'); + const box2Child = jasmine.createSpy('box 2 child'); + const box3 = jasmine.createSpy('box 3'); // Listing a definition for box 2's child but not for box 2 should mean // box 2's child is never parsed. @@ -294,10 +294,10 @@ describe('Mp4Parser', function() { }); it('can parse partial parent box and find first child', function() { - let parentBox = jasmine.createSpy('parent box').and.callFake( + const parentBox = jasmine.createSpy('parent box').and.callFake( shaka.util.Mp4Parser.sampleDescription); - let childBox1 = jasmine.createSpy('child box 1').and.callFake( + const childBox1 = jasmine.createSpy('child box 1').and.callFake( function(box) { // We found what we were looking for, so stop parsing. box.parser.stop(); diff --git a/test/util/object_utils_unit.js b/test/util/object_utils_unit.js index e0e2f3bf68..097125ed94 100644 --- a/test/util/object_utils_unit.js +++ b/test/util/object_utils_unit.js @@ -38,7 +38,7 @@ describe('ObjectUtils', function() { }); it('clones nested objects', function() { - let o = { + const o = { foo: 'bar', lorem: 'ipsum', dolor: { @@ -59,21 +59,21 @@ describe('ObjectUtils', function() { other: 123, }, }; - let copy = cloneObject(o); + const copy = cloneObject(o); expect(copy).not.toBe(o); expect(copy).toEqual(o); }); it('clones Arrays with non-default length', function() { - let a = [1, 2, 3]; + const a = [1, 2, 3]; a.length = 10; - let copy = cloneObject(a); + const copy = cloneObject(a); expect(copy).toEqual(a); expect(copy.length).toEqual(10); }); it('ignores cyclic objects', function() { - let o = {foo: 'bar'}; + const o = {foo: 'bar'}; o['baz'] = o; expect(cloneObject(o)).toEqual({foo: 'bar', baz: null}); }); diff --git a/test/util/pssh_unit.js b/test/util/pssh_unit.js index 550135a4e4..01b8ebe564 100644 --- a/test/util/pssh_unit.js +++ b/test/util/pssh_unit.js @@ -16,8 +16,8 @@ */ describe('Pssh', function() { - let fromHex = shaka.util.Uint8ArrayUtils.fromHex; - let toHex = shaka.util.Uint8ArrayUtils.toHex; + const fromHex = shaka.util.Uint8ArrayUtils.fromHex; + const toHex = shaka.util.Uint8ArrayUtils.toHex; const WIDEVINE_SYSTEM_ID = 'edef8ba979d64acea3c827dcd51d21ed'; const PLAYREADY_SYSTEM_ID = '9a04f07998404286ab92e65be0885f95'; @@ -74,28 +74,28 @@ describe('Pssh', function() { GENERIC_PSSH.substr(0, GENERIC_PSSH.length - 6); it('parses a Widevine PSSH', function() { - let pssh = new shaka.util.Pssh(fromHex(WIDEVINE_PSSH)); + const pssh = new shaka.util.Pssh(fromHex(WIDEVINE_PSSH)); expect(pssh.systemIds.length).toBe(1); expect(pssh.systemIds[0]).toBe(WIDEVINE_SYSTEM_ID); expect(pssh.cencKeyIds.length).toBe(0); }); it('parses a PlayReady PSSH', function() { - let pssh = new shaka.util.Pssh(fromHex(PLAYREADY_PSSH)); + const pssh = new shaka.util.Pssh(fromHex(PLAYREADY_PSSH)); expect(pssh.systemIds.length).toBe(1); expect(pssh.systemIds[0]).toBe(PLAYREADY_SYSTEM_ID); expect(pssh.cencKeyIds.length).toBe(0); }); it('parses a generic CENC PSSH', function() { - let pssh = new shaka.util.Pssh(fromHex(GENERIC_PSSH)); + const pssh = new shaka.util.Pssh(fromHex(GENERIC_PSSH)); expect(pssh.systemIds.length).toBe(1); expect(pssh.systemIds[0]).toBe(GENERIC_SYSTEM_ID); expect(pssh.cencKeyIds.length).toBe(2); }); it('throws on a truncated PSSH', function() { - let psshs = [ + const psshs = [ fromHex(TRUNCATED_WIDEVINE_PSSH), fromHex(TRUNCATED_PLAYREADY_PSSH), fromHex(TRUNCATED_GENERIC_PSSH), @@ -109,7 +109,7 @@ describe('Pssh', function() { for (let i = 0; i < psshs.length; ++i) { try { - let pssh = new shaka.util.Pssh(psshs[i]); + const pssh = new shaka.util.Pssh(psshs[i]); expect(pssh).toBeTruthy(); // Closure: don't complain about unused vars fail(); } catch (error) { @@ -224,25 +224,25 @@ describe('Pssh', function() { }); it('extracts boundaries for concatenated boxes', function() { - let psshData = fromHex( + const psshData = fromHex( GENERIC_PSSH + WIDEVINE_PSSH + OTHER_BOX + PLAYREADY_PSSH); - let pssh = new shaka.util.Pssh(psshData); + const pssh = new shaka.util.Pssh(psshData); expect(pssh.dataBoundaries.length).toBe(3); - let data1 = psshData.subarray( + const data1 = psshData.subarray( pssh.dataBoundaries[0].start, pssh.dataBoundaries[0].end + 1); - let data2 = psshData.subarray( + const data2 = psshData.subarray( pssh.dataBoundaries[1].start, pssh.dataBoundaries[1].end + 1); - let data3 = psshData.subarray( + const data3 = psshData.subarray( pssh.dataBoundaries[2].start, pssh.dataBoundaries[2].end + 1); diff --git a/test/util/stream_utils_unit.js b/test/util/stream_utils_unit.js index 24a26d1ed8..c98b664d18 100644 --- a/test/util/stream_utils_unit.js +++ b/test/util/stream_utils_unit.js @@ -35,7 +35,7 @@ describe('StreamUtils', function() { .language('en') .build(); - let chosen = filterStreamsByLanguageAndRole( + const chosen = filterStreamsByLanguageAndRole( manifest.periods[0].textStreams, 'en', ''); @@ -54,7 +54,7 @@ describe('StreamUtils', function() { .primary() .build(); - let chosen = filterStreamsByLanguageAndRole( + const chosen = filterStreamsByLanguageAndRole( manifest.periods[0].textStreams, 'en', ''); @@ -76,7 +76,7 @@ describe('StreamUtils', function() { .roles(['caption']) .build(); - let chosen = filterStreamsByLanguageAndRole( + const chosen = filterStreamsByLanguageAndRole( manifest.periods[0].textStreams, 'en', 'main'); @@ -97,7 +97,7 @@ describe('StreamUtils', function() { .roles(['secondary']) .build(); - let chosen = filterStreamsByLanguageAndRole( + const chosen = filterStreamsByLanguageAndRole( manifest.periods[0].textStreams, 'en', ''); @@ -118,7 +118,7 @@ describe('StreamUtils', function() { .roles(['secondary']) .build(); - let chosen = filterStreamsByLanguageAndRole( + const chosen = filterStreamsByLanguageAndRole( manifest.periods[0].textStreams, 'en', 'main'); // A role that is not present. @@ -150,7 +150,7 @@ describe('StreamUtils', function() { .roles(['main']) .build(); - let chosen = filterStreamsByLanguageAndRole( + const chosen = filterStreamsByLanguageAndRole( manifest.periods[0].textStreams, 'en', ''); @@ -184,7 +184,7 @@ describe('StreamUtils', function() { .roles(['main']) .build(); - let chosen = filterStreamsByLanguageAndRole( + const chosen = filterStreamsByLanguageAndRole( manifest.periods[0].textStreams, 'zh', ''); @@ -208,7 +208,7 @@ describe('StreamUtils', function() { .language('es').primary() .build(); - let chosen = filterStreamsByLanguageAndRole( + const chosen = filterStreamsByLanguageAndRole( manifest.periods[0].textStreams, 'zh', ''); @@ -242,7 +242,7 @@ describe('StreamUtils', function() { .roles(['main']) .build(); - let chosen = filterStreamsByLanguageAndRole( + const chosen = filterStreamsByLanguageAndRole( manifest.periods[0].textStreams, 'zh', ''); @@ -281,7 +281,7 @@ describe('StreamUtils', function() { .roles(['main']) .build(); - let chosen = filterStreamsByLanguageAndRole( + const chosen = filterStreamsByLanguageAndRole( manifest.periods[0].textStreams, 'zh', ''); @@ -305,7 +305,7 @@ describe('StreamUtils', function() { .addAudio(2).channelsCount(2) .build(); - let chosen = filterVariantsByAudioChannelCount( + const chosen = filterVariantsByAudioChannelCount( manifest.periods[0].variants, 2); expect(chosen.length).toBe(2); expect(chosen[0]).toBe(manifest.periods[0].variants[0]); @@ -324,7 +324,7 @@ describe('StreamUtils', function() { .addAudio(2).channelsCount(2) .build(); - let chosen = filterVariantsByAudioChannelCount( + const chosen = filterVariantsByAudioChannelCount( manifest.periods[0].variants, 6); expect(chosen.length).toBe(2); expect(chosen[0]).toBe(manifest.periods[0].variants[0]); @@ -343,7 +343,7 @@ describe('StreamUtils', function() { .addAudio(2).channelsCount(6) .build(); - let chosen = filterVariantsByAudioChannelCount( + const chosen = filterVariantsByAudioChannelCount( manifest.periods[0].variants, 2); expect(chosen.length).toBe(2); expect(chosen[0]).toBe(manifest.periods[0].variants[0]); @@ -367,8 +367,8 @@ describe('StreamUtils', function() { .addTextStream(4).mime('application/mp4', 'bogus') .build(); - let noAudio = null; - let noVideo = null; + const noAudio = null; + const noVideo = null; shaka.util.StreamUtils.filterNewPeriod( fakeDrmEngine, noAudio, noVideo, manifest.periods[0]); @@ -376,7 +376,7 @@ describe('StreamUtils', function() { // The last two streams should be removed because their full MIME types // are bogus. expect(manifest.periods[0].textStreams.length).toBe(2); - let textStreams = manifest.periods[0].textStreams; + const textStreams = manifest.periods[0].textStreams; expect(textStreams[0].id).toBe(1); expect(textStreams[1].id).toBe(2); }); diff --git a/test/util/string_utils_unit.js b/test/util/string_utils_unit.js index 32ed0f081a..849185d5d0 100644 --- a/test/util/string_utils_unit.js +++ b/test/util/string_utils_unit.js @@ -21,16 +21,16 @@ describe('StringUtils', function() { it('parses fromUTF8', function() { // This is 4 Unicode characters, the last will be split into a surrogate // pair. - let arr = [0x46, 0xe2, 0x82, 0xac, 0x20, 0xf0, 0x90, 0x8d, 0x88]; - let buffer = new Uint8Array(arr).buffer; + const arr = [0x46, 0xe2, 0x82, 0xac, 0x20, 0xf0, 0x90, 0x8d, 0x88]; + const buffer = new Uint8Array(arr).buffer; expect(StringUtils.fromUTF8(buffer)).toBe('F\u20ac \ud800\udf48'); }); it('strips the BOM in fromUTF8', function() { // This is 4 Unicode characters, the last will be split into a surrogate // pair. - let arr = [0xef, 0xbb, 0xbf, 0x74, 0x65, 0x78, 0x74]; - let buffer = new Uint8Array(arr).buffer; + const arr = [0xef, 0xbb, 0xbf, 0x74, 0x65, 0x78, 0x74]; + const buffer = new Uint8Array(arr).buffer; const ContentType = shaka.util.ManifestParserUtils.ContentType; expect(StringUtils.fromUTF8(buffer)).toBe(ContentType.TEXT); }); @@ -38,60 +38,60 @@ describe('StringUtils', function() { it('parses fromUTF16 big-endian', function() { // This is big-endian pairs of 16-bit numbers. This translates into 3 // Unicode characters where the last is split into a surrogate pair. - let arr = [0x00, 0x46, 0x38, 0x01, 0xd8, 0x01, 0xdc, 0x37]; - let buffer = new Uint8Array(arr).buffer; + const arr = [0x00, 0x46, 0x38, 0x01, 0xd8, 0x01, 0xdc, 0x37]; + const buffer = new Uint8Array(arr).buffer; expect(StringUtils.fromUTF16(buffer, false)).toBe('F\u3801\ud801\udc37'); }); it('parses fromUTF16 little-endian', function() { // This is little-endian pairs of 16-bit numbers. This translates into 3 // Unicode characters where the last is split into a surrogate pair. - let arr = [0x46, 0x00, 0x01, 0x38, 0x01, 0xd8, 0x37, 0xdc]; - let buffer = new Uint8Array(arr).buffer; + const arr = [0x46, 0x00, 0x01, 0x38, 0x01, 0xd8, 0x37, 0xdc]; + const buffer = new Uint8Array(arr).buffer; expect(StringUtils.fromUTF16(buffer, true)).toBe('F\u3801\ud801\udc37'); }); describe('fromBytesAutoDetect', function() { it('detects UTF-8 BOM', function() { - let arr = [0xef, 0xbb, 0xbf, 0x46, 0x6f, 0x6f]; - let buffer = new Uint8Array(arr).buffer; + const arr = [0xef, 0xbb, 0xbf, 0x46, 0x6f, 0x6f]; + const buffer = new Uint8Array(arr).buffer; expect(StringUtils.fromBytesAutoDetect(buffer)).toBe('Foo'); }); it('detects UTF-16 BE BOM', function() { - let arr = [0xfe, 0xff, 0x00, 0x46, 0x00, 0x6f, 0x00, 0x6f]; - let buffer = new Uint8Array(arr).buffer; + const arr = [0xfe, 0xff, 0x00, 0x46, 0x00, 0x6f, 0x00, 0x6f]; + const buffer = new Uint8Array(arr).buffer; expect(StringUtils.fromBytesAutoDetect(buffer)).toBe('Foo'); }); it('detects UTF-16 LE BOM', function() { - let arr = [0xff, 0xfe, 0x46, 0x00, 0x6f, 0x00, 0x6f, 0x00]; - let buffer = new Uint8Array(arr).buffer; + const arr = [0xff, 0xfe, 0x46, 0x00, 0x6f, 0x00, 0x6f, 0x00]; + const buffer = new Uint8Array(arr).buffer; expect(StringUtils.fromBytesAutoDetect(buffer)).toBe('Foo'); }); it('guesses UTF-8', function() { - let arr = [0x46, 0x6f, 0x6f]; - let buffer = new Uint8Array(arr).buffer; + const arr = [0x46, 0x6f, 0x6f]; + const buffer = new Uint8Array(arr).buffer; expect(StringUtils.fromBytesAutoDetect(buffer)).toBe('Foo'); }); it('guesses UTF-16 BE', function() { - let arr = [0x00, 0x46, 0x00, 0x6f, 0x00, 0x6f]; - let buffer = new Uint8Array(arr).buffer; + const arr = [0x00, 0x46, 0x00, 0x6f, 0x00, 0x6f]; + const buffer = new Uint8Array(arr).buffer; expect(StringUtils.fromBytesAutoDetect(buffer)).toBe('Foo'); }); it('guesses UTF-16 LE', function() { - let arr = [0x46, 0x00, 0x6f, 0x00, 0x6f, 0x00]; - let buffer = new Uint8Array(arr).buffer; + const arr = [0x46, 0x00, 0x6f, 0x00, 0x6f, 0x00]; + const buffer = new Uint8Array(arr).buffer; expect(StringUtils.fromBytesAutoDetect(buffer)).toBe('Foo'); }); it('fails if unable to guess', function() { try { - let arr = [0x01, 0x02, 0x03, 0x04]; - let buffer = new Uint8Array(arr).buffer; + const arr = [0x01, 0x02, 0x03, 0x04]; + const buffer = new Uint8Array(arr).buffer; StringUtils.fromBytesAutoDetect(buffer); fail('Should not be able to guess'); } catch (e) { @@ -102,9 +102,9 @@ describe('StringUtils', function() { }); it('converts toUTF8', function() { - let str = 'Xe\u4524\u1952'; - let arr = [0x58, 0x65, 0xe4, 0x94, 0xa4, 0xe1, 0xa5, 0x92]; - let buffer = StringUtils.toUTF8(str); + const str = 'Xe\u4524\u1952'; + const arr = [0x58, 0x65, 0xe4, 0x94, 0xa4, 0xe1, 0xa5, 0x92]; + const buffer = StringUtils.toUTF8(str); expect(new Uint8Array(buffer)).toEqual(new Uint8Array(arr)); }); @@ -123,7 +123,7 @@ describe('StringUtils', function() { }); it('does not cause stack overflow, #335', function() { - let buffer = new Uint8Array(8e5).buffer; // Well above arg count limit. + const buffer = new Uint8Array(8e5).buffer; // Well above arg count limit. expect(StringUtils.fromUTF8(buffer).length).toBe(buffer.byteLength); expect(StringUtils.fromUTF16(buffer, true).length) .toBe(buffer.byteLength / 2); diff --git a/test/util/text_parser_unit.js b/test/util/text_parser_unit.js index 92acaabb0e..07316e42ce 100644 --- a/test/util/text_parser_unit.js +++ b/test/util/text_parser_unit.js @@ -20,23 +20,23 @@ describe('TextParser', function() { describe('atEnd', function() { it('is false at start', function() { - let parser = new TextParser('FOO'); + const parser = new TextParser('FOO'); expect(parser.atEnd()).toBe(false); }); it('is true if no data at start', function() { - let parser = new TextParser(''); + const parser = new TextParser(''); expect(parser.atEnd()).toBe(true); }); it('is false if there is more after read', function() { - let parser = new TextParser('FOO BAR'); + const parser = new TextParser('FOO BAR'); parser.readRegex(/FOO/g); expect(parser.atEnd()).toBe(false); }); it('is true at the end', function() { - let parser = new TextParser('FOO'); + const parser = new TextParser('FOO'); parser.readLine(); expect(parser.atEnd()).toBe(true); }); @@ -44,24 +44,24 @@ describe('TextParser', function() { describe('readLine', function() { it('returns null at end', function() { - let parser = new TextParser(''); + const parser = new TextParser(''); expect(parser.atEnd()).toBe(true); expect(parser.readLine()).toBe(null); }); it('returns line read', function() { - let parser = new TextParser('A Line\n Another'); + const parser = new TextParser('A Line\n Another'); expect(parser.readLine()).toBe('A Line'); }); it('reads to end of string', function() { - let parser = new TextParser('A Line'); + const parser = new TextParser('A Line'); expect(parser.readLine()).toBe('A Line'); expect(parser.atEnd()).toBe(true); }); it('will return empty lines', function() { - let parser = new TextParser('Line\n\nNew Line'); + const parser = new TextParser('Line\n\nNew Line'); expect(parser.readLine()).toBe('Line'); expect(parser.readLine()).toBe(''); expect(parser.readLine()).toBe('New Line'); @@ -70,30 +70,30 @@ describe('TextParser', function() { describe('readWord', function() { it('returns null at end', function() { - let parser = new TextParser(''); + const parser = new TextParser(''); expect(parser.atEnd()).toBe(true); expect(parser.readWord()).toBe(null); }); it('returns word read', function() { - let parser = new TextParser('FOO BAR'); + const parser = new TextParser('FOO BAR'); expect(parser.readWord()).toBe('FOO'); }); it('moves position correctly', function() { - let parser = new TextParser('FOO BAR'); + const parser = new TextParser('FOO BAR'); expect(parser.readWord()).toBe('FOO'); expect(parser.readLine()).toBe(' BAR'); }); it('reads to end', function() { - let parser = new TextParser('FOO'); + const parser = new TextParser('FOO'); expect(parser.readWord()).toBe('FOO'); expect(parser.atEnd()).toBe(true); }); it('reads to end of line', function() { - let parser = new TextParser('FOO\nBAR'); + const parser = new TextParser('FOO\nBAR'); expect(parser.readWord()).toBe('FOO'); expect(parser.readRegex(/\nBAR/gm)).toBeTruthy(); }); @@ -101,44 +101,44 @@ describe('TextParser', function() { describe('readRegex', function() { it('returns null at end', function() { - let parser = new TextParser(''); + const parser = new TextParser(''); expect(parser.atEnd()).toBe(true); expect(parser.readRegex(/(?:)/g)).toBe(null); }); it('moves position', function() { - let parser = new TextParser('FOOBAR'); + const parser = new TextParser('FOOBAR'); expect(parser.readRegex(/FOO/g)).toBeTruthy(); expect(parser.readLine()).toBe('BAR'); }); it('will read to end', function() { - let parser = new TextParser('FOO'); + const parser = new TextParser('FOO'); expect(parser.readRegex(/FO+/g)).toBeTruthy(); expect(parser.atEnd()).toBe(true); }); it('only reads if matches', function() { - let parser = new TextParser('FOO'); + const parser = new TextParser('FOO'); expect(parser.readRegex(/CAT/g)).toBe(null); expect(parser.readLine()).toBe('FOO'); }); it('only reads if match is at current position', function() { - let parser = new TextParser('AABB'); + const parser = new TextParser('AABB'); expect(parser.readRegex(/B+/g)).toBe(null); expect(parser.readLine()).toBe('AABB'); }); it('only reads the first match', function() { - let parser = new TextParser('AABBAA'); + const parser = new TextParser('AABBAA'); expect(parser.readRegex(/A+/g)).toBeTruthy(); expect(parser.readLine()).toBe('BBAA'); }); it('returns results object', function() { - let parser = new TextParser('00:11:22'); - let results = parser.readRegex(/(\d+):(\d+):/g); + const parser = new TextParser('00:11:22'); + const results = parser.readRegex(/(\d+):(\d+):/g); expect(results).toBeTruthy(); expect(results.length).toBe(3); expect(results[0]).toBe('00:11:'); @@ -149,25 +149,25 @@ describe('TextParser', function() { describe('skipWhitespace', function() { it('skips blocks of whitespace', function() { - let parser = new TextParser(' CAT'); + const parser = new TextParser(' CAT'); parser.skipWhitespace(); expect(parser.readRegex(/CAT/g)).toBeTruthy(); }); it('skips mixed whitespace', function() { - let parser = new TextParser(' \t\t CAT'); + const parser = new TextParser(' \t\t CAT'); parser.skipWhitespace(); expect(parser.readRegex(/CAT/g)).toBeTruthy(); }); it('does not skip newlines', function() { - let parser = new TextParser(' \nCAT'); + const parser = new TextParser(' \nCAT'); parser.skipWhitespace(); expect(parser.readRegex(/\nCAT/gm)).toBeTruthy(); }); it('will skip to end of string', function() { - let parser = new TextParser(' '); + const parser = new TextParser(' '); expect(parser.atEnd()).toBe(false); parser.skipWhitespace(); expect(parser.atEnd()).toBe(true); diff --git a/test/util/xml_utils_unit.js b/test/util/xml_utils_unit.js index e2acf8c11f..3edc014889 100644 --- a/test/util/xml_utils_unit.js +++ b/test/util/xml_utils_unit.js @@ -23,16 +23,16 @@ describe('XmlUtils', function() { describe('findChild', function() { it('finds a child node', function() { - let xmlString = [ + const xmlString = [ '<?xml version="1.0"?>', '<Root>', ' <Child></Child>', '</Root>', ].join('\n'); - let xml = new DOMParser().parseFromString(xmlString, 'application/xml'); + const xml = new DOMParser().parseFromString(xmlString, 'application/xml'); goog.asserts.assert(xml, 'parseFromString should succeed'); - let root = XmlUtils.findChild(xml, 'Root'); + const root = XmlUtils.findChild(xml, 'Root'); goog.asserts.assert(root, 'findChild should find element'); expect(XmlUtils.findChild(root, 'Child')).toBeTruthy(); @@ -40,17 +40,17 @@ describe('XmlUtils', function() { }); it('handles duplicate child nodes', function() { - let xmlString = [ + const xmlString = [ '<?xml version="1.0"?>', '<Root>', ' <Child></Child>', ' <Child></Child>', '</Root>', ].join('\n'); - let xml = new DOMParser().parseFromString(xmlString, 'application/xml'); + const xml = new DOMParser().parseFromString(xmlString, 'application/xml'); goog.asserts.assert(xml, 'parseFromString should succeed'); - let root = XmlUtils.findChild(xml, 'Root'); + const root = XmlUtils.findChild(xml, 'Root'); goog.asserts.assert(root, 'findChild should find element'); expect(XmlUtils.findChild(root, 'Child')).toBeNull(); @@ -58,17 +58,17 @@ describe('XmlUtils', function() { }); it('findChildren', function() { - let xmlString = [ + const xmlString = [ '<?xml version="1.0"?>', '<Root>', ' <Child></Child>', ' <Child></Child>', '</Root>', ].join('\n'); - let xml = new DOMParser().parseFromString(xmlString, 'application/xml'); + const xml = new DOMParser().parseFromString(xmlString, 'application/xml'); goog.asserts.assert(xml, 'parseFromString should succeed'); - let roots = XmlUtils.findChildren(xml, 'Root'); + const roots = XmlUtils.findChildren(xml, 'Root'); expect(roots).toBeTruthy(); expect(roots.length).toBe(1); @@ -81,57 +81,57 @@ describe('XmlUtils', function() { describe('getContents', function() { it('returns node contents', function() { - let xmlString = [ + const xmlString = [ '<?xml version="1.0"?>', '<Root>', ' foo bar', '</Root>', ].join('\n'); - let xml = new DOMParser().parseFromString(xmlString, 'application/xml'); + const xml = new DOMParser().parseFromString(xmlString, 'application/xml'); goog.asserts.assert(xml, 'parseFromString should succeed'); - let root = XmlUtils.findChild(xml, 'Root'); + const root = XmlUtils.findChild(xml, 'Root'); goog.asserts.assert(root, 'findChild should find element'); expect(XmlUtils.getContents(root)).toBe('foo bar'); }); it('handles empty node contents', function() { - let xmlString = [ + const xmlString = [ '<?xml version="1.0"?>', '<Root>', '</Root>', ].join('\n'); - let xml = new DOMParser().parseFromString(xmlString, 'application/xml'); + const xml = new DOMParser().parseFromString(xmlString, 'application/xml'); goog.asserts.assert(xml, 'parseFromString should succeed'); - let root = XmlUtils.findChild(xml, 'Root'); + const root = XmlUtils.findChild(xml, 'Root'); goog.asserts.assert(root, 'findChild should find element'); expect(XmlUtils.getContents(root)).toBe(''); }); it('handles null node contents', function() { - let xmlString = [ + const xmlString = [ '<?xml version="1.0"?>', '<Root>', '</Root>', ].join('\n'); - let xml = new DOMParser().parseFromString(xmlString, 'application/xml'); + const xml = new DOMParser().parseFromString(xmlString, 'application/xml'); goog.asserts.assert(xml, 'parseFromString should succeed'); expect(XmlUtils.getContents(xml)).toBeNull(); }); it('handles CDATA sections', function() { - let xmlString = [ + const xmlString = [ '<?xml version="1.0"?>', '<Root>', '<![CDATA[<Foo> Bar]]>', '</Root>', ].join('\n'); - let xml = new DOMParser().parseFromString(xmlString, 'application/xml'); + const xml = new DOMParser().parseFromString(xmlString, 'application/xml'); goog.asserts.assert(xml, 'parseFromString should succeed'); - let root = XmlUtils.findChild(xml, 'Root'); + const root = XmlUtils.findChild(xml, 'Root'); goog.asserts.assert(root, 'findChild should find element'); expect(XmlUtils.getContents(root)).toBe('<Foo> Bar'); }); @@ -142,7 +142,7 @@ describe('XmlUtils', function() { let xml; beforeEach(function() { - let xmlString = [ + const xmlString = [ '<?xml version="1.0"?>', '<Root a="2-7" b="-5" c="">', '</Root>', @@ -152,7 +152,7 @@ describe('XmlUtils', function() { }); it('delegates to parser function', function() { - let root = XmlUtils.findChild(xml, 'Root'); + const root = XmlUtils.findChild(xml, 'Root'); goog.asserts.assert(root, 'findChild should find element'); expect(XmlUtils.parseAttr(root, 'a', XmlUtils.parseRange)).toEqual( {start: 2, end: 7}); @@ -162,14 +162,14 @@ describe('XmlUtils', function() { }); it('supports default values', function() { - let root = XmlUtils.findChild(xml, 'Root'); + const root = XmlUtils.findChild(xml, 'Root'); goog.asserts.assert(root, 'findChild should find element'); expect(XmlUtils.parseAttr(root, 'd', XmlUtils.parseInt, 9)).toBe(9); }); }); it('parseDate', function() { - let parseDate = shaka.util.XmlUtils.parseDate; + const parseDate = shaka.util.XmlUtils.parseDate; // Should be parsed as UTC independent of local timezone. expect(parseDate('2015-11-30T12:46:33')).toBe(1448887593); @@ -182,7 +182,7 @@ describe('XmlUtils', function() { }); it('parseDuration', function() { - let parseDuration = shaka.util.XmlUtils.parseDuration; + const parseDuration = shaka.util.XmlUtils.parseDuration; // No time. expect(parseDuration('P')).toBe(0); @@ -267,7 +267,7 @@ describe('XmlUtils', function() { }); it('parseRange', function() { - let parseRange = shaka.util.XmlUtils.parseRange; + const parseRange = shaka.util.XmlUtils.parseRange; expect(parseRange('0-0')).toEqual({start: 0, end: 0}); expect(parseRange('1-1')).toEqual({start: 1, end: 1}); @@ -290,7 +290,7 @@ describe('XmlUtils', function() { }); it('parseInt', function() { - let parseInt = shaka.util.XmlUtils.parseInt; + const parseInt = shaka.util.XmlUtils.parseInt; expect(parseInt('0')).toBe(0); expect(parseInt('1')).toBe(1); @@ -315,7 +315,7 @@ describe('XmlUtils', function() { }); it('parsePositiveInt', function() { - let parsePositiveInt = shaka.util.XmlUtils.parsePositiveInt; + const parsePositiveInt = shaka.util.XmlUtils.parsePositiveInt; expect(parsePositiveInt('0')).toBeNull(); expect(parsePositiveInt('1')).toBe(1); @@ -340,7 +340,7 @@ describe('XmlUtils', function() { }); it('parseNonNegativeInt', function() { - let parseNonNegativeInt = shaka.util.XmlUtils.parseNonNegativeInt; + const parseNonNegativeInt = shaka.util.XmlUtils.parseNonNegativeInt; expect(parseNonNegativeInt('0')).toBe(0); expect(parseNonNegativeInt('1')).toBe(1); @@ -365,7 +365,7 @@ describe('XmlUtils', function() { }); it('parseFloat', function() { - let parseFloat = shaka.util.XmlUtils.parseFloat; + const parseFloat = shaka.util.XmlUtils.parseFloat; expect(parseFloat('0')).toBe(0); expect(parseFloat('1')).toBe(1); diff --git a/ui/controls.js b/ui/controls.js index c836007847..f597459110 100644 --- a/ui/controls.js +++ b/ui/controls.js @@ -587,7 +587,7 @@ shaka.ui.Controls.prototype.createDOM_ = function() { // Settings menus need to be positioned lower, if the seekbar is absent. if (!this.seekBar_) { - for (let menu of this.settingsMenus_) { + for (const menu of this.settingsMenus_) { menu.classList.add('shaka-low-position'); } } @@ -729,16 +729,16 @@ shaka.ui.Controls.prototype.addEventListeners_ = function() { const noPropagationElements = this.videoContainer_.getElementsByClassName( 'shaka-no-propagation'); for (let i = 0; i < noPropagationElements.length; i++) { - let element = noPropagationElements[i]; + const element = noPropagationElements[i]; element.addEventListener( 'click', function(event) { event.stopPropagation(); }); } // Keep showing controls if one of those elements is hovered - let showControlsElements = this.videoContainer_.getElementsByClassName( + const showControlsElements = this.videoContainer_.getElementsByClassName( 'shaka-show-controls-on-mouse-over'); for (let i = 0; i < showControlsElements.length; i++) { - let element = showControlsElements[i]; + const element = showControlsElements[i]; element.addEventListener( 'mouseover', () => { this.overrideCssShowControls_ = true; @@ -1045,12 +1045,12 @@ shaka.ui.Controls.prototype.onSeekEnd_ = function() { * @private */ shaka.ui.Controls.prototype.onKeyUp_ = function(event) { - let key = event.key; + const key = event.key; - let activeElement = document.activeElement; - let isVolumeBar = activeElement && activeElement.classList ? + const activeElement = document.activeElement; + const isVolumeBar = activeElement && activeElement.classList ? activeElement.classList.contains('shaka-volume-bar') : false; - let isSeekBar = activeElement && activeElement.classList && + const isSeekBar = activeElement && activeElement.classList && activeElement.classList.contains('shaka-seek-bar'); // Show the control panel if it is on focus or any button is pressed. if (this.controlsContainer_.contains(activeElement)) { @@ -1153,12 +1153,12 @@ shaka.ui.Controls.prototype.updateTimeAndSeekRange_ = function() { let displayTime = this.isSeeking_ ? Number(this.seekBar_.value) : Number(this.video_.currentTime); - let bufferedLength = this.video_.buffered.length; - let bufferedStart = bufferedLength ? this.video_.buffered.start(0) : 0; - let bufferedEnd = + const bufferedLength = this.video_.buffered.length; + const bufferedStart = bufferedLength ? this.video_.buffered.start(0) : 0; + const bufferedEnd = bufferedLength ? this.video_.buffered.end(bufferedLength - 1) : 0; - let seekRange = this.player_.seekRange(); - let seekRangeSize = seekRange.end - seekRange.start; + const seekRange = this.player_.seekRange(); + const seekRangeSize = seekRange.end - seekRange.start; if (this.seekBar_) { this.seekBar_.min = seekRange.start; @@ -1167,7 +1167,7 @@ shaka.ui.Controls.prototype.updateTimeAndSeekRange_ = function() { if (this.player_.isLive()) { // The amount of time we are behind the live edge. - let behindLive = Math.floor(seekRange.end - displayTime); + const behindLive = Math.floor(seekRange.end - displayTime); displayTime = Math.max(0, behindLive); if (!this.isSeeking_ && this.seekBar_) { @@ -1185,16 +1185,16 @@ shaka.ui.Controls.prototype.updateTimeAndSeekRange_ = function() { const seekWindow = seekRange.end - seekRange.start; if (seekWindow < Constants.MIN_SEEK_WINDOW_TO_SHOW_SEEKBAR) { shaka.ui.Utils.setDisplay(this.seekBarContainer_, false); - for (let menu of this.settingsMenus_) { + for (const menu of this.settingsMenus_) { menu.classList.add('shaka-low-position'); } } else { shaka.ui.Utils.setDisplay(this.seekBarContainer_, true); - for (let menu of this.settingsMenus_) { + for (const menu of this.settingsMenus_) { menu.classList.remove('shaka-low-position'); } - let gradient = ['to right']; + const gradient = ['to right']; if (bufferedLength == 0) { gradient.push('#000 0%'); } else { diff --git a/ui/language_utils.js b/ui/language_utils.js index 334736daaa..0e3ff0cebc 100644 --- a/ui/language_utils.js +++ b/ui/language_utils.js @@ -56,10 +56,10 @@ shaka.ui.LanguageUtils = class { // 4. Add new buttons languages.forEach((language) => { - let button = shaka.util.Dom.createHTMLElement('button'); + const button = shaka.util.Dom.createHTMLElement('button'); button.addEventListener('click', () => { onLanguageSelected(language); }); - let span = shaka.util.Dom.createHTMLElement('span'); + const span = shaka.util.Dom.createHTMLElement('span'); span.textContent = shaka.ui.LanguageUtils.getLanguageName(language, localization); button.appendChild(span); diff --git a/ui/overflow_menu.js b/ui/overflow_menu.js index 3c619958ac..519dec37a5 100644 --- a/ui/overflow_menu.js +++ b/ui/overflow_menu.js @@ -64,7 +64,7 @@ goog.require('shaka.util.Dom'); for (let i = 0; i < this.backToOverflowMenuButtons_.length; i++) { - let button = this.backToOverflowMenuButtons_[i]; + const button = this.backToOverflowMenuButtons_[i]; button.addEventListener('click', () => { // Hide the submenus, display the overflow menu this.controls.hideSettingsMenus(); diff --git a/ui/presentation_time.js b/ui/presentation_time.js index ee38cdb56e..75177003d5 100644 --- a/ui/presentation_time.js +++ b/ui/presentation_time.js @@ -63,16 +63,16 @@ shaka.ui.PresentationTimeTracker = class extends shaka.ui.Element { updateTime_() { const isSeeking = this.controls.isSeeking(); let displayTime = this.controls.getDisplayTime(); - let duration = this.video.duration; - let seekRange = this.player.seekRange(); - let seekRangeSize = seekRange.end - seekRange.start; + const duration = this.video.duration; + const seekRange = this.player.seekRange(); + const seekRangeSize = seekRange.end - seekRange.start; if (this.player.isLive()) { // The amount of time we are behind the live edge. - let behindLive = Math.floor(seekRange.end - displayTime); + const behindLive = Math.floor(seekRange.end - displayTime); displayTime = Math.max(0, behindLive); - let showHour = seekRangeSize >= 3600; + const showHour = seekRangeSize >= 3600; // Consider "LIVE" when less than 1 second behind the live-edge. Always // show the full time string when seeking, including the leading '-'; @@ -89,7 +89,7 @@ shaka.ui.PresentationTimeTracker = class extends shaka.ui.Element { this.currentTime_.disabled = true; } } else { - let showHour = duration >= 3600; + const showHour = duration >= 3600; this.currentTime_.textContent = this.buildTimeString_(displayTime, showHour); @@ -112,8 +112,8 @@ shaka.ui.PresentationTimeTracker = class extends shaka.ui.Element { * @private */ buildTimeString_(displayTime, showHour) { - let h = Math.floor(displayTime / 3600); - let m = Math.floor((displayTime / 60) % 60); + const h = Math.floor(displayTime / 3600); + const m = Math.floor((displayTime / 60) % 60); let s = Math.floor(displayTime % 60); if (s < 10) s = '0' + s; let text = m + ':' + s; diff --git a/ui/resolution_selection.js b/ui/resolution_selection.js index 4e0aac64be..2f27191b72 100644 --- a/ui/resolution_selection.js +++ b/ui/resolution_selection.js @@ -249,7 +249,7 @@ shaka.ui.ResolutionSelection = class extends shaka.ui.Element { */ onTrackSelected_(track) { // Disable abr manager before changing tracks. - let config = {abr: {enabled: false}}; + const config = {abr: {enabled: false}}; this.player.configure(config); this.player.selectVariantTrack(track, /* clearBuffer */ true); diff --git a/ui/ui_utils.js b/ui/ui_utils.js index d3dd85cbcc..d6f72bf00c 100644 --- a/ui/ui_utils.js +++ b/ui/ui_utils.js @@ -29,7 +29,7 @@ goog.require('goog.asserts'); */ // TODO: This can be replaced by shaka.util.Dom.getElementByClassName shaka.ui.Utils.getFirstDescendantWithClassName = function(element, className) { - let descendant = shaka.ui.Utils.getDescendantIfExists(element, className); + const descendant = shaka.ui.Utils.getDescendantIfExists(element, className); goog.asserts.assert(descendant != null, 'Should not be null!'); return descendant; @@ -42,7 +42,7 @@ shaka.ui.Utils.getFirstDescendantWithClassName = function(element, className) { * @return {?HTMLElement} */ shaka.ui.Utils.getDescendantIfExists = function(element, className) { - let childrenWithClassName = element.getElementsByClassName(className); + const childrenWithClassName = element.getElementsByClassName(className); if (childrenWithClassName.length) { return /** @type {!HTMLElement} */ (childrenWithClassName[0]); } diff --git a/ui/volume_bar.js b/ui/volume_bar.js index 65505e4ce0..1acfa9bd9b 100644 --- a/ui/volume_bar.js +++ b/ui/volume_bar.js @@ -91,7 +91,7 @@ shaka.ui.VolumeBar = class extends shaka.ui.Element { } // TODO: Can we do this with LESS? - let gradient = ['to right']; + const gradient = ['to right']; gradient.push(shaka.ui.Constants.VOLUME_BAR_VOLUME_LEVEL_COLOR + (this.bar_.value * 100) + '%'); gradient.push(shaka.ui.Constants.VOLUME_BAR_BASE_COLOR +