speedtest_worker.js 27 KB

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