From 96b8c77bcdbbc096f76ced3ded02c994a1275f2b Mon Sep 17 00:00:00 2001 From: davotoula Date: Mon, 22 Sep 2025 18:11:29 +0200 Subject: [PATCH 01/19] there is a plan --- .../amethyst/service/uploads/MediaCompressor.kt | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt index 9f5cfe255..ba61af180 100644 --- a/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt @@ -49,6 +49,19 @@ class MediaCompressorResult( val size: Long?, ) +/** The plan + * 1. Check input resolution and input fps + * 2. Create configuration matrix: for each quality level, set bitrate based on input resolution + * 3. Create Configuration with no quality setting, a bitrate setting, resizer, streamable = true, isMinBitrateCheckEnabled=false + * + * + * Don't use Configuration.quality which only determines bitrate. Instead let's create aggressive bitrates based on input and selected quality + * H265 is not supported, use bitrates that suit h264 + * Detect fps in source, multiple bitrate by 1.5 if 60fps or higher + * Bitrate floor has to be 1Mbps for now + * Future extension: Modify library to use bps for bitrate instead of Mbps which allows only 1Mbps as lowest and increments of 1 (Int) + * + */ class MediaCompressor { // ALL ERRORS ARE IGNORED. The original file is returned. suspend fun compress( From 931c6681c6e52d9d78b1bb04b4a636a30e49d80d Mon Sep 17 00:00:00 2001 From: davotoula Date: Mon, 22 Sep 2025 18:20:30 +0200 Subject: [PATCH 02/19] added compression rules --- .../service/uploads/MediaCompressor.kt | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt index ba61af180..72c6da617 100644 --- a/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt @@ -49,6 +49,50 @@ class MediaCompressorResult( val size: Long?, ) +data class CompressionRule( + val width: Int, + val height: Int, + val bitrateMbps: Float, + val description: String, +) + +private val compressionRules = + mapOf( + CompressorQuality.LOW to + mapOf( + "4K" to CompressionRule(1280, 720, 2f, "4K→720p, 2Mbps"), + "1440p" to CompressionRule(1280, 720, 2f, "1440p→720p, 2Mbps"), + "1080p" to CompressionRule(854, 480, 1f, "1080p→480p, 1Mbps"), + "720p" to CompressionRule(640, 360, 1f, "720p→360p, 1Mbps"), + "480p" to CompressionRule(426, 240, 1f, "480p→240p, 1Mbps"), + "360p" to CompressionRule(426, 240, 0.3f, "360p→240p, 0.3Mbps"), + "240p" to CompressionRule(320, 180, 0.2f, "240p→180p, 0.2Mbps"), + "default" to CompressionRule(854, 480, 1f, "Low quality fallback, 1Mbps"), + ), + CompressorQuality.MEDIUM to + mapOf( + "4K" to CompressionRule(1920, 1080, 6f, "4K→1080p, 6Mbps"), + "1440p" to CompressionRule(1920, 1080, 6f, "1440p→1080p, 6Mbps"), + "1080p" to CompressionRule(1280, 720, 3f, "1080p→720p, 3Mbps"), + "720p" to CompressionRule(854, 480, 2f, "720p→480p, 2Mbps"), + "480p" to CompressionRule(640, 360, 1f, "480p→360p, 1Mbps"), + "360p" to CompressionRule(426, 240, 0.5f, "360p→240p, 0.5Mbps"), + "240p" to CompressionRule(320, 180, 0.3f, "240p→180p, 0.3Mbps"), + "default" to CompressionRule(1280, 720, 2f, "Medium quality fallback, 2Mbps"), + ), + CompressorQuality.HIGH to + mapOf( + "4K" to CompressionRule(3840, 2160, 16f, "4K→4K, 16Mbps"), + "1440p" to CompressionRule(1920, 1080, 8f, "1440p→1080p, 8Mbps"), + "1080p" to CompressionRule(1920, 1080, 6f, "1080p→1080p, 6Mbps"), + "720p" to CompressionRule(1280, 720, 3f, "720p→720p, 3Mbps"), + "480p" to CompressionRule(854, 480, 2f, "480p→480p, 2Mbps"), + "360p" to CompressionRule(640, 360, 1f, "360p→360p, 1Mbps"), + "240p" to CompressionRule(426, 240, 0.5f, "240p→240p, 0.5Mbps"), + "default" to CompressionRule(1920, 1080, 3f, "High quality fallback, 3Mbps"), + ), + ) + /** The plan * 1. Check input resolution and input fps * 2. Create configuration matrix: for each quality level, set bitrate based on input resolution From 87f224b6b85d66113002859ce5711cec392bcd3a Mon Sep 17 00:00:00 2001 From: davotoula Date: Mon, 22 Sep 2025 18:28:23 +0200 Subject: [PATCH 03/19] get video resolution, framerate and rotation --- .../service/uploads/MediaCompressor.kt | 64 ++++++++++++++++++- 1 file changed, 62 insertions(+), 2 deletions(-) diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt index 72c6da617..730384d95 100644 --- a/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt @@ -22,6 +22,7 @@ package com.vitorpamplona.amethyst.service.uploads import android.content.Context import android.graphics.Bitmap +import android.media.MediaMetadataRetriever import android.net.Uri import androidx.core.net.toUri import androidx.media3.common.MimeTypes @@ -56,6 +57,31 @@ data class CompressionRule( val description: String, ) +private data class VideoInfo( + val resolution: VideoResolution, + val framerate: Float, +) + +data class VideoResolution( + val width: Int, + val height: Int, +) { + val pixels: Int get() = width * height + val isPortrait: Boolean get() = height > width + + fun getStandardName(): String = + when { + pixels >= 3840 * 2160 -> "4K" + pixels >= 2560 * 1440 -> "1440p" + pixels >= 1920 * 1080 -> "1080p" + pixels >= 1280 * 720 -> "720p" + pixels >= 854 * 480 -> "480p" + pixels >= 640 * 360 -> "360p" + pixels >= 426 * 240 -> "240p" + else -> "${width}x$height" + } +} + private val compressionRules = mapOf( CompressorQuality.LOW to @@ -93,9 +119,43 @@ private val compressionRules = ), ) +private fun getVideoInfo( + uri: Uri, + context: Context, +): VideoInfo? = + try { + val retriever = MediaMetadataRetriever() + retriever.setDataSource(context, uri) + val width = retriever.prepareVideoWidth() + val height = retriever.prepareVideoHeight() + val rotation = retriever.prepareRotation() ?: 0 + + // Get framerate + val framerateString = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_CAPTURE_FRAMERATE) + val framerate = framerateString?.toFloatOrNull() ?: 30.0f + + retriever.release() + + if (width != null && height != null && width > 0 && height > 0) { + // Account for rotation + val resolution = + if (rotation == 90 || rotation == 270) { + VideoResolution(height, width) + } else { + VideoResolution(width, height) + } + VideoInfo(resolution, framerate) + } else { + null + } + } catch (e: Exception) { + Log.w("MediaCompressor", "Failed to get video resolution: ${e.message}") + null + } + /** The plan - * 1. Check input resolution and input fps - * 2. Create configuration matrix: for each quality level, set bitrate based on input resolution + * xxx 1. Check input resolution and input fps + * xxx 2. Create configuration matrix: for each quality level, set bitrate based on input resolution * 3. Create Configuration with no quality setting, a bitrate setting, resizer, streamable = true, isMinBitrateCheckEnabled=false * * From 97d6c791c09e187f271e05b24f9a19658a5e5349 Mon Sep 17 00:00:00 2001 From: davotoula Date: Mon, 22 Sep 2025 19:00:56 +0200 Subject: [PATCH 04/19] determine resizer and bitrate from input source combined with our compression rules use 1 as lowest BitrateMbps --- .../service/uploads/MediaCompressor.kt | 47 +++++++++++++------ 1 file changed, 33 insertions(+), 14 deletions(-) diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt index 730384d95..b0f113d5d 100644 --- a/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt @@ -28,9 +28,9 @@ import androidx.core.net.toUri import androidx.media3.common.MimeTypes import com.abedelazizshe.lightcompressorlibrary.CompressionListener import com.abedelazizshe.lightcompressorlibrary.VideoCompressor -import com.abedelazizshe.lightcompressorlibrary.VideoQuality import com.abedelazizshe.lightcompressorlibrary.config.AppSpecificStorageConfiguration import com.abedelazizshe.lightcompressorlibrary.config.Configuration +import com.abedelazizshe.lightcompressorlibrary.config.VideoResizer import com.vitorpamplona.amethyst.service.checkNotInMainThread import com.vitorpamplona.amethyst.ui.components.util.MediaCompressorFileUtils import com.vitorpamplona.quartz.utils.Log @@ -41,6 +41,7 @@ import kotlinx.coroutines.suspendCancellableCoroutine import kotlinx.coroutines.withTimeoutOrNull import java.io.File import kotlin.coroutines.resume +import kotlin.math.roundToInt import kotlin.uuid.ExperimentalUuidApi import kotlin.uuid.Uuid @@ -55,7 +56,16 @@ data class CompressionRule( val height: Int, val bitrateMbps: Float, val description: String, -) +) { + fun getBitrateMbpsInt(): Int { + // Library doesn't support float so we have to convert it to int and use 1 as minimum + return if (bitrateMbps < 1) { + 1 + } else { + bitrateMbps.roundToInt() + } + } +} private data class VideoInfo( val resolution: VideoResolution, @@ -157,6 +167,7 @@ private fun getVideoInfo( * xxx 1. Check input resolution and input fps * xxx 2. Create configuration matrix: for each quality level, set bitrate based on input resolution * 3. Create Configuration with no quality setting, a bitrate setting, resizer, streamable = true, isMinBitrateCheckEnabled=false + * 4. Don't upload converted file if compression results in larger file * * * Don't use Configuration.quality which only determines bitrate. Instead let's create aggressive bitrates based on input and selected quality @@ -200,18 +211,24 @@ class MediaCompressor { applicationContext: Context, mediaQuality: CompressorQuality, ): MediaCompressorResult { - val videoQuality = - when (mediaQuality) { - CompressorQuality.VERY_LOW -> VideoQuality.VERY_LOW - // Override user selection LOW to use VERY_LOW for better video streaming experience - CompressorQuality.LOW -> VideoQuality.VERY_LOW - CompressorQuality.MEDIUM -> VideoQuality.MEDIUM - CompressorQuality.HIGH -> VideoQuality.HIGH - CompressorQuality.VERY_HIGH -> VideoQuality.VERY_HIGH - else -> VideoQuality.MEDIUM + val videoInfo = getVideoInfo(uri, applicationContext) + + val videoBitrateInMbps = + if (videoInfo != null) { + compressionRules.getValue(mediaQuality).getValue(videoInfo.resolution.getStandardName()).getBitrateMbpsInt() + } else { + // Default/fallback logic when videoInfo is null + 2 } - Log.d("MediaCompressor", "Using video compression $videoQuality") + val resizer = + if (videoInfo != null) { + val rules = compressionRules.getValue(mediaQuality).getValue(videoInfo.resolution.getStandardName()) + VideoResizer.limitSize(rules.width.toDouble(), rules.height.toDouble()) + } else { + // null VideoResizer should result in unchanged resolution + null + } val result = withTimeoutOrNull(30000) { @@ -221,7 +238,7 @@ class MediaCompressor { context = applicationContext, // => Source can be provided as content uris uris = listOf(uri), - isStreamable = false, + isStreamable = true, // THIS STORAGE // sharedStorageConfiguration = SharedStorageConfiguration( // saveAt = SaveLocation.movies, // => default is movies @@ -231,9 +248,11 @@ class MediaCompressor { storageConfiguration = AppSpecificStorageConfiguration(), configureWith = Configuration( - quality = videoQuality, + videoBitrateInMbps = videoBitrateInMbps, + resizer = resizer, // => required name videoNames = listOf(Uuid.random().toString()), + isMinBitrateCheckEnabled = false, ), listener = object : CompressionListener { From f5202dd8a989e10b8ccd376411bf1f4ed282dd53 Mon Sep 17 00:00:00 2001 From: davotoula Date: Mon, 22 Sep 2025 19:29:58 +0200 Subject: [PATCH 05/19] added log statements --- .../amethyst/service/uploads/MediaCompressor.kt | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt index b0f113d5d..b55bd03b9 100644 --- a/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt @@ -167,7 +167,7 @@ private fun getVideoInfo( * xxx 1. Check input resolution and input fps * xxx 2. Create configuration matrix: for each quality level, set bitrate based on input resolution * 3. Create Configuration with no quality setting, a bitrate setting, resizer, streamable = true, isMinBitrateCheckEnabled=false - * 4. Don't upload converted file if compression results in larger file + * 4. Don't upload converted file if compression results in larger file (return MediaCompressorResult(uri, contentType, null)) * * * Don't use Configuration.quality which only determines bitrate. Instead let's create aggressive bitrates based on input and selected quality @@ -215,18 +215,23 @@ class MediaCompressor { val videoBitrateInMbps = if (videoInfo != null) { - compressionRules.getValue(mediaQuality).getValue(videoInfo.resolution.getStandardName()).getBitrateMbpsInt() + val bitrate = compressionRules.getValue(mediaQuality).getValue(videoInfo.resolution.getStandardName()).getBitrateMbpsInt() + Log.d("MediaCompressor", "Video bitrate calculated: ${bitrate}Mbps for ${videoInfo.resolution.getStandardName()} quality=$mediaQuality") + bitrate } else { // Default/fallback logic when videoInfo is null + Log.d("MediaCompressor", "Video bitrate fallback: 2Mbps (videoInfo unavailable)") 2 } val resizer = if (videoInfo != null) { val rules = compressionRules.getValue(mediaQuality).getValue(videoInfo.resolution.getStandardName()) + Log.d("MediaCompressor", "Video resizer: ${videoInfo.resolution.width}x${videoInfo.resolution.height} -> ${rules.width}x${rules.height} (${rules.description})") VideoResizer.limitSize(rules.width.toDouble(), rules.height.toDouble()) } else { // null VideoResizer should result in unchanged resolution + Log.d("MediaCompressor", "Video resizer: null (original resolution preserved)") null } From f805b70ec0bb8049b708c90b0a6866b0c63f5a3f Mon Sep 17 00:00:00 2001 From: davotoula Date: Mon, 22 Sep 2025 19:42:38 +0200 Subject: [PATCH 06/19] added log statements and a toast --- .../service/uploads/MediaCompressor.kt | 34 ++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt index b55bd03b9..3551c70b0 100644 --- a/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt @@ -24,6 +24,9 @@ import android.content.Context import android.graphics.Bitmap import android.media.MediaMetadataRetriever import android.net.Uri +import android.text.format.Formatter.formatFileSize +import android.util.Log +import android.widget.Toast import androidx.core.net.toUri import androidx.media3.common.MimeTypes import com.abedelazizshe.lightcompressorlibrary.CompressionListener @@ -235,6 +238,17 @@ class MediaCompressor { null } + // Get original file size for compression reporting + val originalSize = + try { + applicationContext.contentResolver.openInputStream(uri)?.use { inputStream -> + inputStream.available().toLong() + } ?: 0L + } catch (e: Exception) { + Log.w("MediaCompressor", "Failed to get original file size: ${e.message}") + 0L + } + val result = withTimeoutOrNull(30000) { suspendCancellableCoroutine { continuation -> @@ -274,7 +288,25 @@ class MediaCompressor { path: String?, ) { if (path != null) { - Log.d("MediaCompressor", "Video compression success. Compressed size [$size]") + val reductionPercent = + if (originalSize > 0) { + ((originalSize - size) * 100.0 / originalSize).toInt() + } else { + 0 + } + + // Show compression result toast + if (originalSize > 0 && size > 0) { + val message = + "Video compressed: ${formatFileSize(applicationContext, size)} " + + "(${if (reductionPercent > 0) "-$reductionPercent%" else "+${-reductionPercent}%"})" + + // Post on main thread for Toast + android.os.Handler(android.os.Looper.getMainLooper()).post { + Toast.makeText(applicationContext, message, Toast.LENGTH_LONG).show() + } + } + Log.d("MediaCompressor", "Video compression success. Original size [$originalSize] -> Compressed size [$size] ($reductionPercent% reduction)") continuation.resume(MediaCompressorResult(Uri.fromFile(File(path)), contentType, size)) } else { Log.d("MediaCompressor", "Video compression successful, but returned null path") From 8588c9a6fcdc882411e35d7aa136901d0b1a65c6 Mon Sep 17 00:00:00 2001 From: davotoula Date: Mon, 22 Sep 2025 19:52:59 +0200 Subject: [PATCH 07/19] update plan --- .../vitorpamplona/amethyst/service/uploads/MediaCompressor.kt | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt index 3551c70b0..8f46b9097 100644 --- a/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt @@ -169,8 +169,10 @@ private fun getVideoInfo( /** The plan * xxx 1. Check input resolution and input fps * xxx 2. Create configuration matrix: for each quality level, set bitrate based on input resolution - * 3. Create Configuration with no quality setting, a bitrate setting, resizer, streamable = true, isMinBitrateCheckEnabled=false + * xxx 3. Create Configuration with no quality setting, a bitrate setting, resizer, streamable = true, isMinBitrateCheckEnabled=false * 4. Don't upload converted file if compression results in larger file (return MediaCompressorResult(uri, contentType, null)) + * xxx 5. Add toast message about file size saving + * 7. refactor (helper class for video compression) * * * Don't use Configuration.quality which only determines bitrate. Instead let's create aggressive bitrates based on input and selected quality From 49dc63c876e415cc76451cfc77798aad5bf19ad4 Mon Sep 17 00:00:00 2001 From: davotoula Date: Mon, 22 Sep 2025 20:22:45 +0200 Subject: [PATCH 08/19] Sanity check: if compressed file is larger than original, return original --- .../amethyst/service/uploads/MediaCompressor.kt | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt index 8f46b9097..7260adae4 100644 --- a/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt @@ -290,6 +290,13 @@ class MediaCompressor { path: String?, ) { if (path != null) { + // Sanity check: if compressed file is larger than original, return original + if (originalSize > 0 && size >= originalSize) { + Log.d("MediaCompressor", "Compressed file ($size bytes) is larger than original ($originalSize bytes). Using original file.") + continuation.resume(MediaCompressorResult(uri, contentType, null)) + return + } + val reductionPercent = if (originalSize > 0) { ((originalSize - size) * 100.0 / originalSize).toInt() From 524ead2eacba55a96774b9be1615ff1a31427cad Mon Sep 17 00:00:00 2001 From: davotoula Date: Mon, 22 Sep 2025 20:51:24 +0200 Subject: [PATCH 09/19] move video compression into helper --- .../service/uploads/MediaCompressor.kt | 130 +------- .../service/uploads/VideoCompressionHelper.kt | 287 ++++++++++++++++++ 2 files changed, 294 insertions(+), 123 deletions(-) create mode 100644 amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/VideoCompressionHelper.kt diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt index 7260adae4..665547200 100644 --- a/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt @@ -22,18 +22,10 @@ package com.vitorpamplona.amethyst.service.uploads import android.content.Context import android.graphics.Bitmap -import android.media.MediaMetadataRetriever import android.net.Uri -import android.text.format.Formatter.formatFileSize import android.util.Log -import android.widget.Toast import androidx.core.net.toUri import androidx.media3.common.MimeTypes -import com.abedelazizshe.lightcompressorlibrary.CompressionListener -import com.abedelazizshe.lightcompressorlibrary.VideoCompressor -import com.abedelazizshe.lightcompressorlibrary.config.AppSpecificStorageConfiguration -import com.abedelazizshe.lightcompressorlibrary.config.Configuration -import com.abedelazizshe.lightcompressorlibrary.config.VideoResizer import com.vitorpamplona.amethyst.service.checkNotInMainThread import com.vitorpamplona.amethyst.ui.components.util.MediaCompressorFileUtils import com.vitorpamplona.quartz.utils.Log @@ -54,125 +46,14 @@ class MediaCompressorResult( val size: Long?, ) -data class CompressionRule( - val width: Int, - val height: Int, - val bitrateMbps: Float, - val description: String, -) { - fun getBitrateMbpsInt(): Int { - // Library doesn't support float so we have to convert it to int and use 1 as minimum - return if (bitrateMbps < 1) { - 1 - } else { - bitrateMbps.roundToInt() - } - } -} - -private data class VideoInfo( - val resolution: VideoResolution, - val framerate: Float, -) - -data class VideoResolution( - val width: Int, - val height: Int, -) { - val pixels: Int get() = width * height - val isPortrait: Boolean get() = height > width - - fun getStandardName(): String = - when { - pixels >= 3840 * 2160 -> "4K" - pixels >= 2560 * 1440 -> "1440p" - pixels >= 1920 * 1080 -> "1080p" - pixels >= 1280 * 720 -> "720p" - pixels >= 854 * 480 -> "480p" - pixels >= 640 * 360 -> "360p" - pixels >= 426 * 240 -> "240p" - else -> "${width}x$height" - } -} - -private val compressionRules = - mapOf( - CompressorQuality.LOW to - mapOf( - "4K" to CompressionRule(1280, 720, 2f, "4K→720p, 2Mbps"), - "1440p" to CompressionRule(1280, 720, 2f, "1440p→720p, 2Mbps"), - "1080p" to CompressionRule(854, 480, 1f, "1080p→480p, 1Mbps"), - "720p" to CompressionRule(640, 360, 1f, "720p→360p, 1Mbps"), - "480p" to CompressionRule(426, 240, 1f, "480p→240p, 1Mbps"), - "360p" to CompressionRule(426, 240, 0.3f, "360p→240p, 0.3Mbps"), - "240p" to CompressionRule(320, 180, 0.2f, "240p→180p, 0.2Mbps"), - "default" to CompressionRule(854, 480, 1f, "Low quality fallback, 1Mbps"), - ), - CompressorQuality.MEDIUM to - mapOf( - "4K" to CompressionRule(1920, 1080, 6f, "4K→1080p, 6Mbps"), - "1440p" to CompressionRule(1920, 1080, 6f, "1440p→1080p, 6Mbps"), - "1080p" to CompressionRule(1280, 720, 3f, "1080p→720p, 3Mbps"), - "720p" to CompressionRule(854, 480, 2f, "720p→480p, 2Mbps"), - "480p" to CompressionRule(640, 360, 1f, "480p→360p, 1Mbps"), - "360p" to CompressionRule(426, 240, 0.5f, "360p→240p, 0.5Mbps"), - "240p" to CompressionRule(320, 180, 0.3f, "240p→180p, 0.3Mbps"), - "default" to CompressionRule(1280, 720, 2f, "Medium quality fallback, 2Mbps"), - ), - CompressorQuality.HIGH to - mapOf( - "4K" to CompressionRule(3840, 2160, 16f, "4K→4K, 16Mbps"), - "1440p" to CompressionRule(1920, 1080, 8f, "1440p→1080p, 8Mbps"), - "1080p" to CompressionRule(1920, 1080, 6f, "1080p→1080p, 6Mbps"), - "720p" to CompressionRule(1280, 720, 3f, "720p→720p, 3Mbps"), - "480p" to CompressionRule(854, 480, 2f, "480p→480p, 2Mbps"), - "360p" to CompressionRule(640, 360, 1f, "360p→360p, 1Mbps"), - "240p" to CompressionRule(426, 240, 0.5f, "240p→240p, 0.5Mbps"), - "default" to CompressionRule(1920, 1080, 3f, "High quality fallback, 3Mbps"), - ), - ) - -private fun getVideoInfo( - uri: Uri, - context: Context, -): VideoInfo? = - try { - val retriever = MediaMetadataRetriever() - retriever.setDataSource(context, uri) - val width = retriever.prepareVideoWidth() - val height = retriever.prepareVideoHeight() - val rotation = retriever.prepareRotation() ?: 0 - - // Get framerate - val framerateString = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_CAPTURE_FRAMERATE) - val framerate = framerateString?.toFloatOrNull() ?: 30.0f - - retriever.release() - - if (width != null && height != null && width > 0 && height > 0) { - // Account for rotation - val resolution = - if (rotation == 90 || rotation == 270) { - VideoResolution(height, width) - } else { - VideoResolution(width, height) - } - VideoInfo(resolution, framerate) - } else { - null - } - } catch (e: Exception) { - Log.w("MediaCompressor", "Failed to get video resolution: ${e.message}") - null - } - /** The plan * xxx 1. Check input resolution and input fps * xxx 2. Create configuration matrix: for each quality level, set bitrate based on input resolution * xxx 3. Create Configuration with no quality setting, a bitrate setting, resizer, streamable = true, isMinBitrateCheckEnabled=false - * 4. Don't upload converted file if compression results in larger file (return MediaCompressorResult(uri, contentType, null)) + * xxx 4. Don't upload converted file if compression results in larger file (return MediaCompressorResult(uri, contentType, null)) * xxx 5. Add toast message about file size saving - * 7. refactor (helper class for video compression) + * xxx 6. refactor (helper class for video compression) + * 7. Fix toast for case when compressed file is larger than original * * * Don't use Configuration.quality which only determines bitrate. Instead let's create aggressive bitrates based on input and selected quality @@ -200,7 +81,10 @@ class MediaCompressor { // branch into compression based on content type return when { - contentType?.startsWith("video", ignoreCase = true) == true -> compressVideo(uri, contentType, applicationContext, mediaQuality) + contentType?.startsWith("video", ignoreCase = true) == true -> { + val helper = VideoCompressionHelper() + helper.compressVideo(uri, contentType, applicationContext, mediaQuality) + } contentType?.startsWith("image", ignoreCase = true) == true && !contentType.contains("gif") && !contentType.contains("svg") -> diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/VideoCompressionHelper.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/VideoCompressionHelper.kt new file mode 100644 index 000000000..f53fae257 --- /dev/null +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/VideoCompressionHelper.kt @@ -0,0 +1,287 @@ +/** + * Copyright (c) 2025 Vitor Pamplona + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the + * Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN + * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +package com.vitorpamplona.amethyst.service.uploads + +import android.content.Context +import android.media.MediaMetadataRetriever +import android.net.Uri +import android.text.format.Formatter.formatFileSize +import android.util.Log +import android.widget.Toast +import com.abedelazizshe.lightcompressorlibrary.CompressionListener +import com.abedelazizshe.lightcompressorlibrary.VideoCompressor +import com.abedelazizshe.lightcompressorlibrary.config.AppSpecificStorageConfiguration +import com.abedelazizshe.lightcompressorlibrary.config.Configuration +import com.abedelazizshe.lightcompressorlibrary.config.VideoResizer +import kotlinx.coroutines.suspendCancellableCoroutine +import kotlinx.coroutines.withTimeoutOrNull +import java.io.File +import java.util.UUID +import kotlin.coroutines.resume +import kotlin.math.roundToInt + +data class VideoInfo( + val resolution: VideoResolution, + val framerate: Float, +) + +data class VideoResolution( + val width: Int, + val height: Int, +) { + val pixels: Int get() = width * height + + fun getStandardName(): String = + when { + pixels >= 3840 * 2160 -> "4K" + pixels >= 2560 * 1440 -> "1440p" + pixels >= 1920 * 1080 -> "1080p" + pixels >= 1280 * 720 -> "720p" + pixels >= 854 * 480 -> "480p" + pixels >= 640 * 360 -> "360p" + pixels >= 426 * 240 -> "240p" + else -> "${width}x$height" + } +} + +data class CompressionRule( + val width: Int, + val height: Int, + val bitrateMbps: Float, + val description: String, +) { + fun getBitrateMbpsInt(): Int { + // Library doesn't support float so we have to convert it to int and use 1 as minimum + return if (bitrateMbps < 1) { + 1 + } else { + bitrateMbps.roundToInt() + } + } +} + +class VideoCompressionHelper { + companion object { + private val compressionRules = + mapOf( + CompressorQuality.LOW to + mapOf( + "4K" to CompressionRule(1280, 720, 2f, "4K→720p, 2Mbps"), + "1440p" to CompressionRule(1280, 720, 2f, "1440p→720p, 2Mbps"), + "1080p" to CompressionRule(854, 480, 1f, "1080p→480p, 1Mbps"), + "720p" to CompressionRule(640, 360, 1f, "720p→360p, 1Mbps"), + "480p" to CompressionRule(426, 240, 1f, "480p→240p, 1Mbps"), + "360p" to CompressionRule(426, 240, 0.3f, "360p→240p, 0.3Mbps"), + "240p" to CompressionRule(320, 180, 0.2f, "240p→180p, 0.2Mbps"), + "default" to CompressionRule(854, 480, 1f, "Low quality fallback, 1Mbps"), + ), + CompressorQuality.MEDIUM to + mapOf( + "4K" to CompressionRule(1920, 1080, 6f, "4K→1080p, 6Mbps"), + "1440p" to CompressionRule(1920, 1080, 6f, "1440p→1080p, 6Mbps"), + "1080p" to CompressionRule(1280, 720, 3f, "1080p→720p, 3Mbps"), + "720p" to CompressionRule(854, 480, 2f, "720p→480p, 2Mbps"), + "480p" to CompressionRule(640, 360, 1f, "480p→360p, 1Mbps"), + "360p" to CompressionRule(426, 240, 0.5f, "360p→240p, 0.5Mbps"), + "240p" to CompressionRule(320, 180, 0.3f, "240p→180p, 0.3Mbps"), + "default" to CompressionRule(1280, 720, 2f, "Medium quality fallback, 2Mbps"), + ), + CompressorQuality.HIGH to + mapOf( + "4K" to CompressionRule(3840, 2160, 16f, "4K→4K, 16Mbps"), + "1440p" to CompressionRule(1920, 1080, 8f, "1440p→1080p, 8Mbps"), + "1080p" to CompressionRule(1920, 1080, 6f, "1080p→1080p, 6Mbps"), + "720p" to CompressionRule(1280, 720, 3f, "720p→720p, 3Mbps"), + "480p" to CompressionRule(854, 480, 2f, "480p→480p, 2Mbps"), + "360p" to CompressionRule(640, 360, 1f, "360p→360p, 1Mbps"), + "240p" to CompressionRule(426, 240, 0.5f, "240p→240p, 0.5Mbps"), + "default" to CompressionRule(1920, 1080, 3f, "High quality fallback, 3Mbps"), + ), + ) + } + + suspend fun compressVideo( + uri: Uri, + contentType: String?, + applicationContext: Context, + mediaQuality: CompressorQuality, + ): MediaCompressorResult { + val videoInfo = getVideoInfo(uri, applicationContext) + + val videoBitrateInMbps = + if (videoInfo != null) { + val bitrate = compressionRules.getValue(mediaQuality).getValue(videoInfo.resolution.getStandardName()).getBitrateMbpsInt() + Log.d("VideoCompressionHelper", "Video bitrate calculated: ${bitrate}Mbps for ${videoInfo.resolution.getStandardName()} quality=$mediaQuality") + bitrate + } else { + // Default/fallback logic when videoInfo is null + Log.d("VideoCompressionHelper", "Video bitrate fallback: 2Mbps (videoInfo unavailable)") + 2 + } + + val resizer = + if (videoInfo != null) { + val rules = compressionRules.getValue(mediaQuality).getValue(videoInfo.resolution.getStandardName()) + Log.d("VideoCompressionHelper", "Video resizer: ${videoInfo.resolution.width}x${videoInfo.resolution.height} -> ${rules.width}x${rules.height} (${rules.description})") + VideoResizer.limitSize(rules.width.toDouble(), rules.height.toDouble()) + } else { + // null VideoResizer should result in unchanged resolution + Log.d("VideoCompressionHelper", "Video resizer: null (original resolution preserved)") + null + } + + // Get original file size for compression reporting + val originalSize = + try { + applicationContext.contentResolver.openInputStream(uri)?.use { inputStream -> + inputStream.available().toLong() + } ?: 0L + } catch (e: Exception) { + Log.w("VideoCompressionHelper", "Failed to get original file size: ${e.message}") + 0L + } + + val result = + withTimeoutOrNull(30000) { + suspendCancellableCoroutine { continuation -> + VideoCompressor.start( + // => This is required + context = applicationContext, + // => Source can be provided as content uris + uris = listOf(uri), + isStreamable = true, + // THIS STORAGE + // sharedStorageConfiguration = SharedStorageConfiguration( + // saveAt = SaveLocation.movies, // => default is movies + // videoName = "compressed_video" // => required name + // ), + // OR AND NOT BOTH + storageConfiguration = AppSpecificStorageConfiguration(), + configureWith = + Configuration( + videoBitrateInMbps = videoBitrateInMbps, + resizer = resizer, + // => required name + videoNames = listOf(UUID.randomUUID().toString()), + isMinBitrateCheckEnabled = false, + ), + listener = + object : CompressionListener { + override fun onProgress( + index: Int, + percent: Float, + ) {} + + override fun onStart(index: Int) {} + + override fun onSuccess( + index: Int, + size: Long, + path: String?, + ) { + if (path != null) { + // Sanity check: if compressed file is larger than original, return original + if (originalSize > 0 && size >= originalSize) { + Log.d("VideoCompressionHelper", "Compressed file ($size bytes) is larger than original ($originalSize bytes). Using original file.") + continuation.resume(MediaCompressorResult(uri, contentType, null)) + return + } + + val reductionPercent = + if (originalSize > 0) { + ((originalSize - size) * 100.0 / originalSize).toInt() + } else { + 0 + } + + // Show compression result toast + if (originalSize > 0 && size > 0) { + val message = + "Video compressed: ${formatFileSize(applicationContext, size)} " + + "(${if (reductionPercent > 0) "-$reductionPercent%" else "+${-reductionPercent}%"})" + + // Post on main thread for Toast + android.os.Handler(android.os.Looper.getMainLooper()).post { + Toast.makeText(applicationContext, message, Toast.LENGTH_LONG).show() + } + } + Log.d("VideoCompressionHelper", "Video compression success. Original size [$originalSize] -> Compressed size [$size] ($reductionPercent% reduction)") + continuation.resume(MediaCompressorResult(Uri.fromFile(File(path)), contentType, size)) + } else { + Log.d("VideoCompressionHelper", "Video compression successful, but returned null path") + continuation.resume(null) + } + } + + override fun onFailure( + index: Int, + failureMessage: String, + ) { + Log.d("VideoCompressionHelper", "Video compression failed: $failureMessage") + // keeps going with original video + continuation.resume(null) + } + + override fun onCancelled(index: Int) { + continuation.resume(null) + } + }, + ) + } + } + + return result ?: MediaCompressorResult(uri, contentType, null) + } + + private fun getVideoInfo( + uri: Uri, + context: Context, + ): VideoInfo? = + try { + val retriever = MediaMetadataRetriever() + retriever.setDataSource(context, uri) + val width = retriever.prepareVideoWidth() + val height = retriever.prepareVideoHeight() + val rotation = retriever.prepareRotation() ?: 0 + + // Get framerate + val framerateString = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_CAPTURE_FRAMERATE) + val framerate = framerateString?.toFloatOrNull() ?: 30.0f + + retriever.release() + + if (width != null && height != null && width > 0 && height > 0) { + // Account for rotation + val resolution = + if (rotation == 90 || rotation == 270) { + VideoResolution(height, width) + } else { + VideoResolution(width, height) + } + VideoInfo(resolution, framerate) + } else { + null + } + } catch (e: Exception) { + Log.w("VideoCompressionHelper", "Failed to get video resolution: ${e.message}") + null + } +} From 947f59fa6faa3f8b515c9f84ee9fe256a792e30b Mon Sep 17 00:00:00 2001 From: davotoula Date: Mon, 22 Sep 2025 21:09:53 +0200 Subject: [PATCH 10/19] add bitrate multiplier for 60fps content fix toast when new file larger than old --- .../service/uploads/MediaCompressor.kt | 3 +- .../service/uploads/VideoCompressionHelper.kt | 55 ++++++++++++------- 2 files changed, 37 insertions(+), 21 deletions(-) diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt index 665547200..f916d0556 100644 --- a/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt @@ -53,7 +53,8 @@ class MediaCompressorResult( * xxx 4. Don't upload converted file if compression results in larger file (return MediaCompressorResult(uri, contentType, null)) * xxx 5. Add toast message about file size saving * xxx 6. refactor (helper class for video compression) - * 7. Fix toast for case when compressed file is larger than original + * xxx 7. Fix toast for case when compressed file is larger than original + * xxx 8. fix ratio multiplier for framerate ->60 * * * Don't use Configuration.quality which only determines bitrate. Instead let's create aggressive bitrates based on input and selected quality diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/VideoCompressionHelper.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/VideoCompressionHelper.kt index f53fae257..51a2e5eaa 100644 --- a/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/VideoCompressionHelper.kt +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/VideoCompressionHelper.kt @@ -23,6 +23,8 @@ package com.vitorpamplona.amethyst.service.uploads import android.content.Context import android.media.MediaMetadataRetriever import android.net.Uri +import android.os.Handler +import android.os.Looper import android.text.format.Formatter.formatFileSize import android.util.Log import android.widget.Toast @@ -128,9 +130,16 @@ class VideoCompressionHelper { val videoBitrateInMbps = if (videoInfo != null) { - val bitrate = compressionRules.getValue(mediaQuality).getValue(videoInfo.resolution.getStandardName()).getBitrateMbpsInt() - Log.d("VideoCompressionHelper", "Video bitrate calculated: ${bitrate}Mbps for ${videoInfo.resolution.getStandardName()} quality=$mediaQuality") - bitrate + val baseBitrate = compressionRules.getValue(mediaQuality).getValue(videoInfo.resolution.getStandardName()).getBitrateMbpsInt() + // Apply 1.5x multiplier for 60fps or higher videos + val adjustedBitrate = + if (videoInfo.framerate >= 60f) { + (baseBitrate * 1.5f).roundToInt() + } else { + baseBitrate + } + Log.d("VideoCompressionHelper", "Video bitrate calculated: ${adjustedBitrate}Mbps for ${videoInfo.resolution.getStandardName()} quality=$mediaQuality framerate=${videoInfo.framerate}fps") + adjustedBitrate } else { // Default/fallback logic when videoInfo is null Log.d("VideoCompressionHelper", "Video bitrate fallback: 2Mbps (videoInfo unavailable)") @@ -188,7 +197,8 @@ class VideoCompressionHelper { override fun onProgress( index: Int, percent: Float, - ) {} + ) { + } override fun onStart(index: Int) {} @@ -198,13 +208,6 @@ class VideoCompressionHelper { path: String?, ) { if (path != null) { - // Sanity check: if compressed file is larger than original, return original - if (originalSize > 0 && size >= originalSize) { - Log.d("VideoCompressionHelper", "Compressed file ($size bytes) is larger than original ($originalSize bytes). Using original file.") - continuation.resume(MediaCompressorResult(uri, contentType, null)) - return - } - val reductionPercent = if (originalSize > 0) { ((originalSize - size) * 100.0 / originalSize).toInt() @@ -212,16 +215,19 @@ class VideoCompressionHelper { 0 } - // Show compression result toast - if (originalSize > 0 && size > 0) { - val message = - "Video compressed: ${formatFileSize(applicationContext, size)} " + - "(${if (reductionPercent > 0) "-$reductionPercent%" else "+${-reductionPercent}%"})" + // Sanity check: if compressed file is larger than original, return original + if (originalSize > 0 && size >= originalSize) { + Log.d("VideoCompressionHelper", "Compressed file ($size bytes) is larger than original ($originalSize bytes). Using original file.") + applicationContext.showToast("Video compression didn't reduce size. Using original file.") + continuation.resume(MediaCompressorResult(uri, contentType, null)) + return + } - // Post on main thread for Toast - android.os.Handler(android.os.Looper.getMainLooper()).post { - Toast.makeText(applicationContext, message, Toast.LENGTH_LONG).show() - } + if (originalSize > 0 && size > 0) { + val sizeLabel = formatFileSize(applicationContext, size) + val percentLabel = if (reductionPercent >= 0) "-$reductionPercent%" else "+${-reductionPercent}%" + + applicationContext.showToast("Video compressed: $sizeLabel ($percentLabel)") } Log.d("VideoCompressionHelper", "Video compression success. Original size [$originalSize] -> Compressed size [$size] ($reductionPercent% reduction)") continuation.resume(MediaCompressorResult(Uri.fromFile(File(path)), contentType, size)) @@ -251,6 +257,15 @@ class VideoCompressionHelper { return result ?: MediaCompressorResult(uri, contentType, null) } + private fun Context.showToast( + message: String, + duration: Int = Toast.LENGTH_LONG, + ) { + Handler(Looper.getMainLooper()).post { + Toast.makeText(this, message, duration).show() + } + } + private fun getVideoInfo( uri: Uri, context: Context, From ed758ef13ef4052d26b0f5ae1a075272527ca3b7 Mon Sep 17 00:00:00 2001 From: davotoula Date: Mon, 22 Sep 2025 21:10:21 +0200 Subject: [PATCH 11/19] remove unused code --- .../amethyst/service/uploads/MediaCompressor.kt | 9 --------- 1 file changed, 9 deletions(-) diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt index f916d0556..2effe4674 100644 --- a/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt @@ -270,15 +270,6 @@ class MediaCompressor { 3 -> CompressorQuality.UNCOMPRESSED else -> CompressorQuality.MEDIUM } - - fun compressorQualityToInt(compressorQuality: CompressorQuality): Int = - when (compressorQuality) { - CompressorQuality.LOW -> 0 - CompressorQuality.MEDIUM -> 1 - CompressorQuality.HIGH -> 2 - CompressorQuality.UNCOMPRESSED -> 3 - else -> 1 - } } } From 9af1e10ec20d50128e7f9473ede2a49d3df4ede6 Mon Sep 17 00:00:00 2001 From: davotoula Date: Mon, 22 Sep 2025 21:26:07 +0200 Subject: [PATCH 12/19] refactor: Safe file size lookup using OpenableColumns.SIZE if (continuation.isActive) before resuming. Better logging levels (Log.e for errors, Log.w for warnings). Configurable compression timeout --- .../service/uploads/VideoCompressionHelper.kt | 172 +++++++++++------- 1 file changed, 109 insertions(+), 63 deletions(-) diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/VideoCompressionHelper.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/VideoCompressionHelper.kt index 51a2e5eaa..9a6033fb8 100644 --- a/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/VideoCompressionHelper.kt +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/VideoCompressionHelper.kt @@ -125,115 +125,139 @@ class VideoCompressionHelper { contentType: String?, applicationContext: Context, mediaQuality: CompressorQuality, + timeoutMs: Long = 60_000L, // configurable, default 60s ): MediaCompressorResult { val videoInfo = getVideoInfo(uri, applicationContext) val videoBitrateInMbps = if (videoInfo != null) { - val baseBitrate = compressionRules.getValue(mediaQuality).getValue(videoInfo.resolution.getStandardName()).getBitrateMbpsInt() - // Apply 1.5x multiplier for 60fps or higher videos - val adjustedBitrate = + val baseBitrate = + compressionRules + .getValue(mediaQuality) + .getValue(videoInfo.resolution.getStandardName()) + .getBitrateMbpsInt() + + // Apply 1.5x multiplier for 60fps+ + val adjusted = if (videoInfo.framerate >= 60f) { (baseBitrate * 1.5f).roundToInt() } else { baseBitrate } - Log.d("VideoCompressionHelper", "Video bitrate calculated: ${adjustedBitrate}Mbps for ${videoInfo.resolution.getStandardName()} quality=$mediaQuality framerate=${videoInfo.framerate}fps") - adjustedBitrate + + Log.d( + "VideoCompressionHelper", + "Bitrate: ${adjusted}Mbps for ${videoInfo.resolution.getStandardName()} " + + "quality=$mediaQuality framerate=${videoInfo.framerate}fps", + ) + adjusted } else { - // Default/fallback logic when videoInfo is null - Log.d("VideoCompressionHelper", "Video bitrate fallback: 2Mbps (videoInfo unavailable)") + Log.w("VideoCompressionHelper", "Video bitrate fallback: 2Mbps (videoInfo unavailable)") 2 } val resizer = if (videoInfo != null) { - val rules = compressionRules.getValue(mediaQuality).getValue(videoInfo.resolution.getStandardName()) - Log.d("VideoCompressionHelper", "Video resizer: ${videoInfo.resolution.width}x${videoInfo.resolution.height} -> ${rules.width}x${rules.height} (${rules.description})") + val rules = + compressionRules + .getValue(mediaQuality) + .getValue(videoInfo.resolution.getStandardName()) + Log.d( + "VideoCompressionHelper", + "Resizer: ${videoInfo.resolution.width}x${videoInfo.resolution.height} -> " + + "${rules.width}x${rules.height} (${rules.description})", + ) VideoResizer.limitSize(rules.width.toDouble(), rules.height.toDouble()) } else { - // null VideoResizer should result in unchanged resolution - Log.d("VideoCompressionHelper", "Video resizer: null (original resolution preserved)") + Log.d("VideoCompressionHelper", "Resizer: null (original resolution preserved)") null } - // Get original file size for compression reporting - val originalSize = - try { - applicationContext.contentResolver.openInputStream(uri)?.use { inputStream -> - inputStream.available().toLong() - } ?: 0L - } catch (e: Exception) { - Log.w("VideoCompressionHelper", "Failed to get original file size: ${e.message}") - 0L - } + // Get original file size safely + val originalSize = applicationContext.getFileSize(uri) val result = - withTimeoutOrNull(30000) { + withTimeoutOrNull(timeoutMs) { suspendCancellableCoroutine { continuation -> VideoCompressor.start( - // => This is required context = applicationContext, - // => Source can be provided as content uris uris = listOf(uri), isStreamable = true, - // THIS STORAGE - // sharedStorageConfiguration = SharedStorageConfiguration( - // saveAt = SaveLocation.movies, // => default is movies - // videoName = "compressed_video" // => required name - // ), - // OR AND NOT BOTH storageConfiguration = AppSpecificStorageConfiguration(), configureWith = Configuration( videoBitrateInMbps = videoBitrateInMbps, resizer = resizer, - // => required name videoNames = listOf(UUID.randomUUID().toString()), isMinBitrateCheckEnabled = false, ), listener = object : CompressionListener { + override fun onStart(index: Int) {} + override fun onProgress( index: Int, percent: Float, - ) { - } - - override fun onStart(index: Int) {} + ) {} override fun onSuccess( index: Int, size: Long, path: String?, ) { - if (path != null) { - val reductionPercent = - if (originalSize > 0) { - ((originalSize - size) * 100.0 / originalSize).toInt() - } else { - 0 - } + if (path == null) { + applicationContext.notifyUser( + "Video compression succeeded, but path was null", + "VideoCompressionHelper", + Log.WARN, + ) + if (continuation.isActive) continuation.resume(null) + return + } - // Sanity check: if compressed file is larger than original, return original - if (originalSize > 0 && size >= originalSize) { - Log.d("VideoCompressionHelper", "Compressed file ($size bytes) is larger than original ($originalSize bytes). Using original file.") - applicationContext.showToast("Video compression didn't reduce size. Using original file.") - continuation.resume(MediaCompressorResult(uri, contentType, null)) - return + val reductionPercent = + if (originalSize > 0) { + ((originalSize - size) * 100.0 / originalSize).toInt() + } else { + 0 } - if (originalSize > 0 && size > 0) { - val sizeLabel = formatFileSize(applicationContext, size) - val percentLabel = if (reductionPercent >= 0) "-$reductionPercent%" else "+${-reductionPercent}%" - - applicationContext.showToast("Video compressed: $sizeLabel ($percentLabel)") + // Sanity check: compression not smaller than original + if (originalSize > 0 && size >= originalSize) { + applicationContext.notifyUser( + "Compressed file larger than original. Using original.", + "VideoCompressionHelper", + Log.WARN, + ) + if (continuation.isActive) { + continuation.resume( + MediaCompressorResult(uri, contentType, null), + ) } - Log.d("VideoCompressionHelper", "Video compression success. Original size [$originalSize] -> Compressed size [$size] ($reductionPercent% reduction)") - continuation.resume(MediaCompressorResult(Uri.fromFile(File(path)), contentType, size)) - } else { - Log.d("VideoCompressionHelper", "Video compression successful, but returned null path") - continuation.resume(null) + return + } + + // Show compression result + if (originalSize > 0 && size > 0) { + val sizeLabel = formatFileSize(applicationContext, size) + val percentLabel = + if (reductionPercent >= 0) "-$reductionPercent%" else "+${-reductionPercent}%" + applicationContext.notifyUser( + "Video compressed: $sizeLabel ($percentLabel)", + "VideoCompressionHelper", + ) + } + + Log.d( + "VideoCompressionHelper", + "Compression success: Original [$originalSize] -> " + + "Compressed [$size] ($reductionPercent% reduction)", + ) + + if (continuation.isActive) { + continuation.resume( + MediaCompressorResult(Uri.fromFile(File(path)), contentType, size), + ) } } @@ -241,13 +265,17 @@ class VideoCompressionHelper { index: Int, failureMessage: String, ) { - Log.d("VideoCompressionHelper", "Video compression failed: $failureMessage") - // keeps going with original video - continuation.resume(null) + applicationContext.notifyUser( + "Video compression failed: $failureMessage", + "VideoCompressionHelper", + Log.ERROR, + ) + if (continuation.isActive) continuation.resume(null) } override fun onCancelled(index: Int) { - continuation.resume(null) + Log.w("VideoCompressionHelper", "Video compression cancelled") + if (continuation.isActive) continuation.resume(null) } }, ) @@ -257,13 +285,31 @@ class VideoCompressionHelper { return result ?: MediaCompressorResult(uri, contentType, null) } - private fun Context.showToast( + private fun Context.getFileSize(uri: Uri): Long = + try { + contentResolver.query(uri, arrayOf(android.provider.OpenableColumns.SIZE), null, null, null)?.use { cursor -> + val sizeIndex = cursor.getColumnIndex(android.provider.OpenableColumns.SIZE) + if (cursor.moveToFirst()) cursor.getLong(sizeIndex) else 0L + } ?: 0L + } catch (e: Exception) { + Log.w("VideoCompressionHelper", "Failed to get file size: ${e.message}") + 0L + } + + private fun Context.notifyUser( message: String, + logTag: String, + logLevel: Int = Log.DEBUG, duration: Int = Toast.LENGTH_LONG, ) { Handler(Looper.getMainLooper()).post { Toast.makeText(this, message, duration).show() } + when (logLevel) { + Log.ERROR -> Log.e(logTag, message) + Log.WARN -> Log.w(logTag, message) + else -> Log.d(logTag, message) + } } private fun getVideoInfo( From b6dd6a988b58007fbdc7b7f20ece9ee07ca8f7ae Mon Sep 17 00:00:00 2001 From: davotoula Date: Mon, 22 Sep 2025 21:33:12 +0200 Subject: [PATCH 13/19] change to enum for video resolutions --- .../service/uploads/VideoCompressionHelper.kt | 88 +++++++++++-------- 1 file changed, 52 insertions(+), 36 deletions(-) diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/VideoCompressionHelper.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/VideoCompressionHelper.kt index 9a6033fb8..e622c798e 100644 --- a/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/VideoCompressionHelper.kt +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/VideoCompressionHelper.kt @@ -51,19 +51,35 @@ data class VideoResolution( ) { val pixels: Int get() = width * height - fun getStandardName(): String = + fun getStandard(): VideoStandard = when { - pixels >= 3840 * 2160 -> "4K" - pixels >= 2560 * 1440 -> "1440p" - pixels >= 1920 * 1080 -> "1080p" - pixels >= 1280 * 720 -> "720p" - pixels >= 854 * 480 -> "480p" - pixels >= 640 * 360 -> "360p" - pixels >= 426 * 240 -> "240p" - else -> "${width}x$height" + pixels >= 3840 * 2160 -> VideoStandard.UHD_4K + pixels >= 2560 * 1440 -> VideoStandard.QHD_1440P + pixels >= 1920 * 1080 -> VideoStandard.FHD_1080P + pixels >= 1280 * 720 -> VideoStandard.HD_720P + pixels >= 854 * 480 -> VideoStandard.SD_480P + pixels >= 640 * 360 -> VideoStandard.NHD_360P + pixels >= 426 * 240 -> VideoStandard.QVGA_240P + else -> VideoStandard.UNKNOWN } } +enum class VideoStandard( + val label: String, +) { + UHD_4K("4K"), + QHD_1440P("1440p"), + FHD_1080P("1080p"), + HD_720P("720p"), + SD_480P("480p"), + NHD_360P("360p"), + QVGA_240P("240p"), + UNKNOWN("unknown"), + ; + + override fun toString(): String = label +} + data class CompressionRule( val width: Int, val height: Int, @@ -86,36 +102,36 @@ class VideoCompressionHelper { mapOf( CompressorQuality.LOW to mapOf( - "4K" to CompressionRule(1280, 720, 2f, "4K→720p, 2Mbps"), - "1440p" to CompressionRule(1280, 720, 2f, "1440p→720p, 2Mbps"), - "1080p" to CompressionRule(854, 480, 1f, "1080p→480p, 1Mbps"), - "720p" to CompressionRule(640, 360, 1f, "720p→360p, 1Mbps"), - "480p" to CompressionRule(426, 240, 1f, "480p→240p, 1Mbps"), - "360p" to CompressionRule(426, 240, 0.3f, "360p→240p, 0.3Mbps"), - "240p" to CompressionRule(320, 180, 0.2f, "240p→180p, 0.2Mbps"), - "default" to CompressionRule(854, 480, 1f, "Low quality fallback, 1Mbps"), + VideoStandard.UHD_4K to CompressionRule(1280, 720, 2f, "4K→720p, 2Mbps"), + VideoStandard.QHD_1440P to CompressionRule(1280, 720, 2f, "1440p→720p, 2Mbps"), + VideoStandard.FHD_1080P to CompressionRule(854, 480, 1f, "1080p→480p, 1Mbps"), + VideoStandard.HD_720P to CompressionRule(640, 360, 1f, "720p→360p, 1Mbps"), + VideoStandard.SD_480P to CompressionRule(426, 240, 1f, "480p→240p, 1Mbps"), + VideoStandard.NHD_360P to CompressionRule(426, 240, 0.3f, "360p→240p, 0.3Mbps"), + VideoStandard.QVGA_240P to CompressionRule(320, 180, 0.2f, "240p→180p, 0.2Mbps"), + VideoStandard.UNKNOWN to CompressionRule(854, 480, 1f, "Low quality fallback, 1Mbps"), ), CompressorQuality.MEDIUM to mapOf( - "4K" to CompressionRule(1920, 1080, 6f, "4K→1080p, 6Mbps"), - "1440p" to CompressionRule(1920, 1080, 6f, "1440p→1080p, 6Mbps"), - "1080p" to CompressionRule(1280, 720, 3f, "1080p→720p, 3Mbps"), - "720p" to CompressionRule(854, 480, 2f, "720p→480p, 2Mbps"), - "480p" to CompressionRule(640, 360, 1f, "480p→360p, 1Mbps"), - "360p" to CompressionRule(426, 240, 0.5f, "360p→240p, 0.5Mbps"), - "240p" to CompressionRule(320, 180, 0.3f, "240p→180p, 0.3Mbps"), - "default" to CompressionRule(1280, 720, 2f, "Medium quality fallback, 2Mbps"), + VideoStandard.UHD_4K to CompressionRule(1920, 1080, 6f, "4K→1080p, 6Mbps"), + VideoStandard.QHD_1440P to CompressionRule(1920, 1080, 6f, "1440p→1080p, 6Mbps"), + VideoStandard.FHD_1080P to CompressionRule(1280, 720, 3f, "1080p→720p, 3Mbps"), + VideoStandard.HD_720P to CompressionRule(854, 480, 2f, "720p→480p, 2Mbps"), + VideoStandard.SD_480P to CompressionRule(640, 360, 1f, "480p→360p, 1Mbps"), + VideoStandard.NHD_360P to CompressionRule(426, 240, 0.5f, "360p→240p, 0.5Mbps"), + VideoStandard.QVGA_240P to CompressionRule(320, 180, 0.3f, "240p→180p, 0.3Mbps"), + VideoStandard.UNKNOWN to CompressionRule(1280, 720, 2f, "Medium quality fallback, 2Mbps"), ), CompressorQuality.HIGH to mapOf( - "4K" to CompressionRule(3840, 2160, 16f, "4K→4K, 16Mbps"), - "1440p" to CompressionRule(1920, 1080, 8f, "1440p→1080p, 8Mbps"), - "1080p" to CompressionRule(1920, 1080, 6f, "1080p→1080p, 6Mbps"), - "720p" to CompressionRule(1280, 720, 3f, "720p→720p, 3Mbps"), - "480p" to CompressionRule(854, 480, 2f, "480p→480p, 2Mbps"), - "360p" to CompressionRule(640, 360, 1f, "360p→360p, 1Mbps"), - "240p" to CompressionRule(426, 240, 0.5f, "240p→240p, 0.5Mbps"), - "default" to CompressionRule(1920, 1080, 3f, "High quality fallback, 3Mbps"), + VideoStandard.UHD_4K to CompressionRule(3840, 2160, 16f, "4K→4K, 16Mbps"), + VideoStandard.QHD_1440P to CompressionRule(1920, 1080, 8f, "1440p→1080p, 8Mbps"), + VideoStandard.FHD_1080P to CompressionRule(1920, 1080, 6f, "1080p→1080p, 6Mbps"), + VideoStandard.HD_720P to CompressionRule(1280, 720, 3f, "720p→720p, 3Mbps"), + VideoStandard.SD_480P to CompressionRule(854, 480, 2f, "480p→480p, 2Mbps"), + VideoStandard.NHD_360P to CompressionRule(640, 360, 1f, "360p→360p, 1Mbps"), + VideoStandard.QVGA_240P to CompressionRule(426, 240, 0.5f, "240p→240p, 0.5Mbps"), + VideoStandard.UNKNOWN to CompressionRule(1920, 1080, 3f, "High quality fallback, 3Mbps"), ), ) } @@ -134,7 +150,7 @@ class VideoCompressionHelper { val baseBitrate = compressionRules .getValue(mediaQuality) - .getValue(videoInfo.resolution.getStandardName()) + .getValue(videoInfo.resolution.getStandard()) .getBitrateMbpsInt() // Apply 1.5x multiplier for 60fps+ @@ -147,7 +163,7 @@ class VideoCompressionHelper { Log.d( "VideoCompressionHelper", - "Bitrate: ${adjusted}Mbps for ${videoInfo.resolution.getStandardName()} " + + "Bitrate: ${adjusted}Mbps for ${videoInfo.resolution.getStandard()} " + "quality=$mediaQuality framerate=${videoInfo.framerate}fps", ) adjusted @@ -161,7 +177,7 @@ class VideoCompressionHelper { val rules = compressionRules .getValue(mediaQuality) - .getValue(videoInfo.resolution.getStandardName()) + .getValue(videoInfo.resolution.getStandard()) Log.d( "VideoCompressionHelper", "Resizer: ${videoInfo.resolution.width}x${videoInfo.resolution.height} -> " + From 41a233d1757f7644179563a1a01c2af1bc7c42f7 Mon Sep 17 00:00:00 2001 From: davotoula Date: Mon, 22 Sep 2025 22:54:37 +0200 Subject: [PATCH 14/19] fix for library bug. Temp file name with "_temp" is returned instead of final file name --- .../amethyst/service/uploads/VideoCompressionHelper.kt | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/VideoCompressionHelper.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/VideoCompressionHelper.kt index e622c798e..3153797b5 100644 --- a/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/VideoCompressionHelper.kt +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/VideoCompressionHelper.kt @@ -270,9 +270,16 @@ class VideoCompressionHelper { "Compressed [$size] ($reductionPercent% reduction)", ) + // Attempt to correct the path: if it contains "_temp" then remove it + val correctedPath = + if (path.contains("_temp")) { + path.replace("_temp", "") + } else { + path + } if (continuation.isActive) { continuation.resume( - MediaCompressorResult(Uri.fromFile(File(path)), contentType, size), + MediaCompressorResult(Uri.fromFile(File(correctedPath)), contentType, size), ) } } From db9160a6c239196c23fdba96eb08549a726fc4c9 Mon Sep 17 00:00:00 2001 From: davotoula Date: Tue, 23 Sep 2025 09:19:10 +0200 Subject: [PATCH 15/19] finally block ensures release() is called even if exceptions occur --- .../service/uploads/VideoCompressionHelper.kt | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/VideoCompressionHelper.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/VideoCompressionHelper.kt index 3153797b5..94ac64348 100644 --- a/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/VideoCompressionHelper.kt +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/VideoCompressionHelper.kt @@ -338,9 +338,10 @@ class VideoCompressionHelper { private fun getVideoInfo( uri: Uri, context: Context, - ): VideoInfo? = - try { - val retriever = MediaMetadataRetriever() + ): VideoInfo? { + var retriever: MediaMetadataRetriever? = null + return try { + retriever = MediaMetadataRetriever() retriever.setDataSource(context, uri) val width = retriever.prepareVideoWidth() val height = retriever.prepareVideoHeight() @@ -350,8 +351,6 @@ class VideoCompressionHelper { val framerateString = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_CAPTURE_FRAMERATE) val framerate = framerateString?.toFloatOrNull() ?: 30.0f - retriever.release() - if (width != null && height != null && width > 0 && height > 0) { // Account for rotation val resolution = @@ -367,5 +366,12 @@ class VideoCompressionHelper { } catch (e: Exception) { Log.w("VideoCompressionHelper", "Failed to get video resolution: ${e.message}") null + } finally { + try { + retriever?.release() + } catch (e: Exception) { + Log.w("VideoCompressionHelper", "Failed to release MediaMetadataRetriever: ${e.message}") + } } + } } From 544d6d39335a2333ec037b560c15585355a4a529 Mon Sep 17 00:00:00 2001 From: davotoula Date: Tue, 23 Sep 2025 09:20:41 +0200 Subject: [PATCH 16/19] remove plan --- .../service/uploads/MediaCompressor.kt | 18 ------------------ 1 file changed, 18 deletions(-) diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt index 2effe4674..ba24ed61f 100644 --- a/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt @@ -46,24 +46,6 @@ class MediaCompressorResult( val size: Long?, ) -/** The plan - * xxx 1. Check input resolution and input fps - * xxx 2. Create configuration matrix: for each quality level, set bitrate based on input resolution - * xxx 3. Create Configuration with no quality setting, a bitrate setting, resizer, streamable = true, isMinBitrateCheckEnabled=false - * xxx 4. Don't upload converted file if compression results in larger file (return MediaCompressorResult(uri, contentType, null)) - * xxx 5. Add toast message about file size saving - * xxx 6. refactor (helper class for video compression) - * xxx 7. Fix toast for case when compressed file is larger than original - * xxx 8. fix ratio multiplier for framerate ->60 - * - * - * Don't use Configuration.quality which only determines bitrate. Instead let's create aggressive bitrates based on input and selected quality - * H265 is not supported, use bitrates that suit h264 - * Detect fps in source, multiple bitrate by 1.5 if 60fps or higher - * Bitrate floor has to be 1Mbps for now - * Future extension: Modify library to use bps for bitrate instead of Mbps which allows only 1Mbps as lowest and increments of 1 (Int) - * - */ class MediaCompressor { // ALL ERRORS ARE IGNORED. The original file is returned. suspend fun compress( From b030486e7e51e3fe522a3a327225e38d3b45e827 Mon Sep 17 00:00:00 2001 From: davotoula Date: Tue, 23 Sep 2025 09:55:03 +0200 Subject: [PATCH 17/19] fixes after rebase --- .../service/uploads/MediaCompressor.kt | 142 ------------------ 1 file changed, 142 deletions(-) diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt index ba24ed61f..aa508e31c 100644 --- a/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt @@ -23,7 +23,6 @@ package com.vitorpamplona.amethyst.service.uploads import android.content.Context import android.graphics.Bitmap import android.net.Uri -import android.util.Log import androidx.core.net.toUri import androidx.media3.common.MimeTypes import com.vitorpamplona.amethyst.service.checkNotInMainThread @@ -32,13 +31,6 @@ import com.vitorpamplona.quartz.utils.Log import id.zelory.compressor.Compressor import id.zelory.compressor.constraint.default import kotlinx.coroutines.CancellationException -import kotlinx.coroutines.suspendCancellableCoroutine -import kotlinx.coroutines.withTimeoutOrNull -import java.io.File -import kotlin.coroutines.resume -import kotlin.math.roundToInt -import kotlin.uuid.ExperimentalUuidApi -import kotlin.uuid.Uuid class MediaCompressorResult( val uri: Uri, @@ -76,140 +68,6 @@ class MediaCompressor { } } - @OptIn(ExperimentalUuidApi::class) - private suspend fun compressVideo( - uri: Uri, - contentType: String?, - applicationContext: Context, - mediaQuality: CompressorQuality, - ): MediaCompressorResult { - val videoInfo = getVideoInfo(uri, applicationContext) - - val videoBitrateInMbps = - if (videoInfo != null) { - val bitrate = compressionRules.getValue(mediaQuality).getValue(videoInfo.resolution.getStandardName()).getBitrateMbpsInt() - Log.d("MediaCompressor", "Video bitrate calculated: ${bitrate}Mbps for ${videoInfo.resolution.getStandardName()} quality=$mediaQuality") - bitrate - } else { - // Default/fallback logic when videoInfo is null - Log.d("MediaCompressor", "Video bitrate fallback: 2Mbps (videoInfo unavailable)") - 2 - } - - val resizer = - if (videoInfo != null) { - val rules = compressionRules.getValue(mediaQuality).getValue(videoInfo.resolution.getStandardName()) - Log.d("MediaCompressor", "Video resizer: ${videoInfo.resolution.width}x${videoInfo.resolution.height} -> ${rules.width}x${rules.height} (${rules.description})") - VideoResizer.limitSize(rules.width.toDouble(), rules.height.toDouble()) - } else { - // null VideoResizer should result in unchanged resolution - Log.d("MediaCompressor", "Video resizer: null (original resolution preserved)") - null - } - - // Get original file size for compression reporting - val originalSize = - try { - applicationContext.contentResolver.openInputStream(uri)?.use { inputStream -> - inputStream.available().toLong() - } ?: 0L - } catch (e: Exception) { - Log.w("MediaCompressor", "Failed to get original file size: ${e.message}") - 0L - } - - val result = - withTimeoutOrNull(30000) { - suspendCancellableCoroutine { continuation -> - VideoCompressor.start( - // => This is required - context = applicationContext, - // => Source can be provided as content uris - uris = listOf(uri), - isStreamable = true, - // THIS STORAGE - // sharedStorageConfiguration = SharedStorageConfiguration( - // saveAt = SaveLocation.movies, // => default is movies - // videoName = "compressed_video" // => required name - // ), - // OR AND NOT BOTH - storageConfiguration = AppSpecificStorageConfiguration(), - configureWith = - Configuration( - videoBitrateInMbps = videoBitrateInMbps, - resizer = resizer, - // => required name - videoNames = listOf(Uuid.random().toString()), - isMinBitrateCheckEnabled = false, - ), - listener = - object : CompressionListener { - override fun onProgress( - index: Int, - percent: Float, - ) {} - - override fun onStart(index: Int) {} - - override fun onSuccess( - index: Int, - size: Long, - path: String?, - ) { - if (path != null) { - // Sanity check: if compressed file is larger than original, return original - if (originalSize > 0 && size >= originalSize) { - Log.d("MediaCompressor", "Compressed file ($size bytes) is larger than original ($originalSize bytes). Using original file.") - continuation.resume(MediaCompressorResult(uri, contentType, null)) - return - } - - val reductionPercent = - if (originalSize > 0) { - ((originalSize - size) * 100.0 / originalSize).toInt() - } else { - 0 - } - - // Show compression result toast - if (originalSize > 0 && size > 0) { - val message = - "Video compressed: ${formatFileSize(applicationContext, size)} " + - "(${if (reductionPercent > 0) "-$reductionPercent%" else "+${-reductionPercent}%"})" - - // Post on main thread for Toast - android.os.Handler(android.os.Looper.getMainLooper()).post { - Toast.makeText(applicationContext, message, Toast.LENGTH_LONG).show() - } - } - Log.d("MediaCompressor", "Video compression success. Original size [$originalSize] -> Compressed size [$size] ($reductionPercent% reduction)") - continuation.resume(MediaCompressorResult(Uri.fromFile(File(path)), contentType, size)) - } else { - Log.d("MediaCompressor", "Video compression successful, but returned null path") - continuation.resume(null) - } - } - - override fun onFailure( - index: Int, - failureMessage: String, - ) { - Log.d("MediaCompressor", "Video compression failed: $failureMessage") - // keeps going with original video - continuation.resume(null) - } - - override fun onCancelled(index: Int) { - continuation.resume(null) - } - }, - ) - } - } - - return result ?: MediaCompressorResult(uri, contentType, null) - } - private suspend fun compressImage( uri: Uri, contentType: String?, From e5df870ace505da2acf987c604e75216b19e1c2e Mon Sep 17 00:00:00 2001 From: davotoula Date: Tue, 23 Sep 2025 10:24:48 +0200 Subject: [PATCH 18/19] move framerate adjustment into getBitrateMbpsInt to prevent ,precision errors Clean up logging --- .../service/uploads/VideoCompressionHelper.kt | 59 ++++++++----------- 1 file changed, 23 insertions(+), 36 deletions(-) diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/VideoCompressionHelper.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/VideoCompressionHelper.kt index 94ac64348..7ce6cdb98 100644 --- a/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/VideoCompressionHelper.kt +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/VideoCompressionHelper.kt @@ -86,18 +86,19 @@ data class CompressionRule( val bitrateMbps: Float, val description: String, ) { - fun getBitrateMbpsInt(): Int { + fun getBitrateMbpsInt(framerate: Float): Int { + // Apply 1.5x multiplier for 60fps+ videos + val multiplier = if (framerate >= 60f) 1.5f else 1.0f + // Library doesn't support float so we have to convert it to int and use 1 as minimum - return if (bitrateMbps < 1) { - 1 - } else { - bitrateMbps.roundToInt() - } + return (bitrateMbps * multiplier).roundToInt().coerceAtLeast(1) } } class VideoCompressionHelper { companion object { + private const val LOG_TAG = "VideoCompressionHelper" + private val compressionRules = mapOf( CompressorQuality.LOW to @@ -147,28 +148,19 @@ class VideoCompressionHelper { val videoBitrateInMbps = if (videoInfo != null) { - val baseBitrate = + val bitrateMbpsInt = compressionRules .getValue(mediaQuality) .getValue(videoInfo.resolution.getStandard()) - .getBitrateMbpsInt() - - // Apply 1.5x multiplier for 60fps+ - val adjusted = - if (videoInfo.framerate >= 60f) { - (baseBitrate * 1.5f).roundToInt() - } else { - baseBitrate - } + .getBitrateMbpsInt(videoInfo.framerate) Log.d( - "VideoCompressionHelper", - "Bitrate: ${adjusted}Mbps for ${videoInfo.resolution.getStandard()} " + - "quality=$mediaQuality framerate=${videoInfo.framerate}fps", + LOG_TAG, + "Bitrate: ${bitrateMbpsInt}Mbps for ${videoInfo.resolution.getStandard()} " + + "quality=$mediaQuality framerate=${videoInfo.framerate}fps.", ) - adjusted } else { - Log.w("VideoCompressionHelper", "Video bitrate fallback: 2Mbps (videoInfo unavailable)") + Log.w(LOG_TAG, "Video bitrate fallback: 2Mbps (videoInfo unavailable)") 2 } @@ -179,13 +171,13 @@ class VideoCompressionHelper { .getValue(mediaQuality) .getValue(videoInfo.resolution.getStandard()) Log.d( - "VideoCompressionHelper", + LOG_TAG, "Resizer: ${videoInfo.resolution.width}x${videoInfo.resolution.height} -> " + "${rules.width}x${rules.height} (${rules.description})", ) VideoResizer.limitSize(rules.width.toDouble(), rules.height.toDouble()) } else { - Log.d("VideoCompressionHelper", "Resizer: null (original resolution preserved)") + Log.d(LOG_TAG, "Resizer: null (original resolution preserved)") null } @@ -224,7 +216,6 @@ class VideoCompressionHelper { if (path == null) { applicationContext.notifyUser( "Video compression succeeded, but path was null", - "VideoCompressionHelper", Log.WARN, ) if (continuation.isActive) continuation.resume(null) @@ -242,7 +233,6 @@ class VideoCompressionHelper { if (originalSize > 0 && size >= originalSize) { applicationContext.notifyUser( "Compressed file larger than original. Using original.", - "VideoCompressionHelper", Log.WARN, ) if (continuation.isActive) { @@ -260,12 +250,11 @@ class VideoCompressionHelper { if (reductionPercent >= 0) "-$reductionPercent%" else "+${-reductionPercent}%" applicationContext.notifyUser( "Video compressed: $sizeLabel ($percentLabel)", - "VideoCompressionHelper", ) } Log.d( - "VideoCompressionHelper", + LOG_TAG, "Compression success: Original [$originalSize] -> " + "Compressed [$size] ($reductionPercent% reduction)", ) @@ -290,14 +279,13 @@ class VideoCompressionHelper { ) { applicationContext.notifyUser( "Video compression failed: $failureMessage", - "VideoCompressionHelper", Log.ERROR, ) if (continuation.isActive) continuation.resume(null) } override fun onCancelled(index: Int) { - Log.w("VideoCompressionHelper", "Video compression cancelled") + Log.w(LOG_TAG, "Video compression cancelled") if (continuation.isActive) continuation.resume(null) } }, @@ -315,13 +303,12 @@ class VideoCompressionHelper { if (cursor.moveToFirst()) cursor.getLong(sizeIndex) else 0L } ?: 0L } catch (e: Exception) { - Log.w("VideoCompressionHelper", "Failed to get file size: ${e.message}") + Log.w(LOG_TAG, "Failed to get file size: ${e.message}") 0L } private fun Context.notifyUser( message: String, - logTag: String, logLevel: Int = Log.DEBUG, duration: Int = Toast.LENGTH_LONG, ) { @@ -329,9 +316,9 @@ class VideoCompressionHelper { Toast.makeText(this, message, duration).show() } when (logLevel) { - Log.ERROR -> Log.e(logTag, message) - Log.WARN -> Log.w(logTag, message) - else -> Log.d(logTag, message) + Log.ERROR -> Log.e(LOG_TAG, message) + Log.WARN -> Log.w(LOG_TAG, message) + else -> Log.d(LOG_TAG, message) } } @@ -364,13 +351,13 @@ class VideoCompressionHelper { null } } catch (e: Exception) { - Log.w("VideoCompressionHelper", "Failed to get video resolution: ${e.message}") + Log.w(LOG_TAG, "Failed to get video resolution: ${e.message}") null } finally { try { retriever?.release() } catch (e: Exception) { - Log.w("VideoCompressionHelper", "Failed to release MediaMetadataRetriever: ${e.message}") + Log.w(LOG_TAG, "Failed to release MediaMetadataRetriever: ${e.message}") } } } From ccc5d03d84482f17e7f27ebc54bf930d78bcbab9 Mon Sep 17 00:00:00 2001 From: davotoula Date: Tue, 23 Sep 2025 11:28:09 +0200 Subject: [PATCH 19/19] converted VideoCompressionHelper to singleton --- .../service/uploads/MediaCompressor.kt | 3 +- .../service/uploads/VideoCompressionHelper.kt | 78 +++++++++---------- 2 files changed, 39 insertions(+), 42 deletions(-) diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt index aa508e31c..0b506c4dc 100644 --- a/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/MediaCompressor.kt @@ -57,8 +57,7 @@ class MediaCompressor { // branch into compression based on content type return when { contentType?.startsWith("video", ignoreCase = true) == true -> { - val helper = VideoCompressionHelper() - helper.compressVideo(uri, contentType, applicationContext, mediaQuality) + VideoCompressionHelper.compressVideo(uri, contentType, applicationContext, mediaQuality) } contentType?.startsWith("image", ignoreCase = true) == true && !contentType.contains("gif") && diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/VideoCompressionHelper.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/VideoCompressionHelper.kt index 7ce6cdb98..894b40708 100644 --- a/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/VideoCompressionHelper.kt +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/service/uploads/VideoCompressionHelper.kt @@ -95,47 +95,45 @@ data class CompressionRule( } } -class VideoCompressionHelper { - companion object { - private const val LOG_TAG = "VideoCompressionHelper" +object VideoCompressionHelper { + private const val LOG_TAG = "VideoCompressionHelper" - private val compressionRules = - mapOf( - CompressorQuality.LOW to - mapOf( - VideoStandard.UHD_4K to CompressionRule(1280, 720, 2f, "4K→720p, 2Mbps"), - VideoStandard.QHD_1440P to CompressionRule(1280, 720, 2f, "1440p→720p, 2Mbps"), - VideoStandard.FHD_1080P to CompressionRule(854, 480, 1f, "1080p→480p, 1Mbps"), - VideoStandard.HD_720P to CompressionRule(640, 360, 1f, "720p→360p, 1Mbps"), - VideoStandard.SD_480P to CompressionRule(426, 240, 1f, "480p→240p, 1Mbps"), - VideoStandard.NHD_360P to CompressionRule(426, 240, 0.3f, "360p→240p, 0.3Mbps"), - VideoStandard.QVGA_240P to CompressionRule(320, 180, 0.2f, "240p→180p, 0.2Mbps"), - VideoStandard.UNKNOWN to CompressionRule(854, 480, 1f, "Low quality fallback, 1Mbps"), - ), - CompressorQuality.MEDIUM to - mapOf( - VideoStandard.UHD_4K to CompressionRule(1920, 1080, 6f, "4K→1080p, 6Mbps"), - VideoStandard.QHD_1440P to CompressionRule(1920, 1080, 6f, "1440p→1080p, 6Mbps"), - VideoStandard.FHD_1080P to CompressionRule(1280, 720, 3f, "1080p→720p, 3Mbps"), - VideoStandard.HD_720P to CompressionRule(854, 480, 2f, "720p→480p, 2Mbps"), - VideoStandard.SD_480P to CompressionRule(640, 360, 1f, "480p→360p, 1Mbps"), - VideoStandard.NHD_360P to CompressionRule(426, 240, 0.5f, "360p→240p, 0.5Mbps"), - VideoStandard.QVGA_240P to CompressionRule(320, 180, 0.3f, "240p→180p, 0.3Mbps"), - VideoStandard.UNKNOWN to CompressionRule(1280, 720, 2f, "Medium quality fallback, 2Mbps"), - ), - CompressorQuality.HIGH to - mapOf( - VideoStandard.UHD_4K to CompressionRule(3840, 2160, 16f, "4K→4K, 16Mbps"), - VideoStandard.QHD_1440P to CompressionRule(1920, 1080, 8f, "1440p→1080p, 8Mbps"), - VideoStandard.FHD_1080P to CompressionRule(1920, 1080, 6f, "1080p→1080p, 6Mbps"), - VideoStandard.HD_720P to CompressionRule(1280, 720, 3f, "720p→720p, 3Mbps"), - VideoStandard.SD_480P to CompressionRule(854, 480, 2f, "480p→480p, 2Mbps"), - VideoStandard.NHD_360P to CompressionRule(640, 360, 1f, "360p→360p, 1Mbps"), - VideoStandard.QVGA_240P to CompressionRule(426, 240, 0.5f, "240p→240p, 0.5Mbps"), - VideoStandard.UNKNOWN to CompressionRule(1920, 1080, 3f, "High quality fallback, 3Mbps"), - ), - ) - } + private val compressionRules = + mapOf( + CompressorQuality.LOW to + mapOf( + VideoStandard.UHD_4K to CompressionRule(1280, 720, 2f, "4K→720p, 2Mbps"), + VideoStandard.QHD_1440P to CompressionRule(1280, 720, 2f, "1440p→720p, 2Mbps"), + VideoStandard.FHD_1080P to CompressionRule(854, 480, 1f, "1080p→480p, 1Mbps"), + VideoStandard.HD_720P to CompressionRule(640, 360, 1f, "720p→360p, 1Mbps"), + VideoStandard.SD_480P to CompressionRule(426, 240, 1f, "480p→240p, 1Mbps"), + VideoStandard.NHD_360P to CompressionRule(426, 240, 0.3f, "360p→240p, 0.3Mbps"), + VideoStandard.QVGA_240P to CompressionRule(320, 180, 0.2f, "240p→180p, 0.2Mbps"), + VideoStandard.UNKNOWN to CompressionRule(854, 480, 1f, "Low quality fallback, 1Mbps"), + ), + CompressorQuality.MEDIUM to + mapOf( + VideoStandard.UHD_4K to CompressionRule(1920, 1080, 6f, "4K→1080p, 6Mbps"), + VideoStandard.QHD_1440P to CompressionRule(1920, 1080, 6f, "1440p→1080p, 6Mbps"), + VideoStandard.FHD_1080P to CompressionRule(1280, 720, 3f, "1080p→720p, 3Mbps"), + VideoStandard.HD_720P to CompressionRule(854, 480, 2f, "720p→480p, 2Mbps"), + VideoStandard.SD_480P to CompressionRule(640, 360, 1f, "480p→360p, 1Mbps"), + VideoStandard.NHD_360P to CompressionRule(426, 240, 0.5f, "360p→240p, 0.5Mbps"), + VideoStandard.QVGA_240P to CompressionRule(320, 180, 0.3f, "240p→180p, 0.3Mbps"), + VideoStandard.UNKNOWN to CompressionRule(1280, 720, 2f, "Medium quality fallback, 2Mbps"), + ), + CompressorQuality.HIGH to + mapOf( + VideoStandard.UHD_4K to CompressionRule(3840, 2160, 16f, "4K→4K, 16Mbps"), + VideoStandard.QHD_1440P to CompressionRule(1920, 1080, 8f, "1440p→1080p, 8Mbps"), + VideoStandard.FHD_1080P to CompressionRule(1920, 1080, 6f, "1080p→1080p, 6Mbps"), + VideoStandard.HD_720P to CompressionRule(1280, 720, 3f, "720p→720p, 3Mbps"), + VideoStandard.SD_480P to CompressionRule(854, 480, 2f, "480p→480p, 2Mbps"), + VideoStandard.NHD_360P to CompressionRule(640, 360, 1f, "360p→360p, 1Mbps"), + VideoStandard.QVGA_240P to CompressionRule(426, 240, 0.5f, "240p→240p, 0.5Mbps"), + VideoStandard.UNKNOWN to CompressionRule(1920, 1080, 3f, "High quality fallback, 3Mbps"), + ), + ) suspend fun compressVideo( uri: Uri,