@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class) package eu.friedcutlet.yokan.services.media import eu.friedcutlet.yokan.services.files.IosSecurityScopedBookmarks import kotlin.coroutines.resume import kotlinx.cinterop.addressOf import kotlinx.cinterop.usePinned import kotlinx.coroutines.suspendCancellableCoroutine import platform.AVFoundation.AVAssetImageGenerator import platform.AVFoundation.AVAssetImageGeneratorSucceeded import platform.AVFoundation.AVURLAsset import platform.AVFoundation.valueWithCMTime import platform.CoreGraphics.CGSizeMake import platform.CoreMedia.CMTimeGetSeconds import platform.CoreMedia.CMTimeMakeWithSeconds import platform.Foundation.NSData import platform.Foundation.NSURL import platform.Foundation.NSValue import platform.UIKit.UIImage import platform.UIKit.UIImageJPEGRepresentation import platform.posix.memcpy /** AVFoundation decodes inside the folder's security scope (open-in-place and bookmarked folders). */ actual fun createPlatformVideoFrameExtractor(): VideoFrameExtractor = VideoFrameExtractor { url, maxDimension -> IosSecurityScopedBookmarks.withAccessAsync(url.removePrefix("file://")) { path -> val asset = AVURLAsset.URLAssetWithURL(NSURL.fileURLWithPath(path), options = null) val generator = AVAssetImageGenerator.assetImageGeneratorWithAsset(asset).apply { appliesPreferredTrackTransform = true maximumSize = CGSizeMake(maxDimension.toDouble(), maxDimension.toDouble()) } val seconds = CMTimeGetSeconds(asset.duration).takeIf { it.isFinite() && it > 0 } ?: 0.0 val time = NSValue.valueWithCMTime(CMTimeMakeWithSeconds(seconds * 0.1, 600)) suspendCancellableCoroutine { continuation -> continuation.invokeOnCancellation { generator.cancelAllCGImageGeneration() } generator.generateCGImagesAsynchronouslyForTimes(listOf(time)) { _, image, _, result, _ -> // The CGImage is only valid inside this handler. val bytes = if (result == AVAssetImageGeneratorSucceeded && image != null) { UIImageJPEGRepresentation(UIImage.imageWithCGImage(image), 0.85)?.toByteArray() } else null if (continuation.isActive) continuation.resume(bytes) } } } } private fun NSData.toByteArray(): ByteArray = ByteArray(length.toInt()).also { output -> if (output.isNotEmpty()) output.usePinned { memcpy(it.addressOf(0), bytes, length) } }