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

Major: Improved audio stability. Added NewPlatformAudioOutput, providing a callback-based audio generator that is much more stable #1983

Merged
merged 1 commit into from
Oct 25, 2023
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
268 changes: 97 additions & 171 deletions korge-core/src/android/korlibs/audio/sound/AndroidNativeSoundProvider.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,216 +3,142 @@ package korlibs.audio.sound
import android.content.*
import android.media.*
import android.os.*
import korlibs.datastructure.*
import korlibs.datastructure.lock.*
import korlibs.datastructure.event.*
import korlibs.datastructure.pauseable.*
import korlibs.datastructure.thread.*
import korlibs.io.android.*
import korlibs.io.async.*
import korlibs.time.*
import kotlinx.coroutines.*
import kotlin.coroutines.*
import kotlin.coroutines.cancellation.CancellationException

actual val nativeSoundProvider: NativeSoundProvider by lazy { AndroidNativeSoundProvider() }

class AndroidNativeSoundProvider : NativeSoundProvider() {
companion object {
val MAX_CHANNELS = 16
}

class AndroidNativeSoundProvider : NativeSoundProviderNew() {
override val target: String = "android"

private var audioManager: AudioManager? = null
val audioSessionId: Int by lazy {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP)
audioManager!!.generateAudioSessionId() else -1
}
//val audioSessionId get() = audioManager!!.generateAudioSessionId()

//private val activeOutputs = LinkedHashSet<AndroidPlatformAudioOutput>()
private val threadPool = Pool { id ->
//Console.info("Creating AudioThread[$id]")
AudioThread(this, id = id).also { it.isDaemon = true }.also { it.start() }
override fun createNewPlatformAudioOutput(coroutineContext: CoroutineContext, channels: Int, frequency: Int, gen: (AudioSamplesInterleaved) -> Unit): NewPlatformAudioOutput {
ensureAudioManager(coroutineContext)
return AndroidNewPlatformAudioOutput(this, coroutineContext, channels, frequency, gen)
}

override var paused: Boolean = false
set(value) {
if (field != value) {
field = value
//(this as java.lang.Object).notifyAll()
}
private val pauseable = SyncPauseable()
override var paused: Boolean by pauseable::paused

fun ensureAudioManager(coroutineContext: CoroutineContext) {
if (audioManager == null) {
val ctx = coroutineContext[AndroidCoroutineContext.Key]?.context ?: error("Can't find the Android Context on the CoroutineContext. Must call withAndroidContext first")
audioManager = ctx.getSystemService(Context.AUDIO_SERVICE) as AudioManager
}
}

class AudioThread(val provider: AndroidNativeSoundProvider, var freq: Int = 44100, val id: Int = -1) : Thread() {
var props: SoundProps = DummySoundProps
val deque = AudioSamplesDeque(2)
val lock = Lock()
@Volatile
var running = true
class AndroidNewPlatformAudioOutput(
val provider: AndroidNativeSoundProvider,
coroutineContext: CoroutineContext,
channels: Int,
frequency: Int,
gen: (AudioSamplesInterleaved) -> Unit
) : NewPlatformAudioOutput(coroutineContext, channels, frequency, gen) {
var thread: NativeThread? = null

override fun internalStart() {
thread = nativeThread(isDaemon = true) { thread ->
//val bufferSamples = 4096
val bufferSamples = 1024

val atChannelSize = Short.SIZE_BYTES * channels * bufferSamples
val atChannel = if (channels >= 2) AudioFormat.CHANNEL_OUT_STEREO else AudioFormat.CHANNEL_OUT_MONO
val atMode = AudioTrack.MODE_STREAM
val at = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
AudioTrack(
AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_GAME)
//.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.setContentType(AudioAttributes.CONTENT_TYPE_UNKNOWN)
.build(),
AudioFormat.Builder()
.setChannelMask(atChannel)
.setSampleRate(frequency)
.setEncoding(AudioFormat.ENCODING_PCM_16BIT)
.build(),
atChannelSize,
atMode,
provider.audioSessionId
)
} else {
@Suppress("DEPRECATION")
AudioTrack(
AudioManager.STREAM_MUSIC,
frequency,
atChannel,
AudioFormat.ENCODING_PCM_16BIT,
atChannelSize,
atMode
)
}
if (at.state == AudioTrack.STATE_UNINITIALIZED) {
System.err.println("Audio track was not initialized correctly frequency=$frequency, bufferSamples=$bufferSamples")
}

init {
this.isDaemon = true
}
val buffer = AudioSamplesInterleaved(channels, bufferSamples)
at.play()

var lastVolL = Float.NaN
var lastVolR = Float.NaN

override fun run() {
val bufferSamples = 4096

val at = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
AudioTrack(
AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_GAME)
//.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.setContentType(AudioAttributes.CONTENT_TYPE_UNKNOWN)
.build(),
AudioFormat.Builder()
.setChannelMask(AudioFormat.CHANNEL_IN_STEREO)
.setSampleRate(freq)
.setEncoding(AudioFormat.ENCODING_PCM_16BIT)
.build(),
2 * 2 * bufferSamples,
AudioTrack.MODE_STREAM,
provider.audioSessionId
)
} else {
@Suppress("DEPRECATION")
AudioTrack(
AudioManager.STREAM_MUSIC,
freq,
AudioFormat.CHANNEL_OUT_STEREO,
AudioFormat.ENCODING_PCM_16BIT,
2 * 2 * bufferSamples,
AudioTrack.MODE_STREAM
)
}
if (at.state == AudioTrack.STATE_UNINITIALIZED) {
System.err.println("Audio track was not initialized correctly freq=$freq, bufferSamples=$bufferSamples")
}
//if (at.state == AudioTrack.STATE_INITIALIZED) at.play()
while (running) {
try {
val temp = AudioSamplesInterleaved(2, bufferSamples)
//val tempEmpty = ShortArray(1024)
var paused = true
var lastVolume = Float.NaN
while (running) {
//println("Android sound thread running = ${currentThreadId} ${currentThreadName}")

if (provider.paused) {
at.stop()
//at.pause()
//at.flush()
while (provider.paused && running) {
//(provider as java.lang.Object).wait(10_000L)
Thread.sleep(250L)
}
at.play()
}
while (thread.threadSuggestRunning) {
provider.pauseable.checkPaused()

val readCount = lock { deque.read(temp) }
if (at.state == AudioTrack.STATE_UNINITIALIZED) {
Thread.sleep(50L)
if (this.paused) {
at.pause()
Thread.sleep(20L)
continue
} else {
at.play()
}
if (readCount > 0) {
if (paused) {
//println("[KORAU] Resume $id")
paused = false
at.play()

when (at.state) {
AudioTrack.STATE_UNINITIALIZED -> {
Thread.sleep(20L)
}
//println("AUDIO CHUNK: $readCount : ${temp.data.toList()}")
if (at.state == AudioTrack.STATE_INITIALIZED) {
at.playbackRate = freq
AudioTrack.STATE_INITIALIZED -> {
at.playbackRate = frequency
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
at.playbackParams.speed = props.pitch.toFloat()
at.playbackParams.speed = this.pitch.toFloat()
}
val vol = props.volume.toFloat()
if (lastVolume != vol) {
val volL = this.volumeForChannel(0).toFloat()
val volR = this.volumeForChannel(1).toFloat()
if (lastVolL != volL || lastVolR != volR) {
lastVolL = volL
lastVolR = volR
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
at.setVolume(vol)
at.setVolume(volL)
} else {
@Suppress("DEPRECATION")
at.setStereoVolume(vol, vol)
at.setStereoVolume(volL, volR)
}
}
lastVolume = vol
at.write(temp.data, 0, readCount * 2)
}
} else {
//at.write(tempEmpty, 0, tempEmpty.size)
if (!paused) {
//println("[KORAU] Stop $id")
//at.flush()
at.stop()
paused = true

genSafe(buffer)
at.write(buffer.data, 0, buffer.data.size)
}
Thread.sleep(2L)
}
}
} catch (e: Throwable) {
e.printStackTrace()
} finally {
//println("[KORAU] Completed $id")
try {
at.stop()
} catch (e: CancellationException) {
throw e
} catch (e: Throwable) {
e.printStackTrace()
}
at.flush()
at.stop()
at.release()
}
}
at.release()
}
}

fun ensureAudioManager(coroutineContext: CoroutineContext) {
if (audioManager == null) {
val ctx = coroutineContext[AndroidCoroutineContext.Key]?.context ?: error("Can't find the Android Context on the CoroutineContext. Must call withAndroidContext first")
audioManager = ctx.getSystemService(Context.AUDIO_SERVICE) as AudioManager
}
}

override fun createPlatformAudioOutput(coroutineContext: CoroutineContext, freq: Int): PlatformAudioOutput {
ensureAudioManager(coroutineContext)
return AndroidPlatformAudioOutput(coroutineContext, freq, this)
}

class AndroidPlatformAudioOutput(coroutineContext: CoroutineContext, frequency: Int, val provider: AndroidNativeSoundProvider) : PlatformAudioOutput(coroutineContext, frequency) {
private var started = false
internal var thread: AudioThread? = null
private val threadDeque get() = thread?.deque

override val availableSamples: Int get() = threadDeque?.availableRead ?: 0

override suspend fun add(samples: AudioSamples, offset: Int, size: Int) {
//println("AndroidPlatformAudioOutput.add")
while (thread == null) delay(10.milliseconds)
while (threadDeque!!.availableRead >= 44100) delay(1.milliseconds)

thread!!.lock { threadDeque!!.write(samples, offset, size) }
}

override fun start() {
if (started) return
started = true
launchImmediately(coroutineContext) {
while (provider.threadPool.totalItemsInUse >= MAX_CHANNELS) {
delay(10.milliseconds)
}
thread = provider.threadPool.alloc()
thread?.props = this
thread?.freq = frequency
threadDeque?.clear()
//val temp = AudioSamplesInterleaved(2, bufferSamples)
}
//provider.activeOutputs += this
}

override fun stop() {
if (!started) return
//provider.activeOutputs -= this
started = false
if (thread != null) {
provider.threadPool.free(thread!!)
}
override fun internalStop() {
thread?.threadSuggestRunning = false
thread = null
}
}
Expand Down
21 changes: 7 additions & 14 deletions korge-core/src/common/korlibs/audio/sound/AudioData.kt
Original file line number Diff line number Diff line change
@@ -1,19 +1,11 @@
package korlibs.audio.sound

import korlibs.time.TimeSpan
import korlibs.time.seconds
import korlibs.memory.arraycopy
import korlibs.audio.format.AudioDecodingProps
import korlibs.audio.format.AudioEncodingProps
import korlibs.audio.format.AudioFormat
import korlibs.audio.format.AudioFormats
import korlibs.audio.format.defaultAudioFormats
import korlibs.io.file.VfsFile
import korlibs.io.file.VfsOpenMode
import korlibs.io.file.baseName
import korlibs.io.lang.invalidOp
import korlibs.io.stream.openUse
import kotlin.math.min
import korlibs.audio.format.*
import korlibs.io.file.*
import korlibs.io.lang.*
import korlibs.memory.*
import korlibs.time.*
import kotlin.math.*

class AudioData(
val rate: Int,
Expand All @@ -32,6 +24,7 @@ class AudioData(
val totalSamples: Int get() = samples.totalSamples
val totalTime: TimeSpan get() = timeAtSample(totalSamples)
fun timeAtSample(sample: Int): TimeSpan = ((sample).toDouble() / rate.toDouble()).seconds
fun sampleAtTime(time: TimeSpan): Int = (time.seconds * rate.toDouble()).toInt()

operator fun get(channel: Int): ShortArray = samples.data[channel]
operator fun get(channel: Int, sample: Int): Short = samples.data[channel][sample]
Expand Down
Loading
Loading