Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * Copyright (C) 2013 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.compat.annotation.UnsupportedAppUsage;
21 import android.graphics.ImageFormat;
22 import android.graphics.Point;
23 import android.graphics.Rect;
24 import android.hardware.camera2.CameraCharacteristics;
25 import android.hardware.camera2.CameraMetadata;
26 import android.hardware.camera2.CaptureRequest;
27 import android.hardware.camera2.CaptureResult;
28 import android.hardware.camera2.marshal.MarshalQueryable;
29 import android.hardware.camera2.marshal.MarshalRegistry;
30 import android.hardware.camera2.marshal.Marshaler;
31 import android.hardware.camera2.marshal.impl.MarshalQueryableArray;
32 import android.hardware.camera2.marshal.impl.MarshalQueryableBlackLevelPattern;
33 import android.hardware.camera2.marshal.impl.MarshalQueryableBoolean;
34 import android.hardware.camera2.marshal.impl.MarshalQueryableColorSpaceTransform;
35 import android.hardware.camera2.marshal.impl.MarshalQueryableEnum;
36 import android.hardware.camera2.marshal.impl.MarshalQueryableHighSpeedVideoConfiguration;
37 import android.hardware.camera2.marshal.impl.MarshalQueryableMeteringRectangle;
38 import android.hardware.camera2.marshal.impl.MarshalQueryableNativeByteToInteger;
39 import android.hardware.camera2.marshal.impl.MarshalQueryablePair;
40 import android.hardware.camera2.marshal.impl.MarshalQueryableParcelable;
41 import android.hardware.camera2.marshal.impl.MarshalQueryablePrimitive;
42 import android.hardware.camera2.marshal.impl.MarshalQueryableRange;
43 import android.hardware.camera2.marshal.impl.MarshalQueryableRecommendedStreamConfiguration;
44 import android.hardware.camera2.marshal.impl.MarshalQueryableRect;
45 import android.hardware.camera2.marshal.impl.MarshalQueryableReprocessFormatsMap;
46 import android.hardware.camera2.marshal.impl.MarshalQueryableRggbChannelVector;
47 import android.hardware.camera2.marshal.impl.MarshalQueryableSize;
48 import android.hardware.camera2.marshal.impl.MarshalQueryableSizeF;
49 import android.hardware.camera2.marshal.impl.MarshalQueryableStreamConfiguration;
50 import android.hardware.camera2.marshal.impl.MarshalQueryableStreamConfigurationDuration;
51 import android.hardware.camera2.marshal.impl.MarshalQueryableString;
52 import android.hardware.camera2.params.Capability;
53 import android.hardware.camera2.params.DeviceStateSensorOrientationMap;
54 import android.hardware.camera2.params.DynamicRangeProfiles;
55 import android.hardware.camera2.params.Face;
56 import android.hardware.camera2.params.HighSpeedVideoConfiguration;
57 import android.hardware.camera2.params.LensShadingMap;
58 import android.hardware.camera2.params.MandatoryStreamCombination;
59 import android.hardware.camera2.params.MultiResolutionStreamConfigurationMap;
60 import android.hardware.camera2.params.OisSample;
61 import android.hardware.camera2.params.RecommendedStreamConfiguration;
62 import android.hardware.camera2.params.RecommendedStreamConfigurationMap;
63 import android.hardware.camera2.params.ReprocessFormatsMap;
64 import android.hardware.camera2.params.StreamConfiguration;
65 import android.hardware.camera2.params.StreamConfigurationDuration;
66 import android.hardware.camera2.params.StreamConfigurationMap;
67 import android.hardware.camera2.params.TonemapCurve;
68 import android.hardware.camera2.utils.ArrayUtils;
69 import android.hardware.camera2.utils.TypeReference;
70 import android.location.Location;
71 import android.location.LocationManager;
72 import android.os.Build;
73 import android.os.Parcel;
74 import android.os.Parcelable;
75 import android.os.ServiceSpecificException;
76 import android.util.Log;
77 import android.util.Range;
78 import android.util.Size;
79
80 import dalvik.annotation.optimization.FastNative;
81 import dalvik.system.VMRuntime;
82
83 import java.io.IOException;
84 import java.nio.ByteBuffer;
85 import java.nio.ByteOrder;
86 import java.util.ArrayList;
87 import java.util.Arrays;
88 import java.util.Collections;
89 import java.util.HashMap;
90 import java.util.HashSet;
91 import java.util.List;
92 import java.util.Map;
93 import java.util.Objects;
94 import java.util.Set;
95
96 /**
97 * Implementation of camera metadata marshal/unmarshal across Binder to
98 * the camera service
99 */
100 public class CameraMetadataNative implements Parcelable {
101
102 public static class Key<T> {
103 private boolean mHasTag;
104 private int mTag;
105 private long mVendorId = Long.MAX_VALUE;
106 private final Class<T> mType;
107 private final TypeReference<T> mTypeReference;
108 private final String mName;
109 private final String mFallbackName;
110 private final int mHash;
111
112 /**
113 * @hide
114 */
115 public Key(String name, Class<T> type, long vendorId) {
116 if (name == null) {
117 throw new NullPointerException("Key needs a valid name");
118 } else if (type == null) {
119 throw new NullPointerException("Type needs to be non-null");
120 }
121 mName = name;
122 mFallbackName = null;
123 mType = type;
124 mVendorId = vendorId;
125 mTypeReference = TypeReference.createSpecializedTypeReference(type);
126 mHash = mName.hashCode() ^ mTypeReference.hashCode();
127 }
128
129 /**
130 * @hide
131 */
132 public Key(String name, String fallbackName, Class<T> type) {
133 if (name == null) {
134 throw new NullPointerException("Key needs a valid name");
135 } else if (type == null) {
136 throw new NullPointerException("Type needs to be non-null");
137 }
138 mName = name;
139 mFallbackName = fallbackName;
140 mType = type;
141 mTypeReference = TypeReference.createSpecializedTypeReference(type);
142 mHash = mName.hashCode() ^ mTypeReference.hashCode();
143 }
144
145 /**
146 * Visible for testing only.
147 *
148 * <p>Use the CameraCharacteristics.Key, CaptureResult.Key, or CaptureRequest.Key
149 * for application code or vendor-extended keys.</p>
150 */
151 public Key(String name, Class<T> type) {
152 if (name == null) {
153 throw new NullPointerException("Key needs a valid name");
154 } else if (type == null) {
155 throw new NullPointerException("Type needs to be non-null");
156 }
157 mName = name;
158 mFallbackName = null;
159 mType = type;
160 mTypeReference = TypeReference.createSpecializedTypeReference(type);
161 mHash = mName.hashCode() ^ mTypeReference.hashCode();
162 }
163
164 /**
165 * Visible for testing only.
166 *
167 * <p>Use the CameraCharacteristics.Key, CaptureResult.Key, or CaptureRequest.Key
168 * for application code or vendor-extended keys.</p>
169 */
170 @SuppressWarnings("unchecked")
171 public Key(String name, TypeReference<T> typeReference) {
172 if (name == null) {
173 throw new NullPointerException("Key needs a valid name");
174 } else if (typeReference == null) {
175 throw new NullPointerException("TypeReference needs to be non-null");
176 }
177 mName = name;
178 mFallbackName = null;
179 mType = (Class<T>)typeReference.getRawType();
180 mTypeReference = typeReference;
181 mHash = mName.hashCode() ^ mTypeReference.hashCode();
182 }
183
184 /**
185 * Return a camelCase, period separated name formatted like:
186 * {@code "root.section[.subsections].name"}.
187 *
188 * <p>Built-in keys exposed by the Android SDK are always prefixed with {@code "android."};
189 * keys that are device/platform-specific are prefixed with {@code "com."}.</p>
190 *
191 * <p>For example, {@code CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP} would
192 * have a name of {@code "android.scaler.streamConfigurationMap"}; whereas a device
193 * specific key might look like {@code "com.google.nexus.data.private"}.</p>
194 *
195 * @return String representation of the key name
196 */
197 public final String getName() {
198 return mName;
199 }
200
201 /**
202 * {@inheritDoc}
203 */
204 @Override
205 public final int hashCode() {
206 return mHash;
207 }
208
209 /**
210 * Compare this key against other native keys, request keys, result keys, and
211 * characteristics keys.
212 *
213 * <p>Two keys are considered equal if their name and type reference are equal.</p>
214 *
215 * <p>Note that the equality against non-native keys is one-way. A native key may be equal
216 * to a result key; but that same result key will not be equal to a native key.</p>
217 */
218 @SuppressWarnings("rawtypes")
219 @Override
220 public final boolean equals(Object o) {
221 if (this == o) {
222 return true;
223 }
224
225 if (o == null || this.hashCode() != o.hashCode()) {
226 return false;
227 }
228
229 Key<?> lhs;
230
231 if (o instanceof CaptureResult.Key) {
232 lhs = ((CaptureResult.Key)o).getNativeKey();
233 } else if (o instanceof CaptureRequest.Key) {
234 lhs = ((CaptureRequest.Key)o).getNativeKey();
235 } else if (o instanceof CameraCharacteristics.Key) {
236 lhs = ((CameraCharacteristics.Key)o).getNativeKey();
237 } else if ((o instanceof Key)) {
238 lhs = (Key<?>)o;
239 } else {
240 return false;
241 }
242
243 return mName.equals(lhs.mName) && mTypeReference.equals(lhs.mTypeReference);
244 }
245
246 /**
247 * <p>
248 * Get the tag corresponding to this key. This enables insertion into the
249 * native metadata.
250 * </p>
251 *
252 * <p>This value is looked up the first time, and cached subsequently.</p>
253 *
254 * <p>This function may be called without cacheTag() if this is not a vendor key.
255 * If this is a vendor key, cacheTag() must be called first before getTag() can
256 * be called. Otherwise, mVendorId could be default (Long.MAX_VALUE) and vendor
257 * tag lookup could fail.</p>
258 *
259 * @return The tag numeric value corresponding to the string
260 */
261 @UnsupportedAppUsage
262 public final int getTag() {
263 if (!mHasTag) {
264 mTag = CameraMetadataNative.getTag(mName, mVendorId);
265 mHasTag = true;
266 }
267 return mTag;
268 }
269
270 /**
271 * Whether this key's tag is cached.
272 *
273 * @hide
274 */
275 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
276 public final boolean hasTag() {
277 return mHasTag;
278 }
279
280 /**
281 * Cache this key's tag.
282 *
283 * @hide
284 */
285 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
286 public final void cacheTag(int tag) {
287 mHasTag = true;
288 mTag = tag;
289 }
290
291 /**
292 * Get the raw class backing the type {@code T} for this key.
293 *
294 * <p>The distinction is only important if {@code T} is a generic, e.g.
295 * {@code Range<Integer>} since the nested type will be erased.</p>
296 */
297 public final Class<T> getType() {
298 // TODO: remove this; other places should use #getTypeReference() instead
299 return mType;
300 }
301
302 /**
303 * Get the vendor tag provider id.
304 *
305 * @hide
306 */
307 public final long getVendorId() {
308 return mVendorId;
309 }
310
311 /**
312 * Get the type reference backing the type {@code T} for this key.
313 *
314 * <p>The distinction is only important if {@code T} is a generic, e.g.
315 * {@code Range<Integer>} since the nested type will be retained.</p>
316 */
317 public final TypeReference<T> getTypeReference() {
318 return mTypeReference;
319 }
320 }
321
322 private static final String TAG = "CameraMetadataJV";
323 private static final boolean DEBUG = false;
324
325 // this should be in sync with HAL_PIXEL_FORMAT_BLOB defined in graphics.h
326 public static final int NATIVE_JPEG_FORMAT = 0x21;
327
328 private static final String CELLID_PROCESS = "CELLID";
329 private static final String GPS_PROCESS = "GPS";
330 private static final int FACE_LANDMARK_SIZE = 6;
331
332 private static final int MANDATORY_STREAM_CONFIGURATIONS_DEFAULT = 0;
333 private static final int MANDATORY_STREAM_CONFIGURATIONS_MAX_RESOLUTION = 1;
334 private static final int MANDATORY_STREAM_CONFIGURATIONS_CONCURRENT = 2;
335 private static final int MANDATORY_STREAM_CONFIGURATIONS_10BIT = 3;
336 private static final int MANDATORY_STREAM_CONFIGURATIONS_USE_CASE = 4;
337 private static final int MANDATORY_STREAM_CONFIGURATIONS_PREVIEW_STABILIZATION = 5;
338
339 private static String translateLocationProviderToProcess(final String provider) {
340 if (provider == null) {
341 return null;
342 }
343 switch(provider) {
344 case LocationManager.GPS_PROVIDER:
345 return GPS_PROCESS;
346 case LocationManager.NETWORK_PROVIDER:
347 return CELLID_PROCESS;
348 default:
349 return null;
350 }
351 }
352
353 private static String translateProcessToLocationProvider(final String process) {
354 if (process == null) {
355 return null;
356 }
357 switch(process) {
358 case GPS_PROCESS:
359 return LocationManager.GPS_PROVIDER;
360 case CELLID_PROCESS:
361 return LocationManager.NETWORK_PROVIDER;
362 default:
363 return null;
364 }
365 }
366
367 public CameraMetadataNative() {
368 super();
369 mMetadataPtr = nativeAllocate();
370 if (mMetadataPtr == 0) {
371 throw new OutOfMemoryError("Failed to allocate native CameraMetadata");
372 }
373 updateNativeAllocation();
374 }
375
376 /**
377 * Copy constructor - clone metadata
378 */
379 public CameraMetadataNative(CameraMetadataNative other) {
380 super();
381 mMetadataPtr = nativeAllocateCopy(other.mMetadataPtr);
382 if (mMetadataPtr == 0) {
383 throw new OutOfMemoryError("Failed to allocate native CameraMetadata");
384 }
385 updateNativeAllocation();
386 }
387
388 /**
389 * Move the contents from {@code other} into a new camera metadata instance.</p>
390 *
391 * <p>After this call, {@code other} will become empty.</p>
392 *
393 * @param other the previous metadata instance which will get pilfered
394 * @return a new metadata instance with the values from {@code other} moved into it
395 */
396 public static CameraMetadataNative move(CameraMetadataNative other) {
397 CameraMetadataNative newObject = new CameraMetadataNative();
398 newObject.swap(other);
399 return newObject;
400 }
401
402 /**
403 * Set all metadata values in the destination argument by using the corresponding
404 * values from the source. Metadata tags present in the destination and absent
405 * from the source will remain unmodified.
406 *
407 * @param dst Destination metadata
408 * @param src Source metadata
409 * @hide
410 */
411 public static void update(CameraMetadataNative dst, CameraMetadataNative src) {
412 nativeUpdate(dst.mMetadataPtr, src.mMetadataPtr);
413 }
414
415 public static final @android.annotation.NonNull Parcelable.Creator<CameraMetadataNative> CREATOR =
416 new Parcelable.Creator<CameraMetadataNative>() {
417 @Override
418 public CameraMetadataNative createFromParcel(Parcel in) {
419 CameraMetadataNative metadata = new CameraMetadataNative();
420 metadata.readFromParcel(in);
421 return metadata;
422 }
423
424 @Override
425 public CameraMetadataNative[] newArray(int size) {
426 return new CameraMetadataNative[size];
427 }
428 };
429
430 @Override
431 public int describeContents() {
432 return 0;
433 }
434
435 @Override
436 public void writeToParcel(Parcel dest, int flags) {
437 nativeWriteToParcel(dest, mMetadataPtr);
438 }
439
440 /**
441 * @hide
442 */
443 public <T> T get(CameraCharacteristics.Key<T> key) {
444 return get(key.getNativeKey());
445 }
446
447 /**
448 * @hide
449 */
450 public <T> T get(CaptureResult.Key<T> key) {
451 return get(key.getNativeKey());
452 }
453
454 /**
455 * @hide
456 */
457 public <T> T get(CaptureRequest.Key<T> key) {
458 return get(key.getNativeKey());
459 }
460
461 /**
462 * Look-up a metadata field value by its key.
463 *
464 * @param key a non-{@code null} key instance
465 * @return the field corresponding to the {@code key}, or {@code null} if no value was set
466 */
467 public <T> T get(Key<T> key) {
468 Objects.requireNonNull(key, "key must not be null");
469
470 // Check if key has been overridden to use a wrapper class on the java side.
471 GetCommand g = sGetCommandMap.get(key);
472 if (g != null) {
473 return g.getValue(this, key);
474 }
475 return getBase(key);
476 }
477
478 public void readFromParcel(Parcel in) {
479 nativeReadFromParcel(in, mMetadataPtr);
480 updateNativeAllocation();
481 }
482
483 /**
484 * Set the global client-side vendor tag descriptor to allow use of vendor
485 * tags in camera applications.
486 *
487 * @throws ServiceSpecificException
488 * @hide
489 */
490 public static void setupGlobalVendorTagDescriptor() throws ServiceSpecificException {
491 int err = nativeSetupGlobalVendorTagDescriptor();
492 if (err != 0) {
493 throw new ServiceSpecificException(err, "Failure to set up global vendor tags");
494 }
495 }
496
497 /**
498 * Set the global client-side vendor tag descriptor to allow use of vendor
499 * tags in camera applications.
500 *
501 * @return int An error code corresponding to one of the
502 * {@link ICameraService} error constants, or 0 on success.
503 */
504 private static native int nativeSetupGlobalVendorTagDescriptor();
505
506 /**
507 * Set a camera metadata field to a value. The field definitions can be
508 * found in {@link CameraCharacteristics}, {@link CaptureResult}, and
509 * {@link CaptureRequest}.
510 *
511 * @param key The metadata field to write.
512 * @param value The value to set the field to, which must be of a matching
513 * type to the key.
514 */
515 public <T> void set(Key<T> key, T value) {
516 SetCommand s = sSetCommandMap.get(key);
517 if (s != null) {
518 s.setValue(this, value);
519 return;
520 }
521
522 setBase(key, value);
523 }
524
525 public <T> void set(CaptureRequest.Key<T> key, T value) {
526 set(key.getNativeKey(), value);
527 }
528
529 public <T> void set(CaptureResult.Key<T> key, T value) {
530 set(key.getNativeKey(), value);
531 }
532
533 public <T> void set(CameraCharacteristics.Key<T> key, T value) {
534 set(key.getNativeKey(), value);
535 }
536
537 // Keep up-to-date with camera_metadata.h
538 /**
539 * @hide
540 */
541 public static final int TYPE_BYTE = 0;
542 /**
543 * @hide
544 */
545 public static final int TYPE_INT32 = 1;
546 /**
547 * @hide
548 */
549 public static final int TYPE_FLOAT = 2;
550 /**
551 * @hide
552 */
553 public static final int TYPE_INT64 = 3;
554 /**
555 * @hide
556 */
557 public static final int TYPE_DOUBLE = 4;
558 /**
559 * @hide
560 */
561 public static final int TYPE_RATIONAL = 5;
562 /**
563 * @hide
564 */
565 public static final int NUM_TYPES = 6;
566
567 private void close() {
568 // Delete native pointer, but does not clear it
569 nativeClose(mMetadataPtr);
570 mMetadataPtr = 0;
571
572 if (mBufferSize > 0) {
573 VMRuntime.getRuntime().registerNativeFree(mBufferSize);
574 }
575 mBufferSize = 0;
576 }
577
578 private <T> T getBase(CameraCharacteristics.Key<T> key) {
579 return getBase(key.getNativeKey());
580 }
581
582 private <T> T getBase(CaptureResult.Key<T> key) {
583 return getBase(key.getNativeKey());
584 }
585
586 private <T> T getBase(CaptureRequest.Key<T> key) {
587 return getBase(key.getNativeKey());
588 }
589
590 private <T> T getBase(Key<T> key) {
591 int tag;
592 if (key.hasTag()) {
593 tag = key.getTag();
594 } else {
595 tag = nativeGetTagFromKeyLocal(mMetadataPtr, key.getName());
596 key.cacheTag(tag);
597 }
598 byte[] values = readValues(tag);
599 if (values == null) {
600 // If the key returns null, use the fallback key if exists.
601 // This is to support old key names for the newly published keys.
602 if (key.mFallbackName == null) {
603 return null;
604 }
605 tag = nativeGetTagFromKeyLocal(mMetadataPtr, key.mFallbackName);
606 values = readValues(tag);
607 if (values == null) {
608 return null;
609 }
610 }
611
612 int nativeType = nativeGetTypeFromTagLocal(mMetadataPtr, tag);
613 Marshaler<T> marshaler = getMarshalerForKey(key, nativeType);
614 ByteBuffer buffer = ByteBuffer.wrap(values).order(ByteOrder.nativeOrder());
615 return marshaler.unmarshal(buffer);
616 }
617
618 // Use Command pattern here to avoid lots of expensive if/equals checks in get for overridden
619 // metadata.
620 private static final HashMap<Key<?>, GetCommand> sGetCommandMap =
621 new HashMap<Key<?>, GetCommand>();
622 static {
623 sGetCommandMap.put(
624 CameraCharacteristics.SCALER_AVAILABLE_FORMATS.getNativeKey(), new GetCommand() {
625 @Override
626 @SuppressWarnings("unchecked")
627 public <T> T getValue(CameraMetadataNative metadata, Key<T> key) {
628 return (T) metadata.getAvailableFormats();
629 }
630 });
631 sGetCommandMap.put(
632 CaptureResult.STATISTICS_FACES.getNativeKey(), new GetCommand() {
633 @Override
634 @SuppressWarnings("unchecked")
635 public <T> T getValue(CameraMetadataNative metadata, Key<T> key) {
636 return (T) metadata.getFaces();
637 }
638 });
639 sGetCommandMap.put(
640 CaptureResult.STATISTICS_FACE_RECTANGLES.getNativeKey(), new GetCommand() {
641 @Override
642 @SuppressWarnings("unchecked")
643 public <T> T getValue(CameraMetadataNative metadata, Key<T> key) {
644 return (T) metadata.getFaceRectangles();
645 }
646 });
647 sGetCommandMap.put(
648 CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP.getNativeKey(),
649 new GetCommand() {
650 @Override
651 @SuppressWarnings("unchecked")
652 public <T> T getValue(CameraMetadataNative metadata, Key<T> key) {
653 return (T) metadata.getStreamConfigurationMap();
654 }
655 });
656 sGetCommandMap.put(
657 CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP_MAXIMUM_RESOLUTION.getNativeKey(),
658 new GetCommand() {
659 @Override
660 @SuppressWarnings("unchecked")
661 public <T> T getValue(CameraMetadataNative metadata, Key<T> key) {
662 return (T) metadata.getStreamConfigurationMapMaximumResolution();
663 }
664 });
665 sGetCommandMap.put(
666 CameraCharacteristics.SCALER_MANDATORY_STREAM_COMBINATIONS.getNativeKey(),
667 new GetCommand() {
668 @Override
669 @SuppressWarnings("unchecked")
670 public <T> T getValue(CameraMetadataNative metadata, Key<T> key) {
671 return (T) metadata.getMandatoryStreamCombinations();
672 }
673 });
674 sGetCommandMap.put(
675 CameraCharacteristics.SCALER_MANDATORY_CONCURRENT_STREAM_COMBINATIONS.getNativeKey(),
676 new GetCommand() {
677 @Override
678 @SuppressWarnings("unchecked")
679 public <T> T getValue(CameraMetadataNative metadata, Key<T> key) {
680 return (T) metadata.getMandatoryConcurrentStreamCombinations();
681 }
682 });
683
684 sGetCommandMap.put(
685 CameraCharacteristics.SCALER_MANDATORY_TEN_BIT_OUTPUT_STREAM_COMBINATIONS.getNativeKey(),
686 new GetCommand() {
687 @Override
688 @SuppressWarnings("unchecked")
689 public <T> T getValue(CameraMetadataNative metadata, Key<T> key) {
690 return (T) metadata.getMandatory10BitStreamCombinations();
691 }
692 });
693
694 sGetCommandMap.put(
695 CameraCharacteristics.SCALER_MANDATORY_MAXIMUM_RESOLUTION_STREAM_COMBINATIONS.getNativeKey(),
696 new GetCommand() {
697 @Override
698 @SuppressWarnings("unchecked")
699 public <T> T getValue(CameraMetadataNative metadata, Key<T> key) {
700 return (T) metadata.getMandatoryMaximumResolutionStreamCombinations();
701 }
702 });
703
704 sGetCommandMap.put(
705 CameraCharacteristics.SCALER_MANDATORY_USE_CASE_STREAM_COMBINATIONS.getNativeKey(),
706 new GetCommand() {
707 @Override
708 @SuppressWarnings("unchecked")
709 public <T> T getValue(CameraMetadataNative metadata, Key<T> key) {
710 return (T) metadata.getMandatoryUseCaseStreamCombinations();
711 }
712 });
713 sGetCommandMap.put(
714 CameraCharacteristics.SCALER_MANDATORY_PREVIEW_STABILIZATION_OUTPUT_STREAM_COMBINATIONS.getNativeKey(),
715 new GetCommand() {
716 @Override
717 @SuppressWarnings("unchecked")
718 public <T> T getValue(CameraMetadataNative metadata, Key<T> key) {
719 return (T) metadata.getMandatoryPreviewStabilizationStreamCombinations();
720 }
721 });
722
723 sGetCommandMap.put(
724 CameraCharacteristics.CONTROL_MAX_REGIONS_AE.getNativeKey(), new GetCommand() {
725 @Override
726 @SuppressWarnings("unchecked")
727 public <T> T getValue(CameraMetadataNative metadata, Key<T> key) {
728 return (T) metadata.getMaxRegions(key);
729 }
730 });
731 sGetCommandMap.put(
732 CameraCharacteristics.CONTROL_MAX_REGIONS_AWB.getNativeKey(), new GetCommand() {
733 @Override
734 @SuppressWarnings("unchecked")
735 public <T> T getValue(CameraMetadataNative metadata, Key<T> key) {
736 return (T) metadata.getMaxRegions(key);
737 }
738 });
739 sGetCommandMap.put(
740 CameraCharacteristics.CONTROL_MAX_REGIONS_AF.getNativeKey(), new GetCommand() {
741 @Override
742 @SuppressWarnings("unchecked")
743 public <T> T getValue(CameraMetadataNative metadata, Key<T> key) {
744 return (T) metadata.getMaxRegions(key);
745 }
746 });
747 sGetCommandMap.put(
748 CameraCharacteristics.REQUEST_MAX_NUM_OUTPUT_RAW.getNativeKey(), new GetCommand() {
749 @Override
750 @SuppressWarnings("unchecked")
751 public <T> T getValue(CameraMetadataNative metadata, Key<T> key) {
752 return (T) metadata.getMaxNumOutputs(key);
753 }
754 });
755 sGetCommandMap.put(
756 CameraCharacteristics.REQUEST_MAX_NUM_OUTPUT_PROC.getNativeKey(), new GetCommand() {
757 @Override
758 @SuppressWarnings("unchecked")
759 public <T> T getValue(CameraMetadataNative metadata, Key<T> key) {
760 return (T) metadata.getMaxNumOutputs(key);
761 }
762 });
763 sGetCommandMap.put(
764 CameraCharacteristics.REQUEST_MAX_NUM_OUTPUT_PROC_STALLING.getNativeKey(),
765 new GetCommand() {
766 @Override
767 @SuppressWarnings("unchecked")
768 public <T> T getValue(CameraMetadataNative metadata, Key<T> key) {
769 return (T) metadata.getMaxNumOutputs(key);
770 }
771 });
772 sGetCommandMap.put(
773 CaptureRequest.TONEMAP_CURVE.getNativeKey(), new GetCommand() {
774 @Override
775 @SuppressWarnings("unchecked")
776 public <T> T getValue(CameraMetadataNative metadata, Key<T> key) {
777 return (T) metadata.getTonemapCurve();
778 }
779 });
780 sGetCommandMap.put(
781 CaptureResult.JPEG_GPS_LOCATION.getNativeKey(), new GetCommand() {
782 @Override
783 @SuppressWarnings("unchecked")
784 public <T> T getValue(CameraMetadataNative metadata, Key<T> key) {
785 return (T) metadata.getGpsLocation();
786 }
787 });
788 sGetCommandMap.put(
789 CaptureResult.STATISTICS_LENS_SHADING_CORRECTION_MAP.getNativeKey(),
790 new GetCommand() {
791 @Override
792 @SuppressWarnings("unchecked")
793 public <T> T getValue(CameraMetadataNative metadata, Key<T> key) {
794 return (T) metadata.getLensShadingMap();
795 }
796 });
797 sGetCommandMap.put(
798 CameraCharacteristics.INFO_DEVICE_STATE_SENSOR_ORIENTATION_MAP.getNativeKey(),
799 new GetCommand() {
800 @Override
801 @SuppressWarnings("unchecked")
802 public <T> T getValue(CameraMetadataNative metadata, Key<T> key) {
803 return (T) metadata.getDeviceStateOrientationMap();
804 }
805 });
806 sGetCommandMap.put(
807 CameraCharacteristics.REQUEST_AVAILABLE_DYNAMIC_RANGE_PROFILES.getNativeKey(),
808 new GetCommand() {
809 @Override
810 @SuppressWarnings("unchecked")
811 public <T> T getValue(CameraMetadataNative metadata, Key<T> key) {
812 return (T) metadata.getDynamicRangeProfiles();
813 }
814 });
815 sGetCommandMap.put(
816 CaptureResult.STATISTICS_OIS_SAMPLES.getNativeKey(),
817 new GetCommand() {
818 @Override
819 @SuppressWarnings("unchecked")
820 public <T> T getValue(CameraMetadataNative metadata, Key<T> key) {
821 return (T) metadata.getOisSamples();
822 }
823 });
824 sGetCommandMap.put(
825 CameraCharacteristics.CONTROL_AVAILABLE_EXTENDED_SCENE_MODE_CAPABILITIES.getNativeKey(),
826 new GetCommand() {
827 @Override
828 @SuppressWarnings("unchecked")
829 public <T> T getValue(CameraMetadataNative metadata, Key<T> key) {
830 return (T) metadata.getExtendedSceneModeCapabilities();
831 }
832 });
833 sGetCommandMap.put(
834 CameraCharacteristics.SCALER_MULTI_RESOLUTION_STREAM_CONFIGURATION_MAP.getNativeKey(),
835 new GetCommand() {
836 @Override
837 @SuppressWarnings("unchecked")
838 public <T> T getValue(CameraMetadataNative metadata, Key<T> key) {
839 return (T) metadata.getMultiResolutionStreamConfigurationMap();
840 }
841 });
842 }
843
844 private int[] getAvailableFormats() {
845 int[] availableFormats = getBase(CameraCharacteristics.SCALER_AVAILABLE_FORMATS);
846 if (availableFormats != null) {
847 for (int i = 0; i < availableFormats.length; i++) {
848 // JPEG has different value between native and managed side, need override.
849 if (availableFormats[i] == NATIVE_JPEG_FORMAT) {
850 availableFormats[i] = ImageFormat.JPEG;
851 }
852 }
853 }
854
855 return availableFormats;
856 }
857
858 private boolean setFaces(Face[] faces) {
859 if (faces == null) {
860 return false;
861 }
862
863 int numFaces = faces.length;
864
865 // Detect if all faces are SIMPLE or not; count # of valid faces
866 boolean fullMode = true;
867 for (Face face : faces) {
868 if (face == null) {
869 numFaces--;
870 Log.w(TAG, "setFaces - null face detected, skipping");
871 continue;
872 }
873
874 if (face.getId() == Face.ID_UNSUPPORTED) {
875 fullMode = false;
876 }
877 }
878
879 Rect[] faceRectangles = new Rect[numFaces];
880 byte[] faceScores = new byte[numFaces];
881 int[] faceIds = null;
882 int[] faceLandmarks = null;
883
884 if (fullMode) {
885 faceIds = new int[numFaces];
886 faceLandmarks = new int[numFaces * FACE_LANDMARK_SIZE];
887 }
888
889 int i = 0;
890 for (Face face : faces) {
891 if (face == null) {
892 continue;
893 }
894
895 faceRectangles[i] = face.getBounds();
896 faceScores[i] = (byte)face.getScore();
897
898 if (fullMode) {
899 faceIds[i] = face.getId();
900
901 int j = 0;
902
903 faceLandmarks[i * FACE_LANDMARK_SIZE + j++] = face.getLeftEyePosition().x;
904 faceLandmarks[i * FACE_LANDMARK_SIZE + j++] = face.getLeftEyePosition().y;
905 faceLandmarks[i * FACE_LANDMARK_SIZE + j++] = face.getRightEyePosition().x;
906 faceLandmarks[i * FACE_LANDMARK_SIZE + j++] = face.getRightEyePosition().y;
907 faceLandmarks[i * FACE_LANDMARK_SIZE + j++] = face.getMouthPosition().x;
908 faceLandmarks[i * FACE_LANDMARK_SIZE + j++] = face.getMouthPosition().y;
909 }
910
911 i++;
912 }
913
914 set(CaptureResult.STATISTICS_FACE_RECTANGLES, faceRectangles);
915 set(CaptureResult.STATISTICS_FACE_IDS, faceIds);
916 set(CaptureResult.STATISTICS_FACE_LANDMARKS, faceLandmarks);
917 set(CaptureResult.STATISTICS_FACE_SCORES, faceScores);
918
919 return true;
920 }
921
922 private Face[] getFaces() {
923 Integer faceDetectMode = get(CaptureResult.STATISTICS_FACE_DETECT_MODE);
924 byte[] faceScores = get(CaptureResult.STATISTICS_FACE_SCORES);
925 Rect[] faceRectangles = get(CaptureResult.STATISTICS_FACE_RECTANGLES);
926 int[] faceIds = get(CaptureResult.STATISTICS_FACE_IDS);
927 int[] faceLandmarks = get(CaptureResult.STATISTICS_FACE_LANDMARKS);
928
929 if (areValuesAllNull(faceDetectMode, faceScores, faceRectangles, faceIds, faceLandmarks)) {
930 return null;
931 }
932
933 if (faceDetectMode == null) {
934 Log.w(TAG, "Face detect mode metadata is null, assuming the mode is SIMPLE");
935 faceDetectMode = CaptureResult.STATISTICS_FACE_DETECT_MODE_SIMPLE;
936 } else if (faceDetectMode > CaptureResult.STATISTICS_FACE_DETECT_MODE_FULL) {
937 // Face detect mode is larger than FULL, assuming the mode is FULL
938 faceDetectMode = CaptureResult.STATISTICS_FACE_DETECT_MODE_FULL;
939 } else {
940 if (faceDetectMode == CaptureResult.STATISTICS_FACE_DETECT_MODE_OFF) {
941 return new Face[0];
942 }
943 if (faceDetectMode != CaptureResult.STATISTICS_FACE_DETECT_MODE_SIMPLE &&
944 faceDetectMode != CaptureResult.STATISTICS_FACE_DETECT_MODE_FULL) {
945 Log.w(TAG, "Unknown face detect mode: " + faceDetectMode);
946 return new Face[0];
947 }
948 }
949
950 // Face scores and rectangles are required by SIMPLE and FULL mode.
951 if (faceScores == null || faceRectangles == null) {
952 Log.w(TAG, "Expect face scores and rectangles to be non-null");
953 return new Face[0];
954 } else if (faceScores.length != faceRectangles.length) {
955 Log.w(TAG, String.format("Face score size(%d) doesn match face rectangle size(%d)!",
956 faceScores.length, faceRectangles.length));
957 }
958
959 // To be safe, make number of faces is the minimal of all face info metadata length.
960 int numFaces = Math.min(faceScores.length, faceRectangles.length);
961 // Face id and landmarks are only required by FULL mode.
962 if (faceDetectMode == CaptureResult.STATISTICS_FACE_DETECT_MODE_FULL) {
963 if (faceIds == null || faceLandmarks == null) {
964 Log.w(TAG, "Expect face ids and landmarks to be non-null for FULL mode," +
965 "fallback to SIMPLE mode");
966 faceDetectMode = CaptureResult.STATISTICS_FACE_DETECT_MODE_SIMPLE;
967 } else {
968 if (faceIds.length != numFaces ||
969 faceLandmarks.length != numFaces * FACE_LANDMARK_SIZE) {
970 Log.w(TAG, String.format("Face id size(%d), or face landmark size(%d) don't" +
971 "match face number(%d)!",
972 faceIds.length, faceLandmarks.length * FACE_LANDMARK_SIZE, numFaces));
973 }
974 // To be safe, make number of faces is the minimal of all face info metadata length.
975 numFaces = Math.min(numFaces, faceIds.length);
976 numFaces = Math.min(numFaces, faceLandmarks.length / FACE_LANDMARK_SIZE);
977 }
978 }
979
980 ArrayList<Face> faceList = new ArrayList<Face>();
981 if (faceDetectMode == CaptureResult.STATISTICS_FACE_DETECT_MODE_SIMPLE) {
982 for (int i = 0; i < numFaces; i++) {
983 if (faceScores[i] <= Face.SCORE_MAX &&
984 faceScores[i] >= Face.SCORE_MIN) {
985 faceList.add(new Face(faceRectangles[i], faceScores[i]));
986 }
987 }
988 } else {
989 // CaptureResult.STATISTICS_FACE_DETECT_MODE_FULL
990 for (int i = 0; i < numFaces; i++) {
991 if (faceScores[i] <= Face.SCORE_MAX &&
992 faceScores[i] >= Face.SCORE_MIN &&
993 faceIds[i] >= 0) {
994 Point leftEye = new Point(faceLandmarks[i*FACE_LANDMARK_SIZE],
995 faceLandmarks[i*FACE_LANDMARK_SIZE+1]);
996 Point rightEye = new Point(faceLandmarks[i*FACE_LANDMARK_SIZE+2],
997 faceLandmarks[i*FACE_LANDMARK_SIZE+3]);
998 Point mouth = new Point(faceLandmarks[i*FACE_LANDMARK_SIZE+4],
999 faceLandmarks[i*FACE_LANDMARK_SIZE+5]);
1000 Face face = new Face(faceRectangles[i], faceScores[i], faceIds[i],
1001 leftEye, rightEye, mouth);
1002 faceList.add(face);
1003 }
1004 }
1005 }
1006 Face[] faces = new Face[faceList.size()];
1007 faceList.toArray(faces);
1008 return faces;
1009 }
1010
1011 // Face rectangles are defined as (left, top, right, bottom) instead of
1012 // (left, top, width, height) at the native level, so the normal Rect
1013 // conversion that does (l, t, w, h) -> (l, t, r, b) is unnecessary. Undo
1014 // that conversion here for just the faces.
1015 private Rect[] getFaceRectangles() {
1016 Rect[] faceRectangles = getBase(CaptureResult.STATISTICS_FACE_RECTANGLES);
1017 if (faceRectangles == null) return null;
1018
1019 Rect[] fixedFaceRectangles = new Rect[faceRectangles.length];
1020 for (int i = 0; i < faceRectangles.length; i++) {
1021 fixedFaceRectangles[i] = new Rect(
1022 faceRectangles[i].left,
1023 faceRectangles[i].top,
1024 faceRectangles[i].right - faceRectangles[i].left,
1025 faceRectangles[i].bottom - faceRectangles[i].top);
1026 }
1027 return fixedFaceRectangles;
1028 }
1029
1030 private boolean setLensShadingMap(LensShadingMap lensShadingMap) {
1031 if (lensShadingMap == null) {
1032 return false;
1033 }
1034 float[] lsmArray = new float[lensShadingMap.getGainFactorCount()];
1035 lensShadingMap.copyGainFactors(lsmArray, 0);
1036 setBase(CaptureResult.STATISTICS_LENS_SHADING_MAP, lsmArray);
1037
1038 Size s = new Size(lensShadingMap.getRowCount(), lensShadingMap.getColumnCount());
1039 setBase(CameraCharacteristics.LENS_INFO_SHADING_MAP_SIZE, s);
1040 return true;
1041 }
1042
1043 private LensShadingMap getLensShadingMap() {
1044 float[] lsmArray = getBase(CaptureResult.STATISTICS_LENS_SHADING_MAP);
1045 Size s = get(CameraCharacteristics.LENS_INFO_SHADING_MAP_SIZE);
1046
1047 // Do not warn if lsmArray is null while s is not. This is valid.
1048 if (lsmArray == null) {
1049 return null;
1050 }
1051
1052 if (s == null) {
1053 Log.w(TAG, "getLensShadingMap - Lens shading map size was null.");
1054 return null;
1055 }
1056
1057 LensShadingMap map = new LensShadingMap(lsmArray, s.getHeight(), s.getWidth());
1058 return map;
1059 }
1060
1061 private DeviceStateSensorOrientationMap getDeviceStateOrientationMap() {
1062 long[] mapArray = getBase(CameraCharacteristics.INFO_DEVICE_STATE_ORIENTATIONS);
1063
1064 // Do not warn if map is null while s is not. This is valid.
1065 if (mapArray == null) {
1066 return null;
1067 }
1068
1069 DeviceStateSensorOrientationMap map = new DeviceStateSensorOrientationMap(mapArray);
1070 return map;
1071 }
1072
1073 private DynamicRangeProfiles getDynamicRangeProfiles() {
1074 long[] profileArray = getBase(
1075 CameraCharacteristics.REQUEST_AVAILABLE_DYNAMIC_RANGE_PROFILES_MAP);
1076
1077 if (profileArray == null) {
1078 return null;
1079 }
1080
1081 return new DynamicRangeProfiles(profileArray);
1082 }
1083
1084 private Location getGpsLocation() {
1085 String processingMethod = get(CaptureResult.JPEG_GPS_PROCESSING_METHOD);
1086 double[] coords = get(CaptureResult.JPEG_GPS_COORDINATES);
1087 Long timeStamp = get(CaptureResult.JPEG_GPS_TIMESTAMP);
1088
1089 if (areValuesAllNull(processingMethod, coords, timeStamp)) {
1090 return null;
1091 }
1092
1093 Location l = new Location(translateProcessToLocationProvider(processingMethod));
1094 if (timeStamp != null) {
1095 // Location expects timestamp in [ms.]
1096 l.setTime(timeStamp * 1000);
1097 } else {
1098 Log.w(TAG, "getGpsLocation - No timestamp for GPS location.");
1099 }
1100
1101 if (coords != null) {
1102 l.setLatitude(coords[0]);
1103 l.setLongitude(coords[1]);
1104 l.setAltitude(coords[2]);
1105 } else {
1106 Log.w(TAG, "getGpsLocation - No coordinates for GPS location");
1107 }
1108
1109 return l;
1110 }
1111
1112 private boolean setGpsLocation(Location l) {
1113 if (l == null) {
1114 return false;
1115 }
1116
1117 double[] coords = { l.getLatitude(), l.getLongitude(), l.getAltitude() };
1118 String processMethod = translateLocationProviderToProcess(l.getProvider());
1119 //JPEG_GPS_TIMESTAMP expects sec. instead of msec.
1120 long timestamp = l.getTime() / 1000;
1121
1122 set(CaptureRequest.JPEG_GPS_TIMESTAMP, timestamp);
1123 set(CaptureRequest.JPEG_GPS_COORDINATES, coords);
1124
1125 if (processMethod == null) {
1126 Log.w(TAG, "setGpsLocation - No process method, Location is not from a GPS or NETWORK" +
1127 "provider");
1128 } else {
1129 setBase(CaptureRequest.JPEG_GPS_PROCESSING_METHOD, processMethod);
1130 }
1131 return true;
1132 }
1133
1134 private void parseRecommendedConfigurations(RecommendedStreamConfiguration[] configurations,
1135 StreamConfigurationMap fullMap, boolean isDepth,
1136 ArrayList<ArrayList<StreamConfiguration>> /*out*/streamConfigList,
1137 ArrayList<ArrayList<StreamConfigurationDuration>> /*out*/streamDurationList,
1138 ArrayList<ArrayList<StreamConfigurationDuration>> /*out*/streamStallList,
1139 boolean[] /*out*/supportsPrivate) {
1140
1141 streamConfigList.ensureCapacity(RecommendedStreamConfigurationMap.MAX_USECASE_COUNT);
1142 streamDurationList.ensureCapacity(RecommendedStreamConfigurationMap.MAX_USECASE_COUNT);
1143 streamStallList.ensureCapacity(RecommendedStreamConfigurationMap.MAX_USECASE_COUNT);
1144 for (int i = 0; i < RecommendedStreamConfigurationMap.MAX_USECASE_COUNT; i++) {
1145 streamConfigList.add(new ArrayList<StreamConfiguration> ());
1146 streamDurationList.add(new ArrayList<StreamConfigurationDuration> ());
1147 streamStallList.add(new ArrayList<StreamConfigurationDuration> ());
1148 }
1149
1150 for (RecommendedStreamConfiguration c : configurations) {
1151 int width = c.getWidth();
1152 int height = c.getHeight();
1153 int internalFormat = c.getFormat();
1154 int publicFormat =
1155 (isDepth) ? StreamConfigurationMap.depthFormatToPublic(internalFormat) :
1156 StreamConfigurationMap.imageFormatToPublic(internalFormat);
1157 Size sz = new Size(width, height);
1158 int usecaseBitmap = c.getUsecaseBitmap();
1159
1160 if (!c.isInput()) {
1161 StreamConfigurationDuration minDurationConfiguration = null;
1162 StreamConfigurationDuration stallDurationConfiguration = null;
1163
1164 StreamConfiguration streamConfiguration = new StreamConfiguration(internalFormat,
1165 width, height, /*input*/ false);
1166
1167 long minFrameDuration = fullMap.getOutputMinFrameDuration(publicFormat, sz);
1168 if (minFrameDuration > 0) {
1169 minDurationConfiguration = new StreamConfigurationDuration(internalFormat,
1170 width, height, minFrameDuration);
1171 }
1172
1173 long stallDuration = fullMap.getOutputStallDuration(publicFormat, sz);
1174 if (stallDuration > 0) {
1175 stallDurationConfiguration = new StreamConfigurationDuration(internalFormat,
1176 width, height, stallDuration);
1177 }
1178
1179 for (int i = 0; i < RecommendedStreamConfigurationMap.MAX_USECASE_COUNT; i++) {
1180 if ((usecaseBitmap & (1 << i)) != 0) {
1181 ArrayList<StreamConfiguration> sc = streamConfigList.get(i);
1182 sc.add(streamConfiguration);
1183
1184 if (minFrameDuration > 0) {
1185 ArrayList<StreamConfigurationDuration> scd = streamDurationList.get(i);
1186 scd.add(minDurationConfiguration);
1187 }
1188
1189 if (stallDuration > 0) {
1190 ArrayList<StreamConfigurationDuration> scs = streamStallList.get(i);
1191 scs.add(stallDurationConfiguration);
1192 }
1193
1194 if ((supportsPrivate != null) && !supportsPrivate[i] &&
1195 (publicFormat == ImageFormat.PRIVATE)) {
1196 supportsPrivate[i] = true;
1197 }
1198 }
1199 }
1200 } else {
1201 if (usecaseBitmap != (1 << RecommendedStreamConfigurationMap.USECASE_ZSL)) {
1202 throw new IllegalArgumentException("Recommended input stream configurations " +
1203 "should only be advertised in the ZSL use case!");
1204 }
1205
1206 ArrayList<StreamConfiguration> sc = streamConfigList.get(
1207 RecommendedStreamConfigurationMap.USECASE_ZSL);
1208 sc.add(new StreamConfiguration(internalFormat,
1209 width, height, /*input*/ true));
1210 }
1211 }
1212 }
1213
1214 private class StreamConfigurationData {
1215 StreamConfiguration [] streamConfigurationArray = null;
1216 StreamConfigurationDuration [] minDurationArray = null;
1217 StreamConfigurationDuration [] stallDurationArray = null;
1218 }
1219
1220 public void initializeStreamConfigurationData(ArrayList<StreamConfiguration> sc,
1221 ArrayList<StreamConfigurationDuration> scd, ArrayList<StreamConfigurationDuration> scs,
1222 StreamConfigurationData /*out*/scData) {
1223 if ((scData == null) || (sc == null)) {
1224 return;
1225 }
1226
1227 scData.streamConfigurationArray = new StreamConfiguration[sc.size()];
1228 scData.streamConfigurationArray = sc.toArray(scData.streamConfigurationArray);
1229
1230 if ((scd != null) && !scd.isEmpty()) {
1231 scData.minDurationArray = new StreamConfigurationDuration[scd.size()];
1232 scData.minDurationArray = scd.toArray(scData.minDurationArray);
1233 } else {
1234 scData.minDurationArray = new StreamConfigurationDuration[0];
1235 }
1236
1237 if ((scs != null) && !scs.isEmpty()) {
1238 scData.stallDurationArray = new StreamConfigurationDuration[scs.size()];
1239 scData.stallDurationArray = scs.toArray(scData.stallDurationArray);
1240 } else {
1241 scData.stallDurationArray = new StreamConfigurationDuration[0];
1242 }
1243 }
1244
1245 /**
1246 * Retrieve the list of recommended stream configurations.
1247 *
1248 * @return A list of recommended stream configuration maps for each common use case or null
1249 * in case the recommended stream configurations are invalid or incomplete.
1250 * @hide
1251 */
1252 public ArrayList<RecommendedStreamConfigurationMap> getRecommendedStreamConfigurations() {
1253 RecommendedStreamConfiguration[] configurations = getBase(
1254 CameraCharacteristics.SCALER_AVAILABLE_RECOMMENDED_STREAM_CONFIGURATIONS);
1255 RecommendedStreamConfiguration[] depthConfigurations = getBase(
1256 CameraCharacteristics.DEPTH_AVAILABLE_RECOMMENDED_DEPTH_STREAM_CONFIGURATIONS);
1257 if ((configurations == null) && (depthConfigurations == null)) {
1258 return null;
1259 }
1260
1261 StreamConfigurationMap fullMap = getStreamConfigurationMap();
1262 ArrayList<RecommendedStreamConfigurationMap> recommendedConfigurations =
1263 new ArrayList<RecommendedStreamConfigurationMap> ();
1264
1265 ArrayList<ArrayList<StreamConfiguration>> streamConfigList =
1266 new ArrayList<ArrayList<StreamConfiguration>>();
1267 ArrayList<ArrayList<StreamConfigurationDuration>> streamDurationList =
1268 new ArrayList<ArrayList<StreamConfigurationDuration>>();
1269 ArrayList<ArrayList<StreamConfigurationDuration>> streamStallList =
1270 new ArrayList<ArrayList<StreamConfigurationDuration>>();
1271 boolean[] supportsPrivate =
1272 new boolean[RecommendedStreamConfigurationMap.MAX_USECASE_COUNT];
1273 try {
1274 if (configurations != null) {
1275 parseRecommendedConfigurations(configurations, fullMap, /*isDepth*/ false,
1276 streamConfigList, streamDurationList, streamStallList, supportsPrivate);
1277 }
1278 } catch (IllegalArgumentException e) {
1279 Log.e(TAG, "Failed parsing the recommended stream configurations!");
1280 return null;
1281 }
1282
1283 ArrayList<ArrayList<StreamConfiguration>> depthStreamConfigList =
1284 new ArrayList<ArrayList<StreamConfiguration>>();
1285 ArrayList<ArrayList<StreamConfigurationDuration>> depthStreamDurationList =
1286 new ArrayList<ArrayList<StreamConfigurationDuration>>();
1287 ArrayList<ArrayList<StreamConfigurationDuration>> depthStreamStallList =
1288 new ArrayList<ArrayList<StreamConfigurationDuration>>();
1289 if (depthConfigurations != null) {
1290 try {
1291 parseRecommendedConfigurations(depthConfigurations, fullMap, /*isDepth*/ true,
1292 depthStreamConfigList, depthStreamDurationList, depthStreamStallList,
1293 /*supportsPrivate*/ null);
1294 } catch (IllegalArgumentException e) {
1295 Log.e(TAG, "Failed parsing the recommended depth stream configurations!");
1296 return null;
1297 }
1298 }
1299
1300 ReprocessFormatsMap inputOutputFormatsMap = getBase(
1301 CameraCharacteristics.SCALER_AVAILABLE_RECOMMENDED_INPUT_OUTPUT_FORMATS_MAP);
1302 HighSpeedVideoConfiguration[] highSpeedVideoConfigurations = getBase(
1303 CameraCharacteristics.CONTROL_AVAILABLE_HIGH_SPEED_VIDEO_CONFIGURATIONS);
1304 boolean listHighResolution = isBurstSupported();
1305 recommendedConfigurations.ensureCapacity(
1306 RecommendedStreamConfigurationMap.MAX_USECASE_COUNT);
1307 for (int i = 0; i < RecommendedStreamConfigurationMap.MAX_USECASE_COUNT; i++) {
1308 StreamConfigurationData scData = new StreamConfigurationData();
1309 if (configurations != null) {
1310 initializeStreamConfigurationData(streamConfigList.get(i),
1311 streamDurationList.get(i), streamStallList.get(i), scData);
1312 }
1313
1314 StreamConfigurationData depthScData = new StreamConfigurationData();
1315 if (depthConfigurations != null) {
1316 initializeStreamConfigurationData(depthStreamConfigList.get(i),
1317 depthStreamDurationList.get(i), depthStreamStallList.get(i), depthScData);
1318 }
1319
1320 if ((scData.streamConfigurationArray == null ||
1321 scData.streamConfigurationArray.length == 0) &&
1322 (depthScData.streamConfigurationArray == null ||
1323 depthScData.streamConfigurationArray.length == 0)) {
1324 recommendedConfigurations.add(null);
1325 continue;
1326 }
1327
1328 // Dynamic depth streams involve alot of SW processing and currently cannot be
1329 // recommended.
1330 StreamConfigurationMap map = null;
1331 switch (i) {
1332 case RecommendedStreamConfigurationMap.USECASE_PREVIEW:
1333 case RecommendedStreamConfigurationMap.USECASE_RAW:
1334 case RecommendedStreamConfigurationMap.USECASE_LOW_LATENCY_SNAPSHOT:
1335 case RecommendedStreamConfigurationMap.USECASE_VIDEO_SNAPSHOT:
1336 map = new StreamConfigurationMap(scData.streamConfigurationArray,
1337 scData.minDurationArray, scData.stallDurationArray,
1338 /*depthconfiguration*/ null, /*depthminduration*/ null,
1339 /*depthstallduration*/ null,
1340 /*dynamicDepthConfigurations*/ null,
1341 /*dynamicDepthMinFrameDurations*/ null,
1342 /*dynamicDepthStallDurations*/ null,
1343 /*heicconfiguration*/ null,
1344 /*heicminduration*/ null,
1345 /*heicstallduration*/ null,
1346 /*highspeedvideoconfigurations*/ null,
1347 /*inputoutputformatsmap*/ null, listHighResolution, supportsPrivate[i]);
1348 break;
1349 case RecommendedStreamConfigurationMap.USECASE_RECORD:
1350 map = new StreamConfigurationMap(scData.streamConfigurationArray,
1351 scData.minDurationArray, scData.stallDurationArray,
1352 /*depthconfiguration*/ null, /*depthminduration*/ null,
1353 /*depthstallduration*/ null,
1354 /*dynamicDepthConfigurations*/ null,
1355 /*dynamicDepthMinFrameDurations*/ null,
1356 /*dynamicDepthStallDurations*/ null,
1357 /*heicconfiguration*/ null,
1358 /*heicminduration*/ null,
1359 /*heicstallduration*/ null,
1360 highSpeedVideoConfigurations,
1361 /*inputoutputformatsmap*/ null, listHighResolution, supportsPrivate[i]);
1362 break;
1363 case RecommendedStreamConfigurationMap.USECASE_ZSL:
1364 map = new StreamConfigurationMap(scData.streamConfigurationArray,
1365 scData.minDurationArray, scData.stallDurationArray,
1366 depthScData.streamConfigurationArray, depthScData.minDurationArray,
1367 depthScData.stallDurationArray,
1368 /*dynamicDepthConfigurations*/ null,
1369 /*dynamicDepthMinFrameDurations*/ null,
1370 /*dynamicDepthStallDurations*/ null,
1371 /*heicconfiguration*/ null,
1372 /*heicminduration*/ null,
1373 /*heicstallduration*/ null,
1374 /*highSpeedVideoConfigurations*/ null,
1375 inputOutputFormatsMap, listHighResolution, supportsPrivate[i]);
1376 break;
1377 default:
1378 map = new StreamConfigurationMap(scData.streamConfigurationArray,
1379 scData.minDurationArray, scData.stallDurationArray,
1380 depthScData.streamConfigurationArray, depthScData.minDurationArray,
1381 depthScData.stallDurationArray,
1382 /*dynamicDepthConfigurations*/ null,
1383 /*dynamicDepthMinFrameDurations*/ null,
1384 /*dynamicDepthStallDurations*/ null,
1385 /*heicconfiguration*/ null,
1386 /*heicminduration*/ null,
1387 /*heicstallduration*/ null,
1388 /*highSpeedVideoConfigurations*/ null,
1389 /*inputOutputFormatsMap*/ null, listHighResolution, supportsPrivate[i]);
1390 }
1391
1392 recommendedConfigurations.add(new RecommendedStreamConfigurationMap(map, /*usecase*/i,
1393 supportsPrivate[i]));
1394 }
1395
1396 return recommendedConfigurations;
1397 }
1398
1399 private boolean isCapabilitySupported(int capabilityRequested) {
1400 boolean ret = false;
1401
1402 int[] capabilities = getBase(CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES);
1403 for (int capability : capabilities) {
1404 if (capabilityRequested == capability) {
1405 ret = true;
1406 break;
1407 }
1408 }
1409
1410 return ret;
1411 }
1412
1413 /**
1414 * @hide
1415 */
1416 public boolean isUltraHighResolutionSensor() {
1417 return isCapabilitySupported(
1418 CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_ULTRA_HIGH_RESOLUTION_SENSOR);
1419
1420 }
1421 private boolean isBurstSupported() {
1422 return isCapabilitySupported(
1423 CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_BURST_CAPTURE);
1424 }
1425
1426 private boolean isPreviewStabilizationSupported() {
1427 boolean ret = false;
1428
1429 int[] videoStabilizationModes =
1430 getBase(CameraCharacteristics.CONTROL_AVAILABLE_VIDEO_STABILIZATION_MODES);
1431 if (videoStabilizationModes == null) {
1432 return false;
1433 }
1434 for (int mode : videoStabilizationModes) {
1435 if (mode == CameraMetadata.CONTROL_VIDEO_STABILIZATION_MODE_PREVIEW_STABILIZATION) {
1436 ret = true;
1437 break;
1438 }
1439 }
1440
1441 return ret;
1442 }
1443
1444 private MandatoryStreamCombination[] getMandatoryStreamCombinationsHelper(
1445 int mandatoryStreamsType) {
1446 int[] capabilities = getBase(CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES);
1447 ArrayList<Integer> caps = new ArrayList<Integer>();
1448 caps.ensureCapacity(capabilities.length);
1449 for (int c : capabilities) {
1450 caps.add(new Integer(c));
1451 }
1452 int hwLevel = getBase(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL);
1453 MandatoryStreamCombination.Builder build = new MandatoryStreamCombination.Builder(
1454 mCameraId, hwLevel, mDisplaySize, caps, getStreamConfigurationMap(),
1455 getStreamConfigurationMapMaximumResolution(), isPreviewStabilizationSupported());
1456
1457 List<MandatoryStreamCombination> combs = null;
1458 switch (mandatoryStreamsType) {
1459 case MANDATORY_STREAM_CONFIGURATIONS_CONCURRENT:
1460 combs = build.getAvailableMandatoryConcurrentStreamCombinations();
1461 break;
1462 case MANDATORY_STREAM_CONFIGURATIONS_MAX_RESOLUTION:
1463 combs = build.getAvailableMandatoryMaximumResolutionStreamCombinations();
1464 break;
1465 case MANDATORY_STREAM_CONFIGURATIONS_10BIT:
1466 combs = build.getAvailableMandatory10BitStreamCombinations();
1467 break;
1468 case MANDATORY_STREAM_CONFIGURATIONS_USE_CASE:
1469 combs = build.getAvailableMandatoryStreamUseCaseCombinations();
1470 break;
1471 case MANDATORY_STREAM_CONFIGURATIONS_PREVIEW_STABILIZATION:
1472 combs = build.getAvailableMandatoryPreviewStabilizedStreamCombinations();
1473 break;
1474 default:
1475 combs = build.getAvailableMandatoryStreamCombinations();
1476 }
1477 if ((combs != null) && (!combs.isEmpty())) {
1478 MandatoryStreamCombination[] combArray = new MandatoryStreamCombination[combs.size()];
1479 combArray = combs.toArray(combArray);
1480 return combArray;
1481 }
1482 return null;
1483 }
1484
1485 private MandatoryStreamCombination[] getMandatory10BitStreamCombinations() {
1486 return getMandatoryStreamCombinationsHelper(MANDATORY_STREAM_CONFIGURATIONS_10BIT);
1487 }
1488
1489 private MandatoryStreamCombination[] getMandatoryConcurrentStreamCombinations() {
1490 if (!mHasMandatoryConcurrentStreams) {
1491 return null;
1492 }
1493 return getMandatoryStreamCombinationsHelper(MANDATORY_STREAM_CONFIGURATIONS_CONCURRENT);
1494 }
1495
1496 private MandatoryStreamCombination[] getMandatoryMaximumResolutionStreamCombinations() {
1497 if (!isUltraHighResolutionSensor()) {
1498 return null;
1499 }
1500 return getMandatoryStreamCombinationsHelper(MANDATORY_STREAM_CONFIGURATIONS_MAX_RESOLUTION);
1501 }
1502
1503 private MandatoryStreamCombination[] getMandatoryStreamCombinations() {
1504 return getMandatoryStreamCombinationsHelper(MANDATORY_STREAM_CONFIGURATIONS_DEFAULT);
1505 }
1506
1507 private MandatoryStreamCombination[] getMandatoryUseCaseStreamCombinations() {
1508 return getMandatoryStreamCombinationsHelper(MANDATORY_STREAM_CONFIGURATIONS_USE_CASE);
1509 }
1510
1511 private MandatoryStreamCombination[] getMandatoryPreviewStabilizationStreamCombinations() {
1512 return getMandatoryStreamCombinationsHelper(
1513 MANDATORY_STREAM_CONFIGURATIONS_PREVIEW_STABILIZATION);
1514 }
1515
1516 private StreamConfigurationMap getStreamConfigurationMap() {
1517 StreamConfiguration[] configurations = getBase(
1518 CameraCharacteristics.SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
1519 StreamConfigurationDuration[] minFrameDurations = getBase(
1520 CameraCharacteristics.SCALER_AVAILABLE_MIN_FRAME_DURATIONS);
1521 StreamConfigurationDuration[] stallDurations = getBase(
1522 CameraCharacteristics.SCALER_AVAILABLE_STALL_DURATIONS);
1523 StreamConfiguration[] depthConfigurations = getBase(
1524 CameraCharacteristics.DEPTH_AVAILABLE_DEPTH_STREAM_CONFIGURATIONS);
1525 StreamConfigurationDuration[] depthMinFrameDurations = getBase(
1526 CameraCharacteristics.DEPTH_AVAILABLE_DEPTH_MIN_FRAME_DURATIONS);
1527 StreamConfigurationDuration[] depthStallDurations = getBase(
1528 CameraCharacteristics.DEPTH_AVAILABLE_DEPTH_STALL_DURATIONS);
1529 StreamConfiguration[] dynamicDepthConfigurations = getBase(
1530 CameraCharacteristics.DEPTH_AVAILABLE_DYNAMIC_DEPTH_STREAM_CONFIGURATIONS);
1531 StreamConfigurationDuration[] dynamicDepthMinFrameDurations = getBase(
1532 CameraCharacteristics.DEPTH_AVAILABLE_DYNAMIC_DEPTH_MIN_FRAME_DURATIONS);
1533 StreamConfigurationDuration[] dynamicDepthStallDurations = getBase(
1534 CameraCharacteristics.DEPTH_AVAILABLE_DYNAMIC_DEPTH_STALL_DURATIONS);
1535 StreamConfiguration[] heicConfigurations = getBase(
1536 CameraCharacteristics.HEIC_AVAILABLE_HEIC_STREAM_CONFIGURATIONS);
1537 StreamConfigurationDuration[] heicMinFrameDurations = getBase(
1538 CameraCharacteristics.HEIC_AVAILABLE_HEIC_MIN_FRAME_DURATIONS);
1539 StreamConfigurationDuration[] heicStallDurations = getBase(
1540 CameraCharacteristics.HEIC_AVAILABLE_HEIC_STALL_DURATIONS);
1541 HighSpeedVideoConfiguration[] highSpeedVideoConfigurations = getBase(
1542 CameraCharacteristics.CONTROL_AVAILABLE_HIGH_SPEED_VIDEO_CONFIGURATIONS);
1543 ReprocessFormatsMap inputOutputFormatsMap = getBase(
1544 CameraCharacteristics.SCALER_AVAILABLE_INPUT_OUTPUT_FORMATS_MAP);
1545 boolean listHighResolution = isBurstSupported();
1546 return new StreamConfigurationMap(
1547 configurations, minFrameDurations, stallDurations,
1548 depthConfigurations, depthMinFrameDurations, depthStallDurations,
1549 dynamicDepthConfigurations, dynamicDepthMinFrameDurations,
1550 dynamicDepthStallDurations, heicConfigurations,
1551 heicMinFrameDurations, heicStallDurations,
1552 highSpeedVideoConfigurations, inputOutputFormatsMap,
1553 listHighResolution);
1554 }
1555
1556 private StreamConfigurationMap getStreamConfigurationMapMaximumResolution() {
1557 if (!isUltraHighResolutionSensor()) {
1558 return null;
1559 }
1560 StreamConfiguration[] configurations = getBase(
1561 CameraCharacteristics.SCALER_AVAILABLE_STREAM_CONFIGURATIONS_MAXIMUM_RESOLUTION);
1562 StreamConfigurationDuration[] minFrameDurations = getBase(
1563 CameraCharacteristics.SCALER_AVAILABLE_MIN_FRAME_DURATIONS_MAXIMUM_RESOLUTION);
1564 StreamConfigurationDuration[] stallDurations = getBase(
1565 CameraCharacteristics.SCALER_AVAILABLE_STALL_DURATIONS_MAXIMUM_RESOLUTION);
1566 StreamConfiguration[] depthConfigurations = getBase(
1567 CameraCharacteristics.DEPTH_AVAILABLE_DEPTH_STREAM_CONFIGURATIONS_MAXIMUM_RESOLUTION);
1568 StreamConfigurationDuration[] depthMinFrameDurations = getBase(
1569 CameraCharacteristics.DEPTH_AVAILABLE_DEPTH_MIN_FRAME_DURATIONS_MAXIMUM_RESOLUTION);
1570 StreamConfigurationDuration[] depthStallDurations = getBase(
1571 CameraCharacteristics.DEPTH_AVAILABLE_DEPTH_STALL_DURATIONS_MAXIMUM_RESOLUTION);
1572 StreamConfiguration[] dynamicDepthConfigurations = getBase(
1573 CameraCharacteristics.DEPTH_AVAILABLE_DYNAMIC_DEPTH_STREAM_CONFIGURATIONS_MAXIMUM_RESOLUTION);
1574 StreamConfigurationDuration[] dynamicDepthMinFrameDurations = getBase(
1575 CameraCharacteristics.DEPTH_AVAILABLE_DYNAMIC_DEPTH_MIN_FRAME_DURATIONS_MAXIMUM_RESOLUTION);
1576 StreamConfigurationDuration[] dynamicDepthStallDurations = getBase(
1577 CameraCharacteristics.DEPTH_AVAILABLE_DYNAMIC_DEPTH_STALL_DURATIONS_MAXIMUM_RESOLUTION);
1578 StreamConfiguration[] heicConfigurations = getBase(
1579 CameraCharacteristics.HEIC_AVAILABLE_HEIC_STREAM_CONFIGURATIONS_MAXIMUM_RESOLUTION);
1580 StreamConfigurationDuration[] heicMinFrameDurations = getBase(
1581 CameraCharacteristics.HEIC_AVAILABLE_HEIC_MIN_FRAME_DURATIONS_MAXIMUM_RESOLUTION);
1582 StreamConfigurationDuration[] heicStallDurations = getBase(
1583 CameraCharacteristics.HEIC_AVAILABLE_HEIC_STALL_DURATIONS_MAXIMUM_RESOLUTION);
1584 HighSpeedVideoConfiguration[] highSpeedVideoConfigurations = getBase(
1585 CameraCharacteristics.CONTROL_AVAILABLE_HIGH_SPEED_VIDEO_CONFIGURATIONS_MAXIMUM_RESOLUTION);
1586 ReprocessFormatsMap inputOutputFormatsMap = getBase(
1587 CameraCharacteristics.SCALER_AVAILABLE_INPUT_OUTPUT_FORMATS_MAP_MAXIMUM_RESOLUTION);
1588 // TODO: Is this correct, burst capability shouldn't necessarily correspond to max res mode
1589 boolean listHighResolution = isBurstSupported();
1590 return new StreamConfigurationMap(
1591 configurations, minFrameDurations, stallDurations,
1592 depthConfigurations, depthMinFrameDurations, depthStallDurations,
1593 dynamicDepthConfigurations, dynamicDepthMinFrameDurations,
1594 dynamicDepthStallDurations, heicConfigurations,
1595 heicMinFrameDurations, heicStallDurations,
1596 highSpeedVideoConfigurations, inputOutputFormatsMap,
1597 listHighResolution, false);
1598 }
1599
1600 private <T> Integer getMaxRegions(Key<T> key) {
1601 final int AE = 0;
1602 final int AWB = 1;
1603 final int AF = 2;
1604
1605 // The order of the elements is: (AE, AWB, AF)
1606 int[] maxRegions = getBase(CameraCharacteristics.CONTROL_MAX_REGIONS);
1607
1608 if (maxRegions == null) {
1609 return null;
1610 }
1611
1612 if (key.equals(CameraCharacteristics.CONTROL_MAX_REGIONS_AE)) {
1613 return maxRegions[AE];
1614 } else if (key.equals(CameraCharacteristics.CONTROL_MAX_REGIONS_AWB)) {
1615 return maxRegions[AWB];
1616 } else if (key.equals(CameraCharacteristics.CONTROL_MAX_REGIONS_AF)) {
1617 return maxRegions[AF];
1618 } else {
1619 throw new AssertionError("Invalid key " + key);
1620 }
1621 }
1622
1623 private <T> Integer getMaxNumOutputs(Key<T> key) {
1624 final int RAW = 0;
1625 final int PROC = 1;
1626 final int PROC_STALLING = 2;
1627
1628 // The order of the elements is: (raw, proc+nonstalling, proc+stalling)
1629 int[] maxNumOutputs = getBase(CameraCharacteristics.REQUEST_MAX_NUM_OUTPUT_STREAMS);
1630
1631 if (maxNumOutputs == null) {
1632 return null;
1633 }
1634
1635 if (key.equals(CameraCharacteristics.REQUEST_MAX_NUM_OUTPUT_RAW)) {
1636 return maxNumOutputs[RAW];
1637 } else if (key.equals(CameraCharacteristics.REQUEST_MAX_NUM_OUTPUT_PROC)) {
1638 return maxNumOutputs[PROC];
1639 } else if (key.equals(CameraCharacteristics.REQUEST_MAX_NUM_OUTPUT_PROC_STALLING)) {
1640 return maxNumOutputs[PROC_STALLING];
1641 } else {
1642 throw new AssertionError("Invalid key " + key);
1643 }
1644 }
1645
1646 private <T> TonemapCurve getTonemapCurve() {
1647 float[] red = getBase(CaptureRequest.TONEMAP_CURVE_RED);
1648 float[] green = getBase(CaptureRequest.TONEMAP_CURVE_GREEN);
1649 float[] blue = getBase(CaptureRequest.TONEMAP_CURVE_BLUE);
1650
1651 if (areValuesAllNull(red, green, blue)) {
1652 return null;
1653 }
1654
1655 if (red == null || green == null || blue == null) {
1656 Log.w(TAG, "getTonemapCurve - missing tone curve components");
1657 return null;
1658 }
1659 TonemapCurve tc = new TonemapCurve(red, green, blue);
1660 return tc;
1661 }
1662
1663 private OisSample[] getOisSamples() {
1664 long[] timestamps = getBase(CaptureResult.STATISTICS_OIS_TIMESTAMPS);
1665 float[] xShifts = getBase(CaptureResult.STATISTICS_OIS_X_SHIFTS);
1666 float[] yShifts = getBase(CaptureResult.STATISTICS_OIS_Y_SHIFTS);
1667
1668 if (timestamps == null) {
1669 if (xShifts != null) {
1670 throw new AssertionError("timestamps is null but xShifts is not");
1671 }
1672
1673 if (yShifts != null) {
1674 throw new AssertionError("timestamps is null but yShifts is not");
1675 }
1676
1677 return null;
1678 }
1679
1680 if (xShifts == null) {
1681 throw new AssertionError("timestamps is not null but xShifts is");
1682 }
1683
1684 if (yShifts == null) {
1685 throw new AssertionError("timestamps is not null but yShifts is");
1686 }
1687
1688 if (xShifts.length != timestamps.length) {
1689 throw new AssertionError(String.format(
1690 "timestamps has %d entries but xShifts has %d", timestamps.length,
1691 xShifts.length));
1692 }
1693
1694 if (yShifts.length != timestamps.length) {
1695 throw new AssertionError(String.format(
1696 "timestamps has %d entries but yShifts has %d", timestamps.length,
1697 yShifts.length));
1698 }
1699
1700 OisSample[] samples = new OisSample[timestamps.length];
1701 for (int i = 0; i < timestamps.length; i++) {
1702 samples[i] = new OisSample(timestamps[i], xShifts[i], yShifts[i]);
1703 }
1704 return samples;
1705 }
1706
1707 private Capability[] getExtendedSceneModeCapabilities() {
1708 int[] maxSizes =
1709 getBase(CameraCharacteristics.CONTROL_AVAILABLE_EXTENDED_SCENE_MODE_MAX_SIZES);
1710 float[] zoomRanges = getBase(
1711 CameraCharacteristics.CONTROL_AVAILABLE_EXTENDED_SCENE_MODE_ZOOM_RATIO_RANGES);
1712 Range<Float> zoomRange = getBase(CameraCharacteristics.CONTROL_ZOOM_RATIO_RANGE);
1713 float maxDigitalZoom = getBase(CameraCharacteristics.SCALER_AVAILABLE_MAX_DIGITAL_ZOOM);
1714
1715 if (maxSizes == null) {
1716 return null;
1717 }
1718 if (maxSizes.length % 3 != 0) {
1719 throw new AssertionError("availableExtendedSceneModeMaxSizes must be tuples of "
1720 + "[mode, width, height]");
1721 }
1722 int numExtendedSceneModes = maxSizes.length / 3;
1723 int numExtendedSceneModeZoomRanges = 0;
1724 if (zoomRanges != null) {
1725 if (zoomRanges.length % 2 != 0) {
1726 throw new AssertionError("availableExtendedSceneModeZoomRanges must be tuples of "
1727 + "[minZoom, maxZoom]");
1728 }
1729 numExtendedSceneModeZoomRanges = zoomRanges.length / 2;
1730 if (numExtendedSceneModes - numExtendedSceneModeZoomRanges != 1) {
1731 throw new AssertionError("Number of extended scene mode zoom ranges must be 1 "
1732 + "less than number of supported modes");
1733 }
1734 }
1735
1736 float modeOffMinZoomRatio = 1.0f;
1737 float modeOffMaxZoomRatio = maxDigitalZoom;
1738 if (zoomRange != null) {
1739 modeOffMinZoomRatio = zoomRange.getLower();
1740 modeOffMaxZoomRatio = zoomRange.getUpper();
1741 }
1742
1743 Capability[] capabilities = new Capability[numExtendedSceneModes];
1744 for (int i = 0, j = 0; i < numExtendedSceneModes; i++) {
1745 int mode = maxSizes[3 * i];
1746 int width = maxSizes[3 * i + 1];
1747 int height = maxSizes[3 * i + 2];
1748 if (mode != CameraMetadata.CONTROL_EXTENDED_SCENE_MODE_DISABLED
1749 && j < numExtendedSceneModeZoomRanges) {
1750 capabilities[i] = new Capability(mode, width, height, zoomRanges[2 * j],
1751 zoomRanges[2 * j + 1]);
1752 j++;
1753 } else {
1754 capabilities[i] = new Capability(mode, width, height, modeOffMinZoomRatio,
1755 modeOffMaxZoomRatio);
1756 }
1757 }
1758
1759 return capabilities;
1760 }
1761
1762 private <T> void setBase(CameraCharacteristics.Key<T> key, T value) {
1763 setBase(key.getNativeKey(), value);
1764 }
1765
1766 private <T> void setBase(CaptureResult.Key<T> key, T value) {
1767 setBase(key.getNativeKey(), value);
1768 }
1769
1770 private <T> void setBase(CaptureRequest.Key<T> key, T value) {
1771 setBase(key.getNativeKey(), value);
1772 }
1773
1774 private <T> void setBase(Key<T> key, T value) {
1775 int tag;
1776 if (key.hasTag()) {
1777 tag = key.getTag();
1778 } else {
1779 tag = nativeGetTagFromKeyLocal(mMetadataPtr, key.getName());
1780 key.cacheTag(tag);
1781 }
1782 if (value == null) {
1783 // Erase the entry
1784 writeValues(tag, /*src*/null);
1785 return;
1786 } // else update the entry to a new value
1787
1788 int nativeType = nativeGetTypeFromTagLocal(mMetadataPtr, tag);
1789 Marshaler<T> marshaler = getMarshalerForKey(key, nativeType);
1790 int size = marshaler.calculateMarshalSize(value);
1791
1792 // TODO: Optimization. Cache the byte[] and reuse if the size is big enough.
1793 byte[] values = new byte[size];
1794
1795 ByteBuffer buffer = ByteBuffer.wrap(values).order(ByteOrder.nativeOrder());
1796 marshaler.marshal(value, buffer);
1797
1798 writeValues(tag, values);
1799 }
1800
1801 // Use Command pattern here to avoid lots of expensive if/equals checks in get for overridden
1802 // metadata.
1803 private static final HashMap<Key<?>, SetCommand> sSetCommandMap =
1804 new HashMap<Key<?>, SetCommand>();
1805 static {
1806 sSetCommandMap.put(CameraCharacteristics.SCALER_AVAILABLE_FORMATS.getNativeKey(),
1807 new SetCommand() {
1808 @Override
1809 public <T> void setValue(CameraMetadataNative metadata, T value) {
1810 metadata.setAvailableFormats((int[]) value);
1811 }
1812 });
1813 sSetCommandMap.put(CaptureResult.STATISTICS_FACE_RECTANGLES.getNativeKey(),
1814 new SetCommand() {
1815 @Override
1816 public <T> void setValue(CameraMetadataNative metadata, T value) {
1817 metadata.setFaceRectangles((Rect[]) value);
1818 }
1819 });
1820 sSetCommandMap.put(CaptureResult.STATISTICS_FACES.getNativeKey(),
1821 new SetCommand() {
1822 @Override
1823 public <T> void setValue(CameraMetadataNative metadata, T value) {
1824 metadata.setFaces((Face[])value);
1825 }
1826 });
1827 sSetCommandMap.put(CaptureRequest.TONEMAP_CURVE.getNativeKey(), new SetCommand() {
1828 @Override
1829 public <T> void setValue(CameraMetadataNative metadata, T value) {
1830 metadata.setTonemapCurve((TonemapCurve) value);
1831 }
1832 });
1833 sSetCommandMap.put(CaptureResult.JPEG_GPS_LOCATION.getNativeKey(), new SetCommand() {
1834 @Override
1835 public <T> void setValue(CameraMetadataNative metadata, T value) {
1836 metadata.setGpsLocation((Location) value);
1837 }
1838 });
1839 sSetCommandMap.put(CaptureRequest.SCALER_CROP_REGION.getNativeKey(),
1840 new SetCommand() {
1841 @Override
1842 public <T> void setValue(CameraMetadataNative metadata, T value) {
1843 metadata.setScalerCropRegion((Rect) value);
1844 }
1845 });
1846 sSetCommandMap.put(CaptureRequest.CONTROL_AWB_REGIONS.getNativeKey(),
1847 new SetCommand() {
1848 @Override
1849 public <T> void setValue(CameraMetadataNative metadata, T value) {
1850 metadata.setAWBRegions(value);
1851 }
1852 });
1853 sSetCommandMap.put(CaptureRequest.CONTROL_AF_REGIONS.getNativeKey(),
1854 new SetCommand() {
1855 @Override
1856 public <T> void setValue(CameraMetadataNative metadata, T value) {
1857 metadata.setAFRegions(value);
1858 }
1859 });
1860 sSetCommandMap.put(CaptureRequest.CONTROL_AE_REGIONS.getNativeKey(),
1861 new SetCommand() {
1862 @Override
1863 public <T> void setValue(CameraMetadataNative metadata, T value) {
1864 metadata.setAERegions(value);
1865 }
1866 });
1867 sSetCommandMap.put(CaptureResult.STATISTICS_LENS_SHADING_CORRECTION_MAP.getNativeKey(),
1868 new SetCommand() {
1869 @Override
1870 public <T> void setValue(CameraMetadataNative metadata, T value) {
1871 metadata.setLensShadingMap((LensShadingMap) value);
1872 }
1873 });
1874 }
1875
1876 private boolean setAvailableFormats(int[] value) {
1877 int[] availableFormat = value;
1878 if (value == null) {
1879 // Let setBase() to handle the null value case.
1880 return false;
1881 }
1882
1883 int[] newValues = new int[availableFormat.length];
1884 for (int i = 0; i < availableFormat.length; i++) {
1885 newValues[i] = availableFormat[i];
1886 if (availableFormat[i] == ImageFormat.JPEG) {
1887 newValues[i] = NATIVE_JPEG_FORMAT;
1888 }
1889 }
1890
1891 setBase(CameraCharacteristics.SCALER_AVAILABLE_FORMATS, newValues);
1892 return true;
1893 }
1894
1895 /**
1896 * Convert Face Rectangles from managed side to native side as they have different definitions.
1897 * <p>
1898 * Managed side face rectangles are defined as: left, top, width, height.
1899 * Native side face rectangles are defined as: left, top, right, bottom.
1900 * The input face rectangle need to be converted to native side definition when set is called.
1901 * </p>
1902 *
1903 * @param faceRects Input face rectangles.
1904 * @return true if face rectangles can be set successfully. Otherwise, Let the caller
1905 * (setBase) to handle it appropriately.
1906 */
1907 private boolean setFaceRectangles(Rect[] faceRects) {
1908 if (faceRects == null) {
1909 return false;
1910 }
1911
1912 Rect[] newFaceRects = new Rect[faceRects.length];
1913 for (int i = 0; i < newFaceRects.length; i++) {
1914 newFaceRects[i] = new Rect(
1915 faceRects[i].left,
1916 faceRects[i].top,
1917 faceRects[i].right + faceRects[i].left,
1918 faceRects[i].bottom + faceRects[i].top);
1919 }
1920
1921 setBase(CaptureResult.STATISTICS_FACE_RECTANGLES, newFaceRects);
1922 return true;
1923 }
1924
1925 private <T> boolean setTonemapCurve(TonemapCurve tc) {
1926 if (tc == null) {
1927 return false;
1928 }
1929
1930 float[][] curve = new float[3][];
1931 for (int i = TonemapCurve.CHANNEL_RED; i <= TonemapCurve.CHANNEL_BLUE; i++) {
1932 int pointCount = tc.getPointCount(i);
1933 curve[i] = new float[pointCount * TonemapCurve.POINT_SIZE];
1934 tc.copyColorCurve(i, curve[i], 0);
1935 }
1936 setBase(CaptureRequest.TONEMAP_CURVE_RED, curve[0]);
1937 setBase(CaptureRequest.TONEMAP_CURVE_GREEN, curve[1]);
1938 setBase(CaptureRequest.TONEMAP_CURVE_BLUE, curve[2]);
1939
1940 return true;
1941 }
1942
1943 private <T> boolean setScalerCropRegion(Rect cropRegion) {
1944 if (cropRegion == null) {
1945 return false;
1946 }
1947 setBase(CaptureRequest.SCALER_CROP_REGION_SET, true);
1948 setBase(CaptureRequest.SCALER_CROP_REGION, cropRegion);
1949 return true;
1950 }
1951
1952 private <T> boolean setAFRegions(T afRegions) {
1953 if (afRegions == null) {
1954 return false;
1955 }
1956 setBase(CaptureRequest.CONTROL_AF_REGIONS_SET, true);
1957 // The cast to CaptureRequest.Key is needed since java does not support template
1958 // specialization and we need to route this method to
1959 // setBase(CaptureRequest.Key<T> key, T value)
1960 setBase((CaptureRequest.Key)CaptureRequest.CONTROL_AF_REGIONS, afRegions);
1961 return true;
1962 }
1963
1964 private <T> boolean setAERegions(T aeRegions) {
1965 if (aeRegions == null) {
1966 return false;
1967 }
1968 setBase(CaptureRequest.CONTROL_AE_REGIONS_SET, true);
1969 setBase((CaptureRequest.Key)CaptureRequest.CONTROL_AE_REGIONS, aeRegions);
1970 return true;
1971 }
1972
1973 private <T> boolean setAWBRegions(T awbRegions) {
1974 if (awbRegions == null) {
1975 return false;
1976 }
1977 setBase(CaptureRequest.CONTROL_AWB_REGIONS_SET, true);
1978 setBase((CaptureRequest.Key)CaptureRequest.CONTROL_AWB_REGIONS, awbRegions);
1979 return true;
1980 }
1981
1982 private void updateNativeAllocation() {
1983 long currentBufferSize = nativeGetBufferSize(mMetadataPtr);
1984
1985 if (currentBufferSize != mBufferSize) {
1986 if (mBufferSize > 0) {
1987 VMRuntime.getRuntime().registerNativeFree(mBufferSize);
1988 }
1989
1990 mBufferSize = currentBufferSize;
1991
1992 if (mBufferSize > 0) {
1993 VMRuntime.getRuntime().registerNativeAllocation(mBufferSize);
1994 }
1995 }
1996 }
1997
1998 private int mCameraId = -1;
1999 private boolean mHasMandatoryConcurrentStreams = false;
2000 private Size mDisplaySize = new Size(0, 0);
2001 private long mBufferSize = 0;
2002 private MultiResolutionStreamConfigurationMap mMultiResolutionStreamConfigurationMap = null;
2003
2004 /**
2005 * Set the current camera Id.
2006 *
2007 * @param cameraId Current camera id.
2008 *
2009 * @hide
2010 */
2011 public void setCameraId(int cameraId) {
2012 mCameraId = cameraId;
2013 }
2014
2015 /**
2016 * Set the current camera Id.
2017 *
2018 * @param hasMandatoryConcurrentStreams whether the metadata advertises mandatory concurrent
2019 * streams.
2020 *
2021 * @hide
2022 */
2023 public void setHasMandatoryConcurrentStreams(boolean hasMandatoryConcurrentStreams) {
2024 mHasMandatoryConcurrentStreams = hasMandatoryConcurrentStreams;
2025 }
2026
2027 /**
2028 * Set the current display size.
2029 *
2030 * @param displaySize The current display size.
2031 *
2032 * @hide
2033 */
2034 public void setDisplaySize(Size displaySize) {
2035 mDisplaySize = displaySize;
2036 }
2037
2038 /**
2039 * Set the multi-resolution stream configuration map.
2040 *
2041 * @param multiResolutionMap The multi-resolution stream configuration map.
2042 *
2043 * @hide
2044 */
2045 public void setMultiResolutionStreamConfigurationMap(
2046 @NonNull Map<String, StreamConfiguration[]> multiResolutionMap) {
2047 mMultiResolutionStreamConfigurationMap =
2048 new MultiResolutionStreamConfigurationMap(multiResolutionMap);
2049 }
2050
2051 /**
2052 * Get the multi-resolution stream configuration map.
2053 *
2054 * @return The multi-resolution stream configuration map.
2055 *
2056 * @hide
2057 */
2058 public MultiResolutionStreamConfigurationMap getMultiResolutionStreamConfigurationMap() {
2059 return mMultiResolutionStreamConfigurationMap;
2060 }
2061
2062 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2063 private long mMetadataPtr; // native std::shared_ptr<CameraMetadata>*
2064
2065 @FastNative
2066 private static native long nativeAllocate();
2067 @FastNative
2068 private static native long nativeAllocateCopy(long ptr)
2069 throws NullPointerException;
2070
2071
2072 @FastNative
2073 private static native void nativeUpdate(long dst, long src);
2074 private static synchronized native void nativeWriteToParcel(Parcel dest, long ptr);
2075 private static synchronized native void nativeReadFromParcel(Parcel source, long ptr);
2076 private static synchronized native void nativeSwap(long ptr, long otherPtr)
2077 throws NullPointerException;
2078 @FastNative
2079 private static native void nativeSetVendorId(long ptr, long vendorId);
2080 private static synchronized native void nativeClose(long ptr);
2081 private static synchronized native boolean nativeIsEmpty(long ptr);
2082 private static synchronized native int nativeGetEntryCount(long ptr);
2083 private static synchronized native long nativeGetBufferSize(long ptr);
2084
2085 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2086 private static synchronized native byte[] nativeReadValues(int tag, long ptr);
2087 private static synchronized native void nativeWriteValues(int tag, byte[] src, long ptr);
2088 private static synchronized native void nativeDump(long ptr) throws IOException; // dump to LOGD
2089
2090 private static synchronized native ArrayList nativeGetAllVendorKeys(long ptr, Class keyClass);
2091 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2092 private static synchronized native int nativeGetTagFromKeyLocal(long ptr, String keyName)
2093 throws IllegalArgumentException;
2094 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2095 private static synchronized native int nativeGetTypeFromTagLocal(long ptr, int tag)
2096 throws IllegalArgumentException;
2097 @FastNative
2098 private static native int nativeGetTagFromKey(String keyName, long vendorId)
2099 throws IllegalArgumentException;
2100 @FastNative
2101 private static native int nativeGetTypeFromTag(int tag, long vendorId)
2102 throws IllegalArgumentException;
2103
2104 /**
2105 * <p>Perform a 0-copy swap of the internal metadata with another object.</p>
2106 *
2107 * <p>Useful to convert a CameraMetadata into e.g. a CaptureRequest.</p>
2108 *
2109 * @param other Metadata to swap with
2110 * @throws NullPointerException if other was null
2111 * @hide
2112 */
2113 public void swap(CameraMetadataNative other) {
2114 nativeSwap(mMetadataPtr, other.mMetadataPtr);
2115 mCameraId = other.mCameraId;
2116 mHasMandatoryConcurrentStreams = other.mHasMandatoryConcurrentStreams;
2117 mDisplaySize = other.mDisplaySize;
2118 mMultiResolutionStreamConfigurationMap = other.mMultiResolutionStreamConfigurationMap;
2119 updateNativeAllocation();
2120 other.updateNativeAllocation();
2121 }
2122
2123 /**
2124 * Set the native metadata vendor id.
2125 *
2126 * @hide
2127 */
2128 public void setVendorId(long vendorId) {
2129 nativeSetVendorId(mMetadataPtr, vendorId);
2130 }
2131
2132 /**
2133 * @hide
2134 */
2135 public int getEntryCount() {
2136 return nativeGetEntryCount(mMetadataPtr);
2137 }
2138
2139 /**
2140 * Does this metadata contain at least 1 entry?
2141 *
2142 * @hide
2143 */
2144 public boolean isEmpty() {
2145 return nativeIsEmpty(mMetadataPtr);
2146 }
2147
2148
2149 /**
2150 * Retrieves the pointer to the native shared_ptr<CameraMetadata> as a Java long.
2151 *
2152 * @hide
2153 */
2154 public long getMetadataPtr() {
2155 return mMetadataPtr;
2156 }
2157
2158 /**
2159 * Return a list containing keys of the given key class for all defined vendor tags.
2160 *
2161 * @hide
2162 */
2163 public <K> ArrayList<K> getAllVendorKeys(Class<K> keyClass) {
2164 if (keyClass == null) {
2165 throw new NullPointerException();
2166 }
2167 return (ArrayList<K>) nativeGetAllVendorKeys(mMetadataPtr, keyClass);
2168 }
2169
2170 /**
2171 * Convert a key string into the equivalent native tag.
2172 *
2173 * @throws IllegalArgumentException if the key was not recognized
2174 * @throws NullPointerException if the key was null
2175 *
2176 * @hide
2177 */
2178 public static int getTag(String key) {
2179 return nativeGetTagFromKey(key, Long.MAX_VALUE);
2180 }
2181
2182 /**
2183 * Convert a key string into the equivalent native tag.
2184 *
2185 * @throws IllegalArgumentException if the key was not recognized
2186 * @throws NullPointerException if the key was null
2187 *
2188 * @hide
2189 */
2190 public static int getTag(String key, long vendorId) {
2191 return nativeGetTagFromKey(key, vendorId);
2192 }
2193
2194 /**
2195 * Get the underlying native type for a tag.
2196 *
2197 * @param tag An integer tag, see e.g. {@link #getTag}
2198 * @param vendorId A vendor tag provider id
2199 * @return An int enum for the metadata type, see e.g. {@link #TYPE_BYTE}
2200 *
2201 * @hide
2202 */
2203 public static int getNativeType(int tag, long vendorId) {
2204 return nativeGetTypeFromTag(tag, vendorId);
2205 }
2206
2207 /**
2208 * <p>Updates the existing entry for tag with the new bytes pointed by src, erasing
2209 * the entry if src was null.</p>
2210 *
2211 * <p>An empty array can be passed in to update the entry to 0 elements.</p>
2212 *
2213 * @param tag An integer tag, see e.g. {@link #getTag}
2214 * @param src An array of bytes, or null to erase the entry
2215 *
2216 * @hide
2217 */
2218 public void writeValues(int tag, byte[] src) {
2219 nativeWriteValues(tag, src, mMetadataPtr);
2220 }
2221
2222 /**
2223 * <p>Returns a byte[] of data corresponding to this tag. Use a wrapped bytebuffer to unserialize
2224 * the data properly.</p>
2225 *
2226 * <p>An empty array can be returned to denote an existing entry with 0 elements.</p>
2227 *
2228 * @param tag An integer tag, see e.g. {@link #getTag}
2229 *
2230 * @return {@code null} if there were 0 entries for this tag, a byte[] otherwise.
2231 * @hide
2232 */
2233 public byte[] readValues(int tag) {
2234 // TODO: Optimization. Native code returns a ByteBuffer instead.
2235 return nativeReadValues(tag, mMetadataPtr);
2236 }
2237
2238 /**
2239 * Dumps the native metadata contents to logcat.
2240 *
2241 * <p>Visibility for testing/debugging only. The results will not
2242 * include any synthesized keys, as they are invisible to the native layer.</p>
2243 *
2244 * @hide
2245 */
2246 public void dumpToLog() {
2247 try {
2248 nativeDump(mMetadataPtr);
2249 } catch (IOException e) {
2250 Log.wtf(TAG, "Dump logging failed", e);
2251 }
2252 }
2253
2254 @Override
2255 protected void finalize() throws Throwable {
2256 try {
2257 close();
2258 } finally {
2259 super.finalize();
2260 }
2261 }
2262
2263 /**
2264 * Get the marshaler compatible with the {@code key} and type {@code T}.
2265 *
2266 * @throws UnsupportedOperationException
2267 * if the native/managed type combination for {@code key} is not supported
2268 */
2269 private static <T> Marshaler<T> getMarshalerForKey(Key<T> key, int nativeType) {
2270 return MarshalRegistry.getMarshaler(key.getTypeReference(),
2271 nativeType);
2272 }
2273
2274 @SuppressWarnings({ "unchecked", "rawtypes" })
2275 private static void registerAllMarshalers() {
2276 if (DEBUG) {
2277 Log.v(TAG, "Shall register metadata marshalers");
2278 }
2279
2280 MarshalQueryable[] queryList = new MarshalQueryable[] {
2281 // marshalers for standard types
2282 new MarshalQueryablePrimitive(),
2283 new MarshalQueryableEnum(),
2284 new MarshalQueryableArray(),
2285
2286 // pseudo standard types, that expand/narrow the native type into a managed type
2287 new MarshalQueryableBoolean(),
2288 new MarshalQueryableNativeByteToInteger(),
2289
2290 // marshalers for custom types
2291 new MarshalQueryableRect(),
2292 new MarshalQueryableSize(),
2293 new MarshalQueryableSizeF(),
2294 new MarshalQueryableString(),
2295 new MarshalQueryableReprocessFormatsMap(),
2296 new MarshalQueryableRange(),
2297 new MarshalQueryablePair(),
2298 new MarshalQueryableMeteringRectangle(),
2299 new MarshalQueryableColorSpaceTransform(),
2300 new MarshalQueryableStreamConfiguration(),
2301 new MarshalQueryableStreamConfigurationDuration(),
2302 new MarshalQueryableRggbChannelVector(),
2303 new MarshalQueryableBlackLevelPattern(),
2304 new MarshalQueryableHighSpeedVideoConfiguration(),
2305 new MarshalQueryableRecommendedStreamConfiguration(),
2306
2307 // generic parcelable marshaler (MUST BE LAST since it has lowest priority)
2308 new MarshalQueryableParcelable(),
2309 };
2310
2311 for (MarshalQueryable query : queryList) {
2312 MarshalRegistry.registerMarshalQueryable(query);
2313 }
2314 if (DEBUG) {
2315 Log.v(TAG, "Registered metadata marshalers");
2316 }
2317 }
2318
2319 /** Check if input arguments are all {@code null}.
2320 *
2321 * @param objs Input arguments for null check
2322 * @return {@code true} if input arguments are all {@code null}, otherwise {@code false}
2323 */
2324 private static boolean areValuesAllNull(Object... objs) {
2325 for (Object o : objs) {
2326 if (o != null) return false;
2327 }
2328 return true;
2329 }
2330
2331 /**
2332 * Return the set of physical camera ids that this logical {@link CameraDevice} is made
2333 * up of.
2334 *
2335 * If the camera device isn't a logical camera, return an empty set.
2336 *
2337 * @hide
2338 */
2339 public Set<String> getPhysicalCameraIds() {
2340 int[] availableCapabilities = get(CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES);
2341 if (availableCapabilities == null) {
2342 throw new AssertionError("android.request.availableCapabilities must be non-null "
2343 + "in the characteristics");
2344 }
2345
2346 if (!ArrayUtils.contains(availableCapabilities,
2347 CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_LOGICAL_MULTI_CAMERA)) {
2348 return Collections.emptySet();
2349 }
2350 byte[] physicalCamIds = get(CameraCharacteristics.LOGICAL_MULTI_CAMERA_PHYSICAL_IDS);
2351
2352 String physicalCamIdString = null;
2353 try {
2354 physicalCamIdString = new String(physicalCamIds, "UTF-8");
2355 } catch (java.io.UnsupportedEncodingException e) {
2356 throw new AssertionError("android.logicalCam.physicalIds must be UTF-8 string");
2357 }
2358 String[] physicalCameraIdArray = physicalCamIdString.split("\0");
2359
2360 return Collections.unmodifiableSet(
2361 new HashSet<String>(Arrays.asList(physicalCameraIdArray)));
2362 }
2363
2364 static {
2365 registerAllMarshalers();
2366 }
2367 }