speedtest_worker.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  1. /*
  2. HTML5 Speedtest v4.7.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 = null; //test ID (sent back by telemetry if used, null 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 (/PlayStation 4.(\d+\.\d+)/i.test(ua)) {
  145. //PS4 browser has the same bug as IE11/Edge
  146. settings.forceIE11Workaround = true;
  147. }
  148. if (/Chrome.(\d+)/i.test(ua) && /Android|iPhone|iPad|iPod|Windows Phone/i.test(ua)) {
  149. //cheap af
  150. //Chrome mobile introduced a limitation somewhere around version 65, we have to limit XHR upload size to 4 megabytes
  151. settings.xhr_ul_blob_megabytes = 4;
  152. }
  153. //telemetry_level has to be parsed and not just copied
  154. 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
  155. //transform test_order to uppercase, just in case
  156. settings.test_order = settings.test_order.toUpperCase();
  157. } catch (e) {
  158. twarn("Possible error in custom test settings. Some settings may not be applied. Exception: " + e);
  159. }
  160. // run the tests
  161. tverb(JSON.stringify(settings));
  162. test_pointer = 0;
  163. var iRun = false,
  164. dRun = false,
  165. uRun = false,
  166. pRun = false;
  167. var runNextTest = function() {
  168. if (testStatus == 5) return;
  169. if (test_pointer >= settings.test_order.length) {
  170. //test is finished
  171. if (settings.telemetry_level > 0)
  172. sendTelemetry(function(id) {
  173. testStatus = 4;
  174. if (id != null) testId = id;
  175. });
  176. else testStatus = 4;
  177. return;
  178. }
  179. switch (settings.test_order.charAt(test_pointer)) {
  180. case "I":
  181. {
  182. test_pointer++;
  183. if (iRun) {
  184. runNextTest();
  185. return;
  186. } else iRun = true;
  187. getIp(runNextTest);
  188. }
  189. break;
  190. case "D":
  191. {
  192. test_pointer++;
  193. if (dRun) {
  194. runNextTest();
  195. return;
  196. } else dRun = true;
  197. testStatus = 1;
  198. dlTest(runNextTest);
  199. }
  200. break;
  201. case "U":
  202. {
  203. test_pointer++;
  204. if (uRun) {
  205. runNextTest();
  206. return;
  207. } else uRun = true;
  208. testStatus = 3;
  209. ulTest(runNextTest);
  210. }
  211. break;
  212. case "P":
  213. {
  214. test_pointer++;
  215. if (pRun) {
  216. runNextTest();
  217. return;
  218. } else pRun = true;
  219. testStatus = 2;
  220. pingTest(runNextTest);
  221. }
  222. break;
  223. case "_":
  224. {
  225. test_pointer++;
  226. setTimeout(runNextTest, 1000);
  227. }
  228. break;
  229. default:
  230. test_pointer++;
  231. }
  232. };
  233. runNextTest();
  234. }
  235. if (params[0] === "abort") {
  236. // abort command
  237. tlog("manually aborted");
  238. clearRequests(); // stop all xhr activity
  239. runNextTest = null;
  240. if (interval) clearInterval(interval); // clear timer if present
  241. if (settings.telemetry_level > 1) sendTelemetry(function() {});
  242. testStatus = 5;
  243. dlStatus = "";
  244. ulStatus = "";
  245. pingStatus = "";
  246. jitterStatus = ""; // set test as aborted
  247. }
  248. });
  249. // stops all XHR activity, aggressively
  250. function clearRequests() {
  251. tverb("stopping pending XHRs");
  252. if (xhr) {
  253. for (var i = 0; i < xhr.length; i++) {
  254. try {
  255. xhr[i].onprogress = null;
  256. xhr[i].onload = null;
  257. xhr[i].onerror = null;
  258. } catch (e) {}
  259. try {
  260. xhr[i].upload.onprogress = null;
  261. xhr[i].upload.onload = null;
  262. xhr[i].upload.onerror = null;
  263. } catch (e) {}
  264. try {
  265. xhr[i].abort();
  266. } catch (e) {}
  267. try {
  268. delete xhr[i];
  269. } catch (e) {}
  270. }
  271. xhr = null;
  272. }
  273. }
  274. // gets client's IP using url_getIp, then calls the done function
  275. var ipCalled = false; // used to prevent multiple accidental calls to getIp
  276. var ispInfo = ""; //used for telemetry
  277. function getIp(done) {
  278. tverb("getIp");
  279. if (ipCalled) return;
  280. else ipCalled = true; // getIp already called?
  281. var startT = new Date().getTime();
  282. xhr = new XMLHttpRequest();
  283. xhr.onload = function() {
  284. tlog("IP: " + xhr.responseText + ", took " + (new Date().getTime() - startT) + "ms");
  285. try {
  286. var data = JSON.parse(xhr.responseText);
  287. clientIp = data.processedString;
  288. ispInfo = data.rawIspInfo;
  289. } catch (e) {
  290. clientIp = xhr.responseText;
  291. ispInfo = "";
  292. }
  293. done();
  294. };
  295. xhr.onerror = function() {
  296. tlog("getIp failed, took " + (new Date().getTime() - startT) + "ms");
  297. done();
  298. };
  299. 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);
  300. xhr.send();
  301. }
  302. // download test, calls done function when it's over
  303. var dlCalled = false; // used to prevent multiple accidental calls to dlTest
  304. function dlTest(done) {
  305. tverb("dlTest");
  306. if (dlCalled) return;
  307. else dlCalled = true; // dlTest already called?
  308. var totLoaded = 0.0, // total number of loaded bytes
  309. startT = new Date().getTime(), // timestamp when test was started
  310. bonusT = 0, //how many milliseconds the test has been shortened by (higher on faster connections)
  311. graceTimeDone = false, //set to true after the grace time is past
  312. failed = false; // set to true if a stream fails
  313. xhr = [];
  314. // function to create a download stream. streams are slightly delayed so that they will not end at the same time
  315. var testStream = function(i, delay) {
  316. setTimeout(
  317. function() {
  318. if (testStatus !== 1) return; // delayed stream ended up starting after the end of the download test
  319. tverb("dl test stream started " + i + " " + delay);
  320. var prevLoaded = 0; // number of bytes loaded last time onprogress was called
  321. var x = new XMLHttpRequest();
  322. xhr[i] = x;
  323. xhr[i].onprogress = function(event) {
  324. tverb("dl stream progress event " + i + " " + event.loaded);
  325. if (testStatus !== 1) {
  326. try {
  327. x.abort();
  328. } catch (e) {}
  329. } // just in case this XHR is still running after the download test
  330. // progress event, add number of new loaded bytes to totLoaded
  331. var loadDiff = event.loaded <= 0 ? 0 : event.loaded - prevLoaded;
  332. if (isNaN(loadDiff) || !isFinite(loadDiff) || loadDiff < 0) return; // just in case
  333. totLoaded += loadDiff;
  334. prevLoaded = event.loaded;
  335. }.bind(this);
  336. xhr[i].onload = function() {
  337. // the large file has been loaded entirely, start again
  338. tverb("dl stream finished " + i);
  339. try {
  340. xhr[i].abort();
  341. } catch (e) {} // reset the stream data to empty ram
  342. testStream(i, 0);
  343. }.bind(this);
  344. xhr[i].onerror = function() {
  345. // error
  346. tverb("dl stream failed " + i);
  347. if (settings.xhr_ignoreErrors === 0) failed = true; //abort
  348. try {
  349. xhr[i].abort();
  350. } catch (e) {}
  351. delete xhr[i];
  352. if (settings.xhr_ignoreErrors === 1) testStream(i, 0); //restart stream
  353. }.bind(this);
  354. // send xhr
  355. try {
  356. if (settings.xhr_dlUseBlob) xhr[i].responseType = "blob";
  357. else xhr[i].responseType = "arraybuffer";
  358. } catch (e) {}
  359. 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
  360. xhr[i].send();
  361. }.bind(this),
  362. 1 + delay
  363. );
  364. }.bind(this);
  365. // open streams
  366. for (var i = 0; i < settings.xhr_dlMultistream; i++) {
  367. testStream(i, settings.xhr_multistreamDelay * i);
  368. }
  369. // every 200ms, update dlStatus
  370. interval = setInterval(
  371. function() {
  372. tverb("DL: " + dlStatus + (graceTimeDone ? "" : " (in grace time)"));
  373. var t = new Date().getTime() - startT;
  374. if (graceTimeDone) dlProgress = (t + bonusT) / (settings.time_dl_max * 1000);
  375. if (t < 200) return;
  376. if (!graceTimeDone) {
  377. if (t > 1000 * settings.time_dlGraceTime) {
  378. if (totLoaded > 0) {
  379. // if the connection is so slow that we didn't get a single chunk yet, do not reset
  380. startT = new Date().getTime();
  381. bonusT = 0;
  382. totLoaded = 0.0;
  383. }
  384. graceTimeDone = true;
  385. }
  386. } else {
  387. var speed = totLoaded / (t / 1000.0);
  388. if (settings.time_auto) {
  389. //decide how much to shorten the test. Every 200ms, the test is shortened by the bonusT calculated here
  390. var bonus = (6.4 * speed) / 100000;
  391. bonusT += bonus > 800 ? 800 : bonus;
  392. }
  393. //update status
  394. 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
  395. if ((t + bonusT) / 1000.0 > settings.time_dl_max || failed) {
  396. // test is over, stop streams and timer
  397. if (failed || isNaN(dlStatus)) dlStatus = "Fail";
  398. clearRequests();
  399. clearInterval(interval);
  400. dlProgress = 1;
  401. tlog("dlTest: " + dlStatus + ", took " + (new Date().getTime() - startT) + "ms");
  402. done();
  403. }
  404. }
  405. }.bind(this),
  406. 200
  407. );
  408. }
  409. // upload test, calls done function whent it's over
  410. var ulCalled = false; // used to prevent multiple accidental calls to ulTest
  411. function ulTest(done) {
  412. tverb("ulTest");
  413. if (ulCalled) return;
  414. else ulCalled = true; // ulTest already called?
  415. // garbage data for upload test
  416. var r = new ArrayBuffer(1048576);
  417. var maxInt = Math.pow(2, 32) - 1;
  418. try {
  419. r = new Uint32Array(r);
  420. for (var i = 0; i < r.length; i++) r[i] = Math.random() * maxInt;
  421. } catch (e) {}
  422. var req = [];
  423. var reqsmall = [];
  424. for (var i = 0; i < settings.xhr_ul_blob_megabytes; i++) req.push(r);
  425. req = new Blob(req);
  426. r = new ArrayBuffer(262144);
  427. try {
  428. r = new Uint32Array(r);
  429. for (var i = 0; i < r.length; i++) r[i] = Math.random() * maxInt;
  430. } catch (e) {}
  431. reqsmall.push(r);
  432. reqsmall = new Blob(reqsmall);
  433. var totLoaded = 0.0, // total number of transmitted bytes
  434. startT = new Date().getTime(), // timestamp when test was started
  435. bonusT = 0, //how many milliseconds the test has been shortened by (higher on faster connections)
  436. graceTimeDone = false, //set to true after the grace time is past
  437. failed = false; // set to true if a stream fails
  438. xhr = [];
  439. // function to create an upload stream. streams are slightly delayed so that they will not end at the same time
  440. var testStream = function(i, delay) {
  441. setTimeout(
  442. function() {
  443. if (testStatus !== 3) return; // delayed stream ended up starting after the end of the upload test
  444. tverb("ul test stream started " + i + " " + delay);
  445. var prevLoaded = 0; // number of bytes transmitted last time onprogress was called
  446. var x = new XMLHttpRequest();
  447. xhr[i] = x;
  448. var ie11workaround;
  449. if (settings.forceIE11Workaround) ie11workaround = true;
  450. else {
  451. try {
  452. xhr[i].upload.onprogress;
  453. ie11workaround = false;
  454. } catch (e) {
  455. ie11workaround = true;
  456. }
  457. }
  458. if (ie11workaround) {
  459. // 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
  460. xhr[i].onload = xhr[i].onerror = function() {
  461. tverb("ul stream progress event (ie11wa)");
  462. totLoaded += reqsmall.size;
  463. testStream(i, 0);
  464. };
  465. xhr[i].open("POST", settings.url_ul + url_sep(settings.url_ul) + "r=" + Math.random(), true); // random string to prevent caching
  466. try{
  467. xhr[i].setRequestHeader("Content-Encoding", "identity"); // disable compression (some browsers may refuse it, but data is incompressible anyway)
  468. }catch(e){}
  469. try{
  470. xhr[i].setRequestHeader("Content-Type", "application/octet-stream"); //force content-type to application/octet-stream in case the server misinterprets it
  471. }catch(e){}
  472. xhr[i].send(reqsmall);
  473. } else {
  474. // REGULAR version, no workaround
  475. xhr[i].upload.onprogress = function(event) {
  476. tverb("ul stream progress event " + i + " " + event.loaded);
  477. if (testStatus !== 3) {
  478. try {
  479. x.abort();
  480. } catch (e) {}
  481. } // just in case this XHR is still running after the upload test
  482. // progress event, add number of new loaded bytes to totLoaded
  483. var loadDiff = event.loaded <= 0 ? 0 : event.loaded - prevLoaded;
  484. if (isNaN(loadDiff) || !isFinite(loadDiff) || loadDiff < 0) return; // just in case
  485. totLoaded += loadDiff;
  486. prevLoaded = event.loaded;
  487. }.bind(this);
  488. xhr[i].upload.onload = function() {
  489. // this stream sent all the garbage data, start again
  490. tverb("ul stream finished " + i);
  491. testStream(i, 0);
  492. }.bind(this);
  493. xhr[i].upload.onerror = function() {
  494. tverb("ul stream failed " + i);
  495. if (settings.xhr_ignoreErrors === 0) failed = true; //abort
  496. try {
  497. xhr[i].abort();
  498. } catch (e) {}
  499. delete xhr[i];
  500. if (settings.xhr_ignoreErrors === 1) testStream(i, 0); //restart stream
  501. }.bind(this);
  502. // send xhr
  503. xhr[i].open("POST", settings.url_ul + url_sep(settings.url_ul) + "r=" + Math.random(), true); // random string to prevent caching
  504. try{
  505. xhr[i].setRequestHeader("Content-Encoding", "identity"); // disable compression (some browsers may refuse it, but data is incompressible anyway)
  506. }catch(e){}
  507. try{
  508. xhr[i].setRequestHeader("Content-Type", "application/octet-stream"); //force content-type to application/octet-stream in case the server misinterprets it
  509. }catch(e){}
  510. xhr[i].send(req);
  511. }
  512. }.bind(this),
  513. 1
  514. );
  515. }.bind(this);
  516. // open streams
  517. for (var i = 0; i < settings.xhr_ulMultistream; i++) {
  518. testStream(i, settings.xhr_multistreamDelay * i);
  519. }
  520. // every 200ms, update ulStatus
  521. interval = setInterval(
  522. function() {
  523. tverb("UL: " + ulStatus + (graceTimeDone ? "" : " (in grace time)"));
  524. var t = new Date().getTime() - startT;
  525. if (graceTimeDone) ulProgress = (t + bonusT) / (settings.time_ul_max * 1000);
  526. if (t < 200) return;
  527. if (!graceTimeDone) {
  528. if (t > 1000 * settings.time_ulGraceTime) {
  529. if (totLoaded > 0) {
  530. // if the connection is so slow that we didn't get a single chunk yet, do not reset
  531. startT = new Date().getTime();
  532. bonusT = 0;
  533. totLoaded = 0.0;
  534. }
  535. graceTimeDone = true;
  536. }
  537. } else {
  538. var speed = totLoaded / (t / 1000.0);
  539. if (settings.time_auto) {
  540. //decide how much to shorten the test. Every 200ms, the test is shortened by the bonusT calculated here
  541. var bonus = (6.4 * speed) / 100000;
  542. bonusT += bonus > 800 ? 800 : bonus;
  543. }
  544. //update status
  545. 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
  546. if ((t + bonusT) / 1000.0 > settings.time_ul_max || failed) {
  547. // test is over, stop streams and timer
  548. if (failed || isNaN(ulStatus)) ulStatus = "Fail";
  549. clearRequests();
  550. clearInterval(interval);
  551. ulProgress = 1;
  552. tlog("ulTest: " + ulStatus + ", took " + (new Date().getTime() - startT) + "ms");
  553. done();
  554. }
  555. }
  556. }.bind(this),
  557. 200
  558. );
  559. }
  560. // ping+jitter test, function done is called when it's over
  561. var ptCalled = false; // used to prevent multiple accidental calls to pingTest
  562. function pingTest(done) {
  563. tverb("pingTest");
  564. if (ptCalled) return;
  565. else ptCalled = true; // pingTest already called?
  566. var startT = new Date().getTime(); //when the test was started
  567. var prevT = null; // last time a pong was received
  568. var ping = 0.0; // current ping value
  569. var jitter = 0.0; // current jitter value
  570. var i = 0; // counter of pongs received
  571. var prevInstspd = 0; // last ping time, used for jitter calculation
  572. xhr = [];
  573. // ping function
  574. var doPing = function() {
  575. tverb("ping");
  576. pingProgress = i / settings.count_ping;
  577. prevT = new Date().getTime();
  578. xhr[0] = new XMLHttpRequest();
  579. xhr[0].onload = function() {
  580. // pong
  581. tverb("pong");
  582. if (i === 0) {
  583. prevT = new Date().getTime(); // first pong
  584. } else {
  585. var instspd = new Date().getTime() - prevT;
  586. if (settings.ping_allowPerformanceApi) {
  587. try {
  588. //try to get accurate performance timing using performance api
  589. var p = performance.getEntries();
  590. p = p[p.length - 1];
  591. var d = p.responseStart - p.requestStart; //best precision: chromium-based
  592. 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
  593. if (d > 0 && d < instspd) instspd = d;
  594. } catch (e) {
  595. //if not possible, keep the estimate
  596. //firefox can't access performance api from worker: worst precision
  597. tverb("Performance API not supported, using estimate");
  598. }
  599. }
  600. var instjitter = Math.abs(instspd - prevInstspd);
  601. if (i === 1) ping = instspd;
  602. /* first ping, can't tell jitter yet*/ else {
  603. 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
  604. if (i === 2) jitter = instjitter;
  605. //discard the first jitter measurement because it might be much higher than it should be
  606. 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.
  607. }
  608. prevInstspd = instspd;
  609. }
  610. pingStatus = ping.toFixed(2);
  611. jitterStatus = jitter.toFixed(2);
  612. i++;
  613. tverb("ping: " + pingStatus + " jitter: " + jitterStatus);
  614. if (i < settings.count_ping) doPing();
  615. else {
  616. // more pings to do?
  617. pingProgress = 1;
  618. tlog("ping: " + pingStatus + " jitter: " + jitterStatus + ", took " + (new Date().getTime() - startT) + "ms");
  619. done();
  620. }
  621. }.bind(this);
  622. xhr[0].onerror = function() {
  623. // a ping failed, cancel test
  624. tverb("ping failed");
  625. if (settings.xhr_ignoreErrors === 0) {
  626. //abort
  627. pingStatus = "Fail";
  628. jitterStatus = "Fail";
  629. clearRequests();
  630. tlog("ping test failed, took " + (new Date().getTime() - startT) + "ms");
  631. pingProgress = 1;
  632. done();
  633. }
  634. if (settings.xhr_ignoreErrors === 1) doPing(); //retry ping
  635. if (settings.xhr_ignoreErrors === 2) {
  636. //ignore failed ping
  637. i++;
  638. if (i < settings.count_ping) doPing();
  639. else {
  640. // more pings to do?
  641. pingProgress = 1;
  642. tlog("ping: " + pingStatus + " jitter: " + jitterStatus + ", took " + (new Date().getTime() - startT) + "ms");
  643. done();
  644. }
  645. }
  646. }.bind(this);
  647. // send xhr
  648. xhr[0].open("GET", settings.url_ping + url_sep(settings.url_ping) + "r=" + Math.random(), true); // random string to prevent caching
  649. xhr[0].send();
  650. }.bind(this);
  651. doPing(); // start first ping
  652. }
  653. // telemetry
  654. function sendTelemetry(done) {
  655. if (settings.telemetry_level < 1) return;
  656. xhr = new XMLHttpRequest();
  657. xhr.onload = function() {
  658. try {
  659. var parts = xhr.responseText.split(" ");
  660. if (parts[0] == "id") {
  661. try {
  662. var id = parts[1];
  663. done(id);
  664. } catch (e) {
  665. done(null);
  666. }
  667. } else done(null);
  668. } catch (e) {
  669. done(null);
  670. }
  671. };
  672. xhr.onerror = function() {
  673. console.log("TELEMETRY ERROR " + xhr.status);
  674. done(null);
  675. };
  676. xhr.open("POST", settings.url_telemetry + url_sep(settings.url_telemetry) + "r=" + Math.random(), true);
  677. var telemetryIspInfo = {
  678. processedString: clientIp,
  679. rawIspInfo: typeof ispInfo === "object" ? ispInfo : ""
  680. };
  681. try {
  682. var fd = new FormData();
  683. fd.append("ispinfo", JSON.stringify(telemetryIspInfo));
  684. fd.append("dl", dlStatus);
  685. fd.append("ul", ulStatus);
  686. fd.append("ping", pingStatus);
  687. fd.append("jitter", jitterStatus);
  688. fd.append("log", settings.telemetry_level > 1 ? log : "");
  689. fd.append("extra", settings.telemetry_extra);
  690. xhr.send(fd);
  691. } catch (ex) {
  692. 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 : "");
  693. xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  694. xhr.send(postData);
  695. }
  696. }