forked from trav/lintunes
v0.102.0: Connections › Connect to Mumble… plays into a Mumble room as a user of its own — it joins the server your Mumble is on (or one you saved there), follows you from room to room unless you pick one, and pauses rather than playing out loud if the connection drops; name, quality and stereo in Preferences › Integrations
This commit is contained in:
@@ -1,3 +1,3 @@
|
||||
"""LinTunes — iTunes-style music library manager and player for Linux."""
|
||||
|
||||
__version__ = "0.101.0"
|
||||
__version__ = "0.102.0"
|
||||
|
||||
@@ -157,6 +157,23 @@ def _airplay(p, color):
|
||||
]))
|
||||
|
||||
|
||||
def _mumble(p, color):
|
||||
"""A headset with a boom mic: playing into a voice-chat room."""
|
||||
pen = QPen(color, 1.6)
|
||||
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
|
||||
p.setPen(pen)
|
||||
p.setBrush(Qt.BrushStyle.NoBrush)
|
||||
# The headband, over the top from ear to ear.
|
||||
p.drawArc(QRectF(4.0, 3.0, 12.0, 14.0), 0, 180 * 16)
|
||||
# The boom, from the right cup round to the mouth.
|
||||
p.drawArc(QRectF(7.5, 8.5, 8.5, 8.0), 270 * 16, 90 * 16)
|
||||
p.setPen(Qt.PenStyle.NoPen)
|
||||
p.setBrush(color)
|
||||
p.drawRoundedRect(QRectF(2.6, 9.0, 3.6, 5.6), 1.2, 1.2)
|
||||
p.drawRoundedRect(QRectF(13.8, 9.0, 3.6, 5.6), 1.2, 1.2)
|
||||
p.drawEllipse(QPointF(11.4, 16.5), 1.5, 1.5)
|
||||
|
||||
|
||||
def _sun(p, color):
|
||||
"""Light mode's glyph: a disc and eight rays."""
|
||||
import math
|
||||
@@ -222,6 +239,7 @@ _DRAWERS = {
|
||||
"repeat_one": _repeat_one,
|
||||
"cast": _cast,
|
||||
"airplay": _airplay,
|
||||
"mumble": _mumble,
|
||||
"sun": _sun,
|
||||
"moon": _moon,
|
||||
"speakers": _speakers,
|
||||
|
||||
@@ -21,6 +21,7 @@ from lintunes.andtunes import install as andtunes_install
|
||||
from lintunes.andtunes import sync as andtunes_sync
|
||||
from lintunes.art_search import AlbumArtFetcher
|
||||
from lintunes.airplay.controller import AirPlayController
|
||||
from lintunes.mumble.controller import MumbleController
|
||||
from lintunes.cast.controller import CastController
|
||||
from lintunes.eventlog import log_control
|
||||
from lintunes.config import load_config, save_config
|
||||
@@ -158,6 +159,9 @@ class MainWindow(QMainWindow):
|
||||
# The same for AirPlay. At most one of the two is ever connected:
|
||||
# connecting either disconnects the other first.
|
||||
self._airplay = AirPlayController(self.player, self)
|
||||
# And a Mumble room (Round 134): LinTunes as a user of its own,
|
||||
# talking the music in. One of the three at a time.
|
||||
self._mumble = MumbleController(self.player, prefs, self)
|
||||
# Where the Rabbit is, found off the GUI thread: a wedged gvfs-MTP
|
||||
# mount blocks any listing of it forever (Round 71). Nothing probes
|
||||
# until the Connections menu opens.
|
||||
@@ -193,7 +197,8 @@ class MainWindow(QMainWindow):
|
||||
self.setCentralWidget(central)
|
||||
|
||||
self._transport = TransportBar(self.player, manager, self._prefs,
|
||||
cast=self._cast, airplay=self._airplay)
|
||||
cast=self._cast, airplay=self._airplay,
|
||||
mumble=self._mumble)
|
||||
layout.addWidget(self._transport)
|
||||
# DJ mode (Round 93): the shelf is made the first time it opens.
|
||||
self._dj = None
|
||||
@@ -431,8 +436,21 @@ class MainWindow(QMainWindow):
|
||||
self._airplay.disconnected.connect(
|
||||
lambda reason: self.statusBar().showMessage(
|
||||
reason or "Stopped AirPlay — playing here again", 8000))
|
||||
# The toolbar's speakers button is lit while either plays.
|
||||
for controller in (self._cast, self._airplay):
|
||||
self._mumble.connecting.connect(
|
||||
lambda server: self.statusBar().showMessage(
|
||||
f"Connecting to {server.label()}…", 8000))
|
||||
self._mumble.connected.connect(
|
||||
lambda name: self.statusBar().showMessage(
|
||||
f"Playing on {name}", 6000))
|
||||
self._mumble.disconnected.connect(
|
||||
lambda reason: self.statusBar().showMessage(
|
||||
reason or "Left Mumble — paused", 8000))
|
||||
self._mumble.notice.connect(
|
||||
lambda text: self.statusBar().showMessage(text, 10000))
|
||||
self._mumble.failed.connect(
|
||||
lambda msg: QMessageBox.warning(self, "Mumble", msg))
|
||||
# The toolbar's speakers button is lit while any of them plays.
|
||||
for controller in (self._cast, self._airplay, self._mumble):
|
||||
controller.connected.connect(self._show_speakers_state)
|
||||
controller.disconnected.connect(self._show_speakers_state)
|
||||
self._airplay.failed.connect(
|
||||
@@ -650,6 +668,14 @@ class MainWindow(QMainWindow):
|
||||
connections_menu, "Connect to Chromecast…", "", self._toggle_cast)
|
||||
self._airplay_action = self._add_action(
|
||||
connections_menu, "Connect to AirPlay…", "", self._toggle_airplay)
|
||||
self._mumble_action = self._add_action(
|
||||
connections_menu, "Connect to Mumble…", "", self._toggle_mumble)
|
||||
# Which room the bot is in: shown only while it's connected.
|
||||
self._mumble_rooms = QMenu("Mumble Room", self)
|
||||
self._mumble_rooms.aboutToShow.connect(self._fill_mumble_rooms)
|
||||
self._mumble_rooms_action = connections_menu.addMenu(
|
||||
self._mumble_rooms)
|
||||
self._mumble_rooms_action.setVisible(False)
|
||||
# Re-checked every time the menu opens. The device part is a
|
||||
# background probe; its answer updates the open menu when it lands.
|
||||
connections_menu.aboutToShow.connect(self._refresh_connection_actions)
|
||||
@@ -731,7 +757,8 @@ class MainWindow(QMainWindow):
|
||||
# pyatv) yet.
|
||||
for action, controller, text in (
|
||||
(self._cast_action, self._cast, "Connect to Chromecast…"),
|
||||
(self._airplay_action, self._airplay, "Connect to AirPlay…")):
|
||||
(self._airplay_action, self._airplay, "Connect to AirPlay…"),
|
||||
(self._mumble_action, self._mumble, "Connect to Mumble…")):
|
||||
if controller.is_connected():
|
||||
action.setText(f"Disconnect from {controller.device_name()}")
|
||||
action.setEnabled(True)
|
||||
@@ -742,6 +769,7 @@ class MainWindow(QMainWindow):
|
||||
action.setEnabled(available)
|
||||
action.setToolTip(
|
||||
"" if available else f"{why} — run: pip install -e .")
|
||||
self._mumble_rooms_action.setVisible(self._mumble.is_connected())
|
||||
|
||||
# ---- connections: casting ----
|
||||
|
||||
@@ -759,6 +787,7 @@ class MainWindow(QMainWindow):
|
||||
dialog = ChromecastDialog(self._cast.discovery(), self)
|
||||
if dialog.exec() and dialog.selected_device is not None:
|
||||
self._airplay.disconnect()
|
||||
self._mumble.disconnect()
|
||||
self._cast.connect_to(dialog.selected_device)
|
||||
|
||||
def _toggle_airplay(self):
|
||||
@@ -775,8 +804,62 @@ class MainWindow(QMainWindow):
|
||||
dialog = AirPlayDialog(self._airplay.discovery(), self)
|
||||
if dialog.exec() and dialog.selected_device is not None:
|
||||
self._cast.disconnect()
|
||||
self._mumble.disconnect()
|
||||
self._airplay.connect_to(dialog.selected_device)
|
||||
|
||||
def _toggle_mumble(self):
|
||||
"""Joins the server this computer's Mumble is on, straight away;
|
||||
with Mumble not connected, asks which of its saved servers."""
|
||||
if self._mumble.is_connected():
|
||||
self._mumble.disconnect()
|
||||
return
|
||||
available, why = self._mumble.is_available()
|
||||
if not available:
|
||||
QMessageBox.information(self, "Mumble playback unavailable",
|
||||
f"{why}.")
|
||||
return
|
||||
choices = self._mumble.choices()
|
||||
server = choices[0] if choices and choices[0].current else None
|
||||
if server is None:
|
||||
from lintunes.gui.mumble_dialog import MumbleServerDialog
|
||||
from lintunes.mumble.controller import bot_name
|
||||
dialog = MumbleServerDialog(choices, bot_name(self._prefs), self)
|
||||
if not dialog.exec() or dialog.selected_server is None:
|
||||
return
|
||||
server = dialog.selected_server
|
||||
# A typed address that is a saved server: its password, and the
|
||||
# name trav uses there (whom to follow).
|
||||
saved = next((c for c in choices if c.same_place(server)), None)
|
||||
if saved is not None and saved is not server:
|
||||
server.name = server.name or saved.name
|
||||
server.username = server.username or saved.username
|
||||
server.password = server.password or saved.password
|
||||
self._cast.disconnect()
|
||||
self._airplay.disconnect()
|
||||
self._mumble.connect_to(server)
|
||||
|
||||
def _fill_mumble_rooms(self):
|
||||
"""Follow me, then the server's rooms as Mumble shows them."""
|
||||
menu = self._mumble_rooms
|
||||
menu.clear()
|
||||
whom = self._mumble.follow_name()
|
||||
follow = menu.addAction(f"Follow {whom}" if whom else "Follow Me")
|
||||
follow.setCheckable(True)
|
||||
follow.setChecked(bool(self._mumble.following()))
|
||||
follow.setEnabled(bool(whom))
|
||||
if not whom:
|
||||
follow.setToolTip("Mumble didn't say what name you use on this "
|
||||
"server, so there's no one to follow")
|
||||
follow.triggered.connect(lambda: self._mumble.set_room(None))
|
||||
menu.addSeparator()
|
||||
here = self._mumble.current_room()
|
||||
for channel_id, depth, name in self._mumble.rooms():
|
||||
action = menu.addAction(" " * depth + name)
|
||||
action.setCheckable(True)
|
||||
action.setChecked(channel_id == here)
|
||||
action.triggered.connect(
|
||||
lambda _=False, cid=channel_id: self._mumble.set_room(cid))
|
||||
|
||||
def _show_speaker_menu(self, button):
|
||||
"""The toolbar's speakers button: Connections' Chromecast and AirPlay
|
||||
entries (each "Disconnect from …" while it plays), under the button."""
|
||||
@@ -784,10 +867,13 @@ class MainWindow(QMainWindow):
|
||||
menu = QMenu(self)
|
||||
menu.addAction(self._cast_action)
|
||||
menu.addAction(self._airplay_action)
|
||||
menu.addAction(self._mumble_action)
|
||||
if self._mumble.is_connected():
|
||||
menu.addMenu(self._mumble_rooms)
|
||||
menu.exec(button.mapToGlobal(button.rect().bottomLeft()))
|
||||
|
||||
def _show_speakers_state(self, *_):
|
||||
for controller in (self._cast, self._airplay):
|
||||
for controller in (self._cast, self._airplay, self._mumble):
|
||||
if controller.is_connected():
|
||||
self._transport.set_speakers_active(True, controller.device_name())
|
||||
return
|
||||
@@ -3628,6 +3714,7 @@ class MainWindow(QMainWindow):
|
||||
self._cassette.shutdown()
|
||||
self._cast.shutdown()
|
||||
self._airplay.shutdown()
|
||||
self._mumble.shutdown()
|
||||
if self._dj is not None:
|
||||
self._dj.shutdown() # its audio thread must end before Qt does
|
||||
self.player.shutdown()
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
"""Connect to Mumble…'s picker, shown only when the running Mumble isn't
|
||||
connected anywhere (if it is, LinTunes joins that server without asking):
|
||||
the servers saved in Mumble, and a box for any other address."""
|
||||
|
||||
from PyQt6.QtWidgets import (
|
||||
QDialog, QDialogButtonBox, QLabel, QLineEdit, QListWidget,
|
||||
QListWidgetItem, QVBoxLayout)
|
||||
from PyQt6.QtCore import Qt
|
||||
|
||||
from lintunes.mumble import servers
|
||||
|
||||
|
||||
def parse_address(text: str) -> servers.Server | None:
|
||||
"""``host``, ``host:port``, ``[v6]:port`` or a ``mumble://`` URL."""
|
||||
text = text.strip()
|
||||
if not text:
|
||||
return None
|
||||
if "://" not in text:
|
||||
text = "mumble://" + text
|
||||
return servers.parse_url(text)
|
||||
|
||||
|
||||
class MumbleServerDialog(QDialog):
|
||||
def __init__(self, choices: list[servers.Server], bot_name: str,
|
||||
parent=None):
|
||||
super().__init__(parent)
|
||||
self.setWindowTitle("Connect to Mumble")
|
||||
self.setMinimumWidth(380)
|
||||
self._selected: servers.Server | None = None
|
||||
layout = QVBoxLayout(self)
|
||||
|
||||
intro = QLabel(
|
||||
"Your Mumble isn't connected to a server, so pick one. LinTunes "
|
||||
"joins as a user of its own and follows you between rooms.")
|
||||
intro.setWordWrap(True)
|
||||
layout.addWidget(intro)
|
||||
|
||||
self._list = QListWidget()
|
||||
self._list.setAlternatingRowColors(True)
|
||||
for server in choices:
|
||||
item = QListWidgetItem(server.label())
|
||||
item.setData(Qt.ItemDataRole.UserRole, server)
|
||||
self._list.addItem(item)
|
||||
if not choices:
|
||||
self._list.hide()
|
||||
layout.addWidget(QLabel("You have no servers saved in Mumble."))
|
||||
self._list.itemSelectionChanged.connect(self._on_list)
|
||||
self._list.itemDoubleClicked.connect(lambda _: self._accept())
|
||||
layout.addWidget(self._list, stretch=1)
|
||||
|
||||
self._address = QLineEdit()
|
||||
self._address.setPlaceholderText("Another server: host or host:port")
|
||||
self._address.textChanged.connect(self._on_typed)
|
||||
self._address.returnPressed.connect(self._accept)
|
||||
layout.addWidget(self._address)
|
||||
|
||||
note = QLabel(f"Joins as “{bot_name}”. Change the name, bitrate and "
|
||||
"stereo in Preferences › Integrations.")
|
||||
note.setWordWrap(True)
|
||||
note.setEnabled(False)
|
||||
layout.addWidget(note)
|
||||
|
||||
buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Cancel)
|
||||
self._connect = buttons.addButton(
|
||||
"Connect", QDialogButtonBox.ButtonRole.AcceptRole)
|
||||
self._connect.setDefault(True)
|
||||
self._connect.setEnabled(False)
|
||||
self._connect.clicked.connect(self._accept)
|
||||
buttons.rejected.connect(self.reject)
|
||||
layout.addWidget(buttons)
|
||||
if choices:
|
||||
self._list.setCurrentRow(0)
|
||||
|
||||
@property
|
||||
def selected_server(self) -> servers.Server | None:
|
||||
return self._selected
|
||||
|
||||
def _on_list(self):
|
||||
if self._list.selectedItems():
|
||||
self._address.blockSignals(True)
|
||||
self._address.clear()
|
||||
self._address.blockSignals(False)
|
||||
self._connect.setEnabled(self._choice() is not None)
|
||||
|
||||
def _on_typed(self, text: str):
|
||||
if text.strip():
|
||||
self._list.clearSelection()
|
||||
self._connect.setEnabled(self._choice() is not None)
|
||||
|
||||
def _choice(self) -> servers.Server | None:
|
||||
if self._address.text().strip():
|
||||
return parse_address(self._address.text())
|
||||
items = self._list.selectedItems()
|
||||
return items[0].data(Qt.ItemDataRole.UserRole) if items else None
|
||||
|
||||
def _accept(self):
|
||||
choice = self._choice()
|
||||
if choice is not None:
|
||||
self._selected = choice
|
||||
self.accept()
|
||||
@@ -153,6 +153,7 @@ class PreferencesDialog(QDialog):
|
||||
self._build_dj_cache_group()]),
|
||||
("Integrations", [self._build_lastfm_group(),
|
||||
self._build_acoustid_group(),
|
||||
self._build_mumble_group(),
|
||||
self._build_web_server_group()])):
|
||||
self._add_page(title, groups)
|
||||
self.pages_list.currentRowChanged.connect(self._show_page)
|
||||
@@ -1448,6 +1449,55 @@ class PreferencesDialog(QDialog):
|
||||
form.addRow("AcoustID key:", self._acoustid_key)
|
||||
return group
|
||||
|
||||
def _build_mumble_group(self) -> QGroupBox:
|
||||
"""Connections › Connect to Mumble…: how the bot appears and sounds."""
|
||||
from lintunes.mumble.controller import (
|
||||
BITRATES_KBPS, DEFAULT_KBPS, DEFAULT_NAME)
|
||||
group = QGroupBox("Mumble")
|
||||
form = QFormLayout(group)
|
||||
hint = QLabel(
|
||||
"Connect to Mumble… joins the server your Mumble is on as a "
|
||||
"user of its own and plays into your room, following you as you "
|
||||
"move. Everyone in the room hears it, you included, a moment "
|
||||
"late. Each listener can turn it up or down in their own Mumble.")
|
||||
hint.setWordWrap(True)
|
||||
form.addRow(hint)
|
||||
self._mumble_name = QLineEdit(
|
||||
self._prefs.get("mumble_name", DEFAULT_NAME) or "")
|
||||
self._mumble_name.setPlaceholderText(DEFAULT_NAME)
|
||||
self._mumble_name.setToolTip(
|
||||
"Takes effect the next time LinTunes connects")
|
||||
self._mumble_name.editingFinished.connect(
|
||||
lambda: self._prefs.set(
|
||||
"mumble_name", self._mumble_name.text().strip()
|
||||
or DEFAULT_NAME))
|
||||
form.addRow("Name:", self._mumble_name)
|
||||
self._mumble_kbps = QComboBox()
|
||||
for kbps in BITRATES_KBPS:
|
||||
self._mumble_kbps.addItem(f"{kbps} kbps", kbps)
|
||||
current = int(self._prefs.get("mumble_kbps", DEFAULT_KBPS)
|
||||
or DEFAULT_KBPS)
|
||||
index = self._mumble_kbps.findData(current)
|
||||
self._mumble_kbps.setCurrentIndex(
|
||||
index if index >= 0 else self._mumble_kbps.findData(DEFAULT_KBPS))
|
||||
self._mumble_kbps.setToolTip(
|
||||
"Opus, for music. A server caps each user's bandwidth (often "
|
||||
"72 or 558 kbps); LinTunes plays at that cap when this is more")
|
||||
self._mumble_kbps.currentIndexChanged.connect(
|
||||
lambda _: self._prefs.set("mumble_kbps",
|
||||
self._mumble_kbps.currentData()))
|
||||
form.addRow("Quality:", self._mumble_kbps)
|
||||
self._mumble_stereo = QCheckBox("Stereo")
|
||||
self._mumble_stereo.setChecked(
|
||||
bool(self._prefs.get("mumble_stereo", True)))
|
||||
self._mumble_stereo.setToolTip(
|
||||
"Listeners whose Mumble plays only mono hear both sides mixed. "
|
||||
"Mono puts the whole bitrate into one channel")
|
||||
self._mumble_stereo.toggled.connect(
|
||||
lambda on: self._prefs.set("mumble_stereo", on))
|
||||
form.addRow("", self._mumble_stereo)
|
||||
return group
|
||||
|
||||
def _build_web_server_group(self) -> QGroupBox:
|
||||
"""Where Export Web Mix uploads to. config.json, not preferences: the
|
||||
host is usually an ssh alias on *this* machine, and nothing about the
|
||||
|
||||
@@ -788,6 +788,7 @@ class TransportBar(QWidget):
|
||||
identify_clicked = pyqtSignal()
|
||||
|
||||
def __init__(self, player, manager, prefs, cast=None, airplay=None,
|
||||
mumble=None,
|
||||
parent=None):
|
||||
super().__init__(parent)
|
||||
self._player = player
|
||||
@@ -1039,7 +1040,8 @@ class TransportBar(QWidget):
|
||||
# a no-op.
|
||||
self._visualizer.cast_stop_requested.connect(
|
||||
lambda: (cast.disconnect(),
|
||||
airplay is not None and airplay.disconnect()))
|
||||
airplay is not None and airplay.disconnect(),
|
||||
mumble is not None and mumble.disconnect()))
|
||||
|
||||
# ---- DJ mode ----
|
||||
|
||||
|
||||
@@ -155,7 +155,7 @@ class VisualizerWidget(QWidget):
|
||||
self._glyph = getattr(sink, "glyph", "cast")
|
||||
self._device = getattr(sink, "name", "") or "a Chromecast"
|
||||
self._clear()
|
||||
verb = "Playing on" if self._glyph == "airplay" else "Casting to"
|
||||
verb = "Casting to" if self._glyph == "cast" else "Playing on"
|
||||
self.setToolTip(f"{verb} {self._device} — click to stop")
|
||||
else:
|
||||
self._device = ""
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
"""Playing to a Mumble server (Connections › Connect to Mumble…, Round 134).
|
||||
|
||||
LinTunes joins the server as a user of its own — a bot, with its own name and
|
||||
certificate — and talks into a room with the music. It is a third
|
||||
`PlaybackSink` beside Chromecast and AirPlay: while it is connected nothing
|
||||
comes out of this computer's speakers, and someone in the same room (trav,
|
||||
in Mumble with headphones on) hears it the way everyone else does.
|
||||
|
||||
Everything is hand-rolled, the AirPlay sender's way: `proto.py` is the wire
|
||||
format (a TLS stream of length-prefixed protobuf messages, voice tunnelled in
|
||||
the same stream), `opus.py` is libopus through ctypes, `client.py` the
|
||||
connection, `sink.py` the player side, `servers.py` where to connect (the
|
||||
running Mumble's D-Bus, its saved servers). pymumble was the alternative and
|
||||
is abandoned, and its generated protobuf code doesn't load on protobuf ≥ 4.
|
||||
"""
|
||||
@@ -0,0 +1,107 @@
|
||||
"""LinTunes' own Mumble identity, and how it decides a server is the real one.
|
||||
|
||||
**Its certificate** is self-signed, made once per machine by the `openssl`
|
||||
CLI (a runtime tool, like ffmpeg) and kept in ``$XDG_DATA_HOME/lintunes/
|
||||
mumble/`` — never the synced share: the key is this machine's. A certificate
|
||||
is what lets a server recognise the bot again after a dropped connection
|
||||
(its old session is replaced rather than "name already in use") and what an
|
||||
admin registers if the server ever wants that.
|
||||
|
||||
**The server's certificate**: a CA-signed one is checked the normal way. A
|
||||
self-signed one (most Mumble servers) is accepted only if its SHA-1 is the
|
||||
one trav's Mumble already accepted for that host and port, or — for a server
|
||||
his Mumble never had to ask about — the one LinTunes saw the first time,
|
||||
remembered in config.json's ``mumble_server_certs``. A changed certificate
|
||||
is refused, never silently re-trusted.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
from lintunes import paths
|
||||
from lintunes.config import load_config, save_config
|
||||
|
||||
PINS_KEY = "mumble_server_certs"
|
||||
SUBJECT = "/CN=LinTunes"
|
||||
|
||||
|
||||
class CertificateError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def identity_dir() -> Path:
|
||||
return paths.data_dir() / "mumble"
|
||||
|
||||
|
||||
def ensure_identity(directory: Path | None = None) -> tuple[Path, Path]:
|
||||
"""(cert.pem, key.pem), made on first use."""
|
||||
directory = directory or identity_dir()
|
||||
cert, key = directory / "cert.pem", directory / "key.pem"
|
||||
if cert.is_file() and key.is_file():
|
||||
return cert, key
|
||||
if shutil.which("openssl") is None:
|
||||
raise CertificateError("openssl isn't installed")
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
tmp_cert, tmp_key = cert.with_suffix(".tmp"), key.with_suffix(".tmp")
|
||||
result = subprocess.run(
|
||||
["openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes",
|
||||
"-keyout", str(tmp_key), "-out", str(tmp_cert),
|
||||
"-days", "7300", "-subj", SUBJECT],
|
||||
stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=60)
|
||||
if result.returncode != 0 or not tmp_cert.is_file():
|
||||
for p in (tmp_cert, tmp_key):
|
||||
p.unlink(missing_ok=True)
|
||||
raise CertificateError(
|
||||
result.stderr.strip().splitlines()[-1] if result.stderr.strip()
|
||||
else "openssl couldn't make a certificate")
|
||||
os.chmod(tmp_key, 0o600)
|
||||
os.replace(tmp_key, key)
|
||||
os.replace(tmp_cert, cert)
|
||||
return cert, key
|
||||
|
||||
|
||||
def digest(der: bytes) -> str:
|
||||
return hashlib.sha1(der).hexdigest()
|
||||
|
||||
|
||||
def _pin_key(host: str, port: int) -> str:
|
||||
return f"{host.lower()}:{int(port)}"
|
||||
|
||||
|
||||
def pinned(host: str, port: int) -> str | None:
|
||||
return (load_config().get(PINS_KEY) or {}).get(_pin_key(host, port))
|
||||
|
||||
|
||||
def pin(host: str, port: int, value: str):
|
||||
config = load_config()
|
||||
pins = dict(config.get(PINS_KEY) or {})
|
||||
if pins.get(_pin_key(host, port)) == value:
|
||||
return
|
||||
pins[_pin_key(host, port)] = value
|
||||
config[PINS_KEY] = pins
|
||||
save_config(config)
|
||||
|
||||
|
||||
def check_self_signed(host: str, port: int, der: bytes,
|
||||
mumble_digest: str | None) -> str:
|
||||
"""Accept or refuse a certificate no CA vouches for. Returns how it was
|
||||
trusted ("mumble" | "pinned" | "first use"); raises CertificateError."""
|
||||
seen = digest(der)
|
||||
if mumble_digest:
|
||||
if seen == mumble_digest.lower():
|
||||
return "mumble"
|
||||
raise CertificateError(
|
||||
f"{host}'s certificate isn't the one your Mumble accepted for it")
|
||||
known = pinned(host, port)
|
||||
if known is not None:
|
||||
if seen == known:
|
||||
return "pinned"
|
||||
raise CertificateError(
|
||||
f"{host}'s certificate has changed since LinTunes last "
|
||||
f"connected (to trust the new one, remove {_pin_key(host, port)} "
|
||||
f"from {PINS_KEY} in config.json)")
|
||||
pin(host, port, seen)
|
||||
return "first use"
|
||||
@@ -0,0 +1,380 @@
|
||||
"""One connection to a Mumble server, on the shared asyncio loop.
|
||||
|
||||
Everything here runs on the loop thread (`airplay.loop.AsyncLoop` — the same
|
||||
kind of daemon loop; Mumble gets its own instance). The connection keeps the
|
||||
server's channel tree and user list current from the messages it reads, and
|
||||
reports changes through plain callbacks, which the controller turns into Qt
|
||||
signals for the GUI thread.
|
||||
|
||||
**Following**: the person to follow is matched by the name they use on the
|
||||
server (from Mumble's own URL, or the saved server). While following, every
|
||||
move of theirs moves the bot after them; a room picked by hand pins it there
|
||||
instead.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import ssl
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from lintunes.mumble import certs, proto
|
||||
|
||||
log = logging.getLogger("lintunes.mumble")
|
||||
|
||||
CONNECT_TIMEOUT_S = 10.0
|
||||
PING_INTERVAL_S = 15.0
|
||||
|
||||
|
||||
class MumbleError(ConnectionError):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass
|
||||
class Channel:
|
||||
channel_id: int
|
||||
name: str = ""
|
||||
parent: int | None = None
|
||||
position: int = 0
|
||||
|
||||
|
||||
@dataclass
|
||||
class User:
|
||||
session: int
|
||||
name: str = ""
|
||||
channel_id: int = 0
|
||||
suppressed: bool = False
|
||||
mute: bool = False # by an admin
|
||||
self_mute: bool = False
|
||||
|
||||
@property
|
||||
def muted(self) -> bool:
|
||||
return self.mute or self.self_mute
|
||||
|
||||
|
||||
@dataclass
|
||||
class ServerState:
|
||||
session: int = 0
|
||||
max_bandwidth: int = 0
|
||||
welcome: str = ""
|
||||
channels: dict[int, Channel] = field(default_factory=dict)
|
||||
users: dict[int, User] = field(default_factory=dict)
|
||||
|
||||
def path_of(self, channel_id: int) -> list[str]:
|
||||
path, seen = [], set()
|
||||
channel = self.channels.get(channel_id)
|
||||
while channel is not None and channel.parent is not None \
|
||||
and channel.channel_id not in seen:
|
||||
seen.add(channel.channel_id)
|
||||
path.insert(0, channel.name)
|
||||
channel = self.channels.get(channel.parent)
|
||||
return path
|
||||
|
||||
def channel_by_path(self, path: list[str]) -> int | None:
|
||||
"""The channel at ``Room/Sub-room`` (root's children first)."""
|
||||
current = self.root_id()
|
||||
if current is None:
|
||||
return None
|
||||
for name in path:
|
||||
child = next((c.channel_id for c in self.channels.values()
|
||||
if c.parent == current and c.name == name), None)
|
||||
if child is None:
|
||||
return None
|
||||
current = child
|
||||
return current
|
||||
|
||||
def root_id(self) -> int | None:
|
||||
if 0 in self.channels:
|
||||
return 0
|
||||
return next((c.channel_id for c in self.channels.values()
|
||||
if c.parent is None), None)
|
||||
|
||||
def tree(self) -> list[tuple[int, int, str]]:
|
||||
"""[(channel id, depth, name)] in Mumble's own order: by position,
|
||||
then by name, depth first."""
|
||||
children: dict[int | None, list[Channel]] = {}
|
||||
for c in self.channels.values():
|
||||
children.setdefault(c.parent, []).append(c)
|
||||
out = []
|
||||
|
||||
def walk(parent, depth):
|
||||
for c in sorted(children.get(parent, []),
|
||||
key=lambda c: (c.position, c.name.lower())):
|
||||
out.append((c.channel_id, depth, c.name))
|
||||
if c.channel_id != parent:
|
||||
walk(c.channel_id, depth + 1)
|
||||
root = self.root_id()
|
||||
if root is None:
|
||||
return out
|
||||
out.append((root, 0, self.channels[root].name or "Root"))
|
||||
walk(root, 1)
|
||||
return out
|
||||
|
||||
def find_user(self, name: str, besides: int = 0) -> User | None:
|
||||
if not name:
|
||||
return None
|
||||
folded = name.casefold()
|
||||
return next((u for u in self.users.values()
|
||||
if u.session != besides and u.name.casefold() == folded),
|
||||
None)
|
||||
|
||||
def me(self) -> User | None:
|
||||
return self.users.get(self.session)
|
||||
|
||||
|
||||
class Connection:
|
||||
"""A bot's session. ``on_event(kind, detail)`` is called on the loop
|
||||
thread for: "channels", "moved" (the bot's channel changed), "suppressed"
|
||||
(bool), "denied" (str), "lost" (str)."""
|
||||
|
||||
def __init__(self, on_event=None):
|
||||
self.state = ServerState()
|
||||
self.trust = ""
|
||||
self._on_event = on_event or (lambda kind, detail: None)
|
||||
self._reader = None
|
||||
self._writer = None
|
||||
self._tasks: list[asyncio.Task] = []
|
||||
self._closed = False
|
||||
self.follow_name = ""
|
||||
self.pinned_channel: int | None = None
|
||||
self._last_suppressed = None
|
||||
|
||||
# ---- connecting ----
|
||||
|
||||
async def connect(self, host: str, port: int, name: str, password: str,
|
||||
certfile=None, keyfile=None, mumble_digest=None,
|
||||
target_path=None):
|
||||
try:
|
||||
await asyncio.wait_for(self._open(host, port, certfile, keyfile,
|
||||
mumble_digest),
|
||||
CONNECT_TIMEOUT_S)
|
||||
except asyncio.TimeoutError:
|
||||
raise MumbleError(f"{host} didn't answer") from None
|
||||
except certs.CertificateError as e:
|
||||
raise MumbleError(str(e)) from None
|
||||
except ConnectionResetError:
|
||||
# What a server's flood protection looks like from here, too:
|
||||
# too many connects from one address in two minutes is a ban.
|
||||
raise MumbleError(f"{host} closed the connection straight away "
|
||||
"(it may be refusing this computer for a "
|
||||
"while after many connects)") from None
|
||||
except OSError as e:
|
||||
raise MumbleError(e.strerror or str(e)
|
||||
or type(e).__name__) from None
|
||||
self._writer.write(proto.version_message()
|
||||
+ proto.authenticate_message(name, password))
|
||||
await self._writer.drain()
|
||||
try:
|
||||
await asyncio.wait_for(self._handshake(), CONNECT_TIMEOUT_S)
|
||||
except asyncio.TimeoutError:
|
||||
await self.close()
|
||||
raise MumbleError(f"{host} didn't let LinTunes in") from None
|
||||
except BaseException:
|
||||
await self.close()
|
||||
raise
|
||||
self._tasks = [asyncio.ensure_future(self._read_forever()),
|
||||
asyncio.ensure_future(self._ping_forever())]
|
||||
# Where to go first: the followed person's room, else the room the
|
||||
# URL named, else wherever the server put us.
|
||||
followed = self.state.find_user(self.follow_name, self.state.session)
|
||||
target = followed.channel_id if followed else None
|
||||
if target is None and target_path:
|
||||
target = self.state.channel_by_path(target_path)
|
||||
if target is not None:
|
||||
self.move_to(target)
|
||||
|
||||
async def _open(self, host, port, certfile, keyfile, mumble_digest):
|
||||
verified = ssl.create_default_context()
|
||||
if certfile:
|
||||
verified.load_cert_chain(certfile, keyfile)
|
||||
try:
|
||||
self._reader, self._writer = await asyncio.open_connection(
|
||||
host, port, ssl=verified, server_hostname=host)
|
||||
self.trust = "CA"
|
||||
return
|
||||
except ssl.SSLCertVerificationError:
|
||||
pass
|
||||
# Self-signed, as most Mumble servers are: connect without the CA
|
||||
# check and accept it only on its digest (certs.check_self_signed).
|
||||
loose = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
|
||||
loose.check_hostname = False
|
||||
loose.verify_mode = ssl.CERT_NONE
|
||||
loose.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||
if certfile:
|
||||
loose.load_cert_chain(certfile, keyfile)
|
||||
self._reader, self._writer = await asyncio.open_connection(
|
||||
host, port, ssl=loose, server_hostname=host)
|
||||
der = self._writer.get_extra_info("ssl_object").getpeercert(True)
|
||||
try:
|
||||
self.trust = certs.check_self_signed(host, port, der or b"",
|
||||
mumble_digest)
|
||||
except certs.CertificateError:
|
||||
self._writer.close()
|
||||
raise
|
||||
|
||||
async def _handshake(self):
|
||||
frames = proto.FrameReader()
|
||||
while True:
|
||||
data = await self._reader.read(65536)
|
||||
if not data:
|
||||
raise MumbleError("the server closed the connection")
|
||||
for kind, payload in frames.feed(data):
|
||||
if kind == proto.REJECT:
|
||||
fields = proto.decode(payload)
|
||||
reason = proto.text(fields, 2) or proto.REJECT_REASONS.get(
|
||||
proto.first(fields, 1, 0), "the server refused")
|
||||
raise MumbleError(reason)
|
||||
self._handle(kind, payload, quiet=True)
|
||||
if kind == proto.SERVER_SYNC:
|
||||
self._frames = frames
|
||||
return
|
||||
|
||||
# ---- reading ----
|
||||
|
||||
async def _read_forever(self):
|
||||
reason = "the server closed the connection"
|
||||
try:
|
||||
while True:
|
||||
data = await self._reader.read(65536)
|
||||
if not data:
|
||||
break
|
||||
for kind, payload in self._frames.feed(data):
|
||||
self._handle(kind, payload)
|
||||
except asyncio.CancelledError:
|
||||
return
|
||||
except (OSError, ValueError) as e:
|
||||
reason = str(e) or type(e).__name__
|
||||
if not self._closed:
|
||||
self._closed = True
|
||||
self._on_event("lost", reason)
|
||||
|
||||
def _handle(self, kind: int, payload: bytes, quiet: bool = False):
|
||||
if kind in (proto.UDP_TUNNEL, proto.PING, proto.CRYPT_SETUP):
|
||||
return # voice from others, ping replies, UDP keys
|
||||
fields = proto.decode(payload)
|
||||
state = self.state
|
||||
if kind == proto.SERVER_SYNC:
|
||||
state.session = proto.first(fields, 1, 0)
|
||||
state.max_bandwidth = proto.first(fields, 2, state.max_bandwidth)
|
||||
state.welcome = proto.text(fields, 3)
|
||||
elif kind == proto.SERVER_CONFIG:
|
||||
state.max_bandwidth = proto.first(fields, 1, state.max_bandwidth)
|
||||
elif kind == proto.CHANNEL_STATE:
|
||||
cid = proto.first(fields, 1, 0)
|
||||
channel = state.channels.setdefault(cid, Channel(cid))
|
||||
if 2 in fields:
|
||||
channel.parent = proto.first(fields, 2)
|
||||
if 3 in fields:
|
||||
channel.name = proto.text(fields, 3)
|
||||
if 9 in fields:
|
||||
position = proto.first(fields, 9, 0)
|
||||
channel.position = position - (1 << 64) \
|
||||
if position >= 1 << 63 else position
|
||||
if not quiet:
|
||||
self._on_event("channels", None)
|
||||
elif kind == proto.CHANNEL_REMOVE:
|
||||
state.channels.pop(proto.first(fields, 1, -1), None)
|
||||
if not quiet:
|
||||
self._on_event("channels", None)
|
||||
elif kind == proto.USER_STATE:
|
||||
self._user_state(fields, quiet)
|
||||
elif kind == proto.USER_REMOVE:
|
||||
session = proto.first(fields, 1, 0)
|
||||
state.users.pop(session, None)
|
||||
if session == state.session and state.session and not quiet:
|
||||
self._closed = True
|
||||
why = proto.text(fields, 3)
|
||||
self._on_event("lost", "LinTunes was removed from the server"
|
||||
+ (f": {why}" if why else ""))
|
||||
elif kind == proto.PERMISSION_DENIED and not quiet:
|
||||
reason = proto.text(fields, 4)
|
||||
self._on_event("denied", reason or
|
||||
"the server didn't allow that")
|
||||
|
||||
def _user_state(self, fields: dict, quiet: bool):
|
||||
state = self.state
|
||||
session = proto.first(fields, 1, 0)
|
||||
existing = state.users.get(session)
|
||||
old_channel = existing.channel_id if existing is not None else None
|
||||
user = state.users.setdefault(session, User(session))
|
||||
if 3 in fields:
|
||||
user.name = proto.text(fields, 3)
|
||||
moved = 5 in fields
|
||||
if moved:
|
||||
user.channel_id = proto.first(fields, 5, 0)
|
||||
if 8 in fields:
|
||||
user.suppressed = bool(proto.first(fields, 8))
|
||||
if 6 in fields:
|
||||
user.mute = bool(proto.first(fields, 6))
|
||||
if 9 in fields:
|
||||
user.self_mute = bool(proto.first(fields, 9))
|
||||
if quiet:
|
||||
return
|
||||
if session == state.session:
|
||||
if moved:
|
||||
self._on_event("moved", user.channel_id)
|
||||
silenced = user.suppressed or user.muted
|
||||
if silenced != self._last_suppressed:
|
||||
self._last_suppressed = silenced
|
||||
self._on_event("suppressed", silenced)
|
||||
return
|
||||
if (moved and self.pinned_channel is None and self.follow_name
|
||||
and user.name.casefold() == self.follow_name.casefold()
|
||||
and user.channel_id != old_channel):
|
||||
me = state.me()
|
||||
if me is not None and me.channel_id != user.channel_id:
|
||||
self.move_to(user.channel_id)
|
||||
|
||||
# ---- writing ----
|
||||
|
||||
def send(self, data: bytes):
|
||||
if self._writer is not None and not self._closed:
|
||||
self._writer.write(data)
|
||||
|
||||
async def drain(self):
|
||||
if self._writer is not None and not self._closed:
|
||||
await self._writer.drain()
|
||||
|
||||
def move_to(self, channel_id: int):
|
||||
if self.state.session:
|
||||
self.send(proto.move_message(self.state.session, channel_id))
|
||||
|
||||
def set_comment(self, comment: str):
|
||||
if self.state.session:
|
||||
self.send(proto.comment_message(self.state.session, comment))
|
||||
|
||||
def set_follow(self, name: str, pinned_channel: int | None):
|
||||
"""Follow `name` (pinned_channel None), or stay in pinned_channel."""
|
||||
self.follow_name = name
|
||||
self.pinned_channel = pinned_channel
|
||||
if pinned_channel is not None:
|
||||
self.move_to(pinned_channel)
|
||||
return
|
||||
followed = self.state.find_user(name, self.state.session)
|
||||
if followed is not None:
|
||||
self.move_to(followed.channel_id)
|
||||
|
||||
async def _ping_forever(self):
|
||||
try:
|
||||
while not self._closed:
|
||||
await asyncio.sleep(PING_INTERVAL_S)
|
||||
self.send(proto.ping_message(int(time.time() * 1000)))
|
||||
await self.drain()
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
except OSError:
|
||||
pass # the reader reports the loss
|
||||
|
||||
async def close(self):
|
||||
self._closed = True
|
||||
current = asyncio.current_task()
|
||||
for task in self._tasks:
|
||||
if task is not current:
|
||||
task.cancel()
|
||||
writer, self._writer = self._writer, None
|
||||
if writer is not None:
|
||||
try:
|
||||
writer.close()
|
||||
await asyncio.wait_for(writer.wait_closed(), 2.0)
|
||||
except Exception: # noqa: BLE001 — closing is best effort
|
||||
pass
|
||||
@@ -0,0 +1,266 @@
|
||||
"""Owns the Mumble session on MainWindow's behalf (AirPlayController's shape).
|
||||
|
||||
Widget-free: state goes out as signals. The connection lives on its own
|
||||
asyncio loop thread; its events come back through `_event`, queued onto the
|
||||
GUI thread.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import shutil
|
||||
|
||||
from PyQt6.QtCore import QObject, QTimer, pyqtSignal
|
||||
|
||||
from lintunes.airplay.loop import AsyncLoop
|
||||
from lintunes.config import load_config
|
||||
from lintunes.eventlog import log_control
|
||||
from lintunes.inhibit import INHIBIT_LOGOUT, INHIBIT_SUSPEND, SleepInhibitor
|
||||
from lintunes.mumble import certs, opus, servers
|
||||
from lintunes.mumble.client import Connection
|
||||
|
||||
log = logging.getLogger("lintunes.mumble")
|
||||
|
||||
DEFAULT_NAME = "LinTunes"
|
||||
BITRATES_KBPS = (48, 64, 96, 128, 160, 192, 256)
|
||||
DEFAULT_KBPS = 128
|
||||
|
||||
|
||||
def settings_from(prefs) -> dict:
|
||||
"""The sink's settings: synced preferences, plus the machine's latency."""
|
||||
get = prefs.get if prefs is not None else (lambda k, d=None: d)
|
||||
return {
|
||||
"kbps": int(get("mumble_kbps", DEFAULT_KBPS) or DEFAULT_KBPS),
|
||||
"stereo": bool(get("mumble_stereo", True)),
|
||||
"latency_ms": load_config().get("mumble_latency_ms"),
|
||||
}
|
||||
|
||||
|
||||
def bot_name(prefs) -> str:
|
||||
name = prefs.get("mumble_name", DEFAULT_NAME) if prefs is not None else ""
|
||||
return (name or "").strip() or DEFAULT_NAME
|
||||
|
||||
|
||||
def is_available() -> tuple[bool, str]:
|
||||
if not opus.available():
|
||||
return False, "libopus isn't installed"
|
||||
if shutil.which("ffmpeg") is None:
|
||||
return False, "ffmpeg isn't installed (Mumble playback decodes with it)"
|
||||
if shutil.which("openssl") is None:
|
||||
return False, "openssl isn't installed (it makes LinTunes' certificate)"
|
||||
return True, ""
|
||||
|
||||
|
||||
class MumbleController(QObject):
|
||||
connecting = pyqtSignal(object) # servers.Server
|
||||
connected = pyqtSignal(str) # "<bot name> on <server>"
|
||||
disconnected = pyqtSignal(str) # reason; "" when the user asked
|
||||
failed = pyqtSignal(str)
|
||||
rooms_changed = pyqtSignal() # channel tree, or the bot's room
|
||||
notice = pyqtSignal(str) # something worth a status-bar line
|
||||
|
||||
_event = pyqtSignal(str, object)
|
||||
_connect_done = pyqtSignal(object, int)
|
||||
|
||||
def __init__(self, player, prefs=None, parent=None):
|
||||
super().__init__(parent)
|
||||
self._player = player
|
||||
self._prefs = prefs
|
||||
self._loop = AsyncLoop()
|
||||
self._connection: Connection | None = None
|
||||
self._server: servers.Server | None = None
|
||||
self._sink = None
|
||||
self._attempt = 0
|
||||
self._event.connect(self._on_event)
|
||||
self._connect_done.connect(self._on_connect_result)
|
||||
if prefs is not None:
|
||||
prefs.changed.connect(self._on_prefs_changed)
|
||||
# Every packet the room hears is decoded and encoded here.
|
||||
self._inhibitor = SleepInhibitor(
|
||||
reason="Playing into a Mumble room",
|
||||
flags=INHIBIT_LOGOUT | INHIBIT_SUSPEND)
|
||||
|
||||
# ---- state ----
|
||||
|
||||
def is_available(self) -> tuple[bool, str]:
|
||||
return is_available()
|
||||
|
||||
def is_connected(self) -> bool:
|
||||
return self._sink is not None
|
||||
|
||||
def device_name(self) -> str:
|
||||
if self._server is None or self._sink is None:
|
||||
return ""
|
||||
return f"{self._server.name or self._server.host} (Mumble)"
|
||||
|
||||
def server(self) -> servers.Server | None:
|
||||
return self._server
|
||||
|
||||
def choices(self) -> list[servers.Server]:
|
||||
"""The server Mumble is on, then Mumble's saved servers."""
|
||||
return servers.choices(servers.current_server(),
|
||||
servers.saved_servers())
|
||||
|
||||
def rooms(self) -> list[tuple[int, int, str]]:
|
||||
if self._connection is None:
|
||||
return []
|
||||
return self._connection.state.tree()
|
||||
|
||||
def current_room(self) -> int | None:
|
||||
me = self._connection.state.me() if self._connection else None
|
||||
return me.channel_id if me is not None else None
|
||||
|
||||
def following(self) -> str:
|
||||
"""Whose room the bot follows; "" when pinned or nobody to follow."""
|
||||
c = self._connection
|
||||
if c is None or c.pinned_channel is not None:
|
||||
return ""
|
||||
return c.follow_name
|
||||
|
||||
def follow_name(self) -> str:
|
||||
return self._connection.follow_name if self._connection else ""
|
||||
|
||||
def bitrate(self) -> int:
|
||||
return self._sink.bitrate() if self._sink is not None else 0
|
||||
|
||||
# ---- connecting ----
|
||||
|
||||
def connect_to(self, server: servers.Server):
|
||||
if self._connection is not None:
|
||||
self.disconnect()
|
||||
self._attempt += 1
|
||||
attempt = self._attempt
|
||||
self.connecting.emit(server)
|
||||
name = bot_name(self._prefs)
|
||||
log_control("mumble", "connect", f"{server.address} as {name}")
|
||||
connection = Connection(
|
||||
on_event=lambda kind, detail: self._event.emit(kind, detail))
|
||||
connection.follow_name = server.username
|
||||
future = self._loop.submit(self._connect(connection, server, name))
|
||||
|
||||
def done(f):
|
||||
try:
|
||||
f.result()
|
||||
result = {"connection": connection, "server": server}
|
||||
except Exception as e: # noqa: BLE001 — reported, never raised
|
||||
result = {"error": str(e) or type(e).__name__,
|
||||
"connection": connection}
|
||||
self._connect_done.emit(result, attempt)
|
||||
|
||||
future.add_done_callback(done)
|
||||
|
||||
async def _connect(self, connection, server, name):
|
||||
import asyncio
|
||||
loop = asyncio.get_running_loop()
|
||||
cert, key = await loop.run_in_executor(None, certs.ensure_identity)
|
||||
digest = servers.accepted_digest(server.host, server.port)
|
||||
await connection.connect(server.host, server.port, name,
|
||||
server.password, str(cert), str(key),
|
||||
mumble_digest=digest,
|
||||
target_path=server.channel_path)
|
||||
|
||||
def _on_connect_result(self, result: dict, attempt: int):
|
||||
connection = result["connection"]
|
||||
if attempt != self._attempt:
|
||||
self._loop.submit(connection.close())
|
||||
return
|
||||
if "error" in result:
|
||||
log_control("mumble", "failed", result["error"])
|
||||
self.failed.emit(f"Couldn't connect: {result['error']}")
|
||||
return
|
||||
from lintunes.mumble.sink import MumbleSink
|
||||
self._connection = connection
|
||||
self._server = result["server"]
|
||||
log_control("mumble", "connected",
|
||||
f"{self._server.address} (certificate: {connection.trust},"
|
||||
f" max bandwidth {connection.state.max_bandwidth} bit/s)")
|
||||
self._sink = MumbleSink(connection, self._loop,
|
||||
self.device_name(), settings_from(self._prefs),
|
||||
self)
|
||||
self._sink.unavailable.connect(
|
||||
lambda reason: QTimer.singleShot(
|
||||
0, lambda: self._on_unavailable(reason)))
|
||||
self._player.set_sink(self._sink)
|
||||
self._inhibitor.inhibit()
|
||||
self.connected.emit(self.device_name())
|
||||
self.rooms_changed.emit()
|
||||
wanted = settings_from(self._prefs)["kbps"] * 1000
|
||||
if self._sink.bitrate() < wanted:
|
||||
self.notice.emit(
|
||||
f"The server allows {self._sink.bitrate() // 1000} kbps "
|
||||
f"per user, so LinTunes plays at that instead of "
|
||||
f"{wanted // 1000}")
|
||||
|
||||
# ---- the room ----
|
||||
|
||||
def set_room(self, channel_id: int | None):
|
||||
"""A room to stay in, or None to follow whoever Mumble connected as."""
|
||||
connection = self._connection
|
||||
if connection is None:
|
||||
return
|
||||
name = connection.follow_name
|
||||
self._loop.submit(self._call(lambda: connection.set_follow(
|
||||
name, channel_id)))
|
||||
self.rooms_changed.emit()
|
||||
|
||||
@staticmethod
|
||||
async def _call(fn):
|
||||
fn()
|
||||
|
||||
def _on_event(self, kind: str, detail):
|
||||
if self._connection is None:
|
||||
return
|
||||
if kind == "lost":
|
||||
if self._sink is not None:
|
||||
self._sink.fail(f"Lost the Mumble server: {detail}")
|
||||
return
|
||||
if kind == "denied":
|
||||
self.notice.emit(f"Mumble: {detail}")
|
||||
elif kind == "suppressed" and detail:
|
||||
self.notice.emit("LinTunes can't talk in this Mumble room "
|
||||
"(it's muted or the room doesn't let it speak)")
|
||||
self.rooms_changed.emit()
|
||||
|
||||
def _on_prefs_changed(self):
|
||||
if self._sink is not None:
|
||||
self._sink.configure(settings_from(self._prefs))
|
||||
|
||||
# ---- disconnecting ----
|
||||
|
||||
def disconnect(self, reason: str = ""):
|
||||
sink, self._sink = self._sink, None
|
||||
connection, self._connection = self._connection, None
|
||||
if sink is None and connection is None:
|
||||
return
|
||||
log_control("mumble", "disconnect", f"reason={reason or 'user'}")
|
||||
if sink is not None:
|
||||
# Paused first, so the swap back doesn't carry on out of this
|
||||
# computer's speakers (MumbleSink.fail's rule).
|
||||
sink.pause()
|
||||
self._player.set_sink(None)
|
||||
self._teardown(sink, connection, reason)
|
||||
|
||||
def _on_unavailable(self, reason: str):
|
||||
sink, self._sink = self._sink, None
|
||||
connection, self._connection = self._connection, None
|
||||
if sink is None:
|
||||
return
|
||||
log_control("mumble", "lost", reason)
|
||||
self._teardown(sink, connection, reason)
|
||||
|
||||
def _teardown(self, sink, connection, reason: str):
|
||||
if sink is not None:
|
||||
sink.shutdown()
|
||||
if connection is not None:
|
||||
try:
|
||||
self._loop.run(connection.close(), 2.0)
|
||||
except Exception: # noqa: BLE001 — leaving regardless
|
||||
pass
|
||||
self._server = None
|
||||
self._inhibitor.release()
|
||||
self.disconnected.emit(reason)
|
||||
self.rooms_changed.emit()
|
||||
|
||||
def shutdown(self):
|
||||
if self._sink is not None:
|
||||
self._player.stop()
|
||||
self.disconnect()
|
||||
self._inhibitor.release()
|
||||
@@ -0,0 +1,105 @@
|
||||
"""libopus's encoder through ctypes — the system library Mumble itself and
|
||||
Qt's ffmpeg already need, so no pip dependency (opuslib is unmaintained)."""
|
||||
|
||||
import ctypes
|
||||
import ctypes.util
|
||||
|
||||
SAMPLE_RATE = 48000
|
||||
APPLICATION_AUDIO = 2049
|
||||
SET_BITRATE = 4002
|
||||
SET_VBR = 4006
|
||||
SET_COMPLEXITY = 4010
|
||||
SET_VBR_CONSTRAINT = 4020
|
||||
SET_SIGNAL = 4024
|
||||
SIGNAL_MUSIC = 3002
|
||||
MAX_PACKET = 4000
|
||||
|
||||
_lib = None
|
||||
|
||||
|
||||
def _library():
|
||||
global _lib
|
||||
if _lib is None:
|
||||
name = ctypes.util.find_library("opus")
|
||||
candidates = [name] if name else []
|
||||
candidates += ["libopus.so.0", "libopus.0.dylib", "libopus.dylib"]
|
||||
for candidate in candidates:
|
||||
try:
|
||||
lib = ctypes.CDLL(candidate)
|
||||
break
|
||||
except OSError:
|
||||
continue
|
||||
else:
|
||||
raise OSError("libopus isn't installed")
|
||||
lib.opus_encoder_create.restype = ctypes.c_void_p
|
||||
lib.opus_encoder_create.argtypes = [
|
||||
ctypes.c_int32, ctypes.c_int, ctypes.c_int,
|
||||
ctypes.POINTER(ctypes.c_int)]
|
||||
lib.opus_encode.restype = ctypes.c_int32
|
||||
lib.opus_encode.argtypes = [
|
||||
ctypes.c_void_p, ctypes.c_char_p, ctypes.c_int,
|
||||
ctypes.c_char_p, ctypes.c_int32]
|
||||
lib.opus_encoder_destroy.argtypes = [ctypes.c_void_p]
|
||||
lib.opus_encoder_ctl.restype = ctypes.c_int
|
||||
lib.opus_strerror.restype = ctypes.c_char_p
|
||||
lib.opus_strerror.argtypes = [ctypes.c_int]
|
||||
_lib = lib
|
||||
return _lib
|
||||
|
||||
|
||||
def available() -> bool:
|
||||
try:
|
||||
_library()
|
||||
return True
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
class OpusError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
class Encoder:
|
||||
"""48 kHz music encoder; int16 interleaved PCM in, one Opus packet out."""
|
||||
|
||||
def __init__(self, channels: int, bitrate: int):
|
||||
lib = _library()
|
||||
error = ctypes.c_int(0)
|
||||
self.channels = channels
|
||||
self._state = lib.opus_encoder_create(
|
||||
SAMPLE_RATE, channels, APPLICATION_AUDIO, ctypes.byref(error))
|
||||
if error.value != 0 or not self._state:
|
||||
raise OpusError(lib.opus_strerror(error.value).decode())
|
||||
self._out = ctypes.create_string_buffer(MAX_PACKET)
|
||||
# Constrained VBR: the server's bandwidth check is over each second,
|
||||
# and unconstrained VBR can swing past it on a loud passage.
|
||||
self._ctl(SET_VBR, 1)
|
||||
self._ctl(SET_VBR_CONSTRAINT, 1)
|
||||
self._ctl(SET_COMPLEXITY, 10)
|
||||
self._ctl(SET_SIGNAL, SIGNAL_MUSIC)
|
||||
self.set_bitrate(bitrate)
|
||||
|
||||
def _ctl(self, request: int, value: int):
|
||||
if self._state:
|
||||
_library().opus_encoder_ctl(ctypes.c_void_p(self._state),
|
||||
ctypes.c_int(request),
|
||||
ctypes.c_int32(int(value)))
|
||||
|
||||
def set_bitrate(self, bitrate: int):
|
||||
self.bitrate = int(bitrate)
|
||||
self._ctl(SET_BITRATE, self.bitrate)
|
||||
|
||||
def encode(self, pcm: bytes, samples_per_channel: int) -> bytes:
|
||||
count = _library().opus_encode(self._state, pcm, samples_per_channel,
|
||||
self._out, MAX_PACKET)
|
||||
if count < 0:
|
||||
raise OpusError(_library().opus_strerror(count).decode())
|
||||
return self._out.raw[:count]
|
||||
|
||||
def close(self):
|
||||
state, self._state = self._state, None
|
||||
if state:
|
||||
_library().opus_encoder_destroy(state)
|
||||
|
||||
def __del__(self):
|
||||
self.close()
|
||||
@@ -0,0 +1,256 @@
|
||||
"""Mumble's wire format, as far as a talking bot needs it. Pure, no I/O.
|
||||
|
||||
The control channel is TLS carrying frames of ``type (u16 BE) · length (u32
|
||||
BE) · protobuf``. Only a handful of message types matter, so the protobuf is
|
||||
encoded and decoded by hand from Mumble.proto's field numbers rather than
|
||||
generated code.
|
||||
|
||||
Voice goes in the same stream as `UDPTunnel` frames in the *legacy* packet
|
||||
format: LinTunes announces itself as a 1.4 client, which every 1.4 and 1.5
|
||||
server answers in that format (1.5's protobuf voice is only for clients that
|
||||
say they are 1.5). A legacy Opus packet is ``header · sequence · length ·
|
||||
opus``, where the header byte is ``type << 5 | target`` and the two numbers
|
||||
are Mumble's own variable-length integers — not protobuf varints.
|
||||
"""
|
||||
|
||||
import struct
|
||||
|
||||
# Message types (Mumble.proto's order).
|
||||
VERSION = 0
|
||||
UDP_TUNNEL = 1
|
||||
AUTHENTICATE = 2
|
||||
PING = 3
|
||||
REJECT = 4
|
||||
SERVER_SYNC = 5
|
||||
CHANNEL_REMOVE = 6
|
||||
CHANNEL_STATE = 7
|
||||
USER_REMOVE = 8
|
||||
USER_STATE = 9
|
||||
TEXT_MESSAGE = 11
|
||||
PERMISSION_DENIED = 12
|
||||
CRYPT_SETUP = 15
|
||||
CODEC_VERSION = 21
|
||||
SERVER_CONFIG = 24
|
||||
|
||||
HEADER = struct.Struct(">HI")
|
||||
MAX_MESSAGE = 8 * 1024 * 1024 # Mumble's own cap on a control message
|
||||
|
||||
# Announced as 1.4.0: see the module docstring for why not 1.5.
|
||||
CLIENT_VERSION = (1 << 16) | (4 << 8) | 0
|
||||
CLIENT_TYPE_BOT = 1
|
||||
|
||||
VOICE_OPUS = 4
|
||||
TERMINATOR = 0x2000
|
||||
MAX_OPUS_BYTES = TERMINATOR - 1 # the length field's 13 bits
|
||||
|
||||
REJECT_REASONS = {
|
||||
0: "the server refused the connection",
|
||||
1: "this version of Mumble isn't allowed on the server",
|
||||
2: "the name isn't allowed on the server",
|
||||
3: "the password is wrong",
|
||||
4: "the password is wrong",
|
||||
5: "that name is already in use on the server",
|
||||
6: "the server is full",
|
||||
7: "the server needs a certificate",
|
||||
8: "the server needs this name to be registered",
|
||||
}
|
||||
|
||||
|
||||
# ---- protobuf ----
|
||||
|
||||
def _varint(value: int) -> bytes:
|
||||
if value < 0:
|
||||
value &= (1 << 64) - 1
|
||||
out = bytearray()
|
||||
while True:
|
||||
byte = value & 0x7F
|
||||
value >>= 7
|
||||
if value:
|
||||
out.append(byte | 0x80)
|
||||
else:
|
||||
out.append(byte)
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def encode(fields: list[tuple[int, object]]) -> bytes:
|
||||
"""``[(field number, value)]`` → protobuf. Ints and bools are varints,
|
||||
str and bytes are length-delimited; None is left out."""
|
||||
out = bytearray()
|
||||
for number, value in fields:
|
||||
if value is None:
|
||||
continue
|
||||
if isinstance(value, (bytes, bytearray, str)):
|
||||
data = value.encode("utf-8") if isinstance(value, str) else value
|
||||
out += _varint(number << 3 | 2) + _varint(len(data)) + data
|
||||
else:
|
||||
out += _varint(number << 3 | 0) + _varint(int(value))
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def decode(data: bytes) -> dict[int, list]:
|
||||
"""protobuf → ``{field number: [values]}``: varints as ints,
|
||||
length-delimited fields as bytes, fixed-width fields as ints."""
|
||||
fields: dict[int, list] = {}
|
||||
i, n = 0, len(data)
|
||||
while i < n:
|
||||
key, i = _read_varint(data, i)
|
||||
number, wire = key >> 3, key & 7
|
||||
if wire == 0:
|
||||
value, i = _read_varint(data, i)
|
||||
elif wire == 2:
|
||||
length, i = _read_varint(data, i)
|
||||
if i + length > n:
|
||||
raise ValueError("truncated field")
|
||||
value, i = bytes(data[i:i + length]), i + length
|
||||
elif wire == 1:
|
||||
value, i = int.from_bytes(data[i:i + 8], "little"), i + 8
|
||||
elif wire == 5:
|
||||
value, i = int.from_bytes(data[i:i + 4], "little"), i + 4
|
||||
else:
|
||||
raise ValueError(f"unknown wire type {wire}")
|
||||
fields.setdefault(number, []).append(value)
|
||||
return fields
|
||||
|
||||
|
||||
def _read_varint(data: bytes, i: int) -> tuple[int, int]:
|
||||
value = shift = 0
|
||||
while True:
|
||||
if i >= len(data):
|
||||
raise ValueError("truncated varint")
|
||||
byte = data[i]
|
||||
i += 1
|
||||
value |= (byte & 0x7F) << shift
|
||||
if not byte & 0x80:
|
||||
return value, i
|
||||
shift += 7
|
||||
|
||||
|
||||
def first(fields: dict, number: int, default=None):
|
||||
values = fields.get(number)
|
||||
return values[-1] if values else default
|
||||
|
||||
|
||||
def text(fields: dict, number: int, default: str = "") -> str:
|
||||
value = first(fields, number)
|
||||
return value.decode("utf-8", "replace") if value is not None else default
|
||||
|
||||
|
||||
# ---- framing ----
|
||||
|
||||
def frame(kind: int, payload: bytes) -> bytes:
|
||||
return HEADER.pack(kind, len(payload)) + payload
|
||||
|
||||
|
||||
class FrameReader:
|
||||
"""Bytes in, ``(type, payload)`` out, however the stream splits them."""
|
||||
|
||||
def __init__(self):
|
||||
self._buffer = bytearray()
|
||||
|
||||
def feed(self, data: bytes) -> list[tuple[int, bytes]]:
|
||||
self._buffer += data
|
||||
frames = []
|
||||
while len(self._buffer) >= HEADER.size:
|
||||
kind, length = HEADER.unpack_from(self._buffer)
|
||||
if length > MAX_MESSAGE:
|
||||
raise ValueError(f"message of {length} bytes")
|
||||
end = HEADER.size + length
|
||||
if len(self._buffer) < end:
|
||||
break
|
||||
frames.append((kind, bytes(self._buffer[HEADER.size:end])))
|
||||
del self._buffer[:end]
|
||||
return frames
|
||||
|
||||
|
||||
# ---- the messages a bot sends ----
|
||||
|
||||
def version_message() -> bytes:
|
||||
import platform
|
||||
return frame(VERSION, encode([
|
||||
(1, CLIENT_VERSION),
|
||||
(2, "LinTunes"),
|
||||
(3, platform.system() or "Linux"),
|
||||
(4, platform.release() or ""),
|
||||
]))
|
||||
|
||||
|
||||
def authenticate_message(username: str, password: str = "") -> bytes:
|
||||
return frame(AUTHENTICATE, encode([
|
||||
(1, username),
|
||||
(2, password or None),
|
||||
(5, True), # opus
|
||||
(6, CLIENT_TYPE_BOT),
|
||||
]))
|
||||
|
||||
|
||||
def ping_message(timestamp: int) -> bytes:
|
||||
return frame(PING, encode([(1, timestamp)]))
|
||||
|
||||
|
||||
def move_message(session: int, channel_id: int) -> bytes:
|
||||
return frame(USER_STATE, encode([(1, session), (5, channel_id)]))
|
||||
|
||||
|
||||
def comment_message(session: int, comment: str) -> bytes:
|
||||
return frame(USER_STATE, encode([(1, session), (14, comment)]))
|
||||
|
||||
|
||||
# ---- voice ----
|
||||
|
||||
def mumble_varint(value: int) -> bytes:
|
||||
"""Mumble's own variable-length integer (PacketDataStream)."""
|
||||
if value < 0:
|
||||
raise ValueError("negative")
|
||||
if value < 0x80:
|
||||
return bytes([value])
|
||||
if value < 0x4000:
|
||||
return bytes([(value >> 8) | 0x80, value & 0xFF])
|
||||
if value < 0x200000:
|
||||
return bytes([(value >> 16) | 0xC0, (value >> 8) & 0xFF, value & 0xFF])
|
||||
if value < 0x10000000:
|
||||
return bytes([(value >> 24) | 0xE0, (value >> 16) & 0xFF,
|
||||
(value >> 8) & 0xFF, value & 0xFF])
|
||||
return b"\xF0" + struct.pack(">I", value & 0xFFFFFFFF)
|
||||
|
||||
|
||||
def read_mumble_varint(data: bytes, i: int = 0) -> tuple[int, int]:
|
||||
b = data[i]
|
||||
if b < 0x80:
|
||||
return b, i + 1
|
||||
if b < 0xC0:
|
||||
return (b & 0x3F) << 8 | data[i + 1], i + 2
|
||||
if b < 0xE0:
|
||||
return (b & 0x1F) << 16 | data[i + 1] << 8 | data[i + 2], i + 3
|
||||
if b < 0xF0:
|
||||
return ((b & 0x0F) << 24 | data[i + 1] << 16 | data[i + 2] << 8
|
||||
| data[i + 3]), i + 4
|
||||
if b == 0xF0:
|
||||
return struct.unpack_from(">I", data, i + 1)[0], i + 5
|
||||
raise ValueError("unsupported varint form")
|
||||
|
||||
|
||||
def voice_packet(sequence: int, opus: bytes, terminator: bool = False,
|
||||
target: int = 0) -> bytes:
|
||||
"""One legacy Opus voice packet, client → server (no session id)."""
|
||||
if len(opus) > MAX_OPUS_BYTES:
|
||||
raise ValueError(f"opus frame of {len(opus)} bytes")
|
||||
length = len(opus) | (TERMINATOR if terminator else 0)
|
||||
return (bytes([VOICE_OPUS << 5 | (target & 0x1F)])
|
||||
+ mumble_varint(sequence) + mumble_varint(length) + opus)
|
||||
|
||||
|
||||
def voice_frame(sequence: int, opus: bytes, terminator: bool = False) -> bytes:
|
||||
return frame(UDP_TUNNEL, voice_packet(sequence, opus, terminator))
|
||||
|
||||
|
||||
def payload_budget_bps(max_bandwidth: int, packets_per_s: float) -> int:
|
||||
"""The Opus bitrate that fits under the server's per-user bandwidth.
|
||||
|
||||
The server counts every voice packet it receives against
|
||||
`max_bandwidth` (bits/s) and drops what goes over, so the header bytes
|
||||
(~5) and a margin for constrained-VBR swings come out first. 0 = the
|
||||
server set no limit."""
|
||||
if not max_bandwidth or max_bandwidth <= 0:
|
||||
return 0
|
||||
overhead = packets_per_s * 8 * 8
|
||||
return max(8000, int(max_bandwidth * 0.9 - overhead))
|
||||
@@ -0,0 +1,174 @@
|
||||
"""Where to connect: the server trav's own Mumble is on, or one he saved.
|
||||
|
||||
Two read-only sources, both the Mumble app's:
|
||||
|
||||
* its D-Bus service (``net.sourceforge.mumble.mumble``), whose
|
||||
`getCurrentUrl` answers ``mumble://user@host:port/Room/Sub-room?version=…``
|
||||
while it is connected — the server *and* the room trav is in, never the
|
||||
password; and
|
||||
* its database (`mumble.sqlite`): the saved servers (the Connect dialog's
|
||||
favourites, passwords included) and the certificate digests trav has
|
||||
accepted for self-signed servers, which is how LinTunes checks a server
|
||||
is the one Mumble already trusts.
|
||||
|
||||
The database is opened read-only (``mode=ro``) and only those two tables are
|
||||
read. Nothing is ever written there.
|
||||
"""
|
||||
|
||||
import sqlite3
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from urllib.parse import unquote, urlsplit
|
||||
|
||||
DEFAULT_PORT = 64738
|
||||
|
||||
DBUS_SERVICE = "net.sourceforge.mumble.mumble"
|
||||
DBUS_PATH = "/"
|
||||
DBUS_INTERFACE = "net.sourceforge.mumble.Mumble"
|
||||
DBUS_TIMEOUT_MS = 2000
|
||||
|
||||
|
||||
@dataclass
|
||||
class Server:
|
||||
host: str
|
||||
port: int = DEFAULT_PORT
|
||||
name: str = "" # the label trav gave it in Mumble
|
||||
username: str = "" # *trav's* name there, for following him
|
||||
password: str = ""
|
||||
channel_path: list[str] = field(default_factory=list) # trav's room
|
||||
current: bool = False # the server Mumble is connected to now
|
||||
|
||||
@property
|
||||
def address(self) -> str:
|
||||
host = f"[{self.host}]" if ":" in self.host else self.host
|
||||
return host if self.port == DEFAULT_PORT else f"{host}:{self.port}"
|
||||
|
||||
def label(self) -> str:
|
||||
if self.name and self.name != self.host:
|
||||
return f"{self.name} ({self.address})"
|
||||
return self.address
|
||||
|
||||
def same_place(self, other: "Server") -> bool:
|
||||
return (self.host.lower() == other.host.lower()
|
||||
and self.port == other.port)
|
||||
|
||||
|
||||
def parse_url(url: str) -> Server | None:
|
||||
"""A ``mumble://`` URL → Server, or None if it isn't one."""
|
||||
if not url:
|
||||
return None
|
||||
try:
|
||||
parts = urlsplit(url.strip())
|
||||
port = parts.port
|
||||
except ValueError:
|
||||
return None
|
||||
if parts.scheme.lower() != "mumble" or not parts.hostname:
|
||||
return None
|
||||
path = [unquote(p) for p in parts.path.split("/") if p]
|
||||
return Server(host=parts.hostname, port=port or DEFAULT_PORT,
|
||||
username=unquote(parts.username or ""),
|
||||
password=unquote(parts.password or ""),
|
||||
channel_path=path)
|
||||
|
||||
|
||||
def current_url() -> str | None:
|
||||
"""The running Mumble's connection as a URL; None when Mumble isn't
|
||||
running or isn't connected (it answers that with a D-Bus error)."""
|
||||
try:
|
||||
from PyQt6.QtDBus import QDBusConnection, QDBusInterface, QDBusMessage
|
||||
except ImportError:
|
||||
return None
|
||||
bus = QDBusConnection.sessionBus()
|
||||
if not bus.isConnected():
|
||||
return None
|
||||
interface = QDBusInterface(DBUS_SERVICE, DBUS_PATH, DBUS_INTERFACE, bus)
|
||||
if not interface.isValid():
|
||||
return None
|
||||
interface.setTimeout(DBUS_TIMEOUT_MS)
|
||||
reply = interface.call("getCurrentUrl")
|
||||
if reply.type() != QDBusMessage.MessageType.ReplyMessage:
|
||||
return None
|
||||
arguments = reply.arguments()
|
||||
return str(arguments[0]) if arguments else None
|
||||
|
||||
|
||||
def current_server() -> Server | None:
|
||||
server = parse_url(current_url() or "")
|
||||
if server is not None:
|
||||
server.current = True
|
||||
return server
|
||||
|
||||
|
||||
def database_paths(home: Path | None = None) -> list[Path]:
|
||||
"""Where each kind of Mumble install keeps mumble.sqlite, likeliest
|
||||
first: Flathub's, then a distro package's (1.4+), then 1.3's."""
|
||||
home = home or Path.home()
|
||||
return [
|
||||
home / ".var/app/info.mumble.Mumble/data/Mumble/Mumble/mumble.sqlite",
|
||||
home / ".local/share/Mumble/Mumble/mumble.sqlite",
|
||||
home / ".local/share/data/Mumble/Mumble/mumble.sqlite",
|
||||
home / "Library/Application Support/Mumble/Mumble/mumble.sqlite",
|
||||
]
|
||||
|
||||
|
||||
def _open(path: Path):
|
||||
return sqlite3.connect(f"file:{path}?mode=ro", uri=True, timeout=1.0)
|
||||
|
||||
|
||||
def find_database(home: Path | None = None) -> Path | None:
|
||||
return next((p for p in database_paths(home) if p.is_file()), None)
|
||||
|
||||
|
||||
def saved_servers(database: Path | None = None) -> list[Server]:
|
||||
"""Mumble's favourites, in the order Mumble lists them (by name)."""
|
||||
database = database or find_database()
|
||||
if database is None:
|
||||
return []
|
||||
try:
|
||||
with _open(database) as db:
|
||||
rows = db.execute(
|
||||
"SELECT name, hostname, port, username, password FROM servers"
|
||||
" ORDER BY name COLLATE NOCASE").fetchall()
|
||||
except sqlite3.Error:
|
||||
return []
|
||||
servers = []
|
||||
for name, host, port, username, password in rows:
|
||||
if not host:
|
||||
continue
|
||||
servers.append(Server(host=str(host), port=int(port or DEFAULT_PORT),
|
||||
name=str(name or ""),
|
||||
username=str(username or ""),
|
||||
password=str(password or "")))
|
||||
return servers
|
||||
|
||||
|
||||
def accepted_digest(host: str, port: int,
|
||||
database: Path | None = None) -> str | None:
|
||||
"""The SHA-1 (hex) of the certificate trav accepted for host:port in
|
||||
Mumble, if the server's certificate needed accepting."""
|
||||
database = database or find_database()
|
||||
if database is None:
|
||||
return None
|
||||
try:
|
||||
with _open(database) as db:
|
||||
row = db.execute(
|
||||
"SELECT digest FROM cert WHERE lower(hostname) = lower(?)"
|
||||
" AND port = ?", (host, int(port))).fetchone()
|
||||
except sqlite3.Error:
|
||||
return None
|
||||
return str(row[0]).lower() if row and row[0] else None
|
||||
|
||||
|
||||
def choices(current: Server | None, saved: list[Server]) -> list[Server]:
|
||||
"""What Connect to Mumble… offers: the server Mumble is on first, filled
|
||||
in from its favourite (the password lives only there), then the rest of
|
||||
the favourites."""
|
||||
out = []
|
||||
if current is not None:
|
||||
match = next((s for s in saved if s.same_place(current)), None)
|
||||
if match is not None:
|
||||
current.name = current.name or match.name
|
||||
current.password = current.password or match.password
|
||||
out.append(current)
|
||||
out += [s for s in saved if current is None or not s.same_place(current)]
|
||||
return out
|
||||
@@ -0,0 +1,382 @@
|
||||
"""The Player sink that talks the music into a Mumble room.
|
||||
|
||||
One *stream* per stretch of continuous playback (AirPlaySink's shape): the
|
||||
`ffmpeg` CLI decodes from the position to 48 kHz int16 PCM, each 40 ms is
|
||||
scaled by the volume slider, Opus-encoded and sent as a voice packet at the
|
||||
pace it plays. Pausing ends the stream with a terminator packet (so every
|
||||
listener's Mumble stops cleanly instead of waiting out its jitter buffer),
|
||||
and play/seek start a new one at ``-ss``. Each start bumps a generation, so
|
||||
a stream a seek replaced can't report "finished" and advance the queue.
|
||||
|
||||
Position is what's been *sent* minus `latency_ms`: the trip through the
|
||||
server and each listener's jitter buffer, which nothing here can see.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import time
|
||||
|
||||
import numpy as np
|
||||
from PyQt6.QtCore import QTimer, pyqtSignal
|
||||
from PyQt6.QtMultimedia import QAudio
|
||||
|
||||
from lintunes.airplay.support import can_stream, ffmpeg_command
|
||||
from lintunes.mumble import opus, proto
|
||||
from lintunes.player import PlaybackSink
|
||||
|
||||
log = logging.getLogger("lintunes.mumble")
|
||||
|
||||
FRAME_MS = 40
|
||||
SAMPLES = opus.SAMPLE_RATE * FRAME_MS // 1000 # per channel
|
||||
PACKETS_PER_S = 1000 / FRAME_MS
|
||||
DEFAULT_LATENCY_MS = 150
|
||||
|
||||
FINISHED = "finished"
|
||||
DECODE_ERROR = "decode_error"
|
||||
DROPPED = "dropped"
|
||||
|
||||
|
||||
def bitrate_for(kbps: int, max_bandwidth: int) -> int:
|
||||
"""The bitrate asked for, held under what the server allows a user."""
|
||||
wanted = max(16, int(kbps)) * 1000
|
||||
budget = proto.payload_budget_bps(max_bandwidth, PACKETS_PER_S)
|
||||
return min(wanted, budget) if budget else wanted
|
||||
|
||||
|
||||
def apply_gain(pcm: bytes, gain: float) -> bytes:
|
||||
if gain >= 0.9999:
|
||||
return pcm
|
||||
samples = np.frombuffer(pcm, dtype="<i2").astype(np.float32)
|
||||
return (samples * gain).astype("<i2").tobytes()
|
||||
|
||||
|
||||
def mumble_reason(location: str, kind: str = "") -> str:
|
||||
if not location:
|
||||
return "it has no file"
|
||||
return "it's copy-protected, so it can't be decoded"
|
||||
|
||||
|
||||
class Stream:
|
||||
"""One song from one position. Loop-thread written, GUI-thread read;
|
||||
plain fields only, so a read is never torn."""
|
||||
|
||||
def __init__(self, path: str, start_ms: int):
|
||||
self.path = path
|
||||
self.start_ms = max(0, int(start_ms))
|
||||
self.frames_sent = 0
|
||||
self.exhausted = False
|
||||
self.decode_error = ""
|
||||
self.started_at: float | None = None
|
||||
|
||||
def sent_ms(self) -> int:
|
||||
return self.start_ms + self.frames_sent * FRAME_MS
|
||||
|
||||
|
||||
class MumbleSink(PlaybackSink):
|
||||
provides_pcm = False
|
||||
glyph = "mumble"
|
||||
listen_src = "mumble"
|
||||
|
||||
POLL_MS = 200
|
||||
|
||||
_stream_ended = pyqtSignal(int, str, str)
|
||||
|
||||
def __init__(self, connection, loop, name: str, settings: dict,
|
||||
parent=None):
|
||||
super().__init__(parent)
|
||||
self._connection = connection
|
||||
self._loop = loop
|
||||
self.name = name or "Mumble"
|
||||
self._channels = 2 if settings.get("stereo", True) else 1
|
||||
self._kbps = int(settings.get("kbps", 128))
|
||||
self.latency_ms = int(settings.get("latency_ms") or DEFAULT_LATENCY_MS)
|
||||
self._gain = 1.0
|
||||
self._sequence = 0
|
||||
self._track = None
|
||||
self._stream: Stream | None = None
|
||||
self._generation = 0
|
||||
self._playing = False
|
||||
self._position_ms = 0
|
||||
self._duration_ms = 0
|
||||
self._shutdown_done = False
|
||||
self._dying = False
|
||||
self._task: asyncio.Task | None = None
|
||||
self._lock: asyncio.Lock | None = None
|
||||
self._encoder = None
|
||||
self._stream_ended.connect(self._on_stream_ended)
|
||||
self._poll = QTimer(self)
|
||||
self._poll.setInterval(self.POLL_MS)
|
||||
self._poll.timeout.connect(self._on_poll)
|
||||
|
||||
# ---- settings ----
|
||||
|
||||
def bitrate(self) -> int:
|
||||
return bitrate_for(self._kbps, self._connection.state.max_bandwidth)
|
||||
|
||||
def configure(self, settings: dict):
|
||||
"""Preferences changed: bitrate now, channels from the next stream."""
|
||||
self._kbps = int(settings.get("kbps", self._kbps))
|
||||
self._channels = 2 if settings.get("stereo", True) else 1
|
||||
self.latency_ms = int(settings.get("latency_ms") or self.latency_ms)
|
||||
|
||||
# ---- PlaybackSink ----
|
||||
|
||||
def can_play(self, track) -> bool:
|
||||
return can_stream(track.location, track.kind)
|
||||
|
||||
def unplayable_reason(self, track) -> str:
|
||||
return mumble_reason(track.location, track.kind)
|
||||
|
||||
def load(self, track, autoplay: bool, start_ms: int):
|
||||
self._track = track
|
||||
self._duration_ms = track.total_time or 0
|
||||
self.duration_changed.emit(self._duration_ms)
|
||||
self._set_position(max(0, start_ms))
|
||||
if autoplay:
|
||||
self._start_stream(self._position_ms)
|
||||
else:
|
||||
self._halt_stream()
|
||||
self._set_playing(False)
|
||||
|
||||
def play(self):
|
||||
if self._track is None or self._playing:
|
||||
return
|
||||
self._start_stream(self._position_ms)
|
||||
|
||||
def pause(self):
|
||||
self._freeze_position()
|
||||
self._halt_stream()
|
||||
self._set_playing(False)
|
||||
|
||||
def stop(self):
|
||||
self.pause()
|
||||
|
||||
def seek(self, position_ms: int):
|
||||
target = max(0, position_ms)
|
||||
if self._playing:
|
||||
self._start_stream(target)
|
||||
else:
|
||||
self._set_position(target)
|
||||
|
||||
def position_ms(self) -> int:
|
||||
return self._position_ms
|
||||
|
||||
def duration_ms(self) -> int:
|
||||
return self._duration_ms
|
||||
|
||||
def is_playing(self) -> bool:
|
||||
return self._playing
|
||||
|
||||
def set_volume(self, level: float):
|
||||
level = max(0.0, min(1.0, float(level)))
|
||||
# LocalSink's curve: one slider position, one loudness, any output.
|
||||
self._gain = QAudio.convertVolume(
|
||||
level, QAudio.VolumeScale.LogarithmicVolumeScale,
|
||||
QAudio.VolumeScale.LinearVolumeScale)
|
||||
|
||||
def shutdown(self):
|
||||
if self._shutdown_done:
|
||||
return
|
||||
self._shutdown_done = True
|
||||
self._poll.stop()
|
||||
self._generation += 1
|
||||
try:
|
||||
self._loop.run(self._halt(), 2.0)
|
||||
except Exception: # noqa: BLE001 — quitting regardless
|
||||
pass
|
||||
|
||||
# ---- GUI side ----
|
||||
|
||||
def _start_stream(self, start_ms: int):
|
||||
if self._shutdown_done or self._dying or self._track is None:
|
||||
return
|
||||
self._generation += 1
|
||||
stream = Stream(self._track.location, start_ms)
|
||||
self._stream = stream
|
||||
log.info("stream %d: %s from %d ms", self._generation,
|
||||
self._track.name or self._track.location, start_ms)
|
||||
self._set_position(start_ms)
|
||||
self._set_playing(True)
|
||||
self._poll.start()
|
||||
self._loop.submit(self._restart(self._generation, stream))
|
||||
|
||||
def _halt_stream(self):
|
||||
self._generation += 1
|
||||
self._stream = None
|
||||
self._poll.stop()
|
||||
if not self._shutdown_done:
|
||||
self._loop.submit(self._halt())
|
||||
|
||||
def _heard(self, stream: Stream) -> int:
|
||||
if stream.frames_sent == 0:
|
||||
return stream.start_ms
|
||||
return max(stream.start_ms, stream.sent_ms() - self.latency_ms)
|
||||
|
||||
def _freeze_position(self):
|
||||
if self._stream is not None:
|
||||
self._set_position(self._heard(self._stream))
|
||||
|
||||
def _on_poll(self):
|
||||
if self._stream is not None:
|
||||
self._set_position(self._heard(self._stream))
|
||||
|
||||
def _on_stream_ended(self, generation: int, outcome: str, detail: str):
|
||||
log.info("stream %d ended: %s %s", generation, outcome, detail)
|
||||
if generation != self._generation or self._shutdown_done:
|
||||
return
|
||||
self._stream = None
|
||||
self._poll.stop()
|
||||
if outcome == FINISHED:
|
||||
self._set_position(self._duration_ms or self._position_ms)
|
||||
self._set_playing(False)
|
||||
self.ended.emit()
|
||||
elif outcome == DECODE_ERROR:
|
||||
self._set_playing(False)
|
||||
self.error.emit(f"it couldn't be decoded ({detail})")
|
||||
else:
|
||||
self.fail(f"Lost the Mumble server ({detail}).")
|
||||
|
||||
def fail(self, reason: str):
|
||||
"""The connection is gone: Player falls back to the local output —
|
||||
*paused*, unlike a lost speaker. This is a work call, and music
|
||||
jumping out of this computer mid-meeting is worse than silence."""
|
||||
if self._dying:
|
||||
return
|
||||
self._dying = True
|
||||
self._freeze_position()
|
||||
self._halt_stream()
|
||||
self._set_playing(False)
|
||||
self.unavailable.emit(reason)
|
||||
|
||||
def _set_playing(self, playing: bool):
|
||||
if playing != self._playing:
|
||||
self._playing = playing
|
||||
self.state_changed.emit(playing)
|
||||
|
||||
def _set_position(self, position_ms: int):
|
||||
self._position_ms = position_ms
|
||||
self.position_changed.emit(position_ms)
|
||||
|
||||
# ---- loop thread ----
|
||||
|
||||
def _loop_lock(self) -> asyncio.Lock:
|
||||
if self._lock is None:
|
||||
self._lock = asyncio.Lock()
|
||||
return self._lock
|
||||
|
||||
async def _restart(self, generation: int, stream: Stream):
|
||||
async with self._loop_lock():
|
||||
await self._cancel_task(terminate=False)
|
||||
if generation != self._generation:
|
||||
return
|
||||
self._task = asyncio.ensure_future(self._run(generation, stream))
|
||||
|
||||
async def _halt(self):
|
||||
async with self._loop_lock():
|
||||
await self._cancel_task(terminate=True)
|
||||
|
||||
async def _cancel_task(self, terminate: bool):
|
||||
task, self._task = self._task, None
|
||||
if task is not None and not task.done():
|
||||
task.cancel()
|
||||
try:
|
||||
await task
|
||||
except BaseException: # noqa: BLE001 — it's being replaced
|
||||
pass
|
||||
if terminate:
|
||||
self._send_terminator()
|
||||
|
||||
def _encoder_for(self, channels: int):
|
||||
bitrate = self.bitrate()
|
||||
encoder = self._encoder
|
||||
if encoder is None or encoder.channels != channels:
|
||||
if encoder is not None:
|
||||
encoder.close()
|
||||
encoder = self._encoder = opus.Encoder(channels, bitrate)
|
||||
elif encoder.bitrate != bitrate:
|
||||
encoder.set_bitrate(bitrate)
|
||||
return encoder
|
||||
|
||||
def _send_terminator(self):
|
||||
"""A frame of silence flagged as the end of talking."""
|
||||
encoder = self._encoder
|
||||
if encoder is None:
|
||||
return
|
||||
silence = bytes(SAMPLES * encoder.channels * 2)
|
||||
try:
|
||||
packet = encoder.encode(silence, SAMPLES)
|
||||
self._sequence += FRAME_MS // 10
|
||||
self._connection.send(proto.voice_frame(self._sequence, packet,
|
||||
terminator=True))
|
||||
except Exception: # noqa: BLE001 — courtesy only
|
||||
pass
|
||||
|
||||
async def _run(self, generation: int, stream: Stream):
|
||||
channels = self._channels
|
||||
frame_bytes = SAMPLES * channels * 2
|
||||
process = await asyncio.create_subprocess_exec(
|
||||
*ffmpeg_command(stream.path, stream.start_ms, opus.SAMPLE_RATE,
|
||||
channels, 2, big_endian=False),
|
||||
stdin=asyncio.subprocess.DEVNULL, stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE)
|
||||
outcome, detail = FINISHED, ""
|
||||
try:
|
||||
encoder = self._encoder_for(channels)
|
||||
clock = time.monotonic()
|
||||
n = 0
|
||||
pending: bytes | None = None
|
||||
while True:
|
||||
try:
|
||||
pcm = await process.stdout.readexactly(frame_bytes)
|
||||
except asyncio.IncompleteReadError as e:
|
||||
pcm = e.partial
|
||||
if pcm:
|
||||
pcm += bytes(frame_bytes - len(pcm))
|
||||
if not pcm:
|
||||
break
|
||||
# One frame behind, so the song's last frame goes out with
|
||||
# the terminator flag.
|
||||
if pending is not None:
|
||||
await self._send(encoder, pending, n, clock, False)
|
||||
n += 1
|
||||
stream.frames_sent = n
|
||||
if n % 25 == 0: # a preference may have moved it
|
||||
encoder = self._encoder_for(channels)
|
||||
pending = pcm
|
||||
code = await process.wait()
|
||||
if n == 0 and pending is None and code != 0:
|
||||
lines = (await process.stderr.read()).decode(
|
||||
"utf-8", "replace").strip().splitlines()
|
||||
outcome = DECODE_ERROR
|
||||
detail = lines[-1] if lines else f"ffmpeg exited with {code}"
|
||||
elif pending is not None:
|
||||
await self._send(encoder, pending, n, clock, True)
|
||||
stream.frames_sent = n + 1
|
||||
stream.exhausted = outcome == FINISHED
|
||||
# The listeners hear the end a latency later.
|
||||
await asyncio.sleep(self.latency_ms / 1000.0)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except (OSError, opus.OpusError) as e:
|
||||
outcome, detail = DROPPED, str(e) or type(e).__name__
|
||||
finally:
|
||||
if process.returncode is None:
|
||||
try:
|
||||
process.kill()
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
self._stream_ended.emit(generation, outcome, detail)
|
||||
|
||||
async def _send(self, encoder, pcm: bytes, n: int, clock: float,
|
||||
last: bool):
|
||||
# Real time, never ahead: the server counts bandwidth per second and
|
||||
# each listener's jitter buffer is sized for a talker, not a burst.
|
||||
delay = clock + n * FRAME_MS / 1000.0 - time.monotonic()
|
||||
if delay > 0:
|
||||
await asyncio.sleep(delay)
|
||||
packet = encoder.encode(apply_gain(pcm, self._gain), SAMPLES)
|
||||
self._sequence += FRAME_MS // 10
|
||||
self._connection.send(proto.voice_frame(self._sequence, packet,
|
||||
terminator=last))
|
||||
if n % 10 == 0:
|
||||
await self._connection.drain()
|
||||
@@ -97,6 +97,13 @@ DEFAULTS = {
|
||||
# say so in the status bar with Add Anyway (gui/duplicate_notice.py);
|
||||
# True = the old prompt that asks every time.
|
||||
"ask_on_duplicates": False,
|
||||
# Connections › Connect to Mumble… (Round 134): the name the bot shows
|
||||
# under in the room, and how it encodes. Synced: both desktops' bots
|
||||
# should look and sound the same. The latency and the certificates are
|
||||
# this machine's (config.json, $XDG_DATA_HOME/lintunes/mumble).
|
||||
"mumble_name": "LinTunes",
|
||||
"mumble_kbps": 128,
|
||||
"mumble_stereo": True,
|
||||
# The quiet "tink" when a sync, export or URL import finishes.
|
||||
"sound_effects": True,
|
||||
# The yearly Wrapped (storage/listen_history.py). Synced on purpose: one
|
||||
|
||||
Reference in New Issue
Block a user