Radio Delay v2 — KDE PipeWire.
Retarde le son d’une application (QMPlay2 par défaut) vers une sortie (enceinte Bluetooth, etc.). Sans PortAudio ni JACK : uniquement pactl + parec + pacat (pipewire-pulse).
Chaîne audio : QMPlay2 -> sink virtuel RadioDelay_Input -> parec (monitor) -> tampon retardé (ce script) -> pacat -> sortie choisie
Le problème de départ : RadioDelay_Input n’apparaissait pas dans la liste d’entrées. PortAudio et JACK figent leur liste de périphériques au lancement, donc le sink créé ensuite n’y figurait pas.
La solution : radio_delay.py n’utilise plus PortAudio. Le script s’appuie sur pactl, parec et pacat.
- Il crée le sink virtuel
RadioDelay_Inputet y redirige l’application choisie. - Il lit le monitor avec
parec, retarde le flux de 0 à 10 s, puis l’envoie à la sortie choisie avecpacat. - Le retard se règle à chaud, avec environ 0,15 s de latence fixe en plus.
- À l’arrêt ou à la fermeture, l’application retrouve sa sortie d’origine.
Corrections en cours de route
- QMPlay2 n’était pas détecté, car il n’expose ni nom d’application ni binaire. La détection regarde maintenant aussi
node.nameetmedia.icon_name. - La barre d’état affichait un message trompeur : elle indique maintenant l’état réel.
Dernière évolution : une liste déroulante modifiable permet de choisir l’application à retarder (QMPlay2 par défaut). Elle se remplit avec les flux audio en cours, via « Actualiser les applications ».
Limites : le retard propre au Bluetooth n’est pas compensé, donc on règle à l’oreille. Après un plantage, l’application peut rester muette, sur le sink virtuel. Il suffit de la remettre sur ta sortie dans le mixeur KDE, ou de cliquer sur « Supprimer l’entrée ».
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
#!/usr/bin/env python3
"""Radio Delay v2 — KDE / PipeWire.
Retarde le son d'une application (QMPlay2 par défaut) vers une sortie (enceinte Bluetooth, etc.).
Sans PortAudio ni JACK : uniquement pactl + parec + pacat (pipewire-pulse).
Chaîne audio :
QMPlay2 -> sink virtuel RadioDelay_Input -> parec (monitor)
-> tampon retardé (ce script) -> pacat -> sortie choisie
"""
import fcntl
import json
import os
import shutil
import signal
import subprocess
import sys
import threading
import time
from collections import deque
from PySide6.QtCore import Qt, QTimer
from PySide6.QtWidgets import (
QApplication, QWidget, QVBoxLayout, QHBoxLayout, QLabel, QPushButton,
QSlider, QComboBox, QMessageBox, QGroupBox
)
SINK_NAME = "radio_delay_input"
SINK_DESC = "RadioDelay_Input"
MONITOR_NAME = SINK_NAME + ".monitor"
RATE = 48000
CHANNELS = 2
BYTES_PER_FRAME = CHANNELS * 4 # float32
CHUNK_FRAMES = 1920 # 40 ms
CHUNK_BYTES = CHUNK_FRAMES * BYTES_PER_FRAME
CHUNK_MS = CHUNK_FRAMES * 1000 / RATE
MAX_DELAY_MS = 10000
ROUTE_INTERVAL_MS = 1000
F_SETPIPE_SZ = 1031
def run_cmd(args):
return subprocess.run(args, text=True, capture_output=True)
def list_sinks():
"""Retourne [(name, description, index)] des sorties PipeWire/Pulse."""
r = run_cmd(["pactl", "-f", "json", "list", "sinks"])
if r.returncode == 0:
try:
return [(s["name"], s.get("description") or s["name"], str(s["index"]))
for s in json.loads(r.stdout)]
except (json.JSONDecodeError, KeyError, TypeError):
pass
sinks = []
r = run_cmd(["pactl", "list", "short", "sinks"])
for line in r.stdout.splitlines():
f = line.split("\t")
if len(f) >= 2:
sinks.append((f[1], f[1], f[0]))
return sinks
class DelayEngine:
"""parec -> file d'attente de blocs de 40 ms -> pacat, avec retard réglable à chaud."""
def __init__(self):
self.rec = None
self.play = None
self.q = deque()
self.delay_ms = 0
self.running = False
self.error = None
self.threads = []
# --- commandes (séparées pour pouvoir les tester) ---
def _rec_cmd(self, source):
return ["parec", "--device", source, "--format=float32le", f"--rate={RATE}",
f"--channels={CHANNELS}", "--raw", "--latency-msec=20",
"--client-name=RadioDelay", "--stream-name=RadioDelay-capture"]
def _play_cmd(self, sink):
return ["pacat", "--playback", "--device", sink, "--format=float32le",
f"--rate={RATE}", f"--channels={CHANNELS}", "--raw",
"--latency-msec=100",
"--client-name=RadioDelay", "--stream-name=RadioDelay-output"]
def _target(self):
return int(round(self.delay_ms / CHUNK_MS))
def set_delay(self, delay_ms):
self.delay_ms = int(delay_ms)
def start(self, source, sink, delay_ms):
self.stop()
self.error = None
self.q.clear()
self.delay_ms = int(delay_ms)
self.rec = subprocess.Popen(self._rec_cmd(source),
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
self.play = subprocess.Popen(self._play_cmd(sink),
stdin=subprocess.PIPE, stderr=subprocess.PIPE)
time.sleep(0.3)
for proc, name in ((self.rec, "parec"), (self.play, "pacat")):
if proc.poll() is not None:
err = proc.stderr.read().decode(errors="replace").strip()
code = proc.returncode
self.stop()
raise RuntimeError(f"{name} s'est arrêté : {err or 'code ' + str(code)}")
try: # tube court = peu de latence parasite
fcntl.fcntl(self.play.stdin.fileno(), F_SETPIPE_SZ, 16384)
except OSError:
pass
self.running = True
self.threads = [
threading.Thread(target=self._reader, daemon=True),
threading.Thread(target=self._writer, daemon=True),
]
for t in self.threads:
t.start()
def stop(self):
self.running = False
procs = [p for p in (self.rec, self.play) if p is not None]
for p in procs:
try:
p.terminate()
except (ProcessLookupError, OSError):
pass
for p in procs:
try:
p.wait(timeout=2)
except subprocess.TimeoutExpired:
p.kill()
p.wait()
for t in self.threads:
if t is not threading.current_thread():
t.join(timeout=2)
for p in procs:
for f in (p.stdin, p.stdout, p.stderr):
try:
if f:
f.close()
except Exception:
pass
self.threads = []
self.rec = None
self.play = None
self.q.clear()
# --- threads ---
def _reader(self):
out = self.rec.stdout
while self.running:
data = out.read(CHUNK_BYTES)
if len(data) < CHUNK_BYTES:
if self.running:
self.error = "La capture (parec) s'est arrêtée."
self.running = False
return
self.q.append(data)
limit = self._target() + 25
while len(self.q) > limit:
try:
self.q.popleft()
except IndexError:
break
@staticmethod
def _write_all(fd, data):
view = memoryview(data)
while len(view):
n = os.write(fd, view)
view = view[n:]
def _writer(self):
fd = self.play.stdin.fileno()
silence = bytes(CHUNK_BYTES)
while self.running:
target = self._target()
try:
# Délai réduit : on saute l'audio en trop pour rattraper.
while len(self.q) > target + 2:
self.q.popleft()
chunk = self.q.popleft() if len(self.q) > target else silence
except IndexError:
chunk = silence
try:
self._write_all(fd, chunk) # bloque au rythme de pacat (temps réel)
except OSError:
if self.running:
self.error = "La lecture (pacat) s'est arrêtée."
self.running = False
return
class RadioDelayWindow(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("Radio Delay — synchronisation audio")
self.setMinimumWidth(540)
self.engine = DelayEngine()
self.module_id = None
self.sink_index = None
self.original_sinks = {}
self.target_pattern = "qmplay2"
self.target_label = "QMPlay2"
self._build_ui()
self.route_timer = QTimer(self)
self.route_timer.setInterval(ROUTE_INTERVAL_MS)
self.route_timer.timeout.connect(self.route_qmplay2)
self.watch_timer = QTimer(self)
self.watch_timer.setInterval(500)
self.watch_timer.timeout.connect(self.check_engine)
self.ensure_virtual_sink()
self.refresh_devices()
self.refresh_apps()
# ------------------------------------------------------------ UI
def _build_ui(self):
layout = QVBoxLayout(self)
info = QLabel(
"Redirige automatiquement le son de l'application choisie vers RadioDelay, le retarde, "
"puis l'envoie vers la sortie choisie. Les autres applications ne sont pas modifiées."
)
info.setWordWrap(True)
layout.addWidget(info)
sink_box = QGroupBox("Entrée virtuelle")
sink_layout = QVBoxLayout(sink_box)
self.sink_status = QLabel("Création de l'entrée virtuelle…")
self.sink_status.setWordWrap(True)
sink_layout.addWidget(self.sink_status)
sink_buttons = QHBoxLayout()
self.create_sink_btn = QPushButton("Vérifier / créer l'entrée")
self.remove_sink_btn = QPushButton("Supprimer l'entrée")
sink_buttons.addWidget(self.create_sink_btn)
sink_buttons.addWidget(self.remove_sink_btn)
sink_layout.addLayout(sink_buttons)
layout.addWidget(sink_box)
self.create_sink_btn.clicked.connect(self.ensure_virtual_sink)
self.remove_sink_btn.clicked.connect(self.remove_sink)
app_box = QGroupBox("Application à retarder")
app_layout = QVBoxLayout(app_box)
app_layout.addWidget(QLabel(
"Application dont le son est retardé (liste des flux audio en cours ; "
"tu peux aussi taper un nom) :"))
self.app_combo = QComboBox()
self.app_combo.setEditable(True)
self.app_combo.addItem("QMPlay2")
app_layout.addWidget(self.app_combo)
refresh_apps_btn = QPushButton("Actualiser les applications")
refresh_apps_btn.clicked.connect(self.refresh_apps)
app_layout.addWidget(refresh_apps_btn)
layout.addWidget(app_box)
device_box = QGroupBox("Sortie")
device_layout = QVBoxLayout(device_box)
device_layout.addWidget(QLabel("Sortie (enceinte / casque Bluetooth) :"))
self.output_combo = QComboBox()
device_layout.addWidget(self.output_combo)
refresh = QPushButton("Actualiser les sorties")
refresh.clicked.connect(self.refresh_devices)
device_layout.addWidget(refresh)
layout.addWidget(device_box)
delay_box = QGroupBox("Décalage audio")
delay_layout = QVBoxLayout(delay_box)
self.value_label = QLabel("0 ms (0,00 s)")
self.value_label.setAlignment(Qt.AlignCenter)
self.value_label.setStyleSheet("font-size: 22px; font-weight: bold;")
delay_layout.addWidget(self.value_label)
self.slider = QSlider(Qt.Horizontal)
self.slider.setRange(0, MAX_DELAY_MS)
self.slider.setSingleStep(40)
self.slider.setPageStep(200)
self.slider.valueChanged.connect(self.change_delay)
delay_layout.addWidget(self.slider)
marks = QHBoxLayout()
marks.addWidget(QLabel("0 ms"))
marks.addStretch()
marks.addWidget(QLabel("5 000 ms"))
marks.addStretch()
marks.addWidget(QLabel("10 000 ms"))
delay_layout.addLayout(marks)
layout.addWidget(delay_box)
controls = QHBoxLayout()
self.start_btn = QPushButton("Démarrer le retard + redirection")
self.stop_btn = QPushButton("Arrêter")
self.stop_btn.setEnabled(False)
controls.addWidget(self.start_btn)
controls.addWidget(self.stop_btn)
layout.addLayout(controls)
self.start_btn.clicked.connect(self.start_audio)
self.stop_btn.clicked.connect(self.stop_audio)
self.status_label = QLabel("Prêt. Lance la lecture dans l'application, choisis-la dans la liste, puis démarre le retard.")
self.status_label.setWordWrap(True)
layout.addWidget(self.status_label)
note = QLabel(
"Le retard réel = valeur du curseur + ~0,2 s de latence fixe (tampons). "
"Le retard du Bluetooth lui-même n'est pas compensé : règle à l'oreille."
)
note.setWordWrap(True)
note.setStyleSheet("color: gray;")
layout.addWidget(note)
# ------------------------------------------------- sink virtuel
def get_sink_index(self):
result = run_cmd(["pactl", "list", "short", "sinks"])
if result.returncode == 0:
for line in result.stdout.splitlines():
fields = line.split()
if len(fields) >= 2 and fields[1] == SINK_NAME:
return fields[0]
return None
def ensure_virtual_sink(self):
if not shutil.which("pactl") or not shutil.which("parec") or not shutil.which("pacat"):
QMessageBox.critical(self, "Outils manquants",
"pactl / parec / pacat introuvables (paquet libpulse + pipewire-pulse).")
return
self.sink_index = self.get_sink_index()
if self.sink_index is not None:
self.sink_status.setText(
f"Entrée virtuelle disponible (index {self.sink_index}). "
"L'application choisie sera redirigée automatiquement au démarrage du retard."
)
self.remove_sink_btn.setEnabled(True)
return
result = run_cmd([
"pactl", "load-module", "module-null-sink",
f"sink_name={SINK_NAME}",
f"sink_properties=device.description={SINK_DESC}",
f"rate={RATE}", f"channels={CHANNELS}"
])
if result.returncode != 0:
QMessageBox.critical(self, "Erreur PipeWire",
result.stderr.strip() or result.stdout.strip())
self.sink_status.setText("Impossible de créer l'entrée virtuelle.")
return
self.module_id = result.stdout.strip()
self.sink_index = self.get_sink_index()
self.sink_status.setText(
f"Entrée virtuelle prête (index {self.sink_index}). "
"La redirection automatique sera activée au démarrage du retard."
)
self.remove_sink_btn.setEnabled(True)
self.refresh_devices()
def remove_sink(self):
self.stop_audio()
if self.module_id:
run_cmd(["pactl", "unload-module", str(self.module_id)])
self.module_id = None
else:
# entrée créée lors d'une session précédente : on la décharge par son nom
r = run_cmd(["pactl", "list", "short", "modules"])
for line in r.stdout.splitlines():
f = line.split("\t")
if len(f) >= 3 and f[1] == "module-null-sink" and f"sink_name={SINK_NAME}" in line:
run_cmd(["pactl", "unload-module", f[0]])
self.sink_index = None
self.sink_status.setText("Entrée virtuelle supprimée.")
self.remove_sink_btn.setEnabled(False)
# ---------------------------------------------------- sorties
def refresh_devices(self):
previous = self.output_combo.currentData()
self.output_combo.clear()
sinks = [s for s in list_sinks() if s[0] != SINK_NAME]
for name, desc, _idx in sinks:
self.output_combo.addItem(f"{desc} [{name}]", name)
wanted = previous
if wanted is None:
for name, _d, _i in sinks:
if name.startswith("bluez_output"):
wanted = name
break
if wanted is None:
r = run_cmd(["pactl", "get-default-sink"])
if r.returncode == 0:
wanted = r.stdout.strip()
if wanted is not None:
for n in range(self.output_combo.count()):
if self.output_combo.itemData(n) == wanted:
self.output_combo.setCurrentIndex(n)
break
if not sinks:
self.status_label.setText("Aucune sortie trouvée (pactl list sinks).")
else:
self.status_label.setText("Sorties actualisées. Vérifie que l'enceinte Bluetooth est choisie.")
# ---------------------------------------------------- routage
@staticmethod
def app_name(props):
for key in ("application.name", "node.name", "application.process.binary",
"node.description", "media.name"):
value = props.get(key)
if value:
return str(value)
return ""
@staticmethod
def is_own_stream(props):
return any("radiodelay" in str(props.get(k, "")).lower()
for k in ("application.name", "node.name", "media.name"))
def is_target(self, props):
"""Le flux correspond-il à l'application choisie dans la liste ?"""
pattern = self.target_pattern
if not pattern or self.is_own_stream(props):
return False
for key in ("application.name", "application.process.binary",
"application.process.executable", "media.name",
"node.name", "node.description", "media.icon_name"):
value = props.get(key, "")
if value and pattern in str(value).lower():
return True
return False
def refresh_apps(self):
current = self.app_combo.currentText().strip()
names = []
r = run_cmd(["pactl", "-f", "json", "list", "sink-inputs"])
if r.returncode == 0:
try:
for stream in json.loads(r.stdout):
props = stream.get("properties", {}) or {}
if self.is_own_stream(props):
continue
name = self.app_name(props)
if name and name not in names:
names.append(name)
except json.JSONDecodeError:
pass
self.app_combo.clear()
if current:
self.app_combo.addItem(current)
for name in names:
if name.lower() != current.lower():
self.app_combo.addItem(name)
self.app_combo.setCurrentIndex(0 if current else -1)
if not names:
self.status_label.setText(
"Aucun flux audio en cours : lance la lecture puis actualise, ou tape un nom.")
def route_qmplay2(self):
if not self.engine.running:
return
if self.sink_index is None:
self.sink_index = self.get_sink_index()
if self.sink_index is None:
self.status_label.setText("Entrée virtuelle introuvable : clique sur « Vérifier / créer l'entrée ».")
return
result = run_cmd(["pactl", "-f", "json", "list", "sink-inputs"])
if result.returncode != 0:
self.status_label.setText("pactl -f json list sink-inputs a échoué : " + result.stderr.strip())
return
try:
streams = json.loads(result.stdout)
except json.JSONDecodeError:
return
found = False
for stream in streams:
props = stream.get("properties", {}) or {}
if not self.is_target(props):
continue
found = True
stream_id = str(stream.get("index"))
current_sink = str(stream.get("sink"))
if current_sink == str(self.sink_index):
self.status_label.setText(f"{self.target_label} est redirigé vers RadioDelay. Son retardé actif.")
continue
if stream_id not in self.original_sinks:
self.original_sinks[stream_id] = current_sink
moved = run_cmd(["pactl", "move-sink-input", stream_id, SINK_NAME])
if moved.returncode == 0:
self.status_label.setText(f"{self.target_label} est redirigé vers RadioDelay. Son retardé actif.")
if not found:
self.status_label.setText(
f"Retard actif, mais aucun flux « {self.target_label} » détecté : lance la lecture "
"dans l'application, puis clique sur « Actualiser les applications » si besoin."
)
def restore_qmplay2(self):
default = run_cmd(["pactl", "get-default-sink"])
fallback = default.stdout.strip() if default.returncode == 0 else ""
for stream_id, previous_sink in list(self.original_sinks.items()):
result = run_cmd(["pactl", "move-sink-input", stream_id, previous_sink])
if result.returncode != 0 and fallback:
run_cmd(["pactl", "move-sink-input", stream_id, fallback])
# filet de sécurité : tout flux QMPlay2 resté sur l'entrée virtuelle
if fallback:
r = run_cmd(["pactl", "-f", "json", "list", "sink-inputs"])
if r.returncode == 0:
try:
for s in json.loads(r.stdout):
if (self.is_target(s.get("properties", {}) or {})
and str(s.get("sink")) == str(self.sink_index)):
run_cmd(["pactl", "move-sink-input", str(s.get("index")), fallback])
except json.JSONDecodeError:
pass
self.original_sinks.clear()
# ----------------------------------------------------- actions
def change_delay(self, value):
self.value_label.setText(f"{value:,} ms ({value / 1000:.2f} s)".replace(",", " "))
self.engine.set_delay(value)
def start_audio(self):
if self.sink_index is None:
self.ensure_virtual_sink()
if self.sink_index is None:
return
if self.output_combo.count() == 0:
QMessageBox.warning(self, "Sortie manquante", "Aucune sortie disponible.")
return
self.target_label = self.app_combo.currentText().strip()
self.target_pattern = self.target_label.lower()
if not self.target_pattern:
QMessageBox.warning(self, "Application manquante", "Choisis ou tape l'application à retarder.")
return
try:
self.engine.start(MONITOR_NAME, self.output_combo.currentData(), self.slider.value())
except Exception as e:
QMessageBox.critical(self, "Impossible de démarrer l'audio", str(e))
return
self.start_btn.setEnabled(False)
self.stop_btn.setEnabled(True)
self.app_combo.setEnabled(False)
self.status_label.setText(f"Retard actif. Recherche du flux « {self.target_label} »…")
self.route_qmplay2()
self.route_timer.start()
self.watch_timer.start()
def check_engine(self):
if self.engine.error:
msg = self.engine.error
self.stop_audio()
self.status_label.setText(msg)
def stop_audio(self):
self.route_timer.stop()
self.watch_timer.stop()
self.engine.stop()
self.restore_qmplay2()
self.start_btn.setEnabled(True)
self.stop_btn.setEnabled(False)
self.app_combo.setEnabled(True)
self.status_label.setText("Traitement arrêté. L'application a été renvoyée vers sa sortie précédente.")
def closeEvent(self, event):
self.stop_audio()
if self.module_id:
run_cmd(["pactl", "unload-module", str(self.module_id)])
self.module_id = None
event.accept()
if __name__ == "__main__":
app = QApplication(sys.argv)
window = RadioDelayWindow()
window.show()
# Ctrl+C dans le terminal : fermeture propre (restauration de QMPlay2)
signal.signal(signal.SIGINT, lambda *_: window.close())
signal.signal(signal.SIGTERM, lambda *_: window.close())
tick = QTimer()
tick.start(500)
tick.timeout.connect(lambda: None)
sys.exit(app.exec())