"""AG CuteMusic's mixer as a sound device: "AG Podcast Mixer" (docs/jamming-ag-cutemusic.md,
python3-sipsimple docs/PodcastMixerLink.md).

AG CuteMusic's package installs PipeWire nodes that are always there: ag_podcast_mixer (its mix, our microphone) and
ag_podcast_mixer_call (what we play, its BLINK strip). SIP calls reach them through the ALSA PCM described "AG Podcast
Mixer" (the SDK has only ALSA on Linux), WebRTC rooms through pipewiresrc / pipewiresink by node name (videoroom.py).

- The device is listed (Devices menu: the combined section only) while the nodes are there, AG CuteMusic running or
  not (silence while its mixer is off), as the driver's on macOS: chosen once and left so. Watched every 2 s
  (Watcher): when the nodes come or go the engine's sound devices are read again (MainWindow.refresh_devices).
- Chosen as the input, the call carries music: echo cancelling off and 48 kHz (SIP), stereo at a music bitrate
  (WebRTC rooms, videoroom.py). The settings are changed while it is chosen and put back when another input is
  (apply_music_mode), so Preferences show what is in effect.
- Who is in the call, for the mixer's BLINK strip, and its HANG UP and REDIAL: AG CuteMusic's control channel on the
  session bus (CallPublisher), as Blink for macOS has on the driver.
"""

import json
import os
import time

from PyQt6.QtCore import QObject, QTimer, pyqtSignal, pyqtSlot

from application.notification import IObserver, NotificationCenter
from zope.interface import implementer

from blink.logging import ActivityLog
from blink.resources import ApplicationData
from blink.util import run_in_gui_thread


__all__ = ['DEVICE', 'DEVICE_HINT', 'installed', 'app_running', 'unavailable_reason', 'unavailable_hint', 'running', 'visible', 'separate', 'podcast_device', 'keep_alert_device', 'pipewire_nodes', 'selected', 'apply_music_mode', 'open_mixer', 'Watcher', 'CallPublisher']


DEVICE = 'AG Podcast Mixer'             # its name in the device lists (the ALSA PCM's description)
MUSIC_SAMPLE_RATE = 48000


# AG CuteMusic's other devices: never Blink's (PipeWire node descriptions, should a backend list them)
NOT_FOR_BLINK = ('AG Podcast Mixer Feed', 'AG Podcast Mixer Call', 'AG Podcast Streaming', 'AG Podcast Streaming Feed')
MIXER_NODE = 'ag_podcast_mixer'
CALL_NODE = 'ag_podcast_mixer_call'

SERVICE = 'org.agprojects.PodcastMixer'         # AG CuteMusic's control channel on the session bus (its bus.py)
PATH = '/org/agprojects/PodcastMixer'
INTERFACE = 'org.agprojects.PodcastMixer'


DEVICE_HINT = 'AG CuteMusic\'s mixer: your microphone, music and jingles go out in the call, the others come back on their own fader'


def installed():
    """Whether AG CuteMusic is installed (its program on the path)."""
    import shutil
    return bool(shutil.which('ag-cute-music'))


def app_running():
    """Whether AG CuteMusic runs (it owns its name on the session bus)."""
    try:
        from PyQt6.QtDBus import QDBusConnection
    except ImportError:
        return False
    bus = QDBusConnection.sessionBus()
    return bus.isConnected() and bool(bus.interface().isServiceRegistered(SERVICE).value())


def unavailable_reason():
    """Why the mixer cannot be chosen now, a few words for its menu item."""
    import platform
    if platform.system() == 'Windows':
        return 'not on Windows'
    if not installed():
        return 'sudo apt install ag-cute-music'       # shown in the menu: a grayed item's tool tip may not be
    return 'log out and in again'       # installed, PipeWire has not read its nodes yet


def unavailable_hint():
    """The menu item's tool tip: what to do."""
    import platform
    if platform.system() == 'Windows':
        return 'AG CuteMusic\'s mixer is not a sound device on Windows yet'
    if not installed():
        return 'Install AG CuteMusic to use its mixer in calls:  sudo apt install ag-cute-music'
    return ('AG CuteMusic is installed but PipeWire has not loaded its devices yet: log out and in again, or run '
            'systemctl --user restart pipewire')


_nodes_checked = (0.0, False)


def pipewire_nodes():
    """Whether AG CuteMusic's PipeWire nodes are there (its package's pipewire/ag-podcast-mixer.conf): the source
    ag_podcast_mixer and the sink ag_podcast_mixer_call. Asked of pipewire-pulse (pactl), at most once a second."""
    global _nodes_checked
    import shutil
    import subprocess
    import sys
    when, found = _nodes_checked
    if time.monotonic() - when < 1.0:
        return found
    found = False
    if sys.platform.startswith('linux') and shutil.which('pactl'):
        try:
            sources = subprocess.run(['pactl', 'list', 'short', 'sources'], capture_output=True, text=True, timeout=2).stdout
            sinks = subprocess.run(['pactl', 'list', 'short', 'sinks'], capture_output=True, text=True, timeout=2).stdout
            names = lambda text: {line.split('\t')[1] for line in text.splitlines() if line.count('\t') >= 1}
            found = MIXER_NODE in names(sources) and CALL_NODE in names(sinks)
        except (OSError, subprocess.SubprocessError, IndexError):
            found = False
    _nodes_checked = (time.monotonic(), found)
    return found


def running():
    """Whether the mixer can be used as a device: AG CuteMusic's PipeWire nodes are there."""
    return pipewire_nodes()


def visible(devices):
    """The devices to list: the mixer only while its nodes are there."""
    return [device for device in devices if device != DEVICE or running()]


def podcast_device(name):
    """Whether name is one of AG CuteMusic's devices (the mixer, its Feed and Call, the streaming ones)."""
    return bool(name) and (name == DEVICE or name in NOT_FOR_BLINK)


def separate(devices, keep=None):
    """An input, output or alert device list: AG CuteMusic's devices left out. The mixer is chosen once, in the
    Devices menu's combined input and output section; keep: the device the setting has now, kept so that it shows."""
    return [device for device in visible(devices) if not podcast_device(device) or (device == DEVICE and device == keep)]


_alert_device = None        # the alert device as last chosen, never one of AG CuteMusic's


def keep_alert_device():
    """Alerts never on AG CuteMusic's devices: one set there (by hand, or by a device switch that took it along) goes
    back to the alert device as it was before (System Default when none was known)."""
    global _alert_device
    from sipsimple.configuration.settings import SIPSimpleSettings
    settings = SIPSimpleSettings()
    current = settings.audio.alert_device
    if not podcast_device(current):
        _alert_device = current
        return
    back = _alert_device or 'system_default'
    ActivityLog().info(f'[audio] Alert device {current} is AG CuteMusic\'s: back to {back}')
    settings.audio.alert_device = back
    settings.save()


def selected(settings=None):
    """Whether the mixer is the input (the call is music)."""
    if settings is None:
        from sipsimple.configuration.settings import SIPSimpleSettings
        settings = SIPSimpleSettings()
    return settings.audio.input_device == DEVICE


def _state_path():
    return ApplicationData.get('cutemusic.json')


def apply_music_mode():
    """The mixer chosen as the input: echo cancelling off and 48 kHz, the settings before kept; another input: they
    are put back. Called when the input device changes."""
    from sipsimple.configuration.settings import SIPSimpleSettings
    settings = SIPSimpleSettings()
    path = _state_path()
    try:
        with open(path) as file:
            before = json.load(file)
    except (OSError, ValueError):
        before = None
    if selected(settings) and before is None:
        before = {'echo_canceller': settings.audio.echo_canceller.enabled, 'sample_rate': int(settings.audio.sample_rate),
                  'stereo': bool(getattr(settings.audio, 'stereo', False))}
        with open(path, 'w') as file:
            json.dump(before, file)
        settings.audio.echo_canceller.enabled = False
        settings.audio.sample_rate = MUSIC_SAMPLE_RATE
        if hasattr(settings.audio, 'stereo'):       # an SDK with stereo audio (audio.stereo)
            settings.audio.stereo = True
        settings.save()
        ActivityLog().info(f'[audio] {DEVICE}: music mode, echo cancelling off, {MUSIC_SAMPLE_RATE} Hz'
                           f'{", stereo" if getattr(settings.audio, "stereo", False) else ""} '
                           f'(were {"on" if before["echo_canceller"] else "off"}, {before["sample_rate"]} Hz)')
    elif not selected(settings) and before is not None:
        settings.audio.echo_canceller.enabled = bool(before.get('echo_canceller', True))
        settings.audio.sample_rate = int(before.get('sample_rate') or settings.audio.sample_rate)
        if hasattr(settings.audio, 'stereo'):
            settings.audio.stereo = bool(before.get('stereo', False))
        settings.save()
        try:
            os.unlink(path)
        except OSError:
            pass
        ActivityLog().info(f'[audio] {DEVICE} no longer the input: echo cancelling '
                           f'{"on" if settings.audio.echo_canceller.enabled else "off"}, {settings.audio.sample_rate} Hz again')


def open_mixer():
    """AG CuteMusic in front on its Mixer view (the notice's icon, MainWindow.MixerNotice): asked on the session bus
    (ShowMixer) when it runs; started with --mixer when it is installed but not running."""
    import shutil
    import subprocess
    if app_running():
        from PyQt6.QtDBus import QDBusConnection, QDBusMessage
        QDBusConnection.sessionBus().send(QDBusMessage.createMethodCall(SERVICE, PATH, INTERFACE, 'ShowMixer'))
        return
    if not shutil.which('ag-cute-music'):
        ActivityLog().info('[audio] AG CuteMusic is not installed')
        return
    try:
        subprocess.Popen([shutil.which('ag-cute-music'), '--mixer'], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
                         stderr=subprocess.DEVNULL, start_new_session=True)
        ActivityLog().info('[audio] Starting AG CuteMusic on its mixer')
    except OSError as e:
        ActivityLog().warning(f'[audio] Cannot start AG CuteMusic: {e}')


class Watcher(QObject):
    """changed(running): AG CuteMusic's PipeWire nodes came or went (installed, PipeWire restarted)."""

    changed = pyqtSignal(bool)

    def __init__(self, parent=None):
        super().__init__(parent)
        self.running = running()
        self._timer = QTimer(self, interval=2000)
        self._timer.timeout.connect(self._check)
        self._timer.start()

    def _check(self):
        now = running()
        if now != self.running:
            self.running = now
            ActivityLog().info(f'[audio] AG CuteMusic\'s PipeWire nodes {"there: " + DEVICE + " listed" if now else "gone: " + DEVICE + " no longer listed"}')
            self.changed.emit(now)


# Who is in the call, and AG CuteMusic's HANG UP and REDIAL

# a call's progress as AG CuteMusic shows it ('state' left out once connected)
_PROGRESS = {'connecting/dns_lookup': 'dialing', 'connection/dns_lookup_succeeded': 'dialing', 'initializing': 'dialing',
             'connecting': 'calling', 'connecting/starting': 'calling',
             'connecting/ringing': 'ringing', 'connecting/early_media': 'ringing', 'ending': 'hanging up'}


def _address(uri):
    """user@domain, never with sip: or parameters."""
    text = str(uri or '').strip()
    if '<' in text and text.endswith('>'):
        text = text.split('<', 1)[1][:-1]
    for prefix in ('sip:', 'sips:'):
        if text.startswith(prefix):
            text = text[len(prefix):]
    return text.split(';', 1)[0]


def _real_name(name, address):
    """name when it is a real display name: not the address, a URI or its user part."""
    name = str(name or '').strip()
    if not name or name == address or name.startswith(('sip:', 'sips:')) or name.lower() == address.split('@', 1)[0].lower():
        return ''
    return name


@implementer(IObserver)
class CallPublisher(QObject):
    """Blink seen by AG CuteMusic, as Blink for macOS is (python3-sipsimple docs/PodcastMixerLink.md):

    - its calls on AG CuteMusic's control channel, D-Bus (SetCalls(pid, json)), every 2 s and at once on a change of
      call state (AG CuteMusic forgets an entry not set for 10 s); "" on quit:
        {"pid": <ours>, "calls": [{"kind": "call", "id", "name", "address", "held", "state"?, "started"?, "rtt"?,
                                   "loss_rx"?, "loss_tx"?, "participants"?}],
         "redial": {"address", "name"} | null, "ended": {"seq", "at", "by", "address"} | null}
      state while not connected (dialing, calling, ringing, incoming, hanging up), started (epoch s) once connected,
      the quality once measured (rtt ms, the round trip; loss % the last 2 s, received and sent). A WebRTC room is a
      call too, id videoroom:<session>, with participants [{"id", "name", "level" (dBFS, null: none now), "levels"? (left and
      right in dBFS, null: silent; stereo only), "channels" (1, 2, null: not known), "muted"}]: a meter and a MUTE each in the BLINK strip; set while a room is
      joined (every 0.1 s, as GStreamer's level reads them), so the levels move. ended: how our last audio call ended, for AG CuteMusic's auto-redial: 'local' (hung up,
      cancelled or declined here), 'remote' (the other side hung up), 'failed' (not reached); a podcast's room as a call.
    - AG CuteMusic's requests, the Request signal ({"seq", "pid", "op": "hangup" with "id", "redial", "call" with
      "address" (its auto-redial), or "mute" with "id", "participant", "muted"}): the one naming us acted on once (a seq
      not seen): hangup ends that call's session or leaves that room, redial calls as Redial does (a podcast: rejoined as
      it was started), call calls the address with audio (a podcast's: rejoined), mute mutes a room's participant.

    Read every tick from Blink's own lists (the sessions with audio, the rooms joined), not kept from notifications:
    nothing is left behind when one is missed. The calls not on hold first."""

    def __init__(self, parent=None):
        super().__init__(parent)
        self._logged = None         # the calls as last logged
        self._seq = None            # the last request acted on
        self._stats = {}            # {session id: the audio stream's statistics a tick ago}: the loss over a tick
        self._ended = None          # how our last audio call ended ({"seq", "at", "by", "address"})
        self._rooms_joined = set()  # the podcasts' rooms (session ids) once established: their end is 'remote'
        self._room_started = {}     # room session id: when it was established (epoch s)
        self._room_counts = {}      # room session id: the packet counters a tick ago (the loss over a tick)
        self._room_quality = {}     # room session id: {rtt, loss_rx, loss_tx} as last measured
        self._bus = None
        self._bus_listening = False
        try:
            from PyQt6.QtDBus import QDBusConnection
            bus = QDBusConnection.sessionBus()
            if bus.isConnected():
                self._bus = bus
                self._bus_listening = bus.connect('', PATH, INTERFACE, 'Request', self._bus_request)
        except ImportError:
            pass
        if self._bus is None or not self._bus_listening:
            ActivityLog().info('[audio] No session bus: AG CuteMusic will not see our calls')
        notification_center = NotificationCenter()
        for name in self._CALL_CHANGES + self._CALL_ENDS:
            notification_center.add_observer(self, name=name)
        self._timer = QTimer(self, interval=2000)
        self._timer.timeout.connect(self._tick)          # (a keep-alive and the quality: the rest is event-based)
        self._timer.start()
        self._fast_timer = QTimer(self, interval=100)
        self._fast_timer.timeout.connect(self._fast_tick)     # while a room is joined: its participants' levels, as often as GStreamer reads them
        self._fast_timer.start()
        self._publish()

    _CALL_CHANGES = ('BlinkSessionDidChangeState', 'BlinkSessionDidChangeHoldState', 'BlinkSessionWillEnd',
                     'BlinkSessionDidEnd', 'BlinkSessionNewIncoming', 'BlinkSessionNewOutgoing', 'BlinkSessionDidChangeStreams',
                     'VideoroomSessionDidChangeState', 'VideoroomSessionParticipantsDidChange')

    _CALL_ENDS = ('SIPSessionDidEnd', 'SIPSessionDidFail')

    @run_in_gui_thread
    def handle_notification(self, notification):
        if self._timer is None:
            return
        if notification.name in self._CALL_ENDS:
            self._call_ended(notification)
        elif notification.name == 'VideoroomSessionDidChangeState':
            self._room_changed(notification)
        self._publish()         # at once, not at the next tick: AG CuteMusic follows the call's progress

    def _tick(self):
        self._measure_rooms()
        self._publish()

    def _measure_rooms(self):
        """The rooms' quality, every tick (2 s), as a SIP call's: the round trip and what we lost sending (the server's
        report of our audio: remote-inbound-rtp) and receiving (the feeds' audio: inbound-rtp) since the last tick.
        The statistics asked now land for the next tick (webrtcbin's get-stats answers later)."""
        try:
            from blink.webrtc.videoroom import VideoroomManager
            sessions = [session for session in list(VideoroomManager().sessions) if session.state == 'established']
        except Exception:
            return
        alive = set()
        for session in sessions:
            alive.add(session.id)
            stats = getattr(session, 'stats', {}) or {}
            remote = stats.get(('remote-inbound-rtp', 'audio'), {})
            sent = stats.get(('outbound-rtp', 'audio'), {})
            counts = {'tx_sent': sent.get('packets-sent'), 'tx_lost': remote.get('packets-lost'), 'rx_received': 0, 'rx_lost': 0}
            for participant in list(session.feeds.values()):
                inbound = (getattr(participant, 'stats', {}) or {}).get(('inbound-rtp', 'audio'), {})
                counts['rx_received'] += inbound.get('packets-received') or 0
                counts['rx_lost'] += max(0, inbound.get('packets-lost') or 0)
            before, self._room_counts[session.id] = self._room_counts.get(session.id), counts
            rtt = remote.get('round-trip-time')
            quality = {'rtt': int(round(rtt * 1000))} if rtt else {}
            if before is not None:
                def loss(lost, total):
                    try:
                        lost = counts[lost] - before[lost]
                        total = counts[total] - before[total] + (lost if total == 'rx_received' else 0)
                    except TypeError:       # (not there yet)
                        return None
                    return round(100.0 * lost / total, 1) if total > 0 and lost > 0 else 0.0
                for key, (lost, total) in (('loss_tx', ('tx_lost', 'tx_sent')), ('loss_rx', ('rx_lost', 'rx_received'))):
                    value = loss(lost, total)
                    if value is not None:
                        quality[key] = value
            if quality.get('rtt'):
                self._room_quality[session.id] = quality
            try:
                session.request_stats()
            except Exception:
                pass
        for key in set(self._room_counts) - alive:
            self._room_counts.pop(key, None)
            self._room_quality.pop(key, None)

    def _fast_tick(self):
        try:
            from blink.webrtc.videoroom import VideoroomManager
            rooms = any(session.state == 'established' for session in list(VideoroomManager().sessions))
        except Exception:
            rooms = False
        if rooms:
            self._publish()

    # How a call ended, for AG CuteMusic's auto-redial

    def _set_ended(self, by, address):
        self._ended = {'seq': (self._ended or {}).get('seq', 0) + 1, 'at': round(time.time(), 1), 'by': by, 'address': address}

    def _call_ended(self, notification):
        """An audio call ended: 'local' (hung up, cancelled or declined here), 'remote' (the other side hung up) or
        'failed' (not reached: busy, declined there, no answer, network)."""
        session, data = notification.sender, notification.data
        streams = list(getattr(session, 'streams', None) or getattr(session, 'proposed_streams', None) or [])
        if not any(getattr(stream, 'type', None) == 'audio' for stream in streams):
            return
        originator = getattr(data, 'originator', None)
        if notification.name == 'SIPSessionDidEnd':
            by = 'remote' if originator == 'remote' else 'local'
        elif originator == 'local' and (getattr(data, 'code', None) == 487 or getattr(session, 'direction', None) == 'incoming'):
            by = 'local'
        else:
            by = 'failed'
        try:
            address = _address(session.remote_identity.uri)
        except AttributeError:
            address = ''
        self._set_ended(by, address)
        ActivityLog().info(f'[audio] Call with {address or "?"} ended ({by}): told AG CuteMusic')

    def _room_changed(self, notification):
        """A room established (since when, for its duration) or ended. A podcast's end (Join Podcast: stereo over WebRTC)
        is told as a call's: 'local' (left here), 'remote' (ended once joined: the server, the network) or 'failed'
        (never joined), its address the podcast's, which AG CuteMusic's call request rejoins. Other rooms: not told."""
        session, state = notification.sender, notification.data.state
        if state == 'established':
            self._room_started.setdefault(session.id, time.time())
            if getattr(session, 'stereo', False):
                self._rooms_joined.add(session.id)
            return
        if state != 'terminated':
            return
        self._room_started.pop(session.id, None)
        joined = session.id in self._rooms_joined
        self._rooms_joined.discard(session.id)
        if not getattr(session, 'stereo', False):
            return
        reason = notification.data.reason or ''
        by = 'local' if reason == 'left' else ('remote' if joined else 'failed')
        from blink.podcast import last_podcast_any
        podcast = last_podcast_any()
        self._set_ended(by, _address(podcast.conference_uri if podcast is not None else session.room))
        ActivityLog().info(f'[audio] Podcast in {session.room} ended ({by}, {reason}): told AG CuteMusic')

    # What we tell

    def _calls(self):
        from blink.sessions import SessionManager
        calls = []
        alive = set()
        for session in list(SessionManager().sessions):
            try:
                state = str(session.state or '')
                if not state.startswith(('connecting', 'connection', 'connected', 'initializing', 'ending')) or \
                        'audio' not in session.streams.types:
                    continue
                uri = session.contact_uri.uri if session.contact_uri is not None else session.uri
                address = _address(uri)
                contact = session.contact
                call = {'kind': 'call', 'id': f'{id(session):x}', 'name': _real_name(contact.name if contact is not None else '', address),
                        'address': address, 'held': bool(session.local_hold)}
                if state.startswith('connected'):
                    started = time.time() - session.info.duration.total_seconds()
                    call['started'] = round(started, 1)
                    alive.add(id(session))
                    quality = self._quality(session)
                    if quality is not None:
                        call.update(quality)
                else:
                    call['state'] = 'incoming' if session.direction == 'incoming' and state.startswith('connecting') else \
                        _PROGRESS.get(state, 'calling')
                calls.append(call)
            except Exception:
                continue
        for key in set(self._stats) - alive:
            del self._stats[key]
        calls.sort(key=lambda call: call['held'])         # (stable: in Blink's order otherwise)
        return calls

    def _quality(self, session):
        """{rtt, loss_rx, loss_tx} from the audio stream's statistics (the loss since the last tick), None until
        measured."""
        stream = session.streams.get('audio', None)
        statistics = getattr(stream, 'statistics', None) if stream is not None else None
        if not statistics:
            return None
        before, self._stats[id(session)] = self._stats.get(id(session)), statistics
        try:
            rtt = int(round(statistics['rtt']['last'] / 1000))         # the round trip, ms
            if before is None:
                return {'rtt': rtt} if rtt else None

            def loss(direction):
                packets = statistics[direction]['packets'] - before[direction]['packets']
                lost = statistics[direction]['packets_lost'] - before[direction]['packets_lost']
                return round(100.0 * lost / (packets + lost), 1) if packets + lost > 0 and lost > 0 else 0.0
            return {'rtt': rtt, 'loss_rx': loss('rx'), 'loss_tx': loss('tx')}
        except (KeyError, TypeError):
            return None

    _ROOM_PROGRESS = {'idle': 'dialing', 'connecting': 'calling', 'accepted': 'calling'}
    LEVEL_STALE = 1.5       # s: a participant's level older than this is not sent (none: silent, or not read)

    def _room_calls(self):
        """The WebRTC rooms joined, as calls: id videoroom:<session>, with who is in them."""
        try:
            from blink.webrtc.videoroom import VideoroomManager
            sessions = list(VideoroomManager().sessions)
        except Exception:
            return []
        calls = []
        for session in sessions:
            if session.state == 'terminated':
                continue
            address = _address(session.sip_room)
            try:
                from blink.contacts import URIUtils
                contact, contact_uri = URIUtils.find_contact(session.sip_room)
                name = getattr(contact, 'name', '')
            except Exception:
                name = ''
            call = {'kind': 'call', 'id': f'videoroom:{session.id}', 'name': _real_name(name, address), 'address': address,
                    'held': bool(getattr(session, 'on_hold', False)), 'participants': self._participants(session)}
            progress = self._ROOM_PROGRESS.get(session.state)
            if progress is not None:
                call['state'] = progress
            elif session.id in self._room_started:
                call['started'] = round(self._room_started[session.id], 1)
                call.update(self._room_quality.get(session.id, {}))     # RTT and loss, once measured
            calls.append(call)
        return calls

    def _participants(self, session):
        """Who is in a room (a VU meter and a MUTE each in the BLINK strip): {"id", "name", "level" (dBFS, None: none
        now), "channels" (1, 2; None: not known), "muted"}, from the levels of the room's tiles."""
        from blink.webrtc.videoroom import VU_FLOOR_DB
        from time import monotonic
        now = monotonic()
        found = []
        for participant in list(session.participants.values()):
            if getattr(participant, 'parent', None) or not participant.visible:     # an extra video, the bridge, our own SIP leg
                continue
            levels = list(getattr(participant, 'peaks', None) or participant.levels or [])     # the peak now: the meter falls in AG CuteMusic
            meter = max(levels) if levels else 0.0
            fresh = now - getattr(participant, 'levels_at', 0.0) < self.LEVEL_STALE
            level = round(VU_FLOOR_DB * (1.0 - meter), 1) if meter > 0 and fresh else None
            entry = {'id': str(participant.id), 'name': participant.name, 'level': level,
                     'channels': len(levels) if levels else None, 'muted': bool(participant.muted)}
            if level is not None and len(levels) == 2:      # left and right each (level: the louder one, for older AG CuteMusics)
                entry['levels'] = [round(VU_FLOOR_DB * (1.0 - value), 1) if value > 0 else None for value in levels]
            found.append(entry)
        return found

    @staticmethod
    def _redial():
        """What REDIAL calls: Redial's target, or the last podcast when no call was made after it; None when there is none."""
        from blink.podcast import last_podcast
        podcast = last_podcast()
        if podcast is not None:
            return {'address': _address(podcast.conference_uri), 'name': ''}
        from blink.sessions import SessionManager
        uri = SessionManager().last_dialed_uri
        if uri is None:
            return None
        address = _address(uri)
        try:
            from blink.contacts import URIUtils
            contact, contact_uri = URIUtils.find_contact(uri)
            name = getattr(contact, 'name', '')
        except Exception:
            name = ''
        return {'address': address, 'name': _real_name(name, address)}

    def _state(self):
        calls = self._calls() + self._room_calls()
        calls.sort(key=lambda call: call['held'])         # (stable: in Blink's order otherwise)
        return {'pid': os.getpid(), 'calls': calls, 'redial': self._redial(), 'ended': self._ended}

    def _publish(self):
        state = self._state()
        # the bus: every time, unchanged or not (AG CuteMusic forgets an entry not set for 10 s)
        self._set_calls(json.dumps(state))
        summary = ', '.join((call.get('name') or call.get('address') or '') + (' (on hold)' if call.get('held') else '') +
                            (f' ({call["state"]})' if call.get('state') else '') +
                            (f' with {len(call["participants"])} participants' if call.get('participants') else '') for call in state['calls']) or 'none'
        if summary != self._logged:     # (not the levels, which change every 0.1 s)
            self._logged = summary
            ActivityLog().info(f'[audio] Calls shown in AG CuteMusic\'s mixer: {summary}')

    def _set_calls(self, text):
        if self._bus is None:
            return
        from PyQt6.QtDBus import QDBusMessage
        message = QDBusMessage.createMethodCall(SERVICE, PATH, INTERFACE, 'SetCalls')
        message.setArguments([os.getpid(), text])
        self._bus.send(message)         # (no reply waited for: AG CuteMusic may not be there)

    # What AG CuteMusic asks

    @pyqtSlot(str)
    def _bus_request(self, text):
        self._handle_request(text)

    def _handle_request(self, text):
        try:
            request = json.loads(text)
            seq, pid, op = int(request.get('seq')), int(request.get('pid')), request.get('op')
        except (TypeError, ValueError, AttributeError):
            return
        if pid != os.getpid() or (self._seq is not None and seq <= self._seq):
            return
        self._seq = seq
        if op == 'hangup' and str(request.get('id', '')).startswith('videoroom:'):
            session = self._room_session(request.get('id'))
            if session is None:
                ActivityLog().info('[audio] AG CuteMusic asked to leave a video conference that is gone')
                return
            ActivityLog().info(f'[audio] AG CuteMusic: leave the video conference {session.room}')
            from blink.webrtc.videoroomwindow import VideoroomWindow
            window = VideoroomWindow.windows.get(session)
            if window is not None:
                window.close()      # as its Leave button: the room's chat ends with it
            else:
                session.leave()
        elif op == 'mute' and str(request.get('id', '')).startswith('videoroom:'):     # a room's participant, from its MUTE
            session = self._room_session(request.get('id'))
            participant = next((p for p in (session.participants.values() if session is not None else [])
                                if str(p.id) == str(request.get('participant'))), None)
            if participant is None:
                ActivityLog().info('[audio] AG CuteMusic asked to mute someone no longer in the room')
                return
            muted = bool(request.get('muted', True))
            ActivityLog().info(f'[audio] AG CuteMusic: {"mute" if muted else "unmute"} {participant.uri}')
            session.mute_participant(participant, muted)
        elif op == 'call' and request.get('address'):      # its auto-redial: the one the dropped call was with
            address = str(request.get('address'))
            from blink.podcast import podcast_for, rejoin
            podcast = podcast_for(address)
            if podcast is not None:     # a podcast: rejoined as it was started (stereo over WebRTC, its choices)
                ActivityLog().info(f'[audio] AG CuteMusic: rejoin the podcast {address}')
                rejoin(podcast)
            else:
                ActivityLog().info(f'[audio] AG CuteMusic: call {address} again')
                from blink.contacts import URIUtils
                from blink.sessions import SessionManager, StreamDescription
                contact, contact_uri = URIUtils.find_contact(address)
                SessionManager().create_session(contact, contact_uri, [StreamDescription('audio')])
        elif op == 'hangup':
            from blink.sessions import SessionManager
            session = next((session for session in list(SessionManager().sessions) if f'{id(session):x}' == str(request.get('id'))), None)
            if session is None:
                ActivityLog().info('[audio] AG CuteMusic asked to hang up a call that is gone')
                return
            ActivityLog().info(f'[audio] AG CuteMusic: hang up the call with {_address(session.uri)}')
            session.end()
        elif op == 'redial':
            from blink.podcast import last_podcast, rejoin
            podcast = last_podcast()
            if podcast is not None:     # the last call was a podcast: rejoined as it was started
                ActivityLog().info(f'[audio] AG CuteMusic: redial the podcast {podcast.conference_uri}')
                rejoin(podcast)
                self._publish()
                return
            ActivityLog().info('[audio] AG CuteMusic: redial')
            parent = self.parent()
            if parent is not None and hasattr(parent, '_AH_RedialActionTriggered'):
                parent._AH_RedialActionTriggered()      # the same media as the last call (stereo as that contact's)
        self._publish()

    @staticmethod
    def _room_session(call_id):
        from blink.webrtc.videoroom import VideoroomManager
        wanted = str(call_id).split(':', 1)[1]
        return next((session for session in list(VideoroomManager().sessions) if session.id == wanted and session.state != 'terminated'), None)

    def stop(self):
        if self._timer is not None:
            self._timer.stop()
            self._timer = None
        if getattr(self, '_fast_timer', None) is not None:
            self._fast_timer.stop()
            self._fast_timer = None
        for name in self._CALL_CHANGES + self._CALL_ENDS:
            NotificationCenter().discard_observer(self, name=name)
        self._set_calls('')         # our entry gone from AG CuteMusic's list
        if self._bus is not None and self._bus_listening:
            self._bus.disconnect('', PATH, INTERFACE, 'Request', self._bus_request)
