speedtest_worker.js 25 KB

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