summaryrefslogtreecommitdiffstats
path: root/core/java/android/hardware/camera2/DngCreator.java
blob: 57a080b9346bcfcae2598d9e00ca5fc70be4de2f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
/*
 * Copyright 2014 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.camera2;

import android.annotation.IntRange;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.ImageFormat;
import android.hardware.camera2.impl.CameraMetadataNative;
import android.location.Location;
import android.media.ExifInterface;
import android.media.Image;
import android.os.SystemClock;
import android.util.Size;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimeZone;

/**
 * The {@link DngCreator} class provides functions to write raw pixel data as a DNG file.
 *
 * <p>
 * This class is designed to be used with the {@link android.graphics.ImageFormat#RAW_SENSOR}
 * buffers available from {@link android.hardware.camera2.CameraDevice}, or with Bayer-type raw
 * pixel data that is otherwise generated by an application.  The DNG metadata tags will be
 * generated from a {@link android.hardware.camera2.CaptureResult} object or set directly.
 * </p>
 *
 * <p>
 * The DNG file format is a cross-platform file format that is used to store pixel data from
 * camera sensors with minimal pre-processing applied.  DNG files allow for pixel data to be
 * defined in a user-defined colorspace, and have associated metadata that allow for this
 * pixel data to be converted to the standard CIE XYZ colorspace during post-processing.
 * </p>
 *
 * <p>
 * For more information on the DNG file format and associated metadata, please refer to the
 * <a href=
 * "https://wwwimages2.adobe.com/content/dam/Adobe/en/products/photoshop/pdfs/dng_spec_1.4.0.0.pdf">
 * Adobe DNG 1.4.0.0 specification</a>.
 * </p>
 */
public final class DngCreator implements AutoCloseable {

    private static final String TAG = "DngCreator";
    /**
     * Create a new DNG object.
     *
     * <p>
     * It is not necessary to call any set methods to write a well-formatted DNG file.
     * </p>
     * <p>
     * DNG metadata tags will be generated from the corresponding parameters in the
     * {@link android.hardware.camera2.CaptureResult} object.
     * </p>
     * <p>
     * For best quality DNG files, it is strongly recommended that lens shading map output is
     * enabled if supported. See {@link CaptureRequest#STATISTICS_LENS_SHADING_MAP_MODE}.
     * </p>
     * @param characteristics an object containing the static
     *          {@link android.hardware.camera2.CameraCharacteristics}.
     * @param metadata a metadata object to generate tags from.
     */
    public DngCreator(@NonNull CameraCharacteristics characteristics,
            @NonNull CaptureResult metadata) {
        if (characteristics == null || metadata == null) {
            throw new IllegalArgumentException("Null argument to DngCreator constructor");
        }

        // Find current time
        long currentTime = System.currentTimeMillis();

        // Find boot time
        long bootTimeMillis = currentTime - SystemClock.elapsedRealtime();

        // Find capture time (nanos since boot)
        Long timestamp = metadata.get(CaptureResult.SENSOR_TIMESTAMP);
        long captureTime = currentTime;
        if (timestamp != null) {
            captureTime = timestamp / 1000000 + bootTimeMillis;
        }

        // Format for metadata
        String formattedCaptureTime = sDateTimeStampFormat.format(captureTime);

        nativeInit(characteristics.getNativeCopy(), metadata.getNativeCopy(),
                formattedCaptureTime);
    }

    /**
     * Set the orientation value to write.
     *
     * <p>
     * This will be written as the TIFF "Orientation" tag {@code (0x0112)}.
     * Calling this will override any prior settings for this tag.
     * </p>
     *
     * @param orientation the orientation value to set, one of:
     *                    <ul>
     *                      <li>{@link android.media.ExifInterface#ORIENTATION_NORMAL}</li>
     *                      <li>{@link android.media.ExifInterface#ORIENTATION_FLIP_HORIZONTAL}</li>
     *                      <li>{@link android.media.ExifInterface#ORIENTATION_ROTATE_180}</li>
     *                      <li>{@link android.media.ExifInterface#ORIENTATION_FLIP_VERTICAL}</li>
     *                      <li>{@link android.media.ExifInterface#ORIENTATION_TRANSPOSE}</li>
     *                      <li>{@link android.media.ExifInterface#ORIENTATION_ROTATE_90}</li>
     *                      <li>{@link android.media.ExifInterface#ORIENTATION_TRANSVERSE}</li>
     *                      <li>{@link android.media.ExifInterface#ORIENTATION_ROTATE_270}</li>
     *                    </ul>
     * @return this {@link #DngCreator} object.
     */
    @NonNull
    public DngCreator setOrientation(int orientation) {
        if (orientation < ExifInterface.ORIENTATION_UNDEFINED ||
                orientation > ExifInterface.ORIENTATION_ROTATE_270) {
            throw new IllegalArgumentException("Orientation " + orientation +
                    " is not a valid EXIF orientation value");
        }
        nativeSetOrientation(orientation);
        return this;
    }

    /**
     * Set the thumbnail image.
     *
     * <p>
     * Pixel data will be converted to a Baseline TIFF RGB image, with 8 bits per color channel.
     * The alpha channel will be discarded.  Thumbnail images with a dimension larger than
     * {@link #MAX_THUMBNAIL_DIMENSION} will be rejected.
     * </p>
     *
     * @param pixels a {@link android.graphics.Bitmap} of pixel data.
     * @return this {@link #DngCreator} object.
     * @throws java.lang.IllegalArgumentException if the given thumbnail image has a dimension
     *      larger than {@link #MAX_THUMBNAIL_DIMENSION}.
     */
    @NonNull
    public DngCreator setThumbnail(@NonNull Bitmap pixels) {
        if (pixels == null) {
            throw new IllegalArgumentException("Null argument to setThumbnail");
        }

        int width = pixels.getWidth();
        int height = pixels.getHeight();

        if (width > MAX_THUMBNAIL_DIMENSION || height > MAX_THUMBNAIL_DIMENSION) {
            throw new IllegalArgumentException("Thumbnail dimensions width,height (" + width +
                    "," + height + ") too large, dimensions must be smaller than " +
                    MAX_THUMBNAIL_DIMENSION);
        }

        ByteBuffer rgbBuffer = convertToRGB(pixels);
        nativeSetThumbnail(rgbBuffer, width, height);

        return this;
    }

    /**
     * Set the thumbnail image.
     *
     * <p>
     * Pixel data is interpreted as a {@link android.graphics.ImageFormat#YUV_420_888} image.
     * Thumbnail images with a dimension larger than {@link #MAX_THUMBNAIL_DIMENSION} will be
     * rejected.
     * </p>
     *
     * @param pixels an {@link android.media.Image} object with the format
     *               {@link android.graphics.ImageFormat#YUV_420_888}.
     * @return this {@link #DngCreator} object.
     * @throws java.lang.IllegalArgumentException if the given thumbnail image has a dimension
     *      larger than {@link #MAX_THUMBNAIL_DIMENSION}.
     */
    @NonNull
    public DngCreator setThumbnail(@NonNull Image pixels) {
        if (pixels == null) {
            throw new IllegalArgumentException("Null argument to setThumbnail");
        }

        int format = pixels.getFormat();
        if (format != ImageFormat.YUV_420_888) {
            throw new IllegalArgumentException("Unsupported Image format " + format);
        }

        int width = pixels.getWidth();
        int height = pixels.getHeight();

        if (width > MAX_THUMBNAIL_DIMENSION || height > MAX_THUMBNAIL_DIMENSION) {
            throw new IllegalArgumentException("Thumbnail dimensions width,height (" + width +
                    "," + height + ") too large, dimensions must be smaller than " +
                    MAX_THUMBNAIL_DIMENSION);
        }

        ByteBuffer rgbBuffer = convertToRGB(pixels);
        nativeSetThumbnail(rgbBuffer, width, height);

        return this;
    }

    /**
     * Set image location metadata.
     *
     * <p>
     * The given location object must contain at least a valid time, latitude, and longitude
     * (equivalent to the values returned by {@link android.location.Location#getTime()},
     * {@link android.location.Location#getLatitude()}, and
     * {@link android.location.Location#getLongitude()} methods).
     * </p>
     *
     * @param location an {@link android.location.Location} object to set.
     * @return this {@link #DngCreator} object.
     *
     * @throws java.lang.IllegalArgumentException if the given location object doesn't
     *          contain enough information to set location metadata.
     */
    @NonNull
    public DngCreator setLocation(@NonNull Location location) {
        if (location == null) {
            throw new IllegalArgumentException("Null location passed to setLocation");
        }
        double latitude = location.getLatitude();
        double longitude = location.getLongitude();
        long time = location.getTime();

        int[] latTag = toExifLatLong(latitude);
        int[] longTag = toExifLatLong(longitude);
        String latRef = latitude >= 0 ? GPS_LAT_REF_NORTH : GPS_LAT_REF_SOUTH;
        String longRef = longitude >= 0 ? GPS_LONG_REF_EAST : GPS_LONG_REF_WEST;

        String dateTag = sExifGPSDateStamp.format(time);
        mGPSTimeStampCalendar.setTimeInMillis(time);
        int[] timeTag = new int[] { mGPSTimeStampCalendar.get(Calendar.HOUR_OF_DAY), 1,
                mGPSTimeStampCalendar.get(Calendar.MINUTE), 1,
                mGPSTimeStampCalendar.get(Calendar.SECOND), 1 };
        nativeSetGpsTags(latTag, latRef, longTag, longRef, dateTag, timeTag);
        return this;
    }

    /**
     * Set the user description string to write.
     *
     * <p>
     * This is equivalent to setting the TIFF "ImageDescription" tag {@code (0x010E)}.
     * </p>
     *
     * @param description the user description string.
     * @return this {@link #DngCreator} object.
     */
    @NonNull
    public DngCreator setDescription(@NonNull String description) {
        if (description == null) {
            throw new IllegalArgumentException("Null description passed to setDescription.");
        }
        nativeSetDescription(description);
        return this;
    }

    /**
     * Write the {@link android.graphics.ImageFormat#RAW_SENSOR} pixel data to a DNG file with
     * the currently configured metadata.
     *
     * <p>
     * Raw pixel data must have 16 bits per pixel, and the input must contain at least
     * {@code offset + 2 * width * height)} bytes.  The width and height of
     * the input are taken from the width and height set in the {@link DngCreator} metadata tags,
     * and will typically be equal to the width and height of
     * {@link CameraCharacteristics#SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE}.  Prior to
     * API level 23, this was always the same as
     * {@link CameraCharacteristics#SENSOR_INFO_ACTIVE_ARRAY_SIZE}.
     * The pixel layout in the input is determined from the reported color filter arrangement (CFA)
     * set in {@link CameraCharacteristics#SENSOR_INFO_COLOR_FILTER_ARRANGEMENT}.  If insufficient
     * metadata is available to write a well-formatted DNG file, an
     * {@link java.lang.IllegalStateException} will be thrown.
     * </p>
     *
     * @param dngOutput an {@link java.io.OutputStream} to write the DNG file to.
     * @param size the {@link Size} of the image to write, in pixels.
     * @param pixels an {@link java.io.InputStream} of pixel data to write.
     * @param offset the offset of the raw image in bytes.  This indicates how many bytes will
     *               be skipped in the input before any pixel data is read.
     *
     * @throws IOException if an error was encountered in the input or output stream.
     * @throws java.lang.IllegalStateException if not enough metadata information has been
     *          set to write a well-formatted DNG file.
     * @throws java.lang.IllegalArgumentException if the size passed in does not match the
     */
    public void writeInputStream(@NonNull OutputStream dngOutput, @NonNull Size size,
            @NonNull InputStream pixels, @IntRange(from=0) long offset) throws IOException {
        if (dngOutput == null) {
            throw new IllegalArgumentException("Null dngOutput passed to writeInputStream");
        } else if (size == null) {
            throw new IllegalArgumentException("Null size passed to writeInputStream");
        } else if (pixels == null) {
            throw new IllegalArgumentException("Null pixels passed to writeInputStream");
        } else if (offset < 0) {
            throw new IllegalArgumentException("Negative offset passed to writeInputStream");
        }

        int width = size.getWidth();
        int height = size.getHeight();
        if (width <= 0 || height <= 0) {
            throw new IllegalArgumentException("Size with invalid width, height: (" + width + "," +
                    height + ") passed to writeInputStream");
        }
        nativeWriteInputStream(dngOutput, pixels, width, height, offset);
    }

    /**
     * Write the {@link android.graphics.ImageFormat#RAW_SENSOR} pixel data to a DNG file with
     * the currently configured metadata.
     *
     * <p>
     * Raw pixel data must have 16 bits per pixel, and the input must contain at least
     * {@code offset + 2 * width * height)} bytes.  The width and height of
     * the input are taken from the width and height set in the {@link DngCreator} metadata tags,
     * and will typically be equal to the width and height of
     * {@link CameraCharacteristics#SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE}.  Prior to
     * API level 23, this was always the same as
     * {@link CameraCharacteristics#SENSOR_INFO_ACTIVE_ARRAY_SIZE}.
     * The pixel layout in the input is determined from the reported color filter arrangement (CFA)
     * set in {@link CameraCharacteristics#SENSOR_INFO_COLOR_FILTER_ARRANGEMENT}.  If insufficient
     * metadata is available to write a well-formatted DNG file, an
     * {@link java.lang.IllegalStateException} will be thrown.
     * </p>
     *
     * <p>
     * Any mark or limit set on this {@link ByteBuffer} is ignored, and will be cleared by this
     * method.
     * </p>
     *
     * @param dngOutput an {@link java.io.OutputStream} to write the DNG file to.
     * @param size the {@link Size} of the image to write, in pixels.
     * @param pixels an {@link java.nio.ByteBuffer} of pixel data to write.
     * @param offset the offset of the raw image in bytes.  This indicates how many bytes will
     *               be skipped in the input before any pixel data is read.
     *
     * @throws IOException if an error was encountered in the input or output stream.
     * @throws java.lang.IllegalStateException if not enough metadata information has been
     *          set to write a well-formatted DNG file.
     */
    public void writeByteBuffer(@NonNull OutputStream dngOutput, @NonNull Size size,
            @NonNull ByteBuffer pixels, @IntRange(from=0) long offset)
            throws IOException {
        if (dngOutput == null) {
            throw new IllegalArgumentException("Null dngOutput passed to writeByteBuffer");
        } else if (size == null) {
            throw new IllegalArgumentException("Null size passed to writeByteBuffer");
        } else if (pixels == null) {
            throw new IllegalArgumentException("Null pixels passed to writeByteBuffer");
        } else if (offset < 0) {
            throw new IllegalArgumentException("Negative offset passed to writeByteBuffer");
        }

        int width = size.getWidth();
        int height = size.getHeight();

        writeByteBuffer(width, height, pixels, dngOutput, DEFAULT_PIXEL_STRIDE,
                width * DEFAULT_PIXEL_STRIDE, offset);
    }

    /**
     * Write the pixel data to a DNG file with the currently configured metadata.
     *
     * <p>
     * For this method to succeed, the {@link android.media.Image} input must contain
     * {@link android.graphics.ImageFormat#RAW_SENSOR} pixel data, otherwise an
     * {@link java.lang.IllegalArgumentException} will be thrown.
     * </p>
     *
     * @param dngOutput an {@link java.io.OutputStream} to write the DNG file to.
     * @param pixels an {@link android.media.Image} to write.
     *
     * @throws java.io.IOException if an error was encountered in the output stream.
     * @throws java.lang.IllegalArgumentException if an image with an unsupported format was used.
     * @throws java.lang.IllegalStateException if not enough metadata information has been
     *          set to write a well-formatted DNG file.
     */
    public void writeImage(@NonNull OutputStream dngOutput, @NonNull Image pixels)
            throws IOException {
        if (dngOutput == null) {
            throw new IllegalArgumentException("Null dngOutput to writeImage");
        } else if (pixels == null) {
            throw new IllegalArgumentException("Null pixels to writeImage");
        }

        int format = pixels.getFormat();
        if (format != ImageFormat.RAW_SENSOR) {
            throw new IllegalArgumentException("Unsupported image format " + format);
        }

        Image.Plane[] planes = pixels.getPlanes();
        if (planes == null || planes.length <= 0) {
            throw new IllegalArgumentException("Image with no planes passed to writeImage");
        }

        ByteBuffer buf = planes[0].getBuffer();
        writeByteBuffer(pixels.getWidth(), pixels.getHeight(), buf, dngOutput,
                planes[0].getPixelStride(), planes[0].getRowStride(), 0);
    }

    @Override
    public void close() {
        nativeDestroy();
    }

    /**
     * Max width or height dimension for thumbnails.
     */
    public static final int MAX_THUMBNAIL_DIMENSION = 256; // max pixel dimension for TIFF/EP

    @Override
    protected void finalize() throws Throwable {
        try {
            close();
        } finally {
            super.finalize();
        }
    }

    private static final String GPS_LAT_REF_NORTH = "N";
    private static final String GPS_LAT_REF_SOUTH = "S";
    private static final String GPS_LONG_REF_EAST = "E";
    private static final String GPS_LONG_REF_WEST = "W";

    private static final String GPS_DATE_FORMAT_STR = "yyyy:MM:dd";
    private static final String TIFF_DATETIME_FORMAT = "yyyy:MM:dd kk:mm:ss";
    private static final DateFormat sExifGPSDateStamp = new SimpleDateFormat(GPS_DATE_FORMAT_STR);
    private static final DateFormat sDateTimeStampFormat =
            new SimpleDateFormat(TIFF_DATETIME_FORMAT);
    private final Calendar mGPSTimeStampCalendar = Calendar
            .getInstance(TimeZone.getTimeZone("UTC"));

    static {
        sDateTimeStampFormat.setTimeZone(TimeZone.getDefault());
        sExifGPSDateStamp.setTimeZone(TimeZone.getTimeZone("UTC"));
    }

    private static final int DEFAULT_PIXEL_STRIDE = 2; // bytes per sample
    private static final int BYTES_PER_RGB_PIX = 3; // byts per pixel

    /**
     * Offset, rowStride, and pixelStride are given in bytes.  Height and width are given in pixels.
     */
    private void writeByteBuffer(int width, int height, ByteBuffer pixels, OutputStream dngOutput,
                                 int pixelStride, int rowStride, long offset)  throws IOException {
        if (width <= 0 || height <= 0) {
            throw new IllegalArgumentException("Image with invalid width, height: (" + width + "," +
                    height + ") passed to write");
        }
        long capacity = pixels.capacity();
        long totalSize = ((long) rowStride) * height + offset;
        if (capacity < totalSize) {
            throw new IllegalArgumentException("Image size " + capacity +
                    " is too small (must be larger than " + totalSize + ")");
        }
        int minRowStride = pixelStride * width;
        if (minRowStride > rowStride) {
            throw new IllegalArgumentException("Invalid image pixel stride, row byte width " +
                    minRowStride + " is too large, expecting " + rowStride);
        }
        pixels.clear(); // Reset mark and limit
        nativeWriteImage(dngOutput, width, height, pixels, rowStride, pixelStride, offset,
                pixels.isDirect());
        pixels.clear();
    }

    /**
     * Convert a single YUV pixel to RGB.
     */
    private static void yuvToRgb(byte[] yuvData, int outOffset, /*out*/byte[] rgbOut) {
        final int COLOR_MAX = 255;

        float y = yuvData[0] & 0xFF;  // Y channel
        float cb = yuvData[1] & 0xFF; // U channel
        float cr = yuvData[2] & 0xFF; // V channel

        // convert YUV -> RGB (from JFIF's "Conversion to and from RGB" section)
        float r = y + 1.402f * (cr - 128);
        float g = y - 0.34414f * (cb - 128) - 0.71414f * (cr - 128);
        float b = y + 1.772f * (cb - 128);

        // clamp to [0,255]
        rgbOut[outOffset] = (byte) Math.max(0, Math.min(COLOR_MAX, r));
        rgbOut[outOffset + 1] = (byte) Math.max(0, Math.min(COLOR_MAX, g));
        rgbOut[outOffset + 2] = (byte) Math.max(0, Math.min(COLOR_MAX, b));
    }

    /**
     * Convert a single {@link Color} pixel to RGB.
     */
    private static void colorToRgb(int color, int outOffset, /*out*/byte[] rgbOut) {
        rgbOut[outOffset] = (byte) Color.red(color);
        rgbOut[outOffset + 1] = (byte) Color.green(color);
        rgbOut[outOffset + 2] = (byte) Color.blue(color);
        // Discards Alpha
    }

    /**
     * Generate a direct RGB {@link ByteBuffer} from a YUV420_888 {@link Image}.
     */
    private static ByteBuffer convertToRGB(Image yuvImage) {
        // TODO: Optimize this with renderscript intrinsic.
        int width = yuvImage.getWidth();
        int height = yuvImage.getHeight();
        ByteBuffer buf = ByteBuffer.allocateDirect(BYTES_PER_RGB_PIX * width * height);

        Image.Plane yPlane = yuvImage.getPlanes()[0];
        Image.Plane uPlane = yuvImage.getPlanes()[1];
        Image.Plane vPlane = yuvImage.getPlanes()[2];

        ByteBuffer yBuf = yPlane.getBuffer();
        ByteBuffer uBuf = uPlane.getBuffer();
        ByteBuffer vBuf = vPlane.getBuffer();

        yBuf.rewind();
        uBuf.rewind();
        vBuf.rewind();

        int yRowStride = yPlane.getRowStride();
        int vRowStride = vPlane.getRowStride();
        int uRowStride = uPlane.getRowStride();

        int yPixStride = yPlane.getPixelStride();
        int vPixStride = vPlane.getPixelStride();
        int uPixStride = uPlane.getPixelStride();

        byte[] yuvPixel = { 0, 0, 0 };
        byte[] yFullRow = new byte[yPixStride * (width - 1) + 1];
        byte[] uFullRow = new byte[uPixStride * (width / 2 - 1) + 1];
        byte[] vFullRow = new byte[vPixStride * (width / 2 - 1) + 1];
        byte[] finalRow = new byte[BYTES_PER_RGB_PIX * width];
        for (int i = 0; i < height; i++) {
            int halfH = i / 2;
            yBuf.position(yRowStride * i);
            yBuf.get(yFullRow);
            uBuf.position(uRowStride * halfH);
            uBuf.get(uFullRow);
            vBuf.position(vRowStride * halfH);
            vBuf.get(vFullRow);
            for (int j = 0; j < width; j++) {
                int halfW = j / 2;
                yuvPixel[0] = yFullRow[yPixStride * j];
                yuvPixel[1] = uFullRow[uPixStride * halfW];
                yuvPixel[2] = vFullRow[vPixStride * halfW];
                yuvToRgb(yuvPixel, j * BYTES_PER_RGB_PIX, /*out*/finalRow);
            }
            buf.put(finalRow);
        }

        yBuf.rewind();
        uBuf.rewind();
        vBuf.rewind();
        buf.rewind();
        return buf;
    }

    /**
     * Generate a direct RGB {@link ByteBuffer} from a {@link Bitmap}.
     */
    private static ByteBuffer convertToRGB(Bitmap argbBitmap) {
        // TODO: Optimize this.
        int width = argbBitmap.getWidth();
        int height = argbBitmap.getHeight();
        ByteBuffer buf = ByteBuffer.allocateDirect(BYTES_PER_RGB_PIX * width * height);

        int[] pixelRow = new int[width];
        byte[] finalRow = new byte[BYTES_PER_RGB_PIX * width];
        for (int i = 0; i < height; i++) {
            argbBitmap.getPixels(pixelRow, /*offset*/0, /*stride*/width, /*x*/0, /*y*/i,
                    /*width*/width, /*height*/1);
            for (int j = 0; j < width; j++) {
                colorToRgb(pixelRow[j], j * BYTES_PER_RGB_PIX, /*out*/finalRow);
            }
            buf.put(finalRow);
        }

        buf.rewind();
        return buf;
    }

    /**
     * Convert coordinate to EXIF GPS tag format.
     */
    private static int[] toExifLatLong(double value) {
        // convert to the format dd/1 mm/1 ssss/100
        value = Math.abs(value);
        int degrees = (int) value;
        value = (value - degrees) * 60;
        int minutes = (int) value;
        value = (value - minutes) * 6000;
        int seconds = (int) value;
        return new int[] { degrees, 1, minutes, 1, seconds, 100 };
    }

    /**
     * This field is used by native code, do not access or modify.
     */
    private long mNativeContext;

    private static native void nativeClassInit();

    private synchronized native void nativeInit(CameraMetadataNative nativeCharacteristics,
                                                CameraMetadataNative nativeResult,
                                                String captureTime);

    private synchronized native void nativeDestroy();

    private synchronized native void nativeSetOrientation(int orientation);

    private synchronized native void nativeSetDescription(String description);

    private synchronized native void nativeSetGpsTags(int[] latTag, String latRef, int[] longTag,
                                                      String longRef, String dateTag,
                                                      int[] timeTag);

    private synchronized native void nativeSetThumbnail(ByteBuffer buffer, int width, int height);

    private synchronized native void nativeWriteImage(OutputStream out, int width, int height,
                                                      ByteBuffer rawBuffer, int rowStride,
                                                      int pixStride, long offset, boolean isDirect)
                                                      throws IOException;

    private synchronized native void nativeWriteInputStream(OutputStream out, InputStream rawStream,
                                                            int width, int height, long offset)
                                                            throws IOException;

    static {
        nativeClassInit();
    }
}