forked from peers/peerjs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathencodingQueue.ts
64 lines (47 loc) · 1.13 KB
/
encodingQueue.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import { EventEmitter } from "eventemitter3";
import logger from "./logger";
export class EncodingQueue extends EventEmitter {
readonly fileReader: FileReader = new FileReader();
private _queue: Blob[] = [];
private _processing: boolean = false;
constructor() {
super();
this.fileReader.onload = (evt) => {
this._processing = false;
if (evt.target) {
this.emit("done", evt.target.result as ArrayBuffer);
}
this.doNextTask();
};
this.fileReader.onerror = (evt) => {
logger.error(`EncodingQueue error:`, evt);
this._processing = false;
this.destroy();
this.emit("error", evt);
};
}
get queue(): Blob[] {
return this._queue;
}
get size(): number {
return this.queue.length;
}
get processing(): boolean {
return this._processing;
}
enque(blob: Blob): void {
this.queue.push(blob);
if (this.processing) return;
this.doNextTask();
}
destroy(): void {
this.fileReader.abort();
this._queue = [];
}
private doNextTask(): void {
if (this.size === 0) return;
if (this.processing) return;
this._processing = true;
this.fileReader.readAsArrayBuffer(this.queue.shift());
}
}