Skip to content

Commit

Permalink
Replace Glide with Coil
Browse files Browse the repository at this point in the history
  • Loading branch information
nielsvanvelzen committed Jul 11, 2023
1 parent 40f186f commit 387baf9
Show file tree
Hide file tree
Showing 11 changed files with 119 additions and 153 deletions.
4 changes: 1 addition & 3 deletions app/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
plugins {
id("com.android.application")
kotlin("android")
alias(libs.plugins.kotlin.ksp)
alias(libs.plugins.kotlin.serialization)
alias(libs.plugins.aboutlibraries)
}
Expand Down Expand Up @@ -149,8 +148,7 @@ dependencies {

// Image utility
implementation(libs.blurhash)
implementation(libs.glide.core)
ksp(libs.glide.ksp)
implementation(libs.bundles.coil)

// Crash Reporting
implementation(libs.bundles.acra)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.await
import com.bumptech.glide.Glide
import com.vanniktech.blurhash.BlurHash
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
Expand Down Expand Up @@ -70,13 +69,6 @@ class JellyfinApplication : Application() {
super.onLowMemory()

BlurHash.clearCache()
Glide.with(this).onLowMemory()
}

override fun onTrimMemory(level: Int) {
super.onTrimMemory(level)

Glide.with(this).onTrimMemory(level)
}

override fun attachBaseContext(base: Context?) {
Expand Down
22 changes: 0 additions & 22 deletions app/src/main/java/org/jellyfin/androidtv/JellyfinGlideModule.kt

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@ package org.jellyfin.androidtv.data.service
import android.content.Context
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asImageBitmap
import com.bumptech.glide.Glide
import androidx.core.graphics.drawable.toBitmap
import coil.ImageLoader
import coil.request.ImageRequest
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
Expand All @@ -20,9 +20,7 @@ import org.jellyfin.sdk.api.client.ApiClient
import org.jellyfin.sdk.api.client.extensions.imageApi
import org.jellyfin.sdk.model.api.BaseItemDto
import org.jellyfin.sdk.model.api.ImageType
import timber.log.Timber
import java.util.UUID
import java.util.concurrent.ExecutionException
import kotlin.time.Duration
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.seconds
Expand All @@ -32,6 +30,7 @@ class BackgroundService(
private val jellyfin: Jellyfin,
private val api: ApiClient,
private val userPreferences: UserPreferences,
private val imageLoader: ImageLoader,
) {
companion object {
val SLIDESHOW_DURATION = 30.seconds
Expand Down Expand Up @@ -106,22 +105,11 @@ class BackgroundService(
// Cancel current loading job
loadBackgroundsJob?.cancel()
loadBackgroundsJob = scope.launch(Dispatchers.IO) {
_backgrounds = backdropUrls
.map { url ->
Glide.with(context).asBitmap().load(url).submit()
}
.map { future ->
async {
try {
future.get().asImageBitmap()
} catch (ex: ExecutionException) {
Timber.e(ex, "There was an error fetching the background image.")
null
}
}
}
.awaitAll()
.filterNotNull()
_backgrounds = backdropUrls.mapNotNull { url ->
imageLoader.execute(
request = ImageRequest.Builder(context).data(url).build()
).drawable?.toBitmap()?.asImageBitmap()
}

// Go to first background
_currentIndex = 0
Expand Down
18 changes: 17 additions & 1 deletion app/src/main/java/org/jellyfin/androidtv/di/AppModule.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
package org.jellyfin.androidtv.di

import android.content.Context
import android.os.Build
import coil.ImageLoader
import coil.decode.GifDecoder
import coil.decode.ImageDecoderDecoder
import coil.decode.SvgDecoder
import org.jellyfin.androidtv.BuildConfig
import org.jellyfin.androidtv.auth.repository.ServerRepository
import org.jellyfin.androidtv.auth.repository.UserRepository
Expand Down Expand Up @@ -90,6 +95,17 @@ val appModule = module {
)
}

// Coil (images)
single {
ImageLoader.Builder(androidContext()).apply {
components {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) add(ImageDecoderDecoder.Factory())
else add(GifDecoder.Factory())
add(SvgDecoder.Factory())
}
}.build()
}

// Non API related
single { DataRefreshService() }
single { PlaybackControllerContainer() }
Expand All @@ -110,7 +126,7 @@ val appModule = module {
viewModel { ScreensaverViewModel(get()) }
viewModel { SearchViewModel(get()) }

single { BackgroundService(get(), get(), get(), get()) }
single { BackgroundService(get(), get(), get(), get(), get()) }

single { MarkdownRenderer(get()) }

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalContext
import com.bumptech.glide.Glide
import androidx.core.graphics.drawable.toBitmap
import coil.ImageLoader
import coil.request.ImageRequest
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
Expand All @@ -27,14 +29,14 @@ import org.jellyfin.sdk.model.api.ImageType
import org.jellyfin.sdk.model.constant.ItemSortBy
import org.koin.androidx.compose.get
import timber.log.Timber
import java.util.concurrent.ExecutionException
import kotlin.time.Duration.Companion.seconds

@Composable
fun DreamHost() {
val api = get<ApiClient>()
val userPreferences = get<UserPreferences>()
val mediaManager = get<MediaManager>()
val imageLoader = get<ImageLoader>()
val context = LocalContext.current

var libraryShowcase by remember { mutableStateOf<DreamContent.LibraryShowcase?>(null) }
Expand All @@ -44,7 +46,7 @@ fun DreamHost() {
delay(2.seconds)

while (true) {
libraryShowcase = getRandomLibraryShowcase(api, context)
libraryShowcase = getRandomLibraryShowcase(api, imageLoader, context)
delay(30.seconds)
}
}
Expand All @@ -62,7 +64,11 @@ fun DreamHost() {
)
}

private suspend fun getRandomLibraryShowcase(api: ApiClient, context: Context): DreamContent.LibraryShowcase? {
private suspend fun getRandomLibraryShowcase(
api: ApiClient,
imageLoader: ImageLoader,
context: Context
): DreamContent.LibraryShowcase? {
try {
val response by api.itemsApi.getItemsByUserId(
includeItemTypes = listOf(BaseItemKind.MOVIE, BaseItemKind.SERIES),
Expand All @@ -89,12 +95,9 @@ private suspend fun getRandomLibraryShowcase(api: ApiClient, context: Context):
)

val backdrop = withContext(Dispatchers.IO) {
try {
Glide.with(context).asBitmap().load(backdropUrl).submit().get()
} catch (err: ExecutionException) {
Timber.e("Unable to retrieve image for item ${item.id}", err)
null
}
imageLoader.execute(
request = ImageRequest.Builder(context).data(backdropUrl).build()
).drawable?.toBitmap()
} ?: return null

return DreamContent.LibraryShowcase(item, backdrop)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,18 @@ import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Build
import android.os.ParcelFileDescriptor
import androidx.core.graphics.drawable.toBitmap
import androidx.core.net.toUri
import androidx.lifecycle.ProcessLifecycleOwner
import androidx.lifecycle.lifecycleScope
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import coil.ImageLoader
import coil.request.ImageRequest
import org.jellyfin.androidtv.BuildConfig
import org.jellyfin.androidtv.R
import org.koin.android.ext.android.inject
import java.io.IOException

class ImageProvider : ContentProvider() {
private val imageLoader by inject<ImageLoader>()

override fun onCreate(): Boolean = true

override fun getType(uri: Uri) = null
Expand All @@ -33,30 +33,40 @@ class ImageProvider : ContentProvider() {
val (read, write) = ParcelFileDescriptor.createPipe()
val outputStream = ParcelFileDescriptor.AutoCloseOutputStream(write)

ProcessLifecycleOwner.get().lifecycleScope.launch(Dispatchers.IO) {
Glide.with(context!!)
.asBitmap()
.error(R.drawable.placeholder_icon)
.load(src)
.into(object : CustomTarget<Bitmap>() {
override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
@Suppress("DEPRECATION")
val format = when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.R -> Bitmap.CompressFormat.WEBP_LOSSY
else -> Bitmap.CompressFormat.WEBP
}
resource.compress(format, 95, outputStream)
outputStream.close()
}
imageLoader.enqueue(ImageRequest.Builder(context!!).apply {
data(src)
error(R.drawable.placeholder_icon)
target(
onSuccess = { drawable -> writeDrawable(drawable, outputStream) },
onError = { drawable -> writeDrawable(requireNotNull(drawable), outputStream) }
)
}.build())

return read
}

override fun onLoadCleared(placeholder: Drawable?) = outputStream.close()
})
private fun writeDrawable(
drawable: Drawable,
outputStream: ParcelFileDescriptor.AutoCloseOutputStream
) {
@Suppress("DEPRECATION")
val format = when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.R -> Bitmap.CompressFormat.WEBP_LOSSY
else -> Bitmap.CompressFormat.WEBP
}

return read
try {
outputStream.use {
drawable.toBitmap().compress(format, COMPRESSION_QUALITY, outputStream)
}
} catch (_: IOException) {
// Ignore IOException as this is commonly thrown when the load request is cancelled
}
}

companion object {
private const val COMPRESSION_QUALITY = 95

/**
* Get a [Uri] that uses the [ImageProvider] to load an image. The input should be a valid
* Jellyfin image URL created using the SDK.
Expand Down
35 changes: 18 additions & 17 deletions app/src/main/java/org/jellyfin/androidtv/ui/AsyncImageView.kt
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,16 @@ import androidx.core.graphics.drawable.toDrawable
import androidx.core.view.doOnAttach
import androidx.lifecycle.findViewTreeLifecycleOwner
import androidx.lifecycle.lifecycleScope
import com.bumptech.glide.Glide
import com.bumptech.glide.load.model.GlideUrl
import com.bumptech.glide.load.model.LazyHeaders
import coil.ImageLoader
import coil.request.ImageRequest
import coil.transform.CircleCropTransformation
import com.vanniktech.blurhash.BlurHash
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.jellyfin.androidtv.R
import org.jellyfin.sdk.api.client.ApiClient
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
import kotlin.math.round
import kotlin.time.Duration.Companion.milliseconds

Expand All @@ -30,9 +31,10 @@ class AsyncImageView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0,
) : AppCompatImageView(context, attrs, defStyleAttr) {
) : AppCompatImageView(context, attrs, defStyleAttr), KoinComponent {
private val lifeCycleOwner get() = findViewTreeLifecycleOwner()
private val styledAttributes = context.obtainStyledAttributes(attrs, R.styleable.AsyncImageView, defStyleAttr, 0)
private val imageLoader by inject<ImageLoader>()

/**
* The duration of the crossfade when changing switching the images of the url, blurhash and
Expand Down Expand Up @@ -73,21 +75,20 @@ class AsyncImageView @JvmOverloads constructor(

// Start loading image or placeholder
if (url == null) {
Glide.with(this@AsyncImageView).load(placeholder).apply {
if (circleCrop) circleCrop()
}.into(this@AsyncImageView)
} else {
val glideUrl = GlideUrl(url, LazyHeaders.Builder().apply {
setHeader("Accept", ApiClient.HEADER_ACCEPT)
imageLoader.enqueue(ImageRequest.Builder(context).apply {
target(this@AsyncImageView)
data(placeholder)
if (circleCrop) transformations(CircleCropTransformation())
}.build())

Glide.with(this@AsyncImageView).load(glideUrl).apply {
} else {
imageLoader.enqueue(ImageRequest.Builder(context).apply {
crossfade(crossFadeDuration.inWholeMilliseconds.toInt())
target(this@AsyncImageView)
data(url)
placeholder(placeholderOrBlurHash)
if (circleCrop) transformations(CircleCropTransformation())
error(placeholder)
if (circleCrop) circleCrop()
// FIXME: Glide is unable to scale the image when transitions are enabled
//transition(DrawableTransitionOptions.withCrossFade(crossFadeDuration.inWholeMilliseconds.toInt()))
}.into(this@AsyncImageView)
}.build())
}
}
}
Expand Down
Loading

0 comments on commit 387baf9

Please sign in to comment.