speedtest_worker.js 26 KB

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