Repository navigation
Expand file tree
/
Copy pathaudio_recorder.py
More file actions
635 lines (557 loc) · 25.4 KB
/
Copy pathaudio_recorder.py
File metadata and controls
635 lines (557 loc) · 25.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
# WriterAgent - AI Writing Assistant for LibreOffice
# Copyright (c) 2024 John Balis
# Copyright (c) 2026 KeithCu (modifications and relicensing)
#
# 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 <http://www.gnu.org/licenses/>.
"""Host adapter: venv subprocess or downloaded sounddevice capture for sidebar recording."""
from __future__ import annotations
import logging
import os
import struct
import threading
import time
from typing import TYPE_CHECKING, Any, Callable
from plugin.framework.errors import best_effort
from plugin.chatbot.audio_recorder_state import (
AudioRecorderEvent,
AudioRecorderState,
AudioStatus,
DeviceReadyEvent,
ErrorOccurredEvent,
InitializeDeviceEffect,
ReportErrorEffect,
StartRecordingEffect,
StartRequestedEvent,
StopRecordingEffect,
StopRequestedEvent,
next_state,
)
from plugin.framework.worker_pool import BackgroundHandle, run_in_background
from plugin.scripting.audio_recorder_service import (
make_temp_wav_path,
resolve_recording_python,
spawn_recording_process,
)
from plugin.scripting.native_binaries import ensure_native_binaries_on_path
from plugin.scripting.audio_silence_detector import SilenceDetector, load_silence_detector_config
if TYPE_CHECKING:
from plugin.scripting.audio_recorder_service import Recording
log = logging.getLogger(__name__)
WAV_HEADER_BYTES = 44
# Same value as MAX_RECORDING_DURATION_SEC in plugin/scripting/venv/audio_recorder.py
# (the venv child cannot import this module).
MAX_RECORDING_DURATION_SEC = 4 * 3600
def finalize_wav_header(path: str | None) -> bool:
"""Rewrite RIFF and data chunk sizes for a 44-byte PCM WAV header."""
if not path or not os.path.isfile(path):
return False
try:
size = os.path.getsize(path)
if size <= WAV_HEADER_BYTES:
return False
data_bytes = size - WAV_HEADER_BYTES
if data_bytes % 2 != 0:
return False
with open(path, "r+b") as f:
header = f.read(WAV_HEADER_BYTES)
if len(header) < WAV_HEADER_BYTES:
return False
if header[0:4] != b"RIFF" or header[8:12] != b"WAVE":
return False
f.seek(4)
f.write(struct.pack("<I", size - 8))
f.seek(40)
f.write(struct.pack("<I", data_bytes))
return True
except OSError:
return False
def _wav_file_has_bytes(path: str | None) -> bool:
"""True when the capture child has already written a non-empty WAV.
The child writes the file continuously. The stop handshake can fail after
the child has written audio, and the bytes on disk are still the user's take.
"""
if not path:
return False
try:
return os.path.isfile(path) and os.path.getsize(path) > WAV_HEADER_BYTES
except OSError:
return False
class AudioRecorder:
fs: int = 16000
channels: int = 1
_auto_stop_lock: threading.Lock
_auto_stop_notified: bool
_wav_lock: threading.Lock
_lifecycle_lock: threading.Lock
stop_deferred: bool
state: AudioRecorderState
def __init__(self) -> None:
self.temp_filename: str | None = None
self._recording: Recording | None = None
self._auto_stopped_path: str | None = None
self._auto_stop_notified = False
self._auto_stop_lock = threading.Lock()
# Held across host writeframes so Stop can close the WAV only after
# that callback has dropped the file.
self._wav_lock = threading.Lock()
self._lifecycle_lock = threading.Lock()
self.stop_deferred = False
self._epoch: int = 0
self._start_job: BackgroundHandle | None = None
self._stop_job: BackgroundHandle | None = None
# Epoch of the start job that owes on_capture_stopped(None); older jobs cannot consume newer stops.
self._commit_epoch: int | None = None
self._discard_take: bool = False
self.stream: Any = None
self.wav_file: Any = None
self._silence_detector: SilenceDetector | None = None
self._host_stream_start_time: float = 0.0
self._on_auto_stop: Callable[[], None] | None = None
self._on_silence_progress: Callable[[int], None] | None = None
self._on_recording_error: Callable[[str], None] | None = None
self._on_device_ready: Callable[[], None] | None = None
self._on_capture_stopped: Callable[[str | None], None] | None = None
self.state = AudioRecorderState(status=AudioStatus.IDLE)
def set_auto_stop_callbacks(
self,
*,
on_auto_stop: Callable[[], None] | None = None,
on_silence_progress: Callable[[int], None] | None = None,
on_error: Callable[[str], None] | None = None,
on_device_ready: Callable[[], None] | None = None,
on_capture_stopped: Callable[[str | None], None] | None = None,
) -> None:
"""Register UI hooks for silence-based auto-stop, child errors, device ready, and stop handoff."""
self._on_auto_stop = on_auto_stop
self._on_silence_progress = on_silence_progress
self._on_recording_error = on_error
self._on_device_ready = on_device_ready
self._on_capture_stopped = on_capture_stopped
def apply_device_ready(self) -> None:
"""Transition from initializing to recording once the device is open.
No-op unless status is currently initializing.
"""
if self.state.status == AudioStatus.INITIALIZING:
self._apply_event(DeviceReadyEvent())
def _notify_auto_stop(self, path: str | None = None) -> None:
# _auto_stop_notified latches one STOP_REC_CLICKED per auto-stop; silent chunks must not re-post.
with self._auto_stop_lock:
if self._auto_stop_notified:
return
self._auto_stop_notified = True
if path:
self._auto_stopped_path = path
if self._on_auto_stop is None:
return
callback = self._on_auto_stop
log.info("audio recorder: notifying auto-stop (path=%s)", path)
best_effort(callback, "dispatch audio auto-stop callback")
def _notify_recording_error(self, msg: str) -> None:
"""Stdout-monitor hook. Must not raise (ReportErrorEffect raises).
Child errors after ready post on_error on the UI thread, not _apply_event from the monitor.
"""
callback = self._on_recording_error
if callback is not None:
best_effort(lambda: callback(msg), "dispatch audio error callback")
return
self.apply_stdout_error(msg)
def apply_stdout_error(self, msg: str) -> None:
"""Apply a post-ready child error without escaping ReportErrorEffect."""
try:
self._apply_event(ErrorOccurredEvent(msg))
except RuntimeError:
log.warning("audio recorder: %s", msg)
def _notify_silence_progress(self, ms: int) -> None:
cb = self._on_silence_progress
if cb is not None:
best_effort(lambda: cb(ms), "dispatch silence progress callback")
def _start_stdout_monitor(self) -> None:
recording = self._recording
if recording is None:
return
# The recording's handoff is shared with stop. The monitor is the only stdout reader
# after ready; stop waits on the handoff instead of reading the same pipe.
recording.start_monitor(
on_auto_stopped=self._notify_auto_stop,
on_silence_progress=self._notify_silence_progress,
on_error=self._notify_recording_error,
)
def _take_new_temp_wav(self, epoch: int) -> str | None:
"""Create a unique temporary WAV file for this recording epoch.
Takes ownership of any abandoned temp_filename under the lifecycle lock
so failed or aborted takes do not leak files. Creating the path and deleting
the previous file run outside the lock. A second epoch check confirms this
take was not cancelled while creating the path before publishing it,
discarding the path if stale so a newer take's file is not overwritten.
"""
with self._lifecycle_lock:
if self._epoch != epoch:
return None
old_path = self.temp_filename
self.temp_filename = None
if old_path:
best_effort(lambda: os.remove(old_path), "delete previous temp wav")
new_path = make_temp_wav_path()
with self._lifecycle_lock:
if self._epoch != epoch:
stale = True
else:
stale = False
self.temp_filename = new_path
if stale:
best_effort(lambda: os.remove(new_path), "delete stale temp wav")
return None
return new_path
def _teardown_capture(self) -> None:
"""Idempotent teardown of child process, stream, and WAV file."""
if self._recording is not None:
self._recording.terminate()
self._recording = None
self._auto_stopped_path = None
if self.stream is not None:
# stream.stop() returns only after the current callback does, and
# that callback no longer holds _wav_lock. Close after that.
best_effort(self.stream.stop, "audio stream stop")
best_effort(self.stream.close, "audio stream close")
self.stream = None
self._close_host_wav()
self._silence_detector = None
def _notify_device_ready(self) -> None:
if self._on_device_ready is not None:
self._on_device_ready()
else:
self.apply_device_ready()
def _background_rec_stop(self, target: Any, *args: Any, **kwargs: Any) -> BackgroundHandle:
return run_in_background(
target,
*args,
name="audio-rec-stop",
dedicated=True,
**kwargs,
)
def _if_start_epoch_current(self, epoch: int, assign: Callable[[], None]) -> bool:
"""Run assign under the lifecycle lock when epoch still matches; else stale."""
with self._lifecycle_lock:
if self._epoch != epoch:
return False
assign()
return True
def _finish_stop(
self,
recording: Recording,
auto_path: str | None,
temp_path: str | None,
) -> None:
"""Wait for WAV path and reap child process off the UI thread.
Handoff wait and child reap run off the VCL thread; on_capture_stopped delivers the path.
Valid on-disk audio is kept when handshake or reap fails.
"""
path: str | None = None
try:
if recording.monitor_started:
try:
path = recording.finish()
except Exception as exc:
log.warning("Recording.finish failed: %s", exc)
if path is None:
wav_candidate = auto_path or temp_path
finalized = finalize_wav_header(wav_candidate)
recording.terminate()
if finalized:
if not auto_path:
log.warning("Stop handshake failed; using WAV already on disk")
path = wav_candidate
elif temp_path:
best_effort(lambda: os.remove(temp_path), "delete failed stop wav")
finally:
with self._lifecycle_lock:
discard = self._discard_take
if discard:
if path:
best_effort(lambda: os.remove(path), "discard captured wav")
else:
callback = self._on_capture_stopped
if callback is not None:
best_effort(lambda: callback(path), "on_capture_stopped")
def _handle_stale_start_exit(
self,
epoch: int,
temp_path: str | None = None,
recording: Recording | None = None,
wav: Any = None,
) -> None:
"""Clean up resources when start_capture exits early due to cancellation, stop, or error.
Under the lifecycle lock, delivers stop completion only when this start job's epoch matches
the stop commit token. Terminates only the passed recording, deletes only the passed temp WAV,
and closes only the passed host WAV.
"""
with self._lifecycle_lock:
deliver = self._commit_epoch == epoch
if deliver:
self._commit_epoch = None
if recording is not None and self._recording is recording:
self._recording = None
if wav is not None and self.wav_file is wav:
self.wav_file = None
if recording is not None:
recording.terminate()
if temp_path:
best_effort(lambda: os.remove(temp_path), "delete stale start wav")
if wav is not None:
with self._wav_lock:
best_effort(wav.close, "close stale host wav")
if deliver:
callback = self._on_capture_stopped
if callback is not None:
best_effort(lambda: callback(None), "on_capture_stopped")
def _start_capture(self, epoch: int) -> None:
import wave
silence_config = load_silence_detector_config()
self._auto_stopped_path = None
temp_path: str | None = None
exe, _err = resolve_recording_python()
if exe:
recording: Recording | None = None
try:
temp_path = self._take_new_temp_wav(epoch)
if temp_path is None:
self._handle_stale_start_exit(epoch, None, None)
return
recording = spawn_recording_process(exe, temp_path, silence_config=silence_config)
if not self._if_start_epoch_current(epoch, lambda: setattr(self, "_recording", recording)):
self._handle_stale_start_exit(epoch, temp_path, recording)
return
log.info(
"audio recorder: venv subprocess path (silence_stop_ms=%d)",
silence_config.silence_stop_ms,
)
recording.wait_ready()
if not self._if_start_epoch_current(epoch, self._start_stdout_monitor):
self._handle_stale_start_exit(epoch, temp_path, recording)
return
self._notify_device_ready()
except Exception as exc:
with self._lifecycle_lock:
stale = (self._epoch != epoch)
self._handle_stale_start_exit(epoch, temp_path, recording)
if not stale:
msg = str(exc) if isinstance(exc, RuntimeError) else f"Venv audio recording failed to start: {exc}"
self._notify_recording_error(msg)
else:
# Host-side capture via downloaded sounddevice binaries (no venv).
wav: Any = None
stream: Any = None
try:
ensure_native_binaries_on_path()
import sounddevice as sd
temp_path = self._take_new_temp_wav(epoch)
if temp_path is None:
self._handle_stale_start_exit(epoch, None, None)
return
wav = wave.open(temp_path, "wb")
wav.setnchannels(self.channels)
wav.setsampwidth(2) # 16-bit
wav.setframerate(self.fs)
detector = SilenceDetector(silence_config, sample_rate=self.fs)
log.info(
"audio recorder: host sounddevice path (silence_stop_ms=%d)",
silence_config.silence_stop_ms,
)
stream_start_time = time.monotonic()
def callback(indata: Any, frames: int, time_info: Any, status: Any) -> None:
if status:
log.debug("host recording status: %s", status)
if time.monotonic() - self._host_stream_start_time > MAX_RECORDING_DURATION_SEC:
self._notify_auto_stop(self.temp_filename)
self._notify_recording_error("Recording stopped: recording too long")
return
pcm = bytes(indata)
with self._wav_lock:
wav_obj = self.wav_file
# Status and the file are read together. Stop nulls
# wav_file under the same lock before close, so a
# chunk cannot pass this check and then write a
# closed file.
if self.state.status != AudioStatus.RECORDING or wav_obj is None:
return
try:
wav_obj.writeframes(pcm)
except Exception:
# Stop may already have closed the WAV.
# Swallow the write so the exception does not
# abort the PortAudio thread and drop later chunks.
log.debug("host recording writeframes failed", exc_info=True)
return
if not silence_config.enabled:
return
result = detector.process_chunk(pcm)
if detector.should_emit_silence_progress(result):
self._notify_silence_progress(result.silence_ms)
if result.should_stop:
self._notify_auto_stop(self.temp_filename)
stream = sd.RawInputStream(
samplerate=self.fs, channels=self.channels, dtype="int16", callback=callback
)
def publish_host_state() -> None:
self.stream = stream
self.wav_file = wav
self._silence_detector = detector
self._host_stream_start_time = stream_start_time
if not self._if_start_epoch_current(epoch, publish_host_state):
best_effort(stream.close, "close stream")
self._handle_stale_start_exit(epoch, temp_path, None, wav=wav)
return
self._notify_device_ready()
except Exception as exc:
if stream is not None:
best_effort(stream.close, "close stream")
with self._lifecycle_lock:
stale = (self._epoch != epoch)
self._handle_stale_start_exit(epoch, temp_path, None, wav=wav)
if not stale:
self._notify_recording_error(
f"Audio recording failed to start. "
f"Please configure a Python venv or click 'Download Audio' in Settings → Python. Error: {exc}"
)
def _execute_effect(self, effect: object) -> None:
from plugin.framework.dev_build import is_dev_build
testing = is_dev_build()
if isinstance(effect, InitializeDeviceEffect):
self._auto_stop_notified = False
if testing:
from plugin.chatbot.sidebar_test_hooks import try_stub_initialize
if try_stub_initialize(self):
return
with self._lifecycle_lock:
self._epoch += 1
epoch = self._epoch
self._commit_epoch = None
self._discard_take = False
self._start_job = run_in_background(
self._start_capture,
epoch,
name="audio-rec-start",
dedicated=True,
)
elif isinstance(effect, StartRecordingEffect):
if self.stream is not None:
try:
self.stream.start()
except Exception as e:
self._apply_event(ErrorOccurredEvent(f"Audio recording failed to start stream: {e}"))
elif isinstance(effect, StopRecordingEffect):
if testing:
from plugin.chatbot.sidebar_test_hooks import try_stub_stop
if try_stub_stop(self):
return
stream_published = self.stream is not None
if stream_published:
self._teardown_capture()
with self._lifecycle_lock:
start_alive = self._start_job is not None and self._start_job.is_alive()
recording = self._recording
monitor_started = recording is not None and recording.monitor_started
auto_path = self._auto_stopped_path
temp_path = self.temp_filename
self._recording = None
self._auto_stopped_path = None
# If the start job is alive and the monitor has not started, bump epoch,
# kill the process tree without waiting on UI thread; the start job reaps.
if start_alive and not monitor_started and not stream_published:
invalidated = self._epoch
self._epoch += 1
if recording is not None:
self._background_rec_stop(recording.kill_tree)
if not self._discard_take:
self._commit_epoch = invalidated
self.stop_deferred = True
else:
self._commit_epoch = None
self.temp_filename = None
return
if recording is not None and temp_path and self.state.status != AudioStatus.ERROR:
if recording.is_alive() and monitor_started:
try:
recording.signal_stop()
except Exception as exc:
log.warning("Recording.signal_stop failed: %s", exc)
if not self._discard_take:
self.stop_deferred = True
self.temp_filename = None
self._stop_job = self._background_rec_stop(
self._finish_stop,
recording,
auto_path,
temp_path,
)
return
if recording is not None:
self._stop_job = self._background_rec_stop(recording.terminate)
if self.state.status == AudioStatus.ERROR:
# An empty WAV from a failed start is deleted immediately here.
# A non-empty WAV stays on temp_filename until cleanup or the
# next take's _take_new_temp_wav cleans it up.
if not _wav_file_has_bytes(self.temp_filename):
self._teardown_capture()
self._delete_wav()
elif isinstance(effect, ReportErrorEffect):
raise RuntimeError(effect.error_message)
def _apply_event(self, event: AudioRecorderEvent) -> None:
step = next_state(self.state, event)
self.state = step.state
for effect in step.effects:
self._execute_effect(effect)
def start_recording(self) -> None:
self.stop_deferred = False
self._apply_event(StartRequestedEvent())
def stop_recording(self) -> str | None:
self.stop_deferred = False
self._apply_event(StopRequestedEvent())
path = self.temp_filename
self.temp_filename = None
return path
def _close_host_wav(self) -> None:
"""Close the host WAV after the capture callback has dropped it.
Stop must not close wav_file while the PortAudio callback can
still be inside writeframes, and cleanup's failure path must close
the file or the mic handle stays open. This waits for _wav_lock,
clears the attribute the callback checks, then closes.
"""
with self._wav_lock:
wav = self.wav_file
self.wav_file = None
if wav is not None:
best_effort(wav.close, "Failed to close wav_file")
def cleanup(self) -> None:
"""Terminate an in-flight recording child (panel teardown)."""
with self._lifecycle_lock:
self._discard_take = True
self._commit_epoch = None
if self._recording is not None or self.stream is not None or self.state.status in (AudioStatus.INITIALIZING, AudioStatus.RECORDING):
try:
self._apply_event(StopRequestedEvent())
except Exception:
# A failed Stop must not leave the host WAV open. The
# callback can still be inside writeframes, so stop the
# stream first (that waits for the callback) and close after.
self._teardown_capture()
self._close_host_wav()
self._delete_wav()
def _delete_wav(self) -> None:
if self.temp_filename:
try:
os.remove(self.temp_filename)
except OSError as exc:
log.debug("Failed to remove temp_filename: %s", exc)
self.temp_filename = None