diff --git a/.gitignore b/.gitignore
new file mode 100644
index 000000000..52b8dffa3
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1 @@
+ugly.bat
diff --git a/README.md b/README.md
index adba922bb..0eea20e14 100644
--- a/README.md
+++ b/README.md
@@ -16,9 +16,21 @@ Only modern browsers are supported (IE11, latest Edge, latest Chrome, latest Fir
- Your server must accept large POST requests (up to 20 Megabytes), otherwise the upload test will fail
- It's also better if your server does not use compression, but it's not mandatory
-## How to use
+## Quick installation videos
+* [Debian 9.0 with Apache](https://fdossena.com/?p=speedtest/quickstart_deb.frag)
+* [Windows Server 2016 with IIS](https://fdossena.com/?p=speedtest/quickstart_win.frag)
+
+Also, here's an [example config on Ubuntu 16 LTS](https://github.com/adolfintel/speedtest/issues/50)
+
+## How to use in your site
See the examples or doc.md
+## Docker
+Please see the ```docker``` branch
+
+## Donate
+If you want to support this project, you can [send a donation via PayPal](https://www.paypal.me/sineisochronic).
+
## License
Copyright (C) 2016-2017 Federico Dossena
diff --git a/apache2_dynamic/php/empty.php b/apache2_dynamic/php/empty.php
index 7395f6cc7..eb1fc85b6 100644
--- a/apache2_dynamic/php/empty.php
+++ b/apache2_dynamic/php/empty.php
@@ -3,4 +3,5 @@
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
+header("Connection: keep-alive");
?>
\ No newline at end of file
diff --git a/doc.md b/doc.md
index 606ccf7a6..384a2c2f5 100644
--- a/doc.md
+++ b/doc.md
@@ -1,7 +1,7 @@
# HTML5 Speedtest
> by Federico Dossena
-> Version 4.2.1, May 15 2017
+> Version 4.2.9, July 19 2017
> [https://github.com/adolfintel/speedtest/](https://github.com/adolfintel/speedtest/)
@@ -24,6 +24,9 @@ First of all, the requirements to run this test:
If this looks good, let's proceed and see how to use the test.
+## Quick installation videos
+* [Debian 9.0 with Apache](https://fdossena.com/?p=speedtest/quickstart_deb.frag)
+* [Windows Server 2016 with IIS](https://fdossena.com/?p=speedtest/quickstart_win.frag)
## Installation
To install the test on your server, upload the following files:
@@ -108,22 +111,22 @@ format:
* `5` = Test aborted
* __dlStatus__ is either
* Empty string (not started or aborted)
- * Download speed in Megabit/s as a number with 2 digits
+ * Download speed in Megabit/s as a number with 2 decimals
* The string "Fail" (test failed)
* __ulStatus__ is either
* Empty string (not started or aborted)
- * Upload speed in Megabit/s as a number with 2 digits
+ * Upload speed in Megabit/s as a number with 2 decimals
* The string "Fail" (test failed)
* __pingStatus__ is either
* Empty string (not started or aborted)
- * Estimated ping in milliseconds as a number with 2 digits
+ * Estimated ping in milliseconds as a number with 2 decimals
* The string "Fail" (test failed)
* __clientIp__ is either
* Empty string (not fetched yet or failed)
* The client's IP address as a string
* __jitterStatus__ is either
* Empty string (not started or aborted)
- * Estimated jitter in milliseconds as a number with 2 digits (lower = stable connection)
+ * Estimated jitter in milliseconds as a number with 2 decimals (lower = stable connection)
* The string "Fail" (test failed)
* __pointOfTest__ is either
* Empty string for a single server test or failure on list retrieval
@@ -134,23 +137,23 @@ format:
* __isp__ Internet Service Provider name (http://ipinfo.io/developers#terms-of-use)
### Starting the test
-To start the test, send the start command to the worker:
+To start the test with the default settings, which is usually the best choice, send the start command to the worker:
```js
w.postMessage('start')
```
-This starts the test with the default settings, which is usually the best choice. If you want, you can change these settings and pass them to the worker as JSON with like this:
+If you want, you can change these settings and pass them to the worker as JSON when you start it, like this:
```js
w.postMessage('start {"param1": "value1", "param2": "value2", ...}')
```
#### Test parameters
-* __time_dl__: How long the download test should be in seconds
+* __time_dl__: How long the download test should be in seconds. The test will continue regardless of this limit if the speed is still 0.00 when the limit is reached.
* Default: `15`
* Recommended: `>=5`
-* __time_ul__: How long the upload test should be in seconds
+* __time_ul__: How long the upload test should be in seconds. The test will continue regardless of this limit if the speed is still 0.00 when the limit is reached.
* Default: `15`
* Recommended: `>=10`
* __count_ping__: How many pings to perform in the ping test
@@ -159,25 +162,31 @@ w.postMessage('start {"param1": "value1", "param2": "value2", ...}')
* __ping_timeout__: Max wait time for a ping request in milliseconds
* Default: `1000`
* Recommended: `>=10`
-* __url_dl__: path to garbage.php or a large file to use for the download test
- * Default: `/download/`
- * __Important:__ route configured in .htaccess file
-* __url_ul__: path to ab empty file or empty.php to use for the upload test
- * Default: `/upload`
- * __Important:__ route configured in .htaccess file
+* __url_dl__: path to garbage.php or a large file to use for the download test.
+ * Default: `garbage.php`
+ * The string "-1" disables the test
+ * __Important:__ path is relative to js file
+* __url_ul__: path to an empty file or empty.php to use for the upload test
+ * Default: `empty.php`
+ * The string "-1" disables the test
+ * __Important:__ path is relative to js file
* __url_ping__: path to an empty file or empty.php to use for the ping test
- * Default: `/ping`
- * __Important:__ route configured in .htaccess file
+ * Default: `empty.php`
+ * The string "-1" disables the test
+ * __Important:__ path is relative to js file
* __url_getIp__: path to getIP.php or replacement
- * Default: `/ip`
- * __Important:__ route configured in .htaccess file
+ * Default: `getIP.php`
+ * The string "-1" disables the test
+ * __Important:__ path is relative to js file
* __url_getPointsOfTest__: REST service URL to retrieve the list of available Points of Test
- * Default: `/pots`
+ * Default: `pots.php`
* __url_saveResult__: REST service URL to save test results
- * Default: `/save`
+ * Default: `save.php`
* __url_ispInfo___: Geolocation service and ISP information (http://ipinfo.io/developers#terms-of-use)
* Default: `http://ipinfo.io`
-* __enable_quirks__: enables browser-specific optimizations. These optimizations override some of the default settings below. They do not override settings that are explicitly set.
+
+#### Advanced test parameters
+* __enable_quirks__: enables browser-specific optimizations. These optimizations override some of the default settings. They do not override settings that are explicitly set.
* Default: `true`
* __enable_multiPots__: enables multiple servers deployment with detection of lowest latency available
* Default: `false`
@@ -194,15 +203,25 @@ w.postMessage('start {"param1": "value1", "param2": "value2", ...}')
* Default: `3`
* Recommended: `>=1`
* Default override: 1 on Firefox if enable_quirks is true
- * Default override: 10 on Safari if enable_quirks is true
-* __allow_fetchAPI__: allow the use of Fetch API for the download test instead of regular XHR. Experimental, not recommended.
- * Default: `false`
-* __force_fetchAPI__: forces the use of Fetch API on all browsers that support it
- * Default: `false`
-Fetch API are used if the following conditions are met:
- * allow_fetchAPI is true
- * Chromium-based browser with support for Fetch API and enable_quirks is true
-OR force_fetchAPI is true and the browser supports Fetch API
+* __xhr_ignoreErrors__: how to react to errors in download/upload streams and the ping test
+ * `0`: Fail test on error (behaviour of previous versions of this test)
+ * `1`: Restart a stream/ping when it fails
+ * `2`: Ignore all errors
+ * Default: `1`
+ * Recommended: `1`
+* __time_dlGraceTime__: How long to wait (in seconds) before actually measuring the download speed. This is a good idea because we want to wait for the TCP window to be at its maximum (or close to it)
+ * Default: `1.5`
+ * Recommended: `>=0`
+* __time_ulGraceTime__: How long to wait (in seconds) before actually measuring the upload speed. This is a good idea because we want to wait for the buffers to be full (avoids the peak at the beginning of the test)
+ * Default: `3`
+ * Recommended: `>=1`
+* __overheadCompensationFactor__: compensation for HTTP and network overhead. Default value assumes typical MTUs used over the Internet. You might want to change this if you're using this in your internal network with different MTUs, or if you're using IPv6 instead of IPv4.
+ * Default: `1.13359567567567567568` (1048576/925000) assumes HTTP+TCP+IPv4+ETH with typical MTUs used over the Internet
+ * `1.0513`: HTTP+TCP+IPv6+ETH, over the Internet (empirically tested, not calculated)
+ * `1.0369`: Alternative value for HTTP+TCP+IPv4+ETH, over the Internet (empirically tested, not calculated)
+ * `1460 / 1514`: TCP+IPv4+ETH, ignoring HTTP overhead
+ * `1440 / 1514`: TCP+IPv6+ETH, ignoring HTTP overhead
+ * `1`: ignore overheads. This measures the speed at which you actually download and upload files
### Aborting the test prematurely
The test can be aborted at any time by sending an abort command to the worker:
@@ -213,8 +232,24 @@ w.postMessage('abort')
This will terminate all network activity and stop the worker.
-__Important:__ do not simply kill the worker while it's running, as it will leave pending XHR requests!
+__Important:__ do not simply kill the worker while it's running, as it may leave pending XHR requests!
+
+## Troubleshooting
+These are the most common issues reported by users, and how to fix them
+
+#### Download test gives very low result
+Are garbage.php and empty.php (or your replacements) reachable?
+Press F12, select network and start the test. Do you see errors? (cancelled requests are not errors)
+If a small download starts, open it in a text editor. Does it say it's missing openssl_random_pseudo_bytes()? In this case, install OpenSSL (this is usually included when you install Apache and PHP on most distros).
+
+#### Upload test is inaccurate, and I see lag spikes
+Check your server's maximum POST size, make sure it's at least 20Mbytes, possibly more
+
+#### All tests are wrong, give extremely high results, browser lags/crashes, ...
+You're running the test on localhost, therefore it is trying to measure the speed of your loopback interface. The test is meant to be run over an Internet connection, from a different machine.
+#### Ping test shows double the actual ping
+Make sure your server is sending the ```Connection:keep-alive``` header
## Using the test without PHP
If your server does not support PHP, or you're using something newer like Node.js, you can still use this test by replacing `garbage.php`, `empty.php` and `getIP.php` with equivalents.
@@ -231,12 +266,12 @@ It is important here to turn off compression, and generate incompressible data.
A symlink to `/dev/urandom` is also ok.
#### Replacement for `empty.php`
-Your replacement must simply respond with a HTTP code 200 and send nothing else. You may want to send additional headers to disable caching.
+Your replacement must simply respond with a HTTP code 200 and send nothing else. You may want to send additional headers to disable caching. The test assumes that Connection:keep-alive is sent by the server.
#### Replacement for `getIP.php`
Your replacement must simply respond with the client's IP as plaintext. Nothing fancy.
-### JS
+#### JS
You need to start the test with your replacements like this:
```js
@@ -245,10 +280,13 @@ w.postMessage('start {"url_dl": "newGarbageURL", "url_ul": "newEmptyURL", "url_p
## Known bugs and limitations
+* The ping/jitter test is measured by seeing how long it takes for an empty XHR to complete. It is not an acutal ICMP ping
* __Chrome:__ high CPU usage from XHR requests with very fast connections (like gigabit).
For this reason, the test may report inaccurate results if your CPU is too slow. (Does not affect most computers)
* __IE11:__ the upload test is not precise on very fast connections
+* __IE11:__ the upload test may not work over HTTPS
* __Safari:__ works, but needs more testing and tweaking for very fast connections
+* __Firefox:__ on some Linux systems with hardware acceleration turned off, the page rendering makes the browser lag, reducing the accuracy of the ping/jitter test
## Making changes
Since this is an open source project, you can modify it.
@@ -261,7 +299,7 @@ To create the minified version, use UglifyJS like this:
uglifyjs -c --screw-ie8 speedtest_worker.js > speedtest_worker.min.js
```
-Pull requests are much appreciated. If you don't use github (or git), simply contact me.
+Pull requests are much appreciated. If you don't use github (or git), simply contact me at dosse91@paranoici.org.
__Important:__ please add your name to modified versions to distinguish them from the main project.
diff --git a/example6.html b/example6.html
index 748a35551..d81fc2bd9 100644
--- a/example6.html
+++ b/example6.html
@@ -97,8 +97,8 @@
+
+
+
+
diff --git a/speedtest_worker.js b/speedtest_worker.js
index 692492ac2..592ad9002 100644
--- a/speedtest_worker.js
+++ b/speedtest_worker.js
@@ -1,8 +1,8 @@
/*
- HTML5 Speedtest v4.2.1
- by Federico Dossena
- https://github.com/adolfintel/speedtest/
- GNU LGPLv3 License
+ HTML5 Speedtest v4.2.8
+ by Federico Dossena
+ https://github.com/adolfintel/speedtest/
+ GNU LGPLv3 License
*/
// data reported to main thread
@@ -22,6 +22,8 @@ var isp = '' // internet service provider
var settings = {
time_ul: 15, // duration of upload test in seconds
time_dl: 15, // duration of download test in seconds
+ time_ulGraceTime: 3, //time to wait in seconds before actually measuring ul speed (wait for buffers to fill)
+ time_dlGraceTime: 1.5, //time to wait in seconds before actually measuring dl speed (wait for TCP window to increase)
count_ping: 35, // number of pings to perform in ping test
ping_timeout: 1000, // timeout for ping requests
url_dl: '/download/', // path to a large file or garbage.php, used for download test.
@@ -33,12 +35,12 @@ var settings = {
url_ispInfo: 'http://ipinfo.io', // Geolocation service and ISP information
xhr_dlMultistream: 10, // number of download streams to use (can be different if enable_quirks is active)
xhr_ulMultistream: 3, // number of upload streams to use (can be different if enable_quirks is active)
+ xhr_ignoreErrors: 1, // 0=fail on errors, 1=attempt to restart a stream if it fails, 2=ignore all errors
xhr_dlUseBlob: false, // if set to true, it reduces ram usage but uses the hard drive (useful with large garbagePhp_chunkSize and/or high xhr_dlMultistream)
garbagePhp_chunkSize: 20, // size of chunks sent by garbage.php (can be different if enable_quirks is active)
enable_quirks: true, // enable quirks for specific browsers. currently it overrides settings to optimize for specific browsers, unless they are already being overridden with the start command
enable_multiPots: false, // enable multiple points of test
- allow_fetchAPI: false, // enables Fetch API. currently disabled because it leaks memory like no tomorrow
- force_fetchAPI: false // when Fetch API is enabled, it will force usage on every browser that supports it
+ overheadCompensationFactor: 1048576/925000 //compensation for HTTP+TCP+IP+ETH overhead. 925000 is how much data is actually carried over 1048576 (1mb) bytes downloaded/uploaded. This default value assumes HTTP+TCP+IPv4+ETH with typical MTUs over the Internet. You may want to change this if you're going through your local network with a different MTU or if you're going over IPv6 (see doc.md for some other values)
}
var xhr = null // array of currently active xhr requests
@@ -53,12 +55,17 @@ var interval = null // timer used in tests
var useFetchAPI = false
/*
- listener for commands from main thread to this worker.
- commands:
- -status: returns the current status as a string of values spearated by a semicolon (;) in this order: testStatus;dlStatus;ulStatus;pingStatus;clientIp;jitterStatus
- -abort: aborts the current test
- -start: starts the test. optionally, settings can be passed as JSON.
- example: start {"time_ul":"10", "time_dl":"10", "count_ping":"50"}
+ this function is used on URLs passed in the settings to determine whether we need a ? or an & as a separator
+*/
+function url_sep (url) { return url.match(/\?/) ? '&' : '?'; }
+
+/*
+ listener for commands from main thread to this worker.
+ commands:
+ -status: returns the current status as a string of values spearated by a semicolon (;) in this order: testStatus;dlStatus;ulStatus;pingStatus;clientIp;jitterStatus
+ -abort: aborts the current test
+ -start: starts the test. optionally, settings can be passed as JSON.
+ example: start {"time_ul":"10", "time_dl":"10", "count_ping":"50"}
*/
this.addEventListener('message', function (e) {
var params = e.data.split(' ')
@@ -86,7 +93,11 @@ this.addEventListener('message', function (e) {
testStatus = 1
try {
// parse settings, if present
- var s = JSON.parse(e.data.substring(5))
+ var s = {}
+ try{
+ var ss = e.data.substring(5);
+ if (ss) s = JSON.parse(ss);
+ }catch(e){ console.warn("Error parsing custom settings JSON. Please check your syntax"); }
if (typeof s.url_dl !== 'undefined') settings.url_dl = s.url_dl // download url
if (typeof s.url_ul !== 'undefined') settings.url_ul = s.url_ul // upload url
if (typeof s.url_ping !== 'undefined') settings.url_ping = s.url_ping // ping url
@@ -98,7 +109,6 @@ this.addEventListener('message', function (e) {
if (typeof s.time_ul !== 'undefined') settings.time_ul = s.time_ul // duration of upload test
if (typeof s.enable_quirks !== 'undefined') settings.enable_quirks = s.enable_quirks // enable quirks or not
if (typeof s.enable_multiPots !== 'undefined') settings.enable_multiPots = s.enable_multiPots // enable multiple points of test and lowest latency detection using cross domain requests
- if (typeof s.allow_fetchAPI !== 'undefined') settings.allow_fetchAPI = s.allow_fetchAPI // allows fetch api to be used if supported
// quirks for specific browsers. more may be added in future releases
if (settings.enable_quirks) {
var ua = navigator.userAgent
@@ -110,44 +120,25 @@ this.addEventListener('message', function (e) {
// edge more precise with 3 download streams
settings.xhr_dlMultistream = 3
}
- if ((/Safari.(\d+)/i.test(ua)) && !(/Chrome.(\d+)/i.test(ua))) {
- // safari more precise with 10 upload streams and 5mb chunks for download test
- settings.xhr_ulMultistream = 10
- settings.garbagePhp_chunkSize = 5
- }
if (/Chrome.(\d+)/i.test(ua) && (!!self.fetch)) {
- // chrome can't handle large xhr very well, use fetch api if available and allowed
- if (settings.allow_fetchAPI) useFetchAPI = true
// chrome more precise with 5 streams
settings.xhr_dlMultistream = 5
}
}
+
if (typeof s.count_ping !== 'undefined') settings.count_ping = s.count_ping // number of pings for ping test
if (typeof s.xhr_dlMultistream !== 'undefined') settings.xhr_dlMultistream = s.xhr_dlMultistream // number of download streams
if (typeof s.xhr_ulMultistream !== 'undefined') settings.xhr_ulMultistream = s.xhr_ulMultistream // number of upload streams
+ if (typeof s.xhr_ignoreErrors !== 'undefined') settings.xhr_ignoreErrors = s.xhr_ignoreErrors // what to do in case of errors during the test
if (typeof s.xhr_dlUseBlob !== 'undefined') settings.xhr_dlUseBlob = s.xhr_dlUseBlob // use blob for download test
if (typeof s.garbagePhp_chunkSize !== 'undefined') settings.garbagePhp_chunkSize = s.garbagePhp_chunkSize // size of garbage.php chunks
- if (typeof s.force_fetchAPI !== 'undefined') settings.force_fetchAPI = s.force_fetchAPI // use fetch api on all browsers that support it if enabled
- if (settings.allow_fetchAPI && settings.force_fetchAPI && (!!self.fetch)) useFetchAPI = true
- } catch (e) { }
+ if (typeof s.time_dlGraceTime !== 'undefined') settings.time_dlGraceTime = s.time_dlGraceTime // dl test grace time before measuring
+ if (typeof s.time_ulGraceTime !== 'undefined') settings.time_ulGraceTime = s.time_ulGraceTime // ul test grace time before measuring
+ if (typeof s.overheadCompensationFactor !== 'undefined') settings.overheadCompensationFactor = s.overheadCompensationFactor //custom overhead compensation factor (default assumes HTTP+TCP+IP+ETH with typical MTUs)
+ } catch (e) { console.warn("Possible error in custom test settings. Some settings may not be applied. Exception: "+e) }
// run the tests
console.log(settings)
- console.log('Fetch API: ' + useFetchAPI)
- getServer(function () {
- getIp(function() {
- ispInfo(function () {
- dlTest(function () {
- testStatus = 2
- pingTest(function () {
- testStatus = 3
- ulTest(function () {
- testStatus = 4
- })
- })
- })
- })
- })
- })
+ getServer(function () { getIp(function() { ispInfo(function () { dlTest(function () { testStatus = 2; pingTest(function () { testStatus = 3; ulTest(function () { testStatus = 4 }) }) }) }) }) })
}
if (params[0] === 'abort') { // abort command
clearRequests() // stop all xhr activity
@@ -180,6 +171,7 @@ function clearRequests () {
}
// gets client's IP using url_getIp, then calls the done function
function getIp (done) {
+ if (settings.url_getIp == "-1") {done(); return}
xhr = new XMLHttpRequest()
xhr.onload = function () {
clientIp = xhr.responseText
@@ -188,7 +180,7 @@ function getIp (done) {
xhr.onerror = function () {
done()
}
- xhr.open('GET', settings.url_getIp + '?r=' + Math.random(), true)
+ xhr.open('GET', settings.url_getIp + url_sep(settings.url_getIp) + 'r=' + Math.random(), true)
xhr.send()
}
// returns a server url with the lowest latency
@@ -251,60 +243,45 @@ function getServer (done) {
var dlCalled = false // used to prevent multiple accidental calls to dlTest
function dlTest (done) {
if (dlCalled) return; else dlCalled = true // dlTest already called?
- var totLoaded = 0.0 // total number of loaded bytes
- var startT = new Date().getTime() // timestamp when test was started
- var failed = false // set to true if a stream fails
+ if (settings.url_dl == "-1") {done(); return}
+ var totLoaded = 0.0, // total number of loaded bytes
+ startT = new Date().getTime(), // timestamp when test was started
+ graceTimeDone = false, //set to true after the grace time is past
+ failed = false // set to true if a stream fails
xhr = []
// function to create a download stream. streams are slightly delayed so that they will not end at the same time
var testStream = function (i, delay) {
setTimeout(function () {
if (testStatus !== 1) return // delayed stream ended up starting after the end of the download test
- if (useFetchAPI) {
- var queryString = settings.url_dl + settings.garbagePhp_chunkSize + '?r=' + Math.random()
- xhr[i] = fetch(queryString).then(function (response) {
- var reader = response.body.getReader()
- var consume = function () {
- return reader.read().then(function (result) {
- if (result.done) testStream(i); else {
- totLoaded += result.value.length
- if (xhr[i].cancelRequested) reader.cancel()
- }
- return consume()
- })
- }
- return consume()
- })
- } else {
- var prevLoaded = 0 // number of bytes loaded last time onprogress was called
- var x = new XMLHttpRequest()
- xhr[i] = x
- xhr[i].onprogress = function (event) {
- if (testStatus !== 1) { try { x.abort() } catch (e) { } } // just in case this XHR is still running after the download test
- // progress event, add number of new loaded bytes to totLoaded
- var loadDiff = event.loaded <= 0 ? 0 : (event.loaded - prevLoaded)
- if (isNaN(loadDiff) || !isFinite(loadDiff) || loadDiff < 0) return // just in case
- totLoaded += loadDiff
- prevLoaded = event.loaded
- }
- xhr[i].onload = function () {
- // the large file has been loaded entirely, start again
- try { xhr[i].abort() } catch (e) { } // reset the stream data to empty ram
- testStream(i, 0)
- }
- xhr[i].onerror = function () {
- // error, abort
- failed = true
- try { xhr[i].abort() } catch (e) { }
- delete (xhr[i])
- }
- // send xhr
- try { if (settings.xhr_dlUseBlob) xhr[i].responseType = 'blob'; else xhr[i].responseType = 'arraybuffer' } catch (e) { }
- var queryString = settings.url_dl + settings.garbagePhp_chunkSize + '?r=' + Math.random()
- xhr[i].open('GET', queryString, true) // random string to prevent caching
- xhr[i].send()
- }
- }, 1 + delay)
- }
+ var prevLoaded = 0 // number of bytes loaded last time onprogress was called
+ var x = new XMLHttpRequest()
+ xhr[i] = x
+ xhr[i].onprogress = function (event) {
+ if (testStatus !== 1) { try { x.abort() } catch (e) { } } // just in case this XHR is still running after the download test
+ // progress event, add number of new loaded bytes to totLoaded
+ var loadDiff = event.loaded <= 0 ? 0 : (event.loaded - prevLoaded)
+ if (isNaN(loadDiff) || !isFinite(loadDiff) || loadDiff < 0) return // just in case
+ totLoaded += loadDiff
+ prevLoaded = event.loaded
+ }.bind(this)
+ xhr[i].onload = function () {
+ // the large file has been loaded entirely, start again
+ try { xhr[i].abort() } catch (e) { } // reset the stream data to empty ram
+ testStream(i, 0)
+ }.bind(this)
+ xhr[i].onerror = function () {
+ // error
+ if (settings.xhr_ignoreErrors === 0) failed=true //abort
+ try { xhr[i].abort() } catch (e) { }
+ delete (xhr[i])
+ if (settings.xhr_ignoreErrors === 1) testStream(i, 100) //restart stream after 100ms
+ }.bind(this)
+ // send xhr
+ try { if (settings.xhr_dlUseBlob) xhr[i].responseType = 'blob'; else xhr[i].responseType = 'arraybuffer' } catch (e) { }
+ xhr[i].open('GET', settings.url_dl + url_sep(settings.url_dl) + 'r=' + Math.random() + '&ckSize=' + settings.garbagePhp_chunkSize, true) // random string to prevent caching
+ xhr[i].send()
+ }.bind(this), 1 + delay)
+ }.bind(this)
// open streams
for (var i = 0; i < settings.xhr_dlMultistream; i++) {
testStream(i, 100 * i)
@@ -313,13 +290,23 @@ function dlTest (done) {
interval = setInterval(function () {
var t = new Date().getTime() - startT
if (t < 200) return
- var speed = totLoaded / (t / 1000.0)
- dlStatus = ((speed * 8) / 925000.0).toFixed(2) // 925000 instead of 1048576 to account for overhead
- if ((t / 1000.0) > settings.time_dl || failed) { // test is over, stop streams and timer
- if (failed || isNaN(dlStatus)) dlStatus = 'Fail'
- clearRequests()
- clearInterval(interval)
- done()
+ if (!graceTimeDone){
+ if (t > 1000 * settings.time_dlGraceTime){
+ if (totLoaded > 0){ // if the connection is so slow that we didn't get a single chunk yet, do not reset
+ startT = new Date().getTime()
+ totLoaded = 0.0;
+ }
+ graceTimeDone = true;
+ }
+ }else{
+ var speed = totLoaded / (t / 1000.0)
+ dlStatus = ((speed * 8 * settings.overheadCompensationFactor)/1048576).toFixed(2) // speed is multiplied by 8 to go from bytes to bits, overhead compensation is applied, then everything is divided by 1048576 to go to megabits/s
+ if (((t / 1000.0) > settings.time_dl && dlStatus > 0) || failed) { // test is over, stop streams and timer
+ if (failed || isNaN(dlStatus)) dlStatus = 'Fail'
+ clearRequests()
+ clearInterval(interval)
+ done()
+ }
}
}, 200)
}
@@ -338,9 +325,11 @@ reqsmall = new Blob(reqsmall)
var ulCalled = false // used to prevent multiple accidental calls to ulTest
function ulTest (done) {
if (ulCalled) return; else ulCalled = true // ulTest already called?
- var totLoaded = 0.0 // total number of transmitted bytes
- var startT = new Date().getTime() // timestamp when test was started
- var failed = false // set to true if a stream fails
+ if (settings.url_ul == "-1") {done(); return}
+ var totLoaded = 0.0, // total number of transmitted bytes
+ startT = new Date().getTime(), // timestamp when test was started
+ graceTimeDone = false, //set to true after the grace time is past
+ failed = false // set to true if a stream fails
xhr = []
// function to create an upload stream. streams are slightly delayed so that they will not end at the same time
var testStream = function (i, delay) {
@@ -364,11 +353,12 @@ function ulTest (done) {
}
xhr[i].onerror = function () {
// error, abort
- failed = true
+ if (settings.xhr_ignoreErrors === 0) failed = true //abort
try { xhr[i].abort() } catch (e) { }
delete (xhr[i])
+ if (settings.xhr_ignoreErrors === 1) testStream(i,100); //restart stream after 100ms
}
- xhr[i].open('POST', settings.url_ul + '?r=' + Math.random(), true) // random string to prevent caching
+ xhr[i].open('POST', settings.url_ul + url_sep(settings.url_ul) + 'r=' + Math.random(), true) // random string to prevent caching
xhr[i].setRequestHeader('Content-Encoding', 'identity') // disable compression (some browsers may refuse it, but data is incompressible anyway)
xhr[i].send(reqsmall)
} else {
@@ -386,13 +376,13 @@ function ulTest (done) {
testStream(i, 0)
}
xhr[i].upload.onerror = function () {
- // error, abort
- failed = true
+ if (settings.xhr_ignoreErrors === 0) failed=true //abort
try { xhr[i].abort() } catch (e) { }
delete (xhr[i])
- }
+ if (settings.xhr_ignoreErrors === 1) testStream(i, 100) //restart stream after 100ms
+ }.bind(this)
// send xhr
- xhr[i].open('POST', settings.url_ul + '?r=' + Math.random(), true) // random string to prevent caching
+ xhr[i].open('POST', settings.url_ul + url_sep(settings.url_ul) + 'r=' + Math.random(), true) // random string to prevent caching
xhr[i].setRequestHeader('Content-Encoding', 'identity') // disable compression (some browsers may refuse it, but data is incompressible anyway)
xhr[i].send(req)
}
@@ -406,13 +396,23 @@ function ulTest (done) {
interval = setInterval(function () {
var t = new Date().getTime() - startT
if (t < 200) return
- var speed = totLoaded / (t / 1000.0)
- ulStatus = ((speed * 8) / 925000.0).toFixed(2) // 925000 instead of 1048576 to account for overhead
- if ((t / 1000.0) > settings.time_ul || failed) { // test is over, stop streams and timer
- if (failed || isNaN(ulStatus)) ulStatus = 'Fail'
- clearRequests()
- clearInterval(interval)
- done()
+ if (!graceTimeDone){
+ if (t > 1000 * settings.time_ulGraceTime){
+ if (totLoaded > 0){ // if the connection is so slow that we didn't get a single chunk yet, do not reset
+ startT = new Date().getTime()
+ totLoaded = 0.0;
+ }
+ graceTimeDone = true;
+ }
+ }else{
+ var speed = totLoaded / (t / 1000.0)
+ ulStatus = ((speed * 8 * settings.overheadCompensationFactor)/1048576).toFixed(2) // speed is multiplied by 8 to go from bytes to bits, overhead compensation is applied, then everything is divided by 1048576 to go to megabits/s
+ if (((t / 1000.0) > settings.time_ul && ulStatus > 0) || failed) { // test is over, stop streams and timer
+ if (failed || isNaN(ulStatus)) ulStatus = 'Fail'
+ clearRequests()
+ clearInterval(interval)
+ done()
+ }
}
}, 200)
}
@@ -420,6 +420,7 @@ function ulTest (done) {
var ptCalled = false // used to prevent multiple accidental calls to pingTest
function pingTest (done) {
if (ptCalled) return; else ptCalled = true // pingTest already called?
+ if (settings.url_ping == "-1") {done(); return}
var prevT = null // last time a pong was received
var ping = 0.0 // current ping value
var jitter = 0.0 // current jitter value
@@ -440,9 +441,9 @@ function pingTest (done) {
if (i === 0) {
prevT = new Date().getTime() // first pong
} else {
- var instspd = (new Date().getTime() - prevT) / 2
+ var instspd = (new Date().getTime() - prevT)
var instjitter = Math.abs(instspd - prevInstspd)
- if (i === 1) ping = instspd; /* first ping, can't tell jiutter yet */ else {
+ if (i === 1) ping = instspd; /* first ping, can't tell jitter yet*/ else {
ping = ping * 0.9 + instspd * 0.1 // ping, weighted average
jitter = instjitter > jitter ? (jitter * 0.2 + instjitter * 0.8) : (jitter * 0.9 + instjitter * 0.1) // update jitter, weighted average. spikes in ping values are given more weight.
}
@@ -450,14 +451,27 @@ function pingTest (done) {
}
pingStatus = ping.toFixed(2)
jitterStatus = jitter.toFixed(2)
- pingCb()
- }
- xhr[0].ontimeout = xhr[0].onerror = function () {
- packetLoss += 1
- pingCb()
- }
+ i++
+ if (i < settings.count_ping) doPing(); else done() // more pings to do?
+ }.bind(this)
+ xhr[0].onerror = function () {
+ // a ping failed, cancel test
+ if (settings.xhr_ignoreErrors === 0) { //abort
+ pingStatus = 'Fail'
+ jitterStatus = 'Fail'
+ clearRequests()
+ done()
+ }
+ if (settings.xhr_ignoreErrors === 1) doPing() //retry ping
+
+ if (settings.xhr_ignoreErrors === 2){ //ignore failed ping
+ i++
+ packetLoss += 1
+ if (i < settings.count_ping) doPing(); else done() // more pings to do?
+ }
+ }.bind(this)
// sent xhr
- xhr[0].open('GET', settings.url_ping + '?r=' + Math.random(), true) // random string to prevent caching
+ xhr[0].open('GET', settings.url_ping + url_sep(settings.url_ping) + 'r=' + Math.random(), true) // random string to prevent caching
xhr[0].send()
}
doPing() // start first ping
diff --git a/speedtest_worker.min.js b/speedtest_worker.min.js
index 3e1a0c715..69f40eddf 100644
--- a/speedtest_worker.min.js
+++ b/speedtest_worker.min.js
@@ -1 +1 @@
-function clearRequests(){if(xhr){for(var i=0;isettings.time_dl||failed)&&((failed||isNaN(dlStatus))&&(dlStatus="Fail"),clearRequests(),clearInterval(interval),done()))},200)}}function ulTest(done){if(!ulCalled){ulCalled=!0;var totLoaded=0,startT=(new Date).getTime(),failed=!1;xhr=[];for(var testStream=function(i,delay){setTimeout(function(){if(3===testStatus){var prevLoaded=0,x=new XMLHttpRequest;xhr[i]=x;var ie11workaround;try{xhr[i].upload.onprogress,ie11workaround=!1}catch(e){ie11workaround=!0}ie11workaround?(xhr[i].onload=function(){totLoaded+=262144,testStream(i,0)},xhr[i].onerror=function(){failed=!0;try{xhr[i].abort()}catch(e){}delete xhr[i]},xhr[i].open("POST",settings.url_ul+"?r="+Math.random(),!0),xhr[i].setRequestHeader("Content-Encoding","identity"),xhr[i].send(reqsmall)):(xhr[i].upload.onprogress=function(event){if(3!==testStatus)try{x.abort()}catch(e){}var loadDiff=event.loaded<=0?0:event.loaded-prevLoaded;isNaN(loadDiff)||!isFinite(loadDiff)||loadDiff<0||(totLoaded+=loadDiff,prevLoaded=event.loaded)},xhr[i].upload.onload=function(){testStream(i,0)},xhr[i].upload.onerror=function(){failed=!0;try{xhr[i].abort()}catch(e){}delete xhr[i]},xhr[i].open("POST",settings.url_ul+"?r="+Math.random(),!0),xhr[i].setRequestHeader("Content-Encoding","identity"),xhr[i].send(req))}},1)},i=0;isettings.time_ul||failed)&&((failed||isNaN(ulStatus))&&(ulStatus="Fail"),clearRequests(),clearInterval(interval),done()))},200)}}function pingTest(done){if(!ptCalled){ptCalled=!0;var prevT=null,ping=0,jitter=0,i=0,prevInstspd=0;xhr=[];var doPing=function(){var pingCb=function(){++ijitter?.2*jitter+.8*instjitter:.9*jitter+.1*instjitter),prevInstspd=instspd}pingStatus=ping.toFixed(2),jitterStatus=jitter.toFixed(2),pingCb()},xhr[0].ontimeout=xhr[0].onerror=function(){packetLoss+=1,pingCb()},xhr[0].open("GET",settings.url_ping+"?r="+Math.random(),!0),xhr[0].send()};doPing()}}function ispInfo(done){try{(xhr=new XMLHttpRequest).onload=function(){var ispInfo=JSON.parse(xhr.responseText);ispInfo.hasOwnProperty("ip")&&(clientIp=ispInfo.ip),ispInfo.hasOwnProperty("country")&&(country=ispInfo.country),ispInfo.hasOwnProperty("region")&&(region=ispInfo.region),ispInfo.hasOwnProperty("org")&&(isp=ispInfo.org),done()},xhr.onerror=function(){done()},xhr.open("GET",settings.url_ispInfo+"/"+clientIp+"/json",!0),xhr.setRequestHeader("Accept","application/json"),xhr.send()}catch(e){console.log(e.message)}}function saveResult(result){4===testStatus&&((xhr=new XMLHttpRequest).onload=function(){console.log(xhr.responseText)},xhr.onerror=function(){},xhr.open("POST",settings.url_saveResult,!0),xhr.setRequestHeader("Content-Type","application/json"),xhr.setRequestHeader("Accept","application/json"),xhr.send(JSON.stringify({data:result})))}var testStatus=0,dlStatus="",ulStatus="",pingStatus="",jitterStatus="",clientIp="",pot="",packetLoss=0,country="",region="",isp="",settings={time_ul:15,time_dl:15,count_ping:35,ping_timeout:1e3,url_dl:"/download/",url_ul:"/upload",url_ping:"/ping",url_getIp:"/ip",url_getPointsOfTest:"/pots",url_saveResult:"/save",url_ispInfo:"http://ipinfo.io",xhr_dlMultistream:10,xhr_ulMultistream:3,xhr_dlUseBlob:!1,garbagePhp_chunkSize:20,enable_quirks:!0,enable_multiPots:!1,allow_fetchAPI:!1,force_fetchAPI:!1},xhr=null,interval=null,useFetchAPI=!1;this.addEventListener("message",function(e){var params=e.data.split(" "),useragent="";try{useragent=navigator.userAgent}catch(e){console.log(e.message)}if("status"===params[0]&&(postMessage(testStatus+";"+dlStatus+";"+ulStatus+";"+pingStatus+";"+clientIp+";"+jitterStatus+";"+pot+";"+packetLoss+";"+country+";"+region+";"+isp+";"+useragent),saveResult({download:dlStatus,upload:ulStatus,ping:pingStatus,jitter:jitterStatus,packetloss:packetLoss,pot:pot,ip:clientIp,useragent:useragent,country:country,region:region,isp:isp})),"start"===params[0]&&0===testStatus){testStatus=1;try{var s=JSON.parse(e.data.substring(5));if(void 0!==s.url_dl&&(settings.url_dl=s.url_dl),void 0!==s.url_ul&&(settings.url_ul=s.url_ul),void 0!==s.url_ping&&(settings.url_ping=s.url_ping),void 0!==s.ping_timeout&&(settings.ping_timeout=s.ping_timeout),void 0!==s.url_getIp&&(settings.url_getIp=s.url_getIp),void 0!==s.url_getPointsOfTest&&(settings.url_getPointsOfTest=s.url_getPointsOfTest),void 0!==s.url_saveResult&&(settings.url_saveResult=s.url_saveResult),void 0!==s.time_dl&&(settings.time_dl=s.time_dl),void 0!==s.time_ul&&(settings.time_ul=s.time_ul),void 0!==s.enable_quirks&&(settings.enable_quirks=s.enable_quirks),void 0!==s.enable_multiPots&&(settings.enable_multiPots=s.enable_multiPots),void 0!==s.allow_fetchAPI&&(settings.allow_fetchAPI=s.allow_fetchAPI),settings.enable_quirks){var ua=navigator.userAgent;/Firefox.(\d+\.\d+)/i.test(ua)&&(settings.xhr_ulMultistream=1),/Edge.(\d+\.\d+)/i.test(ua)&&(settings.xhr_dlMultistream=3),/Safari.(\d+)/i.test(ua)&&!/Chrome.(\d+)/i.test(ua)&&(settings.xhr_ulMultistream=10,settings.garbagePhp_chunkSize=5),/Chrome.(\d+)/i.test(ua)&&self.fetch&&(settings.allow_fetchAPI&&(useFetchAPI=!0),settings.xhr_dlMultistream=5)}void 0!==s.count_ping&&(settings.count_ping=s.count_ping),void 0!==s.xhr_dlMultistream&&(settings.xhr_dlMultistream=s.xhr_dlMultistream),void 0!==s.xhr_ulMultistream&&(settings.xhr_ulMultistream=s.xhr_ulMultistream),void 0!==s.xhr_dlUseBlob&&(settings.xhr_dlUseBlob=s.xhr_dlUseBlob),void 0!==s.garbagePhp_chunkSize&&(settings.garbagePhp_chunkSize=s.garbagePhp_chunkSize),void 0!==s.force_fetchAPI&&(settings.force_fetchAPI=s.force_fetchAPI),settings.allow_fetchAPI&&settings.force_fetchAPI&&self.fetch&&(useFetchAPI=!0)}catch(e){}console.log(settings),console.log("Fetch API: "+useFetchAPI),getServer(function(){getIp(function(){ispInfo(function(){dlTest(function(){testStatus=2,pingTest(function(){testStatus=3,ulTest(function(){testStatus=4})})})})})})}"abort"===params[0]&&(clearRequests(),interval&&clearInterval(interval),testStatus=5,dlStatus="",ulStatus="",pingStatus="",jitterStatus="",pot="",packetLoss=0,country="",region="",isp="")});var dlCalled=!1,r=new ArrayBuffer(1048576);try{r=new Float32Array(r);for(var i=0;isettings.time_dl&&dlStatus>0||failed)&&((failed||isNaN(dlStatus))&&(dlStatus="Fail"),clearRequests(),clearInterval(interval),done())):t>1e3*settings.time_dlGraceTime&&(totLoaded>0&&(startT=(new Date).getTime(),totLoaded=0),graceTimeDone=!0))},200)}else done()}function ulTest(done){if(!ulCalled)if(ulCalled=!0,"-1"!=settings.url_ul){var totLoaded=0,startT=(new Date).getTime(),graceTimeDone=!1,failed=!1;xhr=[];for(var testStream=function(i,delay){setTimeout(function(){if(3===testStatus){var prevLoaded=0,x=new XMLHttpRequest;xhr[i]=x;var ie11workaround;try{xhr[i].upload.onprogress,ie11workaround=!1}catch(e){ie11workaround=!0}ie11workaround?(xhr[i].onload=function(){totLoaded+=262144,testStream(i,0)},xhr[i].onerror=function(){0===settings.xhr_ignoreErrors&&(failed=!0);try{xhr[i].abort()}catch(e){}delete xhr[i],1===settings.xhr_ignoreErrors&&testStream(i,100)},xhr[i].open("POST",settings.url_ul+url_sep(settings.url_ul)+"r="+Math.random(),!0),xhr[i].setRequestHeader("Content-Encoding","identity"),xhr[i].send(reqsmall)):(xhr[i].upload.onprogress=function(event){if(3!==testStatus)try{x.abort()}catch(e){}var loadDiff=event.loaded<=0?0:event.loaded-prevLoaded;isNaN(loadDiff)||!isFinite(loadDiff)||loadDiff<0||(totLoaded+=loadDiff,prevLoaded=event.loaded)},xhr[i].upload.onload=function(){testStream(i,0)},xhr[i].upload.onerror=function(){0===settings.xhr_ignoreErrors&&(failed=!0);try{xhr[i].abort()}catch(e){}delete xhr[i],1===settings.xhr_ignoreErrors&&testStream(i,100)}.bind(this),xhr[i].open("POST",settings.url_ul+url_sep(settings.url_ul)+"r="+Math.random(),!0),xhr[i].setRequestHeader("Content-Encoding","identity"),xhr[i].send(req))}},1)},i=0;isettings.time_ul&&ulStatus>0||failed)&&((failed||isNaN(ulStatus))&&(ulStatus="Fail"),clearRequests(),clearInterval(interval),done())):t>1e3*settings.time_ulGraceTime&&(totLoaded>0&&(startT=(new Date).getTime(),totLoaded=0),graceTimeDone=!0))},200)}else done()}function pingTest(done){if(!ptCalled)if(ptCalled=!0,"-1"!=settings.url_ping){var prevT=null,ping=0,jitter=0,i=0,prevInstspd=0;xhr=[];var doPing=function(){prevT=(new Date).getTime(),xhr[0]=new XMLHttpRequest,xhr[0].timeout=settings.ping_timeout,xhr[0].onload=function(){if(0===i)prevT=(new Date).getTime();else{var instspd=(new Date).getTime()-prevT,instjitter=Math.abs(instspd-prevInstspd);1===i?ping=instspd:(ping=.9*ping+.1*instspd,jitter=instjitter>jitter?.2*jitter+.8*instjitter:.9*jitter+.1*instjitter),prevInstspd=instspd}pingStatus=ping.toFixed(2),jitterStatus=jitter.toFixed(2),++i