Debian Codegraph @

core/java/android/hardware/camera2/impl/CameraExtensionSessionImpl.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package android.hardware.camera2.impl;
18
19 import android.annotation.NonNull;
20 import android.annotation.Nullable;
21 import android.annotation.RequiresPermission;
22 import android.content.Context;
23 import android.graphics.ImageFormat;
24 import android.graphics.SurfaceTexture;
25 import android.hardware.HardwareBuffer;
26 import android.hardware.SyncFence;
27 import android.hardware.camera2.CameraAccessException;
28 import android.hardware.camera2.CameraCaptureSession;
29 import android.hardware.camera2.CameraCharacteristics;
30 import android.hardware.camera2.CameraDevice;
31 import android.hardware.camera2.CameraExtensionCharacteristics;
32 import android.hardware.camera2.CameraExtensionSession;
33 import android.hardware.camera2.CameraManager;
34 import android.hardware.camera2.CaptureFailure;
35 import android.hardware.camera2.CaptureRequest;
36 import android.hardware.camera2.CaptureResult;
37 import android.hardware.camera2.TotalCaptureResult;
38 import android.hardware.camera2.extension.CaptureBundle;
39 import android.hardware.camera2.extension.CaptureStageImpl;
40 import android.hardware.camera2.extension.ICaptureProcessorImpl;
41 import android.hardware.camera2.extension.IImageCaptureExtenderImpl;
42 import android.hardware.camera2.extension.IInitializeSessionCallback;
43 import android.hardware.camera2.extension.IPreviewExtenderImpl;
44 import android.hardware.camera2.extension.IProcessResultImpl;
45 import android.hardware.camera2.extension.IRequestUpdateProcessorImpl;
46 import android.hardware.camera2.extension.ParcelImage;
47 import android.hardware.camera2.params.DynamicRangeProfiles;
48 import android.hardware.camera2.params.ExtensionSessionConfiguration;
49 import android.hardware.camera2.params.OutputConfiguration;
50 import android.hardware.camera2.params.SessionConfiguration;
51 import android.hardware.camera2.utils.SurfaceUtils;
52 import android.media.Image;
53 import android.media.ImageReader;
54 import android.media.ImageWriter;
55 import android.os.Binder;
56 import android.os.Handler;
57 import android.os.HandlerThread;
58 import android.os.RemoteException;
59 import android.util.Log;
60 import android.util.LongSparseArray;
61 import android.util.Pair;
62 import android.util.Size;
63 import android.view.Surface;
64
65 import java.io.Closeable;
66 import java.io.IOException;
67 import java.util.ArrayList;
68 import java.util.HashMap;
69 import java.util.List;
70 import java.util.Map;
71 import java.util.Set;
72 import java.util.concurrent.Executor;
73
74 public final class CameraExtensionSessionImpl extends CameraExtensionSession {
75 private static final int PREVIEW_QUEUE_SIZE = 10;
76 private static final String TAG = "CameraExtensionSessionImpl";
77
78 private final Executor mExecutor;
79 private final CameraDevice mCameraDevice;
80 private final long mExtensionClientId;
81 private final IImageCaptureExtenderImpl mImageExtender;
82 private final IPreviewExtenderImpl mPreviewExtender;
83 private final Handler mHandler;
84 private final HandlerThread mHandlerThread;
85 private final StateCallback mCallbacks;
86 private final List<Size> mSupportedPreviewSizes;
87 private final InitializeSessionHandler mInitializeHandler;
88 private final int mSessionId;
89 private final Set<CaptureRequest.Key> mSupportedRequestKeys;
90 private final Set<CaptureResult.Key> mSupportedResultKeys;
91 private boolean mCaptureResultsSupported;
92
93 private CameraCaptureSession mCaptureSession = null;
94 private Surface mCameraRepeatingSurface, mClientRepeatingRequestSurface;
95 private Surface mCameraBurstSurface, mClientCaptureSurface;
96 private ImageReader mRepeatingRequestImageReader = null;
97 private ImageReader mBurstCaptureImageReader = null;
98 private ImageReader mStubCaptureImageReader = null;
99 private ImageWriter mRepeatingRequestImageWriter = null;
100 private CameraOutputImageCallback mRepeatingRequestImageCallback = null;
101 private CameraOutputImageCallback mBurstCaptureImageCallback = null;
102
103 private CameraExtensionJpegProcessor mImageJpegProcessor = null;
104 private ICaptureProcessorImpl mImageProcessor = null;
105 private CameraExtensionForwardProcessor mPreviewImageProcessor = null;
106 private IRequestUpdateProcessorImpl mPreviewRequestUpdateProcessor = null;
107 private int mPreviewProcessorType = IPreviewExtenderImpl.PROCESSOR_TYPE_NONE;
108
109 private boolean mInitialized;
110 // Enable/Disable internal preview/(repeating request). Extensions expect
111 // that preview/(repeating request) is enabled and active at any point in time.
112 // In case the client doesn't explicitly enable repeating requests, the framework
113 // will do so internally.
114 private boolean mInternalRepeatingRequestEnabled = true;
115
116 // Lock to synchronize cross-thread access to device public interface
117 final Object mInterfaceLock;
118
119 private static int nativeGetSurfaceFormat(Surface surface) {
120 return SurfaceUtils.getSurfaceFormat(surface);
121 }
122
123 /**
124 * @hide
125 */
126 @RequiresPermission(android.Manifest.permission.CAMERA)
127 public static CameraExtensionSessionImpl createCameraExtensionSession(
128 @NonNull android.hardware.camera2.impl.CameraDeviceImpl cameraDevice,
129 @NonNull Context ctx,
130 @NonNull ExtensionSessionConfiguration config,
131 int sessionId)
132 throws CameraAccessException, RemoteException {
133 long clientId = CameraExtensionCharacteristics.registerClient(ctx);
134 if (clientId < 0) {
135 throw new UnsupportedOperationException("Unsupported extension!");
136 }
137
138 String cameraId = cameraDevice.getId();
139 CameraManager manager = ctx.getSystemService(CameraManager.class);
140 CameraCharacteristics chars = manager.getCameraCharacteristics(cameraId);
141 CameraExtensionCharacteristics extensionChars = new CameraExtensionCharacteristics(ctx,
142 cameraId, chars);
143
144 if (!CameraExtensionCharacteristics.isExtensionSupported(cameraDevice.getId(),
145 config.getExtension(), chars)) {
146 throw new UnsupportedOperationException("Unsupported extension type: " +
147 config.getExtension());
148 }
149
150 if (config.getOutputConfigurations().isEmpty() ||
151 config.getOutputConfigurations().size() > 2) {
152 throw new IllegalArgumentException("Unexpected amount of output surfaces, received: " +
153 config.getOutputConfigurations().size() + " expected <= 2");
154 }
155
156 for (OutputConfiguration c : config.getOutputConfigurations()) {
157 if (c.getDynamicRangeProfile() != DynamicRangeProfiles.STANDARD) {
158 throw new IllegalArgumentException("Unsupported dynamic range profile: " +
159 c.getDynamicRangeProfile());
160 }
161 if (c.getStreamUseCase() !=
162 CameraCharacteristics.SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT) {
163 throw new IllegalArgumentException("Unsupported stream use case: " +
164 c.getStreamUseCase());
165 }
166 }
167
168 Pair<IPreviewExtenderImpl, IImageCaptureExtenderImpl> extenders =
169 CameraExtensionCharacteristics.initializeExtension(config.getExtension());
170
171 int suitableSurfaceCount = 0;
172 List<Size> supportedPreviewSizes = extensionChars.getExtensionSupportedSizes(
173 config.getExtension(), SurfaceTexture.class);
174 Surface repeatingRequestSurface = CameraExtensionUtils.getRepeatingRequestSurface(
175 config.getOutputConfigurations(), supportedPreviewSizes);
176 if (repeatingRequestSurface != null) {
177 suitableSurfaceCount++;
178 }
179
180 HashMap<Integer, List<Size>> supportedCaptureSizes = new HashMap<>();
181 for (int format : CameraExtensionUtils.SUPPORTED_CAPTURE_OUTPUT_FORMATS) {
182 List<Size> supportedSizes = extensionChars.getExtensionSupportedSizes(
183 config.getExtension(), format);
184 if (supportedSizes != null) {
185 supportedCaptureSizes.put(format, supportedSizes);
186 }
187 }
188 Surface burstCaptureSurface = CameraExtensionUtils.getBurstCaptureSurface(
189 config.getOutputConfigurations(), supportedCaptureSizes);
190 if (burstCaptureSurface != null) {
191 suitableSurfaceCount++;
192 }
193
194 if (suitableSurfaceCount != config.getOutputConfigurations().size()) {
195 throw new IllegalArgumentException("One or more unsupported output surfaces found!");
196 }
197
198 extenders.first.init(cameraId, chars.getNativeMetadata());
199 extenders.first.onInit(cameraId, chars.getNativeMetadata());
200 extenders.second.init(cameraId, chars.getNativeMetadata());
201 extenders.second.onInit(cameraId, chars.getNativeMetadata());
202
203 CameraExtensionSessionImpl session = new CameraExtensionSessionImpl(
204 extenders.second,
205 extenders.first,
206 supportedPreviewSizes,
207 clientId,
208 cameraDevice,
209 repeatingRequestSurface,
210 burstCaptureSurface,
211 config.getStateCallback(),
212 config.getExecutor(),
213 sessionId,
214 extensionChars.getAvailableCaptureRequestKeys(config.getExtension()),
215 extensionChars.getAvailableCaptureResultKeys(config.getExtension()));
216
217 session.initialize();
218
219 return session;
220 }
221
222 public CameraExtensionSessionImpl(@NonNull IImageCaptureExtenderImpl imageExtender,
223 @NonNull IPreviewExtenderImpl previewExtender,
224 @NonNull List<Size> previewSizes,
225 long extensionClientId,
226 @NonNull android.hardware.camera2.impl.CameraDeviceImpl cameraDevice,
227 @Nullable Surface repeatingRequestSurface,
228 @Nullable Surface burstCaptureSurface,
229 @NonNull StateCallback callback,
230 @NonNull Executor executor,
231 int sessionId,
232 @NonNull Set<CaptureRequest.Key> requestKeys,
233 @Nullable Set<CaptureResult.Key> resultKeys) {
234 mExtensionClientId = extensionClientId;
235 mImageExtender = imageExtender;
236 mPreviewExtender = previewExtender;
237 mCameraDevice = cameraDevice;
238 mCallbacks = callback;
239 mExecutor = executor;
240 mClientRepeatingRequestSurface = repeatingRequestSurface;
241 mClientCaptureSurface = burstCaptureSurface;
242 mSupportedPreviewSizes = previewSizes;
243 mHandlerThread = new HandlerThread(TAG);
244 mHandlerThread.start();
245 mHandler = new Handler(mHandlerThread.getLooper());
246 mInitialized = false;
247 mInitializeHandler = new InitializeSessionHandler();
248 mSessionId = sessionId;
249 mSupportedRequestKeys = requestKeys;
250 mSupportedResultKeys = resultKeys;
251 mCaptureResultsSupported = !resultKeys.isEmpty();
252 mInterfaceLock = cameraDevice.mInterfaceLock;
253 }
254
255 private void initializeRepeatingRequestPipeline() throws RemoteException {
256 CameraExtensionUtils.SurfaceInfo repeatingSurfaceInfo =
257 new CameraExtensionUtils.SurfaceInfo();
258 mPreviewProcessorType = mPreviewExtender.getProcessorType();
259 if (mClientRepeatingRequestSurface != null) {
260 repeatingSurfaceInfo = CameraExtensionUtils.querySurface(
261 mClientRepeatingRequestSurface);
262 } else {
263 // Make the intermediate surface behave as any regular 'SurfaceTexture'
264 CameraExtensionUtils.SurfaceInfo captureSurfaceInfo = CameraExtensionUtils.querySurface(
265 mClientCaptureSurface);
266 Size captureSize = new Size(captureSurfaceInfo.mWidth, captureSurfaceInfo.mHeight);
267 Size previewSize = findSmallestAspectMatchedSize(mSupportedPreviewSizes, captureSize);
268 repeatingSurfaceInfo.mWidth = previewSize.getWidth();
269 repeatingSurfaceInfo.mHeight = previewSize.getHeight();
270 repeatingSurfaceInfo.mUsage = HardwareBuffer.USAGE_GPU_SAMPLED_IMAGE;
271 }
272
273 if (mPreviewProcessorType == IPreviewExtenderImpl.PROCESSOR_TYPE_IMAGE_PROCESSOR) {
274 try {
275 mPreviewImageProcessor = new CameraExtensionForwardProcessor(
276 mPreviewExtender.getPreviewImageProcessor(), repeatingSurfaceInfo.mFormat,
277 repeatingSurfaceInfo.mUsage, mHandler);
278 } catch (ClassCastException e) {
279 throw new UnsupportedOperationException("Failed casting preview processor!");
280 }
281 mPreviewImageProcessor.onImageFormatUpdate(
282 CameraExtensionCharacteristics.PROCESSING_INPUT_FORMAT);
283 mPreviewImageProcessor.onResolutionUpdate(new Size(repeatingSurfaceInfo.mWidth,
284 repeatingSurfaceInfo.mHeight));
285 mPreviewImageProcessor.onOutputSurface(null, -1);
286 mRepeatingRequestImageReader = ImageReader.newInstance(repeatingSurfaceInfo.mWidth,
287 repeatingSurfaceInfo.mHeight,
288 CameraExtensionCharacteristics.PROCESSING_INPUT_FORMAT, PREVIEW_QUEUE_SIZE,
289 repeatingSurfaceInfo.mUsage);
290 mCameraRepeatingSurface = mRepeatingRequestImageReader.getSurface();
291 } else if (mPreviewProcessorType ==
292 IPreviewExtenderImpl.PROCESSOR_TYPE_REQUEST_UPDATE_ONLY) {
293 try {
294 mPreviewRequestUpdateProcessor = mPreviewExtender.getRequestUpdateProcessor();
295 } catch (ClassCastException e) {
296 throw new UnsupportedOperationException("Failed casting preview processor!");
297 }
298 mRepeatingRequestImageReader = ImageReader.newInstance(repeatingSurfaceInfo.mWidth,
299 repeatingSurfaceInfo.mHeight,
300 CameraExtensionCharacteristics.NON_PROCESSING_INPUT_FORMAT,
301 PREVIEW_QUEUE_SIZE, repeatingSurfaceInfo.mUsage);
302 mCameraRepeatingSurface = mRepeatingRequestImageReader.getSurface();
303 android.hardware.camera2.extension.Size sz =
304 new android.hardware.camera2.extension.Size();
305 sz.width = repeatingSurfaceInfo.mWidth;
306 sz.height = repeatingSurfaceInfo.mHeight;
307 mPreviewRequestUpdateProcessor.onResolutionUpdate(sz);
308 mPreviewRequestUpdateProcessor.onImageFormatUpdate(
309 CameraExtensionCharacteristics.NON_PROCESSING_INPUT_FORMAT);
310 } else {
311 mRepeatingRequestImageReader = ImageReader.newInstance(repeatingSurfaceInfo.mWidth,
312 repeatingSurfaceInfo.mHeight,
313 CameraExtensionCharacteristics.NON_PROCESSING_INPUT_FORMAT,
314 PREVIEW_QUEUE_SIZE, repeatingSurfaceInfo.mUsage);
315 mCameraRepeatingSurface = mRepeatingRequestImageReader.getSurface();
316 }
317 mRepeatingRequestImageCallback = new CameraOutputImageCallback(
318 mRepeatingRequestImageReader);
319 mRepeatingRequestImageReader
320 .setOnImageAvailableListener(mRepeatingRequestImageCallback, mHandler);
321 }
322
323 private void initializeBurstCapturePipeline() throws RemoteException {
324 mImageProcessor = mImageExtender.getCaptureProcessor();
325 if ((mImageProcessor == null) && (mImageExtender.getMaxCaptureStage() != 1)) {
326 throw new UnsupportedOperationException("Multiple stages expected without" +
327 " a valid capture processor!");
328 }
329
330 if (mImageProcessor != null) {
331 if (mClientCaptureSurface != null) {
332 CameraExtensionUtils.SurfaceInfo surfaceInfo = CameraExtensionUtils.querySurface(
333 mClientCaptureSurface);
334 if (surfaceInfo.mFormat == ImageFormat.JPEG) {
335 mImageJpegProcessor = new CameraExtensionJpegProcessor(mImageProcessor);
336 mImageProcessor = mImageJpegProcessor;
337 }
338 mBurstCaptureImageReader = ImageReader.newInstance(surfaceInfo.mWidth,
339 surfaceInfo.mHeight, CameraExtensionCharacteristics.PROCESSING_INPUT_FORMAT,
340 mImageExtender.getMaxCaptureStage());
341 } else {
342 // The client doesn't intend to trigger multi-frame capture, however the
343 // image extender still needs to get initialized and the camera still capture
344 // stream configured for the repeating request processing to work.
345 mBurstCaptureImageReader = ImageReader.newInstance(
346 mRepeatingRequestImageReader.getWidth(),
347 mRepeatingRequestImageReader.getHeight(),
348 CameraExtensionCharacteristics.PROCESSING_INPUT_FORMAT, 1);
349 // The still capture output is not going to be used but we still need a valid
350 // surface to register.
351 mStubCaptureImageReader = ImageReader.newInstance(
352 mRepeatingRequestImageReader.getWidth(),
353 mRepeatingRequestImageReader.getHeight(),
354 CameraExtensionCharacteristics.PROCESSING_INPUT_FORMAT, 1);
355 mImageProcessor.onOutputSurface(mStubCaptureImageReader.getSurface(),
356 CameraExtensionCharacteristics.PROCESSING_INPUT_FORMAT);
357 }
358
359 mBurstCaptureImageCallback = new CameraOutputImageCallback(mBurstCaptureImageReader);
360 mBurstCaptureImageReader.setOnImageAvailableListener(mBurstCaptureImageCallback,
361 mHandler);
362 mCameraBurstSurface = mBurstCaptureImageReader.getSurface();
363 android.hardware.camera2.extension.Size sz =
364 new android.hardware.camera2.extension.Size();
365 sz.width = mBurstCaptureImageReader.getWidth();
366 sz.height = mBurstCaptureImageReader.getHeight();
367 mImageProcessor.onResolutionUpdate(sz);
368 mImageProcessor.onImageFormatUpdate(mBurstCaptureImageReader.getImageFormat());
369 } else {
370 if (mClientCaptureSurface != null) {
371 // Redirect camera output directly in to client output surface
372 mCameraBurstSurface = mClientCaptureSurface;
373 } else {
374 // The client doesn't intend to trigger multi-frame capture, however the
375 // image extender still needs to get initialized and the camera still capture
376 // stream configured for the repeating request processing to work.
377 mBurstCaptureImageReader = ImageReader.newInstance(
378 mRepeatingRequestImageReader.getWidth(),
379 mRepeatingRequestImageReader.getHeight(),
380 // Camera devices accept only Jpeg output if the image processor is null
381 ImageFormat.JPEG, 1);
382 mCameraBurstSurface = mBurstCaptureImageReader.getSurface();
383 }
384 }
385 }
386
387 private void finishPipelineInitialization() throws RemoteException {
388 if (mClientRepeatingRequestSurface != null) {
389 if (mPreviewProcessorType == IPreviewExtenderImpl.PROCESSOR_TYPE_REQUEST_UPDATE_ONLY) {
390 mPreviewRequestUpdateProcessor.onOutputSurface(mClientRepeatingRequestSurface,
391 nativeGetSurfaceFormat(mClientRepeatingRequestSurface));
392 mRepeatingRequestImageWriter = ImageWriter.newInstance(
393 mClientRepeatingRequestSurface,
394 PREVIEW_QUEUE_SIZE,
395 CameraExtensionCharacteristics.NON_PROCESSING_INPUT_FORMAT);
396 } else if (mPreviewProcessorType == IPreviewExtenderImpl.PROCESSOR_TYPE_NONE) {
397 mRepeatingRequestImageWriter = ImageWriter.newInstance(
398 mClientRepeatingRequestSurface,
399 PREVIEW_QUEUE_SIZE,
400 CameraExtensionCharacteristics.NON_PROCESSING_INPUT_FORMAT);
401 }
402 }
403 if ((mImageProcessor != null) && (mClientCaptureSurface != null)) {
404 CameraExtensionUtils.SurfaceInfo surfaceInfo = CameraExtensionUtils.querySurface(
405 mClientCaptureSurface);
406 mImageProcessor.onOutputSurface(mClientCaptureSurface, surfaceInfo.mFormat);
407 }
408 }
409
410 /**
411 * @hide
412 */
413 public synchronized void initialize() throws CameraAccessException, RemoteException {
414 if (mInitialized) {
415 Log.d(TAG,
416 "Session already initialized");
417 return;
418 }
419
420 ArrayList<CaptureStageImpl> sessionParamsList = new ArrayList<>();
421 ArrayList<OutputConfiguration> outputList = new ArrayList<>();
422 initializeRepeatingRequestPipeline();
423 outputList.add(new OutputConfiguration(mCameraRepeatingSurface));
424 CaptureStageImpl previewSessionParams = mPreviewExtender.onPresetSession();
425 if (previewSessionParams != null) {
426 sessionParamsList.add(previewSessionParams);
427 }
428 initializeBurstCapturePipeline();
429 outputList.add(new OutputConfiguration(mCameraBurstSurface));
430 CaptureStageImpl stillCaptureSessionParams = mImageExtender.onPresetSession();
431 if (stillCaptureSessionParams != null) {
432 sessionParamsList.add(stillCaptureSessionParams);
433 }
434
435 SessionConfiguration sessionConfig = new SessionConfiguration(
436 SessionConfiguration.SESSION_REGULAR,
437 outputList,
438 new CameraExtensionUtils.HandlerExecutor(mHandler),
439 new SessionStateHandler());
440
441 if (!sessionParamsList.isEmpty()) {
442 CaptureRequest sessionParamRequest = createRequest(mCameraDevice, sessionParamsList,
443 null, CameraDevice.TEMPLATE_PREVIEW);
444 sessionConfig.setSessionParameters(sessionParamRequest);
445 }
446
447 mCameraDevice.createCaptureSession(sessionConfig);
448 }
449
450 @Override
451 public @NonNull CameraDevice getDevice() {
452 synchronized (mInterfaceLock) {
453 return mCameraDevice;
454 }
455 }
456
457 @Override
458 public int setRepeatingRequest(@NonNull CaptureRequest request,
459 @NonNull Executor executor,
460 @NonNull ExtensionCaptureCallback listener)
461 throws CameraAccessException {
462 synchronized (mInterfaceLock) {
463 if (!mInitialized) {
464 throw new IllegalStateException("Uninitialized component");
465 }
466
467 if (mClientRepeatingRequestSurface == null) {
468 throw new IllegalArgumentException("No registered preview surface");
469 }
470
471 if (!request.containsTarget(mClientRepeatingRequestSurface) ||
472 (request.getTargets().size() != 1)) {
473 throw new IllegalArgumentException("Invalid repeating request output target!");
474 }
475
476 mInternalRepeatingRequestEnabled = false;
477 try {
478 return setRepeatingRequest(mPreviewExtender.getCaptureStage(),
479 new PreviewRequestHandler(request, executor, listener,
480 mRepeatingRequestImageCallback), request);
481 } catch (RemoteException e) {
482 Log.e(TAG, "Failed to set repeating request! Extension service does not "
483 + "respond");
484 throw new CameraAccessException(CameraAccessException.CAMERA_ERROR);
485 }
486 }
487 }
488
489 private ArrayList<CaptureStageImpl> compileInitialRequestList() {
490 ArrayList<CaptureStageImpl> captureStageList = new ArrayList<>();
491 try {
492 CaptureStageImpl initialPreviewParams = mPreviewExtender.onEnableSession();
493 if (initialPreviewParams != null) {
494 captureStageList.add(initialPreviewParams);
495 }
496
497 CaptureStageImpl initialStillCaptureParams = mImageExtender.onEnableSession();
498 if (initialStillCaptureParams != null) {
499 captureStageList.add(initialStillCaptureParams);
500 }
501 } catch (RemoteException e) {
502 Log.e(TAG, "Failed to initialize session parameters! Extension service does not"
503 + " respond!");
504 }
505
506 return captureStageList;
507 }
508
509 private List<CaptureRequest> createBurstRequest(CameraDevice cameraDevice,
510 List<CaptureStageImpl> captureStageList, CaptureRequest clientRequest,
511 Surface target, int captureTemplate, Map<CaptureRequest, Integer> captureMap) {
512 CaptureRequest.Builder requestBuilder;
513 ArrayList<CaptureRequest> ret = new ArrayList<>();
514 for (CaptureStageImpl captureStage : captureStageList) {
515 try {
516 requestBuilder = cameraDevice.createCaptureRequest(captureTemplate);
517 } catch (CameraAccessException e) {
518 return null;
519 }
520
521 // This will guarantee that client configured
522 // parameters always have the highest priority.
523 for (CaptureRequest.Key requestKey : mSupportedRequestKeys){
524 Object value = clientRequest.get(requestKey);
525 if (value != null) {
526 captureStage.parameters.set(requestKey, value);
527 }
528 }
529
530 requestBuilder.addTarget(target);
531 CaptureRequest request = requestBuilder.build();
532 CameraMetadataNative.update(request.getNativeMetadata(), captureStage.parameters);
533 ret.add(request);
534 if (captureMap != null) {
535 captureMap.put(request, captureStage.id);
536 }
537 }
538
539 return ret;
540 }
541
542 private CaptureRequest createRequest(CameraDevice cameraDevice,
543 List<CaptureStageImpl> captureStageList, Surface target, int captureTemplate,
544 CaptureRequest clientRequest) throws CameraAccessException {
545 CaptureRequest.Builder requestBuilder;
546 requestBuilder = cameraDevice.createCaptureRequest(captureTemplate);
547 if (target != null) {
548 requestBuilder.addTarget(target);
549 }
550
551 CaptureRequest ret = requestBuilder.build();
552 CameraMetadataNative nativeMeta = ret.getNativeMetadata();
553 for (CaptureStageImpl captureStage : captureStageList) {
554 if (captureStage != null) {
555 CameraMetadataNative.update(nativeMeta, captureStage.parameters);
556 }
557 }
558
559 if (clientRequest != null) {
560 // This will guarantee that client configured
561 // parameters always have the highest priority.
562 for (CaptureRequest.Key requestKey : mSupportedRequestKeys) {
563 Object value = clientRequest.get(requestKey);
564 if (value != null) {
565 nativeMeta.set(requestKey, value);
566 }
567 }
568 }
569
570 return ret;
571 }
572
573 private CaptureRequest createRequest(CameraDevice cameraDevice,
574 List<CaptureStageImpl> captureStageList,
575 Surface target,
576 int captureTemplate) throws CameraAccessException {
577 return createRequest(cameraDevice, captureStageList, target, captureTemplate,
578 /*clientRequest*/ null);
579 }
580
581 @Override
582 public int capture(@NonNull CaptureRequest request,
583 @NonNull Executor executor,
584 @NonNull ExtensionCaptureCallback listener) throws CameraAccessException {
585 if (!mInitialized) {
586 throw new IllegalStateException("Uninitialized component");
587 }
588
589 if (request.getTargets().size() != 1) {
590 throw new IllegalArgumentException("Single capture to both preview & still capture " +
591 "outputs target is not supported!");
592 }
593
594 int seqId = -1;
595 if ((mClientCaptureSurface != null) && request.containsTarget(mClientCaptureSurface)) {
596 HashMap<CaptureRequest, Integer> requestMap = new HashMap<>();
597 List<CaptureRequest> burstRequest;
598 try {
599 burstRequest = createBurstRequest(mCameraDevice,
600 mImageExtender.getCaptureStages(), request, mCameraBurstSurface,
601 CameraDevice.TEMPLATE_STILL_CAPTURE, requestMap);
602 } catch (RemoteException e) {
603 Log.e(TAG, "Failed to initialize internal burst request! Extension service does"
604 + " not respond!");
605 throw new CameraAccessException(CameraAccessException.CAMERA_ERROR);
606 }
607 if (burstRequest == null) {
608 throw new UnsupportedOperationException(
609 "Failed to create still capture burst request");
610 }
611
612 seqId = mCaptureSession.captureBurstRequests(burstRequest,
613 new CameraExtensionUtils.HandlerExecutor(mHandler),
614 new BurstRequestHandler(request, executor, listener, requestMap,
615 mBurstCaptureImageCallback));
616 } else if ((mClientRepeatingRequestSurface != null) &&
617 request.containsTarget(mClientRepeatingRequestSurface)) {
618
619 CaptureRequest captureRequest = null;
620 try {
621 ArrayList<CaptureStageImpl> captureStageList = new ArrayList<>();
622 captureStageList.add(mPreviewExtender.getCaptureStage());
623
624 captureRequest = createRequest(mCameraDevice, captureStageList,
625 mCameraRepeatingSurface, CameraDevice.TEMPLATE_PREVIEW, request);
626 } catch (RemoteException e) {
627 Log.e(TAG, "Failed to initialize capture request! Extension service does"
628 + " not respond!");
629 throw new CameraAccessException(CameraAccessException.CAMERA_ERROR);
630 }
631
632 seqId = mCaptureSession.capture(captureRequest, new PreviewRequestHandler(request,
633 executor, listener, mRepeatingRequestImageCallback, true /*singleCapture*/),
634 mHandler);
635 } else {
636 throw new IllegalArgumentException("Capture request to unknown output surface!");
637 }
638
639 return seqId;
640 }
641
642 @Override
643 public void stopRepeating() throws CameraAccessException {
644 synchronized (mInterfaceLock) {
645 if (!mInitialized) {
646 throw new IllegalStateException("Uninitialized component");
647 }
648
649 mInternalRepeatingRequestEnabled = true;
650 mCaptureSession.stopRepeating();
651 }
652 }
653
654 @Override
655 public void close() throws CameraAccessException {
656 synchronized (mInterfaceLock) {
657 if (mInitialized) {
658 mInternalRepeatingRequestEnabled = false;
659 mCaptureSession.stopRepeating();
660
661 ArrayList<CaptureStageImpl> captureStageList = new ArrayList<>();
662 try {
663 CaptureStageImpl disableParams = mPreviewExtender.onDisableSession();
664 if (disableParams != null) {
665 captureStageList.add(disableParams);
666 }
667
668 CaptureStageImpl disableStillCaptureParams =
669 mImageExtender.onDisableSession();
670 if (disableStillCaptureParams != null) {
671 captureStageList.add(disableStillCaptureParams);
672 }
673 } catch (RemoteException e) {
674 Log.e(TAG, "Failed to disable extension! Extension service does not "
675 + "respond!");
676 }
677 if (!captureStageList.isEmpty()) {
678 CaptureRequest disableRequest = createRequest(mCameraDevice, captureStageList,
679 mCameraRepeatingSurface, CameraDevice.TEMPLATE_PREVIEW);
680 mCaptureSession.capture(disableRequest,
681 new CloseRequestHandler(mRepeatingRequestImageCallback), mHandler);
682 }
683
684 mCaptureSession.close();
685 }
686 }
687 }
688
689 private void setInitialCaptureRequest(List<CaptureStageImpl> captureStageList,
690 InitialRequestHandler requestHandler)
691 throws CameraAccessException {
692 CaptureRequest initialRequest = createRequest(mCameraDevice,
693 captureStageList, mCameraRepeatingSurface, CameraDevice.TEMPLATE_PREVIEW);
694 mCaptureSession.capture(initialRequest, requestHandler, mHandler);
695 }
696
697 private int setRepeatingRequest(CaptureStageImpl captureStage,
698 CameraCaptureSession.CaptureCallback requestHandler) throws CameraAccessException {
699 return setRepeatingRequest(captureStage, requestHandler, /*clientRequest*/ null);
700 }
701
702 private int setRepeatingRequest(CaptureStageImpl captureStage,
703 CameraCaptureSession.CaptureCallback requestHandler, CaptureRequest clientRequest)
704 throws CameraAccessException {
705 ArrayList<CaptureStageImpl> captureStageList = new ArrayList<>();
706 captureStageList.add(captureStage);
707 CaptureRequest repeatingRequest = createRequest(mCameraDevice, captureStageList,
708 mCameraRepeatingSurface, CameraDevice.TEMPLATE_PREVIEW, clientRequest);
709 return mCaptureSession.setSingleRepeatingRequest(repeatingRequest,
710 new CameraExtensionUtils.HandlerExecutor(mHandler), requestHandler);
711 }
712
713 /** @hide */
714 public void release(boolean skipCloseNotification) {
715 boolean notifyClose = false;
716
717 synchronized (mInterfaceLock) {
718 mInternalRepeatingRequestEnabled = false;
719 mHandlerThread.quitSafely();
720
721 try {
722 mPreviewExtender.onDeInit();
723 mImageExtender.onDeInit();
724 } catch (RemoteException e) {
725 Log.e(TAG, "Failed to release extensions! Extension service does not"
726 + " respond!");
727 }
728
729 if (mExtensionClientId >= 0) {
730 CameraExtensionCharacteristics.unregisterClient(mExtensionClientId);
731 if (mInitialized) {
732 notifyClose = true;
733 CameraExtensionCharacteristics.releaseSession();
734 }
735 }
736 mInitialized = false;
737
738 if (mRepeatingRequestImageCallback != null) {
739 mRepeatingRequestImageCallback.close();
740 mRepeatingRequestImageCallback = null;
741 }
742
743 if (mRepeatingRequestImageReader != null) {
744 mRepeatingRequestImageReader.close();
745 mRepeatingRequestImageReader = null;
746 }
747
748 if (mBurstCaptureImageCallback != null) {
749 mBurstCaptureImageCallback.close();
750 mBurstCaptureImageCallback = null;
751 }
752
753 if (mBurstCaptureImageReader != null) {
754 mBurstCaptureImageReader.close();
755 mBurstCaptureImageReader = null;
756 }
757
758 if (mStubCaptureImageReader != null) {
759 mStubCaptureImageReader.close();
760 mStubCaptureImageReader = null;
761 }
762
763 if (mRepeatingRequestImageWriter != null) {
764 mRepeatingRequestImageWriter.close();
765 mRepeatingRequestImageWriter = null;
766 }
767
768 if (mPreviewImageProcessor != null) {
769 mPreviewImageProcessor.close();
770 mPreviewImageProcessor = null;
771 }
772
773 if (mImageJpegProcessor != null) {
774 mImageJpegProcessor.close();
775 mImageJpegProcessor = null;
776 }
777
778 mCaptureSession = null;
779 mImageProcessor = null;
780 mCameraRepeatingSurface = mClientRepeatingRequestSurface = null;
781 mCameraBurstSurface = mClientCaptureSurface = null;
782 }
783
784 if (notifyClose && !skipCloseNotification) {
785 final long ident = Binder.clearCallingIdentity();
786 try {
787 mExecutor.execute(() -> mCallbacks.onClosed(CameraExtensionSessionImpl.this));
788 } finally {
789 Binder.restoreCallingIdentity(ident);
790 }
791 }
792 }
793
794 private void notifyConfigurationFailure() {
795 synchronized (mInterfaceLock) {
796 if (mInitialized) {
797 return;
798 }
799 }
800
801 release(true /*skipCloseNotification*/);
802
803 final long ident = Binder.clearCallingIdentity();
804 try {
805 mExecutor.execute(
806 () -> mCallbacks.onConfigureFailed(CameraExtensionSessionImpl.this));
807 } finally {
808 Binder.restoreCallingIdentity(ident);
809 }
810 }
811
812 private void notifyConfigurationSuccess() {
813 synchronized (mInterfaceLock) {
814 if (mInitialized) {
815 return;
816 } else {
817 mInitialized = true;
818 }
819 }
820
821 final long ident = Binder.clearCallingIdentity();
822 try {
823 mExecutor.execute(() -> mCallbacks.onConfigured(CameraExtensionSessionImpl.this));
824 } finally {
825 Binder.restoreCallingIdentity(ident);
826 }
827 }
828
829 private class SessionStateHandler extends
830 android.hardware.camera2.CameraCaptureSession.StateCallback {
831 @Override
832 public void onClosed(@NonNull CameraCaptureSession session) {
833 release(false /*skipCloseNotification*/);
834 }
835
836 @Override
837 public void onConfigureFailed(@NonNull CameraCaptureSession session) {
838 notifyConfigurationFailure();
839 }
840
841 @Override
842 public void onConfigured(@NonNull CameraCaptureSession session) {
843 synchronized (mInterfaceLock) {
844 mCaptureSession = session;
845 try {
846 finishPipelineInitialization();
847 CameraExtensionCharacteristics.initializeSession(mInitializeHandler);
848 } catch (RemoteException e) {
849 Log.e(TAG, "Failed to initialize session! Extension service does"
850 + " not respond!");
851 notifyConfigurationFailure();
852 }
853 }
854 }
855 }
856
857 private class InitializeSessionHandler extends IInitializeSessionCallback.Stub {
858 @Override
859 public void onSuccess() {
860 mHandler.post(new Runnable() {
861 @Override
862 public void run() {
863 boolean status = true;
864 ArrayList<CaptureStageImpl> initialRequestList =
865 compileInitialRequestList();
866 if (!initialRequestList.isEmpty()) {
867 try {
868 setInitialCaptureRequest(initialRequestList,
869 new InitialRequestHandler(
870 mRepeatingRequestImageCallback));
871 } catch (CameraAccessException e) {
872 Log.e(TAG,
873 "Failed to initialize the initial capture "
874 + "request!");
875 status = false;
876 }
877 } else {
878 try {
879 setRepeatingRequest(mPreviewExtender.getCaptureStage(),
880 new PreviewRequestHandler(null, null, null,
881 mRepeatingRequestImageCallback));
882 } catch (CameraAccessException | RemoteException e) {
883 Log.e(TAG,
884 "Failed to initialize internal repeating "
885 + "request!");
886 status = false;
887 }
888
889 }
890
891 if (!status) {
892 notifyConfigurationFailure();
893 }
894 }
895 });
896 }
897
898 @Override
899 public void onFailure() {
900 mHandler.post(new Runnable() {
901 @Override
902 public void run() {
903 mCaptureSession.close();
904 Log.e(TAG, "Failed to initialize proxy service session!"
905 + " This can happen when trying to configure multiple "
906 + "concurrent extension sessions!");
907 notifyConfigurationFailure();
908 }
909 });
910 }
911 }
912
913 private class BurstRequestHandler extends CameraCaptureSession.CaptureCallback {
914 private final Executor mExecutor;
915 private final ExtensionCaptureCallback mCallbacks;
916 private final CaptureRequest mClientRequest;
917 private final HashMap<CaptureRequest, Integer> mCaptureRequestMap;
918 private final CameraOutputImageCallback mBurstImageCallback;
919
920 private HashMap<Integer, Pair<Image, TotalCaptureResult>> mCaptureStageMap =
921 new HashMap<>();
922 private LongSparseArray<Pair<Image, Integer>> mCapturePendingMap =
923 new LongSparseArray<>();
924
925 private ImageCallback mImageCallback = null;
926 private boolean mCaptureFailed = false;
927 private CaptureResultHandler mCaptureResultHandler = null;
928
929 public BurstRequestHandler(@NonNull CaptureRequest request, @NonNull Executor executor,
930 @NonNull ExtensionCaptureCallback callbacks,
931 @NonNull HashMap<CaptureRequest, Integer> requestMap,
932 @Nullable CameraOutputImageCallback imageCallback) {
933 mClientRequest = request;
934 mExecutor = executor;
935 mCallbacks = callbacks;
936 mCaptureRequestMap = requestMap;
937 mBurstImageCallback = imageCallback;
938 }
939
940 private void notifyCaptureFailed() {
941 if (!mCaptureFailed) {
942 mCaptureFailed = true;
943
944 final long ident = Binder.clearCallingIdentity();
945 try {
946 mExecutor.execute(
947 () -> mCallbacks.onCaptureFailed(CameraExtensionSessionImpl.this,
948 mClientRequest));
949 } finally {
950 Binder.restoreCallingIdentity(ident);
951 }
952
953 for (Pair<Image, TotalCaptureResult> captureStage : mCaptureStageMap.values()) {
954 captureStage.first.close();
955 }
956 mCaptureStageMap.clear();
957 }
958 }
959
960 @Override
961 public void onCaptureStarted(@NonNull CameraCaptureSession session,
962 @NonNull CaptureRequest request,
963 long timestamp,
964 long frameNumber) {
965 // Trigger the client callback only once in case of burst request
966 boolean initialCallback = false;
967 synchronized (mInterfaceLock) {
968 if ((mImageProcessor != null) && (mImageCallback == null)) {
969 mImageCallback = new ImageCallback();
970 initialCallback = true;
971 } else if (mImageProcessor == null) {
972 // No burst expected in this case
973 initialCallback = true;
974 }
975 }
976
977 if (initialCallback) {
978 final long ident = Binder.clearCallingIdentity();
979 try {
980 mExecutor.execute(
981 () -> mCallbacks.onCaptureStarted(CameraExtensionSessionImpl.this,
982 mClientRequest, timestamp));
983 } finally {
984 Binder.restoreCallingIdentity(ident);
985 }
986 }
987
988 if ((mBurstImageCallback != null) && (mImageCallback != null)) {
989 mBurstImageCallback.registerListener(timestamp, mImageCallback);
990 }
991 }
992
993 @Override
994 public void onCaptureBufferLost(@NonNull CameraCaptureSession session,
995 @NonNull CaptureRequest request,
996 @NonNull Surface target, long frameNumber) {
997 notifyCaptureFailed();
998 }
999
1000 @Override
1001 public void onCaptureFailed(@NonNull CameraCaptureSession session,
1002 @NonNull CaptureRequest request,
1003 @NonNull CaptureFailure failure) {
1004 notifyCaptureFailed();
1005 }
1006
1007 @Override
1008 public void onCaptureSequenceAborted(@NonNull CameraCaptureSession session,
1009 int sequenceId) {
1010 final long ident = Binder.clearCallingIdentity();
1011 try {
1012 mExecutor.execute(
1013 () -> mCallbacks.onCaptureSequenceAborted(CameraExtensionSessionImpl.this,
1014 sequenceId));
1015 } finally {
1016 Binder.restoreCallingIdentity(ident);
1017 }
1018 }
1019
1020 @Override
1021 public void onCaptureSequenceCompleted(@NonNull CameraCaptureSession session,
1022 int sequenceId,
1023 long frameNumber) {
1024 final long ident = Binder.clearCallingIdentity();
1025 try {
1026 mExecutor.execute(
1027 () -> mCallbacks
1028 .onCaptureSequenceCompleted(CameraExtensionSessionImpl.this,
1029 sequenceId));
1030 } finally {
1031 Binder.restoreCallingIdentity(ident);
1032 }
1033 }
1034
1035 @Override
1036 public void onCaptureCompleted(@NonNull CameraCaptureSession session,
1037 @NonNull CaptureRequest request,
1038 @NonNull TotalCaptureResult result) {
1039 if (!mCaptureRequestMap.containsKey(request)) {
1040 Log.e(TAG,
1041 "Unexpected still capture request received!");
1042 return;
1043 }
1044 Integer stageId = mCaptureRequestMap.get(request);
1045
1046 Long timestamp = result.get(CaptureResult.SENSOR_TIMESTAMP);
1047 if (timestamp != null) {
1048 if (mCaptureResultsSupported && (mCaptureResultHandler == null)) {
1049 mCaptureResultHandler = new CaptureResultHandler(mClientRequest, mExecutor,
1050 mCallbacks, result.getSequenceId());
1051 }
1052 if (mImageProcessor != null) {
1053 if (mCapturePendingMap.indexOfKey(timestamp) >= 0) {
1054 Image img = mCapturePendingMap.get(timestamp).first;
1055 mCaptureStageMap.put(stageId, new Pair<>(img, result));
1056 checkAndFireBurstProcessing();
1057 } else {
1058 mCapturePendingMap.put(timestamp, new Pair<>(null, stageId));
1059 mCaptureStageMap.put(stageId, new Pair<>(null, result));
1060 }
1061 } else {
1062 mCaptureRequestMap.clear();
1063 final long ident = Binder.clearCallingIdentity();
1064 try {
1065 mExecutor.execute(
1066 () -> mCallbacks
1067 .onCaptureProcessStarted(CameraExtensionSessionImpl.this,
1068 mClientRequest));
1069
1070 if (mCaptureResultHandler != null) {
1071 mCaptureResultHandler.onCaptureCompleted(timestamp,
1072 initializeFilteredResults(result));
1073 }
1074 } finally {
1075 Binder.restoreCallingIdentity(ident);
1076 }
1077 }
1078 } else {
1079 Log.e(TAG,
1080 "Capture result without valid sensor timestamp!");
1081 }
1082 }
1083
1084 private void checkAndFireBurstProcessing() {
1085 if (mCaptureRequestMap.size() == mCaptureStageMap.size()) {
1086 for (Pair<Image, TotalCaptureResult> captureStage : mCaptureStageMap
1087 .values()) {
1088 if ((captureStage.first == null) || (captureStage.second == null)) {
1089 return;
1090 }
1091 }
1092
1093 mCaptureRequestMap.clear();
1094 mCapturePendingMap.clear();
1095 boolean processStatus = true;
1096 Byte jpegQuality = mClientRequest.get(CaptureRequest.JPEG_QUALITY);
1097 Integer jpegOrientation = mClientRequest.get(CaptureRequest.JPEG_ORIENTATION);
1098 List<CaptureBundle> captureList = initializeParcelable(mCaptureStageMap,
1099 jpegOrientation, jpegQuality);
1100 try {
1101 mImageProcessor.process(captureList, mCaptureResultHandler);
1102 } catch (RemoteException e) {
1103 Log.e(TAG, "Failed to process multi-frame request! Extension service "
1104 + "does not respond!");
1105 processStatus = false;
1106 }
1107
1108 for (CaptureBundle bundle : captureList) {
1109 bundle.captureImage.buffer.close();
1110 }
1111 captureList.clear();
1112 for (Pair<Image, TotalCaptureResult> captureStage : mCaptureStageMap.values()) {
1113 captureStage.first.close();
1114 }
1115 mCaptureStageMap.clear();
1116
1117 final long ident = Binder.clearCallingIdentity();
1118 try {
1119 if (processStatus) {
1120 mExecutor.execute(() -> mCallbacks.onCaptureProcessStarted(
1121 CameraExtensionSessionImpl.this, mClientRequest));
1122 } else {
1123 mExecutor.execute(() -> mCallbacks.onCaptureFailed(
1124 CameraExtensionSessionImpl.this, mClientRequest));
1125 }
1126 } finally {
1127 Binder.restoreCallingIdentity(ident);
1128 }
1129 }
1130 }
1131
1132 private class ImageCallback implements OnImageAvailableListener {
1133 @Override
1134 public void onImageDropped(long timestamp) {
1135 notifyCaptureFailed();
1136 }
1137
1138 @Override
1139 public void onImageAvailable(ImageReader reader, Image img) {
1140 if (mCaptureFailed) {
1141 img.close();
1142 }
1143
1144 long timestamp = img.getTimestamp();
1145 reader.detachImage(img);
1146 if (mCapturePendingMap.indexOfKey(timestamp) >= 0) {
1147 Integer stageId = mCapturePendingMap.get(timestamp).second;
1148 Pair<Image, TotalCaptureResult> captureStage =
1149 mCaptureStageMap.get(stageId);
1150 if (captureStage != null) {
1151 mCaptureStageMap.put(stageId,
1152 new Pair<>(img,
1153 captureStage.second));
1154 checkAndFireBurstProcessing();
1155 } else {
1156 Log.e(TAG,
1157 "Capture stage: " +
1158 mCapturePendingMap.get(timestamp).second +
1159 " is absent!");
1160 }
1161 } else {
1162 mCapturePendingMap.put(timestamp,
1163 new Pair<>(img,
1164 -1));
1165 }
1166 }
1167 }
1168 }
1169
1170 private class ImageLoopbackCallback implements OnImageAvailableListener {
1171 @Override
1172 public void onImageDropped(long timestamp) { }
1173
1174 @Override
1175 public void onImageAvailable(ImageReader reader, Image img) {
1176 img.close();
1177 }
1178 }
1179
1180 private class InitialRequestHandler extends CameraCaptureSession.CaptureCallback {
1181 private final CameraOutputImageCallback mImageCallback;
1182
1183 public InitialRequestHandler(CameraOutputImageCallback imageCallback) {
1184 mImageCallback = imageCallback;
1185 }
1186
1187 @Override
1188 public void onCaptureStarted(@NonNull CameraCaptureSession session,
1189 @NonNull CaptureRequest request, long timestamp, long frameNumber) {
1190 mImageCallback.registerListener(timestamp, new ImageLoopbackCallback());
1191 }
1192
1193 @Override
1194 public void onCaptureSequenceAborted(@NonNull CameraCaptureSession session,
1195 int sequenceId) {
1196 Log.e(TAG, "Initial capture request aborted!");
1197 notifyConfigurationFailure();
1198 }
1199
1200 @Override
1201 public void onCaptureFailed(@NonNull CameraCaptureSession session,
1202 @NonNull CaptureRequest request,
1203 @NonNull CaptureFailure failure) {
1204 Log.e(TAG, "Initial capture request failed!");
1205 notifyConfigurationFailure();
1206 }
1207
1208 @Override
1209 public void onCaptureSequenceCompleted(@NonNull CameraCaptureSession session,
1210 int sequenceId,
1211 long frameNumber) {
1212 boolean status = true;
1213 synchronized (mInterfaceLock) {
1214 /**
1215 * Initialize and set the initial repeating request which will execute in the
1216 * absence of client repeating requests.
1217 */
1218 try {
1219 setRepeatingRequest(mPreviewExtender.getCaptureStage(),
1220 new PreviewRequestHandler(null, null, null,
1221 mImageCallback));
1222 } catch (CameraAccessException | RemoteException e) {
1223 Log.e(TAG, "Failed to start the internal repeating request!");
1224 status = false;
1225 }
1226
1227 }
1228
1229 if (!status) {
1230 notifyConfigurationFailure();
1231 }
1232 }
1233 }
1234
1235 private interface OnImageAvailableListener {
1236 void onImageDropped(long timestamp);
1237 void onImageAvailable (ImageReader reader, Image img);
1238 }
1239
1240 private class CameraOutputImageCallback implements ImageReader.OnImageAvailableListener,
1241 Closeable {
1242 private final ImageReader mImageReader;
1243 // Map timestamp to specific images and listeners
1244 private HashMap<Long, Pair<Image, OnImageAvailableListener>> mImageListenerMap =
1245 new HashMap<>();
1246 private boolean mOutOfBuffers = false;
1247
1248 CameraOutputImageCallback(ImageReader imageReader) {
1249 mImageReader = imageReader;
1250 }
1251
1252 @Override
1253 public void onImageAvailable(ImageReader reader) {
1254 Image img;
1255 try {
1256 img = reader.acquireNextImage();
1257 } catch (IllegalStateException e) {
1258 Log.e(TAG, "Failed to acquire image, too many images pending!");
1259 mOutOfBuffers = true;
1260 return;
1261 }
1262 if (img == null) {
1263 Log.e(TAG, "Invalid image!");
1264 return;
1265 }
1266
1267 Long timestamp = img.getTimestamp();
1268 if (mImageListenerMap.containsKey(timestamp)) {
1269 Pair<Image, OnImageAvailableListener> entry = mImageListenerMap.remove(timestamp);
1270 if (entry.second != null) {
1271 entry.second.onImageAvailable(reader, img);
1272 } else {
1273 Log.w(TAG, "Invalid image listener, dropping frame!");
1274 img.close();
1275 }
1276 } else {
1277 mImageListenerMap.put(img.getTimestamp(), new Pair<>(img, null));
1278 }
1279
1280 notifyDroppedImages(timestamp);
1281 }
1282
1283 private void notifyDroppedImages(long timestamp) {
1284 Set<Long> timestamps = mImageListenerMap.keySet();
1285 ArrayList<Long> removedTs = new ArrayList<>();
1286 for (long ts : timestamps) {
1287 if (ts < timestamp) {
1288 Log.e(TAG, "Dropped image with ts: " + ts);
1289 Pair<Image, OnImageAvailableListener> entry = mImageListenerMap.get(ts);
1290 if (entry.second != null) {
1291 entry.second.onImageDropped(ts);
1292 }
1293 if (entry.first != null) {
1294 entry.first.close();
1295 }
1296 removedTs.add(ts);
1297 }
1298 }
1299 for (long ts : removedTs) {
1300 mImageListenerMap.remove(ts);
1301 }
1302 }
1303
1304 public void registerListener(Long timestamp, OnImageAvailableListener listener) {
1305 if (mImageListenerMap.containsKey(timestamp)) {
1306 Pair<Image, OnImageAvailableListener> entry = mImageListenerMap.remove(timestamp);
1307 if (entry.first != null) {
1308 listener.onImageAvailable(mImageReader, entry.first);
1309 if (mOutOfBuffers) {
1310 mOutOfBuffers = false;
1311 Log.w(TAG,"Out of buffers, retry!");
1312 onImageAvailable(mImageReader);
1313 }
1314 } else {
1315 Log.w(TAG, "No valid image for listener with ts: " +
1316 timestamp.longValue());
1317 }
1318 } else {
1319 mImageListenerMap.put(timestamp, new Pair<>(null, listener));
1320 }
1321 }
1322
1323 @Override
1324 public void close() {
1325 for (Pair<Image, OnImageAvailableListener> entry : mImageListenerMap.values()) {
1326 if (entry.first != null) {
1327 entry.first.close();
1328 }
1329 }
1330 for (long timestamp : mImageListenerMap.keySet()) {
1331 Pair<Image, OnImageAvailableListener> entry = mImageListenerMap.get(timestamp);
1332 if (entry.second != null) {
1333 entry.second.onImageDropped(timestamp);
1334 }
1335 }
1336 mImageListenerMap.clear();
1337 }
1338 }
1339
1340 private class CloseRequestHandler extends CameraCaptureSession.CaptureCallback {
1341 private final CameraOutputImageCallback mImageCallback;
1342
1343 public CloseRequestHandler(CameraOutputImageCallback imageCallback) {
1344 mImageCallback = imageCallback;
1345 }
1346
1347 @Override
1348 public void onCaptureStarted(@NonNull CameraCaptureSession session,
1349 @NonNull CaptureRequest request, long timestamp, long frameNumber) {
1350 mImageCallback.registerListener(timestamp, new ImageLoopbackCallback());
1351 }
1352 }
1353
1354 private class CaptureResultHandler extends IProcessResultImpl.Stub {
1355 private final Executor mExecutor;
1356 private final ExtensionCaptureCallback mCallbacks;
1357 private final CaptureRequest mClientRequest;
1358 private final int mRequestId;
1359
1360 public CaptureResultHandler(@NonNull CaptureRequest clientRequest,
1361 @NonNull Executor executor, @NonNull ExtensionCaptureCallback listener,
1362 int requestId) {
1363 mClientRequest = clientRequest;
1364 mExecutor = executor;
1365 mCallbacks = listener;
1366 mRequestId = requestId;
1367 }
1368
1369 @Override
1370 public void onCaptureCompleted(long shutterTimestamp, CameraMetadataNative result) {
1371 if (result == null) {
1372 Log.e(TAG,"Invalid capture result!");
1373 return;
1374 }
1375
1376 result.set(CaptureResult.SENSOR_TIMESTAMP, shutterTimestamp);
1377 TotalCaptureResult totalResult = new TotalCaptureResult(mCameraDevice.getId(), result,
1378 mClientRequest, mRequestId, shutterTimestamp, new ArrayList<CaptureResult>(),
1379 mSessionId, new PhysicalCaptureResultInfo[0]);
1380 final long ident = Binder.clearCallingIdentity();
1381 try {
1382 mExecutor.execute(
1383 () -> mCallbacks.onCaptureResultAvailable(CameraExtensionSessionImpl.this,
1384 mClientRequest, totalResult));
1385 } finally {
1386 Binder.restoreCallingIdentity(ident);
1387 }
1388 }
1389 }
1390
1391 // This handler can operate in three modes:
1392 // 1) Using valid client callbacks, which means camera buffers will be propagated the
1393 // registered output surfaces and clients will be notified accordingly.
1394 // 2) Without any client callbacks where an internal repeating request is kept active
1395 // to satisfy the extensions continuous preview/(repeating request) requirement.
1396 // 3) Single capture mode, where internal repeating requests are ignored and the preview
1397 // logic is only triggered for the image processor case.
1398 private class PreviewRequestHandler extends CameraCaptureSession.CaptureCallback {
1399 private final Executor mExecutor;
1400 private final ExtensionCaptureCallback mCallbacks;
1401 private final CaptureRequest mClientRequest;
1402 private final boolean mClientNotificationsEnabled;
1403 private final CameraOutputImageCallback mRepeatingImageCallback;
1404 private final boolean mSingleCapture;
1405 private OnImageAvailableListener mImageCallback = null;
1406 private LongSparseArray<Pair<Image, TotalCaptureResult>> mPendingResultMap =
1407 new LongSparseArray<>();
1408 private CaptureResultHandler mCaptureResultHandler = null;
1409
1410 private boolean mRequestUpdatedNeeded = false;
1411
1412 public PreviewRequestHandler(@Nullable CaptureRequest clientRequest,
1413 @Nullable Executor executor, @Nullable ExtensionCaptureCallback listener,
1414 @NonNull CameraOutputImageCallback imageCallback) {
1415 this(clientRequest, executor, listener, imageCallback, false /*singleCapture*/);
1416 }
1417
1418 public PreviewRequestHandler(@Nullable CaptureRequest clientRequest,
1419 @Nullable Executor executor, @Nullable ExtensionCaptureCallback listener,
1420 @NonNull CameraOutputImageCallback imageCallback, boolean singleCapture) {
1421 mClientRequest = clientRequest;
1422 mExecutor = executor;
1423 mCallbacks = listener;
1424 mClientNotificationsEnabled =
1425 (mClientRequest != null) && (mExecutor != null) && (mCallbacks != null);
1426 mRepeatingImageCallback = imageCallback;
1427 mSingleCapture = singleCapture;
1428 }
1429
1430 @Override
1431 public void onCaptureStarted(@NonNull CameraCaptureSession session,
1432 @NonNull CaptureRequest request,
1433 long timestamp,
1434 long frameNumber) {
1435 synchronized (mInterfaceLock) {
1436 // Setup the image callback handler for this repeating request just once
1437 // after streaming resumes.
1438 if (mImageCallback == null) {
1439 if (mPreviewProcessorType ==
1440 IPreviewExtenderImpl.PROCESSOR_TYPE_IMAGE_PROCESSOR) {
1441 if (mClientNotificationsEnabled) {
1442 mPreviewImageProcessor.onOutputSurface(mClientRepeatingRequestSurface,
1443 nativeGetSurfaceFormat(mClientRepeatingRequestSurface));
1444 } else {
1445 mPreviewImageProcessor.onOutputSurface(null, -1);
1446 }
1447 mImageCallback = new ImageProcessCallback();
1448 } else {
1449 mImageCallback = mClientNotificationsEnabled ?
1450 new ImageForwardCallback(mRepeatingRequestImageWriter) :
1451 new ImageLoopbackCallback();
1452 }
1453 }
1454 }
1455
1456 if (mClientNotificationsEnabled) {
1457 final long ident = Binder.clearCallingIdentity();
1458 try {
1459 mExecutor.execute(
1460 () -> mCallbacks.onCaptureStarted(CameraExtensionSessionImpl.this,
1461 mClientRequest, timestamp));
1462 } finally {
1463 Binder.restoreCallingIdentity(ident);
1464 }
1465 }
1466
1467 mRepeatingImageCallback.registerListener(timestamp, mImageCallback);
1468 }
1469
1470 @Override
1471 public void onCaptureSequenceAborted(@NonNull CameraCaptureSession session,
1472 int sequenceId) {
1473 synchronized (mInterfaceLock) {
1474 if (mInternalRepeatingRequestEnabled && !mSingleCapture) {
1475 resumeInternalRepeatingRequest(true);
1476 }
1477 }
1478
1479 if (mClientNotificationsEnabled) {
1480 final long ident = Binder.clearCallingIdentity();
1481 try {
1482 mExecutor.execute(
1483 () -> mCallbacks
1484 .onCaptureSequenceAborted(CameraExtensionSessionImpl.this,
1485 sequenceId));
1486 } finally {
1487 Binder.restoreCallingIdentity(ident);
1488 }
1489 } else {
1490 notifyConfigurationFailure();
1491 }
1492 }
1493
1494 @Override
1495 public void onCaptureSequenceCompleted(@NonNull CameraCaptureSession session,
1496 int sequenceId,
1497 long frameNumber) {
1498
1499 synchronized (mInterfaceLock) {
1500 if (mRequestUpdatedNeeded && !mSingleCapture) {
1501 mRequestUpdatedNeeded = false;
1502 resumeInternalRepeatingRequest(false);
1503 } else if (mInternalRepeatingRequestEnabled && !mSingleCapture) {
1504 resumeInternalRepeatingRequest(true);
1505 }
1506 }
1507
1508 if (mClientNotificationsEnabled) {
1509 final long ident = Binder.clearCallingIdentity();
1510 try {
1511 mExecutor.execute(
1512 () -> mCallbacks
1513 .onCaptureSequenceCompleted(CameraExtensionSessionImpl.this,
1514 sequenceId));
1515 } finally {
1516 Binder.restoreCallingIdentity(ident);
1517 }
1518 }
1519 }
1520
1521 @Override
1522 public void onCaptureFailed(@NonNull CameraCaptureSession session,
1523 @NonNull CaptureRequest request,
1524 @NonNull CaptureFailure failure) {
1525
1526 if (mClientNotificationsEnabled) {
1527 final long ident = Binder.clearCallingIdentity();
1528 try {
1529 mExecutor.execute(
1530 () -> mCallbacks.onCaptureFailed(CameraExtensionSessionImpl.this,
1531 mClientRequest));
1532 } finally {
1533 Binder.restoreCallingIdentity(ident);
1534 }
1535 }
1536 }
1537
1538 @Override
1539 public void onCaptureCompleted(@NonNull CameraCaptureSession session,
1540 @NonNull CaptureRequest request,
1541 @NonNull TotalCaptureResult result) {
1542 boolean notifyClient = mClientNotificationsEnabled;
1543 boolean processStatus = true;
1544
1545 synchronized (mInterfaceLock) {
1546 final Long timestamp = result.get(CaptureResult.SENSOR_TIMESTAMP);
1547 if (timestamp != null) {
1548 if (mCaptureResultsSupported && mClientNotificationsEnabled &&
1549 (mCaptureResultHandler == null)) {
1550 mCaptureResultHandler = new CaptureResultHandler(mClientRequest, mExecutor,
1551 mCallbacks, result.getSequenceId());
1552 }
1553 if ((!mSingleCapture) && (mPreviewProcessorType ==
1554 IPreviewExtenderImpl.PROCESSOR_TYPE_REQUEST_UPDATE_ONLY)) {
1555 CaptureStageImpl captureStage = null;
1556 try {
1557 captureStage = mPreviewRequestUpdateProcessor.process(
1558 result.getNativeMetadata(), result.getSequenceId());
1559 } catch (RemoteException e) {
1560 Log.e(TAG, "Extension service does not respond during " +
1561 "processing!");
1562 }
1563 if (captureStage != null) {
1564 try {
1565 setRepeatingRequest(captureStage, this, request);
1566 mRequestUpdatedNeeded = true;
1567 } catch (IllegalStateException e) {
1568 // This is possible in case the camera device closes and the
1569 // and the callback here is executed before the onClosed
1570 // notification.
1571 } catch (CameraAccessException e) {
1572 Log.e(TAG, "Failed to update repeating request settings!");
1573 }
1574 } else {
1575 mRequestUpdatedNeeded = false;
1576 }
1577 } else if (mPreviewProcessorType ==
1578 IPreviewExtenderImpl.PROCESSOR_TYPE_IMAGE_PROCESSOR) {
1579 int idx = mPendingResultMap.indexOfKey(timestamp);
1580
1581 if ((idx >= 0) && (mPendingResultMap.get(timestamp).first == null)) {
1582 // Image was dropped before we can receive the capture results
1583 if ((mCaptureResultHandler != null)) {
1584 mCaptureResultHandler.onCaptureCompleted(timestamp,
1585 initializeFilteredResults(result));
1586 }
1587 discardPendingRepeatingResults(idx, mPendingResultMap, false);
1588 } else if (idx >= 0) {
1589 // Image came before the capture results
1590 ParcelImage parcelImage = initializeParcelImage(
1591 mPendingResultMap.get(timestamp).first);
1592 try {
1593 mPreviewImageProcessor.process(parcelImage, result,
1594 mCaptureResultHandler);
1595 } catch (RemoteException e) {
1596 processStatus = false;
1597 Log.e(TAG, "Extension service does not respond during " +
1598 "processing, dropping frame!");
1599 } catch (RuntimeException e) {
1600 // Runtime exceptions can happen in a few obscure cases where the
1601 // client tries to initialize a new capture session while this
1602 // session is still ongoing. In such scenario, the camera will
1603 // disconnect from the intermediate output surface, which will
1604 // invalidate the images that we acquired previously. This can
1605 // happen before we get notified via "onClosed" so there aren't
1606 // many options to avoid the exception.
1607 processStatus = false;
1608 Log.e(TAG, "Runtime exception encountered during buffer " +
1609 "processing, dropping frame!");
1610 } finally {
1611 parcelImage.buffer.close();
1612 mPendingResultMap.get(timestamp).first.close();
1613 }
1614 discardPendingRepeatingResults(idx, mPendingResultMap, false);
1615 } else {
1616 // Image not yet available
1617 notifyClient = false;
1618 mPendingResultMap.put(timestamp,
1619 new Pair<>(null,
1620 result));
1621 }
1622 } else {
1623 // No special handling for PROCESSOR_TYPE_NONE
1624 }
1625 if (notifyClient) {
1626 final long ident = Binder.clearCallingIdentity();
1627 try {
1628 if (processStatus) {
1629 mExecutor.execute(() -> mCallbacks
1630 .onCaptureProcessStarted(
1631 CameraExtensionSessionImpl.this,
1632 mClientRequest));
1633 if ((mCaptureResultHandler != null) && (mPreviewProcessorType !=
1634 IPreviewExtenderImpl.PROCESSOR_TYPE_IMAGE_PROCESSOR)) {
1635 mCaptureResultHandler.onCaptureCompleted(timestamp,
1636 initializeFilteredResults(result));
1637 }
1638 } else {
1639 mExecutor.execute(
1640 () -> mCallbacks
1641 .onCaptureFailed(
1642 CameraExtensionSessionImpl.this,
1643 mClientRequest));
1644 }
1645 } finally {
1646 Binder.restoreCallingIdentity(ident);
1647 }
1648 }
1649 } else {
1650 Log.e(TAG,
1651 "Result without valid sensor timestamp!");
1652 }
1653 }
1654
1655 if (!notifyClient) {
1656 notifyConfigurationSuccess();
1657 }
1658 }
1659
1660 private void resumeInternalRepeatingRequest(boolean internal) {
1661 try {
1662 if (internal) {
1663 setRepeatingRequest(mPreviewExtender.getCaptureStage(),
1664 new PreviewRequestHandler(null, null, null,
1665 mRepeatingImageCallback));
1666 } else {
1667 setRepeatingRequest(mPreviewExtender.getCaptureStage(), this, mClientRequest);
1668 }
1669 } catch (RemoteException e) {
1670 Log.e(TAG, "Failed to resume internal repeating request, extension service"
1671 + " fails to respond!");
1672 } catch (IllegalStateException e) {
1673 // This is possible in case we try to resume before the state "onClosed"
1674 // notification is able to reach us.
1675 Log.w(TAG, "Failed to resume internal repeating request!");
1676 } catch (CameraAccessException e) {
1677 Log.e(TAG, "Failed to resume internal repeating request!");
1678 }
1679 }
1680
1681 // Find the timestamp of the oldest pending buffer
1682 private Long calculatePruneThreshold(
1683 LongSparseArray<Pair<Image, TotalCaptureResult>> previewMap) {
1684 long oldestTimestamp = Long.MAX_VALUE;
1685 for (int idx = 0; idx < previewMap.size(); idx++) {
1686 Pair<Image, TotalCaptureResult> entry = previewMap.valueAt(idx);
1687 long timestamp = previewMap.keyAt(idx);
1688 if ((entry.first != null) && (timestamp < oldestTimestamp)) {
1689 oldestTimestamp = timestamp;
1690 }
1691 }
1692 return (oldestTimestamp == Long.MAX_VALUE) ? 0 : oldestTimestamp;
1693 }
1694
1695 private void discardPendingRepeatingResults(int idx, LongSparseArray<Pair<Image,
1696 TotalCaptureResult>> previewMap, boolean notifyCurrentIndex) {
1697 if (idx < 0) {
1698 return;
1699 }
1700 for (int i = idx; i >= 0; i--) {
1701 if (previewMap.valueAt(i).first != null) {
1702 previewMap.valueAt(i).first.close();
1703 } else if (mClientNotificationsEnabled && (previewMap.valueAt(i).second != null) &&
1704 ((i != idx) || notifyCurrentIndex)) {
1705 TotalCaptureResult result = previewMap.valueAt(i).second;
1706 Long timestamp = result.get(CaptureResult.SENSOR_TIMESTAMP);
1707 if (mCaptureResultHandler != null) {
1708 mCaptureResultHandler.onCaptureCompleted(timestamp,
1709 initializeFilteredResults(result));
1710 }
1711
1712 Log.w(TAG, "Preview frame drop with timestamp: " + previewMap.keyAt(i));
1713 final long ident = Binder.clearCallingIdentity();
1714 try {
1715 mExecutor.execute(
1716 () -> mCallbacks
1717 .onCaptureFailed(CameraExtensionSessionImpl.this,
1718 mClientRequest));
1719 } finally {
1720 Binder.restoreCallingIdentity(ident);
1721 }
1722
1723 }
1724 previewMap.removeAt(i);
1725 }
1726 }
1727
1728 private class ImageForwardCallback implements OnImageAvailableListener {
1729 private final ImageWriter mOutputWriter;
1730
1731 public ImageForwardCallback(@NonNull ImageWriter imageWriter) {
1732 mOutputWriter = imageWriter;
1733 }
1734
1735 @Override
1736 public void onImageDropped(long timestamp) {
1737 discardPendingRepeatingResults(mPendingResultMap.indexOfKey(timestamp),
1738 mPendingResultMap, true);
1739 }
1740
1741 @Override
1742 public void onImageAvailable(ImageReader reader, Image img) {
1743 if (img == null) {
1744 Log.e(TAG, "Invalid image!");
1745 return;
1746 }
1747
1748 try {
1749 mOutputWriter.queueInputImage(img);
1750 } catch (IllegalStateException e) {
1751 // This is possible in case the client disconnects from the output surface
1752 // abruptly.
1753 Log.w(TAG, "Output surface likely abandoned, dropping buffer!");
1754 img.close();
1755 } catch (RuntimeException e) {
1756 // NOTE: This is intended to catch RuntimeException from ImageReader.detachImage
1757 // ImageReader.detachImage is not supposed to throw RuntimeExceptions but the
1758 // bug went unchecked for a few years and now its behavior cannot be changed
1759 // without breaking backwards compatibility.
1760
1761 if (!e.getClass().equals(RuntimeException.class)) {
1762 // re-throw any exceptions that aren't base RuntimeException since they are
1763 // coming from elsewhere, and we shouldn't silently drop those.
1764 throw e;
1765 }
1766
1767 Log.w(TAG, "Output surface likely abandoned, dropping buffer!");
1768 img.close();
1769 }
1770 }
1771 }
1772
1773 private class ImageProcessCallback implements OnImageAvailableListener {
1774
1775 @Override
1776 public void onImageDropped(long timestamp) {
1777 discardPendingRepeatingResults(mPendingResultMap.indexOfKey(timestamp),
1778 mPendingResultMap, true);
1779 // Add an empty frame&results entry to flag that we dropped a frame
1780 // and valid capture results can immediately return to client.
1781 mPendingResultMap.put(timestamp, new Pair<>(null, null));
1782 }
1783
1784 @Override
1785 public void onImageAvailable(ImageReader reader, Image img) {
1786 if (mPendingResultMap.size() + 1 >= PREVIEW_QUEUE_SIZE) {
1787 // We reached the maximum acquired images limit. This is possible in case we
1788 // have capture failures that result in absent or missing capture results. In
1789 // such scenario we can prune the oldest pending buffer.
1790 discardPendingRepeatingResults(
1791 mPendingResultMap
1792 .indexOfKey(calculatePruneThreshold(mPendingResultMap)),
1793 mPendingResultMap, true);
1794 }
1795
1796 if (img == null) {
1797 Log.e(TAG,
1798 "Invalid preview buffer!");
1799 return;
1800 }
1801 try {
1802 reader.detachImage(img);
1803 } catch (IllegalStateException e) {
1804 Log.e(TAG, "Failed to detach image!");
1805 img.close();
1806 return;
1807 } catch (RuntimeException e) {
1808 // NOTE: This is intended to catch RuntimeException from ImageReader.detachImage
1809 // ImageReader.detachImage is not supposed to throw RuntimeExceptions but the
1810 // bug went unchecked for a few years and now its behavior cannot be changed
1811 // without breaking backwards compatibility.
1812
1813 if (!e.getClass().equals(RuntimeException.class)) {
1814 // re-throw any exceptions that aren't base RuntimeException since they are
1815 // coming from elsewhere, and we shouldn't silently drop those.
1816 throw e;
1817 }
1818
1819 Log.e(TAG, "Failed to detach image!");
1820 img.close();
1821 return;
1822 }
1823
1824 long timestamp = img.getTimestamp();
1825 int idx = mPendingResultMap.indexOfKey(timestamp);
1826 if (idx >= 0) {
1827 boolean processStatus = true;
1828 ParcelImage parcelImage = initializeParcelImage(img);
1829 try {
1830 mPreviewImageProcessor.process(parcelImage,
1831 mPendingResultMap.get(timestamp).second, mCaptureResultHandler);
1832 } catch (RemoteException e) {
1833 processStatus = false;
1834 Log.e(TAG, "Extension service does not respond during " +
1835 "processing, dropping frame!");
1836 } finally {
1837 parcelImage.buffer.close();
1838 img.close();
1839 }
1840 discardPendingRepeatingResults(idx, mPendingResultMap, false);
1841 if (mClientNotificationsEnabled) {
1842 final long ident = Binder.clearCallingIdentity();
1843 try {
1844 if (processStatus) {
1845 mExecutor.execute(() -> mCallbacks.onCaptureProcessStarted(
1846 CameraExtensionSessionImpl.this,
1847 mClientRequest));
1848 } else {
1849 mExecutor.execute(() -> mCallbacks.onCaptureFailed(
1850 CameraExtensionSessionImpl.this,
1851 mClientRequest));
1852 }
1853 } finally {
1854 Binder.restoreCallingIdentity(ident);
1855 }
1856 }
1857 } else {
1858 mPendingResultMap.put(timestamp, new Pair<>(img, null));
1859 }
1860 }
1861 }
1862 }
1863
1864 private CameraMetadataNative initializeFilteredResults(TotalCaptureResult result) {
1865 CameraMetadataNative captureResults = new CameraMetadataNative();
1866 for (CaptureResult.Key key : mSupportedResultKeys) {
1867 Object value = result.get(key);
1868 if (value != null) {
1869 captureResults.set(key, value);
1870 }
1871 }
1872 return captureResults;
1873 }
1874
1875 private static Size findSmallestAspectMatchedSize(@NonNull List<Size> sizes,
1876 @NonNull Size arSize) {
1877 final float TOLL = .01f;
1878
1879 if (arSize.getHeight() == 0) {
1880 throw new IllegalArgumentException("Invalid input aspect ratio");
1881 }
1882
1883 float targetAR = ((float) arSize.getWidth()) / arSize.getHeight();
1884 Size ret = null;
1885 Size fallbackSize = null;
1886 for (Size sz : sizes) {
1887 if (fallbackSize == null) {
1888 fallbackSize = sz;
1889 }
1890 if ((sz.getHeight() > 0) &&
1891 ((ret == null) ||
1892 (ret.getWidth() * ret.getHeight()) <
1893 (sz.getWidth() * sz.getHeight()))) {
1894 float currentAR = ((float) sz.getWidth()) / sz.getHeight();
1895 if (Math.abs(currentAR - targetAR) <= TOLL) {
1896 ret = sz;
1897 }
1898 }
1899 }
1900 if (ret == null) {
1901 Log.e(TAG, "AR matched size not found returning first size in list");
1902 ret = fallbackSize;
1903 }
1904
1905 return ret;
1906 }
1907
1908 private static ParcelImage initializeParcelImage(Image img) {
1909 ParcelImage parcelImage = new ParcelImage();
1910 parcelImage.buffer = img.getHardwareBuffer();
1911 try {
1912 SyncFence fd = img.getFence();
1913 if (fd.isValid()) {
1914 parcelImage.fence = fd.getFdDup();
1915 }
1916 } catch (IOException e) {
1917 Log.e(TAG, "Failed to parcel buffer fence!");
1918 }
1919 parcelImage.width = img.getWidth();
1920 parcelImage.height = img.getHeight();
1921 parcelImage.format = img.getFormat();
1922 parcelImage.timestamp = img.getTimestamp();
1923 parcelImage.transform = img.getTransform();
1924 parcelImage.scalingMode = img.getScalingMode();
1925 parcelImage.planeCount = img.getPlaneCount();
1926 parcelImage.crop = img.getCropRect();
1927
1928 return parcelImage;
1929 }
1930
1931 private static List<CaptureBundle> initializeParcelable(
1932 HashMap<Integer, Pair<Image, TotalCaptureResult>> captureMap, Integer jpegOrientation,
1933 Byte jpegQuality) {
1934 ArrayList<CaptureBundle> ret = new ArrayList<>();
1935 for (Integer stagetId : captureMap.keySet()) {
1936 Pair<Image, TotalCaptureResult> entry = captureMap.get(stagetId);
1937 CaptureBundle bundle = new CaptureBundle();
1938 bundle.stage = stagetId;
1939 bundle.captureImage = initializeParcelImage(entry.first);
1940 bundle.sequenceId = entry.second.getSequenceId();
1941 bundle.captureResult = entry.second.getNativeMetadata();
1942 if (jpegOrientation != null) {
1943 bundle.captureResult.set(CaptureResult.JPEG_ORIENTATION, jpegOrientation);
1944 }
1945 if (jpegQuality != null) {
1946 bundle.captureResult.set(CaptureResult.JPEG_QUALITY, jpegQuality);
1947 }
1948 ret.add(bundle);
1949 }
1950
1951 return ret;
1952 }
1953 }