This repository has been archived by the owner on Dec 5, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
camera.dart
680 lines (603 loc) · 21.1 KB
/
camera.dart
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
// Copyright 2018 The Chromium Authors. All rights reserved.
// 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:typed_data';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
part 'camera_image.dart';
final MethodChannel _channel = const MethodChannel('plugins.flutter.io/camera');
enum CameraLensDirection { front, back, external }
/// Affect the quality of video recording and image capture:
///
/// If a preset is not available on the camera being used a preset of lower quality will be selected automatically.
enum ResolutionPreset {
/// 352x288 on iOS, 240p (320x240) on Android
low,
/// 480p (640x480 on iOS, 720x480 on Android)
medium,
/// 720p (1280x720)
high,
/// 1080p (1920x1080)
veryHigh,
/// 2160p (3840x2160)
ultraHigh,
/// The highest resolution available.
max,
}
/// Affect the white balance of video recording and image capture:
enum WhiteBalancePreset {
/// The camera device's auto-white balance routine is disabled.
off,
/// The camera device's auto-white balance routine is active.
auto,
/// The camera device's auto-white balance routine is disabled; the camera device uses incandescent light as the assumed scene illumination for white balance.
incandescent,
/// The camera device's auto-white balance routine is disabled; the camera device uses fluorescent light as the assumed scene illumination for white balance.
fluorescent,
/// The camera device's auto-white balance routine is disabled; the camera device uses warm fluorescent light as the assumed scene illumination for white balance.
warmFluorescent,
/// The camera device's auto-white balance routine is disabled; the camera device uses daylight light as the assumed scene illumination for white balance.
daylight,
/// The camera device's auto-white balance routine is disabled; the camera device uses cloudy daylight light as the assumed scene illumination for white balance.
cloudy,
/// The camera device's auto-white balance routine is disabled; the camera device uses twilight light as the assumed scene illumination for white balance.
twilight,
/// The camera device's auto-white balance routine is disabled; the camera device uses shade light as the assumed scene illumination for white balance.
shade,
}
// ignore: inference_failure_on_function_return_type
typedef onLatestImageAvailable = Function(CameraImage image);
/// Returns the resolution preset as a String.
String serializeResolutionPreset(ResolutionPreset resolutionPreset) {
switch (resolutionPreset) {
case ResolutionPreset.max:
return 'max';
case ResolutionPreset.ultraHigh:
return 'ultraHigh';
case ResolutionPreset.veryHigh:
return 'veryHigh';
case ResolutionPreset.high:
return 'high';
case ResolutionPreset.medium:
return 'medium';
case ResolutionPreset.low:
return 'low';
}
throw ArgumentError('Unknown ResolutionPreset value');
}
/// Returns the white balance preset as a String.
String serializeWhiteBalancePreset(WhiteBalancePreset whiteBalancePreset) {
switch (whiteBalancePreset) {
case WhiteBalancePreset.off:
return 'off';
case WhiteBalancePreset.auto:
return 'auto';
case WhiteBalancePreset.incandescent:
return 'incandescent';
case WhiteBalancePreset.fluorescent:
return 'fluorescent';
case WhiteBalancePreset.warmFluorescent:
return 'warmFluorescent';
case WhiteBalancePreset.daylight:
return 'daylight';
case WhiteBalancePreset.cloudy:
return 'cloudy';
case WhiteBalancePreset.twilight:
return 'twilight';
case WhiteBalancePreset.shade:
return 'shade';
}
throw ArgumentError('Unknown WhiteBalancePreset value');
}
CameraLensDirection _parseCameraLensDirection(String string) {
switch (string) {
case 'front':
return CameraLensDirection.front;
case 'back':
return CameraLensDirection.back;
case 'external':
return CameraLensDirection.external;
}
throw ArgumentError('Unknown CameraLensDirection value');
}
/// Completes with a list of available cameras.
///
/// May throw a [CameraException].
Future<List<CameraDescription>> availableCameras() async {
try {
final List<Map<dynamic, dynamic>> cameras = await _channel
.invokeListMethod<Map<dynamic, dynamic>>('availableCameras');
return cameras.map((Map<dynamic, dynamic> camera) {
return CameraDescription(
name: camera['name'],
lensDirection: _parseCameraLensDirection(camera['lensFacing']),
sensorOrientation: camera['sensorOrientation'],
);
}).toList();
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
class CameraDescription {
CameraDescription({this.name, this.lensDirection, this.sensorOrientation});
final String name;
final CameraLensDirection lensDirection;
/// Clockwise angle through which the output image needs to be rotated to be upright on the device screen in its native orientation.
///
/// **Range of valid values:**
/// 0, 90, 180, 270
///
/// On Android, also defines the direction of rolling shutter readout, which
/// is from top to bottom in the sensor's coordinate system.
final int sensorOrientation;
@override
bool operator ==(Object o) {
return o is CameraDescription &&
o.name == name &&
o.lensDirection == lensDirection;
}
@override
int get hashCode {
return hashValues(name, lensDirection);
}
@override
String toString() {
return '$runtimeType($name, $lensDirection, $sensorOrientation)';
}
}
/// This is thrown when the plugin reports an error.
class CameraException implements Exception {
CameraException(this.code, this.description);
String code;
String description;
@override
String toString() => '$runtimeType($code, $description)';
}
// Build the UI texture view of the video data with textureId.
class CameraPreview extends StatelessWidget {
const CameraPreview(this.controller);
final CameraController controller;
@override
Widget build(BuildContext context) {
return controller.value.isInitialized
? Texture(textureId: controller._textureId)
: Container();
}
}
/// The state of a [CameraController].
class CameraValue {
const CameraValue({
this.isInitialized,
this.errorDescription,
this.previewSize,
this.isRecordingVideo,
this.isTakingPicture,
this.isStreamingImages,
bool isRecordingPaused,
}) : _isRecordingPaused = isRecordingPaused;
const CameraValue.uninitialized()
: this(
isInitialized: false,
isRecordingVideo: false,
isTakingPicture: false,
isStreamingImages: false,
isRecordingPaused: false,
);
/// True after [CameraController.initialize] has completed successfully.
final bool isInitialized;
/// True when a picture capture request has been sent but as not yet returned.
final bool isTakingPicture;
/// True when the camera is recording (not the same as previewing).
final bool isRecordingVideo;
/// True when images from the camera are being streamed.
final bool isStreamingImages;
final bool _isRecordingPaused;
/// True when camera [isRecordingVideo] and recording is paused.
bool get isRecordingPaused => isRecordingVideo && _isRecordingPaused;
final String errorDescription;
/// The size of the preview in pixels.
///
/// Is `null` until [isInitialized] is `true`.
final Size previewSize;
/// Convenience getter for `previewSize.height / previewSize.width`.
///
/// Can only be called when [initialize] is done.
double get aspectRatio => previewSize.height / previewSize.width;
bool get hasError => errorDescription != null;
CameraValue copyWith({
bool isInitialized,
bool isRecordingVideo,
bool isTakingPicture,
bool isStreamingImages,
String errorDescription,
Size previewSize,
bool isRecordingPaused,
}) {
return CameraValue(
isInitialized: isInitialized ?? this.isInitialized,
errorDescription: errorDescription,
previewSize: previewSize ?? this.previewSize,
isRecordingVideo: isRecordingVideo ?? this.isRecordingVideo,
isTakingPicture: isTakingPicture ?? this.isTakingPicture,
isStreamingImages: isStreamingImages ?? this.isStreamingImages,
isRecordingPaused: isRecordingPaused ?? _isRecordingPaused,
);
}
@override
String toString() {
return '$runtimeType('
'isRecordingVideo: $isRecordingVideo, '
'isRecordingVideo: $isRecordingVideo, '
'isInitialized: $isInitialized, '
'errorDescription: $errorDescription, '
'previewSize: $previewSize, '
'isStreamingImages: $isStreamingImages)';
}
}
/// Controls a device camera.
///
/// Use [availableCameras] to get a list of available cameras.
///
/// Before using a [CameraController] a call to [initialize] must complete.
///
/// To show the camera preview on the screen use a [CameraPreview] widget.
class CameraController extends ValueNotifier<CameraValue> {
CameraController(
this.description,
this.resolutionPreset, {
this.enableAudio = true,
this.iso = 0,
this.shutterSpeed = 0,
this.whiteBalance = WhiteBalancePreset.auto,
this.focusDistance = 0,
}) : super(const CameraValue.uninitialized());
final CameraDescription description;
final ResolutionPreset resolutionPreset;
/// Whether to include audio when recording a video.
final bool enableAudio;
/// Flash state
bool isFlashOn;
/// ISO value
final int iso;
/// Shutter speed
final int shutterSpeed;
/// White balance preset
final WhiteBalancePreset whiteBalance;
/// Distance from camera to focused object
final double focusDistance;
int _textureId;
bool _isDisposed = false;
StreamSubscription<dynamic> _eventSubscription;
StreamSubscription<dynamic> _imageStreamSubscription;
Completer<void> _creatingCompleter;
/// Initializes the camera on the device.
///
/// Throws a [CameraException] if the initialization fails.
Future<void> initialize() async {
if (_isDisposed) {
return Future<void>.value();
}
try {
_creatingCompleter = Completer<void>();
final Map<String, dynamic> reply =
await _channel.invokeMapMethod<String, dynamic>(
'initialize',
<String, dynamic>{
'cameraName': description.name,
'resolutionPreset': serializeResolutionPreset(resolutionPreset),
'enableAudio': enableAudio,
'iso': iso,
'shutterSpeed': (shutterSpeed == 0) ? 0 : 1000000000 ~/ shutterSpeed,
'whiteBalance': serializeWhiteBalancePreset(whiteBalance),
'focusDistance': 1 / focusDistance,
},
);
_textureId = reply['textureId'];
value = value.copyWith(
isInitialized: true,
previewSize: Size(
reply['previewWidth'].toDouble(),
reply['previewHeight'].toDouble(),
),
);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
_eventSubscription =
EventChannel('flutter.io/cameraPlugin/cameraEvents$_textureId')
.receiveBroadcastStream()
.listen(_listener);
_creatingCompleter.complete();
return _creatingCompleter.future;
}
/// Prepare the capture session for video recording.
///
/// Use of this method is optional, but it may be called for performance
/// reasons on iOS.
///
/// Preparing audio can cause a minor delay in the CameraPreview view on iOS.
/// If video recording is intended, calling this early eliminates this delay
/// that would otherwise be experienced when video recording is started.
/// This operation is a no-op on Android.
///
/// Throws a [CameraException] if the prepare fails.
Future<void> prepareForVideoRecording() async {
await _channel.invokeMethod<void>('prepareForVideoRecording');
}
/// Listen to events from the native plugins.
///
/// A "cameraClosing" event is sent when the camera is closed automatically by the system (for example when the app go to background). The plugin will try to reopen the camera automatically but any ongoing recording will end.
void _listener(dynamic event) {
final Map<dynamic, dynamic> map = event;
if (_isDisposed) {
return;
}
switch (map['eventType']) {
case 'error':
value = value.copyWith(errorDescription: event['errorDescription']);
break;
case 'cameraClosing':
value = value.copyWith(isRecordingVideo: false);
break;
}
}
/// Captures an image and saves it to [path].
///
/// A path can for example be obtained using
/// [path_provider](https://pub.dartlang.org/packages/path_provider).
///
/// If a file already exists at the provided path an error will be thrown.
/// The file can be read as this function returns.
///
/// Throws a [CameraException] if the capture fails.
Future<void> takePicture(String path) async {
if (!value.isInitialized || _isDisposed) {
throw CameraException(
'Uninitialized CameraController.',
'takePicture was called on uninitialized CameraController',
);
}
if (value.isTakingPicture) {
throw CameraException(
'Previous capture has not returned yet.',
'takePicture was called before the previous capture returned.',
);
}
try {
value = value.copyWith(isTakingPicture: true);
await _channel.invokeMethod<void>(
'takePicture',
<String, dynamic>{'textureId': _textureId, 'path': path},
);
value = value.copyWith(isTakingPicture: false);
} on PlatformException catch (e) {
value = value.copyWith(isTakingPicture: false);
throw CameraException(e.code, e.message);
}
}
/// Start streaming images from platform camera.
///
/// Settings for capturing images on iOS and Android is set to always use the
/// latest image available from the camera and will drop all other images.
///
/// When running continuously with [CameraPreview] widget, this function runs
/// best with [ResolutionPreset.low]. Running on [ResolutionPreset.high] can
/// have significant frame rate drops for [CameraPreview] on lower end
/// devices.
///
/// Throws a [CameraException] if image streaming or video recording has
/// already started.
// TODO(bmparr): Add settings for resolution and fps.
Future<void> startImageStream(onLatestImageAvailable onAvailable) async {
if (!value.isInitialized || _isDisposed) {
throw CameraException(
'Uninitialized CameraController',
'startImageStream was called on uninitialized CameraController.',
);
}
if (value.isRecordingVideo) {
throw CameraException(
'A video recording is already started.',
'startImageStream was called while a video is being recorded.',
);
}
if (value.isStreamingImages) {
throw CameraException(
'A camera has started streaming images.',
'startImageStream was called while a camera was streaming images.',
);
}
try {
await _channel.invokeMethod<void>('startImageStream');
value = value.copyWith(isStreamingImages: true);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
const EventChannel cameraEventChannel =
EventChannel('plugins.flutter.io/camera/imageStream');
_imageStreamSubscription =
cameraEventChannel.receiveBroadcastStream().listen(
(dynamic imageData) {
onAvailable(CameraImage._fromPlatformData(imageData));
},
);
}
Future<bool> flash(bool value) async {
try {
return await _channel.invokeMethod(
'enableFlash',
<String, dynamic>{
'flash': value,
},
);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Stop streaming images from platform camera.
///
/// Throws a [CameraException] if image streaming was not started or video
/// recording was started.
Future<void> stopImageStream() async {
if (!value.isInitialized || _isDisposed) {
throw CameraException(
'Uninitialized CameraController',
'stopImageStream was called on uninitialized CameraController.',
);
}
if (value.isRecordingVideo) {
throw CameraException(
'A video recording is already started.',
'stopImageStream was called while a video is being recorded.',
);
}
if (!value.isStreamingImages) {
throw CameraException(
'No camera is streaming images',
'stopImageStream was called when no camera is streaming images.',
);
}
try {
value = value.copyWith(isStreamingImages: false);
await _channel.invokeMethod<void>('stopImageStream');
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
await _imageStreamSubscription.cancel();
_imageStreamSubscription = null;
}
/// Start a video recording and save the file to [path].
///
/// A path can for example be obtained using
/// [path_provider](https://pub.dartlang.org/packages/path_provider).
///
/// The file is written on the flight as the video is being recorded.
/// If a file already exists at the provided path an error will be thrown.
/// The file can be read as soon as [stopVideoRecording] returns.
///
/// Throws a [CameraException] if the capture fails.
Future<void> startVideoRecording(String filePath) async {
if (!value.isInitialized || _isDisposed) {
throw CameraException(
'Uninitialized CameraController',
'startVideoRecording was called on uninitialized CameraController',
);
}
if (value.isRecordingVideo) {
throw CameraException(
'A video recording is already started.',
'startVideoRecording was called when a recording is already started.',
);
}
if (value.isStreamingImages) {
throw CameraException(
'A camera has started streaming images.',
'startVideoRecording was called while a camera was streaming images.',
);
}
try {
await _channel.invokeMethod<void>(
'startVideoRecording',
<String, dynamic>{'textureId': _textureId, 'filePath': filePath},
);
value = value.copyWith(isRecordingVideo: true, isRecordingPaused: false);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Stop recording.
Future<void> stopVideoRecording() async {
if (!value.isInitialized || _isDisposed) {
throw CameraException(
'Uninitialized CameraController',
'stopVideoRecording was called on uninitialized CameraController',
);
}
if (!value.isRecordingVideo) {
throw CameraException(
'No video is recording',
'stopVideoRecording was called when no video is recording.',
);
}
try {
value = value.copyWith(isRecordingVideo: false);
await _channel.invokeMethod<void>(
'stopVideoRecording',
<String, dynamic>{'textureId': _textureId},
);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Pause video recording.
///
/// This feature is only available on iOS and Android sdk 24+.
Future<void> pauseVideoRecording() async {
if (!value.isInitialized || _isDisposed) {
throw CameraException(
'Uninitialized CameraController',
'pauseVideoRecording was called on uninitialized CameraController',
);
}
if (!value.isRecordingVideo) {
throw CameraException(
'No video is recording',
'pauseVideoRecording was called when no video is recording.',
);
}
try {
value = value.copyWith(isRecordingPaused: true);
await _channel.invokeMethod<void>(
'pauseVideoRecording',
<String, dynamic>{'textureId': _textureId},
);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Resume video recording after pausing.
///
/// This feature is only available on iOS and Android sdk 24+.
Future<void> resumeVideoRecording() async {
if (!value.isInitialized || _isDisposed) {
throw CameraException(
'Uninitialized CameraController',
'resumeVideoRecording was called on uninitialized CameraController',
);
}
if (!value.isRecordingVideo) {
throw CameraException(
'No video is recording',
'resumeVideoRecording was called when no video is recording.',
);
}
try {
value = value.copyWith(isRecordingPaused: false);
await _channel.invokeMethod<void>(
'resumeVideoRecording',
<String, dynamic>{'textureId': _textureId},
);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Releases the resources of this camera.
@override
Future<void> dispose() async {
if (_isDisposed) {
return;
}
_isDisposed = true;
super.dispose();
if (_creatingCompleter != null) {
await _creatingCompleter.future;
await _channel.invokeMethod<void>(
'dispose',
<String, dynamic>{'textureId': _textureId},
);
await _eventSubscription?.cancel();
}
}
}