speedtest_worker.js 24 KB

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