This commit is contained in:
Benoit Marty 2021-07-13 18:16:30 +02:00
parent c938a30dd9
commit df795d1881
1 changed files with 27 additions and 21 deletions

View File

@ -16,6 +16,7 @@
package org.matrix.android.sdk.internal.session.room.send package org.matrix.android.sdk.internal.session.room.send
import timber.log.Timber
import javax.inject.Inject import javax.inject.Inject
import kotlin.math.abs import kotlin.math.abs
import kotlin.math.ceil import kotlin.math.ceil
@ -38,43 +39,48 @@ internal class WaveFormSanitizer @Inject constructor() {
} }
// Limit the number of items // Limit the number of items
val result = mutableListOf<Int>() val sizeInRangeList = mutableListOf<Int>()
if (waveForm.size < MIN_NUMBER_OF_VALUES) { when {
waveForm.size < MIN_NUMBER_OF_VALUES -> {
// Repeat the same value to have at least 30 items // Repeat the same value to have at least 30 items
val repeatTimes = ceil(MIN_NUMBER_OF_VALUES / waveForm.size.toDouble()).toInt() val repeatTimes = ceil(MIN_NUMBER_OF_VALUES / waveForm.size.toDouble()).toInt()
waveForm.map { value -> waveForm.map { value ->
repeat(repeatTimes) { repeat(repeatTimes) {
result.add(value) sizeInRangeList.add(value)
} }
} }
} else if (waveForm.size > MAX_NUMBER_OF_VALUES) { }
waveForm.size > MAX_NUMBER_OF_VALUES -> {
val keepOneOf = ceil(waveForm.size.toDouble() / MAX_NUMBER_OF_VALUES).toInt() val keepOneOf = ceil(waveForm.size.toDouble() / MAX_NUMBER_OF_VALUES).toInt()
waveForm.mapIndexed { idx, value -> waveForm.mapIndexed { idx, value ->
if (idx % keepOneOf == 0) { if (idx % keepOneOf == 0) {
result.add(value) sizeInRangeList.add(value)
} }
} }
} else { }
result.addAll(waveForm) else -> {
sizeInRangeList.addAll(waveForm)
}
} }
// OK, ensure all items are positive // OK, ensure all items are positive
val limited = result.map { val positiveList = sizeInRangeList.map {
abs(it) abs(it)
} }
// Ensure max is not above MAX_VALUE // Ensure max is not above MAX_VALUE
val max = limited.maxOrNull() ?: MAX_VALUE val max = positiveList.maxOrNull() ?: MAX_VALUE
val final = if (max > MAX_VALUE) { val finalList = if (max > MAX_VALUE) {
// Reduce the range // Reduce the values
limited.map { positiveList.map {
it * MAX_VALUE / max it * MAX_VALUE / max
} }
} else { } else {
limited positiveList
} }
return final Timber.d("Sanitize from ${waveForm.size} items to ${finalList.size} items")
return finalList
} }
} }