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;
118 char *psz_last_status_line;
126 size_t i_sendbuf_len;
130 struct sout_stream_id_t
136 /*****************************************************************************
138 *****************************************************************************/
139 #define SOUT_CFG_PREFIX "sout-raop-"
141 #define HOST_TEXT N_("Host")
142 #define HOST_LONGTEXT N_("Hostname or IP address of target device")
144 #define VOLUME_TEXT N_("Volume")
145 #define VOLUME_LONGTEXT N_("Output volume for analog output: 0 for silence, " \
146 "1..255 from almost silent to very loud.")
149 set_shortname( N_("RAOP") )
150 set_description( N_("Remote Audio Output Protocol stream output") )
151 set_capability( "sout stream", 0 )
152 add_shortcut( "raop" )
153 set_category( CAT_SOUT )
154 set_subcategory( SUBCAT_SOUT_STREAM )
155 add_string( SOUT_CFG_PREFIX "host", "", NULL,
156 HOST_TEXT, HOST_LONGTEXT, false )
157 add_integer_with_range( SOUT_CFG_PREFIX "volume", 100, 0, 255, NULL,
158 VOLUME_TEXT, VOLUME_LONGTEXT, false )
159 set_callbacks( Open, Close )
162 static const char *const ppsz_sout_options[] = {
169 /*****************************************************************************
171 *****************************************************************************/
172 static void FreeSys( vlc_object_t *p_this, sout_stream_sys_t *p_sys )
174 sout_stream_t *p_stream = (sout_stream_t*)p_this;
176 if ( p_sys->i_control_fd >= 0 )
177 net_Close( p_sys->i_control_fd );
178 if ( p_sys->i_stream_fd >= 0 )
179 net_Close( p_sys->i_stream_fd );
180 if ( p_sys->b_volume_callback )
181 var_DelCallback( p_stream, SOUT_CFG_PREFIX "volume",
182 VolumeCallback, NULL );
184 gcry_cipher_close( p_sys->aes_ctx );
186 free( p_sys->p_sendbuf );
187 free( p_sys->psz_host );
188 free( p_sys->psz_url );
189 free( p_sys->psz_session );
190 free( p_sys->psz_client_instance );
191 free( p_sys->psz_last_status_line );
195 static void FreeId( sout_stream_id_t *id )
200 static void RemoveBase64Padding( char *str )
202 char *ps_pos = strchr( str, '=' );
203 if ( ps_pos != NULL )
207 static int CheckForGcryptErrorWithLine( sout_stream_t *p_stream,
208 gcry_error_t i_gcrypt_err,
209 unsigned int i_line )
211 if ( i_gcrypt_err != GPG_ERR_NO_ERROR )
213 msg_Err( p_stream, "gcrypt error (line %d): %s", i_line,
214 gpg_strerror( i_gcrypt_err ) );
221 /* Wrapper to pass line number for easier debugging */
222 #define CheckForGcryptError( p_this, i_gcrypt_err ) \
223 CheckForGcryptErrorWithLine( p_this, i_gcrypt_err, __LINE__ )
225 /* MGF1 is specified in RFC2437, section 10.2.1. Variables are named after the
228 static int MGF1( vlc_object_t *p_this,
229 unsigned char *mask, size_t l,
230 const unsigned char *Z, const size_t zLen,
233 sout_stream_t *p_stream = (sout_stream_t*)p_this;
234 gcry_error_t i_gcrypt_err;
235 gcry_md_hd_t md_handle = NULL;
237 unsigned char *ps_md;
238 uint32_t counter = 0;
241 int i_err = VLC_SUCCESS;
243 assert( mask != NULL );
246 hLen = gcry_md_get_algo_dlen( Hash );
248 i_gcrypt_err = gcry_md_open( &md_handle, Hash, 0 );
249 if ( CheckForGcryptError( p_stream, i_gcrypt_err ) )
251 i_err = VLC_EGENERIC;
257 /* 3. For counter from 0 to \lceil{l / hLen}\rceil-1, do the following:
258 * a. Convert counter to an octet string C of length 4 with the
259 * primitive I2OSP: C = I2OSP (counter, 4)
261 C[0] = (counter >> 24) & 0xff;
262 C[1] = (counter >> 16) & 0xff;
263 C[2] = (counter >> 8) & 0xff;
264 C[3] = counter & 0xff;
267 /* b. Concatenate the hash of the seed Z and C to the octet string T:
268 * T = T || Hash (Z || C)
270 gcry_md_reset( md_handle );
271 gcry_md_write( md_handle, Z, zLen );
272 gcry_md_write( md_handle, C, 4 );
273 ps_md = gcry_md_read( md_handle, Hash );
275 /* 4. Output the leading l octets of T as the octet string mask. */
276 i_copylen = __MIN( l, hLen );
277 memcpy( mask, ps_md, i_copylen );
283 gcry_md_close( md_handle );
288 /* EME-OAEP-ENCODE is specified in RFC2437, section 9.1.1.1. Variables are
289 * named after the specification.
291 static int AddOaepPadding( vlc_object_t *p_this,
292 unsigned char *EM, const size_t emLenWithPrefix,
293 const unsigned char *M, const size_t mLen,
294 const unsigned char *P, const size_t pLen )
296 const int Hash = GCRY_MD_SHA1;
297 const unsigned int hLen = gcry_md_get_algo_dlen( Hash );
298 unsigned char *seed = NULL;
299 unsigned char *DB = NULL;
300 unsigned char *dbMask = NULL;
301 unsigned char *seedMask = NULL;
305 int i_err = VLC_SUCCESS;
307 /* Space for 0x00 prefix in EM. */
308 emLen = emLenWithPrefix - 1;
311 * If ||M|| > emLen-2hLen-1 then output "message too long" and stop.
313 if ( mLen > (emLen - (2 * hLen) - 1) )
315 msg_Err( p_this , "Message too long" );
320 * Generate an octet string PS consisting of emLen-||M||-2hLen-1 zero
321 * octets. The length of PS may be 0.
323 psLen = emLen - mLen - (2 * hLen) - 1;
327 * Concatenate pHash, PS, the message M, and other padding to form a data
328 * block DB as: DB = pHash || PS || 01 || M
330 DB = calloc( 1, hLen + psLen + 1 + mLen );
331 dbMask = calloc( 1, emLen - hLen );
332 seedMask = calloc( 1, hLen );
334 if ( DB == NULL || dbMask == NULL || seedMask == NULL )
341 * Let pHash = Hash(P), an octet string of length hLen.
343 gcry_md_hash_buffer( Hash, DB, P, pLen );
346 * Generate an octet string PS consisting of emLen-||M||-2hLen-1 zero
347 * octets. The length of PS may be 0.
349 memset( DB + hLen, 0, psLen );
352 * Concatenate pHash, PS, the message M, and other padding to form a data
353 * block DB as: DB = pHash || PS || 01 || M
355 DB[hLen + psLen] = 0x01;
356 memcpy( DB + hLen + psLen + 1, M, mLen );
359 * Generate a random octet string seed of length hLen
361 seed = gcry_random_bytes( hLen, GCRY_STRONG_RANDOM );
369 * Let dbMask = MGF(seed, emLen-hLen).
371 i_err = MGF1( p_this, dbMask, emLen - hLen, seed, hLen, Hash );
372 if ( i_err != VLC_SUCCESS )
376 * Let maskedDB = DB \xor dbMask.
378 for ( i = 0; i < (emLen - hLen); ++i )
382 * Let seedMask = MGF(maskedDB, hLen).
384 i_err = MGF1( p_this, seedMask, hLen, DB, emLen - hLen, Hash );
385 if ( i_err != VLC_SUCCESS )
389 * Let maskedSeed = seed \xor seedMask.
391 for ( i = 0; i < hLen; ++i )
392 seed[i] ^= seedMask[i];
395 * Let EM = maskedSeed || maskedDB.
397 assert( (1 + hLen + (hLen + psLen + 1 + mLen)) == emLenWithPrefix );
399 memcpy( EM + 1, seed, hLen );
400 memcpy( EM + 1 + hLen, DB, hLen + psLen + 1 + mLen );
415 static int EncryptAesKeyBase64( vlc_object_t *p_this, char **result )
417 sout_stream_t *p_stream = (sout_stream_t*)p_this;
418 sout_stream_sys_t *p_sys = p_stream->p_sys;
419 gcry_error_t i_gcrypt_err;
420 gcry_sexp_t sexp_rsa_params = NULL;
421 gcry_sexp_t sexp_input = NULL;
422 gcry_sexp_t sexp_encrypted = NULL;
423 gcry_sexp_t sexp_token_a = NULL;
424 gcry_mpi_t mpi_pubkey = NULL;
425 gcry_mpi_t mpi_exp = NULL;
426 gcry_mpi_t mpi_input = NULL;
427 gcry_mpi_t mpi_output = NULL;
428 unsigned char ps_padded_key[256];
429 unsigned char *ps_value;
431 int i_err = VLC_SUCCESS;
433 /* Add RSA-OAES-SHA1 padding */
434 i_err = AddOaepPadding( p_this,
435 ps_padded_key, sizeof( ps_padded_key ),
436 p_sys->ps_aes_key, sizeof( p_sys->ps_aes_key ),
438 if ( i_err != VLC_SUCCESS )
441 /* Read public key */
442 i_gcrypt_err = gcry_mpi_scan( &mpi_pubkey, GCRYMPI_FMT_USG,
444 sizeof( ps_raop_rsa_pubkey ) - 1, NULL );
445 if ( CheckForGcryptError( p_stream, i_gcrypt_err ) )
447 i_err = VLC_EGENERIC;
452 i_gcrypt_err = gcry_mpi_scan( &mpi_exp, GCRYMPI_FMT_USG, ps_raop_rsa_exp,
453 sizeof( ps_raop_rsa_exp ) - 1, NULL );
454 if ( CheckForGcryptError( p_stream, i_gcrypt_err ) )
456 i_err = VLC_EGENERIC;
460 /* If the input data starts with a set bit (0x80), gcrypt thinks it's a
461 * signed integer and complains. Prefixing it with a zero byte (\0)
462 * works, but involves more work. Converting it to an MPI in our code is
465 i_gcrypt_err = gcry_mpi_scan( &mpi_input, GCRYMPI_FMT_USG,
466 ps_padded_key, sizeof( ps_padded_key ),
468 if ( CheckForGcryptError( p_stream, i_gcrypt_err ) )
470 i_err = VLC_EGENERIC;
474 /* Build S-expression with RSA parameters */
475 i_gcrypt_err = gcry_sexp_build( &sexp_rsa_params, NULL,
476 "(public-key(rsa(n %m)(e %m)))",
477 mpi_pubkey, mpi_exp );
478 if ( CheckForGcryptError( p_stream, i_gcrypt_err ) )
480 i_err = VLC_EGENERIC;
484 /* Build S-expression for data */
485 i_gcrypt_err = gcry_sexp_build( &sexp_input, NULL, "(data(value %m))",
487 if ( CheckForGcryptError( p_stream, i_gcrypt_err ) )
489 i_err = VLC_EGENERIC;
494 i_gcrypt_err = gcry_pk_encrypt( &sexp_encrypted, sexp_input,
496 if ( CheckForGcryptError( p_stream, i_gcrypt_err ) )
498 i_err = VLC_EGENERIC;
502 /* Extract encrypted data */
503 sexp_token_a = gcry_sexp_find_token( sexp_encrypted, "a", 0 );
506 msg_Err( p_this , "Token 'a' not found in result S-expression" );
507 i_err = VLC_EGENERIC;
511 mpi_output = gcry_sexp_nth_mpi( sexp_token_a, 1, GCRYMPI_FMT_USG );
514 msg_Err( p_this, "Unable to extract MPI from result" );
515 i_err = VLC_EGENERIC;
519 /* Copy encrypted data into char array */
520 i_gcrypt_err = gcry_mpi_aprint( GCRYMPI_FMT_USG, &ps_value, &i_value_size,
522 if ( CheckForGcryptError( p_stream, i_gcrypt_err ) )
524 i_err = VLC_EGENERIC;
528 /* Encode in Base64 */
529 *result = vlc_b64_encode_binary( ps_value, i_value_size );
532 gcry_sexp_release( sexp_rsa_params );
533 gcry_sexp_release( sexp_input );
534 gcry_sexp_release( sexp_encrypted );
535 gcry_sexp_release( sexp_token_a );
536 gcry_mpi_release( mpi_pubkey );
537 gcry_mpi_release( mpi_exp );
538 gcry_mpi_release( mpi_input );
539 gcry_mpi_release( mpi_output );
544 /* Splits the value of a received header.
546 * Example: "Transport: RTP/AVP/TCP;unicast;mode=record;server_port=6000"
548 static int SplitHeader( char **ppsz_next, char **ppsz_name,
551 /* Find semicolon (separator between assignments) */
552 *ppsz_name = strsep( ppsz_next, psz_delim_semicolon );
556 *ppsz_name += strspn( *ppsz_name, psz_delim_space );
559 *ppsz_value = *ppsz_name;
560 strsep( ppsz_value, psz_delim_equal );
568 static void FreeHeader( void *p_value, void *p_data )
570 VLC_UNUSED( p_data );
574 static int ReadStatusLine( vlc_object_t *p_this )
576 sout_stream_t *p_stream = (sout_stream_t*)p_this;
577 sout_stream_sys_t *p_sys = p_stream->p_sys;
578 char *psz_line = NULL;
583 p_sys->psz_last_status_line = net_Gets( p_this, p_sys->i_control_fd,
585 if ( !p_sys->psz_last_status_line )
587 i_result = VLC_EGENERIC;
591 /* Create working copy */
592 psz_line = strdup( p_sys->psz_last_status_line );
596 psz_token = strsep( &psz_next, psz_delim_space );
597 if ( !psz_token || strncmp( psz_token, "RTSP/1.", 7 ) != 0 )
599 msg_Err( p_this, "Unknown protocol (%s)",
600 p_sys->psz_last_status_line );
601 i_result = VLC_EGENERIC;
606 psz_token = strsep( &psz_next, psz_delim_space );
609 msg_Err( p_this, "Request failed (%s)",
610 p_sys->psz_last_status_line );
611 i_result = VLC_EGENERIC;
615 i_result = atoi( psz_token );
623 static int ReadHeader( vlc_object_t *p_this,
624 vlc_dictionary_t *p_resp_headers,
627 sout_stream_t *p_stream = (sout_stream_t*)p_this;
628 sout_stream_sys_t *p_sys = p_stream->p_sys;
629 char *psz_original = NULL;
630 char *psz_line = NULL;
635 int i_err = VLC_SUCCESS;
637 psz_line = net_Gets( p_this, p_sys->i_control_fd, NULL );
640 i_err = VLC_EGENERIC;
644 /* Empty line for response end */
645 if ( psz_line[0] == '\0' )
647 else if ( p_resp_headers )
649 psz_original = strdup( psz_line );
652 psz_token = strsep( &psz_next, psz_delim_colon );
653 if ( !psz_token || psz_next[0] != ' ' )
655 msg_Err( p_this, "Invalid header format (%s)", psz_original );
656 i_err = VLC_EGENERIC;
660 psz_name = psz_token;
661 psz_value = psz_next + 1;
663 vlc_dictionary_insert( p_resp_headers, psz_name, strdup( psz_value ) );
667 free( psz_original );
673 static int WriteAuxHeaders( vlc_object_t *p_this,
674 vlc_dictionary_t *p_req_headers )
676 sout_stream_t *p_stream = (sout_stream_t*)p_this;
677 sout_stream_sys_t *p_sys = p_stream->p_sys;
678 char **ppsz_keys = NULL;
681 int i_err = VLC_SUCCESS;
685 ppsz_keys = vlc_dictionary_all_keys( p_req_headers );
686 for ( i = 0; ppsz_keys[i]; ++i )
688 psz_key = ppsz_keys[i];
689 psz_value = vlc_dictionary_value_for_key( p_req_headers, psz_key );
691 i_rc = net_Printf( p_this, p_sys->i_control_fd, NULL,
692 "%s: %s\r\n", psz_key, psz_value );
695 i_err = VLC_EGENERIC;
701 for ( i = 0; ppsz_keys[i]; ++i )
702 free( ppsz_keys[i] );
708 static int SendRequest( vlc_object_t *p_this, const char *psz_method,
709 const char *psz_content_type, const char *psz_body,
710 vlc_dictionary_t *p_req_headers )
712 sout_stream_t *p_stream = (sout_stream_t*)p_this;
713 sout_stream_sys_t *p_sys = p_stream->p_sys;
714 const unsigned char psz_headers_end[] = "\r\n";
715 size_t i_body_length = 0;
716 int i_err = VLC_SUCCESS;
719 i_rc = net_Printf( p_this, p_sys->i_control_fd, NULL,
721 "User-Agent: " RAOP_USER_AGENT "\r\n"
722 "Client-Instance: %s\r\n"
724 psz_method, p_sys->psz_url,
725 p_sys->psz_client_instance,
729 i_err = VLC_EGENERIC;
733 if ( psz_content_type )
735 i_rc = net_Printf( p_this, p_sys->i_control_fd, NULL,
736 "Content-Type: %s\r\n", psz_content_type );
746 i_body_length = strlen( psz_body );
748 i_rc = net_Printf( p_this, p_sys->i_control_fd, NULL,
749 "Content-Length: %u\r\n",
750 (unsigned int)i_body_length );
760 i_err = WriteAuxHeaders( p_this, p_req_headers );
761 if ( i_err != VLC_SUCCESS )
765 i_rc = net_Write( p_this, p_sys->i_control_fd, NULL,
766 psz_headers_end, sizeof( psz_headers_end ) - 1 );
774 net_Write( p_this, p_sys->i_control_fd, NULL,
775 psz_body, i_body_length );
781 static int ExecRequest( vlc_object_t *p_this, const char *psz_method,
782 const char *psz_content_type, const char *psz_body,
783 vlc_dictionary_t *p_req_headers,
784 vlc_dictionary_t *p_resp_headers )
786 sout_stream_t *p_stream = (sout_stream_t*)p_this;
787 sout_stream_sys_t *p_sys = p_stream->p_sys;
789 int i_err = VLC_SUCCESS;
792 if ( p_sys->i_control_fd < 0 )
794 msg_Err( p_this, "Control connection not open" );
795 i_err = VLC_EGENERIC;
800 i_err = SendRequest( p_this, psz_method, psz_content_type, psz_body,
802 if ( i_err != VLC_SUCCESS )
805 /* Read status line */
806 i_status = ReadStatusLine( p_this );
813 if ( p_resp_headers )
814 vlc_dictionary_clear( p_resp_headers, FreeHeader, NULL );
818 while ( !headers_done )
820 i_err = ReadHeader( p_this, p_resp_headers, &headers_done );
821 if ( i_err != VLC_SUCCESS )
825 if ( i_status != 200 )
827 msg_Err( p_this, "Request failed (%s), status is %d",
828 p_sys->psz_last_status_line, i_status );
829 i_err = VLC_EGENERIC;
834 FREENULL( p_sys->psz_last_status_line );
839 static int AnnounceSDP( vlc_object_t *p_this, char *psz_local,
840 uint32_t i_session_id )
842 sout_stream_t *p_stream = (sout_stream_t*)p_this;
843 sout_stream_sys_t *p_sys = p_stream->p_sys;
844 vlc_dictionary_t req_headers;
845 vlc_dictionary_t resp_headers;
846 unsigned char ps_sac[16];
847 char *psz_sdp = NULL;
848 char *psz_sac_base64 = NULL;
849 char *psz_aes_key_base64 = NULL;
850 char *psz_aes_iv_base64 = NULL;
851 int i_err = VLC_SUCCESS;
854 vlc_dictionary_init( &req_headers, 0 );
855 vlc_dictionary_init( &resp_headers, 0 );
857 /* Encrypt AES key and encode it in Base64 */
858 i_rc = EncryptAesKeyBase64( p_this, &psz_aes_key_base64 );
859 if ( i_rc != VLC_SUCCESS || psz_aes_key_base64 == NULL )
861 i_err = VLC_EGENERIC;
864 RemoveBase64Padding( psz_aes_key_base64 );
866 /* Encode AES IV in Base64 */
867 psz_aes_iv_base64 = vlc_b64_encode_binary( p_sys->ps_aes_iv,
868 sizeof( p_sys->ps_aes_iv ) );
869 if ( psz_aes_iv_base64 == NULL )
871 i_err = VLC_EGENERIC;
874 RemoveBase64Padding( psz_aes_iv_base64 );
876 /* Random bytes for Apple-Challenge header */
877 gcry_randomize( ps_sac, sizeof( ps_sac ), GCRY_STRONG_RANDOM );
879 psz_sac_base64 = vlc_b64_encode_binary( ps_sac, sizeof( ps_sac ) );
880 if ( psz_sac_base64 == NULL )
882 i_err = VLC_EGENERIC;
885 RemoveBase64Padding( psz_sac_base64 );
888 * Note: IPv6 addresses also use "IP4". Make sure not to include the
891 i_rc = asprintf( &psz_sdp,
893 "o=iTunes %u 0 IN IP4 %s\r\n"
897 "m=audio 0 RTP/AVP 96\r\n"
898 "a=rtpmap:96 AppleLossless\r\n"
899 "a=fmtp:96 4096 0 16 40 10 14 2 255 0 0 44100\r\n"
902 i_session_id, psz_local, p_sys->psz_host,
903 psz_aes_key_base64, psz_aes_iv_base64 );
911 /* Build and send request */
912 vlc_dictionary_insert( &req_headers, "Apple-Challenge", psz_sac_base64 );
914 i_err = ExecRequest( p_this, "ANNOUNCE", "application/sdp", psz_sdp,
915 &req_headers, &resp_headers);
916 if ( i_err != VLC_SUCCESS )
920 vlc_dictionary_clear( &req_headers, NULL, NULL );
921 vlc_dictionary_clear( &resp_headers, FreeHeader, NULL );
924 free( psz_sac_base64 );
925 free( psz_aes_key_base64 );
926 free( psz_aes_iv_base64 );
931 static int SendSetup( vlc_object_t *p_this )
933 sout_stream_t *p_stream = (sout_stream_t*)p_this;
934 sout_stream_sys_t *p_sys = p_stream->p_sys;
935 vlc_dictionary_t req_headers;
936 vlc_dictionary_t resp_headers;
937 int i_err = VLC_SUCCESS;
943 vlc_dictionary_init( &req_headers, 0 );
944 vlc_dictionary_init( &resp_headers, 0 );
946 vlc_dictionary_insert( &req_headers, "Transport",
947 ((void*)"RTP/AVP/TCP;unicast;interleaved=0-1;"
950 i_err = ExecRequest( p_this, "SETUP", NULL, NULL,
951 &req_headers, &resp_headers );
952 if ( i_err != VLC_SUCCESS )
955 psz_tmp = vlc_dictionary_value_for_key( &resp_headers, "Session" );
958 msg_Err( p_this, "Missing 'Session' header during setup" );
959 i_err = VLC_EGENERIC;
963 free( p_sys->psz_session );
964 p_sys->psz_session = strdup( psz_tmp );
966 /* Get server_port */
967 psz_next = vlc_dictionary_value_for_key( &resp_headers, "Transport" );
968 while ( SplitHeader( &psz_next, &psz_name, &psz_value ) )
970 if ( psz_value && strcmp( psz_name, "server_port" ) == 0 )
972 p_sys->i_server_port = atoi( psz_value );
977 if ( !p_sys->i_server_port )
979 msg_Err( p_this, "Missing 'server_port' during setup" );
980 i_err = VLC_EGENERIC;
985 psz_next = vlc_dictionary_value_for_key( &resp_headers,
986 "Audio-Jack-Status" );
987 while ( SplitHeader( &psz_next, &psz_name, &psz_value ) )
989 if ( strcmp( psz_name, "type" ) != 0 )
992 if ( strcmp( psz_value, "analog" ) == 0 )
993 p_sys->i_jack_type = JACK_TYPE_ANALOG;
995 else if ( strcmp( psz_value, "digital" ) == 0 )
996 p_sys->i_jack_type = JACK_TYPE_DIGITAL;
1002 vlc_dictionary_clear( &req_headers, NULL, NULL );
1003 vlc_dictionary_clear( &resp_headers, FreeHeader, NULL );
1008 static int SendRecord( vlc_object_t *p_this )
1010 sout_stream_t *p_stream = (sout_stream_t*)p_this;
1011 sout_stream_sys_t *p_sys = p_stream->p_sys;
1012 vlc_dictionary_t req_headers;
1013 vlc_dictionary_t resp_headers;
1014 int i_err = VLC_SUCCESS;
1017 vlc_dictionary_init( &req_headers, 0 );
1018 vlc_dictionary_init( &resp_headers, 0 );
1020 vlc_dictionary_insert( &req_headers, "Range", (void *)"npt=0-" );
1021 vlc_dictionary_insert( &req_headers, "RTP-Info",
1022 (void *)"seq=0;rtptime=0" );
1023 vlc_dictionary_insert( &req_headers, "Session",
1024 (void *)p_sys->psz_session );
1026 i_err = ExecRequest( p_this, "RECORD", NULL, NULL,
1027 &req_headers, &resp_headers );
1028 if ( i_err != VLC_SUCCESS )
1031 psz_value = vlc_dictionary_value_for_key( &resp_headers, "Audio-Latency" );
1033 p_sys->i_audio_latency = atoi( psz_value );
1035 p_sys->i_audio_latency = 0;
1038 vlc_dictionary_clear( &req_headers, NULL, NULL );
1039 vlc_dictionary_clear( &resp_headers, FreeHeader, NULL );
1044 static int SendFlush( vlc_object_t *p_this )
1046 VLC_UNUSED( p_this );
1048 vlc_dictionary_t req_headers;
1049 int i_err = VLC_SUCCESS;
1051 vlc_dictionary_init( &req_headers, 0 );
1053 vlc_dictionary_insert( &req_headers, "RTP-Info",
1054 (void *)"seq=0;rtptime=0" );
1056 i_err = ExecRequest( p_this, "FLUSH", NULL, NULL, &req_headers, NULL );
1057 if ( i_err != VLC_SUCCESS )
1061 vlc_dictionary_clear( &req_headers, NULL, NULL );
1066 static int SendTeardown( vlc_object_t *p_this )
1068 int i_err = VLC_SUCCESS;
1070 i_err = ExecRequest( p_this, "TEARDOWN", NULL, NULL, NULL, NULL );
1071 if ( i_err != VLC_SUCCESS )
1078 static int UpdateVolume( vlc_object_t *p_this )
1080 sout_stream_t *p_stream = (sout_stream_t*)p_this;
1081 sout_stream_sys_t *p_sys = p_stream->p_sys;
1082 vlc_dictionary_t req_headers;
1083 char *psz_parameters = NULL;
1085 int i_err = VLC_SUCCESS;
1088 vlc_dictionary_init( &req_headers, 0 );
1090 /* Our volume is 0..255, RAOP is -144..0 (-144 off, -30..0 on) */
1093 p_sys->i_volume = __MAX( 0, __MIN( p_sys->i_volume, 255 ) );
1095 if ( p_sys->i_volume == 0 )
1098 d_volume = -30 + ( ( (double)p_sys->i_volume ) * 30.0 / 255.0 );
1100 /* Format without using locales */
1101 i_rc = us_asprintf( &psz_parameters, "volume: %0.6f\r\n", d_volume );
1108 vlc_dictionary_insert( &req_headers, "Session",
1109 (void *)p_sys->psz_session );
1111 i_err = ExecRequest( p_this, "SET_PARAMETER",
1112 "text/parameters", psz_parameters,
1113 &req_headers, NULL );
1114 if ( i_err != VLC_SUCCESS )
1118 vlc_dictionary_clear( &req_headers, NULL, NULL );
1119 free( psz_parameters );
1124 static void LogInfo( vlc_object_t *p_this )
1126 sout_stream_t *p_stream = (sout_stream_t*)p_this;
1127 sout_stream_sys_t *p_sys = p_stream->p_sys;
1128 const char *psz_jack_name;
1130 msg_Info( p_this, "Audio latency: %d", p_sys->i_audio_latency );
1132 switch ( p_sys->i_jack_type )
1134 case JACK_TYPE_ANALOG:
1135 psz_jack_name = "analog";
1138 case JACK_TYPE_DIGITAL:
1139 psz_jack_name = "digital";
1142 case JACK_TYPE_NONE:
1144 psz_jack_name = "none";
1148 msg_Info( p_this, "Jack type: %s", psz_jack_name );
1151 static void SendAudio( sout_stream_t *p_stream, block_t *p_buffer )
1153 sout_stream_sys_t *p_sys = p_stream->p_sys;
1154 gcry_error_t i_gcrypt_err;
1157 size_t i_payload_len;
1158 size_t i_realloc_len;
1161 const uint8_t header[16] = {
1162 0x24, 0x00, 0x00, 0x00,
1163 0xf0, 0xff, 0x00, 0x00,
1164 0x00, 0x00, 0x00, 0x00,
1165 0x00, 0x00, 0x00, 0x00,
1170 i_len = sizeof( header ) + p_buffer->i_buffer;
1172 /* Buffer resize needed? */
1173 if ( i_len > p_sys->i_sendbuf_len || p_sys->p_sendbuf == NULL )
1175 /* Grow in blocks of 4K */
1176 i_realloc_len = (1 + (i_len / 4096)) * 4096;
1178 p_sys->p_sendbuf = realloc( p_sys->p_sendbuf, i_realloc_len );
1179 if ( p_sys->p_sendbuf == NULL )
1182 p_sys->i_sendbuf_len = i_realloc_len;
1186 memcpy( p_sys->p_sendbuf, header, sizeof( header ) );
1187 memcpy( p_sys->p_sendbuf + sizeof( header ),
1188 p_buffer->p_buffer, p_buffer->i_buffer );
1190 /* Calculate payload length and update header */
1191 i_payload_len = i_len - 4;
1192 if ( i_payload_len > 0xffff )
1194 msg_Err( p_stream, "Buffer is too long (%u bytes)",
1195 (unsigned int)i_payload_len );
1199 p_sys->p_sendbuf[2] = ( i_payload_len >> 8 ) & 0xff;
1200 p_sys->p_sendbuf[3] = i_payload_len & 0xff;
1203 i_gcrypt_err = gcry_cipher_reset( p_sys->aes_ctx );
1204 if ( CheckForGcryptError( p_stream, i_gcrypt_err ) )
1208 i_gcrypt_err = gcry_cipher_setiv( p_sys->aes_ctx, p_sys->ps_aes_iv,
1209 sizeof( p_sys->ps_aes_iv ) );
1210 if ( CheckForGcryptError( p_stream, i_gcrypt_err ) )
1213 /* Encrypt in place. Only full blocks of 16 bytes are encrypted,
1214 * the rest (0-15 bytes) is left unencrypted.
1217 gcry_cipher_encrypt( p_sys->aes_ctx,
1218 p_sys->p_sendbuf + sizeof( header ),
1219 ( p_buffer->i_buffer / 16 ) * 16,
1221 if ( CheckForGcryptError( p_stream, i_gcrypt_err ) )
1225 rc = net_Write( p_stream, p_sys->i_stream_fd, NULL,
1226 p_sys->p_sendbuf, i_len );
1230 p_next = p_buffer->p_next;
1231 block_Release( p_buffer );
1236 block_ChainRelease( p_buffer );
1241 /*****************************************************************************
1243 *****************************************************************************/
1244 static int Open( vlc_object_t *p_this )
1246 sout_stream_t *p_stream = (sout_stream_t*)p_this;
1247 sout_stream_sys_t *p_sys;
1248 char psz_local[NI_MAXNUMERICHOST];
1249 gcry_error_t i_gcrypt_err;
1250 int i_err = VLC_SUCCESS;
1251 uint32_t i_session_id;
1252 uint64_t i_client_instance;
1256 config_ChainParse( p_stream, SOUT_CFG_PREFIX, ppsz_sout_options,
1259 p_sys = calloc( 1, sizeof( *p_sys ) );
1260 if ( p_sys == NULL )
1266 p_stream->p_sys = p_sys;
1267 p_stream->pf_add = Add;
1268 p_stream->pf_del = Del;
1269 p_stream->pf_send = Send;
1270 p_stream->p_sout->i_out_pace_nocontrol++;
1272 p_sys->i_control_fd = -1;
1273 p_sys->i_stream_fd = -1;
1274 p_sys->i_volume = var_GetInteger( p_stream, SOUT_CFG_PREFIX "volume");
1275 p_sys->i_jack_type = JACK_TYPE_NONE;
1277 p_sys->psz_host = var_GetNonEmptyString( p_stream,
1278 SOUT_CFG_PREFIX "host" );
1279 if ( p_sys->psz_host == NULL )
1281 msg_Err( p_this, "Missing host" );
1282 i_err = VLC_EGENERIC;
1286 var_AddCallback( p_stream, SOUT_CFG_PREFIX "volume",
1287 VolumeCallback, NULL );
1288 p_sys->b_volume_callback = true;
1290 /* Open control connection */
1291 p_sys->i_control_fd = net_ConnectTCP( p_stream, p_sys->psz_host,
1293 if ( p_sys->i_control_fd < 0 )
1295 msg_Err( p_this, "Cannot establish control connection to %s:%d (%m)",
1296 p_sys->psz_host, RAOP_PORT );
1297 i_err = VLC_EGENERIC;
1301 /* Get local IP address */
1302 if ( net_GetSockAddress( p_sys->i_control_fd, psz_local, NULL ) )
1304 msg_Err( p_this, "cannot get local IP address" );
1305 i_err = VLC_EGENERIC;
1309 /* Random session ID */
1310 gcry_randomize( &i_session_id, sizeof( i_session_id ),
1311 GCRY_STRONG_RANDOM );
1313 /* Random client instance */
1314 gcry_randomize( &i_client_instance, sizeof( i_client_instance ),
1315 GCRY_STRONG_RANDOM );
1316 if ( asprintf( &p_sys->psz_client_instance, "%016"PRIX64,
1317 i_client_instance ) < 0 )
1323 /* Build session URL */
1324 if ( asprintf( &p_sys->psz_url, "rtsp://%s/%u",
1325 psz_local, i_session_id ) < 0 )
1331 /* Generate AES key and IV */
1332 gcry_randomize( p_sys->ps_aes_key, sizeof( p_sys->ps_aes_key ),
1333 GCRY_STRONG_RANDOM );
1334 gcry_randomize( p_sys->ps_aes_iv, sizeof( p_sys->ps_aes_iv ),
1335 GCRY_STRONG_RANDOM );
1338 i_gcrypt_err = gcry_cipher_open( &p_sys->aes_ctx, GCRY_CIPHER_AES,
1339 GCRY_CIPHER_MODE_CBC, 0 );
1340 if ( CheckForGcryptError( p_stream, i_gcrypt_err ) )
1342 i_err = VLC_EGENERIC;
1347 i_gcrypt_err = gcry_cipher_setkey( p_sys->aes_ctx, p_sys->ps_aes_key,
1348 sizeof( p_sys->ps_aes_key ) );
1349 if ( CheckForGcryptError( p_stream, i_gcrypt_err ) )
1351 i_err = VLC_EGENERIC;
1355 /* Protocol handshake */
1356 i_err = AnnounceSDP( p_this, psz_local, i_session_id );
1357 if ( i_err != VLC_SUCCESS )
1360 i_err = SendSetup( p_this );
1361 if ( i_err != VLC_SUCCESS )
1364 i_err = SendRecord( p_this );
1365 if ( i_err != VLC_SUCCESS )
1368 i_err = UpdateVolume( p_this );
1369 if ( i_err != VLC_SUCCESS )
1374 /* Open stream connection */
1375 p_sys->i_stream_fd = net_ConnectTCP( p_stream, p_sys->psz_host,
1376 p_sys->i_server_port );
1377 if ( p_sys->i_stream_fd < 0 )
1379 msg_Err( p_this, "Cannot establish stream connection to %s:%d (%m)",
1380 p_sys->psz_host, p_sys->i_server_port );
1381 i_err = VLC_EGENERIC;
1386 if ( i_err != VLC_SUCCESS )
1387 FreeSys( p_this, p_sys );
1393 /*****************************************************************************
1395 *****************************************************************************/
1396 static void Close( vlc_object_t *p_this )
1398 sout_stream_t *p_stream = (sout_stream_t*)p_this;
1399 sout_stream_sys_t *p_sys = p_stream->p_sys;
1401 SendFlush( p_this );
1402 SendTeardown( p_this );
1404 FreeSys( p_this, p_sys );
1406 p_stream->p_sout->i_out_pace_nocontrol--;
1410 /*****************************************************************************
1412 *****************************************************************************/
1413 static sout_stream_id_t *Add( sout_stream_t *p_stream, es_format_t *p_fmt )
1415 sout_stream_sys_t *p_sys = p_stream->p_sys;
1416 sout_stream_id_t *id = NULL;
1418 id = calloc( 1, sizeof( *id ) );
1422 es_format_Copy( &id->fmt, p_fmt );
1424 switch ( id->fmt.i_cat )
1427 if ( id->fmt.i_codec == VLC_CODEC_ALAC )
1429 if ( p_sys->p_audio_stream )
1431 msg_Warn( p_stream, "Only the first Apple Lossless audio "
1434 else if ( id->fmt.audio.i_rate != 44100 ||
1435 id->fmt.audio.i_channels != 2 )
1437 msg_Err( p_stream, "The Apple Lossless audio stream must be "
1438 "encoded with 44100 Hz and 2 channels" );
1442 /* Use this stream */
1443 p_sys->p_audio_stream = id;
1446 else if ( !p_sys->b_alac_warning )
1448 msg_Err( p_stream, "Apple Lossless is the only codec supported. "
1449 "Use the \"transcode\" module for conversion "
1450 "(e.g. \"transcode{acodec=alac,"
1451 "channels=2}\")." );
1452 p_sys->b_alac_warning = true;
1458 /* Leave other stream types alone */
1471 /*****************************************************************************
1473 *****************************************************************************/
1474 static int Del( sout_stream_t *p_stream, sout_stream_id_t *id )
1476 sout_stream_sys_t *p_sys = p_stream->p_sys;
1477 int i_err = VLC_SUCCESS;
1479 if ( p_sys->p_audio_stream == id )
1480 p_sys->p_audio_stream = NULL;
1488 /*****************************************************************************
1490 *****************************************************************************/
1491 static int Send( sout_stream_t *p_stream, sout_stream_id_t *id,
1494 sout_stream_sys_t *p_sys = p_stream->p_sys;
1496 if ( id->fmt.i_cat == AUDIO_ES && id == p_sys->p_audio_stream )
1498 /* SendAudio takes care of releasing the buffers */
1499 SendAudio( p_stream, p_buffer );
1503 block_ChainRelease( p_buffer );
1510 /*****************************************************************************
1511 * VolumeCallback: called when the volume is changed on the fly.
1512 *****************************************************************************/
1513 static int VolumeCallback( vlc_object_t *p_this, char const *psz_cmd,
1514 vlc_value_t oldval, vlc_value_t newval,
1517 VLC_UNUSED(psz_cmd);
1521 sout_stream_t *p_stream = (sout_stream_t*)p_this;
1522 sout_stream_sys_t *p_sys = p_stream->p_sys;
1524 /* TODO: Implement volume change */