Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Manually close ImageDecoder. #1109

Merged
merged 5 commits into from
Jan 27, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
// https://youtrack.jetbrains.com/issue/KTIJ-196
@file:Suppress("SameParameterValue", "UnusedEquals", "UnusedUnaryOperator")
@file:Suppress("SameParameterValue")

package coil.decode

Expand Down
150 changes: 80 additions & 70 deletions coil-gif/src/main/java/coil/decode/ImageDecoderDecoder.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package coil.decode
import android.graphics.ImageDecoder
import android.graphics.drawable.AnimatedImageDrawable
import android.graphics.drawable.AnimatedImageDrawable.REPEAT_INFINITE
import android.graphics.drawable.Drawable
import android.os.Build.VERSION.SDK_INT
import androidx.annotation.RequiresApi
import androidx.core.graphics.decodeDrawable
Expand Down Expand Up @@ -45,76 +46,57 @@ class ImageDecoderDecoder @JvmOverloads constructor(

override suspend fun decode(): DecodeResult {
var isSampled = false
val baseDrawable = withSource { source ->
source.toImageDecoderSource().decodeDrawable { info, _ ->
val (srcWidth, srcHeight) = info.size
val dstWidth = options.size.width.pxOrElse { srcWidth }
val dstHeight = options.size.height.pxOrElse { srcHeight }
if (srcWidth > 0 && srcHeight > 0 &&
(srcWidth != dstWidth || srcHeight != dstHeight)) {
val multiplier = DecodeUtils.computeSizeMultiplier(
srcWidth = srcWidth,
srcHeight = srcHeight,
dstWidth = dstWidth,
dstHeight = dstHeight,
scale = options.scale
)

// Set the target size if the image is larger than the requested dimensions or
// the request requires exact dimensions.
isSampled = multiplier < 1
if (isSampled || !options.allowInexactSize) {
val targetWidth = (multiplier * srcWidth).roundToInt()
val targetHeight = (multiplier * srcHeight).roundToInt()
setTargetSize(targetWidth, targetHeight)
val drawable = runInterruptible {
var imageDecoder: ImageDecoder? = null
val wrappedSource = wrapImageSource(source)
try {
wrappedSource.toImageDecoderSource().decodeDrawable { info, _ ->
// Capture the image decoder to manually close it later.
imageDecoder = this

// Configure the output image's size.
val (srcWidth, srcHeight) = info.size
val dstWidth = options.size.width.pxOrElse { srcWidth }
val dstHeight = options.size.height.pxOrElse { srcHeight }
if (srcWidth > 0 && srcHeight > 0 &&
(srcWidth != dstWidth || srcHeight != dstHeight)) {
val multiplier = DecodeUtils.computeSizeMultiplier(
srcWidth = srcWidth,
srcHeight = srcHeight,
dstWidth = dstWidth,
dstHeight = dstHeight,
scale = options.scale
)

// Set the target size if the image is larger than the requested dimensions
// or the request requires exact dimensions.
isSampled = multiplier < 1
if (isSampled || !options.allowInexactSize) {
val targetWidth = (multiplier * srcWidth).roundToInt()
val targetHeight = (multiplier * srcHeight).roundToInt()
setTargetSize(targetWidth, targetHeight)
}
}
}

allocator = if (options.config.isHardware) {
ImageDecoder.ALLOCATOR_HARDWARE
} else {
ImageDecoder.ALLOCATOR_SOFTWARE
}

memorySizePolicy = if (options.allowRgb565) {
ImageDecoder.MEMORY_POLICY_LOW_RAM
} else {
ImageDecoder.MEMORY_POLICY_DEFAULT
// Configure any other attributes.
configureImageDecoderProperties()
}

if (options.colorSpace != null) {
setTargetColorSpace(options.colorSpace)
}

isUnpremultipliedRequired = !options.premultipliedAlpha

postProcessor = options.parameters.animatedTransformation()?.asPostProcessor()
} finally {
imageDecoder?.close()
wrappedSource.close()
}
}
return DecodeResult(wrapDrawable(drawable), isSampled)
}

val drawable = if (baseDrawable is AnimatedImageDrawable) {
baseDrawable.repeatCount = options.parameters.repeatCount() ?: REPEAT_INFINITE

// Set the start and end animation callbacks if any one is supplied through the request.
val onStart = options.parameters.animationStartCallback()
val onEnd = options.parameters.animationEndCallback()
if (onStart != null || onEnd != null) {
// Animation callbacks must be set on the main thread.
withContext(Dispatchers.Main.immediate) {
baseDrawable.registerAnimationCallback(animatable2CallbackOf(onStart, onEnd))
}
}

// Wrap AnimatedImageDrawable in a ScaleDrawable so it always scales to fill its bounds.
ScaleDrawable(baseDrawable, options.scale)
private fun wrapImageSource(source: ImageSource): ImageSource {
return if (enforceMinimumFrameDelay && DecodeUtils.isGif(source.source())) {
// Wrap the source to rewrite its frame delay as it's read.
val rewritingSource = FrameDelayRewritingSource(source.source())
ImageSource(rewritingSource.buffer(), options.context)
} else {
baseDrawable
source
}

return DecodeResult(
drawable = drawable,
isSampled = isSampled
)
}

private fun ImageSource.toImageDecoderSource(): ImageDecoder.Source {
Expand All @@ -133,6 +115,7 @@ class ImageDecoderDecoder @JvmOverloads constructor(
if (metadata is ResourceMetadata && metadata.packageName == options.context.packageName) {
return ImageDecoder.createSource(options.context.resources, metadata.resId)
}

return when {
SDK_INT >= 31 -> ImageDecoder.createSource(source().readByteArray())
SDK_INT == 30 -> ImageDecoder.createSource(ByteBuffer.wrap(source().readByteArray()))
Expand All @@ -141,16 +124,43 @@ class ImageDecoderDecoder @JvmOverloads constructor(
}
}

private suspend fun <T> withSource(block: (ImageSource) -> T): T = runInterruptible {
if (enforceMinimumFrameDelay && DecodeUtils.isGif(source.source())) {
// Wrap the source to rewrite its frame delay as it's read.
source.use {
val rewritingSource = FrameDelayRewritingSource(source.source())
ImageSource(rewritingSource.buffer(), options.context).use(block)
}
private fun ImageDecoder.configureImageDecoderProperties() {
allocator = if (options.config.isHardware) {
ImageDecoder.ALLOCATOR_HARDWARE
} else {
source.use(block)
ImageDecoder.ALLOCATOR_SOFTWARE
}
memorySizePolicy = if (options.allowRgb565) {
ImageDecoder.MEMORY_POLICY_LOW_RAM
} else {
ImageDecoder.MEMORY_POLICY_DEFAULT
}
if (options.colorSpace != null) {
setTargetColorSpace(options.colorSpace)
}
isUnpremultipliedRequired = !options.premultipliedAlpha
postProcessor = options.parameters.animatedTransformation()?.asPostProcessor()
}

private suspend fun wrapDrawable(baseDrawable: Drawable): Drawable {
if (baseDrawable !is AnimatedImageDrawable) {
return baseDrawable
}

baseDrawable.repeatCount = options.parameters.repeatCount() ?: REPEAT_INFINITE

// Set the start and end animation callbacks if any one is supplied through the request.
val onStart = options.parameters.animationStartCallback()
val onEnd = options.parameters.animationEndCallback()
if (onStart != null || onEnd != null) {
// Animation callbacks must be set on the main thread.
withContext(Dispatchers.Main.immediate) {
baseDrawable.registerAnimationCallback(animatable2CallbackOf(onStart, onEnd))
}
}

// Wrap AnimatedImageDrawable in a ScaleDrawable so it always scales to fill its bounds.
return ScaleDrawable(baseDrawable, options.scale)
}

@RequiresApi(28)
Expand Down