Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
QtCamera2.java
Go to the documentation of this file.
1// Copyright (C) 2022 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3package org.qtproject.qt.android.multimedia.qffmpeg;
4
5import android.annotation.SuppressLint;
6import android.annotation.TargetApi;
7import android.content.Context;
8import android.graphics.ImageFormat;
9import android.graphics.Rect;
10import android.hardware.camera2.CameraAccessException;
11import android.hardware.camera2.CameraCaptureSession;
12import android.hardware.camera2.CameraDevice;
13import android.hardware.camera2.CameraMetadata;
14import android.hardware.camera2.CameraManager;
15import android.hardware.camera2.CaptureFailure;
16import android.hardware.camera2.CaptureResult;
17import android.hardware.camera2.CaptureRequest;
18import android.hardware.camera2.params.OutputConfiguration;
19import android.hardware.camera2.params.SessionConfiguration;
20import android.media.Image;
21import android.media.ImageReader;
22import android.os.Handler;
23import android.os.HandlerThread;
24import android.util.Log;
25import android.util.Range;
26import android.view.Surface;
27import java.lang.Thread;
28import java.util.ArrayList;
29import java.util.List;
30import java.util.concurrent.CountDownLatch;
31import java.util.concurrent.TimeUnit;
32
33import org.qtproject.qt.android.UsedFromNativeCode;
34
35@TargetApi(23)
36class QtCamera2 {
37 static final String LOG_TAG = "QtCamera2";
38
39 // Should be called if an on-going still photo capture has failed to finish.
40 // This lets us submit an appropriate error and notify QImageCapture that there will
41 // be no photo emitted.
42 // TODO: In the future we should send a more descriptive error message to QImageCapture, and
43 // and pass it as a parameter here.
44 native void onStillPhotoCaptureFailed(long qAndroidCameraPtr);
45
46 // The pointer to the associated QAndroidCamera object. If this is
47 // null, it implies we are shutting down.
48 // Don't use directly.
49 private long mQAndroidCameraPtr = 0;
50 CameraDevice mCameraDevice = null;
51 // Counted down by CameraDeviceStateCallback.onClosed(), awaited in stopAndClose()
52 volatile CountDownLatch mDeviceClosedLatch = null;
53 QtVideoDeviceManager mVideoDeviceManager = null;
54 // Thread and handler to that allows us to receive callbacks and frames on a background thread.
55 HandlerThread mBackgroundThread;
56 Handler mBackgroundHandler;
57 // Output of preview/video frames, the native side owns the image reader behind it.
58 Surface mPreviewSurface = null;
59 // Used to emit still photo images to the C++ thread.
60 ImageReader mStillPhotoImageReader = null;
61 CameraManager mCameraManager;
62 CameraCaptureSession mCaptureSession;
63 // Callback of the session being created or active. Events from callbacks of replaced
64 // sessions are ignored, see CameraCaptureSessionStateCallback.
65 volatile CameraCaptureSessionStateCallback mCurrentSessionCallback;
66 CaptureRequest.Builder mPreviewRequestBuilder;
67 CaptureRequest mPreviewRequest;
68 String mCameraId;
69 List<Surface> mTargetSurfaces = new ArrayList<>();
70
71 private static int MaxNumberFrames = 12;
72
73 // The purpose of this class is to gather variables that are accessed across
74 // the C++ QCamera's thread, and the background capture-processing thread.
75 // It also acts as the mutex for these variables.
76 // All access to these variables must happen after locking the instance.
77 class SyncedMembers {
78 // Idle -> Started: start(). Started <-> Capturing: still photo begins/ends.
79 // Idle/Started -> Reconfiguring: session rebuilt for a new still size, start() returns it
80 // to Started, a failure to Idle. Anything -> Idle: stopAndClose().
82 State mState = State.Idle;
83
84 // A still photo requested while reconfiguring runs once the session is configured.
85 boolean mStillCaptureDeferred = false;
86
87 QtCameraActivation mPendingActivation = null;
88
89 // Preview is running, settings are applied to it directly
90 boolean isStarted() {
91 return mState == State.Started || mState == State.Capturing;
92 }
93
94 boolean isTakingStillPhoto() {
95 return mState == State.Capturing;
96 }
97
98 void endStillPhoto() {
99 if (mState == State.Capturing)
100 mState = State.Started;
101 }
102
103 private CameraSettings mCameraSettings = new CameraSettings();
104 }
105 final SyncedMembers mSyncedMembers = new SyncedMembers();
106
107 // Resets the control properties of this camera to their default values.
109 public void resetControlProperties() {
110 synchronized (mSyncedMembers) {
111 mSyncedMembers.mCameraSettings = new CameraSettings();
112 }
113 }
114
115 long getQAndroidCameraPtr() {
116 // We always assume the QAndroidCamera instance is assigned when constructing
117 // this class, and we assume that we never invoke any QAndroidCamera methods
118 // after it has been destroyed.
119 assert(mQAndroidCameraPtr != 0);
120 return mQAndroidCameraPtr;
121 }
122
123 private QtCameraActivation takePendingActivation() {
124 synchronized (mSyncedMembers) {
125 QtCameraActivation activation = mSyncedMembers.mPendingActivation;
126 mSyncedMembers.mPendingActivation = null;
127 return activation;
128 }
129 }
130
131 void reportActivationSuccess() {
132 QtCameraActivation activation = takePendingActivation();
133 if (activation != null)
134 activation.reportSuccess();
135 }
136
137 // The error message is public, it ends up in QCamera::errorString().
138 boolean reportActivationFailure(String errorMessage) {
139 QtCameraActivation activation = takePendingActivation();
140 if (activation == null)
141 return false;
142 activation.reportFailure(errorMessage);
143 return true;
144 }
145
146 // Returns a deep copy of the CameraSettings instance. Thread-safe.
147 private CameraSettings atomicCameraSettingsCopy() {
148 synchronized (mSyncedMembers) {
149 return new CameraSettings(mSyncedMembers.mCameraSettings);
150 }
151 }
152
153 QtExifDataHandler mExifDataHandler = null;
154
155 native void onCameraOpened(long qAndroidCameraPtr);
156 native void onCameraDisconnect(long qAndroidCameraPtr);
157 native void onCameraError(long qAndroidCameraPtr, int error);
158
159 CameraDeviceStateCallback mStateCallback = new CameraDeviceStateCallback(this);
160
161 native void onCaptureSessionConfigured(long qAndroidCameraPtr);
162 native void onCaptureSessionConfigureFailed(long qAndroidCameraPtr);
163 native void onStillReaderSwapFailed(long qAndroidCameraPtr);
164
165 native void onSessionClosed(long qAndroidCameraPtr);
166 native void onCaptureSessionFailed(long qAndroidCameraPtr, int reason, long frameNumber);
167
168 // This callback is used when doing normal preview. The only purpose is to detect if something
169 // goes wrong, so we can report back to QCamera.
170 // The events in this class are invoked from the background processing thread.
171 class PreviewCaptureSessionCallback extends CameraCaptureSession.CaptureCallback {
172 @Override
173 public void onCaptureFailed(
174 CameraCaptureSession session,
175 CaptureRequest request,
176 CaptureFailure failure)
177 {
178 super.onCaptureFailed(session, request, failure);
179 onCaptureSessionFailed(
180 getQAndroidCameraPtr(),
181 failure.getReason(),
182 failure.getFrameNumber());
183 }
184 }
185
186 // Callback that is being used for error-handling when doing preview.
187 // TODO: The variable can be removed in the future, and instead just recreate the object
188 // every time we go into previewing.
189 PreviewCaptureSessionCallback mPreviewCaptureCallback = new PreviewCaptureSessionCallback();
190
191 QtCamera2(long qAndroidCameraPtr, Context context) {
192 assert(qAndroidCameraPtr != 0);
193 assert(context != null);
194
195 mQAndroidCameraPtr = qAndroidCameraPtr;
196 mCameraManager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
197 mVideoDeviceManager = new QtVideoDeviceManager(context);
198 startBackgroundThread();
199 }
200
201 void startBackgroundThread() {
202 mBackgroundThread = new HandlerThread("CameraBackground");
203 mBackgroundThread.start();
204 mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
205 }
206
208 void stopBackgroundThread() {
209 mBackgroundThread.quitSafely();
210 try {
211 mBackgroundThread.join();
212 mBackgroundThread = null;
213 mBackgroundHandler = null;
214 } catch (Exception e) {
215 e.printStackTrace();
216 }
217 }
218
219 // activation is null for internal restarts, where nobody waits for the result.
221 @SuppressLint("MissingPermission")
222 void open(String cameraId, QtCameraActivation activation) {
223 synchronized (mSyncedMembers) {
224 assert(mSyncedMembers.mPendingActivation == null);
225 mSyncedMembers.mPendingActivation = activation;
226 }
227
228 try {
229 mCameraId = cameraId;
230 mCameraManager.openCamera(cameraId,mStateCallback,mBackgroundHandler);
231 } catch (Exception e){
232 Log.w(LOG_TAG, "Failed to open camera:" + e);
233 reportActivationFailure("Failed to open camera");
234 }
235 }
236
237 native void onStillPhotoAvailable(long qAndroidCameraPtr, Image frame);
238
239 // Callback for when we receive a finalized still photo in mStillPhotoImageReader.
240 ImageReader.OnImageAvailableListener mOnStillPhotoAvailableListener = new ImageReader.OnImageAvailableListener() {
241 @Override
242 public void onImageAvailable(ImageReader reader) {
243 QtCamera2.this.onStillPhotoAvailable(getQAndroidCameraPtr(), reader.acquireLatestImage());
244 }
245 };
246
248 void prepareCamera(int minFps, int maxFps, Surface previewSurface, int stillWidth, int stillHeight) {
249 if (mPreviewSurface != null)
250 removeSurface(mPreviewSurface);
251 mPreviewSurface = previewSurface;
252 addSurface(mPreviewSurface);
253 setFrameRate(minFps, maxFps);
254 addStillImageReader(stillWidth, stillHeight);
255 }
256
257 void addStillImageReader(int width, int height) {
258 if (mStillPhotoImageReader != null)
259 removeSurface(mStillPhotoImageReader.getSurface());
260
261 mStillPhotoImageReader =
262 ImageReader.newInstance(width, height, ImageFormat.JPEG, MaxNumberFrames);
263 mStillPhotoImageReader.setOnImageAvailableListener(mOnStillPhotoAvailableListener, mBackgroundHandler);
264 addSurface(mStillPhotoImageReader.getSurface());
265 }
266
267 // Swaps the still ImageReader and rebuilds the session, keeping the camera open. Runs on the
268 // background handler so it can't interleave with session callbacks. Failure is reported
269 // through onStillReaderSwapFailed.
271 boolean updateStillImageReader(int width, int height) {
272 final Handler handler = mBackgroundHandler;
273 if (mCameraDevice == null || mStillPhotoImageReader == null || handler == null)
274 return false;
275
276 synchronized (mSyncedMembers) {
277 if (mSyncedMembers.isTakingStillPhoto())
278 return false;
279 mSyncedMembers.mState = SyncedMembers.State.Reconfiguring;
280 }
281
282 return handler.post(() -> {
283 if (mCameraDevice == null || mStillPhotoImageReader == null)
284 return; // Closed in the meantime
285
286 mCurrentSessionCallback = null;
287 if (mCaptureSession != null) {
288 mCaptureSession.close();
289 mCaptureSession = null;
290 }
291
292 // Not closed: native code may still hold its Images. GC releases it once they're gone.
293 mStillPhotoImageReader.setOnImageAvailableListener(null, null);
294 addStillImageReader(width, height);
295
296 if (!createSession())
297 onSessionConfigureFailed();
298 });
299 }
300
301 // Called on the background thread when configuring the session failed.
302 void onSessionConfigureFailed() {
303 final boolean isStillReaderSwap;
304 synchronized (mSyncedMembers) {
305 isStillReaderSwap = mSyncedMembers.mState == SyncedMembers.State.Reconfiguring;
306 }
307 if (isStillReaderSwap)
308 onStillReaderSwapFailed(getQAndroidCameraPtr());
309 else if (!reportActivationFailure("Failed to configure camera"))
310 onCaptureSessionConfigureFailed(getQAndroidCameraPtr());
311 onSessionReconfigured(false);
312 }
313
314 // Called on the background thread. Runs the deferred still capture, if any.
315 void onSessionReconfigured(boolean success) {
316 final boolean captureDeferred;
317 synchronized (mSyncedMembers) {
318 if (mSyncedMembers.mState == SyncedMembers.State.Reconfiguring)
319 mSyncedMembers.mState = SyncedMembers.State.Idle;
320 captureDeferred = mSyncedMembers.mStillCaptureDeferred;
321 mSyncedMembers.mStillCaptureDeferred = false;
322 }
323 if (!captureDeferred)
324 return;
325 if (success)
326 beginStillPhotoCapture();
327 else
328 onStillPhotoCaptureFailed(getQAndroidCameraPtr());
329 }
330
331 private void setFrameRate(int minFrameRate, int maxFrameRate) {
332 synchronized (mSyncedMembers) {
333 if (minFrameRate <= 0 || maxFrameRate <= 0)
334 mSyncedMembers.mCameraSettings.mFpsRange = null;
335 else
336 mSyncedMembers.mCameraSettings.mFpsRange = new Range<>(minFrameRate, maxFrameRate);
337 }
338 }
339
340 boolean addSurface(Surface surface) {
341 if (mTargetSurfaces.contains(surface))
342 return true;
343
344 return mTargetSurfaces.add(surface);
345 }
346
347 boolean removeSurface(Surface surface) {
348 return mTargetSurfaces.remove(surface);
349 }
350
352 void clearSurfaces() {
353 mTargetSurfaces.clear();
354 }
355
357 boolean createSession() {
358 if (mCameraDevice == null)
359 return false;
360
361 try {
362 List<OutputConfiguration> outputs = new ArrayList<>(mTargetSurfaces.size());
363 for (Surface surface : mTargetSurfaces)
364 outputs.add(new OutputConfiguration(surface));
365
366 mCurrentSessionCallback = new CameraCaptureSessionStateCallback(this);
367 SessionConfiguration config = new SessionConfiguration(
368 SessionConfiguration.SESSION_REGULAR, outputs,
369 mBackgroundHandler::post, mCurrentSessionCallback);
370 mCameraDevice.createCaptureSession(config);
371 return true;
372 } catch (Exception exception) {
373 Log.w(LOG_TAG, "Failed to create a capture session:" + exception);
374 }
375 reportActivationFailure("Failed to start camera");
376 return false;
377 }
378
379 // A pending activation completes in CameraCaptureSessionStateCallback.onActive().
381 boolean start() {
382 if (mCameraDevice == null || mCaptureSession == null) {
383 Log.w(LOG_TAG, "Cannot start preview without a camera device and capture session");
384 reportActivationFailure("Failed to start camera");
385 return false;
386 }
387
388 try {
389 synchronized (mSyncedMembers) {
390 setRepeatingRequestToPreview();
391 if (!mSyncedMembers.isTakingStillPhoto())
392 mSyncedMembers.mState = SyncedMembers.State.Started;
393 }
394 return true;
395 } catch (CameraAccessException exception) {
396 Log.w(LOG_TAG, "Failed to start preview:" + exception);
397 }
398 reportActivationFailure("Failed to start camera");
399 return false;
400 }
401
403 void stopAndClose() {
404 // Local closedLatch awaited outside the lock below, since mDeviceClosedLatch
405 // can be reassigned by a later open/close
406 CountDownLatch closedLatch = null;
407
408 // Report in-flight still capture as failed
409 boolean abortedStillPhoto = false;
410
411 synchronized (mSyncedMembers) {
412 try {
413 if (mSyncedMembers.isTakingStillPhoto() || mSyncedMembers.mStillCaptureDeferred)
414 abortedStillPhoto = true;
415 if (null != mCaptureSession) {
416 mCaptureSession.close();
417 mCaptureSession = null;
418 }
419 if (null != mCameraDevice) {
420 closedLatch = new CountDownLatch(1);
421 mDeviceClosedLatch = closedLatch;
422 mCameraDevice.close(); // async
423 mCameraDevice = null;
424 }
425 mCameraId = "";
426 mTargetSurfaces.clear();
427 } catch (Exception exception) {
428 Log.w(LOG_TAG, "Failed to stop and close:" + exception);
429 }
430 mSyncedMembers.mState = SyncedMembers.State.Idle;
431 mSyncedMembers.mStillCaptureDeferred = false;
432 }
433
434 if (abortedStillPhoto)
435 onStillPhotoCaptureFailed(getQAndroidCameraPtr());
436
437 reportActivationFailure("Camera was stopped while starting");
438
439 // Wait for onClosed() so background thread can be stopped
440 if (closedLatch != null) {
441 try {
442 if (!closedLatch.await(2, TimeUnit.SECONDS))
443 // NOTE: Fallthrough can race if onClosed never fires
444 Log.w(LOG_TAG, "Timed out waiting for camera device to close");
445 } catch (InterruptedException exception) {
446 Thread.currentThread().interrupt();
447 }
448 }
449 }
450
451 // Called by QAndroidCamera destructor. We should shut down everything and clean
452 // up resources. Any pending jobs on the background threads are flushed.
454 void destroy() {
455 assert(mBackgroundThread != null);
456 assert(Thread.currentThread() != mBackgroundThread);
457
458 // stopAndClose() waits for CameraDevice.onClosed(), which is delivered on the
459 // background thread, so the background thread must be stopped afterwards.
460 stopAndClose();
461 // Blocks this thread until all events are flushed.
462 stopBackgroundThread();
463 mQAndroidCameraPtr = 0;
464 }
465
466 // Can by StillPhotoPrecaptureCallback on background thread in order to finalize a still photo
467 // capture.
468 void finalizeStillPhoto(CameraSettings cameraSettings) throws CameraAccessException
469 {
470 final CaptureRequest.Builder requestBuilder =
471 mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
472 requestBuilder.addTarget(mStillPhotoImageReader.getSurface());
473 requestBuilder.set(
474 CaptureRequest.CONTROL_CAPTURE_INTENT,
475 CaptureRequest.CONTROL_CAPTURE_INTENT_STILL_CAPTURE);
476
477 applyStillPhotoSettingsToCaptureRequestBuilder(
478 requestBuilder,
479 cameraSettings);
480
481 mCaptureSession.capture(
482 requestBuilder.build(),
483 new CameraStillPhotoFinalizerCallback(this),
484 mBackgroundHandler);
485 }
486
487 // This function starts the process of taking a still photo. The final outputted image will
488 // be returned in the still photo image reader.
489 //
490 // Capturing a still photo requires the following steps:
491 // - We need to submit two requests: One repeating request and one single instant request.
492 // The single request triggers the calibration of auto-focus and/or auto-exposure,
493 // depending on what settings are set for the camera. This calibration takes some time,
494 // and we need to wait for these to settle. The logic for waiting for these to settle
495 // happens in the repeating request using the class StillPhotoPrecaptureCallback.
496 // - When the auto-focus and/or auto-exposure has settled, the StillPhotoPrecaptureCallback
497 // will submit a final request to finalize the photo. When the photo is finalized,
498 // we transition back into regular previewing.
499 // - Supporting auto flash is a corner case. When running auto-flash, we might get the result
500 // that no flash is needed, in which case we continue to finalizing the still photo
501 // as usual. If we receive the result that flash is required, we resubmit the still photo
502 // capture commands all over again as if we are using QCamera::FlashModeOn.
504 void beginStillPhotoCapture() {
505 boolean abortCapture = false;
506 synchronized (mSyncedMembers) {
507 if (mSyncedMembers.mState == SyncedMembers.State.Reconfiguring
508 || mSyncedMembers.mStillCaptureDeferred) {
509 mSyncedMembers.mStillCaptureDeferred = true;
510 return;
511 }
512 if (mSyncedMembers.isTakingStillPhoto()) {
513 // Queuing multiple still photos is not implemented.
514 // TODO: We might have to signal to QImageCapture here that capturing failed.
515 Log.w(
516 LOG_TAG,
517 "beginStillPhotoCapture() was called on camera backend while there " +
518 "is already a still photo in progress. This is not supported. Likely Qt " +
519 "developer bug.");
520 return;
521 }
522
523 if (!mSyncedMembers.isStarted()) {
524 Log.w(LOG_TAG, "Can't begin still photo capture, camera is not started");
525 abortCapture = true;
526 } else {
527 mSyncedMembers.mState = SyncedMembers.State.Capturing;
528 }
529 }
530
531 if (abortCapture) {
532 onStillPhotoCaptureFailed(getQAndroidCameraPtr());
533 return;
534 }
535
536 final CameraSettings cameraSettings = atomicCameraSettingsCopy();
537 try {
538 submitNewStillPhotoCapture(cameraSettings);
539 } catch (Exception e) {
540 Log.w(LOG_TAG, "Failed to begin still photo capture: " + e);
541 e.printStackTrace();
542 synchronized (mSyncedMembers) {
543 mSyncedMembers.endStillPhoto();
544 }
545 onStillPhotoCaptureFailed(getQAndroidCameraPtr());
546 // TODO: Try to go back to previewing if applicable. If that fails too, shut down
547 // camera session and report QCamera as inactive.
548 }
549 }
550
551 void submitNewStillPhotoCapture(CameraSettings cameraSettings) throws CameraAccessException
552 {
553 CaptureRequest.Builder requestBuilder = mCameraDevice.createCaptureRequest(
554 CameraDevice.TEMPLATE_STILL_CAPTURE);
555 // Any in-between frames gathered while waiting for still photo, can be sent into
556 // the preview surface.
557 requestBuilder.addTarget(mPreviewSurface);
558
559 applyStillPhotoSettingsToCaptureRequestBuilder(
560 requestBuilder,
561 cameraSettings);
562
563 // We need to trigger the auto-focus and auto-exposure mechanism in a single capture
564 // request, but waiting for it to settle happens in the repeating request.
565 // If configuration ended up with AF_MODE_AUTO, this implies we should trigger the
566 // auto focus to lock in.
567 final boolean triggerAutoFocus = requestBuilder.get(CaptureRequest.CONTROL_AF_MODE)
568 == CaptureResult.CONTROL_AF_MODE_AUTO;
569
570 final Integer aeMode = requestBuilder.get(CaptureRequest.CONTROL_AE_MODE);
571 boolean triggerAutoExposure = aeMode != null
572 && aeMode != CaptureResult.CONTROL_AE_MODE_OFF;
573
574 final CameraStillPhotoPrecaptureCallback precaptureCallback =
575 new CameraStillPhotoPrecaptureCallback(
576 this,
577 cameraSettings,
578 triggerAutoFocus,
579 triggerAutoExposure);
580
581 mCaptureSession.setRepeatingRequest(
582 requestBuilder.build(),
583 precaptureCallback,
584 mBackgroundHandler);
585
586 // Once we have prepared the repeating request that will wait, we re-use the
587 // request-builder and modify it to include the trigger commands, and then submit
588 // it as a one-time request.
589 if (triggerAutoFocus) {
590 requestBuilder.set(
591 CaptureRequest.CONTROL_AF_TRIGGER,
592 CaptureRequest.CONTROL_AF_TRIGGER_START);
593 }
594 if (triggerAutoExposure) {
595 requestBuilder.set(
596 CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER,
597 CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER_START);
598 }
599
600 // TODO: We should have a callback here that can track if still photo fails
601 mCaptureSession.capture(requestBuilder.build(), null, mBackgroundHandler);
602 }
603
605 void saveExifToFile(String path)
606 {
607 if (mExifDataHandler != null)
608 mExifDataHandler.save(path);
609 else
610 Log.e(LOG_TAG, "No Exif data that could be saved to " + path);
611 }
612
613 private Rect getScalerCropRegion(float zoomFactor)
614 {
615 Rect activePixels = mVideoDeviceManager.getActiveArraySize(mCameraId);
616 float zoomRatio = 1.0f;
617 if (zoomFactor != 0.0f)
618 zoomRatio = 1.0f / zoomFactor;
619
620 int croppedWidth = activePixels.width() - (int)(activePixels.width() * zoomRatio);
621 int croppedHeight = activePixels.height() - (int)(activePixels.height() * zoomRatio);
622 return new Rect(croppedWidth/2, croppedHeight/2, activePixels.width() - croppedWidth/2,
623 activePixels.height() - croppedHeight/2);
624 }
625
626 private void applyZoomSettingsToRequestBuilder(CaptureRequest.Builder requBuilder, float zoomFactor)
627 {
628 if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.R) {
629 requBuilder.set(CaptureRequest.SCALER_CROP_REGION, getScalerCropRegion(zoomFactor));
630 } else {
631 requBuilder.set(CaptureRequest.CONTROL_ZOOM_RATIO, zoomFactor);
632 }
633 }
634
636 void zoomTo(float factor)
637 {
638 synchronized (mSyncedMembers) {
639 mSyncedMembers.mCameraSettings.mZoomFactor = factor;
640
641 if (!mSyncedMembers.isStarted()) {
642 // Camera capture has not begun. Zoom will be applied during start().
643 return;
644 }
645
646 // TODO: In the future we can call .setRepeatingRequestToPreview() directly,
647 // which will recreate the request builder as necessary and apply it with all
648 // settings consistently.
649 applyZoomSettingsToRequestBuilder(mPreviewRequestBuilder, factor);
650 mPreviewRequest = mPreviewRequestBuilder.build();
651
652 if (mSyncedMembers.isTakingStillPhoto()) {
653 // Don't set any request if we are in the middle of taking a still photo.
654 // The setting will be applied to the preview after the still photo routine is done.
655 return;
656 }
657 try {
658 mCaptureSession.setRepeatingRequest(
659 mPreviewRequest,
660 mPreviewCaptureCallback,
661 mBackgroundHandler);
662 } catch (Exception exception) {
663 Log.w(LOG_TAG, "Failed to set zoom:" + exception);
664 }
665 }
666 }
667
668 // As described in QPlatformCamera::setFocusMode, this function must apply the focus-distance
669 // whenever the new QCamera::focusMode is set to Manual.
670 // For now, the QtCamera2 implementation only supports Auto and Manual FocusModes.
672 void setFocusMode(int newFocusMode)
673 {
674 // TODO: In the future, not all QCamera::FocusModes will have a 1:1 mapping to the
675 // CONTROL_AF_MODE values. We will need a general solution to translate between
676 // QCamera::FocusModes and the relevant Android Camera2 properties.
677
678 // Expand with more values in the future.
679 // Translate into the corresponding CONTROL_AF_MODE.
680 int newAfMode = 0;
681 if (newFocusMode == 0) // FocusModeAuto
682 newAfMode = CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE;
683 else if (newFocusMode == 5) // FocusModeManual
684 newAfMode = CaptureRequest.CONTROL_AF_MODE_OFF;
685 else {
686 Log.d(
687 LOG_TAG,
688 "received a QCamera::FocusMode from native code that is not recognized. " +
689 "Likely Qt developer bug. Ignoring.");
690 return;
691 }
692
693 // TODO: Ideally this should check if newAfMode is supported through isAfModeAvailable()
694 // but in some situation, mCameraId will be null and therefore isAfModeAvailable will always
695 // return false. One example of this is during QCamera::setCameraDevice.
696 /*
697 if (!isAfModeAvailable(newAfMode)) {
698 Log.d(
699 LOG_TAG,
700 "received a QCamera::FocusMode from native code that is not reported as supported. " +
701 "Likely Qt developer bug. Ignoring.");
702 return;
703 }
704 */
705
706 synchronized (mSyncedMembers) {
707 mSyncedMembers.mCameraSettings.mAFMode = newAfMode;
708
709 // If the camera is not in the started state yet, we skip activating focus-mode here.
710 // Instead it will get applied when the camera is initialized.
711 if (!mSyncedMembers.isStarted())
712 return;
713
714 applyFocusSettingsToCaptureRequestBuilder(
715 mPreviewRequestBuilder,
716 mSyncedMembers.mCameraSettings,
717 false);
718 mPreviewRequest = mPreviewRequestBuilder.build();
719
720 if (mSyncedMembers.isTakingStillPhoto()) {
721 // Don't set any request if we are in the middle of taking a still photo.
722 // The setting will be applied to the preview after the still photo routine is done.
723 return;
724 }
725 try {
726 mCaptureSession.setRepeatingRequest(
727 mPreviewRequest,
728 mPreviewCaptureCallback,
729 mBackgroundHandler);
730 } catch (Exception exception) {
731 Log.w(LOG_TAG, "Failed to set focus mode:" + exception);
732 }
733 }
734 }
735
737 void setFlashMode(String flashMode)
738 {
739 synchronized (mSyncedMembers) {
740 int flashModeValue = mVideoDeviceManager.stringToControlAEMode(flashMode);
741 if (flashModeValue < 0) {
742 Log.w(LOG_TAG, "Unknown flash mode");
743 return;
744 }
745 mSyncedMembers.mCameraSettings.mStillPhotoFlashMode = flashModeValue;
746 }
747 }
748
749 // Sets the focus distance of the camera. Input is the same that accepted by the
750 // QCamera public API. Accepts a float in the range 0,1. Where 0 means as close as possible,
751 // and 1 means infinity.
752 //
753 // This should never be called if the device specifies focus-distance as unsupported.
755 public void setFocusDistance(float distanceInput)
756 {
757 if (distanceInput < 0.f || distanceInput > 1.f) {
758 Log.w(
759 LOG_TAG,
760 "received out-of-bounds value when setting camera focus-distance. " +
761 "Likely Qt developer bug. Ignoring.");
762 return;
763 }
764
765 // TODO: Add error handling to check if current mCameraId supports setting focus-distance.
766 // See setFocusMode relevant issue.
767
768 synchronized (mSyncedMembers) {
769 mSyncedMembers.mCameraSettings.mFocusDistance = distanceInput;
770
771 // If the camera is not in the started state yet, we skip applying any camera-controls
772 // here. It will get applied once the camera is ready.
773 if (!mSyncedMembers.isStarted())
774 return;
775
776 // If we are currently in QCamera::FocusModeManual, we apply the focus distance
777 // immediately. Otherwise, we store the value and apply it during setFocusMode(Manual).
778 if (mSyncedMembers.mCameraSettings.mAFMode == CaptureRequest.CONTROL_AF_MODE_OFF) {
779 applyFocusSettingsToCaptureRequestBuilder(
780 mPreviewRequestBuilder,
781 mSyncedMembers.mCameraSettings,
782 false);
783
784 mPreviewRequest = mPreviewRequestBuilder.build();
785
786 if (mSyncedMembers.isTakingStillPhoto()) {
787 // Don't set any request if we are in the middle of taking a still photo.
788 // The setting will be applied to the preview after the still photo routine is done.
789 return;
790 }
791
792 try {
793 mCaptureSession.setRepeatingRequest(
794 mPreviewRequest,
795 mPreviewCaptureCallback,
796 mBackgroundHandler);
797 } catch (Exception exception) {
798 Log.w(LOG_TAG, "Failed to set focus distance:" + exception);
799 }
800 }
801 }
802 }
803
804 private int getTorchModeValue(boolean mode)
805 {
806 return mode ? CameraMetadata.FLASH_MODE_TORCH : CameraMetadata.FLASH_MODE_OFF;
807 }
808
810 void setTorchMode(boolean torchMode)
811 {
812 synchronized (mSyncedMembers) {
813 mSyncedMembers.mCameraSettings.mTorchMode = getTorchModeValue(torchMode);
814
815 if (mSyncedMembers.isStarted()) {
816 mPreviewRequestBuilder.set(CaptureRequest.FLASH_MODE, mSyncedMembers.mCameraSettings.mTorchMode);
817 mPreviewRequest = mPreviewRequestBuilder.build();
818
819 if (mSyncedMembers.isTakingStillPhoto()) {
820 // Don't set any request if we are in the middle of taking a still photo.
821 // The setting will be applied to the preview after the still photo routine is done.
822 return;
823 }
824
825 try {
826 mCaptureSession.setRepeatingRequest(
827 mPreviewRequest,
828 mPreviewCaptureCallback,
829 mBackgroundHandler);
830 } catch (Exception exception) {
831 Log.w(LOG_TAG, "Failed to set flash mode:" + exception);
832 }
833 }
834 }
835 }
836
837 // Called indirectly from C++ when the QCamera goes active.
838 // Called again from Java camera background thread when a still photo is done.
840 void setRepeatingRequestToPreview() throws CameraAccessException {
841 synchronized (mSyncedMembers) {
842 mPreviewRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_RECORD);
843 mPreviewRequestBuilder.addTarget(mPreviewSurface);
844
845 applyPreviewSettingsToCaptureRequestBuilder(
846 mPreviewRequestBuilder,
847 mSyncedMembers.mCameraSettings);
848
849 mPreviewRequest = mPreviewRequestBuilder.build();
850 mCaptureSession.setRepeatingRequest(
851 mPreviewRequest,
852 mPreviewCaptureCallback,
853 mBackgroundHandler);
854 }
855 }
856
857 private void applyStillPhotoSettingsToCaptureRequestBuilder(
858 CaptureRequest.Builder requestBuilder,
859 CameraSettings cameraSettings)
860 {
861 requestBuilder.set(
862 CaptureRequest.CONTROL_CAPTURE_INTENT,
863 CaptureRequest.CONTROL_CAPTURE_INTENT_STILL_CAPTURE);
864 // Hint for the camera to use automatic modes for auto-focus, auto-exposure and
865 // white-balance where applicable.
866 requestBuilder.set(
867 CaptureRequest.CONTROL_MODE,
868 CaptureRequest.CONTROL_MODE_AUTO);
869 // TODO: We don't support any other exposure modes (such as manual control) yet. Will need
870 // to modify this in the future if we do.
871 requestBuilder.set(
872 CaptureRequest.CONTROL_AE_MODE,
873 CaptureRequest.CONTROL_AE_MODE_ON);
874
875 applyZoomSettingsToRequestBuilder(requestBuilder, cameraSettings.mZoomFactor);
876
877 applyFocusSettingsToCaptureRequestBuilder(
878 requestBuilder,
879 cameraSettings,
880 true);
881
882 // Ideally we would pass AE_MODE_ON_ALWAYS_FLASH straight to the camera and let it
883 // control the flash unit. This has proven unreliable during testing. Instead we use
884 // regular CONTROL_AE_MODE_ON and force the flash on.
885 if (cameraSettings.mStillPhotoFlashMode == CaptureRequest.CONTROL_AE_MODE_ON_ALWAYS_FLASH) {
886 requestBuilder.set(
887 CaptureRequest.CONTROL_AE_MODE,
888 CaptureRequest.CONTROL_AE_MODE_ON);
889 // Ideally, this should be set to SINGLE, only when we are finalizing the capture.
890 // However, this causes an issue on some Motorola devices where the flash will have
891 // wrong timing compared to the capture, and we will end up with no flash in the final
892 // photo.
893 requestBuilder.set(
894 CaptureRequest.FLASH_MODE,
895 CaptureRequest.FLASH_MODE_TORCH);
896 } else if (cameraSettings.mStillPhotoFlashMode == CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH) {
897 requestBuilder.set(
898 CaptureRequest.CONTROL_AE_MODE,
899 CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
900 }
901 }
902
903 private void applyPreviewSettingsToCaptureRequestBuilder(
904 CaptureRequest.Builder requestBuilder,
905 CameraSettings cameraSettings)
906 {
907 requestBuilder.set(CaptureRequest.CONTROL_CAPTURE_INTENT, CameraMetadata.CONTROL_CAPTURE_INTENT_VIDEO_RECORD);
908
909 applyFocusSettingsToCaptureRequestBuilder(
910 requestBuilder,
911 cameraSettings,
912 false);
913
914 // TODO: Check if AE_MODE_ON is available
915 requestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON);
916 requestBuilder.set(CaptureRequest.FLASH_MODE, cameraSettings.mTorchMode);
917
918 applyZoomSettingsToRequestBuilder(requestBuilder, cameraSettings.mZoomFactor);
919 if (cameraSettings.mFpsRange != null) {
920 requestBuilder.set(
921 CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE,
922 cameraSettings.mFpsRange);
923 }
924
925 // TODO: This should likely not be set because trigger-events should only be submitted
926 // once. Meanwhile, this request will be used for preview which is repeating.
927 mPreviewRequestBuilder.set(
928 CaptureRequest.CONTROL_AF_TRIGGER,
929 CameraMetadata.CONTROL_AF_TRIGGER_IDLE);
930 mPreviewRequestBuilder.set(
931 CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER,
932 CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER_IDLE);
933 }
934
935 // If taking still photo, remember to trigger auto-focus calibration if CONTROL_AF_MODE is set
936 // to CONTROL_AF_MODE_AUTO.
937 void applyFocusSettingsToCaptureRequestBuilder(
938 CaptureRequest.Builder requestBuilder,
939 CameraSettings cameraSettings,
940 boolean stillPhoto)
941 {
942 int desiredAfMode = cameraSettings.mAFMode;
943 // During still photo, If the camera settings is set to CONTINUOUS_PICTURE, this is an
944 // indication that we are in QCamera::FocusModeAuto. In which case we should be using
945 // AF_MODE_AUTO, which lets us lock in focus once and keep it there until still photo
946 // is done.
947 if (stillPhoto && desiredAfMode == CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE) {
948 desiredAfMode = CaptureRequest.CONTROL_AF_MODE_AUTO;
949 }
950
951 if (!isAfModeAvailable(desiredAfMode)) {
952 // If we don't support our desired AF_MODE, fallback to AF_MODE_OFF if that is
953 // available. Otherwise don't set any focus-mode, leave it as default and
954 // undefined state. Note: Setting CONTROL_AF_MODE to null is illegal and will cause an
955 // exception thrown.
956 if (isAfModeAvailable(CaptureRequest.CONTROL_AF_MODE_OFF)) {
957 requestBuilder.set(
958 CaptureRequest.CONTROL_AF_MODE,
959 CaptureRequest.CONTROL_AF_MODE_OFF);
960 }
961
962 requestBuilder.set(CaptureRequest.LENS_FOCUS_DISTANCE, null);
963 return;
964 }
965
966 requestBuilder.set(CaptureRequest.CONTROL_AF_MODE, desiredAfMode);
967
968 // Set correct lens focus distance if we are in QCamera::FocusModeManual
969 if (desiredAfMode == CaptureRequest.CONTROL_AF_MODE_OFF) {
970 final float lensFocusDistance = calcLensFocusDistanceFromQCameraFocusDistance(
971 cameraSettings.mFocusDistance);
972 if (lensFocusDistance < 0) {
973 Log.w(
974 LOG_TAG,
975 "Tried to apply FocusModeManual on a camera that doesn't support "
976 + "setting lens distance. Likely Qt developer bug. Ignoring.");
977 } else {
978 requestBuilder.set(CaptureRequest.LENS_FOCUS_DISTANCE, lensFocusDistance);
979 }
980 } else {
981 requestBuilder.set(CaptureRequest.LENS_FOCUS_DISTANCE, null);
982 }
983 }
984
985 // Calculates the CaptureRequest.LENS_FOCUS_DISTANCE equivalent given a QCamera::focusDistance
986 // value. Returns -1 on failure, such as if camera does not support setting manual focus
987 // distance.
988 private float calcLensFocusDistanceFromQCameraFocusDistance(float qCameraFocusDistance) {
989 float lensMinimumFocusDistance =
990 mVideoDeviceManager.getLensInfoMinimumFocusDistance(mCameraId);
991 if (lensMinimumFocusDistance <= 0)
992 return -1;
993
994 // Input is 0 to 1, with 0 meaning as close as possible.
995 // Android Camera2 expects it to be in the range [0, minimumFocusDistance]
996 // where higher values means closer to the camera and 0 means as far away as possible.
997 // We need to map to this range.
998 return (1.f - qCameraFocusDistance) * lensMinimumFocusDistance;
999 }
1000
1001 // Helper function to check if a given CaptureRequest.CONTROL_AF_MODE is supported on this
1002 // device
1003 private boolean isAfModeAvailable(int afMode) {
1004 if (mVideoDeviceManager == null || mCameraId == null || mCameraId.isEmpty())
1005 return false;
1006 return mVideoDeviceManager.isAfModeAvailable(mCameraId, afMode);
1007 }
1008
1009 // AF_STATE_NOT_FOCUSED_LOCKED implies we tried to calibrate the auto-focus, but failed
1010 // to establish focus and the hardware has now given up and locked the focus.
1011 static boolean afStateIsReadyForCapture(Integer afState) {
1012 return afState == null
1013 || afState == CaptureResult.CONTROL_AF_STATE_FOCUSED_LOCKED
1014 || afState == CaptureResult.CONTROL_AF_STATE_NOT_FOCUSED_LOCKED;
1015 }
1016
1017 static boolean aeStateIsReadyForCapture(Integer aeState) {
1018 return aeState == null
1019 || aeState == CaptureResult.CONTROL_AE_STATE_CONVERGED
1020 || aeState == CaptureResult.CONTROL_AE_STATE_FLASH_REQUIRED;
1021 }
1022}
\inmodule QtGui
QPainter Context
#define LOG_TAG
Definition extract.cpp:14
Catch::Generators::GeneratorWrapper< T > handler(Catch::Generators::GeneratorWrapper< T > &&generator)
Returns a generator wrapping generator that ensures that changes its semantics so that the first call...
Napi::String String
Definition qnapi_p.h:70
QImageReader reader("image.png")
[1]
#define assert
DBusConnection const char DBusError DBusBusType DBusError return DBusConnection DBusHandleMessageFunction void DBusFreeFunction return DBusConnection return DBusConnection return const char DBusError return DBusConnection DBusMessage dbus_uint32_t return DBusConnection dbus_bool_t DBusConnection DBusAddWatchFunction DBusRemoveWatchFunction DBusWatchToggledFunction void DBusFreeFunction return DBusConnection DBusDispatchStatusFunction void DBusFreeFunction DBusTimeout return DBusTimeout return DBusWatch return DBusWatch unsigned int return DBusError const DBusError return const DBusMessage return DBusMessage return DBusMessage return DBusMessage return DBusMessage return DBusMessage return DBusMessageIter int const void return DBusMessageIter DBusMessageIter return DBusMessageIter void DBusMessageIter void int return DBusMessage DBusMessageIter return DBusMessageIter return DBusMessageIter DBusMessageIter const char const char const char const char return DBusMessage return DBusMessage const char return DBusMessage dbus_bool_t return DBusMessage dbus_uint32_t return DBusMessage void
DBusConnection const char DBusError * error
EGLConfig config
[3]
OutputConfiguration
GLenum mode
GLuint start
GLfloat GLfloat f
[26]
GLint GLsizei width
GLsizei const GLchar *const * path
@ Handler
QFrame frame
[0]
file open(QIODevice::ReadOnly)
QNetworkRequest request(url)
[0]