저조도 모드 세션 사용

저조도 부스트 세션을 사용하여 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");
    });

이 코드의 핵심 사항

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

캡처 결과 전달

Google 저조도 보정은 적용할 올바른 밝기의 양을 알기 위해 특정 카메라 메타데이터가 필요합니다. processCaptureResult() 메서드에 TotalCaptureResult를 전달해야 합니다. 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;
  }
}

이 코드의 핵심 사항

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