/
camera_controller.dart
836 lines (752 loc) · 28.3 KB
/
camera_controller.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
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
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
// Copyright 2013 The Flutter 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:math';
import 'package:camera_platform_interface/camera_platform_interface.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../camera.dart';
/// Signature for a callback receiving the a camera image.
///
/// This is used by [CameraController.startImageStream].
// TODO(stuartmorgan): Fix this naming the next time there's a breaking change
// to this package.
// ignore: camel_case_types
typedef onLatestImageAvailable = Function(CameraImage image);
/// Completes with a list of available cameras.
///
/// May throw a [CameraException].
Future<List<CameraDescription>> availableCameras() async {
return CameraPlatform.instance.availableCameras();
}
// TODO(stuartmorgan): Remove this once the package requires 2.10, where the
// dart:async `unawaited` accepts a nullable future.
void _unawaited(Future<void>? future) {}
/// The state of a [CameraController].
class CameraValue {
/// Creates a new camera controller state.
const CameraValue({
required this.isInitialized,
this.errorDescription,
this.previewSize,
required this.isRecordingVideo,
required this.isTakingPicture,
required this.isStreamingImages,
required bool isRecordingPaused,
required this.flashMode,
required this.exposureMode,
required this.focusMode,
required this.exposurePointSupported,
required this.focusPointSupported,
required this.deviceOrientation,
this.lockedCaptureOrientation,
this.recordingOrientation,
this.isPreviewPaused = false,
this.previewPauseOrientation,
}) : _isRecordingPaused = isRecordingPaused;
/// Creates a new camera controller state for an uninitialized controller.
const CameraValue.uninitialized()
: this(
isInitialized: false,
isRecordingVideo: false,
isTakingPicture: false,
isStreamingImages: false,
isRecordingPaused: false,
flashMode: FlashMode.auto,
exposureMode: ExposureMode.auto,
exposurePointSupported: false,
focusMode: FocusMode.auto,
focusPointSupported: false,
deviceOrientation: DeviceOrientation.portraitUp,
isPreviewPaused: 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 the preview widget has been paused manually.
final bool isPreviewPaused;
/// Set to the orientation the preview was paused in, if it is currently paused.
final DeviceOrientation? previewPauseOrientation;
/// True when camera [isRecordingVideo] and recording is paused.
bool get isRecordingPaused => isRecordingVideo && _isRecordingPaused;
/// Description of an error state.
///
/// This is null while the controller is not in an error state.
/// When [hasError] is true this contains the error description.
final String? errorDescription;
/// The size of the preview in pixels.
///
/// Is `null` until [isInitialized] is `true`.
final Size? previewSize;
/// Convenience getter for `previewSize.width / previewSize.height`.
///
/// Can only be called when [initialize] is done.
double get aspectRatio => previewSize!.width / previewSize!.height;
/// Whether the controller is in an error state.
///
/// When true [errorDescription] describes the error.
bool get hasError => errorDescription != null;
/// The flash mode the camera is currently set to.
final FlashMode flashMode;
/// The exposure mode the camera is currently set to.
final ExposureMode exposureMode;
/// The focus mode the camera is currently set to.
final FocusMode focusMode;
/// Whether setting the exposure point is supported.
final bool exposurePointSupported;
/// Whether setting the focus point is supported.
final bool focusPointSupported;
/// The current device UI orientation.
final DeviceOrientation deviceOrientation;
/// The currently locked capture orientation.
final DeviceOrientation? lockedCaptureOrientation;
/// Whether the capture orientation is currently locked.
bool get isCaptureOrientationLocked => lockedCaptureOrientation != null;
/// The orientation of the currently running video recording.
final DeviceOrientation? recordingOrientation;
/// Creates a modified copy of the object.
///
/// Explicitly specified fields get the specified value, all other fields get
/// the same value of the current object.
CameraValue copyWith({
bool? isInitialized,
bool? isRecordingVideo,
bool? isTakingPicture,
bool? isStreamingImages,
String? errorDescription,
Size? previewSize,
bool? isRecordingPaused,
FlashMode? flashMode,
ExposureMode? exposureMode,
FocusMode? focusMode,
bool? exposurePointSupported,
bool? focusPointSupported,
DeviceOrientation? deviceOrientation,
DeviceOrientation? lockedCaptureOrientation,
DeviceOrientation? recordingOrientation,
bool? isPreviewPaused,
DeviceOrientation? previewPauseOrientation,
}) {
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,
flashMode: flashMode ?? this.flashMode,
exposureMode: exposureMode ?? this.exposureMode,
focusMode: focusMode ?? this.focusMode,
exposurePointSupported:
exposurePointSupported ?? this.exposurePointSupported,
focusPointSupported: focusPointSupported ?? this.focusPointSupported,
deviceOrientation: deviceOrientation ?? this.deviceOrientation,
lockedCaptureOrientation:
lockedCaptureOrientation ?? this.lockedCaptureOrientation,
recordingOrientation: recordingOrientation ?? this.recordingOrientation,
isPreviewPaused: isPreviewPaused ?? this.isPreviewPaused,
previewPauseOrientation:
previewPauseOrientation ?? this.previewPauseOrientation,
);
}
@override
String toString() {
return '${objectRuntimeType(this, 'CameraValue')}('
'isRecordingVideo: $isRecordingVideo, '
'isInitialized: $isInitialized, '
'errorDescription: $errorDescription, '
'previewSize: $previewSize, '
'isStreamingImages: $isStreamingImages, '
'flashMode: $flashMode, '
'exposureMode: $exposureMode, '
'focusMode: $focusMode, '
'exposurePointSupported: $exposurePointSupported, '
'focusPointSupported: $focusPointSupported, '
'deviceOrientation: $deviceOrientation, '
'lockedCaptureOrientation: $lockedCaptureOrientation, '
'recordingOrientation: $recordingOrientation, '
'isPreviewPaused: $isPreviewPaused, '
'previewPausedOrientation: $previewPauseOrientation)';
}
}
/// 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> {
/// Creates a new camera controller in an uninitialized state.
CameraController(
this.description,
this.resolutionPreset, {
this.enableAudio = true,
this.imageFormatGroup,
}) : super(const CameraValue.uninitialized());
/// The properties of the camera device controlled by this controller.
final CameraDescription description;
/// The resolution this controller is targeting.
///
/// This resolution preset is not guaranteed to be available on the device,
/// if unavailable a lower resolution will be used.
///
/// See also: [ResolutionPreset].
final ResolutionPreset resolutionPreset;
/// Whether to include audio when recording a video.
final bool enableAudio;
/// The [ImageFormatGroup] describes the output of the raw image format.
///
/// When null the imageFormat will fallback to the platforms default.
final ImageFormatGroup? imageFormatGroup;
/// The id of a camera that hasn't been initialized.
@visibleForTesting
static const int kUninitializedCameraId = -1;
int _cameraId = kUninitializedCameraId;
bool _isDisposed = false;
StreamSubscription<CameraImageData>? _imageStreamSubscription;
FutureOr<bool>? _initCalled;
StreamSubscription<DeviceOrientationChangedEvent>?
_deviceOrientationSubscription;
/// Checks whether [CameraController.dispose] has completed successfully.
///
/// This is a no-op when asserts are disabled.
void debugCheckIsDisposed() {
assert(_isDisposed);
}
/// The camera identifier with which the controller is associated.
int get cameraId => _cameraId;
/// Initializes the camera on the device.
///
/// Throws a [CameraException] if the initialization fails.
Future<void> initialize() async {
if (_isDisposed) {
throw CameraException(
'Disposed CameraController',
'initialize was called on a disposed CameraController',
);
}
try {
final Completer<CameraInitializedEvent> initializeCompleter =
Completer<CameraInitializedEvent>();
_deviceOrientationSubscription = CameraPlatform.instance
.onDeviceOrientationChanged()
.listen((DeviceOrientationChangedEvent event) {
value = value.copyWith(
deviceOrientation: event.orientation,
);
});
_cameraId = await CameraPlatform.instance.createCamera(
description,
resolutionPreset,
enableAudio: enableAudio,
);
_unawaited(CameraPlatform.instance
.onCameraInitialized(_cameraId)
.first
.then((CameraInitializedEvent event) {
initializeCompleter.complete(event);
}));
await CameraPlatform.instance.initializeCamera(
_cameraId,
imageFormatGroup: imageFormatGroup ?? ImageFormatGroup.unknown,
);
value = value.copyWith(
isInitialized: true,
previewSize: await initializeCompleter.future
.then((CameraInitializedEvent event) => Size(
event.previewWidth,
event.previewHeight,
)),
exposureMode: await initializeCompleter.future
.then((CameraInitializedEvent event) => event.exposureMode),
focusMode: await initializeCompleter.future
.then((CameraInitializedEvent event) => event.focusMode),
exposurePointSupported: await initializeCompleter.future.then(
(CameraInitializedEvent event) => event.exposurePointSupported),
focusPointSupported: await initializeCompleter.future
.then((CameraInitializedEvent event) => event.focusPointSupported),
);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
_initCalled = true;
}
/// 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 and Web.
///
/// Throws a [CameraException] if the prepare fails.
Future<void> prepareForVideoRecording() async {
await CameraPlatform.instance.prepareForVideoRecording();
}
/// Pauses the current camera preview
Future<void> pausePreview() async {
if (value.isPreviewPaused) {
return;
}
try {
await CameraPlatform.instance.pausePreview(_cameraId);
value = value.copyWith(
isPreviewPaused: true,
previewPauseOrientation:
value.lockedCaptureOrientation ?? value.deviceOrientation);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Resumes the current camera preview
Future<void> resumePreview() async {
if (!value.isPreviewPaused) {
return;
}
try {
await CameraPlatform.instance.resumePreview(_cameraId);
value = value.copyWith(isPreviewPaused: false);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Captures an image and returns the file where it was saved.
///
/// Throws a [CameraException] if the capture fails.
Future<XFile> takePicture() async {
_throwIfNotInitialized('takePicture');
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);
final XFile file = await CameraPlatform.instance.takePicture(_cameraId);
value = value.copyWith(isTakingPicture: false);
return file;
} 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.
///
/// The `startImageStream` method is only available on Android and iOS (other
/// platforms won't be supported in current setup).
///
// TODO(bmparr): Add settings for resolution and fps.
Future<void> startImageStream(onLatestImageAvailable onAvailable) async {
assert(defaultTargetPlatform == TargetPlatform.android ||
defaultTargetPlatform == TargetPlatform.iOS);
_throwIfNotInitialized('startImageStream');
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 {
_imageStreamSubscription = CameraPlatform.instance
.onStreamedFrameAvailable(_cameraId)
.listen((CameraImageData imageData) {
onAvailable(CameraImage.fromPlatformInterface(imageData));
});
value = value.copyWith(isStreamingImages: true);
} 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.
///
/// The `stopImageStream` method is only available on Android and iOS (other
/// platforms won't be supported in current setup).
Future<void> stopImageStream() async {
assert(defaultTargetPlatform == TargetPlatform.android ||
defaultTargetPlatform == TargetPlatform.iOS);
_throwIfNotInitialized('stopImageStream');
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 _imageStreamSubscription?.cancel();
_imageStreamSubscription = null;
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Start a video recording.
///
/// You may optionally pass an [onAvailable] callback to also have the
/// video frames streamed to this callback.
///
/// The video is returned as a [XFile] after calling [stopVideoRecording].
/// Throws a [CameraException] if the capture fails.
Future<void> startVideoRecording(
{onLatestImageAvailable? onAvailable}) async {
_throwIfNotInitialized('startVideoRecording');
if (value.isRecordingVideo) {
throw CameraException(
'A video recording is already started.',
'startVideoRecording was called when a recording is already started.',
);
}
Function(CameraImageData image)? streamCallback;
if (onAvailable != null) {
streamCallback = (CameraImageData imageData) {
onAvailable(CameraImage.fromPlatformInterface(imageData));
};
}
try {
await CameraPlatform.instance.startVideoCapturing(
VideoCaptureOptions(_cameraId, streamCallback: streamCallback));
value = value.copyWith(
isRecordingVideo: true,
isRecordingPaused: false,
isStreamingImages: onAvailable != null,
recordingOrientation:
value.lockedCaptureOrientation ?? value.deviceOrientation);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Stops the video recording and returns the file where it was saved.
///
/// Throws a [CameraException] if the capture failed.
Future<XFile> stopVideoRecording() async {
_throwIfNotInitialized('stopVideoRecording');
if (!value.isRecordingVideo) {
throw CameraException(
'No video is recording',
'stopVideoRecording was called when no video is recording.',
);
}
if (value.isStreamingImages) {
stopImageStream();
}
try {
final XFile file =
await CameraPlatform.instance.stopVideoRecording(_cameraId);
value = value.copyWith(isRecordingVideo: false);
return file;
} 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 {
_throwIfNotInitialized('pauseVideoRecording');
if (!value.isRecordingVideo) {
throw CameraException(
'No video is recording',
'pauseVideoRecording was called when no video is recording.',
);
}
try {
await CameraPlatform.instance.pauseVideoRecording(_cameraId);
value = value.copyWith(isRecordingPaused: true);
} 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 {
_throwIfNotInitialized('resumeVideoRecording');
if (!value.isRecordingVideo) {
throw CameraException(
'No video is recording',
'resumeVideoRecording was called when no video is recording.',
);
}
try {
await CameraPlatform.instance.resumeVideoRecording(_cameraId);
value = value.copyWith(isRecordingPaused: false);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Returns a widget showing a live camera preview.
Widget buildPreview() {
_throwIfNotInitialized('buildPreview');
try {
return CameraPlatform.instance.buildPreview(_cameraId);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Gets the maximum supported zoom level for the selected camera.
Future<double> getMaxZoomLevel() {
_throwIfNotInitialized('getMaxZoomLevel');
try {
return CameraPlatform.instance.getMaxZoomLevel(_cameraId);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Gets the minimum supported zoom level for the selected camera.
Future<double> getMinZoomLevel() {
_throwIfNotInitialized('getMinZoomLevel');
try {
return CameraPlatform.instance.getMinZoomLevel(_cameraId);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Set the zoom level for the selected camera.
///
/// The supplied [zoom] value should be between 1.0 and the maximum supported
/// zoom level returned by the `getMaxZoomLevel`. Throws an `CameraException`
/// when an illegal zoom level is suplied.
Future<void> setZoomLevel(double zoom) {
_throwIfNotInitialized('setZoomLevel');
try {
return CameraPlatform.instance.setZoomLevel(_cameraId, zoom);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Sets the flash mode for taking pictures.
Future<void> setFlashMode(FlashMode mode) async {
try {
await CameraPlatform.instance.setFlashMode(_cameraId, mode);
value = value.copyWith(flashMode: mode);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Sets the exposure mode for taking pictures.
Future<void> setExposureMode(ExposureMode mode) async {
try {
await CameraPlatform.instance.setExposureMode(_cameraId, mode);
value = value.copyWith(exposureMode: mode);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Sets the exposure point for automatically determining the exposure value.
///
/// Supplying a `null` value will reset the exposure point to it's default
/// value.
Future<void> setExposurePoint(Offset? point) async {
if (point != null &&
(point.dx < 0 || point.dx > 1 || point.dy < 0 || point.dy > 1)) {
throw ArgumentError(
'The values of point should be anywhere between (0,0) and (1,1).');
}
try {
await CameraPlatform.instance.setExposurePoint(
_cameraId,
point == null
? null
: Point<double>(
point.dx,
point.dy,
),
);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Gets the minimum supported exposure offset for the selected camera in EV units.
Future<double> getMinExposureOffset() async {
_throwIfNotInitialized('getMinExposureOffset');
try {
return CameraPlatform.instance.getMinExposureOffset(_cameraId);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Gets the maximum supported exposure offset for the selected camera in EV units.
Future<double> getMaxExposureOffset() async {
_throwIfNotInitialized('getMaxExposureOffset');
try {
return CameraPlatform.instance.getMaxExposureOffset(_cameraId);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Gets the supported step size for exposure offset for the selected camera in EV units.
///
/// Returns 0 when the camera supports using a free value without stepping.
Future<double> getExposureOffsetStepSize() async {
_throwIfNotInitialized('getExposureOffsetStepSize');
try {
return CameraPlatform.instance.getExposureOffsetStepSize(_cameraId);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Sets the exposure offset for the selected camera.
///
/// The supplied [offset] value should be in EV units. 1 EV unit represents a
/// doubling in brightness. It should be between the minimum and maximum offsets
/// obtained through `getMinExposureOffset` and `getMaxExposureOffset` respectively.
/// Throws a `CameraException` when an illegal offset is supplied.
///
/// When the supplied [offset] value does not align with the step size obtained
/// through `getExposureStepSize`, it will automatically be rounded to the nearest step.
///
/// Returns the (rounded) offset value that was set.
Future<double> setExposureOffset(double offset) async {
_throwIfNotInitialized('setExposureOffset');
// Check if offset is in range
final List<double> range = await Future.wait(
<Future<double>>[getMinExposureOffset(), getMaxExposureOffset()]);
if (offset < range[0] || offset > range[1]) {
throw CameraException(
'exposureOffsetOutOfBounds',
'The provided exposure offset was outside the supported range for this device.',
);
}
// Round to the closest step if needed
final double stepSize = await getExposureOffsetStepSize();
if (stepSize > 0) {
final double inv = 1.0 / stepSize;
double roundedOffset = (offset * inv).roundToDouble() / inv;
if (roundedOffset > range[1]) {
roundedOffset = (offset * inv).floorToDouble() / inv;
} else if (roundedOffset < range[0]) {
roundedOffset = (offset * inv).ceilToDouble() / inv;
}
offset = roundedOffset;
}
try {
return CameraPlatform.instance.setExposureOffset(_cameraId, offset);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Locks the capture orientation.
///
/// If [orientation] is omitted, the current device orientation is used.
Future<void> lockCaptureOrientation([DeviceOrientation? orientation]) async {
try {
await CameraPlatform.instance.lockCaptureOrientation(
_cameraId, orientation ?? value.deviceOrientation);
value = value.copyWith(
lockedCaptureOrientation: orientation ?? value.deviceOrientation);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Sets the focus mode for taking pictures.
Future<void> setFocusMode(FocusMode mode) async {
try {
await CameraPlatform.instance.setFocusMode(_cameraId, mode);
value = value.copyWith(focusMode: mode);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Unlocks the capture orientation.
Future<void> unlockCaptureOrientation() async {
try {
await CameraPlatform.instance.unlockCaptureOrientation(_cameraId);
value = value.copyWith();
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Sets the focus point for automatically determining the focus value.
///
/// Supplying a `null` value will reset the focus point to it's default
/// value.
Future<void> setFocusPoint(Offset? point) async {
if (point != null &&
(point.dx < 0 || point.dx > 1 || point.dy < 0 || point.dy > 1)) {
throw ArgumentError(
'The values of point should be anywhere between (0,0) and (1,1).');
}
try {
await CameraPlatform.instance.setFocusPoint(
_cameraId,
point == null
? null
: Point<double>(
point.dx,
point.dy,
),
);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Releases the resources of this camera.
@override
Future<void> dispose() async {
if (_isDisposed) {
return;
}
_unawaited(_deviceOrientationSubscription?.cancel());
_isDisposed = true;
super.dispose();
if (_initCalled != null) {
await _initCalled;
await CameraPlatform.instance.dispose(_cameraId);
}
}
void _throwIfNotInitialized(String functionName) {
if (!value.isInitialized) {
throw CameraException(
'Uninitialized CameraController',
'$functionName() was called on an uninitialized CameraController.',
);
}
if (_isDisposed) {
throw CameraException(
'Disposed CameraController',
'$functionName() was called on a disposed CameraController.',
);
}
}
@override
void removeListener(VoidCallback listener) {
// Prevent ValueListenableBuilder in CameraPreview widget from causing an
// exception to be thrown by attempting to remove its own listener after
// the controller has already been disposed.
if (!_isDisposed) {
super.removeListener(listener);
}
}
}