/
/
/
1"""Constants for the AirPlay provider."""
2
3from __future__ import annotations
4
5from dataclasses import replace
6from enum import IntEnum, StrEnum
7from typing import Final
8
9from music_assistant_models.enums import ContentType, PlayerFeature
10from music_assistant_models.media_items import AudioFormat
11
12from music_assistant.constants import CONF_ENTRY_SYNC_ADJUST
13
14DOMAIN = "airplay"
15
16
17class StreamingProtocol(IntEnum):
18 """AirPlay streaming protocol versions."""
19
20 RAOP = 1 # AirPlay 1 (RAOP)
21 AIRPLAY2 = 2 # AirPlay 2
22
23
24class AirPlayRemoteCommand(StrEnum):
25 """Transport commands received from an AirPlay receiver."""
26
27 PLAY = "play"
28 PAUSE = "pause"
29 PLAY_PAUSE = "play_pause"
30 NEXT = "next"
31 PREVIOUS = "previous"
32
33
34class ClockReadiness(StrEnum):
35 """
36 How a receiver's clock readiness resolved for an anchor decision.
37
38 Only PROJECTED carries an instant; the rest all mean "anchor on the lead
39 alone", but for very different reasons - one is a device that will not play
40 at all, and treating them alike hides it.
41 """
42
43 # The binary projected when the receiver's clock becomes usable.
44 PROJECTED = "projected"
45 # NTP timing: there is no receiver clock to wait for.
46 NOT_APPLICABLE = "not_applicable"
47 # The receiver never answered our PTP clock and will render silence.
48 STALLED = "stalled"
49 # Nothing arrived within the wait: a slow device (retryable) or a receiver
50 # whose readiness went unreported.
51 UNREPORTED = "unreported"
52
53
54CONF_PASSWORD: Final[str] = "password"
55# Storage-only marker (no config entry) set when the device rejected the stored
56# password, so the player keeps asking for setup across restarts until a working
57# password is entered.
58CONF_PASSWORD_INVALID: Final[str] = "password_invalid"
59CONF_IGNORE_VOLUME: Final[str] = "ignore_volume"
60CONF_ENCRYPTION: Final[str] = "encryption"
61# Advanced per-device escape hatch: force the legacy RAOP protocol on an
62# AirPlay-2-capable receiver whose AirPlay 2 implementation misbehaves.
63CONF_FORCE_RAOP: Final[str] = "force_raop"
64CONF_STORED_VOLUME: Final[str] = "stored_volume"
65CONF_COMPANION_CREDENTIALS: Final[str] = "companion_credentials"
66CONF_MRP_CREDENTIALS: Final[str] = "mrp_credentials"
67CONF_NATIVE_MRP_CREDENTIALS: Final[str] = "native_mrp_credentials"
68
69# Bundle id of the Music Assistant tvOS dashboard app, launched over Companion on
70# eligible Apple TVs (see tvos/docs/launch-contract.md).
71TVOS_APP_BUNDLE_ID: Final[str] = "io.music-assistant.tvos"
72
73AIRPLAY_DISCOVERY_TYPE: Final[str] = "_airplay._tcp.local."
74COMPANION_DISCOVERY_TYPE: Final[str] = "_companion-link._tcp.local."
75MRP_DISCOVERY_TYPE: Final[str] = "_mediaremotetv._tcp.local."
76RAOP_DISCOVERY_TYPE: Final[str] = "_raop._tcp.local."
77DACP_DISCOVERY_TYPE: Final[str] = "_dacp._tcp.local."
78
79# Lower bound for a late joiner's anchor, and the whole anchor whenever the
80# binary reports no readiness projection ([STATUS] clock_ready). It has to keep
81# the binary's own clock verification viable without any device evidence: that
82# verification gives up 850 ms before the anchor, and a cold receiver was
83# measured taking 1078 ms after connect to send its first clock probe, so an
84# anchor below 1078 + 850 = ~1.93 s can close the window before a single probe
85# arrives - the joiner then seats on a cold clock and lands audibly behind.
86# 2500 ms clears that by ~570 ms, the margin the field-proven value carried.
87AIRPLAY_LATE_JOIN_MIN_HEADROOM_MS: Final[int] = 2500
88# How long a group start, a join or the Sendspin bridge waits for the binary's
89# first receiver-clock projection ([STATUS] clock_ready with state=probing|
90# ready). The binary emits its first line right after [STATUS] connected and
91# refreshes it about every 250 ms, and the projection exists from the receiver's
92# first probe (~1078 ms after connect on a cold device), so this only has to
93# cover a slower device before giving up and anchoring on the lead alone.
94# Independent of the binary's own stall report (state=stalled), which is a
95# slower, higher-confidence diagnosis of a receiver that never answers at all: a
96# wait that times out here has simply run out of planning time and falls back,
97# while a stall says the speaker will not play. Keep them apart - tightening the
98# stall report to meet this deadline would trade the margin that keeps it free
99# of false alarms.
100AIRPLAY_CLOCK_READY_TIMEOUT_MS: Final[int] = 2500
101# Lead added on top of a reported readiness instant, wherever one is waited for.
102# The binary refuses to place an anchor inside its own 250 ms floor, measured
103# from when IT reads the START command rather than when the server sends it (the
104# same trap as AIRPLAY_START_LEAD_MS), so the lead carries that floor plus 250 ms
105# for the command reaching the binary and for the convergence error of a
106# projection made from the receiver's very first probe.
107AIRPLAY_CLOCK_READY_LEAD_MS: Final[int] = 500
108# Default receiver buffer depth per device family: (manufacturer wildcard,
109# model wildcard, firmware wildcard) -> depth in ms, matched case-insensitively
110# in order, first match wins; unmatched devices stay on Automatic (the binary's
111# stock depth). LinkPlay pipelines starve at the stock depth - silent renderer
112# behind a perfectly healthy session - so their queue is deepened, at the cost
113# of slower warm seeks (the depth IS the audible latency of a seek or skip).
114# Extend the table as field reports identify more starving devices.
115AIRPLAY_BUFFER_DEPTH_DEFAULTS: Final[tuple[tuple[str, str, str, int], ...]] = (
116 # The newer LinkPlay platform names Linkplay as the manufacturer (WiiM, ...).
117 # 1750 ms is what a WiiM needs once it is also master of a native multiroom
118 # group.
119 ("linkplay*", "*", "*", 1750),
120 # The older LinkPlay platform ships under OEM brands (Edifier, ...) but
121 # marks the platform in its firmware string. It starves far deeper: an
122 # Edifier MS50A stays silent at 2250 ms and renders from 2500 ms, which is
123 # the 2250 ms pipeline the same device declares as its RAOP latency plus the
124 # binary's delivery margin. Every shallower value - including the 1750 ms
125 # this row used to inherit from the row above - is below what the device
126 # itself asks for.
127 ("*", "*", "p20.linkplay.*", 2500),
128)
129# Per-player override of the splice receiver-queue depth in ms (0 = automatic).
130CONF_BUFFER_DEPTH: Final[str] = "buffer_depth"
131# How long a plain (non-join) START waits for the binary's [STATUS] started ack.
132# Nothing holds that ack back, so the window only has to cover the command's trip
133# down the pipe and the answer coming back - unlike a join's ack below, which is
134# withheld until the receiver clock verification resolves.
135AIRPLAY_START_ACK_TIMEOUT_MS: Final[int] = 2000
136# How long a join START waits for the binary's [STATUS] started ack. That ack is
137# held back until the clock verification above resolves, so the window must
138# cover the verification arm window plus a poll round on top of the commanded
139# anchor (which bounds the verification), where a plain START acks within the
140# command round-trip. On timeout the server falls back to trusting the commanded
141# instant, so a window shorter than the binary's verification silently maps the
142# joiner's content onto an instant the binary never used.
143AIRPLAY_JOIN_START_ACK_TIMEOUT_MS: Final[int] = 5000
144# How far the content a corrected anchor actually cut may fall short of the cut
145# it asked for before the reported media position is re-based and the shortfall
146# reported. The binary derives the cut it took from the bytes it discarded, so a
147# few ms of byte quantization is expected and correcting for it would only
148# jitter the base; anything larger means the cut really did end early (the input
149# ran out inside it, or a teardown settled it) and the position is over-advanced
150# by that much for the rest of the anchor.
151AIRPLAY_CONTENT_CUT_TOLERANCE_MS: Final[int] = 20
152# Anchor leads for a readiness-confirmed START (cold and warm alike), solo and
153# group: the session only anchors after the binary confirmed the connection
154# ([STATUS] connected) and the new audio flowing ([STATUS] audio), so a lead no
155# longer guesses at setup or transcoder spin-up time. Both cover the receiver
156# re-anchor (accepted down to ~150 ms in the flush-ladder measurements) plus
157# the command's trip down the pipe; the group one also covers fanning the
158# shared instant out to every member. The pipe margin is what keeps them
159# workable: the binary rejects any instant inside its own 250 ms floor,
160# measured from when IT reads the command, and corrects a miss to that floor
161# plus another full lead â so a lead sitting exactly on the floor misses by the
162# delivery time every time and turns a start into a group-wide re-anchor ladder.
163AIRPLAY_START_LEAD_MS: Final[int] = 400
164AIRPLAY_GROUP_START_LEAD_MS: Final[int] = 500
165# Cold GROUP starts anchor further out: a receiver on a brand-new session
166# still acquires its PTP slave lock (~1.7-2.3 s measured on Sonos) and cannot
167# render at an anchor inside that window - it starts late and the group opens
168# audibly out of sync. Warm re-anchors reuse a locked clock and keep the
169# short leads above; solo cold starts have no sync partner to miss.
170AIRPLAY_COLD_GROUP_START_LEAD_MS: Final[int] = 2500
171# Margin added on top of a member's reported warm lead (the splice-timeline
172# queue depth on Apple receivers) when anchoring a warm re-start: covers the
173# command round-trips between the flush acks and the shared START so every
174# member's skip target lands beyond its queued audio.
175AIRPLAY_SPLICE_LEAD_MARGIN_MS: Final[int] = 150
176
177# Floor for the late-join PCM ring, which has to hold every sample between the
178# audible position and the write head: a joiner's anchor maps onto content the
179# group was already fed but has not played yet. That distance - the write-head
180# lead - is the sum of every buffer between the session's byte counter and the
181# speaker, and it is far larger than the binary's own ring alone:
182# ~5.7 s the per-member ffmpeg and the pipes around it (measured 5.2 s
183# steady / 5.7 s peak at 44.1 kHz/16-bit, which is the worst case in
184# SECONDS - the same buffers hold ~4.3 s at the 32-bit hi-res carrier
185# rate, and low-delay ffmpeg flags do not shrink them)
186# ~4.0 s the cliairplay ring: the binary's own lead (2000 ms default,
187# clamped to the device-reported window) plus its 2 s of slack
188# ~2.0 s the receiver's own buffer
189# ~11.7 s in total, against 8.9-11.0 s measured across native AirPlay 2
190# sessions (Apple TV and Sonos, joining in both directions). This floor is that
191# sum rounded up, and it is only a floor: the lead is measured per session and
192# the ring grows to match, because a receiver that reports a wider lead window
193# or buffers more deeply moves the sum with nothing to announce it.
194AIRPLAY_LATE_JOIN_RING_MIN_SECONDS: Final[float] = 12.0
195# Grown on top of the largest lead a session has actually shown, so a lead that
196# drifts up between two joins cannot clip the oldest sample a joiner needs.
197AIRPLAY_LATE_JOIN_RING_MARGIN_SECONDS: Final[float] = 2.0
198# Hard bound on the ring, which is per session (one ring feeds every member) and
199# costs byte_rate x seconds. Bounded in BYTES rather than seconds on purpose:
200# the seconds the ring must hold are largest at the LOWEST byte rate (see the
201# measurements above), so a single byte bound buys ~35 s at 44.1 kHz/16-bit -
202# three times the measured lead, where the seconds are actually needed - and
203# still ~16 s at the 32-bit hi-res carrier, where the pipeline holds fewer
204# seconds anyway. 6 MiB per playing group is a few percent of the server's idle
205# footprint.
206AIRPLAY_LATE_JOIN_RING_MAX_BYTES: Final[int] = 6 * 1024 * 1024
207
208# Delay (seconds) before automatically re-joining a group member whose
209# cliairplay process died unexpectedly mid-session (e.g. the device rode out a
210# network blackout longer than the binary's own keepalive tolerance). A single
211# attempt keeps the behaviour predictable: it waits long enough for a short
212# blackout to clear, and if the device is still gone the player is left idle.
213# Staged retries can be reintroduced by adding entries to the tuple.
214AIRPLAY_REJOIN_ATTEMPT_DELAYS: Final[tuple[int, ...]] = (5,)
215
216# Shared audible instant for a native announcement over a live stream: now +
217# the largest member span + this margin. A member can only mix the clip into
218# audio it has not delivered yet, and its span (warm_lead_ms on the Apple
219# splice timeline, the reported lead_ms otherwise) is how far its delivery
220# head runs ahead of the audible position - so the earliest instant EVERY
221# member can honor lies one max-span out. The margin covers fanning the
222# command out over the pipes and the per-member arm processing, so one shared
223# instant stays feasible for all members.
224AIRPLAY_ANNOUNCE_AT_MARGIN_MS: Final[int] = 300
225# Span assumed for a member whose binary reported neither a warm lead nor a
226# device lead (both read 0 = unreported): the binary's own default playback
227# lead, which bounds how far its delivery head can run ahead.
228AIRPLAY_ANNOUNCE_FALLBACK_SPAN_MS: Final[int] = 2000
229# Music gain (dB) under the clip while it plays; the binary ramps the duck in
230# and out itself. <= -60 mutes the music entirely. -18 dB puts the music
231# clearly in the background under speech (-12 was field-judged too shallow).
232AIRPLAY_ANNOUNCE_DUCK_DB: Final[int] = -18
233# Silence appended to every announcement clip file. The binary holds the duck
234# for the whole file, so this keeps the music ducked past the announcement -
235# the volume restore lands inside this cushion instead of racing the duck's
236# 200 ms tail ramp (a restore that lands after the ramp plays a moment of
237# full-level music at the still-bumped device volume).
238AIRPLAY_ANNOUNCE_DUCK_TAIL_S: Final[float] = 1.0
239# On top of the lead to the commanded instant: how long to wait for a member's
240# announce_started before treating that member as not announcing. An outdated
241# binary silently ignores the unknown command, so this bounded wait is also
242# what detects that and routes the announcement to the fallback path.
243AIRPLAY_ANNOUNCE_STARTED_TIMEOUT_MS: Final[int] = 3000
244# On top of the clip's audible end: how long to wait for announce_done. The
245# wait stays bounded because a queue that ends mid-clip emits its eof, which
246# ends the status stream while the clip still plays out over the drain.
247AIRPLAY_ANNOUNCE_DONE_TIMEOUT_MS: Final[int] = 5000
248# Pad after the clip's audible end before the pre-announcement volume is
249# restored: covers the jitter between the acked instant and true audibility.
250AIRPLAY_ANNOUNCE_VOLUME_RESTORE_PAD_MS: Final[int] = 500
251# Delay of the announcement-volume bump past the clip's audible start: a bump
252# that lands early (a receiver playing out later than the reported instant)
253# raises the still-playing music, so it is biased into the clip where the duck
254# ramp masks it - the pre-announce chime covers the first moments anyway.
255AIRPLAY_ANNOUNCE_VOLUME_BUMP_DELAY_MS: Final[int] = 300
256# The AirPlay volume parameter is linear dB: 0..100 maps onto -30..0 dB on
257# every flow (libraop raopcl_float_volume, reused verbatim by the native AP2
258# SET_PARAMETER path), so one volume point is exactly 0.3 dB of output. This
259# makes the announcement volume bump's effect on the music bed computable, and
260# the duck is deepened by the same amount to keep the music's perceived level
261# at the configured duck depth.
262AIRPLAY_VOLUME_DB_PER_POINT: Final[float] = 0.3
263# Drain margin for a dedicated announcement session: covers the receiver
264# playing out its buffered audio after the clip's last byte was fed.
265AIRPLAY_ANNOUNCE_SESSION_DRAIN_S: Final[float] = 2.0
266
267# Cover art is rendered to a local JPEG for the binary to embed (the binary
268# does not fetch URLs). 512px keeps the SET_PARAMETER payload small while still
269# looking sharp on speaker apps and the Apple TV now-playing screen.
270AIRPLAY_ARTWORK_SIZE: Final[int] = 512
271# How long a track-change metadata push waits for that render, so the artwork
272# can ride the SENDMETA bundle and the receiver rewrites its now-playing state
273# once instead of twice (bare replace, then artwork). A render that misses the
274# budget is not abandoned: it keeps running and is delivered with the
275# stand-alone ARTWORK command once it completes.
276AIRPLAY_ARTWORK_RENDER_TIMEOUT: Final[float] = 1.5
277EXTERNAL_ARTWORK_PATH_PREFIX: Final[str] = "external_artwork"
278
279# Per-protocol credential storage keys
280CONF_RAOP_CREDENTIALS: Final[str] = "raop_credentials"
281CONF_AIRPLAY_CREDENTIALS: Final[str] = "airplay_credentials"
282
283# AirPlay serves the shared sync-adjust control as a non-advanced (always visible)
284# setting: the binary handles lead/buffer automatically and does not apply
285# device-reported render latency, so sync_adjust is the primary way to compensate
286# a device wired to a TV / AV receiver / amplifier that adds its own audio delay.
287# The AirPlay-scoped strings spell out the sign; the shared entry stays advanced
288# for other providers.
289CONF_ENTRY_SYNC_ADJUST_AIRPLAY = replace(CONF_ENTRY_SYNC_ADJUST, advanced=False)
290
291# Interactive setup-flow input keys (transient PIN/password form fields and the
292# optional "set up now?" choice for the control pairing steps).
293CONF_PAIRING_PIN: Final[str] = "pairing_pin"
294CONF_PAIRING_PASSWORD: Final[str] = "pairing_password"
295CONF_COMPANION_PAIRING_PIN: Final[str] = "companion_pairing_pin"
296CONF_MRP_PAIRING_PIN: Final[str] = "mrp_pairing_pin"
297CONF_PAIR_NOW: Final[str] = "pair_now"
298
299FALLBACK_VOLUME: Final[int] = 20
300AIRPLAY_VOLUME_MUTE: Final[float] = -144.0
301
302AIRPLAY_PCM_FORMAT = AudioFormat(
303 content_type=ContentType.from_bit_depth(16), sample_rate=44100, bit_depth=16
304)
305# Sample rates advertised for a receiver that supports 24-bit (AirPlay 2 flow
306# only). At 24-bit the cliairplay binary expects raw s32le on stdin and truncates
307# to 24-bit ALAC internally.
308AIRPLAY_HIRES_SAMPLE_RATES: Final[list[tuple[int, int]]] = [(44100, 24), (48000, 24)]
309
310# Bits in the audioFormat bit space (shared with the receiver's /info format
311# tables) that mark 24-bit ALAC: 44.1 kHz and 48 kHz respectively. Receivers
312# understate these - the Apple TV lists them for its buffered stream only, yet
313# renders them fine on the realtime stream - so a device advertising either bit
314# on either stream is treated as 24-bit capable.
315AIRPLAY_HIRES_AUDIO_FORMATS: Final[int] = (1 << 19) | (1 << 21)
316
317BASE_PLAYER_FEATURES: Final[set[PlayerFeature]] = {
318 PlayerFeature.PLAY_MEDIA,
319 PlayerFeature.PLAY_ANNOUNCEMENT,
320 PlayerFeature.SET_MEMBERS,
321 PlayerFeature.MULTI_DEVICE_DSP,
322 PlayerFeature.VOLUME_SET,
323 PlayerFeature.VOLUME_MUTE,
324}
325
326
327PIN_REQUIRED = 0x8
328PASSWORD_BIT = 0x80
329LEGACY_PAIRING_BIT = 0x200
330# Observed on tvOS when an AirPlay password is set. Apple TVs keep PASSWORD_BIT
331# raised at all times (it marks their onscreen-code capability, not a password),
332# so this is the only flags-based password signal they give.
333ATV_PASSWORD_BIT = 0x1000
334
335# Provider setting: opt-in for the shared PTP daemon's per-packet timing trace
336# (Announce/Sync/Follow_Up) when verbose logging is active. Off by default â
337# the trace floods the log and only matters for clock-sync debugging.
338CONF_VERBOSE_PTP_LOGGING: Final[str] = "verbose_ptp_logging"
339
340# The cliairplay binary tags no log levels on its output, so a genuine problem is
341# recognised by keyword and promoted to a warning that stays visible at normal levels.
342CLI_PROBLEM_MARKERS: Final[tuple[str, ...]] = ("error", "cannot", "failed", "unable")
343# Bound on how many of those promoted lines the shared PTP daemon may produce per
344# window before the rest are counted instead of logged. The markers above are
345# deliberately broad, and "error" is ordinary vocabulary in clock telemetry
346# (offset error, path delay error), so with the daemon's per-packet trace running
347# at ~10 lines/s a single matching line would otherwise fill the log at WARNING.
348# A burst still gets through, which is what a real one-shot daemon failure is.
349PTP_DAEMON_WARN_BURST: Final[int] = 5
350PTP_DAEMON_WARN_WINDOW: Final[float] = 60.0
351