Merge pull request #45 from D-Modem/claude/project-thread-nu12ep

Read greetings from more sound files than WAV
This commit is contained in:
Neo authored and GitHub committed 2026-11-11 06:48:42 -08:00
commit b61fa7f24b
9 files changed
+690 -87

No files matched your search

@@ -37,6 +37,7 @@ import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
@@ -46,8 +47,10 @@ import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.core.content.ContextCompat
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.dmodem.app.android.modem.ModemState
import org.dmodem.app.android.ppp.DialIn
import org.dmodem.app.android.settings.FaxSettingsStore
@@ -275,8 +278,14 @@ fun VoiceSettingsSection() {
val recording by Voice.recording.collectAsStateWithLifecycle()
val messages by Voice.messages.collectAsStateWithLifecycle()
val mic = rememberMicrophone()
val scope = rememberCoroutineScope()
val pick = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
if (uri != null) Voice.chooseGreeting(context, uri)?.let { Toast.makeText(context, "That greeting: $it", Toast.LENGTH_LONG).show() }
if (uri != null) {
scope.launch {
withContext(Dispatchers.IO) { Voice.chooseGreeting(context, uri) }
?.let { Toast.makeText(context, "That greeting: $it", Toast.LENGTH_LONG).show() }
}
}
}
LaunchedEffect(Unit) { Voice.reload(context) }
val s = current ?: return
@@ -323,7 +332,7 @@ fun VoiceSettingsSection() {
} else {
OutlinedButton(onClick = { mic { Voice.recordGreeting(context) } }) { Text("Record") }
OutlinedButton(onClick = { Voice.playGreeting(context) }, enabled = greeting > 0) { Text("Play") }
OutlinedButton(onClick = { pick.launch(arrayOf("audio/wav", "audio/x-wav", "audio/*")) }) { Text("File…") }
OutlinedButton(onClick = { pick.launch(arrayOf("audio/*")) }) { Text("File…") }
TextButton(onClick = { Voice.clearGreeting(context) }, enabled = greeting > 0) { Text("None") }
}
}
@@ -0,0 +1,105 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package org.dmodem.app.android.voice
import android.content.Context
import android.media.AudioFormat
import android.media.MediaCodec
import android.media.MediaExtractor
import android.media.MediaFormat
import android.net.Uri
import android.os.SystemClock
import java.nio.ByteOrder
import org.dmodem.app.voice.SoundFile
/**
* Sound files the phone's own decoders read (MP3, AAC/M4A, FLAC, Ogg
* Vorbis, Opus, AMR and the rest it has), as a voice call's samples:
* 8000 Hz, one channel. For the greeting, when [SoundFile] doesn't read
* the file itself.
*/
object SystemSound {
/** the most decoded (s): a greeting is shorter */
private const val MAX_S = 300
/** how long decoding may take (ms), whatever the file */
private const val TIME_MS = 30_000L
/** [uri]'s first sound track decoded, at 8000 Hz, one channel; null if the phone can't */
fun decode(c: Context, uri: Uri): ShortArray? {
val ex = MediaExtractor()
try {
ex.setDataSource(c, uri, null)
val track = (0 until ex.trackCount).firstOrNull {
ex.getTrackFormat(it).getString(MediaFormat.KEY_MIME)?.startsWith("audio/") == true
} ?: return null
ex.selectTrack(track)
val fmt = ex.getTrackFormat(track)
val codec = MediaCodec.createDecoderByType(fmt.getString(MediaFormat.KEY_MIME)!!)
try {
codec.configure(fmt, null, null, 0)
codec.start()
return drain(ex, codec, fmt)
} finally {
runCatching { codec.stop() }
codec.release()
}
} catch (e: Exception) {
return null
} finally {
ex.release()
}
}
/** the track fed to [codec] and what it gives collected, then mixed and resampled */
private fun drain(ex: MediaExtractor, codec: MediaCodec, fmt: MediaFormat): ShortArray? {
var rate = fmt.getInteger(MediaFormat.KEY_SAMPLE_RATE)
var channels = fmt.getInteger(MediaFormat.KEY_CHANNEL_COUNT)
var float = false
var pcm = ShortArray(1 shl 16)
var n = 0
val info = MediaCodec.BufferInfo()
var fed = false
val until = SystemClock.elapsedRealtime() + TIME_MS
while (SystemClock.elapsedRealtime() < until && n < MAX_S.toLong() * rate * channels) {
if (!fed) {
val i = codec.dequeueInputBuffer(10_000)
if (i >= 0) {
val got = ex.readSampleData(codec.getInputBuffer(i)!!, 0)
if (got < 0) {
codec.queueInputBuffer(i, 0, 0, 0, MediaCodec.BUFFER_FLAG_END_OF_STREAM)
fed = true
} else {
codec.queueInputBuffer(i, 0, got, ex.sampleTime, 0)
ex.advance()
}
}
}
val o = codec.dequeueOutputBuffer(info, 10_000)
if (o == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
val f = codec.outputFormat
rate = f.getInteger(MediaFormat.KEY_SAMPLE_RATE)
channels = f.getInteger(MediaFormat.KEY_CHANNEL_COUNT)
float = f.containsKey(MediaFormat.KEY_PCM_ENCODING) &&
f.getInteger(MediaFormat.KEY_PCM_ENCODING) == AudioFormat.ENCODING_PCM_FLOAT
} else if (o >= 0) {
val b = codec.getOutputBuffer(o)!!.order(ByteOrder.nativeOrder())
b.position(info.offset)
b.limit(info.offset + info.size)
val k = if (float) info.size / 4 else info.size / 2
if (n + k > pcm.size) pcm = pcm.copyOf(maxOf(pcm.size * 2, n + k))
if (float) {
val fb = b.asFloatBuffer()
for (j in 0 until k) pcm[n + j] = (fb.get(j) * 32767f).coerceIn(-32768f, 32767f).toInt().toShort()
} else {
b.asShortBuffer().get(pcm, n, k)
}
n += k
codec.releaseOutputBuffer(o, false)
if (info.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM != 0) break
}
}
if (n == 0 || channels < 1 || rate <= 0) return null
return SoundFile.mix(pcm, n / channels, channels, rate)
}
}
@@ -301,11 +301,15 @@ object Voice {
/** the greeting's recording ended (it's kept) */
fun stopRecording() = Sounds.stopRecording()
/** the greeting from a WAV file the user chose: null, or why not */
/**
* the greeting from a sound file the user chose (WAV, AIFF and .au read
* here, the rest by the phone's decoders): null, or why not. Slow for a
* long MP3: off the main thread
*/
fun chooseGreeting(context: Context, uri: Uri): String? {
val c = context.applicationContext
val data = runCatching { c.contentResolver.openInputStream(uri)?.use { it.readBytes() } }.getOrNull() ?: return "it can't be read"
val pcm = Wav.decode(data) ?: return "it isn't a WAV file of PCM, A-law or μ-law"
val pcm = Wav.decode(data) ?: SystemSound.decode(c, uri) ?: return "it isn't a sound file this phone can play"
if (pcm.isEmpty()) return "it has no sound"
val n = minOf(pcm.size, GREETING_MAX_S * VOICE_RATE)
greetingFile(c).writeBytes(Wav.encode(pcm, n))
+12 -2
View File
@@ -49,8 +49,18 @@ app shows it). Nothing leaves the phone.
While a message is being left, **Listen** plays it on the loudspeaker
and **Pick up** turns it into a call (the message isn't kept). The
greeting is recorded with the microphone (a minute at most) or chosen
from a WAV file (PCM, A-law or μ-law, any rate: mixed to one channel and
resampled to 8000 Hz).
from a sound file, at any rate: mixed to one channel and resampled to
8000 Hz. The app reads these itself, the same on both phones:
| File | Kinds |
| --- | --- |
| WAV | PCM of 8 to 32 bits, 32 and 64-bit floats, A-law, μ-law, IMA and Microsoft ADPCM |
| AIFF, AIFF-C | PCM, floats, A-law, μ-law |
| Sun/NeXT `.au` | PCM, floats, A-law, μ-law |
The rest goes to the phone's own decoders: on Android MediaCodec (MP3,
AAC/M4A, FLAC, Ogg Vorbis, Opus, AMR, and whatever else the phone has),
on iOS AVAudioFile (MP3, AAC/M4A, FLAC, ALAC, CAF).
Calls answered as faxes by the fax settings, or by dial-in, are answered
on the first ring: with either on, the answering machine waits.
+4 -4
View File
@@ -87,7 +87,7 @@ struct PhoneView: View {
.navigationTitle("Phone")
.onAppear { reload(); greeting.reload() }
.onChange(of: jobs.voice?.running) { _ in reload() }
.fileImporter(isPresented: $choosing, allowedContentTypes: [UTType.wav]) { r in
.fileImporter(isPresented: $choosing, allowedContentTypes: [UTType.audio]) { r in
if case .success(let u) = r { error = greeting.choose(u) }
}
}
@@ -227,7 +227,7 @@ final class VoicePlayer: NSObject, ObservableObject, AVAudioPlayerDelegate {
}
}
/// The answering machine's greeting: recorded from the microphone (a minute at most), chosen from a WAV file, or none
/// The answering machine's greeting: recorded from the microphone (a minute at most), chosen from a sound file, or none
@MainActor
final class GreetingRecorder: ObservableObject {
@Published private(set) var recording = false
@@ -272,11 +272,11 @@ final class GreetingRecorder: ObservableObject {
reload()
}
/// the greeting from the WAV at [u]: nil, or why not
/// the greeting from the sound file at [u]: nil, or why not
func choose(_ u: URL) -> String? {
let scoped = u.startAccessingSecurityScopedResource()
defer { if scoped { u.stopAccessingSecurityScopedResource() } }
guard let pcm = VoiceFiles.decode(u) else { return "That file isn't a WAV of PCM, A-law or μ-law" }
guard let pcm = VoiceFiles.decode(u) else { return "That file isn't a sound file this phone can play" }
if pcm.size == 0 { return "That file has no sound" }
let n = min(pcm.size, 60 * 8000)
do {
+48 -2
View File
@@ -210,10 +210,56 @@ enum VoiceFiles {
return d
}
/// a WAV file's samples at 8000 Hz (nil: not one this reads)
/// a sound file's samples at 8000 Hz, one channel: WAV, AIFF and .au
/// read by the shared code, the rest (MP3, AAC/M4A, FLAC, ALAC, CAF)
/// by the phone's decoders (nil: not one either reads)
static func decode(_ url: URL) -> KotlinShortArray? {
guard let d = try? Data(contentsOf: url) else { return nil }
return Wav.shared.decode(data: bytes(d))
if let pcm = Wav.shared.decode(data: bytes(d)) { return pcm }
guard let s = bySystem(url) else { return nil }
let pcm = KotlinShortArray(size: Int32(s.count))
for (i, v) in s.enumerated() { pcm.set(index: Int32(i), value: v) }
return pcm
}
/// a sound file the phone decodes, at 8000 Hz, one channel (five
/// minutes at most); nil if it can't
static func bySystem(_ url: URL, maxSeconds: Int = 300) -> [Int16]? {
guard let f = try? AVAudioFile(forReading: url) else { return nil }
let src = f.processingFormat
guard src.sampleRate > 0, src.channelCount > 0,
let dst = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 8000, channels: 1, interleaved: false),
let conv = AVAudioConverter(from: src, to: dst),
let inBuf = AVAudioPCMBuffer(pcmFormat: src, frameCapacity: 4096),
let outBuf = AVAudioPCMBuffer(pcmFormat: dst, frameCapacity: AVAudioFrameCount(4096 * 8000 / src.sampleRate) + 64)
else { return nil }
// (the channels mixed, not the first alone)
conv.downmix = true
var out: [Int16] = []
var ended = false
while out.count < maxSeconds * 8000 {
outBuf.frameLength = 0
var err: NSError?
let st = conv.convert(to: outBuf, error: &err) { _, status in
if !ended {
do { try f.read(into: inBuf) } catch { inBuf.frameLength = 0 }
ended = inBuf.frameLength == 0
}
if ended {
status.pointee = .endOfStream
return nil
}
status.pointee = .haveData
return inBuf
}
if let x = outBuf.floatChannelData?[0] {
for i in 0..<Int(outBuf.frameLength) {
out.append(Int16(max(-32768, min(32767, x[i] * 32767))))
}
}
if st == .error || st == .endOfStream { break }
}
return out.isEmpty ? nil : out
}
/// [samples] (floats at 8000 Hz) written to [url] as a WAV
@@ -0,0 +1,381 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package org.dmodem.app.voice
import kotlin.math.pow
/**
* Sound files read as a voice call's samples (8000 Hz, one channel: the
* channels mixed, the rate converted), for a greeting chosen from a file.
* Read here, the same as the desktop apps' library: WAV (PCM of 8 to 32
* bits, 32 and 64-bit floats, A-law, μ-law, IMA and Microsoft ADPCM),
* AIFF and AIFF-C (PCM, floats, A-law, μ-law) and Sun/NeXT .au. The rest
* (MP3, AAC, FLAC, Ogg) the phone's own decoders read, and [mix] brings
* what they give to 8000 Hz.
*/
object SoundFile {
private const val PCM = 0
private const val FLOAT = 1
private const val ALAW = 2
private const val ULAW = 3
private const val IMA = 4
private const val MSADPCM = 5
/** what a file holds, and where */
private class Sound {
var enc = -1
var bits = 0
/** 0: little-endian, 1: big-endian, 2: big-endian with 8-bit samples signed */
var big = 0
var channels = 0
var block = 0
var rate = 0.0
var at = -1
var bytes = 0
/** MS ADPCM's coefficient pairs */
var coef: Array<IntArray> = emptyArray()
}
/** [data]'s samples at 8000 Hz, one channel; null if it isn't a file this reads */
fun decode(data: ByteArray): ShortArray? {
if (data.size < 12) return null
val f = Sound()
val ok = when {
tag(data, 0, "RIFF") && tag(data, 8, "WAVE") -> parseWav(data, f)
tag(data, 0, "FORM") && (tag(data, 8, "AIFF") || tag(data, 8, "AIFC")) -> parseAiff(data, f)
tag(data, 0, ".snd") -> parseAu(data, f)
else -> false
}
if (!ok || f.channels !in 1..8 || !(f.rate >= 1000) || f.rate > 384000) return null
val cap = mostFrames(f)
if (cap < 0 || cap > 100_000_000L) return null
val mono = ShortArray(cap.toInt())
val frames = decodeMono(data, f, mono)
if (frames < 0) return null
return resample(mono, frames, f.rate)
}
/**
* [n] interleaved frames of [pcm] ([channels] of them each, at [rate] Hz),
* as a voice call's samples: mixed to one channel, at 8000 Hz
*/
fun mix(pcm: ShortArray, n: Int, channels: Int, rate: Int): ShortArray {
if (channels < 1 || rate <= 0) return ShortArray(0)
val frames = minOf(n, pcm.size / channels)
val mono = ShortArray(frames) { i ->
var sum = 0
for (c in 0 until channels) sum += pcm[i * channels + c]
(sum / channels).toShort()
}
return resample(mono, frames, rate.toDouble())
}
/** [frames] of [mono] at [rate] Hz, at 8000 Hz (linear between the two around each) */
private fun resample(mono: ShortArray, frames: Int, rate: Double): ShortArray {
if (frames <= 0) return ShortArray(0)
val outN = (frames.toDouble() * VOICE_RATE / rate).toLong().toInt()
return ShortArray(outN) { i ->
val at = i.toDouble() * rate / VOICE_RATE
val k = at.toInt()
val frac = at - k
val k1 = if (k + 1 < frames) k + 1 else frames - 1
val y = (1 - frac) * mono[k] + frac * mono[k1]
y.coerceIn(-32768.0, 32767.0).toInt().toShort()
}
}
/** whether [s] is at [at] in [d] */
private fun tag(d: ByteArray, at: Int, s: String) =
at + s.length <= d.size && s.indices.all { d[at + it].toInt() == s[it].code }
/** the octet at [at] */
private fun u8(d: ByteArray, at: Int) = d[at].toInt() and 0xff
/** the 16 bits at [at], little-endian */
private fun u16(d: ByteArray, at: Int) = u8(d, at) or (u8(d, at + 1) shl 8)
/** the 32 bits at [at], little-endian */
private fun u32(d: ByteArray, at: Int): Long = u16(d, at).toLong() or (u16(d, at + 2).toLong() shl 16)
/** the 32 bits at [at], big-endian */
private fun b32(d: ByteArray, at: Int): Long =
(u8(d, at).toLong() shl 24) or (u8(d, at + 1).toLong() shl 16) or (u8(d, at + 2).toLong() shl 8) or u8(d, at + 3).toLong()
/** an 80-bit IEEE extended (AIFF's rate) */
private fun extended(d: ByteArray, at: Int): Double {
val e = (((u8(d, at) and 0x7f) shl 8) or u8(d, at + 1)) - 16383 - 63
val m = b32(d, at + 2).toDouble() * 4294967296.0 + b32(d, at + 6).toDouble()
val v = m * 2.0.pow(e)
return if (u8(d, at) and 0x80 != 0) -v else v
}
/** a RIFF WAVE's format and sound into [f]: false if this doesn't read it */
private fun parseWav(d: ByteArray, f: Sound): Boolean {
var p = 12
var fmt = false
var code = 0
while (d.size - p >= 8) {
val len = u32(d, p + 4)
val body = p + 8
val left = (d.size - body).toLong()
if (tag(d, p, "fmt ") && len >= 16 && left >= 16) {
code = u16(d, body)
f.channels = u16(d, body + 2)
f.rate = u32(d, body + 4).toDouble()
f.block = u16(d, body + 12)
f.bits = u16(d, body + 14)
// (WAVE_FORMAT_EXTENSIBLE: its subformat's code)
if (code == 0xfffe && len >= 26 && left >= 26) code = u16(d, body + 24)
if (code == 2 && len >= 22 && left >= 22) {
val k = u16(d, body + 20)
if (k > 64 || 22L + 4 * k > left) return false
f.coef = Array(k) { i ->
intArrayOf(u16(d, body + 22 + 4 * i).toShort().toInt(), u16(d, body + 24 + 4 * i).toShort().toInt())
}
}
fmt = true
} else if (tag(d, p, "data")) {
f.at = body
f.bytes = minOf(len, left).toInt()
break
}
if (len > left) break
p = body + len.toInt() + (len and 1).toInt()
}
if (!fmt || f.at < 0) return false
f.enc = when (code) {
1 -> PCM
3 -> FLOAT
6 -> ALAW
7 -> ULAW
0x11 -> IMA
2 -> MSADPCM
else -> return false
}
return true
}
/** an AIFF or AIFF-C's format and sound into [f]: false if this doesn't read it */
private fun parseAiff(d: ByteArray, f: Sound): Boolean {
val aifc = tag(d, 8, "AIFC")
var p = 12
var comm = false
var comp = "NONE"
while (d.size - p >= 8) {
val len = b32(d, p + 4)
val body = p + 8
val left = (d.size - body).toLong()
if (tag(d, p, "COMM") && len >= 18 && left >= 18) {
f.channels = (u8(d, body) shl 8) or u8(d, body + 1)
f.bits = (u8(d, body + 6) shl 8) or u8(d, body + 7)
f.rate = extended(d, body + 8)
if (aifc && len >= 22 && left >= 22) comp = (0 until 4).map { u8(d, body + 18 + it).toChar() }.joinToString("")
comm = true
} else if (tag(d, p, "SSND") && len >= 8 && left >= 8) {
val off = b32(d, body)
val l = minOf(len, left)
if (off > l - 8) return false
f.at = body + 8 + off.toInt()
f.bytes = (l - 8 - off).toInt()
}
if (len > left) break
p = body + len.toInt() + (len and 1).toInt()
}
if (!comm || f.at < 0) return false
f.big = 1
when (comp) {
"NONE", "twos" -> f.enc = PCM
"sowt" -> { f.enc = PCM; f.big = 0 }
"fl32", "FL32" -> { f.enc = FLOAT; f.bits = 32 }
"fl64", "FL64" -> { f.enc = FLOAT; f.bits = 64 }
"ulaw", "ULAW" -> { f.enc = ULAW; f.bits = 8 }
"alaw", "ALAW" -> { f.enc = ALAW; f.bits = 8 }
else -> return false
}
// (AIFF's 8-bit samples are signed)
if (f.enc == PCM && f.bits == 8) f.big = 2
return true
}
/** a Sun/NeXT .au's format and sound into [f]: false if this doesn't read it */
private fun parseAu(d: ByteArray, f: Sound): Boolean {
if (d.size < 24) return false
val off = b32(d, 4)
val len = b32(d, 8)
val enc = b32(d, 12)
f.rate = b32(d, 16).toDouble()
f.channels = b32(d, 20).coerceAtMost(Int.MAX_VALUE.toLong()).toInt()
if (off < 24 || off > d.size) return false
f.at = off.toInt()
f.bytes = d.size - f.at
if (len != 0xffffffffL && len < f.bytes) f.bytes = len.toInt()
f.big = 1
when (enc) {
1L -> { f.enc = ULAW; f.bits = 8 }
2L -> { f.enc = PCM; f.bits = 8; f.big = 2 }
3L -> { f.enc = PCM; f.bits = 16 }
4L -> { f.enc = PCM; f.bits = 24 }
5L -> { f.enc = PCM; f.bits = 32 }
6L -> { f.enc = FLOAT; f.bits = 32 }
7L -> { f.enc = FLOAT; f.bits = 64 }
27L -> { f.enc = ALAW; f.bits = 8 }
else -> return false
}
return true
}
/** a sample [w] octets wide at [q] as 16 bits ([big] as [Sound.big]) */
private fun pcmAt(d: ByteArray, q: Int, w: Int, big: Int): Int {
if (w == 1) return if (big == 2) d[q].toInt() * 256 else (u8(d, q) - 128) * 256
var v = 0L
for (i in 0 until w) v = v or (u8(d, if (big != 0) q + i else q + w - 1 - i).toLong() shl (8 * (w - 1 - i)))
// (the top two octets: the sample's sign is the top bit)
return (v ushr (8 * (w - 2))).toInt().toShort().toInt()
}
/** a float [w] octets wide at [q] as 16 bits */
private fun floatAt(d: ByteArray, q: Int, w: Int, big: Int): Int {
var v = 0L
for (i in 0 until w) v = v or (u8(d, if (big != 0) q + w - 1 - i else q + i).toLong() shl (8 * i))
val x = if (w == 4) Float.fromBits(v.toInt()).toDouble() else Double.fromBits(v)
if (x.isNaN()) return 0
return (x * 32767.0).coerceIn(-32768.0, 32767.0).toInt()
}
private val imaSteps = intArrayOf(
7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31, 34,
37, 41, 45, 50, 55, 60, 66, 73, 80, 88, 97, 107, 118, 130, 143,
157, 173, 190, 209, 230, 253, 279, 307, 337, 371, 408, 449, 494,
544, 598, 658, 724, 796, 876, 963, 1060, 1166, 1282, 1411, 1552,
1707, 1878, 2066, 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428,
4871, 5358, 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487,
12635, 13899, 15289, 16818, 18500, 20350, 22385, 24623, 27086,
29794, 32767,
)
private val imaIndex = intArrayOf(-1, -1, -1, -1, 2, 4, 6, 8, -1, -1, -1, -1, 2, 4, 6, 8)
private val msAdapt = intArrayOf(230, 230, 230, 230, 307, 409, 512, 614, 768, 614, 512, 409, 307, 230, 230, 230)
/** the most frames [f] could hold */
private fun mostFrames(f: Sound): Long {
if (f.enc == IMA || f.enc == MSADPCM) {
if (f.block <= 0) return 0
return (f.bytes.toLong() / f.block + 1) * (f.block.toLong() * 2 + 2)
}
if (f.bits < 8) return 0
return f.bytes.toLong() / ((f.bits / 8).toLong() * f.channels)
}
/** [f]'s sound into [out], its channels mixed: how many frames, -1 if it can't */
private fun decodeMono(d: ByteArray, f: Sound, out: ShortArray): Int {
val ch = f.channels
val cap = out.size
val end = f.at + f.bytes
var fr = 0
when (f.enc) {
IMA -> {
// blocks: per channel a header (sample, index), then 4-octet
// groups of 8 nibbles per channel in turn
val per = if (f.block > 4 * ch) (f.block - 4 * ch) * 2 / ch + 1 else 0
if (per <= 0 || per > 65536) return -1
var b = f.at
val pred = IntArray(ch)
val idx = IntArray(ch)
while (end - b >= f.block && fr < cap) {
val n = minOf(per, cap - fr)
for (c in 0 until ch) {
pred[c] = u16(d, b + 4 * c).toShort().toInt()
idx[c] = minOf(u8(d, b + 4 * c + 2), 88)
}
for (c in 0 until ch) {
if (n > 0) out[fr] = (out[fr] + pred[c] / ch).toShort()
var k = 1
var q = b + 4 * ch + 4 * c
while (k < per && q + 4 <= b + f.block) {
var j = 0
while (j < 8 && k < per) {
val nib = (u8(d, q + j / 2) shr ((j and 1) * 4)) and 15
val step = imaSteps[idx[c]]
var diff = step shr 3
if (nib and 4 != 0) diff += step
if (nib and 2 != 0) diff += step shr 1
if (nib and 1 != 0) diff += step shr 2
pred[c] = (pred[c] + if (nib and 8 != 0) -diff else diff).coerceIn(-32768, 32767)
idx[c] = (idx[c] + imaIndex[nib]).coerceIn(0, 88)
if (k < n) out[fr + k] = (out[fr + k] + pred[c] / ch).toShort()
j++
k++
}
q += 4 * ch
}
}
fr += n
b += f.block
}
return fr
}
MSADPCM -> {
if (ch > 2 || f.coef.isEmpty() || f.block < 7 * ch) return -1
val per = (f.block - 7 * ch) * 2 / ch + 2
var b = f.at
val pred = IntArray(ch)
val delta = IntArray(ch)
val s1 = IntArray(ch)
val s2 = IntArray(ch)
while (end - b >= f.block && fr < cap) {
var q = b
val n = minOf(per, cap - fr)
for (c in 0 until ch) pred[c] = u8(d, q + c).let { if (it < f.coef.size) it else 0 }
q += ch
for (c in 0 until ch) { delta[c] = u16(d, q).toShort().toInt(); q += 2 }
for (c in 0 until ch) { s1[c] = u16(d, q).toShort().toInt(); q += 2 }
for (c in 0 until ch) { s2[c] = u16(d, q).toShort().toInt(); q += 2 }
// (the header's two samples: the older first)
if (n > 0) out[fr] = (s2.sum() / ch).toShort()
if (n > 1) out[fr + 1] = (s1.sum() / ch).toShort()
for (k in 2 until per) {
var v = 0L
for (c in 0 until ch) {
val ni = (k - 2) * ch + c
val nib = (u8(d, q + ni / 2) shr (if (ni and 1 != 0) 0 else 4)) and 15
val sn = if (nib and 8 != 0) nib - 16 else nib
val co = f.coef[pred[c]]
var p = (s1[c].toLong() * co[0] + s2[c].toLong() * co[1]) / 256
p += sn.toLong() * delta[c]
p = p.coerceIn(-32768L, 32767L)
s2[c] = s1[c]
s1[c] = p.toInt()
// (a broken file's grows without end)
delta[c] = (delta[c].toLong() * msAdapt[nib] / 256).toInt().coerceIn(16, 0x100000)
v += p
}
if (k < n) out[fr + k] = (v / ch).toInt().toShort()
}
fr += n
b += f.block
}
return fr
}
else -> {
val w = f.bits / 8
if (w < 1 || w > 8 || (f.enc == PCM && w > 4) || (f.enc == FLOAT && w != 4 && w != 8) ||
((f.enc == ALAW || f.enc == ULAW) && w != 1)
) return -1
val frames = minOf(f.bytes.toLong() / (w.toLong() * ch), cap.toLong()).toInt()
for (i in 0 until frames) {
var sum = 0L
for (c in 0 until ch) {
val q = f.at + (i * ch + c) * w
sum += when (f.enc) {
ULAW -> G711.unulaw(u8(d, q))
ALAW -> G711.unalaw(u8(d, q))
FLOAT -> floatAt(d, q, w, f.big)
else -> pcmAt(d, q, w, f.big)
}
}
out[i] = (sum / ch).toInt().toShort()
}
return frames
}
}
}
}
@@ -6,9 +6,8 @@ import org.dmodem.app.io.Sink
/**
* WAV files: a voice call's samples written (16 bit PCM, 8000 Hz, mono:
* the answering machine's messages, a recorded greeting), and any PCM,
* A-law or μ-law WAV read as those (a greeting chosen from a file: mixed
* to one channel, resampled to 8000 Hz).
* the answering machine's messages, a recorded greeting), and sound
* files read as those ([SoundFile]: a greeting chosen from a file).
*/
object Wav {
/** the 44-octet header of a WAV of [n] samples */
@@ -57,76 +56,6 @@ object Wav {
/** a WAV file's length in seconds, from its size (one written here) */
fun seconds(fileSize: Long): Int = (maxOf(fileSize - 44, 0) / (VOICE_RATE * 2)).toInt()
/** a WAV file's samples at 8000 Hz, one channel; null if it isn't a WAV this reads */
fun decode(data: ByteArray): ShortArray? {
/** the 16 bits at [at], little-endian */
fun u16(at: Int) = (data[at].toInt() and 0xff) or ((data[at + 1].toInt() and 0xff) shl 8)
/** the 32 bits at [at], little-endian */
fun u32(at: Int): Long = u16(at).toLong() or (u16(at + 2).toLong() shl 16)
/** whether [s] is at [at] */
fun tag(at: Int, s: String) = s.indices.all { data[at + it].toInt() == s[it].code }
if (data.size < 12 || !tag(0, "RIFF") || !tag(8, "WAVE")) return null
var format = 0
var channels = 0
var bits = 0
var rate = 0L
var samples = -1
var bytes = 0
var haveFmt = false
var p = 12
while (data.size - p >= 8) {
val len = u32(p + 4)
val body = p + 8
val left = (data.size - body).toLong()
if (tag(p, "fmt ") && len >= 16 && left >= 16) {
format = u16(body)
channels = u16(body + 2)
rate = u32(body + 4)
bits = u16(body + 14)
// (WAVE_FORMAT_EXTENSIBLE: its subformat's code)
if (format == 0xfffe && len >= 26 && left >= 26) format = u16(body + 24)
haveFmt = true
} else if (tag(p, "data")) {
samples = body
bytes = minOf(len, left).toInt()
break
}
if (len > left) break
p = body + len.toInt() + (len and 1).toInt()
}
if (!haveFmt || samples < 0 || channels !in 1..8 || rate !in 1000..192000) return null
val width = when {
format == 1 && (bits == 8 || bits == 16) -> bits / 8
(format == 6 || format == 7) && bits == 8 -> 1
else -> return null
}
val frames = bytes / (width * channels)
if (frames <= 0) return ShortArray(0)
val outN = (frames.toDouble() * VOICE_RATE / rate).toLong().toInt()
/** channel [c] of frame [frame] as a 16-bit sample */
fun sample(frame: Int, c: Int): Int {
val q = samples + (frame * channels + c) * width
return when {
format == 7 -> G711.unulaw(data[q].toInt() and 0xff)
format == 6 -> G711.unalaw(data[q].toInt() and 0xff)
width == 1 -> ((data[q].toInt() and 0xff) - 128) * 256
else -> u16(q).toShort().toInt()
}
}
return ShortArray(outN) { i ->
// (linear between the two frames around it, each the mean of its channels)
val at = i.toDouble() * rate / VOICE_RATE
val f = at.toInt()
val frac = at - f
var y = 0.0
for (k in 0..1) {
val ff = minOf(f + k, frames - 1)
var sum = 0.0
for (c in 0 until channels) sum += sample(ff, c)
sum /= channels
y += if (k == 1) frac * sum else (1 - frac) * sum
}
y.coerceIn(-32768.0, 32767.0).toInt().toShort()
}
}
/** a sound file's samples at 8000 Hz, one channel; null if it isn't one this reads ([SoundFile]) */
fun decode(data: ByteArray): ShortArray? = SoundFile.decode(data)
}
@@ -0,0 +1,119 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package org.dmodem.app.voice
import kotlin.math.abs
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
/** Sound files other than 16-bit WAV read as a voice call's samples (the desktop library's tests, the same files) */
class SoundFileTest {
/** [hex]'s octets */
private fun bytes(hex: String) = ByteArray(hex.length / 2) { hex.substring(2 * it, 2 * it + 2).toInt(16).toByte() }
/** [v] into [b] at [at], big-endian, 16 bits */
private fun be16(b: ByteArray, at: Int, v: Int) { b[at] = (v shr 8).toByte(); b[at + 1] = v.toByte() }
/** [v] into [b] at [at], big-endian, 32 bits */
private fun be32(b: ByteArray, at: Int, v: Long) { be16(b, at, (v shr 16).toInt()); be16(b, at + 2, v.toInt()) }
/** [s]'s characters into [b] at [at] */
private fun tag(b: ByteArray, at: Int, s: String) = s.forEachIndexed { i, c -> b[at + i] = c.code.toByte() }
/** an AIFF of 16-bit samples, big-endian, 8000 Hz, mono */
@Test
fun aiff() {
val a = ByteArray(12 + 26 + 16 + 8)
tag(a, 0, "FORM"); be32(a, 4, a.size - 8L); tag(a, 8, "AIFF")
tag(a, 12, "COMM"); be32(a, 16, 18)
be16(a, 20, 1); be32(a, 22, 4); be16(a, 26, 16)
// (8000 as an 80-bit extended: 0x400B FA00...)
a[28] = 0x40; a[29] = 0x0b; a[30] = 0xfa.toByte()
tag(a, 38, "SSND"); be32(a, 42, 16)
be16(a, 54, 0x1000); be16(a, 56, 0xf000); be16(a, 58, 0x7fff); be16(a, 60, 0x8000)
assertContentEquals(shortArrayOf(4096, -4096, 32767, -32768), SoundFile.decode(a))
}
/** a Sun .au of μ-law, 8000 Hz, mono */
@Test
fun au() {
val u = ByteArray(27)
tag(u, 0, ".snd"); be32(u, 4, 24); be32(u, 8, 3); be32(u, 12, 1); be32(u, 16, 8000); be32(u, 20, 1)
u[24] = 0xff.toByte(); u[25] = 0; u[26] = 0x80.toByte()
assertContentEquals(shortArrayOf(0, -32124, 32124), SoundFile.decode(u))
}
/** WAVs of 24-bit samples and of 32-bit floats */
@Test
fun wideWav() {
val w = Wav.header(3).copyOf(50)
w[32] = 3; w[34] = 24; w[40] = 6
bytes("000040" + "0000c0").copyInto(w, 44)
assertContentEquals(shortArrayOf(16384, -16384), SoundFile.decode(w))
val f = Wav.header(4).copyOf(52)
f[20] = 3; f[32] = 4; f[34] = 32; f[40] = 8
// 0.5, -1.0
bytes("0000003f" + "000080bf").copyInto(f, 44)
assertContentEquals(shortArrayOf(16383, -32767), SoundFile.decode(f))
}
/** ADPCM: Microsoft's as ffmpeg decodes it, IMA within a few steps (ffmpeg's arithmetic is finer than the IMA's own) */
@Test
fun adpcm() {
val at = intArrayOf(1, 5, 9, 100, 300, 577)
val ms = assertNotNull(SoundFile.decode(bytes(MS_WAV)))
assertEquals(580, ms.size)
assertContentEquals(intArrayOf(1567, 3890, -1630, 4191, -4014, -40), IntArray(at.size) { ms[at[it]].toInt() })
val ima = assertNotNull(SoundFile.decode(bytes(IMA_WAV)))
assertEquals(605, ima.size)
val want = intArrayOf(13, 536, -1554, 4238, -3936, 8)
for (i in at.indices) assertTrue(abs(ima[at[i]] - want[i]) <= 8, "sample ${at[i]}: ${ima[at[i]]}, not ${want[i]}")
}
/** a phone's decoder's 44.1 kHz stereo brought to 8000 Hz, one channel */
@Test
fun mixed() {
val pcm = ShortArray(44100 * 2) { if (it % 2 == 0) 1000 else 3000 }
val m = SoundFile.mix(pcm, 44100, 2, 44100)
assertEquals(8000, m.size)
assertTrue(m.all { it.toInt() == 2000 })
}
/** what isn't a sound file this reads */
@Test
fun notOnes() {
assertNull(SoundFile.decode(bytes("464f524d00000004" + "41494646")))
assertNull(SoundFile.decode(bytes("494433040000000000000000")))
assertNull(SoundFile.decode(ByteArray(3)))
}
private companion object {
/** ffmpeg -f lavfi -i sine=f=500:r=8000:d=0.07 -c:a adpcm_ima_wav -block_size 64 */
val IMA_WAV =
"524946469601000057415645666d74201400000011000100401f0000803e000040000400020079006661637404000000" +
"300200004c4953541a000000494e464f495346540e0000004c61766636302e31362e3130300064617461400100000000" +
"0000777777f2ad9921533312b9cdbb8a30453312b9cdbb9a31453312b9cdbb9a31453312b9cdbb9a31453312b9cdbb9a" +
"31453312b9cdbb9a31453312b9cde1f939009b1952432380dbcbab1852432390dacbab1852432390dacbab1852432390" +
"dacbab1852432390dacbab1852432390dacbab1852432390dacbab185243500b390002a9ccbb8a30453312b9cdbb8a30" +
"453302b8cdbb8a30453302b8cdbb8a30453302b8cdbb8a30453302b8cdbb8a30453302b8cdbb8a30453302b8cdbb39f1" +
"37000843442280cbbcab0853342391dbbcab0853342391dbbcab0853342391dbbcab0853342391dbbcab0853342391db" +
"bcab1953342391dbbcab19533423ff0f3600b8bdbc8a21353402a9bdbc8a21353402a9bdbc8a21353402a9bdbc8a2135" +
"3402a9bdbc8a213580808080808080808080808000880088008800880008"
/** the same, -c:a adpcm_ms */
val MS_WAV =
"52494646b401000057415645666d74203200000002000100401f0000803e000040000400200074000700000100000002" +
"00ff00000000c0004000f0000000cc0130ff880118ff6661637404000000300200004c4953541a000000494e464f4953" +
"46540e0000004c61766636302e31362e3130300064617461400100000010001f0600007776ecdcdff125343200dbdcde" +
"0035343200dbdcde0035343200dbdcdef13534321fdbdcdef13534321fdbdcdef13534321fdbdcdef1353432008701c7" +
"0eff0feccddef13543321fdbcddef13543321fdbcddef13543321fdbcddef13543321fdbcddef13543321fdbcddef135" +
"43321fdbcddef13543321fdb009901e1f90000ddf14444221fdccdce003444221fdccdce012444221fdccdce01244422" +
"1fdccdce012444221fdccdce012444221fdccdce012444221fdccdce00b70139f101f02353221febdcde003534320feb" +
"dcde0035343200dbdcde0035343200dbdcdef13534321fdbdcdef13534321fdbdcdef13534321fdbdcdef13500c4011f" +
"060000321fdbcddef13543321fdbcddef13543321fdbcddef13543321fdbcddef13543321fdbcddef13543321fdbcdde" +
"f135400000000000000f1f1f"
}
}