Menggunakan sesi peningkatan cahaya redup

Gunakan sesi peningkatan cahaya redup untuk mengaktifkan dan menonaktifkan Peningkatan Cahaya Redup 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 disediakan oleh paket com.google.android.gms.cameralowlight layanan Google Play. Lihat dokumentasi layanan Google Play untuk mengetahui informasi tentang cara mengakses API layanan Google Play.

Membuat objek callback

Saat membuat sesi pengoptimalan pencahayaan rendah, Anda harus meneruskan objek yang mengimplementasikan antarmuka LowLightBoostCallback. Fungsi objek ini dipanggil saat sesi terputus atau dihancurkan. Kode berikut menunjukkan cara membuat callback:

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

Poin penting tentang kode ini

  • Kode ini menentukan metode pribadi, createLowLightBoostCallback(), yang membuat objek callback. Anda akan memanggil metode tersebut saat benar-benar membuat sesi pengoptimalan cahaya redup, seperti yang dijelaskan dalam Membuat sesi.
  • Callback dipanggil saat sesi terputus atau dihancurkan. Callback ini tidak dipanggil saat sesi dibuat. Untuk memeriksa apakah sesi berhasil dibuat, periksa objek Task yang ditampilkan oleh LowLightBoostClient.createSession.

Membuat sesi

Untuk membuat sesi low light, panggil metode 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");
    });

Poin penting tentang kode ini

  • Anda meneruskan objek LowLightBoostOptions ke createSession() untuk mengonfigurasi sesi. Objek ini menentukan hal-hal seperti platform target, ID kamera yang akan digunakan, dan dimensi pratinjau.
  • Kode ini mengasumsikan bahwa Anda telah membuka koneksi ke kamera Camera2, dan menggunakan informasi tersebut untuk menetapkan nilai cameraId, previewWidth, previewHeight. Untuk informasi selengkapnya, lihat dokumentasi Camera2.
  • enableLowLightBoost adalah nilai boolean yang menentukan apakah pengoptimalan cahaya redup harus dimulai dalam keadaan aktif atau nonaktif.
  • createLowLightBoostCallback adalah metode yang Anda tulis untuk membuat objek callback. Objek ini dipanggil saat sesi terputus atau dihancurkan.
  • Metode LowLightBoostClient.createSession() menampilkan objek Task. Anda menggunakan objek ini untuk menyiapkan pemroses keberhasilan dan kegagalan. Ambil video di dalam pemroses keberhasilan.
  • Anda dapat menentukan Executor untuk menjalankan pemroses. Jika Anda tidak menentukan Executor, pemroses akan berjalan di thread utama. Dalam kode ini, kami mengasumsikan lowLightBoostExecutor adalah Executor yang sesuai.

Meneruskan hasil pengambilan

Mode Foto Malam Google memerlukan metadata kamera tertentu untuk mengetahui jumlah kecerahan yang tepat untuk diterapkan. Anda harus meneruskan TotalCaptureResult ke metode processCaptureResult(). Anda bisa mendapatkan TotalCaptureResult dalam metode callback onCaptureCompleted().

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

Poin penting tentang kode ini

  • Kode ini hanya menampilkan kode CaptureCallback yang relevan dengan Google LLB. Anda mungkin akan memiliki kode lain dalam callback ini.
  • Dengan meneruskan TotalCaptureResult, Google LLB dapat menganalisis data eksposur otomatis dan metadata lain yang diperlukan untuk peningkatan cahaya rendah guna memproses deteksi suasana dan menentukan seberapa besar peningkatan yang akan diterapkan ke frame.
  • Anda harus meneruskan objek captureCallback saat membuat sesi kamera, misalnya dengan `setSingleRepeatingRequest().

Memulai pratinjau kamera

Setelah membuat sesi low light, Anda dapat memulai streaming pratinjau kamera. Anda harus melakukannya di dalam callback onSuccess() yang Anda teruskan ke sesi pencahayaan rendah, seperti yang dijelaskan dalam Membuat sesi. Kode berikut menunjukkan cara merekam video:

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

Poin penting tentang kode ini

Merilis sesi

Saat kamera tidak lagi aktif, lepaskan sesi pengoptimalan cahaya rendah dengan memanggil LowLightBoostSession.release(). Secara khusus, Anda harus memastikan untuk merilis sesi saat aktivitas Anda dihancurkan. Anda dapat melakukannya dengan memanggil metode dalam metode onDestroy() aktivitas Anda:

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

Poin penting tentang kode ini

  • Setelah sesi dirilis, Anda tidak boleh memanggil metode apa pun. Anda harus menghapus variabel apa pun yang mengarah ke sesi, seperti yang dilakukan kode ini.