-
Notifications
You must be signed in to change notification settings - Fork 286
/
Copy pathreact-webcam.tsx
427 lines (351 loc) · 11.3 KB
/
react-webcam.tsx
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
import * as React from "react";
// polyfill based on https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia
(function polyfillGetUserMedia() {
if (typeof window === 'undefined') {
return;
}
// Older browsers might not implement mediaDevices at all, so we set an empty object first
if (navigator.mediaDevices === undefined) {
(navigator as any).mediaDevices = {};
}
// Some browsers partially implement mediaDevices. We can't just assign an object
// with getUserMedia as it would overwrite existing properties.
// Here, we will just add the getUserMedia property if it's missing.
if (navigator.mediaDevices.getUserMedia === undefined) {
navigator.mediaDevices.getUserMedia = function(constraints) {
// First get ahold of the legacy getUserMedia, if present
const getUserMedia =
navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia;
// Some browsers just don't implement it - return a rejected promise with an error
// to keep a consistent interface
if (!getUserMedia) {
return Promise.reject(
new Error("getUserMedia is not implemented in this browser")
);
}
// Otherwise, wrap the call to the old navigator.getUserMedia with a Promise
return new Promise(function(resolve, reject) {
getUserMedia.call(navigator, constraints, resolve, reject);
});
};
}
})();
function hasGetUserMedia() {
return !!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia);
}
interface ScreenshotDimensions {
width: number;
height: number;
}
interface ChildrenProps {
getScreenshot: (screenshotDimensions?: ScreenshotDimensions) => string | null;
}
export type WebcamProps = Omit<React.HTMLProps<HTMLVideoElement>, "ref"> & {
audio: boolean;
audioConstraints?: MediaStreamConstraints["audio"];
disablePictureInPicture: boolean;
forceScreenshotSourceSize: boolean;
imageSmoothing: boolean;
mirrored: boolean;
minScreenshotHeight?: number;
minScreenshotWidth?: number;
onUserMedia: (stream: MediaStream) => void;
onUserMediaError: (error: string | DOMException) => void;
screenshotFormat: "image/webp" | "image/png" | "image/jpeg";
screenshotQuality: number;
videoConstraints?: MediaStreamConstraints["video"];
children?: (childrenProps: ChildrenProps) => JSX.Element;
}
interface WebcamState {
hasUserMedia: boolean;
src?: string;
}
export default class Webcam extends React.Component<WebcamProps, WebcamState> {
static defaultProps = {
audio: false,
disablePictureInPicture: false,
forceScreenshotSourceSize: false,
imageSmoothing: true,
mirrored: false,
onUserMedia: () => undefined,
onUserMediaError: () => undefined,
screenshotFormat: "image/webp",
screenshotQuality: 0.92,
};
private canvas: HTMLCanvasElement | null = null;
private ctx: CanvasRenderingContext2D | null = null;
private requestUserMediaId = 0;
private unmounted = false;
stream: MediaStream | null;
video: HTMLVideoElement | null;
constructor(props: WebcamProps) {
super(props);
this.state = {
hasUserMedia: false
};
}
componentDidMount() {
const { state, props } = this;
this.unmounted = false;
if (!hasGetUserMedia()) {
props.onUserMediaError("getUserMedia not supported");
return;
}
if (!state.hasUserMedia) {
this.requestUserMedia();
}
if (props.children && typeof props.children != 'function') {
console.warn("children must be a function");
}
}
componentDidUpdate(nextProps: WebcamProps) {
const { props } = this;
if (!hasGetUserMedia()) {
props.onUserMediaError("getUserMedia not supported");
return;
}
const audioConstraintsChanged =
JSON.stringify(nextProps.audioConstraints) !==
JSON.stringify(props.audioConstraints);
const videoConstraintsChanged =
JSON.stringify(nextProps.videoConstraints) !==
JSON.stringify(props.videoConstraints);
const minScreenshotWidthChanged =
nextProps.minScreenshotWidth !== props.minScreenshotWidth;
const minScreenshotHeightChanged =
nextProps.minScreenshotHeight !== props.minScreenshotHeight;
if (
videoConstraintsChanged ||
minScreenshotWidthChanged ||
minScreenshotHeightChanged
) {
this.canvas = null;
this.ctx = null;
}
if (audioConstraintsChanged || videoConstraintsChanged) {
this.stopAndCleanup();
this.requestUserMedia();
}
}
componentWillUnmount() {
this.unmounted = true;
this.stopAndCleanup();
}
private static stopMediaStream(stream: MediaStream | null) {
if (stream) {
if (stream.getVideoTracks && stream.getAudioTracks) {
stream.getVideoTracks().map(track => {
stream.removeTrack(track);
track.stop();
});
stream.getAudioTracks().map(track => {
stream.removeTrack(track);
track.stop()
});
} else {
((stream as unknown) as MediaStreamTrack).stop();
}
}
}
private stopAndCleanup() {
const { state } = this;
if (state.hasUserMedia) {
Webcam.stopMediaStream(this.stream);
if (state.src) {
window.URL.revokeObjectURL(state.src);
}
}
}
getScreenshot(screenshotDimensions?: ScreenshotDimensions) {
const { state, props } = this;
if (!state.hasUserMedia) return null;
const canvas = this.getCanvas(screenshotDimensions);
return (
canvas &&
canvas.toDataURL(props.screenshotFormat, props.screenshotQuality)
);
}
getCanvas(screenshotDimensions?: ScreenshotDimensions) {
const { state, props } = this;
if (!this.video) {
return null;
}
if (!state.hasUserMedia || !this.video.videoHeight) return null;
if (!this.ctx) {
let canvasWidth = this.video.videoWidth;
let canvasHeight = this.video.videoHeight;
if (!this.props.forceScreenshotSourceSize) {
const aspectRatio = canvasWidth / canvasHeight;
canvasWidth = props.minScreenshotWidth || this.video.clientWidth;
canvasHeight = canvasWidth / aspectRatio;
if (
props.minScreenshotHeight &&
canvasHeight < props.minScreenshotHeight
) {
canvasHeight = props.minScreenshotHeight;
canvasWidth = canvasHeight * aspectRatio;
}
}
this.canvas = document.createElement("canvas");
this.canvas.width = screenshotDimensions?.width || canvasWidth;
this.canvas.height = screenshotDimensions?.height || canvasHeight;
this.ctx = this.canvas.getContext("2d");
}
const { ctx, canvas } = this;
if (ctx && canvas) {
// adjust the height and width of the canvas to the given dimensions
canvas.width = screenshotDimensions?.width || canvas.width;
canvas.height = screenshotDimensions?.height || canvas.height;
// mirror the screenshot
if (props.mirrored) {
ctx.translate(canvas.width, 0);
ctx.scale(-1, 1);
}
ctx.imageSmoothingEnabled = props.imageSmoothing;
ctx.drawImage(this.video, 0, 0, screenshotDimensions?.width || canvas.width, screenshotDimensions?.height || canvas.height);
// invert mirroring
if (props.mirrored) {
ctx.scale(-1, 1);
ctx.translate(-canvas.width, 0);
}
}
return canvas;
}
private requestUserMedia() {
const { props } = this;
const sourceSelected = (
audioConstraints: boolean | MediaTrackConstraints | undefined,
videoConstraints: boolean | MediaTrackConstraints | undefined,
) => {
const constraints: MediaStreamConstraints = {
video: typeof videoConstraints !== "undefined" ? videoConstraints : true
};
if (props.audio) {
constraints.audio =
typeof audioConstraints !== "undefined" ? audioConstraints : true;
}
this.requestUserMediaId++
const myRequestUserMediaId = this.requestUserMediaId
navigator.mediaDevices
.getUserMedia(constraints)
.then(stream => {
if (this.unmounted || myRequestUserMediaId !== this.requestUserMediaId) {
Webcam.stopMediaStream(stream);
} else {
this.handleUserMedia(null, stream);
}
})
.catch(e => {
this.handleUserMedia(e);
});
};
if ("mediaDevices" in navigator) {
sourceSelected(props.audioConstraints, props.videoConstraints);
} else {
const optionalSource = (id: string | null) => ({ optional: [{ sourceId: id }] }) as MediaTrackConstraints;
const constraintToSourceId = (constraint) => {
const { deviceId } = constraint;
if (typeof deviceId === "string") {
return deviceId;
}
if (Array.isArray(deviceId) && deviceId.length > 0) {
return deviceId[0];
}
if (typeof deviceId === "object" && deviceId.ideal) {
return deviceId.ideal;
}
return null;
};
// @ts-ignore: deprecated api
MediaStreamTrack.getSources(sources => {
let audioSource: string | null = null;
let videoSource: string | null = null;
sources.forEach((source: MediaStreamTrack) => {
if (source.kind === "audio") {
audioSource = source.id;
} else if (source.kind === "video") {
videoSource = source.id;
}
});
const audioSourceId = constraintToSourceId(props.audioConstraints);
if (audioSourceId) {
audioSource = audioSourceId;
}
const videoSourceId = constraintToSourceId(props.videoConstraints);
if (videoSourceId) {
videoSource = videoSourceId;
}
sourceSelected(
optionalSource(audioSource),
optionalSource(videoSource)
);
});
}
}
private handleUserMedia(err, stream?: MediaStream) {
const { props } = this;
if (err || !stream) {
this.setState({ hasUserMedia: false });
props.onUserMediaError(err);
return;
}
this.stream = stream;
try {
if (this.video) {
this.video.srcObject = stream;
}
this.setState({ hasUserMedia: true });
} catch (error) {
this.setState({
hasUserMedia: true,
src: window.URL.createObjectURL(stream)
});
}
props.onUserMedia(stream);
}
render() {
const { state, props } = this;
const {
audio,
forceScreenshotSourceSize,
disablePictureInPicture,
onUserMedia,
onUserMediaError,
screenshotFormat,
screenshotQuality,
minScreenshotWidth,
minScreenshotHeight,
audioConstraints,
videoConstraints,
imageSmoothing,
mirrored,
style = {},
children,
...rest
} = props;
const videoStyle = mirrored ? { ...style, transform: `${style.transform || ""} scaleX(-1)` } : style;
const childrenProps: ChildrenProps = {
getScreenshot: this.getScreenshot.bind(this),
};
return (
<>
<video
autoPlay
disablePictureInPicture={disablePictureInPicture}
src={state.src}
muted={!audio}
playsInline
ref={ref => {
this.video = ref;
}}
style={videoStyle}
{...rest}
/>
{children && children(childrenProps)}
</>
);
}
}