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