Spaces:
Running
Running
| function stopStream(stream) { | |
| stream?.getTracks?.().forEach(track => track.stop()); | |
| } | |
| export class WebcamSession { | |
| constructor(acquire) { | |
| this.acquire = acquire; | |
| this.stream = null; | |
| this.pending = null; | |
| this.version = 0; | |
| } | |
| async open(constraints) { | |
| if (this.stream) return this.stream; | |
| if (this.pending) return this.pending; | |
| const version = this.version; | |
| const pending = Promise.resolve(this.acquire(constraints)).then(stream => { | |
| if (version !== this.version) { | |
| stopStream(stream); | |
| return null; | |
| } | |
| this.stream = stream; | |
| return stream; | |
| }).finally(() => { | |
| if (this.pending === pending) this.pending = null; | |
| }); | |
| this.pending = pending; | |
| return pending; | |
| } | |
| close() { | |
| this.version += 1; | |
| this.pending = null; | |
| stopStream(this.stream); | |
| this.stream = null; | |
| } | |
| } | |