blob: ccd12e7416d45745308e1f9ce22f32ba72ac68a3 [file] [log] [blame]
Michael Kolb8872c232013-01-29 10:33:22 -08001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Angus Kongb50b5cb2013-08-09 14:55:20 -070017package com.android.camera.util;
Michael Kolb8872c232013-01-29 10:33:22 -080018
Michael Kolb8872c232013-01-29 10:33:22 -080019import android.app.Activity;
20import android.app.AlertDialog;
21import android.app.admin.DevicePolicyManager;
22import android.content.ActivityNotFoundException;
Sascha Haeberlingfae11a12013-08-15 14:29:49 -070023import android.content.ComponentName;
Michael Kolb8872c232013-01-29 10:33:22 -080024import android.content.ContentResolver;
25import android.content.Context;
26import android.content.DialogInterface;
27import android.content.Intent;
Doris Liubd1b8f92014-01-03 17:59:51 -080028import android.content.res.TypedArray;
Michael Kolb8872c232013-01-29 10:33:22 -080029import android.graphics.Bitmap;
30import android.graphics.BitmapFactory;
31import android.graphics.Matrix;
32import android.graphics.Point;
Jiawen Chen09713762014-09-16 17:05:37 -070033import android.graphics.PointF;
Michael Kolb8872c232013-01-29 10:33:22 -080034import android.graphics.Rect;
35import android.graphics.RectF;
Sascha Haeberlinga2dd9ea2014-08-15 18:45:15 -070036import android.hardware.camera2.CameraCharacteristics;
37import android.hardware.camera2.CameraMetadata;
Michael Kolb8872c232013-01-29 10:33:22 -080038import android.location.Location;
39import android.net.Uri;
Michael Kolb8872c232013-01-29 10:33:22 -080040import android.os.ParcelFileDescriptor;
41import android.telephony.TelephonyManager;
42import android.util.DisplayMetrics;
Michael Kolb8872c232013-01-29 10:33:22 -080043import android.util.TypedValue;
Doris Liu0ba8eaa2013-10-16 12:51:02 -070044import android.view.Display;
Michael Kolb8872c232013-01-29 10:33:22 -080045import android.view.OrientationEventListener;
46import android.view.Surface;
47import android.view.View;
48import android.view.WindowManager;
49import android.view.animation.AlphaAnimation;
50import android.view.animation.Animation;
Angus Kongb40738a2013-06-03 14:55:34 -070051import android.widget.Toast;
Michael Kolb8872c232013-01-29 10:33:22 -080052
Sascha Haeberlingb7639c62013-09-09 14:42:43 -070053import com.android.camera.CameraActivity;
Angus Kongb50b5cb2013-08-09 14:55:20 -070054import com.android.camera.CameraDisabledException;
Angus Kong2bca2102014-03-11 16:27:30 -070055import com.android.camera.debug.Log;
Angus Kongc195e7a2014-02-20 16:56:37 -080056import com.android.camera.filmstrip.ImageData;
Sascha Haeberling37f36112013-08-06 14:31:52 -070057import com.android.camera2.R;
Sol Boucher5a344962014-06-17 14:05:08 -070058import com.android.ex.camera2.portability.CameraCapabilities;
59import com.android.ex.camera2.portability.CameraSettings;
Michael Kolb8872c232013-01-29 10:33:22 -080060
Sascha Haeberling638e6f02013-09-18 14:28:51 -070061import java.io.Closeable;
62import java.io.IOException;
63import java.lang.reflect.Method;
64import java.text.SimpleDateFormat;
65import java.util.Date;
66import java.util.List;
67import java.util.Locale;
Sascha Haeberling638e6f02013-09-18 14:28:51 -070068
Michael Kolb8872c232013-01-29 10:33:22 -080069/**
70 * Collection of utility functions used in this package.
71 */
Angus Kongb50b5cb2013-08-09 14:55:20 -070072public class CameraUtil {
Angus Kong2bca2102014-03-11 16:27:30 -070073 private static final Log.Tag TAG = new Log.Tag("Util");
Michael Kolb8872c232013-01-29 10:33:22 -080074
ztenghui16a35202013-09-23 11:35:36 -070075 // For calculate the best fps range for still image capture.
76 private final static int MAX_PREVIEW_FPS_TIMES_1000 = 400000;
77 private final static int PREFERRED_PREVIEW_FPS_TIMES_1000 = 30000;
78
Angus Kongb50b5cb2013-08-09 14:55:20 -070079 // For creating crop intents.
80 public static final String KEY_RETURN_DATA = "return-data";
81 public static final String KEY_SHOW_WHEN_LOCKED = "showWhenLocked";
82
Sascha Haeberlingf2627902014-09-02 14:20:57 -070083 /** Orientation hysteresis amount used in rounding, in degrees. */
Michael Kolb8872c232013-01-29 10:33:22 -080084 public static final int ORIENTATION_HYSTERESIS = 5;
85
86 public static final String REVIEW_ACTION = "com.android.camera.action.REVIEW";
Sascha Haeberlingf2627902014-09-02 14:20:57 -070087 /** See android.hardware.Camera.ACTION_NEW_PICTURE. */
Michael Kolb8872c232013-01-29 10:33:22 -080088 public static final String ACTION_NEW_PICTURE = "android.hardware.action.NEW_PICTURE";
Sascha Haeberlingf2627902014-09-02 14:20:57 -070089 /** See android.hardware.Camera.ACTION_NEW_VIDEO. */
Michael Kolb8872c232013-01-29 10:33:22 -080090 public static final String ACTION_NEW_VIDEO = "android.hardware.action.NEW_VIDEO";
91
Sascha Haeberlingf2627902014-09-02 14:20:57 -070092 /**
93 * Broadcast Action: The camera application has become active in
94 * picture-taking mode.
95 */
Dan Aminzadefca1c5e2013-08-14 17:36:56 -070096 public static final String ACTION_CAMERA_STARTED = "com.android.camera.action.CAMERA_STARTED";
Sascha Haeberlingf2627902014-09-02 14:20:57 -070097 /**
98 * Broadcast Action: The camera application is no longer in active
99 * picture-taking mode.
100 */
Dan Aminzadefca1c5e2013-08-14 17:36:56 -0700101 public static final String ACTION_CAMERA_STOPPED = "com.android.camera.action.CAMERA_STOPPED";
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700102 /**
103 * When the camera application is active in picture-taking mode, it listens
104 * for this intent, which upon receipt will trigger the shutter to capture a
105 * new picture, as if the user had pressed the shutter button.
106 */
Dan Aminzadefca1c5e2013-08-14 17:36:56 -0700107 public static final String ACTION_CAMERA_SHUTTER_CLICK =
108 "com.android.camera.action.SHUTTER_CLICK";
109
Sascha Haeberlingfae11a12013-08-15 14:29:49 -0700110 // Fields for the show-on-maps-functionality
111 private static final String MAPS_PACKAGE_NAME = "com.google.android.apps.maps";
112 private static final String MAPS_CLASS_NAME = "com.google.android.maps.MapsActivity";
113
114 /** Has to be in sync with the receiving MovieActivity. */
115 public static final String KEY_TREAT_UP_AS_BACK = "treat-up-as-back";
Michael Kolb8872c232013-01-29 10:33:22 -0800116
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700117 /** Private intent extras. Test only. */
Michael Kolb8872c232013-01-29 10:33:22 -0800118 private static final String EXTRAS_CAMERA_FACING =
119 "android.intent.extras.CAMERA_FACING";
120
121 private static float sPixelDensity = 1;
122 private static ImageFileNamer sImageFileNamer;
123
Angus Kongb50b5cb2013-08-09 14:55:20 -0700124 private CameraUtil() {
Michael Kolb8872c232013-01-29 10:33:22 -0800125 }
126
127 public static void initialize(Context context) {
128 DisplayMetrics metrics = new DisplayMetrics();
129 WindowManager wm = (WindowManager)
130 context.getSystemService(Context.WINDOW_SERVICE);
131 wm.getDefaultDisplay().getMetrics(metrics);
132 sPixelDensity = metrics.density;
133 sImageFileNamer = new ImageFileNamer(
134 context.getString(R.string.image_file_name_format));
135 }
136
137 public static int dpToPixel(int dp) {
138 return Math.round(sPixelDensity * dp);
139 }
140
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700141 /**
142 * Rotates the bitmap by the specified degree. If a new bitmap is created,
143 * the original bitmap is recycled.
144 */
Michael Kolb8872c232013-01-29 10:33:22 -0800145 public static Bitmap rotate(Bitmap b, int degrees) {
146 return rotateAndMirror(b, degrees, false);
147 }
148
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700149 /**
150 * Rotates and/or mirrors the bitmap. If a new bitmap is created, the
151 * original bitmap is recycled.
152 */
Michael Kolb8872c232013-01-29 10:33:22 -0800153 public static Bitmap rotateAndMirror(Bitmap b, int degrees, boolean mirror) {
154 if ((degrees != 0 || mirror) && b != null) {
155 Matrix m = new Matrix();
156 // Mirror first.
157 // horizontal flip + rotation = -rotation + horizontal flip
158 if (mirror) {
159 m.postScale(-1, 1);
160 degrees = (degrees + 360) % 360;
161 if (degrees == 0 || degrees == 180) {
162 m.postTranslate(b.getWidth(), 0);
163 } else if (degrees == 90 || degrees == 270) {
164 m.postTranslate(b.getHeight(), 0);
165 } else {
166 throw new IllegalArgumentException("Invalid degrees=" + degrees);
167 }
168 }
169 if (degrees != 0) {
170 // clockwise
171 m.postRotate(degrees,
172 (float) b.getWidth() / 2, (float) b.getHeight() / 2);
173 }
174
175 try {
176 Bitmap b2 = Bitmap.createBitmap(
177 b, 0, 0, b.getWidth(), b.getHeight(), m, true);
178 if (b != b2) {
179 b.recycle();
180 b = b2;
181 }
182 } catch (OutOfMemoryError ex) {
183 // We have no memory to rotate. Return the original bitmap.
184 }
185 }
186 return b;
187 }
188
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700189 /**
190 * Compute the sample size as a function of minSideLength and
191 * maxNumOfPixels. minSideLength is used to specify that minimal width or
192 * height of a bitmap. maxNumOfPixels is used to specify the maximal size in
193 * pixels that is tolerable in terms of memory usage. The function returns a
194 * sample size based on the constraints.
195 * <p>
196 * Both size and minSideLength can be passed in as -1 which indicates no
197 * care of the corresponding constraint. The functions prefers returning a
198 * sample size that generates a smaller bitmap, unless minSideLength = -1.
199 * <p>
Michael Kolb8872c232013-01-29 10:33:22 -0800200 * Also, the function rounds up the sample size to a power of 2 or multiple
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700201 * of 8 because BitmapFactory only honors sample size this way. For example,
202 * BitmapFactory downsamples an image by 2 even though the request is 3. So
203 * we round up the sample size to avoid OOM.
Michael Kolb8872c232013-01-29 10:33:22 -0800204 */
205 public static int computeSampleSize(BitmapFactory.Options options,
Sascha Haeberlingc6da1a12014-11-06 09:50:51 -0800206 int minSideLength, int maxNumOfPixels) {
Michael Kolb8872c232013-01-29 10:33:22 -0800207 int initialSize = computeInitialSampleSize(options, minSideLength,
Sascha Haeberlingc6da1a12014-11-06 09:50:51 -0800208 maxNumOfPixels);
Michael Kolb8872c232013-01-29 10:33:22 -0800209
210 int roundedSize;
211 if (initialSize <= 8) {
212 roundedSize = 1;
213 while (roundedSize < initialSize) {
214 roundedSize <<= 1;
215 }
216 } else {
217 roundedSize = (initialSize + 7) / 8 * 8;
218 }
219
220 return roundedSize;
221 }
222
223 private static int computeInitialSampleSize(BitmapFactory.Options options,
224 int minSideLength, int maxNumOfPixels) {
225 double w = options.outWidth;
226 double h = options.outHeight;
227
228 int lowerBound = (maxNumOfPixels < 0) ? 1 :
229 (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));
230 int upperBound = (minSideLength < 0) ? 128 :
231 (int) Math.min(Math.floor(w / minSideLength),
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700232 Math.floor(h / minSideLength));
Michael Kolb8872c232013-01-29 10:33:22 -0800233
234 if (upperBound < lowerBound) {
235 // return the larger one when there is no overlapping zone.
236 return lowerBound;
237 }
238
239 if (maxNumOfPixels < 0 && minSideLength < 0) {
240 return 1;
241 } else if (minSideLength < 0) {
242 return lowerBound;
243 } else {
244 return upperBound;
245 }
246 }
247
248 public static Bitmap makeBitmap(byte[] jpegData, int maxNumOfPixels) {
249 try {
250 BitmapFactory.Options options = new BitmapFactory.Options();
251 options.inJustDecodeBounds = true;
252 BitmapFactory.decodeByteArray(jpegData, 0, jpegData.length,
253 options);
254 if (options.mCancel || options.outWidth == -1
255 || options.outHeight == -1) {
256 return null;
257 }
258 options.inSampleSize = computeSampleSize(
259 options, -1, maxNumOfPixels);
260 options.inJustDecodeBounds = false;
261
262 options.inDither = false;
263 options.inPreferredConfig = Bitmap.Config.ARGB_8888;
264 return BitmapFactory.decodeByteArray(jpegData, 0, jpegData.length,
265 options);
266 } catch (OutOfMemoryError ex) {
267 Log.e(TAG, "Got oom exception ", ex);
268 return null;
269 }
270 }
271
272 public static void closeSilently(Closeable c) {
Sascha Haeberling846d3ab2014-02-04 12:48:55 +0100273 if (c == null) {
274 return;
275 }
Michael Kolb8872c232013-01-29 10:33:22 -0800276 try {
277 c.close();
278 } catch (Throwable t) {
279 // do nothing
280 }
281 }
282
283 public static void Assert(boolean cond) {
284 if (!cond) {
285 throw new AssertionError();
286 }
287 }
288
Michael Kolb8872c232013-01-29 10:33:22 -0800289 public static void showErrorAndFinish(final Activity activity, int msgId) {
290 DialogInterface.OnClickListener buttonListener =
291 new DialogInterface.OnClickListener() {
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700292 @Override
293 public void onClick(DialogInterface dialog, int which) {
294 activity.finish();
295 }
296 };
Michael Kolb8872c232013-01-29 10:33:22 -0800297 TypedValue out = new TypedValue();
298 activity.getTheme().resolveAttribute(android.R.attr.alertDialogIcon, out, true);
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700299 // Some crash reports indicate users leave app prior to this dialog
300 // appearing, so check to ensure that the activity is not shutting down
301 // before attempting to attach a dialog to the window manager.
Alan Newbergerb19aba92014-05-16 11:45:14 -0700302 if (!activity.isFinishing()) {
Senpo Hu13159192014-10-13 11:54:16 -0700303 Log.e(TAG, "Show fatal error dialog");
Alan Newbergerb19aba92014-05-16 11:45:14 -0700304 new AlertDialog.Builder(activity)
305 .setCancelable(false)
306 .setTitle(R.string.camera_error_title)
307 .setMessage(msgId)
308 .setNeutralButton(R.string.dialog_ok, buttonListener)
309 .setIcon(out.resourceId)
310 .show();
311 }
Michael Kolb8872c232013-01-29 10:33:22 -0800312 }
313
314 public static <T> T checkNotNull(T object) {
Sascha Haeberling846d3ab2014-02-04 12:48:55 +0100315 if (object == null) {
316 throw new NullPointerException();
317 }
Michael Kolb8872c232013-01-29 10:33:22 -0800318 return object;
319 }
320
321 public static boolean equals(Object a, Object b) {
322 return (a == b) || (a == null ? false : a.equals(b));
323 }
324
325 public static int nextPowerOf2(int n) {
Jiawen Chen09713762014-09-16 17:05:37 -0700326 // TODO: what happens if n is negative or already a power of 2?
Michael Kolb8872c232013-01-29 10:33:22 -0800327 n -= 1;
328 n |= n >>> 16;
329 n |= n >>> 8;
330 n |= n >>> 4;
331 n |= n >>> 2;
332 n |= n >>> 1;
333 return n + 1;
334 }
335
336 public static float distance(float x, float y, float sx, float sy) {
337 float dx = x - sx;
338 float dy = y - sy;
Sascha Haeberling638e6f02013-09-18 14:28:51 -0700339 return (float) Math.sqrt(dx * dx + dy * dy);
Michael Kolb8872c232013-01-29 10:33:22 -0800340 }
341
Jiawen Chen09713762014-09-16 17:05:37 -0700342 /**
343 * Clamps x to between min and max (inclusive on both ends, x = min --> min,
344 * x = max --> max).
345 */
Michael Kolb8872c232013-01-29 10:33:22 -0800346 public static int clamp(int x, int min, int max) {
Sascha Haeberling846d3ab2014-02-04 12:48:55 +0100347 if (x > max) {
348 return max;
349 }
350 if (x < min) {
351 return min;
352 }
Michael Kolb8872c232013-01-29 10:33:22 -0800353 return x;
354 }
355
Jiawen Chen09713762014-09-16 17:05:37 -0700356 /**
357 * Clamps x to between min and max (inclusive on both ends, x = min --> min,
358 * x = max --> max).
359 */
Igor Murashkin160b0362013-10-14 14:57:30 -0700360 public static float clamp(float x, float min, float max) {
Sascha Haeberling846d3ab2014-02-04 12:48:55 +0100361 if (x > max) {
362 return max;
363 }
364 if (x < min) {
365 return min;
366 }
Igor Murashkin160b0362013-10-14 14:57:30 -0700367 return x;
368 }
369
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700370 /**
371 * Linear interpolation between a and b by the fraction t. t = 0 --> a, t =
372 * 1 --> b.
373 */
374 public static float lerp(float a, float b, float t) {
375 return a + t * (b - a);
376 }
377
378 /**
Jiawen Chen09713762014-09-16 17:05:37 -0700379 * Given (nx, ny) \in [0, 1]^2, in the display's portrait coordinate system,
Sascha Haeberlingc6da1a12014-11-06 09:50:51 -0800380 * returns normalized sensor coordinates \in [0, 1]^2 depending on how the
381 * sensor's orientation \in {0, 90, 180, 270}.
Jiawen Chen09713762014-09-16 17:05:37 -0700382 * <p>
383 * Returns null if sensorOrientation is not one of the above.
384 * </p>
385 */
386 public static PointF normalizedSensorCoordsForNormalizedDisplayCoords(
Sascha Haeberlingc6da1a12014-11-06 09:50:51 -0800387 float nx, float ny, int sensorOrientation) {
Jiawen Chen09713762014-09-16 17:05:37 -0700388 switch (sensorOrientation) {
Sascha Haeberlingc6da1a12014-11-06 09:50:51 -0800389 case 0:
390 return new PointF(nx, ny);
391 case 90:
392 return new PointF(ny, 1.0f - nx);
393 case 180:
394 return new PointF(1.0f - nx, 1.0f - ny);
395 case 270:
396 return new PointF(1.0f - ny, nx);
397 default:
398 return null;
Jiawen Chen09713762014-09-16 17:05:37 -0700399 }
400 }
401
402 /**
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700403 * Given a size, return the largest size with the given aspectRatio that
404 * maximally fits into the bounding rectangle of the original Size.
405 *
406 * @param size the original Size to crop
407 * @param aspectRatio the target aspect ratio
408 * @return the largest Size with the given aspect ratio that is smaller than
409 * or equal to the original Size.
410 */
411 public static Size constrainToAspectRatio(Size size, float aspectRatio) {
412 float width = size.getWidth();
413 float height = size.getHeight();
414
415 float currentAspectRatio = width * 1.0f / height;
416
417 if (currentAspectRatio > aspectRatio) {
418 // chop longer side
419 if (width > height) {
420 width = height * aspectRatio;
421 } else {
422 height = width / aspectRatio;
423 }
424 } else if (currentAspectRatio < aspectRatio) {
425 // chop shorter side
426 if (width < height) {
427 width = height * aspectRatio;
428 } else {
429 height = width / aspectRatio;
430 }
431 }
432
433 return new Size((int) width, (int) height);
434 }
435
Sascha Haeberling846d3ab2014-02-04 12:48:55 +0100436 public static int getDisplayRotation(Context context) {
437 WindowManager windowManager = (WindowManager) context
438 .getSystemService(Context.WINDOW_SERVICE);
439 int rotation = windowManager.getDefaultDisplay()
Michael Kolb8872c232013-01-29 10:33:22 -0800440 .getRotation();
441 switch (rotation) {
Sascha Haeberling59c784b2014-08-05 10:53:08 -0700442 case Surface.ROTATION_0:
443 return 0;
444 case Surface.ROTATION_90:
445 return 90;
446 case Surface.ROTATION_180:
447 return 180;
448 case Surface.ROTATION_270:
449 return 270;
Michael Kolb8872c232013-01-29 10:33:22 -0800450 }
451 return 0;
452 }
453
Doris Liu0ba8eaa2013-10-16 12:51:02 -0700454 /**
455 * Calculate the default orientation of the device based on the width and
456 * height of the display when rotation = 0 (i.e. natural width and height)
Sascha Haeberling59c784b2014-08-05 10:53:08 -0700457 *
Doris Liu8dc878f2014-05-05 14:10:34 -0700458 * @param context current context
Doris Liu0ba8eaa2013-10-16 12:51:02 -0700459 * @return whether the default orientation of the device is portrait
460 */
Doris Liu8dc878f2014-05-05 14:10:34 -0700461 public static boolean isDefaultToPortrait(Context context) {
462 Display currentDisplay = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE))
463 .getDefaultDisplay();
Doris Liu0ba8eaa2013-10-16 12:51:02 -0700464 Point displaySize = new Point();
465 currentDisplay.getSize(displaySize);
466 int orientation = currentDisplay.getRotation();
467 int naturalWidth, naturalHeight;
468 if (orientation == Surface.ROTATION_0 || orientation == Surface.ROTATION_180) {
469 naturalWidth = displaySize.x;
470 naturalHeight = displaySize.y;
471 } else {
472 naturalWidth = displaySize.y;
473 naturalHeight = displaySize.x;
474 }
475 return naturalWidth < naturalHeight;
476 }
477
Michael Kolb8872c232013-01-29 10:33:22 -0800478 public static int roundOrientation(int orientation, int orientationHistory) {
479 boolean changeOrientation = false;
480 if (orientationHistory == OrientationEventListener.ORIENTATION_UNKNOWN) {
481 changeOrientation = true;
482 } else {
483 int dist = Math.abs(orientation - orientationHistory);
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700484 dist = Math.min(dist, 360 - dist);
485 changeOrientation = (dist >= 45 + ORIENTATION_HYSTERESIS);
Michael Kolb8872c232013-01-29 10:33:22 -0800486 }
487 if (changeOrientation) {
488 return ((orientation + 45) / 90 * 90) % 360;
489 }
490 return orientationHistory;
491 }
492
Angus Kong88289042014-04-22 16:39:42 -0700493 private static Size getDefaultDisplaySize(Context context) {
Sascha Haeberling846d3ab2014-02-04 12:48:55 +0100494 WindowManager windowManager = (WindowManager) context
495 .getSystemService(Context.WINDOW_SERVICE);
Angus Kong88289042014-04-22 16:39:42 -0700496 Point res = new Point();
497 windowManager.getDefaultDisplay().getSize(res);
498 return new Size(res);
Michael Kolb8872c232013-01-29 10:33:22 -0800499 }
500
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700501 public static com.android.ex.camera2.portability.Size getOptimalPreviewSize(Context context,
502 List<com.android.ex.camera2.portability.Size> sizes, double targetRatio) {
503 int optimalPickIndex = getOptimalPreviewSizeIndex(context, Size.convert(sizes),
504 targetRatio);
505 if (optimalPickIndex == -1) {
506 return null;
507 } else {
508 return sizes.get(optimalPickIndex);
509 }
Ruben Brunk714d4d02013-10-09 16:01:16 -0700510 }
511
Sascha Haeberlingc6da1a12014-11-06 09:50:51 -0800512 /**
513 * Returns the index into 'sizes' that is most optimal given the current
514 * screen and target aspect ratio..
515 * <p>
516 * This is using a default aspect ratio tolerance. If the tolerance is to be
517 * given you should call
518 * {@link #getOptimalPreviewSizeIndex(Context, List, double, Double)}
519 *
520 * @param context used to get the screen dimensions. TODO: Refactor to take
521 * in screen dimensions directly
522 * @param previewSizes the available preview sizes
523 * @param targetRatio the target aspect ratio, typically the aspect ratio of
524 * the picture size
525 * @return The index into 'previewSizes' for the optimal size, or -1, if no
526 * matching size was found.
527 */
Angus Kong88289042014-04-22 16:39:42 -0700528 public static int getOptimalPreviewSizeIndex(Context context,
529 List<Size> sizes, double targetRatio) {
Ruben Brunk714d4d02013-10-09 16:01:16 -0700530 // Use a very small tolerance because we want an exact match.
Sascha Haeberlingc6da1a12014-11-06 09:50:51 -0800531 final double aspectRatioTolerance;
Alan Newberger2ebdbd52014-11-04 14:21:33 -0800532 // HTC 4:3 ratios is over .01 from true 4:3, targeted fix for those
533 // devices here, see b/18241645
534 if (ApiHelper.IS_HTC && targetRatio > 1.3433 && targetRatio < 1.35) {
535 Log.w(TAG, "4:3 ratio out of normal tolerance, increasing tolerance to 0.02");
Sascha Haeberlingc6da1a12014-11-06 09:50:51 -0800536 aspectRatioTolerance = 0.02;
Alan Newberger2ebdbd52014-11-04 14:21:33 -0800537 } else {
Sascha Haeberlingc6da1a12014-11-06 09:50:51 -0800538 aspectRatioTolerance = 0.01;
Alan Newberger2ebdbd52014-11-04 14:21:33 -0800539 }
Sascha Haeberlingc6da1a12014-11-06 09:50:51 -0800540 return getOptimalPreviewSizeIndex(context, sizes, targetRatio, aspectRatioTolerance);
541 }
542
543 /**
544 * Returns the index into 'sizes' that is most optimal given the current
545 * screen, target aspect ratio and tolerance.
546 *
547 * @param context used to get the screen dimensions. TODO: Refactor to take
548 * in screen dimensions directly
549 * @param previewSizes the available preview sizes
550 * @param targetRatio the target aspect ratio, typically the aspect ratio of
551 * the picture size
552 * @param aspectRatioTolerance the tolerance we allow between the selected
553 * preview size's aspect ratio and the target ratio. If this is
554 * set to 'null', the default value is used.
555 * @return The index into 'previewSizes' for the optimal size, or -1, if no
556 * matching size was found.
557 */
558 public static int getOptimalPreviewSizeIndex(Context context,
559 List<Size> previewSizes, double targetRatio, Double aspectRatioTolerance) {
560 if (previewSizes == null) {
Sascha Haeberling846d3ab2014-02-04 12:48:55 +0100561 return -1;
562 }
Ruben Brunk714d4d02013-10-09 16:01:16 -0700563
Sascha Haeberlingc6da1a12014-11-06 09:50:51 -0800564 // If no particular aspect ratio tolerance is set, use the default
565 // value.
566 if (aspectRatioTolerance == null) {
567 return getOptimalPreviewSizeIndex(context, previewSizes, targetRatio);
568 }
569
Ruben Brunk714d4d02013-10-09 16:01:16 -0700570 int optimalSizeIndex = -1;
Michael Kolb8872c232013-01-29 10:33:22 -0800571 double minDiff = Double.MAX_VALUE;
572
573 // Because of bugs of overlay and layout, we sometimes will try to
574 // layout the viewfinder in the portrait orientation and thus get the
575 // wrong size of preview surface. When we change the preview size, the
576 // new overlay will be created before the old one closed, which causes
577 // an exception. For now, just get the screen size.
Angus Kong88289042014-04-22 16:39:42 -0700578 Size defaultDisplaySize = getDefaultDisplaySize(context);
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700579 int targetHeight = Math.min(defaultDisplaySize.getWidth(), defaultDisplaySize.getHeight());
Michael Kolb8872c232013-01-29 10:33:22 -0800580 // Try to find an size match aspect ratio and size
Sascha Haeberlingc6da1a12014-11-06 09:50:51 -0800581 for (int i = 0; i < previewSizes.size(); i++) {
582 Size size = previewSizes.get(i);
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700583 double ratio = (double) size.getWidth() / size.getHeight();
Sascha Haeberlingc6da1a12014-11-06 09:50:51 -0800584 if (Math.abs(ratio - targetRatio) > aspectRatioTolerance) {
Sascha Haeberling846d3ab2014-02-04 12:48:55 +0100585 continue;
586 }
Igor Murashkincf2a8182014-08-25 13:21:26 -0700587
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700588 double heightDiff = Math.abs(size.getHeight() - targetHeight);
Igor Murashkincf2a8182014-08-25 13:21:26 -0700589 if (heightDiff < minDiff) {
Ruben Brunk714d4d02013-10-09 16:01:16 -0700590 optimalSizeIndex = i;
Igor Murashkincf2a8182014-08-25 13:21:26 -0700591 minDiff = heightDiff;
592 } else if (heightDiff == minDiff) {
593 // Prefer resolutions smaller-than-display when an equally close
594 // larger-than-display resolution is available
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700595 if (size.getHeight() < targetHeight) {
Igor Murashkincf2a8182014-08-25 13:21:26 -0700596 optimalSizeIndex = i;
597 minDiff = heightDiff;
598 }
Michael Kolb8872c232013-01-29 10:33:22 -0800599 }
600 }
601 // Cannot find the one match the aspect ratio. This should not happen.
602 // Ignore the requirement.
Ruben Brunk714d4d02013-10-09 16:01:16 -0700603 if (optimalSizeIndex == -1) {
Sascha Haeberlingc6da1a12014-11-06 09:50:51 -0800604 Log.w(TAG, "No preview size match the aspect ratio. available sizes: " + previewSizes);
Michael Kolb8872c232013-01-29 10:33:22 -0800605 minDiff = Double.MAX_VALUE;
Sascha Haeberlingc6da1a12014-11-06 09:50:51 -0800606 for (int i = 0; i < previewSizes.size(); i++) {
607 Size size = previewSizes.get(i);
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700608 if (Math.abs(size.getHeight() - targetHeight) < minDiff) {
Ruben Brunk714d4d02013-10-09 16:01:16 -0700609 optimalSizeIndex = i;
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700610 minDiff = Math.abs(size.getHeight() - targetHeight);
Michael Kolb8872c232013-01-29 10:33:22 -0800611 }
612 }
613 }
I-Jong Lin4ed861a2014-10-10 16:34:34 -0700614
Ruben Brunk714d4d02013-10-09 16:01:16 -0700615 return optimalSizeIndex;
Michael Kolb8872c232013-01-29 10:33:22 -0800616 }
617
I-Jong Lin4ed861a2014-10-10 16:34:34 -0700618 /**
619 * Returns the largest picture size which matches the given aspect ratio,
Sascha Haeberlingc6da1a12014-11-06 09:50:51 -0800620 * except for the special WYSIWYG case where the picture size exactly
621 * matches the target size.
I-Jong Lin4ed861a2014-10-10 16:34:34 -0700622 *
Sascha Haeberlingc6da1a12014-11-06 09:50:51 -0800623 * @param sizes a list of candidate sizes, available for use
624 * @param targetWidth the ideal width of the video snapshot
I-Jong Lin4ed861a2014-10-10 16:34:34 -0700625 * @param targetHeight the ideal height of the video snapshot
626 * @return the Optimal Video Snapshot Picture Size
627 */
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700628 public static com.android.ex.camera2.portability.Size getOptimalVideoSnapshotPictureSize(
I-Jong Lin4ed861a2014-10-10 16:34:34 -0700629 List<com.android.ex.camera2.portability.Size> sizes, int targetWidth,
630 int targetHeight) {
631
Michael Kolb8872c232013-01-29 10:33:22 -0800632 // Use a very small tolerance because we want an exact match.
633 final double ASPECT_TOLERANCE = 0.001;
Sascha Haeberling846d3ab2014-02-04 12:48:55 +0100634 if (sizes == null) {
635 return null;
636 }
Michael Kolb8872c232013-01-29 10:33:22 -0800637
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700638 com.android.ex.camera2.portability.Size optimalSize = null;
Michael Kolb8872c232013-01-29 10:33:22 -0800639
Sascha Haeberlingc6da1a12014-11-06 09:50:51 -0800640 // WYSIWYG Override
641 // We assume that physical display constraints have already been
642 // imposed on the variables sizes
I-Jong Lin4ed861a2014-10-10 16:34:34 -0700643 for (com.android.ex.camera2.portability.Size size : sizes) {
644 if (size.height() == targetHeight && size.width() == targetWidth) {
645 return size;
646 }
647 }
648
Michael Kolb8872c232013-01-29 10:33:22 -0800649 // Try to find a size matches aspect ratio and has the largest width
I-Jong Lin4ed861a2014-10-10 16:34:34 -0700650 final double targetRatio = (double) targetWidth / targetHeight;
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700651 for (com.android.ex.camera2.portability.Size size : sizes) {
Angus Kong00b7b102014-04-24 15:46:52 -0700652 double ratio = (double) size.width() / size.height();
Sascha Haeberling846d3ab2014-02-04 12:48:55 +0100653 if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) {
654 continue;
655 }
Angus Kong00b7b102014-04-24 15:46:52 -0700656 if (optimalSize == null || size.width() > optimalSize.width()) {
Michael Kolb8872c232013-01-29 10:33:22 -0800657 optimalSize = size;
658 }
659 }
660
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700661 // Cannot find one that matches the aspect ratio. This should not
662 // happen. Ignore the requirement.
Michael Kolb8872c232013-01-29 10:33:22 -0800663 if (optimalSize == null) {
664 Log.w(TAG, "No picture size match the aspect ratio");
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700665 for (com.android.ex.camera2.portability.Size size : sizes) {
Angus Kong00b7b102014-04-24 15:46:52 -0700666 if (optimalSize == null || size.width() > optimalSize.width()) {
Michael Kolb8872c232013-01-29 10:33:22 -0800667 optimalSize = size;
668 }
669 }
670 }
671 return optimalSize;
672 }
673
Michael Kolb8872c232013-01-29 10:33:22 -0800674 /**
675 * Returns whether the device is voice-capable (meaning, it can do MMS).
676 */
677 public static boolean isMmsCapable(Context context) {
678 TelephonyManager telephonyManager = (TelephonyManager)
679 context.getSystemService(Context.TELEPHONY_SERVICE);
680 if (telephonyManager == null) {
681 return false;
682 }
683
684 try {
685 Class<?> partypes[] = new Class[0];
686 Method sIsVoiceCapable = TelephonyManager.class.getMethod(
687 "isVoiceCapable", partypes);
688
689 Object arglist[] = new Object[0];
690 Object retobj = sIsVoiceCapable.invoke(telephonyManager, arglist);
691 return (Boolean) retobj;
692 } catch (java.lang.reflect.InvocationTargetException ite) {
693 // Failure, must be another device.
694 // Assume that it is voice capable.
695 } catch (IllegalAccessException iae) {
696 // Failure, must be an other device.
697 // Assume that it is voice capable.
698 } catch (NoSuchMethodException nsme) {
699 }
700 return true;
701 }
702
703 // This is for test only. Allow the camera to launch the specific camera.
704 public static int getCameraFacingIntentExtras(Activity currentActivity) {
705 int cameraId = -1;
706
707 int intentCameraId =
Angus Kongb50b5cb2013-08-09 14:55:20 -0700708 currentActivity.getIntent().getIntExtra(CameraUtil.EXTRAS_CAMERA_FACING, -1);
Michael Kolb8872c232013-01-29 10:33:22 -0800709
710 if (isFrontCameraIntent(intentCameraId)) {
711 // Check if the front camera exist
Angus Kong20fad242013-11-11 18:23:46 -0800712 int frontCameraId = ((CameraActivity) currentActivity).getCameraProvider()
713 .getFirstFrontCameraId();
Michael Kolb8872c232013-01-29 10:33:22 -0800714 if (frontCameraId != -1) {
715 cameraId = frontCameraId;
716 }
717 } else if (isBackCameraIntent(intentCameraId)) {
718 // Check if the back camera exist
Angus Kong20fad242013-11-11 18:23:46 -0800719 int backCameraId = ((CameraActivity) currentActivity).getCameraProvider()
720 .getFirstBackCameraId();
Michael Kolb8872c232013-01-29 10:33:22 -0800721 if (backCameraId != -1) {
722 cameraId = backCameraId;
723 }
724 }
725 return cameraId;
726 }
727
728 private static boolean isFrontCameraIntent(int intentCameraId) {
729 return (intentCameraId == android.hardware.Camera.CameraInfo.CAMERA_FACING_FRONT);
730 }
731
732 private static boolean isBackCameraIntent(int intentCameraId) {
733 return (intentCameraId == android.hardware.Camera.CameraInfo.CAMERA_FACING_BACK);
734 }
735
736 private static int sLocation[] = new int[2];
737
738 // This method is not thread-safe.
739 public static boolean pointInView(float x, float y, View v) {
740 v.getLocationInWindow(sLocation);
741 return x >= sLocation[0] && x < (sLocation[0] + v.getWidth())
742 && y >= sLocation[1] && y < (sLocation[1] + v.getHeight());
743 }
744
745 public static int[] getRelativeLocation(View reference, View view) {
746 reference.getLocationInWindow(sLocation);
747 int referenceX = sLocation[0];
748 int referenceY = sLocation[1];
749 view.getLocationInWindow(sLocation);
750 sLocation[0] -= referenceX;
751 sLocation[1] -= referenceY;
752 return sLocation;
753 }
754
755 public static boolean isUriValid(Uri uri, ContentResolver resolver) {
Sascha Haeberling846d3ab2014-02-04 12:48:55 +0100756 if (uri == null) {
757 return false;
758 }
Michael Kolb8872c232013-01-29 10:33:22 -0800759
760 try {
761 ParcelFileDescriptor pfd = resolver.openFileDescriptor(uri, "r");
762 if (pfd == null) {
763 Log.e(TAG, "Fail to open URI. URI=" + uri);
764 return false;
765 }
766 pfd.close();
767 } catch (IOException ex) {
768 return false;
769 }
770 return true;
771 }
772
Michael Kolb8872c232013-01-29 10:33:22 -0800773 public static void dumpRect(RectF rect, String msg) {
774 Log.v(TAG, msg + "=(" + rect.left + "," + rect.top
775 + "," + rect.right + "," + rect.bottom + ")");
776 }
777
778 public static void rectFToRect(RectF rectF, Rect rect) {
779 rect.left = Math.round(rectF.left);
780 rect.top = Math.round(rectF.top);
781 rect.right = Math.round(rectF.right);
782 rect.bottom = Math.round(rectF.bottom);
783 }
784
Doris Liu36ebcb12013-10-28 14:44:24 -0700785 public static Rect rectFToRect(RectF rectF) {
786 Rect rect = new Rect();
787 rectFToRect(rectF, rect);
788 return rect;
789 }
790
791 public static RectF rectToRectF(Rect r) {
792 return new RectF(r.left, r.top, r.right, r.bottom);
793 }
794
Michael Kolb8872c232013-01-29 10:33:22 -0800795 public static void prepareMatrix(Matrix matrix, boolean mirror, int displayOrientation,
796 int viewWidth, int viewHeight) {
797 // Need mirror for front camera.
798 matrix.setScale(mirror ? -1 : 1, 1);
799 // This is the value for android.hardware.Camera.setDisplayOrientation.
800 matrix.postRotate(displayOrientation);
801 // Camera driver coordinates range from (-1000, -1000) to (1000, 1000).
802 // UI coordinates range from (0, 0) to (width, height).
803 matrix.postScale(viewWidth / 2000f, viewHeight / 2000f);
804 matrix.postTranslate(viewWidth / 2f, viewHeight / 2f);
805 }
806
Doris Liu36ebcb12013-10-28 14:44:24 -0700807 public static void prepareMatrix(Matrix matrix, boolean mirror, int displayOrientation,
Sascha Haeberling59c784b2014-08-05 10:53:08 -0700808 Rect previewRect) {
Doris Liu36ebcb12013-10-28 14:44:24 -0700809 // Need mirror for front camera.
810 matrix.setScale(mirror ? -1 : 1, 1);
811 // This is the value for android.hardware.Camera.setDisplayOrientation.
812 matrix.postRotate(displayOrientation);
813
814 // Camera driver coordinates range from (-1000, -1000) to (1000, 1000).
815 // We need to map camera driver coordinates to preview rect coordinates
816 Matrix mapping = new Matrix();
817 mapping.setRectToRect(new RectF(-1000, -1000, 1000, 1000), rectToRectF(previewRect),
818 Matrix.ScaleToFit.FILL);
819 matrix.setConcat(mapping, matrix);
820 }
821
Michael Kolb8872c232013-01-29 10:33:22 -0800822 public static String createJpegName(long dateTaken) {
823 synchronized (sImageFileNamer) {
824 return sImageFileNamer.generateName(dateTaken);
825 }
826 }
827
828 public static void broadcastNewPicture(Context context, Uri uri) {
829 context.sendBroadcast(new Intent(ACTION_NEW_PICTURE, uri));
830 // Keep compatibility
831 context.sendBroadcast(new Intent("com.android.camera.NEW_PICTURE", uri));
832 }
833
834 public static void fadeIn(View view, float startAlpha, float endAlpha, long duration) {
Sascha Haeberling846d3ab2014-02-04 12:48:55 +0100835 if (view.getVisibility() == View.VISIBLE) {
836 return;
837 }
Michael Kolb8872c232013-01-29 10:33:22 -0800838
839 view.setVisibility(View.VISIBLE);
840 Animation animation = new AlphaAnimation(startAlpha, endAlpha);
841 animation.setDuration(duration);
842 view.startAnimation(animation);
843 }
844
Sascha Haeberling37f36112013-08-06 14:31:52 -0700845 /**
846 * Down-samples a jpeg byte array.
Sascha Haeberling59c784b2014-08-05 10:53:08 -0700847 *
Sascha Haeberling37f36112013-08-06 14:31:52 -0700848 * @param data a byte array of jpeg data
849 * @param downSampleFactor down-sample factor
850 * @return decoded and down-sampled bitmap
851 */
852 public static Bitmap downSample(final byte[] data, int downSampleFactor) {
853 final BitmapFactory.Options opts = new BitmapFactory.Options();
854 // Downsample the image
855 opts.inSampleSize = downSampleFactor;
856 return BitmapFactory.decodeByteArray(data, 0, data.length, opts);
857 }
858
Angus Kong6607dae2014-06-10 16:07:45 -0700859 public static void setGpsParameters(CameraSettings settings, Location loc) {
Michael Kolb8872c232013-01-29 10:33:22 -0800860 // Clear previous GPS location from the parameters.
Angus Kong6607dae2014-06-10 16:07:45 -0700861 settings.clearGpsData();
Michael Kolb8872c232013-01-29 10:33:22 -0800862
Angus Kong6607dae2014-06-10 16:07:45 -0700863 boolean hasLatLon = false;
864 double lat;
865 double lon;
Michael Kolb8872c232013-01-29 10:33:22 -0800866 // Set GPS location.
867 if (loc != null) {
Angus Kong6607dae2014-06-10 16:07:45 -0700868 lat = loc.getLatitude();
869 lon = loc.getLongitude();
870 hasLatLon = (lat != 0.0d) || (lon != 0.0d);
871 }
Michael Kolb8872c232013-01-29 10:33:22 -0800872
Angus Kong6607dae2014-06-10 16:07:45 -0700873 if (!hasLatLon) {
874 // We always encode GpsTimeStamp even if the GPS location is not
875 // available.
876 settings.setGpsData(
877 new CameraSettings.GpsData(0f, 0f, 0f, System.currentTimeMillis() / 1000, null)
Sascha Haeberling59c784b2014-08-05 10:53:08 -0700878 );
Angus Kong6607dae2014-06-10 16:07:45 -0700879 } else {
880 Log.d(TAG, "Set gps location");
881 // for NETWORK_PROVIDER location provider, we may have
882 // no altitude information, but the driver needs it, so
883 // we fake one.
884 // Location.getTime() is UTC in milliseconds.
885 // gps-timestamp is UTC in seconds.
886 long utcTimeSeconds = loc.getTime() / 1000;
887 settings.setGpsData(new CameraSettings.GpsData(loc.getLatitude(), loc.getLongitude(),
888 (loc.hasAltitude() ? loc.getAltitude() : 0),
889 (utcTimeSeconds != 0 ? utcTimeSeconds : System.currentTimeMillis()),
890 loc.getProvider().toUpperCase()));
Michael Kolb8872c232013-01-29 10:33:22 -0800891 }
892 }
893
ztenghui16a35202013-09-23 11:35:36 -0700894 /**
895 * For still image capture, we need to get the right fps range such that the
896 * camera can slow down the framerate to allow for less-noisy/dark
897 * viewfinder output in dark conditions.
898 *
Angus Kong88289042014-04-22 16:39:42 -0700899 * @param capabilities Camera's capabilities.
ztenghui16a35202013-09-23 11:35:36 -0700900 * @return null if no appropiate fps range can't be found. Otherwise, return
901 * the right range.
902 */
Angus Kong88289042014-04-22 16:39:42 -0700903 public static int[] getPhotoPreviewFpsRange(CameraCapabilities capabilities) {
904 return getPhotoPreviewFpsRange(capabilities.getSupportedPreviewFpsRange());
Ruben Brunk2a74dfd2013-10-29 18:28:32 -0700905 }
906
907 public static int[] getPhotoPreviewFpsRange(List<int[]> frameRates) {
ztenghui16a35202013-09-23 11:35:36 -0700908 if (frameRates.size() == 0) {
909 Log.e(TAG, "No suppoted frame rates returned!");
910 return null;
911 }
912
913 // Find the lowest min rate in supported ranges who can cover 30fps.
914 int lowestMinRate = MAX_PREVIEW_FPS_TIMES_1000;
915 for (int[] rate : frameRates) {
Angus Kong831347d2014-06-16 16:07:28 -0700916 int minFps = rate[0];
917 int maxFps = rate[1];
ztenghui16a35202013-09-23 11:35:36 -0700918 if (maxFps >= PREFERRED_PREVIEW_FPS_TIMES_1000 &&
919 minFps <= PREFERRED_PREVIEW_FPS_TIMES_1000 &&
920 minFps < lowestMinRate) {
921 lowestMinRate = minFps;
922 }
923 }
924
925 // Find all the modes with the lowest min rate found above, the pick the
926 // one with highest max rate.
927 int resultIndex = -1;
928 int highestMaxRate = 0;
929 for (int i = 0; i < frameRates.size(); i++) {
930 int[] rate = frameRates.get(i);
Angus Kong831347d2014-06-16 16:07:28 -0700931 int minFps = rate[0];
932 int maxFps = rate[1];
ztenghui16a35202013-09-23 11:35:36 -0700933 if (minFps == lowestMinRate && highestMaxRate < maxFps) {
934 highestMaxRate = maxFps;
935 resultIndex = i;
936 }
937 }
938
939 if (resultIndex >= 0) {
940 return frameRates.get(resultIndex);
941 }
942 Log.e(TAG, "Can't find an appropiate frame rate range!");
943 return null;
944 }
Angus Kongd82eae22013-06-11 12:00:15 -0700945
Angus Kong6607dae2014-06-10 16:07:45 -0700946 public static int[] getMaxPreviewFpsRange(List<int[]> frameRates) {
Angus Kongd82eae22013-06-11 12:00:15 -0700947 if (frameRates != null && frameRates.size() > 0) {
948 // The list is sorted. Return the last element.
949 return frameRates.get(frameRates.size() - 1);
950 }
951 return new int[0];
952 }
953
Angus Kong20fad242013-11-11 18:23:46 -0800954 public static void throwIfCameraDisabled(Context context) throws CameraDisabledException {
955 // Check if device policy has disabled the camera.
956 DevicePolicyManager dpm =
957 (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
958 if (dpm.getCameraDisabled(null)) {
959 throw new CameraDisabledException();
960 }
961 }
962
Doris Liu213a4a02014-02-04 16:57:55 -0800963 /**
964 * Generates a 1d Gaussian mask of the input array size, and store the mask
965 * in the input array.
966 *
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700967 * @param mask empty array of size n, where n will be used as the size of
968 * the Gaussian mask, and the array will be populated with the
969 * values of the mask.
Doris Liu213a4a02014-02-04 16:57:55 -0800970 */
971 private static void getGaussianMask(float[] mask) {
972 int len = mask.length;
973 int mid = len / 2;
974 float sigma = len;
975 float sum = 0;
976 for (int i = 0; i <= mid; i++) {
Sascha Haeberling1332fc02014-10-28 10:18:31 -0700977 float ex = (float) Math.exp(-(i - mid) * (i - mid) / (mid * mid))
Doris Liu213a4a02014-02-04 16:57:55 -0800978 / (2 * sigma * sigma);
979 int symmetricIndex = len - 1 - i;
980 mask[i] = ex;
981 mask[symmetricIndex] = ex;
982 sum += mask[i];
983 if (i != symmetricIndex) {
984 sum += mask[symmetricIndex];
985 }
986 }
987
988 for (int i = 0; i < mask.length; i++) {
989 mask[i] /= sum;
990 }
991
992 }
993
994 /**
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700995 * Add two pixels together where the second pixel will be applied with a
996 * weight.
Doris Liu213a4a02014-02-04 16:57:55 -0800997 *
998 * @param pixel pixel color value of weight 1
999 * @param newPixel second pixel color value where the weight will be applied
Sascha Haeberlingf2627902014-09-02 14:20:57 -07001000 * @param weight a float weight that will be applied to the second pixel
1001 * color
Doris Liu213a4a02014-02-04 16:57:55 -08001002 * @return the weighted addition of the two pixels
1003 */
1004 public static int addPixel(int pixel, int newPixel, float weight) {
Sascha Haeberlingf2627902014-09-02 14:20:57 -07001005 // TODO: scale weight to [0, 1024] to avoid casting to float and back to
1006 // int.
Sascha Haeberlinga7cbfc02014-02-14 11:06:03 +01001007 int r = ((pixel & 0x00ff0000) + (int) ((newPixel & 0x00ff0000) * weight)) & 0x00ff0000;
1008 int g = ((pixel & 0x0000ff00) + (int) ((newPixel & 0x0000ff00) * weight)) & 0x0000ff00;
1009 int b = ((pixel & 0x000000ff) + (int) ((newPixel & 0x000000ff) * weight)) & 0x000000ff;
Doris Liu213a4a02014-02-04 16:57:55 -08001010 return 0xff000000 | r | g | b;
1011 }
1012
1013 /**
Sascha Haeberlingf2627902014-09-02 14:20:57 -07001014 * Apply blur to the input image represented in an array of colors and put
1015 * the output image, in the form of an array of colors, into the output
1016 * array.
Doris Liu213a4a02014-02-04 16:57:55 -08001017 *
1018 * @param src source array of colors
1019 * @param out output array of colors after the blur
1020 * @param w width of the image
1021 * @param h height of the image
1022 * @param size size of the Gaussian blur mask
1023 */
1024 public static void blur(int[] src, int[] out, int w, int h, int size) {
1025 float[] k = new float[size];
1026 int off = size / 2;
1027
1028 getGaussianMask(k);
1029
1030 int[] tmp = new int[src.length];
1031
Sascha Haeberlingf2627902014-09-02 14:20:57 -07001032 // Apply the 1d Gaussian mask horizontally to the image and put the
1033 // intermediat results in a temporary array.
Doris Liu213a4a02014-02-04 16:57:55 -08001034 int rowPointer = 0;
1035 for (int y = 0; y < h; y++) {
1036 for (int x = 0; x < w; x++) {
1037 int sum = 0;
1038 for (int i = 0; i < k.length; i++) {
1039 int dx = x + i - off;
Sascha Haeberlingf2627902014-09-02 14:20:57 -07001040 dx = clamp(dx, 0, w - 1);
Doris Liu213a4a02014-02-04 16:57:55 -08001041 sum = addPixel(sum, src[rowPointer + dx], k[i]);
1042 }
1043 tmp[x + rowPointer] = sum;
1044 }
1045 rowPointer += w;
1046 }
1047
1048 // Apply the 1d Gaussian mask vertically to the intermediate array, and
1049 // the final results will be stored in the output array.
1050 for (int x = 0; x < w; x++) {
1051 rowPointer = 0;
1052 for (int y = 0; y < h; y++) {
1053 int sum = 0;
1054 for (int i = 0; i < k.length; i++) {
1055 int dy = y + i - off;
1056 dy = clamp(dy, 0, h - 1);
1057 sum = addPixel(sum, tmp[dy * w + x], k[i]);
1058 }
1059 out[x + rowPointer] = sum;
1060 rowPointer += w;
1061 }
1062 }
1063 }
1064
Angus Kongc195e7a2014-02-20 16:56:37 -08001065 /**
1066 * Calculates a new dimension to fill the bound with the original aspect
1067 * ratio preserved.
1068 *
1069 * @param imageWidth The original width.
1070 * @param imageHeight The original height.
Sascha Haeberlingf2627902014-09-02 14:20:57 -07001071 * @param imageRotation The clockwise rotation in degrees of the image which
1072 * the original dimension comes from.
Angus Kongc195e7a2014-02-20 16:56:37 -08001073 * @param boundWidth The width of the bound.
1074 * @param boundHeight The height of the bound.
Angus Kongc195e7a2014-02-20 16:56:37 -08001075 * @returns The final width/height stored in Point.x/Point.y to fill the
Sascha Haeberlingf2627902014-09-02 14:20:57 -07001076 * bounds and preserve image aspect ratio.
Angus Kongc195e7a2014-02-20 16:56:37 -08001077 */
1078 public static Point resizeToFill(int imageWidth, int imageHeight, int imageRotation,
1079 int boundWidth, int boundHeight) {
1080 if (imageRotation % 180 != 0) {
1081 // Swap width and height.
1082 int savedWidth = imageWidth;
1083 imageWidth = imageHeight;
1084 imageHeight = savedWidth;
1085 }
1086 if (imageWidth == ImageData.SIZE_FULL
1087 || imageHeight == ImageData.SIZE_FULL) {
1088 imageWidth = boundWidth;
1089 imageHeight = boundHeight;
1090 }
1091
1092 Point p = new Point();
1093 p.x = boundWidth;
1094 p.y = boundHeight;
1095
1096 if (imageWidth * boundHeight > boundWidth * imageHeight) {
1097 p.y = imageHeight * p.x / imageWidth;
1098 } else {
1099 p.x = imageWidth * p.y / imageHeight;
1100 }
1101
1102 return p;
1103 }
1104
Michael Kolb8872c232013-01-29 10:33:22 -08001105 private static class ImageFileNamer {
Igor Murashkin160b0362013-10-14 14:57:30 -07001106 private final SimpleDateFormat mFormat;
Michael Kolb8872c232013-01-29 10:33:22 -08001107
1108 // The date (in milliseconds) used to generate the last name.
1109 private long mLastDate;
1110
1111 // Number of names generated for the same second.
1112 private int mSameSecondCount;
1113
1114 public ImageFileNamer(String format) {
1115 mFormat = new SimpleDateFormat(format);
1116 }
1117
1118 public String generateName(long dateTaken) {
1119 Date date = new Date(dateTaken);
1120 String result = mFormat.format(date);
1121
1122 // If the last name was generated for the same second,
1123 // we append _1, _2, etc to the name.
1124 if (dateTaken / 1000 == mLastDate / 1000) {
1125 mSameSecondCount++;
1126 result += "_" + mSameSecondCount;
1127 } else {
1128 mLastDate = dateTaken;
1129 mSameSecondCount = 0;
1130 }
1131
1132 return result;
1133 }
1134 }
Angus Kongb40738a2013-06-03 14:55:34 -07001135
Sascha Haeberlingb7639c62013-09-09 14:42:43 -07001136 public static void playVideo(Activity activity, Uri uri, String title) {
Angus Kongb40738a2013-06-03 14:55:34 -07001137 try {
Sascha Haeberlingc6da1a12014-11-06 09:50:51 -08001138 CameraActivity cameraActivity = (CameraActivity) activity;
Senpo Hube707312014-09-10 14:43:16 -07001139 boolean isSecureCamera = cameraActivity.isSecureCamera();
ztenghui98b2a282013-10-11 17:15:40 -07001140 if (!isSecureCamera) {
Spike Sprague4f93e192014-08-19 18:53:41 -07001141 Intent intent = IntentHelper.getVideoPlayerIntent(uri)
ztenghui98b2a282013-10-11 17:15:40 -07001142 .putExtra(Intent.EXTRA_TITLE, title)
1143 .putExtra(KEY_TREAT_UP_AS_BACK, true);
Senpo Hube707312014-09-10 14:43:16 -07001144 cameraActivity.launchActivityByIntent(intent);
ztenghui98b2a282013-10-11 17:15:40 -07001145 } else {
1146 // In order not to send out any intent to be intercepted and
1147 // show the lock screen immediately, we just let the secure
1148 // camera activity finish.
1149 activity.finish();
1150 }
Angus Kongb40738a2013-06-03 14:55:34 -07001151 } catch (ActivityNotFoundException e) {
Sascha Haeberlingb7639c62013-09-09 14:42:43 -07001152 Toast.makeText(activity, activity.getString(R.string.video_err),
Angus Kongb40738a2013-06-03 14:55:34 -07001153 Toast.LENGTH_SHORT).show();
1154 }
1155 }
Sascha Haeberlingfae11a12013-08-15 14:29:49 -07001156
1157 /**
1158 * Starts GMM with the given location shown. If this fails, and GMM could
1159 * not be found, we use a geo intent as a fallback.
1160 *
Sascha Haeberlingb7639c62013-09-09 14:42:43 -07001161 * @param activity the activity to use for launching the Maps intent.
Sascha Haeberlingfae11a12013-08-15 14:29:49 -07001162 * @param latLong a 2-element array containing {latitude/longitude}.
1163 */
Sascha Haeberlingb7639c62013-09-09 14:42:43 -07001164 public static void showOnMap(Activity activity, double[] latLong) {
Sascha Haeberlingfae11a12013-08-15 14:29:49 -07001165 try {
1166 // We don't use "geo:latitude,longitude" because it only centers
1167 // the MapView to the specified location, but we need a marker
1168 // for further operations (routing to/from).
1169 // The q=(lat, lng) syntax is suggested by geo-team.
1170 String uri = String.format(Locale.ENGLISH, "http://maps.google.com/maps?f=q&q=(%f,%f)",
1171 latLong[0], latLong[1]);
1172 ComponentName compName = new ComponentName(MAPS_PACKAGE_NAME,
1173 MAPS_CLASS_NAME);
1174 Intent mapsIntent = new Intent(Intent.ACTION_VIEW,
1175 Uri.parse(uri)).setComponent(compName);
Alan Newberger437a1862014-10-01 17:18:35 -07001176 mapsIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT);
Senpo Hu9f2b20a2014-08-29 16:27:03 -07001177 activity.startActivity(mapsIntent);
Sascha Haeberlingfae11a12013-08-15 14:29:49 -07001178 } catch (ActivityNotFoundException e) {
1179 // Use the "geo intent" if no GMM is installed
1180 Log.e(TAG, "GMM activity not found!", e);
1181 String url = String.format(Locale.ENGLISH, "geo:%f,%f", latLong[0], latLong[1]);
1182 Intent mapsIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
Sascha Haeberlingb7639c62013-09-09 14:42:43 -07001183 activity.startActivity(mapsIntent);
Sascha Haeberlingfae11a12013-08-15 14:29:49 -07001184 }
1185 }
Angus Kong7d2388d2013-09-18 23:56:01 -07001186
Angus Kongb21215a2013-09-20 18:41:46 -07001187 /**
1188 * Dumps the stack trace.
1189 *
1190 * @param level How many levels of the stack are dumped. 0 means all.
Sascha Haeberlingf2627902014-09-02 14:20:57 -07001191 * @return A {@link java.lang.String} of all the output with newline between
1192 * each.
Angus Kongb21215a2013-09-20 18:41:46 -07001193 */
Angus Kong7d2388d2013-09-18 23:56:01 -07001194 public static String dumpStackTrace(int level) {
1195 StackTraceElement[] elems = Thread.currentThread().getStackTrace();
1196 // Ignore the first 3 elements.
Angus Kongb21215a2013-09-20 18:41:46 -07001197 level = (level == 0 ? elems.length : Math.min(level + 3, elems.length));
Angus Kong7d2388d2013-09-18 23:56:01 -07001198 String ret = new String();
1199 for (int i = 3; i < level; i++) {
Angus Kongb21215a2013-09-20 18:41:46 -07001200 ret = ret + "\t" + elems[i].toString() + '\n';
Angus Kong7d2388d2013-09-18 23:56:01 -07001201 }
1202 return ret;
1203 }
Doris Liubd1b8f92014-01-03 17:59:51 -08001204
Doris Liubd1b8f92014-01-03 17:59:51 -08001205 /**
1206 * Gets the theme color of a specific mode.
1207 *
1208 * @param modeIndex index of the mode
1209 * @param context current context
1210 * @return theme color of the mode if input index is valid, otherwise 0
1211 */
1212 public static int getCameraThemeColorId(int modeIndex, Context context) {
1213
1214 // Find the theme color using id from the color array
1215 TypedArray colorRes = context.getResources()
1216 .obtainTypedArray(R.array.camera_mode_theme_color);
1217 if (modeIndex >= colorRes.length() || modeIndex < 0) {
1218 // Mode index not found
1219 Log.e(TAG, "Invalid mode index: " + modeIndex);
1220 return 0;
1221 }
1222 return colorRes.getResourceId(modeIndex, 0);
1223 }
1224
1225 /**
1226 * Gets the mode icon resource id of a specific mode.
1227 *
1228 * @param modeIndex index of the mode
1229 * @param context current context
1230 * @return icon resource id if the index is valid, otherwise 0
1231 */
1232 public static int getCameraModeIconResId(int modeIndex, Context context) {
1233 // Find the camera mode icon using id
1234 TypedArray cameraModesIcons = context.getResources()
1235 .obtainTypedArray(R.array.camera_mode_icon);
1236 if (modeIndex >= cameraModesIcons.length() || modeIndex < 0) {
1237 // Mode index not found
1238 Log.e(TAG, "Invalid mode index: " + modeIndex);
1239 return 0;
1240 }
1241 return cameraModesIcons.getResourceId(modeIndex, 0);
1242 }
1243
1244 /**
1245 * Gets the mode text of a specific mode.
1246 *
1247 * @param modeIndex index of the mode
1248 * @param context current context
1249 * @return mode text if the index is valid, otherwise a new empty string
1250 */
1251 public static String getCameraModeText(int modeIndex, Context context) {
1252 // Find the camera mode icon using id
1253 String[] cameraModesText = context.getResources()
1254 .getStringArray(R.array.camera_mode_text);
1255 if (modeIndex < 0 || modeIndex >= cameraModesText.length) {
1256 Log.e(TAG, "Invalid mode index: " + modeIndex);
1257 return new String();
1258 }
1259 return cameraModesText[modeIndex];
1260 }
Erin Dahlgrenfecd7232014-01-16 13:29:42 -08001261
1262 /**
Spike Sprague79718f62014-01-28 18:48:22 -08001263 * Gets the mode content description of a specific mode.
1264 *
1265 * @param modeIndex index of the mode
1266 * @param context current context
Sascha Haeberlingf2627902014-09-02 14:20:57 -07001267 * @return mode content description if the index is valid, otherwise a new
1268 * empty string
Spike Sprague79718f62014-01-28 18:48:22 -08001269 */
1270 public static String getCameraModeContentDescription(int modeIndex, Context context) {
1271 String[] cameraModesDesc = context.getResources()
1272 .getStringArray(R.array.camera_mode_content_description);
1273 if (modeIndex < 0 || modeIndex >= cameraModesDesc.length) {
1274 Log.e(TAG, "Invalid mode index: " + modeIndex);
1275 return new String();
1276 }
1277 return cameraModesDesc[modeIndex];
1278 }
1279
1280 /**
Erin Dahlgrenfecd7232014-01-16 13:29:42 -08001281 * Gets the shutter icon res id for a specific mode.
1282 *
1283 * @param modeIndex index of the mode
1284 * @param context current context
1285 * @return mode shutter icon id if the index is valid, otherwise 0.
1286 */
1287 public static int getCameraShutterIconId(int modeIndex, Context context) {
1288 // Find the camera mode icon using id
1289 TypedArray shutterIcons = context.getResources()
Sascha Haeberlingf2627902014-09-02 14:20:57 -07001290 .obtainTypedArray(R.array.camera_mode_shutter_icon);
Erin Dahlgrenfecd7232014-01-16 13:29:42 -08001291 if (modeIndex < 0 || modeIndex >= shutterIcons.length()) {
1292 Log.e(TAG, "Invalid mode index: " + modeIndex);
Alan Newberger7bc335f2014-07-23 11:25:07 -07001293 throw new IllegalStateException("Invalid mode index: " + modeIndex);
Erin Dahlgrenfecd7232014-01-16 13:29:42 -08001294 }
1295 return shutterIcons.getResourceId(modeIndex, 0);
1296 }
Doris Liu213a4a02014-02-04 16:57:55 -08001297
1298 /**
1299 * Gets the parent mode that hosts a specific mode in nav drawer.
1300 *
1301 * @param modeIndex index of the mode
1302 * @param context current context
1303 * @return mode id if the index is valid, otherwise 0
1304 */
1305 public static int getCameraModeParentModeId(int modeIndex, Context context) {
1306 // Find the camera mode icon using id
1307 int[] cameraModeParent = context.getResources()
1308 .getIntArray(R.array.camera_mode_nested_in_nav_drawer);
1309 if (modeIndex < 0 || modeIndex >= cameraModeParent.length) {
1310 Log.e(TAG, "Invalid mode index: " + modeIndex);
1311 return 0;
1312 }
1313 return cameraModeParent[modeIndex];
1314 }
Doris Liub520b972014-02-14 14:14:46 -08001315
1316 /**
1317 * Gets the mode cover icon resource id of a specific mode.
1318 *
1319 * @param modeIndex index of the mode
1320 * @param context current context
1321 * @return icon resource id if the index is valid, otherwise 0
1322 */
1323 public static int getCameraModeCoverIconResId(int modeIndex, Context context) {
1324 // Find the camera mode icon using id
1325 TypedArray cameraModesIcons = context.getResources()
1326 .obtainTypedArray(R.array.camera_mode_cover_icon);
1327 if (modeIndex >= cameraModesIcons.length() || modeIndex < 0) {
1328 // Mode index not found
1329 Log.e(TAG, "Invalid mode index: " + modeIndex);
1330 return 0;
1331 }
1332 return cameraModesIcons.getResourceId(modeIndex, 0);
1333 }
Sascha Haeberling59c784b2014-08-05 10:53:08 -07001334
1335 /**
1336 * Gets the number of cores available in this device, across all processors.
1337 * Requires: Ability to peruse the filesystem at "/sys/devices/system/cpu"
1338 * <p>
1339 * Source: http://stackoverflow.com/questions/7962155/
1340 *
1341 * @return The number of cores, or 1 if failed to get result
1342 */
1343 public static int getNumCpuCores() {
1344 // Private Class to display only CPU devices in the directory listing
1345 class CpuFilter implements java.io.FileFilter {
1346 @Override
1347 public boolean accept(java.io.File pathname) {
1348 // Check if filename is "cpu", followed by a single digit number
1349 if (java.util.regex.Pattern.matches("cpu[0-9]+", pathname.getName())) {
1350 return true;
1351 }
1352 return false;
1353 }
1354 }
1355
1356 try {
1357 // Get directory containing CPU info
1358 java.io.File dir = new java.io.File("/sys/devices/system/cpu/");
1359 // Filter to only list the devices we care about
1360 java.io.File[] files = dir.listFiles(new CpuFilter());
1361 // Return the number of cores (virtual CPU devices)
1362 return files.length;
1363 } catch (Exception e) {
1364 // Default to return 1 core
1365 Log.e(TAG, "Failed to count number of cores, defaulting to 1", e);
1366 return 1;
1367 }
1368 }
Sascha Haeberlinga2dd9ea2014-08-15 18:45:15 -07001369
1370 /**
1371 * Given the device orientation and Camera2 characteristics, this returns
1372 * the required JPEG rotation for this camera.
1373 *
1374 * @param deviceOrientationDegrees the device orientation in degrees.
1375 * @return The JPEG orientation in degrees.
1376 */
1377 public static int getJpegRotation(int deviceOrientationDegrees,
1378 CameraCharacteristics characteristics) {
1379 if (deviceOrientationDegrees == OrientationEventListener.ORIENTATION_UNKNOWN) {
1380 return 0;
1381 }
1382 int facing = characteristics.get(CameraCharacteristics.LENS_FACING);
1383 int sensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
1384 if (facing == CameraMetadata.LENS_FACING_FRONT) {
1385 return (sensorOrientation + deviceOrientationDegrees) % 360;
1386 } else {
1387 return (sensorOrientation - deviceOrientationDegrees + 360) % 360;
1388 }
1389 }
Michael Kolb8872c232013-01-29 10:33:22 -08001390}