1 /*****************************************************************************
2 * raop.c: Remote Audio Output Protocol streaming support
3 *****************************************************************************
4 * Copyright (C) 2008 the VideoLAN team
7 * Author: Michael Hanselmann
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22 *****************************************************************************/
24 /*****************************************************************************
26 *****************************************************************************/
35 #include <vlc_common.h>
36 #include <vlc_plugin.h>
38 #include <vlc_block.h>
39 #include <vlc_network.h>
40 #include <vlc_strings.h>
41 #include <vlc_charset.h>
42 #include <vlc_gcrypt.h>
45 #define RAOP_PORT 5000
46 #define RAOP_USER_AGENT "VLC " VERSION
49 static const char ps_raop_rsa_pubkey[] =
50 "\xe7\xd7\x44\xf2\xa2\xe2\x78\x8b\x6c\x1f\x55\xa0\x8e\xb7\x05\x44"
51 "\xa8\xfa\x79\x45\xaa\x8b\xe6\xc6\x2c\xe5\xf5\x1c\xbd\xd4\xdc\x68"
52 "\x42\xfe\x3d\x10\x83\xdd\x2e\xde\xc1\xbf\xd4\x25\x2d\xc0\x2e\x6f"
53 "\x39\x8b\xdf\x0e\x61\x48\xea\x84\x85\x5e\x2e\x44\x2d\xa6\xd6\x26"
54 "\x64\xf6\x74\xa1\xf3\x04\x92\x9a\xde\x4f\x68\x93\xef\x2d\xf6\xe7"
55 "\x11\xa8\xc7\x7a\x0d\x91\xc9\xd9\x80\x82\x2e\x50\xd1\x29\x22\xaf"
56 "\xea\x40\xea\x9f\x0e\x14\xc0\xf7\x69\x38\xc5\xf3\x88\x2f\xc0\x32"
57 "\x3d\xd9\xfe\x55\x15\x5f\x51\xbb\x59\x21\xc2\x01\x62\x9f\xd7\x33"
58 "\x52\xd5\xe2\xef\xaa\xbf\x9b\xa0\x48\xd7\xb8\x13\xa2\xb6\x76\x7f"
59 "\x6c\x3c\xcf\x1e\xb4\xce\x67\x3d\x03\x7b\x0d\x2e\xa3\x0c\x5f\xff"
60 "\xeb\x06\xf8\xd0\x8a\xdd\xe4\x09\x57\x1a\x9c\x68\x9f\xef\x10\x72"
61 "\x88\x55\xdd\x8c\xfb\x9a\x8b\xef\x5c\x89\x43\xef\x3b\x5f\xaa\x15"
62 "\xdd\xe6\x98\xbe\xdd\xf3\x59\x96\x03\xeb\x3e\x6f\x61\x37\x2b\xb6"
63 "\x28\xf6\x55\x9f\x59\x9a\x78\xbf\x50\x06\x87\xaa\x7f\x49\x76\xc0"
64 "\x56\x2d\x41\x29\x56\xf8\x98\x9e\x18\xa6\x35\x5b\xd8\x15\x97\x82"
65 "\x5e\x0f\xc8\x75\x34\x3e\xc7\x82\x11\x76\x25\xcd\xbf\x98\x44\x7b";
67 static const char ps_raop_rsa_exp[] = "\x01\x00\x01";
69 static const char psz_delim_space[] = " ";
70 static const char psz_delim_colon[] = ":";
71 static const char psz_delim_equal[] = "=";
72 static const char psz_delim_semicolon[] = ";";
75 /*****************************************************************************
77 *****************************************************************************/
78 static int Open( vlc_object_t * );
79 static void Close( vlc_object_t * );
81 static sout_stream_id_t *Add( sout_stream_t *, es_format_t * );
82 static int Del( sout_stream_t *, sout_stream_id_t * );
83 static int Send( sout_stream_t *, sout_stream_id_t *, block_t* );
85 static int VolumeCallback( vlc_object_t *p_this, char const *psz_cmd,
86 vlc_value_t oldval, vlc_value_t newval,
96 struct sout_stream_sys_t
98 /* Input parameters */
103 sout_stream_id_t *p_audio_stream;
105 bool b_volume_callback;
107 /* Connection state */
111 uint8_t ps_aes_key[16];
112 uint8_t ps_aes_iv[16];
113 gcry_cipher_hd_t aes_ctx;
116 char *psz_client_instance;
125 size_t i_sendbuf_len;
129 struct sout_stream_id_t
135 /*****************************************************************************
137 *****************************************************************************/
138 #define SOUT_CFG_PREFIX "sout-raop-"
140 #define HOST_TEXT N_("Host")
141 #define HOST_LONGTEXT N_("Hostname or IP address of target device")
143 #define VOLUME_TEXT N_("Volume")
144 #define VOLUME_LONGTEXT N_("Output volume for analog output: 0 for silence, " \
145 "1..255 from almost silent to very loud.")
148 set_shortname( N_("RAOP") )
149 set_description( N_("Remote Audio Output Protocol streaming plugin") );
150 set_capability( "sout stream", 0 );
151 add_shortcut( "raop" );
152 set_category( CAT_SOUT );
153 set_subcategory( SUBCAT_SOUT_STREAM );
154 add_string( SOUT_CFG_PREFIX "host", "", NULL,
155 HOST_TEXT, HOST_LONGTEXT, false );
156 add_integer_with_range( SOUT_CFG_PREFIX "volume", 100, 0, 255, NULL,
157 VOLUME_TEXT, VOLUME_LONGTEXT, false );
158 set_callbacks( Open, Close );
161 static const char *const ppsz_sout_options[] = {
168 /*****************************************************************************
170 *****************************************************************************/
171 static void FreeSys( vlc_object_t *p_this, sout_stream_sys_t *p_sys )
173 sout_stream_t *p_stream = (sout_stream_t*)p_this;
175 if ( p_sys->i_control_fd >= 0 )
176 net_Close( p_sys->i_control_fd );
177 if ( p_sys->i_stream_fd >= 0 )
178 net_Close( p_sys->i_stream_fd );
179 if ( p_sys->b_volume_callback )
180 var_DelCallback( p_stream, SOUT_CFG_PREFIX "volume",
181 VolumeCallback, NULL );
183 gcry_cipher_close( p_sys->aes_ctx );
185 free( p_sys->p_sendbuf );
186 free( p_sys->psz_host );
187 free( p_sys->psz_url );
188 free( p_sys->psz_session );
189 free( p_sys->psz_client_instance );
193 static void FreeId( sout_stream_id_t *id )
198 static void RemoveBase64Padding( char *str )
200 char *ps_pos = strchr( str, '=' );
201 if ( ps_pos != NULL )
205 static int CheckForGcryptErrorWithLine( sout_stream_t *p_stream,
206 gcry_error_t i_gcrypt_err,
207 unsigned int i_line )
209 if ( i_gcrypt_err != GPG_ERR_NO_ERROR )
211 msg_Err( p_stream, "gcrypt error (line %d): %s", i_line,
212 gpg_strerror( i_gcrypt_err ) );
219 /* Wrapper to pass line number for easier debugging */
220 #define CheckForGcryptError( p_this, i_gcrypt_err ) \
221 CheckForGcryptErrorWithLine( p_this, i_gcrypt_err, __LINE__ )
223 /* MGF1 is specified in RFC2437, section 10.2.1. Variables are named after the
226 static int MGF1( vlc_object_t *p_this,
227 unsigned char *mask, size_t l,
228 const unsigned char *Z, const size_t zLen,
231 sout_stream_t *p_stream = (sout_stream_t*)p_this;
232 gcry_error_t i_gcrypt_err;
233 gcry_md_hd_t md_handle = NULL;
235 unsigned char *ps_md;
236 uint32_t counter = 0;
239 int i_err = VLC_SUCCESS;
241 assert( mask != NULL );
244 hLen = gcry_md_get_algo_dlen( Hash );
246 i_gcrypt_err = gcry_md_open( &md_handle, Hash, 0 );
247 if ( CheckForGcryptError( p_stream, i_gcrypt_err ) )
249 i_err = VLC_EGENERIC;
255 /* 3. For counter from 0 to \lceil{l / hLen}\rceil-1, do the following:
256 * a. Convert counter to an octet string C of length 4 with the
257 * primitive I2OSP: C = I2OSP (counter, 4)
259 C[0] = (counter >> 24) & 0xff;
260 C[1] = (counter >> 16) & 0xff;
261 C[2] = (counter >> 8) & 0xff;
262 C[3] = counter & 0xff;
265 /* b. Concatenate the hash of the seed Z and C to the octet string T:
266 * T = T || Hash (Z || C)
268 gcry_md_reset( md_handle );
269 gcry_md_write( md_handle, Z, zLen );
270 gcry_md_write( md_handle, C, 4 );
271 ps_md = gcry_md_read( md_handle, Hash );
273 /* 4. Output the leading l octets of T as the octet string mask. */
274 i_copylen = __MIN( l, hLen );
275 memcpy( mask, ps_md, i_copylen );
281 gcry_md_close( md_handle );
286 /* EME-OAEP-ENCODE is specified in RFC2437, section 9.1.1.1. Variables are
287 * named after the specification.
289 static int AddOaepPadding( vlc_object_t *p_this,
290 unsigned char *EM, const size_t emLenWithPrefix,
291 const unsigned char *M, const size_t mLen,
292 const unsigned char *P, const size_t pLen )
294 const int Hash = GCRY_MD_SHA1;
295 const unsigned int hLen = gcry_md_get_algo_dlen( Hash );
296 unsigned char *seed = NULL;
297 unsigned char *DB = NULL;
298 unsigned char *dbMask = NULL;
299 unsigned char *seedMask = NULL;
303 int i_err = VLC_SUCCESS;
305 /* Space for 0x00 prefix in EM. */
306 emLen = emLenWithPrefix - 1;
309 * If ||M|| > emLen-2hLen-1 then output "message too long" and stop.
311 if ( mLen > (emLen - (2 * hLen) - 1) )
313 msg_Err( p_this , "Message too long" );
318 * Generate an octet string PS consisting of emLen-||M||-2hLen-1 zero
319 * octets. The length of PS may be 0.
321 psLen = emLen - mLen - (2 * hLen) - 1;
325 * Concatenate pHash, PS, the message M, and other padding to form a data
326 * block DB as: DB = pHash || PS || 01 || M
328 DB = calloc( 1, hLen + psLen + 1 + mLen );
329 dbMask = calloc( 1, emLen - hLen );
330 seedMask = calloc( 1, hLen );
332 if ( DB == NULL || dbMask == NULL || seedMask == NULL )
339 * Let pHash = Hash(P), an octet string of length hLen.
341 gcry_md_hash_buffer( Hash, DB, P, pLen );
344 * Generate an octet string PS consisting of emLen-||M||-2hLen-1 zero
345 * octets. The length of PS may be 0.
347 memset( DB + hLen, 0, psLen );
350 * Concatenate pHash, PS, the message M, and other padding to form a data
351 * block DB as: DB = pHash || PS || 01 || M
353 DB[hLen + psLen] = 0x01;
354 memcpy( DB + hLen + psLen + 1, M, mLen );
357 * Generate a random octet string seed of length hLen
359 seed = gcry_random_bytes( hLen, GCRY_STRONG_RANDOM );
367 * Let dbMask = MGF(seed, emLen-hLen).
369 i_err = MGF1( p_this, dbMask, emLen - hLen, seed, hLen, Hash );
370 if ( i_err != VLC_SUCCESS )
374 * Let maskedDB = DB \xor dbMask.
376 for ( i = 0; i < (emLen - hLen); ++i )
380 * Let seedMask = MGF(maskedDB, hLen).
382 i_err = MGF1( p_this, seedMask, hLen, DB, emLen - hLen, Hash );
383 if ( i_err != VLC_SUCCESS )
387 * Let maskedSeed = seed \xor seedMask.
389 for ( i = 0; i < hLen; ++i )
390 seed[i] ^= seedMask[i];
393 * Let EM = maskedSeed || maskedDB.
395 assert( (1 + hLen + (hLen + psLen + 1 + mLen)) == emLenWithPrefix );
397 memcpy( EM + 1, seed, hLen );
398 memcpy( EM + 1 + hLen, DB, hLen + psLen + 1 + mLen );
413 static int EncryptAesKeyBase64( vlc_object_t *p_this, char **result )
415 sout_stream_t *p_stream = (sout_stream_t*)p_this;
416 sout_stream_sys_t *p_sys = p_stream->p_sys;
417 gcry_error_t i_gcrypt_err;
418 gcry_sexp_t sexp_rsa_params = NULL;
419 gcry_sexp_t sexp_input = NULL;
420 gcry_sexp_t sexp_encrypted = NULL;
421 gcry_sexp_t sexp_token_a = NULL;
422 gcry_mpi_t mpi_pubkey = NULL;
423 gcry_mpi_t mpi_exp = NULL;
424 gcry_mpi_t mpi_input = NULL;
425 gcry_mpi_t mpi_output = NULL;
426 unsigned char ps_padded_key[256];
427 unsigned char *ps_value;
429 int i_err = VLC_SUCCESS;
431 /* Add RSA-OAES-SHA1 padding */
432 i_err = AddOaepPadding( p_this,
433 ps_padded_key, sizeof( ps_padded_key ),
434 p_sys->ps_aes_key, sizeof( p_sys->ps_aes_key ),
436 if ( i_err != VLC_SUCCESS )
439 /* Read public key */
440 i_gcrypt_err = gcry_mpi_scan( &mpi_pubkey, GCRYMPI_FMT_USG,
442 sizeof( ps_raop_rsa_pubkey ) - 1, NULL );
443 if ( CheckForGcryptError( p_stream, i_gcrypt_err ) )
445 i_err = VLC_EGENERIC;
450 i_gcrypt_err = gcry_mpi_scan( &mpi_exp, GCRYMPI_FMT_USG, ps_raop_rsa_exp,
451 sizeof( ps_raop_rsa_exp ) - 1, NULL );
452 if ( CheckForGcryptError( p_stream, i_gcrypt_err ) )
454 i_err = VLC_EGENERIC;
458 /* If the input data starts with a set bit (0x80), gcrypt thinks it's a
459 * signed integer and complains. Prefixing it with a zero byte (\0)
460 * works, but involves more work. Converting it to an MPI in our code is
463 i_gcrypt_err = gcry_mpi_scan( &mpi_input, GCRYMPI_FMT_USG,
464 ps_padded_key, sizeof( ps_padded_key ),
466 if ( CheckForGcryptError( p_stream, i_gcrypt_err ) )
468 i_err = VLC_EGENERIC;
472 /* Build S-expression with RSA parameters */
473 i_gcrypt_err = gcry_sexp_build( &sexp_rsa_params, NULL,
474 "(public-key(rsa(n %m)(e %m)))",
475 mpi_pubkey, mpi_exp );
476 if ( CheckForGcryptError( p_stream, i_gcrypt_err ) )
478 i_err = VLC_EGENERIC;
482 /* Build S-expression for data */
483 i_gcrypt_err = gcry_sexp_build( &sexp_input, NULL, "(data(value %m))",
485 if ( CheckForGcryptError( p_stream, i_gcrypt_err ) )
487 i_err = VLC_EGENERIC;
492 i_gcrypt_err = gcry_pk_encrypt( &sexp_encrypted, sexp_input,
494 if ( CheckForGcryptError( p_stream, i_gcrypt_err ) )
496 i_err = VLC_EGENERIC;
500 /* Extract encrypted data */
501 sexp_token_a = gcry_sexp_find_token( sexp_encrypted, "a", 0 );
504 msg_Err( p_this , "Token 'a' not found in result S-expression" );
505 i_err = VLC_EGENERIC;
509 mpi_output = gcry_sexp_nth_mpi( sexp_token_a, 1, GCRYMPI_FMT_USG );
512 msg_Err( p_this, "Unable to extract MPI from result" );
513 i_err = VLC_EGENERIC;
517 /* Copy encrypted data into char array */
518 i_gcrypt_err = gcry_mpi_aprint( GCRYMPI_FMT_USG, &ps_value, &i_value_size,
520 if ( CheckForGcryptError( p_stream, i_gcrypt_err ) )
522 i_err = VLC_EGENERIC;
526 /* Encode in Base64 */
527 *result = vlc_b64_encode_binary( ps_value, i_value_size );
530 gcry_sexp_release( sexp_rsa_params );
531 gcry_sexp_release( sexp_input );
532 gcry_sexp_release( sexp_encrypted );
533 gcry_sexp_release( sexp_token_a );
534 gcry_mpi_release( mpi_pubkey );
535 gcry_mpi_release( mpi_exp );
536 gcry_mpi_release( mpi_input );
537 gcry_mpi_release( mpi_output );
542 /* Splits the value of a received header.
544 * Example: "Transport: RTP/AVP/TCP;unicast;mode=record;server_port=6000"
546 static int SplitHeader( char **ppsz_next, char **ppsz_name,
549 /* Find semicolon (separator between assignments) */
550 *ppsz_name = strsep( ppsz_next, psz_delim_semicolon );
554 *ppsz_name += strspn( *ppsz_name, psz_delim_space );
557 *ppsz_value = *ppsz_name;
558 strsep( ppsz_value, psz_delim_equal );
566 static void FreeHeader( void *p_value, void *p_data )
568 VLC_UNUSED( p_data );
572 static int ReadStatusLine( vlc_object_t *p_this )
574 sout_stream_t *p_stream = (sout_stream_t*)p_this;
575 sout_stream_sys_t *p_sys = p_stream->p_sys;
576 char *psz_original = NULL;
577 char *psz_line = NULL;
580 int i_err = VLC_SUCCESS;
582 psz_line = net_Gets( p_this, p_sys->i_control_fd, NULL );
585 i_err = VLC_EGENERIC;
589 psz_original = strdup( psz_line );
593 psz_token = strsep( &psz_next, psz_delim_space );
594 if ( !psz_token || strncmp( psz_token, "RTSP/1.", 7 ) != 0 )
596 msg_Err( p_this, "Unknown protocol (%s)", psz_original );
597 i_err = VLC_EGENERIC;
602 psz_token = strsep( &psz_next, psz_delim_space );
603 if ( !psz_token || strcmp( psz_token, "200" ) != 0 )
605 msg_Err( p_this, "Request failed (%s)", psz_original );
606 i_err = VLC_EGENERIC;
611 free( psz_original );
617 static int ReadHeader( vlc_object_t *p_this,
618 vlc_dictionary_t *p_resp_headers,
621 sout_stream_t *p_stream = (sout_stream_t*)p_this;
622 sout_stream_sys_t *p_sys = p_stream->p_sys;
623 char *psz_original = NULL;
624 char *psz_line = NULL;
629 int i_err = VLC_SUCCESS;
631 psz_line = net_Gets( p_this, p_sys->i_control_fd, NULL );
634 i_err = VLC_EGENERIC;
638 /* Empty line for response end */
639 if ( psz_line[0] == '\0' )
641 else if ( p_resp_headers )
643 psz_original = strdup( psz_line );
646 psz_token = strsep( &psz_next, psz_delim_colon );
647 if ( !psz_token || psz_next[0] != ' ' )
649 msg_Err( p_this, "Invalid header format (%s)", psz_original );
650 i_err = VLC_EGENERIC;
654 psz_name = psz_token;
655 psz_value = psz_next + 1;
657 vlc_dictionary_insert( p_resp_headers, psz_name, strdup( psz_value ) );
661 free( psz_original );
667 static int WriteAuxHeaders( vlc_object_t *p_this,
668 vlc_dictionary_t *p_req_headers )
670 sout_stream_t *p_stream = (sout_stream_t*)p_this;
671 sout_stream_sys_t *p_sys = p_stream->p_sys;
672 char **ppsz_keys = NULL;
675 int i_err = VLC_SUCCESS;
679 ppsz_keys = vlc_dictionary_all_keys( p_req_headers );
680 for ( i = 0; ppsz_keys[i]; ++i )
682 psz_key = ppsz_keys[i];
683 psz_value = vlc_dictionary_value_for_key( p_req_headers, psz_key );
685 i_rc = net_Printf( p_this, p_sys->i_control_fd, NULL,
686 "%s: %s\r\n", psz_key, psz_value );
689 i_err = VLC_EGENERIC;
695 for ( i = 0; ppsz_keys[i]; ++i )
696 free( ppsz_keys[i] );
702 static int SendRequest( vlc_object_t *p_this, const char *psz_method,
703 const char *psz_content_type, const char *psz_body,
704 vlc_dictionary_t *p_req_headers )
706 sout_stream_t *p_stream = (sout_stream_t*)p_this;
707 sout_stream_sys_t *p_sys = p_stream->p_sys;
708 const unsigned char psz_headers_end[] = "\r\n";
709 size_t i_body_length = 0;
710 int i_err = VLC_SUCCESS;
713 i_rc = net_Printf( p_this, p_sys->i_control_fd, NULL,
715 "User-Agent: " RAOP_USER_AGENT "\r\n"
716 "Client-Instance: %s\r\n"
718 psz_method, p_sys->psz_url,
719 p_sys->psz_client_instance,
723 i_err = VLC_EGENERIC;
727 if ( psz_content_type )
729 i_rc = net_Printf( p_this, p_sys->i_control_fd, NULL,
730 "Content-Type: %s\r\n", psz_content_type );
740 i_body_length = strlen( psz_body );
742 i_rc = net_Printf( p_this, p_sys->i_control_fd, NULL,
743 "Content-Length: %u\r\n",
744 (unsigned int)i_body_length );
754 i_err = WriteAuxHeaders( p_this, p_req_headers );
755 if ( i_err != VLC_SUCCESS )
759 i_rc = net_Write( p_this, p_sys->i_control_fd, NULL,
760 psz_headers_end, sizeof( psz_headers_end ) - 1 );
768 net_Write( p_this, p_sys->i_control_fd, NULL,
769 psz_body, i_body_length );
775 static int ExecRequest( vlc_object_t *p_this, const char *psz_method,
776 const char *psz_content_type, const char *psz_body,
777 vlc_dictionary_t *p_req_headers,
778 vlc_dictionary_t *p_resp_headers )
780 sout_stream_t *p_stream = (sout_stream_t*)p_this;
781 sout_stream_sys_t *p_sys = p_stream->p_sys;
783 int i_err = VLC_SUCCESS;
785 if ( p_sys->i_control_fd < 0 )
787 msg_Err( p_this, "Control connection not open" );
788 i_err = VLC_EGENERIC;
793 i_err = SendRequest( p_this, psz_method, psz_content_type, psz_body,
795 if ( i_err != VLC_SUCCESS )
798 /* Read status line */
799 i_err = ReadStatusLine( p_this );
800 if ( i_err != VLC_SUCCESS )
803 if ( p_resp_headers )
804 vlc_dictionary_clear( p_resp_headers, FreeHeader, NULL );
808 while ( !headers_done )
810 i_err = ReadHeader( p_this, p_resp_headers, &headers_done );
811 if ( i_err != VLC_SUCCESS )
819 static int AnnounceSDP( vlc_object_t *p_this, char *psz_local,
820 uint32_t i_session_id )
822 sout_stream_t *p_stream = (sout_stream_t*)p_this;
823 sout_stream_sys_t *p_sys = p_stream->p_sys;
824 vlc_dictionary_t req_headers;
825 vlc_dictionary_t resp_headers;
826 unsigned char ps_sac[16];
827 char *psz_sdp = NULL;
828 char *psz_sac_base64 = NULL;
829 char *psz_aes_key_base64 = NULL;
830 char *psz_aes_iv_base64 = NULL;
831 int i_err = VLC_SUCCESS;
834 vlc_dictionary_init( &req_headers, 0 );
835 vlc_dictionary_init( &resp_headers, 0 );
837 /* Encrypt AES key and encode it in Base64 */
838 i_rc = EncryptAesKeyBase64( p_this, &psz_aes_key_base64 );
839 if ( i_rc != VLC_SUCCESS || psz_aes_key_base64 == NULL )
841 i_err = VLC_EGENERIC;
844 RemoveBase64Padding( psz_aes_key_base64 );
846 /* Encode AES IV in Base64 */
847 psz_aes_iv_base64 = vlc_b64_encode_binary( p_sys->ps_aes_iv,
848 sizeof( p_sys->ps_aes_iv ) );
849 if ( psz_aes_iv_base64 == NULL )
851 i_err = VLC_EGENERIC;
854 RemoveBase64Padding( psz_aes_iv_base64 );
856 /* Random bytes for Apple-Challenge header */
857 gcry_randomize( ps_sac, sizeof( ps_sac ), GCRY_STRONG_RANDOM );
859 psz_sac_base64 = vlc_b64_encode_binary( ps_sac, sizeof( ps_sac ) );
860 if ( psz_sac_base64 == NULL )
862 i_err = VLC_EGENERIC;
865 RemoveBase64Padding( psz_sac_base64 );
868 * Note: IPv6 addresses also use "IP4". Make sure not to include the
871 i_rc = asprintf( &psz_sdp,
873 "o=iTunes %u 0 IN IP4 %s\r\n"
877 "m=audio 0 RTP/AVP 96\r\n"
878 "a=rtpmap:96 AppleLossless\r\n"
879 "a=fmtp:96 4096 0 16 40 10 14 2 255 0 0 44100\r\n"
882 i_session_id, psz_local, p_sys->psz_host,
883 psz_aes_key_base64, psz_aes_iv_base64 );
891 /* Build and send request */
892 vlc_dictionary_insert( &req_headers, "Apple-Challenge", psz_sac_base64 );
894 i_err = ExecRequest( p_this, "ANNOUNCE", "application/sdp", psz_sdp,
895 &req_headers, &resp_headers);
896 if ( i_err != VLC_SUCCESS )
900 vlc_dictionary_clear( &req_headers, NULL, NULL );
901 vlc_dictionary_clear( &resp_headers, FreeHeader, NULL );
904 free( psz_sac_base64 );
905 free( psz_aes_key_base64 );
906 free( psz_aes_iv_base64 );
911 static int SendSetup( vlc_object_t *p_this )
913 sout_stream_t *p_stream = (sout_stream_t*)p_this;
914 sout_stream_sys_t *p_sys = p_stream->p_sys;
915 vlc_dictionary_t req_headers;
916 vlc_dictionary_t resp_headers;
917 int i_err = VLC_SUCCESS;
923 vlc_dictionary_init( &req_headers, 0 );
924 vlc_dictionary_init( &resp_headers, 0 );
926 vlc_dictionary_insert( &req_headers, "Transport",
927 ((void*)"RTP/AVP/TCP;unicast;interleaved=0-1;"
930 i_err = ExecRequest( p_this, "SETUP", NULL, NULL,
931 &req_headers, &resp_headers );
932 if ( i_err != VLC_SUCCESS )
935 psz_tmp = vlc_dictionary_value_for_key( &resp_headers, "Session" );
938 msg_Err( p_this, "Missing 'Session' header during setup" );
939 i_err = VLC_EGENERIC;
943 free( p_sys->psz_session );
944 p_sys->psz_session = strdup( psz_tmp );
946 /* Get server_port */
947 psz_next = vlc_dictionary_value_for_key( &resp_headers, "Transport" );
948 while ( SplitHeader( &psz_next, &psz_name, &psz_value ) )
950 if ( psz_value && strcmp( psz_name, "server_port" ) == 0 )
952 p_sys->i_server_port = atoi( psz_value );
957 if ( !p_sys->i_server_port )
959 msg_Err( p_this, "Missing 'server_port' during setup" );
960 i_err = VLC_EGENERIC;
965 psz_next = vlc_dictionary_value_for_key( &resp_headers,
966 "Audio-Jack-Status" );
967 while ( SplitHeader( &psz_next, &psz_name, &psz_value ) )
969 if ( strcmp( psz_name, "type" ) != 0 )
972 if ( strcmp( psz_value, "analog" ) == 0 )
973 p_sys->i_jack_type = JACK_TYPE_ANALOG;
975 else if ( strcmp( psz_value, "digital" ) == 0 )
976 p_sys->i_jack_type = JACK_TYPE_DIGITAL;
982 vlc_dictionary_clear( &req_headers, NULL, NULL );
983 vlc_dictionary_clear( &resp_headers, FreeHeader, NULL );
988 static int SendRecord( vlc_object_t *p_this )
990 sout_stream_t *p_stream = (sout_stream_t*)p_this;
991 sout_stream_sys_t *p_sys = p_stream->p_sys;
992 vlc_dictionary_t req_headers;
993 vlc_dictionary_t resp_headers;
994 int i_err = VLC_SUCCESS;
997 vlc_dictionary_init( &req_headers, 0 );
998 vlc_dictionary_init( &resp_headers, 0 );
1000 vlc_dictionary_insert( &req_headers, "Range", (void *)"npt=0-" );
1001 vlc_dictionary_insert( &req_headers, "RTP-Info",
1002 (void *)"seq=0;rtptime=0" );
1003 vlc_dictionary_insert( &req_headers, "Session",
1004 (void *)p_sys->psz_session );
1006 i_err = ExecRequest( p_this, "RECORD", NULL, NULL,
1007 &req_headers, &resp_headers );
1008 if ( i_err != VLC_SUCCESS )
1011 psz_value = vlc_dictionary_value_for_key( &resp_headers, "Audio-Latency" );
1013 p_sys->i_audio_latency = atoi( psz_value );
1015 p_sys->i_audio_latency = 0;
1018 vlc_dictionary_clear( &req_headers, NULL, NULL );
1019 vlc_dictionary_clear( &resp_headers, FreeHeader, NULL );
1024 static int SendFlush( vlc_object_t *p_this )
1026 VLC_UNUSED( p_this );
1028 vlc_dictionary_t req_headers;
1029 int i_err = VLC_SUCCESS;
1031 vlc_dictionary_init( &req_headers, 0 );
1033 vlc_dictionary_insert( &req_headers, "RTP-Info",
1034 (void *)"seq=0;rtptime=0" );
1036 i_err = ExecRequest( p_this, "FLUSH", NULL, NULL, &req_headers, NULL );
1037 if ( i_err != VLC_SUCCESS )
1041 vlc_dictionary_clear( &req_headers, NULL, NULL );
1046 static int SendTeardown( vlc_object_t *p_this )
1048 int i_err = VLC_SUCCESS;
1050 i_err = ExecRequest( p_this, "TEARDOWN", NULL, NULL, NULL, NULL );
1051 if ( i_err != VLC_SUCCESS )
1058 static int UpdateVolume( vlc_object_t *p_this )
1060 sout_stream_t *p_stream = (sout_stream_t*)p_this;
1061 sout_stream_sys_t *p_sys = p_stream->p_sys;
1062 vlc_dictionary_t req_headers;
1063 char *psz_parameters = NULL;
1065 int i_err = VLC_SUCCESS;
1068 vlc_dictionary_init( &req_headers, 0 );
1070 /* Our volume is 0..255, RAOP is -144..0 (-144 off, -30..0 on) */
1073 p_sys->i_volume = __MAX( 0, __MIN( p_sys->i_volume, 255 ) );
1075 if ( p_sys->i_volume == 0 )
1078 d_volume = -30 + ( ( (double)p_sys->i_volume ) * 30.0 / 255.0 );
1080 /* Format without using locales */
1081 i_rc = us_asprintf( &psz_parameters, "volume: %0.6f\r\n", d_volume );
1088 vlc_dictionary_insert( &req_headers, "Session",
1089 (void *)p_sys->psz_session );
1091 i_err = ExecRequest( p_this, "SET_PARAMETER",
1092 "text/parameters", psz_parameters,
1093 &req_headers, NULL );
1094 if ( i_err != VLC_SUCCESS )
1098 vlc_dictionary_clear( &req_headers, NULL, NULL );
1099 free( psz_parameters );
1104 static void LogInfo( vlc_object_t *p_this )
1106 sout_stream_t *p_stream = (sout_stream_t*)p_this;
1107 sout_stream_sys_t *p_sys = p_stream->p_sys;
1108 const char *psz_jack_name;
1110 msg_Info( p_this, "Audio latency: %d", p_sys->i_audio_latency );
1112 switch ( p_sys->i_jack_type )
1114 case JACK_TYPE_ANALOG:
1115 psz_jack_name = "analog";
1118 case JACK_TYPE_DIGITAL:
1119 psz_jack_name = "digital";
1122 case JACK_TYPE_NONE:
1124 psz_jack_name = "none";
1128 msg_Info( p_this, "Jack type: %s", psz_jack_name );
1131 static void SendAudio( sout_stream_t *p_stream, block_t *p_buffer )
1133 sout_stream_sys_t *p_sys = p_stream->p_sys;
1134 gcry_error_t i_gcrypt_err;
1137 size_t i_payload_len;
1138 size_t i_realloc_len;
1141 const uint8_t header[16] = {
1142 0x24, 0x00, 0x00, 0x00,
1143 0xf0, 0xff, 0x00, 0x00,
1144 0x00, 0x00, 0x00, 0x00,
1145 0x00, 0x00, 0x00, 0x00,
1150 i_len = sizeof( header ) + p_buffer->i_buffer;
1152 /* Buffer resize needed? */
1153 if ( i_len > p_sys->i_sendbuf_len || p_sys->p_sendbuf == NULL )
1155 /* Grow in blocks of 4K */
1156 i_realloc_len = (1 + (i_len / 4096)) * 4096;
1158 p_sys->p_sendbuf = realloc( p_sys->p_sendbuf, i_realloc_len );
1159 if ( p_sys->p_sendbuf == NULL )
1162 p_sys->i_sendbuf_len = i_realloc_len;
1166 memcpy( p_sys->p_sendbuf, header, sizeof( header ) );
1167 memcpy( p_sys->p_sendbuf + sizeof( header ),
1168 p_buffer->p_buffer, p_buffer->i_buffer );
1170 /* Calculate payload length and update header */
1171 i_payload_len = i_len - 4;
1172 if ( i_payload_len > 0xffff )
1174 msg_Err( p_stream, "Buffer is too long (%u bytes)",
1175 (unsigned int)i_payload_len );
1179 p_sys->p_sendbuf[2] = ( i_payload_len >> 8 ) & 0xff;
1180 p_sys->p_sendbuf[3] = i_payload_len & 0xff;
1183 i_gcrypt_err = gcry_cipher_reset( p_sys->aes_ctx );
1184 if ( CheckForGcryptError( p_stream, i_gcrypt_err ) )
1188 i_gcrypt_err = gcry_cipher_setiv( p_sys->aes_ctx, p_sys->ps_aes_iv,
1189 sizeof( p_sys->ps_aes_iv ) );
1190 if ( CheckForGcryptError( p_stream, i_gcrypt_err ) )
1193 /* Encrypt in place. Only full blocks of 16 bytes are encrypted,
1194 * the rest (0-15 bytes) is left unencrypted.
1197 gcry_cipher_encrypt( p_sys->aes_ctx,
1198 p_sys->p_sendbuf + sizeof( header ),
1199 ( p_buffer->i_buffer / 16 ) * 16,
1201 if ( CheckForGcryptError( p_stream, i_gcrypt_err ) )
1205 rc = net_Write( p_stream, p_sys->i_stream_fd, NULL,
1206 p_sys->p_sendbuf, i_len );
1210 p_next = p_buffer->p_next;
1211 block_Release( p_buffer );
1216 block_ChainRelease( p_buffer );
1221 /*****************************************************************************
1223 *****************************************************************************/
1224 static int Open( vlc_object_t *p_this )
1226 sout_stream_t *p_stream = (sout_stream_t*)p_this;
1227 sout_stream_sys_t *p_sys;
1228 char psz_local[NI_MAXNUMERICHOST];
1229 gcry_error_t i_gcrypt_err;
1230 int i_err = VLC_SUCCESS;
1231 uint32_t i_session_id;
1232 uint64_t i_client_instance;
1236 config_ChainParse( p_stream, SOUT_CFG_PREFIX, ppsz_sout_options,
1239 p_sys = calloc( 1, sizeof( *p_sys ) );
1240 if ( p_sys == NULL )
1246 p_stream->p_sys = p_sys;
1247 p_stream->pf_add = Add;
1248 p_stream->pf_del = Del;
1249 p_stream->pf_send = Send;
1250 p_stream->p_sout->i_out_pace_nocontrol++;
1252 p_sys->i_control_fd = -1;
1253 p_sys->i_stream_fd = -1;
1254 p_sys->i_volume = var_GetInteger( p_stream, SOUT_CFG_PREFIX "volume");
1255 p_sys->i_jack_type = JACK_TYPE_NONE;
1257 p_sys->psz_host = var_GetNonEmptyString( p_stream,
1258 SOUT_CFG_PREFIX "host" );
1259 if ( p_sys->psz_host == NULL )
1261 msg_Err( p_this, "Missing host" );
1262 i_err = VLC_EGENERIC;
1266 var_AddCallback( p_stream, SOUT_CFG_PREFIX "volume",
1267 VolumeCallback, NULL );
1268 p_sys->b_volume_callback = true;
1270 /* Open control connection */
1271 p_sys->i_control_fd = net_ConnectTCP( p_stream, p_sys->psz_host,
1273 if ( p_sys->i_control_fd < 0 )
1275 msg_Err( p_this, "Cannot establish control connection to %s:%d (%m)",
1276 p_sys->psz_host, RAOP_PORT );
1277 i_err = VLC_EGENERIC;
1281 /* Get local IP address */
1282 if ( net_GetSockAddress( p_sys->i_control_fd, psz_local, NULL ) )
1284 msg_Err( p_this, "cannot get local IP address" );
1285 i_err = VLC_EGENERIC;
1289 /* Random session ID */
1290 gcry_randomize( &i_session_id, sizeof( i_session_id ),
1291 GCRY_STRONG_RANDOM );
1293 /* Random client instance */
1294 gcry_randomize( &i_client_instance, sizeof( i_client_instance ),
1295 GCRY_STRONG_RANDOM );
1296 if ( asprintf( &p_sys->psz_client_instance, "%016llX",
1297 i_client_instance ) < 0 )
1303 /* Build session URL */
1304 if ( asprintf( &p_sys->psz_url, "rtsp://%s/%u",
1305 psz_local, i_session_id ) < 0 )
1311 /* Generate AES key and IV */
1312 gcry_randomize( p_sys->ps_aes_key, sizeof( p_sys->ps_aes_key ),
1313 GCRY_STRONG_RANDOM );
1314 gcry_randomize( p_sys->ps_aes_iv, sizeof( p_sys->ps_aes_iv ),
1315 GCRY_STRONG_RANDOM );
1318 i_gcrypt_err = gcry_cipher_open( &p_sys->aes_ctx, GCRY_CIPHER_AES,
1319 GCRY_CIPHER_MODE_CBC, 0 );
1320 if ( CheckForGcryptError( p_stream, i_gcrypt_err ) )
1322 i_err = VLC_EGENERIC;
1327 i_gcrypt_err = gcry_cipher_setkey( p_sys->aes_ctx, p_sys->ps_aes_key,
1328 sizeof( p_sys->ps_aes_key ) );
1329 if ( CheckForGcryptError( p_stream, i_gcrypt_err ) )
1331 i_err = VLC_EGENERIC;
1335 /* Protocol handshake */
1336 i_err = AnnounceSDP( p_this, psz_local, i_session_id );
1337 if ( i_err != VLC_SUCCESS )
1340 i_err = SendSetup( p_this );
1341 if ( i_err != VLC_SUCCESS )
1344 i_err = SendRecord( p_this );
1345 if ( i_err != VLC_SUCCESS )
1348 i_err = UpdateVolume( p_this );
1349 if ( i_err != VLC_SUCCESS )
1354 /* Open stream connection */
1355 p_sys->i_stream_fd = net_ConnectTCP( p_stream, p_sys->psz_host,
1356 p_sys->i_server_port );
1357 if ( p_sys->i_stream_fd < 0 )
1359 msg_Err( p_this, "Cannot establish stream connection to %s:%d (%m)",
1360 p_sys->psz_host, p_sys->i_server_port );
1361 i_err = VLC_EGENERIC;
1366 if ( i_err != VLC_SUCCESS )
1367 FreeSys( p_this, p_sys );
1373 /*****************************************************************************
1375 *****************************************************************************/
1376 static void Close( vlc_object_t *p_this )
1378 sout_stream_t *p_stream = (sout_stream_t*)p_this;
1379 sout_stream_sys_t *p_sys = p_stream->p_sys;
1381 SendFlush( p_this );
1382 SendTeardown( p_this );
1384 FreeSys( p_this, p_sys );
1386 p_stream->p_sout->i_out_pace_nocontrol--;
1390 /*****************************************************************************
1392 *****************************************************************************/
1393 static sout_stream_id_t *Add( sout_stream_t *p_stream, es_format_t *p_fmt )
1395 sout_stream_sys_t *p_sys = p_stream->p_sys;
1396 sout_stream_id_t *id = NULL;
1398 id = calloc( 1, sizeof( *id ) );
1402 es_format_Copy( &id->fmt, p_fmt );
1404 switch ( id->fmt.i_cat )
1407 if ( id->fmt.i_codec == VLC_FOURCC('a', 'l', 'a', 'c') )
1409 if ( p_sys->p_audio_stream )
1411 msg_Warn( p_stream, "Only the first Apple Lossless audio "
1414 else if ( id->fmt.audio.i_rate != 44100 ||
1415 id->fmt.audio.i_channels != 2 )
1417 msg_Err( p_stream, "The Apple Lossless audio stream must be "
1418 "encoded with 44100 Hz and 2 channels" );
1422 /* Use this stream */
1423 p_sys->p_audio_stream = id;
1426 else if ( !p_sys->b_alac_warning )
1428 msg_Err( p_stream, "Apple Lossless is the only codec supported. "
1429 "Use the \"transcode\" module for conversion "
1430 "(e.g. \"transcode{acodec=alac,"
1431 "channels=2}\")." );
1432 p_sys->b_alac_warning = true;
1438 /* Leave other stream types alone */
1451 /*****************************************************************************
1453 *****************************************************************************/
1454 static int Del( sout_stream_t *p_stream, sout_stream_id_t *id )
1456 sout_stream_sys_t *p_sys = p_stream->p_sys;
1457 int i_err = VLC_SUCCESS;
1459 if ( p_sys->p_audio_stream == id )
1460 p_sys->p_audio_stream = NULL;
1468 /*****************************************************************************
1470 *****************************************************************************/
1471 static int Send( sout_stream_t *p_stream, sout_stream_id_t *id,
1474 sout_stream_sys_t *p_sys = p_stream->p_sys;
1476 if ( id->fmt.i_cat == AUDIO_ES && id == p_sys->p_audio_stream )
1478 /* SendAudio takes care of releasing the buffers */
1479 SendAudio( p_stream, p_buffer );
1483 block_ChainRelease( p_buffer );
1490 /*****************************************************************************
1491 * VolumeCallback: called when the volume is changed on the fly.
1492 *****************************************************************************/
1493 static int VolumeCallback( vlc_object_t *p_this, char const *psz_cmd,
1494 vlc_value_t oldval, vlc_value_t newval,
1497 VLC_UNUSED(psz_cmd);
1501 sout_stream_t *p_stream = (sout_stream_t*)p_this;
1502 sout_stream_sys_t *p_sys = p_stream->p_sys;
1504 /* TODO: Implement volume change */