void bindPreview()

in react-native-pytorch-core/android/src/main/java/org/pytorch/rn/core/camera/CameraView.java [220:290]


  void bindPreview(@NonNull ProcessCameraProvider cameraProvider) {

    // Unbind previous use cases. Without this, on unmounting and mounting CameraView again, the
    // app will crash.
    cameraProvider.unbindAll();

    Preview preview = new Preview.Builder().build();

    // Some devices do not have front and back camera, like the emulator on a laptop.
    CameraSelector cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA;
    try {
      if (cameraProvider.hasCamera(mPreferredCameraSelector)) {
        cameraSelector = mPreferredCameraSelector;
      }
    } catch (CameraInfoUnavailableException e) {
    }

    ImageAnalysis imageAnalysis =
        new ImageAnalysis.Builder()
            .setTargetResolution(mTargetResolution)
            .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
            .build();

    imageAnalysis.setAnalyzer(
        cameraExecutor,
        imageProxy -> {
          IImage image = new Image(imageProxy, mReactContext.getApplicationContext());
          JSContext.NativeJSRef ref = JSContext.wrapObject(image);
          mReactContext
              .getJSModule(RCTEventEmitter.class)
              .receiveEvent(CameraView.this.getId(), "onFrame", ref.getJSRef());
        });

    mImageCapture = new ImageCapture.Builder().setTargetResolution(mTargetResolution).build();

    OrientationEventListener orientationEventListener =
        new OrientationEventListener(mReactContext.getApplicationContext()) {
          @Override
          public void onOrientationChanged(int orientation) {
            int rotation;

            // Monitors orientation values to determine the target rotation value
            if (orientation >= 45 && orientation < 135) {
              rotation = Surface.ROTATION_270;
            } else if (orientation >= 135 && orientation < 225) {
              rotation = Surface.ROTATION_180;
            } else if (orientation >= 225 && orientation < 315) {
              rotation = Surface.ROTATION_90;
            } else {
              rotation = Surface.ROTATION_0;
            }

            mImageCapture.setTargetRotation(rotation);
            imageAnalysis.setTargetRotation(rotation);
          }
        };

    orientationEventListener.enable();

    mCamera =
        cameraProvider.bindToLifecycle(
            (LifecycleOwner) mReactContext.getCurrentActivity(),
            cameraSelector,
            preview,
            imageAnalysis,
            mImageCapture);
    mCaptureButton.setVisibility(View.VISIBLE);

    preview.setSurfaceProvider(
        ContextCompat.getMainExecutor(mReactContext), mPreviewView.getSurfaceProvider());
  }