camera2 api: Add CameraMetadata get/set support

* Add a Rational class
* Can get/set Key<T> where T is a primitive (or Rational)
* Can get/set Key<T> where T is a primitive array
* Can get/set Key<T> where T is an enum (synthetic constructor only)

Not implemented yet:
* When T is anything else, i.e. Rect, Size, etc

Bug: 9529161
Change-Id: I64438024a1e8327a38dd2672652626f0ffbb70e3
diff --git a/core/java/android/hardware/photography/CameraMetadata.java b/core/java/android/hardware/photography/CameraMetadata.java
index 5488952..1988967 100644
--- a/core/java/android/hardware/photography/CameraMetadata.java
+++ b/core/java/android/hardware/photography/CameraMetadata.java
@@ -20,7 +20,18 @@
 import android.os.Parcel;
 import android.util.Log;
 
+import java.lang.reflect.Array;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Field;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.util.ArrayList;
 import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
 import java.util.Map;
 
 /**
@@ -72,9 +83,19 @@
      * type to the key.
      */
     public <T> void set(Key<T> key, T value) {
-        Log.e(TAG, "Not fully implemented yet");
+        int tag = key.getTag();
 
-        mMetadataMap.put(key, value);
+        int nativeType = getNativeType(tag);
+
+        int size = packSingle(value, null, key.mType, nativeType, /* sizeOnly */true);
+
+        // TODO: Optimization. Cache the byte[] and reuse if the size is big enough.
+        byte[] values = new byte[size];
+
+        ByteBuffer buffer = ByteBuffer.wrap(values).order(ByteOrder.nativeOrder());
+        packSingle(value, buffer, key.mType, nativeType, /*sizeOnly*/false);
+
+        writeValues(tag, values);
     }
 
     /**
@@ -82,14 +103,536 @@
      * found in {@link CameraProperties}, {@link CaptureResult}, and
      * {@link CaptureRequest}.
      *
+     * @throws IllegalArgumentException if the key was not valid
+     *
      * @param key the metadata field to read.
      * @return the value of that key, or {@code null} if the field is not set.
      */
     @SuppressWarnings("unchecked")
     public <T> T get(Key<T> key) {
-        Log.e(TAG, "Not fully implemented yet");
+        int tag = key.getTag();
+        byte[] values = readValues(tag);
+        if (values == null) {
+            return null;
+        }
 
-        return (T) mMetadataMap.get(key);
+        int nativeType = getNativeType(tag);
+
+        ByteBuffer buffer = ByteBuffer.wrap(values).order(ByteOrder.nativeOrder());
+        return unpackSingle(buffer, key.mType, nativeType);
+    }
+
+    // Keep up-to-date with camera_metadata.h
+    /**
+     * @hide
+     */
+    public static final int TYPE_BYTE = 0;
+    /**
+     * @hide
+     */
+    public static final int TYPE_INT32 = 1;
+    /**
+     * @hide
+     */
+    public static final int TYPE_FLOAT = 2;
+    /**
+     * @hide
+     */
+    public static final int TYPE_INT64 = 3;
+    /**
+     * @hide
+     */
+    public static final int TYPE_DOUBLE = 4;
+    /**
+     * @hide
+     */
+    public static final int TYPE_RATIONAL = 5;
+    /**
+     * @hide
+     */
+    public static final int NUM_TYPES = 6;
+
+    private static int getTypeSize(int nativeType) {
+        switch(nativeType) {
+            case TYPE_BYTE:
+                return 1;
+            case TYPE_INT32:
+            case TYPE_FLOAT:
+                return 4;
+            case TYPE_INT64:
+            case TYPE_DOUBLE:
+            case TYPE_RATIONAL:
+                return 8;
+        }
+
+        throw new UnsupportedOperationException("Unknown type, can't get size "
+                + nativeType);
+    }
+
+    private static Class<?> getExpectedType(int nativeType) {
+        switch(nativeType) {
+            case TYPE_BYTE:
+                return Byte.TYPE;
+            case TYPE_INT32:
+                return Integer.TYPE;
+            case TYPE_FLOAT:
+                return Float.TYPE;
+            case TYPE_INT64:
+                return Long.TYPE;
+            case TYPE_DOUBLE:
+                return Double.TYPE;
+            case TYPE_RATIONAL:
+                return Rational.class;
+        }
+
+        throw new UnsupportedOperationException("Unknown type, can't map to Java type "
+                + nativeType);
+    }
+
+    @SuppressWarnings("unchecked")
+    private static <T> int packSingleNative(T value, ByteBuffer buffer, Class<T> type,
+            int nativeType, boolean sizeOnly) {
+
+        if (!sizeOnly) {
+            /**
+             * Rewrite types when the native type doesn't match the managed type
+             *  - Boolean -> Byte
+             *  - Integer -> Byte
+             */
+
+            if (nativeType == TYPE_BYTE && type == Boolean.TYPE) {
+                // Since a boolean can't be cast to byte, and we don't want to use putBoolean
+                boolean asBool = (Boolean) value;
+                byte asByte = (byte) (asBool ? 1 : 0);
+                value = (T) (Byte) asByte;
+            } else if (nativeType == TYPE_BYTE && type == Integer.TYPE) {
+                int asInt = (Integer) value;
+                byte asByte = (byte) asInt;
+                value = (T) (Byte) asByte;
+            } else if (type != getExpectedType(nativeType)) {
+                throw new UnsupportedOperationException("Tried to pack a type of " + type +
+                        " but we expected the type to be " + getExpectedType(nativeType));
+            }
+
+            if (nativeType == TYPE_BYTE) {
+                buffer.put((Byte) value);
+            } else if (nativeType == TYPE_INT32) {
+                buffer.putInt((Integer) value);
+            } else if (nativeType == TYPE_FLOAT) {
+                buffer.putFloat((Float) value);
+            } else if (nativeType == TYPE_INT64) {
+                buffer.putLong((Long) value);
+            } else if (nativeType == TYPE_DOUBLE) {
+                buffer.putDouble((Double) value);
+            } else if (nativeType == TYPE_RATIONAL) {
+                Rational r = (Rational) value;
+                buffer.putInt(r.getNumerator());
+                buffer.putInt(r.getDenominator());
+            }
+
+        }
+
+        return getTypeSize(nativeType);
+    }
+
+    @SuppressWarnings({"unchecked", "rawtypes"})
+    private static <T> int packSingle(T value, ByteBuffer buffer, Class<T> type, int nativeType,
+            boolean sizeOnly) {
+
+        int size = 0;
+
+        if (type.isPrimitive() || type == Rational.class) {
+            size = packSingleNative(value, buffer, type, nativeType, sizeOnly);
+        } else if (type.isEnum()) {
+            size = packEnum((Enum)value, buffer, (Class<Enum>)type, nativeType, sizeOnly);
+        } else if (type.isArray()) {
+            size = packArray(value, buffer, type, nativeType, sizeOnly);
+        } else {
+            size = packClass(value, buffer, type, nativeType, sizeOnly);
+        }
+
+        return size;
+    }
+
+    private static <T extends Enum<T>> int packEnum(T value, ByteBuffer buffer, Class<T> type,
+            int nativeType, boolean sizeOnly) {
+
+        // TODO: add support for enums with their own values.
+        return packSingleNative(value.ordinal(), buffer, Integer.TYPE, nativeType, sizeOnly);
+    }
+
+    @SuppressWarnings("unchecked")
+    private static <T> int packClass(T value, ByteBuffer buffer, Class<T> type, int nativeType,
+            boolean sizeOnly) {
+
+        /**
+         * FIXME: This doesn't actually work because getFields() returns fields in an unordered
+         * manner. Although we could sort and get the data to come out correctly on the *java* side,
+         * it would not be data-compatible with our strict XML definitions.
+         *
+         * Rewrite this code to use Parcelables instead, they are most likely compatible with
+         * what we are trying to do in general.
+         */
+        List<Field> instanceFields = findInstanceFields(type);
+        if (instanceFields.size() == 0) {
+            throw new UnsupportedOperationException("Class has no instance fields: " + type);
+        }
+
+        int fieldCount = instanceFields.size();
+        int bufferSize = 0;
+
+        HashSet<Class<?>> fieldTypes = new HashSet<Class<?>>();
+        for (Field f : instanceFields) {
+            fieldTypes.add(f.getType());
+        }
+
+        /**
+         * Pack arguments one field at a time. If we can't access field, look for its accessor
+         * method instead.
+         */
+        for (int i = 0; i < fieldCount; ++i) {
+            Object arg;
+
+            Field f = instanceFields.get(i);
+
+            if ((f.getModifiers() & Modifier.PUBLIC) != 0) {
+                try {
+                    arg = f.get(value);
+                } catch (IllegalAccessException e) {
+                    throw new UnsupportedOperationException(
+                            "Failed to access field " + f + " of type " + type, e);
+                } catch (IllegalArgumentException e) {
+                    throw new UnsupportedOperationException(
+                            "Illegal arguments when accessing field " + f + " of type " + type, e);
+                }
+            } else {
+                Method accessor = null;
+                // try to find a public accessor method
+                for(Method m : type.getMethods()) {
+                    Log.v(TAG, String.format("Looking for getter in method %s for field %s", m, f));
+
+                    // Must have 0 arguments
+                    if (m.getParameterTypes().length != 0) {
+                        continue;
+                    }
+
+                    // Return type must be same as field type
+                    if (m.getReturnType() != f.getType()) {
+                        continue;
+                    }
+
+                    // Strip 'm' from variable prefix if the next letter is capitalized
+                    String fieldName = f.getName();
+                    char[] nameChars = f.getName().toCharArray();
+                    if (nameChars.length >= 2 && nameChars[0] == 'm'
+                            && Character.isUpperCase(nameChars[1])) {
+                        fieldName = String.valueOf(nameChars, /*start*/1, nameChars.length - 1);
+                    }
+
+                    Log.v(TAG, String.format("Normalized field name: %s", fieldName));
+
+                    // #getFoo() , getfoo(), foo(), all match.
+                    if (m.getName().toLowerCase().equals(fieldName.toLowerCase()) ||
+                            m.getName().toLowerCase().equals("get" + fieldName.toLowerCase())) {
+                        accessor = m;
+                        break;
+                    }
+                }
+
+                if (accessor == null) {
+                    throw new UnsupportedOperationException(
+                            "Failed to find getter method for field " + f + " in type " + type);
+                }
+
+                try {
+                    arg = accessor.invoke(value);
+                } catch (IllegalAccessException e) {
+                    // Impossible
+                    throw new UnsupportedOperationException("Failed to access method + " + accessor
+                            + " in type " + type, e);
+                } catch (IllegalArgumentException e) {
+                    // Impossible
+                    throw new UnsupportedOperationException("Bad arguments for method + " + accessor
+                            + " in type " + type, e);
+                } catch (InvocationTargetException e) {
+                    // Possibly but extremely unlikely
+                    throw new UnsupportedOperationException("Failed to invoke method + " + accessor
+                            + " in type " + type, e);
+                }
+            }
+
+            bufferSize += packSingle(arg, buffer, (Class<Object>)f.getType(), nativeType, sizeOnly);
+        }
+
+        return bufferSize;
+    }
+
+    private static <T> int packArray(T value, ByteBuffer buffer, Class<T> type, int nativeType,
+            boolean sizeOnly) {
+
+        int size = 0;
+        int arrayLength = Array.getLength(value);
+
+        @SuppressWarnings("unchecked")
+        Class<Object> componentType = (Class<Object>)type.getComponentType();
+
+        for (int i = 0; i < arrayLength; ++i) {
+            size += packSingle(Array.get(value, i), buffer, componentType, nativeType, sizeOnly);
+        }
+
+        return size;
+    }
+
+    @SuppressWarnings("unchecked")
+    private static <T> T unpackSingleNative(ByteBuffer buffer, Class<T> type, int nativeType) {
+
+        T val;
+
+        if (nativeType == TYPE_BYTE) {
+            val = (T) (Byte) buffer.get();
+        } else if (nativeType == TYPE_INT32) {
+            val = (T) (Integer) buffer.getInt();
+        } else if (nativeType == TYPE_FLOAT) {
+            val = (T) (Float) buffer.getFloat();
+        } else if (nativeType == TYPE_INT64) {
+            val = (T) (Long) buffer.getLong();
+        } else if (nativeType == TYPE_DOUBLE) {
+            val = (T) (Double) buffer.getDouble();
+        } else if (nativeType == TYPE_RATIONAL) {
+            val = (T) new Rational(buffer.getInt(), buffer.getInt());
+        } else {
+            throw new UnsupportedOperationException("Unknown type, can't unpack a native type "
+                + nativeType);
+        }
+
+        /**
+         * Rewrite types when the native type doesn't match the managed type
+         *  - Byte -> Boolean
+         *  - Byte -> Integer
+         */
+
+        if (nativeType == TYPE_BYTE && type == Boolean.TYPE) {
+            // Since a boolean can't be cast to byte, and we don't want to use getBoolean
+            byte asByte = (Byte) val;
+            boolean asBool = asByte != 0;
+            val = (T) (Boolean) asBool;
+        } else if (nativeType == TYPE_BYTE && type == Integer.TYPE) {
+            byte asByte = (Byte) val;
+            int asInt = asByte;
+            val = (T) (Integer) asInt;
+        } else if (type != getExpectedType(nativeType)) {
+            throw new UnsupportedOperationException("Tried to unpack a type of " + type +
+                    " but we expected the type to be " + getExpectedType(nativeType));
+        }
+
+        return val;
+    }
+
+    private static <T> List<Field> findInstanceFields(Class<T> type) {
+        List<Field> fields = new ArrayList<Field>();
+
+        for (Field f : type.getDeclaredFields()) {
+            if (f.isSynthetic()) {
+                throw new UnsupportedOperationException(
+                        "Marshalling synthetic fields not supported in type " + type);
+            }
+
+            // Skip static fields
+            int modifiers = f.getModifiers();
+            if ((modifiers & Modifier.STATIC) == 0) {
+                fields.add(f);
+            }
+
+            Log.v(TAG, String.format("Field %s has modifiers %d", f, modifiers));
+        }
+
+        if (type.getDeclaredFields().length == 0) {
+            Log.w(TAG, String.format("Type %s had 0 fields of any kind", type));
+        }
+        return fields;
+    }
+
+    @SuppressWarnings({"unchecked", "rawtypes"})
+    private static <T> T unpackSingle(ByteBuffer buffer, Class<T> type, int nativeType) {
+
+        if (type.isPrimitive() || type == Rational.class) {
+            return unpackSingleNative(buffer, type, nativeType);
+        }
+
+        if (type.isEnum()) {
+            return (T) unpackEnum(buffer, (Class<Enum>)type, nativeType);
+        }
+
+        if (type.isArray()) {
+            return unpackArray(buffer, type, nativeType);
+        }
+
+        T instance = unpackClass(buffer, type, nativeType);
+
+        return instance;
+    }
+
+    private static <T> Constructor<T> findApplicableConstructor(Class<T> type) {
+
+        List<Field> instanceFields = findInstanceFields(type);
+        if (instanceFields.size() == 0) {
+            throw new UnsupportedOperationException("Class has no instance fields: " + type);
+        }
+
+        Constructor<T> constructor = null;
+        int fieldCount = instanceFields.size();
+
+        HashSet<Class<?>> fieldTypes = new HashSet<Class<?>>();
+        for (Field f : instanceFields) {
+            fieldTypes.add(f.getType());
+        }
+
+        /**
+         * Find which constructor to use:
+         * - must be public
+         * - same amount of arguments as there are instance fields
+         * - each argument is same type as each field (in any order)
+         */
+        @SuppressWarnings("unchecked")
+        Constructor<T>[] constructors = (Constructor<T>[]) type.getConstructors();
+        for (Constructor<T> ctor : constructors) {
+            Log.v(TAG, String.format("Inspecting constructor '%s'", ctor));
+
+            Class<?>[] parameterTypes = ctor.getParameterTypes();
+            if (parameterTypes.length == fieldCount) {
+                boolean match = true;
+
+                HashSet<Class<?>> argTypes = new HashSet<Class<?>>();
+                for (Class<?> t : parameterTypes) {
+                    argTypes.add(t);
+                }
+
+                // Order does not matter
+                match = argTypes.equals(fieldTypes);
+
+                /*
+                // check if the types are the same
+                for (int i = 0; i < fieldCount; ++i) {
+                    if (parameterTypes[i] != instanceFields.get(i).getType()) {
+
+                        Log.v(TAG, String.format(
+                                "Constructor arg (%d) type %s did not match field type %s", i,
+                                parameterTypes[i], instanceFields.get(i).getType()));
+
+                        match = false;
+                        break;
+                    }
+                }
+                */
+
+                if (match) {
+                    constructor = ctor;
+                    break;
+                } else {
+                    Log.w(TAG, String.format("Constructor args did not have matching types"));
+                }
+            } else {
+                Log.v(TAG, String.format(
+                        "Constructor did not have expected amount of fields (had %d, expected %d)",
+                        parameterTypes.length, fieldCount));
+            }
+        }
+
+        if (constructors.length == 0) {
+            Log.w(TAG, String.format("Type %s had no public constructors", type));
+        }
+
+        if (constructor == null) {
+            throw new UnsupportedOperationException(
+                    "Failed to find any applicable constructors for type " + type);
+        }
+
+        return constructor;
+    }
+
+    private static <T extends Enum<T>> T unpackEnum(ByteBuffer buffer, Class<T> type,
+            int nativeType) {
+
+        // TODO: add support for enums with their own values.
+
+        T[] values = type.getEnumConstants();
+        int ordinal = unpackSingleNative(buffer, Integer.TYPE, nativeType);
+
+        if (ordinal < 0 || ordinal >= values.length) {
+            Log.e(TAG, String.format("Got invalid enum value %d for type %s, assuming it's 0",
+                    ordinal, type));
+            ordinal = 0;
+        }
+
+        return values[ordinal];
+    }
+
+    private static <T> T unpackClass(ByteBuffer buffer, Class<T> type, int nativeType) {
+
+        /**
+         * FIXME: This doesn't actually work because getFields() returns fields in an unordered
+         * manner. Although we could sort and get the data to come out correctly on the *java* side,
+         * it would not be data-compatible with our strict XML definitions.
+         *
+         * Rewrite this code to use Parcelables instead, they are most likely compatible with
+         * what we are trying to do in general.
+         */
+
+        List<Field> instanceFields = findInstanceFields(type);
+        if (instanceFields.size() == 0) {
+            throw new UnsupportedOperationException("Class has no instance fields: " + type);
+        }
+        int fieldCount = instanceFields.size();
+
+        Constructor<T> constructor = findApplicableConstructor(type);
+
+        /**
+         * Build the arguments by unpacking one field at a time
+         * (note that while the field type might be different, the native type is the same)
+         */
+        Object[] arguments = new Object[fieldCount];
+        for (int i = 0; i < fieldCount; ++i) {
+            Object o = unpackSingle(buffer, instanceFields.get(i).getType(), nativeType);
+            arguments[i] = o;
+        }
+
+        T instance;
+        try {
+            instance = constructor.newInstance(arguments);
+        } catch (InstantiationException e) {
+            // type is abstract class, interface, etc...
+            throw new UnsupportedOperationException("Failed to instantiate type " + type, e);
+        } catch (IllegalAccessException e) {
+            // This could happen if we have to access a private.
+            throw new UnsupportedOperationException("Failed to access type " + type, e);
+        } catch (IllegalArgumentException e) {
+            throw new UnsupportedOperationException("Illegal arguments for constructor of type "
+                    + type, e);
+        } catch (InvocationTargetException e) {
+            throw new UnsupportedOperationException(
+                    "Underlying constructor threw exception for type " + type, e);
+        }
+
+        return instance;
+    }
+
+    @SuppressWarnings("unchecked")
+    private static <T> T unpackArray(ByteBuffer buffer, Class<T> type, int nativeType) {
+
+        Class<?> componentType = type.getComponentType();
+        Object array;
+
+        int remaining = buffer.remaining();
+        // FIXME: Assumes that the rest of the ByteBuffer is part of the array.
+        int arraySize = remaining / getTypeSize(nativeType);
+
+        array = Array.newInstance(componentType, arraySize);
+        for (int i = 0; i < arraySize; ++i) {
+           Object elem = unpackSingle(buffer, componentType, nativeType);
+           Array.set(array, i, elem);
+        }
+
+        return (T) array;
     }
 
     @Override
@@ -111,11 +654,22 @@
     }
 
     public static class Key<T> {
-        public Key(String name) {
+
+        private boolean mHasTag;
+        private int mTag;
+        private final Class<T> mType;
+
+        /*
+         * @hide
+         */
+        public Key(String name, Class<T> type) {
             if (name == null) {
                 throw new NullPointerException("Key needs a valid name");
+            } else if (type == null) {
+                throw new NullPointerException("Type needs to be non-null");
             }
             mName = name;
+            mType = type;
         }
 
         public final String getName() {
@@ -144,13 +698,30 @@
         }
 
         private final String mName;
+
+        /**
+         * <p>
+         * Get the tag corresponding to this key. This enables insertion into the
+         * native metadata.
+         * </p>
+         *
+         * <p>This value is looked up the first time, and cached subsequently.</p>
+         *
+         * @return the tag numeric value corresponding to the string
+         *
+         * @hide
+         */
+        public final int getTag() {
+            if (!mHasTag) {
+                mTag = CameraMetadata.getTag(mName);
+                mHasTag = true;
+            }
+            return mTag;
+        }
     }
 
     private final Map<Key<?>, Object> mMetadataMap;
 
-    /**
-     * @hide
-     */
     private long mMetadataPtr; // native CameraMetadata*
 
     private native long nativeAllocate();
@@ -160,6 +731,14 @@
     private native synchronized void nativeClose();
     private native synchronized boolean nativeIsEmpty();
     private native synchronized int nativeGetEntryCount();
+
+    private native synchronized byte[] nativeReadValues(int tag);
+    private native synchronized void nativeWriteValues(int tag, byte[] src);
+
+    private static native int nativeGetTagFromKey(String keyName)
+            throws IllegalArgumentException;
+    private static native int nativeGetTypeFromTag(int tag)
+            throws IllegalArgumentException;
     private static native void nativeClassInit();
 
     /**
@@ -214,6 +793,61 @@
         }
     }
 
+    /**
+     * Convert a key string into the equivalent native tag.
+     *
+     * @throws IllegalArgumentException if the key was not recognized
+     * @throws NullPointerException if the key was null
+     *
+     * @hide
+     */
+    public static int getTag(String key) {
+        return nativeGetTagFromKey(key);
+    }
+
+    /**
+     * Get the underlying native type for a tag.
+     *
+     * @param tag an integer tag, see e.g. {@link #getTag}
+     * @return an int enum for the metadata type, see e.g. {@link #TYPE_BYTE}
+     *
+     * @hide
+     */
+    public static int getNativeType(int tag) {
+        return nativeGetTypeFromTag(tag);
+    }
+
+    /**
+     * <p>Updates the existing entry for tag with the new bytes pointed by src, erasing
+     * the entry if src was null.</p>
+     *
+     * <p>An empty array can be passed in to update the entry to 0 elements.</p>
+     *
+     * @param tag an integer tag, see e.g. {@link #getTag}
+     * @param src an array of bytes, or null to erase the entry
+     *
+     * @hide
+     */
+    public void writeValues(int tag, byte[] src) {
+        nativeWriteValues(tag, src);
+    }
+
+    /**
+     * <p>Returns a byte[] of data corresponding to this tag. Use a wrapped bytebuffer to unserialize
+     * the data properly.</p>
+     *
+     * <p>An empty array can be returned to denote an existing entry with 0 elements.</p>
+     *
+     * @param tag an integer tag, see e.g. {@link #getTag}
+     *
+     * @return null if there were 0 entries for this tag, a byte[] otherwise.
+     * @hide
+     */
+    public byte[] readValues(int tag) {
+     // TODO: Optimization. Native code returns a ByteBuffer instead.
+        return nativeReadValues(tag);
+    }
+
     @Override
     protected void finalize() throws Throwable {
         try {
@@ -230,4 +864,4 @@
         System.loadLibrary("media_jni");
         nativeClassInit();
     }
-}
\ No newline at end of file
+}
diff --git a/core/java/android/hardware/photography/CameraProperties.java b/core/java/android/hardware/photography/CameraProperties.java
index ad42285..2ed4e3a 100644
--- a/core/java/android/hardware/photography/CameraProperties.java
+++ b/core/java/android/hardware/photography/CameraProperties.java
@@ -40,7 +40,7 @@
      * removable cameras of the same model.
      */
     public static final Key<String> INFO_MODEL =
-            new Key<String>("android.info.model");
+            new Key<String>("android.info.model", String.class);
 
     /**
      * A unique identifier for this camera. For removable cameras, every
@@ -49,7 +49,7 @@
      * identifier is equal to the the device's id.
      */
     public static final Key<String> INFO_IDENTIFIER =
-            new Key<String>("android.info.identifier");
+            new Key<String>("android.info.identifier", String.class);
 
     /**
      * <p>Whether this camera is removable or not.</p>
@@ -59,7 +59,7 @@
      * determine if this camera is a match for a camera device seen earlier.</p>
      */
     public static final Key<Boolean> INFO_REMOVABLE =
-            new Key<Boolean>("android.info.isRemovable");
+            new Key<Boolean>("android.info.isRemovable", Boolean.TYPE);
 
     /**
      * <p>The hardware operational model of this device. One of the
@@ -100,7 +100,7 @@
      * @see #INFO_SUPPORTED_HARDWARE_LEVEL_FULL
      */
     public static final Key<Integer> INFO_SUPPORTED_HARDWARE_LEVEL =
-            new Key<Integer>("android.info.supportedHardwareLevel");
+            new Key<Integer>("android.info.supportedHardwareLevel", Integer.TYPE);
 
     /**
      * <p>The type reported by limited-capability camera devices.</p>
@@ -164,8 +164,8 @@
      * {@link android.graphics.ImageFormat#YUV_420_888} are guaranteed to be
      * supported.</p>
      */
-    public static final Key<Integer[]> SCALER_AVAILABLE_FORMATS =
-            new Key<Integer[]>("android.scaler.availableFormats");
+    public static final Key<int[]> SCALER_AVAILABLE_FORMATS =
+            new Key<int[]>("android.scaler.availableFormats", int[].class);
 
     /**
      * <p>The available output sizes for JPEG buffers from this camera
@@ -174,7 +174,7 @@
      * when using format {@link android.graphics.ImageFormat#JPEG}.</p>
      */
     public static final Key<Size[]> SCALER_AVAILABLE_JPEG_SIZES =
-            new Key<Size[]>("android.scaler.availableJpegSizes");
+            new Key<Size[]>("android.scaler.availableJpegSizes", Size[].class);
 
     /**
      * <p>The available sizes for output buffers from this camera device, when
@@ -194,7 +194,7 @@
      *
      */
     public static final Key<Size[]> SCALER_AVAILABLE_PROCESSED_SIZES =
-            new Key<Size[]>("android.scaler.availableProcessedSizes");
+            new Key<Size[]>("android.scaler.availableProcessedSizes", Size[].class);
 
     /**
      * <p>The available sizes for output buffers from this camera device, when
@@ -207,7 +207,7 @@
      * when using image format {@link android.graphics.ImageFormat#RAW_SENSOR}.</p>
      */
     public static final Key<Size[]> SCALER_AVAILABLE_RAW_SIZES =
-            new Key<Size[]>("android.scaler.availableRawSizes");
+            new Key<Size[]>("android.scaler.availableRawSizes", Size[].class);
 
     /**
      * <p>The coordinates of the sensor's active pixel array, relative to its
@@ -230,7 +230,7 @@
      * being the top-left corner of the active array.</p>
      */
     public static final Key<Rect> SENSOR_ACTIVE_ARRAY_SIZE =
-            new Key<Rect>("android.sensor.activeArraySize");
+            new Key<Rect>("android.sensor.activeArraySize", Rect.class);
 
     /**
      * <p>The size of the sensor's total pixel array available for readout. Some
@@ -240,7 +240,7 @@
      * the supported capture sizes.</p>
      */
     public static final Key<Size> SENSOR_PIXEL_ARRAY_SIZE =
-            new Key<Size>("android.sensor.activeArraySize");
+            new Key<Size>("android.sensor.activeArraySize", Size.class);
 
     // TODO: Many more of these.
 
diff --git a/core/java/android/hardware/photography/CaptureRequest.java b/core/java/android/hardware/photography/CaptureRequest.java
index ac2041b..d4a7a3c 100644
--- a/core/java/android/hardware/photography/CaptureRequest.java
+++ b/core/java/android/hardware/photography/CaptureRequest.java
@@ -58,14 +58,14 @@
      * The exposure time for this capture, in nanoseconds.
      */
     public static final Key<Long> SENSOR_EXPOSURE_TIME =
-            new Key<Long>("android.sensor.exposureTime");
+            new Key<Long>("android.sensor.exposureTime", Long.TYPE);
 
     /**
      * The sensor sensitivity (gain) setting for this camera.
      * This is represented as an ISO sensitivity value
      */
     public static final Key<Integer> SENSOR_SENSITIVITY =
-            new Key<Integer>("android.sensor.sensitivity");
+            new Key<Integer>("android.sensor.sensitivity", Integer.TYPE);
 
     // Many more settings
 
diff --git a/core/java/android/hardware/photography/CaptureResult.java b/core/java/android/hardware/photography/CaptureResult.java
index b502c4c..2fdd466 100644
--- a/core/java/android/hardware/photography/CaptureResult.java
+++ b/core/java/android/hardware/photography/CaptureResult.java
@@ -42,15 +42,15 @@
      * or {@link android.media.Image#getTimestamp Image.getTimestamp()} for this
      * capture's image data.
      */
-    public static final Key SENSOR_TIMESTAMP =
-            new Key<Long>("android.sensor.timestamp");
+    public static final Key<Long> SENSOR_TIMESTAMP =
+            new Key<Long>("android.sensor.timestamp", Long.TYPE);
 
     /**
      * The state of the camera device's auto-exposure algorithm. One of the
      * CONTROL_AE_STATE_* enumerations.
      */
-    public static final Key CONTROL_AE_STATE =
-            new Key<Integer>("android.control.aeState");
+    public static final Key<Integer> CONTROL_AE_STATE =
+            new Key<Integer>("android.control.aeState", Integer.TYPE);
 
     /**
      * The auto-exposure algorithm is inactive.
@@ -96,8 +96,8 @@
      * The list of faces detected in this capture. Available if face detection
      * was enabled for this capture
      */
-    public static final Key STATISTICS_DETECTED_FACES =
-            new Key<Face[]>("android.statistics.faces");
+    public static final Key<Face[]> STATISTICS_DETECTED_FACES =
+            new Key<Face[]>("android.statistics.faces", Face[].class);
 
     // TODO: Many many more
 
diff --git a/core/java/android/hardware/photography/Rational.java b/core/java/android/hardware/photography/Rational.java
new file mode 100644
index 0000000..66e533e
--- /dev/null
+++ b/core/java/android/hardware/photography/Rational.java
@@ -0,0 +1,162 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package android.hardware.photography;
+
+/**
+ * The rational data type used by CameraMetadata keys. Contains a pair of ints representing the
+ * numerator and denominator of a Rational number. This type is immutable.
+ */
+public final class Rational {
+    private final int mNumerator;
+    private final int mDenominator;
+
+    /**
+     * <p>Create a Rational with a given numerator and denominator.</p>
+     *
+     * <p>
+     * The signs of the numerator and the denominator may be flipped such that the denominator
+     * is always 0.
+     * </p>
+     *
+     * @param numerator the numerator of the rational
+     * @param denominator the denominator of the rational
+     *
+     * @throws IllegalArgumentException if the denominator is 0
+     */
+    public Rational(int numerator, int denominator) {
+
+        if (denominator == 0) {
+            throw new IllegalArgumentException("Argument 'denominator' is 0");
+        }
+
+        if (denominator < 0) {
+            numerator = -numerator;
+            denominator = -denominator;
+        }
+
+        mNumerator = numerator;
+        mDenominator = denominator;
+    }
+
+    /**
+     * Gets the numerator of the rational.
+     */
+    public int getNumerator() {
+        return mNumerator;
+    }
+
+    /**
+     * Gets the denominator of the rational
+     */
+    public int getDenominator() {
+        return mDenominator;
+    }
+
+    /**
+     * <p>Compare this Rational to another object and see if they are equal.</p>
+     *
+     * <p>A Rational object can only be equal to another Rational object (comparing against any other
+     * type will return false).</p>
+     *
+     * <p>A Rational object is considered equal to another Rational object if and only if their
+     * reduced forms have the same numerator and denominator.</p>
+     *
+     * <p>A reduced form of a Rational is calculated by dividing both the numerator and the
+     * denominator by their greatest common divisor.</p>
+     *
+     * <pre>
+     *      (new Rational(1, 2)).equals(new Rational(1, 2)) == true  // trivially true
+     *      (new Rational(2, 3)).equals(new Rational(1, 2)) == false // trivially false
+     *      (new Rational(1, 2)).equals(new Rational(2, 4)) == true  // true after reduction
+     * </pre>
+     *
+     * @param obj a reference to another object
+     *
+     * @return boolean that determines whether or not the two Rational objects are equal.
+     */
+    @Override
+    public boolean equals(Object obj) {
+        if (obj == null) {
+            return false;
+        }
+        if (this == obj) {
+            return true;
+        }
+        if (obj instanceof Rational) {
+            Rational other = (Rational) obj;
+            if(mNumerator == other.mNumerator && mDenominator == other.mDenominator) {
+                return true;
+            } else {
+                int thisGcd = gcd();
+                int otherGcd = other.gcd();
+
+                int thisNumerator = mNumerator / thisGcd;
+                int thisDenominator = mDenominator / thisGcd;
+
+                int otherNumerator = other.mNumerator / otherGcd;
+                int otherDenominator = other.mDenominator / otherGcd;
+
+                return (thisNumerator == otherNumerator && thisDenominator == otherDenominator);
+            }
+        }
+        return false;
+    }
+
+    @Override
+    public String toString() {
+        return mNumerator + "/" + mDenominator;
+    }
+
+    @Override
+    public int hashCode() {
+        final long INT_MASK = 0xffffffffL;
+
+        long asLong = INT_MASK & mNumerator;
+        asLong <<= 32;
+
+        asLong |= (INT_MASK & mDenominator);
+
+        return ((Long)asLong).hashCode();
+    }
+
+    /**
+     * Calculates the greatest common divisor using Euclid's algorithm.
+     *
+     * @return int value representing the gcd. Always positive.
+     * @hide
+     */
+    public int gcd() {
+        /**
+         * Non-recursive implementation of Euclid's algorithm:
+         *
+         *  gcd(a, 0) := a
+         *  gcd(a, b) := gcd(b, a mod b)
+         *
+         */
+
+        int a = mNumerator;
+        int b = mDenominator;
+
+        while (b != 0) {
+            int oldB = b;
+
+            b = a % b;
+            a = oldB;
+        }
+
+        return Math.abs(a);
+    }
+}
diff --git a/core/java/android/hardware/photography/Size.java b/core/java/android/hardware/photography/Size.java
index e1115d3..ee7980e 100644
--- a/core/java/android/hardware/photography/Size.java
+++ b/core/java/android/hardware/photography/Size.java
@@ -24,12 +24,12 @@
     /**
      * Create a new immutable Size instance
      *
-     * @param w The width to store in the Size instance
-     * @param h The height to store in the Size instance
+     * @param width The width to store in the Size instance
+     * @param height The height to store in the Size instance
      */
-    Size(int w, int h) {
-        mWidth = w;
-        mHeight = h;
+    Size(int width, int height) {
+        mWidth = width;
+        mHeight = height;
     }
 
     public final int getWidth() {
diff --git a/core/jni/Android.mk b/core/jni/Android.mk
index 20e5011..d60fa18 100644
--- a/core/jni/Android.mk
+++ b/core/jni/Android.mk
@@ -196,6 +196,7 @@
 	libgui \
 	libinput \
 	libcamera_client \
+	libcamera_metadata \
 	libskia \
 	libsqlite \
 	libEGL \
diff --git a/core/jni/android_hardware_photography_CameraMetadata.cpp b/core/jni/android_hardware_photography_CameraMetadata.cpp
index fa363f3..5070d2c 100644
--- a/core/jni/android_hardware_photography_CameraMetadata.cpp
+++ b/core/jni/android_hardware_photography_CameraMetadata.cpp
@@ -16,6 +16,7 @@
 */
 
 // #define LOG_NDEBUG 0
+// #define LOG_NNDEBUG 0
 #define LOG_TAG "CameraMetadata-JNI"
 #include <utils/Log.h>
 
@@ -25,6 +26,16 @@
 #include "android_runtime/AndroidRuntime.h"
 
 #include <camera/CameraMetadata.h>
+#include <nativehelper/ScopedUtfChars.h>
+#include <nativehelper/ScopedPrimitiveArray.h>
+
+#if defined(LOG_NNDEBUG)
+#if !LOG_NNDEBUG
+#define ALOGVV ALOGV
+#endif
+#else
+#define ALOGVV(...)
+#endif
 
 // fully-qualified class name
 #define CAMERA_METADATA_CLASS_NAME "android/hardware/photography/CameraMetadata"
@@ -37,9 +48,70 @@
 
 static fields_t fields;
 
+namespace {
+struct Helpers {
+    static size_t getTypeSize(uint8_t type) {
+        if (type >= NUM_TYPES) {
+            ALOGE("%s: Invalid type specified (%ud)", __FUNCTION__, type);
+            return static_cast<size_t>(-1);
+        }
+
+        return camera_metadata_type_size[type];
+    }
+
+    static status_t updateAny(CameraMetadata *metadata,
+                          uint32_t tag,
+                          uint32_t type,
+                          const void *data,
+                          size_t dataBytes) {
+
+        if (type >= NUM_TYPES) {
+            ALOGE("%s: Invalid type specified (%ud)", __FUNCTION__, type);
+            return INVALID_OPERATION;
+        }
+
+        size_t typeSize = getTypeSize(type);
+
+        if (dataBytes % typeSize != 0) {
+            ALOGE("%s: Expected dataBytes (%ud) to be divisible by typeSize "
+                  "(%ud)", __FUNCTION__, dataBytes, typeSize);
+            return BAD_VALUE;
+        }
+
+        size_t dataCount = dataBytes / typeSize;
+
+        switch(type) {
+#define METADATA_UPDATE(runtime_type, compile_type)                            \
+            case runtime_type: {                                               \
+                const compile_type *dataPtr =                                  \
+                        static_cast<const compile_type*>(data);                \
+                return metadata->update(tag, dataPtr, dataCount);              \
+            }                                                                  \
+
+            METADATA_UPDATE(TYPE_BYTE,     uint8_t);
+            METADATA_UPDATE(TYPE_INT32,    int32_t);
+            METADATA_UPDATE(TYPE_FLOAT,    float);
+            METADATA_UPDATE(TYPE_INT64,    int64_t);
+            METADATA_UPDATE(TYPE_DOUBLE,   double);
+            METADATA_UPDATE(TYPE_RATIONAL, camera_metadata_rational_t);
+
+            default: {
+                // unreachable
+                ALOGE("%s: Unreachable", __FUNCTION__);
+                return INVALID_OPERATION;
+            }
+        }
+
+#undef METADATA_UPDATE
+    }
+};
+} // namespace {}
+
 extern "C" {
 
 static void CameraMetadata_classInit(JNIEnv *env, jobject thiz);
+static jint CameraMetadata_getTagFromKey(JNIEnv *env, jobject thiz, jstring keyName);
+static jint CameraMetadata_getTypeFromTag(JNIEnv *env, jobject thiz, jint tag);
 
 // Less safe access to native pointer. Does NOT throw any Java exceptions if NULL.
 static CameraMetadata* CameraMetadata_getPointerNoThrow(JNIEnv *env, jobject thiz) {
@@ -140,6 +212,86 @@
     metadata->swap(*otherMetadata);
 }
 
+static jbyteArray CameraMetadata_readValues(JNIEnv *env, jobject thiz, jint tag) {
+    ALOGV("%s (tag = %d)", __FUNCTION__, tag);
+
+    CameraMetadata* metadata = CameraMetadata_getPointerThrow(env, thiz);
+    if (metadata == NULL) return NULL;
+
+    int tagType = get_camera_metadata_tag_type(tag);
+    if (tagType == -1) {
+        jniThrowExceptionFmt(env, "java/lang/IllegalArgumentException",
+                             "Tag (%d) did not have a type", tag);
+        return NULL;
+    }
+    size_t tagSize = Helpers::getTypeSize(tagType);
+
+    camera_metadata_entry entry = metadata->find(tag);
+    if (entry.count == 0) {
+         if (!metadata->exists(tag)) {
+             ALOGV("%s: Tag %d does not have any entries", __FUNCTION__, tag);
+             return NULL;
+         } else {
+             // OK: we will return a 0-sized array.
+             ALOGV("%s: Tag %d had an entry, but it had 0 data", __FUNCTION__,
+                   tag);
+         }
+    }
+
+    jsize byteCount = entry.count * tagSize;
+    jbyteArray byteArray = env->NewByteArray(byteCount);
+    if (env->ExceptionCheck()) return NULL;
+
+    // Copy into java array from native array
+    ScopedByteArrayRW arrayWriter(env, byteArray);
+    memcpy(arrayWriter.get(), entry.data.u8, byteCount);
+
+    return byteArray;
+}
+
+static void CameraMetadata_writeValues(JNIEnv *env, jobject thiz, jint tag, jbyteArray src) {
+    ALOGV("%s (tag = %d)", __FUNCTION__, tag);
+
+    CameraMetadata* metadata = CameraMetadata_getPointerThrow(env, thiz);
+    if (metadata == NULL) return;
+
+    int tagType = get_camera_metadata_tag_type(tag);
+    if (tagType == -1) {
+        jniThrowExceptionFmt(env, "java/lang/IllegalArgumentException",
+                             "Tag (%d) did not have a type", tag);
+        return;
+    }
+    size_t tagSize = Helpers::getTypeSize(tagType);
+
+    status_t res;
+
+    if (src == NULL) {
+        // If array is NULL, delete the entry
+        res = metadata->erase(tag);
+    } else {
+        // Copy from java array into native array
+        ScopedByteArrayRO arrayReader(env, src);
+        if (arrayReader.get() == NULL) return;
+
+        res = Helpers::updateAny(metadata, static_cast<uint32_t>(tag),
+                                 tagType, arrayReader.get(), arrayReader.size());
+    }
+
+    if (res == OK) {
+        return;
+    } else if (res == BAD_VALUE) {
+        jniThrowExceptionFmt(env, "java/lang/IllegalArgumentException",
+                             "Src byte array was poorly formed");
+    } else if (res == INVALID_OPERATION) {
+        jniThrowExceptionFmt(env, "java/lang/IllegalStateException",
+                             "Internal error while trying to update metadata");
+    } else {
+        jniThrowExceptionFmt(env, "java/lang/IllegalStateException",
+                             "Unknown error (%d) while trying to update "
+                            "metadata", res);
+    }
+}
+
 static void CameraMetadata_readFromParcel(JNIEnv *env, jobject thiz, jobject parcel) {
     ALOGV("%s", __FUNCTION__);
     CameraMetadata* metadata = CameraMetadata_getPointerThrow(env, thiz);
@@ -187,9 +339,17 @@
 //-------------------------------------------------
 
 static JNINativeMethod gCameraMetadataMethods[] = {
+// static methods
   { "nativeClassInit",
     "()V",
     (void *)CameraMetadata_classInit },
+  { "nativeGetTagFromKey",
+    "(Ljava/lang/String;)I",
+    (void *)CameraMetadata_getTagFromKey },
+  { "nativeGetTypeFromTag",
+    "(I)I",
+    (void *)CameraMetadata_getTypeFromTag },
+// instance methods
   { "nativeAllocate",
     "()J",
     (void*)CameraMetadata_allocate },
@@ -205,6 +365,13 @@
   { "nativeSwap",
     "(L" CAMERA_METADATA_CLASS_NAME ";)V",
     (void *)CameraMetadata_swap },
+  { "nativeReadValues",
+    "(I)[B",
+    (void *)CameraMetadata_readValues },
+  { "nativeWriteValues",
+    "(I[B)V",
+    (void *)CameraMetadata_writeValues },
+// Parcelable interface
   { "nativeReadFromParcel",
     "(Landroid/os/Parcel;)V",
     (void *)CameraMetadata_readFromParcel },
@@ -268,4 +435,99 @@
 
     jclass clazz = env->FindClass(CAMERA_METADATA_CLASS_NAME);
 }
+
+static jint CameraMetadata_getTagFromKey(JNIEnv *env, jobject thiz, jstring keyName) {
+
+    ScopedUtfChars keyScoped(env, keyName);
+    const char *key = keyScoped.c_str();
+    if (key == NULL) {
+        // exception thrown by ScopedUtfChars
+        return 0;
+    }
+    size_t keyLength = strlen(key);
+
+    ALOGV("%s (key = '%s')", __FUNCTION__, key);
+
+    // First, find the section by the longest string match
+    const char *section = NULL;
+    size_t sectionIndex = 0;
+    size_t sectionLength = 0;
+    for (size_t i = 0; i < ANDROID_SECTION_COUNT; ++i) {
+        const char *str = camera_metadata_section_names[i];
+        ALOGVV("%s: Trying to match against section '%s'",
+               __FUNCTION__, str);
+        if (strstr(key, str) == key) { // key begins with the section name
+            size_t strLength = strlen(str);
+
+            ALOGVV("%s: Key begins with section name", __FUNCTION__);
+
+            // section name is the longest we've found so far
+            if (section == NULL || sectionLength < strLength) {
+                section = str;
+                sectionIndex = i;
+                sectionLength = strLength;
+
+                ALOGVV("%s: Found new best section (idx %d)", __FUNCTION__, sectionIndex);
+            }
+        }
+    }
+
+    // TODO: vendor ext
+    // TODO: Make above get_camera_metadata_section_from_name ?
+
+    if (section == NULL) {
+        jniThrowExceptionFmt(env, "java/lang/IllegalArgumentException",
+                             "Could not find section name for key '%s')", key);
+        return 0;
+    } else {
+        ALOGV("%s: Found matched section '%s' (%d)",
+              __FUNCTION__, section, sectionIndex);
+    }
+
+    // Get the tag name component of the key
+    const char *keyTagName = key + sectionLength + 1; // x.y.z -> z
+    if (sectionLength + 1 >= keyLength) {
+        jniThrowExceptionFmt(env, "java/lang/IllegalArgumentException",
+                             "Key length too short for key '%s')", key);
+    }
+
+    // Match rest of name against the tag names in that section only
+    uint32_t tagBegin, tagEnd; // [tagBegin, tagEnd)
+    tagBegin = camera_metadata_section_bounds[sectionIndex][0];
+    tagEnd = camera_metadata_section_bounds[sectionIndex][1];
+
+    uint32_t tag;
+    for (tag = tagBegin; tag < tagEnd; ++tag) {
+        const char *tagName = get_camera_metadata_tag_name(tag);
+
+        if (strcmp(keyTagName, tagName) == 0) {
+            ALOGV("%s: Found matched tag '%s' (%d)",
+                  __FUNCTION__, tagName, tag);
+            break;
+        }
+    }
+
+    // TODO: vendor ext
+    // TODO: Make above get_camera_metadata_tag_from_name ?
+
+    if (tag == tagEnd) {
+        jniThrowExceptionFmt(env, "java/lang/IllegalArgumentException",
+                             "Could not find tag name for key '%s')", key);
+        return 0;
+    }
+
+    return tag;
+}
+
+static jint CameraMetadata_getTypeFromTag(JNIEnv *env, jobject thiz, jint tag) {
+    int tagType = get_camera_metadata_tag_type(tag);
+    if (tagType == -1) {
+        jniThrowExceptionFmt(env, "java/lang/IllegalArgumentException",
+                             "Tag (%d) did not have a type", tag);
+        return -1;
+    }
+
+    return tagType;
+}
+
 } // extern "C"