Media Enhancement API 提供了一种低延迟、可保护隐私的设备端 AI 解决方案,该解决方案利用硬件加速功能,在不增加 APK 大小的情况下提供高质量的媒体改进。如需了解详情,请参阅了解媒体增强功能。
静态位图模式 (EnhancementMode.BITMAP) 专为静态、解码后的图片处理而设计。
在位图模式下运行需要操作系统序列化未压缩的像素数据,并将其从 CPU 内存通过系统总线复制到 GPU 内存,然后通过反向复制返回处理后的帧。它针对单帧执行进行了优化,与实时视频流式传输不兼容。
此工作流涉及创建会话、使用该会话处理单个位图,然后处理结果。前面部分中的代码示例详细介绍了此用例。
- 配置选项:创建一个
EnhancementOptions对象,确保将enhancementMode设置为EnhancementMode.BITMAP。 - 创建会话:使用我们之前定义的
createSessionAsync封装容器创建EnhancementSession。这是一个开销较大的对象,因此请仅在需要时创建。 - 处理图片:调用会话、输入位图和所需选项。
- 处理结果:挂起函数在成功时返回新的增强型位图,在失败时抛出异常。
- 释放会话:至关重要的是,在完成操作后调用
session.release()以释放 GPU 资源。
EnhancementSession 是一个重量级上下文对象,用于维护永久性 GPU 或 NPU 内存流水线。它会分配专用视频 RAM (VRAM) 和原生系统句柄。为防止严重的内存泄漏和潜在的 OutOfMemoryError 崩溃,请遵循以下生命周期原则:
- 延迟实例化:在用户发起增强操作之前,请勿创建会话。
- 策略性重复使用:在处理具有相同配置(尺寸和开关选项)的多张图片时,维护并重复使用单个会话实例。
- 提示拆解:在视觉任务终止时立即调用
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。模块安装会通过网络下载模型文件。 如果用户已处于慢速连接状态,请勿开始安装。
如果上述任何条件不满足,则显示下载的图片,而不进行增强。
实现模式
该模式的工作原理如下:
- 显示低分辨率图片:在小图片下载后立即进行渲染。
- 在后台美化:如果美化引擎已准备就绪,请在位图模式下处理图片,并启用放大和去模糊功能。
- 换入结果:将显示的图片替换为增强后的位图。短暂的淡入淡出效果可让切换不那么明显。
以下 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使用固定的输入维度。请求采用一致尺寸的低分辨率图片,以便您的应用可以跨图片重复使用单个会话。 - 缓存美化后的结果:将美化后的位图存储在图片缓存中,这样您的应用就无需再次处理同一图片。如果您启用放大功能,则增强后的位图会大于输入位图。根据较大的位图调整缓存大小。