Skip to content
Open
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
81 changes: 81 additions & 0 deletions feature/voiceburst/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
/*
* Copyright (c) 2026 Meshtastic LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/

import java.io.File

plugins {
alias(libs.plugins.meshtastic.kmp.feature)
alias(libs.plugins.meshtastic.kotlinx.serialization)
}

// --- Codec2 JNI detection ---------------------------------------------------
val codec2SoArm64 = File(projectDir, "src/androidMain/jniLibs/arm64-v8a/libcodec2.so")
val codec2JniArm64 = File(projectDir, "src/androidMain/jniLibs/arm64-v8a/libcodec2_jni.so")
val codec2SoX86_64 = File(projectDir, "src/androidMain/jniLibs/x86_64/libcodec2.so")
val codec2JniX86_64 = File(projectDir, "src/androidMain/jniLibs/x86_64/libcodec2_jni.so")
val codec2Available = (codec2SoArm64.exists() && codec2JniArm64.exists()) ||
(codec2SoX86_64.exists() && codec2JniX86_64.exists())

if (codec2Available) {
logger.lifecycle(":feature:voiceburst -- libcodec2.so + libcodec2_jni.so found")
} else {
logger.lifecycle(":feature:voiceburst -- .so not found -> stub mode (run scripts/build_codec2.sh)")
}
Comment on lines +33 to +37
Copy link

Copilot AI Apr 5, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The Gradle log messages here are in Italian ("trovate", "assenti", "esegui...") and also include a unicode arrow. The PR description says all comments/messages should be English; please translate these messages and keep them ASCII/UTF-8 clean so they render consistently in build output.

Copilot uses AI. Check for mistakes.

kotlin {
jvm()

@Suppress("UnstableApiUsage")
android {
namespace = "org.meshtastic.feature.voiceburst"
androidResources.enable = false
withHostTest { isIncludeAndroidResources = true }
}

sourceSets {
commonMain.dependencies {
implementation(projects.core.common)
implementation(projects.core.data)
implementation(projects.core.datastore)
implementation(projects.core.model)
implementation(projects.core.navigation)
implementation(projects.core.proto)
implementation(projects.core.repository)
implementation(projects.core.service)
implementation(projects.core.ui)
implementation(projects.core.di)

implementation(libs.kotlinx.collections.immutable)
}

androidUnitTest.dependencies {
implementation(libs.junit)
implementation(libs.robolectric)
implementation(libs.turbine)
implementation(libs.kotlinx.coroutines.test)
implementation(libs.androidx.test.ext.junit)
}

commonTest.dependencies {
implementation(project(":core:testing"))
}
}
}

// No externalNativeBuild block needed.
// Prebuilt .so files in jniLibs/ are packaged automatically by AGP.
// The JNI wrapper is compiled separately via scripts/build_codec2.sh.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/*
* Copyright (c) 2026 Chris7X
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, see <https://www.gnu.org/licenses/>.
*/

package com.geeksville.mesh.voiceburst

import android.util.Log

/**
* JNI binding to a prebuilt libcodec2 library.
* Both shared objects (libcodec2.so + libcodec2_jni.so) must be present in jniLibs/.
*/
internal object Codec2JNI {

private const val TAG = "Codec2JNI"
private var loaded = false

fun ensureLoaded() {
if (!loaded) {
try {
System.loadLibrary("codec2")
Log.i(TAG, "libcodec2.so loaded OK")
} catch (e: UnsatisfiedLinkError) {
Log.e(TAG, "Failed to load libcodec2.so: ${e.message}")
return
}
try {
System.loadLibrary("codec2_jni")
Log.i(TAG, "libcodec2_jni.so loaded OK — JNI active")
loaded = true
} catch (e: UnsatisfiedLinkError) {
Log.e(TAG, "Failed to load libcodec2_jni.so: ${e.message}")
// loaded remains false -> fallback to stub
}
}
}

val isAvailable: Boolean
get() = loaded

// Codec2 operating modes
const val MODE_3200 = 0
const val MODE_2400 = 1
const val MODE_1600 = 2
const val MODE_1400 = 3
const val MODE_1300 = 4
const val MODE_1200 = 5
const val MODE_700C = 8
const val MODE_450 = 10

@JvmStatic external fun getSamplesPerFrame(mode: Int): Int
@JvmStatic external fun getBytesPerFrame(mode: Int): Int
@JvmStatic external fun create(mode: Int): Long
@JvmStatic external fun encode(ptr: Long, pcm: ShortArray): ByteArray
@JvmStatic external fun decode(ptr: Long, frame: ByteArray): ShortArray
@JvmStatic external fun destroy(ptr: Long)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/*
* Copyright (c) 2026 Chris7X
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, see <https://www.gnu.org/licenses/>.
*/
package org.meshtastic.codec2

/**
* Backwards-compatible alias to the canonical Codec2 JNI wrapper used by
* the voiceburst feature. The actual implementation lives in
* [com.geeksville.mesh.voiceburst.Codec2JNI].
*/
typealias Codec2Jni = com.geeksville.mesh.voiceburst.Codec2JNI
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
/*
* Copyright (c) 2026 Chris7X
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.meshtastic.feature.voiceburst.audio

import android.media.AudioAttributes
import android.media.AudioFormat
import android.media.AudioManager
import android.media.AudioTrack
import co.touchlab.kermit.Logger
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

private const val TAG = "AndroidAudioPlayer"

/**
* Android implementation of [AudioPlayer].
*
* Key implementation notes:
* - BUG: MODE_STATIC with bufferSize < minBufferSize -> STATE_NO_STATIC_DATA (state=2) -> silence.
* FIX: bufferSize = maxOf(minBufferSize, pcmBytes) ALWAYS, even in static mode.
* - Using MODE_STREAM: simpler and avoids the STATE_NO_STATIC_DATA issue.
* For 1 second at 8kHz (16000 bytes) MODE_STREAM is more than adequate.
* - USAGE_MEDIA -> main speaker (not earpiece).
* - [playingFilePath] StateFlow to sync play/stop icons in the UI.
*/
class AndroidAudioPlayer(
private val scope: CoroutineScope,
) : AudioPlayer {

private var audioTrack: AudioTrack? = null
private var playingJob: Job? = null

private val _playingFilePath = MutableStateFlow<String?>(null)
override val playingFilePath: StateFlow<String?> = _playingFilePath.asStateFlow()

override val isPlaying: Boolean
get() = audioTrack?.playState == AudioTrack.PLAYSTATE_PLAYING

override fun play(pcmData: ShortArray, filePath: String, onComplete: () -> Unit) {
// If already playing, stop before starting a new track
if (isPlaying) {
Logger.d(tag = TAG) { "Stopping previous track before starting new one" }
stopInternal()
}

if (pcmData.isEmpty()) {
Logger.w(tag = TAG) { "PCM data is empty -- skipping playback" }
onComplete()
return
}

val sampleRate = SAMPLE_RATE_HZ
val channelConfig = AudioFormat.CHANNEL_OUT_MONO
val audioEncoding = AudioFormat.ENCODING_PCM_16BIT

val minBufferSize = AudioTrack.getMinBufferSize(sampleRate, channelConfig, audioEncoding)
if (minBufferSize <= 0) {
Logger.e(tag = TAG) { "getMinBufferSize error: $minBufferSize" }
onComplete()
return
}

// CRITICAL: bufferSize must always be >= minBufferSize.
// With MODE_STATIC, if bufferSize < minBufferSize -> state=STATE_NO_STATIC_DATA=2 -> silence.
// MODE_STREAM is used for simplicity and robustness.
val pcmBytes = pcmData.size * Short.SIZE_BYTES
val bufferSize = maxOf(minBufferSize, pcmBytes)

val attrs = AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
.build()

val format = AudioFormat.Builder()
.setSampleRate(sampleRate)
.setEncoding(audioEncoding)
.setChannelMask(channelConfig)
.build()

val track = try {
AudioTrack(attrs, format, bufferSize, AudioTrack.MODE_STREAM, AudioManager.AUDIO_SESSION_ID_GENERATE)
} catch (e: Exception) {
Logger.e(e, tag = TAG) { "Failed to create AudioTrack" }
onComplete()
return
}

if (track.state != AudioTrack.STATE_INITIALIZED) {
Logger.e(tag = TAG) { "AudioTrack not initialized: state=${track.state} (expected ${AudioTrack.STATE_INITIALIZED})" }
track.release()
onComplete()
return
}

audioTrack = track
_playingFilePath.value = filePath.ifEmpty { null }

playingJob = scope.launch(Dispatchers.IO) {
try {
// MODE_STREAM: call play() FIRST, then write() for streaming
track.play()
Logger.d(tag = TAG) { "Playback started: ${pcmData.size} samples @ ${sampleRate}Hz" }

val written = track.write(pcmData, 0, pcmData.size)
if (written < 0) {
Logger.e(tag = TAG) { "write() error: $written" }
} else {
Logger.d(tag = TAG) { "Write complete: $written samples" }
// Wait for the DAC to drain all samples in the buffer
val drainMs = written.toLong() * 1000L / sampleRate + DRAIN_GUARD_MS
kotlinx.coroutines.delay(drainMs)
}
} catch (e: Exception) {
Logger.e(e, tag = TAG) { "Playback error" }
} finally {
releaseTrack(track)
_playingFilePath.value = null
scope.launch(Dispatchers.Main) { onComplete() }
}
}
}

override fun stop() {
if (!isPlaying && playingJob?.isActive != true) return
Logger.d(tag = TAG) { "Stopping playback" }
stopInternal()
}

private fun stopInternal() {
playingJob?.cancel()
playingJob = null
audioTrack?.let { releaseTrack(it) }
_playingFilePath.value = null
}

private fun releaseTrack(track: AudioTrack) {
try { track.stop() } catch (_: Exception) {}
try { track.flush() } catch (_: Exception) {}
track.release()
if (audioTrack === track) audioTrack = null
}

companion object {
private const val SAMPLE_RATE_HZ = 8000
private const val DRAIN_GUARD_MS = 150L // extra margin for DAC drain
}
}
Loading