aboutsummaryrefslogtreecommitdiffstats
path: root/airtunes2.rst
blob: c06db62fcb0db23b24429e9fe97341d20169d450 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
AirTunes 2 protocol
===================

.. contents:: :depth: 4

Introduction
------------

TODO

In the examples below, values to be replaced are put into curly
braces ("{}"). The braces should not be included after replacing
the values.

Credits
-------

* `Apple Inc. <http://www.apple.com/>`_
* `Rogue Amoeba Software, LLC <http://www.rogueamoeba.com/>`_


Streaming audio to an AirTunes 2 compatible device
--------------------------------------------------

If encryption is necessary, a random key and IV (initialization vector) for AES
encryption, 16 bytes each, should be generated.

Every stream has a timestamp (uint64; initially set to ``INITIAL_TIMESTAMP``,
see Constants_) and sequence number (int16; initially set to 0) attached to it.
Both are updated when sending audio packets.

Up to ``PACKET_BACKLOG`` audio packets should be kept around to resend them if
necessary. After sending a audio packet, the sender should check if a sync
packet should also be sent (basically every ``TIMESYNC_INTERVAL`` frames and
just after connecting).


Preferred TCP/UDP ports
-----------------------

=========== ====
Connection  Port
=========== ====
RTSP        5000
Audio data  6000
RTP control 6001
Timing      6002
=========== ====


Payload types
-------------

=============== ====
Timing request  0x52
Timing response 0x53
Sync            0x54
Range resend    0x55
Audio data      0x60
=============== ====

Data types
----------

When transferred over the network, multi-byte values need to converted
to network byte order. No aligning must be used within the packet
structures.

RtpHeader
~~~~~~~~~

::

  /* RTP header bits */
  RTP_HEADER_A_EXTENSION = 0x10;
  RTP_HEADER_A_SOURCE = 0x0f;

  RTP_HEADER_B_PAYLOAD_TYPE = 0x7f;
  RTP_HEADER_B_MARKER = 0x80;

  /* sizeof(RtpHeader) == 4 */
  RtpHeader {
   uint8_t a;
   uint8_t b;
   uint16_t seqnum;
  
   /* extension = bool(a & RTP_HEADER_A_EXTENSION) */
   /* source = a & RTP_HEADER_A_SOURCE */
  
   /* payload_type = b & RTP_HEADER_B_PAYLOAD_TYPE */
   /* marker = bool(b & RTP_HEADER_B_MARKER) */
  }


RtpTime
~~~~~~~

::

  /* sizeof(RtpTime) == 8 */
  struct RtpTime {
    /* Seconds since 1900-01-01 00:00:00 (TODO: Timezone?) */
    uint32_t integer;
    
    /* Fraction of second (0..2^32) */
    uint32_t fraction;
  }


TimingPacket
~~~~~~~~~~~~

::

  /* sizeof(TimingPacket) == 32 */
  struct TimingPacket {
    RtpHeader header;
    RtpTime timestamp;
    RtpTime reference_time;
    RtpTime received_time;
    RtpTime send_time;
  }


SyncPacket
~~~~~~~~~~

::

  /* sizeof(SyncPacket) == 20 */
  struct SyncPacket {
    RtpHeader header;
    uint32_t timestamp;
    RtpTime some_time;
    uint32_t next_timestamp;
  }


ResendPacket
~~~~~~~~~~~~

::

  /* sizeof(RtpResendPacket) == 8 */
  struct RtpResendHeader {
    RtpHeader header;
    uint16_t missed_seqnum;
    uint16_t count;
  }


Constants
---------

===================== ========================= ==========================
Name                  Value                     Description
===================== ========================= ==========================
FRAMES_PER_PACKET     352                       Audio frames per packet
SHORTS_PER_PACKET     2 * FRAMES_PER_PACKET     Shorts per packet
TIMESTAMPS_PER_SECOND 44100                     Timestamps per second
TIMESYNC_INTERVAL     44100                     Once per second
TIME_PER_PACKET       FRAMES_PER_PACKET / 44100 Milliseconds
PACKET_BACKLOG        1000                      Packet resend buffer size
INITIAL_TIMESTAMP     0x10000000
===================== ========================= ==========================


RTSP
----

Common request headers
~~~~~~~~~~~~~~~~~~~~~~

.. _rtp-info:

================ =================================================
Client-Instance  | 64 random bytes in hex. Must be unique per
                   connection.
CSeq             | Request sequence number. Can either be counted
                   locally or response sequence number can be
                   increased by one.
RTP-Info         ``rtptime={RTP timestamp}``
Session          Server session ID (after SETUP)
User-Agent       | ``iTunes/{Version} (Windows; N;)``
                   (e.g. Version=``iTunes/7.6.2 (Windows; N;)``)
================ =================================================


Request URI
~~~~~~~~~~~

Unless specified otherwise, ``rtsp://{Local IP address}/{Client session ID}``
must be used as the request URI. The client session ID is a random number
between 0 and 2^32 generated once per connection.


ANNOUNCE
~~~~~~~~

======= ===========================================================
Headers | ``Content-Type: application/sdp``
Body    | ``v=0\r\n``
        | ``o=iTunes {Client session ID} O IN IP4 {Local IP address}\r\n``
        | ``s=iTunes\r\n``
        | ``c=IN IP4 {Server IP address}\r\n``
        | ``t=0 0\r\n``
        | ``m=audio 0 RTP/AVP 96\r\n``
        | ``a=rtpmap:96 AppleLossless\r\n``
        | ``a=fmtp:96 {Frames per packet} 0 16 40 10 14 2 255 0 0 44100\r\n``
        | ``a=rsaaeskey:{AES key in base64 w/o padding}\r\n``
        | ``a=aesiv:{AES IV in base64 w/o padding}\r\n``
        | ``\r\n``
======= ===========================================================

FLUSH
~~~~~

======= =============================================
Headers ``RTP-Info: seq={Last RTP seqnum};rtptime=0``
======= =============================================

OPTIONS
~~~~~~~

======= ============================================================
URI     ``*``
Headers ``Apple-Challenge: {16 random bytes in base64 w/o padding}``
======= ============================================================

RECORD
~~~~~~

======= =========================================
Headers | ``Range: ntp={Note 1}``
        | ``RTP-Info: seq={Note 2};rtptime={Note 3}``
======= =========================================

Note 1: Normal play time (apparently always 0), float, >=0. (TODO)

Note 2: Apparently a random number between 0 and 8192. (TODO)

Note 3: Apparently always zero. (TODO)

SET_PARAMETER
~~~~~~~~~~~~~

Setting volume
``````````````

======= =================================
Headers ``Content-Type: text/parameters``
Body    ``volume: %f``
======= =================================

Volume is either -144.0 (muted) or (-30.0)..(0.0).

Set progress
````````````

======= =================================
Headers ``Content-Type: text/parameters``
Body    ``progress: %f/%f/%f``
======= =================================

Values are RTP timestamp as unsigned integers (TODO).

Set DAAP metadata
`````````````````

======= =================================
Headers | ``Content-Type: application/x-dmap-tagged``
        | RTP-Info_
Body    DAAP metadata
======= =================================

SETUP
~~~~~

======= ====================================================
Headers ``Transport: RTP/AVP/UDP;unicast;interleaved=0-1;mode=record;control_port={Control port};timing_port={Timing port}``
======= ====================================================

Get ``server_port``, ``control_port`` and ``timing_port`` from ``Transport``
response header. Get ``Session`` response header and use it as server session ID.

TEARDOWN
~~~~~~~~

Nothing special.

Rogue Amoeba extensions
~~~~~~~~~~~~~~~~~~~~~~~

X_RA_SET_ALBUM_ART
``````````````````

Use this only if server wants PList metadata. Use the ``SET_PARAMETER``
method if DAAP metadata is requested.

======= ========================================
Headers | ``Content-Type: {Image content type}``
        | RTP-Info_
Body    Image data
======= ========================================


X_RA_SET_PLIST_METADATA
```````````````````````

======= ===================================
Headers | ``Content-Type: application/xml``
        | RTP-Info_
Body    Metadata in PList format
======= ===================================


Detect speaker type
~~~~~~~~~~~~~~~~~~~

If ``Audio-Jack-Status`` is in response:

::

  speaker_type() {
    if ("disconnected" in Audio-Jack-Status) {
      return unplugged;
  
    } else if ("connected" in Audio-Jack-Status) {
      if ("digital" in Audio-Jack-Status) {
        return digital;
      }
  
      return analog;
    }
    
    return unknown;
  }


Detect metadata and audio latency
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

If ``Apple-Response``, ``Server`` or ``Audio-Latency`` in response:

::

  if (Apple-Response in response) {
    lowercase_password = False;
    audio_format = EncryptedALAC;
    wants_album_art = False;
    wants_metadata = False;
    wants_progress = False;
    has_bad_latency_header = False;
  }

  if (Server in response) {
    lowercase_password = True;
    has_bad_latency_header = True;

    if (not Apple-Response in response) {
      audio_format = UnencryptedALAC;
      wants_album_art = DAAP;
      wants_metadata = DAAP;
      wants_progress = True;
    }
  }
  
  if (Audio-Latency in response) {
    if (not has_bad_latency_header) {
      audio_latency = Audio-Latency;
    } else {
      if (Audio-Latency == 322 or
          Audio-Latency == 15049) {
        audio_latency = 11025;
      }
  
      /* Why always 11025? */
      audio_latency = 11025;
    }
  }


Timing
------

Replying to timing packet
~~~~~~~~~~~~~~~~~~~~~~~~~ 

::

  on_timing_packet(TimingPacket req) {
   assert req.header.payload_type == PAYLOAD_TIMING_REQUEST;
  
   TimingPacket res;
   res.header = req.header;
   res.header.payload_type = PAYLOAD_TIMING_RESPONSE;
   res.reftime = req.send_time;
   res.received_time = time_now();
   res.send_time = time_now();
  
   send(res);
  }


Sync
----

Sync packets are sent once per second or when adding a speaker.

TODO: More details such as timing adjustments.

Sending sync packet
~~~~~~~~~~~~~~~~~~~

::
  
  send_sync(uint32_t timestamp, bool first) {
   SyncPacket packet;
   packet.header.payload_type = PAYLOAD_SYNC;
   packet.header.marker = True;
   packet.header.seqnum = 7; /* Why fixed? */
  
   if (first) {
     packet.header.extension = True;
   }
  
   packet.now_timestamp = /* TODO */;
   packet.next_timestamp = timestamp;
   packet.some_time = /* TODO */;
  }


Audio
-----

Audio packet
~~~~~~~~~~~~

Header::

  /* The first 4 bytes are an RtpHeader */
  { 0x80, 0x60, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00,
    0x62, 0x74, 0x05, 0xb9 }


Audio codec
~~~~~~~~~~~

=============== =====================
Codec           Apple Lossless (ALAC)
Sample size     16 Bit
Channels        2
Sample rate     44100
=============== =====================


Packetizing audio
~~~~~~~~~~~~~~~~~

#. Collect ``FRAMES_PER_PACKET`` frames from input data (each frame is
   2 bytes)
#. Encode input frames using ALAC codec
#. Encode packet data

   - Raw L16
   
     #. Convert raw input data to big endian (it's an array of uint16)
     #. Copy audio header and converted audio data into one buffer
     #. Set 2nd byte of buffer to 0xa

   - Unencrypted ALAC
   
     #. Copy audio header to buffer
     #. Append ALAC encoded audio data to buffer
     
   - Encrypted ALAC
   
     #. Encrypt ALAC encoded audio data (only complete 16 byte blocks,
        the rest stays unencrypted)
     #. Copy audio header to buffer
     #. Append encrypted audio data to buffer
     
#. Set bytes 2-4 to sequence number in big endian
#. Set bytes 4-8 to timestamp in big endian
#. Increase sequence number by one for next packet
#. Increase timestamp by number of frames in this packet


Metadata
--------

DAAP metadata
~~~~~~~~~~~~~

=============== =============================
Content-type    ``application/x-dmap-tagged``
Item name field ``dmap.itemname``
Artist field    ``daap.songartist``
Album field     ``daap.songalbum``
=============== =============================

PList metadata
~~~~~~~~~~~~~~

=============== =============================
Content-type    ``application/xml``
Title field     ``title``
Artist field    ``artist``
Album field     ``album``
=============== =============================


Zeroconf TXT record
-------------------

======= =======================================================
Field   Description
======= =======================================================
txtvers TXT record version (always ``1``)
pw      ``true`` if password required, ``false`` otherwise
sr      Audio sample rate
ss      Audio bit rate
ch      Number of audio channels
tp      Protocol (``UDP`` [TODO: or ``TCP``?])
======= =======================================================


Rogue Amoeba extensions
~~~~~~~~~~~~~~~~~~~~~~~

============== =======================================
Field          Description
============== =======================================
rast           ``afs`` if Airfoil speaker
ramach         ``{Platform name}.{OS major version}``
raver          Library version
raAudioFormats ``ALAC`` or ``L16``
============== =======================================