π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Add native video frame extraction support
Neeraj Gupta7cf356b42e4a
diff --git a/mobile/packages/native_video_editor/android/build.gradle b/mobile/packages/native_video_editor/android/build.gradleindex aa299f3f68..bf555531a6 100644--- a/mobile/packages/native_video_editor/android/build.gradle+++ b/mobile/packages/native_video_editor/android/build.gradle@@ -3,7 +3,7 @@ version '1.0'buildscript {ext.kotlin_version = '1.9.25'- ext.media3_version = '1.9.2'+ ext.media3_version = '1.10.1'repositories {google()mavenCentral()@@ -25,6 +25,11 @@ rootProject.allprojects {apply plugin: 'com.android.library'apply plugin: 'kotlin-android'+configurations.configureEach {+ // Frame extraction receives videos only, never still images.+ exclude group: "androidx.exifinterface", module: "exifinterface"+}+def nativeVideoEditorCompileSdkVersion = rootProject.ext.has('compileSdkVersion') ?rootProject.ext.compileSdkVersion : 35@@ -59,6 +64,7 @@ dependencies {implementation "androidx.media3:media3-common:$media3_version"implementation "androidx.media3:media3-effect:$media3_version"implementation "androidx.media3:media3-extractor:$media3_version"+ implementation "androidx.media3:media3-inspector-frame:$media3_version"// Guava for ImmutableListimplementation "com.google.guava:guava:31.1-android"diff --git a/mobile/packages/native_video_editor/android/src/main/kotlin/io/ente/native_video_editor/Media3TransformerProcessor.kt b/mobile/packages/native_video_editor/android/src/main/kotlin/io/ente/native_video_editor/Media3TransformerProcessor.ktindex a47df047b9..af647c828e 100644--- a/mobile/packages/native_video_editor/android/src/main/kotlin/io/ente/native_video_editor/Media3TransformerProcessor.kt+++ b/mobile/packages/native_video_editor/android/src/main/kotlin/io/ente/native_video_editor/Media3TransformerProcessor.kt@@ -1,46 +1,39 @@package io.ente.native_video_editorimport android.content.Context-import android.util.Log+import android.media.MediaMetadataRetrieverimport android.net.Uri+import android.os.Handler+import android.os.Looperimport androidx.media3.common.Effectimport androidx.media3.common.MediaItemimport androidx.media3.common.MimeTypes+import androidx.media3.common.util.UnstableApiimport androidx.media3.common.util.Size-import androidx.media3.effect.*-import androidx.media3.transformer.*-import kotlinx.coroutines.*+import androidx.media3.effect.Crop+import androidx.media3.effect.Presentation+import androidx.media3.effect.ScaleAndRotateTransformation+import androidx.media3.transformer.Composition+import androidx.media3.transformer.EditedMediaItem+import androidx.media3.transformer.EditedMediaItemSequence+import androidx.media3.transformer.Effects+import androidx.media3.transformer.ExportException+import androidx.media3.transformer.ExportResult+import androidx.media3.transformer.ProgressHolder+import androidx.media3.transformer.Transformer+import kotlinx.coroutines.CancellationException+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job+import kotlinx.coroutines.coroutineScope+import kotlinx.coroutines.delay+import kotlinx.coroutines.isActive+import kotlinx.coroutines.launch+import kotlinx.coroutines.suspendCancellableCoroutine+import kotlinx.coroutines.withContextimport java.io.File-import java.util.concurrent.CountDownLatch-import kotlin.math.roundToInt-/**- * Processor using Media3 Transformer for efficient video editing operations.- * Handles trim, rotate, and crop operations with proper effect chaining.- */+@UnstableApiclass Media3TransformerProcessor(private val context: Context) {- companion object {- private const val TAG = "Media3Transformer"-- // Logging levels for debugging (enabled only for debug builds when available)- private val IS_DEBUG_BUILD: Boolean = try {- val field = Class.forName("io.ente.native_video_editor.BuildConfig")- .getField("DEBUG")- field.getBoolean(null)- } catch (_: Exception) {- false- }-- private val LOG_VERBOSE = IS_DEBUG_BUILD- private val LOG_PROGRESS = IS_DEBUG_BUILD- private val LOG_ERRORS = true // Keep error logging enabled- private const val ROTATION_90 = 90- private const val ROTATION_270 = 270- }-- /**- * Process video with multiple transformations in a single pass- */suspend fun processVideo(inputPath: String,outputPath: String,@@ -52,412 +45,237 @@ class Media3TransformerProcessor(private val context: Context) {cropWidth: Int? = null,cropHeight: Int? = null,onProgress: ((Float) -> Unit)? = null- ): ProcessingResult = withContext(Dispatchers.Main) {- val startTime = System.currentTimeMillis()- val latch = CountDownLatch(1)- var processingError: Exception? = null- var hasVideoEffects = false-- logVerbose("Starting video processing:")- logVerbose(" Input: $inputPath")- logVerbose(" Output: $outputPath")- logVerbose(" Trim: ${if (trimStartMs != null) "$trimStartMs-$trimEndMs ms" else "none"}")- logVerbose(" Rotate: ${rotateDegrees ?: "none"} degrees")- logVerbose(" Crop: ${if (cropX != null) "[$cropX,$cropY ${cropWidth}x$cropHeight]" else "none"}")-- try {- // Get video info first- val videoInfo = getVideoInfo(inputPath)- val originalWidth = videoInfo.width- val originalHeight = videoInfo.height- val originalRotation = videoInfo.rotation+ ): Boolean {+ val inputFile = File(inputPath).canonicalFile+ val outputFile = File(outputPath).canonicalFile+ require(inputFile.isFile && inputFile != outputFile) {+ "Input must be a video file and output must be a different path"+ }+ require((trimStartMs == null) == (trimEndMs == null)) {+ "Trim bounds must be provided together"+ }+ require(trimStartMs == null || (trimStartMs >= 0 && trimStartMs < trimEndMs!!)) {+ "Invalid trim bounds"+ }+ require(rotateDegrees == null || rotateDegrees in setOf(0, 90, 180, 270)) {+ "Invalid rotation"+ }+ val cropValues = listOf(cropX, cropY, cropWidth, cropHeight)+ require(cropValues.all { it == null } || cropValues.all { it != null }) {+ "Crop values must be provided together"+ }+ val crop = if (cropX == null) {+ null+ } else {+ CropSpec(cropX, cropY!!, cropWidth!!, cropHeight!!)+ }+ require(crop == null || crop.isPositive) { "Invalid crop rectangle" }- logVerbose("Original video: ${originalWidth}x$originalHeight, rotation=$originalRotation")+ return try {+ val mediaItem = buildMediaItem(inputFile, trimStartMs, trimEndMs)+ val videoInfo = crop?.let { getVideoInfo(inputFile.path) }+ val effects = buildVideoEffects(videoInfo, crop, rotateDegrees)+ val editedMediaItem = EditedMediaItem.Builder(mediaItem).apply {+ if (effects.isNotEmpty()) {+ setEffects(Effects(emptyList(), effects))+ }+ }.build()+ @Suppress("DEPRECATION")+ val sequence = EditedMediaItemSequence.Builder(listOf(editedMediaItem)).build()+ val composition = Composition.Builder(listOf(sequence)).build()- // Build MediaItem with optional clipping- val mediaItemBuilder = MediaItem.Builder().setUri(Uri.fromFile(File(inputPath)))+ val exportResult = withContext(Dispatchers.Main) {+ export(+ composition = composition,+ outputPath = outputFile.path,+ transcodeVideo = effects.isNotEmpty(),+ optimizeTrim = trimStartMs != null && effects.isEmpty(),+ onProgress = onProgress+ )+ }+ require(outputFile.isFile && outputFile.length() > 0) {+ "Output file was not created"+ }+ when (exportResult.videoConversionProcess) {+ ExportResult.CONVERSION_PROCESS_TRANSCODED,+ ExportResult.CONVERSION_PROCESS_TRANSMUXED_AND_TRANSCODED -> true+ else -> false+ }+ } catch (error: CancellationException) {+ outputFile.delete()+ throw error+ } catch (error: Exception) {+ outputFile.delete()+ throw VideoProcessingException("Video processing failed: ${error.message}", error)+ }+ }+ private fun buildMediaItem(+ inputFile: File,+ trimStartMs: Long?,+ trimEndMs: Long?+ ): MediaItem = MediaItem.Builder()+ .setUri(Uri.fromFile(inputFile))+ .apply {if (trimStartMs != null && trimEndMs != null) {- logVerbose("Applying trim: $trimStartMs-$trimEndMs ms")- mediaItemBuilder.setClippingConfiguration(+ setClippingConfiguration(MediaItem.ClippingConfiguration.Builder().setStartPositionMs(trimStartMs).setEndPositionMs(trimEndMs)- .setStartsAtKeyFrame(false) // Allow precise cuts+ .setStartsAtKeyFrame(false).build())}-- val mediaItem = mediaItemBuilder.build()-- // Build effects list- val videoEffects = mutableListOf<Effect>()-- // Add crop effect if needed BEFORE rotation- // Flutter sends crop coordinates in display space.- // Like FFmpeg and iOS, we'll use these coordinates directly without transformation.- var outDimsFromCrop: Size? = null- if (cropX != null && cropY != null && cropWidth != null && cropHeight != null) {- logVerbose("Crop input: x=$cropX, y=$cropY, w=$cropWidth, h=$cropHeight")- logVerbose("Video dims: ${originalWidth}x$originalHeight, rotation=$originalRotation")-- // Use crop coordinates as-is, just like FFmpeg does- // No special treatment for metadata rotation- val fileX = cropX- val fileY = cropY- val fileW = cropWidth- val fileH = cropHeight-- logVerbose("Using crop coordinates as-is: x=$fileX, y=$fileY, w=$fileW, h=$fileH")-- // When video has rotation metadata, swap dimensions for crop fraction calculation- // This is because Flutter sends display-space coordinates (after rotation)- val effectiveWidth: Int- val effectiveHeight: Int- if (originalRotation == 90 || originalRotation == 270) {- effectiveWidth = originalHeight- effectiveHeight = originalWidth- logVerbose("Video has 90/270 rotation, swapping dimensions for crop calculation: ${effectiveWidth}x$effectiveHeight")- } else {- effectiveWidth = originalWidth- effectiveHeight = originalHeight- }-- // Calculate crop as a fraction of the effective video dimensions- val cropLeftFraction = fileX.toFloat() / effectiveWidth- val cropRightFraction = (fileX + fileW).toFloat() / effectiveWidth- val cropTopFraction = fileY.toFloat() / effectiveHeight- val cropBottomFraction = (fileY + fileH).toFloat() / effectiveHeight-- logVerbose("Crop fractions: L=$cropLeftFraction, R=$cropRightFraction, T=$cropTopFraction, B=$cropBottomFraction")-- // Use Crop effect with NDC coordinates (-1 to 1)- val ndcLeft = -1f + 2f * cropLeftFraction- val ndcRight = -1f + 2f * cropRightFraction- val ndcBottom = 1f - 2f * cropBottomFraction- val ndcTop = 1f - 2f * cropTopFraction-- logVerbose("NDC coordinates: left=$ndcLeft, right=$ndcRight, bottom=$ndcBottom, top=$ndcTop")- logVerbose("Expected crop output: ${cropWidth}x$cropHeight pixels")-- val cropEffect = Crop(- /* left = */ ndcLeft,- /* right = */ ndcRight,- /* bottom = */ ndcBottom,- /* top = */ ndcTop- )-- // Preserve output dimensions from the crop- outDimsFromCrop = Size(cropWidth, cropHeight)-- videoEffects.add(cropEffect)- hasVideoEffects = true+ }+ .build()++ private fun buildVideoEffects(+ videoInfo: VideoInfo?,+ crop: CropSpec?,+ rotateDegrees: Int?+ ): List<Effect> = buildList {+ val cropSize = crop?.let {+ val video = requireNotNull(videoInfo)+ val displayWidth = if (video.rotation == 90 || video.rotation == 270) {+ video.height+ } else {+ video.width}-- // Add rotation effect AFTER crop- if (rotateDegrees != null && rotateDegrees != 0) {- val normalizedDegrees = rotateDegrees % 360- logVerbose("Adding rotation effect: $normalizedDegrees degrees")-- // Validate rotation degrees- if (normalizedDegrees !in listOf(0, 90, 180, 270)) {- throw IllegalArgumentException("Rotation degrees must be 0, 90, 180, or 270")- }-- // Use ScaleAndRotateTransformation for proper rotation support- // Media3 uses positive degrees for clockwise rotation- val rotationEffect = ScaleAndRotateTransformation.Builder()- .setRotationDegrees(normalizedDegrees.toFloat())- .build()-- videoEffects.add(rotationEffect)- logVerbose("Added ScaleAndRotateTransformation with rotation: $normalizedDegrees degrees (clockwise)")-- hasVideoEffects = true+ val displayHeight = if (video.rotation == 90 || video.rotation == 270) {+ video.width+ } else {+ video.height}+ require(displayWidth > 0 && displayHeight > 0) {+ "Video dimensions are unavailable"+ }+ require(+ it.x.toLong() + it.width <= displayWidth &&+ it.y.toLong() + it.height <= displayHeight+ ) { "Crop rectangle exceeds the displayed video" }++ add(+ Crop(+ -1f + 2f * it.x / displayWidth,+ -1f + 2f * (it.x + it.width) / displayWidth,+ 1f - 2f * (it.y + it.height) / displayHeight,+ 1f - 2f * it.y / displayHeight+ )+ )+ Size(it.width, it.height)+ }- // Add Presentation effect to set output dimensions- // Base output on the file-space crop dimensions we actually applied.- if (outDimsFromCrop != null) {- var outputWidth = outDimsFromCrop!!.width- var outputHeight = outDimsFromCrop!!.height-- // If a user-requested rotation (not metadata) is applied after crop,- // swap output dimensions for 90/270 degrees.- if (rotateDegrees != null && (rotateDegrees % 180) != 0) {- val tmp = outputWidth- outputWidth = outputHeight- outputHeight = tmp- }+ if (rotateDegrees != null && rotateDegrees != 0) {+ add(+ ScaleAndRotateTransformation.Builder()+ .setRotationDegrees(-rotateDegrees.toFloat())+ .build()+ )+ }- val presentationEffect = Presentation.createForWidthAndHeight(- outputWidth,- outputHeight,+ if (cropSize != null) {+ val swapsDimensions = rotateDegrees == 90 || rotateDegrees == 270+ add(+ Presentation.createForWidthAndHeight(+ if (swapsDimensions) cropSize.height else cropSize.width,+ if (swapsDimensions) cropSize.width else cropSize.height,Presentation.LAYOUT_SCALE_TO_FIT_WITH_CROP)- videoEffects.add(presentationEffect)- }-- // Configure Transformer- val transformerBuilder = Transformer.Builder(context)- .setVideoMimeType(MimeTypes.VIDEO_H264) // Use H.264 for compatibility- .addListener(object : Transformer.Listener {- override fun onCompleted(composition: Composition, exportResult: ExportResult) {- logVerbose("Export completed successfully")- logVerbose("Export result: duration=${exportResult.approximateDurationMs}ms, " +- "size=${exportResult.fileSizeBytes} bytes")- latch.countDown()- }+ )+ }+ }- override fun onError(- composition: Composition,- exportResult: ExportResult,- exportException: ExportException- ) {- logError(- "Export failed (code=${exportException.errorCode}, type=${exportException::class.java.simpleName})",- exportException- )- exportException.cause?.let { cause ->- logError(- "Root cause: ${cause::class.java.simpleName} - ${cause.message}",- cause- )+ private suspend fun export(+ composition: Composition,+ outputPath: String,+ transcodeVideo: Boolean,+ optimizeTrim: Boolean,+ onProgress: ((Float) -> Unit)?+ ): ExportResult = coroutineScope {+ var progressJob: Job? = null+ try {+ suspendCancellableCoroutine { continuation ->+ val transformerBuilder = Transformer.Builder(context)+ if (transcodeVideo) {+ transformerBuilder.setVideoMimeType(MimeTypes.VIDEO_H264)+ }+ if (optimizeTrim) {+ transformerBuilder.experimentalSetTrimOptimizationEnabled(true)+ }+ val transformer = transformerBuilder+ .addListener(object : Transformer.Listener {+ override fun onCompleted(+ composition: Composition,+ exportResult: ExportResult+ ) {+ if (continuation.isActive) {+ onProgress?.invoke(1f)+ continuation.resumeWith(Result.success(exportResult))+ }}- logError("Export result: $exportResult")- processingError = exportException- latch.countDown()- }- })-- val transformer = transformerBuilder.build()-- // Create EditedMediaItem with effects- val editedMediaItemBuilder = EditedMediaItem.Builder(mediaItem)-- // Apply effects if any- if (videoEffects.isNotEmpty()) {- logVerbose("Applying ${videoEffects.size} video effects to EditedMediaItem")- val effects = Effects(- /* audioProcessors = */ emptyList(),- /* videoEffects = */ videoEffects- )- editedMediaItemBuilder.setEffects(effects)- }-- val editedMediaItem = editedMediaItemBuilder.build()- @Suppress("DEPRECATION")- val sequence = EditedMediaItemSequence.Builder(listOf(editedMediaItem)).build()- val composition = Composition.Builder(listOf(sequence)).build()-- // Start export- logVerbose("Starting export...")- transformer.start(composition, outputPath)-- // Monitor progress- val progressJob = launch {- while (latch.count > 0) {- val progressHolder = ProgressHolder()- val progressState = transformer.getProgress(progressHolder)- when (progressState) {- Transformer.PROGRESS_STATE_NOT_STARTED -> {- logProgress("Progress: Not started")+ override fun onError(+ composition: Composition,+ exportResult: ExportResult,+ exportException: ExportException+ ) {+ if (continuation.isActive) {+ continuation.resumeWith(Result.failure(exportException))+ }}- Transformer.PROGRESS_STATE_WAITING_FOR_AVAILABILITY -> {- logProgress("Progress: Waiting for availability")- }- Transformer.PROGRESS_STATE_AVAILABLE -> {- val progress = progressHolder.progress / 100f- logProgress("Progress: ${(progress * 100).roundToInt()}%")- onProgress?.invoke(progress)- }- Transformer.PROGRESS_STATE_UNAVAILABLE -> {- logProgress("Progress: Unavailable")- }- }+ })+ .build()- delay(100)+ continuation.invokeOnCancellation {+ Handler(Looper.getMainLooper()).post(transformer::cancel)}- }-- // Wait for completion- withContext(Dispatchers.IO) {- latch.await()- }- progressJob.cancel()-- // Check for errors- processingError?.let { throw it }-- val processingTime = System.currentTimeMillis() - startTime- logVerbose("Processing completed in ${processingTime}ms")-- // Verify output file exists- val outputFile = File(outputPath)- if (!outputFile.exists()) {- throw VideoProcessingException("Output file was not created")- }-- logVerbose("Output file size: ${outputFile.length()} bytes")-- ProcessingResult(- outputPath = outputPath,- processingTimeMs = processingTime,- isReEncoded = hasVideoEffects || (trimStartMs != null),- method = "Media3 Transformer"- )-- } catch (e: Exception) {- if (e is ExportException) {- logError(- "Media3 transformer failed (code=${e.errorCode}, type=${e::class.java.simpleName})",- e- )- e.cause?.let { cause ->- logError(- "Media3 transformer root cause: ${cause::class.java.simpleName} - ${cause.message}",- cause- )+ transformer.start(composition, outputPath)+ progressJob = launch {+ val holder = ProgressHolder()+ while (isActive && continuation.isActive) {+ if (transformer.getProgress(holder) == Transformer.PROGRESS_STATE_AVAILABLE) {+ onProgress?.invoke(holder.progress / 100f)+ }+ delay(100)+ }}- } else {- logError("Failed to process video", e)}- throw VideoProcessingException("Video processing failed: ${e.message}", e)+ } finally {+ progressJob?.cancel()}}- /**- * Dedicated trim operation for optimal performance- */- suspend fun trimVideo(- inputPath: String,- outputPath: String,- startTimeMs: Long,- endTimeMs: Long,- onProgress: ((Float) -> Unit)? = null- ): ProcessingResult {- return processVideo(- inputPath = inputPath,- outputPath = outputPath,- trimStartMs = startTimeMs,- trimEndMs = endTimeMs,- onProgress = onProgress- )- }-- /**- * Dedicated rotate operation- */- suspend fun rotateVideo(- inputPath: String,- outputPath: String,- degrees: Int,- onProgress: ((Float) -> Unit)? = null- ): ProcessingResult {- return processVideo(- inputPath = inputPath,- outputPath = outputPath,- rotateDegrees = degrees,- onProgress = onProgress- )- }-- /**- * Dedicated crop operation- */- suspend fun cropVideo(- inputPath: String,- outputPath: String,- cropX: Int,- cropY: Int,- cropWidth: Int,- cropHeight: Int,- onProgress: ((Float) -> Unit)? = null- ): ProcessingResult {- return processVideo(- inputPath = inputPath,- outputPath = outputPath,- cropX = cropX,- cropY = cropY,- cropWidth = cropWidth,- cropHeight = cropHeight,- onProgress = onProgress- )- }-- /**- * Get video information- */private fun getVideoInfo(videoPath: String): VideoInfo {- val retriever = android.media.MediaMetadataRetriever()+ val retriever = MediaMetadataRetriever()return try {retriever.setDataSource(videoPath)-VideoInfo(width = retriever.extractMetadata(- android.media.MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH+ MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH)?.toIntOrNull() ?: 0,height = retriever.extractMetadata(- android.media.MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT+ MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT)?.toIntOrNull() ?: 0,rotation = retriever.extractMetadata(- android.media.MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION- )?.toIntOrNull() ?: 0,- duration = retriever.extractMetadata(- android.media.MediaMetadataRetriever.METADATA_KEY_DURATION- )?.toLongOrNull() ?: 0L,- bitrate = retriever.extractMetadata(- android.media.MediaMetadataRetriever.METADATA_KEY_BITRATE- )?.toLongOrNull() ?: 0L+ MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION+ )?.toIntOrNull()?.let { ((it % 360) + 360) % 360 } ?: 0)} finally {retriever.release()}}-- // Logging helpers- private fun logVerbose(message: String) {- if (LOG_VERBOSE) Log.d(TAG, message)- }-- private fun logProgress(message: String) {- if (LOG_PROGRESS) Log.i(TAG, message)- }-- private fun logError(message: String, throwable: Throwable? = null) {- if (LOG_ERRORS) {- if (throwable != null) {- Log.e(TAG, message, throwable)- } else {- Log.e(TAG, message)- }- }- }}-/**- * Video information data class- */-private data class VideoInfo(+private data class CropSpec(+ val x: Int,+ val y: Int,val width: Int,- val height: Int,- val rotation: Int,- val duration: Long,- val bitrate: Long-)+ val height: Int+) {+ val isPositive: Boolean+ get() = x >= 0 && y >= 0 && width > 0 && height > 0+}-/**- * Result of video processing operation- */-data class ProcessingResult(- val outputPath: String,- val processingTimeMs: Long,- val isReEncoded: Boolean,- val method: String-)+private data class VideoInfo(val width: Int, val height: Int, val rotation: Int)-/**- * Custom exception for video processing errors- */class VideoProcessingException(message: String, cause: Throwable? = null) : Exception(message, cause)diff --git a/mobile/packages/native_video_editor/android/src/main/kotlin/io/ente/native_video_editor/NativeVideoEditorPlugin.kt b/mobile/packages/native_video_editor/android/src/main/kotlin/io/ente/native_video_editor/NativeVideoEditorPlugin.ktindex 1f83ee4d32..5e8865ef52 100644--- a/mobile/packages/native_video_editor/android/src/main/kotlin/io/ente/native_video_editor/NativeVideoEditorPlugin.kt+++ b/mobile/packages/native_video_editor/android/src/main/kotlin/io/ente/native_video_editor/NativeVideoEditorPlugin.kt@@ -1,11 +1,20 @@package io.ente.native_video_editorimport android.content.Context+import android.graphics.Bitmapimport android.media.*+import android.net.Uriimport android.os.Buildimport android.util.Logimport androidx.annotation.NonNull+import androidx.media3.common.MediaItem+import androidx.media3.common.util.UnstableApi+import androidx.media3.effect.Presentation+import androidx.media3.exoplayer.SeekParameters+import androidx.media3.inspector.frame.FrameExtractorimport androidx.media3.transformer.ExportException+import com.google.common.util.concurrent.ListenableFuture+import com.google.common.util.concurrent.MoreExecutorsimport io.flutter.embedding.engine.plugins.FlutterPluginimport io.flutter.plugin.common.EventChannelimport io.flutter.plugin.common.MethodCall@@ -13,16 +22,27 @@ import io.flutter.plugin.common.MethodChannelimport io.flutter.plugin.common.MethodChannel.MethodCallHandlerimport io.flutter.plugin.common.MethodChannel.Resultimport kotlinx.coroutines.*+import kotlinx.coroutines.sync.Semaphore+import kotlinx.coroutines.sync.withPermitimport java.io.File-import java.nio.ByteBuffer-+import java.io.FileOutputStream+import java.util.UUID+import java.util.concurrent.ConcurrentHashMap+import java.util.concurrent.ExecutionException+import java.util.concurrent.atomic.AtomicBoolean+import kotlin.math.max+import kotlin.math.roundToInt++@UnstableApiclass NativeVideoEditorPlugin : FlutterPlugin, MethodCallHandler, EventChannel.StreamHandler {private lateinit var channel: MethodChannelprivate lateinit var progressChannel: EventChannelprivate var progressEventSink: EventChannel.EventSink? = nullprivate lateinit var context: Context- private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())- private var currentJob: Job? = null+ private var scope = CoroutineScope(Dispatchers.IO + SupervisorJob())+ private var currentExportJob: Job? = null+ private val frameJobs = ConcurrentHashMap<String, Job>()+ private val frameSemaphore = Semaphore(2)// Unified Media3 Transformer processor for all operationsprivate lateinit var media3Processor: Media3TransformerProcessor@@ -32,6 +52,9 @@ class NativeVideoEditorPlugin : FlutterPlugin, MethodCallHandler, EventChannel.S}override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {+ if (!scope.isActive) {+ scope = CoroutineScope(Dispatchers.IO + SupervisorJob())+ }context = flutterPluginBinding.applicationContextchannel = MethodChannel(flutterPluginBinding.binaryMessenger, "native_video_editor")channel.setMethodCallHandler(this)@@ -44,159 +67,120 @@ class NativeVideoEditorPlugin : FlutterPlugin, MethodCallHandler, EventChannel.S}override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {+ val engineScope = scope+ if (!engineScope.isActive) returnwhen (call.method) {- "trimVideo" -> {- val inputPath = call.argument<String>("inputPath")!!- val outputPath = call.argument<String>("outputPath")!!- val startTimeMs = call.argument<Int>("startTimeMs")!!.toLong()- val endTimeMs = call.argument<Int>("endTimeMs")!!.toLong()+ "processVideo" -> {+ handleProcessVideo(call, result, engineScope)+ }- currentJob = scope.launch {+ "getVideoInfo" -> {+ val videoPath = call.argument<String>("videoPath")+ if (videoPath.isNullOrBlank()) {+ result.error("INVALID_ARGS", "Missing video path", null)+ return+ }+ engineScope.launch {try {- // Use unified Media3 Transformer for optimized trimming- val processingResult = media3Processor.trimVideo(- inputPath = inputPath,- outputPath = outputPath,- startTimeMs = startTimeMs,- endTimeMs = endTimeMs,- onProgress = { progress ->- scope.launch(Dispatchers.Main) {- progressEventSink?.success(progress)- }- }- )-+ val info = getVideoInfo(videoPath)withContext(Dispatchers.Main) {- result.success(- mapOf(- "outputPath" to processingResult.outputPath,- "isReEncoded" to processingResult.isReEncoded,- "processingTimeMs" to processingResult.processingTimeMs,- "method" to processingResult.method- )- )+ if (canReply(engineScope)) {+ result.success(info)+ }}} catch (e: LinkageError) {- reportProcessingError(result, "TRIM_LINKAGE_ERROR", "Trim", e)+ reportProcessingError(+ result,+ "INFO_LINKAGE_ERROR",+ "Get video info",+ e,+ engineScope+ )} catch (e: Exception) {- reportProcessingError(result, "TRIM_ERROR", "Trim", e)- } finally {- currentJob = null+ reportProcessingError(+ result,+ "INFO_ERROR",+ "Get video info",+ e,+ engineScope+ )}}}- "rotateVideo" -> {- val inputPath = call.argument<String>("inputPath")!!- val outputPath = call.argument<String>("outputPath")!!- val degrees = call.argument<Int>("degrees")!!-- currentJob = scope.launch {- try {- // Use unified Media3 Transformer for rotation with proper effects- val processingResult = media3Processor.rotateVideo(- inputPath = inputPath,- outputPath = outputPath,- degrees = degrees,- onProgress = { progress ->- scope.launch(Dispatchers.Main) {- progressEventSink?.success(progress)- }- }- )-- withContext(Dispatchers.Main) {- result.success(- mapOf(- "outputPath" to processingResult.outputPath,- "isReEncoded" to processingResult.isReEncoded,- "processingTimeMs" to processingResult.processingTimeMs,- "method" to processingResult.method- )- )- }- } catch (e: LinkageError) {- reportProcessingError(result, "ROTATE_LINKAGE_ERROR", "Rotation", e)- } catch (e: Exception) {- reportProcessingError(result, "ROTATE_ERROR", "Rotation", e)- } finally {- currentJob = null- }+ "extractFrame" -> {+ val outputPath = call.argument<String>("outputPath")+ val positionMs = call.argument<Number>("positionMs")+ if (outputPath.isNullOrBlank() || positionMs == null) {+ result.error("INVALID_ARGS", "Invalid frame arguments", null)+ return}+ handleExtractFrames(+ call = call,+ result = result,+ requestId = UUID.randomUUID().toString(),+ outputPaths = listOf(outputPath),+ positionsMs = listOf(positionMs.toLong()),+ engineScope = engineScope+ )}- "cropVideo" -> {- val inputPath = call.argument<String>("inputPath")!!- val outputPath = call.argument<String>("outputPath")!!- val x = call.argument<Int>("x")!!- val y = call.argument<Int>("y")!!- val width = call.argument<Int>("width")!!- val height = call.argument<Int>("height")!!-- currentJob = scope.launch {- try {- // Use unified Media3 Transformer for cropping with proper effects- val processingResult = media3Processor.cropVideo(- inputPath = inputPath,- outputPath = outputPath,- cropX = x,- cropY = y,- cropWidth = width,- cropHeight = height,- onProgress = { progress ->- scope.launch(Dispatchers.Main) {- progressEventSink?.success(progress)- }- }- )+ "extractTimeline" -> {+ val requestId = call.argument<String>("requestId")+ val outputPaths = call.argument<List<String>>("outputPaths")+ val positions = call.argument<List<Number>>("positionsMs")+ if (requestId.isNullOrBlank() || outputPaths == null || positions == null) {+ result.error("INVALID_ARGS", "Invalid timeline arguments", null)+ return+ }+ val positionsMs = positions.map(Number::toLong)+ handleExtractFrames(+ call,+ result,+ requestId,+ outputPaths,+ positionsMs,+ engineScope+ )+ }+ "cancelFrameExtraction" -> {+ val requestId = call.argument<String>("requestId")+ if (requestId.isNullOrBlank()) {+ result.error("INVALID_ARGS", "Missing frame request ID", null)+ return+ }+ val frameJob = frameJobs[requestId]+ if (frameJob == null) {+ result.success(null)+ } else {+ engineScope.launch {+ frameJob.cancelAndJoin()withContext(Dispatchers.Main) {- result.success(- mapOf(- "outputPath" to processingResult.outputPath,- "isReEncoded" to processingResult.isReEncoded,- "processingTimeMs" to processingResult.processingTimeMs,- "method" to processingResult.method- )- )+ if (canReply(engineScope)) {+ result.success(null)+ }}- } catch (e: LinkageError) {- reportProcessingError(result, "CROP_LINKAGE_ERROR", "Crop", e)- } catch (e: Exception) {- reportProcessingError(result, "CROP_ERROR", "Crop", e)- } finally {- currentJob = null}}}- "processVideo" -> {- handleProcessVideo(call, result)- }-- "getVideoInfo" -> {- val videoPath = call.argument<String>("videoPath")!!- currentJob = scope.launch {- try {- val info = getVideoInfo(videoPath)+ "cancelProcessing" -> {+ val exportJob = currentExportJob+ if (exportJob == null) {+ result.success(null)+ } else {+ engineScope.launch {+ exportJob.cancelAndJoin()withContext(Dispatchers.Main) {- result.success(info)+ if (canReply(engineScope)) {+ result.success(null)+ }}- } catch (e: LinkageError) {- reportProcessingError(result, "INFO_LINKAGE_ERROR", "Get video info", e)- } catch (e: Exception) {- reportProcessingError(result, "INFO_ERROR", "Get video info", e)- } finally {- currentJob = null}}}- "cancelProcessing" -> {- currentJob?.cancel()- result.success(null)- }-else -> result.notImplemented()}}@@ -205,7 +189,16 @@ class NativeVideoEditorPlugin : FlutterPlugin, MethodCallHandler, EventChannel.Sval retriever = MediaMetadataRetriever()return try {retriever.setDataSource(videoPath)+ getVideoInfo(retriever, videoPath)+ } finally {+ retriever.release()+ }+ }+ private fun getVideoInfo(+ retriever: MediaMetadataRetriever,+ videoPath: String+ ): Map<String, Any> {val duration = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)?.toLongOrNull() ?: run {@@ -236,44 +229,323 @@ class NativeVideoEditorPlugin : FlutterPlugin, MethodCallHandler, EventChannel.Sval bitrate = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_BITRATE- )?.toLongOrNull() ?: run {- Log.w(TAG, "Failed to extract bitrate metadata from video: $videoPath")- 0L- }+ )?.toLongOrNull()?.takeIf { it > 0 }val frameRate = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_CAPTURE_FRAMERATE- )?.toFloatOrNull() ?: run {- Log.w(TAG, "Failed to extract frame rate metadata from video: $videoPath")- 0f- }+ )?.toFloatOrNull()?.takeIf { it > 0 }} else {- 0f+ null+ }++ val normalizedRotation = ((rotation % 360) + 360) % 360+ val swapsDimensions = normalizedRotation == 90 || normalizedRotation == 270++ return buildMap {+ put("duration", duration)+ put("width", width)+ put("height", height)+ put("displayWidth", if (swapsDimensions) height else width)+ put("displayHeight", if (swapsDimensions) width else height)+ put("rotation", normalizedRotation)+ bitrate?.let { put("bitrate", it) }+ frameRate?.let { put("frameRate", it) }}+ }++ private fun handleExtractFrames(+ call: MethodCall,+ result: Result,+ requestId: String,+ outputPaths: List<String>,+ positionsMs: List<Long>,+ engineScope: CoroutineScope+ ) {+ val inputPath = call.argument<String>("inputPath")+ val maxWidth = call.argument<Int>("maxWidth")+ val maxHeight = call.argument<Int>("maxHeight")+ val quality = call.argument<Int>("quality")+ val policy = call.argument<String>("policy")+ val validPaths = try {+ val inputFile = inputPath?.let(::File)?.canonicalFile+ val outputs = outputPaths.map { File(it).canonicalFile }+ inputFile != null &&+ inputFile.isFile &&+ outputs.none { it == inputFile } &&+ outputs.distinct().size == outputs.size+ } catch (_: Exception) {+ false+ }+ if (inputPath.isNullOrBlank() ||+ maxWidth == null || maxWidth <= 0 ||+ maxHeight == null || maxHeight <= 0 ||+ quality == null || quality !in 1..100 ||+ policy !in setOf("precise", "nearestSync") ||+ positionsMs.isEmpty() ||+ positionsMs.size != outputPaths.size ||+ positionsMs.any { it < 0 } ||+ outputPaths.any(String::isBlank) ||+ !validPaths+ ) {+ result.error("INVALID_ARGS", "Invalid frame extraction arguments", null)+ return+ }+ val precise = policy == "precise"+ val resultCompleted = AtomicBoolean(false)- mapOf(- "duration" to duration,- "width" to width,- "height" to height,- "rotation" to rotation,- "bitrate" to bitrate,- "frameRate" to frameRate+ val job = engineScope.launch(start = CoroutineStart.LAZY) {+ val writtenFiles = mutableListOf<File>()+ try {+ val payload = frameSemaphore.withPermit {+ val retriever = MediaMetadataRetriever()+ var fallbackExtractor: FrameExtractor? = null+ try {+ retriever.setDataSource(inputPath)+ val videoInfo = getVideoInfo(retriever, inputPath)+ val durationMs = (videoInfo["duration"] as Long).coerceAtLeast(0L)+ val displayWidth = videoInfo["displayWidth"] as Int+ val displayHeight = videoInfo["displayHeight"] as Int+ val targetSize = boundedSize(+ displayWidth,+ displayHeight,+ maxWidth,+ maxHeight+ )+ val option = if (precise) {+ MediaMetadataRetriever.OPTION_CLOSEST+ } else {+ MediaMetadataRetriever.OPTION_CLOSEST_SYNC+ }+ val frames = ArrayList<Map<String, Any>>(positionsMs.size)++ positionsMs.forEachIndexed { index, requestedPositionMs ->+ ensureActive()+ val positionMs = clampFramePosition(requestedPositionMs, durationMs)+ val frame = try {+ extractScaledFrame(+ retriever,+ positionMs * 1_000,+ option,+ targetSize.first,+ targetSize.second+ )+ } catch (error: RuntimeException) {+ Log.w(TAG, "Platform frame decoder failed at ${positionMs}ms", error)+ null+ } ?: run {+ Log.w(+ TAG,+ "Platform decoder returned no frame at ${positionMs}ms; using Media3"+ )+ val extractor = fallbackExtractor ?: createFallbackFrameExtractor(+ inputPath,+ targetSize.second,+ precise+ ).also { fallbackExtractor = it }+ extractFallbackFrame(extractor, positionMs)+ }+ ensureActive()++ val outputFile = File(outputPaths[index])+ outputFile.parentFile?.mkdirs()+ try {+ try {+ FileOutputStream(outputFile, false).use { stream ->+ if (!frame.compress(Bitmap.CompressFormat.JPEG, quality, stream)) {+ throw IllegalStateException("JPEG encoder rejected the frame")+ }+ }+ } catch (error: Exception) {+ outputFile.delete()+ throw error+ }+ writtenFiles.add(outputFile)+ frames.add(+ mapOf(+ "outputPath" to outputFile.path,+ "width" to frame.width,+ "height" to frame.height+ )+ )+ } finally {+ frame.recycle()+ }+ }++ mapOf<String, Any>("videoInfo" to videoInfo, "frames" to frames)+ } finally {+ retriever.release()+ fallbackExtractor?.let { extractor ->+ withContext(NonCancellable + Dispatchers.Main) {+ extractor.close()+ }+ }+ }+ }+ withContext(Dispatchers.Main) {+ if (resultCompleted.compareAndSet(false, true) && canReply(engineScope)) {+ result.success(payload)+ }+ }+ } catch (e: CancellationException) {+ withContext(NonCancellable + Dispatchers.Main) {+ if (resultCompleted.compareAndSet(false, true)) {+ writtenFiles.forEach(File::delete)+ if (canReply(engineScope)) {+ result.error("FRAME_CANCELLED", "Frame extraction was cancelled", requestId)+ }+ }+ }+ } catch (e: Exception) {+ if (resultCompleted.compareAndSet(false, true)) {+ writtenFiles.forEach(File::delete)+ reportProcessingError(+ result,+ "FRAME_EXTRACTION_ERROR",+ "Frame extraction",+ e,+ engineScope+ )+ }+ } finally {+ frameJobs.remove(requestId, coroutineContext.job)+ }+ }+ if (frameJobs.putIfAbsent(requestId, job) != null) {+ job.cancel()+ if (resultCompleted.compareAndSet(false, true)) {+ result.error("DUPLICATE_REQUEST", "Frame request ID is already active", requestId)+ }+ return+ }+ job.start()+ }++ private fun clampFramePosition(positionMs: Long, durationMs: Long): Long {+ if (durationMs <= 0) return max(0L, positionMs)+ return positionMs.coerceIn(0L, max(0L, durationMs - 1L))+ }++ private fun boundedSize(+ width: Int,+ height: Int,+ maxWidth: Int,+ maxHeight: Int+ ): Pair<Int, Int> {+ require(width > 0 && height > 0) { "Video dimensions are unavailable" }+ val scale = minOf(+ 1.0,+ maxWidth.toDouble() / width,+ maxHeight.toDouble() / height+ )+ return Pair(+ max(1, (width * scale).roundToInt()),+ max(1, (height * scale).roundToInt())+ )+ }++ private fun extractScaledFrame(+ retriever: MediaMetadataRetriever,+ positionUs: Long,+ option: Int,+ targetWidth: Int,+ targetHeight: Int+ ): Bitmap? {+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {+ return retriever.getScaledFrameAtTime(+ positionUs,+ option,+ targetWidth,+ targetHeight)- } finally {- retriever.release()}++ val source = retriever.getFrameAtTime(positionUs, option) ?: return null+ if (source.width <= targetWidth && source.height <= targetHeight) {+ return source+ }+ val scale = minOf(+ 1.0,+ targetWidth.toDouble() / source.width,+ targetHeight.toDouble() / source.height+ )+ val scaled = Bitmap.createScaledBitmap(+ source,+ max(1, (source.width * scale).roundToInt()),+ max(1, (source.height * scale).roundToInt()),+ true+ )+ if (scaled !== source) source.recycle()+ return scaled}- private fun handleProcessVideo(call: MethodCall, result: Result) {- val inputPath = call.argument<String>("inputPath")!!- val outputPath = call.argument<String>("outputPath")!!+ private suspend fun createFallbackFrameExtractor(+ inputPath: String,+ targetHeight: Int,+ precise: Boolean+ ): FrameExtractor = withContext(Dispatchers.Main) {+ FrameExtractor.Builder(+ context,+ MediaItem.fromUri(Uri.fromFile(File(inputPath)))+ )+ .setEffects(listOf(Presentation.createForHeight(targetHeight)))+ .setSeekParameters(+ if (precise) SeekParameters.EXACT else SeekParameters.CLOSEST_SYNC+ )+ .build()+ }++ private suspend fun extractFallbackFrame(+ extractor: FrameExtractor,+ positionMs: Long+ ): Bitmap {+ val future = withContext(Dispatchers.Main) {+ extractor.getFrame(positionMs)+ }+ val frame = future.awaitResult()+ return frame.bitmap+ }++ private suspend fun <T> ListenableFuture<T>.awaitResult(): T =+ suspendCancellableCoroutine { continuation ->+ continuation.invokeOnCancellation { cancel(true) }+ addListener(+ {+ try {+ continuation.resumeWith(kotlin.Result.success(get()))+ } catch (error: ExecutionException) {+ continuation.resumeWith(+ kotlin.Result.failure(error.cause ?: error)+ )+ } catch (error: Exception) {+ continuation.resumeWith(kotlin.Result.failure(error))+ }+ },+ MoreExecutors.directExecutor()+ )+ }++ private fun handleProcessVideo(+ call: MethodCall,+ result: Result,+ engineScope: CoroutineScope+ ) {+ val inputPath = call.argument<String>("inputPath")+ val outputPath = call.argument<String>("outputPath")+ if (inputPath.isNullOrBlank() ||+ outputPath.isNullOrBlank() ||+ currentExportJob?.isActive == true+ ) {+ result.error("INVALID_ARGS", "Invalid or concurrent export request", null)+ return+ }- currentJob = scope.launch {+ val job = engineScope.launch(start = CoroutineStart.LAZY) {try {// Collect all transformation parameters- val trimStartMs = call.argument<Int>("trimStartMs")?.toLong()- val trimEndMs = call.argument<Int>("trimEndMs")?.toLong()+ val trimStartMs = call.argument<Number>("trimStartMs")?.toLong()+ val trimEndMs = call.argument<Number>("trimEndMs")?.toLong()val rotateDegrees = call.argument<Int>("rotateDegrees")val cropX = call.argument<Int>("cropX")val cropY = call.argument<Int>("cropY")@@ -281,7 +553,7 @@ class NativeVideoEditorPlugin : FlutterPlugin, MethodCallHandler, EventChannel.Sval cropHeight = call.argument<Int>("cropHeight")// Process all transformations in a single pass with Media3 Transformer- val processingResult = media3Processor.processVideo(+ val isReEncoded = media3Processor.processVideo(inputPath = inputPath,outputPath = outputPath,trimStartMs = trimStartMs,@@ -292,61 +564,92 @@ class NativeVideoEditorPlugin : FlutterPlugin, MethodCallHandler, EventChannel.ScropWidth = cropWidth,cropHeight = cropHeight,onProgress = { progress ->- scope.launch(Dispatchers.Main) {- progressEventSink?.success(progress)+ engineScope.launch(Dispatchers.Main) {+ if (canReply(engineScope)) {+ progressEventSink?.success(progress)+ }}})- val processingSteps = mutableListOf<String>()- if (trimStartMs != null) processingSteps.add("Trim")- if (rotateDegrees != null && rotateDegrees != 0) processingSteps.add("Rotate")- if (cropX != null) processingSteps.add("Crop")-withContext(Dispatchers.Main) {- result.success(- mapOf(- "outputPath" to outputPath,- "isReEncoded" to processingResult.isReEncoded,- "processingTimeMs" to processingResult.processingTimeMs,- "processingSteps" to processingSteps+ if (canReply(engineScope)) {+ result.success(+ mapOf(+ "outputPath" to outputPath,+ "isReEncoded" to isReEncoded+ ))- )+ }}} catch (e: LinkageError) {- reportProcessingError(result, "PROCESS_LINKAGE_ERROR", "Process video", e)+ reportProcessingError(+ result,+ "PROCESS_LINKAGE_ERROR",+ "Process video",+ e,+ engineScope+ )+ } catch (e: CancellationException) {+ reportProcessingError(+ result,+ "PROCESS_CANCELLED",+ "Process video",+ e,+ engineScope+ )} catch (e: Exception) {- reportProcessingError(result, "PROCESS_ERROR", "Process video", e)+ reportProcessingError(+ result,+ "PROCESS_ERROR",+ "Process video",+ e,+ engineScope+ )} finally {- currentJob = null+ if (currentExportJob == coroutineContext.job) {+ currentExportJob = null+ }}}+ currentExportJob = job+ job.start()}private suspend fun reportProcessingError(result: Result,code: String,operation: String,- throwable: Throwable+ throwable: Throwable,+ engineScope: CoroutineScope) {Log.e(TAG, "$operation failed", throwable)- withContext(Dispatchers.Main) {- result.error(- code,- throwable.message ?: throwable::class.java.simpleName,- buildErrorDetails(throwable)- )+ withContext(NonCancellable + Dispatchers.Main) {+ if (canReply(engineScope)) {+ result.error(+ code,+ throwable.message ?: throwable::class.java.simpleName,+ buildErrorDetails(throwable)+ )+ }}}+ private fun canReply(engineScope: CoroutineScope): Boolean = engineScope.isActive+override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {+ progressEventSink = nullchannel.setMethodCallHandler(null)progressChannel.setStreamHandler(null)scope.cancel()+ currentExportJob = null+ frameJobs.clear()}override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {- progressEventSink = events+ if (scope.isActive) {+ progressEventSink = events+ }}override fun onCancel(arguments: Any?) {diff --git a/mobile/packages/native_video_editor/ios/Classes/NativeVideoEditorPlugin.swift b/mobile/packages/native_video_editor/ios/Classes/NativeVideoEditorPlugin.swiftindex 7d4e6f5dff..69fe0b8116 100644--- a/mobile/packages/native_video_editor/ios/Classes/NativeVideoEditorPlugin.swift+++ b/mobile/packages/native_video_editor/ios/Classes/NativeVideoEditorPlugin.swift@@ -1,17 +1,27 @@import Flutter-import UIKitimport AVFoundation-import Photos+import ImageIOpublic class NativeVideoEditorPlugin: NSObject, FlutterPlugin {+ private var isDetached = falseprivate var currentExportSession: AVAssetExportSession?+ private var exportCancellationResult: FlutterResult?private var progressEventSink: FlutterEventSink?private var progressTimer: Timer?+ private var frameGenerators: [String: AVAssetImageGenerator] = [:]+ private var frameOutputPaths: [String: [String]] = [:]+ private var cancelledFrameRequests = Set<String>()+ private var frameCancellationResults: [String: FlutterResult] = [:]+ private let frameStartQueue = DispatchQueue(+ label: "io.ente.native-video-editor.frames"+ )+ private let frameSemaphore = DispatchSemaphore(value: 2)public static func register(with registrar: FlutterPluginRegistrar) {let channel = FlutterMethodChannel(name: "native_video_editor", binaryMessenger: registrar.messenger())let instance = NativeVideoEditorPlugin()registrar.addMethodCallDelegate(instance, channel: channel)+ registrar.publish(instance)let progressChannel = FlutterEventChannel(name: "native_video_editor/progress", binaryMessenger: registrar.messenger())progressChannel.setStreamHandler(instance)@@ -19,46 +29,6 @@ public class NativeVideoEditorPlugin: NSObject, FlutterPlugin {public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {switch call.method {- case "trimVideo":- guard let args = call.arguments as? [String: Any],- let inputPath = args["inputPath"] as? String,- let outputPath = args["outputPath"] as? String,- let startTimeMs = args["startTimeMs"] as? Int,- let endTimeMs = args["endTimeMs"] as? Int else {- result(flutterError("INVALID_ARGS", message: "Invalid arguments"))- return- }-- trimVideo(inputPath: inputPath, outputPath: outputPath,- startTimeMs: startTimeMs, endTimeMs: endTimeMs, result: result)-- case "rotateVideo":- guard let args = call.arguments as? [String: Any],- let inputPath = args["inputPath"] as? String,- let outputPath = args["outputPath"] as? String,- let degrees = args["degrees"] as? Int else {- result(flutterError("INVALID_ARGS", message: "Invalid arguments"))- return- }-- rotateVideo(inputPath: inputPath, outputPath: outputPath,- degrees: degrees, result: result)-- case "cropVideo":- guard let args = call.arguments as? [String: Any],- let inputPath = args["inputPath"] as? String,- let outputPath = args["outputPath"] as? String,- let x = args["x"] as? Int,- let y = args["y"] as? Int,- let width = args["width"] as? Int,- let height = args["height"] as? Int else {- result(flutterError("INVALID_ARGS", message: "Invalid arguments"))- return- }-- cropVideo(inputPath: inputPath, outputPath: outputPath,- x: x, y: y, width: width, height: height, result: result)-case "processVideo":handleProcessVideo(call: call, result: result)@@ -71,480 +41,380 @@ public class NativeVideoEditorPlugin: NSObject, FlutterPlugin {getVideoInfo(videoPath: videoPath, result: result)- case "cancelProcessing":- currentExportSession?.cancelExport()- result(nil)-- default:- result(FlutterMethodNotImplemented)- }- }-- private func trimVideo(inputPath: String, outputPath: String,- startTimeMs: Int, endTimeMs: Int, result: @escaping FlutterResult) {- let asset = AVAsset(url: URL(fileURLWithPath: inputPath))-- let startTime = CMTime(value: CMTimeValue(startTimeMs), timescale: 1000)- let endTime = CMTime(value: CMTimeValue(endTimeMs), timescale: 1000)- let timeRange = CMTimeRange(start: startTime, end: endTime)-- // Check if video has metadata rotation- if let videoTrack = asset.tracks(withMediaType: .video).first {- let preferredTransform = videoTrack.preferredTransform- // Check if the transform is not identity (has rotation/orientation)- if !preferredTransform.isIdentity {-- // Create composition to apply the preferred transform- let composition = AVMutableComposition()- guard let compositionVideoTrack = composition.addMutableTrack(- withMediaType: .video,- preferredTrackID: kCMPersistentTrackID_Invalid) else {- result(flutterError("COMPOSITION_ERROR", message: "Failed to create composition track"))- return- }-- var compositionAudioTrack: AVMutableCompositionTrack?- if let audioTrack = asset.tracks(withMediaType: .audio).first {- compositionAudioTrack = composition.addMutableTrack(- withMediaType: .audio,- preferredTrackID: kCMPersistentTrackID_Invalid)- }-- do {- try compositionVideoTrack.insertTimeRange(timeRange, of: videoTrack, at: .zero)-- if let audioTrack = asset.tracks(withMediaType: .audio).first,- let compAudioTrack = compositionAudioTrack {- try compAudioTrack.insertTimeRange(timeRange, of: audioTrack, at: .zero)- }- } catch {- result(flutterError("INSERT_ERROR", message: "Failed to insert track", error: error))- return- }-- // Create video composition with the preferred transform- let videoComp = AVMutableVideoComposition()- videoComp.frameDuration = frameDuration(for: videoTrack)-- let naturalSize = videoTrack.naturalSize- let naturalBounds = CGRect(origin: .zero, size: naturalSize)- let preferredBounds = naturalBounds.applying(preferredTransform)- let orientationAdjustment = CGAffineTransform(- translationX: -preferredBounds.minX,- y: -preferredBounds.minY- )-- let orientationTransform = preferredTransform.concatenating(orientationAdjustment)- let renderSize = CGSize(width: abs(preferredBounds.width), height: abs(preferredBounds.height))-- videoComp.renderSize = renderSize-- let instruction = AVMutableVideoCompositionInstruction()- instruction.timeRange = CMTimeRange(start: .zero, duration: composition.duration)-- let layerInstruction = AVMutableVideoCompositionLayerInstruction(assetTrack: compositionVideoTrack)- layerInstruction.setTransform(orientationTransform, at: .zero)+ case "extractFrame":+ guard let args = call.arguments as? [String: Any],+ let outputPath = args["outputPath"] as? String,+ let position = args["positionMs"] as? NSNumber else {+ result(flutterError("INVALID_ARGS", message: "Invalid frame arguments"))+ return+ }+ extractFrames(+ args: args,+ requestID: UUID().uuidString,+ outputPaths: [outputPath],+ positionsMs: [position.int64Value],+ result: result+ )- instruction.layerInstructions = [layerInstruction]- videoComp.instructions = [instruction]+ case "extractTimeline":+ guard let args = call.arguments as? [String: Any],+ let requestID = args["requestId"] as? String,+ let outputPaths = args["outputPaths"] as? [String],+ let positions = args["positionsMs"] as? [NSNumber] else {+ result(flutterError("INVALID_ARGS", message: "Invalid timeline arguments"))+ return+ }+ extractFrames(+ args: args,+ requestID: requestID,+ outputPaths: outputPaths,+ positionsMs: positions.map(\.int64Value),+ result: result+ )- // Use composition for export- let presetName = AVAssetExportPresetHighestQuality- guard let exportSession = AVAssetExportSession(asset: composition, presetName: presetName) else {- result(flutterError("EXPORT_ERROR", message: "Failed to create export session"))+ case "cancelFrameExtraction":+ guard let args = call.arguments as? [String: Any],+ let requestID = args["requestId"] as? String else {+ result(flutterError("INVALID_ARGS", message: "Missing frame request ID"))+ return+ }+ if let generator = frameGenerators[requestID] {+ cancelledFrameRequests.insert(requestID)+ if frameCancellationResults[requestID] != nil {+ result(nil)return}+ frameCancellationResults[requestID] = result+ generator.cancelAllCGImageGeneration()+ } else {+ result(nil)+ }- currentExportSession = exportSession- exportSession.videoComposition = videoComp- exportSession.outputURL = URL(fileURLWithPath: outputPath)- exportSession.outputFileType = .mp4- exportSession.shouldOptimizeForNetworkUse = true-- startProgressReporting()- exportSession.exportAsynchronously {- DispatchQueue.main.async {- self.stopProgressReporting()- switch exportSession.status {- case .completed:- result([- "outputPath": outputPath,- "isReEncoded": true- ])- case .failed:- result(self.flutterError("TRIM_ERROR", message: "Failed to trim video", error: exportSession.error))- case .cancelled:- result(self.flutterError("CANCELLED", message: "Export cancelled"))- default:- result(self.flutterError("UNKNOWN", message: "Unknown export status", error: exportSession.error))- }- self.currentExportSession = nil- }- }+ case "cancelProcessing":+ guard let exportSession = currentExportSession else {+ result(nil)return}- }-- // Use passthrough if no rotation needed- guard let exportSession = AVAssetExportSession(asset: asset,- presetName: AVAssetExportPresetPassthrough) else {- result(flutterError("EXPORT_ERROR", message: "Failed to create export session"))- return- }-- currentExportSession = exportSession-- exportSession.timeRange = timeRange- exportSession.outputURL = URL(fileURLWithPath: outputPath)- exportSession.outputFileType = .mp4- exportSession.shouldOptimizeForNetworkUse = true-- startProgressReporting()- exportSession.exportAsynchronously {- DispatchQueue.main.async {- self.stopProgressReporting()- switch exportSession.status {- case .completed:- result([- "outputPath": outputPath,- "isReEncoded": false- ])- case .failed:- result(self.flutterError("TRIM_ERROR", message: "Failed to trim video", error: exportSession.error))- case .cancelled:- result(self.flutterError("CANCELLED", message: "Export cancelled"))- default:- result(self.flutterError("UNKNOWN", message: "Unknown export status", error: exportSession.error))- }- self.currentExportSession = nil+ guard exportCancellationResult == nil else {+ result(nil)+ return}+ exportCancellationResult = result+ exportSession.cancelExport()++ default:+ result(FlutterMethodNotImplemented)}}- private func rotateVideo(inputPath: String, outputPath: String,- degrees: Int, result: @escaping FlutterResult) {- let asset = AVAsset(url: URL(fileURLWithPath: inputPath))-- guard let videoTrack = asset.tracks(withMediaType: .video).first else {- result(flutterError("NO_VIDEO", message: "No video track found"))+ private func extractFrames(+ args: [String: Any],+ requestID: String,+ outputPaths: [String],+ positionsMs: [Int64],+ result: @escaping FlutterResult+ ) {+ guard frameGenerators[requestID] == nil else {+ result(flutterError("DUPLICATE_REQUEST", message: "Frame request ID is already active"))return}-- let composition = AVMutableComposition()- guard let compositionVideoTrack = composition.addMutableTrack(- withMediaType: .video,- preferredTrackID: kCMPersistentTrackID_Invalid) else {- result(flutterError("COMPOSITION_ERROR", message: "Failed to create composition track"))+ guard let inputPath = args["inputPath"] as? String,+ let maxWidth = args["maxWidth"] as? NSNumber,+ let maxHeight = args["maxHeight"] as? NSNumber,+ let quality = args["quality"] as? NSNumber,+ let policy = args["policy"] as? String,+ !positionsMs.isEmpty,+ positionsMs.count == outputPaths.count,+ maxWidth.intValue > 0,+ maxHeight.intValue > 0,+ (1...100).contains(quality.intValue),+ policy == "precise" || policy == "nearestSync" else {+ result(flutterError("INVALID_ARGS", message: "Invalid frame extraction arguments"))return}-- var compositionAudioTrack: AVMutableCompositionTrack?- if let audioTrack = asset.tracks(withMediaType: .audio).first {- compositionAudioTrack = composition.addMutableTrack(- withMediaType: .audio,- preferredTrackID: kCMPersistentTrackID_Invalid)- }-- do {- try compositionVideoTrack.insertTimeRange(- CMTimeRange(start: .zero, duration: asset.duration),- of: videoTrack,- at: .zero)-- if let audioTrack = asset.tracks(withMediaType: .audio).first,- let compAudioTrack = compositionAudioTrack {- try compAudioTrack.insertTimeRange(- CMTimeRange(start: .zero, duration: asset.duration),- of: audioTrack,- at: .zero)- }- } catch {- result(flutterError("INSERT_ERROR", message: "Failed to insert track", error: error))+ let inputURL = URL(fileURLWithPath: inputPath)+ .standardizedFileURL.resolvingSymlinksInPath()+ let outputURLs = outputPaths.map {+ URL(fileURLWithPath: $0).standardizedFileURL.resolvingSymlinksInPath()+ }+ guard FileManager.default.fileExists(atPath: inputURL.path),+ positionsMs.allSatisfy({ $0 >= 0 }),+ outputPaths.allSatisfy({ !$0.isEmpty }),+ !outputURLs.contains(inputURL),+ Set(outputURLs.map(\.path)).count == outputURLs.count else {+ result(flutterError("INVALID_ARGS", message: "Invalid frame paths or timestamps"))return}- let videoComposition = AVMutableVideoComposition()- videoComposition.frameDuration = frameDuration(for: videoTrack)-- let naturalSize = videoTrack.naturalSize- let preferredTransform = videoTrack.preferredTransform-- // Apply orientation adjustment to handle existing metadata rotation properly- let naturalBounds = CGRect(origin: .zero, size: naturalSize)- let preferredBounds = naturalBounds.applying(preferredTransform)- let orientationAdjustment = CGAffineTransform(- translationX: -preferredBounds.minX,- y: -preferredBounds.minY+ let asset = AVURLAsset(url: inputURL)+ let generator = AVAssetImageGenerator(asset: asset)+ generator.appliesPreferredTrackTransform = true+ generator.maximumSize = CGSize(+ width: maxWidth.doubleValue,+ height: maxHeight.doubleValue)- let orientationTransform = preferredTransform.concatenating(orientationAdjustment)-- // Calculate oriented size for render calculations- var orientedSize = CGSize(width: abs(preferredBounds.width), height: abs(preferredBounds.height))-- var transform = orientationTransform-- // iOS CGAffineTransform rotates counter-clockwise for positive angles- // To match Android behavior (positive = clockwise), we negate the radians- let radians = CGFloat(degrees) * .pi / 180- let clockwiseRadians = -radians-- // Rotate around the center of the oriented video- let centerX = orientedSize.width / 2- let centerY = orientedSize.height / 2-- transform = transform.translatedBy(x: centerX, y: centerY)- transform = transform.rotated(by: clockwiseRadians)- transform = transform.translatedBy(x: -centerX, y: -centerY)-- // Calculate renderSize from actual transformed bounds (more accurate for metadata-rotated videos)- // Use naturalSize here because transform expects input in natural/file coordinate space- let testRect = CGRect(origin: .zero, size: naturalSize)- let transformedBounds = testRect.applying(transform)-- // Get the actual dimensions after the full transform chain- let finalWidth = abs(transformedBounds.width)- let finalHeight = abs(transformedBounds.height)- let renderSize = CGSize(width: finalWidth, height: finalHeight)-- // Center the video in the renderSize- let targetMinX: CGFloat = (renderSize.width - transformedBounds.width) / 2- let additionalTranslateX = targetMinX - transformedBounds.minX-- let targetMinY: CGFloat = (renderSize.height - transformedBounds.height) / 2- let additionalTranslateY = targetMinY - transformedBounds.minY-- transform = transform.concatenating(CGAffineTransform(translationX: additionalTranslateX, y: additionalTranslateY))-- videoComposition.renderSize = renderSize-- let instruction = AVMutableVideoCompositionInstruction()- instruction.timeRange = CMTimeRange(start: .zero, duration: composition.duration)-- let layerInstruction = AVMutableVideoCompositionLayerInstruction(assetTrack: compositionVideoTrack)- layerInstruction.setTransform(transform, at: .zero)-- instruction.layerInstructions = [layerInstruction]- videoComposition.instructions = [instruction]-- guard let exportSession = AVAssetExportSession(- asset: composition,- presetName: AVAssetExportPresetHighestQuality) else {- result(flutterError("EXPORT_ERROR", message: "Failed to create export session"))- return+ if policy == "precise" {+ generator.requestedTimeToleranceBefore = .zero+ generator.requestedTimeToleranceAfter = .zero+ } else {+ let tolerance = CMTime(value: 300, timescale: 600)+ generator.requestedTimeToleranceBefore = tolerance+ generator.requestedTimeToleranceAfter = tolerance}- currentExportSession = exportSession-- exportSession.videoComposition = videoComposition- exportSession.outputURL = URL(fileURLWithPath: outputPath)- exportSession.outputFileType = .mp4- exportSession.shouldOptimizeForNetworkUse = true-- startProgressReporting()- exportSession.exportAsynchronously {+ cancelledFrameRequests.remove(requestID)+ frameGenerators[requestID] = generator+ frameOutputPaths[requestID] = outputPaths+ frameStartQueue.async { [weak self] in+ guard let self = self else { return }+ self.frameSemaphore.wait()DispatchQueue.main.async {- self.stopProgressReporting()- switch exportSession.status {- case .completed:- result([- "outputPath": outputPath,- "isReEncoded": true- ])- case .failed:- result(self.flutterError("ROTATE_ERROR", message: "Failed to rotate video", error: exportSession.error))- case .cancelled:- result(self.flutterError("CANCELLED", message: "Export cancelled"))- default:- result(self.flutterError("UNKNOWN", message: "Unknown export status", error: exportSession.error))+ if self.cancelledFrameRequests.contains(requestID) {+ self.finishFrameRequest(+ requestID: requestID,+ generator: generator,+ result: result,+ value: self.flutterError("FRAME_CANCELLED", message: "Frame extraction was cancelled")+ )+ return+ }+ self.loadVideoInfo(asset: asset) { [weak self] loadedInfo in+ guard let self = self else { return }+ DispatchQueue.main.async {+ switch loadedInfo {+ case .success(let info):+ let durationMs = info["duration"] as? Int64 ?? 0+ self.generateFrame(+ generator: generator,+ requestID: requestID,+ outputPaths: outputPaths,+ positionsMs: positionsMs,+ durationMs: durationMs,+ quality: quality.doubleValue / 100.0,+ index: 0,+ frames: [],+ videoInfo: info,+ result: result+ )+ case .failure(let error):+ self.finishFrameRequest(+ requestID: requestID,+ generator: generator,+ result: result,+ value: self.flutterError("FRAME_EXTRACTION_ERROR", message: "Failed to inspect video", error: error)+ )+ }+ }}- self.currentExportSession = nil}}}- private func cropVideo(inputPath: String, outputPath: String,- x: Int, y: Int, width: Int, height: Int, result: @escaping FlutterResult) {- let asset = AVAsset(url: URL(fileURLWithPath: inputPath))-- guard let videoTrack = asset.tracks(withMediaType: .video).first else {- result(flutterError("NO_VIDEO", message: "No video track found"))- return- }-- let preferredTransform = videoTrack.preferredTransform- let naturalSize = videoTrack.naturalSize-- let cropRectDisplay = CGRect(- x: CGFloat(x),- y: CGFloat(y),- width: CGFloat(width),- height: CGFloat(height)- )-- let composition = AVMutableComposition()- guard let compositionVideoTrack = composition.addMutableTrack(- withMediaType: .video,- preferredTrackID: kCMPersistentTrackID_Invalid) else {- result(flutterError("COMPOSITION_ERROR", message: "Failed to create composition track"))+ private func generateFrame(+ generator: AVAssetImageGenerator,+ requestID: String,+ outputPaths: [String],+ positionsMs: [Int64],+ durationMs: Int64,+ quality: Double,+ index: Int,+ frames: [[String: Any]],+ videoInfo: [String: Any],+ result: @escaping FlutterResult+ ) {+ if cancelledFrameRequests.contains(requestID) {+ removeFiles(at: outputPaths.prefix(index))+ finishFrameRequest(+ requestID: requestID,+ generator: generator,+ result: result,+ value: flutterError("FRAME_CANCELLED", message: "Frame extraction was cancelled")+ )return}- var compositionAudioTrack: AVMutableCompositionTrack?- if let audioTrack = asset.tracks(withMediaType: .audio).first {- compositionAudioTrack = composition.addMutableTrack(- withMediaType: .audio,- preferredTrackID: kCMPersistentTrackID_Invalid)- }-- do {- try compositionVideoTrack.insertTimeRange(- CMTimeRange(start: .zero, duration: asset.duration),- of: videoTrack,- at: .zero)+ let upperBound = max(Int64(0), durationMs - 1)+ let positionMs = durationMs > 0+ ? min(max(Int64(0), positionsMs[index]), upperBound)+ : max(Int64(0), positionsMs[index])+ let requestedTime = CMTime(value: positionMs, timescale: 1000)++ generator.generateCGImagesAsynchronously(forTimes: [NSValue(time: requestedTime)]) {+ [weak self] _, image, _, generationResult, error in+ guard let self = self else { return }+ guard generationResult == .succeeded, let image = image else {+ DispatchQueue.main.async {+ self.removeFiles(at: outputPaths.prefix(index))+ let code = generationResult == .cancelled+ ? "FRAME_CANCELLED"+ : "FRAME_EXTRACTION_ERROR"+ self.finishFrameRequest(+ requestID: requestID,+ generator: generator,+ result: result,+ value: self.flutterError(code, message: "Failed to decode video frame", error: error)+ )+ }+ return+ }- if let audioTrack = asset.tracks(withMediaType: .audio).first,- let compAudioTrack = compositionAudioTrack {- try compAudioTrack.insertTimeRange(- CMTimeRange(start: .zero, duration: asset.duration),- of: audioTrack,- at: .zero)+ do {+ try self.writeJPEG(image, to: outputPaths[index], quality: quality)+ DispatchQueue.main.async {+ if self.cancelledFrameRequests.contains(requestID) {+ self.removeFiles(at: outputPaths.prefix(index + 1))+ self.finishFrameRequest(+ requestID: requestID,+ generator: generator,+ result: result,+ value: self.flutterError(+ "FRAME_CANCELLED",+ message: "Frame extraction was cancelled"+ )+ )+ return+ }+ var nextFrames = frames+ nextFrames.append([+ "outputPath": outputPaths[index],+ "width": image.width,+ "height": image.height,+ ])+ let nextIndex = index + 1+ if nextIndex == positionsMs.count {+ self.finishFrameRequest(+ requestID: requestID,+ generator: generator,+ result: result,+ value: ["videoInfo": videoInfo, "frames": nextFrames]+ )+ } else {+ self.generateFrame(+ generator: generator,+ requestID: requestID,+ outputPaths: outputPaths,+ positionsMs: positionsMs,+ durationMs: durationMs,+ quality: quality,+ index: nextIndex,+ frames: nextFrames,+ videoInfo: videoInfo,+ result: result+ )+ }+ }+ } catch {+ DispatchQueue.main.async {+ self.removeFiles(at: outputPaths.prefix(index + 1))+ self.finishFrameRequest(+ requestID: requestID,+ generator: generator,+ result: result,+ value: self.flutterError("FRAME_WRITE_ERROR", message: "Failed to write video frame", error: error)+ )+ }}- } catch {- result(flutterError("INSERT_ERROR", message: "Failed to insert track", error: error))- return}+ }- // Create video composition for cropping- let videoComposition = AVMutableVideoComposition()- videoComposition.frameDuration = frameDuration(for: videoTrack)-- // Create layer instruction with crop transform- let instruction = AVMutableVideoCompositionInstruction()- instruction.timeRange = CMTimeRange(start: .zero, duration: composition.duration)-- let layerInstruction = AVMutableVideoCompositionLayerInstruction(assetTrack: compositionVideoTrack)-- let naturalBounds = CGRect(origin: .zero, size: naturalSize)- let preferredBounds = naturalBounds.applying(preferredTransform)- let orientationAdjustment = CGAffineTransform(- translationX: -preferredBounds.minX,- y: -preferredBounds.minY+ private func writeJPEG(_ image: CGImage, to path: String, quality: Double) throws {+ let url = URL(fileURLWithPath: path)+ try FileManager.default.createDirectory(+ at: url.deletingLastPathComponent(),+ withIntermediateDirectories: true)-- let orientationTransform = preferredTransform.concatenating(orientationAdjustment)-- guard orientationTransform.isNearlyInvertible else {- result(flutterError("CROP_ERROR", message: "Invalid orientation transform"))- return+ try? FileManager.default.removeItem(at: url)+ guard let destination = CGImageDestinationCreateWithURL(+ url as CFURL,+ "public.jpeg" as CFString,+ 1,+ nil+ ) else {+ throw NSError(+ domain: "NativeVideoEditor",+ code: 3,+ userInfo: [NSLocalizedDescriptionKey: "Could not create JPEG destination"]+ )}- let orientationInverse = orientationTransform.inverted()-- let displayCorners = [- cropRectDisplay.origin,- CGPoint(x: cropRectDisplay.maxX, y: cropRectDisplay.minY),- CGPoint(x: cropRectDisplay.minX, y: cropRectDisplay.maxY),- CGPoint(x: cropRectDisplay.maxX, y: cropRectDisplay.maxY)- ]-- let fileCorners = displayCorners.map { $0.applying(orientationInverse) }-- let fileMinX = fileCorners.map { $0.x }.min() ?? 0- let fileMinY = fileCorners.map { $0.y }.min() ?? 0- let fileMaxX = fileCorners.map { $0.x }.max() ?? 0- let fileMaxY = fileCorners.map { $0.y }.max() ?? 0-- let fileCropRect = CGRect(- x: fileMinX,- y: fileMinY,- width: fileMaxX - fileMinX,- height: fileMaxY - fileMinY- )-- let cropTranslation = CGAffineTransform(- translationX: -fileCropRect.origin.x,- y: -fileCropRect.origin.y- )-- var transform = cropTranslation.concatenating(orientationTransform)-- let transformedCorners = fileCorners.map { $0.applying(transform) }-- let minX = transformedCorners.map { $0.x }.min() ?? 0- let minY = transformedCorners.map { $0.y }.min() ?? 0- let maxX = transformedCorners.map { $0.x }.max() ?? 0- let maxY = transformedCorners.map { $0.y }.max() ?? 0-- let correctionTransform = CGAffineTransform(- translationX: -minX,- y: -minY- )- transform = transform.concatenating(correctionTransform)-- let outputWidth = max((maxX - minX).rounded(), CGFloat(1))- let outputHeight = max((maxY - minY).rounded(), CGFloat(1))- let renderSize = CGSize(width: outputWidth, height: outputHeight)-- layerInstruction.setTransform(transform, at: .zero)- videoComposition.renderSize = renderSize-- instruction.layerInstructions = [layerInstruction]- videoComposition.instructions = [instruction]-- guard let exportSession = AVAssetExportSession(- asset: composition,- presetName: AVAssetExportPresetHighestQuality) else {- result(flutterError("EXPORT_ERROR", message: "Failed to create export session"))- return+ let properties = [kCGImageDestinationLossyCompressionQuality: quality] as CFDictionary+ CGImageDestinationAddImage(destination, image, properties)+ if !CGImageDestinationFinalize(destination) {+ throw NSError(+ domain: "NativeVideoEditor",+ code: 4,+ userInfo: [NSLocalizedDescriptionKey: "Could not finalize JPEG output"]+ )}+ }- currentExportSession = exportSession-- exportSession.videoComposition = videoComposition- exportSession.outputURL = URL(fileURLWithPath: outputPath)- exportSession.outputFileType = .mp4- exportSession.shouldOptimizeForNetworkUse = true+ private func finishFrameRequest(+ requestID: String,+ generator: AVAssetImageGenerator,+ result: @escaping FlutterResult,+ value: Any+ ) {+ guard let activeGenerator = frameGenerators[requestID],+ activeGenerator === generator else { return }+ frameGenerators.removeValue(forKey: requestID)+ frameOutputPaths.removeValue(forKey: requestID)+ cancelledFrameRequests.remove(requestID)+ frameSemaphore.signal()+ let cancellationResult = frameCancellationResults.removeValue(forKey: requestID)+ if !isDetached {+ result(value)+ cancellationResult?(nil)+ }+ }- startProgressReporting()- exportSession.exportAsynchronously {- DispatchQueue.main.async {- self.stopProgressReporting()- switch exportSession.status {- case .completed:- result([- "outputPath": outputPath,- "isReEncoded": true- ])- case .failed:- result(self.flutterError("CROP_ERROR", message: "Failed to crop video", error: exportSession.error))- case .cancelled:- result(self.flutterError("CANCELLED", message: "Export cancelled"))- default:- result(self.flutterError("UNKNOWN", message: "Unknown export status", error: exportSession.error))- }- self.currentExportSession = nil- }+ private func removeFiles<S: Sequence>(at paths: S) where S.Element == String {+ for path in paths {+ try? FileManager.default.removeItem(atPath: path)}}private func handleProcessVideo(call: FlutterMethodCall, result: @escaping FlutterResult) {+ guard currentExportSession == nil else {+ result(flutterError("CONCURRENT_EXPORT", message: "A video export is already active"))+ return+ }guard let args = call.arguments as? [String: Any],let inputPath = args["inputPath"] as? String,let outputPath = args["outputPath"] as? String else {result(flutterError("INVALID_ARGS", message: "Invalid arguments"))return}+ let trimStartMs = args["trimStartMs"] as? Int+ let trimEndMs = args["trimEndMs"] as? Int+ let rotateDegrees = args["rotateDegrees"] as? Int+ let cropX = args["cropX"] as? Int+ let cropY = args["cropY"] as? Int+ let cropWidth = args["cropWidth"] as? Int+ let cropHeight = args["cropHeight"] as? Int+ let cropValues = [cropX, cropY, cropWidth, cropHeight]+ let inputURL = URL(fileURLWithPath: inputPath)+ .standardizedFileURL.resolvingSymlinksInPath()+ let outputURL = URL(fileURLWithPath: outputPath)+ .standardizedFileURL.resolvingSymlinksInPath()+ guard inputURL != outputURL,+ FileManager.default.fileExists(atPath: inputURL.path),+ (trimStartMs == nil) == (trimEndMs == nil),+ trimStartMs == nil || (trimStartMs! >= 0 && trimStartMs! < trimEndMs!),+ rotateDegrees == nil || [0, 90, 180, 270].contains(rotateDegrees!),+ cropValues.allSatisfy({ $0 == nil }) || cropValues.allSatisfy({ $0 != nil }),+ cropWidth == nil || (cropX! >= 0 && cropY! >= 0 && cropWidth! > 0 && cropHeight! > 0) else {+ result(flutterError("INVALID_ARGS", message: "Invalid video processing arguments"))+ return+ }- let asset = AVAsset(url: URL(fileURLWithPath: inputPath))- var composition = AVMutableComposition()+ let asset = AVAsset(url: inputURL)+ let composition = AVMutableComposition()var videoComposition: AVMutableVideoComposition?- // Handle trim- var timeRange = CMTimeRange(start: .zero, duration: asset.duration)- if let trimStartMs = args["trimStartMs"] as? Int,- let trimEndMs = args["trimEndMs"] as? Int {+ var requestedTimeRange = CMTimeRange(start: .zero, duration: asset.duration)+ if let trimStartMs, let trimEndMs {let startTime = CMTime(value: CMTimeValue(trimStartMs), timescale: 1000)let endTime = CMTime(value: CMTimeValue(trimEndMs), timescale: 1000)- timeRange = CMTimeRange(start: startTime, end: endTime)+ requestedTimeRange = CMTimeRange(start: startTime, end: endTime)}guard let videoTrack = asset.tracks(withMediaType: .video).first,@@ -554,15 +424,28 @@ public class NativeVideoEditorPlugin: NSObject, FlutterPlugin {result(flutterError("COMPOSITION_ERROR", message: "Failed to create composition"))return}+ guard let videoTimeRange = intersection(+ requestedTimeRange,+ with: videoTrack.timeRange+ ) else {+ result(flutterError("INVALID_TIME_RANGE", message: "The edit range does not contain video"))+ return+ }do {- try compositionVideoTrack.insertTimeRange(timeRange, of: videoTrack, at: .zero)+ try compositionVideoTrack.insertTimeRange(videoTimeRange, of: videoTrack, at: .zero)if let audioTrack = asset.tracks(withMediaType: .audio).first,+ let audioTimeRange = intersection(videoTimeRange, with: audioTrack.timeRange),let compositionAudioTrack = composition.addMutableTrack(withMediaType: .audio,preferredTrackID: kCMPersistentTrackID_Invalid) {- try compositionAudioTrack.insertTimeRange(timeRange, of: audioTrack, at: .zero)+ let insertionTime = CMTimeSubtract(audioTimeRange.start, videoTimeRange.start)+ try compositionAudioTrack.insertTimeRange(+ audioTimeRange,+ of: audioTrack,+ at: insertionTime+ )}} catch {result(flutterError("INSERT_ERROR", message: "Failed to insert track", error: error))@@ -576,16 +459,10 @@ public class NativeVideoEditorPlugin: NSObject, FlutterPlugin {var finalTransform = preferredTransformvar renderSize = naturalSize- // Check if video has metadata rotation even if no explicit transformations requested- let hasMetadataRotation = !preferredTransform.isIdentity-- if let cropX = args["cropX"] as? Int,- let cropY = args["cropY"] as? Int,- let cropWidth = args["cropWidth"] as? Int,- let cropHeight = args["cropHeight"] as? Int {+ if let cropX, let cropY, let cropWidth, let cropHeight {isReEncoded = true- let requestedRotation = args["rotateDegrees"] as? Int ?? 0+ let requestedRotation = rotateDegrees ?? 0let normalizedRotation = ((requestedRotation % 360) + 360) % 360let naturalBounds = CGRect(origin: .zero, size: naturalSize)@@ -609,6 +486,21 @@ public class NativeVideoEditorPlugin: NSObject, FlutterPlugin {width: CGFloat(cropWidth),height: CGFloat(cropHeight))+ let displayBounds = CGRect(+ origin: .zero,+ size: CGSize(+ width: abs(preferredBounds.width),+ height: abs(preferredBounds.height)+ )+ )+ let cropTolerance: CGFloat = 0.5+ guard cropRectDisplay.minX >= displayBounds.minX - cropTolerance,+ cropRectDisplay.minY >= displayBounds.minY - cropTolerance,+ cropRectDisplay.maxX <= displayBounds.maxX + cropTolerance,+ cropRectDisplay.maxY <= displayBounds.maxY + cropTolerance else {+ result(flutterError("PROCESS_ERROR", message: "Crop rectangle exceeds the displayed video"))+ return+ }let displayCorners = [cropRectDisplay.origin,@@ -639,10 +531,7 @@ public class NativeVideoEditorPlugin: NSObject, FlutterPlugin {var transform = cropTranslation.concatenating(orientationTransform)if normalizedRotation != 0 {- // iOS CGAffineTransform rotates counter-clockwise for positive angles.- // To match Android behavior (positive = clockwise), negate the radians.- let radians = CGFloat(normalizedRotation) * .pi / 180- let clockwiseRadians = -radians+ let clockwiseRadians = CGFloat(normalizedRotation) * .pi / 180let rotationTransform = CGAffineTransform(rotationAngle: clockwiseRadians)transform = transform.concatenating(rotationTransform)}@@ -666,7 +555,7 @@ public class NativeVideoEditorPlugin: NSObject, FlutterPlugin {finalTransform = transform- } else if let rotateDegrees = args["rotateDegrees"] as? Int, rotateDegrees != 0 {+ } else if let rotateDegrees, rotateDegrees != 0 {isReEncoded = true// Apply orientation adjustment to handle existing metadata rotation properly@@ -679,14 +568,11 @@ public class NativeVideoEditorPlugin: NSObject, FlutterPlugin {let orientationTransform = preferredTransform.concatenating(orientationAdjustment)// Calculate oriented size for render calculations- var orientedSize = CGSize(width: abs(preferredBounds.width), height: abs(preferredBounds.height))+ let orientedSize = CGSize(width: abs(preferredBounds.width), height: abs(preferredBounds.height))var transform = orientationTransform- // iOS CGAffineTransform rotates counter-clockwise for positive angles- // To match Android behavior (positive = clockwise), we negate the radians- let radians = CGFloat(rotateDegrees) * .pi / 180- let clockwiseRadians = -radians+ let clockwiseRadians = CGFloat(rotateDegrees) * .pi / 180// Rotate around the center of the input videolet centerX = orientedSize.width / 2@@ -716,20 +602,6 @@ public class NativeVideoEditorPlugin: NSObject, FlutterPlugin {transform = transform.concatenating(CGAffineTransform(translationX: additionalTranslateX, y: additionalTranslateY))finalTransform = transform- } else if hasMetadataRotation {- // If no explicit transformations but video has metadata rotation, apply it- isReEncoded = true-- let naturalBounds = CGRect(origin: .zero, size: naturalSize)- let preferredBounds = naturalBounds.applying(preferredTransform)- let orientationAdjustment = CGAffineTransform(- translationX: -preferredBounds.minX,- y: -preferredBounds.minY- )-- let orientationTransform = preferredTransform.concatenating(orientationAdjustment)- renderSize = CGSize(width: abs(preferredBounds.width), height: abs(preferredBounds.height))- finalTransform = orientationTransform}if isReEncoded {@@ -745,6 +617,8 @@ public class NativeVideoEditorPlugin: NSObject, FlutterPlugin {instruction.layerInstructions = [layerInstruction]videoComposition!.instructions = [instruction]+ } else {+ compositionVideoTrack.preferredTransform = preferredTransform}// Export@@ -760,9 +634,10 @@ public class NativeVideoEditorPlugin: NSObject, FlutterPlugin {exportSession.videoComposition = videoComp}- exportSession.outputURL = URL(fileURLWithPath: outputPath)+ exportSession.outputURL = outputURLexportSession.outputFileType = .mp4exportSession.shouldOptimizeForNetworkUse = true+ try? FileManager.default.removeItem(at: outputURL)if !isReEncoded {exportSession.timeRange = CMTimeRange(start: .zero, duration: composition.duration)@@ -772,24 +647,60 @@ public class NativeVideoEditorPlugin: NSObject, FlutterPlugin {exportSession.exportAsynchronously {DispatchQueue.main.async {self.stopProgressReporting()- switch exportSession.status {- case .completed:- result([- "outputPath": outputPath,- "isReEncoded": isReEncoded- ])- case .failed:- result(self.flutterError("PROCESS_ERROR", message: "Failed to process video", error: exportSession.error))- case .cancelled:- result(self.flutterError("CANCELLED", message: "Export cancelled"))- default:- result(self.flutterError("UNKNOWN", message: "Unknown export status", error: exportSession.error))+ if self.isDetached {+ try? FileManager.default.removeItem(at: outputURL)+ } else {+ switch exportSession.status {+ case .completed:+ let outputSize = (try? outputURL.resourceValues(+ forKeys: [.fileSizeKey]+ ).fileSize) ?? 0+ if outputSize > 0 {+ result([+ "outputPath": outputPath,+ "isReEncoded": isReEncoded+ ])+ } else {+ try? FileManager.default.removeItem(at: outputURL)+ result(self.flutterError("PROCESS_ERROR", message: "Export produced no output"))+ }+ case .failed:+ try? FileManager.default.removeItem(at: outputURL)+ result(self.flutterError("PROCESS_ERROR", message: "Failed to process video", error: exportSession.error))+ case .cancelled:+ try? FileManager.default.removeItem(at: outputURL)+ result(self.flutterError("PROCESS_CANCELLED", message: "Export cancelled"))+ default:+ try? FileManager.default.removeItem(at: outputURL)+ result(self.flutterError("UNKNOWN", message: "Unknown export status", error: exportSession.error))+ }}self.currentExportSession = nil+ if !self.isDetached {+ self.exportCancellationResult?(nil)+ }+ self.exportCancellationResult = nil}}}+ private func intersection(+ _ requestedRange: CMTimeRange,+ with availableRange: CMTimeRange+ ) -> CMTimeRange? {+ let intersection = CMTimeRangeGetIntersection(+ requestedRange,+ otherRange: availableRange+ )+ guard intersection.isValid,+ !intersection.isEmpty,+ intersection.duration.isNumeric,+ CMTimeCompare(intersection.duration, .zero) > 0 else {+ return nil+ }+ return intersection+ }+private func frameDuration(for track: AVAssetTrack) -> CMTime {let nominal = track.nominalFrameRateif nominal.isFinite && nominal > 0 {@@ -815,35 +726,107 @@ public class NativeVideoEditorPlugin: NSObject, FlutterPlugin {}private func getVideoInfo(videoPath: String, result: @escaping FlutterResult) {- let asset = AVAsset(url: URL(fileURLWithPath: videoPath))+ let asset = AVURLAsset(url: URL(fileURLWithPath: videoPath))+ loadVideoInfo(asset: asset) { [weak self] loadedInfo in+ guard let self = self else { return }+ DispatchQueue.main.async {+ guard !self.isDetached else { return }+ switch loadedInfo {+ case .success(let info):+ result(info)+ case .failure(let error):+ result(self.flutterError(+ "INFO_ERROR",+ message: "Failed to load video metadata",+ error: error+ ))+ }+ }+ }+ }- // Use the synchronous properties for iOS compatibility- let duration = asset.duration- let tracks = asset.tracks+ private func loadVideoInfo(+ asset: AVAsset,+ completion: @escaping (Result<[String: Any], Error>) -> Void+ ) {+ asset.loadValuesAsynchronously(forKeys: ["duration", "tracks"]) { [weak self] in+ guard let self = self else { return }+ var error: NSError?+ guard asset.statusOfValue(forKey: "duration", error: &error) == .loaded,+ asset.statusOfValue(forKey: "tracks", error: &error) == .loaded else {+ completion(.failure(error ?? NSError(+ domain: "NativeVideoEditor",+ code: 1,+ userInfo: [NSLocalizedDescriptionKey: "Video metadata is unavailable"]+ )))+ return+ }+ guard let videoTrack = asset.tracks.first(where: { $0.mediaType == .video }) else {+ completion(.failure(NSError(+ domain: "NativeVideoEditor",+ code: 2,+ userInfo: [NSLocalizedDescriptionKey: "Video track is unavailable"]+ )))+ return+ }++ let trackKeys = [+ "naturalSize",+ "preferredTransform",+ "nominalFrameRate",+ "estimatedDataRate",+ ]+ videoTrack.loadValuesAsynchronously(forKeys: trackKeys) {+ for key in ["naturalSize", "preferredTransform"] {+ var trackError: NSError?+ guard videoTrack.statusOfValue(forKey: key, error: &trackError) == .loaded else {+ completion(.failure(trackError ?? NSError(+ domain: "NativeVideoEditor",+ code: 3,+ userInfo: [NSLocalizedDescriptionKey: "Video track metadata is unavailable: \(key)"]+ )))+ return+ }+ }+ completion(.success(self.loadedVideoInfo(asset: asset)))+ }+ }+ }+ private func loadedVideoInfo(asset: AVAsset) -> [String: Any] {+ let durationSeconds = CMTimeGetSeconds(asset.duration)var info: [String: Any] = [- "duration": CMTimeGetSeconds(duration) * 1000, // Convert to milliseconds+ "duration": durationSeconds.isFinite+ ? Int64(max(0, durationSeconds * 1000))+ : Int64(0),+ "width": 0,+ "height": 0,+ "displayWidth": 0,+ "displayHeight": 0,+ "rotation": 0,]- if let videoTrack = tracks.first(where: { $0.mediaType == .video }) {+ if let videoTrack = asset.tracks.first(where: { $0.mediaType == .video }) {let naturalSize = videoTrack.naturalSize- let preferredTransform = videoTrack.preferredTransform- let nominalFrameRate = videoTrack.nominalFrameRate-- info["width"] = Int(naturalSize.width)- info["height"] = Int(naturalSize.height)- info["frameRate"] = nominalFrameRate-- let angle = atan2(preferredTransform.b, preferredTransform.a)- let rotation = Int(angle * 180 / .pi)+ let transform = videoTrack.preferredTransform+ let transformedBounds = CGRect(origin: .zero, size: naturalSize).applying(transform)+ let angle = atan2(transform.b, transform.a) * 180 / .pi+ let roundedAngle = Int(angle.rounded())+ let rotation = ((roundedAngle % 360) + 360) % 360++ info["width"] = Int(abs(naturalSize.width).rounded())+ info["height"] = Int(abs(naturalSize.height).rounded())+ info["displayWidth"] = Int(abs(transformedBounds.width).rounded())+ info["displayHeight"] = Int(abs(transformedBounds.height).rounded())info["rotation"] = rotation+ if videoTrack.nominalFrameRate > 0 {+ info["frameRate"] = Double(videoTrack.nominalFrameRate)+ }+ if videoTrack.estimatedDataRate > 0 {+ info["bitrate"] = Int64(videoTrack.estimatedDataRate)+ }}-- if let audioTrack = tracks.first(where: { $0.mediaType == .audio }) {- info["hasAudio"] = true- }-- result(info)+ return info}private func startProgressReporting() {@@ -862,6 +845,25 @@ public class NativeVideoEditorPlugin: NSObject, FlutterPlugin {progressTimer?.invalidate()progressTimer = nil}++ public func detachFromEngine(for registrar: FlutterPluginRegistrar) {+ guard !isDetached else { return }+ isDetached = true+ progressEventSink = nil+ stopProgressReporting()++ currentExportSession?.cancelExport()+ exportCancellationResult = nil++ cancelledFrameRequests.formUnion(frameGenerators.keys)+ for outputPaths in frameOutputPaths.values {+ removeFiles(at: outputPaths)+ }+ frameCancellationResults.removeAll()+ for generator in frameGenerators.values {+ generator.cancelAllCGImageGeneration()+ }+ }}private extension CGAffineTransform {@@ -873,7 +875,9 @@ private extension CGAffineTransform {extension NativeVideoEditorPlugin: FlutterStreamHandler {public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? {- progressEventSink = events+ if !isDetached {+ progressEventSink = events+ }return nil}diff --git a/mobile/packages/native_video_editor/pubspec.yaml b/mobile/packages/native_video_editor/pubspec.yamlindex 41f5f4cc21..f60b4f91bc 100644--- a/mobile/packages/native_video_editor/pubspec.yaml+++ b/mobile/packages/native_video_editor/pubspec.yaml@@ -1,5 +1,5 @@name: native_video_editor-description: Native video editing operations for trim, crop, and rotate without re-encoding+description: Ente-owned native video metadata, frame extraction, and editing operationsresolution: workspaceenvironment:@@ -22,4 +22,4 @@ flutter:package: io.ente.native_video_editorpluginClass: NativeVideoEditorPluginios:- pluginClass: NativeVideoEditorPlugin\ No newline at end of file+ pluginClass: NativeVideoEditorPlugin