-
Notifications
You must be signed in to change notification settings - Fork 3.7k
Expand file tree
/
Copy pathandroid_camera.dart
More file actions
454 lines (380 loc) · 13.3 KB
/
android_camera.dart
File metadata and controls
454 lines (380 loc) · 13.3 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
// 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:math';
import 'package:camera_platform_interface/camera_platform_interface.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:stream_transform/stream_transform.dart';
import 'messages.g.dart';
import 'type_conversion.dart';
import 'utils.dart';
/// The Android implementation of [CameraPlatform] that uses method channels.
class AndroidCamera extends CameraPlatform {
/// Creates a new [CameraPlatform] instance.
AndroidCamera({@visibleForTesting CameraApi? hostApi})
: _hostApi = hostApi ?? CameraApi();
/// Registers this class as the default instance of [CameraPlatform].
static void registerWith() {
CameraPlatform.instance = AndroidCamera();
}
final CameraApi _hostApi;
/// The name of the channel that device events from the platform side are
/// sent on.
@visibleForTesting
static const String deviceEventChannelName =
'plugins.flutter.io/camera_android/fromPlatform';
/// The controller we need to broadcast the different events coming
/// from handleMethodCall, specific to camera events.
///
/// It is a `broadcast` because multiple controllers will connect to
/// different stream views of this Controller.
/// This is only exposed for test purposes. It shouldn't be used by clients of
/// the plugin as it may break or change at any time.
@visibleForTesting
final StreamController<CameraEvent> cameraEventStreamController =
StreamController<CameraEvent>.broadcast();
/// Handler for device-level callbacks from the native side.
@visibleForTesting
late final HostDeviceMessageHandler hostHandler = HostDeviceMessageHandler();
/// Map of camera IDs to camera-level callback handlers listening to their
/// respective platform channels.
@visibleForTesting
final Map<int, HostCameraMessageHandler> hostCameraHandlers =
<int, HostCameraMessageHandler>{};
// The stream to receive frames from the native code.
StreamSubscription<dynamic>? _platformImageStreamSubscription;
// The stream for vending frames to platform interface clients.
StreamController<CameraImageData>? _frameStreamController;
Stream<CameraEvent> _cameraEvents(int cameraId) => cameraEventStreamController
.stream
.where((CameraEvent event) => event.cameraId == cameraId);
@override
Future<List<CameraDescription>> availableCameras() async {
try {
final List<PlatformCameraDescription> cameraDescriptions = await _hostApi
.getAvailableCameras();
return cameraDescriptions.map((
PlatformCameraDescription cameraDescription,
) {
return CameraDescription(
name: cameraDescription.name,
lensDirection: cameraLensDirectionFromPlatform(
cameraDescription.lensDirection,
),
sensorOrientation: cameraDescription.sensorOrientation,
);
}).toList();
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
@override
Future<int> createCamera(
CameraDescription cameraDescription,
ResolutionPreset? resolutionPreset, {
bool enableAudio = false,
}) => createCameraWithSettings(
cameraDescription,
MediaSettings(resolutionPreset: resolutionPreset, enableAudio: enableAudio),
);
@override
Future<int> createCameraWithSettings(
CameraDescription cameraDescription,
MediaSettings? mediaSettings,
) async {
try {
return await _hostApi.create(
cameraDescription.name,
mediaSettingsToPlatform(mediaSettings),
);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
@override
Future<void> initializeCamera(
int cameraId, {
ImageFormatGroup imageFormatGroup = ImageFormatGroup.unknown,
}) async {
hostCameraHandlers.putIfAbsent(
cameraId,
() => HostCameraMessageHandler(cameraId, cameraEventStreamController),
);
final completer = Completer<void>();
unawaited(
onCameraInitialized(cameraId).first.then((CameraInitializedEvent value) {
completer.complete();
}),
);
try {
await _hostApi.initialize(imageFormatGroupToPlatform(imageFormatGroup));
} on PlatformException catch (e, s) {
completer.completeError(CameraException(e.code, e.message), s);
}
return completer.future;
}
@override
Future<void> dispose(int cameraId) async {
final HostCameraMessageHandler? handler = hostCameraHandlers.remove(
cameraId,
);
handler?.dispose();
await _hostApi.dispose();
}
@override
Stream<CameraInitializedEvent> onCameraInitialized(int cameraId) {
return _cameraEvents(cameraId).whereType<CameraInitializedEvent>();
}
@override
Stream<CameraResolutionChangedEvent> onCameraResolutionChanged(int cameraId) {
return _cameraEvents(cameraId).whereType<CameraResolutionChangedEvent>();
}
@override
Stream<CameraClosingEvent> onCameraClosing(int cameraId) {
return _cameraEvents(cameraId).whereType<CameraClosingEvent>();
}
@override
Stream<CameraErrorEvent> onCameraError(int cameraId) {
return _cameraEvents(cameraId).whereType<CameraErrorEvent>();
}
@override
Stream<VideoRecordedEvent> onVideoRecordedEvent(int cameraId) {
return _cameraEvents(cameraId).whereType<VideoRecordedEvent>();
}
@override
Stream<DeviceOrientationChangedEvent> onDeviceOrientationChanged() {
return hostHandler.deviceEventStreamController.stream
.whereType<DeviceOrientationChangedEvent>();
}
@override
Future<void> lockCaptureOrientation(
int cameraId,
DeviceOrientation orientation,
) async {
await _hostApi.lockCaptureOrientation(
deviceOrientationToPlatform(orientation),
);
}
@override
Future<void> unlockCaptureOrientation(int cameraId) async {
await _hostApi.unlockCaptureOrientation();
}
@override
Future<XFile> takePicture(int cameraId) async {
final String path = await _hostApi.takePicture();
return XFile(path);
}
// This optimization is unnecessary on Android.
@override
Future<void> prepareForVideoRecording() async {}
@override
Future<void> startVideoRecording(
int cameraId, {
Duration? maxVideoDuration,
}) async {
// Ignore maxVideoDuration, as it is unimplemented and deprecated.
return startVideoCapturing(VideoCaptureOptions(cameraId));
}
@override
Future<void> startVideoCapturing(VideoCaptureOptions options) async {
await _hostApi.startVideoRecording(options.streamCallback != null);
if (options.streamCallback != null) {
_installStreamController().stream.listen(options.streamCallback);
_startStreamListener();
}
}
@override
Future<XFile> stopVideoRecording(int cameraId) async {
final String path = await _hostApi.stopVideoRecording();
return XFile(path);
}
@override
Future<void> pauseVideoRecording(int cameraId) =>
_hostApi.pauseVideoRecording();
@override
Future<void> resumeVideoRecording(int cameraId) =>
_hostApi.resumeVideoRecording();
@override
bool supportsImageStreaming() => true;
@override
Stream<CameraImageData> onStreamedFrameAvailable(
int cameraId, {
CameraImageStreamOptions? options,
}) {
_installStreamController(onListen: _onFrameStreamListen);
return _frameStreamController!.stream;
}
StreamController<CameraImageData> _installStreamController({
void Function()? onListen,
}) {
_frameStreamController = StreamController<CameraImageData>(
onListen: onListen ?? () {},
onPause: _onFrameStreamPauseResume,
onResume: _onFrameStreamPauseResume,
onCancel: _onFrameStreamCancel,
);
return _frameStreamController!;
}
void _onFrameStreamListen() {
_startPlatformStream();
}
Future<void> _startPlatformStream() async {
await _hostApi.startImageStream();
_startStreamListener();
}
void _startStreamListener() {
const cameraEventChannel = EventChannel(
'plugins.flutter.io/camera_android/imageStream',
);
_platformImageStreamSubscription = cameraEventChannel
.receiveBroadcastStream()
.listen((dynamic imageData) {
_frameStreamController!.add(
cameraImageFromPlatformData(imageData as Map<dynamic, dynamic>),
);
});
}
FutureOr<void> _onFrameStreamCancel() async {
await _hostApi.stopImageStream();
await _platformImageStreamSubscription?.cancel();
_platformImageStreamSubscription = null;
_frameStreamController = null;
}
void _onFrameStreamPauseResume() {
throw CameraException(
'InvalidCall',
'Pause and resume are not supported for onStreamedFrameAvailable',
);
}
@override
Future<void> setFlashMode(int cameraId, FlashMode mode) =>
_hostApi.setFlashMode(flashModeToPlatform(mode));
@override
Future<void> setExposureMode(int cameraId, ExposureMode mode) =>
_hostApi.setExposureMode(exposureModeToPlatform(mode));
@override
Future<void> setExposurePoint(int cameraId, Point<double>? point) {
assert(point == null || point.x >= 0 && point.x <= 1);
assert(point == null || point.y >= 0 && point.y <= 1);
return _hostApi.setExposurePoint(pointToPlatform(point));
}
@override
Future<double> getMinExposureOffset(int cameraId) async {
return _hostApi.getMinExposureOffset();
}
@override
Future<double> getMaxExposureOffset(int cameraId) async {
return _hostApi.getMaxExposureOffset();
}
@override
Future<double> getExposureOffsetStepSize(int cameraId) async {
return _hostApi.getExposureOffsetStepSize();
}
@override
Future<double> setExposureOffset(int cameraId, double offset) async {
return _hostApi.setExposureOffset(offset);
}
@override
Future<void> setFocusMode(int cameraId, FocusMode mode) =>
_hostApi.setFocusMode(focusModeToPlatform(mode));
@override
Future<void> setFocusPoint(int cameraId, Point<double>? point) {
assert(point == null || point.x >= 0 && point.x <= 1);
assert(point == null || point.y >= 0 && point.y <= 1);
return _hostApi.setFocusPoint(pointToPlatform(point));
}
@override
Future<double> getMaxZoomLevel(int cameraId) async {
return _hostApi.getMaxZoomLevel();
}
@override
Future<double> getMinZoomLevel(int cameraId) async {
return _hostApi.getMinZoomLevel();
}
@override
Future<void> setZoomLevel(int cameraId, double zoom) async {
try {
await _hostApi.setZoomLevel(zoom);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
@override
Future<void> pausePreview(int cameraId) async {
await _hostApi.pausePreview();
}
@override
Future<void> resumePreview(int cameraId) async {
await _hostApi.resumePreview();
}
@override
Future<void> setDescriptionWhileRecording(
CameraDescription description,
) async {
await _hostApi.setDescriptionWhileRecording(description.name);
}
@override
Future<void> setJpegImageQuality(int cameraId, int quality) =>
_hostApi.setJpegImageQuality(quality);
@override
Widget buildPreview(int cameraId) {
return Texture(textureId: cameraId);
}
}
/// Handles callbacks from the platform host that are not camera-specific.
@visibleForTesting
class HostDeviceMessageHandler implements CameraGlobalEventApi {
/// Creates a new handler and registers it to listen to the global event platform channel.
HostDeviceMessageHandler() {
CameraGlobalEventApi.setUp(this);
}
/// The controller that broadcasts device events coming from the host platform.
final StreamController<DeviceEvent> deviceEventStreamController =
StreamController<DeviceEvent>.broadcast();
@override
void deviceOrientationChanged(PlatformDeviceOrientation orientation) {
deviceEventStreamController.add(
DeviceOrientationChangedEvent(deviceOrientationFromPlatform(orientation)),
);
}
}
/// Handles camera-specific callbacks from the platform host.
@visibleForTesting
class HostCameraMessageHandler implements CameraEventApi {
/// Creates a new handler and registers it to listen to its camera's platform channel.
HostCameraMessageHandler(this.cameraId, this.cameraEventStreamController) {
CameraEventApi.setUp(this, messageChannelSuffix: '$cameraId');
}
/// Removes this handler from its platform channel.
void dispose() {
CameraEventApi.setUp(null, messageChannelSuffix: '$cameraId');
}
/// The ID of the camera for which this handler listens for events.
final int cameraId;
/// The controller which broadcasts camera events from the host platform.
final StreamController<CameraEvent> cameraEventStreamController;
@override
void error(String message) {
cameraEventStreamController.add(CameraErrorEvent(cameraId, message));
}
@override
void initialized(PlatformCameraState initialState) {
cameraEventStreamController.add(
CameraInitializedEvent(
cameraId,
initialState.previewSize.width,
initialState.previewSize.height,
exposureModeFromPlatform(initialState.exposureMode),
initialState.exposurePointSupported,
focusModeFromPlatform(initialState.focusMode),
initialState.focusPointSupported,
),
);
}
@override
void closed() {
cameraEventStreamController.add(CameraClosingEvent(cameraId));
}
}