CameraUtil.java revision 634246650a5ae72bb80ab4fe4be5da1afa23b684
1/* 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 17package com.android.camera.util; 18 19import android.app.Activity; 20import android.app.AlertDialog; 21import android.app.admin.DevicePolicyManager; 22import android.content.ActivityNotFoundException; 23import android.content.ComponentName; 24import android.content.ContentResolver; 25import android.content.Context; 26import android.content.DialogInterface; 27import android.content.Intent; 28import android.content.res.TypedArray; 29import android.graphics.Bitmap; 30import android.graphics.BitmapFactory; 31import android.graphics.Matrix; 32import android.graphics.Point; 33import android.graphics.Rect; 34import android.graphics.RectF; 35import android.hardware.Camera; 36import android.hardware.Camera.CameraInfo; 37import android.hardware.Camera.Parameters; 38import android.location.Location; 39import android.net.Uri; 40import android.os.ParcelFileDescriptor; 41import android.telephony.TelephonyManager; 42import android.util.DisplayMetrics; 43import android.util.FloatMath; 44import android.util.TypedValue; 45import android.view.Display; 46import 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; 52import android.widget.Toast; 53 54import com.android.camera.CameraActivity; 55import com.android.camera.CameraDisabledException; 56import com.android.camera.debug.Log; 57import com.android.camera.filmstrip.ImageData; 58import com.android.camera2.R; 59 60import java.io.Closeable; 61import java.io.IOException; 62import java.lang.reflect.Method; 63import java.text.SimpleDateFormat; 64import java.util.Date; 65import java.util.List; 66import java.util.Locale; 67import java.util.StringTokenizer; 68 69/** 70 * Collection of utility functions used in this package. 71 */ 72public class CameraUtil { 73 private static final Log.Tag TAG = new Log.Tag("Util"); 74 75 // 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 79 // 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 83 // Orientation hysteresis amount used in rounding, in degrees 84 public static final int ORIENTATION_HYSTERESIS = 5; 85 86 public static final String REVIEW_ACTION = "com.android.camera.action.REVIEW"; 87 // See android.hardware.Camera.ACTION_NEW_PICTURE. 88 public static final String ACTION_NEW_PICTURE = "android.hardware.action.NEW_PICTURE"; 89 // See android.hardware.Camera.ACTION_NEW_VIDEO. 90 public static final String ACTION_NEW_VIDEO = "android.hardware.action.NEW_VIDEO"; 91 92 // Broadcast Action: The camera application has become active in picture-taking mode. 93 public static final String ACTION_CAMERA_STARTED = "com.android.camera.action.CAMERA_STARTED"; 94 // Broadcast Action: The camera application is no longer in active picture-taking mode. 95 public static final String ACTION_CAMERA_STOPPED = "com.android.camera.action.CAMERA_STOPPED"; 96 // When the camera application is active in picture-taking mode, it listens for this intent, 97 // which upon receipt will trigger the shutter to capture a new picture, as if the user had 98 // pressed the shutter button. 99 public static final String ACTION_CAMERA_SHUTTER_CLICK = 100 "com.android.camera.action.SHUTTER_CLICK"; 101 102 // Fields from android.hardware.Camera.Parameters 103 public static final String FOCUS_MODE_CONTINUOUS_PICTURE = "continuous-picture"; 104 public static final String RECORDING_HINT = "recording-hint"; 105 private static final String AUTO_EXPOSURE_LOCK_SUPPORTED = "auto-exposure-lock-supported"; 106 private static final String AUTO_WHITE_BALANCE_LOCK_SUPPORTED = "auto-whitebalance-lock-supported"; 107 private static final String VIDEO_SNAPSHOT_SUPPORTED = "video-snapshot-supported"; 108 public static final String SCENE_MODE_HDR = "hdr"; 109 public static final String TRUE = "true"; 110 public static final String FALSE = "false"; 111 112 // Fields for the show-on-maps-functionality 113 private static final String MAPS_PACKAGE_NAME = "com.google.android.apps.maps"; 114 private static final String MAPS_CLASS_NAME = "com.google.android.maps.MapsActivity"; 115 116 /** Has to be in sync with the receiving MovieActivity. */ 117 public static final String KEY_TREAT_UP_AS_BACK = "treat-up-as-back"; 118 119 public static boolean isSupported(String value, List<String> supported) { 120 return supported == null ? false : supported.indexOf(value) >= 0; 121 } 122 123 public static boolean isAutoExposureLockSupported(Parameters params) { 124 return TRUE.equals(params.get(AUTO_EXPOSURE_LOCK_SUPPORTED)); 125 } 126 127 public static boolean isAutoWhiteBalanceLockSupported(Parameters params) { 128 return TRUE.equals(params.get(AUTO_WHITE_BALANCE_LOCK_SUPPORTED)); 129 } 130 131 public static boolean isVideoSnapshotSupported(Parameters params) { 132 return TRUE.equals(params.get(VIDEO_SNAPSHOT_SUPPORTED)); 133 } 134 135 public static boolean isCameraHdrSupported(Parameters params) { 136 List<String> supported = params.getSupportedSceneModes(); 137 return (supported != null) && supported.contains(SCENE_MODE_HDR); 138 } 139 140 public static boolean isMeteringAreaSupported(Parameters params) { 141 return params.getMaxNumMeteringAreas() > 0; 142 } 143 144 public static boolean isFocusAreaSupported(Parameters params) { 145 return (params.getMaxNumFocusAreas() > 0 146 && isSupported(Parameters.FOCUS_MODE_AUTO, 147 params.getSupportedFocusModes())); 148 } 149 150 // Private intent extras. Test only. 151 private static final String EXTRAS_CAMERA_FACING = 152 "android.intent.extras.CAMERA_FACING"; 153 154 private static float sPixelDensity = 1; 155 private static ImageFileNamer sImageFileNamer; 156 157 private CameraUtil() { 158 } 159 160 public static void initialize(Context context) { 161 DisplayMetrics metrics = new DisplayMetrics(); 162 WindowManager wm = (WindowManager) 163 context.getSystemService(Context.WINDOW_SERVICE); 164 wm.getDefaultDisplay().getMetrics(metrics); 165 sPixelDensity = metrics.density; 166 sImageFileNamer = new ImageFileNamer( 167 context.getString(R.string.image_file_name_format)); 168 } 169 170 public static int dpToPixel(int dp) { 171 return Math.round(sPixelDensity * dp); 172 } 173 174 // Rotates the bitmap by the specified degree. 175 // If a new bitmap is created, the original bitmap is recycled. 176 public static Bitmap rotate(Bitmap b, int degrees) { 177 return rotateAndMirror(b, degrees, false); 178 } 179 180 // Rotates and/or mirrors the bitmap. If a new bitmap is created, the 181 // original bitmap is recycled. 182 public static Bitmap rotateAndMirror(Bitmap b, int degrees, boolean mirror) { 183 if ((degrees != 0 || mirror) && b != null) { 184 Matrix m = new Matrix(); 185 // Mirror first. 186 // horizontal flip + rotation = -rotation + horizontal flip 187 if (mirror) { 188 m.postScale(-1, 1); 189 degrees = (degrees + 360) % 360; 190 if (degrees == 0 || degrees == 180) { 191 m.postTranslate(b.getWidth(), 0); 192 } else if (degrees == 90 || degrees == 270) { 193 m.postTranslate(b.getHeight(), 0); 194 } else { 195 throw new IllegalArgumentException("Invalid degrees=" + degrees); 196 } 197 } 198 if (degrees != 0) { 199 // clockwise 200 m.postRotate(degrees, 201 (float) b.getWidth() / 2, (float) b.getHeight() / 2); 202 } 203 204 try { 205 Bitmap b2 = Bitmap.createBitmap( 206 b, 0, 0, b.getWidth(), b.getHeight(), m, true); 207 if (b != b2) { 208 b.recycle(); 209 b = b2; 210 } 211 } catch (OutOfMemoryError ex) { 212 // We have no memory to rotate. Return the original bitmap. 213 } 214 } 215 return b; 216 } 217 218 /* 219 * Compute the sample size as a function of minSideLength 220 * and maxNumOfPixels. 221 * minSideLength is used to specify that minimal width or height of a 222 * bitmap. 223 * maxNumOfPixels is used to specify the maximal size in pixels that is 224 * tolerable in terms of memory usage. 225 * 226 * The function returns a sample size based on the constraints. 227 * Both size and minSideLength can be passed in as -1 228 * which indicates no care of the corresponding constraint. 229 * The functions prefers returning a sample size that 230 * generates a smaller bitmap, unless minSideLength = -1. 231 * 232 * Also, the function rounds up the sample size to a power of 2 or multiple 233 * of 8 because BitmapFactory only honors sample size this way. 234 * For example, BitmapFactory downsamples an image by 2 even though the 235 * request is 3. So we round up the sample size to avoid OOM. 236 */ 237 public static int computeSampleSize(BitmapFactory.Options options, 238 int minSideLength, int maxNumOfPixels) { 239 int initialSize = computeInitialSampleSize(options, minSideLength, 240 maxNumOfPixels); 241 242 int roundedSize; 243 if (initialSize <= 8) { 244 roundedSize = 1; 245 while (roundedSize < initialSize) { 246 roundedSize <<= 1; 247 } 248 } else { 249 roundedSize = (initialSize + 7) / 8 * 8; 250 } 251 252 return roundedSize; 253 } 254 255 private static int computeInitialSampleSize(BitmapFactory.Options options, 256 int minSideLength, int maxNumOfPixels) { 257 double w = options.outWidth; 258 double h = options.outHeight; 259 260 int lowerBound = (maxNumOfPixels < 0) ? 1 : 261 (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels)); 262 int upperBound = (minSideLength < 0) ? 128 : 263 (int) Math.min(Math.floor(w / minSideLength), 264 Math.floor(h / minSideLength)); 265 266 if (upperBound < lowerBound) { 267 // return the larger one when there is no overlapping zone. 268 return lowerBound; 269 } 270 271 if (maxNumOfPixels < 0 && minSideLength < 0) { 272 return 1; 273 } else if (minSideLength < 0) { 274 return lowerBound; 275 } else { 276 return upperBound; 277 } 278 } 279 280 public static Bitmap makeBitmap(byte[] jpegData, int maxNumOfPixels) { 281 try { 282 BitmapFactory.Options options = new BitmapFactory.Options(); 283 options.inJustDecodeBounds = true; 284 BitmapFactory.decodeByteArray(jpegData, 0, jpegData.length, 285 options); 286 if (options.mCancel || options.outWidth == -1 287 || options.outHeight == -1) { 288 return null; 289 } 290 options.inSampleSize = computeSampleSize( 291 options, -1, maxNumOfPixels); 292 options.inJustDecodeBounds = false; 293 294 options.inDither = false; 295 options.inPreferredConfig = Bitmap.Config.ARGB_8888; 296 return BitmapFactory.decodeByteArray(jpegData, 0, jpegData.length, 297 options); 298 } catch (OutOfMemoryError ex) { 299 Log.e(TAG, "Got oom exception ", ex); 300 return null; 301 } 302 } 303 304 public static void closeSilently(Closeable c) { 305 if (c == null) { 306 return; 307 } 308 try { 309 c.close(); 310 } catch (Throwable t) { 311 // do nothing 312 } 313 } 314 315 public static void Assert(boolean cond) { 316 if (!cond) { 317 throw new AssertionError(); 318 } 319 } 320 321 private static void throwIfCameraDisabled(Activity activity) throws CameraDisabledException { 322 // Check if device policy has disabled the camera. 323 DevicePolicyManager dpm = (DevicePolicyManager) activity.getSystemService( 324 Context.DEVICE_POLICY_SERVICE); 325 if (dpm.getCameraDisabled(null)) { 326 throw new CameraDisabledException(); 327 } 328 } 329 330 public static void showErrorAndFinish(final Activity activity, int msgId) { 331 DialogInterface.OnClickListener buttonListener = 332 new DialogInterface.OnClickListener() { 333 @Override 334 public void onClick(DialogInterface dialog, int which) { 335 activity.finish(); 336 } 337 }; 338 TypedValue out = new TypedValue(); 339 activity.getTheme().resolveAttribute(android.R.attr.alertDialogIcon, out, true); 340 new AlertDialog.Builder(activity) 341 .setCancelable(false) 342 .setTitle(R.string.camera_error_title) 343 .setMessage(msgId) 344 .setNeutralButton(R.string.dialog_ok, buttonListener) 345 .setIcon(out.resourceId) 346 .show(); 347 } 348 349 public static <T> T checkNotNull(T object) { 350 if (object == null) { 351 throw new NullPointerException(); 352 } 353 return object; 354 } 355 356 public static boolean equals(Object a, Object b) { 357 return (a == b) || (a == null ? false : a.equals(b)); 358 } 359 360 public static int nextPowerOf2(int n) { 361 n -= 1; 362 n |= n >>> 16; 363 n |= n >>> 8; 364 n |= n >>> 4; 365 n |= n >>> 2; 366 n |= n >>> 1; 367 return n + 1; 368 } 369 370 public static float distance(float x, float y, float sx, float sy) { 371 float dx = x - sx; 372 float dy = y - sy; 373 return (float) Math.sqrt(dx * dx + dy * dy); 374 } 375 376 public static int clamp(int x, int min, int max) { 377 if (x > max) { 378 return max; 379 } 380 if (x < min) { 381 return min; 382 } 383 return x; 384 } 385 386 public static float clamp(float x, float min, float max) { 387 if (x > max) { 388 return max; 389 } 390 if (x < min) { 391 return min; 392 } 393 return x; 394 } 395 396 public static int getDisplayRotation(Context context) { 397 WindowManager windowManager = (WindowManager) context 398 .getSystemService(Context.WINDOW_SERVICE); 399 int rotation = windowManager.getDefaultDisplay() 400 .getRotation(); 401 switch (rotation) { 402 case Surface.ROTATION_0: return 0; 403 case Surface.ROTATION_90: return 90; 404 case Surface.ROTATION_180: return 180; 405 case Surface.ROTATION_270: return 270; 406 } 407 return 0; 408 } 409 410 /** 411 * Calculate the default orientation of the device based on the width and 412 * height of the display when rotation = 0 (i.e. natural width and height) 413 * @param activity the activity context 414 * @return whether the default orientation of the device is portrait 415 */ 416 public static boolean isDefaultToPortrait(Activity activity) { 417 Display currentDisplay = activity.getWindowManager().getDefaultDisplay(); 418 Point displaySize = new Point(); 419 currentDisplay.getSize(displaySize); 420 int orientation = currentDisplay.getRotation(); 421 int naturalWidth, naturalHeight; 422 if (orientation == Surface.ROTATION_0 || orientation == Surface.ROTATION_180) { 423 naturalWidth = displaySize.x; 424 naturalHeight = displaySize.y; 425 } else { 426 naturalWidth = displaySize.y; 427 naturalHeight = displaySize.x; 428 } 429 return naturalWidth < naturalHeight; 430 } 431 432 public static int getDisplayOrientation(int degrees, int cameraId) { 433 // See android.hardware.Camera.setDisplayOrientation for 434 // documentation. 435 Camera.CameraInfo info = new Camera.CameraInfo(); 436 Camera.getCameraInfo(cameraId, info); 437 int result; 438 if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) { 439 result = (info.orientation + degrees) % 360; 440 result = (360 - result) % 360; // compensate the mirror 441 } else { // back-facing 442 result = (info.orientation - degrees + 360) % 360; 443 } 444 return result; 445 } 446 447 public static int getCameraOrientation(int cameraId) { 448 Camera.CameraInfo info = new Camera.CameraInfo(); 449 Camera.getCameraInfo(cameraId, info); 450 return info.orientation; 451 } 452 453 public static int roundOrientation(int orientation, int orientationHistory) { 454 boolean changeOrientation = false; 455 if (orientationHistory == OrientationEventListener.ORIENTATION_UNKNOWN) { 456 changeOrientation = true; 457 } else { 458 int dist = Math.abs(orientation - orientationHistory); 459 dist = Math.min( dist, 360 - dist ); 460 changeOrientation = ( dist >= 45 + ORIENTATION_HYSTERESIS ); 461 } 462 if (changeOrientation) { 463 return ((orientation + 45) / 90 * 90) % 360; 464 } 465 return orientationHistory; 466 } 467 468 private static Size getDefaultDisplaySize(Context context, Point size) { 469 WindowManager windowManager = (WindowManager) context 470 .getSystemService(Context.WINDOW_SERVICE); 471 windowManager.getDefaultDisplay().getSize(size); 472 return new Size(size); 473 } 474 475 public static Size getOptimalPreviewSize(Context context, 476 List<Size> sizes, double targetRatio) { 477 478 Point[] points = new Point[sizes.size()]; 479 480 int index = 0; 481 for (Size s : sizes) { 482 points[index++] = new Point(s.width, s.height); 483 } 484 485 int optimalPickIndex = getOptimalPreviewSize(context, points, targetRatio); 486 return (optimalPickIndex == -1) ? null : sizes.get(optimalPickIndex); 487 } 488 489 public static int getOptimalPreviewSize(Context context, 490 Point[] sizes, double targetRatio) { 491 // Use a very small tolerance because we want an exact match. 492 final double ASPECT_TOLERANCE = 0.01; 493 if (sizes == null) { 494 return -1; 495 } 496 497 int optimalSizeIndex = -1; 498 double minDiff = Double.MAX_VALUE; 499 500 // Because of bugs of overlay and layout, we sometimes will try to 501 // layout the viewfinder in the portrait orientation and thus get the 502 // wrong size of preview surface. When we change the preview size, the 503 // new overlay will be created before the old one closed, which causes 504 // an exception. For now, just get the screen size. 505 Size defaultDisplaySize = getDefaultDisplaySize(context, new Point()); 506 int targetHeight = Math.min(defaultDisplaySize.width, defaultDisplaySize.height); 507 // Try to find an size match aspect ratio and size 508 for (int i = 0; i < sizes.length; i++) { 509 Point size = sizes[i]; 510 double ratio = (double) size.x / size.y; 511 if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) { 512 continue; 513 } 514 if (Math.abs(size.y - targetHeight) < minDiff) { 515 optimalSizeIndex = i; 516 minDiff = Math.abs(size.y - targetHeight); 517 } 518 } 519 // Cannot find the one match the aspect ratio. This should not happen. 520 // Ignore the requirement. 521 if (optimalSizeIndex == -1) { 522 Log.w(TAG, "No preview size match the aspect ratio"); 523 minDiff = Double.MAX_VALUE; 524 for (int i = 0; i < sizes.length; i++) { 525 Point size = sizes[i]; 526 if (Math.abs(size.y - targetHeight) < minDiff) { 527 optimalSizeIndex = i; 528 minDiff = Math.abs(size.y - targetHeight); 529 } 530 } 531 } 532 return optimalSizeIndex; 533 } 534 535 // Returns the largest picture size which matches the given aspect ratio. 536 public static Size getOptimalVideoSnapshotPictureSize( 537 List<Size> sizes, double targetRatio) { 538 // Use a very small tolerance because we want an exact match. 539 final double ASPECT_TOLERANCE = 0.001; 540 if (sizes == null) { 541 return null; 542 } 543 544 Size optimalSize = null; 545 546 // Try to find a size matches aspect ratio and has the largest width 547 for (Size size : sizes) { 548 double ratio = (double) size.width / size.height; 549 if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) { 550 continue; 551 } 552 if (optimalSize == null || size.width > optimalSize.width) { 553 optimalSize = size; 554 } 555 } 556 557 // Cannot find one that matches the aspect ratio. This should not happen. 558 // Ignore the requirement. 559 if (optimalSize == null) { 560 Log.w(TAG, "No picture size match the aspect ratio"); 561 for (Size size : sizes) { 562 if (optimalSize == null || size.width > optimalSize.width) { 563 optimalSize = size; 564 } 565 } 566 } 567 return optimalSize; 568 } 569 570 public static void dumpParameters(Parameters parameters) { 571 String flattened = parameters.flatten(); 572 StringTokenizer tokenizer = new StringTokenizer(flattened, ";"); 573 Log.d(TAG, "Dump all camera parameters:"); 574 while (tokenizer.hasMoreElements()) { 575 Log.d(TAG, tokenizer.nextToken()); 576 } 577 } 578 579 /** 580 * Returns whether the device is voice-capable (meaning, it can do MMS). 581 */ 582 public static boolean isMmsCapable(Context context) { 583 TelephonyManager telephonyManager = (TelephonyManager) 584 context.getSystemService(Context.TELEPHONY_SERVICE); 585 if (telephonyManager == null) { 586 return false; 587 } 588 589 try { 590 Class<?> partypes[] = new Class[0]; 591 Method sIsVoiceCapable = TelephonyManager.class.getMethod( 592 "isVoiceCapable", partypes); 593 594 Object arglist[] = new Object[0]; 595 Object retobj = sIsVoiceCapable.invoke(telephonyManager, arglist); 596 return (Boolean) retobj; 597 } catch (java.lang.reflect.InvocationTargetException ite) { 598 // Failure, must be another device. 599 // Assume that it is voice capable. 600 } catch (IllegalAccessException iae) { 601 // Failure, must be an other device. 602 // Assume that it is voice capable. 603 } catch (NoSuchMethodException nsme) { 604 } 605 return true; 606 } 607 608 // This is for test only. Allow the camera to launch the specific camera. 609 public static int getCameraFacingIntentExtras(Activity currentActivity) { 610 int cameraId = -1; 611 612 int intentCameraId = 613 currentActivity.getIntent().getIntExtra(CameraUtil.EXTRAS_CAMERA_FACING, -1); 614 615 if (isFrontCameraIntent(intentCameraId)) { 616 // Check if the front camera exist 617 int frontCameraId = ((CameraActivity) currentActivity).getCameraProvider() 618 .getFirstFrontCameraId(); 619 if (frontCameraId != -1) { 620 cameraId = frontCameraId; 621 } 622 } else if (isBackCameraIntent(intentCameraId)) { 623 // Check if the back camera exist 624 int backCameraId = ((CameraActivity) currentActivity).getCameraProvider() 625 .getFirstBackCameraId(); 626 if (backCameraId != -1) { 627 cameraId = backCameraId; 628 } 629 } 630 return cameraId; 631 } 632 633 private static boolean isFrontCameraIntent(int intentCameraId) { 634 return (intentCameraId == android.hardware.Camera.CameraInfo.CAMERA_FACING_FRONT); 635 } 636 637 private static boolean isBackCameraIntent(int intentCameraId) { 638 return (intentCameraId == android.hardware.Camera.CameraInfo.CAMERA_FACING_BACK); 639 } 640 641 private static int sLocation[] = new int[2]; 642 643 // This method is not thread-safe. 644 public static boolean pointInView(float x, float y, View v) { 645 v.getLocationInWindow(sLocation); 646 return x >= sLocation[0] && x < (sLocation[0] + v.getWidth()) 647 && y >= sLocation[1] && y < (sLocation[1] + v.getHeight()); 648 } 649 650 public static int[] getRelativeLocation(View reference, View view) { 651 reference.getLocationInWindow(sLocation); 652 int referenceX = sLocation[0]; 653 int referenceY = sLocation[1]; 654 view.getLocationInWindow(sLocation); 655 sLocation[0] -= referenceX; 656 sLocation[1] -= referenceY; 657 return sLocation; 658 } 659 660 public static boolean isUriValid(Uri uri, ContentResolver resolver) { 661 if (uri == null) { 662 return false; 663 } 664 665 try { 666 ParcelFileDescriptor pfd = resolver.openFileDescriptor(uri, "r"); 667 if (pfd == null) { 668 Log.e(TAG, "Fail to open URI. URI=" + uri); 669 return false; 670 } 671 pfd.close(); 672 } catch (IOException ex) { 673 return false; 674 } 675 return true; 676 } 677 678 public static void dumpRect(RectF rect, String msg) { 679 Log.v(TAG, msg + "=(" + rect.left + "," + rect.top 680 + "," + rect.right + "," + rect.bottom + ")"); 681 } 682 683 public static void rectFToRect(RectF rectF, Rect rect) { 684 rect.left = Math.round(rectF.left); 685 rect.top = Math.round(rectF.top); 686 rect.right = Math.round(rectF.right); 687 rect.bottom = Math.round(rectF.bottom); 688 } 689 690 public static Rect rectFToRect(RectF rectF) { 691 Rect rect = new Rect(); 692 rectFToRect(rectF, rect); 693 return rect; 694 } 695 696 public static RectF rectToRectF(Rect r) { 697 return new RectF(r.left, r.top, r.right, r.bottom); 698 } 699 700 public static void prepareMatrix(Matrix matrix, boolean mirror, int displayOrientation, 701 int viewWidth, int viewHeight) { 702 // Need mirror for front camera. 703 matrix.setScale(mirror ? -1 : 1, 1); 704 // This is the value for android.hardware.Camera.setDisplayOrientation. 705 matrix.postRotate(displayOrientation); 706 // Camera driver coordinates range from (-1000, -1000) to (1000, 1000). 707 // UI coordinates range from (0, 0) to (width, height). 708 matrix.postScale(viewWidth / 2000f, viewHeight / 2000f); 709 matrix.postTranslate(viewWidth / 2f, viewHeight / 2f); 710 } 711 712 public static void prepareMatrix(Matrix matrix, boolean mirror, int displayOrientation, 713 Rect previewRect) { 714 // Need mirror for front camera. 715 matrix.setScale(mirror ? -1 : 1, 1); 716 // This is the value for android.hardware.Camera.setDisplayOrientation. 717 matrix.postRotate(displayOrientation); 718 719 // Camera driver coordinates range from (-1000, -1000) to (1000, 1000). 720 // We need to map camera driver coordinates to preview rect coordinates 721 Matrix mapping = new Matrix(); 722 mapping.setRectToRect(new RectF(-1000, -1000, 1000, 1000), rectToRectF(previewRect), 723 Matrix.ScaleToFit.FILL); 724 matrix.setConcat(mapping, matrix); 725 } 726 727 public static String createJpegName(long dateTaken) { 728 synchronized (sImageFileNamer) { 729 return sImageFileNamer.generateName(dateTaken); 730 } 731 } 732 733 public static void broadcastNewPicture(Context context, Uri uri) { 734 context.sendBroadcast(new Intent(ACTION_NEW_PICTURE, uri)); 735 // Keep compatibility 736 context.sendBroadcast(new Intent("com.android.camera.NEW_PICTURE", uri)); 737 } 738 739 public static void fadeIn(View view, float startAlpha, float endAlpha, long duration) { 740 if (view.getVisibility() == View.VISIBLE) { 741 return; 742 } 743 744 view.setVisibility(View.VISIBLE); 745 Animation animation = new AlphaAnimation(startAlpha, endAlpha); 746 animation.setDuration(duration); 747 view.startAnimation(animation); 748 } 749 750 public static void fadeIn(View view) { 751 fadeIn(view, 0F, 1F, 400); 752 753 // We disabled the button in fadeOut(), so enable it here. 754 view.setEnabled(true); 755 } 756 757 public static void fadeOut(View view) { 758 if (view.getVisibility() != View.VISIBLE) { 759 return; 760 } 761 762 // Since the button is still clickable before fade-out animation 763 // ends, we disable the button first to block click. 764 view.setEnabled(false); 765 Animation animation = new AlphaAnimation(1F, 0F); 766 animation.setDuration(400); 767 view.startAnimation(animation); 768 view.setVisibility(View.GONE); 769 } 770 771 public static int getJpegRotation(CameraInfo info, int orientation) { 772 // See android.hardware.Camera.Parameters.setRotation for 773 // documentation. 774 int rotation = 0; 775 if (orientation != OrientationEventListener.ORIENTATION_UNKNOWN) { 776 if (info.facing == CameraInfo.CAMERA_FACING_FRONT) { 777 rotation = (info.orientation - orientation + 360) % 360; 778 } else { // back-facing camera 779 rotation = (info.orientation + orientation) % 360; 780 } 781 } 782 return rotation; 783 } 784 785 /** 786 * Down-samples a jpeg byte array. 787 * @param data a byte array of jpeg data 788 * @param downSampleFactor down-sample factor 789 * @return decoded and down-sampled bitmap 790 */ 791 public static Bitmap downSample(final byte[] data, int downSampleFactor) { 792 final BitmapFactory.Options opts = new BitmapFactory.Options(); 793 // Downsample the image 794 opts.inSampleSize = downSampleFactor; 795 return BitmapFactory.decodeByteArray(data, 0, data.length, opts); 796 } 797 798 public static void setGpsParameters(Parameters parameters, Location loc) { 799 // Clear previous GPS location from the parameters. 800 parameters.removeGpsData(); 801 802 // We always encode GpsTimeStamp 803 parameters.setGpsTimestamp(System.currentTimeMillis() / 1000); 804 805 // Set GPS location. 806 if (loc != null) { 807 double lat = loc.getLatitude(); 808 double lon = loc.getLongitude(); 809 boolean hasLatLon = (lat != 0.0d) || (lon != 0.0d); 810 811 if (hasLatLon) { 812 Log.d(TAG, "Set gps location"); 813 parameters.setGpsLatitude(lat); 814 parameters.setGpsLongitude(lon); 815 parameters.setGpsProcessingMethod(loc.getProvider().toUpperCase()); 816 if (loc.hasAltitude()) { 817 parameters.setGpsAltitude(loc.getAltitude()); 818 } else { 819 // for NETWORK_PROVIDER location provider, we may have 820 // no altitude information, but the driver needs it, so 821 // we fake one. 822 parameters.setGpsAltitude(0); 823 } 824 if (loc.getTime() != 0) { 825 // Location.getTime() is UTC in milliseconds. 826 // gps-timestamp is UTC in seconds. 827 long utcTimeSeconds = loc.getTime() / 1000; 828 parameters.setGpsTimestamp(utcTimeSeconds); 829 } 830 } else { 831 loc = null; 832 } 833 } 834 } 835 836 /** 837 * For still image capture, we need to get the right fps range such that the 838 * camera can slow down the framerate to allow for less-noisy/dark 839 * viewfinder output in dark conditions. 840 * 841 * @param params Camera's parameters. 842 * @return null if no appropiate fps range can't be found. Otherwise, return 843 * the right range. 844 */ 845 public static int[] getPhotoPreviewFpsRange(Parameters params) { 846 return getPhotoPreviewFpsRange(params.getSupportedPreviewFpsRange()); 847 } 848 849 public static int[] getPhotoPreviewFpsRange(List<int[]> frameRates) { 850 if (frameRates.size() == 0) { 851 Log.e(TAG, "No suppoted frame rates returned!"); 852 return null; 853 } 854 855 // Find the lowest min rate in supported ranges who can cover 30fps. 856 int lowestMinRate = MAX_PREVIEW_FPS_TIMES_1000; 857 for (int[] rate : frameRates) { 858 int minFps = rate[Parameters.PREVIEW_FPS_MIN_INDEX]; 859 int maxFps = rate[Parameters.PREVIEW_FPS_MAX_INDEX]; 860 if (maxFps >= PREFERRED_PREVIEW_FPS_TIMES_1000 && 861 minFps <= PREFERRED_PREVIEW_FPS_TIMES_1000 && 862 minFps < lowestMinRate) { 863 lowestMinRate = minFps; 864 } 865 } 866 867 // Find all the modes with the lowest min rate found above, the pick the 868 // one with highest max rate. 869 int resultIndex = -1; 870 int highestMaxRate = 0; 871 for (int i = 0; i < frameRates.size(); i++) { 872 int[] rate = frameRates.get(i); 873 int minFps = rate[Parameters.PREVIEW_FPS_MIN_INDEX]; 874 int maxFps = rate[Parameters.PREVIEW_FPS_MAX_INDEX]; 875 if (minFps == lowestMinRate && highestMaxRate < maxFps) { 876 highestMaxRate = maxFps; 877 resultIndex = i; 878 } 879 } 880 881 if (resultIndex >= 0) { 882 return frameRates.get(resultIndex); 883 } 884 Log.e(TAG, "Can't find an appropiate frame rate range!"); 885 return null; 886 } 887 888 public static int[] getMaxPreviewFpsRange(Parameters params) { 889 List<int[]> frameRates = params.getSupportedPreviewFpsRange(); 890 if (frameRates != null && frameRates.size() > 0) { 891 // The list is sorted. Return the last element. 892 return frameRates.get(frameRates.size() - 1); 893 } 894 return new int[0]; 895 } 896 897 public static void throwIfCameraDisabled(Context context) throws CameraDisabledException { 898 // Check if device policy has disabled the camera. 899 DevicePolicyManager dpm = 900 (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE); 901 if (dpm.getCameraDisabled(null)) { 902 throw new CameraDisabledException(); 903 } 904 } 905 906 /** 907 * Generates a 1d Gaussian mask of the input array size, and store the mask 908 * in the input array. 909 * 910 * @param mask empty array of size n, where n will be used as the size of the 911 * Gaussian mask, and the array will be populated with the values 912 * of the mask. 913 */ 914 private static void getGaussianMask(float[] mask) { 915 int len = mask.length; 916 int mid = len / 2; 917 float sigma = len; 918 float sum = 0; 919 for (int i = 0; i <= mid; i++) { 920 float ex = FloatMath.exp(-(i - mid) * (i - mid) / (mid * mid)) 921 / (2 * sigma * sigma); 922 int symmetricIndex = len - 1 - i; 923 mask[i] = ex; 924 mask[symmetricIndex] = ex; 925 sum += mask[i]; 926 if (i != symmetricIndex) { 927 sum += mask[symmetricIndex]; 928 } 929 } 930 931 for (int i = 0; i < mask.length; i++) { 932 mask[i] /= sum; 933 } 934 935 } 936 937 /** 938 * Add two pixels together where the second pixel will be applied with a weight. 939 * 940 * @param pixel pixel color value of weight 1 941 * @param newPixel second pixel color value where the weight will be applied 942 * @param weight a float weight that will be applied to the second pixel color 943 * @return the weighted addition of the two pixels 944 */ 945 public static int addPixel(int pixel, int newPixel, float weight) { 946 // TODO: scale weight to [0, 1024] to avoid casting to float and back to int. 947 int r = ((pixel & 0x00ff0000) + (int) ((newPixel & 0x00ff0000) * weight)) & 0x00ff0000; 948 int g = ((pixel & 0x0000ff00) + (int) ((newPixel & 0x0000ff00) * weight)) & 0x0000ff00; 949 int b = ((pixel & 0x000000ff) + (int) ((newPixel & 0x000000ff) * weight)) & 0x000000ff; 950 return 0xff000000 | r | g | b; 951 } 952 953 /** 954 * Apply blur to the input image represented in an array of colors and put the 955 * output image, in the form of an array of colors, into the output array. 956 * 957 * @param src source array of colors 958 * @param out output array of colors after the blur 959 * @param w width of the image 960 * @param h height of the image 961 * @param size size of the Gaussian blur mask 962 */ 963 public static void blur(int[] src, int[] out, int w, int h, int size) { 964 float[] k = new float[size]; 965 int off = size / 2; 966 967 getGaussianMask(k); 968 969 int[] tmp = new int[src.length]; 970 971 // Apply the 1d Gaussian mask horizontally to the image and put the intermediate 972 // results in a temporary array. 973 int rowPointer = 0; 974 for (int y = 0; y < h; y++) { 975 for (int x = 0; x < w; x++) { 976 int sum = 0; 977 for (int i = 0; i < k.length; i++) { 978 int dx = x + i - off; 979 dx = clamp(dx, 0, w - 1); 980 sum = addPixel(sum, src[rowPointer + dx], k[i]); 981 } 982 tmp[x + rowPointer] = sum; 983 } 984 rowPointer += w; 985 } 986 987 // Apply the 1d Gaussian mask vertically to the intermediate array, and 988 // the final results will be stored in the output array. 989 for (int x = 0; x < w; x++) { 990 rowPointer = 0; 991 for (int y = 0; y < h; y++) { 992 int sum = 0; 993 for (int i = 0; i < k.length; i++) { 994 int dy = y + i - off; 995 dy = clamp(dy, 0, h - 1); 996 sum = addPixel(sum, tmp[dy * w + x], k[i]); 997 } 998 out[x + rowPointer] = sum; 999 rowPointer += w; 1000 } 1001 } 1002 } 1003 1004 /** 1005 * Calculates a new dimension to fill the bound with the original aspect 1006 * ratio preserved. 1007 * 1008 * @param imageWidth The original width. 1009 * @param imageHeight The original height. 1010 * @param imageRotation The clockwise rotation in degrees of the image 1011 * which the original dimension comes from. 1012 * @param boundWidth The width of the bound. 1013 * @param boundHeight The height of the bound. 1014 * 1015 * @returns The final width/height stored in Point.x/Point.y to fill the 1016 * bounds and preserve image aspect ratio. 1017 */ 1018 public static Point resizeToFill(int imageWidth, int imageHeight, int imageRotation, 1019 int boundWidth, int boundHeight) { 1020 if (imageRotation % 180 != 0) { 1021 // Swap width and height. 1022 int savedWidth = imageWidth; 1023 imageWidth = imageHeight; 1024 imageHeight = savedWidth; 1025 } 1026 if (imageWidth == ImageData.SIZE_FULL 1027 || imageHeight == ImageData.SIZE_FULL) { 1028 imageWidth = boundWidth; 1029 imageHeight = boundHeight; 1030 } 1031 1032 Point p = new Point(); 1033 p.x = boundWidth; 1034 p.y = boundHeight; 1035 1036 if (imageWidth * boundHeight > boundWidth * imageHeight) { 1037 p.y = imageHeight * p.x / imageWidth; 1038 } else { 1039 p.x = imageWidth * p.y / imageHeight; 1040 } 1041 1042 return p; 1043 } 1044 1045 private static class ImageFileNamer { 1046 private final SimpleDateFormat mFormat; 1047 1048 // The date (in milliseconds) used to generate the last name. 1049 private long mLastDate; 1050 1051 // Number of names generated for the same second. 1052 private int mSameSecondCount; 1053 1054 public ImageFileNamer(String format) { 1055 mFormat = new SimpleDateFormat(format); 1056 } 1057 1058 public String generateName(long dateTaken) { 1059 Date date = new Date(dateTaken); 1060 String result = mFormat.format(date); 1061 1062 // If the last name was generated for the same second, 1063 // we append _1, _2, etc to the name. 1064 if (dateTaken / 1000 == mLastDate / 1000) { 1065 mSameSecondCount++; 1066 result += "_" + mSameSecondCount; 1067 } else { 1068 mLastDate = dateTaken; 1069 mSameSecondCount = 0; 1070 } 1071 1072 return result; 1073 } 1074 } 1075 1076 public static void playVideo(Activity activity, Uri uri, String title) { 1077 try { 1078 boolean isSecureCamera = ((CameraActivity)activity).isSecureCamera(); 1079 if (!isSecureCamera) { 1080 Intent intent = IntentHelper.getVideoPlayerIntent(activity, uri) 1081 .putExtra(Intent.EXTRA_TITLE, title) 1082 .putExtra(KEY_TREAT_UP_AS_BACK, true); 1083 activity.startActivityForResult(intent, CameraActivity.REQ_CODE_DONT_SWITCH_TO_PREVIEW); 1084 } else { 1085 // In order not to send out any intent to be intercepted and 1086 // show the lock screen immediately, we just let the secure 1087 // camera activity finish. 1088 activity.finish(); 1089 } 1090 } catch (ActivityNotFoundException e) { 1091 Toast.makeText(activity, activity.getString(R.string.video_err), 1092 Toast.LENGTH_SHORT).show(); 1093 } 1094 } 1095 1096 /** 1097 * Starts GMM with the given location shown. If this fails, and GMM could 1098 * not be found, we use a geo intent as a fallback. 1099 * 1100 * @param activity the activity to use for launching the Maps intent. 1101 * @param latLong a 2-element array containing {latitude/longitude}. 1102 */ 1103 public static void showOnMap(Activity activity, double[] latLong) { 1104 try { 1105 // We don't use "geo:latitude,longitude" because it only centers 1106 // the MapView to the specified location, but we need a marker 1107 // for further operations (routing to/from). 1108 // The q=(lat, lng) syntax is suggested by geo-team. 1109 String uri = String.format(Locale.ENGLISH, "http://maps.google.com/maps?f=q&q=(%f,%f)", 1110 latLong[0], latLong[1]); 1111 ComponentName compName = new ComponentName(MAPS_PACKAGE_NAME, 1112 MAPS_CLASS_NAME); 1113 Intent mapsIntent = new Intent(Intent.ACTION_VIEW, 1114 Uri.parse(uri)).setComponent(compName); 1115 activity.startActivityForResult(mapsIntent, 1116 CameraActivity.REQ_CODE_DONT_SWITCH_TO_PREVIEW); 1117 } catch (ActivityNotFoundException e) { 1118 // Use the "geo intent" if no GMM is installed 1119 Log.e(TAG, "GMM activity not found!", e); 1120 String url = String.format(Locale.ENGLISH, "geo:%f,%f", latLong[0], latLong[1]); 1121 Intent mapsIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); 1122 activity.startActivity(mapsIntent); 1123 } 1124 } 1125 1126 /** 1127 * Dumps the stack trace. 1128 * 1129 * @param level How many levels of the stack are dumped. 0 means all. 1130 * @return A {@link java.lang.String} of all the output with newline 1131 * between each. 1132 */ 1133 public static String dumpStackTrace(int level) { 1134 StackTraceElement[] elems = Thread.currentThread().getStackTrace(); 1135 // Ignore the first 3 elements. 1136 level = (level == 0 ? elems.length : Math.min(level + 3, elems.length)); 1137 String ret = new String(); 1138 for (int i = 3; i < level; i++) { 1139 ret = ret + "\t" + elems[i].toString() + '\n'; 1140 } 1141 return ret; 1142 } 1143 1144 1145 /** 1146 * Gets the theme color of a specific mode. 1147 * 1148 * @param modeIndex index of the mode 1149 * @param context current context 1150 * @return theme color of the mode if input index is valid, otherwise 0 1151 */ 1152 public static int getCameraThemeColorId(int modeIndex, Context context) { 1153 1154 // Find the theme color using id from the color array 1155 TypedArray colorRes = context.getResources() 1156 .obtainTypedArray(R.array.camera_mode_theme_color); 1157 if (modeIndex >= colorRes.length() || modeIndex < 0) { 1158 // Mode index not found 1159 Log.e(TAG, "Invalid mode index: " + modeIndex); 1160 return 0; 1161 } 1162 return colorRes.getResourceId(modeIndex, 0); 1163 } 1164 1165 /** 1166 * Gets the mode icon resource id of a specific mode. 1167 * 1168 * @param modeIndex index of the mode 1169 * @param context current context 1170 * @return icon resource id if the index is valid, otherwise 0 1171 */ 1172 public static int getCameraModeIconResId(int modeIndex, Context context) { 1173 // Find the camera mode icon using id 1174 TypedArray cameraModesIcons = context.getResources() 1175 .obtainTypedArray(R.array.camera_mode_icon); 1176 if (modeIndex >= cameraModesIcons.length() || modeIndex < 0) { 1177 // Mode index not found 1178 Log.e(TAG, "Invalid mode index: " + modeIndex); 1179 return 0; 1180 } 1181 return cameraModesIcons.getResourceId(modeIndex, 0); 1182 } 1183 1184 /** 1185 * Gets the mode text of a specific mode. 1186 * 1187 * @param modeIndex index of the mode 1188 * @param context current context 1189 * @return mode text if the index is valid, otherwise a new empty string 1190 */ 1191 public static String getCameraModeText(int modeIndex, Context context) { 1192 // Find the camera mode icon using id 1193 String[] cameraModesText = context.getResources() 1194 .getStringArray(R.array.camera_mode_text); 1195 if (modeIndex < 0 || modeIndex >= cameraModesText.length) { 1196 Log.e(TAG, "Invalid mode index: " + modeIndex); 1197 return new String(); 1198 } 1199 return cameraModesText[modeIndex]; 1200 } 1201 1202 /** 1203 * Gets the mode content description of a specific mode. 1204 * 1205 * @param modeIndex index of the mode 1206 * @param context current context 1207 * @return mode content description if the index is valid, otherwise a new empty string 1208 */ 1209 public static String getCameraModeContentDescription(int modeIndex, Context context) { 1210 String[] cameraModesDesc = context.getResources() 1211 .getStringArray(R.array.camera_mode_content_description); 1212 if (modeIndex < 0 || modeIndex >= cameraModesDesc.length) { 1213 Log.e(TAG, "Invalid mode index: " + modeIndex); 1214 return new String(); 1215 } 1216 return cameraModesDesc[modeIndex]; 1217 } 1218 1219 /** 1220 * Gets the shutter icon res id for a specific mode. 1221 * 1222 * @param modeIndex index of the mode 1223 * @param context current context 1224 * @return mode shutter icon id if the index is valid, otherwise 0. 1225 */ 1226 public static int getCameraShutterIconId(int modeIndex, Context context) { 1227 // Find the camera mode icon using id 1228 TypedArray shutterIcons = context.getResources() 1229 .obtainTypedArray(R.array.camera_mode_shutter_icon); 1230 if (modeIndex < 0 || modeIndex >= shutterIcons.length()) { 1231 Log.e(TAG, "Invalid mode index: " + modeIndex); 1232 return 0; 1233 } 1234 return shutterIcons.getResourceId(modeIndex, 0); 1235 } 1236 1237 /** 1238 * Gets the parent mode that hosts a specific mode in nav drawer. 1239 * 1240 * @param modeIndex index of the mode 1241 * @param context current context 1242 * @return mode id if the index is valid, otherwise 0 1243 */ 1244 public static int getCameraModeParentModeId(int modeIndex, Context context) { 1245 // Find the camera mode icon using id 1246 int[] cameraModeParent = context.getResources() 1247 .getIntArray(R.array.camera_mode_nested_in_nav_drawer); 1248 if (modeIndex < 0 || modeIndex >= cameraModeParent.length) { 1249 Log.e(TAG, "Invalid mode index: " + modeIndex); 1250 return 0; 1251 } 1252 return cameraModeParent[modeIndex]; 1253 } 1254 1255 /** 1256 * Gets the mode cover icon resource id of a specific mode. 1257 * 1258 * @param modeIndex index of the mode 1259 * @param context current context 1260 * @return icon resource id if the index is valid, otherwise 0 1261 */ 1262 public static int getCameraModeCoverIconResId(int modeIndex, Context context) { 1263 // Find the camera mode icon using id 1264 TypedArray cameraModesIcons = context.getResources() 1265 .obtainTypedArray(R.array.camera_mode_cover_icon); 1266 if (modeIndex >= cameraModesIcons.length() || modeIndex < 0) { 1267 // Mode index not found 1268 Log.e(TAG, "Invalid mode index: " + modeIndex); 1269 return 0; 1270 } 1271 return cameraModesIcons.getResourceId(modeIndex, 0); 1272 } 1273} 1274