File size: 877 Bytes
6c30253
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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;
  }
}