Media Enhancement API는 지연 시간이 짧고 개인 정보를 보호하는 온디바이스 AI 솔루션을 제공합니다. 이 솔루션은 하드웨어 가속을 활용하여 APK 비대화 없이 고품질 미디어 개선을 제공합니다. 자세한 내용은 미디어 보정 기능 이해를 참고하세요.
정적 비트맵 모드 (EnhancementMode.BITMAP)는 정적 디코딩된 이미지 처리를 위해 설계되었습니다.
비트맵 모드에서 작동하려면 OS가 압축되지 않은 픽셀 데이터를 직렬화하고 시스템 버스를 통해 CPU 메모리에서 GPU 메모리로 복사하여 처리된 프레임을 역방향 복사를 통해 반환해야 합니다. 단일 프레임 실행에 최적화되어 있으며 실시간 동영상 스트리밍과 호환되지 않습니다.
이 워크플로에는 세션을 만들고, 세션으로 단일 비트맵을 처리하고, 결과를 처리하는 작업이 포함됩니다. 이전 섹션의 코드 예시에서는 이 사용 사례를 자세히 다룹니다.
- 옵션 구성:
EnhancementOptions객체를 만들고enhancementMode가EnhancementMode.BITMAP로 설정되어 있는지 확인합니다. - 세션 만들기: 이전에 정의한
createSessionAsync래퍼를 사용하여EnhancementSession를 만듭니다. 이 객체는 무거운 객체이므로 필요할 때만 만듭니다. - 이미지 처리: 세션, 입력 비트맵, 원하는 옵션을 호출합니다.
- 결과 처리: 정지 함수는 성공 시 새롭게 개선된 비트맵을 반환하고 실패 시 예외를 발생시킵니다.
- 세션 해제: 완료되면
session.release()를 호출하여 GPU 리소스를 확보하는 것이 중요합니다.
EnhancementSession는 영구 GPU 또는 NPU 메모리 파이프라인을 유지하는 무거운 컨텍스트 객체입니다. 전용 동영상 RAM (VRAM)과 네이티브 시스템 핸들을 할당합니다. 심각한 메모리 누수와 잠재적인 OutOfMemoryError 비정상 종료를 방지하려면 다음 수명 주기 원칙을 준수하세요.
- 지연 인스턴스화: 사용자가 개선 작업을 시작할 때까지 세션을 만들지 않습니다.
- 전략적 재사용: 동일한 구성 (크기 및 전환 옵션)으로 여러 이미지를 처리할 때 단일 세션 인스턴스를 유지하고 재사용합니다.
- 신속한 해체: 시각적 작업이 종료되면 즉시
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를 반환합니다. 모듈 설치는 네트워크를 통해 모델 파일을 다운로드합니다. 사용자가 이미 느린 연결을 사용 중인 경우 설치를 시작하지 않습니다.
이러한 조건 중 하나라도 충족되지 않으면 다운로드한 이미지를 보정 없이 표시합니다.
패턴 구현
패턴은 다음과 같이 작동합니다.
- 저해상도 이미지 표시: 작은 이미지가 다운로드되는 즉시 렌더링합니다.
- 백그라운드에서 보정: 보정 엔진이 준비되면 업스케일링 및 블러 제거가 사용 설정된 비트맵 모드에서 이미지를 처리합니다.
- 결과로 교체: 표시된 이미지를 보정된 비트맵으로 바꿉니다. 짧은 크로스페이드를 사용하면 전환이 눈에 덜 띕니다.
다음 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는 고정된 입력 크기를 사용합니다. 앱이 이미지 간에 단일 세션을 재사용할 수 있도록 일관된 크기의 저해상도 이미지를 요청합니다. - 보정된 결과 캐시: 앱이 동일한 이미지를 다시 처리하지 않도록 보정된 비트맵을 이미지 캐시에 저장합니다. 업스케일링을 사용 설정하면 보정된 비트맵이 입력 비트맵보다 커집니다. 더 큰 비트맵에 맞게 캐시 크기를 조정합니다.