summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--res/layout/capture_module.xml4
-rw-r--r--res/layout/video_module.xml3
-rw-r--r--res/values/qcomarrays.xml10
-rw-r--r--res/values/qcomstrings.xml15
-rw-r--r--res/xml/camera_preferences.xml18
-rw-r--r--src/com/android/camera/CameraSettings.java3
-rw-r--r--src/com/android/camera/CaptureMenu.java9
-rw-r--r--src/com/android/camera/CaptureModule.java812
-rw-r--r--src/com/android/camera/MediaSaveService.java127
-rw-r--r--src/com/android/camera/PhotoUI.java15
-rw-r--r--src/com/android/camera/VideoMenu.java3
-rw-r--r--src/com/android/camera/VideoModule.java2
-rw-r--r--src/com/android/camera/VideoUI.java2
-rw-r--r--src/com/android/camera/exif/ExifTag.java20
-rw-r--r--src/com/android/camera/exif/JpegHeader.java3
-rw-r--r--src/com/android/camera/exif/OrderedDataOutputStream.java2
-rw-r--r--src/com/android/camera/mpo/MpoData.java184
-rw-r--r--src/com/android/camera/mpo/MpoIfdData.java126
-rw-r--r--src/com/android/camera/mpo/MpoImageData.java248
-rw-r--r--src/com/android/camera/mpo/MpoInterface.java143
-rw-r--r--src/com/android/camera/mpo/MpoOutputStream.java333
-rw-r--r--src/com/android/camera/mpo/MpoTag.java163
-rw-r--r--src/com/android/camera/ui/AutoFitSurfaceView.java76
-rw-r--r--src/com/android/camera/util/ClearSightNativeEngine.java351
24 files changed, 2528 insertions, 144 deletions
diff --git a/res/layout/capture_module.xml b/res/layout/capture_module.xml
index 02c32acab..a68af5e08 100644
--- a/res/layout/capture_module.xml
+++ b/res/layout/capture_module.xml
@@ -33,12 +33,12 @@
android:layout_height="match_parent"
android:layout_gravity="center_vertical|center_horizontal">
- <SurfaceView
+ <com.android.camera.ui.AutoFitSurfaceView
android:id="@+id/mdp_preview_content"
android:layout_width="match_parent"
android:layout_height="match_parent" />
- <SurfaceView
+ <com.android.camera.ui.AutoFitSurfaceView
android:id="@+id/mdp_preview_content2"
android:layout_width="300dp"
android:layout_height="300dp" />
diff --git a/res/layout/video_module.xml b/res/layout/video_module.xml
index c1063510b..20d7be1d2 100644
--- a/res/layout/video_module.xml
+++ b/res/layout/video_module.xml
@@ -42,8 +42,7 @@
android:id="@+id/preview_cover"
android:layout_width="match_parent"
android:layout_height="match_parent"
- android:background="@android:color/black"
- android:visibility="gone" />
+ android:background="@android:color/black" />
<View
android:id="@+id/flash_overlay"
android:layout_width="match_parent"
diff --git a/res/values/qcomarrays.xml b/res/values/qcomarrays.xml
index 40c8b8a77..d3218bdaf 100644
--- a/res/values/qcomarrays.xml
+++ b/res/values/qcomarrays.xml
@@ -873,5 +873,15 @@
<item>@string/pref_camera_mono_preview_value_on</item>
<item>@string/pref_camera_mono_preview_value_off</item>
</string-array>
+
+ <string-array name="pref_camera_clearsight_entries" translatable="true">
+ <item>@string/pref_camera_clearsight_entry_on</item>
+ <item>@string/pref_camera_clearsight_entry_off</item>
+ </string-array>
+
+ <string-array name="pref_camera_clearsight_entryvalues" translatable="false">
+ <item>@string/pref_camera_clearsight_value_on</item>
+ <item>@string/pref_camera_clearsight_value_off</item>
+ </string-array>
</resources>
diff --git a/res/values/qcomstrings.xml b/res/values/qcomstrings.xml
index 888000c36..ea90cf72a 100644
--- a/res/values/qcomstrings.xml
+++ b/res/values/qcomstrings.xml
@@ -277,7 +277,7 @@
<string name="pref_camera_cds_default" translatable="false">on</string>
<!-- Default video cds mode setting-->
- <string name="pref_camera_video_cds_default" translatable="false">on</string>
+ <string name="pref_camera_video_cds_default" translatable="false">off</string>
<!-- Settings menu, setting title text for tnr mode-->
<string name="pref_camera_tnr_title">TNR mode</string>
@@ -289,7 +289,7 @@
<string name="pref_camera_tnr_default" translatable="false">off</string>
<!-- Default video tnr mode setting-->
- <string name="pref_camera_video_tnr_default" translatable="false">off</string>
+ <string name="pref_camera_video_tnr_default" translatable="false">on</string>
<!-- Default face detection setting. -->
<string name="pref_camera_facedetection_default" translatable="false">off</string>
@@ -970,5 +970,16 @@
<string name="pref_camera_mono_preview_value_on">on</string>
<string name="pref_camera_mono_preview_value_off">off</string>
+
+ <string name="pref_camera_clearsight_title">ClearSight</string>
+ <string name="pref_camera_clearsight_default" translatable="false">off</string>
+ <string name="pref_camera_clearsight_entry_on">On</string>
+ <string name="pref_camera_clearsight_entry_off">Off</string>
+
+ <string name="pref_camera_clearsight_value_on" translatable="false">on</string>
+ <string name="pref_camera_clearsight_value_off" translatable="false">off</string>
+
+ <string name="clearsight_capture_success">ClearSight capture successful</string>
+ <string name="clearsight_capture_fail">ClearSight capture failed</string>
</resources>
diff --git a/res/xml/camera_preferences.xml b/res/xml/camera_preferences.xml
index 86eb36f71..5fafb855b 100644
--- a/res/xml/camera_preferences.xml
+++ b/res/xml/camera_preferences.xml
@@ -381,9 +381,17 @@
camera:entryValues="@array/pref_camera_dual_camera_entryvalues" />
<ListPreference
- camera:key="pref_camera_mono_preview_key"
- camera:defaultValue="@string/pref_camera_mono_preview_default"
- camera:title="@string/pref_camera_mono_preview_title"
- camera:entries="@array/pref_camera_mono_preview_entries"
- camera:entryValues="@array/pref_camera_mono_preview_entryvalues" />
+ camera:defaultValue="@string/pref_camera_mono_preview_default"
+ camera:entries="@array/pref_camera_mono_preview_entries"
+ camera:entryValues="@array/pref_camera_mono_preview_entryvalues"
+ camera:key="pref_camera_mono_preview_key"
+ camera:title="@string/pref_camera_mono_preview_title" />
+
+ <ListPreference
+ camera:defaultValue="@string/pref_camera_clearsight_default"
+ camera:entries="@array/pref_camera_clearsight_entries"
+ camera:entryValues="@array/pref_camera_clearsight_entryvalues"
+ camera:key="pref_camera_clearsight_key"
+ camera:title="@string/pref_camera_clearsight_title" />
+
</PreferenceGroup>
diff --git a/src/com/android/camera/CameraSettings.java b/src/com/android/camera/CameraSettings.java
index b0bc9c8d7..a12ce5de0 100644
--- a/src/com/android/camera/CameraSettings.java
+++ b/src/com/android/camera/CameraSettings.java
@@ -249,6 +249,7 @@ public class CameraSettings {
public static final String KEY_CAMERA2 = "pref_camera_camera2_key";
public static final String KEY_DUAL_CAMERA = "pref_camera_dual_camera_key";
public static final String KEY_MONO_PREVIEW = "pref_camera_mono_preview_key";
+ public static final String KEY_CLEARSIGHT = "pref_camera_clearsight_key";
public static final String KEY_REFOCUS_PROMPT = "refocus-prompt";
@@ -281,7 +282,7 @@ public class CameraSettings {
//video encoders
VIDEO_ENCODER_TABLE.put(MediaRecorder.VideoEncoder.H263, "h263");
VIDEO_ENCODER_TABLE.put(MediaRecorder.VideoEncoder.H264, "h264");
- VIDEO_ENCODER_TABLE.put(MediaRecorder.VideoEncoder.H265, "h265");
+ // VIDEO_ENCODER_TABLE.put(MediaRecorder.VideoEncoder.H265, "h265");
VIDEO_ENCODER_TABLE.put(MediaRecorder.VideoEncoder.MPEG_4_SP, "m4v");
//video qualities
diff --git a/src/com/android/camera/CaptureMenu.java b/src/com/android/camera/CaptureMenu.java
index 99f919a79..8b8f5c357 100644
--- a/src/com/android/camera/CaptureMenu.java
+++ b/src/com/android/camera/CaptureMenu.java
@@ -97,7 +97,8 @@ public class CaptureMenu extends MenuController
CameraSettings.KEY_CAMERA_SAVEPATH,
CameraSettings.KEY_WHITE_BALANCE,
CameraSettings.KEY_CAMERA2,
- CameraSettings.KEY_DUAL_CAMERA
+ CameraSettings.KEY_DUAL_CAMERA,
+ CameraSettings.KEY_CLEARSIGHT
};
//Todo: 2nd string to contain only developer settings
@@ -109,6 +110,7 @@ public class CaptureMenu extends MenuController
CameraSettings.KEY_WHITE_BALANCE,
CameraSettings.KEY_CAMERA2,
CameraSettings.KEY_DUAL_CAMERA,
+ CameraSettings.KEY_CLEARSIGHT,
CameraSettings.KEY_MONO_PREVIEW
};
@@ -398,6 +400,8 @@ public class CaptureMenu extends MenuController
if (!pref.getValue().equals("dual")) {
setPreference(CameraSettings.KEY_MONO_PREVIEW, "off");
mListMenu.setPreferenceEnabled(CameraSettings.KEY_MONO_PREVIEW, false);
+ setPreference(CameraSettings.KEY_CLEARSIGHT, "off");
+ mListMenu.setPreferenceEnabled(CameraSettings.KEY_CLEARSIGHT, false);
}
if (mListener != null) {
@@ -555,6 +559,9 @@ public class CaptureMenu extends MenuController
if (value.equals("on")) {
} else if (value.equals("off")) {
}
+ } else if (key.equals(CameraSettings.KEY_CLEARSIGHT)) {
+ // restart module to re-create sessions and callbacks
+ mActivity.onModuleSelected(ModuleSwitcher.CAPTURE_MODULE_INDEX);
}
}
diff --git a/src/com/android/camera/CaptureModule.java b/src/com/android/camera/CaptureModule.java
index 52f9327e6..382e691b1 100644
--- a/src/com/android/camera/CaptureModule.java
+++ b/src/com/android/camera/CaptureModule.java
@@ -19,8 +19,22 @@
package com.android.camera;
-import android.annotation.TargetApi;
-import android.app.Activity;
+import java.io.ByteArrayOutputStream;
+import java.nio.ByteBuffer;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.Semaphore;
+import java.util.concurrent.TimeUnit;
+
+import org.codeaurora.snapcam.R;
+
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
@@ -28,20 +42,25 @@ import android.content.res.Configuration;
import android.graphics.ImageFormat;
import android.graphics.Point;
import android.graphics.Rect;
+import android.graphics.YuvImage;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CameraMetadata;
+import android.hardware.camera2.CaptureFailure;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.CaptureResult;
import android.hardware.camera2.TotalCaptureResult;
+import android.hardware.camera2.params.InputConfiguration;
import android.hardware.camera2.params.MeteringRectangle;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.media.CameraProfile;
import android.media.Image;
+import android.media.Image.Plane;
import android.media.ImageReader;
+import android.media.ImageWriter;
import android.net.Uri;
import android.os.Handler;
import android.os.HandlerThread;
@@ -61,20 +80,7 @@ import com.android.camera.PhotoModule.NamedImages;
import com.android.camera.PhotoModule.NamedImages.NamedEntity;
import com.android.camera.ui.RotateTextToast;
import com.android.camera.util.CameraUtil;
-
-import org.codeaurora.snapcam.R;
-
-import java.nio.ByteBuffer;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.Semaphore;
-import java.util.concurrent.TimeUnit;
+import com.android.camera.util.ClearSightNativeEngine;
public class CaptureModule implements CameraModule, PhotoController,
MediaSaveService.Listener {
@@ -83,6 +89,8 @@ public class CaptureModule implements CameraModule, PhotoController,
public static final int MONO_MODE = 2;
private static final int OPEN_CAMERA = 0;
private static final int MAX_NUM_CAM = 3;
+ private static final long TIMESTAMP_THRESHOLD_NS = 10*1000000; // 10 ms
+
/**
* Conversion from screen rotation to JPEG orientation.
*/
@@ -113,6 +121,13 @@ public class CaptureModule implements CameraModule, PhotoController,
private static final String TAG = "SnapCam_CaptureModule";
private static int MODE = DUAL_MODE;
+ private static final int MSG_START_CAPTURE = 0;
+ private static final int MSG_NEW_IMG = 1;
+ private static final int MSG_NEW_RESULT = 2;
+ private static final int MSG_SAVE = 4;
+
+ private static final int NUM_IMAGES_TO_BURST = 4;
+
static {
ORIENTATIONS.append(Surface.ROTATION_0, 90);
ORIENTATIONS.append(Surface.ROTATION_90, 0);
@@ -130,6 +145,11 @@ public class CaptureModule implements CameraModule, PhotoController,
CaptureRequest.Key<Integer> BayerMonoLinkSessionIdKey =
new CaptureRequest.Key<>("org.codeaurora.qcamera3.dualcam_link_meta_data" +
".related_camera_id", Integer.class);
+
+ CaptureResult.Key<Byte> OTP_CALIB_BLOB =
+ new CaptureResult.Key<>("org.codeaurora.qcamera3.dualcam_calib_meta_data.dualcam_calib_meta_data_blob",
+ Byte.class);
+
private int mLastResultAFState = -1;
private Rect[] mCropRegion = new Rect[MAX_NUM_CAM];
private boolean mAutoFocusSupported;
@@ -165,16 +185,24 @@ public class CaptureModule implements CameraModule, PhotoController,
private HandlerThread mCameraThread;
private HandlerThread mImageAvailableThread;
private HandlerThread mCallbackThread;
+ private HandlerThread mImageProcessThread;
+ private HandlerThread mImageReprocessThread;
+
/**
* A {@link Handler} for running tasks in the background.
*/
private Handler mCameraHandler;
private Handler mImageAvailableHandler;
private Handler mCallbackHandler;
+ private ImageProcessHandler mImageProcessHandler;
+ private ImageReprocessHandler mImageReprocessHandler;
+
/**
* An {@link ImageReader} that handles still image capture.
*/
private ImageReader[] mImageReader = new ImageReader[MAX_NUM_CAM];
+ private ImageReader[] mReprocessImageReader = new ImageReader[MAX_NUM_CAM];
+ private ImageWriter[] mImageWriter = new ImageWriter[MAX_NUM_CAM];
private NamedImages mNamedImages;
private ContentResolver mContentResolver;
private MediaSaveService.OnMediaSavedListener mOnMediaSavedListener =
@@ -186,35 +214,472 @@ public class CaptureModule implements CameraModule, PhotoController,
}
}
};
- /**
- * This a callback object for the {@link ImageReader}. "onImageAvailable" will be called when a
- * still image is ready to be saved.
- */
- private final ImageReader.OnImageAvailableListener mOnImageAvailableListener
- = new ImageReader.OnImageAvailableListener() {
+
+ private class ReprocessableImage {
+ final Image mImage;
+ final TotalCaptureResult mCaptureResult;
+
+ ReprocessableImage(Image image, TotalCaptureResult result) {
+ mImage = image;
+ mCaptureResult = result;
+ }
+ }
+
+ private abstract class ImageAvailableListener implements ImageReader.OnImageAvailableListener {
+ int mCamId;
+
+ ImageAvailableListener(int cameraId) {
+ mCamId = cameraId;
+ }
+ }
+
+ private abstract class CameraCaptureCallback extends CameraCaptureSession.CaptureCallback {
+ int mCamId;
+
+ CameraCaptureCallback(int cameraId) {
+ mCamId = cameraId;
+ }
+ }
+
+ private class ImageProcessHandler extends Handler {
+ private ArrayDeque<ReprocessableImage> mBayerFrames = new ArrayDeque<ReprocessableImage>(
+ NUM_IMAGES_TO_BURST);
+ private ArrayDeque<ReprocessableImage> mMonoFrames = new ArrayDeque<ReprocessableImage>(
+ NUM_IMAGES_TO_BURST);
+ private ArrayDeque<TotalCaptureResult> mBayerCaptureResults = new ArrayDeque<TotalCaptureResult>(
+ NUM_IMAGES_TO_BURST);
+ private ArrayDeque<TotalCaptureResult> mMonoCaptureResults = new ArrayDeque<TotalCaptureResult>(
+ NUM_IMAGES_TO_BURST);
+ private ArrayDeque<Image> mBayerImages = new ArrayDeque<Image>(
+ NUM_IMAGES_TO_BURST);
+ private ArrayDeque<Image> mMonoImages = new ArrayDeque<Image>(
+ NUM_IMAGES_TO_BURST);
+ private int[] mNumImagesToProcess = new int[MAX_NUM_CAM];
+
+ public ImageProcessHandler(Looper looper) {
+ super(looper);
+ }
@Override
- public void onImageAvailable(ImageReader reader) {
- Log.d(TAG, "image available");
+ public void handleMessage(Message msg) {
+ switch (msg.what) {
+ case MSG_START_CAPTURE:
+ mNumImagesToProcess[msg.arg1] = msg.arg2;
+ break;
+ case MSG_NEW_IMG:
+ processNewImg(msg);
+ break;
+ case MSG_NEW_RESULT:
+ processNewCaptureResult(msg);
+ break;
+ case MSG_SAVE:
+ processSaveImage(msg);
+ break;
+ }
+ }
+
+ private void processNewImg(Message msg) {
+ Image image = (Image) msg.obj;
+
+ ArrayDeque<Image> imageQueue;
+ ArrayDeque<TotalCaptureResult> resultQueue;
+ ArrayDeque<ReprocessableImage> reprocQueue;
+ // push image onto queue
+ if (msg.arg1 == BAYER_ID) {
+ imageQueue = mBayerImages;
+ resultQueue = mBayerCaptureResults;
+ reprocQueue = mBayerFrames;
+ } else {
+ imageQueue = mMonoImages;
+ resultQueue = mMonoCaptureResults;
+ reprocQueue = mMonoFrames;
+ }
+
+ imageQueue.add(image);
+
+ Log.d(TAG, "processNewImg - cam: " + msg.arg1 + " num imgs: "
+ + imageQueue.size() + " num results: " + resultQueue.size());
+ if (imageQueue.isEmpty() == resultQueue.isEmpty()) {
+ Image headImage = imageQueue.poll();
+ TotalCaptureResult headResult = resultQueue.poll();
+ reprocQueue.add(new ReprocessableImage(headImage, headResult));
+ checkForValidFramePair();
+ mNumImagesToProcess[msg.arg1]--;
+ if (mNumImagesToProcess[BAYER_ID] == 0
+ && mNumImagesToProcess[MONO_ID] == 0) {
+ ClearSightNativeEngine.getInstance().reset();
+ processReprocess();
+ }
+ }
+ }
+
+ private void processNewCaptureResult(Message msg) {
+ if (msg.arg2 == 1) {
+ // capture failed
+ mNumImagesToProcess[msg.arg1]--;
+ } else {
+ TotalCaptureResult result = (TotalCaptureResult) msg.obj;
+ ArrayDeque<Image> imageQueue;
+ ArrayDeque<TotalCaptureResult> resultQueue;
+ ArrayDeque<ReprocessableImage> reprocQueue;
+ // push image onto queue
+ if (msg.arg1 == BAYER_ID) {
+ imageQueue = mBayerImages;
+ resultQueue = mBayerCaptureResults;
+ reprocQueue = mBayerFrames;
+ } else {
+ imageQueue = mMonoImages;
+ resultQueue = mMonoCaptureResults;
+ reprocQueue = mMonoFrames;
+ }
+
+ resultQueue.add(result);
+
+ Log.d(TAG, "processNewCaptureResult - cam: " + msg.arg1
+ + " num imgs: " + imageQueue.size() + " num results: "
+ + resultQueue.size());
+ if (imageQueue.isEmpty() == resultQueue.isEmpty()) {
+ Image headImage = imageQueue.poll();
+ TotalCaptureResult headResult = resultQueue.poll();
+ reprocQueue.add(new ReprocessableImage(headImage,
+ headResult));
+ checkForValidFramePair();
+ mNumImagesToProcess[msg.arg1]--;
+ if (mNumImagesToProcess[BAYER_ID] == 0
+ && mNumImagesToProcess[MONO_ID] == 0) {
+ ClearSightNativeEngine.getInstance().reset();
+ processReprocess();
+ }
+ }
+ }
+ }
+
+ private void checkForValidFramePair() {
+ // if we have images from both
+ // as we just added an image onto one of the queues
+ // this condition is only true when both are not empty
+ Log.d(TAG,
+ "checkForValidFramePair - num bayer frames: "
+ + mBayerFrames.size() + " num mono frames: "
+ + mMonoFrames.size());
+
+ if (mBayerFrames.isEmpty() == mMonoFrames.isEmpty()) {
+ // peek oldest pair of images
+ ReprocessableImage bayer = mBayerFrames.peek();
+ ReprocessableImage mono = mMonoFrames.peek();
+
+ Log.d(TAG,
+ "checkForValidFramePair - bayer ts: "
+ + bayer.mImage.getTimestamp() + " mono ts: "
+ + mono.mImage.getTimestamp());
+ Log.d(TAG,
+ "checkForValidFramePair - difference: "
+ + Math.abs(bayer.mImage.getTimestamp()
+ - mono.mImage.getTimestamp()));
+ // if timestamps are within threshold, keep frames
+ if (Math.abs(bayer.mImage.getTimestamp()
+ - mono.mImage.getTimestamp()) > TIMESTAMP_THRESHOLD_NS) {
+ Log.d(TAG, "checkForValidFramePair - toss pair");
+ // no match, toss
+ bayer = mBayerFrames.poll();
+ mono = mMonoFrames.poll();
+ bayer.mImage.close();
+ mono.mImage.close();
+ }
+ }
+ }
+
+ private void releaseBayerFrames() {
+ for (ReprocessableImage reprocImg : mBayerFrames) {
+ reprocImg.mImage.close();
+ }
+
+ mBayerFrames.clear();
+ }
+
+ private void releaseMonoFrames() {
+ for (ReprocessableImage reprocImg : mMonoFrames) {
+ reprocImg.mImage.close();
+ }
+
+ mMonoFrames.clear();
+ }
+
+ private void processReprocess() {
+ if (mBayerFrames.size() != mMonoFrames.size()
+ || mBayerFrames.isEmpty()) {
+ Log.d(TAG, "processReprocess - frame size mismatch or empty");
+ releaseBayerFrames();
+ releaseMonoFrames();
+ mActivity.runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ RotateTextToast.makeText(mActivity, R.string.clearsight_capture_fail,
+ Toast.LENGTH_SHORT).show();
+ unlockFocus(BAYER_ID);
+ unlockFocus(MONO_ID);
+ }
+ });
+ return;
+ } else {
+ sendReprocessRequests(BAYER_ID);
+ sendReprocessRequests(MONO_ID);
+ }
+ }
+
+ private void sendReprocessRequests(final int camId) {
+ try {
+ ArrayDeque<ReprocessableImage> frameQueue;
+ if (camId == BAYER_ID) {
+ frameQueue = mBayerFrames;
+ } else {
+ frameQueue = mMonoFrames;
+ }
+ Log.d(TAG, "sendReprocessRequests - start cam: " + camId
+ + " num frames: " + frameQueue.size());
+
+ ArrayList<CaptureRequest> reprocRequests = new ArrayList<CaptureRequest>(
+ frameQueue.size());
+ while (!frameQueue.isEmpty()) {
+ ReprocessableImage reprocImg = frameQueue.poll();
+
+ CaptureRequest.Builder reprocRequest = mCameraDevice[camId]
+ .createReprocessCaptureRequest(reprocImg.mCaptureResult);
+ reprocRequest.addTarget(mReprocessImageReader[camId]
+ .getSurface());
+ reprocRequests.add(reprocRequest.build());
+
+ mImageWriter[camId].queueInputImage(reprocImg.mImage);
+ }
+
+ mImageReprocessHandler.obtainMessage(MSG_START_CAPTURE, camId,
+ reprocRequests.size()).sendToTarget();
+ mCaptureSession[camId].captureBurst(reprocRequests,
+ new CameraCaptureCallback(camId) {
+ @Override
+ public void onCaptureCompleted(
+ CameraCaptureSession session,
+ CaptureRequest request,
+ TotalCaptureResult result) {
+ super.onCaptureCompleted(session, request, result);
+ Log.d(TAG, "reprocess - onCaptureCompleted: "
+ + mCamId);
+ // TODO: parse OTP Calib data to be used in final CS
+ // result.get(OTP_CALIB_BLOB);
+ }
+
+ @Override
+ public void onCaptureFailed(
+ CameraCaptureSession session,
+ CaptureRequest request,
+ CaptureFailure failure) {
+ super.onCaptureFailed(session, request, failure);
+ Log.d(TAG, "reprocess - onCaptureFailed: "
+ + mCamId);
+ mImageReprocessHandler.obtainMessage(
+ MSG_NEW_RESULT, mCamId, 1)
+ .sendToTarget();
+ }
+ }, mCameraHandler);
+ } catch (CameraAccessException e) {
+ e.printStackTrace();
+ }
+ }
+
+ private void processSaveImage(Message msg) {
+ Image image = (Image) msg.obj;
+ if (image.getFormat() == ImageFormat.JPEG) {
+ mCaptureStartTime = System.currentTimeMillis();
+ mNamedImages.nameNewImage(mCaptureStartTime);
+ NamedEntity name = mNamedImages.getNextNameEntity();
+ String title = (name == null) ? null : name.title;
+ long date = (name == null) ? -1 : name.date;
+
+ ByteBuffer buffer = image.getPlanes()[0].getBuffer();
+ byte[] bytes = new byte[buffer.remaining()];
+ buffer.get(bytes);
+
+ mActivity.getMediaSaveService().addImage(bytes, title, date,
+ null, image.getWidth(), image.getHeight(), 0, null,
+ mOnMediaSavedListener, mContentResolver, "jpeg");
+ } else {
+ Log.w(TAG, "processSaveImage - image format incorrect: " + image.getFormat());
+ }
+ image.close();
+ }
+ };
+
+ private class ImageReprocessHandler extends Handler {
+ private int[] mNumImagesToProcess = new int[MAX_NUM_CAM];
+
+ public ImageReprocessHandler(Looper looper) {
+ super(looper);
+ }
+
+ @Override
+ public void handleMessage(Message msg) {
+ switch (msg.what) {
+ case MSG_START_CAPTURE:
+ mNumImagesToProcess[msg.arg1] = msg.arg2;
+ break;
+ case MSG_NEW_IMG:
+ processNewImg(msg);
+ break;
+ case MSG_NEW_RESULT:
+ processNewCaptureResult(msg);
+ break;
+ }
+ }
+
+ private void processNewImg(Message msg) {
+ Image image = (Image) msg.obj;
+ boolean isBayer = (msg.arg1 == BAYER_ID);
+
+ Log.d(TAG, "reprocess - processNewImg");
+ if (!ClearSightNativeEngine.getInstance()
+ .hasReferenceImage(isBayer)) {
+ // reference not yet set
+ ClearSightNativeEngine.getInstance().setReferenceImage(isBayer,
+ image);
+ } else {
+ // if ref images set, register this image
+ ClearSightNativeEngine.getInstance().registerImage(isBayer,
+ image);
+ }
+
+ mNumImagesToProcess[msg.arg1]--;
+
+ Log.d(TAG, "reprocess - processNewImg, cam: " + msg.arg1
+ + " count: " + mNumImagesToProcess[msg.arg1]);
+
+ if (mNumImagesToProcess[BAYER_ID] == 0
+ && mNumImagesToProcess[MONO_ID] == 0) {
+ processClearSight();
+ }
+ }
+
+ private void processNewCaptureResult(Message msg) {
+ if (msg.arg2 == 1) {
+ // capture failed
+ mNumImagesToProcess[msg.arg1]--;
+ }
+
+ Log.d(TAG, "reprocess - processNewCaptureResult, cam: " + msg.arg1
+ + " count: " + mNumImagesToProcess[msg.arg1]);
+
+ if (mNumImagesToProcess[BAYER_ID] == 0
+ && mNumImagesToProcess[MONO_ID] == 0) {
+ processClearSight();
+ }
+ }
+
+ private void processClearSight() {
+ Log.d(TAG, "reprocess - processClearSight, bayercount: "
+ + mNumImagesToProcess[BAYER_ID] + " mono count: "
+ + mNumImagesToProcess[MONO_ID]);
+
mCaptureStartTime = System.currentTimeMillis();
mNamedImages.nameNewImage(mCaptureStartTime);
NamedEntity name = mNamedImages.getNextNameEntity();
String title = (name == null) ? null : name.title;
long date = (name == null) ? -1 : name.date;
- Image mImage = reader.acquireNextImage();
- ByteBuffer buffer = mImage.getPlanes()[0].getBuffer();
- //Todo: dont create new buffer and use the one from ImageReader
- byte[] bytes = new byte[buffer.remaining()];
- buffer.get(bytes);
+ ClearSightNativeEngine.ClearsightImage csImage = ClearSightNativeEngine
+ .getInstance().processImage();
+ if (csImage != null) {
+ Log.d(TAG, "reprocess - processClearSight success");
+
+ mActivity.getMediaSaveService().addMpoImage(
+ csImage,
+ createYuvImage(ClearSightNativeEngine.getInstance()
+ .getReferenceImage(true)),
+ createYuvImage(ClearSightNativeEngine.getInstance()
+ .getReferenceImage(false)), null, null, title,
+ date, null, 0, mOnMediaSavedListener, mContentResolver,
+ "jpeg");
- mActivity.getMediaSaveService().addImage(
- bytes, title, date, null, reader.getWidth(), reader.getHeight(),
- 0, null, mOnMediaSavedListener, mContentResolver, "jpeg");
- mImage.close();
+ mActivity.runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ RotateTextToast.makeText(mActivity, R.string.clearsight_capture_success,
+ Toast.LENGTH_SHORT).show();
+ }
+ });
+ } else {
+ Log.d(TAG, "reprocess - processClearSight fail");
+ Image bayerRef = ClearSightNativeEngine.getInstance()
+ .getReferenceImage(true);
+ Image monoRef = ClearSightNativeEngine.getInstance()
+ .getReferenceImage(false);
+ if (bayerRef != null && monoRef != null) {
+ Log.d(TAG, "reprocess - saving with bayer + mono mpo");
+ mActivity.getMediaSaveService().addMpoImage(null,
+ createYuvImage(bayerRef), createYuvImage(monoRef),
+ null, null, title, date, null, 0,
+ mOnMediaSavedListener, mContentResolver, "jpeg");
+ } else {
+ Log.d(TAG, "reprocess - bayer + mono images not available");
+ }
}
+ unlockFocus(BAYER_ID);
+ unlockFocus(MONO_ID);
+ ClearSightNativeEngine.getInstance().reset();
+ }
};
+
+ private void saveDebugImage(byte[] data, int width, int height,
+ boolean isReproc) {
+ mCaptureStartTime = System.currentTimeMillis();
+ mNamedImages.nameNewImage(mCaptureStartTime);
+ NamedEntity name = mNamedImages.getNextNameEntity();
+ String title = (name == null) ? null : name.title;
+ long date = (name == null) ? -1 : name.date;
+
+ if (isReproc) {
+ title += "_reproc";
+ }
+
+ mActivity.getMediaSaveService().addImage(data, title, date, null,
+ width, height, 0, null, mOnMediaSavedListener,
+ mContentResolver, "jpeg");
+ }
+
+ private void saveDebugImage(YuvImage image, boolean isReproc) {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ image.compressToJpeg(
+ new Rect(0, 0, image.getWidth(), image.getHeight()), 100, baos);
+
+ saveDebugImage(baos.toByteArray(), image.getWidth(), image.getHeight(),
+ isReproc);
+ }
+
+ private void saveDebugImage(Image image, boolean isReproc) {
+ saveDebugImage(createYuvImage(image), isReproc);
+ }
+
+ private YuvImage createYuvImage(Image image) {
+ if (image == null) {
+ Log.d(TAG, "createYuvImage - invalid param");
+ return null;
+ }
+ Plane[] planes = image.getPlanes();
+ ByteBuffer yBuffer = planes[0].getBuffer();
+ ByteBuffer vuBuffer = planes[2].getBuffer();
+ int sizeY = yBuffer.capacity();
+ int sizeVU = vuBuffer.capacity();
+ byte[] data = new byte[sizeY + sizeVU];
+ yBuffer.rewind();
+ yBuffer.get(data, 0, sizeY);
+ vuBuffer.rewind();
+ vuBuffer.get(data, sizeY, sizeVU);
+ int[] strides = new int[] { planes[0].getRowStride(),
+ planes[2].getRowStride() };
+
+ return new YuvImage(data, ImageFormat.NV21, image.getWidth(),
+ image.getHeight(), strides);
+ }
+
/**
* {@link CaptureRequest.Builder} for the camera preview
*/
@@ -417,6 +882,7 @@ public class CaptureModule implements CameraModule, PhotoController,
switch (value) {
case "dual":
mode = DUAL_MODE;
+ ClearSightNativeEngine.createInstance();
break;
case "bayer":
mode = BAYER_MODE;
@@ -518,40 +984,62 @@ public class CaptureModule implements CameraModule, PhotoController,
mPreviewRequestBuilder[id].setTag(id);
mPreviewRequestBuilder[id].addTarget(surface);
- list.add(surface);
- list.add(mImageReader[id].getSurface());
- // Here, we create a CameraCaptureSession for camera preview.
- mCameraDevice[id].createCaptureSession(list,
+ CameraCaptureSession.StateCallback captureSessionCallback =
new CameraCaptureSession.StateCallback() {
- @Override
- public void onConfigured(CameraCaptureSession cameraCaptureSession) {
- // The camera is already closed
- if (mPaused || null == mCameraDevice[id]) {
- return;
- }
- // When the session is ready, we start displaying the preview.
- mCaptureSession[id] = cameraCaptureSession;
- initializePreviewConfiguration(id);
- try {
- if (MODE == DUAL_MODE) {
- linkBayerMono(id);
- mIsLinked = true;
- }
- // Finally, we start displaying the camera preview.
- mCaptureSession[id].setRepeatingRequest(mPreviewRequestBuilder[id]
- .build(), mCaptureCallback, mCameraHandler);
- } catch (CameraAccessException e) {
- e.printStackTrace();
- }
+ @Override
+ public void onConfigured(CameraCaptureSession cameraCaptureSession) {
+ // The camera is already closed
+ if (mPaused || null == mCameraDevice[id]) {
+ return;
+ }
+ // When the session is ready, we start displaying the preview.
+ mCaptureSession[id] = cameraCaptureSession;
+ initializePreviewConfiguration(id);
+ try {
+ if (MODE == DUAL_MODE) {
+ linkBayerMono(id);
+ mIsLinked = true;
}
+ // Finally, we start displaying the camera preview.
+ mCaptureSession[id].setRepeatingRequest(mPreviewRequestBuilder[id]
+ .build(), mCaptureCallback, mCameraHandler);
- @Override
- public void onConfigureFailed(
- CameraCaptureSession cameraCaptureSession) {
+ // For Clearsight
+ if(mCaptureSession[id].isReprocessable()) {
+ mImageWriter[id] = ImageWriter.newInstance(cameraCaptureSession.getInputSurface(), NUM_IMAGES_TO_BURST);
}
- }, null
- );
+ } catch (CameraAccessException e) {
+ e.printStackTrace();
+ }
+ }
+
+ @Override
+ public void onConfigureFailed(CameraCaptureSession cameraCaptureSession) {
+ Log.d(TAG, "cameracapturesession - onConfigureFailed");
+ }
+
+ @Override
+ public void onClosed(CameraCaptureSession session) {
+ Log.d(TAG, "cameracapturesession - onClosed");
+ }
+ };
+
+ list.add(surface);
+ list.add(mImageReader[id].getSurface());
+
+ ListPreference pref = mPreferenceGroup.findPreference(CameraSettings.KEY_CLEARSIGHT);
+ if(pref.getValue().equals(mActivity.getString(R.string.pref_camera_clearsight_value_on))) {
+ list.add(mReprocessImageReader[id].getSurface());
+ // Here, we create a CameraCaptureSession for camera preview.
+ mCameraDevice[id].createReprocessableCaptureSession(
+ new InputConfiguration(mImageReader[id].getWidth(),
+ mImageReader[id].getHeight(), mImageReader[id].getImageFormat()),
+ list, captureSessionCallback, null);
+ } else {
+ // Here, we create a CameraCaptureSession for camera preview.
+ mCameraDevice[id].createCaptureSession(list, captureSessionCallback, null);
+ }
} catch (CameraAccessException e) {
}
}
@@ -687,40 +1175,98 @@ public class CaptureModule implements CameraModule, PhotoController,
if (null == mActivity || null == mCameraDevice[id]) {
return;
}
- CaptureRequest.Builder captureBuilder =
- mCameraDevice[id].createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
+
+ ListPreference pref = mPreferenceGroup.findPreference(CameraSettings.KEY_CLEARSIGHT);
+ final boolean csEnabled = pref.getValue().equals(
+ mActivity.getString(R.string.pref_camera_clearsight_value_on));
+ CaptureRequest.Builder captureBuilder;
+ CameraCaptureSession.CaptureCallback captureCallback;
+
+ if(csEnabled) {
+ captureBuilder = mCameraDevice[id].createCaptureRequest(CameraDevice.TEMPLATE_ZERO_SHUTTER_LAG);
+
+ // Orientation
+ // int rotation = mActivity.getWindowManager().getDefaultDisplay().getRotation();
+ // captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, ORIENTATIONS.get(rotation));
+
+ captureCallback = new CameraCaptureSession.CaptureCallback() {
+
+ @Override
+ public void onCaptureCompleted(CameraCaptureSession session,
+ CaptureRequest request,
+ TotalCaptureResult result) {
+ Log.d(TAG, "captureStillPicture onCaptureCompleted: " + id);
+ result.dumpToLog();
+ mImageProcessHandler.obtainMessage(MSG_NEW_RESULT,
+ id, 0, result).sendToTarget();
+ }
+
+ @Override
+ public void onCaptureFailed(CameraCaptureSession session,
+ CaptureRequest request,
+ CaptureFailure result) {
+ Log.d(TAG, "captureStillPicture onCaptureFailed: " + id);
+ mImageProcessHandler.obtainMessage(MSG_NEW_RESULT,
+ id, 1, result).sendToTarget();
+ }
+
+ @Override
+ public void onCaptureSequenceCompleted(CameraCaptureSession session, int
+ sequenceId, long frameNumber) {
+ Log.d(TAG, "captureStillPicture onCaptureSequenceCompleted: " + id);
+ }
+ };
+ } else {
+ // No Clearsight
+ captureBuilder = mCameraDevice[id].createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
+
+ // Orientation
+ int rotation = mActivity.getWindowManager().getDefaultDisplay().getRotation();
+ captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, ORIENTATIONS.get(rotation));
+ captureCallback = new CameraCaptureSession.CaptureCallback() {
+
+ @Override
+ public void onCaptureCompleted(CameraCaptureSession session,
+ CaptureRequest request,
+ TotalCaptureResult result) {
+ Log.d(TAG, "captureStillPicture onCaptureCompleted: " + id);
+ }
+
+ @Override
+ public void onCaptureFailed(CameraCaptureSession session,
+ CaptureRequest request,
+ CaptureFailure result) {
+ Log.d(TAG, "captureStillPicture onCaptureFailed: " + id);
+ }
+
+ @Override
+ public void onCaptureSequenceCompleted(CameraCaptureSession session, int
+ sequenceId, long frameNumber) {
+ Log.d(TAG, "captureStillPicture onCaptureSequenceCompleted: " + id);
+ unlockFocus(id);
+ }
+ };
+ }
captureBuilder.set(CaptureRequest.CONTROL_MODE, CaptureRequest.CONTROL_MODE_AUTO);
captureBuilder.addTarget(getPreviewSurface(id));
captureBuilder.addTarget(mImageReader[id].getSurface());
captureBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_AUTO);
- captureBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER, CaptureRequest
- .CONTROL_AF_TRIGGER_IDLE);
+ captureBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER, CaptureRequest.CONTROL_AF_TRIGGER_IDLE);
applyCaptureSettings(captureBuilder, id);
- // Orientation
- int rotation = mActivity.getWindowManager().getDefaultDisplay().getRotation();
- captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, ORIENTATIONS.get(rotation));
-
- CameraCaptureSession.CaptureCallback CaptureCallback
- = new CameraCaptureSession.CaptureCallback() {
-
- @Override
- public void onCaptureCompleted(CameraCaptureSession session,
- CaptureRequest request,
- TotalCaptureResult result) {
- Log.d(TAG, "captureStillPicture onCaptureCompleted");
- }
+ mCaptureSession[id].stopRepeating();
- @Override
- public void onCaptureSequenceCompleted(CameraCaptureSession session, int
- sequenceId, long frameNumber) {
- Log.d(TAG, "captureStillPicture onCaptureSequenceCompleted");
- unlockFocus(id);
+ if(csEnabled) {
+ List<CaptureRequest> burstList = new ArrayList<CaptureRequest>();
+ for (int i = 0; i < NUM_IMAGES_TO_BURST; i++) {
+ burstList.add(captureBuilder.build());
}
- };
- mCaptureSession[id].stopRepeating();
- mCaptureSession[id].capture(captureBuilder.build(), CaptureCallback, mCallbackHandler);
+ mImageProcessHandler.obtainMessage(MSG_START_CAPTURE, id, burstList.size()).sendToTarget();
+ mCaptureSession[id].captureBurst(burstList, captureCallback, mCallbackHandler);
+ } else {
+ mCaptureSession[id].capture(captureBuilder.build(), captureCallback, mCallbackHandler);
+ }
} catch (CameraAccessException e) {
Log.d(TAG, "Capture still picture has failed");
e.printStackTrace();
@@ -766,7 +1312,7 @@ public class CaptureModule implements CameraModule, PhotoController,
for (int i = 0; i < cameraIdList.length; i++) {
String cameraId = cameraIdList[i];
CameraCharacteristics characteristics
- = manager.getCameraCharacteristics(cameraId);
+ = manager.getCameraCharacteristics(cameraId);
mCharacteristics[i] = characteristics;
mCharacteristicsIndex.add(i);
StreamConfigurationMap map = characteristics.get(
@@ -776,16 +1322,54 @@ public class CaptureModule implements CameraModule, PhotoController,
}
Boolean available = characteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE);
Log.d(TAG, "flash : " + (available == null ? false : available));
- // For still image captures, we use the largest available size.
- Size largest = Collections.max(
- Arrays.asList(map.getOutputSizes(ImageFormat.JPEG)),
- new CompareSizesByArea());
-
- mImageReader[i] = ImageReader.newInstance(largest.getWidth(), largest.getHeight(),
- ImageFormat.JPEG, 3);
- mImageReader[i].setOnImageAvailableListener(
- mOnImageAvailableListener, mImageAvailableHandler);
mCameraId[i] = cameraId;
+
+ ListPreference pref = mPreferenceGroup.findPreference(CameraSettings.KEY_CLEARSIGHT);
+ if(pref.getValue().equals(mActivity.getString(R.string.pref_camera_clearsight_value_on))) {
+ // For still image captures, we use the largest available size.
+ Size largest = Collections.max(
+ Arrays.asList(map.getOutputSizes(ImageFormat.YUV_420_888)),
+ new CompareSizesByArea());
+
+ mImageReader[i] = ImageReader.newInstance(largest.getWidth(), largest.getHeight(),
+ ImageFormat.YUV_420_888, NUM_IMAGES_TO_BURST);
+ mImageReader[i].setOnImageAvailableListener(new ImageAvailableListener(i) {
+ @Override
+ public void onImageAvailable(ImageReader reader) {
+ Log.d(TAG, "image available for cam: " + mCamId);
+ mImageProcessHandler.obtainMessage(
+ MSG_NEW_IMG, mCamId, 0, reader.acquireNextImage()).sendToTarget();
+ }
+ }, mImageAvailableHandler);
+
+ mReprocessImageReader[i] = ImageReader.newInstance(largest.getWidth(), largest.getHeight(),
+ ImageFormat.YUV_420_888, NUM_IMAGES_TO_BURST);
+ mReprocessImageReader[i].setOnImageAvailableListener(new ImageAvailableListener(i) {
+ @Override
+ public void onImageAvailable(ImageReader reader) {
+ Log.d(TAG, "reprocessed image available for cam: " + mCamId);
+ mImageReprocessHandler.obtainMessage(
+ MSG_NEW_IMG, mCamId, 0, reader.acquireNextImage()).sendToTarget();
+ }
+ }, mImageAvailableHandler);
+ } else {
+ // No Clearsight
+ // For still image captures, we use the largest available size.
+ Size largest = Collections.max(
+ Arrays.asList(map.getOutputSizes(ImageFormat.JPEG)),
+ new CompareSizesByArea());
+
+ mImageReader[i] = ImageReader.newInstance(largest.getWidth(), largest.getHeight(),
+ ImageFormat.JPEG, 3);
+ mImageReader[i].setOnImageAvailableListener(new ImageAvailableListener(i) {
+ @Override
+ public void onImageAvailable(ImageReader reader) {
+ Log.d(TAG, "image available for cam: " + mCamId);
+ mImageProcessHandler.obtainMessage(
+ MSG_SAVE, mCamId, 0, reader.acquireNextImage()).sendToTarget();
+ }
+ }, mImageAvailableHandler);
+ }
}
mAutoFocusSupported = CameraUtil.isAutoFocusSupported(mCharacteristics,
mCharacteristicsIndex);
@@ -851,6 +1435,14 @@ public class CaptureModule implements CameraModule, PhotoController,
mImageReader[i].close();
mImageReader[i] = null;
}
+ if (null != mReprocessImageReader[i]) {
+ mReprocessImageReader[i].close();
+ mReprocessImageReader[i] = null;
+ }
+ if (null != mImageWriter[i]) {
+ mImageWriter[i].close();
+ mImageWriter[i] = null;
+ }
}
for (int i = 0; i < MAX_NUM_CAM; i++) {
if (null != mCameraDevice[i]) {
@@ -883,10 +1475,16 @@ public class CaptureModule implements CameraModule, PhotoController,
mImageAvailableThread.start();
mCallbackThread = new HandlerThread("CameraCallback");
mCallbackThread.start();
+ mImageProcessThread = new HandlerThread("CameraImageProcess");
+ mImageProcessThread.start();
+ mImageReprocessThread = new HandlerThread("CameraImageReprocess");
+ mImageReprocessThread.start();
mCameraHandler = new MyCameraHandler(mCameraThread.getLooper());
mImageAvailableHandler = new Handler(mImageAvailableThread.getLooper());
mCallbackHandler = new Handler(mCallbackThread.getLooper());
+ mImageProcessHandler = new ImageProcessHandler(mImageProcessThread.getLooper());
+ mImageReprocessHandler = new ImageReprocessHandler(mImageReprocessThread.getLooper());
}
/**
@@ -896,6 +1494,8 @@ public class CaptureModule implements CameraModule, PhotoController,
mCameraThread.quitSafely();
mImageAvailableThread.quitSafely();
mCallbackThread.quitSafely();
+ mImageProcessThread.quitSafely();
+ mImageReprocessThread.quitSafely();
try {
mCameraThread.join();
mCameraThread = null;
@@ -917,6 +1517,20 @@ public class CaptureModule implements CameraModule, PhotoController,
} catch (InterruptedException e) {
e.printStackTrace();
}
+ try {
+ mImageProcessThread.join();
+ mImageProcessThread = null;
+ mImageProcessHandler = null;
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ try {
+ mImageReprocessThread.join();
+ mImageReprocessThread = null;
+ mImageReprocessHandler = null;
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
}
private void openCamera(int id) {
@@ -955,8 +1569,8 @@ public class CaptureModule implements CameraModule, PhotoController,
Log.d(TAG, "onPause");
mUI.showPreviewCover();
if (mLocationManager != null) mLocationManager.recordLocation(false);
- stopBackgroundThread();
closeCamera();
+ stopBackgroundThread();
mUI.onPause();
}
@@ -969,9 +1583,9 @@ public class CaptureModule implements CameraModule, PhotoController,
public void onResumeAfterSuper() {
Log.d(TAG, "onResume " + MODE);
mCharacteristicsIndex = new ArrayList<>();
+ startBackgroundThread();
setUpCameraOutputs();
readInitialValues();
- startBackgroundThread();
Message msg = Message.obtain();
msg.what = OPEN_CAMERA;
switch (MODE) {
diff --git a/src/com/android/camera/MediaSaveService.java b/src/com/android/camera/MediaSaveService.java
index 46abe0560..8570b16fd 100644
--- a/src/com/android/camera/MediaSaveService.java
+++ b/src/com/android/camera/MediaSaveService.java
@@ -16,11 +16,18 @@
package com.android.camera;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.nio.ByteOrder;
+
import android.app.Service;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.BitmapFactory;
+import android.graphics.Rect;
+import android.graphics.YuvImage;
+import android.hardware.camera2.TotalCaptureResult;
import android.location.Location;
import android.net.Uri;
import android.os.AsyncTask;
@@ -32,6 +39,10 @@ import com.android.camera.PhotoModule;
import com.android.camera.exif.ExifInterface;
import java.io.File;
+import com.android.camera.mpo.MpoData;
+import com.android.camera.mpo.MpoImageData;
+import com.android.camera.mpo.MpoInterface;
+import com.android.camera.util.ClearSightNativeEngine.ClearsightImage;
/*
* Service for saving images in the background thread.
@@ -87,6 +98,31 @@ public class MediaSaveService extends Service {
return (mMemoryUse >= SAVE_TASK_MEMORY_LIMIT);
}
+ public void addMpoImage(final ClearsightImage csImage,
+ final YuvImage bayerImg, final YuvImage monoImg,
+ TotalCaptureResult bayerResult, TotalCaptureResult monoResult,
+ String title, long date, Location loc, int orientation,
+ OnMediaSavedListener l, ContentResolver resolver,
+ String pictureFormat) {
+ if (isQueueFull()) {
+ Log.e(TAG, "Cannot add image when the queue is full");
+ return;
+ }
+
+ MpoSaveTask t = new MpoSaveTask(csImage, bayerImg, monoImg,
+ bayerResult, monoResult, title, date, loc, orientation, l,
+ resolver, pictureFormat);
+
+ long size = (csImage == null ? 0
+ : csImage.getDataLength())
+ + bayerImg.getYuvData().length + monoImg.getYuvData().length;
+ mMemoryUse += size;
+ if (isQueueFull()) {
+ onQueueFull();
+ }
+ t.execute();
+ }
+
public void addImage(final byte[] data, String title, long date, Location loc,
int width, int height, int orientation, ExifInterface exif,
OnMediaSavedListener l, ContentResolver resolver, String pictureFormat) {
@@ -141,6 +177,97 @@ public class MediaSaveService extends Service {
if (mListener != null) mListener.onQueueStatus(false);
}
+ private class MpoSaveTask extends AsyncTask<Void, Void, Uri> {
+ private ClearsightImage csImage;
+ private YuvImage bayerImage;
+ private YuvImage monoImage;
+ private String title;
+ private long date;
+ private Location loc;
+ private int width, height;
+ private int orientation;
+ private TotalCaptureResult bayerResult;
+ private TotalCaptureResult monoResult;
+ private ContentResolver resolver;
+ private OnMediaSavedListener listener;
+ private String pictureFormat;
+
+ public MpoSaveTask(ClearsightImage csImage, YuvImage bayerImg,
+ YuvImage monoImg, TotalCaptureResult bayerResult,
+ TotalCaptureResult monoResult, String title, long date,
+ Location loc, int orientation, OnMediaSavedListener listener,
+ ContentResolver resolver, String pictureFormat) {
+ this.csImage = csImage;
+ this.bayerImage = bayerImg;
+ this.monoImage = monoImg;
+ this.title = title;
+ this.date = date;
+ this.loc = loc;
+ this.width = bayerImg.getWidth();
+ this.height = bayerImg.getHeight();
+ this.orientation = orientation;
+ this.bayerResult = bayerResult;
+ this.monoResult = monoResult;
+ this.resolver = resolver;
+ this.listener = listener;
+ this.pictureFormat = pictureFormat;
+ }
+
+ @Override
+ protected Uri doInBackground(Void... v) {
+ // encode jpeg and add exif for all images
+ MpoData mpo = new MpoData();
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ bayerImage.compressToJpeg(new Rect(0, 0, bayerImage.getWidth(),
+ bayerImage.getHeight()), 100, baos);
+ MpoImageData bayer = new MpoImageData(baos.toByteArray(),
+ ByteOrder.BIG_ENDIAN);
+
+ baos.reset();
+ monoImage.compressToJpeg(new Rect(0, 0, monoImage.getWidth(),
+ monoImage.getHeight()), 100, baos);
+ MpoImageData mono = new MpoImageData(baos.toByteArray(),
+ ByteOrder.BIG_ENDIAN);
+
+ if (csImage == null) {
+ mpo.addAuxiliaryMpoImage(mono);
+ mpo.setPrimaryMpoImage(bayer);
+ } else {
+ MpoImageData cs = new MpoImageData(csImage.compressToJpeg(),
+ ByteOrder.BIG_ENDIAN);
+
+ mpo.addAuxiliaryMpoImage(bayer);
+ mpo.addAuxiliaryMpoImage(mono);
+ mpo.setPrimaryMpoImage(cs);
+ }
+
+ // combine to single mpo
+ String path = Storage.generateFilepath(title, pictureFormat);
+ int size = MpoInterface.writeMpo(mpo, path);
+ // Try to get the real image size after add exif.
+ File f = new File(path);
+ if (f.exists() && f.isFile()) {
+ size = (int) f.length();
+ }
+ return Storage.addImage(resolver, title, date, loc, orientation,
+ size, path, width, height, pictureFormat);
+ }
+
+ @Override
+ protected void onPostExecute(Uri uri) {
+ if (listener != null)
+ listener.onMediaSaved(uri);
+ boolean previouslyFull = isQueueFull();
+ long size = (csImage == null ? 0
+ : csImage.getDataLength())
+ + bayerImage.getYuvData().length
+ + monoImage.getYuvData().length;
+ mMemoryUse -= size;
+ if (isQueueFull() != previouslyFull)
+ onQueueAvailable();
+ }
+ }
+
private class ImageSaveTask extends AsyncTask <Void, Void, Uri> {
private byte[] data;
private String title;
diff --git a/src/com/android/camera/PhotoUI.java b/src/com/android/camera/PhotoUI.java
index d4503af77..c8e01fea0 100644
--- a/src/com/android/camera/PhotoUI.java
+++ b/src/com/android/camera/PhotoUI.java
@@ -259,21 +259,6 @@ public class PhotoUI implements PieListener,
mMaxPreviewHeight = height;
}
- int orientation = mActivity.getResources().getConfiguration().orientation;
- if ((orientation == Configuration.ORIENTATION_PORTRAIT && width > height)
- || (orientation == Configuration.ORIENTATION_LANDSCAPE && width < height)) {
- // The screen has rotated; swap SurfaceView width & height
- // to ensure correct preview
- int oldWidth = width;
- width = height;
- height = oldWidth;
- Log.d(TAG, "Swapping SurfaceView width & height dimensions");
- if (mMaxPreviewWidth != 0 && mMaxPreviewHeight != 0) {
- int temp = mMaxPreviewWidth;
- mMaxPreviewWidth = mMaxPreviewHeight;
- mMaxPreviewHeight = temp;
- }
- }
if (mOrientationResize != mPrevOrientationResize
|| mAspectRatioResize) {
layoutPreview(mAspectRatio);
diff --git a/src/com/android/camera/VideoMenu.java b/src/com/android/camera/VideoMenu.java
index 302dd47f0..670572774 100644
--- a/src/com/android/camera/VideoMenu.java
+++ b/src/com/android/camera/VideoMenu.java
@@ -729,8 +729,7 @@ public class VideoMenu extends MenuController
mPrevSavedVideoCDS = cds;
}
- if ((tnr != null) && !mActivity.getString(R.string.
- pref_camera_video_tnr_default).equals(tnr)) {
+ if ((tnr != null) && !tnr.equals("off")) {
mListMenu.setPreferenceEnabled(
CameraSettings.KEY_VIDEO_CDS_MODE,false);
mListMenu.overrideSettings(
diff --git a/src/com/android/camera/VideoModule.java b/src/com/android/camera/VideoModule.java
index a7a7f0d3a..c21a56ae8 100644
--- a/src/com/android/camera/VideoModule.java
+++ b/src/com/android/camera/VideoModule.java
@@ -315,7 +315,7 @@ public class VideoModule implements CameraModule,
VIDEO_ENCODER_TABLE.put("h263", MediaRecorder.VideoEncoder.H263);
VIDEO_ENCODER_TABLE.put("h264", MediaRecorder.VideoEncoder.H264);
- VIDEO_ENCODER_TABLE.put("h265", MediaRecorder.VideoEncoder.H265);
+ // VIDEO_ENCODER_TABLE.put("h265", MediaRecorder.VideoEncoder.H265);
VIDEO_ENCODER_TABLE.put("m4v", MediaRecorder.VideoEncoder.MPEG_4_SP);
VIDEO_ENCODER_TABLE.putDefault(MediaRecorder.VideoEncoder.DEFAULT);
diff --git a/src/com/android/camera/VideoUI.java b/src/com/android/camera/VideoUI.java
index 8447db27e..c99c8c8f5 100644
--- a/src/com/android/camera/VideoUI.java
+++ b/src/com/android/camera/VideoUI.java
@@ -1123,8 +1123,6 @@ public class VideoUI implements PieRenderer.PieListener,
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
Log.v(TAG, "surfaceChanged: width = " + width + ", height = " + height);
- // Make sure preview cover is hidden if preview data is available.
- hidePreviewCover();
}
@Override
diff --git a/src/com/android/camera/exif/ExifTag.java b/src/com/android/camera/exif/ExifTag.java
index 1d50316dd..fcf0f5c29 100644
--- a/src/com/android/camera/exif/ExifTag.java
+++ b/src/com/android/camera/exif/ExifTag.java
@@ -85,7 +85,7 @@ public class ExifTag {
TYPE_TO_SIZE_MAP[TYPE_RATIONAL] = 8;
}
- static final int SIZE_UNDEFINED = 0;
+ public static final int SIZE_UNDEFINED = 0;
// Exif TagId
private final short mTagId;
@@ -124,7 +124,7 @@ public class ExifTag {
}
// Use builtTag in ExifInterface instead of constructor.
- ExifTag(short tagId, short type, int componentCount, int ifd,
+ public ExifTag(short tagId, short type, int componentCount, int ifd,
boolean hasDefinedComponentCount) {
mTagId = tagId;
mDataType = type;
@@ -163,7 +163,7 @@ public class ExifTag {
return mIfd;
}
- protected void setIfd(int ifdId) {
+ public void setIfd(int ifdId) {
mIfd = ifdId;
}
@@ -785,7 +785,7 @@ public class ExifTag {
* @exception IllegalArgumentException if the data type is
* {@link #TYPE_RATIONAL} or {@link #TYPE_UNSIGNED_RATIONAL}.
*/
- protected long getValueAt(int index) {
+ public long getValueAt(int index) {
if (mValue instanceof long[]) {
return ((long[]) mValue)[index];
} else if (mValue instanceof byte[]) {
@@ -812,7 +812,7 @@ public class ExifTag {
/*
* Get the converted ascii byte. Used by ExifOutputStream.
*/
- protected byte[] getStringByte() {
+ public byte[] getStringByte() {
return (byte[]) mValue;
}
@@ -822,7 +822,7 @@ public class ExifTag {
* @exception IllegalArgumentException If the type is NOT
* {@link #TYPE_RATIONAL} or {@link #TYPE_UNSIGNED_RATIONAL}.
*/
- protected Rational getRational(int index) {
+ public Rational getRational(int index) {
if ((mDataType != TYPE_RATIONAL) && (mDataType != TYPE_UNSIGNED_RATIONAL)) {
throw new IllegalArgumentException("Cannot get RATIONAL value from "
+ convertTypeToString(mDataType));
@@ -833,7 +833,7 @@ public class ExifTag {
/**
* Equivalent to getBytes(buffer, 0, buffer.length).
*/
- protected void getBytes(byte[] buf) {
+ public void getBytes(byte[] buf) {
getBytes(buf, 0, buf.length);
}
@@ -847,7 +847,7 @@ public class ExifTag {
* @exception IllegalArgumentException If the type is NOT
* {@link #TYPE_UNDEFINED} or {@link #TYPE_UNSIGNED_BYTE}.
*/
- protected void getBytes(byte[] buf, int offset, int length) {
+ public void getBytes(byte[] buf, int offset, int length) {
if ((mDataType != TYPE_UNDEFINED) && (mDataType != TYPE_UNSIGNED_BYTE)) {
throw new IllegalArgumentException("Cannot get BYTE value from "
+ convertTypeToString(mDataType));
@@ -860,14 +860,14 @@ public class ExifTag {
* Gets the offset of this tag. This is only valid if this data size > 4 and
* contains an offset to the location of the actual value.
*/
- protected int getOffset() {
+ public int getOffset() {
return mOffset;
}
/**
* Sets the offset of this tag.
*/
- protected void setOffset(int offset) {
+ public void setOffset(int offset) {
mOffset = offset;
}
diff --git a/src/com/android/camera/exif/JpegHeader.java b/src/com/android/camera/exif/JpegHeader.java
index 383617af4..6fc46ca18 100644
--- a/src/com/android/camera/exif/JpegHeader.java
+++ b/src/com/android/camera/exif/JpegHeader.java
@@ -16,8 +16,9 @@
package com.android.camera.exif;
-class JpegHeader {
+public class JpegHeader {
public static final short SOI = (short) 0xFFD8;
+ public static final short APP2 = (short) 0xFFE2;
public static final short APP1 = (short) 0xFFE1;
public static final short APP0 = (short) 0xFFE0;
public static final short EOI = (short) 0xFFD9;
diff --git a/src/com/android/camera/exif/OrderedDataOutputStream.java b/src/com/android/camera/exif/OrderedDataOutputStream.java
index abc0a6eb1..3206d72b0 100644
--- a/src/com/android/camera/exif/OrderedDataOutputStream.java
+++ b/src/com/android/camera/exif/OrderedDataOutputStream.java
@@ -22,7 +22,7 @@ import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
-class OrderedDataOutputStream extends FilterOutputStream {
+public class OrderedDataOutputStream extends FilterOutputStream {
private final ByteBuffer mByteBuffer = ByteBuffer.allocate(4);
private int mSize = 0;
diff --git a/src/com/android/camera/mpo/MpoData.java b/src/com/android/camera/mpo/MpoData.java
new file mode 100644
index 000000000..7cd431ebe
--- /dev/null
+++ b/src/com/android/camera/mpo/MpoData.java
@@ -0,0 +1,184 @@
+/*
+ * Copyright (c) 2016, The Linux Foundation. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided
+ * with the distribution.
+ * * Neither the name of The Linux Foundation nor the names of its
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
+ * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
+ * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+package com.android.camera.mpo;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import com.android.camera.mpo.MpoTag.MpEntry;
+
+public class MpoData {
+
+ private MpoImageData mPrimaryMpoImage;
+ private ArrayList<MpoImageData> mAuxiliaryImages = new ArrayList<MpoImageData>();
+
+ public MpoData() {
+ }
+
+ public void setPrimaryMpoImage(MpoImageData image) {
+ mPrimaryMpoImage = image;
+ addDefaultAttribIfdTags(mPrimaryMpoImage, 1);
+ addDefaultIndexIfdTags();
+ }
+
+ public void addAuxiliaryMpoImage(MpoImageData image) {
+ mAuxiliaryImages.add(image);
+ int imageNum = getAuxiliaryImageCount() + ((mPrimaryMpoImage == null) ? 0 : 1);
+ addDefaultAttribIfdTags(image, imageNum);
+ }
+
+ public boolean removeAuxiliaryMpoImage(MpoImageData image) {
+ boolean ret = mAuxiliaryImages.remove(image);
+ return ret;
+ }
+
+ public MpoImageData getPrimaryMpoImage() {
+ return mPrimaryMpoImage;
+ }
+
+ public List<MpoImageData> getAuxiliaryMpoImages() {
+ return mAuxiliaryImages;
+ }
+
+ public int getAuxiliaryImageCount() {
+ return mAuxiliaryImages.size();
+ }
+
+ public void addDefaultAttribIfdTags(MpoImageData image, int imageNum) {
+ MpoTag mpFormatVersionTag = new MpoTag((short) MpoInterface.TAG_MP_FORMAT_VERSION,
+ MpoTag.TYPE_UNDEFINED, 4, MpoIfdData.TYPE_MP_ATTRIB_IFD, true);
+ mpFormatVersionTag.setValue(MpoIfdData.MP_FORMAT_VER_VALUE);
+ image.addTag(mpFormatVersionTag);
+
+ MpoTag imageNumTag = new MpoTag((short) MpoInterface.TAG_IMAGE_NUMBER,
+ MpoTag.TYPE_UNSIGNED_LONG, 1, MpoIfdData.TYPE_MP_ATTRIB_IFD, false);
+ imageNumTag.setValue(imageNum);
+ image.addTag(imageNumTag);
+ }
+
+ public void addDefaultIndexIfdTags() {
+ if (mPrimaryMpoImage == null)
+ throw new IllegalArgumentException("Primary Mpo Image has not been set");
+ if (getAuxiliaryImageCount() == 0)
+ throw new IllegalArgumentException("No auxiliary images have been added");
+
+ MpoTag mpFormatVersionTag = mPrimaryMpoImage.getTag(
+ (short) MpoInterface.TAG_MP_FORMAT_VERSION, MpoIfdData.TYPE_MP_INDEX_IFD);
+ if (mpFormatVersionTag == null) {
+ mpFormatVersionTag = new MpoTag((short) MpoInterface.TAG_MP_FORMAT_VERSION,
+ MpoTag.TYPE_UNDEFINED, 4, MpoIfdData.TYPE_MP_INDEX_IFD, true);
+ mpFormatVersionTag.setValue(MpoIfdData.MP_FORMAT_VER_VALUE);
+ mPrimaryMpoImage.addTag(mpFormatVersionTag);
+ }
+
+ MpoTag numImagesTag = mPrimaryMpoImage.getTag((short) MpoInterface.TAG_NUM_IMAGES,
+ MpoIfdData.TYPE_MP_INDEX_IFD);
+ if (numImagesTag == null) {
+ numImagesTag = new MpoTag((short) MpoInterface.TAG_NUM_IMAGES,
+ MpoTag.TYPE_UNSIGNED_LONG, 1, MpoIfdData.TYPE_MP_INDEX_IFD, false);
+ }
+ numImagesTag.setValue(getAuxiliaryImageCount() + 1);
+ mPrimaryMpoImage.addTag(numImagesTag);
+
+ // check, create and add required tags
+ MpoTag mpEntryTag = new MpoTag((short) MpoInterface.TAG_MP_ENTRY, MpoTag.TYPE_UNDEFINED,
+ MpoTag.SIZE_UNDEFINED, MpoIfdData.TYPE_MP_INDEX_IFD, false);
+ ArrayList<MpEntry> mpEntries = new ArrayList<MpEntry>(getAuxiliaryImageCount() + 1);
+ mpEntries.add(new MpEntry()); // primary image
+ for (int i = 0; i < getAuxiliaryImageCount(); i++) {
+ mpEntries.add(new MpEntry()); // aux images
+ }
+ mpEntryTag.setValue(mpEntries);
+ mPrimaryMpoImage.addTag(mpEntryTag);
+ }
+
+ public void updateAllTags() {
+ updateAttribIfdTags();
+ updateIndexIfdTags();
+ }
+
+ private void updateIndexIfdTags() {
+ if (mPrimaryMpoImage == null)
+ throw new IllegalArgumentException("Primary Mpo Image has not been set");
+ if (getAuxiliaryImageCount() == 0)
+ throw new IllegalArgumentException("No auxiliary images have been added");
+
+ MpoTag numImagesTag = mPrimaryMpoImage.getTag((short) MpoInterface.TAG_NUM_IMAGES,
+ MpoIfdData.TYPE_MP_INDEX_IFD);
+ if (numImagesTag == null) {
+ numImagesTag = new MpoTag((short) MpoInterface.TAG_NUM_IMAGES,
+ MpoTag.TYPE_UNSIGNED_LONG, 1, MpoIfdData.TYPE_MP_INDEX_IFD, false);
+ }
+ numImagesTag.setValue(getAuxiliaryImageCount() + 1);
+ mPrimaryMpoImage.addTag(numImagesTag);
+
+ // check, create and add required tags
+ MpoTag mpEntryTag = new MpoTag((short) MpoInterface.TAG_MP_ENTRY, MpoTag.TYPE_UNDEFINED,
+ MpoTag.SIZE_UNDEFINED, MpoIfdData.TYPE_MP_INDEX_IFD, false);
+ ArrayList<MpEntry> mpEntries = new ArrayList<MpEntry>(getAuxiliaryImageCount() + 1);
+
+ int imgOffset = 0;
+ // primary image
+ MpEntry entry = new MpEntry(1 << 29, mPrimaryMpoImage.calculateImageSize(), imgOffset);
+ mpEntries.add(entry);
+ imgOffset += mPrimaryMpoImage.calculateImageSize();
+
+ for (MpoImageData image : getAuxiliaryMpoImages()) {
+ int imageSize = image.calculateImageSize();
+ entry = new MpEntry(0x020002, imageSize, imgOffset);
+ mpEntries.add(entry); // aux images
+ imgOffset += imageSize;
+ }
+ mpEntryTag.setValue(mpEntries);
+ mPrimaryMpoImage.addTag(mpEntryTag);
+ }
+
+ private void updateAttribIfdTags() {
+ if (mPrimaryMpoImage == null)
+ throw new IllegalArgumentException("Primary Mpo Image has not been set");
+ if (getAuxiliaryImageCount() == 0)
+ throw new IllegalArgumentException("No auxiliary images have been added");
+
+ int imageNum = 1;
+ MpoTag imageNumTag = null;
+
+ imageNumTag = new MpoTag((short) MpoInterface.TAG_IMAGE_NUMBER, MpoTag.TYPE_UNSIGNED_LONG,
+ 1, MpoIfdData.TYPE_MP_ATTRIB_IFD, false);
+ imageNumTag.setValue(0xFFFFFFFFL);
+ mPrimaryMpoImage.addTag(imageNumTag);
+
+ for (MpoImageData image : getAuxiliaryMpoImages()) {
+ imageNumTag = new MpoTag((short) MpoInterface.TAG_IMAGE_NUMBER,
+ MpoTag.TYPE_UNSIGNED_LONG, 1, MpoIfdData.TYPE_MP_ATTRIB_IFD, false);
+ imageNumTag.setValue(imageNum++);
+ image.addTag(imageNumTag);
+ }
+ }
+} \ No newline at end of file
diff --git a/src/com/android/camera/mpo/MpoIfdData.java b/src/com/android/camera/mpo/MpoIfdData.java
new file mode 100644
index 000000000..8e422944a
--- /dev/null
+++ b/src/com/android/camera/mpo/MpoIfdData.java
@@ -0,0 +1,126 @@
+/*
+ * Copyright (c) 2016, The Linux Foundation. All rights reserved.
+ * Not a contribution.
+ *
+ * Copyright (C) 2012 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 com.android.camera.mpo;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * This class stores all the tags in an MP Index IFD.
+ */
+public class MpoIfdData {
+ public static final int TYPE_MP_INDEX_IFD = 1;
+ public static final int TYPE_MP_ATTRIB_IFD = 2;
+ public static final byte[] MP_FORMAT_VER_VALUE = { 0x30, 0x31, 0x30, 0x30 };
+
+ private final int mIfdId;
+ private final Map<Short, MpoTag> mTags = new HashMap<Short, MpoTag>();
+ private int mOffsetToNextIfd = 0;
+
+ /**
+ * Creates an empty MpIndexIfdData
+ */
+ public MpoIfdData(int ifdId) {
+ mIfdId = ifdId;
+ }
+
+ /**
+ * Get a array the contains all {@link MpoTag} in this IFD.
+ */
+ protected MpoTag[] getAllTags() {
+ return mTags.values().toArray(new MpoTag[mTags.size()]);
+ }
+
+ /**
+ * Gets the {@link MpoTag} with given tag id. Return null if there is no
+ * such tag.
+ */
+ protected MpoTag getTag(short tagId) {
+ return mTags.get(tagId);
+ }
+
+ /**
+ * Adds or replaces a {@link MpoTag}.
+ */
+ protected MpoTag setTag(MpoTag tag) {
+ tag.setIfd(mIfdId);
+ return mTags.put(tag.getTagId(), tag);
+ }
+
+ protected boolean checkCollision(short tagId) {
+ return mTags.get(tagId) != null;
+ }
+
+ /**
+ * Removes the tag of the given ID
+ */
+ protected void removeTag(short tagId) {
+ mTags.remove(tagId);
+ }
+
+ /**
+ * Gets the tags count in the IFD.
+ */
+ protected int getTagCount() {
+ return mTags.size();
+ }
+
+ /**
+ * Sets the offset of next IFD.
+ */
+ protected void setOffsetToNextIfd(int offset) {
+ mOffsetToNextIfd = offset;
+ }
+
+ /**
+ * Gets the offset of next IFD.
+ */
+ protected int getOffsetToNextIfd() {
+ return mOffsetToNextIfd;
+ }
+
+ /**
+ * Returns true if all tags in this two IFDs are equal. Note that tags of
+ * IFD offset will be ignored.
+ */
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj == null) {
+ return false;
+ }
+ if (obj instanceof MpoIfdData) {
+ MpoIfdData data = (MpoIfdData) obj;
+ if (data.getTagCount() == getTagCount()) {
+ MpoTag[] tags = data.getAllTags();
+ for (MpoTag tag : tags) {
+ MpoTag tag2 = mTags.get(tag.getTagId());
+ if (!tag.equals(tag2)) {
+ return false;
+ }
+ }
+ return true;
+ }
+ }
+ return false;
+ }
+}
diff --git a/src/com/android/camera/mpo/MpoImageData.java b/src/com/android/camera/mpo/MpoImageData.java
new file mode 100644
index 000000000..84d2d0f6e
--- /dev/null
+++ b/src/com/android/camera/mpo/MpoImageData.java
@@ -0,0 +1,248 @@
+/*
+ * Copyright (c) 2016, The Linux Foundation. All rights reserved.
+ * Not a contribution.
+ *
+ * Copyright (C) 2012 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 com.android.camera.mpo;
+
+import java.nio.ByteOrder;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * This class stores the MPO header in IFDs according to the MPO specification.
+ */
+
+public class MpoImageData {
+ private static final String TAG = "MpoImageData";
+ static final int OFFSET_TO_FIRST_IFD = 8;
+ static final int MP_FORMAT_IDENTIFIER = 0x4D504600; // 'M' 'P' 'F' 'NULL'
+ static final int MP_HEADER_SIZE = 8;
+ static final int APP_HEADER_SIZE = 6;
+
+ private final MpoIfdData mMpIndexIfdData = new MpoIfdData(MpoIfdData.TYPE_MP_INDEX_IFD);
+ private final MpoIfdData mMpAttribIfdData = new MpoIfdData(MpoIfdData.TYPE_MP_ATTRIB_IFD);
+ private final byte[] mJpegData;
+ private final ByteOrder mByteOrder;
+
+ public MpoImageData(byte[] jpegData, ByteOrder byteOrder) {
+ mJpegData = jpegData;
+ mByteOrder = byteOrder;
+ }
+
+ /**
+ * Gets the jpeg data.
+ */
+ protected byte[] getJpegData() {
+ return mJpegData;
+ }
+
+ /**
+ * Gets the byte order.
+ */
+ protected ByteOrder getByteOrder() {
+ return mByteOrder;
+ }
+
+ /**
+ * Returns the {@link mMpAttribIfdData} object if it exists or null.
+ */
+ protected MpoIfdData getAttribIfdData() {
+ return mMpAttribIfdData;
+ }
+
+ /**
+ * Returns the {@link mMpIndexIfdData} object if it exists or null.
+ */
+ protected MpoIfdData getIndexIfdData() {
+ return mMpIndexIfdData;
+ }
+
+ /**
+ * Returns the {@link MpoIfdData} object corresponding to a given IFD.
+ */
+ protected MpoIfdData getMpIfdData(int ifdId) {
+ return (ifdId == MpoIfdData.TYPE_MP_INDEX_IFD) ? mMpIndexIfdData : mMpAttribIfdData;
+ }
+
+ /**
+ * Returns the tag with a given tag ID in the given IFD if the tag exists.
+ * Otherwise returns null.
+ */
+ protected MpoTag getTag(short tag, int ifd) {
+ MpoIfdData mpIfdData = getMpIfdData(ifd);
+ return mpIfdData.getTag(tag);
+ }
+
+ /**
+ * Adds the given MpoTag to its default IFD and returns an existing MpoTag
+ * with the same TID or null if none exist.
+ */
+ protected MpoTag addTag(MpoTag tag) {
+ if (tag != null) {
+ int ifd = tag.getIfd();
+ return addTag(tag, ifd);
+ }
+ return null;
+ }
+
+ /**
+ * Adds the given MpoTag to the given IFD and returns an existing MpoTag
+ * with the same tag ID or null if none exist.
+ */
+ protected MpoTag addTag(MpoTag tag, int ifdId) {
+ if (tag != null && MpoTag.isValidIfd(ifdId)) {
+ return getMpIfdData(ifdId).setTag(tag);
+ }
+ return null;
+ }
+
+ /**
+ * Removes the tag with a given tag ID and IFD.
+ */
+ protected void removeTag(short tagId, int ifdId) {
+ getMpIfdData(ifdId).removeTag(tagId);
+ }
+
+ /**
+ * Returns a list of all {@link MpoTag}s in the ExifData or null if there
+ * are none.
+ */
+ protected List<MpoTag> getAllTags() {
+ ArrayList<MpoTag> ret = new ArrayList<MpoTag>();
+ MpoTag[] tags = mMpIndexIfdData.getAllTags();
+ if (tags != null) {
+ for (MpoTag t : tags) {
+ ret.add(t);
+ }
+ }
+
+ tags = mMpAttribIfdData.getAllTags();
+ if (tags != null) {
+ for (MpoTag t : tags) {
+ ret.add(t);
+ }
+ }
+
+ if (ret.size() == 0) {
+ return null;
+ }
+ return ret;
+ }
+
+ /**
+ * Returns a list of all {@link MpoTag}s in a given IFD or null if there are
+ * none.
+ */
+ protected List<MpoTag> getAllTagsForIfd(int ifd) {
+ MpoTag[] tags = getMpIfdData(ifd).getAllTags();
+ if (tags == null) {
+ return null;
+ }
+ ArrayList<MpoTag> ret = new ArrayList<MpoTag>(tags.length);
+ for (MpoTag t : tags) {
+ ret.add(t);
+ }
+ if (ret.size() == 0) {
+ return null;
+ }
+ return ret;
+ }
+
+ /**
+ * Returns a list of all {@link MpoTag}s with a given TID or null if there
+ * are none.
+ */
+ protected List<MpoTag> getAllTagsForTagId(short tag) {
+ ArrayList<MpoTag> ret = new ArrayList<MpoTag>();
+ MpoTag t = mMpIndexIfdData.getTag(tag);
+ if (t != null) {
+ ret.add(t);
+ }
+
+ t = mMpAttribIfdData.getTag(tag);
+ if (t != null) {
+ ret.add(t);
+ }
+
+ if (ret.size() == 0) {
+ return null;
+ }
+ return ret;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj == null) {
+ return false;
+ }
+ if (obj instanceof MpoImageData) {
+ MpoImageData data = (MpoImageData) obj;
+ if (data.mByteOrder != mByteOrder) {
+ return false;
+ }
+
+ MpoIfdData indexIfd1 = data.getMpIfdData(MpoIfdData.TYPE_MP_INDEX_IFD);
+ MpoIfdData indexIfd2 = getMpIfdData(MpoIfdData.TYPE_MP_INDEX_IFD);
+ if (indexIfd1 != indexIfd2 && indexIfd1 != null && !indexIfd1.equals(indexIfd2)) {
+ return false;
+ }
+
+ MpoIfdData attribIfd1 = data.getMpIfdData(MpoIfdData.TYPE_MP_ATTRIB_IFD);
+ MpoIfdData attribIfd2 = getMpIfdData(MpoIfdData.TYPE_MP_ATTRIB_IFD);
+ if (attribIfd1 != attribIfd2 && attribIfd1 != null && !attribIfd1.equals(attribIfd2)) {
+ return false;
+ }
+ return true;
+ }
+ return false;
+ }
+
+ private int calculateOffsetOfIfd(MpoIfdData ifd, int offset) {
+ offset += 2 + ifd.getTagCount() * MpoTag.TAG_SIZE + 4;
+ MpoTag[] tags = ifd.getAllTags();
+ for (MpoTag tag : tags) {
+ if (tag.getDataSize() > 4) {
+ tag.setOffset(offset);
+ offset += tag.getDataSize();
+ }
+ }
+ return offset;
+ }
+
+ public int calculateAllIfdOffsets() {
+ int offset = MP_HEADER_SIZE;
+ MpoIfdData indexIfd = getIndexIfdData();
+ if (indexIfd.getTagCount() > 0)
+ offset = calculateOffsetOfIfd(indexIfd, offset);
+
+ MpoIfdData attribIfd = getAttribIfdData();
+ if (attribIfd.getTagCount() > 0) {
+ indexIfd.setOffsetToNextIfd(offset);
+ offset = calculateOffsetOfIfd(attribIfd, offset);
+ }
+
+ return offset;
+ }
+
+ public int calculateImageSize() {
+ return 2 + APP_HEADER_SIZE + calculateAllIfdOffsets() + mJpegData.length;
+ }
+}
diff --git a/src/com/android/camera/mpo/MpoInterface.java b/src/com/android/camera/mpo/MpoInterface.java
new file mode 100644
index 000000000..3e2d9a4e2
--- /dev/null
+++ b/src/com/android/camera/mpo/MpoInterface.java
@@ -0,0 +1,143 @@
+/*
+ * Copyright (c) 2016, The Linux Foundation. All rights reserved.
+ * Not a contribution.
+ *
+ * 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 com.android.camera.mpo;
+
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+
+import android.util.Log;
+
+import com.android.camera.exif.ExifInterface;
+import com.android.camera.util.CameraUtil;
+
+public class MpoInterface {
+ private static final String TAG = "MpoInterface";
+ private static final String NULL_ARGUMENT_STRING = "Argument is null";
+
+ // Index IFD
+ public static final int TAG_MP_FORMAT_VERSION = ExifInterface.defineTag(
+ MpoIfdData.TYPE_MP_INDEX_IFD + MpoIfdData.TYPE_MP_ATTRIB_IFD, (short) 0xB000);
+ public static final int TAG_NUM_IMAGES = ExifInterface.defineTag(MpoIfdData.TYPE_MP_INDEX_IFD,
+ (short) 0xB001);
+ public static final int TAG_MP_ENTRY = ExifInterface.defineTag(MpoIfdData.TYPE_MP_INDEX_IFD,
+ (short) 0xB002);
+ public static final int TAG_IMAGE_UNIQUE_ID_LIST = ExifInterface.defineTag(
+ MpoIfdData.TYPE_MP_INDEX_IFD, (short) 0xB003);
+ public static final int TAG_NUM_CAPTURED_FRAMES = ExifInterface.defineTag(
+ MpoIfdData.TYPE_MP_INDEX_IFD, (short) 0xB004);
+
+ // Attrib IFD
+ public static final int TAG_IMAGE_NUMBER = ExifInterface.defineTag(
+ MpoIfdData.TYPE_MP_ATTRIB_IFD, (short) 0xB101);
+ public static final int TAG_PAN_ORIENTATION = ExifInterface.defineTag(
+ MpoIfdData.TYPE_MP_ATTRIB_IFD, (short) 0xB201);
+ public static final int TAG_PAN_OVERLAP_H = ExifInterface.defineTag(
+ MpoIfdData.TYPE_MP_ATTRIB_IFD, (short) 0xB202);
+ public static final int TAG_PAN_OVERLAP_V = ExifInterface.defineTag(
+ MpoIfdData.TYPE_MP_ATTRIB_IFD, (short) 0xB203);
+ public static final int TAG_BASE_VIEWPOINT_NUM = ExifInterface.defineTag(
+ MpoIfdData.TYPE_MP_ATTRIB_IFD, (short) 0xB204);
+ public static final int TAG_CONVERGE_ANGLE = ExifInterface.defineTag(
+ MpoIfdData.TYPE_MP_ATTRIB_IFD, (short) 0xB205);
+ public static final int TAG_BASELINE_LEN = ExifInterface.defineTag(
+ MpoIfdData.TYPE_MP_ATTRIB_IFD, (short) 0xB206);
+ public static final int TAG_DIVERGE_ANGLE = ExifInterface.defineTag(
+ MpoIfdData.TYPE_MP_ATTRIB_IFD, (short) 0xB207);
+ public static final int TAG_AXIS_DISTANCE_X = ExifInterface.defineTag(
+ MpoIfdData.TYPE_MP_ATTRIB_IFD, (short) 0xB208);
+ public static final int TAG_AXIS_DISTANCE_Y = ExifInterface.defineTag(
+ MpoIfdData.TYPE_MP_ATTRIB_IFD, (short) 0xB209);
+ public static final int TAG_AXIS_DISTANCE_Z = ExifInterface.defineTag(
+ MpoIfdData.TYPE_MP_ATTRIB_IFD, (short) 0xB20A);
+ public static final int TAG_YAW_ANGLE = ExifInterface.defineTag(MpoIfdData.TYPE_MP_ATTRIB_IFD,
+ (short) 0xB20B);
+ public static final int TAG_PITCH_ANGLE = ExifInterface.defineTag(
+ MpoIfdData.TYPE_MP_ATTRIB_IFD, (short) 0xB20C);
+ public static final int TAG_ROLL_ANGLE = ExifInterface.defineTag(MpoIfdData.TYPE_MP_ATTRIB_IFD,
+ (short) 0xB20D);
+
+ public static int writeMpo(MpoData mpo, OutputStream out) {
+ if (mpo == null || out == null)
+ throw new IllegalArgumentException(NULL_ARGUMENT_STRING);
+
+ MpoOutputStream s = getMpoWriterStream(out);
+ s.setMpoData(mpo);
+
+ // check and write mpo file
+ try {
+ s.writeMpoFile();
+ } catch (IOException e) {
+ CameraUtil.closeSilently(s);
+ Log.w(TAG, "IO Exception when writing mpo image");
+ return -1;
+ }
+
+ // close stream
+ CameraUtil.closeSilently(s);
+ return s.size();
+ }
+
+ public static int writeMpo(MpoData mpo, String outFilename) {
+ if (mpo == null || outFilename == null)
+ throw new IllegalArgumentException(NULL_ARGUMENT_STRING);
+
+ return writeMpo(mpo, getFileWriterStream(outFilename));
+ }
+
+ /**
+ * Wraps an OutputStream object with an MpoOutputStream.
+ *
+ * @param outStream
+ * an OutputStream to wrap.
+ * @return an MpoOutputStream that wraps the outStream parameter, and adds
+ * mpo metadata. A jpeg image should be written to this stream.
+ */
+ private static MpoOutputStream getMpoWriterStream(OutputStream outStream) {
+ if (outStream == null) {
+ throw new IllegalArgumentException(NULL_ARGUMENT_STRING);
+ }
+ MpoOutputStream mos = new MpoOutputStream(outStream);
+ return mos;
+ }
+
+ /**
+ * Returns an FileOutputStream object that writes to a file.
+ *
+ * @param outFileName
+ * an String containing a filepath for a file.
+ * @return an FileOutputStream that writes to the outFileName file.
+ * @throws FileNotFoundException
+ */
+ private static OutputStream getFileWriterStream(String outFileName) {
+ if (outFileName == null) {
+ throw new IllegalArgumentException(NULL_ARGUMENT_STRING);
+ }
+ OutputStream out = null;
+ try {
+ out = new FileOutputStream(outFileName);
+ } catch (FileNotFoundException e) {
+ CameraUtil.closeSilently(out);
+ Log.w(TAG, "File not found");
+ }
+ return out;
+ }
+}
diff --git a/src/com/android/camera/mpo/MpoOutputStream.java b/src/com/android/camera/mpo/MpoOutputStream.java
new file mode 100644
index 000000000..6e8e72fd9
--- /dev/null
+++ b/src/com/android/camera/mpo/MpoOutputStream.java
@@ -0,0 +1,333 @@
+/*
+ * Copyright (c) 2016, The Linux Foundation. All rights reserved.
+ * Not a contribution/
+ *
+ * Copyright (C) 2012 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 com.android.camera.mpo;
+
+import java.io.BufferedOutputStream;
+import java.io.FilterOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.util.List;
+
+import android.util.Log;
+
+import com.android.camera.exif.JpegHeader;
+import com.android.camera.exif.OrderedDataOutputStream;
+import com.android.camera.mpo.MpoTag.MpEntry;
+
+class MpoOutputStream extends FilterOutputStream {
+ private static final String TAG = "MpoOutputStream";
+ private static final boolean DEBUG = true;
+ private static final int STREAMBUFFER_SIZE = 0x00010000; // 64Kb
+
+ private static final int STATE_SOI = 0;
+ private static final int STATE_FRAME_HEADER = 1;
+ private static final int STATE_JPEG_DATA = 3;
+
+ private static final short TIFF_HEADER = 0x002A;
+ private static final short TIFF_BIG_ENDIAN = 0x4d4d;
+ private static final short TIFF_LITTLE_ENDIAN = 0x4949;
+ private static final int MAX_EXIF_SIZE = 65535;
+
+ private MpoData mMpoData;
+ private MpoImageData mCurrentImageData;
+ private int mState = STATE_SOI;
+ private int mByteToSkip;
+ private int mByteToCopy;
+ private byte[] mSingleByteArray = new byte[1];
+ private ByteBuffer mBuffer = ByteBuffer.allocate(4);
+ private int mMpoOffsetStart = -1;
+ private int mSize = 0;
+
+ protected MpoOutputStream(OutputStream ou) {
+ super(new BufferedOutputStream(ou, STREAMBUFFER_SIZE));
+ }
+
+ /**
+ * Sets the ExifData to be written into the JPEG file. Should be called
+ * before writing image data.
+ */
+ protected void setMpoData(MpoData mpoData) {
+ mMpoData = mpoData;
+ mMpoData.updateAllTags();
+ }
+
+ private void resetStates() {
+ mState = STATE_SOI;
+ mByteToSkip = 0;
+ mByteToCopy = 0;
+ mBuffer.rewind();
+ }
+
+ private int requestByteToBuffer(int requestByteCount, byte[] buffer, int offset, int length) {
+ int byteNeeded = requestByteCount - mBuffer.position();
+ int byteToRead = length > byteNeeded ? byteNeeded : length;
+ mBuffer.put(buffer, offset, byteToRead);
+ return byteToRead;
+ }
+
+ void writeMpoFile() throws IOException {
+ // check and write primary image
+ mCurrentImageData = mMpoData.getPrimaryMpoImage();
+ write(mCurrentImageData.getJpegData());
+ flush();
+
+ // check and write auxiliary images
+ for (MpoImageData image : mMpoData.getAuxiliaryMpoImages()) {
+ resetStates();
+ mCurrentImageData = image;
+ write(mCurrentImageData.getJpegData());
+ flush();
+ }
+ }
+
+ /**
+ * Writes the image out. The input data should be a valid JPEG format. After
+ * writing, it's Exif header will be replaced by the given header.
+ */
+ @Override
+ public void write(byte[] buffer, int offset, int length) throws IOException {
+ while ((mByteToSkip > 0 || mByteToCopy > 0 || mState != STATE_JPEG_DATA) && length > 0) {
+ if (mByteToSkip > 0) {
+ int byteToProcess = length > mByteToSkip ? mByteToSkip : length;
+ length -= byteToProcess;
+ mByteToSkip -= byteToProcess;
+ offset += byteToProcess;
+ }
+ if (mByteToCopy > 0) {
+ int byteToProcess = length > mByteToCopy ? mByteToCopy : length;
+ out.write(buffer, offset, byteToProcess);
+ mSize += byteToProcess;
+ length -= byteToProcess;
+ mByteToCopy -= byteToProcess;
+ offset += byteToProcess;
+ }
+ if (length == 0) {
+ return;
+ }
+ switch (mState) {
+ case STATE_SOI:
+ int byteRead = requestByteToBuffer(2, buffer, offset, length);
+ offset += byteRead;
+ length -= byteRead;
+ if (mBuffer.position() < 2) {
+ return;
+ }
+ mBuffer.rewind();
+ if (mBuffer.getShort() != JpegHeader.SOI) {
+ throw new IOException("Not a valid jpeg image, cannot write exif");
+ }
+ out.write(mBuffer.array(), 0, 2);
+ mSize += 2;
+ mState = STATE_FRAME_HEADER;
+ mBuffer.rewind();
+ break;
+ case STATE_FRAME_HEADER:
+ // Copy APP1 if it exists
+ // Insert MPO data
+ // Copy remainder of image
+ byteRead = requestByteToBuffer(4, buffer, offset, length);
+ offset += byteRead;
+ length -= byteRead;
+ // Check if this image data doesn't contain SOF.
+ if (mBuffer.position() == 2) {
+ short tag = mBuffer.getShort();
+ if (tag == JpegHeader.EOI) {
+ out.write(mBuffer.array(), 0, 2);
+ mSize += 2;
+ mBuffer.rewind();
+ }
+ }
+ if (mBuffer.position() < 4) {
+ return;
+ }
+ mBuffer.rewind();
+ short marker = mBuffer.getShort();
+ if (marker == JpegHeader.APP1 || marker == JpegHeader.APP0) {
+ out.write(mBuffer.array(), 0, 4);
+ mSize += 4;
+ mByteToCopy = (mBuffer.getShort() & 0x0000ffff) - 2;
+ } else {
+ writeMpoData();
+ out.write(mBuffer.array(), 0, 4);
+ mSize += 4;
+ mState = STATE_JPEG_DATA;
+ }
+ mBuffer.rewind();
+ break;
+ }
+ }
+ if (length > 0) {
+ out.write(buffer, offset, length);
+ mSize += length;
+ }
+ }
+
+ /**
+ * Writes the one bytes out. The input data should be a valid JPEG format.
+ * After writing, it's Exif header will be replaced by the given header.
+ */
+ @Override
+ public void write(int oneByte) throws IOException {
+ mSingleByteArray[0] = (byte) (0xff & oneByte);
+ write(mSingleByteArray);
+ }
+
+ /**
+ * Equivalent to calling write(buffer, 0, buffer.length).
+ */
+ @Override
+ public void write(byte[] buffer) throws IOException {
+ write(buffer, 0, buffer.length);
+ }
+
+ private void writeMpoData() throws IOException {
+ if (mMpoData == null) {
+ return;
+ }
+ if (DEBUG) {
+ Log.v(TAG, "Writing mpo data...");
+ }
+ int exifSize = mCurrentImageData.calculateAllIfdOffsets() + MpoImageData.APP_HEADER_SIZE;
+ if (exifSize > MAX_EXIF_SIZE) {
+ throw new IOException("Exif header is too large (>64Kb)");
+ }
+ OrderedDataOutputStream dataOutputStream = new OrderedDataOutputStream(out);
+ dataOutputStream.setByteOrder(ByteOrder.BIG_ENDIAN);
+ dataOutputStream.writeShort(JpegHeader.APP2);
+ dataOutputStream.writeShort((short) (exifSize));
+ dataOutputStream.writeInt(MpoImageData.MP_FORMAT_IDENTIFIER);
+ if (mMpoOffsetStart == -1) {
+ mMpoOffsetStart = mSize + dataOutputStream.size();
+ }
+ if (mCurrentImageData.getByteOrder() == ByteOrder.BIG_ENDIAN) {
+ dataOutputStream.writeShort(TIFF_BIG_ENDIAN);
+ } else {
+ dataOutputStream.writeShort(TIFF_LITTLE_ENDIAN);
+ }
+ dataOutputStream.setByteOrder(mCurrentImageData.getByteOrder());
+ dataOutputStream.writeShort(TIFF_HEADER);
+ if (exifSize > MpoImageData.MP_HEADER_SIZE + MpoImageData.APP_HEADER_SIZE) {
+ dataOutputStream.writeInt(MpoImageData.OFFSET_TO_FIRST_IFD);
+ writeAllTags(dataOutputStream);
+ } else
+ dataOutputStream.writeInt(0);
+
+ mSize += dataOutputStream.size();
+ }
+
+ private void updateIndexIfdOffsets(MpoIfdData indexIfd, int mpoOffset) {
+ // update offsets
+ MpoTag mpEntryTag = mMpoData.getPrimaryMpoImage().getTag((short) MpoInterface.TAG_MP_ENTRY,
+ MpoIfdData.TYPE_MP_INDEX_IFD);
+ List<MpEntry> mpEntries = mpEntryTag.getMpEntryValue();
+ for (int i = 1; i < mpEntries.size(); i++) { // primary offset is always
+ // 0
+ MpEntry entry = mpEntries.get(i);
+ entry.setImageOffset(entry.getImageOffset() - mpoOffset);
+ }
+
+ mpEntryTag.setValue(mpEntries);
+ }
+
+ private void writeAllTags(OrderedDataOutputStream dataOutputStream) throws IOException {
+ MpoIfdData indexIfd = mCurrentImageData.getIndexIfdData();
+ if (indexIfd.getTagCount() > 0) {
+ updateIndexIfdOffsets(indexIfd, mMpoOffsetStart);
+ writeIfd(indexIfd, dataOutputStream);
+ }
+
+ MpoIfdData attribIfd = mCurrentImageData.getAttribIfdData();
+ if (attribIfd.getTagCount() > 0)
+ writeIfd(attribIfd, dataOutputStream);
+ }
+
+ private void writeIfd(MpoIfdData ifd, OrderedDataOutputStream dataOutputStream)
+ throws IOException {
+ MpoTag[] tags = ifd.getAllTags();
+ dataOutputStream.writeShort((short) tags.length);
+ for (MpoTag tag : tags) {
+ dataOutputStream.writeShort(tag.getTagId());
+ dataOutputStream.writeShort(tag.getDataType());
+ dataOutputStream.writeInt(tag.getComponentCount());
+ if (DEBUG) {
+ Log.v(TAG, "\n" + tag.toString());
+ }
+ if (tag.getDataSize() > 4) {
+ dataOutputStream.writeInt(tag.getOffset());
+ } else {
+ MpoOutputStream.writeTagValue(tag, dataOutputStream);
+ for (int i = 0, n = 4 - tag.getDataSize(); i < n; i++) {
+ dataOutputStream.write(0);
+ }
+ }
+ }
+ dataOutputStream.writeInt(ifd.getOffsetToNextIfd());
+ for (MpoTag tag : tags) {
+ if (tag.getDataSize() > 4) {
+ MpoOutputStream.writeTagValue(tag, dataOutputStream);
+ }
+ }
+ }
+
+ static void writeTagValue(MpoTag tag, OrderedDataOutputStream dataOutputStream)
+ throws IOException {
+ switch (tag.getDataType()) {
+ case MpoTag.TYPE_ASCII:
+ byte buf[] = tag.getStringByte();
+ if (buf.length == tag.getComponentCount()) {
+ buf[buf.length - 1] = 0;
+ dataOutputStream.write(buf);
+ } else {
+ dataOutputStream.write(buf);
+ dataOutputStream.write(0);
+ }
+ break;
+ case MpoTag.TYPE_LONG:
+ case MpoTag.TYPE_UNSIGNED_LONG:
+ for (int i = 0, n = tag.getComponentCount(); i < n; i++) {
+ dataOutputStream.writeInt((int) tag.getValueAt(i));
+ }
+ break;
+ case MpoTag.TYPE_RATIONAL:
+ case MpoTag.TYPE_UNSIGNED_RATIONAL:
+ for (int i = 0, n = tag.getComponentCount(); i < n; i++) {
+ dataOutputStream.writeRational(tag.getRational(i));
+ }
+ break;
+ case MpoTag.TYPE_UNDEFINED:
+ case MpoTag.TYPE_UNSIGNED_BYTE:
+ buf = new byte[tag.getComponentCount()];
+ tag.getBytes(buf);
+ dataOutputStream.write(buf);
+ break;
+ case MpoTag.TYPE_UNSIGNED_SHORT:
+ for (int i = 0, n = tag.getComponentCount(); i < n; i++) {
+ dataOutputStream.writeShort((short) tag.getValueAt(i));
+ }
+ break;
+ }
+ }
+
+ int size() {
+ return mSize;
+ }
+}
diff --git a/src/com/android/camera/mpo/MpoTag.java b/src/com/android/camera/mpo/MpoTag.java
new file mode 100644
index 000000000..bc0e6ce30
--- /dev/null
+++ b/src/com/android/camera/mpo/MpoTag.java
@@ -0,0 +1,163 @@
+/*
+ * Copyright (c) 2016, The Linux Foundation. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided
+ * with the distribution.
+ * * Neither the name of The Linux Foundation nor the names of its
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
+ * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
+ * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+package com.android.camera.mpo;
+
+import java.nio.BufferOverflowException;
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.List;
+
+import android.util.Log;
+
+import com.android.camera.exif.ExifTag;
+
+public class MpoTag extends ExifTag {
+ private static final String TAG = "MpoTag";
+ static final int TAG_SIZE = 12;
+
+ MpoTag(short tagId, short type, int componentCount, int ifd, boolean hasDefinedComponentCount) {
+ super(tagId, type, componentCount, ifd, hasDefinedComponentCount);
+ }
+
+ public boolean setValue(List<MpEntry> entries) {
+ if (getTagId() != (short) MpoInterface.TAG_MP_ENTRY) {
+ return false;
+ }
+
+ byte[] bytes = new byte[entries.size() * MpEntry.SIZE];
+ for (int i = 0; i < entries.size(); i++) {
+ MpEntry entry = entries.get(i);
+ entry.getBytes(ByteBuffer.wrap(bytes, i * MpEntry.SIZE, MpEntry.SIZE));
+ }
+ return setValue(bytes);
+ }
+
+ public List<MpEntry> getMpEntryValue() {
+ if (getTagId() != (short) MpoInterface.TAG_MP_ENTRY) {
+ return null;
+ }
+
+ byte[] bytes = getValueAsBytes();
+ List<MpEntry> entries = new ArrayList<MpEntry>(bytes.length / MpEntry.SIZE);
+ for (int i = 0; i < bytes.length; i += MpEntry.SIZE) {
+ entries.add(new MpEntry(ByteBuffer.wrap(bytes, i, MpEntry.SIZE)));
+ }
+ return entries;
+ }
+
+ static class MpEntry {
+ static final int SIZE = 16;
+ private int mImageAttrib;
+ private int mImageSize;
+ private int mImageOffset;
+ private short mDependantImage1;
+ private short mDependantImage2;
+
+ public MpEntry() {
+ this(0, 0, 0, (short) 0, (short) 0);
+ }
+
+ public MpEntry(int imageAttrib, int imageSize, int imageOffset) {
+ this(imageAttrib, imageSize, imageOffset, (short) 0, (short) 0);
+ }
+
+ public MpEntry(int imageAttrib, int imageSize, int imageOffset, short dependantImage1,
+ short dependantImage2) {
+ mImageAttrib = imageAttrib;
+ mImageSize = imageSize;
+ mImageOffset = imageOffset;
+ mDependantImage1 = dependantImage1;
+ mDependantImage2 = dependantImage2;
+ }
+
+ public MpEntry(ByteBuffer buffer) {
+ mImageAttrib = buffer.getInt();
+ mImageSize = buffer.getInt();
+ mImageOffset = buffer.getInt();
+ mDependantImage1 = buffer.getShort();
+ mDependantImage2 = buffer.getShort();
+ }
+
+ public int getImageAttrib() {
+ return mImageAttrib;
+ }
+
+ public int getImageSize() {
+ return mImageSize;
+ }
+
+ public int getImageOffset() {
+ return mImageOffset;
+ }
+
+ public short getDependantImage1() {
+ return mDependantImage1;
+ }
+
+ public short getDependantImage2() {
+ return mDependantImage2;
+ }
+
+ public void setImageAttrib(int imageAttrib) {
+ mImageAttrib = imageAttrib;
+ }
+
+ public void setImageSize(int imageSize) {
+ mImageSize = imageSize;
+ }
+
+ public void setImageOffset(int imageOffset) {
+ mImageOffset = imageOffset;
+ }
+
+ public void setDependantImage1(short depImage1) {
+ mDependantImage1 = depImage1;
+ }
+
+ public void setDependantImage2(short depImage2) {
+ mDependantImage2 = depImage2;
+ }
+
+ public boolean getBytes(ByteBuffer buffer) {
+ try {
+ buffer.putInt(mImageAttrib);
+ buffer.putInt(mImageSize);
+ buffer.putInt(mImageOffset);
+ buffer.putShort(mDependantImage1);
+ buffer.putShort(mDependantImage2);
+ } catch (BufferOverflowException e) {
+ Log.w(TAG, "Buffer size too small");
+ return false;
+ }
+
+ return true;
+ }
+ }
+} \ No newline at end of file
diff --git a/src/com/android/camera/ui/AutoFitSurfaceView.java b/src/com/android/camera/ui/AutoFitSurfaceView.java
new file mode 100644
index 000000000..38be39cf9
--- /dev/null
+++ b/src/com/android/camera/ui/AutoFitSurfaceView.java
@@ -0,0 +1,76 @@
+/*
+ * 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 com.android.camera.ui;
+
+import android.content.Context;
+import android.util.AttributeSet;
+import android.view.SurfaceView;
+
+/**
+ * A {@link SurfaceView} that can be adjusted to a specified aspect ratio.
+ */
+public class AutoFitSurfaceView extends SurfaceView {
+
+ private int mRatioWidth = 0;
+ private int mRatioHeight = 0;
+
+ public AutoFitSurfaceView(Context context) {
+ this(context, null);
+ }
+
+ public AutoFitSurfaceView(Context context, AttributeSet attrs) {
+ this(context, attrs, 0);
+ }
+
+ public AutoFitSurfaceView(Context context, AttributeSet attrs, int defStyle) {
+ super(context, attrs, defStyle);
+ }
+
+ /**
+ * Sets the aspect ratio for this view. The size of the view will be measured based on the ratio
+ * calculated from the parameters. Note that the actual sizes of parameters don't matter, that
+ * is, calling setAspectRatio(2, 3) and setAspectRatio(4, 6) make the same result.
+ *
+ * @param width Relative horizontal size
+ * @param height Relative vertical size
+ */
+ public void setAspectRatio(int width, int height) {
+ if (width < 0 || height < 0) {
+ throw new IllegalArgumentException("Size cannot be negative.");
+ }
+ mRatioWidth = width;
+ mRatioHeight = height;
+ requestLayout();
+ }
+
+ @Override
+ protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
+ super.onMeasure(widthMeasureSpec, heightMeasureSpec);
+ int width = MeasureSpec.getSize(widthMeasureSpec);
+ int height = MeasureSpec.getSize(heightMeasureSpec);
+ if (0 == mRatioWidth || 0 == mRatioHeight) {
+ setMeasuredDimension(width, height);
+ } else {
+ if (width < height * mRatioWidth / mRatioHeight) {
+ setMeasuredDimension(width, width * mRatioHeight / mRatioWidth);
+ } else {
+ setMeasuredDimension(height * mRatioWidth / mRatioHeight, height);
+ }
+ }
+ }
+
+}
diff --git a/src/com/android/camera/util/ClearSightNativeEngine.java b/src/com/android/camera/util/ClearSightNativeEngine.java
new file mode 100644
index 000000000..cf0a740d7
--- /dev/null
+++ b/src/com/android/camera/util/ClearSightNativeEngine.java
@@ -0,0 +1,351 @@
+/*
+ * Copyright (c) 2016, The Linux Foundation. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided
+ * with the distribution.
+ * * Neither the name of The Linux Foundation nor the names of its
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
+ * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
+ * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+package com.android.camera.util;
+
+import java.io.ByteArrayOutputStream;
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+
+import android.graphics.ImageFormat;
+import android.graphics.Rect;
+import android.graphics.YuvImage;
+import android.media.Image;
+import android.media.Image.Plane;
+import android.util.Log;
+
+public class ClearSightNativeEngine {
+ private static final String TAG = "ClearSightNativeEngine";
+ static {
+ try {
+ System.loadLibrary("jni_clearsight");
+ mLibLoaded = true;
+ Log.v(TAG, "successfully loaded clearsight lib");
+ } catch (UnsatisfiedLinkError e) {
+ Log.e(TAG, "failed to load clearsight lib");
+ e.printStackTrace();
+ mLibLoaded = false;
+ }
+ }
+
+ private static final int METADATA_SIZE = 5;
+ private static final int Y_PLANE = 0;
+ private static final int VU_PLANE = 2;
+
+ // dummy OTP calib data
+ private static final String otp_calib = "Calibration OTP format version = 10301\n"
+ + "Main Native Sensor Resolution width = 4224px\n"
+ + "Main Native Sensor Resolution height = 3136px\n"
+ + "Main Calibration Resolution width = 1280px\n"
+ + "Main Calibration Resolution height = 950px\n"
+ + "Main Focal length ratio = 1.004896\n"
+ + "Aux Native Sensor Resolution width = 1600px\n"
+ + "Aux Native Sensor Resolution height = 1200px\n"
+ + "Aux Calibration Resolution width = 1280px\n"
+ + "Aux Calibration Resolution height = 960px\n"
+ + "Aux Focal length ratio = 1.000000\n"
+ + "Relative Rotation matrix [0] through [8] = 1.000000,-0.003008,0.000251,0.003073,1.000189,0.003329,0.019673,-0.003329,1.000284\n"
+ + "Relative Geometric surface parameters [0] through [31] = -0.307164,-0.879074,4.636152,0.297486,-0.157539,-6.889396,0.109467,-2.797022,-0.066306,-0.120142,0.196464,0.021974,2.905827,0.241197,0.048328,-5.116615,0.496533,-5.263813,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000\n"
+ + "Relative Principal point X axis offset (ox) = 0.000000px\n"
+ + "Relative Principal point Y axis offset (oy) = 0.000000px\n"
+ + "Relative position flag = 1\n"
+ + "Baseline distance = 20.000000mm\n"
+ + "Main sensor mirror and flip setting = 3\n"
+ + "Aux sensor mirror and flip setting = 3\n"
+ + "Module orientation during calibration = 0\n"
+ + "Rotation flag = 0\n"
+ + "Main Normalized Focal length = 1000.0px\n"
+ + "Aux Normalized Focal length = 1000.0px";
+
+ private static boolean mLibLoaded;
+ private static ClearSightNativeEngine mInstance;
+
+ private Image mRefColorImage;
+ private Image mRefMonoImage;
+ private ArrayList<SourceImage> mSrcColor = new ArrayList<SourceImage>();
+ private ArrayList<SourceImage> mSrcMono = new ArrayList<SourceImage>();
+
+ private ClearSightNativeEngine() {
+ }
+
+ public static void createInstance() {
+ if (mInstance == null) {
+ mInstance = new ClearSightNativeEngine();
+ }
+ }
+
+ public static ClearSightNativeEngine getInstance() {
+ createInstance();
+ return mInstance;
+ }
+
+ public boolean isLibLoaded() {
+ return mLibLoaded;
+ }
+
+ public void reset() {
+ mSrcColor.clear();
+ mSrcMono.clear();
+ setReferenceColorImage(null);
+ setReferenceMonoImage(null);
+ }
+
+ public void setReferenceImage(boolean color, Image image) {
+ if (color)
+ setReferenceColorImage(image);
+ else
+ setReferenceMonoImage(image);
+ }
+
+ private void setReferenceColorImage(Image reference) {
+ if (mRefColorImage != null) {
+ mRefColorImage.close();
+ mRefColorImage = null;
+ }
+
+ mRefColorImage = reference;
+
+ if (mRefColorImage != null) {
+ Log.e(TAG,
+ "setRefColorImage - isdirectbuff: "
+ + mRefColorImage.getPlanes()[0].getBuffer()
+ .isDirect());
+ mSrcColor.add(new SourceImage(mRefColorImage.getPlanes()[Y_PLANE]
+ .getBuffer(), mRefColorImage.getPlanes()[VU_PLANE]
+ .getBuffer(), new int[] { 0, 0, 0, 0, 0 }));
+ }
+ }
+
+ private void setReferenceMonoImage(Image reference) {
+ if (mRefMonoImage != null) {
+ mRefMonoImage.close();
+ mRefMonoImage = null;
+ }
+
+ mRefMonoImage = reference;
+
+ if (mRefMonoImage != null) {
+ Log.e(TAG,
+ "setRefMonoImage - isdirectbuff: "
+ + mRefMonoImage.getPlanes()[0].getBuffer()
+ .isDirect());
+ mSrcMono.add(new SourceImage(mRefMonoImage.getPlanes()[Y_PLANE]
+ .getBuffer(), null, new int[] { 0, 0, 0, 0, 0 }));
+ }
+ }
+
+ public boolean hasReferenceImage(boolean color) {
+ return !(color ? mSrcColor.isEmpty() : mSrcMono.isEmpty());
+ }
+
+ public Image getReferenceImage(boolean color) {
+ return color ? mRefColorImage : mRefMonoImage;
+ }
+
+ public boolean registerImage(boolean color, Image image) {
+ return (color ? registerColorImage(image) : registerMonoImage(image));
+ }
+
+ private boolean registerColorImage(Image image) {
+ if (mSrcColor.isEmpty()) {
+ Log.w(TAG, "reference color image not yet set");
+ return false;
+ }
+
+ Plane[] planes = image.getPlanes();
+ ByteBuffer refY = mRefColorImage.getPlanes()[Y_PLANE].getBuffer();
+ ByteBuffer refVU = mRefColorImage.getPlanes()[VU_PLANE].getBuffer();
+ ByteBuffer regY = ByteBuffer.allocateDirect(refY.capacity());
+ ByteBuffer regVU = ByteBuffer.allocateDirect(refVU.capacity());
+ int[] metadata = new int[METADATA_SIZE];
+
+ boolean result = clearSightRegisterImage(refY,
+ planes[Y_PLANE].getBuffer(), planes[VU_PLANE].getBuffer(),
+ image.getWidth(), image.getHeight(),
+ planes[Y_PLANE].getRowStride(),
+ planes[VU_PLANE].getRowStride(), regY, regVU, metadata);
+
+ if (result) {
+ mSrcColor.add(new SourceImage(regY, regVU, metadata));
+ }
+
+ image.close();
+ return result;
+ }
+
+ private boolean registerMonoImage(Image image) {
+ if (mSrcMono.isEmpty()) {
+ Log.w(TAG, "reference mono image not yet set");
+ return false;
+ }
+
+ Plane[] planes = image.getPlanes();
+ ByteBuffer refY = mRefMonoImage.getPlanes()[Y_PLANE].getBuffer();
+ ByteBuffer regY = ByteBuffer.allocateDirect(refY.capacity());
+ int[] metadata = new int[METADATA_SIZE];
+
+ boolean result = clearSightRegisterImage(refY,
+ planes[Y_PLANE].getBuffer(), null, image.getWidth(),
+ image.getHeight(), planes[Y_PLANE].getRowStride(), 0, regY,
+ null, metadata);
+
+ if (result) {
+ mSrcMono.add(new SourceImage(regY, null, metadata));
+ }
+
+ image.close();
+ return result;
+ }
+
+ public ClearsightImage processImage() {
+ // check data validity
+ if (mSrcColor.size() != mSrcMono.size()) {
+ // mis-match in num images
+ Log.e(TAG, "processImage - numImages mismatch - bayer: "
+ + mSrcColor.size() + ", mono: " + mSrcMono.size());
+ return null;
+ }
+
+ int numImages = mSrcColor.size();
+ ByteBuffer[] srcColorY = new ByteBuffer[numImages];
+ ByteBuffer[] srcColorVU = new ByteBuffer[numImages];
+ int[][] metadataColor = new int[numImages][];
+ ByteBuffer[] srcMonoY = new ByteBuffer[numImages];
+ int[][] metadataMono = new int[numImages][];
+
+ Log.e(TAG, "processImage - numImages: " + numImages);
+
+ for (int i = 0; i < numImages; i++) {
+ SourceImage color = mSrcColor.get(i);
+ SourceImage mono = mSrcMono.get(i);
+
+ srcColorY[i] = color.mY;
+ srcColorVU[i] = color.mVU;
+ metadataColor[i] = color.mMetadata;
+
+ srcMonoY[i] = mono.mY;
+ metadataMono[i] = mono.mMetadata;
+ }
+
+ Plane[] colorPlanes = mRefColorImage.getPlanes();
+ Plane[] monoPlanes = mRefMonoImage.getPlanes();
+ ByteBuffer dstY = ByteBuffer.allocateDirect(colorPlanes[Y_PLANE]
+ .getBuffer().capacity());
+ ByteBuffer dstVU = ByteBuffer.allocateDirect(colorPlanes[VU_PLANE]
+ .getBuffer().capacity());
+ int[] roiRect = new int[4];
+
+ boolean result = clearSightProcess(numImages, srcColorY, srcColorVU,
+ metadataColor, mRefColorImage.getWidth(),
+ mRefColorImage.getHeight(),
+ colorPlanes[Y_PLANE].getRowStride(),
+ colorPlanes[VU_PLANE].getRowStride(), srcMonoY, metadataMono,
+ mRefMonoImage.getWidth(), mRefMonoImage.getHeight(),
+ monoPlanes[Y_PLANE].getRowStride(), otp_calib.getBytes(), dstY, dstVU,
+ colorPlanes[Y_PLANE].getRowStride(),
+ colorPlanes[VU_PLANE].getRowStride(), roiRect);
+
+ if (result) {
+ dstY.rewind();
+ dstVU.rewind();
+ byte[] data = new byte[dstY.capacity() + dstVU.capacity()];
+ int[] strides = new int[] { colorPlanes[Y_PLANE].getRowStride(),
+ colorPlanes[VU_PLANE].getRowStride() };
+ dstY.get(data, 0, dstY.capacity());
+ dstVU.get(data, dstY.capacity(), dstVU.capacity());
+ return new ClearsightImage(new YuvImage(data, ImageFormat.NV21,
+ mRefColorImage.getWidth(), mRefColorImage.getHeight(),
+ strides), roiRect);
+ } else {
+ return null;
+ }
+ }
+
+ native public boolean configureClearSight(float focalLengthRatio,
+ float brIntensity, float sharpenIntensity);
+
+ native public boolean clearSightRegisterImage(ByteBuffer refY,
+ ByteBuffer srcY, ByteBuffer srcVU, int width, int height,
+ int strideY, int strideVU, ByteBuffer dstY, ByteBuffer dstVU,
+ int[] metadata);
+
+ native public boolean clearSightProcess(int numImagePairs,
+ ByteBuffer[] srcColorY, ByteBuffer[] srcColorVU,
+ int[][] metadataColor, int srcColorWidth, int srcColorHeight,
+ int srcColorStrideY, int srcColorStrideVU, ByteBuffer[] srcMonoY,
+ int[][] metadataMono, int srcMonoWidth, int srcMonoHeight,
+ int srcMonoStrideY, byte[] otp, ByteBuffer dstY, ByteBuffer dstVU,
+ int dstStrideY, int dstStrideVU, int[] roiRect);
+
+ private class SourceImage {
+ ByteBuffer mY;
+ ByteBuffer mVU;
+ int[] mMetadata;
+
+ SourceImage(ByteBuffer y, ByteBuffer vu, int[] metadata) {
+ mY = y;
+ mVU = vu;
+ mMetadata = metadata;
+ }
+ }
+
+ public static class ClearsightImage {
+ private YuvImage mImage;
+ private Rect mRoiRect;
+
+ ClearsightImage(YuvImage image, int[] rect) {
+ mImage = image;
+ mRoiRect = new Rect(rect[0], rect[1], rect[0] + rect[2], rect[1]
+ + rect[3]);
+ }
+
+ public Rect getRoiRect() {
+ return mRoiRect;
+ }
+
+ public long getDataLength() {
+ return (mImage==null?0:mImage.getYuvData().length);
+ }
+
+ public int getWidth() {
+ return (mRoiRect.right - mRoiRect.left);
+ }
+
+ public int getHeight() {
+ return (mRoiRect.bottom - mRoiRect.top);
+ }
+
+ public byte[] compressToJpeg() {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+
+ mImage.compressToJpeg(mRoiRect, 100, baos);
+ return baos.toByteArray();
+ }
+ }
+}