speedtest_worker.js 18 KB

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