speedtest_worker.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. /*
  2. HTML5 Speedtest v4.2.5
  3. by Federico Dossena
  4. https://github.com/adolfintel/speedtest/
  5. GNU LGPLv3 License
  6. */
  7. // data reported to main thread
  8. var testStatus = 0 // 0=not started, 1=download test, 2=ping+jitter test, 3=upload test, 4=finished, 5=abort/error
  9. var dlStatus = '' // download speed in megabit/s with 2 decimal digits
  10. var ulStatus = '' // upload speed in megabit/s with 2 decimal digits
  11. var pingStatus = '' // ping in milliseconds with 2 decimal digits
  12. var jitterStatus = '' // jitter in milliseconds with 2 decimal digits
  13. var clientIp = '' // client's IP address as reported by getIP.php
  14. // test settings. can be overridden by sending specific values with the start command
  15. var settings = {
  16. time_ul: 15, // duration of upload test in seconds
  17. time_dl: 15, // duration of download test in seconds
  18. time_ulGraceTime: 3, //time to wait in seconds before actually measuring ul speed (wait for buffers to fill)
  19. time_dlGraceTime: 1.5, //time to wait in seconds before actually measuring dl speed (wait for TCP window to increase)
  20. count_ping: 35, // number of pings to perform in ping test
  21. url_dl: 'garbage.php', // path to a large file or garbage.php, used for download test. must be relative to this js file
  22. url_ul: 'empty.php', // path to an empty file, used for upload test. must be relative to this js file
  23. url_ping: 'empty.php', // path to an empty file, used for ping test. must be relative to this js file
  24. url_getIp: 'getIP.php', // path to getIP.php relative to this js file, or a similar thing that outputs the client's ip
  25. xhr_dlMultistream: 10, // number of download streams to use (can be different if enable_quirks is active)
  26. xhr_ulMultistream: 3, // number of upload streams to use (can be different if enable_quirks is active)
  27. xhr_ignoreErrors: 1, // 0=fail on errors, 1=attempt to restart a stream if it fails, 2=ignore all errors
  28. 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)
  29. garbagePhp_chunkSize: 20, // size of chunks sent by garbage.php (can be different if enable_quirks is active)
  30. 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
  31. allow_fetchAPI: false, // enables Fetch API. currently disabled because it leaks memory like no tomorrow
  32. force_fetchAPI: false, // when Fetch API is enabled, it will force usage on every browser that supports it
  33. 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)
  34. }
  35. var xhr = null // array of currently active xhr requests
  36. var interval = null // timer used in tests
  37. /*
  38. when set to true (automatically) the download test will use the fetch api instead of xhr.
  39. fetch api is used if
  40. -allow_fetchAPI is true AND
  41. -(we're on chrome that supports fetch api AND enable_quirks is true) OR (we're on any browser that supports fetch api AND force_fetchAPI is true)
  42. */
  43. var useFetchAPI = false
  44. /*
  45. this function is used on URLs passed in the settings to determine whether we need a ? or an & as a separator
  46. */
  47. function url_sep (url) { return url.match(/\?/) ? '&' : '?'; }
  48. /*
  49. listener for commands from main thread to this worker.
  50. commands:
  51. -status: returns the current status as a string of values spearated by a semicolon (;) in this order: testStatus;dlStatus;ulStatus;pingStatus;clientIp;jitterStatus
  52. -abort: aborts the current test
  53. -start: starts the test. optionally, settings can be passed as JSON.
  54. example: start {"time_ul":"10", "time_dl":"10", "count_ping":"50"}
  55. */
  56. this.addEventListener('message', function (e) {
  57. var params = e.data.split(' ')
  58. if (params[0] === 'status') { // return status
  59. postMessage(testStatus + ';' + dlStatus + ';' + ulStatus + ';' + pingStatus + ';' + clientIp + ';' + jitterStatus)
  60. }
  61. if (params[0] === 'start' && testStatus === 0) { // start new test
  62. testStatus = 1
  63. try {
  64. // parse settings, if present
  65. var s = {}
  66. try{
  67. var ss = e.data.substring(5);
  68. if (ss) s = JSON.parse(ss);
  69. }catch(e){ console.warn("Error parsing custom settings JSON. Please check your syntax"); }
  70. if (typeof s.url_dl !== 'undefined') settings.url_dl = s.url_dl // download url
  71. if (typeof s.url_ul !== 'undefined') settings.url_ul = s.url_ul // upload url
  72. if (typeof s.url_ping !== 'undefined') settings.url_ping = s.url_ping // ping url
  73. if (typeof s.url_getIp !== 'undefined') settings.url_getIp = s.url_getIp // url to getIP.php
  74. if (typeof s.time_dl !== 'undefined') settings.time_dl = s.time_dl // duration of download test
  75. if (typeof s.time_ul !== 'undefined') settings.time_ul = s.time_ul // duration of upload test
  76. if (typeof s.enable_quirks !== 'undefined') settings.enable_quirks = s.enable_quirks // enable quirks or not
  77. if (typeof s.allow_fetchAPI !== 'undefined') settings.allow_fetchAPI = s.allow_fetchAPI // allows fetch api to be used if supported
  78. // quirks for specific browsers. more may be added in future releases
  79. if (settings.enable_quirks) {
  80. var ua = navigator.userAgent
  81. if (/Firefox.(\d+\.\d+)/i.test(ua)) {
  82. // ff more precise with 1 upload stream
  83. settings.xhr_ulMultistream = 1
  84. }
  85. if (/Edge.(\d+\.\d+)/i.test(ua)) {
  86. // edge more precise with 3 download streams
  87. settings.xhr_dlMultistream = 3
  88. }
  89. if ((/Safari.(\d+)/i.test(ua)) && !(/Chrome.(\d+)/i.test(ua))) {
  90. // safari more precise with 10 upload streams and 5mb chunks for download test
  91. settings.xhr_ulMultistream = 10
  92. settings.garbagePhp_chunkSize = 5
  93. }
  94. if (/Chrome.(\d+)/i.test(ua) && (!!self.fetch)) {
  95. // chrome can't handle large xhr very well, use fetch api if available and allowed
  96. if (settings.allow_fetchAPI) useFetchAPI = true
  97. // chrome more precise with 5 streams
  98. settings.xhr_dlMultistream = 5
  99. }
  100. }
  101. if (typeof s.count_ping !== 'undefined') settings.count_ping = s.count_ping // number of pings for ping test
  102. if (typeof s.xhr_dlMultistream !== 'undefined') settings.xhr_dlMultistream = s.xhr_dlMultistream // number of download streams
  103. if (typeof s.xhr_ulMultistream !== 'undefined') settings.xhr_ulMultistream = s.xhr_ulMultistream // number of upload streams
  104. if (typeof s.xhr_ignoreErrors !== 'undefined') settings.xhr_ignoreErrors = s.xhr_ignoreErrors // what to do in case of errors during the test
  105. if (typeof s.xhr_dlUseBlob !== 'undefined') settings.xhr_dlUseBlob = s.xhr_dlUseBlob // use blob for download test
  106. if (typeof s.garbagePhp_chunkSize !== 'undefined') settings.garbagePhp_chunkSize = s.garbagePhp_chunkSize // size of garbage.php chunks
  107. if (typeof s.force_fetchAPI !== 'undefined') settings.force_fetchAPI = s.force_fetchAPI // use fetch api on all browsers that support it if enabled
  108. if (typeof s.time_dlGraceTime !== 'undefined') settings.time_dlGraceTime = s.time_dlGraceTime // dl test grace time before measuring
  109. if (typeof s.time_ulGraceTime !== 'undefined') settings.time_ulGraceTime = s.time_ulGraceTime // ul test grace time before measuring
  110. if (typeof s.overheadCompensationFactor !== 'undefined') settings.overheadCompensationFactor = s.overheadCompensationFactor //custom overhead compensation factor (default assumes HTTP+TCP+IP+ETH with typical MTUs)
  111. if (settings.allow_fetchAPI && settings.force_fetchAPI && (!!self.fetch)) useFetchAPI = true
  112. } catch (e) { console.warn("Possible error in custom test settings. Some settings may not be applied. Exception: "+e) }
  113. // run the tests
  114. console.log(settings)
  115. console.log('Fetch API: ' + useFetchAPI)
  116. getIp(function () { dlTest(function () { testStatus = 2; pingTest(function () { testStatus = 3; ulTest(function () { testStatus = 4 }) }) }) })
  117. }
  118. if (params[0] === 'abort') { // abort command
  119. clearRequests() // stop all xhr activity
  120. if (interval) clearInterval(interval) // clear timer if present
  121. testStatus = 5; dlStatus = ''; ulStatus = ''; pingStatus = ''; jitterStatus = '' // set test as aborted
  122. }
  123. })
  124. // stops all XHR activity, aggressively
  125. function clearRequests () {
  126. if (xhr) {
  127. for (var i = 0; i < xhr.length; i++) {
  128. if (useFetchAPI) try { xhr[i].cancelRequested = true } catch (e) { }
  129. try { xhr[i].onprogress = null; xhr[i].onload = null; xhr[i].onerror = null } catch (e) { }
  130. try { xhr[i].upload.onprogress = null; xhr[i].upload.onload = null; xhr[i].upload.onerror = null } catch (e) { }
  131. try { xhr[i].abort() } catch (e) { }
  132. try { delete (xhr[i]) } catch (e) { }
  133. }
  134. xhr = null
  135. }
  136. }
  137. // gets client's IP using url_getIp, then calls the done function
  138. function getIp (done) {
  139. xhr = new XMLHttpRequest()
  140. xhr.onload = function () {
  141. clientIp = xhr.responseText
  142. done()
  143. }
  144. xhr.onerror = function () {
  145. done()
  146. }
  147. xhr.open('GET', settings.url_getIp + url_sep(settings.url_getIp) + 'r=' + Math.random(), true)
  148. xhr.send()
  149. }
  150. // download test, calls done function when it's over
  151. var dlCalled = false // used to prevent multiple accidental calls to dlTest
  152. function dlTest (done) {
  153. if (dlCalled) return; else dlCalled = true // dlTest already called?
  154. var totLoaded = 0.0, // total number of loaded bytes
  155. startT = new Date().getTime(), // timestamp when test was started
  156. graceTimeDone = false, //set to true after the grace time is past
  157. failed = false // set to true if a stream fails
  158. xhr = []
  159. // function to create a download stream. streams are slightly delayed so that they will not end at the same time
  160. var testStream = function (i, delay) {
  161. setTimeout(function () {
  162. if (testStatus !== 1) return // delayed stream ended up starting after the end of the download test
  163. if (useFetchAPI) {
  164. xhr[i] = fetch(settings.url_dl + url_sep(settings.url_dl) + 'r=' + Math.random() + '&ckSize=' + settings.garbagePhp_chunkSize).then(function (response) {
  165. var reader = response.body.getReader()
  166. var consume = function () {
  167. return reader.read().then(function (result) {
  168. if (result.done) testStream(i); else {
  169. totLoaded += result.value.length
  170. if (xhr[i].cancelRequested) reader.cancel()
  171. }
  172. return consume()
  173. }.bind(this))
  174. }.bind(this)
  175. return consume()
  176. }.bind(this))
  177. } else {
  178. var prevLoaded = 0 // number of bytes loaded last time onprogress was called
  179. var x = new XMLHttpRequest()
  180. xhr[i] = x
  181. xhr[i].onprogress = function (event) {
  182. if (testStatus !== 1) { try { x.abort() } catch (e) { } } // just in case this XHR is still running after the download test
  183. // progress event, add number of new loaded bytes to totLoaded
  184. var loadDiff = event.loaded <= 0 ? 0 : (event.loaded - prevLoaded)
  185. if (isNaN(loadDiff) || !isFinite(loadDiff) || loadDiff < 0) return // just in case
  186. totLoaded += loadDiff
  187. prevLoaded = event.loaded
  188. }.bind(this)
  189. xhr[i].onload = function () {
  190. // the large file has been loaded entirely, start again
  191. try { xhr[i].abort() } catch (e) { } // reset the stream data to empty ram
  192. testStream(i, 0)
  193. }.bind(this)
  194. xhr[i].onerror = function () {
  195. // error
  196. if (settings.xhr_ignoreErrors === 0) failed=true //abort
  197. try { xhr[i].abort() } catch (e) { }
  198. delete (xhr[i])
  199. if (settings.xhr_ignoreErrors === 1) testStream(i, 100) //restart stream after 100ms
  200. }.bind(this)
  201. // send xhr
  202. try { if (settings.xhr_dlUseBlob) xhr[i].responseType = 'blob'; else xhr[i].responseType = 'arraybuffer' } catch (e) { }
  203. 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
  204. xhr[i].send()
  205. }
  206. }.bind(this), 1 + delay)
  207. }.bind(this)
  208. // open streams
  209. for (var i = 0; i < settings.xhr_dlMultistream; i++) {
  210. testStream(i, 100 * i)
  211. }
  212. // every 200ms, update dlStatus
  213. interval = setInterval(function () {
  214. var t = new Date().getTime() - startT
  215. if (t < 200) return
  216. if (!graceTimeDone){
  217. if (t > 1000 * settings.time_dlGraceTime){
  218. if (totLoaded > 0){ // if the connection is so slow that we didn't get a single chunk yet, do not reset
  219. startT = new Date().getTime()
  220. totLoaded = 0.0;
  221. }
  222. graceTimeDone = true;
  223. }
  224. }else{
  225. var speed = totLoaded / (t / 1000.0)
  226. 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
  227. if ((t / 1000.0) > settings.time_dl || failed) { // test is over, stop streams and timer
  228. if (failed || isNaN(dlStatus)) dlStatus = 'Fail'
  229. clearRequests()
  230. clearInterval(interval)
  231. done()
  232. }
  233. }
  234. }.bind(this), 200)
  235. }
  236. // upload test, calls done function whent it's over
  237. // garbage data for upload test
  238. var r = new ArrayBuffer(1048576)
  239. try { r = new Float32Array(r); for (var i = 0; i < r.length; i++)r[i] = Math.random() } catch (e) { }
  240. var req = []
  241. var reqsmall = []
  242. for (var i = 0; i < 20; i++) req.push(r)
  243. req = new Blob(req)
  244. r = new ArrayBuffer(262144)
  245. try { r = new Float32Array(r); for (var i = 0; i < r.length; i++)r[i] = Math.random() } catch (e) { }
  246. reqsmall.push(r)
  247. reqsmall = new Blob(reqsmall)
  248. var ulCalled = false // used to prevent multiple accidental calls to ulTest
  249. function ulTest (done) {
  250. if (ulCalled) return; else ulCalled = true // ulTest already called?
  251. var totLoaded = 0.0, // total number of transmitted bytes
  252. startT = new Date().getTime(), // timestamp when test was started
  253. graceTimeDone = false, //set to true after the grace time is past
  254. failed = false // set to true if a stream fails
  255. xhr = []
  256. // function to create an upload stream. streams are slightly delayed so that they will not end at the same time
  257. var testStream = function (i, delay) {
  258. setTimeout(function () {
  259. if (testStatus !== 3) return // delayed stream ended up starting after the end of the upload test
  260. var prevLoaded = 0 // number of bytes transmitted last time onprogress was called
  261. var x = new XMLHttpRequest()
  262. xhr[i] = x
  263. var ie11workaround
  264. try {
  265. xhr[i].upload.onprogress
  266. ie11workaround = false
  267. } catch (e) {
  268. ie11workaround = true
  269. }
  270. if (ie11workaround) {
  271. // IE11 workarond: xhr.upload does not work properly, therefore we send a bunch of small 256k requests and use the onload event as progress. This is not precise, especially on fast connections
  272. xhr[i].onload = function () {
  273. totLoaded += 262144
  274. testStream(i, 0)
  275. }
  276. xhr[i].onerror = function () {
  277. // error, abort
  278. if (settings.xhr_ignoreErrors === 0) failed = true //abort
  279. try { xhr[i].abort() } catch (e) { }
  280. delete (xhr[i])
  281. if (settings.xhr_ignoreErrors === 1) testStream(i,100); //restart stream after 100ms
  282. }
  283. xhr[i].open('POST', settings.url_ul + url_sep(settings.url_ul) + 'r=' + Math.random(), true) // random string to prevent caching
  284. xhr[i].setRequestHeader('Content-Encoding', 'identity') // disable compression (some browsers may refuse it, but data is incompressible anyway)
  285. xhr[i].send(reqsmall)
  286. } else {
  287. // REGULAR version, no workaround
  288. xhr[i].upload.onprogress = function (event) {
  289. if (testStatus !== 3) { try { x.abort() } catch (e) { } } // just in case this XHR is still running after the upload test
  290. // progress event, add number of new loaded bytes to totLoaded
  291. var loadDiff = event.loaded <= 0 ? 0 : (event.loaded - prevLoaded)
  292. if (isNaN(loadDiff) || !isFinite(loadDiff) || loadDiff < 0) return // just in case
  293. totLoaded += loadDiff
  294. prevLoaded = event.loaded
  295. }.bind(this)
  296. xhr[i].upload.onload = function () {
  297. // this stream sent all the garbage data, start again
  298. testStream(i, 0)
  299. }.bind(this)
  300. xhr[i].upload.onerror = function () {
  301. if (settings.xhr_ignoreErrors === 0) failed=true //abort
  302. try { xhr[i].abort() } catch (e) { }
  303. delete (xhr[i])
  304. if (settings.xhr_ignoreErrors === 1) testStream(i, 100) //restart stream after 100ms
  305. }.bind(this)
  306. // send xhr
  307. xhr[i].open('POST', settings.url_ul + url_sep(settings.url_ul) + 'r=' + Math.random(), true) // random string to prevent caching
  308. xhr[i].setRequestHeader('Content-Encoding', 'identity') // disable compression (some browsers may refuse it, but data is incompressible anyway)
  309. xhr[i].send(req)
  310. }
  311. }.bind(this), 1)
  312. }.bind(this)
  313. // open streams
  314. for (var i = 0; i < settings.xhr_ulMultistream; i++) {
  315. testStream(i, 100 * i)
  316. }
  317. // every 200ms, update ulStatus
  318. interval = setInterval(function () {
  319. var t = new Date().getTime() - startT
  320. if (t < 200) return
  321. if (!graceTimeDone){
  322. if (t > 1000 * settings.time_ulGraceTime){
  323. if (totLoaded > 0){ // if the connection is so slow that we didn't get a single chunk yet, do not reset
  324. startT = new Date().getTime()
  325. totLoaded = 0.0;
  326. }
  327. graceTimeDone = true;
  328. }
  329. }else{
  330. var speed = totLoaded / (t / 1000.0)
  331. 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
  332. if ((t / 1000.0) > settings.time_ul || failed) { // test is over, stop streams and timer
  333. if (failed || isNaN(ulStatus)) ulStatus = 'Fail'
  334. clearRequests()
  335. clearInterval(interval)
  336. done()
  337. }
  338. }
  339. }.bind(this), 200)
  340. }
  341. // ping+jitter test, function done is called when it's over
  342. var ptCalled = false // used to prevent multiple accidental calls to pingTest
  343. function pingTest (done) {
  344. if (ptCalled) return; else ptCalled = true // pingTest already called?
  345. var prevT = null // last time a pong was received
  346. var ping = 0.0 // current ping value
  347. var jitter = 0.0 // current jitter value
  348. var i = 0 // counter of pongs received
  349. var prevInstspd = 0 // last ping time, used for jitter calculation
  350. xhr = []
  351. // ping function
  352. var doPing = function () {
  353. prevT = new Date().getTime()
  354. xhr[0] = new XMLHttpRequest()
  355. xhr[0].onload = function () {
  356. // pong
  357. if (i === 0) {
  358. prevT = new Date().getTime() // first pong
  359. } else {
  360. var instspd = (new Date().getTime() - prevT)
  361. var instjitter = Math.abs(instspd - prevInstspd)
  362. if (i === 1) ping = instspd; /* first ping, can't tell jitter yet*/ else {
  363. ping = ping * 0.9 + instspd * 0.1 // ping, weighted average
  364. 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.
  365. }
  366. prevInstspd = instspd
  367. }
  368. pingStatus = ping.toFixed(2)
  369. jitterStatus = jitter.toFixed(2)
  370. i++
  371. if (i < settings.count_ping) doPing(); else done() // more pings to do?
  372. }.bind(this)
  373. xhr[0].onerror = function () {
  374. // a ping failed, cancel test
  375. if (settings.xhr_ignoreErrors === 0) { //abort
  376. pingStatus = 'Fail'
  377. jitterStatus = 'Fail'
  378. clearRequests()
  379. done()
  380. }
  381. if (settings.xhr_ignoreErrors === 1) doPing() //retry ping
  382. if (settings.xhr_ignoreErrors === 2){ //ignore failed ping
  383. i++
  384. if (i < settings.count_ping) doPing(); else done() // more pings to do?
  385. }
  386. }.bind(this)
  387. // sent xhr
  388. xhr[0].open('GET', settings.url_ping + url_sep(settings.url_ping) + 'r=' + Math.random(), true) // random string to prevent caching
  389. xhr[0].send()
  390. }.bind(this)
  391. doPing() // start first ping
  392. }