Repository navigation
Expand file tree
/
Copy pathcamera.dart
More file actions
791 lines (657 loc) · 27.4 KB
/
Copy pathcamera.dart
File metadata and controls
791 lines (657 loc) · 27.4 KB
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
// Copyright 2013 The Flutter Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:js_interop';
import 'dart:ui';
import 'dart:ui_web' as ui_web;
import 'package:camera_platform_interface/camera_platform_interface.dart';
import 'package:flutter/foundation.dart';
import 'package:web/web.dart' as web;
import 'package:web/web.dart';
import 'camera_service.dart';
import 'pkg_web_tweaks.dart';
import 'types/types.dart';
String _getViewType(int cameraId) => 'plugins.flutter.io/camera_$cameraId';
/// A camera initialized from the media devices in the current window.
/// See: https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices
///
/// The obtained camera stream is constrained by [options] and fetched
/// with [CameraService.getMediaStreamForOptions].
///
/// The camera stream is displayed in the [videoElement] wrapped in the
/// [divElement] to avoid overriding the custom styles applied to
/// the video element in [_applyDefaultVideoStyles].
/// See: https://github.com/flutter/flutter/issues/79519
///
/// The camera stream can be played/stopped by calling [play]/[stop],
/// may capture a picture by calling [takePicture] or capture a video
/// by calling [startVideoRecording], [pauseVideoRecording],
/// [resumeVideoRecording] or [stopVideoRecording].
///
/// The camera zoom may be adjusted with [setZoomLevel]. The provided
/// zoom level must be a value in the range of [getMinZoomLevel] to
/// [getMaxZoomLevel].
///
/// The [textureId] is used to register a camera view with the id
/// defined by [_getViewType].
class Camera {
/// Creates a new instance of [Camera]
/// with the given [textureId] and optional
/// [options] and [window].
Camera({
required this.textureId,
required CameraService cameraService,
this.options = const CameraOptions(),
({int? audioBitrate, int? videoBitrate})? recorderOptions,
}) : recorderOptions = recorderOptions ?? (audioBitrate: null, videoBitrate: null),
_cameraService = cameraService,
canUseOffscreenCanvas = cameraService.hasPropertyOffScreenCanvas(),
canUseMediaStreamTrackProcessor = cameraService.hasMediaStreamTrackProcessor();
/// The texture id used to register the camera view.
final int textureId;
/// The camera options used to initialize a camera, empty by default.
final CameraOptions options;
/// The options used to initialize a MediaRecorder.
final ({int? audioBitrate, int? videoBitrate}) recorderOptions;
/// The video element that displays the camera stream.
/// Initialized in [initialize].
late final web.HTMLVideoElement videoElement;
/// The wrapping element for the [videoElement] to avoid overriding
/// the custom styles applied in [_applyDefaultVideoStyles].
/// Initialized in [initialize].
late final web.HTMLDivElement divElement;
/// The camera stream displayed in the [videoElement].
/// Initialized in [initialize] and [play], reset in [stop].
web.MediaStream? stream;
/// The stream of the camera video tracks that have ended playing.
///
/// This occurs when there is no more camera stream data, e.g.
/// the user has stopped the stream by changing the camera device,
/// revoked the camera permissions or ejected the camera device.
///
/// MediaStreamTrack.onended:
/// https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamTrack/onended
Stream<web.MediaStreamTrack> get onEnded => onEndedController.stream;
/// The stream controller for the [onEnded] stream.
@visibleForTesting
final StreamController<web.MediaStreamTrack> onEndedController =
StreamController<web.MediaStreamTrack>.broadcast();
StreamSubscription<web.Event>? _onEndedSubscription;
/// The stream of the camera video recording errors.
///
/// This occurs when the video recording is not allowed or an unsupported
/// codec is used.
///
/// MediaRecorder.error:
/// https://developer.mozilla.org/en-US/docs/Web/API/MediaRecorder/error_event
Stream<web.ErrorEvent> get onVideoRecordingError => videoRecordingErrorController.stream;
/// The stream provider for [MediaRecorder] error events.
@visibleForTesting
EventStreamProvider<Event> mediaRecorderOnErrorProvider =
EventStreamProviders.errorMediaRecorderEvent;
/// The stream controller for the [onVideoRecordingError] stream.
@visibleForTesting
final StreamController<web.ErrorEvent> videoRecordingErrorController =
StreamController<web.ErrorEvent>.broadcast();
StreamSubscription<web.Event>? _onVideoRecordingErrorSubscription;
/// The camera flash mode.
@visibleForTesting
FlashMode? flashMode;
/// The camera service used to get the media stream for the camera.
final CameraService _cameraService;
/// The current browser window used to access media devices.
@visibleForTesting
web.Window window = web.window;
/// The recorder used to record a video from the camera.
@visibleForTesting
web.MediaRecorder? mediaRecorder;
/// Whether the video of the given type is supported.
@visibleForTesting
bool Function(String) isVideoTypeSupported = (String type) =>
web.MediaRecorder.isTypeSupported(type);
/// The list of consecutive video data files recorded with [mediaRecorder].
final List<web.Blob> _videoData = <web.Blob>[];
/// Completes when the video recording is stopped/finished.
Completer<XFile>? _videoAvailableCompleter;
/// A data listener fired when a new part of video data is available.
void Function(web.BlobEvent)? _videoDataAvailableListener;
/// A listener fired when a video recording is stopped.
void Function(web.Event)? _videoRecordingStoppedListener;
/// A builder to merge a list of blobs into a single blob.
@visibleForTesting
web.Blob Function(List<web.Blob> blobs, String type) blobBuilder =
(List<web.Blob> blobs, String type) => web.Blob(blobs.toJS, web.BlobPropertyBag(type: type));
/// The stream that emits a [VideoRecordedEvent] when a video recording is created.
Stream<VideoRecordedEvent> get onVideoRecordedEvent => videoRecorderController.stream;
/// The stream controller for the [onVideoRecordedEvent] stream.
@visibleForTesting
final StreamController<VideoRecordedEvent> videoRecorderController =
StreamController<VideoRecordedEvent>.broadcast();
/// Used to check if media stream track processor is supported.
@visibleForTesting
final bool canUseMediaStreamTrackProcessor;
/// Used to check if allowed to paint canvas off screen
@visibleForTesting
final bool canUseOffscreenCanvas;
/// The tolerance for the camera streaming frame time.
int get _frameTimeToleranceMs => 1000 / cameraStreamFPS ~/ 2;
/// Initializes the camera stream displayed in the [videoElement].
/// Registers the camera view with [textureId] under [_getViewType] type.
/// Emits the camera default video track on the [onEnded] stream when it ends.
Future<void> initialize() async {
stream = await _cameraService.getMediaStreamForOptions(options, cameraId: textureId);
videoElement = web.HTMLVideoElement();
divElement = web.HTMLDivElement()
..style.setProperty('object-fit', 'cover')
..style.setProperty('height', '100%')
..style.setProperty('width', '100%')
..append(videoElement);
ui_web.platformViewRegistry.registerViewFactory(_getViewType(textureId), (_) => divElement);
videoElement
..autoplay = false
..muted = true
..srcObject = stream
..setAttribute('playsinline', '');
_applyDefaultVideoStyles(videoElement);
final List<web.MediaStreamTrack> videoTracks = stream!.getVideoTracks().toDart;
if (videoTracks.isNotEmpty) {
final web.MediaStreamTrack defaultVideoTrack = videoTracks.first;
_onEndedSubscription = EventStreamProviders.endedEvent.forTarget(defaultVideoTrack).listen((
web.Event _,
) {
onEndedController.add(defaultVideoTrack);
});
}
}
/// Starts the camera stream.
///
/// Initializes the camera source if the camera was previously stopped.
Future<void> play() async {
if (videoElement.srcObject == null) {
stream = await _cameraService.getMediaStreamForOptions(options, cameraId: textureId);
videoElement.srcObject = stream;
}
await videoElement.play().toDart;
}
/// Pauses the camera stream on the current frame.
void pause() {
videoElement.pause();
}
/// Stops the camera stream and resets the camera source.
void stop() {
final List<web.MediaStreamTrack> videoTracks = stream!.getVideoTracks().toDart;
if (videoTracks.isNotEmpty) {
onEndedController.add(videoTracks.first);
}
final List<web.MediaStreamTrack>? tracks = stream?.getTracks().toDart;
if (tracks != null) {
for (final web.MediaStreamTrack track in tracks) {
track.stop();
}
}
videoElement.srcObject = null;
stream = null;
}
/// Captures a picture and returns the saved file in a JPEG format.
///
/// Enables the camera flash (torch mode) for a period of taking a picture
/// if the flash mode is either [FlashMode.auto] or [FlashMode.always].
Future<XFile> takePicture() async {
final bool shouldEnableTorchMode = flashMode == FlashMode.auto || flashMode == FlashMode.always;
if (shouldEnableTorchMode) {
_setTorchMode(enabled: true);
}
final int videoWidth = videoElement.videoWidth;
final int videoHeight = videoElement.videoHeight;
final canvas = web.HTMLCanvasElement()
..width = videoWidth
..height = videoHeight;
final isBackCamera = getLensDirection() == CameraLensDirection.back;
// Flip the picture horizontally if it is not taken from a back camera.
if (!isBackCamera) {
canvas.context2D
..translate(videoWidth, 0)
..scale(-1, 1);
}
canvas.context2D.drawImage(videoElement, 0, 0, videoWidth.toDouble(), videoHeight.toDouble());
final blobCompleter = Completer<web.Blob>();
canvas.toBlob(
(web.Blob blob) {
blobCompleter.complete(blob);
}.toJS,
'image/jpeg',
);
final web.Blob blob = await blobCompleter.future;
if (shouldEnableTorchMode) {
_setTorchMode(enabled: false);
}
return XFile(web.URL.createObjectURL(blob));
}
/// Returns a size of the camera video based on its first video track size.
///
/// Returns [Size.zero] if the camera is missing a video track or
/// the video track does not include the width or height setting.
Size getVideoSize() {
final List<web.MediaStreamTrack> videoTracks =
(videoElement.srcObject as web.MediaStream?)?.getVideoTracks().toDart ??
<web.MediaStreamTrack>[];
if (videoTracks.isEmpty) {
return Size.zero;
}
final web.MediaStreamTrack defaultVideoTrack = videoTracks.first;
final web.MediaTrackSettings defaultVideoTrackSettings = defaultVideoTrack.getSettings();
final int width = defaultVideoTrackSettings.width;
final int height = defaultVideoTrackSettings.height;
return Size(width.toDouble(), height.toDouble());
}
/// Sets the camera flash mode to [mode] by modifying the camera
/// torch mode constraint.
///
/// The torch mode is enabled for [FlashMode.torch] and
/// disabled for [FlashMode.off].
///
/// For [FlashMode.auto] and [FlashMode.always] the torch mode is enabled
/// only for a period of taking a picture in [takePicture].
///
/// Throws a [CameraWebException] if the torch mode is not supported
/// or the camera has not been initialized or started.
void setFlashMode(FlashMode mode) {
final web.MediaDevices mediaDevices = window.navigator.mediaDevices;
final web.MediaTrackSupportedConstraints supportedConstraints = mediaDevices
.getSupportedConstraints();
final bool torchModeSupported = supportedConstraints.torchNullable ?? false;
if (!torchModeSupported) {
throw CameraWebException(
textureId,
CameraErrorCode.torchModeNotSupported,
'The torch mode is not supported in the current browser.',
);
}
// Save the updated flash mode to be used later when taking a picture.
flashMode = mode;
// Enable the torch mode only if the flash mode is torch.
_setTorchMode(enabled: mode == FlashMode.torch);
}
/// Sets the camera torch mode constraint to [enabled].
///
/// Throws a [CameraWebException] if the torch mode is not supported
/// or the camera has not been initialized or started.
void _setTorchMode({required bool enabled}) {
final List<web.MediaStreamTrack> videoTracks =
stream?.getVideoTracks().toDart ?? <web.MediaStreamTrack>[];
if (videoTracks.isNotEmpty) {
final web.MediaStreamTrack defaultVideoTrack = videoTracks.first;
final bool canEnableTorchMode = defaultVideoTrack.getCapabilities().canEnableTorch;
if (canEnableTorchMode) {
defaultVideoTrack.applyWebTweakConstraints(
WebTweakMediaTrackConstraints(torch: enabled.toJS),
);
} else {
throw CameraWebException(
textureId,
CameraErrorCode.torchModeNotSupported,
'The torch mode is not supported by the current camera.',
);
}
} else {
throw CameraWebException(
textureId,
CameraErrorCode.notStarted,
'The camera has not been initialized or started.',
);
}
}
/// Returns the camera maximum zoom level.
///
/// Throws a [CameraWebException] if the zoom level is not supported
/// or the camera has not been initialized or started.
double getMaxZoomLevel() => _cameraService.getZoomLevelCapabilityForCamera(this).maximum;
/// Returns the camera minimum zoom level.
///
/// Throws a [CameraWebException] if the zoom level is not supported
/// or the camera has not been initialized or started.
double getMinZoomLevel() => _cameraService.getZoomLevelCapabilityForCamera(this).minimum;
/// Sets the camera zoom level to [zoom].
///
/// Throws a [CameraWebException] if the zoom level is invalid,
/// not supported or the camera has not been initialized or started.
void setZoomLevel(double zoom) {
final ZoomLevelCapability zoomLevelCapability = _cameraService.getZoomLevelCapabilityForCamera(
this,
);
if (zoom < zoomLevelCapability.minimum || zoom > zoomLevelCapability.maximum) {
throw CameraWebException(
textureId,
CameraErrorCode.zoomLevelInvalid,
'The provided zoom level must be in the range of ${zoomLevelCapability.minimum} to ${zoomLevelCapability.maximum}.',
);
}
zoomLevelCapability.videoTrack.applyWebTweakConstraints(
WebTweakMediaTrackConstraints(zoom: zoom.toJS),
);
}
/// Returns a lens direction of this camera.
///
/// Returns null if the camera is missing a video track or
/// the video track does not include the facing mode setting.
CameraLensDirection? getLensDirection() {
final List<web.MediaStreamTrack> videoTracks =
(videoElement.srcObject as web.MediaStream?)?.getVideoTracks().toDart ??
<web.MediaStreamTrack>[];
if (videoTracks.isEmpty) {
return null;
}
final web.MediaStreamTrack defaultVideoTrack = videoTracks.first;
final web.MediaTrackSettings defaultVideoTrackSettings = defaultVideoTrack.getSettings();
final String? facingMode = defaultVideoTrackSettings.facingModeNullable;
if (facingMode != null && facingMode.isNotEmpty) {
return _cameraService.mapFacingModeToLensDirection(facingMode);
} else {
return null;
}
}
/// Returns the registered view type of the camera.
String getViewType() => _getViewType(textureId);
/// Starts a new video recording using [web.MediaRecorder].
///
/// Throws a [CameraWebException] if the browser does not support any of the
/// available video mime types from [_videoMimeType].
Future<void> startVideoRecording() async {
final options = web.MediaRecorderOptions(mimeType: _videoMimeType);
if (recorderOptions.audioBitrate != null) {
options.audioBitsPerSecond = recorderOptions.audioBitrate!;
}
if (recorderOptions.videoBitrate != null) {
options.videoBitsPerSecond = recorderOptions.videoBitrate!;
}
mediaRecorder ??= web.MediaRecorder(videoElement.srcObject! as web.MediaStream, options);
_videoAvailableCompleter = Completer<XFile>();
_videoDataAvailableListener = (web.BlobEvent event) => _onVideoDataAvailable(event);
_videoRecordingStoppedListener = (web.Event event) => _onVideoRecordingStopped(event);
mediaRecorder!.addEventListener('dataavailable', _videoDataAvailableListener?.toJS);
mediaRecorder!.addEventListener('stop', _videoRecordingStoppedListener?.toJS);
_onVideoRecordingErrorSubscription = mediaRecorderOnErrorProvider
.forTarget(mediaRecorder)
.listen((web.Event event) {
final error = event as web.ErrorEvent;
videoRecordingErrorController.add(error);
});
mediaRecorder!.start();
}
void _onVideoDataAvailable(web.BlobEvent event) {
// Append the recorded part of the video to the list of all video data files.
_videoData.add(event.data);
}
Future<void> _onVideoRecordingStopped(web.Event event) async {
if (_videoData.isNotEmpty) {
// Concatenate all video data files into a single blob.
final String videoType = _videoData.first.type;
final web.Blob videoBlob = blobBuilder(_videoData, videoType);
// Create a file containing the video blob.
final file = XFile(
web.URL.createObjectURL(videoBlob),
mimeType: _videoMimeType,
name: videoBlob.hashCode.toString(),
);
// Emit an event containing the recorded video file.
videoRecorderController.add(VideoRecordedEvent(textureId, file, null));
_videoAvailableCompleter?.complete(file);
}
// Clean up the media recorder with its event listeners and video data.
mediaRecorder!.removeEventListener('dataavailable', _videoDataAvailableListener?.toJS);
mediaRecorder!.removeEventListener('stop', _videoDataAvailableListener?.toJS);
await _onVideoRecordingErrorSubscription?.cancel();
mediaRecorder = null;
_videoDataAvailableListener = null;
_videoRecordingStoppedListener = null;
_videoData.clear();
}
/// Pauses the current video recording.
///
/// Throws a [CameraWebException] if the video recorder is uninitialized.
Future<void> pauseVideoRecording() async {
if (mediaRecorder == null) {
throw _videoRecordingNotStartedException;
}
mediaRecorder!.pause();
}
/// Resumes the current video recording.
///
/// Throws a [CameraWebException] if the video recorder is uninitialized.
Future<void> resumeVideoRecording() async {
if (mediaRecorder == null) {
throw _videoRecordingNotStartedException;
}
mediaRecorder!.resume();
}
/// Stops the video recording and returns the captured video file.
///
/// Throws a [CameraWebException] if the video recorder is uninitialized.
Future<XFile> stopVideoRecording() async {
if (mediaRecorder == null || _videoAvailableCompleter == null) {
throw _videoRecordingNotStartedException;
}
mediaRecorder!.stop();
return _videoAvailableCompleter!.future;
}
/// Disposes the camera by stopping the camera stream,
/// the video recording and reloading the camera source.
Future<void> dispose() async {
// Stop the camera stream.
stop();
await videoRecorderController.close();
mediaRecorder = null;
_videoDataAvailableListener = null;
// Reset the [videoElement] to its initial state.
videoElement
..srcObject = null
..load();
await _onEndedSubscription?.cancel();
_onEndedSubscription = null;
await onEndedController.close();
await _onVideoRecordingErrorSubscription?.cancel();
_onVideoRecordingErrorSubscription = null;
await videoRecordingErrorController.close();
await _cameraFrameStreamController?.close();
}
/// Returns the first supported video mime type (amongst mp4 and webm)
/// to use when recording a video.
///
/// Throws a [CameraWebException] if the browser does not support
/// any of the available video mime types.
String get _videoMimeType {
const types = <String>['video/webm;codecs="vp9,opus"', 'video/mp4', 'video/webm'];
return types.firstWhere(
(String type) => isVideoTypeSupported(type),
orElse: () => throw CameraWebException(
textureId,
CameraErrorCode.notSupported,
'The browser does not support any of the following video types: ${types.join(',')}.',
),
);
}
CameraWebException get _videoRecordingNotStartedException => CameraWebException(
textureId,
CameraErrorCode.videoRecordingNotStarted,
'The video recorder is uninitialized. The recording might not have been started. Make sure to call `startVideoRecording` first.',
);
/// Applies default styles to the video [element].
void _applyDefaultVideoStyles(web.HTMLVideoElement element) {
final isBackCamera = getLensDirection() == CameraLensDirection.back;
// Flip the video horizontally if it is not taken from a back camera.
if (!isBackCamera) {
element.style.transform = 'scaleX(-1)';
}
element.style
..transformOrigin = 'center'
..pointerEvents = 'none'
..width = '100%'
..height = '100%'
..objectFit = 'cover';
}
StreamController<CameraImageData>? _cameraFrameStreamController;
/// Whether the camera frame stream is initialized.
bool _isCameraFrameStreamInitialized() =>
_cameraFrameStreamController != null && !_cameraFrameStreamController!.isClosed;
/// Whether the camera is currently streaming frames.
bool _isCameraFrameStreaming() =>
_isCameraFrameStreamInitialized() && _cameraFrameStreamController!.hasListener;
/// Used for safely emitting camera frame stream event
void _safelyEmitCameraFrameStreamEvent(CameraImageData data) {
if (_isCameraFrameStreamInitialized()) {
_cameraFrameStreamController!.add(data);
}
}
/// Used for safely closing camera frame stream event
void _safelyCloseCameraFrameStream() {
if (_isCameraFrameStreamInitialized()) {
_cameraFrameStreamController!.close();
}
}
/// Used for safely emitting camera frame stream error
void _safelyEmitCameraFrameStreamError(Object error) {
if (_isCameraFrameStreamInitialized()) {
_cameraFrameStreamController!.addError(error);
}
}
// TODO(TecHaxter): Introduce FPS in CameraImageStreamOptions of
// package:camera_platform_interface.
// https://github.com/flutter/flutter/issues/176148
/// The target FPS for the camera frame stream.
///
/// Frames are emitted within a tolerance window, so actual delivery may
/// slightly exceed or fall below this target depending on browser timing.
@visibleForTesting
final int cameraStreamFPS = 60;
/// Returns a stream of camera frames.
///
/// To stop listening to new animation frames close all listening streams.
Stream<CameraImageData> cameraFrameStream({CameraImageStreamOptions? options}) {
if (_isCameraFrameStreamInitialized()) {
return _cameraFrameStreamController!.stream;
}
_cameraFrameStreamController = StreamController<CameraImageData>.broadcast(
onListen: () {
if (canUseMediaStreamTrackProcessor && stream != null) {
_triggerVideoStreamTrackProcessorLoop(
stream!,
onImageAvailable: _safelyEmitCameraFrameStreamEvent,
shouldContinue: _isCameraFrameStreaming,
onClose: _safelyCloseCameraFrameStream,
onError: _safelyEmitCameraFrameStreamError,
);
} else {
_triggerAnimationFramesLoop(_getAndEmitFrameFromVideoElement, fps: cameraStreamFPS);
}
},
);
return _cameraFrameStreamController!.stream;
}
/// Triggers animation frames in a loop at a specified FPS
/// as long as [animationFrameId] is not cancelled
void _triggerAnimationFramesLoop(VoidCallback action, {required int fps}) {
int? animationFrameId;
final num fpsInterval = 1000 / fps;
num lastFrameTimestamp = 0;
late JSExportedDartFunction jsAnimate;
int? animate(num timestamp) {
// Schedule the next frame
animationFrameId = window.requestAnimationFrame(jsAnimate);
// Calculate the elapsed time since the last frame
final num elapsed = timestamp - lastFrameTimestamp;
// If we're close to the next frame (~`_frameTimeToleranceMs`), do it.
if (fpsInterval - elapsed <= _frameTimeToleranceMs) {
// Get ready for next frame
lastFrameTimestamp = timestamp;
// Perform the action task
action();
}
return animationFrameId;
}
jsAnimate = animate.toJS;
// Initialize the animation loop
animationFrameId = animate(window.performance.now());
// Listen for the stream controller cancellation to stop the animation
_cameraFrameStreamController?.onCancel = () {
if (animationFrameId != null) {
window.cancelAnimationFrame(animationFrameId!);
animationFrameId = null;
}
};
}
/// Used to capture [videoElement] and and handle camera frame stream accordingly
void _getAndEmitFrameFromVideoElement() {
try {
final CameraImageData image = _cameraService.takeFrame(videoElement, cameraId: textureId);
_safelyEmitCameraFrameStreamEvent(image);
} catch (e) {
_safelyEmitCameraFrameStreamError(e);
_safelyCloseCameraFrameStream();
}
}
/// Uses [MediaStreamTrackProcessor] to read [web.VideoFrame] from the given
/// [stream] and convert them to [CameraImageData]. The converted
/// [CameraImageData] is emitted to the [_cameraFrameStreamController].
Future<void> _triggerVideoStreamTrackProcessorLoop(
web.MediaStream stream, {
required bool Function() shouldContinue,
required void Function(CameraImageData) onImageAvailable,
required void Function() onClose,
required void Function(Object) onError,
}) async {
web.ReadableStreamDefaultReader? reader;
final copyOptions = web.VideoFrameCopyToOptions(format: 'RGBA');
bool isNonFatal(Object e) =>
e is CameraWebException &&
[
CameraErrorCode.videoTrackReaderClosed,
CameraErrorCode.missingPlaneLayout,
CameraErrorCode.unableToCloneFrame,
].contains(e.code);
try {
reader = _cameraService.getMediaStreamTrackReader(
_cameraService.getMediaStreamVideoTrack(stream, cameraId: textureId),
);
while (shouldContinue()) {
final web.VideoFrame videoFrame = await _cameraService.readVideoTrack(
reader,
cameraId: textureId,
);
try {
final destination = JSUint8Array.withLength(videoFrame.allocationSize(copyOptions));
final int stride = await _cameraService.copyVideoFrameToBufferAndGetStride(
videoFrame,
destination: destination,
copyOptions: copyOptions,
cameraId: textureId,
);
if (!shouldContinue()) {
break;
}
final CameraImageData imageData = _cameraService.getCameraImageData(
width: videoFrame.visibleRect!.width.toInt(),
height: videoFrame.visibleRect!.height.toInt(),
bytesPerRow: stride,
bytes: destination.toDart,
);
onImageAvailable(imageData);
} catch (e) {
if (isNonFatal(e)) {
continue;
}
rethrow;
} finally {
videoFrame.close();
}
}
} catch (e) {
if (!isNonFatal(e)) {
onError(e);
}
} finally {
onClose();
reader?.releaseLock();
}
}
}