|
8 | 8 | package io.element.android.libraries.mediaupload.impl
|
9 | 9 |
|
10 | 10 | import android.content.Context
|
| 11 | +import android.media.MediaMetadataRetriever |
11 | 12 | import android.net.Uri
|
| 13 | +import android.webkit.MimeTypeMap |
12 | 14 | import com.otaliastudios.transcoder.Transcoder
|
13 | 15 | import com.otaliastudios.transcoder.TranscoderListener
|
| 16 | +import com.otaliastudios.transcoder.internal.media.MediaFormatConstants |
14 | 17 | import com.otaliastudios.transcoder.resize.AtMostResizer
|
15 | 18 | import com.otaliastudios.transcoder.strategy.DefaultVideoStrategy
|
| 19 | +import com.otaliastudios.transcoder.strategy.PassThroughTrackStrategy |
| 20 | +import com.otaliastudios.transcoder.strategy.TrackStrategy |
| 21 | +import com.otaliastudios.transcoder.validator.WriteAlwaysValidator |
16 | 22 | import io.element.android.libraries.androidutils.file.createTmpFile
|
| 23 | +import io.element.android.libraries.androidutils.file.getMimeType |
17 | 24 | import io.element.android.libraries.androidutils.file.safeDelete
|
18 | 25 | import io.element.android.libraries.di.ApplicationContext
|
19 | 26 | import kotlinx.coroutines.channels.awaitClose
|
20 | 27 | import kotlinx.coroutines.flow.callbackFlow
|
| 28 | +import timber.log.Timber |
21 | 29 | import java.io.File
|
22 | 30 | import javax.inject.Inject
|
23 | 31 |
|
| 32 | +private const val MP4_EXTENSION = "mp4" |
| 33 | + |
24 | 34 | class VideoCompressor @Inject constructor(
|
25 | 35 | @ApplicationContext private val context: Context,
|
26 | 36 | ) {
|
27 | 37 | fun compress(uri: Uri, shouldBeCompressed: Boolean) = callbackFlow {
|
28 |
| - val tmpFile = context.createTmpFile(extension = "mp4") |
| 38 | + val metadata = getVideoMetadata(uri) |
| 39 | + |
| 40 | + val expectedExtension = MimeTypeMap.getSingleton().getExtensionFromMimeType(context.getMimeType(uri)) |
| 41 | + |
| 42 | + val videoStrategy = VideoStrategyFactory.create( |
| 43 | + expectedExtension = expectedExtension, |
| 44 | + metadata = metadata, |
| 45 | + shouldBeCompressed = shouldBeCompressed |
| 46 | + ) |
| 47 | + |
| 48 | + val tmpFile = context.createTmpFile(extension = MP4_EXTENSION) |
29 | 49 | val future = Transcoder.into(tmpFile.path)
|
30 |
| - .setVideoTrackStrategy( |
31 |
| - DefaultVideoStrategy.Builder() |
32 |
| - .addResizer( |
33 |
| - AtMostResizer( |
34 |
| - if (shouldBeCompressed) { |
35 |
| - 720 |
36 |
| - } else { |
37 |
| - 1080 |
38 |
| - } |
39 |
| - ) |
40 |
| - ) |
41 |
| - .build() |
42 |
| - ) |
| 50 | + .setVideoTrackStrategy(videoStrategy) |
43 | 51 | .addDataSource(context, uri)
|
| 52 | + // Force the output to be written, even if no transcoding was actually needed |
| 53 | + .setValidator(WriteAlwaysValidator()) |
44 | 54 | .setListener(object : TranscoderListener {
|
45 | 55 | override fun onTranscodeProgress(progress: Double) {
|
46 | 56 | trySend(VideoTranscodingEvent.Progress(progress.toFloat()))
|
@@ -69,9 +79,86 @@ class VideoCompressor @Inject constructor(
|
69 | 79 | }
|
70 | 80 | }
|
71 | 81 | }
|
| 82 | + |
| 83 | + private fun getVideoMetadata(uri: Uri): VideoFileMetadata? { |
| 84 | + return runCatching { |
| 85 | + MediaMetadataRetriever().use { |
| 86 | + it.setDataSource(context, uri) |
| 87 | + |
| 88 | + val width = it.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH)?.toIntOrNull() ?: -1 |
| 89 | + val height = it.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT)?.toIntOrNull() ?: -1 |
| 90 | + val bitrate = it.extractMetadata(MediaMetadataRetriever.METADATA_KEY_BITRATE)?.toLongOrNull() ?: -1 |
| 91 | + val framerate = it.extractMetadata(MediaMetadataRetriever.METADATA_KEY_CAPTURE_FRAMERATE)?.toIntOrNull() ?: -1 |
| 92 | + |
| 93 | + val (actualWidth, actualHeight) = if (width == -1 || height == -1) { |
| 94 | + // Try getting the first frame instead |
| 95 | + val bitmap = it.getFrameAtTime(0) ?: return null |
| 96 | + bitmap.width to bitmap.height |
| 97 | + } else { |
| 98 | + width to height |
| 99 | + } |
| 100 | + |
| 101 | + VideoFileMetadata( |
| 102 | + width = actualWidth, |
| 103 | + height = actualHeight, |
| 104 | + bitrate = bitrate, |
| 105 | + frameRate = framerate |
| 106 | + ) |
| 107 | + } |
| 108 | + }.onFailure { |
| 109 | + Timber.e(it, "Failed to get video dimensions") |
| 110 | + }.getOrNull() |
| 111 | + } |
72 | 112 | }
|
73 | 113 |
|
| 114 | +internal data class VideoFileMetadata( |
| 115 | + val width: Int?, |
| 116 | + val height: Int?, |
| 117 | + val bitrate: Long?, |
| 118 | + val frameRate: Int?, |
| 119 | +) |
| 120 | + |
74 | 121 | sealed interface VideoTranscodingEvent {
|
75 | 122 | data class Progress(val value: Float) : VideoTranscodingEvent
|
76 | 123 | data class Completed(val file: File) : VideoTranscodingEvent
|
77 | 124 | }
|
| 125 | + |
| 126 | +internal object VideoStrategyFactory { |
| 127 | + // 720p |
| 128 | + private const val MAX_COMPRESSED_PIXEL_SIZE = 1280 |
| 129 | + |
| 130 | + // 1080p |
| 131 | + private const val MAX_PIXEL_SIZE = 1920 |
| 132 | + |
| 133 | + fun create( |
| 134 | + expectedExtension: String?, |
| 135 | + metadata: VideoFileMetadata?, |
| 136 | + shouldBeCompressed: Boolean, |
| 137 | + ): TrackStrategy { |
| 138 | + val width = metadata?.width ?: Int.MAX_VALUE |
| 139 | + val height = metadata?.height ?: Int.MAX_VALUE |
| 140 | + val bitrate = metadata?.bitrate |
| 141 | + val frameRate = metadata?.frameRate |
| 142 | + |
| 143 | + // We only create a resizer if needed |
| 144 | + val resizer = when { |
| 145 | + shouldBeCompressed && (width > MAX_COMPRESSED_PIXEL_SIZE || height > MAX_COMPRESSED_PIXEL_SIZE) -> AtMostResizer(MAX_COMPRESSED_PIXEL_SIZE) |
| 146 | + width > MAX_PIXEL_SIZE || height > MAX_PIXEL_SIZE -> AtMostResizer(MAX_PIXEL_SIZE) |
| 147 | + else -> null |
| 148 | + } |
| 149 | + |
| 150 | + return if (resizer == null && expectedExtension == MP4_EXTENSION) { |
| 151 | + // If there's no transcoding or resizing needed for the video file, just create a new file with the same contents but no metadata |
| 152 | + PassThroughTrackStrategy() |
| 153 | + } else { |
| 154 | + DefaultVideoStrategy.Builder() |
| 155 | + .apply { |
| 156 | + resizer?.let { addResizer(it) } |
| 157 | + bitrate?.let { bitRate(it) } |
| 158 | + frameRate?.let { frameRate(it) } |
| 159 | + } |
| 160 | + .mimeType(MediaFormatConstants.MIMETYPE_VIDEO_AVC) |
| 161 | + .build() |
| 162 | + } |
| 163 | + } |
| 164 | +} |
0 commit comments