1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
| public class Camera2Helper { private static final String TAG = "Camera2Helper";
private Point maxPreviewSize; private Point minPreviewSize;
public static final String CAMERA_ID_FRONT = "1"; public static final String CAMERA_ID_BACK = "0";
private String mCameraId; private String specificCameraId; private Camera2Listener camera2Listener; private TextureView mTextureView; private int rotation; private Point previewViewSize; private Point specificPreviewSize; private boolean isMirror; private Context context; private boolean mCalibrated; private boolean mIsVertical = true;
private CameraCaptureSession mCaptureSession;
private CameraDevice mCameraDevice;
private Size mPreviewSize;
private Camera2Helper(Camera2Helper.Builder builder) { mTextureView = builder.previewDisplayView; specificCameraId = builder.specificCameraId; camera2Listener = builder.camera2Listener; rotation = builder.rotation; previewViewSize = builder.previewViewSize; specificPreviewSize = builder.previewSize; maxPreviewSize = builder.maxPreviewSize; minPreviewSize = builder.minPreviewSize; isMirror = builder.isMirror; context = builder.context; if (isMirror) { mTextureView.setScaleX(-1); } }
public void setConfiguration(boolean val) { mIsVertical = val; }
public void switchCamera() { if (CAMERA_ID_BACK.equals(mCameraId)) { specificCameraId = CAMERA_ID_FRONT; } else if (CAMERA_ID_FRONT.equals(mCameraId)) { specificCameraId = CAMERA_ID_BACK; } stop(); start(); }
private int getCameraOri(int rotation, String cameraId) { int degrees = rotation * 90; switch (rotation) { case Surface.ROTATION_0: degrees = 0; break; case Surface.ROTATION_90: degrees = 90; break; case Surface.ROTATION_180: degrees = 180; break; case Surface.ROTATION_270: degrees = 270; break; default: break; } int result; if (CAMERA_ID_FRONT.equals(cameraId)) { result = (mSensorOrientation + degrees) % 360; result = (360 - result) % 360; } else { result = (mSensorOrientation - degrees + 360) % 360; } Log.i(TAG, "getCameraOri: " + rotation + " " + result + " " + mSensorOrientation); return result; }
private final TextureView.SurfaceTextureListener mSurfaceTextureListener = new TextureView.SurfaceTextureListener() {
@Override public void onSurfaceTextureAvailable(SurfaceTexture texture, int width, int height) { Log.i(TAG, "onSurfaceTextureAvailable: "); openCamera(); }
@Override public void onSurfaceTextureSizeChanged(SurfaceTexture texture, int width, int height) { Log.i(TAG, "onSurfaceTextureSizeChanged: "); configureTransform(width, height); }
@Override public boolean onSurfaceTextureDestroyed(SurfaceTexture texture) { Log.i(TAG, "onSurfaceTextureDestroyed: "); return true; }
@Override public void onSurfaceTextureUpdated(SurfaceTexture texture) { }
};
private CameraDevice.StateCallback mDeviceStateCallback = new CameraDevice.StateCallback() {
@Override public void onOpened(@NonNull CameraDevice cameraDevice) { Log.i(TAG, "onOpened: "); mCameraOpenCloseLock.release(); mCameraDevice = cameraDevice; createCameraPreviewSession(); if (camera2Listener != null) { camera2Listener.onCameraOpened(cameraDevice, mCameraId, mPreviewSize, getCameraOri(rotation, mCameraId), isMirror); } }
@Override public void onDisconnected(@NonNull CameraDevice cameraDevice) { Log.i(TAG, "onDisconnected: "); mCameraOpenCloseLock.release(); cameraDevice.close(); mCameraDevice = null; if (camera2Listener != null) { camera2Listener.onCameraClosed(); } }
@Override public void onError(@NonNull CameraDevice cameraDevice, int error) { Log.i(TAG, "onError: "); mCameraOpenCloseLock.release(); cameraDevice.close(); mCameraDevice = null;
if (camera2Listener != null) { camera2Listener.onCameraError(new Exception("error occurred, code is " + error)); } }
}; private CameraCaptureSession.StateCallback mCaptureStateCallback = new CameraCaptureSession.StateCallback() {
@Override public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) { Log.i(TAG, "onConfigured: "); if (null == mCameraDevice) { return; }
mCaptureSession = cameraCaptureSession; try { mCaptureSession.setRepeatingRequest(mPreviewRequestBuilder.build(), mCaptureCallBack, mBackgroundHandler); } catch (CameraAccessException e) { e.printStackTrace(); } }
@Override public void onConfigureFailed( @NonNull CameraCaptureSession cameraCaptureSession) { Log.i(TAG, "onConfigureFailed: "); if (camera2Listener != null) { camera2Listener.onCameraError(new Exception("configureFailed")); } } };
private CameraCaptureSession.CaptureCallback mCaptureCallBack = new CameraCaptureSession.CaptureCallback(){ @Override public void onCaptureCompleted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull TotalCaptureResult result) { super.onCaptureCompleted(session, request, result); camera2Listener.onHandleFaces(result); }
@Override public void onCaptureFailed(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull CaptureFailure failure) { super.onCaptureFailed(session, request, failure); } };
private HandlerThread mBackgroundThread;
private Handler mBackgroundHandler;
private ImageReader mImageReader;
private CaptureRequest.Builder mPreviewRequestBuilder;
private Semaphore mCameraOpenCloseLock = new Semaphore(1);
private int mSensorOrientation;
private Size getBestSupportedSize(List<Size> sizes) { Size defaultSize = sizes.get(0); Size[] tempSizes = sizes.toArray(new Size[0]); Arrays.sort(tempSizes, new Comparator<Size>() { @Override public int compare(Size o1, Size o2) { if (o1.getWidth() > o2.getWidth()) { return -1; } else if (o1.getWidth() == o2.getWidth()) { return o1.getHeight() > o2.getHeight() ? -1 : 1; } else { return 1; } } }); sizes = new ArrayList<>(Arrays.asList(tempSizes)); for (int i = sizes.size() - 1; i >= 0; i--) { if (maxPreviewSize != null) { if (sizes.get(i).getWidth() > maxPreviewSize.x || sizes.get(i).getHeight() > maxPreviewSize.y) { sizes.remove(i); continue; } } if (minPreviewSize != null) { if (sizes.get(i).getWidth() < minPreviewSize.x || sizes.get(i).getHeight() < minPreviewSize.y) { sizes.remove(i); } } } if (sizes.size() == 0) { String msg = "can not find suitable previewSize, now using default"; if (camera2Listener != null) { Log.e(TAG, msg); camera2Listener.onCameraError(new Exception(msg)); } return defaultSize; } Size bestSize = sizes.get(0); float previewViewRatio; if (previewViewSize != null) { previewViewRatio = (float) previewViewSize.x / (float) previewViewSize.y; } else { previewViewRatio = (float) bestSize.getWidth() / (float) bestSize.getHeight(); }
if (previewViewRatio > 1) { previewViewRatio = 1 / previewViewRatio; }
for (Size s : sizes) { if (specificPreviewSize != null && specificPreviewSize.x == s.getWidth() && specificPreviewSize.y == s.getHeight()) { return s; } if (Math.abs((s.getHeight() / (float) s.getWidth()) - previewViewRatio) < Math.abs(bestSize.getHeight() / (float) bestSize.getWidth() - previewViewRatio)) { bestSize = s; } } return bestSize; }
public synchronized void start() { if (mCameraDevice != null) { return; } startBackgroundThread();
if (mTextureView.isAvailable()) { openCamera(); } else { mTextureView.setSurfaceTextureListener(mSurfaceTextureListener); } }
public synchronized void stop() { if (mCameraDevice == null) { return; } closeCamera(); stopBackgroundThread(); }
public void release() { stop(); mTextureView = null; camera2Listener = null; context = null; }
private void setUpCameraOutputs(CameraManager cameraManager) { try { if (configCameraParams(cameraManager, specificCameraId)) { return; } for (String cameraId : cameraManager.getCameraIdList()) { if (configCameraParams(cameraManager, cameraId)) { return; } } } catch (CameraAccessException e) { e.printStackTrace(); } catch (NullPointerException e) {
if (camera2Listener != null) { camera2Listener.onCameraError(e); } } }
private boolean configCameraParams(CameraManager manager, String cameraId) throws CameraAccessException { CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
StreamConfigurationMap map = characteristics.get( CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP); if (map == null) { return false; } mPreviewSize = getBestSupportedSize(new ArrayList<Size>(Arrays.asList(map.getOutputSizes(SurfaceTexture.class)))); mImageReader = ImageReader.newInstance(mPreviewSize.getWidth(), mPreviewSize.getHeight(), ImageFormat.YUV_420_888, 2); mImageReader.setOnImageAvailableListener( new OnImageAvailableListenerImpl(), mBackgroundHandler);
mSensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION); mCameraId = cameraId; return true; }
private void openCamera() { CameraManager cameraManager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE); setUpCameraOutputs(cameraManager); configureTransform(mTextureView.getWidth(), mTextureView.getHeight()); try { if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) { throw new RuntimeException("Time out waiting to lock camera opening."); } cameraManager.openCamera(mCameraId, mDeviceStateCallback, mBackgroundHandler); } catch (CameraAccessException e) { if (camera2Listener != null) { camera2Listener.onCameraError(e); } } catch (InterruptedException e) { if (camera2Listener != null) { camera2Listener.onCameraError(e); } } }
private void closeCamera() { try { mCameraOpenCloseLock.acquire(); if (null != mCaptureSession) { mCaptureSession.close(); mCaptureSession = null; } if (null != mCameraDevice) { mCameraDevice.close(); mCameraDevice = null; } if (null != mImageReader) { mImageReader.close(); mImageReader = null; } if (camera2Listener != null) { camera2Listener.onCameraClosed(); } } catch (InterruptedException e) { if (camera2Listener != null) { camera2Listener.onCameraError(e); } } finally { mCameraOpenCloseLock.release(); } }
private void startBackgroundThread() { mBackgroundThread = new HandlerThread("CameraBackground"); mBackgroundThread.start(); mBackgroundHandler = new Handler(mBackgroundThread.getLooper()); }
private void stopBackgroundThread() { mBackgroundThread.quitSafely(); try { mBackgroundThread.join(); mBackgroundThread = null; mBackgroundHandler = null; } catch (InterruptedException e) { e.printStackTrace(); } }
private void createCameraPreviewSession() { try { SurfaceTexture texture = mTextureView.getSurfaceTexture(); assert texture != null;
texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
Surface surface = new Surface(texture);
mPreviewRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
mPreviewRequestBuilder.addTarget(surface); mPreviewRequestBuilder.addTarget(mImageReader.getSurface());
mCameraDevice.createCaptureSession(Arrays.asList(surface, mImageReader.getSurface()), mCaptureStateCallback, mBackgroundHandler ); } catch (CameraAccessException e) { e.printStackTrace(); } }
private void configureTransform(int viewWidth, int viewHeight) { if (null == mTextureView || null == mPreviewSize) { return; } Matrix matrix = new Matrix(); RectF viewRect = new RectF(0, 0, viewWidth, viewHeight); RectF bufferRect = new RectF(0, 0, mPreviewSize.getHeight(), mPreviewSize.getWidth()); float centerX = viewRect.centerX(); float centerY = viewRect.centerY(); if (Surface.ROTATION_90 == rotation || Surface.ROTATION_270 == rotation) { bufferRect.offset(centerX - bufferRect.centerX(), centerY - bufferRect.centerY()); matrix.setRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.FILL); float scale = Math.max( (float) viewHeight / mPreviewSize.getHeight(), (float) viewWidth / mPreviewSize.getWidth()); matrix.postScale(scale, scale, centerX, centerY); matrix.postRotate((90 * (rotation - 2)) % 360, centerX, centerY); } else if (Surface.ROTATION_180 == rotation) { matrix.postRotate(180, centerX, centerY); } Log.i(TAG, "configureTransform: " + getCameraOri(rotation, mCameraId) + " " + rotation * 90); mTextureView.setTransform(matrix); }
public static final class Builder {
private TextureView previewDisplayView;
private boolean isMirror;
private String specificCameraId;
private Camera2Listener camera2Listener;
private Point previewViewSize;
private int rotation;
private Point previewSize;
private Point maxPreviewSize;
private Point minPreviewSize;
private Context context;
public Builder() { }
public Builder previewOn(TextureView val) { previewDisplayView = val; return this; }
public Builder isMirror(boolean val) { isMirror = val; return this; }
public Builder previewSize(Point val) { previewSize = val; return this; }
public Builder maxPreviewSize(Point val) { maxPreviewSize = val; return this; }
public Builder minPreviewSize(Point val) { minPreviewSize = val; return this; }
public Builder previewViewSize(Point val) { previewViewSize = val; return this; }
public Builder rotation(int val) { rotation = val; return this; }
public Builder specificCameraId(String val) { specificCameraId = val; return this; }
public Builder cameraListener(Camera2Listener val) { camera2Listener = val; return this; }
public Builder context(Context val) { context = val; return this; }
public Camera2Helper build() { if (previewViewSize == null) { Log.e(TAG, "previewViewSize is null, now use default previewSize"); } if (camera2Listener == null) { Log.e(TAG, "camera2Listener is null, callback will not be called"); } if (previewDisplayView == null) { throw new NullPointerException("you must preview on a textureView or a surfaceView"); } if (maxPreviewSize != null && minPreviewSize != null) { if (maxPreviewSize.x < minPreviewSize.x || maxPreviewSize.y < minPreviewSize.y) { throw new IllegalArgumentException("maxPreviewSize must greater than minPreviewSize"); } } return new Camera2Helper(this); } }
private class OnImageAvailableListenerImpl implements ImageReader.OnImageAvailableListener { private byte[] y; private byte[] u; private byte[] v; private ReentrantLock lock = new ReentrantLock();
@Override public void onImageAvailable(ImageReader reader) { Image image = reader.acquireNextImage(); if (camera2Listener != null && image.getFormat() == ImageFormat.YUV_420_888) { Image.Plane[] planes = image.getPlanes(); lock.lock(); if (y == null) { y = new byte[planes[0].getBuffer().limit() - planes[0].getBuffer().position()]; u = new byte[planes[1].getBuffer().limit() - planes[1].getBuffer().position()]; v = new byte[planes[2].getBuffer().limit() - planes[2].getBuffer().position()]; } if (image.getPlanes()[0].getBuffer().remaining() == y.length) { planes[0].getBuffer().get(y); planes[1].getBuffer().get(u); planes[2].getBuffer().get(v); camera2Listener.onPreview(y, u, v, mPreviewSize, planes[0].getRowStride()); } lock.unlock(); } image.close(); } } }
|