blob: 4633b2fe218fa6322d663a8f2214bf5e714b4dd9 [file] [log] [blame]
Eino-Ville Talvalab2675542012-12-12 13:29:45 -08001/*
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
17package android.hardware.photography;
18
19import android.os.Parcelable;
20import android.os.Parcel;
Igor Murashkin70725502013-06-25 20:27:06 +000021import android.util.Log;
22
Igor Murashkinb519cc52013-07-02 11:23:44 -070023import java.lang.reflect.Array;
24import java.lang.reflect.Constructor;
25import java.lang.reflect.Field;
26import java.lang.reflect.InvocationTargetException;
27import java.lang.reflect.Method;
28import java.lang.reflect.Modifier;
29import java.nio.ByteBuffer;
30import java.nio.ByteOrder;
31import java.util.ArrayList;
Eino-Ville Talvalab2675542012-12-12 13:29:45 -080032import java.util.HashMap;
Igor Murashkinb519cc52013-07-02 11:23:44 -070033import java.util.HashSet;
34import java.util.List;
Eino-Ville Talvalab2675542012-12-12 13:29:45 -080035import java.util.Map;
36
37/**
38 * The base class for camera controls and information.
39 *
40 * This class defines the basic key/value map used for querying for camera
41 * characteristics or capture results, and for setting camera request
42 * parameters.
43 *
44 * @see CameraDevice
45 * @see CameraManager
46 * @see CameraProperties
47 **/
Igor Murashkin70725502013-06-25 20:27:06 +000048public class CameraMetadata implements Parcelable, AutoCloseable {
Eino-Ville Talvalab2675542012-12-12 13:29:45 -080049
50 public CameraMetadata() {
51 mMetadataMap = new HashMap<Key<?>, Object>();
Eino-Ville Talvalab2675542012-12-12 13:29:45 -080052
Igor Murashkin70725502013-06-25 20:27:06 +000053 mMetadataPtr = nativeAllocate();
54 if (mMetadataPtr == 0) {
55 throw new OutOfMemoryError("Failed to allocate native CameraMetadata");
56 }
Eino-Ville Talvalab2675542012-12-12 13:29:45 -080057 }
58
59 public static final Parcelable.Creator<CameraMetadata> CREATOR =
60 new Parcelable.Creator<CameraMetadata>() {
Igor Murashkin70725502013-06-25 20:27:06 +000061 @Override
Eino-Ville Talvalab2675542012-12-12 13:29:45 -080062 public CameraMetadata createFromParcel(Parcel in) {
Igor Murashkin70725502013-06-25 20:27:06 +000063 CameraMetadata metadata = new CameraMetadata();
64 metadata.readFromParcel(in);
65 return metadata;
Eino-Ville Talvalab2675542012-12-12 13:29:45 -080066 }
67
Igor Murashkin70725502013-06-25 20:27:06 +000068 @Override
Eino-Ville Talvalab2675542012-12-12 13:29:45 -080069 public CameraMetadata[] newArray(int size) {
70 return new CameraMetadata[size];
71 }
72 };
73
Igor Murashkin70725502013-06-25 20:27:06 +000074 private static final String TAG = "CameraMetadataJV";
75
Eino-Ville Talvalab2675542012-12-12 13:29:45 -080076 /**
77 * Set a camera metadata field to a value. The field definitions can be
78 * found in {@link CameraProperties}, {@link CaptureResult}, and
79 * {@link CaptureRequest}.
80 *
81 * @param key the metadata field to write.
82 * @param value the value to set the field to, which must be of a matching
83 * type to the key.
84 */
85 public <T> void set(Key<T> key, T value) {
Igor Murashkinb519cc52013-07-02 11:23:44 -070086 int tag = key.getTag();
Igor Murashkin70725502013-06-25 20:27:06 +000087
Igor Murashkinb519cc52013-07-02 11:23:44 -070088 int nativeType = getNativeType(tag);
89
90 int size = packSingle(value, null, key.mType, nativeType, /* sizeOnly */true);
91
92 // TODO: Optimization. Cache the byte[] and reuse if the size is big enough.
93 byte[] values = new byte[size];
94
95 ByteBuffer buffer = ByteBuffer.wrap(values).order(ByteOrder.nativeOrder());
96 packSingle(value, buffer, key.mType, nativeType, /*sizeOnly*/false);
97
98 writeValues(tag, values);
Eino-Ville Talvalab2675542012-12-12 13:29:45 -080099 }
100
101 /**
102 * Get a camera metadata field value. The field definitions can be
103 * found in {@link CameraProperties}, {@link CaptureResult}, and
104 * {@link CaptureRequest}.
105 *
Igor Murashkinb519cc52013-07-02 11:23:44 -0700106 * @throws IllegalArgumentException if the key was not valid
107 *
Eino-Ville Talvalab2675542012-12-12 13:29:45 -0800108 * @param key the metadata field to read.
109 * @return the value of that key, or {@code null} if the field is not set.
110 */
111 @SuppressWarnings("unchecked")
112 public <T> T get(Key<T> key) {
Igor Murashkinb519cc52013-07-02 11:23:44 -0700113 int tag = key.getTag();
114 byte[] values = readValues(tag);
115 if (values == null) {
116 return null;
117 }
Igor Murashkin70725502013-06-25 20:27:06 +0000118
Igor Murashkinb519cc52013-07-02 11:23:44 -0700119 int nativeType = getNativeType(tag);
120
121 ByteBuffer buffer = ByteBuffer.wrap(values).order(ByteOrder.nativeOrder());
122 return unpackSingle(buffer, key.mType, nativeType);
123 }
124
125 // Keep up-to-date with camera_metadata.h
126 /**
127 * @hide
128 */
129 public static final int TYPE_BYTE = 0;
130 /**
131 * @hide
132 */
133 public static final int TYPE_INT32 = 1;
134 /**
135 * @hide
136 */
137 public static final int TYPE_FLOAT = 2;
138 /**
139 * @hide
140 */
141 public static final int TYPE_INT64 = 3;
142 /**
143 * @hide
144 */
145 public static final int TYPE_DOUBLE = 4;
146 /**
147 * @hide
148 */
149 public static final int TYPE_RATIONAL = 5;
150 /**
151 * @hide
152 */
153 public static final int NUM_TYPES = 6;
154
155 private static int getTypeSize(int nativeType) {
156 switch(nativeType) {
157 case TYPE_BYTE:
158 return 1;
159 case TYPE_INT32:
160 case TYPE_FLOAT:
161 return 4;
162 case TYPE_INT64:
163 case TYPE_DOUBLE:
164 case TYPE_RATIONAL:
165 return 8;
166 }
167
168 throw new UnsupportedOperationException("Unknown type, can't get size "
169 + nativeType);
170 }
171
172 private static Class<?> getExpectedType(int nativeType) {
173 switch(nativeType) {
174 case TYPE_BYTE:
175 return Byte.TYPE;
176 case TYPE_INT32:
177 return Integer.TYPE;
178 case TYPE_FLOAT:
179 return Float.TYPE;
180 case TYPE_INT64:
181 return Long.TYPE;
182 case TYPE_DOUBLE:
183 return Double.TYPE;
184 case TYPE_RATIONAL:
185 return Rational.class;
186 }
187
188 throw new UnsupportedOperationException("Unknown type, can't map to Java type "
189 + nativeType);
190 }
191
192 @SuppressWarnings("unchecked")
193 private static <T> int packSingleNative(T value, ByteBuffer buffer, Class<T> type,
194 int nativeType, boolean sizeOnly) {
195
196 if (!sizeOnly) {
197 /**
198 * Rewrite types when the native type doesn't match the managed type
199 * - Boolean -> Byte
200 * - Integer -> Byte
201 */
202
203 if (nativeType == TYPE_BYTE && type == Boolean.TYPE) {
204 // Since a boolean can't be cast to byte, and we don't want to use putBoolean
205 boolean asBool = (Boolean) value;
206 byte asByte = (byte) (asBool ? 1 : 0);
207 value = (T) (Byte) asByte;
208 } else if (nativeType == TYPE_BYTE && type == Integer.TYPE) {
209 int asInt = (Integer) value;
210 byte asByte = (byte) asInt;
211 value = (T) (Byte) asByte;
212 } else if (type != getExpectedType(nativeType)) {
213 throw new UnsupportedOperationException("Tried to pack a type of " + type +
214 " but we expected the type to be " + getExpectedType(nativeType));
215 }
216
217 if (nativeType == TYPE_BYTE) {
218 buffer.put((Byte) value);
219 } else if (nativeType == TYPE_INT32) {
220 buffer.putInt((Integer) value);
221 } else if (nativeType == TYPE_FLOAT) {
222 buffer.putFloat((Float) value);
223 } else if (nativeType == TYPE_INT64) {
224 buffer.putLong((Long) value);
225 } else if (nativeType == TYPE_DOUBLE) {
226 buffer.putDouble((Double) value);
227 } else if (nativeType == TYPE_RATIONAL) {
228 Rational r = (Rational) value;
229 buffer.putInt(r.getNumerator());
230 buffer.putInt(r.getDenominator());
231 }
232
233 }
234
235 return getTypeSize(nativeType);
236 }
237
238 @SuppressWarnings({"unchecked", "rawtypes"})
239 private static <T> int packSingle(T value, ByteBuffer buffer, Class<T> type, int nativeType,
240 boolean sizeOnly) {
241
242 int size = 0;
243
244 if (type.isPrimitive() || type == Rational.class) {
245 size = packSingleNative(value, buffer, type, nativeType, sizeOnly);
246 } else if (type.isEnum()) {
247 size = packEnum((Enum)value, buffer, (Class<Enum>)type, nativeType, sizeOnly);
248 } else if (type.isArray()) {
249 size = packArray(value, buffer, type, nativeType, sizeOnly);
250 } else {
251 size = packClass(value, buffer, type, nativeType, sizeOnly);
252 }
253
254 return size;
255 }
256
257 private static <T extends Enum<T>> int packEnum(T value, ByteBuffer buffer, Class<T> type,
258 int nativeType, boolean sizeOnly) {
259
260 // TODO: add support for enums with their own values.
Igor Murashkinb9dd6372013-07-11 19:37:04 -0700261 return packSingleNative(getEnumValue(value), buffer, Integer.TYPE, nativeType, sizeOnly);
Igor Murashkinb519cc52013-07-02 11:23:44 -0700262 }
263
264 @SuppressWarnings("unchecked")
265 private static <T> int packClass(T value, ByteBuffer buffer, Class<T> type, int nativeType,
266 boolean sizeOnly) {
267
268 /**
269 * FIXME: This doesn't actually work because getFields() returns fields in an unordered
270 * manner. Although we could sort and get the data to come out correctly on the *java* side,
271 * it would not be data-compatible with our strict XML definitions.
272 *
273 * Rewrite this code to use Parcelables instead, they are most likely compatible with
274 * what we are trying to do in general.
275 */
276 List<Field> instanceFields = findInstanceFields(type);
277 if (instanceFields.size() == 0) {
278 throw new UnsupportedOperationException("Class has no instance fields: " + type);
279 }
280
281 int fieldCount = instanceFields.size();
282 int bufferSize = 0;
283
284 HashSet<Class<?>> fieldTypes = new HashSet<Class<?>>();
285 for (Field f : instanceFields) {
286 fieldTypes.add(f.getType());
287 }
288
289 /**
290 * Pack arguments one field at a time. If we can't access field, look for its accessor
291 * method instead.
292 */
293 for (int i = 0; i < fieldCount; ++i) {
294 Object arg;
295
296 Field f = instanceFields.get(i);
297
298 if ((f.getModifiers() & Modifier.PUBLIC) != 0) {
299 try {
300 arg = f.get(value);
301 } catch (IllegalAccessException e) {
302 throw new UnsupportedOperationException(
303 "Failed to access field " + f + " of type " + type, e);
304 } catch (IllegalArgumentException e) {
305 throw new UnsupportedOperationException(
306 "Illegal arguments when accessing field " + f + " of type " + type, e);
307 }
308 } else {
309 Method accessor = null;
310 // try to find a public accessor method
311 for(Method m : type.getMethods()) {
312 Log.v(TAG, String.format("Looking for getter in method %s for field %s", m, f));
313
314 // Must have 0 arguments
315 if (m.getParameterTypes().length != 0) {
316 continue;
317 }
318
319 // Return type must be same as field type
320 if (m.getReturnType() != f.getType()) {
321 continue;
322 }
323
324 // Strip 'm' from variable prefix if the next letter is capitalized
325 String fieldName = f.getName();
326 char[] nameChars = f.getName().toCharArray();
327 if (nameChars.length >= 2 && nameChars[0] == 'm'
328 && Character.isUpperCase(nameChars[1])) {
329 fieldName = String.valueOf(nameChars, /*start*/1, nameChars.length - 1);
330 }
331
332 Log.v(TAG, String.format("Normalized field name: %s", fieldName));
333
334 // #getFoo() , getfoo(), foo(), all match.
335 if (m.getName().toLowerCase().equals(fieldName.toLowerCase()) ||
336 m.getName().toLowerCase().equals("get" + fieldName.toLowerCase())) {
337 accessor = m;
338 break;
339 }
340 }
341
342 if (accessor == null) {
343 throw new UnsupportedOperationException(
344 "Failed to find getter method for field " + f + " in type " + type);
345 }
346
347 try {
348 arg = accessor.invoke(value);
349 } catch (IllegalAccessException e) {
350 // Impossible
351 throw new UnsupportedOperationException("Failed to access method + " + accessor
352 + " in type " + type, e);
353 } catch (IllegalArgumentException e) {
354 // Impossible
355 throw new UnsupportedOperationException("Bad arguments for method + " + accessor
356 + " in type " + type, e);
357 } catch (InvocationTargetException e) {
358 // Possibly but extremely unlikely
359 throw new UnsupportedOperationException("Failed to invoke method + " + accessor
360 + " in type " + type, e);
361 }
362 }
363
364 bufferSize += packSingle(arg, buffer, (Class<Object>)f.getType(), nativeType, sizeOnly);
365 }
366
367 return bufferSize;
368 }
369
370 private static <T> int packArray(T value, ByteBuffer buffer, Class<T> type, int nativeType,
371 boolean sizeOnly) {
372
373 int size = 0;
374 int arrayLength = Array.getLength(value);
375
376 @SuppressWarnings("unchecked")
377 Class<Object> componentType = (Class<Object>)type.getComponentType();
378
379 for (int i = 0; i < arrayLength; ++i) {
380 size += packSingle(Array.get(value, i), buffer, componentType, nativeType, sizeOnly);
381 }
382
383 return size;
384 }
385
386 @SuppressWarnings("unchecked")
387 private static <T> T unpackSingleNative(ByteBuffer buffer, Class<T> type, int nativeType) {
388
389 T val;
390
391 if (nativeType == TYPE_BYTE) {
392 val = (T) (Byte) buffer.get();
393 } else if (nativeType == TYPE_INT32) {
394 val = (T) (Integer) buffer.getInt();
395 } else if (nativeType == TYPE_FLOAT) {
396 val = (T) (Float) buffer.getFloat();
397 } else if (nativeType == TYPE_INT64) {
398 val = (T) (Long) buffer.getLong();
399 } else if (nativeType == TYPE_DOUBLE) {
400 val = (T) (Double) buffer.getDouble();
401 } else if (nativeType == TYPE_RATIONAL) {
402 val = (T) new Rational(buffer.getInt(), buffer.getInt());
403 } else {
404 throw new UnsupportedOperationException("Unknown type, can't unpack a native type "
405 + nativeType);
406 }
407
408 /**
409 * Rewrite types when the native type doesn't match the managed type
410 * - Byte -> Boolean
411 * - Byte -> Integer
412 */
413
414 if (nativeType == TYPE_BYTE && type == Boolean.TYPE) {
415 // Since a boolean can't be cast to byte, and we don't want to use getBoolean
416 byte asByte = (Byte) val;
417 boolean asBool = asByte != 0;
418 val = (T) (Boolean) asBool;
419 } else if (nativeType == TYPE_BYTE && type == Integer.TYPE) {
420 byte asByte = (Byte) val;
421 int asInt = asByte;
422 val = (T) (Integer) asInt;
423 } else if (type != getExpectedType(nativeType)) {
424 throw new UnsupportedOperationException("Tried to unpack a type of " + type +
425 " but we expected the type to be " + getExpectedType(nativeType));
426 }
427
428 return val;
429 }
430
431 private static <T> List<Field> findInstanceFields(Class<T> type) {
432 List<Field> fields = new ArrayList<Field>();
433
434 for (Field f : type.getDeclaredFields()) {
435 if (f.isSynthetic()) {
436 throw new UnsupportedOperationException(
437 "Marshalling synthetic fields not supported in type " + type);
438 }
439
440 // Skip static fields
441 int modifiers = f.getModifiers();
442 if ((modifiers & Modifier.STATIC) == 0) {
443 fields.add(f);
444 }
445
446 Log.v(TAG, String.format("Field %s has modifiers %d", f, modifiers));
447 }
448
449 if (type.getDeclaredFields().length == 0) {
450 Log.w(TAG, String.format("Type %s had 0 fields of any kind", type));
451 }
452 return fields;
453 }
454
455 @SuppressWarnings({"unchecked", "rawtypes"})
456 private static <T> T unpackSingle(ByteBuffer buffer, Class<T> type, int nativeType) {
457
458 if (type.isPrimitive() || type == Rational.class) {
459 return unpackSingleNative(buffer, type, nativeType);
460 }
461
462 if (type.isEnum()) {
463 return (T) unpackEnum(buffer, (Class<Enum>)type, nativeType);
464 }
465
466 if (type.isArray()) {
467 return unpackArray(buffer, type, nativeType);
468 }
469
470 T instance = unpackClass(buffer, type, nativeType);
471
472 return instance;
473 }
474
475 private static <T> Constructor<T> findApplicableConstructor(Class<T> type) {
476
477 List<Field> instanceFields = findInstanceFields(type);
478 if (instanceFields.size() == 0) {
479 throw new UnsupportedOperationException("Class has no instance fields: " + type);
480 }
481
482 Constructor<T> constructor = null;
483 int fieldCount = instanceFields.size();
484
485 HashSet<Class<?>> fieldTypes = new HashSet<Class<?>>();
486 for (Field f : instanceFields) {
487 fieldTypes.add(f.getType());
488 }
489
490 /**
491 * Find which constructor to use:
492 * - must be public
493 * - same amount of arguments as there are instance fields
494 * - each argument is same type as each field (in any order)
495 */
496 @SuppressWarnings("unchecked")
497 Constructor<T>[] constructors = (Constructor<T>[]) type.getConstructors();
498 for (Constructor<T> ctor : constructors) {
499 Log.v(TAG, String.format("Inspecting constructor '%s'", ctor));
500
501 Class<?>[] parameterTypes = ctor.getParameterTypes();
502 if (parameterTypes.length == fieldCount) {
503 boolean match = true;
504
505 HashSet<Class<?>> argTypes = new HashSet<Class<?>>();
506 for (Class<?> t : parameterTypes) {
507 argTypes.add(t);
508 }
509
510 // Order does not matter
511 match = argTypes.equals(fieldTypes);
512
513 /*
514 // check if the types are the same
515 for (int i = 0; i < fieldCount; ++i) {
516 if (parameterTypes[i] != instanceFields.get(i).getType()) {
517
518 Log.v(TAG, String.format(
519 "Constructor arg (%d) type %s did not match field type %s", i,
520 parameterTypes[i], instanceFields.get(i).getType()));
521
522 match = false;
523 break;
524 }
525 }
526 */
527
528 if (match) {
529 constructor = ctor;
530 break;
531 } else {
532 Log.w(TAG, String.format("Constructor args did not have matching types"));
533 }
534 } else {
535 Log.v(TAG, String.format(
536 "Constructor did not have expected amount of fields (had %d, expected %d)",
537 parameterTypes.length, fieldCount));
538 }
539 }
540
541 if (constructors.length == 0) {
542 Log.w(TAG, String.format("Type %s had no public constructors", type));
543 }
544
545 if (constructor == null) {
546 throw new UnsupportedOperationException(
547 "Failed to find any applicable constructors for type " + type);
548 }
549
550 return constructor;
551 }
552
553 private static <T extends Enum<T>> T unpackEnum(ByteBuffer buffer, Class<T> type,
554 int nativeType) {
Igor Murashkinb519cc52013-07-02 11:23:44 -0700555 int ordinal = unpackSingleNative(buffer, Integer.TYPE, nativeType);
Igor Murashkinb9dd6372013-07-11 19:37:04 -0700556 return getEnumFromValue(type, ordinal);
Igor Murashkinb519cc52013-07-02 11:23:44 -0700557 }
558
559 private static <T> T unpackClass(ByteBuffer buffer, Class<T> type, int nativeType) {
560
561 /**
562 * FIXME: This doesn't actually work because getFields() returns fields in an unordered
563 * manner. Although we could sort and get the data to come out correctly on the *java* side,
564 * it would not be data-compatible with our strict XML definitions.
565 *
566 * Rewrite this code to use Parcelables instead, they are most likely compatible with
567 * what we are trying to do in general.
568 */
569
570 List<Field> instanceFields = findInstanceFields(type);
571 if (instanceFields.size() == 0) {
572 throw new UnsupportedOperationException("Class has no instance fields: " + type);
573 }
574 int fieldCount = instanceFields.size();
575
576 Constructor<T> constructor = findApplicableConstructor(type);
577
578 /**
579 * Build the arguments by unpacking one field at a time
580 * (note that while the field type might be different, the native type is the same)
581 */
582 Object[] arguments = new Object[fieldCount];
583 for (int i = 0; i < fieldCount; ++i) {
584 Object o = unpackSingle(buffer, instanceFields.get(i).getType(), nativeType);
585 arguments[i] = o;
586 }
587
588 T instance;
589 try {
590 instance = constructor.newInstance(arguments);
591 } catch (InstantiationException e) {
592 // type is abstract class, interface, etc...
593 throw new UnsupportedOperationException("Failed to instantiate type " + type, e);
594 } catch (IllegalAccessException e) {
595 // This could happen if we have to access a private.
596 throw new UnsupportedOperationException("Failed to access type " + type, e);
597 } catch (IllegalArgumentException e) {
598 throw new UnsupportedOperationException("Illegal arguments for constructor of type "
599 + type, e);
600 } catch (InvocationTargetException e) {
601 throw new UnsupportedOperationException(
602 "Underlying constructor threw exception for type " + type, e);
603 }
604
605 return instance;
606 }
607
608 @SuppressWarnings("unchecked")
609 private static <T> T unpackArray(ByteBuffer buffer, Class<T> type, int nativeType) {
610
611 Class<?> componentType = type.getComponentType();
612 Object array;
613
614 int remaining = buffer.remaining();
615 // FIXME: Assumes that the rest of the ByteBuffer is part of the array.
616 int arraySize = remaining / getTypeSize(nativeType);
617
618 array = Array.newInstance(componentType, arraySize);
619 for (int i = 0; i < arraySize; ++i) {
620 Object elem = unpackSingle(buffer, componentType, nativeType);
621 Array.set(array, i, elem);
622 }
623
624 return (T) array;
Eino-Ville Talvalab2675542012-12-12 13:29:45 -0800625 }
626
627 @Override
628 public int describeContents() {
629 return 0;
630 }
631
632 @Override
633 public void writeToParcel(Parcel dest, int flags) {
Igor Murashkin70725502013-06-25 20:27:06 +0000634 nativeWriteToParcel(dest);
635 }
Eino-Ville Talvalab2675542012-12-12 13:29:45 -0800636
Igor Murashkin70725502013-06-25 20:27:06 +0000637 /**
638 * Expand this object from a Parcel.
639 * @param in The Parcel from which the object should be read
640 */
641 public void readFromParcel(Parcel in) {
642 nativeReadFromParcel(in);
Eino-Ville Talvalab2675542012-12-12 13:29:45 -0800643 }
644
645 public static class Key<T> {
Igor Murashkinb519cc52013-07-02 11:23:44 -0700646
647 private boolean mHasTag;
648 private int mTag;
649 private final Class<T> mType;
650
651 /*
652 * @hide
653 */
654 public Key(String name, Class<T> type) {
Eino-Ville Talvalab2675542012-12-12 13:29:45 -0800655 if (name == null) {
656 throw new NullPointerException("Key needs a valid name");
Igor Murashkinb519cc52013-07-02 11:23:44 -0700657 } else if (type == null) {
658 throw new NullPointerException("Type needs to be non-null");
Eino-Ville Talvalab2675542012-12-12 13:29:45 -0800659 }
660 mName = name;
Igor Murashkinb519cc52013-07-02 11:23:44 -0700661 mType = type;
Eino-Ville Talvalab2675542012-12-12 13:29:45 -0800662 }
663
664 public final String getName() {
665 return mName;
666 }
667
668 @Override
669 public final int hashCode() {
670 return mName.hashCode();
671 }
672
673 @Override
674 @SuppressWarnings("unchecked")
675 public final boolean equals(Object o) {
676 if (this == o) {
677 return true;
678 }
679
680 if (!(o instanceof Key)) {
681 return false;
682 }
683
684 Key lhs = (Key) o;
685
686 return mName.equals(lhs.mName);
687 }
688
689 private final String mName;
Igor Murashkinb519cc52013-07-02 11:23:44 -0700690
691 /**
692 * <p>
693 * Get the tag corresponding to this key. This enables insertion into the
694 * native metadata.
695 * </p>
696 *
697 * <p>This value is looked up the first time, and cached subsequently.</p>
698 *
699 * @return the tag numeric value corresponding to the string
700 *
701 * @hide
702 */
703 public final int getTag() {
704 if (!mHasTag) {
705 mTag = CameraMetadata.getTag(mName);
706 mHasTag = true;
707 }
708 return mTag;
709 }
Eino-Ville Talvalab2675542012-12-12 13:29:45 -0800710 }
711
Igor Murashkin70725502013-06-25 20:27:06 +0000712 private final Map<Key<?>, Object> mMetadataMap;
713
Igor Murashkin70725502013-06-25 20:27:06 +0000714 private long mMetadataPtr; // native CameraMetadata*
715
716 private native long nativeAllocate();
717 private native synchronized void nativeWriteToParcel(Parcel dest);
718 private native synchronized void nativeReadFromParcel(Parcel source);
719 private native synchronized void nativeSwap(CameraMetadata other) throws NullPointerException;
720 private native synchronized void nativeClose();
721 private native synchronized boolean nativeIsEmpty();
722 private native synchronized int nativeGetEntryCount();
Igor Murashkinb519cc52013-07-02 11:23:44 -0700723
724 private native synchronized byte[] nativeReadValues(int tag);
725 private native synchronized void nativeWriteValues(int tag, byte[] src);
726
727 private static native int nativeGetTagFromKey(String keyName)
728 throws IllegalArgumentException;
729 private static native int nativeGetTypeFromTag(int tag)
730 throws IllegalArgumentException;
Igor Murashkin70725502013-06-25 20:27:06 +0000731 private static native void nativeClassInit();
732
733 /**
734 * <p>Perform a 0-copy swap of the internal metadata with another object.</p>
735 *
736 * <p>Useful to convert a CameraMetadata into e.g. a CaptureRequest.</p>
737 *
738 * @param other metadata to swap with
739 * @throws NullPointerException if other was null
740 * @hide
741 */
742 public void swap(CameraMetadata other) {
743 nativeSwap(other);
744 }
745
746 /**
747 * @hide
748 */
749 public int getEntryCount() {
750 return nativeGetEntryCount();
751 }
752
753 /**
754 * Does this metadata contain at least 1 entry?
755 *
756 * @hide
757 */
758 public boolean isEmpty() {
759 return nativeIsEmpty();
760 }
761
762 /**
763 * <p>Closes this object, and releases all native resources associated with it.</p>
764 *
765 * <p>Calling any other public method after this will result in an IllegalStateException
766 * being thrown.</p>
767 */
768 @Override
769 public void close() throws Exception {
770 // this sets mMetadataPtr to 0
771 nativeClose();
772 mMetadataPtr = 0; // set it to 0 again to prevent eclipse from making this field final
773 }
774
775 /**
776 * Whether or not {@link #close} has already been called (at least once) on this object.
777 * @hide
778 */
779 public boolean isClosed() {
780 synchronized (this) {
781 return mMetadataPtr == 0;
782 }
783 }
784
Igor Murashkinb519cc52013-07-02 11:23:44 -0700785 /**
786 * Convert a key string into the equivalent native tag.
787 *
788 * @throws IllegalArgumentException if the key was not recognized
789 * @throws NullPointerException if the key was null
790 *
791 * @hide
792 */
793 public static int getTag(String key) {
794 return nativeGetTagFromKey(key);
795 }
796
797 /**
798 * Get the underlying native type for a tag.
799 *
800 * @param tag an integer tag, see e.g. {@link #getTag}
801 * @return an int enum for the metadata type, see e.g. {@link #TYPE_BYTE}
802 *
803 * @hide
804 */
805 public static int getNativeType(int tag) {
806 return nativeGetTypeFromTag(tag);
807 }
808
809 /**
810 * <p>Updates the existing entry for tag with the new bytes pointed by src, erasing
811 * the entry if src was null.</p>
812 *
813 * <p>An empty array can be passed in to update the entry to 0 elements.</p>
814 *
815 * @param tag an integer tag, see e.g. {@link #getTag}
816 * @param src an array of bytes, or null to erase the entry
817 *
818 * @hide
819 */
820 public void writeValues(int tag, byte[] src) {
821 nativeWriteValues(tag, src);
822 }
823
824 /**
825 * <p>Returns a byte[] of data corresponding to this tag. Use a wrapped bytebuffer to unserialize
826 * the data properly.</p>
827 *
828 * <p>An empty array can be returned to denote an existing entry with 0 elements.</p>
829 *
830 * @param tag an integer tag, see e.g. {@link #getTag}
831 *
832 * @return null if there were 0 entries for this tag, a byte[] otherwise.
833 * @hide
834 */
835 public byte[] readValues(int tag) {
836 // TODO: Optimization. Native code returns a ByteBuffer instead.
837 return nativeReadValues(tag);
838 }
839
Igor Murashkin70725502013-06-25 20:27:06 +0000840 @Override
841 protected void finalize() throws Throwable {
842 try {
843 close();
844 } finally {
845 super.finalize();
846 }
847 }
848
Igor Murashkinb9dd6372013-07-11 19:37:04 -0700849 private static final HashMap<Class<? extends Enum>, int[]> sEnumValues =
850 new HashMap<Class<? extends Enum>, int[]>();
851 /**
852 * Register a non-sequential set of values to be used with the pack/unpack functions.
853 * This enables get/set to correctly marshal the enum into a value that is C-compatible.
854 *
855 * @param enumType the class for an enum
856 * @param values a list of values mapping to the ordinals of the enum
857 *
858 * @hide
859 */
860 public static <T extends Enum<T>> void registerEnumValues(Class<T> enumType, int[] values) {
861 if (enumType.getEnumConstants().length != values.length) {
862 throw new IllegalArgumentException(
863 "Expected values array to be the same size as the enumTypes values "
864 + values.length + " for type " + enumType);
865 }
866
Igor Murashkind7bf1772013-07-12 18:01:31 -0700867 Log.v(TAG, "Registered enum values for type " + enumType + " values");
868
Igor Murashkinb9dd6372013-07-11 19:37:04 -0700869 sEnumValues.put(enumType, values);
870 }
871
872 /**
873 * Get the numeric value from an enum. This is usually the same as the ordinal value for
874 * enums that have fully sequential values, although for C-style enums the range of values
875 * may not map 1:1.
876 *
877 * @param enumValue enum instance
878 * @return int guaranteed to be ABI-compatible with the C enum equivalent
879 */
880 private static <T extends Enum<T>> int getEnumValue(T enumValue) {
881 int[] values;
882 values = sEnumValues.get(enumValue.getClass());
883
884 int ordinal = enumValue.ordinal();
885 if (values != null) {
886 return values[ordinal];
887 }
888
889 return ordinal;
890 }
891
892 /**
893 * Finds the enum corresponding to it's numeric value. Opposite of {@link #getEnumValue} method.
894 *
895 * @param enumType class of the enum we want to find
896 * @param value the numeric value of the enum
897 * @return an instance of the enum
898 */
899 private static <T extends Enum<T>> T getEnumFromValue(Class<T> enumType, int value) {
900 int ordinal;
901
902 int[] registeredValues = sEnumValues.get(enumType);
903 if (registeredValues != null) {
904 ordinal = -1;
905
906 for (int i = 0; i < registeredValues.length; ++i) {
907 if (registeredValues[i] == value) {
908 ordinal = i;
909 break;
910 }
911 }
912 } else {
913 ordinal = value;
914 }
915
916 T[] values = enumType.getEnumConstants();
917
918 if (ordinal < 0 || ordinal >= values.length) {
919 throw new IllegalArgumentException(
920 String.format(
Igor Murashkind7bf1772013-07-12 18:01:31 -0700921 "Argument 'value' (%d) was not a valid enum value for type %s "
922 + "(registered? %b)",
923 value,
924 enumType, (registeredValues != null)));
Igor Murashkinb9dd6372013-07-11 19:37:04 -0700925 }
926
927 return values[ordinal];
928 }
929
Igor Murashkin70725502013-06-25 20:27:06 +0000930 /**
931 * We use a class initializer to allow the native code to cache some field offsets
932 */
933 static {
934 System.loadLibrary("media_jni");
935 nativeClassInit();
936 }
Igor Murashkinb519cc52013-07-02 11:23:44 -0700937}