package com.suno.android.media.hooks.preload import androidx.annotation.OptIn import androidx.media3.common.C import androidx.media3.common.util.UnstableApi import androidx.media3.exoplayer.source.preload.DefaultPreloadManager import androidx.media3.exoplayer.source.preload.TargetPreloadStatusControl import com.suno.android.media.HooksFeed import java.util.concurrent.atomic.AtomicInteger import javax.inject.Inject import javax.inject.Singleton private const val PRELOAD_DISTANCE = 5 private const val AGGRESSIVE_PRELOAD_DURATION_MS = 5_000L private const val MEDIUM_PRELOAD_DURATION_MS = 3_000L private const val LIGHT_PRELOAD_DURATION_MS = 1_000L /** * Controls preload strategy for hooks feed videos based on distance from current playing video. */ @OptIn(UnstableApi::class) @Singleton @HooksFeed class HooksFeedPreloadStatusControl @Inject constructor() : TargetPreloadStatusControl { private val currentlyPlayingIndex = AtomicInteger(C.INDEX_UNSET) override fun getTargetPreloadStatus( index: Int, ): DefaultPreloadManager.PreloadStatus? { val distance = index - currentlyPlayingIndex.get() val isEligibleForPreload = distance in 1..PRELOAD_DISTANCE return if (isEligibleForPreload) { val duration = when (distance) { 1 -> AGGRESSIVE_PRELOAD_DURATION_MS // Next video - aggressive preload 2 -> MEDIUM_PRELOAD_DURATION_MS // 2 videos away - medium preload else -> LIGHT_PRELOAD_DURATION_MS // 3+ videos away - light preload } DefaultPreloadManager.PreloadStatus.specifiedRangeLoaded(duration) } else { null } } fun updateCurrentlyPlayingIndex( index: Int, ) { currentlyPlayingIndex.set(index) } fun getCurrentlyPlayingIndex(): Int = currentlyPlayingIndex.get() }