Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Detect bitrate in LAN #424

Merged
merged 3 commits into from
Oct 25, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 74 additions & 22 deletions src/apiClient.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,22 @@

/** Maximum bitrate (Int32) */
const MAX_BITRATE = 2147483647;
/** Approximate LAN bitrate */
const LAN_BITRATE = 140000000;
thornbill marked this conversation as resolved.
Show resolved Hide resolved
/** Bitrate test timeout in milliseconds */
const BITRATETEST_TIMEOUT = 5000;

function redetectBitrate(instance) {
stopBitrateDetection(instance);

if (instance.accessToken() && instance.enableAutomaticBitrateDetection !== false) {
setTimeout(redetectBitrateInternal.bind(instance), 6000);
instance.detectTimeout = setTimeout(redetectBitrateInternal.bind(instance), 6000);
}
}

function redetectBitrateInternal() {
this.detectTimeout = null;

if (this.accessToken()) {
this.detectBitrate();
}
Expand All @@ -27,6 +33,7 @@
function stopBitrateDetection(instance) {
if (instance.detectTimeout) {
clearTimeout(instance.detectTimeout);
instance.detectTimeout = null;
}
}

Expand Down Expand Up @@ -66,7 +73,7 @@
options.credentials = 'same-origin';

fetch(url, options)
.then((response) => {

Check warning on line 76 in src/apiClient.js

View workflow job for this annotation

GitHub Actions / Lint

Each then() should return a value or throw
clearTimeout(timeout);
resolve(response);
})
Expand Down Expand Up @@ -280,7 +287,7 @@
}
} else {
onFetchFail(instance, request.url, response);
return Promise.reject(response);

Check warning on line 290 in src/apiClient.js

View workflow job for this annotation

GitHub Actions / Lint

Expected throw instead of Promise.reject
}
})
.catch((error) => {
Expand All @@ -296,7 +303,7 @@

const previousServerAddress = instance.serverAddress();

return tryReconnect(instance)

Check warning on line 306 in src/apiClient.js

View workflow job for this annotation

GitHub Actions / Lint

Avoid nesting promises

Check warning on line 306 in src/apiClient.js

View workflow job for this annotation

GitHub Actions / Lint

Avoid nesting promises
.then(() => {
console.log('Reconnect succeeded');
request.url = request.url.replace(previousServerAddress, instance.serverAddress());
Expand Down Expand Up @@ -352,12 +359,12 @@
}
} else {
onFetchFail(instance, request.url, response);
return Promise.reject(response);

Check warning on line 362 in src/apiClient.js

View workflow job for this annotation

GitHub Actions / Lint

Expected throw instead of Promise.reject
}
})
.catch((error) => {
onFetchFail(instance, request.url, {});
return Promise.reject(error);

Check warning on line 367 in src/apiClient.js

View workflow job for this annotation

GitHub Actions / Lint

Expected throw instead of Promise.reject
});
}

Expand Down Expand Up @@ -444,7 +451,7 @@
if (userId && instance.accessToken()) {
user = getCachedUser(instance, userId);
if (user) {
return Promise.resolve(user);

Check warning on line 454 in src/apiClient.js

View workflow job for this annotation

GitHub Actions / Lint

Avoid wrapping return values in Promise.resolve
}
}
}
Expand Down Expand Up @@ -487,7 +494,7 @@
return this.ajax({
type: 'POST',
url
}).then(done, done);

Check warning on line 497 in src/apiClient.js

View workflow job for this annotation

GitHub Actions / Lint

Avoid calling back inside of a promise
}

done();
Expand Down Expand Up @@ -525,8 +532,8 @@
resolve(result);
};

if (this.onAuthenticated) {

Check warning on line 535 in src/apiClient.js

View workflow job for this annotation

GitHub Actions / Lint

Each then() should return a value or throw
this.onAuthenticated(this, result).then(afterOnAuthenticated);

Check warning on line 536 in src/apiClient.js

View workflow job for this annotation

GitHub Actions / Lint

Expected catch() or return
} else {
afterOnAuthenticated();
}
Expand Down Expand Up @@ -746,22 +753,66 @@
}

getDownloadSpeed(byteSize) {
const url = this.getUrl('Playback/BitrateTest', {
Size: byteSize
});
return new Promise((resolve, reject) => {
const url = this.getUrl('Playback/BitrateTest', {
Size: byteSize
});

const now = new Date().getTime();
console.log(`Requesting ${url}`);
thornbill marked this conversation as resolved.
Show resolved Hide resolved

return this.ajax({
type: 'GET',
url,
timeout: 5000
}).then(() => {
const responseTimeSeconds = (new Date().getTime() - now) / 1000;
const bytesPerSecond = byteSize / responseTimeSeconds;
const bitrate = Math.round(bytesPerSecond * 8);
const xhr = new XMLHttpRequest;

xhr.open('GET', url, true);

xhr.responseType = 'blob';
xhr.timeout = BITRATETEST_TIMEOUT;

const headers = {
'Cache-Control': 'no-cache, no-store'
};

this.setRequestHeaders(headers);

for (const key in headers) {
xhr.setRequestHeader(key, headers[key]);
}

let startTime;

xhr.onreadystatechange = () => {
if (xhr.readyState == XMLHttpRequest.HEADERS_RECEIVED) {
startTime = performance.now();
}
};

xhr.onload = () => {
if (xhr.status < 400) {
const responseTimeSeconds = (performance.now() - startTime) * 1e-3;
const bytesLoaded = xhr.response.size;
const bytesPerSecond = bytesLoaded / responseTimeSeconds;
const bitrate = Math.round(bytesPerSecond * 8);

return bitrate;
console.debug(`BitrateTest ${bytesLoaded} bytes loaded (${byteSize} requested) in ${responseTimeSeconds} seconds -> ${bitrate} bps`);

resolve(bitrate);
} else {
reject(`BitrateTest failed with ${xhr.status} status`);
}
};

xhr.onabort = () => {
reject('BitrateTest abort');
};

xhr.onerror = () => {
reject('BitrateTest error');
};

xhr.ontimeout = () => {
reject('BitrateTest timeout');
};

xhr.send(null);
});
}

Expand Down Expand Up @@ -4092,13 +4143,6 @@
}

function detectBitrateWithEndpointInfo(instance, endpointInfo) {
if (endpointInfo.IsInNetwork) {
const result = 140000000;
instance.lastDetectedBitrate = result;
instance.lastDetectedBitrateTime = new Date().getTime();
return result;
}

return detectBitrateInternal(
instance,
[
Expand All @@ -4116,7 +4160,15 @@
}
],
0
);
).then((result) => {
if (endpointInfo.IsInNetwork) {
result = Math.max(result || 0, LAN_BITRATE);

instance.lastDetectedBitrate = result;
instance.lastDetectedBitrateTime = new Date().getTime();
}
return result;
});
}

function getRemoteImagePrefix(instance, options) {
Expand Down
Loading