Skip to content

Fix OpusDecoder calling nativeCreate() before OpusLoader.load() - #8

Merged
yankeppey merged 1 commit into
yankeppey:mainfrom
serhii-fedunets:fix/decoder-init-order
Jul 9, 2026
Merged

Fix OpusDecoder calling nativeCreate() before OpusLoader.load()#8
yankeppey merged 1 commit into
yankeppey:mainfrom
serhii-fedunets:fix/decoder-init-order

Conversation

@serhii-fedunets

Copy link
Copy Markdown
Contributor

Problem

OpusDecoder's constructor can call the native nativeCreate() JNI method before the Opus native library has been loaded.

Currently, handle is declared as:

private var handle: Long = nativeCreate(sampleRate, channels)

init {
    OpusLoader.load()
    require(handle != 0L) { "Opus decoder create failed" }
}

Kotlin evaluates property initializers and init blocks in the exact order they are declared in the class body. Since the nativeCreate(...) call is part of the property initializer, it executes before the init block's OpusLoader.load() call. On a fresh process where the native library hasn't been loaded by anything else yet, nativeCreate() is invoked before System.loadLibrary("opus_jni") has run, causing an error.

This is inconsistent with OpusEncoder, which correctly declares handle without an initializer and assigns it inside init strictly after OpusLoader.load():

private var handle: Long

init {
    OpusLoader.load()
    handle = nativeCreate(sampleRate, channels, application.value)
    require(handle != 0L) { "nativeCreate failed" }
}

Impact: Any app that constructs an OpusDecoder as the very first Kopus object in its process (without ever creating an OpusEncoder or explicitly calling OpusLoader.load() first) hits a native library load failure. This bug is easily missed in testing because simply exercising the encoder path first "hides" the bug for the rest of the process's lifetime.

Fix

Change OpusDecoder to assign handle inside init, after OpusLoader.load(), matching OpusEncoder's pattern exactly.

@yankeppey
yankeppey merged commit 7586835 into yankeppey:main Jul 9, 2026
2 of 4 checks passed
@yankeppey

Copy link
Copy Markdown
Owner

Thank you!

@serhii-fedunets

Copy link
Copy Markdown
Contributor Author

You're welcome!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants