speedtest_worker.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  1. /*
  2. HTML5 Speedtest v4.7 MPOT
  3. by Federico Dossena
  4. https://github.com/adolfintel/speedtest/
  5. GNU LGPLv3 License
  6. */
  7. // data reported to main thread
  8. var testStatus = -1 // -1=not started, 0=starting, 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. var dlProgress = 0 //progress of download test 0-1
  15. var ulProgress = 0 //progress of upload test 0-1
  16. var pingProgress = 0 //progress of ping+jitter test 0-1
  17. var testId = 'noID' //test ID (sent back by telemetry if used, the string 'noID' otherwise)
  18. var log='' //telemetry log
  19. function tlog(s){if(settings.telemetry_level>=2){log+=Date.now()+': '+s+'\n'}}
  20. function tverb(s){if(settings.telemetry_level>=3){log+=Date.now()+': '+s+'\n'}}
  21. function twarn(s){if(settings.telemetry_level>=2){log+=Date.now()+' WARN: '+s+'\n';} console.warn(s)}
  22. // test settings. can be overridden by sending specific values with the start command
  23. var settings = {
  24. test_order: "IP_D_U", //order in which tests will be performed as a string. D=Download, U=Upload, P=Ping+Jitter, I=IP, _=1 second delay
  25. time_ul_max: 15, // max duration of upload test in seconds
  26. time_dl_max: 15, // max duration of download test in seconds
  27. time_auto: true, // if set to true, tests will take less time on faster connections
  28. time_ulGraceTime: 3, //time to wait in seconds before actually measuring ul speed (wait for buffers to fill)
  29. time_dlGraceTime: 1.5, //time to wait in seconds before actually measuring dl speed (wait for TCP window to increase)
  30. count_ping: 10, // number of pings to perform in ping test
  31. url_dl: 'garbage.php', // path to a large file or garbage.php, used for download test. must be relative to this js file
  32. url_ul: 'empty.php', // path to an empty file, used for upload test. must be relative to this js file
  33. url_ping: 'empty.php', // path to an empty file, used for ping test. must be relative to this js file
  34. url_getIp: 'getIP.php', // path to getIP.php relative to this js file, or a similar thing that outputs the client's ip
  35. getIp_ispInfo: true, //if set to true, the server will include ISP info with the IP address
  36. getIp_ispInfo_distance: 'km', //km or mi=estimate distance from server in km/mi; set to false to disable distance estimation. getIp_ispInfo must be enabled in order for this to work
  37. xhr_dlMultistream: 10, // number of download streams to use (can be different if enable_quirks is active)
  38. xhr_ulMultistream: 3, // number of upload streams to use (can be different if enable_quirks is active)
  39. xhr_ul_sendPostRequestBeforeStartingTest: true, //if set to true, a single empty POST request will be sent to the upload test URL. This bypasses bugs with CORS headers in some browsers.
  40. xhr_multistreamDelay: 300, //how much concurrent requests should be delayed
  41. xhr_ignoreErrors: 1, // 0=fail on errors, 1=attempt to restart a stream if it fails, 2=ignore all errors
  42. 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)
  43. xhr_ul_blob_megabytes: 20, //size in megabytes of the upload blobs sent in the upload test (forced to 4 on chrome mobile)
  44. garbagePhp_chunkSize: 20, // size of chunks sent by garbage.php (can be different if enable_quirks is active)
  45. 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
  46. ping_allowPerformanceApi: true, // if enabled, the ping test will attempt to calculate the ping more precisely using the Performance API. Currently works perfectly in Chrome, badly in Edge, and not at all in Firefox. If Performance API is not supported or the result is obviously wrong, a fallback is provided.
  47. overheadCompensationFactor: 1.06, //can be changed to compensatie for transport overhead. (see doc.md for some other values)
  48. useMebibits: false, //if set to true, speed will be reported in mebibits/s instead of megabits/s
  49. telemetry_level: 0, // 0=disabled, 1=basic (results only), 2=full (results and timing) 3=debug (results+log)
  50. url_telemetry: 'telemetry/telemetry.php', // path to the script that adds telemetry data to the database
  51. telemetry_extra: '' //extra data that can be passed to the telemetry through the settings
  52. }
  53. var xhr = null // array of currently active xhr requests
  54. var interval = null // timer used in tests
  55. var test_pointer = 0 //pointer to the next test to run inside settings.test_order
  56. /*
  57. this function is used on URLs passed in the settings to determine whether we need a ? or an & as a separator
  58. */
  59. function url_sep (url) { return url.match(/\?/) ? '&' : '?'; }
  60. /*
  61. listener for commands from main thread to this worker.
  62. commands:
  63. -status: returns the current status as a JSON string containing testStatus, dlStatus, ulStatus, pingStatus, clientIp, jitterStatus, dlProgress, ulProgress, pingProgress
  64. -abort: aborts the current test
  65. -start: starts the test. optionally, settings can be passed as JSON.
  66. example: start {"time_ul_max":"10", "time_dl_max":"10", "count_ping":"50"}
  67. */
  68. this.addEventListener('message', function (e) {
  69. var params = e.data.split(' ')
  70. if (params[0] === 'status') { // return status
  71. postMessage(JSON.stringify({
  72. testState:testStatus,
  73. dlStatus:dlStatus,
  74. ulStatus:ulStatus,
  75. pingStatus:pingStatus,
  76. clientIp:clientIp,
  77. jitterStatus:jitterStatus,
  78. dlProgress:dlProgress,
  79. ulProgress:ulProgress,
  80. pingProgress:pingProgress,
  81. testId:testId
  82. }))
  83. }
  84. if (params[0] === 'start' && testStatus === -1) { // start new test
  85. testStatus = 0
  86. try {
  87. // parse settings, if present
  88. var s = {}
  89. try{
  90. var ss = e.data.substring(5)
  91. if (ss) s = JSON.parse(ss)
  92. }catch(e){ twarn('Error parsing custom settings JSON. Please check your syntax') }
  93. //copy custom settings
  94. for(var key in s){
  95. if(typeof settings[key] !== 'undefined') settings[key]=s[key]; else twarn("Unknown setting ignored: "+key);
  96. }
  97. // quirks for specific browsers. apply only if not overridden. more may be added in future releases
  98. if (settings.enable_quirks||(typeof s.enable_quirks !== 'undefined' && s.enable_quirks)) {
  99. var ua = navigator.userAgent
  100. if (/Firefox.(\d+\.\d+)/i.test(ua)) {
  101. if(typeof s.xhr_ulMultistream === 'undefined'){
  102. // ff more precise with 1 upload stream
  103. settings.xhr_ulMultistream = 1
  104. }
  105. }
  106. if (/Edge.(\d+\.\d+)/i.test(ua)) {
  107. if(typeof s.xhr_dlMultistream === 'undefined'){
  108. // edge more precise with 3 download streams
  109. settings.xhr_dlMultistream = 3
  110. }
  111. }
  112. if (/Chrome.(\d+)/i.test(ua) && (!!self.fetch)) {
  113. if(typeof s.xhr_dlMultistream === 'undefined'){
  114. // chrome more precise with 5 streams
  115. settings.xhr_dlMultistream = 5
  116. }
  117. }
  118. }
  119. if (/Edge.(\d+\.\d+)/i.test(ua)) {
  120. //Edge 15 introduced a bug that causes onprogress events to not get fired, we have to use the "small chunks" workaround that reduces accuracy
  121. settings.forceIE11Workaround = true
  122. }
  123. if (/Chrome.(\d+)/i.test(ua)&&/Android|iPhone|iPad|iPod|Windows Phone/i.test(ua)){ //cheap af
  124. //Chrome mobile introduced a limitation somewhere around version 65, we have to limit XHR upload size to 4 megabytes
  125. settings.xhr_ul_blob_megabytes=4;
  126. }
  127. //telemetry_level has to be parsed and not just copied
  128. if(typeof s.telemetry_level !== 'undefined') settings.telemetry_level = s.telemetry_level === 'basic' ? 1 : s.telemetry_level === 'full' ? 2 : s.telemetry_level === 'debug' ? 3 : 0; // telemetry level
  129. //transform test_order to uppercase, just in case
  130. settings.test_order=settings.test_order.toUpperCase();
  131. } catch (e) { twarn('Possible error in custom test settings. Some settings might not have been applied. Exception: '+e) }
  132. // run the tests
  133. tverb(JSON.stringify(settings))
  134. test_pointer=0;
  135. var iRun=false,dRun=false,uRun=false,pRun=false;
  136. var runNextTest=function(){
  137. if(testStatus==5) return;
  138. if(test_pointer>=settings.test_order.length){ //test is finished
  139. if(settings.telemetry_level>0)
  140. sendTelemetry(function(id){testStatus=4; if(id!=-1)testId=id})
  141. else testStatus=4
  142. return;
  143. }
  144. switch(settings.test_order.charAt(test_pointer)){
  145. case 'I':{test_pointer++; if(iRun) {runNextTest(); return;} else iRun=true; getIp(runNextTest);} break;
  146. case 'D':{test_pointer++; if(dRun) {runNextTest(); return;} else dRun=true; testStatus=1; dlTest(runNextTest);} break;
  147. case 'U':{test_pointer++; if(uRun) {runNextTest(); return;} else uRun=true; testStatus=3; ulTest(runNextTest);} break;
  148. case 'P':{test_pointer++; if(pRun) {runNextTest(); return;} else pRun=true; testStatus=2; pingTest(runNextTest);} break;
  149. case '_':{test_pointer++; setTimeout(runNextTest,1000);} break;
  150. default: test_pointer++;
  151. }
  152. }
  153. runNextTest()
  154. }
  155. if (params[0] === 'abort') { // abort command
  156. tlog('manually aborted')
  157. clearRequests() // stop all xhr activity
  158. runNextTest=null;
  159. if (interval) clearInterval(interval) // clear timer if present
  160. if (settings.telemetry_level > 1) sendTelemetry(function(){})
  161. testStatus = 5; dlStatus = ''; ulStatus = ''; pingStatus = ''; jitterStatus = '' // set test as aborted
  162. }
  163. })
  164. // stops all XHR activity, aggressively
  165. function clearRequests () {
  166. tverb('stopping pending XHRs')
  167. if (xhr) {
  168. for (var i = 0; i < xhr.length; i++) {
  169. try { xhr[i].onprogress = null; xhr[i].onload = null; xhr[i].onerror = null } catch (e) { }
  170. try { xhr[i].upload.onprogress = null; xhr[i].upload.onload = null; xhr[i].upload.onerror = null } catch (e) { }
  171. try { xhr[i].abort() } catch (e) { }
  172. try { delete (xhr[i]) } catch (e) { }
  173. }
  174. xhr = null
  175. }
  176. }
  177. // gets client's IP using url_getIp, then calls the done function
  178. var ipCalled = false // used to prevent multiple accidental calls to getIp
  179. var ispInfo=""; //used for telemetry
  180. function getIp (done) {
  181. tverb('getIp')
  182. if (ipCalled) return; else ipCalled = true // getIp already called?
  183. var startT=new Date().getTime();
  184. xhr = new XMLHttpRequest()
  185. xhr.onload = function () {
  186. tlog('IP: '+xhr.responseText+', took '+(new Date().getTime()-startT)+'ms')
  187. try{
  188. var data=JSON.parse(xhr.responseText)
  189. clientIp=data.processedString
  190. ispInfo=data.rawIspInfo
  191. }catch(e){
  192. clientIp = xhr.responseText
  193. ispInfo=''
  194. }
  195. done()
  196. }
  197. xhr.onerror = function () {
  198. tlog('getIp failed, took '+(new Date().getTime()-startT)+'ms')
  199. done()
  200. }
  201. xhr.open('GET', settings.url_getIp + url_sep(settings.url_getIp) + (settings.getIp_ispInfo?("isp=true"+(settings.getIp_ispInfo_distance?("&distance="+settings.getIp_ispInfo_distance+"&"):"&")):"&") + 'r=' + Math.random(), true)
  202. xhr.send()
  203. }
  204. // download test, calls done function when it's over
  205. var dlCalled = false // used to prevent multiple accidental calls to dlTest
  206. function dlTest (done) {
  207. tverb('dlTest')
  208. if (dlCalled) return; else dlCalled = true // dlTest already called?
  209. var totLoaded = 0.0, // total number of loaded bytes
  210. startT = new Date().getTime(), // timestamp when test was started
  211. bonusT = 0, //how many milliseconds the test has been shortened by (higher on faster connections)
  212. graceTimeDone = false, //set to true after the grace time is past
  213. failed = false // set to true if a stream fails
  214. xhr = []
  215. // function to create a download stream. streams are slightly delayed so that they will not end at the same time
  216. var testStream = function (i, delay) {
  217. setTimeout(function () {
  218. if (testStatus !== 1) return // delayed stream ended up starting after the end of the download test
  219. tverb('dl test stream started '+i+' '+delay)
  220. var prevLoaded = 0 // number of bytes loaded last time onprogress was called
  221. var x = new XMLHttpRequest()
  222. xhr[i] = x
  223. xhr[i].onprogress = function (event) {
  224. tverb('dl stream progress event '+i+' '+event.loaded)
  225. if (testStatus !== 1) { try { x.abort() } catch (e) { } } // just in case this XHR is still running after the download test
  226. // progress event, add number of new loaded bytes to totLoaded
  227. var loadDiff = event.loaded <= 0 ? 0 : (event.loaded - prevLoaded)
  228. if (isNaN(loadDiff) || !isFinite(loadDiff) || loadDiff < 0) return // just in case
  229. totLoaded += loadDiff
  230. prevLoaded = event.loaded
  231. }.bind(this)
  232. xhr[i].onload = function () {
  233. // the large file has been loaded entirely, start again
  234. tverb('dl stream finished '+i)
  235. try { xhr[i].abort() } catch (e) { } // reset the stream data to empty ram
  236. testStream(i, 0)
  237. }.bind(this)
  238. xhr[i].onerror = function () {
  239. // error
  240. tverb('dl stream failed '+i)
  241. if (settings.xhr_ignoreErrors === 0) failed=true //abort
  242. try { xhr[i].abort() } catch (e) { }
  243. delete (xhr[i])
  244. if (settings.xhr_ignoreErrors === 1) testStream(i, 0) //restart stream
  245. }.bind(this)
  246. // send xhr
  247. try { if (settings.xhr_dlUseBlob) xhr[i].responseType = 'blob'; else xhr[i].responseType = 'arraybuffer' } catch (e) { }
  248. 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
  249. xhr[i].send()
  250. }.bind(this), 1 + delay)
  251. }.bind(this)
  252. // open streams
  253. for (var i = 0; i < settings.xhr_dlMultistream; i++) {
  254. testStream(i, settings.xhr_multistreamDelay * i)
  255. }
  256. // every 200ms, update dlStatus
  257. interval = setInterval(function () {
  258. tverb('DL: '+dlStatus+(graceTimeDone?'':' (in grace time)'))
  259. var t = new Date().getTime() - startT
  260. if (graceTimeDone) dlProgress = (t + bonusT) / (settings.time_dl_max * 1000)
  261. if (t < 200) return
  262. if (!graceTimeDone){
  263. if (t > 1000 * settings.time_dlGraceTime){
  264. if (totLoaded > 0){ // if the connection is so slow that we didn't get a single chunk yet, do not reset
  265. startT = new Date().getTime()
  266. bonusT = 0
  267. totLoaded = 0.0
  268. }
  269. graceTimeDone = true;
  270. }
  271. }else{
  272. var speed = totLoaded / (t / 1000.0)
  273. if(settings.time_auto){
  274. //decide how much to shorten the test. Every 200ms, the test is shortened by the bonusT calculated here
  275. var bonus=6.4*speed/100000
  276. bonusT+=bonus>800?800:bonus
  277. }
  278. //update status
  279. dlStatus = ((speed * 8 * settings.overheadCompensationFactor)/(settings.useMebibits?1048576:1000000)).toFixed(2) // speed is multiplied by 8 to go from bytes to bits, overhead compensation is applied, then everything is divided by 1048576 or 1000000 to go to megabits/mebibits
  280. if ((((t+ bonusT) / 1000.0) > settings.time_dl_max) || failed) { // test is over, stop streams and timer
  281. if (failed || isNaN(dlStatus)) dlStatus = 'Fail'
  282. clearRequests()
  283. clearInterval(interval)
  284. dlProgress = 1
  285. tlog('dlTest: '+dlStatus+', took '+(new Date().getTime() - startT)+'ms')
  286. done()
  287. }
  288. }
  289. }.bind(this), 200)
  290. }
  291. // upload test, calls done function whent it's over
  292. var ulCalled = false // used to prevent multiple accidental calls to ulTest
  293. function ulTest (done) {
  294. tverb('ulTest')
  295. if (ulCalled) return; else ulCalled = true // ulTest already called?
  296. // garbage data for upload test
  297. var r = new ArrayBuffer(1048576)
  298. var maxInt=Math.pow(2,32)-1;
  299. try { r = new Uint32Array(r); for (var i = 0; i < r.length; i++)r[i] = Math.random()*maxInt } catch (e) { }
  300. var req = []
  301. var reqsmall = []
  302. for (var i = 0; i < settings.xhr_ul_blob_megabytes; i++) req.push(r)
  303. req = new Blob(req)
  304. r = new ArrayBuffer(262144)
  305. try { r = new Uint32Array(r); for (var i = 0; i < r.length; i++)r[i] = Math.random()*maxInt } catch (e) { }
  306. reqsmall.push(r)
  307. reqsmall = new Blob(reqsmall)
  308. var testFunction=function(){
  309. var totLoaded = 0.0, // total number of transmitted bytes
  310. startT = new Date().getTime(), // timestamp when test was started
  311. bonusT = 0, //how many milliseconds the test has been shortened by (higher on faster connections)
  312. graceTimeDone = false, //set to true after the grace time is past
  313. failed = false // set to true if a stream fails
  314. xhr = []
  315. // function to create an upload stream. streams are slightly delayed so that they will not end at the same time
  316. var testStream = function (i, delay) {
  317. setTimeout(function () {
  318. if (testStatus !== 3) return // delayed stream ended up starting after the end of the upload test
  319. tverb('ul test stream started '+i+' '+delay)
  320. var prevLoaded = 0 // number of bytes transmitted last time onprogress was called
  321. var x = new XMLHttpRequest()
  322. xhr[i] = x
  323. var ie11workaround
  324. if (settings.forceIE11Workaround) ie11workaround = true; else {
  325. try {
  326. xhr[i].upload.onprogress
  327. ie11workaround = false
  328. } catch (e) {
  329. ie11workaround = true
  330. }
  331. }
  332. if (ie11workaround) {
  333. // 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
  334. xhr[i].onload = function () {
  335. tverb('ul stream progress event (ie11wa)')
  336. totLoaded += reqsmall.size;
  337. testStream(i, 0)
  338. }
  339. xhr[i].onerror = function () {
  340. // error, abort
  341. tverb('ul stream failed (ie11wa)')
  342. if (settings.xhr_ignoreErrors === 0) failed = true //abort
  343. try { xhr[i].abort() } catch (e) { }
  344. delete (xhr[i])
  345. if (settings.xhr_ignoreErrors === 1) testStream(i,0); //restart stream
  346. }
  347. xhr[i].open('POST', settings.url_ul + url_sep(settings.url_ul) + 'r=' + Math.random(), true) // random string to prevent caching
  348. xhr[i].setRequestHeader('Content-Encoding', 'identity') // disable compression (some browsers may refuse it, but data is incompressible anyway)
  349. xhr[i].send(reqsmall)
  350. } else {
  351. // REGULAR version, no workaround
  352. xhr[i].upload.onprogress = function (event) {
  353. tverb('ul stream progress event '+i+' '+event.loaded)
  354. if (testStatus !== 3) { try { x.abort() } catch (e) { } } // just in case this XHR is still running after the upload test
  355. // progress event, add number of new loaded bytes to totLoaded
  356. var loadDiff = event.loaded <= 0 ? 0 : (event.loaded - prevLoaded)
  357. if (isNaN(loadDiff) || !isFinite(loadDiff) || loadDiff < 0) return // just in case
  358. totLoaded += loadDiff
  359. prevLoaded = event.loaded
  360. }.bind(this)
  361. xhr[i].upload.onload = function () {
  362. // this stream sent all the garbage data, start again
  363. tverb('ul stream finished '+i)
  364. testStream(i, 0)
  365. }.bind(this)
  366. xhr[i].upload.onerror = function () {
  367. tverb('ul stream failed '+i)
  368. if (settings.xhr_ignoreErrors === 0) failed=true //abort
  369. try { xhr[i].abort() } catch (e) { }
  370. delete (xhr[i])
  371. if (settings.xhr_ignoreErrors === 1) testStream(i, 0) //restart stream
  372. }.bind(this)
  373. // send xhr
  374. xhr[i].open('POST', settings.url_ul + url_sep(settings.url_ul) + 'r=' + Math.random(), true) // random string to prevent caching
  375. xhr[i].setRequestHeader('Content-Encoding', 'identity') // disable compression (some browsers may refuse it, but data is incompressible anyway)
  376. xhr[i].send(req)
  377. }
  378. }.bind(this), 1)
  379. }.bind(this)
  380. // open streams
  381. for (var i = 0; i < settings.xhr_ulMultistream; i++) {
  382. testStream(i, settings.xhr_multistreamDelay * i)
  383. }
  384. // every 200ms, update ulStatus
  385. interval = setInterval(function () {
  386. tverb('UL: '+ulStatus+(graceTimeDone?'':' (in grace time)'))
  387. var t = new Date().getTime() - startT
  388. if (graceTimeDone) ulProgress = (t + bonusT) / (settings.time_ul_max * 1000)
  389. if (t < 200) return
  390. if (!graceTimeDone){
  391. if (t > 1000 * settings.time_ulGraceTime){
  392. if (totLoaded > 0){ // if the connection is so slow that we didn't get a single chunk yet, do not reset
  393. startT = new Date().getTime()
  394. bonusT=0
  395. totLoaded = 0.0
  396. }
  397. graceTimeDone = true;
  398. }
  399. }else{
  400. var speed = totLoaded / (t / 1000.0)
  401. if(settings.time_auto){
  402. //decide how much to shorten the test. Every 200ms, the test is shortened by the bonusT calculated here
  403. var bonus=6.4*speed/100000
  404. bonusT+=bonus>800?800:bonus
  405. }
  406. //update status
  407. ulStatus = ((speed * 8 * settings.overheadCompensationFactor)/(settings.useMebibits?1048576:1000000)).toFixed(2) // speed is multiplied by 8 to go from bytes to bits, overhead compensation is applied, then everything is divided by 1048576 or 1000000 to go to megabits/mebibits
  408. if ((((t + bonusT) / 1000.0) > settings.time_ul_max) || failed) { // test is over, stop streams and timer
  409. if (failed || isNaN(ulStatus)) ulStatus = 'Fail'
  410. clearRequests()
  411. clearInterval(interval)
  412. ulProgress = 1
  413. tlog('ulTest: '+ulStatus+', took '+(new Date().getTime() - startT)+'ms')
  414. done()
  415. }
  416. }
  417. }.bind(this), 200)
  418. }.bind(this);
  419. if(settings.xhr_ul_sendPostRequestBeforeStartingTest){
  420. tverb('Sending POST request before performing upload test');
  421. xhr=[];
  422. xhr[0]=new XMLHttpRequest();
  423. xhr[0].onload=xhr[0].onerror=function(){
  424. tverb('POST request sent, starting upload test');
  425. testFunction();
  426. }.bind(this);
  427. xhr[0].open('POST',settings.url_ul);
  428. xhr[0].send();
  429. }else testFunction();
  430. }
  431. // ping+jitter test, function done is called when it's over
  432. var ptCalled = false // used to prevent multiple accidental calls to pingTest
  433. function pingTest (done) {
  434. tverb('pingTest')
  435. if (ptCalled) return; else ptCalled = true // pingTest already called?
  436. var startT=new Date().getTime(); //when the test was started
  437. var prevT = null // last time a pong was received
  438. var ping = 0.0 // current ping value
  439. var jitter = 0.0 // current jitter value
  440. var i = 0 // counter of pongs received
  441. var prevInstspd = 0 // last ping time, used for jitter calculation
  442. xhr = []
  443. // ping function
  444. var doPing = function () {
  445. tverb('ping')
  446. pingProgress = i / settings.count_ping
  447. prevT = new Date().getTime()
  448. xhr[0] = new XMLHttpRequest()
  449. xhr[0].onload = function () {
  450. // pong
  451. tverb('pong')
  452. if (i === 0) {
  453. prevT = new Date().getTime() // first pong
  454. } else {
  455. var instspd = new Date().getTime() - prevT
  456. if(settings.ping_allowPerformanceApi){
  457. try{
  458. //try to get accurate performance timing using performance api
  459. var p=performance.getEntries()
  460. p=p[p.length-1]
  461. var d = p.responseStart - p.requestStart //best precision: chromium-based
  462. if (d<=0) d=p.duration //edge: not so good precision because it also considers the overhead and there is no way to avoid it
  463. if (d>0&&d<instspd) instspd=d
  464. }catch(e){
  465. //if not possible, keep the estimate
  466. //firefox can't access performance api from worker: worst precision
  467. tverb('Performance API not supported, using estimate')
  468. }
  469. }
  470. var instjitter = Math.abs(instspd - prevInstspd)
  471. if (i === 1) ping = instspd; /* first ping, can't tell jitter yet*/ else {
  472. ping = instspd < ping ? instspd : ping * 0.8 + instspd * 0.2 // update ping, weighted average. if the instant ping is lower than the current average, it is set to that value instead of averaging
  473. if(i === 2) jitter=instjitter //discard the first jitter measurement because it might be much higher than it should be
  474. else
  475. jitter = instjitter > jitter ? (jitter * 0.3 + instjitter * 0.7) : (jitter * 0.8 + instjitter * 0.2) // update jitter, weighted average. spikes in ping values are given more weight.
  476. }
  477. prevInstspd = instspd
  478. }
  479. pingStatus = ping.toFixed(2)
  480. jitterStatus = jitter.toFixed(2)
  481. i++
  482. tverb('ping: '+pingStatus+' jitter: '+jitterStatus)
  483. if (i < settings.count_ping) doPing(); else { // more pings to do?
  484. pingProgress = 1
  485. tlog('ping: '+pingStatus+' jitter: '+jitterStatus+', took '+(new Date().getTime()-startT)+'ms')
  486. done()
  487. }
  488. }.bind(this)
  489. xhr[0].onerror = function () {
  490. // a ping failed, cancel test
  491. tverb('ping failed')
  492. if (settings.xhr_ignoreErrors === 0) { //abort
  493. pingStatus = 'Fail'
  494. jitterStatus = 'Fail'
  495. clearRequests()
  496. tlog('ping test failed, took '+(new Date().getTime()-startT)+'ms')
  497. pingProgress = 1
  498. done()
  499. }
  500. if (settings.xhr_ignoreErrors === 1) doPing() //retry ping
  501. if (settings.xhr_ignoreErrors === 2){ //ignore failed ping
  502. i++
  503. if (i < settings.count_ping) doPing(); else { // more pings to do?
  504. pingProgress = 1
  505. tlog('ping: '+pingStatus+' jitter: '+jitterStatus+', took '+(new Date().getTime()-startT)+'ms')
  506. done()
  507. }
  508. }
  509. }.bind(this)
  510. // send xhr
  511. xhr[0].open('GET', settings.url_ping + url_sep(settings.url_ping) + 'r=' + Math.random(), true) // random string to prevent caching
  512. xhr[0].send()
  513. }.bind(this)
  514. doPing() // start first ping
  515. }
  516. // telemetry
  517. function sendTelemetry(done){
  518. if (settings.telemetry_level < 1) return
  519. xhr = new XMLHttpRequest()
  520. xhr.onload = function () {
  521. try{
  522. var parts=xhr.responseText.split(' ')
  523. if(parts[0]=='id'){
  524. try{
  525. var id=Number(parts[1])
  526. if(!isNaN(id)) done(id); else done(-1);
  527. }catch(e){done(-1)}
  528. } else done(-1);
  529. }catch(e){
  530. done(-1)
  531. }
  532. }
  533. xhr.onerror = function () { console.log('TELEMETRY ERROR '+xhr.status); done(-1) }
  534. xhr.open('POST', settings.url_telemetry+url_sep(settings.url_telemetry)+"r="+Math.random(), true);
  535. var telemetryIspInfo={
  536. processedString: clientIp,
  537. rawIspInfo: (typeof ispInfo === "object")?ispInfo:""
  538. }
  539. try{
  540. var fd = new FormData()
  541. fd.append('ispinfo', JSON.stringify(telemetryIspInfo));
  542. fd.append('dl', dlStatus)
  543. fd.append('ul', ulStatus)
  544. fd.append('ping', pingStatus)
  545. fd.append('jitter', jitterStatus)
  546. fd.append('log', settings.telemetry_level>1?log:"")
  547. fd.append('extra', settings.telemetry_extra);
  548. xhr.send(fd)
  549. }catch(ex){
  550. var postData = 'extra='+encodeURIComponent(settings.telemetry_extra)+'&ispinfo='+encodeURIComponent(JSON.stringify(telemetryIspInfo))+'&dl='+encodeURIComponent(dlStatus)+'&ul='+encodeURIComponent(ulStatus)+'&ping='+encodeURIComponent(pingStatus)+'&jitter='+encodeURIComponent(jitterStatus)+'&log='+encodeURIComponent(settings.telemetry_level>1?log:'')
  551. xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
  552. xhr.send(postData)
  553. }
  554. }