|
| 1 | +# Speech Enhancer Design |
| 2 | + |
| 3 | +```python |
| 4 | +class SpeechEnhancer(ABC): |
| 5 | + """Abstract base class for speech enhancement engines.""" |
| 6 | + |
| 7 | + @abstractmethod |
| 8 | + def enhance(self, audio: bytes, far: bytes) -> bytes: |
| 9 | + ... |
| 10 | + |
| 11 | + def flush(self) -> bytes: |
| 12 | + return b"" |
| 13 | + |
| 14 | + async def async_enhance( |
| 15 | + self, |
| 16 | + audio: bytes, |
| 17 | + far: bytes, |
| 18 | + ) -> bytes: |
| 19 | + ... |
| 20 | + |
| 21 | + async def async_flush(self) -> bytes: |
| 22 | + ... |
| 23 | + |
| 24 | + @abstractmethod |
| 25 | + def reset(self) -> None: |
| 26 | + ... |
| 27 | + |
| 28 | + @abstractmethod |
| 29 | + def clone(self) -> "SpeechEnhancer": |
| 30 | + ... |
| 31 | +``` |
| 32 | + |
| 33 | +## Audio Format |
| 34 | + |
| 35 | +`SpeechEnhancer` input and output use: |
| 36 | + |
| 37 | +- PCM 16-bit |
| 38 | +- Mono |
| 39 | +- 16000 Hz |
| 40 | +- Raw PCM bytes without a WAV header |
| 41 | + |
| 42 | +`audio` is the near-end microphone signal. `far` is the far-end reference signal, usually derived from the TTS audio being played to the user, and is used for acoustic echo cancellation. |
| 43 | + |
| 44 | +The upstream audio pipeline always provides `far` and guarantees that: |
| 45 | + |
| 46 | +- `far` uses the same audio format as `audio` |
| 47 | +- `len(far) == len(audio)` |
| 48 | +- both buffers describe the near-end input and far-end reference for the same time window |
| 49 | + |
| 50 | +## `enhance` and `async_enhance` |
| 51 | + |
| 52 | +The service layer primarily calls `async_enhance`. If the underlying implementation only has a synchronous API, implement `enhance` and reuse the base class thread-pool wrapper for `async_enhance`. |
| 53 | + |
| 54 | +If the underlying implementation is asynchronous or remote, prefer implementing `async_enhance` directly and wrapping it for `enhance`. |
| 55 | + |
| 56 | +```python |
| 57 | +import asyncio |
| 58 | + |
| 59 | +def enhance(self, audio: bytes, far: bytes) -> bytes: |
| 60 | + return self._run_coro(self.async_enhance(audio, far=far)) |
| 61 | + |
| 62 | +def _run_coro(self, coro: "asyncio.Future[bytes]") -> bytes: |
| 63 | + loop = asyncio.new_event_loop() |
| 64 | + try: |
| 65 | + return loop.run_until_complete(coro) |
| 66 | + finally: |
| 67 | + loop.close() |
| 68 | +``` |
| 69 | + |
| 70 | +## Meaning of `far` |
| 71 | + |
| 72 | +`far` is a required interface argument and enables enhancement engines that need a far-end reference, such as acoustic echo cancellation. |
| 73 | + |
| 74 | +- When nothing is being played, the service layer passes a silent `far` buffer with the same length as `audio`. |
| 75 | +- When TTS is being played, the service layer reads a same-length slice from the TTS reference buffer. |
| 76 | +- If the reference buffer is short, the service layer pads silence on the right and still preserves equal length. |
| 77 | +- FastEnhancer accepts the interface argument but ignores `far` in both local and remote modes. |
| 78 | +- A concrete enhancer implementation that targets an echo-cancellation service may use `far`. |
| 79 | + |
| 80 | +Therefore, implementations may assume that `far` has the same byte length as `audio`. The upstream service pipeline owns this invariant, so concrete enhancers do not need to check it again. |
| 81 | + |
| 82 | +## How the Service Layer Builds the Far-End Reference |
| 83 | + |
| 84 | +`EnhancerManager` consumes `AudioFrameReceived` and publishes `EnhancedAudioFrameReceived`. When a `SpeechEnhancer` model is configured, each user audio frame is processed like this: |
| 85 | + |
| 86 | +```python |
| 87 | +far = far_reference.take(len(audio)) |
| 88 | +enhanced = await enhancer.async_enhance(audio, far=far) |
| 89 | +``` |
| 90 | + |
| 91 | +The far-end reference comes from `TTSChunkReady`. The service layer copies the TTS chunk that is about to be sent to the client, converts it to the speech-enhancer format, and writes it into a reference buffer. |
| 92 | + |
| 93 | +Current conversion rules: |
| 94 | + |
| 95 | +- Treat input TTS chunks as PCM 16-bit mono |
| 96 | +- Resample from `TTSChunkReady.sample_rate` to 16000 Hz |
| 97 | +- Store the converted audio in a bounded FIFO buffer |
| 98 | +- Keep up to 5 seconds by default, configurable with `far_reference_buffer_seconds` |
| 99 | + |
| 100 | +When user audio arrives, the service layer reads a far-end reference buffer with the same byte length as the current `audio`. If no reference is available, it returns same-length silence. |
| 101 | + |
| 102 | +## Role of `TTSChunkPlayed` |
| 103 | + |
| 104 | +`TTSChunkPlayed` means the frontend has confirmed that a TTS chunk finished playback. The current event does not include a `chunk_id`, client playback timestamp, or sample offset, so it cannot provide sample-level alignment. |
| 105 | + |
| 106 | +The service layer uses it to discard already played reference audio that microphone frames did not consume. This prevents stale TTS audio from being used as `far` when the user waits until TTS playback completes before speaking. |
| 107 | + |
| 108 | +More precise alignment should come from future client-side playback reference feedback or timestamped playback events. |
| 109 | + |
| 110 | +## FastEnhancer Behavior |
| 111 | + |
| 112 | +`FastEnhancer` implements the `SpeechEnhancer` interface but does not use `far`. |
| 113 | +This is true for both local ONNX mode and remote FastEnhancer WebSocket mode. |
| 114 | +Remote FastEnhancer continues to use its legacy binary PCM protocol. |
| 115 | + |
| 116 | +`PyWebRTCAudio` is the concrete adapter for the pywebrtc-audio service. Its |
| 117 | +constructor only accepts `base_url`, and it sends the upstream-provided `audio` |
| 118 | +and `far` to the service's `/v1/stream` JSON WebSocket endpoint. |
| 119 | + |
| 120 | +## `flush` |
| 121 | + |
| 122 | +`flush` / `async_flush` drains tail audio buffered inside the enhancer. The service layer inserts a flush barrier after `VADSpeechEnd` so all earlier audio frames are enhanced and dispatched downstream before the flush runs. |
| 123 | + |
| 124 | +For remote FastEnhancer mode, `flush` sends any locally pending padded audio and then uses the remote FastEnhancer flush command. |
| 125 | + |
| 126 | +## `reset` and `clone` |
| 127 | + |
| 128 | +`reset` should clear the current session's streaming state, such as model caches, input/output buffers, remote connections, and pending audio. It should not reload model weights. |
| 129 | + |
| 130 | +`clone` should create an independent runtime instance for a new session. Clones may share weights, configuration, or read-only resources, but must not share streaming buffers, remote connections, pending audio, or session state. |
| 131 | + |
| 132 | +See [Semantics of `clone()` and `reset()` on Model Objects](model_clone_reset.md). |
| 133 | + |
| 134 | +## Implementation Suggestions |
| 135 | + |
| 136 | +- Keep output length aligned with input `audio` whenever possible, so downstream VAD and ASR timelines do not drift. |
| 137 | +- Do not try to infer TTS alignment inside the model interface; length padding and far selection belong to the service layer. |
| 138 | +- If the implementation requires `far`, it may assume the upstream pipeline already matched its length with `audio`. |
| 139 | +- If the implementation does not support `far`, ignore the argument but do not fail on a silent reference. |
| 140 | +- Remote implementations should clear pending audio on `reset` and connection rebuilds. |
0 commit comments