video-optimizer-bot / src /upload /throttle.js
Hugging Face Deployer
Deploy bot to Hugging Face Spaces
03b405b
Raw History Blame Contribute Delete
1.34 kB
const { Transform } = require('stream');
/**
* Throttle stream to a specific bytes-per-second limit
*/
class ThrottleStream extends Transform {
/**
* @param {number} bytesPerSecond Limit rate
*/
constructor(bytesPerSecond) {
super();
this.bytesPerSecond = bytesPerSecond;
this.startTime = Date.now();
this.bytesWritten = 0;
}
_transform(chunk, encoding, callback) {
this.bytesWritten += chunk.length;
this.push(chunk);
if (!this.bytesPerSecond || this.bytesPerSecond <= 0) {
return callback();
}
const elapsedMs = Date.now() - this.startTime;
const expectedMs = (this.bytesWritten / this.bytesPerSecond) * 1000;
const sleepMs = expectedMs - elapsedMs;
if (sleepMs > 0) {
setTimeout(callback, sleepMs);
} else {
callback();
}
}
}
/**
* Helper to wrap any standard readable stream in a dynamic speed throttle
* @param {import('fs').ReadStream} readStream
* @param {number} speedMbps Throttle target in Megabits per second (e.g. 2 Mbps)
* @returns {Transform} Throttled stream
*/
function throttleStream(readStream, speedMbps) {
const bytesPerSecond = (speedMbps * 1000000) / 8;
const throttle = new ThrottleStream(bytesPerSecond);
return readStream.pipe(throttle);
}
module.exports = { ThrottleStream, throttleStream };