Add Face realtime voice bridge

This commit is contained in:
Meta Vens 2026-05-18 02:37:59 +01:00
commit fe6e98941f
10 changed files with 661 additions and 5 deletions

View file

@ -17,6 +17,8 @@ public interface IAquariumRuntime : IDisposable
AquariumUiDocument Ui { get; }
AquariumAudioDocument Audio { get; }
AquariumSynthDocument Synth { get; }
void Start();

View file

@ -0,0 +1,65 @@
using System.Collections.Concurrent;
namespace Aquarium.Engine.Audio;
public sealed class AquariumAudioDocument
{
private readonly ConcurrentQueue<AquariumPcmAudioChunk> pcmChunks = new();
public static AquariumAudioDocument Empty { get; } = new();
public void EnqueuePcm16Base64(string base64Data, int sampleRate, int channels, float gain = 1.0f)
{
if (string.IsNullOrWhiteSpace(base64Data) || sampleRate <= 0 || channels <= 0)
{
return;
}
byte[] bytes;
try
{
bytes = Convert.FromBase64String(base64Data);
}
catch (FormatException)
{
return;
}
var frameCount = bytes.Length / Math.Max(1, channels) / 2;
if (frameCount <= 0)
{
return;
}
var mono = new float[frameCount];
var byteIndex = 0;
var safeGain = Math.Clamp(gain, 0.0f, 4.0f);
for (var frame = 0; frame < frameCount; frame++)
{
var sum = 0.0f;
for (var channel = 0; channel < channels && byteIndex + 1 < bytes.Length; channel++)
{
var sample = (short)(bytes[byteIndex] | (bytes[byteIndex + 1] << 8));
sum += sample / 32768.0f;
byteIndex += 2;
}
mono[frame] = Math.Clamp(sum / channels * safeGain, -1.0f, 1.0f);
}
pcmChunks.Enqueue(new AquariumPcmAudioChunk(mono, sampleRate));
}
public IReadOnlyList<AquariumPcmAudioChunk> DrainPcmChunks(int maxChunks = 64)
{
var drained = new List<AquariumPcmAudioChunk>();
while (drained.Count < maxChunks && pcmChunks.TryDequeue(out var chunk))
{
drained.Add(chunk);
}
return drained;
}
}
public sealed record AquariumPcmAudioChunk(float[] MonoSamples, int SampleRate);

View file

@ -58,7 +58,7 @@ public static class AquariumHost
SyncRendererSettingsToRuntime(renderer, runtimeLoader.Runtime);
runtimeLoader.Update(deltaSeconds, runtimeInput);
synthHost.Update(AquariumSynthDocument.Combine(runtimeLoader.Runtime.Synth, renderer.DebugSynth), deltaSeconds);
synthHost.Update(AquariumSynthDocument.Combine(runtimeLoader.Runtime.Synth, renderer.DebugSynth), runtimeLoader.Runtime.Audio, deltaSeconds);
if (!ReferenceEquals(settingsRuntime, runtimeLoader.Runtime))
{
settingsRuntime = runtimeLoader.Runtime;

View file

@ -11,9 +11,14 @@ internal sealed class AquariumSynthHost : IDisposable
private readonly AquaSynthRenderSession renderSession = new(new AquaSynthNativeOptions(DspSourceDirectory: Path.Combine(AppContext.BaseDirectory, "Synth")));
private float timeSeconds;
public void Update(AquariumSynthDocument synth, float deltaSeconds)
public void Update(AquariumSynthDocument synth, AquariumAudioDocument audio, float deltaSeconds)
{
timeSeconds += Math.Max(deltaSeconds, 0.0f);
foreach (var chunk in audio.DrainPcmChunks())
{
audioDevice.Play(chunk.MonoSamples, chunk.SampleRate);
}
if (!synth.Enabled)
{
return;

View file

@ -5,6 +5,7 @@ using Aquarium.Engine.Input;
using Aquarium.Engine.Render;
using Aquarium.Engine.Ui;
using Aquarium.Epiphany.State;
using Aquarium.Epiphany.Voice;
namespace Aquarium.Epiphany;
@ -14,6 +15,7 @@ public sealed class AquariumRuntime : IAquariumRuntime
private readonly OrbitCameraRig cameraRig;
private readonly AquariumCultStateStore stateStore;
private readonly RealtimeFaceVoiceSession faceVoice;
private ViewFrame ViewFrame;
private GraphicsSettings graphicsSettings;
@ -23,6 +25,7 @@ public sealed class AquariumRuntime : IAquariumRuntime
private float secondsSinceStateSave;
private bool graphicsSettingsDirty;
private bool timePaused;
private string faceVoiceText = "";
public AquariumRuntime(AquariumRuntimeOptions options)
{
Options = options;
@ -43,12 +46,32 @@ public sealed class AquariumRuntime : IAquariumRuntime
ViewFrame = ViewFrame.FromCamera(cameraRig.Target, cameraRig.Distance);
previousFrameTimeSeconds = timeSeconds;
previousCursorWorld = ViewFrame.Center;
faceVoice = new RealtimeFaceVoiceSession(Audio)
{
AppServerUri = liveState.FaceVoiceAppServerUri,
ThreadId = liveState.FaceVoiceThreadId,
Voice = liveState.FaceVoiceVoice,
Prompt = liveState.FaceVoicePrompt
};
Ui = new AquariumUiDocument()
.Panel("Epiphany", 396.0f, 82.0f, 360.0f, panel => panel
.Section("Runtime")
.Toggle("Pause Time", () => timePaused, value => timePaused = value, "Stops Epiphany simulation time while leaving the renderer alive.")
.Slider("Time", () => timeSeconds, value => timeSeconds = MathF.Max(0.0f, value), 0.0f, 720.0f, "0.0", "Scrubs Epiphany simulation time.")
.Button("Flush State", FlushState, "Writes current Epiphany runtime state to CultCache."))
.Button("Flush State", FlushState, "Writes current Epiphany runtime state to CultCache.")
.Section("Face Voice")
.Text("App Server", () => faceVoice.AppServerUri, value => faceVoice.AppServerUri = value.Trim(), "Loopback Codex app-server websocket, e.g. ws://127.0.0.1:8765.")
.Text("Thread", () => faceVoice.ThreadId, value => faceVoice.ThreadId = value.Trim(), "Thread id that owns the realtime Face session.")
.Text("Voice", () => faceVoice.Voice, value => faceVoice.Voice = value.Trim(), "Realtime voice name, such as marin, cedar, or cove.")
.Readout("Status", () => faceVoice.Status, "Realtime transport status.")
.Readout("Audio", () => faceVoice.AudioStats, "Received output-audio chunks from Codex realtime.")
.TextBox("Prompt", () => faceVoice.Prompt, value => faceVoice.Prompt = value, lines: 3, acceptsReturn: true, monospace: false, tooltip: "Backend realtime instructions for Face. This is speech behavior, not memory authority.")
.TextBox("Say", () => faceVoiceText, value => faceVoiceText = value, lines: 2, acceptsReturn: false, submit: SendFaceVoiceText, monospace: false, tooltip: "Send one text utterance through Face voice.")
.Button("Start Voice", faceVoice.Start, "Starts a thread-scoped realtime session with audio output.")
.Button("Stop Voice", faceVoice.Stop, "Stops the realtime Face voice session.")
.Button("Clear Voice Log", faceVoice.ClearTranscript, "Clears local transcript and audio counters.")
.Readout("Error", () => faceVoice.LastError, "Last realtime transport error.")
.TextBox("Transcript", () => faceVoice.Transcript, _ => { }, lines: 7, acceptsReturn: true, monospace: false, tooltip: "Local ephemeral realtime transcript. It is not durable Epiphany memory."))
.Command("pause", args =>
{
timePaused = args.Count == 0 ? !timePaused : bool.TryParse(args[0], out var value) && value;
@ -67,7 +90,35 @@ public sealed class AquariumRuntime : IAquariumRuntime
{
FlushState();
return "state flushed";
}, "Flushes Epiphany state to CultCache.");
}, "Flushes Epiphany state to CultCache.")
.Command("facevoice", args =>
{
if (args.Count == 0)
{
return $"Face voice {faceVoice.Status}; audio {faceVoice.AudioStats}";
}
var verb = args[0].Trim().ToLowerInvariant();
if (verb == "start")
{
faceVoice.Start();
return "Face voice starting";
}
if (verb == "stop")
{
faceVoice.Stop();
return "Face voice stopping";
}
if (verb == "say" && args.Count > 1)
{
faceVoice.SendText(string.Join(" ", args.Skip(1)));
return "Face voice text sent";
}
return "facevoice start | stop | say <text>";
}, "Controls the Face realtime voice session.");
}
public AquariumRuntimeOptions Options { get; }
@ -76,6 +127,8 @@ public sealed class AquariumRuntime : IAquariumRuntime
public AquariumUiDocument Ui { get; }
public AquariumAudioDocument Audio { get; } = new();
public AquariumSynthDocument Synth { get; } = AquariumSynthDocument.Empty;
public AquariumFrame Frame => new(ViewFrame, cameraRig.Position, timeSeconds);
@ -148,6 +201,7 @@ public sealed class AquariumRuntime : IAquariumRuntime
public void Dispose()
{
faceVoice.Dispose();
FlushState();
stateStore.Dispose();
}
@ -161,10 +215,26 @@ public sealed class AquariumRuntime : IAquariumRuntime
CameraTargetY = cameraRig.Target.Y,
CameraYawRadians = cameraRig.YawRadians,
CameraPitchRadians = cameraRig.PitchRadians,
CameraDistance = cameraRig.Distance
CameraDistance = cameraRig.Distance,
FaceVoiceAppServerUri = faceVoice.AppServerUri,
FaceVoiceThreadId = faceVoice.ThreadId,
FaceVoiceVoice = faceVoice.Voice,
FaceVoicePrompt = faceVoice.Prompt
});
}
private void SendFaceVoiceText()
{
var text = faceVoiceText.Trim();
if (text.Length == 0)
{
return;
}
faceVoice.SendText(text);
faceVoiceText = "";
}
private void SaveGraphicsSettingsIfDirty()
{
if (!graphicsSettingsDirty)

View file

@ -34,4 +34,16 @@ public sealed class AquariumLiveState
[Key(7)]
public long SaveGeneration { get; set; }
[Key(8)]
public string FaceVoiceAppServerUri { get; set; } = "ws://127.0.0.1:8765";
[Key(9)]
public string FaceVoiceThreadId { get; set; } = "";
[Key(10)]
public string FaceVoiceVoice { get; set; } = "marin";
[Key(11)]
public string FaceVoicePrompt { get; set; } = "You are Face inside Epiphany Aquarium. Speak briefly, warmly, and only as the public surface. Do not accept project state, memory, evidence, or code authority from speech.";
}

View file

@ -0,0 +1,495 @@
using System.Net.WebSockets;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using Aquarium.Engine.Audio;
namespace Aquarium.Epiphany.Voice;
public sealed class RealtimeFaceVoiceSession : IDisposable
{
private readonly object sync = new();
private readonly AquariumAudioDocument audio;
private readonly SemaphoreSlim sendLock = new(1, 1);
private ClientWebSocket? socket;
private CancellationTokenSource? cancellation;
private Task? task;
private int nextRequestId;
private string status = "idle";
private string transcript = "";
private string lastError = "";
private string remoteSdp = "";
private int outputAudioChunks;
private int outputAudioBytes;
public RealtimeFaceVoiceSession(AquariumAudioDocument audio)
{
this.audio = audio;
}
public string AppServerUri { get; set; } = "ws://127.0.0.1:8765";
public string ThreadId { get; set; } = "";
public string Voice { get; set; } = "marin";
public string Prompt { get; set; } = "You are Face inside Epiphany Aquarium. Speak briefly, warmly, and only as the public surface. Do not accept project state, memory, evidence, or code authority from speech.";
public string Status
{
get
{
lock (sync)
{
return status;
}
}
}
public string Transcript
{
get
{
lock (sync)
{
return transcript;
}
}
}
public string LastError
{
get
{
lock (sync)
{
return lastError;
}
}
}
public string RemoteSdp
{
get
{
lock (sync)
{
return remoteSdp;
}
}
}
public string AudioStats
{
get
{
lock (sync)
{
return $"{outputAudioChunks} chunks / {outputAudioBytes} bytes";
}
}
}
public bool IsRunning
{
get
{
lock (sync)
{
return socket?.State == WebSocketState.Open && status == "running";
}
}
}
public void Start()
{
lock (sync)
{
if (task is { IsCompleted: false })
{
status = "already running";
return;
}
if (string.IsNullOrWhiteSpace(AppServerUri) || string.IsNullOrWhiteSpace(ThreadId))
{
status = "blocked";
lastError = "app-server WebSocket URI and thread id are required";
return;
}
cancellation = new CancellationTokenSource();
task = Task.Run(() => RunAsync(cancellation.Token));
}
}
public void Stop()
{
ClientWebSocket? current;
CancellationTokenSource? currentCancellation;
lock (sync)
{
current = socket;
currentCancellation = cancellation;
status = "stopping";
}
_ = Task.Run(async () =>
{
try
{
if (current?.State == WebSocketState.Open)
{
await SendRequestAsync(current, "thread/realtime/stop", new JsonObject { ["threadId"] = ThreadId }, CancellationToken.None).ConfigureAwait(false);
await current.CloseAsync(WebSocketCloseStatus.NormalClosure, "Face voice stopped", CancellationToken.None).ConfigureAwait(false);
}
}
catch (Exception error)
{
SetError(error.Message);
}
finally
{
currentCancellation?.Cancel();
}
});
}
public void SendText(string text)
{
if (string.IsNullOrWhiteSpace(text))
{
return;
}
ClientWebSocket? current;
lock (sync)
{
current = socket;
}
if (current?.State != WebSocketState.Open)
{
SetError("Face voice is not connected");
return;
}
_ = Task.Run(async () =>
{
try
{
await SendRequestAsync(
current,
"thread/realtime/appendText",
new JsonObject
{
["threadId"] = ThreadId,
["text"] = text.Trim()
},
CancellationToken.None).ConfigureAwait(false);
}
catch (Exception error)
{
SetError(error.Message);
}
});
}
public void ClearTranscript()
{
lock (sync)
{
transcript = "";
lastError = "";
remoteSdp = "";
outputAudioChunks = 0;
outputAudioBytes = 0;
}
}
private async Task RunAsync(CancellationToken token)
{
using var localSocket = new ClientWebSocket();
lock (sync)
{
socket = localSocket;
status = "connecting";
lastError = "";
}
try
{
await localSocket.ConnectAsync(new Uri(AppServerUri), token).ConfigureAwait(false);
SetStatus("initializing");
var initializeId = await SendRequestAsync(
localSocket,
"initialize",
new JsonObject
{
["clientInfo"] = new JsonObject
{
["name"] = "aquarium-engine-face-voice",
["title"] = "Aquarium Engine Face Voice",
["version"] = "0.1.0"
},
["capabilities"] = new JsonObject
{
["experimentalApi"] = true
}
},
token).ConfigureAwait(false);
await ReceiveUntilResponseAsync(localSocket, initializeId, token).ConfigureAwait(false);
await SendNotificationAsync(localSocket, "initialized", null, token).ConfigureAwait(false);
SetStatus("starting realtime");
var startId = await SendRequestAsync(
localSocket,
"thread/realtime/start",
new JsonObject
{
["threadId"] = ThreadId,
["outputModality"] = "audio",
["prompt"] = Prompt,
["voice"] = string.IsNullOrWhiteSpace(Voice) ? null : Voice.Trim()
},
token).ConfigureAwait(false);
await ReceiveUntilResponseAsync(localSocket, startId, token).ConfigureAwait(false);
SetStatus("running");
await ReceiveLoopAsync(localSocket, token).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
SetStatus("stopped");
}
catch (Exception error)
{
SetError(error.Message);
}
finally
{
lock (sync)
{
if (ReferenceEquals(socket, localSocket))
{
socket = null;
}
if (status is "running" or "connecting" or "initializing" or "starting realtime" or "stopping")
{
status = "stopped";
}
}
}
}
private async Task ReceiveUntilResponseAsync(ClientWebSocket current, int requestId, CancellationToken token)
{
while (!token.IsCancellationRequested && current.State == WebSocketState.Open)
{
var message = await ReceiveMessageAsync(current, token).ConfigureAwait(false);
if (message is null)
{
return;
}
var responseId = message["id"]?.GetValue<int?>();
if (responseId == requestId)
{
if (message["error"] is JsonObject error)
{
throw new InvalidOperationException(error["message"]?.GetValue<string>() ?? "app-server request failed");
}
return;
}
HandleMessage(message);
}
}
private async Task ReceiveLoopAsync(ClientWebSocket current, CancellationToken token)
{
while (!token.IsCancellationRequested && current.State == WebSocketState.Open)
{
var message = await ReceiveMessageAsync(current, token).ConfigureAwait(false);
if (message is null)
{
return;
}
HandleMessage(message);
}
}
private void HandleMessage(JsonObject message)
{
if (message["error"] is JsonObject error)
{
SetError(error["message"]?.GetValue<string>() ?? "app-server error");
return;
}
var method = message["method"]?.GetValue<string>();
if (string.IsNullOrWhiteSpace(method))
{
return;
}
var parameters = message["params"] as JsonObject;
switch (method)
{
case "thread/realtime/started":
SetStatus("running");
break;
case "thread/realtime/transcript/delta":
AppendTranscript(parameters?["role"]?.GetValue<string>() ?? "voice", parameters?["delta"]?.GetValue<string>() ?? "");
break;
case "thread/realtime/transcript/done":
AppendTranscript(parameters?["role"]?.GetValue<string>() ?? "voice", parameters?["text"]?.GetValue<string>() ?? "", done: true);
break;
case "thread/realtime/outputAudio/delta":
HandleAudio(parameters?["audio"] as JsonObject);
break;
case "thread/realtime/sdp":
lock (sync)
{
remoteSdp = parameters?["sdp"]?.GetValue<string>() ?? "";
}
break;
case "thread/realtime/error":
SetError(parameters?["message"]?.GetValue<string>() ?? "realtime error");
break;
case "thread/realtime/closed":
SetStatus($"closed {parameters?["reason"]?.GetValue<string>() ?? ""}".Trim());
break;
}
}
private void HandleAudio(JsonObject? audioObject)
{
var data = audioObject?["data"]?.GetValue<string>() ?? "";
var sampleRate = audioObject?["sampleRate"]?.GetValue<int?>() ?? 24000;
var channels = audioObject?["numChannels"]?.GetValue<int?>() ?? 1;
if (!string.IsNullOrWhiteSpace(data))
{
audio.EnqueuePcm16Base64(data, sampleRate, channels, 0.85f);
}
lock (sync)
{
outputAudioChunks++;
outputAudioBytes += data.Length;
}
}
private void AppendTranscript(string role, string text, bool done = false)
{
if (string.IsNullOrEmpty(text))
{
return;
}
lock (sync)
{
var label = string.Equals(role, "assistant", StringComparison.OrdinalIgnoreCase) ? "Face" : "You";
transcript += $"{label}: {text}{(done ? Environment.NewLine : "")}";
if (transcript.Length > 4096)
{
transcript = transcript[^4096..];
}
}
}
private async Task<int> SendRequestAsync(ClientWebSocket current, string method, JsonObject? parameters, CancellationToken token)
{
var id = Interlocked.Increment(ref nextRequestId);
var message = new JsonObject
{
["id"] = id,
["method"] = method
};
if (parameters is not null)
{
message["params"] = parameters;
}
await SendJsonAsync(current, message, token).ConfigureAwait(false);
return id;
}
private Task SendNotificationAsync(ClientWebSocket current, string method, JsonObject? parameters, CancellationToken token)
{
var message = new JsonObject
{
["method"] = method
};
if (parameters is not null)
{
message["params"] = parameters;
}
return SendJsonAsync(current, message, token);
}
private async Task SendJsonAsync(ClientWebSocket current, JsonObject message, CancellationToken token)
{
var bytes = Encoding.UTF8.GetBytes(message.ToJsonString());
await sendLock.WaitAsync(token).ConfigureAwait(false);
try
{
await current.SendAsync(bytes, WebSocketMessageType.Text, true, token).ConfigureAwait(false);
}
finally
{
sendLock.Release();
}
}
private static async Task<JsonObject?> ReceiveMessageAsync(ClientWebSocket current, CancellationToken token)
{
var buffer = new byte[64 * 1024];
using var stream = new MemoryStream();
while (true)
{
var result = await current.ReceiveAsync(buffer, token).ConfigureAwait(false);
if (result.MessageType == WebSocketMessageType.Close)
{
return null;
}
stream.Write(buffer, 0, result.Count);
if (result.EndOfMessage)
{
break;
}
}
var json = Encoding.UTF8.GetString(stream.ToArray());
return JsonNode.Parse(json) as JsonObject;
}
private void SetStatus(string value)
{
lock (sync)
{
status = value;
}
}
private void SetError(string message)
{
lock (sync)
{
status = "error";
lastError = message;
}
}
public void Dispose()
{
cancellation?.Cancel();
socket?.Dispose();
cancellation?.Dispose();
sendLock.Dispose();
}
}

View file

@ -19,6 +19,8 @@ public sealed class MinimalRuntime : IAquariumRuntime
public AquariumUiDocument Ui { get; } = AquariumUiDocument.Empty;
public AquariumAudioDocument Audio { get; } = new();
public AquariumSynthDocument Synth { get; } = AquariumSynthDocument.Empty;
public AquariumFrame Frame => new(

View file

@ -25,6 +25,8 @@ public sealed class ZyphosRuntime : IAquariumRuntime
public AquariumUiDocument Ui { get; }
public AquariumAudioDocument Audio { get; } = new();
public AquariumSynthDocument Synth { get; } = AquariumSynthDocument.Empty;
public AquariumFrame Frame => new(

View file

@ -101,6 +101,8 @@ renderer_state:
- Studio2 PMREM and irradiance DDS cubemaps are loaded as D3D12 TextureCubes; PMREM serves roughness-mip specular, irradiance serves Lambertian diffuse IBL for non-metal bodies.
- DirectWrite/Direct2D unified debug panel with tabs for Aquarium renderer controls, client-declared debug panels, terminal commands, and engine/client tooling surfaces.
- Aquarium exposes an optional synth/audio hosting boundary through AquariumSynthDocument; Aquarium consumes AquaSynth.Faust as a pinned repo-local NuGet package so synth-agent construction cannot break Aquarium builds until the package is intentionally updated. AquaSynth.Core arrives transitively for patch editor/parser surfaces.
- Aquarium now exposes a generic queued PCM audio lane through AquariumAudioDocument. Epiphany Face voice uses it to play streamed Codex realtime output without reaching into the engine's WASAPI internals.
- Epiphany owns the first native Face realtime voice session controller. It stores loopback app-server URI, thread id, voice, and speech prompt in CultCache live state; starts `thread/realtime/start` with audio output over the experimental Codex app-server WebSocket JSON-RPC edge; sends text utterances; reflects ephemeral transcript/error/audio counters in the debug UI; and treats speech as transient Face surface, not durable memory or project authority.
- Global GraphicsSettings document feeding render debug, exposure, bloom intensity, and bloom veil.
- Temporal resolve uses scene color, metadata, and control history only; dormant event history lanes are cut until a real producer and consumer contract exists.
- Isolated Epiphany agent preview renders run through the real D3D12 renderer from src/Aquarium.Epiphany.AgentPreview; preview isolation is owned by a preview-only scene shader, while the engine exposes only final-frame PNG capture.
@ -144,4 +146,5 @@ next_actions:
- Follow docs/zyphos-eusocial-sync.md and E:\Projects\Eusocial Interbeing\Eusocial Interbeing\World\Zyphos Simulation Brief.md before turning Zyphos visual choices into setting claims.
- Follow docs/tsr-inspired-taa-spec.md when changing current temporal diagnostics.
- Promote future runtime knobs into typed CultCache documents before they become process folklore.
- Next Face voice slice: replace text-only input with microphone/WebRTC or a native capture bridge, then move the transport contract from Codex JSON-RPC compatibility toward a typed CultNet FaceVoiceSession once Epiphany advertises that surface.
- Keep Aquarium and Epiphany in one repo until the contracts and graph API are stable enough for Epiphany to move out without carrying engine policy or reload folklore with it.