speedtest_worker.js 24 KB

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