harvest/game/scripts/coop_voice.gd
Forrest 39f9d15cfe Co-op voice/session work, config retune, net budget tool, overhaul plan
Snapshot of in-progress work before the alien overhaul so worker
worktrees branch from current code.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 13:35:53 -04:00

245 lines
8 KiB
GDScript

class_name CoopVoice
extends VoiceChat
## Voice chat in co-op: GD-Sync's VoiceChat, one per player at the same path on both machines
## (CoopSession/Voice1 for player 1, Voice2 for player 2). Each is owned by its player's GD-Sync
## client: the owner's microphone is recorded and sent, and the other machine plays it on the
## Voice bus. GD-Sync's capture and playback are kept; the sending is this class's own: GD-Sync's
## sends the raw samples (32-bit floats) every frame the microphone peaks over a threshold, about
## 60 KB/s. Here the microphone is resampled to RATE and cut into pieces of CHUNK samples (60 ms),
## and each piece of speech goes out as 4-bit IMA ADPCM (encode, decode: 3 + CHUNK / 2 bytes, about
## 6 KB/s while talking). A piece is loud when at least LOUD_PARTS of its four 15 ms parts are
## (RMS over gate_rms), so a click or a knock spread over two pieces doesn't count; the gate opens
## after GATE_OPEN loud pieces in a row, sends the piece before them too (the start of the first
## word), and stays open GATE_HOLD seconds after the last loud piece. Each piece starts with the
## codec's state, so a lost one costs only its own 60 ms.
## This also notes when the voice was last heard, for the "speaking" mark on the partner HUD.
const RATE := 12000
const CHUNK := 720
const GATE_OPEN := 2
const LOUD_PARTS := 2
const GATE_HOLD := 0.4
## Seconds of voice the playback buffer holds (room for a piece that arrives late).
const BUFFER := 0.3
const STEPS: Array[int] = [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]
const INDEX_STEP: Array[int] = [-1, -1, -1, -1, 2, 4, 6, 8]
## Seconds of the game clock when audio last arrived (-1000 = never).
var last_heard: float = -1000.0
## A piece louder than this (RMS, full scale 1) counts as speech.
var gate_rms: float = 0.01
## Pieces sent so far (for tests and the traffic tool).
var pieces_sent: int = 0
# Sending: the resampler (a box filter), the piece being filled, the gate, the codec's state.
var _phase: float = 0.0
var _sum: float = 0.0
var _summed: int = 0
var _piece := PackedFloat32Array()
var _waiting: Array[PackedFloat32Array] = [] # pieces held while the gate is shut
var _loud: int = 0
var _open_left: float = 0.0
var _codec := [0, 0] # predictor, step index
static func make(slot: int) -> CoopVoice:
var v := CoopVoice.new()
v.name = "Voice%d" % (slot + 1)
var out := AudioStreamPlayer.new()
out.name = "Out"
out.bus = &"Voice"
v.add_child(out)
v.set_output_player(out)
return v
func _ready() -> void:
super()
if not Engine.is_editor_hint() and GDSync != null:
GDSync.expose_func(_receive_voice)
func speaking() -> bool:
return Time.get_ticks_msec() / 1000.0 - last_heard < 0.35
func mute_microphone() -> void:
super()
_reset_gate()
## Replaces GD-Sync's sending (see the top).
func _process(_delta: float) -> void:
if GDSync == null or not _input_configured or not GDSync.is_gdsync_owner(self):
return
var n := _record_effect.get_frames_available()
if n <= 0:
return
if _muted:
_record_effect.clear_buffer()
return
for piece in feed(_record_effect.get_buffer(n), AudioServer.get_mix_rate()):
GDSync.call_func_relevant_unreliable(_receive_voice, piece)
## Microphone frames (stereo, at mix_rate) in; the encoded pieces to send out, if any.
func feed(frames: PackedVector2Array, mix_rate: float) -> Array[PackedByteArray]:
var out: Array[PackedByteArray] = []
var step := RATE / mix_rate
for f in frames:
_sum += (f.x + f.y) * 0.5
_summed += 1
_phase += step
if _phase < 1.0:
continue
_phase -= 1.0
_piece.append(_sum / _summed)
_sum = 0.0
_summed = 0
if _piece.size() == CHUNK:
_gate(_piece, out)
_piece = PackedFloat32Array()
return out
func _gate(piece: PackedFloat32Array, out: Array[PackedByteArray]) -> void:
var loud := loud_parts(piece, gate_rms) >= LOUD_PARTS
_loud = _loud + 1 if loud else 0
if _open_left <= 0.0:
if _loud < GATE_OPEN:
_waiting.append(piece)
if _waiting.size() > GATE_OPEN:
_waiting.pop_front()
return
for held in _waiting: # the quiet piece before the speech, and its start
out.append(_encode_next(held))
_waiting.clear()
if loud:
_open_left = GATE_HOLD
else:
_open_left -= float(CHUNK) / RATE
out.append(_encode_next(piece))
func _encode_next(piece: PackedFloat32Array) -> PackedByteArray:
pieces_sent += 1
var bytes := encode(piece, _codec)
return bytes
func _reset_gate() -> void:
_waiting.clear()
_loud = 0
_open_left = 0.0
_piece = PackedFloat32Array()
## A piece from the other machine: decoded into the playback buffer.
func _receive_voice(piece: PackedByteArray) -> void:
last_heard = Time.get_ticks_msec() / 1000.0
if _output_stream_playback == null:
return
var samples := decode(piece)
var room := mini(_output_stream_playback.get_frames_available(), samples.size())
var frames := PackedVector2Array()
frames.resize(room)
for i in room:
frames[i] = Vector2(samples[i], samples[i])
_output_stream_playback.push_buffer(frames)
## GD-Sync's raw audio (another build's VoiceChat): not played; this one's comes as pieces.
func _process_audio(_audio: PackedFloat32Array, _mixrate: float) -> void:
pass
func _configure_output() -> void:
if _output_configured:
return
_output_configured = true
_output_stream = AudioStreamGenerator.new()
_output_stream.mix_rate = RATE
_output_stream.buffer_length = BUFFER
_output_player.stream = _output_stream
_output_player.play()
_output_stream_playback = _output_player.get_stream_playback()
## How many of the piece's four parts are louder than threshold (RMS).
static func loud_parts(piece: PackedFloat32Array, threshold: float) -> int:
var n := 0
var part := piece.size() / 4
for p in 4:
var sum := 0.0
for i in range(p * part, (p + 1) * part):
sum += piece[i] * piece[i]
if sum / maxi(part, 1) >= threshold * threshold:
n += 1
return n
## IMA ADPCM: the codec's state (predictor, step index) at the start, then two samples a byte
## (low nibble first). state carries over from piece to piece and is updated.
static func encode(samples: PackedFloat32Array, state: Array) -> PackedByteArray:
var predictor: int = state[0]
var index: int = state[1]
var out := PackedByteArray()
out.resize(3 + (samples.size() + 1) / 2)
out.encode_s16(0, predictor)
out[2] = index
for i in samples.size():
var target := clampi(roundi(samples[i] * 32767.0), -32768, 32767)
var step: int = STEPS[index]
var diff := target - predictor
var code := 0
if diff < 0:
code = 8
diff = -diff
var delta := step >> 3
if diff >= step:
code |= 4
diff -= step
delta += step
if diff >= step >> 1:
code |= 2
diff -= step >> 1
delta += step >> 1
if diff >= step >> 2:
code |= 1
delta += step >> 2
predictor = clampi(predictor - delta if code & 8 else predictor + delta, -32768, 32767)
index = clampi(index + INDEX_STEP[code & 7], 0, STEPS.size() - 1)
if i % 2 == 0:
out[3 + i / 2] = code
else:
out[3 + i / 2] |= code << 4
state[0] = predictor
state[1] = index
return out
static func decode(piece: PackedByteArray) -> PackedFloat32Array:
var out := PackedFloat32Array()
if piece.size() < 3:
return out
var predictor := piece.decode_s16(0)
var index := clampi(piece[2], 0, STEPS.size() - 1)
out.resize((piece.size() - 3) * 2)
for i in out.size():
var code := (piece[3 + i / 2] >> (4 * (i % 2))) & 15
var step: int = STEPS[index]
var delta := step >> 3
if code & 4:
delta += step
if code & 2:
delta += step >> 1
if code & 1:
delta += step >> 2
predictor = clampi(predictor - delta if code & 8 else predictor + delta, -32768, 32767)
index = clampi(index + INDEX_STEP[code & 7], 0, STEPS.size() - 1)
out[i] = predictor / 32768.0
return out