| 6 | * tree. An additional intellectual property rights grant can be found |
| 7 | * in the file PATENTS. All contributing project authors may |
| 8 | * be found in the AUTHORS file in the root of the source tree. |
| 9 | */ |
| 10 |
| 11 | package org.webrtc; |
| 12 |
| 13 | import android.annotation.TargetApi; |
| 14 | import android.content.Context; |
| 15 | import android.hardware.camera2.CameraAccessException; |
| 16 | import android.hardware.camera2.CameraCaptureSession; |
| 17 | import android.hardware.camera2.CameraCharacteristics; |
| 18 | import android.hardware.camera2.CameraDevice; |
| 19 | import android.hardware.camera2.CameraManager; |
| 20 | import android.hardware.camera2.CameraMetadata; |
| 21 | import android.hardware.camera2.CaptureFailure; |
| 22 | import android.hardware.camera2.CaptureRequest; |
| 23 | import android.os.Handler; |
| 24 | import androidx.annotation.Nullable; |
| 25 | import android.util.Range; |
| 26 | import android.view.Surface; |
| 27 |
| 28 | import java.util.Arrays; |
| 29 | import java.util.List; |
| 30 | import java.util.concurrent.TimeUnit; |
| 31 |
| 32 | import org.webrtc.CameraEnumerationAndroid.CaptureFormat; |
| 33 |
| 34 | @TargetApi(21) |
| 35 | class Camera2Session implements CameraSession { |
| 36 | private static final String TAG = "Camera2Session"; |
| 37 |
| 38 | private static final Histogram camera2StartTimeMsHistogram = |
| 39 | Histogram.createCounts("WebRTC.Android.Camera2.StartTimeMs", 1, 10000, 50); |
| 40 | private static final Histogram camera2StopTimeMsHistogram = |
| 41 | Histogram.createCounts("WebRTC.Android.Camera2.StopTimeMs", 1, 10000, 50); |
| 42 | private static final Histogram camera2ResolutionHistogram = Histogram.createEnumeration( |
| 43 | "WebRTC.Android.Camera2.Resolution", CameraEnumerationAndroid.COMMON_RESOLUTIONS.size()); |
| 44 |
| 45 | private static enum SessionState { RUNNING, STOPPED } |
| 46 |
| 47 | private final Handler cameraThreadHandler; |
| 48 | private final CreateSessionCallback callback; |
| 49 | private final Events events; |
| 50 | private final Context applicationContext; |
| 51 | private final CameraManager cameraManager; |
| 52 | private final SurfaceTextureHelper surfaceTextureHelper; |
| 53 | private final String cameraId; |
| 54 | private final int width; |
| 55 | private final int height; |
| 56 | private final int framerate; |
| 57 |
| 58 | private OrientationHelper orientationHelper; |
| 59 |
| 60 | // Initialized at start |
| 61 | private CameraCharacteristics cameraCharacteristics; |
| 62 | private int cameraOrientation; |
| 63 | private boolean isCameraFrontFacing; |
| 64 | private int fpsUnitFactor; |
| 65 | private CaptureFormat captureFormat; |
| 66 |
| 67 | // Initialized when camera opens |
| 68 | @Nullable private CameraDevice cameraDevice; |
| 69 | @Nullable private Surface surface; |
| 70 |
| 71 | // Initialized when capture session is created |
| 72 | @Nullable private CameraCaptureSession captureSession; |
| 73 |
| 74 | // State |
| 75 | private SessionState state = SessionState.RUNNING; |
| 76 | private boolean firstFrameReported; |
| 77 |
| 78 | // Used only for stats. Only used on the camera thread. |
| 79 | private final long constructionTimeNs; // Construction time of this class. |
| 80 |
| 81 | private class CameraStateCallback extends CameraDevice.StateCallback { |
| 82 | private String getErrorDescription(int errorCode) { |
| 83 | switch (errorCode) { |
| 84 | case CameraDevice.StateCallback.ERROR_CAMERA_DEVICE: |
| 85 | return "Camera device has encountered a fatal error."; |
| 86 | case CameraDevice.StateCallback.ERROR_CAMERA_DISABLED: |
| 87 | return "Camera device could not be opened due to a device policy."; |
| 88 | case CameraDevice.StateCallback.ERROR_CAMERA_IN_USE: |
| 89 | return "Camera device is in use already."; |
| 90 | case CameraDevice.StateCallback.ERROR_CAMERA_SERVICE: |
| 91 | return "Camera service has encountered a fatal error."; |
| 92 | case CameraDevice.StateCallback.ERROR_MAX_CAMERAS_IN_USE: |
| 93 | return "Camera device could not be opened because" |
| 94 | + " there are too many other open camera devices."; |
| 95 | default: |
| 96 | return "Unknown camera error: " + errorCode; |
| 97 | } |
| 98 | } |
| 99 |
| 100 | @Override |
| 101 | public void onDisconnected(CameraDevice camera) { |
| 102 | checkIsOnCameraThread(); |
| 103 | final boolean startFailure = (captureSession == null) && (state != SessionState.STOPPED); |
| 104 | state = SessionState.STOPPED; |
| 105 | stopInternal(); |
| 106 | if (startFailure) { |
| 107 | callback.onFailure(FailureType.DISCONNECTED, "Camera disconnected / evicted."); |
| 108 | } else { |
| 109 | events.onCameraDisconnected(Camera2Session.this); |
| 110 | } |
| 111 | } |
| 112 |
| 113 | @Override |
| 114 | public void onError(CameraDevice camera, int errorCode) { |
| 115 | checkIsOnCameraThread(); |
| 116 | reportError(getErrorDescription(errorCode)); |
| 117 | } |
| 118 |
| 119 | @Override |
| 120 | public void onOpened(CameraDevice camera) { |
| 121 | checkIsOnCameraThread(); |
| 122 |
| 123 | Logging.d(TAG, "Camera opened."); |
| 124 | cameraDevice = camera; |
| 125 |
| 126 | surfaceTextureHelper.setTextureSize(captureFormat.width, captureFormat.height); |
| 127 | surface = new Surface(surfaceTextureHelper.getSurfaceTexture()); |
| 128 | try { |
| 129 | camera.createCaptureSession( |
| 130 | Arrays.asList(surface), new CaptureSessionCallback(), cameraThreadHandler); |
| 131 | } catch (CameraAccessException e) { |
| 132 | reportError("Failed to create capture session. " + e); |
| 133 | return; |
| 134 | } |
| 135 | } |
| 136 |
| 137 | @Override |
| 138 | public void onClosed(CameraDevice camera) { |
| 139 | checkIsOnCameraThread(); |
| 140 |
| 141 | Logging.d(TAG, "Camera device closed."); |
| 142 | events.onCameraClosed(Camera2Session.this); |
| 143 | } |
| 144 | } |
| 145 |
| 146 | private class CaptureSessionCallback extends CameraCaptureSession.StateCallback { |
| 147 | @Override |
| 148 | public void onConfigureFailed(CameraCaptureSession session) { |
| 149 | checkIsOnCameraThread(); |
| 150 | session.close(); |
| 151 | reportError("Failed to configure capture session."); |
| 152 | } |
| 153 |
| 154 | @Override |
| 155 | public void onConfigured(CameraCaptureSession session) { |
| 156 | checkIsOnCameraThread(); |
| 157 | Logging.d(TAG, "Camera capture session configured."); |
| 158 | captureSession = session; |
| 159 | try { |
| 160 | /* |
| 161 | * The viable options for video capture requests are: |
| 162 | * TEMPLATE_PREVIEW: High frame rate is given priority over the highest-quality |
| 163 | * post-processing. |
| 164 | * TEMPLATE_RECORD: Stable frame rate is used, and post-processing is set for recording |
| 165 | * quality. |
| 166 | */ |
| 167 | final CaptureRequest.Builder captureRequestBuilder = |
| 168 | cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_RECORD); |
| 169 | // Set auto exposure fps range. |
| 170 | captureRequestBuilder.set(CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE, |
| 171 | new Range<Integer>(captureFormat.framerate.min / fpsUnitFactor, |
| 172 | captureFormat.framerate.max / fpsUnitFactor)); |
| 173 | captureRequestBuilder.set( |
| 174 | CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON); |
| 175 | captureRequestBuilder.set(CaptureRequest.CONTROL_AE_LOCK, false); |
| 176 | chooseStabilizationMode(captureRequestBuilder); |
| 177 | chooseFocusMode(captureRequestBuilder); |
| 178 |
| 179 | captureRequestBuilder.addTarget(surface); |
| 180 | session.setRepeatingRequest( |
| 181 | captureRequestBuilder.build(), new CameraCaptureCallback(), cameraThreadHandler); |
| 182 | } catch (CameraAccessException e) { |
| 183 | reportError("Failed to start capture request. " + e); |
| 184 | return; |
| 185 | } |
| 186 |
| 187 | surfaceTextureHelper.startListening((VideoFrame frame) -> { |
| 188 | checkIsOnCameraThread(); |
| 189 |
| 190 | if (state != SessionState.RUNNING) { |
| 191 | Logging.d(TAG, "Texture frame captured but camera is no longer running."); |
| 192 | return; |
| 193 | } |
| 194 |
| 195 | if (!firstFrameReported) { |
| 196 | firstFrameReported = true; |
| 197 | final int startTimeMs = |
| 198 | (int) TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - constructionTimeNs); |
| 199 | camera2StartTimeMsHistogram.addSample(startTimeMs); |
| 200 | } |
| 201 |
| 202 | // Undo the mirror that the OS "helps" us with. |
| 203 | // http://developer.android.com/reference/android/hardware/Camera.html#setDisplayOrientation(int) |
| 204 | // Also, undo camera orientation, we report it as rotation instead. |
| 205 | final VideoFrame modifiedFrame = |
| 206 | new VideoFrame(CameraSession.createTextureBufferWithModifiedTransformMatrix( |
| 207 | (TextureBufferImpl) frame.getBuffer(), |
| 208 | /* mirror= */ isCameraFrontFacing, |
| 209 | /* rotation= */ -cameraOrientation), |
| 210 | /* rotation= */ getFrameOrientation(), frame.getTimestampNs()); |
| 211 | events.onFrameCaptured(Camera2Session.this, modifiedFrame); |
| 212 | modifiedFrame.release(); |
| 213 | }); |
| 214 | Logging.d(TAG, "Camera device successfully started."); |
| 215 | callback.onDone(Camera2Session.this); |
| 216 | } |
| 217 |
| 218 | // Prefers optical stabilization over software stabilization if available. Only enables one of |
| 219 | // the stabilization modes at a time because having both enabled can cause strange results. |
| 220 | private void chooseStabilizationMode(CaptureRequest.Builder captureRequestBuilder) { |
| 221 | final int[] availableOpticalStabilization = cameraCharacteristics.get( |
| 222 | CameraCharacteristics.LENS_INFO_AVAILABLE_OPTICAL_STABILIZATION); |
| 223 | if (availableOpticalStabilization != null) { |
| 224 | for (int mode : availableOpticalStabilization) { |
| 225 | if (mode == CaptureRequest.LENS_OPTICAL_STABILIZATION_MODE_ON) { |
| 226 | captureRequestBuilder.set(CaptureRequest.LENS_OPTICAL_STABILIZATION_MODE, |
| 227 | CaptureRequest.LENS_OPTICAL_STABILIZATION_MODE_ON); |
| 228 | captureRequestBuilder.set(CaptureRequest.CONTROL_VIDEO_STABILIZATION_MODE, |
| 229 | CaptureRequest.CONTROL_VIDEO_STABILIZATION_MODE_OFF); |
| 230 | Logging.d(TAG, "Using optical stabilization."); |
| 231 | return; |
| 232 | } |
| 233 | } |
| 234 | } |
| 235 | // If no optical mode is available, try software. |
| 236 | final int[] availableVideoStabilization = cameraCharacteristics.get( |
| 237 | CameraCharacteristics.CONTROL_AVAILABLE_VIDEO_STABILIZATION_MODES); |
| 238 | for (int mode : availableVideoStabilization) { |
| 239 | if (mode == CaptureRequest.CONTROL_VIDEO_STABILIZATION_MODE_ON) { |
| 240 | captureRequestBuilder.set(CaptureRequest.CONTROL_VIDEO_STABILIZATION_MODE, |
| 241 | CaptureRequest.CONTROL_VIDEO_STABILIZATION_MODE_ON); |
| 242 | captureRequestBuilder.set(CaptureRequest.LENS_OPTICAL_STABILIZATION_MODE, |
| 243 | CaptureRequest.LENS_OPTICAL_STABILIZATION_MODE_OFF); |
| 244 | Logging.d(TAG, "Using video stabilization."); |
| 245 | return; |
| 246 | } |
| 247 | } |
| 248 | Logging.d(TAG, "Stabilization not available."); |
| 249 | } |
| 250 |
| 251 | private void chooseFocusMode(CaptureRequest.Builder captureRequestBuilder) { |
| 252 | final int[] availableFocusModes = |
| 253 | cameraCharacteristics.get(CameraCharacteristics.CONTROL_AF_AVAILABLE_MODES); |
| 254 | for (int mode : availableFocusModes) { |
| 255 | if (mode == CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_VIDEO) { |
| 256 | captureRequestBuilder.set( |
| 257 | CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_VIDEO); |
| 258 | Logging.d(TAG, "Using continuous video auto-focus."); |
| 259 | return; |
| 260 | } |
| 261 | } |
| 262 | Logging.d(TAG, "Auto-focus is not available."); |
| 263 | } |
| 264 | } |
| 265 |
| 266 | private static class CameraCaptureCallback extends CameraCaptureSession.CaptureCallback { |
| 267 | @Override |
| 268 | public void onCaptureFailed( |
| 269 | CameraCaptureSession session, CaptureRequest request, CaptureFailure failure) { |
| 270 | Logging.d(TAG, "Capture failed: " + failure); |
| 271 | } |
| 272 | } |
| 273 |
| 274 | public static void create(CreateSessionCallback callback, Events events, |
| 275 | Context applicationContext, CameraManager cameraManager, |
| 276 | SurfaceTextureHelper surfaceTextureHelper, String cameraId, int width, int height, |
| 277 | int framerate) { |
| 278 | new Camera2Session(callback, events, applicationContext, cameraManager, surfaceTextureHelper, |
| 279 | cameraId, width, height, framerate); |
| 280 | } |
| 281 |
| 282 | private Camera2Session(CreateSessionCallback callback, Events events, Context applicationContext, |
| 283 | CameraManager cameraManager, SurfaceTextureHelper surfaceTextureHelper, String cameraId, |
| 284 | int width, int height, int framerate) { |
| 285 | Logging.d(TAG, "Create new camera2 session on camera " + cameraId); |
| 286 |
| 287 | constructionTimeNs = System.nanoTime(); |
| 288 |
| 289 | this.cameraThreadHandler = new Handler(); |
| 290 | this.callback = callback; |
| 291 | this.events = events; |
| 292 | this.applicationContext = applicationContext; |
| 293 | this.cameraManager = cameraManager; |
| 294 | this.surfaceTextureHelper = surfaceTextureHelper; |
| 295 | this.cameraId = cameraId; |
| 296 | this.width = width; |
| 297 | this.height = height; |
| 298 | this.framerate = framerate; |
| 299 | this.orientationHelper = new OrientationHelper(); |
| 300 |
| 301 | start(); |
| 302 | } |
| 303 |
| 304 | private void start() { |
| 305 | checkIsOnCameraThread(); |
| 306 | Logging.d(TAG, "start"); |
| 307 |
| 308 | try { |
| 309 | cameraCharacteristics = cameraManager.getCameraCharacteristics(cameraId); |
| 310 | } catch (final Throwable e) { |
| 311 | reportError("getCameraCharacteristics(): " + e.getMessage()); |
| 312 | return; |
| 313 | } |
| 314 | orientationHelper.start(); |
| 315 | cameraOrientation = cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION); |
| 316 | isCameraFrontFacing = cameraCharacteristics.get(CameraCharacteristics.LENS_FACING) |
| 317 | == CameraMetadata.LENS_FACING_FRONT; |
| 318 |
| 319 | findCaptureFormat(); |
| 320 | openCamera(); |
| 321 | } |
| 322 |
| 323 | private void findCaptureFormat() { |
| 324 | checkIsOnCameraThread(); |
| 325 |
| 326 | Range<Integer>[] fpsRanges = |
| 327 | cameraCharacteristics.get(CameraCharacteristics.CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES); |
| 328 | fpsUnitFactor = Camera2Enumerator.getFpsUnitFactor(fpsRanges); |
| 329 | List<CaptureFormat.FramerateRange> framerateRanges = |
| 330 | Camera2Enumerator.convertFramerates(fpsRanges, fpsUnitFactor); |
| 331 | List<Size> sizes = Camera2Enumerator.getSupportedSizes(cameraCharacteristics); |
| 332 | Logging.d(TAG, "Available preview sizes: " + sizes); |
| 333 | Logging.d(TAG, "Available fps ranges: " + framerateRanges); |
| 334 |
| 335 | if (framerateRanges.isEmpty() || sizes.isEmpty()) { |
| 336 | reportError("No supported capture formats."); |
| 337 | return; |
| 338 | } |
| 339 |
| 340 | final CaptureFormat.FramerateRange bestFpsRange = |
| 341 | CameraEnumerationAndroid.getClosestSupportedFramerateRange(framerateRanges, framerate); |
| 342 |
| 343 | final Size bestSize = CameraEnumerationAndroid.getClosestSupportedSize(sizes, width, height); |
| 344 | CameraEnumerationAndroid.reportCameraResolution(camera2ResolutionHistogram, bestSize); |
| 345 |
| 346 | captureFormat = new CaptureFormat(bestSize.width, bestSize.height, bestFpsRange); |
| 347 | Logging.d(TAG, "Using capture format: " + captureFormat); |
| 348 | } |
| 349 |
| 350 | private void openCamera() { |
| 351 | checkIsOnCameraThread(); |
| 352 |
| 353 | Logging.d(TAG, "Opening camera " + cameraId); |
| 354 | events.onCameraOpening(); |
| 355 |
| 356 | try { |
| 357 | cameraManager.openCamera(cameraId, new CameraStateCallback(), cameraThreadHandler); |
| 358 | } catch (Exception e) { |
| 359 | reportError("Failed to open camera: " + e); |
| 360 | return; |
| 361 | } |
| 362 | } |
| 363 |
| 364 | @Override |
| 365 | public void stop() { |
| 366 | Logging.d(TAG, "Stop camera2 session on camera " + cameraId); |
| 367 | checkIsOnCameraThread(); |
| 368 | if (state != SessionState.STOPPED) { |
| 369 | final long stopStartTime = System.nanoTime(); |
| 370 | state = SessionState.STOPPED; |
| 371 | stopInternal(); |
| 372 | final int stopTimeMs = (int) TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - stopStartTime); |
| 373 | camera2StopTimeMsHistogram.addSample(stopTimeMs); |
| 374 | } |
| 375 | } |
| 376 |
| 377 | private void stopInternal() { |
| 378 | Logging.d(TAG, "Stop internal"); |
| 379 | checkIsOnCameraThread(); |
| 380 |
| 381 | surfaceTextureHelper.stopListening(); |
| 382 |
| 383 | if (captureSession != null) { |
| 384 | captureSession.close(); |
| 385 | captureSession = null; |
| 386 | } |
| 387 | if (surface != null) { |
| 388 | surface.release(); |
| 389 | surface = null; |
| 390 | } |
| 391 | if (cameraDevice != null) { |
| 392 | cameraDevice.close(); |
| 393 | cameraDevice = null; |
| 394 | } |
| 395 | if (orientationHelper != null) { |
| 396 | orientationHelper.stop(); |
| 397 | } |
| 398 |
| 399 | Logging.d(TAG, "Stop done"); |
| 400 | } |
| 401 |
| 402 | private void reportError(String error) { |
| 403 | checkIsOnCameraThread(); |
| 404 | Logging.e(TAG, "Error: " + error); |
| 405 |
| 406 | final boolean startFailure = (captureSession == null) && (state != SessionState.STOPPED); |
| 407 | state = SessionState.STOPPED; |
| 408 | stopInternal(); |
| 409 | if (startFailure) { |
| 410 | callback.onFailure(FailureType.ERROR, error); |
| 411 | } else { |
| 412 | events.onCameraError(this, error); |
| 413 | } |
| 414 | } |
| 415 |
| 416 | private int getFrameOrientation() { |
| 417 | int rotation = orientationHelper.getOrientation(); |
| 418 | OrientationHelper.cameraOrientation = rotation; |
| 419 | if (isCameraFrontFacing) { |
| 420 | rotation = 360 - rotation; |
| 421 | } |
| 422 | OrientationHelper.cameraRotation = rotation; |
| 423 | return (cameraOrientation + rotation) % 360; |
| 424 | } |
| 425 |
| 426 | private void checkIsOnCameraThread() { |
| 427 | if (Thread.currentThread() != cameraThreadHandler.getLooper().getThread()) { |
| 428 | throw new IllegalStateException("Wrong thread"); |
| 429 | } |
| 430 | } |
| 431 | } |
| 432 |