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