Media Enhancement API เป็นโซลูชัน AI ในอุปกรณ์ที่มีเวลาในการตอบสนองต่ำและรักษาความเป็นส่วนตัว ซึ่งใช้ประโยชน์จากการเร่งฮาร์ดแวร์เพื่อปรับปรุงสื่อให้มีคุณภาพสูงโดยไม่มี APK ที่ไม่จำเป็น ดูข้อมูลเพิ่มเติมได้ที่ทำความเข้าใจความสามารถในการเพิ่มประสิทธิภาพสื่อ
โหมดบิตแมปแบบคงที่ (EnhancementMode.BITMAP) ออกแบบมาสำหรับการประมวลผลรูปภาพที่ถอดรหัสแล้วแบบคงที่
การทำงานในโหมดบิตแมปกำหนดให้ระบบปฏิบัติการต้องจัดเรียงข้อมูลพิกเซลที่ไม่มีการบีบอัดตามลำดับ และคัดลอกจากหน่วยความจำ CPU ผ่านบัสระบบไปยังหน่วยความจำ GPU โดยแสดงผลเฟรมที่ประมวลผลแล้วผ่านการคัดลอกแบบย้อนกลับ โดยได้รับการเพิ่มประสิทธิภาพสำหรับการดำเนินการแบบเฟรมเดียวและไม่สามารถใช้ร่วมกับการสตรีมวิดีโอแบบเรียลไทม์
เวิร์กโฟลว์นี้เกี่ยวข้องกับการสร้างเซสชัน การประมวลผลบิตแมปรายการเดียวด้วยเซสชันดังกล่าว และการจัดการผลลัพธ์ ตัวอย่างโค้ดจากส่วนก่อนหน้าจะครอบคลุมกรณีการใช้งานนี้โดยละเอียด
- กำหนดค่าตัวเลือก: สร้างออบเจ็กต์
EnhancementOptionsโดยตรวจสอบว่าได้ตั้งค่าenhancementModeเป็นEnhancementMode.BITMAP - สร้างเซสชัน: ใช้ Wrapper
createSessionAsyncที่เรากำหนดไว้ก่อนหน้านี้เพื่อสร้างEnhancementSessionออบเจ็กต์นี้มีขนาดใหญ่ ดังนั้นให้สร้างเมื่อจำเป็นเท่านั้น - ประมวลผลรูปภาพ: เรียกใช้เซสชัน บิตแมปอินพุต และตัวเลือกที่ต้องการ
- จัดการผลลัพธ์: ฟังก์ชันระงับจะแสดงผลบิตแมปใหม่ที่ได้รับการปรับปรุงเมื่อดำเนินการสำเร็จ หรือแสดงข้อยกเว้นเมื่อดำเนินการไม่สำเร็จ
- ปล่อยเซสชัน: สิ่งสำคัญคือให้เรียกใช้
session.release()เมื่อคุณดำเนินการเสร็จแล้วเพื่อเพิ่มพื้นที่ว่างในทรัพยากร GPU
EnhancementSession เป็นออบเจ็กต์บริบทที่มีน้ำหนักมากซึ่งรักษาไปป์ไลน์หน่วยความจำ GPU หรือ NPU แบบถาวร โดยจะจัดสรรหน่วยความจำวิดีโอ (VRAM) โดยเฉพาะและแฮนเดิลระบบแบบเนทีฟ เพื่อป้องกันไม่ให้หน่วยความจำรั่วไหลอย่างรุนแรงและอาจทำให้ OutOfMemoryError ขัดข้อง ให้ปฏิบัติตามหลักการวงจรต่อไปนี้
- การสร้างอินสแตนซ์แบบ Lazy: อย่าสร้างเซสชันจนกว่าผู้ใช้จะเริ่มการดำเนินการปรับปรุง
- การนำกลับมาใช้ใหม่อย่างมีกลยุทธ์: คงและนำอินสแตนซ์เซสชันเดียวกลับมาใช้ใหม่เมื่อประมวลผลรูปภาพหลายรูปที่มีการกำหนดค่าเหมือนกัน (ขนาดและตัวเลือกเปิด/ปิด)
- การปิดใช้งานพรอมต์: เรียกใช้
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(installStatusCallback).await() } notifyUiEngineReady() } catch (e: Exception) { // Handle potential errors during session creation or image processing. handleInitializationError(e) } } } }
สร้าง Wrapper ของเซสชันและกระบวนการบิตแมป
ใช้ Wrapper ของโครูทีน Kotlin เหล่านี้เพื่อแปลง Callback ของไคลเอ็นต์ที่อิงตามงานเป็นฟังก์ชันการระงับมาตรฐาน ซึ่งจะช่วยให้การดำเนินการเป็นไปอย่างเป็นระเบียบและเป็นลำดับมากขึ้น
// 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 เพื่อจัดการวงจรของเซสชัน วิธีนี้ช่วยให้มั่นใจได้ว่าทรัพยากร GPU ที่ใช้จำนวนมากจะได้รับการปล่อยเมื่อล้าง ViewModel
// 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()แสดงผลเป็นtrueAPI ต้องใช้ Android 11 (ระดับ API 30) ขึ้นไปและได้รับการเพิ่มประสิทธิภาพสำหรับอุปกรณ์ระดับพรีเมียม - รูปภาพแสดงขนาดใหญ่กว่าขนาดที่ดาวน์โหลด: เช่น รูปภาพขนาดเล็กที่แสดงแบบเต็มหน้าจอ หากรูปภาพยังคงมีขนาดเท่าภาพขนาดย่อ การเพิ่มขนาดจะให้ประโยชน์ที่มองเห็นได้เพียงเล็กน้อย
- โมดูลการเพิ่มประสิทธิภาพติดตั้งอยู่แล้ว:
isModuleInstalledAsync()แสดงผลเป็นtrueการติดตั้งโมดูลจะดาวน์โหลดไฟล์โมเดลผ่านเครือข่าย หากผู้ใช้ใช้การเชื่อมต่อที่ช้าอยู่แล้ว อย่าเริ่มการติดตั้ง
หากไม่เป็นไปตามเงื่อนไขเหล่านี้ ให้แสดงรูปภาพที่ดาวน์โหลดโดยไม่มีการปรับปรุง
ใช้รูปแบบ
รูปแบบจะทำงานดังนี้
- แสดงรูปภาพที่มีความละเอียดต่ำ: แสดงผลรูปภาพขนาดเล็กทันทีที่ดาวน์โหลด
- ปรับปรุงในเบื้องหลัง: หากเครื่องมือปรับปรุงพร้อมใช้งาน ให้ประมวลผลรูปภาพในโหมดบิตแมปโดยเปิดใช้การเพิ่มสเกลและการปรับให้คมชัด
- สลับในผลลัพธ์: แทนที่รูปภาพที่แสดงด้วยบิตแมปที่ปรับปรุงแล้ว การเฟดข้ามสั้นๆ จะทำให้การสลับสังเกตเห็นได้น้อยลง
คลาส ProgressiveImageEnhancer ต่อไปนี้จะประมวลผลรูปภาพทีละรูปและใช้เซสชันเดียวซ้ำสำหรับรูปภาพที่มีขนาดเท่ากัน หากการปรับปรุงไม่สำเร็จ enhance() จะแสดงผล null เพื่อให้แอปแสดงรูปภาพความละเอียดต่ำต่อไป คลาสใช้ Wrapper createSessionAsync และ processBitmapAsync ที่กำหนดไว้ในสร้าง Wrapper ของเซสชันและกระบวนการบิตแมป
ติดตั้งโมดูลล่วงหน้าตามที่แสดงในหัวข้อเริ่มต้นเครื่องมือเพิ่มประสิทธิภาพ หาก 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ใช้ขนาดอินพุตคงที่ ขอรูปภาพความละเอียดต่ำในขนาดที่สอดคล้องกันเพื่อให้แอปใช้เซสชันเดียวซ้ำในรูปภาพต่างๆ ได้ - แคชผลลัพธ์ที่ปรับปรุงแล้ว: จัดเก็บบิตแมปที่ปรับปรุงแล้วไว้ในแคชรูปภาพเพื่อให้แอปไม่ประมวลผลรูปภาพเดิมอีก หากเปิดใช้การเพิ่มขนาด บิตแมปที่ปรับปรุงแล้วจะมีขนาดใหญ่กว่าบิตแมปอินพุต ปรับขนาดแคชสำหรับบิตแมปขนาดใหญ่ขึ้น