swfupload.speed.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. /*
  2. Speed Plug-in
  3. Features:
  4. *Adds several properties to the 'file' object indicated upload speed, time left, upload time, etc.
  5. - currentSpeed -- String indicating the upload speed, bytes per second
  6. - averageSpeed -- Overall average upload speed, bytes per second
  7. - movingAverageSpeed -- Speed over averaged over the last several measurements, bytes per second
  8. - timeRemaining -- Estimated remaining upload time in seconds
  9. - timeElapsed -- Number of seconds passed for this upload
  10. - percentUploaded -- Percentage of the file uploaded (0 to 100)
  11. - sizeUploaded -- Formatted size uploaded so far, bytes
  12. *Adds setting 'moving_average_history_size' for defining the window size used to calculate the moving average speed.
  13. *Adds several Formatting functions for formatting that values provided on the file object.
  14. - SWFUpload.speed.formatBPS(bps) -- outputs string formatted in the best units (Gbps, Mbps, Kbps, bps)
  15. - SWFUpload.speed.formatTime(seconds) -- outputs string formatted in the best units (x Hr y M z S)
  16. - SWFUpload.speed.formatSize(bytes) -- outputs string formatted in the best units (w GB x MB y KB z B )
  17. - SWFUpload.speed.formatPercent(percent) -- outputs string formatted with a percent sign (x.xx %)
  18. - SWFUpload.speed.formatUnits(baseNumber, divisionArray, unitLabelArray, fractionalBoolean)
  19. - Formats a number using the division array to determine how to apply the labels in the Label Array
  20. - factionalBoolean indicates whether the number should be returned as a single fractional number with a unit (speed)
  21. or as several numbers labeled with units (time)
  22. */
  23. var SWFUpload;
  24. if (typeof(SWFUpload) === "function") {
  25. SWFUpload.speed = {};
  26. SWFUpload.prototype.initSettings = (function (oldInitSettings) {
  27. return function () {
  28. if (typeof(oldInitSettings) === "function") {
  29. oldInitSettings.call(this);
  30. }
  31. this.ensureDefault = function (settingName, defaultValue) {
  32. this.settings[settingName] = (this.settings[settingName] == undefined) ? defaultValue : this.settings[settingName];
  33. };
  34. // List used to keep the speed stats for the files we are tracking
  35. this.fileSpeedStats = {};
  36. this.speedSettings = {};
  37. this.ensureDefault("moving_average_history_size", "10");
  38. this.speedSettings.user_file_queued_handler = this.settings.file_queued_handler;
  39. this.speedSettings.user_file_queue_error_handler = this.settings.file_queue_error_handler;
  40. this.speedSettings.user_upload_start_handler = this.settings.upload_start_handler;
  41. this.speedSettings.user_upload_error_handler = this.settings.upload_error_handler;
  42. this.speedSettings.user_upload_progress_handler = this.settings.upload_progress_handler;
  43. this.speedSettings.user_upload_success_handler = this.settings.upload_success_handler;
  44. this.speedSettings.user_upload_complete_handler = this.settings.upload_complete_handler;
  45. this.settings.file_queued_handler = SWFUpload.speed.fileQueuedHandler;
  46. this.settings.file_queue_error_handler = SWFUpload.speed.fileQueueErrorHandler;
  47. this.settings.upload_start_handler = SWFUpload.speed.uploadStartHandler;
  48. this.settings.upload_error_handler = SWFUpload.speed.uploadErrorHandler;
  49. this.settings.upload_progress_handler = SWFUpload.speed.uploadProgressHandler;
  50. this.settings.upload_success_handler = SWFUpload.speed.uploadSuccessHandler;
  51. this.settings.upload_complete_handler = SWFUpload.speed.uploadCompleteHandler;
  52. delete this.ensureDefault;
  53. };
  54. })(SWFUpload.prototype.initSettings);
  55. SWFUpload.speed.fileQueuedHandler = function (file) {
  56. if (typeof this.speedSettings.user_file_queued_handler === "function") {
  57. file = SWFUpload.speed.extendFile(file);
  58. return this.speedSettings.user_file_queued_handler.call(this, file);
  59. }
  60. };
  61. SWFUpload.speed.fileQueueErrorHandler = function (file, errorCode, message) {
  62. if (typeof this.speedSettings.user_file_queue_error_handler === "function") {
  63. file = SWFUpload.speed.extendFile(file);
  64. return this.speedSettings.user_file_queue_error_handler.call(this, file, errorCode, message);
  65. }
  66. };
  67. SWFUpload.speed.uploadStartHandler = function (file) {
  68. if (typeof this.speedSettings.user_upload_start_handler === "function") {
  69. file = SWFUpload.speed.extendFile(file, this.fileSpeedStats);
  70. return this.speedSettings.user_upload_start_handler.call(this, file);
  71. }
  72. };
  73. SWFUpload.speed.uploadErrorHandler = function (file, errorCode, message) {
  74. file = SWFUpload.speed.extendFile(file, this.fileSpeedStats);
  75. SWFUpload.speed.removeTracking(file, this.fileSpeedStats);
  76. if (typeof this.speedSettings.user_upload_error_handler === "function") {
  77. return this.speedSettings.user_upload_error_handler.call(this, file, errorCode, message);
  78. }
  79. };
  80. SWFUpload.speed.uploadProgressHandler = function (file, bytesComplete, bytesTotal) {
  81. this.updateTracking(file, bytesComplete);
  82. file = SWFUpload.speed.extendFile(file, this.fileSpeedStats);
  83. if (typeof this.speedSettings.user_upload_progress_handler === "function") {
  84. return this.speedSettings.user_upload_progress_handler.call(this, file, bytesComplete, bytesTotal);
  85. }
  86. };
  87. SWFUpload.speed.uploadSuccessHandler = function (file, serverData) {
  88. if (typeof this.speedSettings.user_upload_success_handler === "function") {
  89. file = SWFUpload.speed.extendFile(file, this.fileSpeedStats);
  90. return this.speedSettings.user_upload_success_handler.call(this, file, serverData);
  91. }
  92. };
  93. SWFUpload.speed.uploadCompleteHandler = function (file) {
  94. file = SWFUpload.speed.extendFile(file, this.fileSpeedStats);
  95. SWFUpload.speed.removeTracking(file, this.fileSpeedStats);
  96. if (typeof this.speedSettings.user_upload_complete_handler === "function") {
  97. return this.speedSettings.user_upload_complete_handler.call(this, file);
  98. }
  99. };
  100. // Private: extends the file object with the speed plugin values
  101. SWFUpload.speed.extendFile = function (file, trackingList) {
  102. var tracking;
  103. if (trackingList) {
  104. tracking = trackingList[file.id];
  105. }
  106. if (tracking) {
  107. file.currentSpeed = tracking.currentSpeed;
  108. file.averageSpeed = tracking.averageSpeed;
  109. file.movingAverageSpeed = tracking.movingAverageSpeed;
  110. file.timeRemaining = tracking.timeRemaining;
  111. file.timeElapsed = tracking.timeElapsed;
  112. file.percentUploaded = tracking.percentUploaded;
  113. file.sizeUploaded = tracking.bytesUploaded;
  114. } else {
  115. file.currentSpeed = 0;
  116. file.averageSpeed = 0;
  117. file.movingAverageSpeed = 0;
  118. file.timeRemaining = 0;
  119. file.timeElapsed = 0;
  120. file.percentUploaded = 0;
  121. file.sizeUploaded = 0;
  122. }
  123. return file;
  124. };
  125. // Private: Updates the speed tracking object, or creates it if necessary
  126. SWFUpload.prototype.updateTracking = function (file, bytesUploaded) {
  127. var tracking = this.fileSpeedStats[file.id];
  128. if (!tracking) {
  129. this.fileSpeedStats[file.id] = tracking = {};
  130. }
  131. // Sanity check inputs
  132. bytesUploaded = bytesUploaded || tracking.bytesUploaded || 0;
  133. if (bytesUploaded < 0) {
  134. bytesUploaded = 0;
  135. }
  136. if (bytesUploaded > file.size) {
  137. bytesUploaded = file.size;
  138. }
  139. var tickTime = (new Date()).getTime();
  140. if (!tracking.startTime) {
  141. tracking.startTime = (new Date()).getTime();
  142. tracking.lastTime = tracking.startTime;
  143. tracking.currentSpeed = 0;
  144. tracking.averageSpeed = 0;
  145. tracking.movingAverageSpeed = 0;
  146. tracking.movingAverageHistory = [];
  147. tracking.timeRemaining = 0;
  148. tracking.timeElapsed = 0;
  149. tracking.percentUploaded = bytesUploaded / file.size;
  150. tracking.bytesUploaded = bytesUploaded;
  151. } else if (tracking.startTime > tickTime) {
  152. this.debug("When backwards in time");
  153. } else {
  154. // Get time and deltas
  155. var now = (new Date()).getTime();
  156. var lastTime = tracking.lastTime;
  157. var deltaTime = now - lastTime;
  158. var deltaBytes = bytesUploaded - tracking.bytesUploaded;
  159. if (deltaBytes === 0 || deltaTime === 0) {
  160. return tracking;
  161. }
  162. // Update tracking object
  163. tracking.lastTime = now;
  164. tracking.bytesUploaded = bytesUploaded;
  165. // Calculate speeds
  166. tracking.currentSpeed = (deltaBytes * 8 ) / (deltaTime / 1000);
  167. tracking.averageSpeed = (tracking.bytesUploaded * 8) / ((now - tracking.startTime) / 1000);
  168. // Calculate moving average
  169. tracking.movingAverageHistory.push(tracking.currentSpeed);
  170. if (tracking.movingAverageHistory.length > this.settings.moving_average_history_size) {
  171. tracking.movingAverageHistory.shift();
  172. }
  173. tracking.movingAverageSpeed = SWFUpload.speed.calculateMovingAverage(tracking.movingAverageHistory);
  174. // Update times
  175. tracking.timeRemaining = (file.size - tracking.bytesUploaded) * 8 / tracking.movingAverageSpeed;
  176. tracking.timeElapsed = (now - tracking.startTime) / 1000;
  177. // Update percent
  178. tracking.percentUploaded = (tracking.bytesUploaded / file.size * 100);
  179. }
  180. return tracking;
  181. };
  182. SWFUpload.speed.removeTracking = function (file, trackingList) {
  183. try {
  184. trackingList[file.id] = null;
  185. delete trackingList[file.id];
  186. } catch (ex) {
  187. }
  188. };
  189. SWFUpload.speed.formatUnits = function (baseNumber, unitDivisors, unitLabels, singleFractional) {
  190. var i, unit, unitDivisor, unitLabel;
  191. if (baseNumber === 0) {
  192. return "0 " + unitLabels[unitLabels.length - 1];
  193. }
  194. if (singleFractional) {
  195. unit = baseNumber;
  196. unitLabel = unitLabels.length >= unitDivisors.length ? unitLabels[unitDivisors.length - 1] : "";
  197. for (i = 0; i < unitDivisors.length; i++) {
  198. if (baseNumber >= unitDivisors[i]) {
  199. unit = (baseNumber / unitDivisors[i]).toFixed(2);
  200. unitLabel = unitLabels.length >= i ? " " + unitLabels[i] : "";
  201. break;
  202. }
  203. }
  204. return unit + unitLabel;
  205. } else {
  206. var formattedStrings = [];
  207. var remainder = baseNumber;
  208. for (i = 0; i < unitDivisors.length; i++) {
  209. unitDivisor = unitDivisors[i];
  210. unitLabel = unitLabels.length > i ? " " + unitLabels[i] : "";
  211. unit = remainder / unitDivisor;
  212. if (i < unitDivisors.length -1) {
  213. unit = Math.floor(unit);
  214. } else {
  215. unit = unit.toFixed(2);
  216. }
  217. if (unit > 0) {
  218. remainder = remainder % unitDivisor;
  219. formattedStrings.push(unit + unitLabel);
  220. }
  221. }
  222. return formattedStrings.join(" ");
  223. }
  224. };
  225. SWFUpload.speed.formatBPS = function (baseNumber) {
  226. var bpsUnits = [1073741824, 1048576, 1024, 1], bpsUnitLabels = ["Gbps", "Mbps", "Kbps", "bps"];
  227. return SWFUpload.speed.formatUnits(baseNumber, bpsUnits, bpsUnitLabels, true);
  228. };
  229. SWFUpload.speed.formatTime = function (baseNumber) {
  230. var timeUnits = [86400, 3600, 60, 1], timeUnitLabels = ["d", "h", "m", "s"];
  231. return SWFUpload.speed.formatUnits(baseNumber, timeUnits, timeUnitLabels, false);
  232. };
  233. SWFUpload.speed.formatBytes = function (baseNumber) {
  234. var sizeUnits = [1073741824, 1048576, 1024, 1], sizeUnitLabels = ["GB", "MB", "KB", "bytes"];
  235. return SWFUpload.speed.formatUnits(baseNumber, sizeUnits, sizeUnitLabels, true);
  236. };
  237. SWFUpload.speed.formatPercent = function (baseNumber) {
  238. return baseNumber.toFixed(2) + " %";
  239. };
  240. SWFUpload.speed.calculateMovingAverage = function (history) {
  241. var vals = [], size, sum = 0.0, mean = 0.0, varianceTemp = 0.0, variance = 0.0, standardDev = 0.0;
  242. var i;
  243. var mSum = 0, mCount = 0;
  244. size = history.length;
  245. // Check for sufficient data
  246. if (size >= 8) {
  247. // Clone the array and Calculate sum of the values
  248. for (i = 0; i < size; i++) {
  249. vals[i] = history[i];
  250. sum += vals[i];
  251. }
  252. mean = sum / size;
  253. // Calculate variance for the set
  254. for (i = 0; i < size; i++) {
  255. varianceTemp += Math.pow((vals[i] - mean), 2);
  256. }
  257. variance = varianceTemp / size;
  258. standardDev = Math.sqrt(variance);
  259. //Standardize the Data
  260. for (i = 0; i < size; i++) {
  261. vals[i] = (vals[i] - mean) / standardDev;
  262. }
  263. // Calculate the average excluding outliers
  264. var deviationRange = 2.0;
  265. for (i = 0; i < size; i++) {
  266. if (vals[i] <= deviationRange && vals[i] >= -deviationRange) {
  267. mCount++;
  268. mSum += history[i];
  269. }
  270. }
  271. } else {
  272. // Calculate the average (not enough data points to remove outliers)
  273. mCount = size;
  274. for (i = 0; i < size; i++) {
  275. mSum += history[i];
  276. }
  277. }
  278. return mSum / mCount;
  279. };
  280. }