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