blob: 627b6bf0165a686d550d7fe9a28f8856b9e2d78b [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;
33import android.graphics.Rect;
34import android.graphics.RectF;
Sascha Haeberlinga2dd9ea2014-08-15 18:45:15 -070035import android.hardware.camera2.CameraCharacteristics;
36import android.hardware.camera2.CameraMetadata;
Michael Kolb8872c232013-01-29 10:33:22 -080037import android.location.Location;
38import android.net.Uri;
Michael Kolb8872c232013-01-29 10:33:22 -080039import android.os.ParcelFileDescriptor;
40import android.telephony.TelephonyManager;
41import android.util.DisplayMetrics;
Doris Liu213a4a02014-02-04 16:57:55 -080042import android.util.FloatMath;
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 Haeberlingf2627902014-09-02 14:20:57 -0700206 int minSideLength, int maxNumOfPixels) {
Michael Kolb8872c232013-01-29 10:33:22 -0800207 int initialSize = computeInitialSampleSize(options, minSideLength,
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700208 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()) {
303 new AlertDialog.Builder(activity)
304 .setCancelable(false)
305 .setTitle(R.string.camera_error_title)
306 .setMessage(msgId)
307 .setNeutralButton(R.string.dialog_ok, buttonListener)
308 .setIcon(out.resourceId)
309 .show();
310 }
Michael Kolb8872c232013-01-29 10:33:22 -0800311 }
312
313 public static <T> T checkNotNull(T object) {
Sascha Haeberling846d3ab2014-02-04 12:48:55 +0100314 if (object == null) {
315 throw new NullPointerException();
316 }
Michael Kolb8872c232013-01-29 10:33:22 -0800317 return object;
318 }
319
320 public static boolean equals(Object a, Object b) {
321 return (a == b) || (a == null ? false : a.equals(b));
322 }
323
324 public static int nextPowerOf2(int n) {
325 n -= 1;
326 n |= n >>> 16;
327 n |= n >>> 8;
328 n |= n >>> 4;
329 n |= n >>> 2;
330 n |= n >>> 1;
331 return n + 1;
332 }
333
334 public static float distance(float x, float y, float sx, float sy) {
335 float dx = x - sx;
336 float dy = y - sy;
Sascha Haeberling638e6f02013-09-18 14:28:51 -0700337 return (float) Math.sqrt(dx * dx + dy * dy);
Michael Kolb8872c232013-01-29 10:33:22 -0800338 }
339
340 public static int clamp(int x, int min, int max) {
Sascha Haeberling846d3ab2014-02-04 12:48:55 +0100341 if (x > max) {
342 return max;
343 }
344 if (x < min) {
345 return min;
346 }
Michael Kolb8872c232013-01-29 10:33:22 -0800347 return x;
348 }
349
Igor Murashkin160b0362013-10-14 14:57:30 -0700350 public static float clamp(float x, float min, float max) {
Sascha Haeberling846d3ab2014-02-04 12:48:55 +0100351 if (x > max) {
352 return max;
353 }
354 if (x < min) {
355 return min;
356 }
Igor Murashkin160b0362013-10-14 14:57:30 -0700357 return x;
358 }
359
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700360 /**
361 * Linear interpolation between a and b by the fraction t. t = 0 --> a, t =
362 * 1 --> b.
363 */
364 public static float lerp(float a, float b, float t) {
365 return a + t * (b - a);
366 }
367
368 /**
369 * Given a size, return the largest size with the given aspectRatio that
370 * maximally fits into the bounding rectangle of the original Size.
371 *
372 * @param size the original Size to crop
373 * @param aspectRatio the target aspect ratio
374 * @return the largest Size with the given aspect ratio that is smaller than
375 * or equal to the original Size.
376 */
377 public static Size constrainToAspectRatio(Size size, float aspectRatio) {
378 float width = size.getWidth();
379 float height = size.getHeight();
380
381 float currentAspectRatio = width * 1.0f / height;
382
383 if (currentAspectRatio > aspectRatio) {
384 // chop longer side
385 if (width > height) {
386 width = height * aspectRatio;
387 } else {
388 height = width / aspectRatio;
389 }
390 } else if (currentAspectRatio < aspectRatio) {
391 // chop shorter side
392 if (width < height) {
393 width = height * aspectRatio;
394 } else {
395 height = width / aspectRatio;
396 }
397 }
398
399 return new Size((int) width, (int) height);
400 }
401
Sascha Haeberling846d3ab2014-02-04 12:48:55 +0100402 public static int getDisplayRotation(Context context) {
403 WindowManager windowManager = (WindowManager) context
404 .getSystemService(Context.WINDOW_SERVICE);
405 int rotation = windowManager.getDefaultDisplay()
Michael Kolb8872c232013-01-29 10:33:22 -0800406 .getRotation();
407 switch (rotation) {
Sascha Haeberling59c784b2014-08-05 10:53:08 -0700408 case Surface.ROTATION_0:
409 return 0;
410 case Surface.ROTATION_90:
411 return 90;
412 case Surface.ROTATION_180:
413 return 180;
414 case Surface.ROTATION_270:
415 return 270;
Michael Kolb8872c232013-01-29 10:33:22 -0800416 }
417 return 0;
418 }
419
Doris Liu0ba8eaa2013-10-16 12:51:02 -0700420 /**
421 * Calculate the default orientation of the device based on the width and
422 * height of the display when rotation = 0 (i.e. natural width and height)
Sascha Haeberling59c784b2014-08-05 10:53:08 -0700423 *
Doris Liu8dc878f2014-05-05 14:10:34 -0700424 * @param context current context
Doris Liu0ba8eaa2013-10-16 12:51:02 -0700425 * @return whether the default orientation of the device is portrait
426 */
Doris Liu8dc878f2014-05-05 14:10:34 -0700427 public static boolean isDefaultToPortrait(Context context) {
428 Display currentDisplay = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE))
429 .getDefaultDisplay();
Doris Liu0ba8eaa2013-10-16 12:51:02 -0700430 Point displaySize = new Point();
431 currentDisplay.getSize(displaySize);
432 int orientation = currentDisplay.getRotation();
433 int naturalWidth, naturalHeight;
434 if (orientation == Surface.ROTATION_0 || orientation == Surface.ROTATION_180) {
435 naturalWidth = displaySize.x;
436 naturalHeight = displaySize.y;
437 } else {
438 naturalWidth = displaySize.y;
439 naturalHeight = displaySize.x;
440 }
441 return naturalWidth < naturalHeight;
442 }
443
Michael Kolb8872c232013-01-29 10:33:22 -0800444 public static int roundOrientation(int orientation, int orientationHistory) {
445 boolean changeOrientation = false;
446 if (orientationHistory == OrientationEventListener.ORIENTATION_UNKNOWN) {
447 changeOrientation = true;
448 } else {
449 int dist = Math.abs(orientation - orientationHistory);
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700450 dist = Math.min(dist, 360 - dist);
451 changeOrientation = (dist >= 45 + ORIENTATION_HYSTERESIS);
Michael Kolb8872c232013-01-29 10:33:22 -0800452 }
453 if (changeOrientation) {
454 return ((orientation + 45) / 90 * 90) % 360;
455 }
456 return orientationHistory;
457 }
458
Angus Kong88289042014-04-22 16:39:42 -0700459 private static Size getDefaultDisplaySize(Context context) {
Sascha Haeberling846d3ab2014-02-04 12:48:55 +0100460 WindowManager windowManager = (WindowManager) context
461 .getSystemService(Context.WINDOW_SERVICE);
Angus Kong88289042014-04-22 16:39:42 -0700462 Point res = new Point();
463 windowManager.getDefaultDisplay().getSize(res);
464 return new Size(res);
Michael Kolb8872c232013-01-29 10:33:22 -0800465 }
466
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700467 public static com.android.ex.camera2.portability.Size getOptimalPreviewSize(Context context,
468 List<com.android.ex.camera2.portability.Size> sizes, double targetRatio) {
469 int optimalPickIndex = getOptimalPreviewSizeIndex(context, Size.convert(sizes),
470 targetRatio);
471 if (optimalPickIndex == -1) {
472 return null;
473 } else {
474 return sizes.get(optimalPickIndex);
475 }
Ruben Brunk714d4d02013-10-09 16:01:16 -0700476 }
477
Angus Kong88289042014-04-22 16:39:42 -0700478 public static int getOptimalPreviewSizeIndex(Context context,
479 List<Size> sizes, double targetRatio) {
Ruben Brunk714d4d02013-10-09 16:01:16 -0700480 // Use a very small tolerance because we want an exact match.
481 final double ASPECT_TOLERANCE = 0.01;
Sascha Haeberling846d3ab2014-02-04 12:48:55 +0100482 if (sizes == null) {
483 return -1;
484 }
Ruben Brunk714d4d02013-10-09 16:01:16 -0700485
486 int optimalSizeIndex = -1;
Michael Kolb8872c232013-01-29 10:33:22 -0800487 double minDiff = Double.MAX_VALUE;
488
489 // Because of bugs of overlay and layout, we sometimes will try to
490 // layout the viewfinder in the portrait orientation and thus get the
491 // wrong size of preview surface. When we change the preview size, the
492 // new overlay will be created before the old one closed, which causes
493 // an exception. For now, just get the screen size.
Angus Kong88289042014-04-22 16:39:42 -0700494 Size defaultDisplaySize = getDefaultDisplaySize(context);
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700495 int targetHeight = Math.min(defaultDisplaySize.getWidth(), defaultDisplaySize.getHeight());
Michael Kolb8872c232013-01-29 10:33:22 -0800496 // Try to find an size match aspect ratio and size
Angus Kong88289042014-04-22 16:39:42 -0700497 for (int i = 0; i < sizes.size(); i++) {
498 Size size = sizes.get(i);
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700499 double ratio = (double) size.getWidth() / size.getHeight();
Sascha Haeberling846d3ab2014-02-04 12:48:55 +0100500 if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) {
501 continue;
502 }
Igor Murashkincf2a8182014-08-25 13:21:26 -0700503
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700504 double heightDiff = Math.abs(size.getHeight() - targetHeight);
Igor Murashkincf2a8182014-08-25 13:21:26 -0700505 if (heightDiff < minDiff) {
Ruben Brunk714d4d02013-10-09 16:01:16 -0700506 optimalSizeIndex = i;
Igor Murashkincf2a8182014-08-25 13:21:26 -0700507 minDiff = heightDiff;
508 } else if (heightDiff == minDiff) {
509 // Prefer resolutions smaller-than-display when an equally close
510 // larger-than-display resolution is available
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700511 if (size.getHeight() < targetHeight) {
Igor Murashkincf2a8182014-08-25 13:21:26 -0700512 optimalSizeIndex = i;
513 minDiff = heightDiff;
514 }
Michael Kolb8872c232013-01-29 10:33:22 -0800515 }
516 }
517 // Cannot find the one match the aspect ratio. This should not happen.
518 // Ignore the requirement.
Ruben Brunk714d4d02013-10-09 16:01:16 -0700519 if (optimalSizeIndex == -1) {
Michael Kolb8872c232013-01-29 10:33:22 -0800520 Log.w(TAG, "No preview size match the aspect ratio");
521 minDiff = Double.MAX_VALUE;
Angus Kong88289042014-04-22 16:39:42 -0700522 for (int i = 0; i < sizes.size(); i++) {
523 Size size = sizes.get(i);
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700524 if (Math.abs(size.getHeight() - targetHeight) < minDiff) {
Ruben Brunk714d4d02013-10-09 16:01:16 -0700525 optimalSizeIndex = i;
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700526 minDiff = Math.abs(size.getHeight() - targetHeight);
Michael Kolb8872c232013-01-29 10:33:22 -0800527 }
528 }
529 }
Ruben Brunk714d4d02013-10-09 16:01:16 -0700530 return optimalSizeIndex;
Michael Kolb8872c232013-01-29 10:33:22 -0800531 }
532
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700533 /** Returns the largest picture size which matches the given aspect ratio. */
534 public static com.android.ex.camera2.portability.Size getOptimalVideoSnapshotPictureSize(
535 List<com.android.ex.camera2.portability.Size> sizes, double targetRatio) {
Michael Kolb8872c232013-01-29 10:33:22 -0800536 // Use a very small tolerance because we want an exact match.
537 final double ASPECT_TOLERANCE = 0.001;
Sascha Haeberling846d3ab2014-02-04 12:48:55 +0100538 if (sizes == null) {
539 return null;
540 }
Michael Kolb8872c232013-01-29 10:33:22 -0800541
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700542 com.android.ex.camera2.portability.Size optimalSize = null;
Michael Kolb8872c232013-01-29 10:33:22 -0800543
544 // Try to find a size matches aspect ratio and has the largest width
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700545 for (com.android.ex.camera2.portability.Size size : sizes) {
Angus Kong00b7b102014-04-24 15:46:52 -0700546 double ratio = (double) size.width() / size.height();
Sascha Haeberling846d3ab2014-02-04 12:48:55 +0100547 if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) {
548 continue;
549 }
Angus Kong00b7b102014-04-24 15:46:52 -0700550 if (optimalSize == null || size.width() > optimalSize.width()) {
Michael Kolb8872c232013-01-29 10:33:22 -0800551 optimalSize = size;
552 }
553 }
554
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700555 // Cannot find one that matches the aspect ratio. This should not
556 // happen. Ignore the requirement.
Michael Kolb8872c232013-01-29 10:33:22 -0800557 if (optimalSize == null) {
558 Log.w(TAG, "No picture size match the aspect ratio");
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700559 for (com.android.ex.camera2.portability.Size size : sizes) {
Angus Kong00b7b102014-04-24 15:46:52 -0700560 if (optimalSize == null || size.width() > optimalSize.width()) {
Michael Kolb8872c232013-01-29 10:33:22 -0800561 optimalSize = size;
562 }
563 }
564 }
565 return optimalSize;
566 }
567
Michael Kolb8872c232013-01-29 10:33:22 -0800568 /**
569 * Returns whether the device is voice-capable (meaning, it can do MMS).
570 */
571 public static boolean isMmsCapable(Context context) {
572 TelephonyManager telephonyManager = (TelephonyManager)
573 context.getSystemService(Context.TELEPHONY_SERVICE);
574 if (telephonyManager == null) {
575 return false;
576 }
577
578 try {
579 Class<?> partypes[] = new Class[0];
580 Method sIsVoiceCapable = TelephonyManager.class.getMethod(
581 "isVoiceCapable", partypes);
582
583 Object arglist[] = new Object[0];
584 Object retobj = sIsVoiceCapable.invoke(telephonyManager, arglist);
585 return (Boolean) retobj;
586 } catch (java.lang.reflect.InvocationTargetException ite) {
587 // Failure, must be another device.
588 // Assume that it is voice capable.
589 } catch (IllegalAccessException iae) {
590 // Failure, must be an other device.
591 // Assume that it is voice capable.
592 } catch (NoSuchMethodException nsme) {
593 }
594 return true;
595 }
596
597 // This is for test only. Allow the camera to launch the specific camera.
598 public static int getCameraFacingIntentExtras(Activity currentActivity) {
599 int cameraId = -1;
600
601 int intentCameraId =
Angus Kongb50b5cb2013-08-09 14:55:20 -0700602 currentActivity.getIntent().getIntExtra(CameraUtil.EXTRAS_CAMERA_FACING, -1);
Michael Kolb8872c232013-01-29 10:33:22 -0800603
604 if (isFrontCameraIntent(intentCameraId)) {
605 // Check if the front camera exist
Angus Kong20fad242013-11-11 18:23:46 -0800606 int frontCameraId = ((CameraActivity) currentActivity).getCameraProvider()
607 .getFirstFrontCameraId();
Michael Kolb8872c232013-01-29 10:33:22 -0800608 if (frontCameraId != -1) {
609 cameraId = frontCameraId;
610 }
611 } else if (isBackCameraIntent(intentCameraId)) {
612 // Check if the back camera exist
Angus Kong20fad242013-11-11 18:23:46 -0800613 int backCameraId = ((CameraActivity) currentActivity).getCameraProvider()
614 .getFirstBackCameraId();
Michael Kolb8872c232013-01-29 10:33:22 -0800615 if (backCameraId != -1) {
616 cameraId = backCameraId;
617 }
618 }
619 return cameraId;
620 }
621
622 private static boolean isFrontCameraIntent(int intentCameraId) {
623 return (intentCameraId == android.hardware.Camera.CameraInfo.CAMERA_FACING_FRONT);
624 }
625
626 private static boolean isBackCameraIntent(int intentCameraId) {
627 return (intentCameraId == android.hardware.Camera.CameraInfo.CAMERA_FACING_BACK);
628 }
629
630 private static int sLocation[] = new int[2];
631
632 // This method is not thread-safe.
633 public static boolean pointInView(float x, float y, View v) {
634 v.getLocationInWindow(sLocation);
635 return x >= sLocation[0] && x < (sLocation[0] + v.getWidth())
636 && y >= sLocation[1] && y < (sLocation[1] + v.getHeight());
637 }
638
639 public static int[] getRelativeLocation(View reference, View view) {
640 reference.getLocationInWindow(sLocation);
641 int referenceX = sLocation[0];
642 int referenceY = sLocation[1];
643 view.getLocationInWindow(sLocation);
644 sLocation[0] -= referenceX;
645 sLocation[1] -= referenceY;
646 return sLocation;
647 }
648
649 public static boolean isUriValid(Uri uri, ContentResolver resolver) {
Sascha Haeberling846d3ab2014-02-04 12:48:55 +0100650 if (uri == null) {
651 return false;
652 }
Michael Kolb8872c232013-01-29 10:33:22 -0800653
654 try {
655 ParcelFileDescriptor pfd = resolver.openFileDescriptor(uri, "r");
656 if (pfd == null) {
657 Log.e(TAG, "Fail to open URI. URI=" + uri);
658 return false;
659 }
660 pfd.close();
661 } catch (IOException ex) {
662 return false;
663 }
664 return true;
665 }
666
Michael Kolb8872c232013-01-29 10:33:22 -0800667 public static void dumpRect(RectF rect, String msg) {
668 Log.v(TAG, msg + "=(" + rect.left + "," + rect.top
669 + "," + rect.right + "," + rect.bottom + ")");
670 }
671
672 public static void rectFToRect(RectF rectF, Rect rect) {
673 rect.left = Math.round(rectF.left);
674 rect.top = Math.round(rectF.top);
675 rect.right = Math.round(rectF.right);
676 rect.bottom = Math.round(rectF.bottom);
677 }
678
Doris Liu36ebcb12013-10-28 14:44:24 -0700679 public static Rect rectFToRect(RectF rectF) {
680 Rect rect = new Rect();
681 rectFToRect(rectF, rect);
682 return rect;
683 }
684
685 public static RectF rectToRectF(Rect r) {
686 return new RectF(r.left, r.top, r.right, r.bottom);
687 }
688
Michael Kolb8872c232013-01-29 10:33:22 -0800689 public static void prepareMatrix(Matrix matrix, boolean mirror, int displayOrientation,
690 int viewWidth, int viewHeight) {
691 // Need mirror for front camera.
692 matrix.setScale(mirror ? -1 : 1, 1);
693 // This is the value for android.hardware.Camera.setDisplayOrientation.
694 matrix.postRotate(displayOrientation);
695 // Camera driver coordinates range from (-1000, -1000) to (1000, 1000).
696 // UI coordinates range from (0, 0) to (width, height).
697 matrix.postScale(viewWidth / 2000f, viewHeight / 2000f);
698 matrix.postTranslate(viewWidth / 2f, viewHeight / 2f);
699 }
700
Doris Liu36ebcb12013-10-28 14:44:24 -0700701 public static void prepareMatrix(Matrix matrix, boolean mirror, int displayOrientation,
Sascha Haeberling59c784b2014-08-05 10:53:08 -0700702 Rect previewRect) {
Doris Liu36ebcb12013-10-28 14:44:24 -0700703 // Need mirror for front camera.
704 matrix.setScale(mirror ? -1 : 1, 1);
705 // This is the value for android.hardware.Camera.setDisplayOrientation.
706 matrix.postRotate(displayOrientation);
707
708 // Camera driver coordinates range from (-1000, -1000) to (1000, 1000).
709 // We need to map camera driver coordinates to preview rect coordinates
710 Matrix mapping = new Matrix();
711 mapping.setRectToRect(new RectF(-1000, -1000, 1000, 1000), rectToRectF(previewRect),
712 Matrix.ScaleToFit.FILL);
713 matrix.setConcat(mapping, matrix);
714 }
715
Michael Kolb8872c232013-01-29 10:33:22 -0800716 public static String createJpegName(long dateTaken) {
717 synchronized (sImageFileNamer) {
718 return sImageFileNamer.generateName(dateTaken);
719 }
720 }
721
722 public static void broadcastNewPicture(Context context, Uri uri) {
723 context.sendBroadcast(new Intent(ACTION_NEW_PICTURE, uri));
724 // Keep compatibility
725 context.sendBroadcast(new Intent("com.android.camera.NEW_PICTURE", uri));
726 }
727
728 public static void fadeIn(View view, float startAlpha, float endAlpha, long duration) {
Sascha Haeberling846d3ab2014-02-04 12:48:55 +0100729 if (view.getVisibility() == View.VISIBLE) {
730 return;
731 }
Michael Kolb8872c232013-01-29 10:33:22 -0800732
733 view.setVisibility(View.VISIBLE);
734 Animation animation = new AlphaAnimation(startAlpha, endAlpha);
735 animation.setDuration(duration);
736 view.startAnimation(animation);
737 }
738
Sascha Haeberling37f36112013-08-06 14:31:52 -0700739 /**
740 * Down-samples a jpeg byte array.
Sascha Haeberling59c784b2014-08-05 10:53:08 -0700741 *
Sascha Haeberling37f36112013-08-06 14:31:52 -0700742 * @param data a byte array of jpeg data
743 * @param downSampleFactor down-sample factor
744 * @return decoded and down-sampled bitmap
745 */
746 public static Bitmap downSample(final byte[] data, int downSampleFactor) {
747 final BitmapFactory.Options opts = new BitmapFactory.Options();
748 // Downsample the image
749 opts.inSampleSize = downSampleFactor;
750 return BitmapFactory.decodeByteArray(data, 0, data.length, opts);
751 }
752
Angus Kong6607dae2014-06-10 16:07:45 -0700753 public static void setGpsParameters(CameraSettings settings, Location loc) {
Michael Kolb8872c232013-01-29 10:33:22 -0800754 // Clear previous GPS location from the parameters.
Angus Kong6607dae2014-06-10 16:07:45 -0700755 settings.clearGpsData();
Michael Kolb8872c232013-01-29 10:33:22 -0800756
Angus Kong6607dae2014-06-10 16:07:45 -0700757 boolean hasLatLon = false;
758 double lat;
759 double lon;
Michael Kolb8872c232013-01-29 10:33:22 -0800760 // Set GPS location.
761 if (loc != null) {
Angus Kong6607dae2014-06-10 16:07:45 -0700762 lat = loc.getLatitude();
763 lon = loc.getLongitude();
764 hasLatLon = (lat != 0.0d) || (lon != 0.0d);
765 }
Michael Kolb8872c232013-01-29 10:33:22 -0800766
Angus Kong6607dae2014-06-10 16:07:45 -0700767 if (!hasLatLon) {
768 // We always encode GpsTimeStamp even if the GPS location is not
769 // available.
770 settings.setGpsData(
771 new CameraSettings.GpsData(0f, 0f, 0f, System.currentTimeMillis() / 1000, null)
Sascha Haeberling59c784b2014-08-05 10:53:08 -0700772 );
Angus Kong6607dae2014-06-10 16:07:45 -0700773 } else {
774 Log.d(TAG, "Set gps location");
775 // for NETWORK_PROVIDER location provider, we may have
776 // no altitude information, but the driver needs it, so
777 // we fake one.
778 // Location.getTime() is UTC in milliseconds.
779 // gps-timestamp is UTC in seconds.
780 long utcTimeSeconds = loc.getTime() / 1000;
781 settings.setGpsData(new CameraSettings.GpsData(loc.getLatitude(), loc.getLongitude(),
782 (loc.hasAltitude() ? loc.getAltitude() : 0),
783 (utcTimeSeconds != 0 ? utcTimeSeconds : System.currentTimeMillis()),
784 loc.getProvider().toUpperCase()));
Michael Kolb8872c232013-01-29 10:33:22 -0800785 }
786 }
787
ztenghui16a35202013-09-23 11:35:36 -0700788 /**
789 * For still image capture, we need to get the right fps range such that the
790 * camera can slow down the framerate to allow for less-noisy/dark
791 * viewfinder output in dark conditions.
792 *
Angus Kong88289042014-04-22 16:39:42 -0700793 * @param capabilities Camera's capabilities.
ztenghui16a35202013-09-23 11:35:36 -0700794 * @return null if no appropiate fps range can't be found. Otherwise, return
795 * the right range.
796 */
Angus Kong88289042014-04-22 16:39:42 -0700797 public static int[] getPhotoPreviewFpsRange(CameraCapabilities capabilities) {
798 return getPhotoPreviewFpsRange(capabilities.getSupportedPreviewFpsRange());
Ruben Brunk2a74dfd2013-10-29 18:28:32 -0700799 }
800
801 public static int[] getPhotoPreviewFpsRange(List<int[]> frameRates) {
ztenghui16a35202013-09-23 11:35:36 -0700802 if (frameRates.size() == 0) {
803 Log.e(TAG, "No suppoted frame rates returned!");
804 return null;
805 }
806
807 // Find the lowest min rate in supported ranges who can cover 30fps.
808 int lowestMinRate = MAX_PREVIEW_FPS_TIMES_1000;
809 for (int[] rate : frameRates) {
Angus Kong831347d2014-06-16 16:07:28 -0700810 int minFps = rate[0];
811 int maxFps = rate[1];
ztenghui16a35202013-09-23 11:35:36 -0700812 if (maxFps >= PREFERRED_PREVIEW_FPS_TIMES_1000 &&
813 minFps <= PREFERRED_PREVIEW_FPS_TIMES_1000 &&
814 minFps < lowestMinRate) {
815 lowestMinRate = minFps;
816 }
817 }
818
819 // Find all the modes with the lowest min rate found above, the pick the
820 // one with highest max rate.
821 int resultIndex = -1;
822 int highestMaxRate = 0;
823 for (int i = 0; i < frameRates.size(); i++) {
824 int[] rate = frameRates.get(i);
Angus Kong831347d2014-06-16 16:07:28 -0700825 int minFps = rate[0];
826 int maxFps = rate[1];
ztenghui16a35202013-09-23 11:35:36 -0700827 if (minFps == lowestMinRate && highestMaxRate < maxFps) {
828 highestMaxRate = maxFps;
829 resultIndex = i;
830 }
831 }
832
833 if (resultIndex >= 0) {
834 return frameRates.get(resultIndex);
835 }
836 Log.e(TAG, "Can't find an appropiate frame rate range!");
837 return null;
838 }
Angus Kongd82eae22013-06-11 12:00:15 -0700839
Angus Kong6607dae2014-06-10 16:07:45 -0700840 public static int[] getMaxPreviewFpsRange(List<int[]> frameRates) {
Angus Kongd82eae22013-06-11 12:00:15 -0700841 if (frameRates != null && frameRates.size() > 0) {
842 // The list is sorted. Return the last element.
843 return frameRates.get(frameRates.size() - 1);
844 }
845 return new int[0];
846 }
847
Angus Kong20fad242013-11-11 18:23:46 -0800848 public static void throwIfCameraDisabled(Context context) throws CameraDisabledException {
849 // Check if device policy has disabled the camera.
850 DevicePolicyManager dpm =
851 (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
852 if (dpm.getCameraDisabled(null)) {
853 throw new CameraDisabledException();
854 }
855 }
856
Doris Liu213a4a02014-02-04 16:57:55 -0800857 /**
858 * Generates a 1d Gaussian mask of the input array size, and store the mask
859 * in the input array.
860 *
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700861 * @param mask empty array of size n, where n will be used as the size of
862 * the Gaussian mask, and the array will be populated with the
863 * values of the mask.
Doris Liu213a4a02014-02-04 16:57:55 -0800864 */
865 private static void getGaussianMask(float[] mask) {
866 int len = mask.length;
867 int mid = len / 2;
868 float sigma = len;
869 float sum = 0;
870 for (int i = 0; i <= mid; i++) {
871 float ex = FloatMath.exp(-(i - mid) * (i - mid) / (mid * mid))
872 / (2 * sigma * sigma);
873 int symmetricIndex = len - 1 - i;
874 mask[i] = ex;
875 mask[symmetricIndex] = ex;
876 sum += mask[i];
877 if (i != symmetricIndex) {
878 sum += mask[symmetricIndex];
879 }
880 }
881
882 for (int i = 0; i < mask.length; i++) {
883 mask[i] /= sum;
884 }
885
886 }
887
888 /**
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700889 * Add two pixels together where the second pixel will be applied with a
890 * weight.
Doris Liu213a4a02014-02-04 16:57:55 -0800891 *
892 * @param pixel pixel color value of weight 1
893 * @param newPixel second pixel color value where the weight will be applied
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700894 * @param weight a float weight that will be applied to the second pixel
895 * color
Doris Liu213a4a02014-02-04 16:57:55 -0800896 * @return the weighted addition of the two pixels
897 */
898 public static int addPixel(int pixel, int newPixel, float weight) {
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700899 // TODO: scale weight to [0, 1024] to avoid casting to float and back to
900 // int.
Sascha Haeberlinga7cbfc02014-02-14 11:06:03 +0100901 int r = ((pixel & 0x00ff0000) + (int) ((newPixel & 0x00ff0000) * weight)) & 0x00ff0000;
902 int g = ((pixel & 0x0000ff00) + (int) ((newPixel & 0x0000ff00) * weight)) & 0x0000ff00;
903 int b = ((pixel & 0x000000ff) + (int) ((newPixel & 0x000000ff) * weight)) & 0x000000ff;
Doris Liu213a4a02014-02-04 16:57:55 -0800904 return 0xff000000 | r | g | b;
905 }
906
907 /**
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700908 * Apply blur to the input image represented in an array of colors and put
909 * the output image, in the form of an array of colors, into the output
910 * array.
Doris Liu213a4a02014-02-04 16:57:55 -0800911 *
912 * @param src source array of colors
913 * @param out output array of colors after the blur
914 * @param w width of the image
915 * @param h height of the image
916 * @param size size of the Gaussian blur mask
917 */
918 public static void blur(int[] src, int[] out, int w, int h, int size) {
919 float[] k = new float[size];
920 int off = size / 2;
921
922 getGaussianMask(k);
923
924 int[] tmp = new int[src.length];
925
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700926 // Apply the 1d Gaussian mask horizontally to the image and put the
927 // intermediat results in a temporary array.
Doris Liu213a4a02014-02-04 16:57:55 -0800928 int rowPointer = 0;
929 for (int y = 0; y < h; y++) {
930 for (int x = 0; x < w; x++) {
931 int sum = 0;
932 for (int i = 0; i < k.length; i++) {
933 int dx = x + i - off;
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700934 dx = clamp(dx, 0, w - 1);
Doris Liu213a4a02014-02-04 16:57:55 -0800935 sum = addPixel(sum, src[rowPointer + dx], k[i]);
936 }
937 tmp[x + rowPointer] = sum;
938 }
939 rowPointer += w;
940 }
941
942 // Apply the 1d Gaussian mask vertically to the intermediate array, and
943 // the final results will be stored in the output array.
944 for (int x = 0; x < w; x++) {
945 rowPointer = 0;
946 for (int y = 0; y < h; y++) {
947 int sum = 0;
948 for (int i = 0; i < k.length; i++) {
949 int dy = y + i - off;
950 dy = clamp(dy, 0, h - 1);
951 sum = addPixel(sum, tmp[dy * w + x], k[i]);
952 }
953 out[x + rowPointer] = sum;
954 rowPointer += w;
955 }
956 }
957 }
958
Angus Kongc195e7a2014-02-20 16:56:37 -0800959 /**
960 * Calculates a new dimension to fill the bound with the original aspect
961 * ratio preserved.
962 *
963 * @param imageWidth The original width.
964 * @param imageHeight The original height.
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700965 * @param imageRotation The clockwise rotation in degrees of the image which
966 * the original dimension comes from.
Angus Kongc195e7a2014-02-20 16:56:37 -0800967 * @param boundWidth The width of the bound.
968 * @param boundHeight The height of the bound.
Angus Kongc195e7a2014-02-20 16:56:37 -0800969 * @returns The final width/height stored in Point.x/Point.y to fill the
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700970 * bounds and preserve image aspect ratio.
Angus Kongc195e7a2014-02-20 16:56:37 -0800971 */
972 public static Point resizeToFill(int imageWidth, int imageHeight, int imageRotation,
973 int boundWidth, int boundHeight) {
974 if (imageRotation % 180 != 0) {
975 // Swap width and height.
976 int savedWidth = imageWidth;
977 imageWidth = imageHeight;
978 imageHeight = savedWidth;
979 }
980 if (imageWidth == ImageData.SIZE_FULL
981 || imageHeight == ImageData.SIZE_FULL) {
982 imageWidth = boundWidth;
983 imageHeight = boundHeight;
984 }
985
986 Point p = new Point();
987 p.x = boundWidth;
988 p.y = boundHeight;
989
990 if (imageWidth * boundHeight > boundWidth * imageHeight) {
991 p.y = imageHeight * p.x / imageWidth;
992 } else {
993 p.x = imageWidth * p.y / imageHeight;
994 }
995
996 return p;
997 }
998
Michael Kolb8872c232013-01-29 10:33:22 -0800999 private static class ImageFileNamer {
Igor Murashkin160b0362013-10-14 14:57:30 -07001000 private final SimpleDateFormat mFormat;
Michael Kolb8872c232013-01-29 10:33:22 -08001001
1002 // The date (in milliseconds) used to generate the last name.
1003 private long mLastDate;
1004
1005 // Number of names generated for the same second.
1006 private int mSameSecondCount;
1007
1008 public ImageFileNamer(String format) {
1009 mFormat = new SimpleDateFormat(format);
1010 }
1011
1012 public String generateName(long dateTaken) {
1013 Date date = new Date(dateTaken);
1014 String result = mFormat.format(date);
1015
1016 // If the last name was generated for the same second,
1017 // we append _1, _2, etc to the name.
1018 if (dateTaken / 1000 == mLastDate / 1000) {
1019 mSameSecondCount++;
1020 result += "_" + mSameSecondCount;
1021 } else {
1022 mLastDate = dateTaken;
1023 mSameSecondCount = 0;
1024 }
1025
1026 return result;
1027 }
1028 }
Angus Kongb40738a2013-06-03 14:55:34 -07001029
Sascha Haeberlingb7639c62013-09-09 14:42:43 -07001030 public static void playVideo(Activity activity, Uri uri, String title) {
Angus Kongb40738a2013-06-03 14:55:34 -07001031 try {
Senpo Hube707312014-09-10 14:43:16 -07001032 CameraActivity cameraActivity = (CameraActivity)activity;
1033 boolean isSecureCamera = cameraActivity.isSecureCamera();
ztenghui98b2a282013-10-11 17:15:40 -07001034 if (!isSecureCamera) {
Spike Sprague4f93e192014-08-19 18:53:41 -07001035 Intent intent = IntentHelper.getVideoPlayerIntent(uri)
ztenghui98b2a282013-10-11 17:15:40 -07001036 .putExtra(Intent.EXTRA_TITLE, title)
1037 .putExtra(KEY_TREAT_UP_AS_BACK, true);
Senpo Hube707312014-09-10 14:43:16 -07001038 cameraActivity.launchActivityByIntent(intent);
ztenghui98b2a282013-10-11 17:15:40 -07001039 } else {
1040 // In order not to send out any intent to be intercepted and
1041 // show the lock screen immediately, we just let the secure
1042 // camera activity finish.
1043 activity.finish();
1044 }
Angus Kongb40738a2013-06-03 14:55:34 -07001045 } catch (ActivityNotFoundException e) {
Sascha Haeberlingb7639c62013-09-09 14:42:43 -07001046 Toast.makeText(activity, activity.getString(R.string.video_err),
Angus Kongb40738a2013-06-03 14:55:34 -07001047 Toast.LENGTH_SHORT).show();
1048 }
1049 }
Sascha Haeberlingfae11a12013-08-15 14:29:49 -07001050
1051 /**
1052 * Starts GMM with the given location shown. If this fails, and GMM could
1053 * not be found, we use a geo intent as a fallback.
1054 *
Sascha Haeberlingb7639c62013-09-09 14:42:43 -07001055 * @param activity the activity to use for launching the Maps intent.
Sascha Haeberlingfae11a12013-08-15 14:29:49 -07001056 * @param latLong a 2-element array containing {latitude/longitude}.
1057 */
Sascha Haeberlingb7639c62013-09-09 14:42:43 -07001058 public static void showOnMap(Activity activity, double[] latLong) {
Sascha Haeberlingfae11a12013-08-15 14:29:49 -07001059 try {
1060 // We don't use "geo:latitude,longitude" because it only centers
1061 // the MapView to the specified location, but we need a marker
1062 // for further operations (routing to/from).
1063 // The q=(lat, lng) syntax is suggested by geo-team.
1064 String uri = String.format(Locale.ENGLISH, "http://maps.google.com/maps?f=q&q=(%f,%f)",
1065 latLong[0], latLong[1]);
1066 ComponentName compName = new ComponentName(MAPS_PACKAGE_NAME,
1067 MAPS_CLASS_NAME);
1068 Intent mapsIntent = new Intent(Intent.ACTION_VIEW,
1069 Uri.parse(uri)).setComponent(compName);
Senpo Hu9f2b20a2014-08-29 16:27:03 -07001070 mapsIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1071 activity.startActivity(mapsIntent);
Sascha Haeberlingfae11a12013-08-15 14:29:49 -07001072 } catch (ActivityNotFoundException e) {
1073 // Use the "geo intent" if no GMM is installed
1074 Log.e(TAG, "GMM activity not found!", e);
1075 String url = String.format(Locale.ENGLISH, "geo:%f,%f", latLong[0], latLong[1]);
1076 Intent mapsIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
Sascha Haeberlingb7639c62013-09-09 14:42:43 -07001077 activity.startActivity(mapsIntent);
Sascha Haeberlingfae11a12013-08-15 14:29:49 -07001078 }
1079 }
Angus Kong7d2388d2013-09-18 23:56:01 -07001080
Angus Kongb21215a2013-09-20 18:41:46 -07001081 /**
1082 * Dumps the stack trace.
1083 *
1084 * @param level How many levels of the stack are dumped. 0 means all.
Sascha Haeberlingf2627902014-09-02 14:20:57 -07001085 * @return A {@link java.lang.String} of all the output with newline between
1086 * each.
Angus Kongb21215a2013-09-20 18:41:46 -07001087 */
Angus Kong7d2388d2013-09-18 23:56:01 -07001088 public static String dumpStackTrace(int level) {
1089 StackTraceElement[] elems = Thread.currentThread().getStackTrace();
1090 // Ignore the first 3 elements.
Angus Kongb21215a2013-09-20 18:41:46 -07001091 level = (level == 0 ? elems.length : Math.min(level + 3, elems.length));
Angus Kong7d2388d2013-09-18 23:56:01 -07001092 String ret = new String();
1093 for (int i = 3; i < level; i++) {
Angus Kongb21215a2013-09-20 18:41:46 -07001094 ret = ret + "\t" + elems[i].toString() + '\n';
Angus Kong7d2388d2013-09-18 23:56:01 -07001095 }
1096 return ret;
1097 }
Doris Liubd1b8f92014-01-03 17:59:51 -08001098
Doris Liubd1b8f92014-01-03 17:59:51 -08001099 /**
1100 * Gets the theme color of a specific mode.
1101 *
1102 * @param modeIndex index of the mode
1103 * @param context current context
1104 * @return theme color of the mode if input index is valid, otherwise 0
1105 */
1106 public static int getCameraThemeColorId(int modeIndex, Context context) {
1107
1108 // Find the theme color using id from the color array
1109 TypedArray colorRes = context.getResources()
1110 .obtainTypedArray(R.array.camera_mode_theme_color);
1111 if (modeIndex >= colorRes.length() || modeIndex < 0) {
1112 // Mode index not found
1113 Log.e(TAG, "Invalid mode index: " + modeIndex);
1114 return 0;
1115 }
1116 return colorRes.getResourceId(modeIndex, 0);
1117 }
1118
1119 /**
1120 * Gets the mode icon resource id of a specific mode.
1121 *
1122 * @param modeIndex index of the mode
1123 * @param context current context
1124 * @return icon resource id if the index is valid, otherwise 0
1125 */
1126 public static int getCameraModeIconResId(int modeIndex, Context context) {
1127 // Find the camera mode icon using id
1128 TypedArray cameraModesIcons = context.getResources()
1129 .obtainTypedArray(R.array.camera_mode_icon);
1130 if (modeIndex >= cameraModesIcons.length() || modeIndex < 0) {
1131 // Mode index not found
1132 Log.e(TAG, "Invalid mode index: " + modeIndex);
1133 return 0;
1134 }
1135 return cameraModesIcons.getResourceId(modeIndex, 0);
1136 }
1137
1138 /**
1139 * Gets the mode text of a specific mode.
1140 *
1141 * @param modeIndex index of the mode
1142 * @param context current context
1143 * @return mode text if the index is valid, otherwise a new empty string
1144 */
1145 public static String getCameraModeText(int modeIndex, Context context) {
1146 // Find the camera mode icon using id
1147 String[] cameraModesText = context.getResources()
1148 .getStringArray(R.array.camera_mode_text);
1149 if (modeIndex < 0 || modeIndex >= cameraModesText.length) {
1150 Log.e(TAG, "Invalid mode index: " + modeIndex);
1151 return new String();
1152 }
1153 return cameraModesText[modeIndex];
1154 }
Erin Dahlgrenfecd7232014-01-16 13:29:42 -08001155
1156 /**
Spike Sprague79718f62014-01-28 18:48:22 -08001157 * Gets the mode content description of a specific mode.
1158 *
1159 * @param modeIndex index of the mode
1160 * @param context current context
Sascha Haeberlingf2627902014-09-02 14:20:57 -07001161 * @return mode content description if the index is valid, otherwise a new
1162 * empty string
Spike Sprague79718f62014-01-28 18:48:22 -08001163 */
1164 public static String getCameraModeContentDescription(int modeIndex, Context context) {
1165 String[] cameraModesDesc = context.getResources()
1166 .getStringArray(R.array.camera_mode_content_description);
1167 if (modeIndex < 0 || modeIndex >= cameraModesDesc.length) {
1168 Log.e(TAG, "Invalid mode index: " + modeIndex);
1169 return new String();
1170 }
1171 return cameraModesDesc[modeIndex];
1172 }
1173
1174 /**
Erin Dahlgrenfecd7232014-01-16 13:29:42 -08001175 * Gets the shutter icon res id for a specific mode.
1176 *
1177 * @param modeIndex index of the mode
1178 * @param context current context
1179 * @return mode shutter icon id if the index is valid, otherwise 0.
1180 */
1181 public static int getCameraShutterIconId(int modeIndex, Context context) {
1182 // Find the camera mode icon using id
1183 TypedArray shutterIcons = context.getResources()
Sascha Haeberlingf2627902014-09-02 14:20:57 -07001184 .obtainTypedArray(R.array.camera_mode_shutter_icon);
Erin Dahlgrenfecd7232014-01-16 13:29:42 -08001185 if (modeIndex < 0 || modeIndex >= shutterIcons.length()) {
1186 Log.e(TAG, "Invalid mode index: " + modeIndex);
Alan Newberger7bc335f2014-07-23 11:25:07 -07001187 throw new IllegalStateException("Invalid mode index: " + modeIndex);
Erin Dahlgrenfecd7232014-01-16 13:29:42 -08001188 }
1189 return shutterIcons.getResourceId(modeIndex, 0);
1190 }
Doris Liu213a4a02014-02-04 16:57:55 -08001191
1192 /**
1193 * Gets the parent mode that hosts a specific mode in nav drawer.
1194 *
1195 * @param modeIndex index of the mode
1196 * @param context current context
1197 * @return mode id if the index is valid, otherwise 0
1198 */
1199 public static int getCameraModeParentModeId(int modeIndex, Context context) {
1200 // Find the camera mode icon using id
1201 int[] cameraModeParent = context.getResources()
1202 .getIntArray(R.array.camera_mode_nested_in_nav_drawer);
1203 if (modeIndex < 0 || modeIndex >= cameraModeParent.length) {
1204 Log.e(TAG, "Invalid mode index: " + modeIndex);
1205 return 0;
1206 }
1207 return cameraModeParent[modeIndex];
1208 }
Doris Liub520b972014-02-14 14:14:46 -08001209
1210 /**
1211 * Gets the mode cover icon resource id of a specific mode.
1212 *
1213 * @param modeIndex index of the mode
1214 * @param context current context
1215 * @return icon resource id if the index is valid, otherwise 0
1216 */
1217 public static int getCameraModeCoverIconResId(int modeIndex, Context context) {
1218 // Find the camera mode icon using id
1219 TypedArray cameraModesIcons = context.getResources()
1220 .obtainTypedArray(R.array.camera_mode_cover_icon);
1221 if (modeIndex >= cameraModesIcons.length() || modeIndex < 0) {
1222 // Mode index not found
1223 Log.e(TAG, "Invalid mode index: " + modeIndex);
1224 return 0;
1225 }
1226 return cameraModesIcons.getResourceId(modeIndex, 0);
1227 }
Sascha Haeberling59c784b2014-08-05 10:53:08 -07001228
1229 /**
1230 * Gets the number of cores available in this device, across all processors.
1231 * Requires: Ability to peruse the filesystem at "/sys/devices/system/cpu"
1232 * <p>
1233 * Source: http://stackoverflow.com/questions/7962155/
1234 *
1235 * @return The number of cores, or 1 if failed to get result
1236 */
1237 public static int getNumCpuCores() {
1238 // Private Class to display only CPU devices in the directory listing
1239 class CpuFilter implements java.io.FileFilter {
1240 @Override
1241 public boolean accept(java.io.File pathname) {
1242 // Check if filename is "cpu", followed by a single digit number
1243 if (java.util.regex.Pattern.matches("cpu[0-9]+", pathname.getName())) {
1244 return true;
1245 }
1246 return false;
1247 }
1248 }
1249
1250 try {
1251 // Get directory containing CPU info
1252 java.io.File dir = new java.io.File("/sys/devices/system/cpu/");
1253 // Filter to only list the devices we care about
1254 java.io.File[] files = dir.listFiles(new CpuFilter());
1255 // Return the number of cores (virtual CPU devices)
1256 return files.length;
1257 } catch (Exception e) {
1258 // Default to return 1 core
1259 Log.e(TAG, "Failed to count number of cores, defaulting to 1", e);
1260 return 1;
1261 }
1262 }
Sascha Haeberlinga2dd9ea2014-08-15 18:45:15 -07001263
1264 /**
1265 * Given the device orientation and Camera2 characteristics, this returns
1266 * the required JPEG rotation for this camera.
1267 *
1268 * @param deviceOrientationDegrees the device orientation in degrees.
1269 * @return The JPEG orientation in degrees.
1270 */
1271 public static int getJpegRotation(int deviceOrientationDegrees,
1272 CameraCharacteristics characteristics) {
1273 if (deviceOrientationDegrees == OrientationEventListener.ORIENTATION_UNKNOWN) {
1274 return 0;
1275 }
1276 int facing = characteristics.get(CameraCharacteristics.LENS_FACING);
1277 int sensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
1278 if (facing == CameraMetadata.LENS_FACING_FRONT) {
1279 return (sensorOrientation + deviceOrientationDegrees) % 360;
1280 } else {
1281 return (sensorOrientation - deviceOrientationDegrees + 360) % 360;
1282 }
1283 }
Michael Kolb8872c232013-01-29 10:33:22 -08001284}