blob: b4159019d22349de6418ad7b7e25e32a47bce136 [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;
Doris Liu213a4a02014-02-04 16:57:55 -080043import android.util.FloatMath;
Michael Kolb8872c232013-01-29 10:33:22 -080044import android.util.TypedValue;
Doris Liu0ba8eaa2013-10-16 12:51:02 -070045import android.view.Display;
Michael Kolb8872c232013-01-29 10:33:22 -080046import android.view.OrientationEventListener;
47import android.view.Surface;
48import android.view.View;
49import android.view.WindowManager;
50import android.view.animation.AlphaAnimation;
51import android.view.animation.Animation;
Angus Kongb40738a2013-06-03 14:55:34 -070052import android.widget.Toast;
Michael Kolb8872c232013-01-29 10:33:22 -080053
Sascha Haeberlingb7639c62013-09-09 14:42:43 -070054import com.android.camera.CameraActivity;
Angus Kongb50b5cb2013-08-09 14:55:20 -070055import com.android.camera.CameraDisabledException;
Angus Kong2bca2102014-03-11 16:27:30 -070056import com.android.camera.debug.Log;
Angus Kongc195e7a2014-02-20 16:56:37 -080057import com.android.camera.filmstrip.ImageData;
Sascha Haeberling37f36112013-08-06 14:31:52 -070058import com.android.camera2.R;
Sol Boucher5a344962014-06-17 14:05:08 -070059import com.android.ex.camera2.portability.CameraCapabilities;
60import com.android.ex.camera2.portability.CameraSettings;
Michael Kolb8872c232013-01-29 10:33:22 -080061
Sascha Haeberling638e6f02013-09-18 14:28:51 -070062import java.io.Closeable;
63import java.io.IOException;
64import java.lang.reflect.Method;
65import java.text.SimpleDateFormat;
66import java.util.Date;
67import java.util.List;
68import java.util.Locale;
Sascha Haeberling638e6f02013-09-18 14:28:51 -070069
Michael Kolb8872c232013-01-29 10:33:22 -080070/**
71 * Collection of utility functions used in this package.
72 */
Angus Kongb50b5cb2013-08-09 14:55:20 -070073public class CameraUtil {
Angus Kong2bca2102014-03-11 16:27:30 -070074 private static final Log.Tag TAG = new Log.Tag("Util");
Michael Kolb8872c232013-01-29 10:33:22 -080075
ztenghui16a35202013-09-23 11:35:36 -070076 // For calculate the best fps range for still image capture.
77 private final static int MAX_PREVIEW_FPS_TIMES_1000 = 400000;
78 private final static int PREFERRED_PREVIEW_FPS_TIMES_1000 = 30000;
79
Angus Kongb50b5cb2013-08-09 14:55:20 -070080 // For creating crop intents.
81 public static final String KEY_RETURN_DATA = "return-data";
82 public static final String KEY_SHOW_WHEN_LOCKED = "showWhenLocked";
83
Sascha Haeberlingf2627902014-09-02 14:20:57 -070084 /** Orientation hysteresis amount used in rounding, in degrees. */
Michael Kolb8872c232013-01-29 10:33:22 -080085 public static final int ORIENTATION_HYSTERESIS = 5;
86
87 public static final String REVIEW_ACTION = "com.android.camera.action.REVIEW";
Sascha Haeberlingf2627902014-09-02 14:20:57 -070088 /** See android.hardware.Camera.ACTION_NEW_PICTURE. */
Michael Kolb8872c232013-01-29 10:33:22 -080089 public static final String ACTION_NEW_PICTURE = "android.hardware.action.NEW_PICTURE";
Sascha Haeberlingf2627902014-09-02 14:20:57 -070090 /** See android.hardware.Camera.ACTION_NEW_VIDEO. */
Michael Kolb8872c232013-01-29 10:33:22 -080091 public static final String ACTION_NEW_VIDEO = "android.hardware.action.NEW_VIDEO";
92
Sascha Haeberlingf2627902014-09-02 14:20:57 -070093 /**
94 * Broadcast Action: The camera application has become active in
95 * picture-taking mode.
96 */
Dan Aminzadefca1c5e2013-08-14 17:36:56 -070097 public static final String ACTION_CAMERA_STARTED = "com.android.camera.action.CAMERA_STARTED";
Sascha Haeberlingf2627902014-09-02 14:20:57 -070098 /**
99 * Broadcast Action: The camera application is no longer in active
100 * picture-taking mode.
101 */
Dan Aminzadefca1c5e2013-08-14 17:36:56 -0700102 public static final String ACTION_CAMERA_STOPPED = "com.android.camera.action.CAMERA_STOPPED";
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700103 /**
104 * When the camera application is active in picture-taking mode, it listens
105 * for this intent, which upon receipt will trigger the shutter to capture a
106 * new picture, as if the user had pressed the shutter button.
107 */
Dan Aminzadefca1c5e2013-08-14 17:36:56 -0700108 public static final String ACTION_CAMERA_SHUTTER_CLICK =
109 "com.android.camera.action.SHUTTER_CLICK";
110
Sascha Haeberlingfae11a12013-08-15 14:29:49 -0700111 // Fields for the show-on-maps-functionality
112 private static final String MAPS_PACKAGE_NAME = "com.google.android.apps.maps";
113 private static final String MAPS_CLASS_NAME = "com.google.android.maps.MapsActivity";
114
115 /** Has to be in sync with the receiving MovieActivity. */
116 public static final String KEY_TREAT_UP_AS_BACK = "treat-up-as-back";
Michael Kolb8872c232013-01-29 10:33:22 -0800117
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700118 /** Private intent extras. Test only. */
Michael Kolb8872c232013-01-29 10:33:22 -0800119 private static final String EXTRAS_CAMERA_FACING =
120 "android.intent.extras.CAMERA_FACING";
121
122 private static float sPixelDensity = 1;
123 private static ImageFileNamer sImageFileNamer;
124
Angus Kongb50b5cb2013-08-09 14:55:20 -0700125 private CameraUtil() {
Michael Kolb8872c232013-01-29 10:33:22 -0800126 }
127
128 public static void initialize(Context context) {
129 DisplayMetrics metrics = new DisplayMetrics();
130 WindowManager wm = (WindowManager)
131 context.getSystemService(Context.WINDOW_SERVICE);
132 wm.getDefaultDisplay().getMetrics(metrics);
133 sPixelDensity = metrics.density;
134 sImageFileNamer = new ImageFileNamer(
135 context.getString(R.string.image_file_name_format));
136 }
137
138 public static int dpToPixel(int dp) {
139 return Math.round(sPixelDensity * dp);
140 }
141
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700142 /**
143 * Rotates the bitmap by the specified degree. If a new bitmap is created,
144 * the original bitmap is recycled.
145 */
Michael Kolb8872c232013-01-29 10:33:22 -0800146 public static Bitmap rotate(Bitmap b, int degrees) {
147 return rotateAndMirror(b, degrees, false);
148 }
149
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700150 /**
151 * Rotates and/or mirrors the bitmap. If a new bitmap is created, the
152 * original bitmap is recycled.
153 */
Michael Kolb8872c232013-01-29 10:33:22 -0800154 public static Bitmap rotateAndMirror(Bitmap b, int degrees, boolean mirror) {
155 if ((degrees != 0 || mirror) && b != null) {
156 Matrix m = new Matrix();
157 // Mirror first.
158 // horizontal flip + rotation = -rotation + horizontal flip
159 if (mirror) {
160 m.postScale(-1, 1);
161 degrees = (degrees + 360) % 360;
162 if (degrees == 0 || degrees == 180) {
163 m.postTranslate(b.getWidth(), 0);
164 } else if (degrees == 90 || degrees == 270) {
165 m.postTranslate(b.getHeight(), 0);
166 } else {
167 throw new IllegalArgumentException("Invalid degrees=" + degrees);
168 }
169 }
170 if (degrees != 0) {
171 // clockwise
172 m.postRotate(degrees,
173 (float) b.getWidth() / 2, (float) b.getHeight() / 2);
174 }
175
176 try {
177 Bitmap b2 = Bitmap.createBitmap(
178 b, 0, 0, b.getWidth(), b.getHeight(), m, true);
179 if (b != b2) {
180 b.recycle();
181 b = b2;
182 }
183 } catch (OutOfMemoryError ex) {
184 // We have no memory to rotate. Return the original bitmap.
185 }
186 }
187 return b;
188 }
189
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700190 /**
191 * Compute the sample size as a function of minSideLength and
192 * maxNumOfPixels. minSideLength is used to specify that minimal width or
193 * height of a bitmap. maxNumOfPixels is used to specify the maximal size in
194 * pixels that is tolerable in terms of memory usage. The function returns a
195 * sample size based on the constraints.
196 * <p>
197 * Both size and minSideLength can be passed in as -1 which indicates no
198 * care of the corresponding constraint. The functions prefers returning a
199 * sample size that generates a smaller bitmap, unless minSideLength = -1.
200 * <p>
Michael Kolb8872c232013-01-29 10:33:22 -0800201 * Also, the function rounds up the sample size to a power of 2 or multiple
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700202 * of 8 because BitmapFactory only honors sample size this way. For example,
203 * BitmapFactory downsamples an image by 2 even though the request is 3. So
204 * we round up the sample size to avoid OOM.
Michael Kolb8872c232013-01-29 10:33:22 -0800205 */
206 public static int computeSampleSize(BitmapFactory.Options options,
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700207 int minSideLength, int maxNumOfPixels) {
Michael Kolb8872c232013-01-29 10:33:22 -0800208 int initialSize = computeInitialSampleSize(options, minSideLength,
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700209 maxNumOfPixels);
Michael Kolb8872c232013-01-29 10:33:22 -0800210
211 int roundedSize;
212 if (initialSize <= 8) {
213 roundedSize = 1;
214 while (roundedSize < initialSize) {
215 roundedSize <<= 1;
216 }
217 } else {
218 roundedSize = (initialSize + 7) / 8 * 8;
219 }
220
221 return roundedSize;
222 }
223
224 private static int computeInitialSampleSize(BitmapFactory.Options options,
225 int minSideLength, int maxNumOfPixels) {
226 double w = options.outWidth;
227 double h = options.outHeight;
228
229 int lowerBound = (maxNumOfPixels < 0) ? 1 :
230 (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));
231 int upperBound = (minSideLength < 0) ? 128 :
232 (int) Math.min(Math.floor(w / minSideLength),
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700233 Math.floor(h / minSideLength));
Michael Kolb8872c232013-01-29 10:33:22 -0800234
235 if (upperBound < lowerBound) {
236 // return the larger one when there is no overlapping zone.
237 return lowerBound;
238 }
239
240 if (maxNumOfPixels < 0 && minSideLength < 0) {
241 return 1;
242 } else if (minSideLength < 0) {
243 return lowerBound;
244 } else {
245 return upperBound;
246 }
247 }
248
249 public static Bitmap makeBitmap(byte[] jpegData, int maxNumOfPixels) {
250 try {
251 BitmapFactory.Options options = new BitmapFactory.Options();
252 options.inJustDecodeBounds = true;
253 BitmapFactory.decodeByteArray(jpegData, 0, jpegData.length,
254 options);
255 if (options.mCancel || options.outWidth == -1
256 || options.outHeight == -1) {
257 return null;
258 }
259 options.inSampleSize = computeSampleSize(
260 options, -1, maxNumOfPixels);
261 options.inJustDecodeBounds = false;
262
263 options.inDither = false;
264 options.inPreferredConfig = Bitmap.Config.ARGB_8888;
265 return BitmapFactory.decodeByteArray(jpegData, 0, jpegData.length,
266 options);
267 } catch (OutOfMemoryError ex) {
268 Log.e(TAG, "Got oom exception ", ex);
269 return null;
270 }
271 }
272
273 public static void closeSilently(Closeable c) {
Sascha Haeberling846d3ab2014-02-04 12:48:55 +0100274 if (c == null) {
275 return;
276 }
Michael Kolb8872c232013-01-29 10:33:22 -0800277 try {
278 c.close();
279 } catch (Throwable t) {
280 // do nothing
281 }
282 }
283
284 public static void Assert(boolean cond) {
285 if (!cond) {
286 throw new AssertionError();
287 }
288 }
289
Michael Kolb8872c232013-01-29 10:33:22 -0800290 public static void showErrorAndFinish(final Activity activity, int msgId) {
291 DialogInterface.OnClickListener buttonListener =
292 new DialogInterface.OnClickListener() {
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700293 @Override
294 public void onClick(DialogInterface dialog, int which) {
295 activity.finish();
296 }
297 };
Michael Kolb8872c232013-01-29 10:33:22 -0800298 TypedValue out = new TypedValue();
299 activity.getTheme().resolveAttribute(android.R.attr.alertDialogIcon, out, true);
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700300 // Some crash reports indicate users leave app prior to this dialog
301 // appearing, so check to ensure that the activity is not shutting down
302 // before attempting to attach a dialog to the window manager.
Alan Newbergerb19aba92014-05-16 11:45:14 -0700303 if (!activity.isFinishing()) {
Senpo Hu13159192014-10-13 11:54:16 -0700304 Log.e(TAG, "Show fatal error dialog");
Alan Newbergerb19aba92014-05-16 11:45:14 -0700305 new AlertDialog.Builder(activity)
306 .setCancelable(false)
307 .setTitle(R.string.camera_error_title)
308 .setMessage(msgId)
309 .setNeutralButton(R.string.dialog_ok, buttonListener)
310 .setIcon(out.resourceId)
311 .show();
312 }
Michael Kolb8872c232013-01-29 10:33:22 -0800313 }
314
315 public static <T> T checkNotNull(T object) {
Sascha Haeberling846d3ab2014-02-04 12:48:55 +0100316 if (object == null) {
317 throw new NullPointerException();
318 }
Michael Kolb8872c232013-01-29 10:33:22 -0800319 return object;
320 }
321
322 public static boolean equals(Object a, Object b) {
323 return (a == b) || (a == null ? false : a.equals(b));
324 }
325
326 public static int nextPowerOf2(int n) {
Jiawen Chen09713762014-09-16 17:05:37 -0700327 // TODO: what happens if n is negative or already a power of 2?
Michael Kolb8872c232013-01-29 10:33:22 -0800328 n -= 1;
329 n |= n >>> 16;
330 n |= n >>> 8;
331 n |= n >>> 4;
332 n |= n >>> 2;
333 n |= n >>> 1;
334 return n + 1;
335 }
336
337 public static float distance(float x, float y, float sx, float sy) {
338 float dx = x - sx;
339 float dy = y - sy;
Sascha Haeberling638e6f02013-09-18 14:28:51 -0700340 return (float) Math.sqrt(dx * dx + dy * dy);
Michael Kolb8872c232013-01-29 10:33:22 -0800341 }
342
Jiawen Chen09713762014-09-16 17:05:37 -0700343 /**
344 * Clamps x to between min and max (inclusive on both ends, x = min --> min,
345 * x = max --> max).
346 */
Michael Kolb8872c232013-01-29 10:33:22 -0800347 public static int clamp(int x, int min, int max) {
Sascha Haeberling846d3ab2014-02-04 12:48:55 +0100348 if (x > max) {
349 return max;
350 }
351 if (x < min) {
352 return min;
353 }
Michael Kolb8872c232013-01-29 10:33:22 -0800354 return x;
355 }
356
Jiawen Chen09713762014-09-16 17:05:37 -0700357 /**
358 * Clamps x to between min and max (inclusive on both ends, x = min --> min,
359 * x = max --> max).
360 */
Igor Murashkin160b0362013-10-14 14:57:30 -0700361 public static float clamp(float x, float min, float max) {
Sascha Haeberling846d3ab2014-02-04 12:48:55 +0100362 if (x > max) {
363 return max;
364 }
365 if (x < min) {
366 return min;
367 }
Igor Murashkin160b0362013-10-14 14:57:30 -0700368 return x;
369 }
370
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700371 /**
372 * Linear interpolation between a and b by the fraction t. t = 0 --> a, t =
373 * 1 --> b.
374 */
375 public static float lerp(float a, float b, float t) {
376 return a + t * (b - a);
377 }
378
379 /**
Jiawen Chen09713762014-09-16 17:05:37 -0700380 * Given (nx, ny) \in [0, 1]^2, in the display's portrait coordinate system,
381 * returns normalized sensor coordinates \in [0, 1]^2 depending on how
382 * the sensor's orientation \in {0, 90, 180, 270}.
383 *
384 * <p>
385 * Returns null if sensorOrientation is not one of the above.
386 * </p>
387 */
388 public static PointF normalizedSensorCoordsForNormalizedDisplayCoords(
389 float nx, float ny, int sensorOrientation) {
390 switch (sensorOrientation) {
391 case 0:
392 return new PointF(nx, ny);
393 case 90:
394 return new PointF(ny, 1.0f - nx);
395 case 180:
396 return new PointF(1.0f - nx, 1.0f - ny);
397 case 270:
398 return new PointF(1.0f - ny, nx);
399 default:
400 return null;
401 }
402 }
403
404 /**
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700405 * Given a size, return the largest size with the given aspectRatio that
406 * maximally fits into the bounding rectangle of the original Size.
407 *
408 * @param size the original Size to crop
409 * @param aspectRatio the target aspect ratio
410 * @return the largest Size with the given aspect ratio that is smaller than
411 * or equal to the original Size.
412 */
413 public static Size constrainToAspectRatio(Size size, float aspectRatio) {
414 float width = size.getWidth();
415 float height = size.getHeight();
416
417 float currentAspectRatio = width * 1.0f / height;
418
419 if (currentAspectRatio > aspectRatio) {
420 // chop longer side
421 if (width > height) {
422 width = height * aspectRatio;
423 } else {
424 height = width / aspectRatio;
425 }
426 } else if (currentAspectRatio < aspectRatio) {
427 // chop shorter side
428 if (width < height) {
429 width = height * aspectRatio;
430 } else {
431 height = width / aspectRatio;
432 }
433 }
434
435 return new Size((int) width, (int) height);
436 }
437
Sascha Haeberling846d3ab2014-02-04 12:48:55 +0100438 public static int getDisplayRotation(Context context) {
439 WindowManager windowManager = (WindowManager) context
440 .getSystemService(Context.WINDOW_SERVICE);
441 int rotation = windowManager.getDefaultDisplay()
Michael Kolb8872c232013-01-29 10:33:22 -0800442 .getRotation();
443 switch (rotation) {
Sascha Haeberling59c784b2014-08-05 10:53:08 -0700444 case Surface.ROTATION_0:
445 return 0;
446 case Surface.ROTATION_90:
447 return 90;
448 case Surface.ROTATION_180:
449 return 180;
450 case Surface.ROTATION_270:
451 return 270;
Michael Kolb8872c232013-01-29 10:33:22 -0800452 }
453 return 0;
454 }
455
Doris Liu0ba8eaa2013-10-16 12:51:02 -0700456 /**
457 * Calculate the default orientation of the device based on the width and
458 * height of the display when rotation = 0 (i.e. natural width and height)
Sascha Haeberling59c784b2014-08-05 10:53:08 -0700459 *
Doris Liu8dc878f2014-05-05 14:10:34 -0700460 * @param context current context
Doris Liu0ba8eaa2013-10-16 12:51:02 -0700461 * @return whether the default orientation of the device is portrait
462 */
Doris Liu8dc878f2014-05-05 14:10:34 -0700463 public static boolean isDefaultToPortrait(Context context) {
464 Display currentDisplay = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE))
465 .getDefaultDisplay();
Doris Liu0ba8eaa2013-10-16 12:51:02 -0700466 Point displaySize = new Point();
467 currentDisplay.getSize(displaySize);
468 int orientation = currentDisplay.getRotation();
469 int naturalWidth, naturalHeight;
470 if (orientation == Surface.ROTATION_0 || orientation == Surface.ROTATION_180) {
471 naturalWidth = displaySize.x;
472 naturalHeight = displaySize.y;
473 } else {
474 naturalWidth = displaySize.y;
475 naturalHeight = displaySize.x;
476 }
477 return naturalWidth < naturalHeight;
478 }
479
Michael Kolb8872c232013-01-29 10:33:22 -0800480 public static int roundOrientation(int orientation, int orientationHistory) {
481 boolean changeOrientation = false;
482 if (orientationHistory == OrientationEventListener.ORIENTATION_UNKNOWN) {
483 changeOrientation = true;
484 } else {
485 int dist = Math.abs(orientation - orientationHistory);
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700486 dist = Math.min(dist, 360 - dist);
487 changeOrientation = (dist >= 45 + ORIENTATION_HYSTERESIS);
Michael Kolb8872c232013-01-29 10:33:22 -0800488 }
489 if (changeOrientation) {
490 return ((orientation + 45) / 90 * 90) % 360;
491 }
492 return orientationHistory;
493 }
494
Angus Kong88289042014-04-22 16:39:42 -0700495 private static Size getDefaultDisplaySize(Context context) {
Sascha Haeberling846d3ab2014-02-04 12:48:55 +0100496 WindowManager windowManager = (WindowManager) context
497 .getSystemService(Context.WINDOW_SERVICE);
Angus Kong88289042014-04-22 16:39:42 -0700498 Point res = new Point();
499 windowManager.getDefaultDisplay().getSize(res);
500 return new Size(res);
Michael Kolb8872c232013-01-29 10:33:22 -0800501 }
502
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700503 public static com.android.ex.camera2.portability.Size getOptimalPreviewSize(Context context,
504 List<com.android.ex.camera2.portability.Size> sizes, double targetRatio) {
505 int optimalPickIndex = getOptimalPreviewSizeIndex(context, Size.convert(sizes),
506 targetRatio);
507 if (optimalPickIndex == -1) {
508 return null;
509 } else {
510 return sizes.get(optimalPickIndex);
511 }
Ruben Brunk714d4d02013-10-09 16:01:16 -0700512 }
513
Angus Kong88289042014-04-22 16:39:42 -0700514 public static int getOptimalPreviewSizeIndex(Context context,
515 List<Size> sizes, double targetRatio) {
Ruben Brunk714d4d02013-10-09 16:01:16 -0700516 // Use a very small tolerance because we want an exact match.
517 final double ASPECT_TOLERANCE = 0.01;
Sascha Haeberling846d3ab2014-02-04 12:48:55 +0100518 if (sizes == null) {
519 return -1;
520 }
Ruben Brunk714d4d02013-10-09 16:01:16 -0700521
522 int optimalSizeIndex = -1;
Michael Kolb8872c232013-01-29 10:33:22 -0800523 double minDiff = Double.MAX_VALUE;
524
525 // Because of bugs of overlay and layout, we sometimes will try to
526 // layout the viewfinder in the portrait orientation and thus get the
527 // wrong size of preview surface. When we change the preview size, the
528 // new overlay will be created before the old one closed, which causes
529 // an exception. For now, just get the screen size.
Angus Kong88289042014-04-22 16:39:42 -0700530 Size defaultDisplaySize = getDefaultDisplaySize(context);
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700531 int targetHeight = Math.min(defaultDisplaySize.getWidth(), defaultDisplaySize.getHeight());
Michael Kolb8872c232013-01-29 10:33:22 -0800532 // Try to find an size match aspect ratio and size
Angus Kong88289042014-04-22 16:39:42 -0700533 for (int i = 0; i < sizes.size(); i++) {
534 Size size = sizes.get(i);
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700535 double ratio = (double) size.getWidth() / size.getHeight();
Sascha Haeberling846d3ab2014-02-04 12:48:55 +0100536 if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) {
537 continue;
538 }
Igor Murashkincf2a8182014-08-25 13:21:26 -0700539
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700540 double heightDiff = Math.abs(size.getHeight() - targetHeight);
Igor Murashkincf2a8182014-08-25 13:21:26 -0700541 if (heightDiff < minDiff) {
Ruben Brunk714d4d02013-10-09 16:01:16 -0700542 optimalSizeIndex = i;
Igor Murashkincf2a8182014-08-25 13:21:26 -0700543 minDiff = heightDiff;
544 } else if (heightDiff == minDiff) {
545 // Prefer resolutions smaller-than-display when an equally close
546 // larger-than-display resolution is available
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700547 if (size.getHeight() < targetHeight) {
Igor Murashkincf2a8182014-08-25 13:21:26 -0700548 optimalSizeIndex = i;
549 minDiff = heightDiff;
550 }
Michael Kolb8872c232013-01-29 10:33:22 -0800551 }
552 }
553 // Cannot find the one match the aspect ratio. This should not happen.
554 // Ignore the requirement.
Ruben Brunk714d4d02013-10-09 16:01:16 -0700555 if (optimalSizeIndex == -1) {
Michael Kolb8872c232013-01-29 10:33:22 -0800556 Log.w(TAG, "No preview size match the aspect ratio");
557 minDiff = Double.MAX_VALUE;
Angus Kong88289042014-04-22 16:39:42 -0700558 for (int i = 0; i < sizes.size(); i++) {
559 Size size = sizes.get(i);
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700560 if (Math.abs(size.getHeight() - targetHeight) < minDiff) {
Ruben Brunk714d4d02013-10-09 16:01:16 -0700561 optimalSizeIndex = i;
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700562 minDiff = Math.abs(size.getHeight() - targetHeight);
Michael Kolb8872c232013-01-29 10:33:22 -0800563 }
564 }
565 }
Ruben Brunk714d4d02013-10-09 16:01:16 -0700566 return optimalSizeIndex;
Michael Kolb8872c232013-01-29 10:33:22 -0800567 }
568
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700569 /** Returns the largest picture size which matches the given aspect ratio. */
570 public static com.android.ex.camera2.portability.Size getOptimalVideoSnapshotPictureSize(
571 List<com.android.ex.camera2.portability.Size> sizes, double targetRatio) {
Michael Kolb8872c232013-01-29 10:33:22 -0800572 // Use a very small tolerance because we want an exact match.
573 final double ASPECT_TOLERANCE = 0.001;
Sascha Haeberling846d3ab2014-02-04 12:48:55 +0100574 if (sizes == null) {
575 return null;
576 }
Michael Kolb8872c232013-01-29 10:33:22 -0800577
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700578 com.android.ex.camera2.portability.Size optimalSize = null;
Michael Kolb8872c232013-01-29 10:33:22 -0800579
580 // Try to find a size matches aspect ratio and has the largest width
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700581 for (com.android.ex.camera2.portability.Size size : sizes) {
Angus Kong00b7b102014-04-24 15:46:52 -0700582 double ratio = (double) size.width() / size.height();
Sascha Haeberling846d3ab2014-02-04 12:48:55 +0100583 if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) {
584 continue;
585 }
Angus Kong00b7b102014-04-24 15:46:52 -0700586 if (optimalSize == null || size.width() > optimalSize.width()) {
Michael Kolb8872c232013-01-29 10:33:22 -0800587 optimalSize = size;
588 }
589 }
590
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700591 // Cannot find one that matches the aspect ratio. This should not
592 // happen. Ignore the requirement.
Michael Kolb8872c232013-01-29 10:33:22 -0800593 if (optimalSize == null) {
594 Log.w(TAG, "No picture size match the aspect ratio");
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700595 for (com.android.ex.camera2.portability.Size size : sizes) {
Angus Kong00b7b102014-04-24 15:46:52 -0700596 if (optimalSize == null || size.width() > optimalSize.width()) {
Michael Kolb8872c232013-01-29 10:33:22 -0800597 optimalSize = size;
598 }
599 }
600 }
601 return optimalSize;
602 }
603
Michael Kolb8872c232013-01-29 10:33:22 -0800604 /**
605 * Returns whether the device is voice-capable (meaning, it can do MMS).
606 */
607 public static boolean isMmsCapable(Context context) {
608 TelephonyManager telephonyManager = (TelephonyManager)
609 context.getSystemService(Context.TELEPHONY_SERVICE);
610 if (telephonyManager == null) {
611 return false;
612 }
613
614 try {
615 Class<?> partypes[] = new Class[0];
616 Method sIsVoiceCapable = TelephonyManager.class.getMethod(
617 "isVoiceCapable", partypes);
618
619 Object arglist[] = new Object[0];
620 Object retobj = sIsVoiceCapable.invoke(telephonyManager, arglist);
621 return (Boolean) retobj;
622 } catch (java.lang.reflect.InvocationTargetException ite) {
623 // Failure, must be another device.
624 // Assume that it is voice capable.
625 } catch (IllegalAccessException iae) {
626 // Failure, must be an other device.
627 // Assume that it is voice capable.
628 } catch (NoSuchMethodException nsme) {
629 }
630 return true;
631 }
632
633 // This is for test only. Allow the camera to launch the specific camera.
634 public static int getCameraFacingIntentExtras(Activity currentActivity) {
635 int cameraId = -1;
636
637 int intentCameraId =
Angus Kongb50b5cb2013-08-09 14:55:20 -0700638 currentActivity.getIntent().getIntExtra(CameraUtil.EXTRAS_CAMERA_FACING, -1);
Michael Kolb8872c232013-01-29 10:33:22 -0800639
640 if (isFrontCameraIntent(intentCameraId)) {
641 // Check if the front camera exist
Angus Kong20fad242013-11-11 18:23:46 -0800642 int frontCameraId = ((CameraActivity) currentActivity).getCameraProvider()
643 .getFirstFrontCameraId();
Michael Kolb8872c232013-01-29 10:33:22 -0800644 if (frontCameraId != -1) {
645 cameraId = frontCameraId;
646 }
647 } else if (isBackCameraIntent(intentCameraId)) {
648 // Check if the back camera exist
Angus Kong20fad242013-11-11 18:23:46 -0800649 int backCameraId = ((CameraActivity) currentActivity).getCameraProvider()
650 .getFirstBackCameraId();
Michael Kolb8872c232013-01-29 10:33:22 -0800651 if (backCameraId != -1) {
652 cameraId = backCameraId;
653 }
654 }
655 return cameraId;
656 }
657
658 private static boolean isFrontCameraIntent(int intentCameraId) {
659 return (intentCameraId == android.hardware.Camera.CameraInfo.CAMERA_FACING_FRONT);
660 }
661
662 private static boolean isBackCameraIntent(int intentCameraId) {
663 return (intentCameraId == android.hardware.Camera.CameraInfo.CAMERA_FACING_BACK);
664 }
665
666 private static int sLocation[] = new int[2];
667
668 // This method is not thread-safe.
669 public static boolean pointInView(float x, float y, View v) {
670 v.getLocationInWindow(sLocation);
671 return x >= sLocation[0] && x < (sLocation[0] + v.getWidth())
672 && y >= sLocation[1] && y < (sLocation[1] + v.getHeight());
673 }
674
675 public static int[] getRelativeLocation(View reference, View view) {
676 reference.getLocationInWindow(sLocation);
677 int referenceX = sLocation[0];
678 int referenceY = sLocation[1];
679 view.getLocationInWindow(sLocation);
680 sLocation[0] -= referenceX;
681 sLocation[1] -= referenceY;
682 return sLocation;
683 }
684
685 public static boolean isUriValid(Uri uri, ContentResolver resolver) {
Sascha Haeberling846d3ab2014-02-04 12:48:55 +0100686 if (uri == null) {
687 return false;
688 }
Michael Kolb8872c232013-01-29 10:33:22 -0800689
690 try {
691 ParcelFileDescriptor pfd = resolver.openFileDescriptor(uri, "r");
692 if (pfd == null) {
693 Log.e(TAG, "Fail to open URI. URI=" + uri);
694 return false;
695 }
696 pfd.close();
697 } catch (IOException ex) {
698 return false;
699 }
700 return true;
701 }
702
Michael Kolb8872c232013-01-29 10:33:22 -0800703 public static void dumpRect(RectF rect, String msg) {
704 Log.v(TAG, msg + "=(" + rect.left + "," + rect.top
705 + "," + rect.right + "," + rect.bottom + ")");
706 }
707
708 public static void rectFToRect(RectF rectF, Rect rect) {
709 rect.left = Math.round(rectF.left);
710 rect.top = Math.round(rectF.top);
711 rect.right = Math.round(rectF.right);
712 rect.bottom = Math.round(rectF.bottom);
713 }
714
Doris Liu36ebcb12013-10-28 14:44:24 -0700715 public static Rect rectFToRect(RectF rectF) {
716 Rect rect = new Rect();
717 rectFToRect(rectF, rect);
718 return rect;
719 }
720
721 public static RectF rectToRectF(Rect r) {
722 return new RectF(r.left, r.top, r.right, r.bottom);
723 }
724
Michael Kolb8872c232013-01-29 10:33:22 -0800725 public static void prepareMatrix(Matrix matrix, boolean mirror, int displayOrientation,
726 int viewWidth, int viewHeight) {
727 // Need mirror for front camera.
728 matrix.setScale(mirror ? -1 : 1, 1);
729 // This is the value for android.hardware.Camera.setDisplayOrientation.
730 matrix.postRotate(displayOrientation);
731 // Camera driver coordinates range from (-1000, -1000) to (1000, 1000).
732 // UI coordinates range from (0, 0) to (width, height).
733 matrix.postScale(viewWidth / 2000f, viewHeight / 2000f);
734 matrix.postTranslate(viewWidth / 2f, viewHeight / 2f);
735 }
736
Doris Liu36ebcb12013-10-28 14:44:24 -0700737 public static void prepareMatrix(Matrix matrix, boolean mirror, int displayOrientation,
Sascha Haeberling59c784b2014-08-05 10:53:08 -0700738 Rect previewRect) {
Doris Liu36ebcb12013-10-28 14:44:24 -0700739 // Need mirror for front camera.
740 matrix.setScale(mirror ? -1 : 1, 1);
741 // This is the value for android.hardware.Camera.setDisplayOrientation.
742 matrix.postRotate(displayOrientation);
743
744 // Camera driver coordinates range from (-1000, -1000) to (1000, 1000).
745 // We need to map camera driver coordinates to preview rect coordinates
746 Matrix mapping = new Matrix();
747 mapping.setRectToRect(new RectF(-1000, -1000, 1000, 1000), rectToRectF(previewRect),
748 Matrix.ScaleToFit.FILL);
749 matrix.setConcat(mapping, matrix);
750 }
751
Michael Kolb8872c232013-01-29 10:33:22 -0800752 public static String createJpegName(long dateTaken) {
753 synchronized (sImageFileNamer) {
754 return sImageFileNamer.generateName(dateTaken);
755 }
756 }
757
758 public static void broadcastNewPicture(Context context, Uri uri) {
759 context.sendBroadcast(new Intent(ACTION_NEW_PICTURE, uri));
760 // Keep compatibility
761 context.sendBroadcast(new Intent("com.android.camera.NEW_PICTURE", uri));
762 }
763
764 public static void fadeIn(View view, float startAlpha, float endAlpha, long duration) {
Sascha Haeberling846d3ab2014-02-04 12:48:55 +0100765 if (view.getVisibility() == View.VISIBLE) {
766 return;
767 }
Michael Kolb8872c232013-01-29 10:33:22 -0800768
769 view.setVisibility(View.VISIBLE);
770 Animation animation = new AlphaAnimation(startAlpha, endAlpha);
771 animation.setDuration(duration);
772 view.startAnimation(animation);
773 }
774
Sascha Haeberling37f36112013-08-06 14:31:52 -0700775 /**
776 * Down-samples a jpeg byte array.
Sascha Haeberling59c784b2014-08-05 10:53:08 -0700777 *
Sascha Haeberling37f36112013-08-06 14:31:52 -0700778 * @param data a byte array of jpeg data
779 * @param downSampleFactor down-sample factor
780 * @return decoded and down-sampled bitmap
781 */
782 public static Bitmap downSample(final byte[] data, int downSampleFactor) {
783 final BitmapFactory.Options opts = new BitmapFactory.Options();
784 // Downsample the image
785 opts.inSampleSize = downSampleFactor;
786 return BitmapFactory.decodeByteArray(data, 0, data.length, opts);
787 }
788
Angus Kong6607dae2014-06-10 16:07:45 -0700789 public static void setGpsParameters(CameraSettings settings, Location loc) {
Michael Kolb8872c232013-01-29 10:33:22 -0800790 // Clear previous GPS location from the parameters.
Angus Kong6607dae2014-06-10 16:07:45 -0700791 settings.clearGpsData();
Michael Kolb8872c232013-01-29 10:33:22 -0800792
Angus Kong6607dae2014-06-10 16:07:45 -0700793 boolean hasLatLon = false;
794 double lat;
795 double lon;
Michael Kolb8872c232013-01-29 10:33:22 -0800796 // Set GPS location.
797 if (loc != null) {
Angus Kong6607dae2014-06-10 16:07:45 -0700798 lat = loc.getLatitude();
799 lon = loc.getLongitude();
800 hasLatLon = (lat != 0.0d) || (lon != 0.0d);
801 }
Michael Kolb8872c232013-01-29 10:33:22 -0800802
Angus Kong6607dae2014-06-10 16:07:45 -0700803 if (!hasLatLon) {
804 // We always encode GpsTimeStamp even if the GPS location is not
805 // available.
806 settings.setGpsData(
807 new CameraSettings.GpsData(0f, 0f, 0f, System.currentTimeMillis() / 1000, null)
Sascha Haeberling59c784b2014-08-05 10:53:08 -0700808 );
Angus Kong6607dae2014-06-10 16:07:45 -0700809 } else {
810 Log.d(TAG, "Set gps location");
811 // for NETWORK_PROVIDER location provider, we may have
812 // no altitude information, but the driver needs it, so
813 // we fake one.
814 // Location.getTime() is UTC in milliseconds.
815 // gps-timestamp is UTC in seconds.
816 long utcTimeSeconds = loc.getTime() / 1000;
817 settings.setGpsData(new CameraSettings.GpsData(loc.getLatitude(), loc.getLongitude(),
818 (loc.hasAltitude() ? loc.getAltitude() : 0),
819 (utcTimeSeconds != 0 ? utcTimeSeconds : System.currentTimeMillis()),
820 loc.getProvider().toUpperCase()));
Michael Kolb8872c232013-01-29 10:33:22 -0800821 }
822 }
823
ztenghui16a35202013-09-23 11:35:36 -0700824 /**
825 * For still image capture, we need to get the right fps range such that the
826 * camera can slow down the framerate to allow for less-noisy/dark
827 * viewfinder output in dark conditions.
828 *
Angus Kong88289042014-04-22 16:39:42 -0700829 * @param capabilities Camera's capabilities.
ztenghui16a35202013-09-23 11:35:36 -0700830 * @return null if no appropiate fps range can't be found. Otherwise, return
831 * the right range.
832 */
Angus Kong88289042014-04-22 16:39:42 -0700833 public static int[] getPhotoPreviewFpsRange(CameraCapabilities capabilities) {
834 return getPhotoPreviewFpsRange(capabilities.getSupportedPreviewFpsRange());
Ruben Brunk2a74dfd2013-10-29 18:28:32 -0700835 }
836
837 public static int[] getPhotoPreviewFpsRange(List<int[]> frameRates) {
ztenghui16a35202013-09-23 11:35:36 -0700838 if (frameRates.size() == 0) {
839 Log.e(TAG, "No suppoted frame rates returned!");
840 return null;
841 }
842
843 // Find the lowest min rate in supported ranges who can cover 30fps.
844 int lowestMinRate = MAX_PREVIEW_FPS_TIMES_1000;
845 for (int[] rate : frameRates) {
Angus Kong831347d2014-06-16 16:07:28 -0700846 int minFps = rate[0];
847 int maxFps = rate[1];
ztenghui16a35202013-09-23 11:35:36 -0700848 if (maxFps >= PREFERRED_PREVIEW_FPS_TIMES_1000 &&
849 minFps <= PREFERRED_PREVIEW_FPS_TIMES_1000 &&
850 minFps < lowestMinRate) {
851 lowestMinRate = minFps;
852 }
853 }
854
855 // Find all the modes with the lowest min rate found above, the pick the
856 // one with highest max rate.
857 int resultIndex = -1;
858 int highestMaxRate = 0;
859 for (int i = 0; i < frameRates.size(); i++) {
860 int[] rate = frameRates.get(i);
Angus Kong831347d2014-06-16 16:07:28 -0700861 int minFps = rate[0];
862 int maxFps = rate[1];
ztenghui16a35202013-09-23 11:35:36 -0700863 if (minFps == lowestMinRate && highestMaxRate < maxFps) {
864 highestMaxRate = maxFps;
865 resultIndex = i;
866 }
867 }
868
869 if (resultIndex >= 0) {
870 return frameRates.get(resultIndex);
871 }
872 Log.e(TAG, "Can't find an appropiate frame rate range!");
873 return null;
874 }
Angus Kongd82eae22013-06-11 12:00:15 -0700875
Angus Kong6607dae2014-06-10 16:07:45 -0700876 public static int[] getMaxPreviewFpsRange(List<int[]> frameRates) {
Angus Kongd82eae22013-06-11 12:00:15 -0700877 if (frameRates != null && frameRates.size() > 0) {
878 // The list is sorted. Return the last element.
879 return frameRates.get(frameRates.size() - 1);
880 }
881 return new int[0];
882 }
883
Angus Kong20fad242013-11-11 18:23:46 -0800884 public static void throwIfCameraDisabled(Context context) throws CameraDisabledException {
885 // Check if device policy has disabled the camera.
886 DevicePolicyManager dpm =
887 (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
888 if (dpm.getCameraDisabled(null)) {
889 throw new CameraDisabledException();
890 }
891 }
892
Doris Liu213a4a02014-02-04 16:57:55 -0800893 /**
894 * Generates a 1d Gaussian mask of the input array size, and store the mask
895 * in the input array.
896 *
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700897 * @param mask empty array of size n, where n will be used as the size of
898 * the Gaussian mask, and the array will be populated with the
899 * values of the mask.
Doris Liu213a4a02014-02-04 16:57:55 -0800900 */
901 private static void getGaussianMask(float[] mask) {
902 int len = mask.length;
903 int mid = len / 2;
904 float sigma = len;
905 float sum = 0;
906 for (int i = 0; i <= mid; i++) {
907 float ex = FloatMath.exp(-(i - mid) * (i - mid) / (mid * mid))
908 / (2 * sigma * sigma);
909 int symmetricIndex = len - 1 - i;
910 mask[i] = ex;
911 mask[symmetricIndex] = ex;
912 sum += mask[i];
913 if (i != symmetricIndex) {
914 sum += mask[symmetricIndex];
915 }
916 }
917
918 for (int i = 0; i < mask.length; i++) {
919 mask[i] /= sum;
920 }
921
922 }
923
924 /**
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700925 * Add two pixels together where the second pixel will be applied with a
926 * weight.
Doris Liu213a4a02014-02-04 16:57:55 -0800927 *
928 * @param pixel pixel color value of weight 1
929 * @param newPixel second pixel color value where the weight will be applied
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700930 * @param weight a float weight that will be applied to the second pixel
931 * color
Doris Liu213a4a02014-02-04 16:57:55 -0800932 * @return the weighted addition of the two pixels
933 */
934 public static int addPixel(int pixel, int newPixel, float weight) {
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700935 // TODO: scale weight to [0, 1024] to avoid casting to float and back to
936 // int.
Sascha Haeberlinga7cbfc02014-02-14 11:06:03 +0100937 int r = ((pixel & 0x00ff0000) + (int) ((newPixel & 0x00ff0000) * weight)) & 0x00ff0000;
938 int g = ((pixel & 0x0000ff00) + (int) ((newPixel & 0x0000ff00) * weight)) & 0x0000ff00;
939 int b = ((pixel & 0x000000ff) + (int) ((newPixel & 0x000000ff) * weight)) & 0x000000ff;
Doris Liu213a4a02014-02-04 16:57:55 -0800940 return 0xff000000 | r | g | b;
941 }
942
943 /**
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700944 * Apply blur to the input image represented in an array of colors and put
945 * the output image, in the form of an array of colors, into the output
946 * array.
Doris Liu213a4a02014-02-04 16:57:55 -0800947 *
948 * @param src source array of colors
949 * @param out output array of colors after the blur
950 * @param w width of the image
951 * @param h height of the image
952 * @param size size of the Gaussian blur mask
953 */
954 public static void blur(int[] src, int[] out, int w, int h, int size) {
955 float[] k = new float[size];
956 int off = size / 2;
957
958 getGaussianMask(k);
959
960 int[] tmp = new int[src.length];
961
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700962 // Apply the 1d Gaussian mask horizontally to the image and put the
963 // intermediat results in a temporary array.
Doris Liu213a4a02014-02-04 16:57:55 -0800964 int rowPointer = 0;
965 for (int y = 0; y < h; y++) {
966 for (int x = 0; x < w; x++) {
967 int sum = 0;
968 for (int i = 0; i < k.length; i++) {
969 int dx = x + i - off;
Sascha Haeberlingf2627902014-09-02 14:20:57 -0700970 dx = clamp(dx, 0, w - 1);
Doris Liu213a4a02014-02-04 16:57:55 -0800971 sum = addPixel(sum, src[rowPointer + dx], k[i]);
972 }
973 tmp[x + rowPointer] = sum;
974 }
975 rowPointer += w;
976 }
977
978 // Apply the 1d Gaussian mask vertically to the intermediate array, and
979 // the final results will be stored in the output array.
980 for (int x = 0; x < w; x++) {
981 rowPointer = 0;
982 for (int y = 0; y < h; y++) {
983 int sum = 0;
984 for (int i = 0; i < k.length; i++) {
985 int dy = y + i - off;
986 dy = clamp(dy, 0, h - 1);
987 sum = addPixel(sum, tmp[dy * w + x], k[i]);
988 }
989 out[x + rowPointer] = sum;
990 rowPointer += w;
991 }
992 }
993 }
994
Angus Kongc195e7a2014-02-20 16:56:37 -0800995 /**
996 * Calculates a new dimension to fill the bound with the original aspect
997 * ratio preserved.
998 *
999 * @param imageWidth The original width.
1000 * @param imageHeight The original height.
Sascha Haeberlingf2627902014-09-02 14:20:57 -07001001 * @param imageRotation The clockwise rotation in degrees of the image which
1002 * the original dimension comes from.
Angus Kongc195e7a2014-02-20 16:56:37 -08001003 * @param boundWidth The width of the bound.
1004 * @param boundHeight The height of the bound.
Angus Kongc195e7a2014-02-20 16:56:37 -08001005 * @returns The final width/height stored in Point.x/Point.y to fill the
Sascha Haeberlingf2627902014-09-02 14:20:57 -07001006 * bounds and preserve image aspect ratio.
Angus Kongc195e7a2014-02-20 16:56:37 -08001007 */
1008 public static Point resizeToFill(int imageWidth, int imageHeight, int imageRotation,
1009 int boundWidth, int boundHeight) {
1010 if (imageRotation % 180 != 0) {
1011 // Swap width and height.
1012 int savedWidth = imageWidth;
1013 imageWidth = imageHeight;
1014 imageHeight = savedWidth;
1015 }
1016 if (imageWidth == ImageData.SIZE_FULL
1017 || imageHeight == ImageData.SIZE_FULL) {
1018 imageWidth = boundWidth;
1019 imageHeight = boundHeight;
1020 }
1021
1022 Point p = new Point();
1023 p.x = boundWidth;
1024 p.y = boundHeight;
1025
1026 if (imageWidth * boundHeight > boundWidth * imageHeight) {
1027 p.y = imageHeight * p.x / imageWidth;
1028 } else {
1029 p.x = imageWidth * p.y / imageHeight;
1030 }
1031
1032 return p;
1033 }
1034
Michael Kolb8872c232013-01-29 10:33:22 -08001035 private static class ImageFileNamer {
Igor Murashkin160b0362013-10-14 14:57:30 -07001036 private final SimpleDateFormat mFormat;
Michael Kolb8872c232013-01-29 10:33:22 -08001037
1038 // The date (in milliseconds) used to generate the last name.
1039 private long mLastDate;
1040
1041 // Number of names generated for the same second.
1042 private int mSameSecondCount;
1043
1044 public ImageFileNamer(String format) {
1045 mFormat = new SimpleDateFormat(format);
1046 }
1047
1048 public String generateName(long dateTaken) {
1049 Date date = new Date(dateTaken);
1050 String result = mFormat.format(date);
1051
1052 // If the last name was generated for the same second,
1053 // we append _1, _2, etc to the name.
1054 if (dateTaken / 1000 == mLastDate / 1000) {
1055 mSameSecondCount++;
1056 result += "_" + mSameSecondCount;
1057 } else {
1058 mLastDate = dateTaken;
1059 mSameSecondCount = 0;
1060 }
1061
1062 return result;
1063 }
1064 }
Angus Kongb40738a2013-06-03 14:55:34 -07001065
Sascha Haeberlingb7639c62013-09-09 14:42:43 -07001066 public static void playVideo(Activity activity, Uri uri, String title) {
Angus Kongb40738a2013-06-03 14:55:34 -07001067 try {
Senpo Hube707312014-09-10 14:43:16 -07001068 CameraActivity cameraActivity = (CameraActivity)activity;
1069 boolean isSecureCamera = cameraActivity.isSecureCamera();
ztenghui98b2a282013-10-11 17:15:40 -07001070 if (!isSecureCamera) {
Spike Sprague4f93e192014-08-19 18:53:41 -07001071 Intent intent = IntentHelper.getVideoPlayerIntent(uri)
ztenghui98b2a282013-10-11 17:15:40 -07001072 .putExtra(Intent.EXTRA_TITLE, title)
1073 .putExtra(KEY_TREAT_UP_AS_BACK, true);
Senpo Hube707312014-09-10 14:43:16 -07001074 cameraActivity.launchActivityByIntent(intent);
ztenghui98b2a282013-10-11 17:15:40 -07001075 } else {
1076 // In order not to send out any intent to be intercepted and
1077 // show the lock screen immediately, we just let the secure
1078 // camera activity finish.
1079 activity.finish();
1080 }
Angus Kongb40738a2013-06-03 14:55:34 -07001081 } catch (ActivityNotFoundException e) {
Sascha Haeberlingb7639c62013-09-09 14:42:43 -07001082 Toast.makeText(activity, activity.getString(R.string.video_err),
Angus Kongb40738a2013-06-03 14:55:34 -07001083 Toast.LENGTH_SHORT).show();
1084 }
1085 }
Sascha Haeberlingfae11a12013-08-15 14:29:49 -07001086
1087 /**
1088 * Starts GMM with the given location shown. If this fails, and GMM could
1089 * not be found, we use a geo intent as a fallback.
1090 *
Sascha Haeberlingb7639c62013-09-09 14:42:43 -07001091 * @param activity the activity to use for launching the Maps intent.
Sascha Haeberlingfae11a12013-08-15 14:29:49 -07001092 * @param latLong a 2-element array containing {latitude/longitude}.
1093 */
Sascha Haeberlingb7639c62013-09-09 14:42:43 -07001094 public static void showOnMap(Activity activity, double[] latLong) {
Sascha Haeberlingfae11a12013-08-15 14:29:49 -07001095 try {
1096 // We don't use "geo:latitude,longitude" because it only centers
1097 // the MapView to the specified location, but we need a marker
1098 // for further operations (routing to/from).
1099 // The q=(lat, lng) syntax is suggested by geo-team.
1100 String uri = String.format(Locale.ENGLISH, "http://maps.google.com/maps?f=q&q=(%f,%f)",
1101 latLong[0], latLong[1]);
1102 ComponentName compName = new ComponentName(MAPS_PACKAGE_NAME,
1103 MAPS_CLASS_NAME);
1104 Intent mapsIntent = new Intent(Intent.ACTION_VIEW,
1105 Uri.parse(uri)).setComponent(compName);
Alan Newberger437a1862014-10-01 17:18:35 -07001106 mapsIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT);
Senpo Hu9f2b20a2014-08-29 16:27:03 -07001107 activity.startActivity(mapsIntent);
Sascha Haeberlingfae11a12013-08-15 14:29:49 -07001108 } catch (ActivityNotFoundException e) {
1109 // Use the "geo intent" if no GMM is installed
1110 Log.e(TAG, "GMM activity not found!", e);
1111 String url = String.format(Locale.ENGLISH, "geo:%f,%f", latLong[0], latLong[1]);
1112 Intent mapsIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
Sascha Haeberlingb7639c62013-09-09 14:42:43 -07001113 activity.startActivity(mapsIntent);
Sascha Haeberlingfae11a12013-08-15 14:29:49 -07001114 }
1115 }
Angus Kong7d2388d2013-09-18 23:56:01 -07001116
Angus Kongb21215a2013-09-20 18:41:46 -07001117 /**
1118 * Dumps the stack trace.
1119 *
1120 * @param level How many levels of the stack are dumped. 0 means all.
Sascha Haeberlingf2627902014-09-02 14:20:57 -07001121 * @return A {@link java.lang.String} of all the output with newline between
1122 * each.
Angus Kongb21215a2013-09-20 18:41:46 -07001123 */
Angus Kong7d2388d2013-09-18 23:56:01 -07001124 public static String dumpStackTrace(int level) {
1125 StackTraceElement[] elems = Thread.currentThread().getStackTrace();
1126 // Ignore the first 3 elements.
Angus Kongb21215a2013-09-20 18:41:46 -07001127 level = (level == 0 ? elems.length : Math.min(level + 3, elems.length));
Angus Kong7d2388d2013-09-18 23:56:01 -07001128 String ret = new String();
1129 for (int i = 3; i < level; i++) {
Angus Kongb21215a2013-09-20 18:41:46 -07001130 ret = ret + "\t" + elems[i].toString() + '\n';
Angus Kong7d2388d2013-09-18 23:56:01 -07001131 }
1132 return ret;
1133 }
Doris Liubd1b8f92014-01-03 17:59:51 -08001134
Doris Liubd1b8f92014-01-03 17:59:51 -08001135 /**
1136 * Gets the theme color of a specific mode.
1137 *
1138 * @param modeIndex index of the mode
1139 * @param context current context
1140 * @return theme color of the mode if input index is valid, otherwise 0
1141 */
1142 public static int getCameraThemeColorId(int modeIndex, Context context) {
1143
1144 // Find the theme color using id from the color array
1145 TypedArray colorRes = context.getResources()
1146 .obtainTypedArray(R.array.camera_mode_theme_color);
1147 if (modeIndex >= colorRes.length() || modeIndex < 0) {
1148 // Mode index not found
1149 Log.e(TAG, "Invalid mode index: " + modeIndex);
1150 return 0;
1151 }
1152 return colorRes.getResourceId(modeIndex, 0);
1153 }
1154
1155 /**
1156 * Gets the mode icon resource id of a specific mode.
1157 *
1158 * @param modeIndex index of the mode
1159 * @param context current context
1160 * @return icon resource id if the index is valid, otherwise 0
1161 */
1162 public static int getCameraModeIconResId(int modeIndex, Context context) {
1163 // Find the camera mode icon using id
1164 TypedArray cameraModesIcons = context.getResources()
1165 .obtainTypedArray(R.array.camera_mode_icon);
1166 if (modeIndex >= cameraModesIcons.length() || modeIndex < 0) {
1167 // Mode index not found
1168 Log.e(TAG, "Invalid mode index: " + modeIndex);
1169 return 0;
1170 }
1171 return cameraModesIcons.getResourceId(modeIndex, 0);
1172 }
1173
1174 /**
1175 * Gets the mode text of a specific mode.
1176 *
1177 * @param modeIndex index of the mode
1178 * @param context current context
1179 * @return mode text if the index is valid, otherwise a new empty string
1180 */
1181 public static String getCameraModeText(int modeIndex, Context context) {
1182 // Find the camera mode icon using id
1183 String[] cameraModesText = context.getResources()
1184 .getStringArray(R.array.camera_mode_text);
1185 if (modeIndex < 0 || modeIndex >= cameraModesText.length) {
1186 Log.e(TAG, "Invalid mode index: " + modeIndex);
1187 return new String();
1188 }
1189 return cameraModesText[modeIndex];
1190 }
Erin Dahlgrenfecd7232014-01-16 13:29:42 -08001191
1192 /**
Spike Sprague79718f62014-01-28 18:48:22 -08001193 * Gets the mode content description of a specific mode.
1194 *
1195 * @param modeIndex index of the mode
1196 * @param context current context
Sascha Haeberlingf2627902014-09-02 14:20:57 -07001197 * @return mode content description if the index is valid, otherwise a new
1198 * empty string
Spike Sprague79718f62014-01-28 18:48:22 -08001199 */
1200 public static String getCameraModeContentDescription(int modeIndex, Context context) {
1201 String[] cameraModesDesc = context.getResources()
1202 .getStringArray(R.array.camera_mode_content_description);
1203 if (modeIndex < 0 || modeIndex >= cameraModesDesc.length) {
1204 Log.e(TAG, "Invalid mode index: " + modeIndex);
1205 return new String();
1206 }
1207 return cameraModesDesc[modeIndex];
1208 }
1209
1210 /**
Erin Dahlgrenfecd7232014-01-16 13:29:42 -08001211 * Gets the shutter icon res id for a specific mode.
1212 *
1213 * @param modeIndex index of the mode
1214 * @param context current context
1215 * @return mode shutter icon id if the index is valid, otherwise 0.
1216 */
1217 public static int getCameraShutterIconId(int modeIndex, Context context) {
1218 // Find the camera mode icon using id
1219 TypedArray shutterIcons = context.getResources()
Sascha Haeberlingf2627902014-09-02 14:20:57 -07001220 .obtainTypedArray(R.array.camera_mode_shutter_icon);
Erin Dahlgrenfecd7232014-01-16 13:29:42 -08001221 if (modeIndex < 0 || modeIndex >= shutterIcons.length()) {
1222 Log.e(TAG, "Invalid mode index: " + modeIndex);
Alan Newberger7bc335f2014-07-23 11:25:07 -07001223 throw new IllegalStateException("Invalid mode index: " + modeIndex);
Erin Dahlgrenfecd7232014-01-16 13:29:42 -08001224 }
1225 return shutterIcons.getResourceId(modeIndex, 0);
1226 }
Doris Liu213a4a02014-02-04 16:57:55 -08001227
1228 /**
1229 * Gets the parent mode that hosts a specific mode in nav drawer.
1230 *
1231 * @param modeIndex index of the mode
1232 * @param context current context
1233 * @return mode id if the index is valid, otherwise 0
1234 */
1235 public static int getCameraModeParentModeId(int modeIndex, Context context) {
1236 // Find the camera mode icon using id
1237 int[] cameraModeParent = context.getResources()
1238 .getIntArray(R.array.camera_mode_nested_in_nav_drawer);
1239 if (modeIndex < 0 || modeIndex >= cameraModeParent.length) {
1240 Log.e(TAG, "Invalid mode index: " + modeIndex);
1241 return 0;
1242 }
1243 return cameraModeParent[modeIndex];
1244 }
Doris Liub520b972014-02-14 14:14:46 -08001245
1246 /**
1247 * Gets the mode cover icon resource id of a specific mode.
1248 *
1249 * @param modeIndex index of the mode
1250 * @param context current context
1251 * @return icon resource id if the index is valid, otherwise 0
1252 */
1253 public static int getCameraModeCoverIconResId(int modeIndex, Context context) {
1254 // Find the camera mode icon using id
1255 TypedArray cameraModesIcons = context.getResources()
1256 .obtainTypedArray(R.array.camera_mode_cover_icon);
1257 if (modeIndex >= cameraModesIcons.length() || modeIndex < 0) {
1258 // Mode index not found
1259 Log.e(TAG, "Invalid mode index: " + modeIndex);
1260 return 0;
1261 }
1262 return cameraModesIcons.getResourceId(modeIndex, 0);
1263 }
Sascha Haeberling59c784b2014-08-05 10:53:08 -07001264
1265 /**
1266 * Gets the number of cores available in this device, across all processors.
1267 * Requires: Ability to peruse the filesystem at "/sys/devices/system/cpu"
1268 * <p>
1269 * Source: http://stackoverflow.com/questions/7962155/
1270 *
1271 * @return The number of cores, or 1 if failed to get result
1272 */
1273 public static int getNumCpuCores() {
1274 // Private Class to display only CPU devices in the directory listing
1275 class CpuFilter implements java.io.FileFilter {
1276 @Override
1277 public boolean accept(java.io.File pathname) {
1278 // Check if filename is "cpu", followed by a single digit number
1279 if (java.util.regex.Pattern.matches("cpu[0-9]+", pathname.getName())) {
1280 return true;
1281 }
1282 return false;
1283 }
1284 }
1285
1286 try {
1287 // Get directory containing CPU info
1288 java.io.File dir = new java.io.File("/sys/devices/system/cpu/");
1289 // Filter to only list the devices we care about
1290 java.io.File[] files = dir.listFiles(new CpuFilter());
1291 // Return the number of cores (virtual CPU devices)
1292 return files.length;
1293 } catch (Exception e) {
1294 // Default to return 1 core
1295 Log.e(TAG, "Failed to count number of cores, defaulting to 1", e);
1296 return 1;
1297 }
1298 }
Sascha Haeberlinga2dd9ea2014-08-15 18:45:15 -07001299
1300 /**
1301 * Given the device orientation and Camera2 characteristics, this returns
1302 * the required JPEG rotation for this camera.
1303 *
1304 * @param deviceOrientationDegrees the device orientation in degrees.
1305 * @return The JPEG orientation in degrees.
1306 */
1307 public static int getJpegRotation(int deviceOrientationDegrees,
1308 CameraCharacteristics characteristics) {
1309 if (deviceOrientationDegrees == OrientationEventListener.ORIENTATION_UNKNOWN) {
1310 return 0;
1311 }
1312 int facing = characteristics.get(CameraCharacteristics.LENS_FACING);
1313 int sensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
1314 if (facing == CameraMetadata.LENS_FACING_FRONT) {
1315 return (sensorOrientation + deviceOrientationDegrees) % 360;
1316 } else {
1317 return (sensorOrientation - deviceOrientationDegrees + 360) % 360;
1318 }
1319 }
Michael Kolb8872c232013-01-29 10:33:22 -08001320}