저조도 모드 세션 사용

저조도 부스트 세션을 사용하여 Google 저조도 부스트를 사용 설정 및 중지합니다.

Kotlin

dependencies {
  val low_light_boost_version = "16.0.0-beta01"
  implementation("org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.10.2")
  implementation("com.google.android.gms:play-services-base:18.7.0")
  implementation("com.google.android.gms:play-services-camera-low-light-boost:${low_light_boost_version}")
  implementation("com.google.android.gms:play-services-tasks:18.3.0")
}

Groovy

dependencies {
  def low_light_boost_version = "16.0.0-beta01"
  implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.10.2'
  implementation 'com.google.android.gms:play-services-base:18.7.0'
  implementation 'com.google.android.gms:play-services-camera-low-light-boost:${low_light_boost_version}'
  implementation 'com.google.android.gms:play-services-tasks:18.3.0'
}

LowLightBoostSession는 Google Play 서비스 com.google.android.gms.cameralowlight 패키지에서 제공합니다. Google Play 서비스 API에 액세스하는 방법에 대한 자세한 내용은 Google Play 서비스 문서를 참고하세요.

콜백 객체 만들기

어두운 곳에서 촬영 시 밝기 향상 세션을 만들 때 LowLightBoostCallback 인터페이스를 구현하는 객체를 전달해야 합니다. 이 객체의 함수는 세션이 연결 해제되거나 소멸될 때 호출됩니다. 다음 코드는 콜백을 만드는 방법을 보여줍니다.

Kotlin

private fun createLowLightBoostCallback(): LowLightBoostCallback =
  object : LowLightBoostCallback() {
    override fun onSessionDestroyed() {
      Log.d(TAG, "onSessionDestroyed")
      lowLightBoostSession = null
    }

    override fun onSessionDisconnected(statusCode: Int) {
      Log.d(TAG, "onSessionDisconnected: error=$statusCode")
      lowLightBoostSession = null
    }
  }

자바

private LowLightBoostCallback createLowLightBoostCallback() {
  LowLightBoostCallback lowLightBoostCallback = new LowLightBoostCallback() {
    @Override
    public void onSessionDestroyed() {
      Log.d(TAG, "onSessionDestroyed");
      lowLightBoostSession = null;
    }

    @Override
    public void onSessionDisconnected(int statusCode) {
      Log.d(TAG, "onSessionCreationFailed: error=" + statusCode);
      lowLightBoostSession = null;
    }
  }
  return lowLightBoostCallback;
}

이 코드에 관한 핵심 사항

  • 이 코드는 콜백 객체를 만드는 비공개 메서드인 createLowLightBoostCallback()를 정의합니다. 세션 만들기에 설명된 대로 실제로 어두운 곳에서 촬영 모드 세션을 만들 때 이 메서드를 호출합니다.
  • 세션이 연결 해제되거나 소멸되면 콜백이 호출됩니다. 세션이 생성될 때는 호출되지 않습니다. 세션이 성공적으로 생성되었는지 확인하려면 LowLightBoostClient.createSession에서 반환된 Task 객체를 검사합니다.

세션 만들기

어두운 곳에서 촬영하는 세션을 만들려면 LowLightBoostClient.createSession 메서드를 호출합니다.

Kotlin

val options = LowLightBoostOptions(
  previewSurface,
  cameraId,
  previewWidth,
  previewHeight,
  enableLowLightBoost
)

launch {
  try {
    val lowLightBoostSession = lowLightBoostClient
      .createSession(options, createLowLightBoostCallback()).await()

    Log.d(TAG, "Session created successfully")

    // Get the surface from the LLB session;
    // give it to camera so camera can write frames to it
  } catch (e: CancellationException) {
    Log.w(TAG, "Session creation was canceled", e)
    lowLightBoostSession = null
  } catch (e: ApiException) {
    Log.e(TAG, "Session creation failed with ApiException:", e)
    lowLightBoostSession = null
  } catch (e: Exception) {
    Log.e(TAG, "Session creation failed with Exception", e)
    lowLightBoostSession = null
  }
}

자바

LowLightBoostOptions options = new LowLightBoostOptions(
  previewSurface,
  cameraId,
  previewWidth,
  previewHeight,
  enableLowLightBoost);

lowLightBoostClient
  .createSession(options, createLowLightBoostCallback())
  .addOnSuccessListener(
    lowLightBoostExecutor,
    (session) -> {
      Log.d(TAG, "Session created successfully");

      // Get the surface from the LLB session;
      // give it to camera so camera can write frames to it

    })
  .addOnFailureListener(
    lowLightBoostExecutor,
    (e) -> {
      ApiException apiException = (ApiException) e;
      Log.d(TAG, "Session creation failed: " + e);
      lowLightBoostSession = null;
    })
  .addOnCompleteListener(
    lowLightBoostExecutor,
    (task) -> Log.d(TAG, "Session creation complete"))
  .addOnCanceledListener(
    lowLightBoostExecutor,
    () -> {
      throw new RuntimeException("Session creation canceled");
    });

이 코드에 관한 핵심 사항

  • LowLightBoostOptions 객체를 createSession()에 전달하여 세션을 구성합니다. 이 객체는 타겟 화면, 사용할 카메라의 ID, 미리보기의 크기 등을 지정합니다.
  • 이 코드에서는 Camera2 카메라에 대한 연결을 이미 열었고 이 정보를 사용하여 cameraId, previewWidth, previewHeight 값을 설정했다고 가정합니다. 자세한 내용은 Camera2 문서를 참고하세요.
  • enableLowLightBoost는 어두운 곳에서 부스트를 시작할지 여부를 지정하는 불리언 값입니다.
  • createLowLightBoostCallback는 콜백 객체를 만들기 위해 작성하는 메서드입니다. 이 객체는 세션이 연결 해제되거나 소멸될 때 호출됩니다.
  • LowLightBoostClient.createSession() 메서드는 Task 객체를 반환합니다. 이 객체를 사용하여 성공 및 실패 리스너를 설정합니다. 성공 리스너 내에서 동영상을 캡처합니다.
  • 리스너를 실행할 Executor를 지정할 수 있습니다. Executor를 지정하지 않으면 리스너가 기본 스레드에서 실행됩니다. 이 코드에서는 lowLightBoostExecutor이 적절한 Executor이라고 가정합니다.

캡처 결과 전달

Google 야간 모드에서는 적용할 밝기 조정의 올바른 양을 알기 위해 특정 카메라 메타데이터가 필요합니다. TotalCaptureResultprocessCaptureResult() 메서드에 전달해야 합니다. onCaptureCompleted() 콜백 메서드에서 TotalCaptureResult를 가져올 수 있습니다.

Kotlin

  val captureCallback = CameraCaptureSession.CaptureCallback() {
    override fun onCaptureCompleted(
      session: CameraCaptureSession,
      request: CaptureRequest,
      result: TotalCaptureResult
    ) {
      super.onCaptureCompleted(session, request, result)
      lowLightBoostSession?.processCaptureResult(result)
    }
  }

자바

  CameraCaptureSession.CaptureCallback captureCallback =
    new CameraCaptureSession.CaptureCallback() {
      @Override
      public void onCaptureCompleted(
        @NonNull CameraCaptureSession session,
        @NonNull CaptureRequest request,
        @NonNull TotalCaptureResult result) {
          super.onCaptureCompleted(session, request, result)
          if (lowLightBoostSession != null) {
            lowLightBoostSession.processCaptureResult(result);
          }
        }
      };

이 코드에 관한 핵심 사항

  • 이 코드에는 Google LLB와 관련된 CaptureCallback 코드만 표시됩니다. 이러한 콜백에는 다른 코드가 있을 수 있습니다.
  • TotalCaptureResult를 전달하면 Google LLB가 자동 노출 데이터와 기타 메타데이터를 분석하여 어두운 곳에서 부스트가 장면 감지를 처리하고 프레임에 적용할 부스트 양을 결정할 수 있습니다.
  • 카메라 세션을 만들 때 captureCallback 객체를 전달해야 합니다(예: `setSingleRepeatingRequest() 사용).

카메라 미리보기 시작

어두운 곳에서 촬영 세션을 만든 후 카메라 미리보기 스트림을 시작할 수 있습니다. 세션 만들기에 설명된 대로 어두운 조명 세션에 전달하는 onSuccess() 콜백 내에서 이를 실행해야 합니다. 다음 코드는 동영상을 캡처하는 방법을 보여줍니다.

Kotlin

MainActivity.this.lowLightBoostSession =
  lowLightBoostSession
MainActivity.this.lowLightBoostSession
  .setSceneDetectorCallback(
    (lowLightBoostSession, boostStrength) -> {
      Log.d(TAG, "onSceneBrightnessChanged: " +
        "boostStrength=$boostStrength")
      // boostStrength > 0.5 indicates a low light scene.
      // Update UI accordingly.
    },
    lowLightBoostExecutor
  )
try {
  startCaptureSession(
    lowLightBoostSession.getCameraSurface())
    // Start a Camera2 session here. Pass the LLB surface
    // to the camera so the camera can write frames to it.
} catch (e: CameraAccessException) {
  Log.e(TAG, "Failed to start capture session", e)
  // Must try again or start the capture session without LLB.
}

자바

MainActivity.this.lowLightBoostSession =
  lowLightBoostSession;
MainActivity.this.lowLightBoostSession
  .setSceneDetectorCallback(
    (lowLightBoostSession, boostStrength) -> {
      Log.d(TAG, "onSceneBrightnessChanged: " +
        "boostStrength=" + boostStrength);
      // boostStrength > 0.5 indicates a low light scene.
      // Update UI accordingly.
    },
    lowLightBoostExecutor
  );
try {
  startCaptureSession(
    lowLightBoostSession.getCameraSurface());
    // Start a Camera2 session here. Pass the LLB surface
    // to the camera so the camera can write frames to it.
} catch (CameraAccessException e) {
  Log.e(TAG, "Failed to start capture session", e);
  // Must try again or start the capture session without LLB.
}

이 코드에 관한 핵심 사항

세션 해제

카메라가 더 이상 활성 상태가 아니면 LowLightBoostSession.release()를 호출하여 어두운 곳에서 밝기 향상 세션을 해제합니다. 특히 활동이 소멸되면 세션을 해제해야 합니다. 활동의 onDestroy() 메서드에서 다음 메서드를 호출하면 됩니다.

Kotlin

override protected void onDestroy() {
  super.onDestroy()
  if (lowLightBoostSession != null) {
    lowLightBoostSession.release()
    lowLightBoostSession = null
  }
}

자바

@Override
protected void onDestroy() {
  super.onDestroy();
  if (lowLightBoostSession != null) {
    lowLightBoostSession.release();
    lowLightBoostSession = null;
  }
}

이 코드에 관한 핵심 사항

  • 세션이 해제된 후에는 세션의 메서드를 호출하면 안 됩니다. 이 코드에서와 같이 세션을 가리키는 변수를 삭제해야 합니다.