@semi-app/miplay 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/README.md +4 -2
  2. package/dist/MAGPIE-LICENSE.txt +21 -0
  3. package/dist/assets/airplay-0f650dbf.png +0 -0
  4. package/dist/assets/index-c3d52e7b.js +1 -0
  5. package/dist/assets/index-cf41e0aa.css +1 -0
  6. package/dist/assets/mina-f2e7977b.png +0 -0
  7. package/dist/assets/miplay-6539f915.js +124 -0
  8. package/dist/assets/miplay-70349e65.png +0 -0
  9. package/dist/assets/miplay-c5d217a1.css +1 -0
  10. package/dist/assets/semi-595e39af.ico +0 -0
  11. package/dist/assets/semi-core-38c824f6.png +0 -0
  12. package/dist/assets/tray-59cb5e08.js +1 -0
  13. package/dist/assets/tray-d30ea4dd.css +1 -0
  14. package/dist/background/main.cjs +19657 -0
  15. package/dist/background/playfair.wasm +0 -0
  16. package/dist/background/vendor/LICENSE +201 -0
  17. package/dist/background/vendor/NOTICE +22 -0
  18. package/dist/background/vendor/README.md +20 -0
  19. package/dist/background/vendor/alac.js +87 -0
  20. package/dist/background/vendor/alacDecoder.js +317 -0
  21. package/dist/background/vendor/appleKey.js +61 -0
  22. package/dist/background/vendor/ntpTiming.js +99 -0
  23. package/dist/background/vendor/package.json +1 -0
  24. package/dist/background/vendor/playfair/BUILD.md +17 -0
  25. package/dist/background/vendor/playfair/LICENSE.md +637 -0
  26. package/dist/background/vendor/playfair/MUSL-COPYRIGHT +193 -0
  27. package/dist/background/vendor/playfair/README.md +24 -0
  28. package/dist/background/vendor/playfair/hand_garble.c +443 -0
  29. package/dist/background/vendor/playfair/modified_md5.c +119 -0
  30. package/dist/background/vendor/playfair/omg_hax.c +540 -0
  31. package/dist/background/vendor/playfair/omg_hax.h +32 -0
  32. package/dist/background/vendor/playfair/playfair.c +31 -0
  33. package/dist/background/vendor/playfair/playfair.h +6 -0
  34. package/dist/background/vendor/playfair/sap_hash.c +96 -0
  35. package/dist/background/vendor/playfair/wasm-wrapper.c +22 -0
  36. package/dist/background/vendor/receiver.js +677 -0
  37. package/dist/index.html +6 -0
  38. package/dist/licenses/@leichtgewicht/ip-codec/LICENSE +21 -0
  39. package/dist/licenses/@mediabunny/aac-encoder/LICENSE +373 -0
  40. package/dist/licenses/array-flatten/LICENSE +21 -0
  41. package/dist/licenses/bonjour/LICENSE +21 -0
  42. package/dist/licenses/buffer-indexof/LICENSE +20 -0
  43. package/dist/licenses/call-bind/LICENSE +21 -0
  44. package/dist/licenses/call-bind-apply-helpers/LICENSE +21 -0
  45. package/dist/licenses/call-bound/LICENSE +21 -0
  46. package/dist/licenses/deep-equal/LICENSE +21 -0
  47. package/dist/licenses/define-data-property/LICENSE +21 -0
  48. package/dist/licenses/define-properties/LICENSE +21 -0
  49. package/dist/licenses/dns-equal/LICENSE +21 -0
  50. package/dist/licenses/dns-packet/LICENSE +21 -0
  51. package/dist/licenses/dns-txt/LICENSE +21 -0
  52. package/dist/licenses/dunder-proto/LICENSE +21 -0
  53. package/dist/licenses/es-define-property/LICENSE +21 -0
  54. package/dist/licenses/es-errors/LICENSE +21 -0
  55. package/dist/licenses/es-object-atoms/LICENSE +21 -0
  56. package/dist/licenses/ffmpeg/COPYING.LGPLv2.1 +502 -0
  57. package/dist/licenses/ffmpeg/LICENSE.md +127 -0
  58. package/dist/licenses/function-bind/LICENSE +20 -0
  59. package/dist/licenses/functions-have-names/LICENSE +21 -0
  60. package/dist/licenses/get-intrinsic/LICENSE +21 -0
  61. package/dist/licenses/get-proto/LICENSE +21 -0
  62. package/dist/licenses/gopd/LICENSE +21 -0
  63. package/dist/licenses/has-property-descriptors/LICENSE +21 -0
  64. package/dist/licenses/has-symbols/LICENSE +21 -0
  65. package/dist/licenses/has-tostringtag/LICENSE +21 -0
  66. package/dist/licenses/hasown/LICENSE +21 -0
  67. package/dist/licenses/is-arguments/LICENSE +20 -0
  68. package/dist/licenses/is-date-object/LICENSE +22 -0
  69. package/dist/licenses/is-regex/LICENSE +20 -0
  70. package/dist/licenses/magpie-MIT.txt +21 -0
  71. package/dist/licenses/math-intrinsics/LICENSE +21 -0
  72. package/dist/licenses/mediabunny/LICENSE +373 -0
  73. package/dist/licenses/mediabunny-MPL-2.0.txt +373 -0
  74. package/dist/licenses/multicast-dns/LICENSE +21 -0
  75. package/dist/licenses/multicast-dns-service-types/LICENSE +21 -0
  76. package/dist/licenses/object-is/LICENSE +20 -0
  77. package/dist/licenses/object-keys/LICENSE +21 -0
  78. package/dist/licenses/regexp.prototype.flags/LICENSE +22 -0
  79. package/dist/licenses/set-function-length/LICENSE +21 -0
  80. package/dist/licenses/set-function-name/LICENSE +21 -0
  81. package/dist/licenses/thunky/LICENSE +21 -0
  82. package/dist/tray.html +5 -0
  83. package/package.json +92 -5
@@ -0,0 +1,677 @@
1
+ /**
2
+ * The receiving half: an AirPlay 1 (RAOP) target other devices can stream to.
3
+ *
4
+ * Ported from libraop's `raop_server.c`. This is the mirror of everything else
5
+ * in the package — an RTSP *server* instead of a client, ALAC decoding instead
6
+ * of encoding, polling someone else's clock instead of serving our own.
7
+ *
8
+ * **Encryption is the caller's decision, not this package's.** A sender may
9
+ * encrypt the audio with an AES key it wraps in the receiver's RSA public key,
10
+ * and may demand an `Apple-Challenge` response signed with the matching private
11
+ * key. That key is Apple's, and shipping it is not something a library should
12
+ * decide for the person publishing it — so both operations are optional hooks
13
+ * ({@link ReceiverOptions.rsa}). With no hook the service advertises `et=0`,
14
+ * which is the honest statement that it takes cleartext only.
15
+ *
16
+ * mDNS advertising is likewise left to the caller: the port and the TXT record
17
+ * are handed out, and the application publishes them with whatever responder it
18
+ * already runs.
19
+ */
20
+ import { connect as connectTcp, createServer } from 'node:net';
21
+ import { createSocket } from 'node:dgram';
22
+ import { createDecipheriv, randomBytes } from 'node:crypto';
23
+ import { AlacDecoder, parseAlacFmtp } from './alacDecoder.js';
24
+ import { ntpNow } from './ntpTiming.js';
25
+ import { answerChallenge, decryptAesKey } from './appleKey.js';
26
+ import { fairplaySetup } from '../fairplay-setup.mjs';
27
+ import { unwrapFairplayKey } from '../fairplay-key.cjs';
28
+ /** Events a session raises, mirroring what the native receiver reported. */
29
+ /** Beyond this a gap is a blackout or a seek, not loss worth asking back for. */
30
+ const MAX_RESEND_RUN = 128;
31
+ /**
32
+ * A running RAOP receiver. One instance serves one sender at a time, which is
33
+ * what the protocol assumes: a second ANNOUNCE replaces the first.
34
+ */
35
+ export class AirPlayReceiver {
36
+ options;
37
+ onEvent;
38
+ server = null;
39
+ sessions = new Map();
40
+ activeSession = null;
41
+ connectionSequence = 0;
42
+ mac;
43
+ lastSeq = -1;
44
+ lastTs = -1;
45
+ counters = {
46
+ received: 0,
47
+ missed: 0,
48
+ retransmitted: 0,
49
+ undecodable: 0,
50
+ resendsAsked: 0,
51
+ framesAnnounced: 0,
52
+ framesDecoded: 0,
53
+ };
54
+ volume = 0;
55
+ constructor(options, onEvent) {
56
+ this.options = options;
57
+ this.onEvent = onEvent;
58
+ this.mac = options.mac ?? randomBytes(6);
59
+ }
60
+ /**
61
+ * What the audio path has seen since the stream started.
62
+ *
63
+ * `missed` counts gaps in the sender's sequence numbers -- audio that never
64
+ * arrived -- and is the number that separates a network problem from a
65
+ * decoding one, which sound identical from the outside.
66
+ */
67
+ get stats() {
68
+ return { ...this.counters };
69
+ }
70
+ /** Start listening. Returns what the caller needs to advertise. */
71
+ async start() {
72
+ const server = createServer((socket) => this.onConnection(socket));
73
+ await new Promise((resolve, reject) => {
74
+ server.once('error', reject);
75
+ server.listen(this.options.port ?? 0, this.options.host, () => {
76
+ server.removeListener('error', reject);
77
+ resolve();
78
+ });
79
+ });
80
+ this.server = server;
81
+ const address = server.address();
82
+ const port = typeof address === 'object' && address ? address.port : 0;
83
+ return {
84
+ instanceName: `${this.mac.toString('hex').toUpperCase()}@${this.options.name}`,
85
+ port,
86
+ txt: {
87
+ tp: 'UDP',
88
+ sm: 'false',
89
+ sv: 'false',
90
+ // `ek=1` and an `et` with a 1 in it are claims about encryption we can
91
+ // only make when the caller supplied the key to back them up.
92
+ ek: '1',
93
+ et: '0,1',
94
+ md: '0,1,2',
95
+ cn: '0,1',
96
+ ch: '2',
97
+ ss: '16',
98
+ sr: '44100',
99
+ // Keep the known-working MiAir RAOP declaration.
100
+ vn: '65537',
101
+ vs: '105.1',
102
+ da: 'true',
103
+ sf: '0x4',
104
+ pw: 'false',
105
+ fn: this.options.name,
106
+ // MiAir audio/PCM/ALAC/RSA/legacy flags, without AAC (not implemented here).
107
+ ft: '0x' + ((1 << 9) | (1 << 14) | (1 << 18) | (1 << 19) | (1 << 22) | (1 << 23) | (1 << 27)).toString(16).toUpperCase(),
108
+ txtvers: '1',
109
+ am: this.options.model ?? 'sonn',
110
+ },
111
+ };
112
+ }
113
+ stop() {
114
+ for (const [socket, session] of this.sessions) {
115
+ this.teardown(session);
116
+ socket.destroy();
117
+ }
118
+ this.sessions.clear();
119
+ this.activeSession = null;
120
+ this.server?.close();
121
+ this.server = null;
122
+ }
123
+ onConnection(socket) {
124
+ if (this.sessions.size >= 8) { this.options.onProtocol?.({ event: 'busy' }); socket.destroy(); return; }
125
+ socket.setNoDelay(true);
126
+ socket.on('error', () => socket.destroy());
127
+ const session = {
128
+ connectionId: ++this.connectionSequence,
129
+ alac: null,
130
+ aesKey: null,
131
+ aesIv: null,
132
+ decoder: null,
133
+ fpKeyMessage: null,
134
+ audio: null,
135
+ control: null,
136
+ timing: null,
137
+ senderTimingPort: 0,
138
+ senderControlPort: 0,
139
+ senderAddress: socket.remoteAddress?.replace(/^::ffff:/, '') ?? '',
140
+ socket,
141
+ dacpId: null,
142
+ activeRemote: null,
143
+ };
144
+ this.sessions.set(socket, session);
145
+ this.options.onProtocol?.({ event: 'connected', connectionId: session.connectionId });
146
+ let buffer = Buffer.alloc(0);
147
+ socket.on('data', (chunk) => {
148
+ buffer = Buffer.concat([buffer, chunk]);
149
+ if (buffer.length > 1114112) { socket.destroy(); return; }
150
+ for (;;) {
151
+ const headerEnd = buffer.indexOf('\r\n\r\n');
152
+ if (headerEnd < 0) {
153
+ return;
154
+ }
155
+ if (headerEnd > 65536) { socket.destroy(); return; }
156
+ const head = buffer.subarray(0, headerEnd).toString('utf8');
157
+ const lines = head.split('\r\n');
158
+ const headers = new Map();
159
+ for (const line of lines.slice(1)) {
160
+ const sep = line.indexOf(':');
161
+ if (sep > 0) {
162
+ headers.set(line.slice(0, sep).trim().toLowerCase(), line.slice(sep + 1).trim());
163
+ }
164
+ }
165
+ const length = Number(headers.get('content-length') ?? '0');
166
+ if (!Number.isInteger(length) || length < 0 || length > 1048576) { socket.destroy(); return; }
167
+ if (buffer.length < headerEnd + 4 + length) {
168
+ return;
169
+ }
170
+ const body = buffer.subarray(headerEnd + 4, headerEnd + 4 + length);
171
+ buffer = buffer.subarray(headerEnd + 4 + length);
172
+ try { this.handleRequest(socket, session, lines[0] ?? '', headers, Buffer.from(body)); }
173
+ catch (e) {
174
+ this.options.onProtocol?.({ event: 'request-failed', connectionId: session.connectionId, code: e.code || (e instanceof RangeError ? 'INVALID_CODEC_DATA' : 'INVALID_REQUEST') });
175
+ socket.destroy();
176
+ }
177
+ }
178
+ });
179
+ socket.on('close', () => {
180
+ const state = this.sessions.get(socket);
181
+ if (state) {
182
+ if (state.reportedConnection) this.onEvent({ type: 'connection', connected: false, connectionId: state.connectionId });
183
+ this.teardown(state);
184
+ this.sessions.delete(socket);
185
+ if (this.activeSession === state) {
186
+ this.activeSession = null; this.onEvent({ type: 'stop', connectionId: state.connectionId });
187
+ }
188
+ this.options.onProtocol?.({ event: 'disconnected', connectionId: session.connectionId, received: this.counters.received, decoded: this.counters.framesDecoded, undecodable: this.counters.undecodable });
189
+ }
190
+ });
191
+ socket.on('error', () => {
192
+ /* the close handler does the cleanup */
193
+ });
194
+ }
195
+ reportConnection(session) {
196
+ const sender = { address: session.senderAddress, name: session.deviceName || '', userAgent: session.userAgent || '' };
197
+ const signature = JSON.stringify(sender);
198
+ if (session.reportedConnection === signature) return;
199
+ session.reportedConnection = signature;
200
+ this.onEvent({ type: 'connection', connected: true, connectionId: session.connectionId, sender });
201
+ }
202
+ reply(socket, cseq, extra = {}, body, status = 200) {
203
+ const headers = {
204
+ CSeq: cseq,
205
+ Server: 'AirTunes/105.1',
206
+ // Senders check this to know the receiver actually has an output; without
207
+ // it an iPhone retries OPTIONS a few times and gives up before it ever
208
+ // gets as far as ANNOUNCE.
209
+ 'Audio-Jack-Status': 'connected; type=analog',
210
+ 'Apple-Jack-Status': 'connected; type=analog',
211
+ 'Content-Length': String(body?.length || 0),
212
+ ...extra,
213
+ };
214
+ if (body) {
215
+ headers['Content-Length'] = String(body.length);
216
+ }
217
+ const text = Object.entries(headers)
218
+ .map(([key, value]) => `${key}: ${value}`)
219
+ .join('\r\n');
220
+ const reason = { 200: 'OK', 453: 'Not Enough Bandwidth', 455: 'Method Not Valid in This State' }[status] || 'Error';
221
+ socket.write(Buffer.concat([Buffer.from(`RTSP/1.0 ${status} ${reason}\r\n${text}\r\n\r\n`), body || Buffer.alloc(0)]), error => {
222
+ this.options.onProtocol?.({ event: error ? 'response-failed' : 'response-sent', connectionId: this.sessions.get(socket)?.connectionId, status, bodyBytes: body?.length || 0 });
223
+ });
224
+ }
225
+ handleRequest(socket, session, requestLine, headers, body) {
226
+ const [method = '', target = ''] = requestLine.split(' ');
227
+ const path = ['/fp-setup', '/auth-setup', '/pair-setup', '/pair-verify', '/info'].includes(target) ? target : 'stream';
228
+ const cseq = headers.get('cseq') ?? '0';
229
+ const clean = value => typeof value === 'string' ? value.replace(/[\x00-\x1f\x7f]/g, '').trim().slice(0, 128) : '';
230
+ // Apple senders commonly use Client-Name; Device-Name is also used by
231
+ // compatible clients. Neither is the software's User-Agent identity.
232
+ const deviceName = clean(headers.get('x-apple-client-name')) || clean(headers.get('x-apple-device-name'));
233
+ if (deviceName) session.deviceName = deviceName;
234
+ if (headers.has('user-agent')) session.userAgent = clean(headers.get('user-agent'));
235
+ if (session.reportedConnection && method !== 'TEARDOWN') this.reportConnection(session);
236
+ this.options.onRequest?.({
237
+ method,
238
+ connectionId: session.connectionId,
239
+ appleChallenge: headers.has('apple-challenge'),
240
+ path, bodyBytes: body.length,
241
+ keyTransport: body.includes('a=fpaeskey:') ? 'fairplay' : body.includes('a=rsaaeskey:') ? 'rsa' : 'none',
242
+ ...(method === 'ANNOUNCE' ? { codec: /AppleLossless/i.test(body.toString()) ? 'ALAC' : /L16\//.test(body.toString()) ? 'L16' : 'unknown' } : {}),
243
+ });
244
+ // Every request carries these; keep the latest so a remote command can be
245
+ // sent at any point in the session.
246
+ const dacpId = headers.get('dacp-id');
247
+ const activeRemote = headers.get('active-remote');
248
+ if (dacpId && dacpId !== session.dacpId) {
249
+ session.dacpId = dacpId;
250
+ session.activeRemote = activeRemote ?? session.activeRemote;
251
+ this.onEvent({ type: 'remote', dacpId, activeRemote: session.activeRemote ?? '' });
252
+ }
253
+ else if (activeRemote) {
254
+ session.activeRemote = activeRemote;
255
+ }
256
+ // A sender may demand proof we hold the AirPort key before it will stream.
257
+ const extra = {};
258
+ const challenge = headers.get('apple-challenge');
259
+ if (challenge) {
260
+ extra['Apple-Response'] = answerChallenge(Buffer.from(challenge, 'base64'), socket.localAddress?.replace(/^::ffff:/, '') ?? '', this.mac);
261
+ }
262
+ switch (method) {
263
+ case 'POST':
264
+ if (path === '/fp-setup') {
265
+ const response = fairplaySetup(body);
266
+ session.fpKeyMessage?.fill(0);
267
+ session.fpKeyMessage = body.length === 164 ? Buffer.from(body) : null;
268
+ this.reportConnection(session);
269
+ this.reply(socket, cseq, { ...extra, 'Content-Type': 'application/octet-stream' }, response);
270
+ } else this.reply(socket, cseq, extra);
271
+ return;
272
+ case 'OPTIONS':
273
+ this.reportConnection(session);
274
+ this.reply(socket, cseq, {
275
+ ...extra,
276
+ Public: 'ANNOUNCE, SETUP, RECORD, PAUSE, FLUSH, FLUSHBUFFERED, TEARDOWN, OPTIONS, POST, GET, PUT, SETPEERSX, SETMAGICCOOKIE, GET_PARAMETER, SET_PARAMETER',
277
+ });
278
+ return;
279
+ case 'ANNOUNCE':
280
+ if (this.activeSession && this.activeSession !== session) {
281
+ this.reply(socket, cseq, extra, undefined, 453); return;
282
+ }
283
+ this.handleAnnounce(session, body.toString('utf8'));
284
+ this.activeSession = session;
285
+ this.reportConnection(session);
286
+ this.reply(socket, cseq, extra);
287
+ return;
288
+ case 'SETUP':
289
+ if (this.activeSession !== session) { this.reply(socket, cseq, extra, undefined, 455); return; }
290
+ void this.handleSetup(socket, session, headers, cseq, extra).catch(() => {
291
+ this.options.onProtocol?.({ event: 'setup-failed' }); socket.destroy();
292
+ });
293
+ return;
294
+ case 'RECORD':
295
+ if (this.activeSession !== session || !session.audio) { this.reply(socket, cseq, extra, undefined, 455); return; }
296
+ this.onEvent({ type: 'play', connectionId: session.connectionId, sender: {
297
+ address: socket.remoteAddress?.replace(/^::ffff:/, '') || '',
298
+ name: session.deviceName || '',
299
+ userAgent: session.userAgent || '',
300
+ } });
301
+ this.reply(socket, cseq, { ...extra, 'Audio-Latency': '0', 'RTP-Info': `seq=${Math.max(0, this.lastSeq)};rtptime=${Math.max(0, this.lastTs)}` });
302
+ return;
303
+ case 'PAUSE':
304
+ if (this.activeSession === session) this.onEvent({ type: 'pause', connectionId: session.connectionId });
305
+ this.reply(socket, cseq, extra); return;
306
+ case 'FLUSHBUFFERED':
307
+ case 'FLUSH':
308
+ if (this.activeSession === session) this.onEvent({ type: 'flush' });
309
+ this.reply(socket, cseq, { ...extra, 'RTP-Info': `seq=${Math.max(0, this.lastSeq)};rtptime=${Math.max(0, this.lastTs)}` });
310
+ return;
311
+ case 'TEARDOWN':
312
+ // This tears down the media session, not necessarily the RTSP
313
+ // TCP/control connection. Only socket.close removes the peer.
314
+ this.teardown(session);
315
+ if (this.activeSession === session) { this.activeSession = null; this.onEvent({ type: 'stop', connectionId: session.connectionId }); }
316
+ this.reply(socket, cseq, extra);
317
+ return;
318
+ case 'SET_PARAMETER':
319
+ this.handleSetParameter(session, headers, body);
320
+ this.reply(socket, cseq, extra);
321
+ return;
322
+ case 'GET_PARAMETER':
323
+ this.reply(socket, cseq, { ...extra, 'Content-Type': 'text/parameters' }, Buffer.from(`volume: ${this.volume.toFixed(6)}\r\n`, 'utf8'));
324
+ return;
325
+ default:
326
+ this.reply(socket, cseq, extra);
327
+ }
328
+ }
329
+ /** Read the codec parameters, and the AES key when the sender encrypted one. */
330
+ handleAnnounce(session, sdp) {
331
+ session.aesKey?.fill(0); session.aesIv?.fill(0);
332
+ session.aesKey = null; session.aesIv = null; session.alac = null; session.decoder = null;
333
+ let fairplayKey;
334
+ session.pcm = /a=rtpmap:\d+ L16\/44100\/2/i.test(sdp);
335
+ for (const line of sdp.split(/\r?\n/)) {
336
+ if (line.startsWith('i=') && !session.deviceName) {
337
+ session.deviceName = line.slice(2).replace(/[\x00-\x1f\x7f]/g, '').trim().slice(0, 128);
338
+ }
339
+ else if (line.startsWith('a=fmtp:')) {
340
+ session.alac = parseAlacFmtp(line.slice(line.indexOf(' ') + 1));
341
+ }
342
+ else if (line.startsWith('a=rsaaeskey:')) {
343
+ const wrapped = Buffer.from(base64Pad(line.slice('a=rsaaeskey:'.length)), 'base64');
344
+ session.aesKey = decryptAesKey(wrapped);
345
+ }
346
+ else if (line.startsWith('a=aesiv:')) {
347
+ session.aesIv = Buffer.from(base64Pad(line.slice('a=aesiv:'.length)), 'base64');
348
+ }
349
+ else if (line.startsWith('a=fpaeskey:')) {
350
+ fairplayKey = Buffer.from(base64Pad(line.slice('a=fpaeskey:'.length)), 'base64');
351
+ }
352
+ }
353
+ if (fairplayKey) {
354
+ try {
355
+ if (session.aesKey) throw Object.assign(new Error('Ambiguous audio key'), { code: 'INVALID_FAIRPLAY_KEY' });
356
+ session.aesKey = unwrapFairplayKey(session.fpKeyMessage, fairplayKey);
357
+ } finally { fairplayKey.fill(0); }
358
+ }
359
+ if (session.alac) {
360
+ session.decoder = new AlacDecoder(session.alac);
361
+ }
362
+ if (session.aesKey && session.aesKey.length !== 16 || session.aesIv && session.aesIv.length !== 16) throw new Error('Invalid audio key');
363
+ }
364
+ async handleSetup(socket, session, headers, cseq, extra) {
365
+ const transport = headers.get('transport') ?? '';
366
+ const field = (name) => {
367
+ const match = new RegExp(`${name}=(\\d+)`).exec(transport);
368
+ return match ? Number(match[1]) : 0;
369
+ };
370
+ session.senderControlPort = field('control_port');
371
+ session.senderTimingPort = field('timing_port');
372
+ const audio = createSocket({ type: 'udp4', reuseAddr: true });
373
+ const control = createSocket({ type: 'udp4', reuseAddr: true });
374
+ const timing = createSocket({ type: 'udp4', reuseAddr: true });
375
+ audio.on('message', (msg) => this.onAudio(session, msg));
376
+ control.on('message', (msg) => this.onControl(session, msg));
377
+ await Promise.all([bind(audio, this.options.host), bind(control, this.options.host), bind(timing, this.options.host)]);
378
+ session.audio = audio;
379
+ session.control = control;
380
+ session.timing = timing;
381
+ // Poll the sender's clock: on RAOP the sender owns the timeline and we
382
+ // follow it, the exact inverse of this package's sending side.
383
+ if (session.senderTimingPort) {
384
+ this.startTimingClient(session);
385
+ }
386
+ this.onEvent({ type: 'stream', port: audio.address().port });
387
+ this.reply(socket, cseq, {
388
+ ...extra,
389
+ Transport: `RTP/AVP/UDP;unicast;mode=record;server_port=${audio.address().port};` +
390
+ `control_port=${control.address().port};timing_port=${timing.address().port}`,
391
+ Session: '1',
392
+ });
393
+ }
394
+ /**
395
+ * Ask the sender to send a run of packets again.
396
+ *
397
+ * Not a standard RTCP NACK: eight bytes, type 0x55, carrying the first
398
+ * missing sequence number and how many follow. Without this a receiver simply
399
+ * keeps whatever holes the network left, and on a link with any loss that is
400
+ * the difference between clean audio and a hiccup every few seconds.
401
+ */
402
+ requestResend(session, first, count) {
403
+ // A silly range means a blackout or a seek, not loss worth chasing.
404
+ if (!session.control || !session.senderControlPort || count > MAX_RESEND_RUN) {
405
+ return;
406
+ }
407
+ const req = Buffer.alloc(8);
408
+ req[0] = 0x80;
409
+ req[1] = 0x55 | 0x80;
410
+ req.writeUInt16BE(1, 2);
411
+ req.writeUInt16BE(first, 4);
412
+ req.writeUInt16BE(count, 6);
413
+ this.counters.resendsAsked += count;
414
+ session.control.send(req, session.senderControlPort, session.senderAddress);
415
+ }
416
+ /**
417
+ * The control port carries two different things and they must not be
418
+ * confused: a retransmit reply (type 0xD6) wraps a real audio packet behind a
419
+ * four-byte header, while a sync packet (0xD4) is the sender telling us where
420
+ * its timeline is. Feeding the latter to the decoder produces exactly what it
421
+ * sounds like.
422
+ */
423
+ onControl(session, msg) {
424
+ if (msg.length < 4) {
425
+ return;
426
+ }
427
+ const type = msg[1] & 0x7f;
428
+ if (type === 0x56) {
429
+ this.onAudio(session, msg.subarray(4), true);
430
+ }
431
+ // 0x54 is the sync packet; the timeline it announces is not used yet.
432
+ }
433
+ /** Ask the sender for the time, the same 0xD2/0xD3 exchange we answer as a sender. */
434
+ startTimingClient(session) {
435
+ const poll = () => {
436
+ if (!session.timing) {
437
+ return;
438
+ }
439
+ const request = Buffer.alloc(32);
440
+ request[0] = 0x80;
441
+ request[1] = 0xd2;
442
+ request.writeUInt16BE(0x0007, 2);
443
+ const now = ntpNow();
444
+ request.writeUInt32BE(Number(now >> 32n), 24);
445
+ request.writeUInt32BE(Number(now & 0xffffffffn), 28);
446
+ session.timing.send(request, session.senderTimingPort, session.senderAddress);
447
+ };
448
+ poll();
449
+ const timer = setInterval(poll, 3000);
450
+ session.timing?.on('close', () => clearInterval(timer));
451
+ }
452
+ /**
453
+ * One audio packet: strip the RTP header, decrypt when the sender encrypted,
454
+ * decode, and hand the PCM up.
455
+ *
456
+ * AES here is CBC over whole 16-byte blocks only — the tail of the payload is
457
+ * left in the clear, which is what the format specifies and what a decoder
458
+ * that assumes otherwise gets wrong.
459
+ */
460
+ onAudio(session, packet, retransmitted = false) {
461
+ if (packet.length <= 12 || !session.pcm && (!session.decoder || !session.alac)) {
462
+ return;
463
+ }
464
+ if (retransmitted) {
465
+ this.counters.retransmitted += 1;
466
+ }
467
+ else {
468
+ const seq = packet.readUInt16BE(2);
469
+ if (this.lastSeq >= 0) {
470
+ // 16-bit wrap, and a retransmit arriving late reads as a jump backwards.
471
+ const delta = (seq - this.lastSeq) & 0xffff;
472
+ if (delta > 1 && delta < 0x8000) {
473
+ this.counters.missed += delta - 1;
474
+ this.requestResend(session, (this.lastSeq + 1) & 0xffff, delta - 1);
475
+ }
476
+ }
477
+ // What the sender says each packet is worth, which need not match what we
478
+ // decode out of it -- and that difference is exactly the kind that goes
479
+ // unnoticed, since neither a gap nor a decode failure shows up.
480
+ const ts = packet.readUInt32BE(4);
481
+ if (this.lastTs >= 0) {
482
+ const step = (ts - this.lastTs) >>> 0;
483
+ if (step > 0 && step < 0x8000) {
484
+ this.counters.framesAnnounced += step;
485
+ }
486
+ }
487
+ this.lastTs = ts;
488
+ this.lastSeq = seq;
489
+ this.counters.received += 1;
490
+ }
491
+ let payload = packet.subarray(12);
492
+ if (session.aesKey && session.aesIv) {
493
+ const whole = payload.length - (payload.length % 16);
494
+ if (whole > 0) {
495
+ const decipher = createDecipheriv('aes-128-cbc', session.aesKey, session.aesIv);
496
+ decipher.setAutoPadding(false);
497
+ const clear = Buffer.concat([decipher.update(payload.subarray(0, whole)), decipher.final()]);
498
+ payload = Buffer.concat([clear, payload.subarray(whole)]);
499
+ }
500
+ }
501
+ let pcm;
502
+ try {
503
+ pcm = session.pcm ? Buffer.from(payload).swap16() : session.decoder?.decode(payload);
504
+ } catch { this.counters.undecodable++; return; }
505
+ if (!pcm) {
506
+ this.counters.undecodable += 1;
507
+ }
508
+ if (pcm) {
509
+ this.counters.framesDecoded += pcm.length / ((session.alac?.channels ?? 2) * 2);
510
+ this.onEvent({
511
+ type: 'pcm',
512
+ sampleRate: session.alac?.sampleRate ?? 44100,
513
+ channels: session.alac?.channels ?? 2,
514
+ data: pcm,
515
+ });
516
+ }
517
+ }
518
+ /** Volume, track metadata and cover art all arrive on SET_PARAMETER. */
519
+ handleSetParameter(session, headers, body) {
520
+ const contentType = headers.get('content-type') ?? '';
521
+ if (contentType.startsWith('text/parameters')) {
522
+ const text = body.toString('utf8');
523
+ // `progress: <start>/<current>/<end>`, all three in RTP ticks at the
524
+ // stream's own sample rate. Converting here keeps the caller from having
525
+ // to know the unit, and the sender is the only party that knows where in
526
+ // the track it is -- nothing in the audio itself carries that.
527
+ const progress = /progress:\s*(\d+)\/(\d+)\/(\d+)/.exec(text);
528
+ if (progress) {
529
+ const rate = session.alac?.sampleRate ?? 44100;
530
+ const start = Number(progress[1]);
531
+ const current = Number(progress[2]);
532
+ const end = Number(progress[3]);
533
+ this.onEvent({
534
+ type: 'progress',
535
+ elapsedMs: Math.max(0, Math.round(((current - start) / rate) * 1000)),
536
+ durationMs: Math.max(0, Math.round(((end - start) / rate) * 1000)),
537
+ });
538
+ }
539
+ const match = /volume:\s*(-?[\d.]+)/.exec(text);
540
+ if (match) {
541
+ this.volume = Number(match[1]);
542
+ // The wire scale is dB from -30 to 0, with -144 for mute.
543
+ this.onEvent({ type: 'volume', value: this.volume });
544
+ }
545
+ return;
546
+ }
547
+ if (contentType.startsWith('image/')) {
548
+ this.onEvent({ type: 'artwork', contentType, data: trimImage(contentType, body) });
549
+ return;
550
+ }
551
+ if (contentType.includes('dmap')) {
552
+ this.onEvent({ type: 'metadata', ...parseDmap(body) });
553
+ }
554
+ }
555
+ teardown(session) {
556
+ session.audio?.close();
557
+ session.control?.close();
558
+ session.timing?.close();
559
+ session.audio = session.control = session.timing = null;
560
+ session.decoder = null;
561
+ session.aesKey?.fill(0); session.aesIv?.fill(0); session.fpKeyMessage?.fill(0);
562
+ session.aesKey = session.aesIv = session.fpKeyMessage = null;
563
+ }
564
+ }
565
+ /**
566
+ * Send a transport command back to the device that is streaming to us.
567
+ *
568
+ * The sender publishes an `_dacp._tcp` service named `iTunes_Ctrl_<DACP-ID>`;
569
+ * resolving that is the caller's job (this package carries no mDNS), and the
570
+ * address it finds goes in here. The request itself is a bare HTTP GET carrying
571
+ * the `Active-Remote` token as its only credential.
572
+ */
573
+ export async function sendRemoteCommand(host, port, activeRemote, command, timeoutMs = 3000) {
574
+ return new Promise((resolve) => {
575
+ const socket = connectTcp({ host, port });
576
+ let settled = false;
577
+ const finish = (ok) => {
578
+ if (!settled) {
579
+ settled = true;
580
+ socket.destroy();
581
+ resolve(ok);
582
+ }
583
+ };
584
+ const timer = setTimeout(() => finish(false), timeoutMs);
585
+ socket.once('connect', () => {
586
+ socket.write(`GET /ctrl-int/1/${command} HTTP/1.0\r\n` +
587
+ `Active-Remote: ${activeRemote}\r\n` +
588
+ `Connection: close\r\n\r\n`);
589
+ });
590
+ socket.once('data', (chunk) => {
591
+ clearTimeout(timer);
592
+ finish(/^HTTP\/1\.[01] 2\d\d/.test(chunk.toString('latin1')));
593
+ });
594
+ socket.once('error', () => {
595
+ clearTimeout(timer);
596
+ finish(false);
597
+ });
598
+ socket.once('close', () => {
599
+ clearTimeout(timer);
600
+ finish(false);
601
+ });
602
+ });
603
+ }
604
+ async function bind(socket, host) {
605
+ await new Promise((resolve, reject) => {
606
+ socket.once('error', reject);
607
+ socket.bind(0, host, () => {
608
+ socket.removeListener('error', reject);
609
+ resolve();
610
+ });
611
+ });
612
+ }
613
+ /** SDP strips base64 padding; Node's decoder wants it back. */
614
+ function base64Pad(value) {
615
+ const trimmed = value.trim();
616
+ return trimmed + '='.repeat((4 - (trimmed.length % 4)) % 4);
617
+ }
618
+ /**
619
+ * Pull the track fields out of a DMAP blob. The container is a tag, a 32-bit
620
+ * length and a payload, nested — only the three fields a now-playing display
621
+ * needs are read.
622
+ */
623
+ /**
624
+ * Cut a fixed-size artwork body down to the image it carries.
625
+ *
626
+ * iOS declares a Content-Length of exactly 180224 bytes for every cover and
627
+ * leaves whatever was in that slot after the image's own end marker -- around
628
+ * 78 KB of it. Decoders stop at the marker, so it renders either way, but
629
+ * passing the tail on means every consumer stores and serves it too, and a
630
+ * stricter one may refuse the file outright.
631
+ */
632
+ function trimImage(contentType, body) {
633
+ if (!contentType.startsWith('image/jpeg') || body.length < 4) {
634
+ return body;
635
+ }
636
+ if (body.readUInt16BE(0) !== 0xffd8) {
637
+ return body;
638
+ }
639
+ const end = body.lastIndexOf(Buffer.from([0xff, 0xd9]));
640
+ return end > 0 && end + 2 < body.length ? body.subarray(0, end + 2) : body;
641
+ }
642
+ function parseDmap(body) {
643
+ const out = {};
644
+ const walk = (buffer) => {
645
+ let offset = 0;
646
+ while (offset + 8 <= buffer.length) {
647
+ const tag = buffer.subarray(offset, offset + 4).toString('latin1');
648
+ const length = buffer.readUInt32BE(offset + 4);
649
+ const value = buffer.subarray(offset + 8, offset + 8 + length);
650
+ if (tag === 'mlit') {
651
+ walk(value);
652
+ }
653
+ else if (tag === 'minm') {
654
+ out.title = value.toString('utf8');
655
+ }
656
+ else if (tag === 'asar') {
657
+ out.artist = value.toString('utf8');
658
+ }
659
+ else if (tag === 'asal') {
660
+ out.album = value.toString('utf8');
661
+ }
662
+ else if (tag === 'astm' && length === 4) {
663
+ // daap.songtime, in milliseconds. Worth having even though `progress`
664
+ // carries a length too: this one arrives with every track's metadata,
665
+ // where progress is sent sparsely -- so it is the only length a
666
+ // receiver can count on seeing for each track.
667
+ const ms = value.readUInt32BE(0);
668
+ if (ms > 0) {
669
+ out.durationMs = ms;
670
+ }
671
+ }
672
+ offset += 8 + length;
673
+ }
674
+ };
675
+ walk(body);
676
+ return out;
677
+ }
@@ -0,0 +1,6 @@
1
+ <!doctype html>
2
+ <html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>音频互联</title> <script type="module" crossorigin src="./assets/index-c3d52e7b.js"></script>
3
+ <link rel="modulepreload" crossorigin href="./assets/miplay-6539f915.js">
4
+ <link rel="stylesheet" href="./assets/miplay-c5d217a1.css">
5
+ <link rel="stylesheet" href="./assets/index-cf41e0aa.css">
6
+ </head><body><div id="root"></div></body></html>