| 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.content.Context; |
| 14 | import android.hardware.Camera; |
| 15 | import android.os.Handler; |
| 16 | import android.os.SystemClock; |
| 17 | import java.io.IOException; |
| 18 | import java.nio.ByteBuffer; |
| 19 | import java.util.List; |
| 20 | import java.util.concurrent.TimeUnit; |
| 21 | import org.webrtc.CameraEnumerationAndroid.CaptureFormat; |
| 22 |
| 23 | @SuppressWarnings("deprecation") |
| 24 | class Camera1Session implements CameraSession { |
| 25 | private static final String TAG = "Camera1Session"; |
| 26 | private static final int NUMBER_OF_CAPTURE_BUFFERS = 3; |
| 27 |
| 28 | private static final Histogram camera1StartTimeMsHistogram = |
| 29 | Histogram.createCounts("WebRTC.Android.Camera1.StartTimeMs", 1, 10000, 50); |
| 30 | private static final Histogram camera1StopTimeMsHistogram = |
| 31 | Histogram.createCounts("WebRTC.Android.Camera1.StopTimeMs", 1, 10000, 50); |
| 32 | private static final Histogram camera1ResolutionHistogram = Histogram.createEnumeration( |
| 33 | "WebRTC.Android.Camera1.Resolution", CameraEnumerationAndroid.COMMON_RESOLUTIONS.size()); |
| 34 |
| 35 | private static enum SessionState { RUNNING, STOPPED } |
| 36 |
| 37 | private final Handler cameraThreadHandler; |
| 38 | private final Events events; |
| 39 | private final boolean captureToTexture; |
| 40 | private final Context applicationContext; |
| 41 | private final SurfaceTextureHelper surfaceTextureHelper; |
| 42 | private final int cameraId; |
| 43 | private final android.hardware.Camera camera; |
| 44 | private final android.hardware.Camera.CameraInfo info; |
| 45 | private final CaptureFormat captureFormat; |
| 46 | // Used only for stats. Only used on the camera thread. |
| 47 | private final long constructionTimeNs; // Construction time of this class. |
| 48 |
| 49 | private OrientationHelper orientationHelper; |
| 50 |
| 51 | private SessionState state; |
| 52 | private boolean firstFrameReported; |
| 53 |
| 54 | // TODO(titovartem) make correct fix during webrtc:9175 |
| 55 | @SuppressWarnings("ByteBufferBackingArray") |
| 56 | public static void create(final CreateSessionCallback callback, final Events events, |
| 57 | final boolean captureToTexture, final Context applicationContext, |
| 58 | final SurfaceTextureHelper surfaceTextureHelper, final int cameraId, final int width, |
| 59 | final int height, final int framerate) { |
| 60 | final long constructionTimeNs = System.nanoTime(); |
| 61 | Logging.d(TAG, "Open camera " + cameraId); |
| 62 | events.onCameraOpening(); |
| 63 |
| 64 | final android.hardware.Camera camera; |
| 65 | try { |
| 66 | camera = android.hardware.Camera.open(cameraId); |
| 67 | } catch (RuntimeException e) { |
| 68 | callback.onFailure(FailureType.ERROR, e.getMessage()); |
| 69 | return; |
| 70 | } |
| 71 |
| 72 | if (camera == null) { |
| 73 | callback.onFailure(FailureType.ERROR, |
| 74 | "android.hardware.Camera.open returned null for camera id = " + cameraId); |
| 75 | return; |
| 76 | } |
| 77 |
| 78 | try { |
| 79 | camera.setPreviewTexture(surfaceTextureHelper.getSurfaceTexture()); |
| 80 | } catch (IOException | RuntimeException e) { |
| 81 | camera.release(); |
| 82 | callback.onFailure(FailureType.ERROR, e.getMessage()); |
| 83 | return; |
| 84 | } |
| 85 |
| 86 | final android.hardware.Camera.CameraInfo info = new android.hardware.Camera.CameraInfo(); |
| 87 | android.hardware.Camera.getCameraInfo(cameraId, info); |
| 88 |
| 89 | final CaptureFormat captureFormat; |
| 90 | try { |
| 91 | final android.hardware.Camera.Parameters parameters = camera.getParameters(); |
| 92 | captureFormat = findClosestCaptureFormat(parameters, width, height, framerate); |
| 93 | final Size pictureSize = findClosestPictureSize(parameters, width, height); |
| 94 | updateCameraParameters(camera, parameters, captureFormat, pictureSize, captureToTexture); |
| 95 | } catch (RuntimeException e) { |
| 96 | camera.release(); |
| 97 | callback.onFailure(FailureType.ERROR, e.getMessage()); |
| 98 | return; |
| 99 | } |
| 100 |
| 101 | if (!captureToTexture) { |
| 102 | final int frameSize = captureFormat.frameSize(); |
| 103 | for (int i = 0; i < NUMBER_OF_CAPTURE_BUFFERS; ++i) { |
| 104 | final ByteBuffer buffer = ByteBuffer.allocateDirect(frameSize); |
| 105 | camera.addCallbackBuffer(buffer.array()); |
| 106 | } |
| 107 | } |
| 108 |
| 109 | // Calculate orientation manually and send it as CVO insted. |
| 110 | camera.setDisplayOrientation(0 /* degrees */); |
| 111 |
| 112 | callback.onDone(new Camera1Session(events, captureToTexture, applicationContext, |
| 113 | surfaceTextureHelper, cameraId, camera, info, captureFormat, constructionTimeNs)); |
| 114 | } |
| 115 |
| 116 | private static void updateCameraParameters(android.hardware.Camera camera, |
| 117 | android.hardware.Camera.Parameters parameters, CaptureFormat captureFormat, Size pictureSize, |
| 118 | boolean captureToTexture) { |
| 119 | final List<String> focusModes = parameters.getSupportedFocusModes(); |
| 120 |
| 121 | parameters.setPreviewFpsRange(captureFormat.framerate.min, captureFormat.framerate.max); |
| 122 | parameters.setPreviewSize(captureFormat.width, captureFormat.height); |
| 123 | parameters.setPictureSize(pictureSize.width, pictureSize.height); |
| 124 | if (!captureToTexture) { |
| 125 | parameters.setPreviewFormat(captureFormat.imageFormat); |
| 126 | } |
| 127 |
| 128 | if (parameters.isVideoStabilizationSupported()) { |
| 129 | parameters.setVideoStabilization(true); |
| 130 | } |
| 131 | if (focusModes.contains(android.hardware.Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) { |
| 132 | parameters.setFocusMode(android.hardware.Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO); |
| 133 | } |
| 134 | camera.setParameters(parameters); |
| 135 | } |
| 136 |
| 137 | private static CaptureFormat findClosestCaptureFormat( |
| 138 | android.hardware.Camera.Parameters parameters, int width, int height, int framerate) { |
| 139 | // Find closest supported format for |width| x |height| @ |framerate|. |
| 140 | final List<CaptureFormat.FramerateRange> supportedFramerates = |
| 141 | Camera1Enumerator.convertFramerates(parameters.getSupportedPreviewFpsRange()); |
| 142 | Logging.d(TAG, "Available fps ranges: " + supportedFramerates); |
| 143 |
| 144 | final CaptureFormat.FramerateRange fpsRange = |
| 145 | CameraEnumerationAndroid.getClosestSupportedFramerateRange(supportedFramerates, framerate); |
| 146 |
| 147 | final Size previewSize = CameraEnumerationAndroid.getClosestSupportedSize( |
| 148 | Camera1Enumerator.convertSizes(parameters.getSupportedPreviewSizes()), width, height); |
| 149 | CameraEnumerationAndroid.reportCameraResolution(camera1ResolutionHistogram, previewSize); |
| 150 |
| 151 | return new CaptureFormat(previewSize.width, previewSize.height, fpsRange); |
| 152 | } |
| 153 |
| 154 | private static Size findClosestPictureSize( |
| 155 | android.hardware.Camera.Parameters parameters, int width, int height) { |
| 156 | return CameraEnumerationAndroid.getClosestSupportedSize( |
| 157 | Camera1Enumerator.convertSizes(parameters.getSupportedPictureSizes()), width, height); |
| 158 | } |
| 159 |
| 160 | private Camera1Session(Events events, boolean captureToTexture, Context applicationContext, |
| 161 | SurfaceTextureHelper surfaceTextureHelper, int cameraId, android.hardware.Camera camera, |
| 162 | android.hardware.Camera.CameraInfo info, CaptureFormat captureFormat, |
| 163 | long constructionTimeNs) { |
| 164 | Logging.d(TAG, "Create new camera1 session on camera " + cameraId); |
| 165 |
| 166 | this.cameraThreadHandler = new Handler(); |
| 167 | this.events = events; |
| 168 | this.captureToTexture = captureToTexture; |
| 169 | this.applicationContext = applicationContext; |
| 170 | this.surfaceTextureHelper = surfaceTextureHelper; |
| 171 | this.cameraId = cameraId; |
| 172 | this.camera = camera; |
| 173 | this.info = info; |
| 174 | this.captureFormat = captureFormat; |
| 175 | this.constructionTimeNs = constructionTimeNs; |
| 176 | this.orientationHelper = new OrientationHelper(); |
| 177 |
| 178 | surfaceTextureHelper.setTextureSize(captureFormat.width, captureFormat.height); |
| 179 |
| 180 | startCapturing(); |
| 181 | } |
| 182 |
| 183 | @Override |
| 184 | public void stop() { |
| 185 | Logging.d(TAG, "Stop camera1 session on camera " + cameraId); |
| 186 | checkIsOnCameraThread(); |
| 187 | if (state != SessionState.STOPPED) { |
| 188 | final long stopStartTime = System.nanoTime(); |
| 189 | stopInternal(); |
| 190 | final int stopTimeMs = (int) TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - stopStartTime); |
| 191 | camera1StopTimeMsHistogram.addSample(stopTimeMs); |
| 192 | } |
| 193 | } |
| 194 |
| 195 | private void startCapturing() { |
| 196 | Logging.d(TAG, "Start capturing"); |
| 197 | checkIsOnCameraThread(); |
| 198 |
| 199 | state = SessionState.RUNNING; |
| 200 |
| 201 | camera.setErrorCallback(new android.hardware.Camera.ErrorCallback() { |
| 202 | @Override |
| 203 | public void onError(int error, android.hardware.Camera camera) { |
| 204 | String errorMessage; |
| 205 | if (error == android.hardware.Camera.CAMERA_ERROR_SERVER_DIED) { |
| 206 | errorMessage = "Camera server died!"; |
| 207 | } else { |
| 208 | errorMessage = "Camera error: " + error; |
| 209 | } |
| 210 | Logging.e(TAG, errorMessage); |
| 211 | stopInternal(); |
| 212 | if (error == android.hardware.Camera.CAMERA_ERROR_EVICTED) { |
| 213 | events.onCameraDisconnected(Camera1Session.this); |
| 214 | } else { |
| 215 | events.onCameraError(Camera1Session.this, errorMessage); |
| 216 | } |
| 217 | } |
| 218 | }); |
| 219 |
| 220 | if (captureToTexture) { |
| 221 | listenForTextureFrames(); |
| 222 | } else { |
| 223 | listenForBytebufferFrames(); |
| 224 | } |
| 225 | orientationHelper.start(); |
| 226 | try { |
| 227 | camera.startPreview(); |
| 228 | } catch (RuntimeException e) { |
| 229 | stopInternal(); |
| 230 | events.onCameraError(this, e.getMessage()); |
| 231 | } |
| 232 | } |
| 233 |
| 234 | private void stopInternal() { |
| 235 | Logging.d(TAG, "Stop internal"); |
| 236 | checkIsOnCameraThread(); |
| 237 | if (state == SessionState.STOPPED) { |
| 238 | Logging.d(TAG, "Camera is already stopped"); |
| 239 | return; |
| 240 | } |
| 241 |
| 242 | state = SessionState.STOPPED; |
| 243 | surfaceTextureHelper.stopListening(); |
| 244 | // Note: stopPreview or other driver code might deadlock. Deadlock in |
| 245 | // android.hardware.Camera._stopPreview(Native Method) has been observed on |
| 246 | // Nexus 5 (hammerhead), OS version LMY48I. |
| 247 | camera.stopPreview(); |
| 248 | camera.release(); |
| 249 | events.onCameraClosed(this); |
| 250 | if (orientationHelper != null) { |
| 251 | orientationHelper.stop(); |
| 252 | } |
| 253 | Logging.d(TAG, "Stop done"); |
| 254 | } |
| 255 |
| 256 | private void listenForTextureFrames() { |
| 257 | surfaceTextureHelper.startListening((VideoFrame frame) -> { |
| 258 | checkIsOnCameraThread(); |
| 259 |
| 260 | if (state != SessionState.RUNNING) { |
| 261 | Logging.d(TAG, "Texture frame captured but camera is no longer running."); |
| 262 | return; |
| 263 | } |
| 264 |
| 265 | if (!firstFrameReported) { |
| 266 | final int startTimeMs = |
| 267 | (int) TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - constructionTimeNs); |
| 268 | camera1StartTimeMsHistogram.addSample(startTimeMs); |
| 269 | firstFrameReported = true; |
| 270 | } |
| 271 |
| 272 | // Undo the mirror that the OS "helps" us with. |
| 273 | // http://developer.android.com/reference/android/hardware/Camera.html#setDisplayOrientation(int) |
| 274 | final VideoFrame modifiedFrame = new VideoFrame( |
| 275 | CameraSession.createTextureBufferWithModifiedTransformMatrix( |
| 276 | (TextureBufferImpl) frame.getBuffer(), |
| 277 | /* mirror= */ info.facing == android.hardware.Camera.CameraInfo.CAMERA_FACING_FRONT, |
| 278 | /* rotation= */ 0), |
| 279 | /* rotation= */ getFrameOrientation(), frame.getTimestampNs()); |
| 280 | events.onFrameCaptured(Camera1Session.this, modifiedFrame); |
| 281 | modifiedFrame.release(); |
| 282 | }); |
| 283 | } |
| 284 |
| 285 | private void listenForBytebufferFrames() { |
| 286 | camera.setPreviewCallbackWithBuffer(new android.hardware.Camera.PreviewCallback() { |
| 287 | @Override |
| 288 | public void onPreviewFrame(final byte[] data, android.hardware.Camera callbackCamera) { |
| 289 | checkIsOnCameraThread(); |
| 290 |
| 291 | if (callbackCamera != camera) { |
| 292 | Logging.e(TAG, "Callback from a different camera. This should never happen."); |
| 293 | return; |
| 294 | } |
| 295 |
| 296 | if (state != SessionState.RUNNING) { |
| 297 | Logging.d(TAG, "Bytebuffer frame captured but camera is no longer running."); |
| 298 | return; |
| 299 | } |
| 300 |
| 301 | final long captureTimeNs = TimeUnit.MILLISECONDS.toNanos(SystemClock.elapsedRealtime()); |
| 302 |
| 303 | if (!firstFrameReported) { |
| 304 | final int startTimeMs = |
| 305 | (int) TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - constructionTimeNs); |
| 306 | camera1StartTimeMsHistogram.addSample(startTimeMs); |
| 307 | firstFrameReported = true; |
| 308 | } |
| 309 |
| 310 | VideoFrame.Buffer frameBuffer = new NV21Buffer( |
| 311 | data, captureFormat.width, captureFormat.height, () -> cameraThreadHandler.post(() -> { |
| 312 | if (state == SessionState.RUNNING) { |
| 313 | camera.addCallbackBuffer(data); |
| 314 | } |
| 315 | })); |
| 316 | final VideoFrame frame = new VideoFrame(frameBuffer, getFrameOrientation(), captureTimeNs); |
| 317 | events.onFrameCaptured(Camera1Session.this, frame); |
| 318 | frame.release(); |
| 319 | } |
| 320 | }); |
| 321 | } |
| 322 |
| 323 | private int getFrameOrientation() { |
| 324 | int rotation = orientationHelper.getOrientation(); |
| 325 | OrientationHelper.cameraOrientation = rotation; |
| 326 | if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) { |
| 327 | rotation = 360 - rotation; |
| 328 | } |
| 329 | OrientationHelper.cameraRotation = rotation; |
| 330 | return (info.orientation + rotation) % 360; |
| 331 | } |
| 332 |
| 333 | private void checkIsOnCameraThread() { |
| 334 | if (Thread.currentThread() != cameraThreadHandler.getLooper().getThread()) { |
| 335 | throw new IllegalStateException("Wrong thread"); |
| 336 | } |
| 337 | } |
| 338 | } |
| 339 |