Bitmap モードでのメディア拡張のライフサイクルについて

Media Enhancement API は、低レイテンシでプライバシーを保護するオンデバイス AI ソリューションを提供します。このソリューションは、ハードウェア アクセラレーションを活用して、APK の肥大化をゼロに抑えながら、高品質のメディア改善を実現します。詳細については、メディア拡張機能についてをご覧ください。

静的ビットマップ モード(EnhancementMode.BITMAP)は、静的なデコードされた画像処理用に設計されています。

ビットマップ モードで動作する場合、OS は非圧縮ピクセルデータをシリアル化し、CPU メモリからシステムバスを介して GPU メモリにコピーして、処理されたフレームを逆コピーで返す必要があります。シングルフレームの実行用に最適化されており、リアルタイムの動画ストリーミングには対応していません。

このワークフローでは、セッションを作成し、そのセッションで 1 つのビットマップを処理して、結果を処理します。前のセクションのコード例では、このユースケースについて詳しく説明しています。

  1. オプションを構成する: EnhancementOptions オブジェクトを作成し、enhancementMode が EnhancementMode.BITMAP に設定されていることを確認します。
  2. セッションを作成する: 前に定義した createSessionAsync ラッパーを使用して EnhancementSession を作成します。これは負荷の大きなオブジェクトであるため、必要な場合にのみ作成してください。
  3. 画像を処理する: セッション、入力ビットマップ、必要なオプションを呼び出します。
  4. 結果を処理する: suspend 関数は、成功すると新しい拡張ビットマップを返し、失敗すると例外をスローします。
  5. セッションを解放する: 重要な点として、終了時に session.release() を呼び出して GPU リソースを解放します。

EnhancementSession は、永続的な GPU または NPU メモリ パイプラインを維持する、重いコンテキスト オブジェクトです。専用のビデオ RAM(VRAM)とネイティブ システム ハンドルを割り当てます。深刻なメモリリークや OutOfMemoryError のクラッシュを防ぐには、次のライフサイクル原則に従ってください。

  1. 遅延インスタンス化: ユーザーが拡張アクションを開始するまでセッションを作成しません。
  2. 戦略的な再利用: 構成(サイズと切り替えオプション)が同じ複数の画像を処理する場合は、単一のセッション インスタンスを維持して再利用します。
  3. プロンプトの破棄: 視覚タスクが終了したらすぐに session.release() を呼び出して、共有ハードウェア リソースを解放します。

拡張エンジンを初期化する

このメソッドは、2 段階のチェックをオーケストレートします。デバイスのハードウェアがアクセラレーションをサポートしているかどうかを確認し、必要な機械学習モジュールが存在することを確認します。

このステップを前提条件として実行すると、アプリがメディアの処理を試みる前に機能を検証することで、ランタイム初期化エラーを防ぐことができます。

class MediaSetupViewModel(application: Application) : AndroidViewModel(application) {
    private val enhancementClient = Enhancement.getClient(application)
    fun initializeEnhancementEngine() {
        viewModelScope.launch {
            try {
                // 1. Verify hardware capability
                val isSupported = enhancementClient.isDeviceSupportedAsync()
                if (!isSupported) {
                    notifyUiDeviceIncompatible()
                    return@launch
                }
                // 2. Verify and download the Google Play services ML modules
                val isInstalled = enhancementClient.isModuleInstalledAsync()
                if (!isInstalled) {
                    notifyUiDownloadingModels()
                    enhancementClient.installModule().await()
                }
                notifyUiEngineReady()
            } catch (e: Exception) {

                // Handle potential errors during session creation or image processing.
                handleInitializationError(e)
            }
        }
    }
}

セッションとビットマップ プロセスのラッパーを作成する

これらの Kotlin コルーチン ラッパーを使用すると、タスクベースのクライアント コールバックを標準のサスペンド関数に変換して、よりクリーンで順次的な実行を可能にできます。

// Wraps the task-based createSession callback into a suspending function.
suspend fun EnhancementClient.createSessionAsync(
    options: EnhancementOptions,
    executor: Executor
): EnhancementSession = withContext(Dispatchers.Main) {
    suspendCancellableCoroutine { continuation ->

        // EnhancementSessionCallback handles session success or failure.
        val callback = object : EnhancementSessionCallback {
            override fun onSessionCreated(session: EnhancementSession) {
                continuation.resume(session)
            }
            override fun onSessionCreationFailed(status: Status) {
                continuation.resumeWithException(
                    Exception("Session creation failed: ${status.statusMessage} (${status.statusCode})")
                )
            }
            override fun onSessionDestroyed() {}
            override fun onSessionDisconnected(status: Status) {}
        }

        // Handles errors during the initial request trigger.
        this@createSessionAsync.createSession(options, callback).addOnFailureListener(executor) { e ->
            if (continuation.isActive) {
                continuation.resumeWithException(e)
            }
        }
    }
}

// Wraps this process in a suspending function for cleaner execution.
suspend fun EnhancementSession.processBitmapAsync(
    bitmap: Bitmap,
    options: EnhancementOptions
): Bitmap = suspendCancellableCoroutine { continuation ->

    // EnhancementCallback returns the processed bitmap or an error code.
    val callback = object : EnhancementCallback {
        override fun onBitmapProcessed(enhancedBitmap: Bitmap) {
            continuation.resume(enhancedBitmap)
        }
        override fun onError(statusCode: Int) {
            continuation.resumeWithException(
                Exception("Bitmap processing failed with status code: $statusCode")
            )
        }
        override fun onSurfaceProcessed(timestamp: Long) {}
    }
    this.process(bitmap, options, callback)
}

ViewModel でビットマップ パイプラインを実行する

拡張パイプラインをアプリケーション アーキテクチャに統合するには、ViewModel を使用してセッションのライフサイクルを管理します。このアプローチにより、ViewModel がクリアされたときに、重い GPU リソースが解放されます。

// Define a data class to hold image information.
data class ImageInfo(val bitmap: Bitmap)
// Define a UI state class to hold loading status, errors, and enhanced image.
data class EnhancementUiState(
    val isLoading: Boolean = false,
    val enhancementError: String? = null,
    val enhancedImage: ImageInfo? = null
)

class EnhancementViewModel(application: Application) : AndroidViewModel(application) {

    // Backing field for UI state, initialized with default values.
    private val _uiState = MutableStateFlow(EnhancementUiState())
    // Publicly exposed UI state flow for observation.
    val uiState: StateFlow<EnhancementUiState> = _uiState.asStateFlow()

// Initialize client to interact with the Media Enhancement service.
    private val enhancementClient: EnhancementClient = Enhancement.getClient(application)

// Single-thread executor for processing background enhancement tasks.
    private val enhancementExecutor = Executors.newSingleThreadExecutor()

// Track session state to enable reuse across multiple processing calls.
    private var enhancementSession: EnhancementSession? = null
    private var sessionOptions: EnhancementOptions? = null

// Primary function to trigger the enhancement workflow for a provided bitmap.
    fun enhanceImage(bitmap: Bitmap) {
        viewModelScope.launch(Dispatchers.IO) {
            _uiState.update { it.copy(isLoading = true, enhancementError = null) }
            try {
                // Define enhancement options (for example, enable upscale, tonemapping) based
                // on bitmap dimensions.
                val options = EnhancementOptions(
                    bitmap.width,
                    bitmap.height,
                    EnhancementMode.BITMAP,
                    isTonemappingEnabled = true,
                    isDeblurAndDenoisePhotoEnabled = true,
                    isUpscalePhotoEnabled = false,
                )
                // 1. Establish the session lazily on demand. A session is configured for
                // specific input dimensions, so replace it when the bitmap size changes.
                if (enhancementSession == null ||
                    sessionOptions?.width != options.width ||
                    sessionOptions?.height != options.height
                ) {
                    enhancementSession?.release()
                    enhancementSession = null
                    enhancementSession = enhancementClient.createSessionAsync(options, enhancementExecutor)
                    sessionOptions = options
                }
                val session = enhancementSession ?: throw IllegalStateException("Session unavailable.")
                // 2. Dispatch image through the neural pipeline
                val enhancedBitmap = session.processBitmapAsync(bitmap, options)
                // 3. Render output to UI
                _uiState.update {
                    it.copy(enhancedImage = ImageInfo(bitmap = enhancedBitmap))
                }
            } catch (e: Exception) {
                _uiState.update { it.copy(enhancementError = e.message) }
            } finally {

// Ensure loading state is reset regardless of the outcome.
                _uiState.update { it.copy(isLoading = false) }
            }
        }
    }
    override fun onCleared() {
        // 4. Critical: Release native GPU hardware resources
        enhancementSession?.release()
        enhancementSession = null
        enhancementExecutor.shutdown()
        super.onCleared()
    }
}

低速なネットワークでは画像を段階的に読み込む

低速のネットワークでは、アプリはフル解像度のファイルではなく、より小さく圧縮されたバージョンの画像をダウンロードできます。アプリは、ビットマップ モードを使用して、デバイス上で画像のアップスケールとブレ軽減を行うことができます。補正された画像は、フル解像度のダウンロードに代わるものであるため、ユーザーは大きなファイルを転送することなく、より鮮明な画像を見ることができます。

このパターンを使用する場面

このパターンは、次のすべてに該当する場合に適しています。

  • デバイスがサポートされている: isDeviceSupportedAsync() が true を返します。この API は Android 11(API レベル 30)以降を必要とし、プレミアムティアのデバイス向けに最適化されています。
  • 画像がダウンロードされたサイズよりも大きく表示されている: たとえば、小さな画像が全画面表示されている場合です。画像がサムネイル サイズのままであれば、アップスケーリングによる目に見えるメリットはほとんどありません。
  • 拡張モジュールがすでにインストールされている: isModuleInstalledAsync() は true を返します。モジュールのインストールでは、ネットワーク経由でモデルファイルがダウンロードされます。ユーザーの接続がすでに遅い場合は、インストールを開始しないでください。

これらの条件のいずれかが満たされない場合は、ダウンロードした画像を補正せずに表示します。

パターンを実装する

このパターンは次のように機能します。

  1. 低解像度の画像を表示する: 小さい画像がダウンロードされたらすぐにレンダリングします。
  2. バックグラウンドで補正する: 補正エンジンが準備できたら、アップスケーリングとブレ軽減を有効にして、ビットマップ モードで画像を処理します。
  3. 結果を入れ替える: 表示されている画像を、補正されたビットマップに置き換えます。クロスフェードを短くすると、スワップが目立たなくなります。

次の ProgressiveImageEnhancer クラスは、一度に 1 つの画像を処理し、同じサイズの画像に対して 1 つのセッションを再利用します。補正が失敗した場合、enhance() は null を返すため、アプリは引き続き低解像度の画像を表示します。このクラスは、セッションとビットマップ プロセスのラッパーを作成するで定義されている createSessionAsync ラッパーと processBitmapAsync ラッパーを使用します。

拡張エンジンを初期化するの説明に沿って、モジュールを事前にインストールします。isDeviceSupportedAsync() と isModuleInstalledAsync() が true を返した場合は、enhance() を呼び出します。

class ProgressiveImageEnhancer(
    private val enhancementClient: EnhancementClient,
    private val executor: Executor,
) {
    // Callers can request enhancements concurrently, but they all share one
    // session, so process one image at a time.
    private val mutex = Mutex()
    private var session: EnhancementSession? = null
    private var sessionOptions: EnhancementOptions? = null

    // Enhancement is optional for this pattern, so return null instead of
    // throwing. The caller can keep the low-resolution image without extra
    // error handling.
    suspend fun enhance(lowResBitmap: Bitmap): Bitmap? = mutex.withLock {
        val options = EnhancementOptions(
            width = lowResBitmap.width,
            height = lowResBitmap.height,
            enhancementMode = EnhancementMode.BITMAP,
            isDeblurAndDenoisePhotoEnabled = true,
            isUpscalePhotoEnabled = true,
        )
        try {
            getOrCreateSession(options).processBitmapAsync(lowResBitmap, options)
        } catch (e: CancellationException) {
            // A cancelled request (for example, the user scrolled away) isn't
            // an enhancement failure, so let the caller's scope handle it.
            throw e
        } catch (e: Exception) {
            null
        }
    }

    // Sessions are expensive to create and are configured for specific input
    // dimensions, so reuse the current one until the image size changes.
    private suspend fun getOrCreateSession(options: EnhancementOptions): EnhancementSession {
        val currentSession = session
        val currentOptions = sessionOptions
        if (currentSession != null &&
            currentOptions != null &&
            currentOptions.width == options.width &&
            currentOptions.height == options.height
        ) {
            return currentSession
        }
        releaseSession()
        return enhancementClient.createSessionAsync(options, executor).also {
            session = it
            sessionOptions = options
        }
    }

    // A session holds GPU memory until it's released, so free it as soon as
    // the images it enhances are no longer on screen. Taking the lock first
    // waits for any in-progress enhancement, so a session that's still being
    // created isn't leaked.
    suspend fun release() = mutex.withLock { releaseSession() }

    private fun releaseSession() {
        session?.release()
        session = null
        sessionOptions = null
    }
}

このパターンを使用する場合は、次のガイドラインに従ってください。

  • 一貫したサイズをリクエストする: EnhancementSession は固定の入力ディメンションを使用します。アプリが画像間で単一のセッションを再利用できるように、低解像度の画像を 1 つの一貫したサイズでリクエストします。
  • 補正結果をキャッシュに保存する: 補正されたビットマップを画像キャッシュに保存して、アプリが同じ画像を再度処理しないようにします。アップスケーリングを有効にすると、拡張されたビットマップは入力ビットマップよりも大きくなります。大きなビットマップに合わせてキャッシュのサイズを設定します。