mozmorris / react-webcam

Webcam component
https://codepen.io/mozmorris/pen/JLZdoP
MIT License
1.65k stars 281 forks source link

Creating multiple <Webcam /> instances at the same time can fail. #231

Open acorn1010 opened 4 years ago

acorn1010 commented 4 years ago

Please follow the general troubleshooting steps first:

Bug reports:

Example to reproduce the failure (in TypeScript). I encountered this on Firefox Browser Developer 80.0b1 (64-bit).

export function Example() {
  const [cams, setCams] = useState<JSX.Element[]>([]);

  function handleAddCam() {
    const newCams: JSX.Element[] = [];
    for (let i = 0; i < 20; ++i) {
      // Create some new cams. Width / height is just so that they're a manageable size.
      newCams.push(<Webcam audio={false} width={128} height={128}/>);
    }
    setCams(prev => [...prev, ...newCams]);
  }

  return <>
      <button type='button' onClick={handleAddCam}>Add Cams</button>
      {cams}
    </>;
}

This fails because the navigator.mediaDevices#mediaDevices method can throw a 'NotReadableError' if the device is busy being accessed by another <Webcam /> instance. A few attempts with a randomized exponential backoff in #requestUserMedia should fix this. Using a singleton factory for synchronously calling navigator.mediaDevices#getUserMedia would result in less failed attempts, but would also take longer to code.

agaertner commented 2 years ago

I think we have a similar issue in that our component isn't disposed or somehow keeps the device binding alive. On ubuntu this causes our webcam to not reappear after the view with the initial webcam component has been closed.