Util.java revision db0757dc9c627e7c5206104664028e386ade7d03
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; 18 19import android.app.Activity; 20import android.app.AlertDialog; 21import android.content.Context; 22import android.content.DialogInterface; 23import android.graphics.Bitmap; 24import android.graphics.BitmapFactory; 25import android.graphics.Matrix; 26import android.hardware.Camera; 27import android.hardware.Camera.Parameters; 28import android.hardware.Camera.Size; 29import android.telephony.TelephonyManager; 30import android.util.Log; 31import android.view.Display; 32import android.view.Surface; 33import android.view.View; 34import android.view.animation.Animation; 35import android.view.animation.TranslateAnimation; 36 37import java.io.Closeable; 38import java.lang.reflect.Method; 39import java.util.List; 40import java.util.StringTokenizer; 41 42/** 43 * Collection of utility functions used in this package. 44 */ 45public class Util { 46 private static final String TAG = "Util"; 47 public static final int DIRECTION_LEFT = 0; 48 public static final int DIRECTION_RIGHT = 1; 49 public static final int DIRECTION_UP = 2; 50 public static final int DIRECTION_DOWN = 3; 51 52 public static final String REVIEW_ACTION = "com.android.camera.action.REVIEW"; 53 54 // Private intent extras. Test only. 55 public static final String EXTRAS_CAMERA_FACING = 56 "android.intent.extras.CAMERA_FACING"; 57 58 private Util() { 59 } 60 61 // Rotates the bitmap by the specified degree. 62 // If a new bitmap is created, the original bitmap is recycled. 63 public static Bitmap rotate(Bitmap b, int degrees) { 64 return rotateAndMirror(b, degrees, false); 65 } 66 67 // Rotates and/or mirrors the bitmap. If a new bitmap is created, the 68 // original bitmap is recycled. 69 public static Bitmap rotateAndMirror(Bitmap b, int degrees, boolean mirror) { 70 if ((degrees != 0 || mirror) && b != null) { 71 Matrix m = new Matrix(); 72 m.setRotate(degrees, 73 (float) b.getWidth() / 2, (float) b.getHeight() / 2); 74 if (mirror) { 75 m.postScale(-1, 1); 76 degrees = (degrees + 360) % 360; 77 if (degrees == 0 || degrees == 180) { 78 m.postTranslate((float) b.getWidth(), 0); 79 } else if (degrees == 90 || degrees == 270) { 80 m.postTranslate((float) b.getHeight(), 0); 81 } else { 82 throw new IllegalArgumentException("Invalid degrees=" + degrees); 83 } 84 } 85 86 try { 87 Bitmap b2 = Bitmap.createBitmap( 88 b, 0, 0, b.getWidth(), b.getHeight(), m, true); 89 if (b != b2) { 90 b.recycle(); 91 b = b2; 92 } 93 } catch (OutOfMemoryError ex) { 94 // We have no memory to rotate. Return the original bitmap. 95 } 96 } 97 return b; 98 } 99 100 /* 101 * Compute the sample size as a function of minSideLength 102 * and maxNumOfPixels. 103 * minSideLength is used to specify that minimal width or height of a 104 * bitmap. 105 * maxNumOfPixels is used to specify the maximal size in pixels that is 106 * tolerable in terms of memory usage. 107 * 108 * The function returns a sample size based on the constraints. 109 * Both size and minSideLength can be passed in as -1 110 * which indicates no care of the corresponding constraint. 111 * The functions prefers returning a sample size that 112 * generates a smaller bitmap, unless minSideLength = -1. 113 * 114 * Also, the function rounds up the sample size to a power of 2 or multiple 115 * of 8 because BitmapFactory only honors sample size this way. 116 * For example, BitmapFactory downsamples an image by 2 even though the 117 * request is 3. So we round up the sample size to avoid OOM. 118 */ 119 public static int computeSampleSize(BitmapFactory.Options options, 120 int minSideLength, int maxNumOfPixels) { 121 int initialSize = computeInitialSampleSize(options, minSideLength, 122 maxNumOfPixels); 123 124 int roundedSize; 125 if (initialSize <= 8) { 126 roundedSize = 1; 127 while (roundedSize < initialSize) { 128 roundedSize <<= 1; 129 } 130 } else { 131 roundedSize = (initialSize + 7) / 8 * 8; 132 } 133 134 return roundedSize; 135 } 136 137 private static int computeInitialSampleSize(BitmapFactory.Options options, 138 int minSideLength, int maxNumOfPixels) { 139 double w = options.outWidth; 140 double h = options.outHeight; 141 142 int lowerBound = (maxNumOfPixels < 0) ? 1 : 143 (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels)); 144 int upperBound = (minSideLength < 0) ? 128 : 145 (int) Math.min(Math.floor(w / minSideLength), 146 Math.floor(h / minSideLength)); 147 148 if (upperBound < lowerBound) { 149 // return the larger one when there is no overlapping zone. 150 return lowerBound; 151 } 152 153 if (maxNumOfPixels < 0 && minSideLength < 0) { 154 return 1; 155 } else if (minSideLength < 0) { 156 return lowerBound; 157 } else { 158 return upperBound; 159 } 160 } 161 162 public static Bitmap makeBitmap(byte[] jpegData, int maxNumOfPixels) { 163 try { 164 BitmapFactory.Options options = new BitmapFactory.Options(); 165 options.inJustDecodeBounds = true; 166 BitmapFactory.decodeByteArray(jpegData, 0, jpegData.length, 167 options); 168 if (options.mCancel || options.outWidth == -1 169 || options.outHeight == -1) { 170 return null; 171 } 172 options.inSampleSize = computeSampleSize( 173 options, -1, maxNumOfPixels); 174 options.inJustDecodeBounds = false; 175 176 options.inDither = false; 177 options.inPreferredConfig = Bitmap.Config.ARGB_8888; 178 return BitmapFactory.decodeByteArray(jpegData, 0, jpegData.length, 179 options); 180 } catch (OutOfMemoryError ex) { 181 Log.e(TAG, "Got oom exception ", ex); 182 return null; 183 } 184 } 185 186 public static void closeSilently(Closeable c) { 187 if (c == null) return; 188 try { 189 c.close(); 190 } catch (Throwable t) { 191 // do nothing 192 } 193 } 194 195 public static void Assert(boolean cond) { 196 if (!cond) { 197 throw new AssertionError(); 198 } 199 } 200 201 public static void showFatalErrorAndFinish( 202 final Activity activity, String title, String message) { 203 DialogInterface.OnClickListener buttonListener = 204 new DialogInterface.OnClickListener() { 205 public void onClick(DialogInterface dialog, int which) { 206 activity.finish(); 207 } 208 }; 209 new AlertDialog.Builder(activity) 210 .setCancelable(false) 211 .setIconAttribute(android.R.attr.alertDialogIcon) 212 .setTitle(title) 213 .setMessage(message) 214 .setNeutralButton(R.string.details_ok, buttonListener) 215 .show(); 216 } 217 218 public static Animation slideOut(View view, int to) { 219 view.setVisibility(View.INVISIBLE); 220 Animation anim; 221 switch (to) { 222 case DIRECTION_LEFT: 223 anim = new TranslateAnimation(0, -view.getWidth(), 0, 0); 224 break; 225 case DIRECTION_RIGHT: 226 anim = new TranslateAnimation(0, view.getWidth(), 0, 0); 227 break; 228 case DIRECTION_UP: 229 anim = new TranslateAnimation(0, 0, 0, -view.getHeight()); 230 break; 231 case DIRECTION_DOWN: 232 anim = new TranslateAnimation(0, 0, 0, view.getHeight()); 233 break; 234 default: 235 throw new IllegalArgumentException(Integer.toString(to)); 236 } 237 anim.setDuration(500); 238 view.startAnimation(anim); 239 return anim; 240 } 241 242 public static Animation slideIn(View view, int from) { 243 view.setVisibility(View.VISIBLE); 244 Animation anim; 245 switch (from) { 246 case DIRECTION_LEFT: 247 anim = new TranslateAnimation(-view.getWidth(), 0, 0, 0); 248 break; 249 case DIRECTION_RIGHT: 250 anim = new TranslateAnimation(view.getWidth(), 0, 0, 0); 251 break; 252 case DIRECTION_UP: 253 anim = new TranslateAnimation(0, 0, -view.getHeight(), 0); 254 break; 255 case DIRECTION_DOWN: 256 anim = new TranslateAnimation(0, 0, view.getHeight(), 0); 257 break; 258 default: 259 throw new IllegalArgumentException(Integer.toString(from)); 260 } 261 anim.setDuration(500); 262 view.startAnimation(anim); 263 return anim; 264 } 265 266 public static <T> T checkNotNull(T object) { 267 if (object == null) throw new NullPointerException(); 268 return object; 269 } 270 271 public static boolean equals(Object a, Object b) { 272 return (a == b) || (a == null ? false : a.equals(b)); 273 } 274 275 public static boolean isPowerOf2(int n) { 276 return (n & -n) == n; 277 } 278 279 public static int nextPowerOf2(int n) { 280 n -= 1; 281 n |= n >>> 16; 282 n |= n >>> 8; 283 n |= n >>> 4; 284 n |= n >>> 2; 285 n |= n >>> 1; 286 return n + 1; 287 } 288 289 public static float distance(float x, float y, float sx, float sy) { 290 float dx = x - sx; 291 float dy = y - sy; 292 return (float) Math.sqrt(dx * dx + dy * dy); 293 } 294 295 public static int clamp(int x, int min, int max) { 296 if (x > max) return max; 297 if (x < min) return min; 298 return x; 299 } 300 301 public static int getDisplayRotation(Activity activity) { 302 int rotation = activity.getWindowManager().getDefaultDisplay() 303 .getRotation(); 304 switch (rotation) { 305 case Surface.ROTATION_0: return 0; 306 case Surface.ROTATION_90: return 90; 307 case Surface.ROTATION_180: return 180; 308 case Surface.ROTATION_270: return 270; 309 } 310 return 0; 311 } 312 313 public static void setCameraDisplayOrientation(Activity activity, 314 int cameraId, Camera camera) { 315 // See android.hardware.Camera.setCameraDisplayOrientation for 316 // documentation. 317 Camera.CameraInfo info = new Camera.CameraInfo(); 318 Camera.getCameraInfo(cameraId, info); 319 int degrees = getDisplayRotation(activity); 320 int result; 321 if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) { 322 result = (info.orientation + degrees) % 360; 323 result = (360 - result) % 360; // compensate the mirror 324 } else { // back-facing 325 result = (info.orientation - degrees + 360) % 360; 326 } 327 camera.setDisplayOrientation(result); 328 } 329 330 public static Size getOptimalPreviewSize(Activity currentActivity, 331 List<Size> sizes, double targetRatio) { 332 // Use a very small tolerance because we want an exact match. 333 final double ASPECT_TOLERANCE = 0.001; 334 if (sizes == null) return null; 335 336 Size optimalSize = null; 337 double minDiff = Double.MAX_VALUE; 338 339 // Because of bugs of overlay and layout, we sometimes will try to 340 // layout the viewfinder in the portrait orientation and thus get the 341 // wrong size of mSurfaceView. When we change the preview size, the 342 // new overlay will be created before the old one closed, which causes 343 // an exception. For now, just get the screen size 344 345 Display display = currentActivity.getWindowManager().getDefaultDisplay(); 346 int targetHeight = Math.min(display.getHeight(), display.getWidth()); 347 348 if (targetHeight <= 0) { 349 // We don't know the size of SurfaceView, use screen height 350 targetHeight = display.getHeight(); 351 } 352 353 // Try to find an size match aspect ratio and size 354 for (Size size : sizes) { 355 double ratio = (double) size.width / size.height; 356 if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue; 357 if (Math.abs(size.height - targetHeight) < minDiff) { 358 optimalSize = size; 359 minDiff = Math.abs(size.height - targetHeight); 360 } 361 } 362 363 // Cannot find the one match the aspect ratio. This should not happen. 364 // Ignore the requirement. 365 if (optimalSize == null) { 366 Log.w(TAG, "No preview size match the aspect ratio"); 367 minDiff = Double.MAX_VALUE; 368 for (Size size : sizes) { 369 if (Math.abs(size.height - targetHeight) < minDiff) { 370 optimalSize = size; 371 minDiff = Math.abs(size.height - targetHeight); 372 } 373 } 374 } 375 return optimalSize; 376 } 377 378 public static void dumpParameters(Parameters parameters) { 379 String flattened = parameters.flatten(); 380 StringTokenizer tokenizer = new StringTokenizer(flattened, ";"); 381 Log.d(TAG, "Dump all camera parameters:"); 382 while (tokenizer.hasMoreElements()) { 383 Log.d(TAG, tokenizer.nextToken()); 384 } 385 } 386 387 /** 388 * Returns whether the device is voice-capable (meaning, it can do MMS). 389 */ 390 public static boolean isMmsCapable(Context context) { 391 TelephonyManager telephonyManager = (TelephonyManager) 392 context.getSystemService(Context.TELEPHONY_SERVICE); 393 if (telephonyManager == null) { 394 return false; 395 } 396 397 try { 398 Class partypes[] = new Class[0]; 399 Method sIsVoiceCapable = TelephonyManager.class.getMethod( 400 "isVoiceCapable", partypes); 401 402 Object arglist[] = new Object[0]; 403 Object retobj = sIsVoiceCapable.invoke(telephonyManager, arglist); 404 return (Boolean) retobj; 405 } catch (java.lang.reflect.InvocationTargetException ite) { 406 // Failure, must be another device. 407 // Assume that it is voice capable. 408 } catch (java.lang.IllegalAccessException iae) { 409 // Failure, must be an other device. 410 // Assume that it is voice capable. 411 } catch (NoSuchMethodException nsme) { 412 } 413 return true; 414 } 415 416 // This is for test only. Allow the camera to launch the specific camera. 417 public static int getCameraFacingIntentExtras(Activity currentActivity) { 418 int cameraId = -1; 419 420 int intentCameraId = 421 currentActivity.getIntent().getIntExtra(Util.EXTRAS_CAMERA_FACING, -1); 422 423 if (isFrontCameraIntent(intentCameraId)) { 424 // Check if the front camera exist 425 int frontCameraId = CameraHolder.instance().getFrontCameraId(); 426 if (frontCameraId != -1) { 427 cameraId = frontCameraId; 428 } 429 } else if (isBackCameraIntent(intentCameraId)) { 430 // Check if the back camera exist 431 int backCameraId = CameraHolder.instance().getBackCameraId(); 432 if (backCameraId != -1) { 433 cameraId = backCameraId; 434 } 435 } 436 return cameraId; 437 } 438 439 private static boolean isFrontCameraIntent(int intentCameraId) { 440 return (intentCameraId == android.hardware.Camera.CameraInfo.CAMERA_FACING_FRONT); 441 } 442 443 private static boolean isBackCameraIntent(int intentCameraId) { 444 return (intentCameraId == android.hardware.Camera.CameraInfo.CAMERA_FACING_BACK); 445 } 446 447} 448