aboutsummaryrefslogtreecommitdiffstats
path: root/airtunes2.rst
blob: fd8213b5dd75eb2532b4380dd3e5fddd477debf8 (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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
AirTunes 2 Protocol
===================

.. contents:: :depth: 4

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

Airtunes 2 is the protocol used by Apple's Airport Express, iTunes and Rogue
Amoeba's Airfoil. The `previously known RAOP protocol
<http://xmms2.org/wiki/
Technical_note_to_describe_the_Remote_Audio_Access_Protocol_(RAOP)
_as_used_in_Apple_iTunes_to_stream_music_to_the_Airport_Express_(ApEx).>`_ does
not support more advanced timing features, and as such, some software, such as
`PulseAudio <http://www.pulseaudio.org/>`_ do not support audio/video syncing
and sometime suffer from unreliable playback. The Airtunes 2 project seeks to
remedy this.

Credits
-------

* `The Airtunes 2 Team <http://git.zx2c4.com/Airtunes2/about/>`_
* `Apple Inc. <http://www.apple.com/>`_
* `Rogue Amoeba Software, LLC <http://www.rogueamoeba.com/>`_

Conventions
-----------

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

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

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

Every stream has an associated RTP timestamp (uint32; initially set to a
random number transmitted to the server in the RECORD RTSP request)
and a sequence number (int16; initially set to random value transmitted to 
the server in the RECORD RTSP request).
Both are updated when sending audio packets. Audio data is encapsulated in
RTP packets which are sent sent as UDP packets to the audio port.

There are ``TIMESTAMPS_PER_SECOND`` RTP timestamp ticks per second (equivalent
to the number of frames per second).

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


Connect
~~~~~~~

#. Establish TCP connection to RTSP port

   - IP address(es) from Zeroconf TXT record

#. Send RTSP ``OPTIONS`` request
#. Send RTSP ``ANNOUNCE`` request

   - Use password authentication based on authentication type from Zeroconf TXT
     record or after receiving HTTP status code 401 (``401 Unauthorized``)

#. Send RTSP ``SETUP`` request
#. Set sequence number of connection to a random value between 0 and 8192,
   initial RTP timestamp to a random value between 0 and 65535. Normal play
   time (npt) is initially 0.
#. Send RTSP ``RECORD`` request
#. Send RTSP ``SET_PARAMETER`` request to set initial volume
   (see `Setting volume`_)
#. Prepare RTP connection for audio packets


Transmitting Audio
~~~~~~~~~~~~~~~~~~

The audio data is encapsulated in an RTP packet (see RFC3550 Section 5.1)

#. Bytes 0-1 of the RTP Header are 0x80, 0x60
#. Bytes 2-3 store the current sequence number (whose initial value was set
   in the RECORD RTSP request)
#. Bytes 4-7 store the current RTP timestamp (initial value was transmitted
   to the Airtunes device in the RECORD RTSP request)
#. Bytes 8-11 store the SSRC (random number which will be the same in all
   audio packets, see RFC3550 Section 5.1 for more details) (TODO: is the
   SSRC the same as the RTSP client session ID ?)
#. Starting at byte 12 comes the audio data (see `Packetizing audio`_ for
   its format)
#. Send this RTP packet as UDP on the audio data port
#. Increase sequence number by one for next audio packet
#. Increase timestamp by number of frames in this audio packet



Disconnect
~~~~~~~~~~

#. Stop sending audio data
#. Close RTSP connection


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) */
  }


NTP Timestamp
~~~~~~~~~~~~~

This is an NTP Timestamp as described in RFC 3450 Section 4. and RFC 1305
(TODO: check this is actually true)

::

  /* 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;
  }


RTP Timestamp
~~~~~~~~~~~~~

This is a 32 bit network order value increasing by 1 for each frame of data
transmitted, which means it increases by FRAMES_PER_PACKET for every RTP
packet sent.


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

::

  /* sizeof(TimingPacket) == 32 */
  struct TimingPacket {
    RtpHeader header;
    uint32_t zero_padding;
    NtpTime reference_time;
    NtpTime received_time;
    NtpTime send_time;
  }


SyncPacket
~~~~~~~~~~

::

  /* sizeof(SyncPacket) == 20 */
  struct SyncPacket {
    RtpHeader header;
    RtpTimestamp timestamp;
    NtpTime some_time;
    RtpTimestamp 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
===================== ========================= ==========================


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: Initial value for the RTP Sequence Number, random 16 bit value

Note 3: Initial value for the RTP Timestamps, random 32 bit value

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.
(TODO server_port is missing from the Transport: example above)

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
======= ===================================


Authentication
~~~~~~~~~~~~~~

AirTunes 2 uses the HTTP Digest authentication method as described
in RFC2617.


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
------

The server will send Timing request UDP packets to the timing port. The
sender will answer to this Timing request with a Timing response UDP packet
sent to the server timing port.

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;
   /* these 3 times are NTP times (ie 64 bit values) */
   res.reference_time = req.send_time;
   res.received_time = time_now();
   res.send_time = time_now();
   /* TODO: is req.send_time the time on the server? the (virtual) NTP time
    * of the audio packet that is being played by the server? Is one of the
    * other timestamp the time on the sender, and the other one, some kind of
    * "common time" to be used by the server and the sender?
    */
  
   send(res);
  }


Sync
----

Sync packets are sent once per second or when adding a speaker. They are sent
to the device control port as UDP packets. The next_timestamp field corresponds
to the RTP timestamp of the next audio packet that will be sent.

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: RTP timestamp taking into account latency? */;
   packet.next_timestamp = current_rtp_timestamp; /* RTP Timestamp that will be used for the next RTP audio packet */
   packet.some_time = /* TODO: an NTP timestamp */
  }


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


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``
============== =======================================