瞭解 Bitmap 模式中的媒體強化生命週期

Media Enhancement API 提供低延遲、隱私權保護的裝置端 AI 解決方案,可運用硬體加速功能,提供高品質的媒體改善功能,且不會增加 APK 檔案大小。詳情請參閱「瞭解媒體強化功能」。

靜態點陣圖模式 (EnhancementMode.BITMAP) 適用於靜態、解碼的圖片處理。

在點陣圖模式下運作時,OS 必須序列化未壓縮的像素資料,並透過系統匯流排將資料從 CPU 記憶體複製到 GPU 記憶體,然後透過反向複製傳回處理過的影格。這項功能已針對單一影格執行作業進行最佳化,不支援即時影片串流。

這個工作流程包括建立工作階段、使用工作階段處理單一點陣圖,然後處理結果。前幾節的程式碼範例詳細說明瞭這個用途。

  1. 設定選項:建立 EnhancementOptions 物件,並確認 enhancementMode 設為 EnhancementMode.BITMAP。
  2. 建立工作階段:使用先前定義的 createSessionAsync 包裝函式建立 EnhancementSession。這是重量級物件,因此請只在需要時建立。
  3. 處理圖片:呼叫工作階段、輸入點陣圖和所需選項。
  4. 處理結果:暫停函式會在成功時傳回新的強化點陣圖,或在失敗時擲回例外狀況。
  5. 釋出工作階段:完成後,請務必呼叫 session.release(),釋出 GPU 資源。

EnhancementSession 是重量級情境物件,可維護永久 GPU 或 NPU 記憶體管道。它會分配專屬視訊 RAM (VRAM) 和原生系統控制代碼。為避免嚴重的記憶體流失和潛在的 OutOfMemoryError 異常終止,請遵循下列生命週期原則:

  1. 延遲例項化:在使用者啟動強化動作前,請勿建立工作階段。
  2. 策略性重複使用:處理多張設定 (尺寸和切換選項) 相同的圖片時,請維護並重複使用單一工作階段例項。
  3. 提示拆解:視覺任務終止時,立即叫用 session.release(),釋出共用硬體資源。

初始化強化引擎

這個方法會執行兩步驟檢查。它會驗證裝置硬體是否支援加速,然後確保必要的機器學習模組存在。

在應用程式嘗試處理媒體前,先執行這項必要步驟來驗證功能,可避免執行階段初始化失敗。

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(installStatusCallback).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) {}
        override fun onCancelled(statusCode: Int) {}
    }
    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. Swap in the result:將顯示的圖片替換為強化後的點陣圖。短暫的交錯淡出效果可讓切換過程較不明顯。

下列 ProgressiveImageEnhancer 類別一次處理一張圖片,並針對相同大小的圖片重複使用單一工作階段。如果強化失敗,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 使用固定的輸入維度。要求大小一致的低解析度圖片,讓應用程式在不同圖片間重複使用單一工作階段。
  • 快取強化結果:將強化後的點陣圖儲存在圖片快取中,這樣應用程式就不會再次處理同一張圖片。如果啟用放大功能,強化後的點陣圖會比輸入點陣圖大。根據較大的點陣圖調整快取大小。