使用低光源增強工作階段

使用低光源增強工作階段,開啟或關閉 Google 低光源增強功能。

Kotlin

dependencies {
  val low_light_boost_version = "16.0.1-beta04"
  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.1-beta04"
  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
    }
  }

Java

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
  }
}

Java

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 低光源強化功能需要特定相機中繼資料,才能判斷正確的亮度調整幅度。您必須將 TotalCaptureResult 傳遞至 processCaptureResult() 方法。您可以在 onCaptureCompleted() 回呼方法中取得 TotalCaptureResult。

Kotlin

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

Java

  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.
}

Java

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
  }
}

Java

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

這段程式碼的重點

  • 工作階段釋出後,請勿呼叫任何方法。您應清除指向工作階段的所有變數,如這段程式碼所示。