]> git.sesse.net Git - vlc/blob - modules/stream_out/raop.c
RTP out: convert s16l to s16b on the fly
[vlc] / modules / stream_out / raop.c
1 /*****************************************************************************
2  * raop.c: Remote Audio Output Protocol streaming support
3  *****************************************************************************
4  * Copyright (C) 2008 the VideoLAN team
5  * $Id$
6  *
7  * Author: Michael Hanselmann
8  *
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.
13  *
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.
18  *
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  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27 #ifdef HAVE_CONFIG_H
28 # include "config.h"
29 #endif
30
31 #include <assert.h>
32
33 #include <gcrypt.h>
34
35 #include <vlc_common.h>
36 #include <vlc_plugin.h>
37 #include <vlc_sout.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>
43 #include <vlc_es.h>
44 #include <vlc_http.h>
45
46 #define RAOP_PORT 5000
47 #define RAOP_USER_AGENT "VLC " VERSION
48
49
50 static const char ps_raop_rsa_pubkey[] =
51     "\xe7\xd7\x44\xf2\xa2\xe2\x78\x8b\x6c\x1f\x55\xa0\x8e\xb7\x05\x44"
52     "\xa8\xfa\x79\x45\xaa\x8b\xe6\xc6\x2c\xe5\xf5\x1c\xbd\xd4\xdc\x68"
53     "\x42\xfe\x3d\x10\x83\xdd\x2e\xde\xc1\xbf\xd4\x25\x2d\xc0\x2e\x6f"
54     "\x39\x8b\xdf\x0e\x61\x48\xea\x84\x85\x5e\x2e\x44\x2d\xa6\xd6\x26"
55     "\x64\xf6\x74\xa1\xf3\x04\x92\x9a\xde\x4f\x68\x93\xef\x2d\xf6\xe7"
56     "\x11\xa8\xc7\x7a\x0d\x91\xc9\xd9\x80\x82\x2e\x50\xd1\x29\x22\xaf"
57     "\xea\x40\xea\x9f\x0e\x14\xc0\xf7\x69\x38\xc5\xf3\x88\x2f\xc0\x32"
58     "\x3d\xd9\xfe\x55\x15\x5f\x51\xbb\x59\x21\xc2\x01\x62\x9f\xd7\x33"
59     "\x52\xd5\xe2\xef\xaa\xbf\x9b\xa0\x48\xd7\xb8\x13\xa2\xb6\x76\x7f"
60     "\x6c\x3c\xcf\x1e\xb4\xce\x67\x3d\x03\x7b\x0d\x2e\xa3\x0c\x5f\xff"
61     "\xeb\x06\xf8\xd0\x8a\xdd\xe4\x09\x57\x1a\x9c\x68\x9f\xef\x10\x72"
62     "\x88\x55\xdd\x8c\xfb\x9a\x8b\xef\x5c\x89\x43\xef\x3b\x5f\xaa\x15"
63     "\xdd\xe6\x98\xbe\xdd\xf3\x59\x96\x03\xeb\x3e\x6f\x61\x37\x2b\xb6"
64     "\x28\xf6\x55\x9f\x59\x9a\x78\xbf\x50\x06\x87\xaa\x7f\x49\x76\xc0"
65     "\x56\x2d\x41\x29\x56\xf8\x98\x9e\x18\xa6\x35\x5b\xd8\x15\x97\x82"
66     "\x5e\x0f\xc8\x75\x34\x3e\xc7\x82\x11\x76\x25\xcd\xbf\x98\x44\x7b";
67
68 static const char ps_raop_rsa_exp[] = "\x01\x00\x01";
69
70 static const char psz_delim_space[] = " ";
71 static const char psz_delim_colon[] = ":";
72 static const char psz_delim_equal[] = "=";
73 static const char psz_delim_semicolon[] = ";";
74
75
76 /*****************************************************************************
77  * Prototypes
78  *****************************************************************************/
79 static int Open( vlc_object_t * );
80 static void Close( vlc_object_t * );
81
82 static sout_stream_id_t *Add( sout_stream_t *, es_format_t * );
83 static int Del( sout_stream_t *, sout_stream_id_t * );
84 static int Send( sout_stream_t *, sout_stream_id_t *, block_t* );
85
86 static int VolumeCallback( vlc_object_t *p_this, char const *psz_cmd,
87                            vlc_value_t oldval, vlc_value_t newval,
88                            void *p_data );
89
90 typedef enum
91 {
92     JACK_TYPE_NONE = 0,
93     JACK_TYPE_ANALOG,
94     JACK_TYPE_DIGITAL,
95 } jack_type_t;
96
97 struct sout_stream_sys_t
98 {
99     /* Input parameters */
100     char *psz_host;
101     char *psz_password;
102     int i_volume;
103
104     /* Plugin status */
105     sout_stream_id_t *p_audio_stream;
106     bool b_alac_warning;
107     bool b_volume_callback;
108
109     /* Connection state */
110     int i_control_fd;
111     int i_stream_fd;
112
113     uint8_t ps_aes_key[16];
114     uint8_t ps_aes_iv[16];
115     gcry_cipher_hd_t aes_ctx;
116
117     char *psz_url;
118     char *psz_client_instance;
119     char *psz_session;
120     char *psz_last_status_line;
121
122     int i_cseq;
123     int i_server_port;
124     int i_audio_latency;
125     int i_jack_type;
126
127     http_auth_t auth;
128
129     /* Send buffer */
130     size_t i_sendbuf_len;
131     uint8_t *p_sendbuf;
132 };
133
134 struct sout_stream_id_t
135 {
136     es_format_t fmt;
137 };
138
139
140 /*****************************************************************************
141  * Module descriptor
142  *****************************************************************************/
143 #define SOUT_CFG_PREFIX "sout-raop-"
144
145 #define HOST_TEXT N_("Host")
146 #define HOST_LONGTEXT N_("Hostname or IP address of target device")
147
148 #define VOLUME_TEXT N_("Volume")
149 #define VOLUME_LONGTEXT N_("Output volume for analog output: 0 for silence, " \
150                            "1..255 from almost silent to very loud.")
151
152 #define PASSWORD_TEXT N_("Password")
153 #define PASSWORD_LONGTEXT N_("Password for target device.")
154
155 #define PASSWORD_FILE_TEXT N_("Password file")
156 #define PASSWORD_FILE_LONGTEXT N_("Read password for target device from file.")
157
158 vlc_module_begin();
159     set_shortname( N_("RAOP") )
160     set_description( N_("Remote Audio Output Protocol stream output") )
161     set_capability( "sout stream", 0 )
162     add_shortcut( "raop" )
163     set_category( CAT_SOUT )
164     set_subcategory( SUBCAT_SOUT_STREAM )
165     add_string( SOUT_CFG_PREFIX "host", "", NULL,
166                 HOST_TEXT, HOST_LONGTEXT, false )
167     add_password( SOUT_CFG_PREFIX "password", NULL, NULL,
168                   PASSWORD_TEXT, PASSWORD_LONGTEXT, false )
169     add_file( SOUT_CFG_PREFIX "password-file", NULL, NULL,
170               PASSWORD_FILE_TEXT, PASSWORD_FILE_LONGTEXT, false )
171     add_integer_with_range( SOUT_CFG_PREFIX "volume", 100, 0, 255, NULL,
172                             VOLUME_TEXT, VOLUME_LONGTEXT, false )
173     set_callbacks( Open, Close )
174 vlc_module_end()
175
176 static const char *const ppsz_sout_options[] = {
177     "host",
178     "password",
179     "password-file",
180     "volume",
181     NULL
182 };
183
184
185 /*****************************************************************************
186  * Utilities:
187  *****************************************************************************/
188 static void FreeSys( vlc_object_t *p_this, sout_stream_sys_t *p_sys )
189 {
190     sout_stream_t *p_stream = (sout_stream_t*)p_this;
191
192     if ( p_sys->i_control_fd >= 0 )
193         net_Close( p_sys->i_control_fd );
194     if ( p_sys->i_stream_fd >= 0 )
195         net_Close( p_sys->i_stream_fd );
196     if ( p_sys->b_volume_callback )
197         var_DelCallback( p_stream, SOUT_CFG_PREFIX "volume",
198                          VolumeCallback, NULL );
199
200     gcry_cipher_close( p_sys->aes_ctx );
201
202     free( p_sys->p_sendbuf );
203     free( p_sys->psz_host );
204     free( p_sys->psz_password );
205     free( p_sys->psz_url );
206     free( p_sys->psz_session );
207     free( p_sys->psz_client_instance );
208     free( p_sys->psz_last_status_line );
209     free( p_sys );
210 }
211
212 static void FreeId( sout_stream_id_t *id )
213 {
214     free( id );
215 }
216
217 static void RemoveBase64Padding( char *str )
218 {
219     char *ps_pos = strchr( str, '=' );
220     if ( ps_pos != NULL )
221         *ps_pos = '\0';
222 }
223
224 static int CheckForGcryptErrorWithLine( sout_stream_t *p_stream,
225                                         gcry_error_t i_gcrypt_err,
226                                         unsigned int i_line )
227 {
228     if ( i_gcrypt_err != GPG_ERR_NO_ERROR )
229     {
230         msg_Err( p_stream, "gcrypt error (line %d): %s", i_line,
231                  gpg_strerror( i_gcrypt_err ) );
232         return 1;
233     }
234
235     return 0;
236 }
237
238 /* Wrapper to pass line number for easier debugging */
239 #define CheckForGcryptError( p_this, i_gcrypt_err ) \
240     CheckForGcryptErrorWithLine( p_this, i_gcrypt_err, __LINE__ )
241
242 /* MGF1 is specified in RFC2437, section 10.2.1. Variables are named after the
243  * specification.
244  */
245 static int MGF1( vlc_object_t *p_this,
246                  unsigned char *mask, size_t l,
247                  const unsigned char *Z, const size_t zLen,
248                  const int Hash )
249 {
250     sout_stream_t *p_stream = (sout_stream_t*)p_this;
251     gcry_error_t i_gcrypt_err;
252     gcry_md_hd_t md_handle = NULL;
253     unsigned int hLen;
254     unsigned char *ps_md;
255     uint32_t counter = 0;
256     uint8_t C[4];
257     size_t i_copylen;
258     int i_err = VLC_SUCCESS;
259
260     assert( mask != NULL );
261     assert( Z != NULL );
262
263     hLen = gcry_md_get_algo_dlen( Hash );
264
265     i_gcrypt_err = gcry_md_open( &md_handle, Hash, 0 );
266     if ( CheckForGcryptError( p_stream, i_gcrypt_err ) )
267     {
268         i_err = VLC_EGENERIC;
269         goto error;
270     }
271
272     while ( l > 0 )
273     {
274         /* 3. For counter from 0 to \lceil{l / hLen}\rceil-1, do the following:
275          * a. Convert counter to an octet string C of length 4 with the
276          *    primitive I2OSP: C = I2OSP (counter, 4)
277          */
278         C[0] = (counter >> 24) & 0xff;
279         C[1] = (counter >> 16) & 0xff;
280         C[2] = (counter >> 8) & 0xff;
281         C[3] = counter & 0xff;
282         ++counter;
283
284         /* b. Concatenate the hash of the seed Z and C to the octet string T:
285          *    T = T || Hash (Z || C)
286          */
287         gcry_md_reset( md_handle );
288         gcry_md_write( md_handle, Z, zLen );
289         gcry_md_write( md_handle, C, 4 );
290         ps_md = gcry_md_read( md_handle, Hash );
291
292         /* 4. Output the leading l octets of T as the octet string mask. */
293         i_copylen = __MIN( l, hLen );
294         memcpy( mask, ps_md, i_copylen );
295         mask += i_copylen;
296         l -= i_copylen;
297     }
298
299 error:
300     gcry_md_close( md_handle );
301
302     return i_err;
303 }
304
305 /* EME-OAEP-ENCODE is specified in RFC2437, section 9.1.1.1. Variables are
306  * named after the specification.
307  */
308 static int AddOaepPadding( vlc_object_t *p_this,
309                            unsigned char *EM, const size_t emLenWithPrefix,
310                            const unsigned char *M, const size_t mLen,
311                            const unsigned char *P, const size_t pLen )
312 {
313     const int Hash = GCRY_MD_SHA1;
314     const unsigned int hLen = gcry_md_get_algo_dlen( Hash );
315     unsigned char *seed = NULL;
316     unsigned char *DB = NULL;
317     unsigned char *dbMask = NULL;
318     unsigned char *seedMask = NULL;
319     size_t emLen;
320     size_t psLen;
321     size_t i;
322     int i_err = VLC_SUCCESS;
323
324     /* Space for 0x00 prefix in EM. */
325     emLen = emLenWithPrefix - 1;
326
327     /* Step 2:
328      * If ||M|| > emLen-2hLen-1 then output "message too long" and stop.
329      */
330     if ( mLen > (emLen - (2 * hLen) - 1) )
331     {
332         msg_Err( p_this , "Message too long" );
333         goto error;
334     }
335
336     /* Step 3:
337      * Generate an octet string PS consisting of emLen-||M||-2hLen-1 zero
338      * octets. The length of PS may be 0.
339      */
340     psLen = emLen - mLen - (2 * hLen) - 1;
341
342     /*
343      * Step 5:
344      * Concatenate pHash, PS, the message M, and other padding to form a data
345      * block DB as: DB = pHash || PS || 01 || M
346      */
347     DB = calloc( 1, hLen + psLen + 1 + mLen );
348     dbMask = calloc( 1, emLen - hLen );
349     seedMask = calloc( 1, hLen );
350
351     if ( DB == NULL || dbMask == NULL || seedMask == NULL )
352     {
353         i_err = VLC_ENOMEM;
354         goto error;
355     }
356
357     /* Step 4:
358      * Let pHash = Hash(P), an octet string of length hLen.
359      */
360     gcry_md_hash_buffer( Hash, DB, P, pLen );
361
362     /* Step 3:
363      * Generate an octet string PS consisting of emLen-||M||-2hLen-1 zero
364      * octets. The length of PS may be 0.
365      */
366     memset( DB + hLen, 0, psLen );
367
368     /* Step 5:
369      * Concatenate pHash, PS, the message M, and other padding to form a data
370      * block DB as: DB = pHash || PS || 01 || M
371      */
372     DB[hLen + psLen] = 0x01;
373     memcpy( DB + hLen + psLen + 1, M, mLen );
374
375     /* Step 6:
376      * Generate a random octet string seed of length hLen
377      */
378     seed = gcry_random_bytes( hLen, GCRY_STRONG_RANDOM );
379     if ( seed == NULL )
380     {
381         i_err = VLC_ENOMEM;
382         goto error;
383     }
384
385     /* Step 7:
386      * Let dbMask = MGF(seed, emLen-hLen).
387      */
388     i_err = MGF1( p_this, dbMask, emLen - hLen, seed, hLen, Hash );
389     if ( i_err != VLC_SUCCESS )
390         goto error;
391
392     /* Step 8:
393      * Let maskedDB = DB \xor dbMask.
394      */
395     for ( i = 0; i < (emLen - hLen); ++i )
396         DB[i] ^= dbMask[i];
397
398     /* Step 9:
399      * Let seedMask = MGF(maskedDB, hLen).
400      */
401     i_err = MGF1( p_this, seedMask, hLen, DB, emLen - hLen, Hash );
402     if ( i_err != VLC_SUCCESS )
403         goto error;
404
405     /* Step 10:
406      * Let maskedSeed = seed \xor seedMask.
407      */
408     for ( i = 0; i < hLen; ++i )
409         seed[i] ^= seedMask[i];
410
411     /* Step 11:
412      * Let EM = maskedSeed || maskedDB.
413      */
414     assert( (1 + hLen + (hLen + psLen + 1 + mLen)) == emLenWithPrefix );
415     EM[0] = 0x00;
416     memcpy( EM + 1, seed, hLen );
417     memcpy( EM + 1 + hLen, DB, hLen + psLen + 1 + mLen );
418
419     /* Step 12:
420      * Output EM.
421      */
422
423 error:
424     free( DB );
425     free( dbMask );
426     free( seedMask );
427     free( seed );
428
429     return i_err;
430 }
431
432 static int EncryptAesKeyBase64( vlc_object_t *p_this, char **result )
433 {
434     sout_stream_t *p_stream = (sout_stream_t*)p_this;
435     sout_stream_sys_t *p_sys = p_stream->p_sys;
436     gcry_error_t i_gcrypt_err;
437     gcry_sexp_t sexp_rsa_params = NULL;
438     gcry_sexp_t sexp_input = NULL;
439     gcry_sexp_t sexp_encrypted = NULL;
440     gcry_sexp_t sexp_token_a = NULL;
441     gcry_mpi_t mpi_pubkey = NULL;
442     gcry_mpi_t mpi_exp = NULL;
443     gcry_mpi_t mpi_input = NULL;
444     gcry_mpi_t mpi_output = NULL;
445     unsigned char ps_padded_key[256];
446     unsigned char *ps_value;
447     size_t i_value_size;
448     int i_err;
449
450     /* Add RSA-OAES-SHA1 padding */
451     i_err = AddOaepPadding( p_this,
452                             ps_padded_key, sizeof( ps_padded_key ),
453                             p_sys->ps_aes_key, sizeof( p_sys->ps_aes_key ),
454                             NULL, 0 );
455     if ( i_err != VLC_SUCCESS )
456         goto error;
457     i_err = VLC_EGENERIC;
458
459     /* Read public key */
460     i_gcrypt_err = gcry_mpi_scan( &mpi_pubkey, GCRYMPI_FMT_USG,
461                                   ps_raop_rsa_pubkey,
462                                   sizeof( ps_raop_rsa_pubkey ) - 1, NULL );
463     if ( CheckForGcryptError( p_stream, i_gcrypt_err ) )
464         goto error;
465
466     /* Read exponent */
467     i_gcrypt_err = gcry_mpi_scan( &mpi_exp, GCRYMPI_FMT_USG, ps_raop_rsa_exp,
468                                   sizeof( ps_raop_rsa_exp ) - 1, NULL );
469     if ( CheckForGcryptError( p_stream, i_gcrypt_err ) )
470         goto error;
471
472     /* If the input data starts with a set bit (0x80), gcrypt thinks it's a
473      * signed integer and complains. Prefixing it with a zero byte (\0)
474      * works, but involves more work. Converting it to an MPI in our code is
475      * cleaner.
476      */
477     i_gcrypt_err = gcry_mpi_scan( &mpi_input, GCRYMPI_FMT_USG,
478                                   ps_padded_key, sizeof( ps_padded_key ),
479                                   NULL);
480     if ( CheckForGcryptError( p_stream, i_gcrypt_err ) )
481         goto error;
482
483     /* Build S-expression with RSA parameters */
484     i_gcrypt_err = gcry_sexp_build( &sexp_rsa_params, NULL,
485                                     "(public-key(rsa(n %m)(e %m)))",
486                                     mpi_pubkey, mpi_exp );
487     if ( CheckForGcryptError( p_stream, i_gcrypt_err ) )
488         goto error;
489
490     /* Build S-expression for data */
491     i_gcrypt_err = gcry_sexp_build( &sexp_input, NULL, "(data(value %m))",
492                                     mpi_input );
493     if ( CheckForGcryptError( p_stream, i_gcrypt_err ) )
494         goto error;
495
496     /* Encrypt data */
497     i_gcrypt_err = gcry_pk_encrypt( &sexp_encrypted, sexp_input,
498                                     sexp_rsa_params );
499     if ( CheckForGcryptError( p_stream, i_gcrypt_err ) )
500         goto error;
501
502     /* Extract encrypted data */
503     sexp_token_a = gcry_sexp_find_token( sexp_encrypted, "a", 0 );
504     if ( !sexp_token_a )
505     {
506         msg_Err( p_this , "Token 'a' not found in result S-expression" );
507         goto error;
508     }
509
510     mpi_output = gcry_sexp_nth_mpi( sexp_token_a, 1, GCRYMPI_FMT_USG );
511     if ( !mpi_output )
512     {
513         msg_Err( p_this, "Unable to extract MPI from result" );
514         goto error;
515     }
516
517     /* Copy encrypted data into char array */
518     i_gcrypt_err = gcry_mpi_aprint( GCRYMPI_FMT_USG, &ps_value, &i_value_size,
519                                     mpi_output );
520     if ( CheckForGcryptError( p_stream, i_gcrypt_err ) )
521     {
522         goto error;
523     }
524
525     /* Encode in Base64 */
526     *result = vlc_b64_encode_binary( ps_value, i_value_size );
527     i_err = VLC_SUCCESS;
528
529 error:
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 );
538
539     return i_err;
540 }
541
542 static char *ReadPasswordFile( vlc_object_t *p_this, const char *psz_path )
543 {
544     FILE *p_file = NULL;
545     char *psz_password = NULL;
546     char *psz_newline;
547     char ps_buffer[256];
548
549     p_file = utf8_fopen( psz_path, "rt" );
550     if ( p_file == NULL )
551     {
552         msg_Err( p_this, "Unable to open password file '%s': %m", psz_path );
553         goto error;
554     }
555
556     /* Read one line only */
557     if ( fgets( ps_buffer, sizeof( ps_buffer ), p_file ) == NULL )
558     {
559         if ( ferror( p_file ) )
560         {
561             msg_Err( p_this, "Error reading '%s': %m", psz_path );
562             goto error;
563         }
564
565         /* Nothing was read, but there was no error either. Maybe the file is
566          * empty. Not all implementations of fgets(3) write \0 to the output
567          * buffer in this case.
568          */
569         ps_buffer[0] = '\0';
570
571     } else {
572         /* Replace first newline with '\0' */
573         psz_newline = strchr( ps_buffer, '\n' );
574         if ( psz_newline != NULL )
575             *psz_newline = '\0';
576     }
577
578     if ( strlen( ps_buffer ) == 0 ) {
579         msg_Err( p_this, "No password could be read from '%s'", psz_path );
580         goto error;
581     }
582
583     psz_password = strdup( ps_buffer );
584
585 error:
586     if ( p_file != NULL )
587         fclose( p_file );
588
589     return psz_password;
590 }
591
592 /* Splits the value of a received header.
593  *
594  * Example: "Transport: RTP/AVP/TCP;unicast;mode=record;server_port=6000"
595  */
596 static int SplitHeader( char **ppsz_next, char **ppsz_name,
597                         char **ppsz_value )
598 {
599     /* Find semicolon (separator between assignments) */
600     *ppsz_name = strsep( ppsz_next, psz_delim_semicolon );
601     if ( *ppsz_name )
602     {
603         /* Skip spaces */
604         *ppsz_name += strspn( *ppsz_name, psz_delim_space );
605
606         /* Get value */
607         *ppsz_value = *ppsz_name;
608         strsep( ppsz_value, psz_delim_equal );
609     }
610     else
611         *ppsz_value = NULL;
612
613     return !!*ppsz_name;
614 }
615
616 static void FreeHeader( void *p_value, void *p_data )
617 {
618     VLC_UNUSED( p_data );
619     free( p_value );
620 }
621
622 static int ReadStatusLine( vlc_object_t *p_this )
623 {
624     sout_stream_t *p_stream = (sout_stream_t*)p_this;
625     sout_stream_sys_t *p_sys = p_stream->p_sys;
626     char *psz_line = NULL;
627     char *psz_token;
628     char *psz_next;
629     int i_result = VLC_EGENERIC;
630
631     p_sys->psz_last_status_line = net_Gets( p_this, p_sys->i_control_fd,
632                                             NULL );
633     if ( !p_sys->psz_last_status_line )
634         goto error;
635
636     /* Create working copy */
637     psz_line = strdup( p_sys->psz_last_status_line );
638     psz_next = psz_line;
639
640     /* Protocol field */
641     psz_token = strsep( &psz_next, psz_delim_space );
642     if ( !psz_token || strncmp( psz_token, "RTSP/1.", 7 ) != 0 )
643     {
644         msg_Err( p_this, "Unknown protocol (%s)",
645                  p_sys->psz_last_status_line );
646         goto error;
647     }
648
649     /* Status field */
650     psz_token = strsep( &psz_next, psz_delim_space );
651     if ( !psz_token )
652     {
653         msg_Err( p_this, "Request failed (%s)",
654                  p_sys->psz_last_status_line );
655         goto error;
656     }
657
658     i_result = atoi( psz_token );
659
660 error:
661     free( psz_line );
662
663     return i_result;
664 }
665
666 static int ReadHeader( vlc_object_t *p_this,
667                        vlc_dictionary_t *p_resp_headers,
668                        int *done )
669 {
670     sout_stream_t *p_stream = (sout_stream_t*)p_this;
671     sout_stream_sys_t *p_sys = p_stream->p_sys;
672     char *psz_original = NULL;
673     char *psz_line = NULL;
674     char *psz_token;
675     char *psz_next;
676     char *psz_name;
677     char *psz_value;
678     int i_err = VLC_SUCCESS;
679
680     psz_line = net_Gets( p_this, p_sys->i_control_fd, NULL );
681     if ( !psz_line )
682     {
683         i_err = VLC_EGENERIC;
684         goto error;
685     }
686
687     /* Empty line for response end */
688     if ( psz_line[0] == '\0' )
689         *done = 1;
690     else
691     {
692         psz_original = strdup( psz_line );
693         psz_next = psz_line;
694
695         psz_token = strsep( &psz_next, psz_delim_colon );
696         if ( !psz_token || psz_next[0] != ' ' )
697         {
698             msg_Err( p_this, "Invalid header format (%s)", psz_original );
699             i_err = VLC_EGENERIC;
700             goto error;
701         }
702
703         psz_name = psz_token;
704         psz_value = psz_next + 1;
705
706         vlc_dictionary_insert( p_resp_headers, psz_name, strdup( psz_value ) );
707     }
708
709 error:
710     free( psz_original );
711     free( psz_line );
712
713     return i_err;
714 }
715
716 static int WriteAuxHeaders( vlc_object_t *p_this,
717                             vlc_dictionary_t *p_req_headers )
718 {
719     sout_stream_t *p_stream = (sout_stream_t*)p_this;
720     sout_stream_sys_t *p_sys = p_stream->p_sys;
721     char **ppsz_keys = NULL;
722     char *psz_key;
723     char *psz_value;
724     int i_err = VLC_SUCCESS;
725     int i_rc;
726     size_t i;
727
728     ppsz_keys = vlc_dictionary_all_keys( p_req_headers );
729     for ( i = 0; ppsz_keys[i]; ++i )
730     {
731         psz_key = ppsz_keys[i];
732         psz_value = vlc_dictionary_value_for_key( p_req_headers, psz_key );
733
734         i_rc = net_Printf( p_this, p_sys->i_control_fd, NULL,
735                            "%s: %s\r\n", psz_key, psz_value );
736         if ( i_rc < 0 )
737         {
738             i_err = VLC_EGENERIC;
739             goto error;
740         }
741     }
742
743 error:
744     for ( i = 0; ppsz_keys[i]; ++i )
745         free( ppsz_keys[i] );
746     free( ppsz_keys );
747
748     return i_err;
749 }
750
751 static int SendRequest( vlc_object_t *p_this, const char *psz_method,
752                         const char *psz_content_type, const char *psz_body,
753                         vlc_dictionary_t *p_req_headers )
754 {
755     sout_stream_t *p_stream = (sout_stream_t*)p_this;
756     sout_stream_sys_t *p_sys = p_stream->p_sys;
757     const unsigned char psz_headers_end[] = "\r\n";
758     size_t i_body_length = 0;
759     int i_err = VLC_SUCCESS;
760     int i_rc;
761
762     i_rc = net_Printf( p_this, p_sys->i_control_fd, NULL,
763                        "%s %s RTSP/1.0\r\n"
764                        "User-Agent: " RAOP_USER_AGENT "\r\n"
765                        "Client-Instance: %s\r\n"
766                        "CSeq: %d\r\n",
767                        psz_method, p_sys->psz_url,
768                        p_sys->psz_client_instance,
769                        ++p_sys->i_cseq );
770     if ( i_rc < 0 )
771     {
772         i_err = VLC_EGENERIC;
773         goto error;
774     }
775
776     if ( psz_content_type )
777     {
778         i_rc = net_Printf( p_this, p_sys->i_control_fd, NULL,
779                            "Content-Type: %s\r\n", psz_content_type );
780         if ( i_rc < 0 )
781         {
782             i_err = VLC_ENOMEM;
783             goto error;
784         }
785     }
786
787     if ( psz_body )
788     {
789         i_body_length = strlen( psz_body );
790
791         i_rc = net_Printf( p_this, p_sys->i_control_fd, NULL,
792                            "Content-Length: %u\r\n",
793                            (unsigned int)i_body_length );
794         if ( i_rc < 0 )
795         {
796             i_err = VLC_ENOMEM;
797             goto error;
798         }
799     }
800
801     i_err = WriteAuxHeaders( p_this, p_req_headers );
802     if ( i_err != VLC_SUCCESS )
803         goto error;
804
805     i_rc = net_Write( p_this, p_sys->i_control_fd, NULL,
806                       psz_headers_end, sizeof( psz_headers_end ) - 1 );
807     if ( i_rc < 0 )
808     {
809         i_err = VLC_ENOMEM;
810         goto error;
811     }
812
813     if ( psz_body )
814         net_Write( p_this, p_sys->i_control_fd, NULL,
815                    psz_body, i_body_length );
816
817 error:
818     return i_err;
819 }
820
821 static int ParseAuthenticateHeader( vlc_object_t *p_this,
822                                     vlc_dictionary_t *p_resp_headers )
823 {
824     sout_stream_t *p_stream = (sout_stream_t*)p_this;
825     sout_stream_sys_t *p_sys = p_stream->p_sys;
826     char *psz_auth;
827     int i_err = VLC_SUCCESS;
828
829     psz_auth = vlc_dictionary_value_for_key( p_resp_headers,
830                                              "WWW-Authenticate" );
831     if ( psz_auth == NULL )
832     {
833         msg_Err( p_this, "HTTP 401 response missing "
834                          "WWW-Authenticate header" );
835         i_err = VLC_EGENERIC;
836         goto error;
837     }
838
839     http_auth_ParseWwwAuthenticateHeader( p_this, &p_sys->auth, psz_auth );
840
841 error:
842     return i_err;
843 }
844
845 static int ExecRequest( vlc_object_t *p_this, const char *psz_method,
846                         const char *psz_content_type, const char *psz_body,
847                         vlc_dictionary_t *p_req_headers,
848                         vlc_dictionary_t *p_resp_headers )
849 {
850     sout_stream_t *p_stream = (sout_stream_t*)p_this;
851     sout_stream_sys_t *p_sys = p_stream->p_sys;
852     char *psz_authorization = NULL;
853     int headers_done;
854     int i_err = VLC_SUCCESS;
855     int i_status;
856     int i_auth_state;
857
858     if ( p_sys->i_control_fd < 0 )
859     {
860         msg_Err( p_this, "Control connection not open" );
861         i_err = VLC_EGENERIC;
862         goto error;
863     }
864
865     i_auth_state = 0;
866     while ( 1 )
867     {
868         /* Send header only when Digest authentication is used */
869         if ( p_sys->psz_password != NULL && p_sys->auth.psz_nonce != NULL )
870         {
871             FREENULL( psz_authorization );
872
873             psz_authorization =
874                 http_auth_FormatAuthorizationHeader( p_this, &p_sys->auth,
875                                                      psz_method,
876                                                      p_sys->psz_url, "",
877                                                      p_sys->psz_password );
878             if ( psz_authorization == NULL )
879             {
880                 i_err = VLC_EGENERIC;
881                 goto error;
882             }
883
884             vlc_dictionary_insert( p_req_headers, "Authorization",
885                                    psz_authorization );
886         }
887
888         /* Send request */
889         i_err = SendRequest( p_this, psz_method, psz_content_type, psz_body,
890                              p_req_headers);
891         if ( i_err != VLC_SUCCESS )
892             goto error;
893
894         /* Read status line */
895         i_status = ReadStatusLine( p_this );
896         if ( i_status < 0 )
897         {
898             i_err = i_status;
899             goto error;
900         }
901
902         vlc_dictionary_clear( p_resp_headers, FreeHeader, NULL );
903
904         /* Read headers */
905         headers_done = 0;
906         while ( !headers_done )
907         {
908             i_err = ReadHeader( p_this, p_resp_headers, &headers_done );
909             if ( i_err != VLC_SUCCESS )
910                 goto error;
911         }
912
913         if ( i_status == 200 )
914             /* Request successful */
915             break;
916         else if ( i_status == 401 )
917         {
918             /* Authorization required */
919             if ( i_auth_state == 1 || p_sys->psz_password == NULL )
920             {
921                 msg_Err( p_this, "Access denied, password invalid" );
922                 i_err = VLC_EGENERIC;
923                 goto error;
924             }
925
926             i_err = ParseAuthenticateHeader( p_this, p_resp_headers );
927             if ( i_err != VLC_SUCCESS )
928                 goto error;
929
930             i_auth_state = 1;
931         }
932         else
933         {
934             msg_Err( p_this, "Request failed (%s), status is %d",
935                      p_sys->psz_last_status_line, i_status );
936             i_err = VLC_EGENERIC;
937             goto error;
938         }
939     }
940
941 error:
942     FREENULL( p_sys->psz_last_status_line );
943     free( psz_authorization );
944
945     return i_err;
946 }
947
948 static int AnnounceSDP( vlc_object_t *p_this, char *psz_local,
949                         uint32_t i_session_id )
950 {
951     sout_stream_t *p_stream = (sout_stream_t*)p_this;
952     sout_stream_sys_t *p_sys = p_stream->p_sys;
953     vlc_dictionary_t req_headers;
954     vlc_dictionary_t resp_headers;
955     unsigned char ps_sac[16];
956     char *psz_sdp = NULL;
957     char *psz_sac_base64 = NULL;
958     char *psz_aes_key_base64 = NULL;
959     char *psz_aes_iv_base64 = NULL;
960     int i_err = VLC_SUCCESS;
961     int i_rc;
962
963     vlc_dictionary_init( &req_headers, 0 );
964     vlc_dictionary_init( &resp_headers, 0 );
965
966     /* Encrypt AES key and encode it in Base64 */
967     i_rc = EncryptAesKeyBase64( p_this, &psz_aes_key_base64 );
968     if ( i_rc != VLC_SUCCESS || psz_aes_key_base64 == NULL )
969     {
970         i_err = VLC_EGENERIC;
971         goto error;
972     }
973     RemoveBase64Padding( psz_aes_key_base64 );
974
975     /* Encode AES IV in Base64 */
976     psz_aes_iv_base64 = vlc_b64_encode_binary( p_sys->ps_aes_iv,
977                                                sizeof( p_sys->ps_aes_iv ) );
978     if ( psz_aes_iv_base64 == NULL )
979     {
980         i_err = VLC_EGENERIC;
981         goto error;
982     }
983     RemoveBase64Padding( psz_aes_iv_base64 );
984
985     /* Random bytes for Apple-Challenge header */
986     gcry_randomize( ps_sac, sizeof( ps_sac ), GCRY_STRONG_RANDOM );
987
988     psz_sac_base64 = vlc_b64_encode_binary( ps_sac, sizeof( ps_sac ) );
989     if ( psz_sac_base64 == NULL )
990     {
991         i_err = VLC_EGENERIC;
992         goto error;
993     }
994     RemoveBase64Padding( psz_sac_base64 );
995
996     /* Build SDP
997      * Note: IPv6 addresses also use "IP4". Make sure not to include the
998      * scope ID.
999      */
1000     i_rc = asprintf( &psz_sdp,
1001                      "v=0\r\n"
1002                      "o=iTunes %u 0 IN IP4 %s\r\n"
1003                      "s=iTunes\r\n"
1004                      "c=IN IP4 %s\r\n"
1005                      "t=0 0\r\n"
1006                      "m=audio 0 RTP/AVP 96\r\n"
1007                      "a=rtpmap:96 AppleLossless\r\n"
1008                      "a=fmtp:96 4096 0 16 40 10 14 2 255 0 0 44100\r\n"
1009                      "a=rsaaeskey:%s\r\n"
1010                      "a=aesiv:%s\r\n",
1011                      i_session_id, psz_local, p_sys->psz_host,
1012                      psz_aes_key_base64, psz_aes_iv_base64 );
1013
1014     if ( i_rc < 0 )
1015     {
1016         i_err = VLC_ENOMEM;
1017         goto error;
1018     }
1019
1020     /* Build and send request */
1021     vlc_dictionary_insert( &req_headers, "Apple-Challenge", psz_sac_base64 );
1022
1023     i_err = ExecRequest( p_this, "ANNOUNCE", "application/sdp", psz_sdp,
1024                          &req_headers, &resp_headers);
1025     if ( i_err != VLC_SUCCESS )
1026         goto error;
1027
1028 error:
1029     vlc_dictionary_clear( &req_headers, NULL, NULL );
1030     vlc_dictionary_clear( &resp_headers, FreeHeader, NULL );
1031
1032     free( psz_sdp );
1033     free( psz_sac_base64 );
1034     free( psz_aes_key_base64 );
1035     free( psz_aes_iv_base64 );
1036
1037     return i_err;
1038 }
1039
1040 static int SendSetup( vlc_object_t *p_this )
1041 {
1042     sout_stream_t *p_stream = (sout_stream_t*)p_this;
1043     sout_stream_sys_t *p_sys = p_stream->p_sys;
1044     vlc_dictionary_t req_headers;
1045     vlc_dictionary_t resp_headers;
1046     int i_err = VLC_SUCCESS;
1047     char *psz_tmp;
1048     char *psz_next;
1049     char *psz_name;
1050     char *psz_value;
1051
1052     vlc_dictionary_init( &req_headers, 0 );
1053     vlc_dictionary_init( &resp_headers, 0 );
1054
1055     vlc_dictionary_insert( &req_headers, "Transport",
1056                            ((void*)"RTP/AVP/TCP;unicast;interleaved=0-1;"
1057                             "mode=record") );
1058
1059     i_err = ExecRequest( p_this, "SETUP", NULL, NULL,
1060                          &req_headers, &resp_headers );
1061     if ( i_err != VLC_SUCCESS )
1062         goto error;
1063
1064     psz_tmp = vlc_dictionary_value_for_key( &resp_headers, "Session" );
1065     if ( !psz_tmp )
1066     {
1067         msg_Err( p_this, "Missing 'Session' header during setup" );
1068         i_err = VLC_EGENERIC;
1069         goto error;
1070     }
1071
1072     free( p_sys->psz_session );
1073     p_sys->psz_session = strdup( psz_tmp );
1074
1075     /* Get server_port */
1076     psz_next = vlc_dictionary_value_for_key( &resp_headers, "Transport" );
1077     while ( SplitHeader( &psz_next, &psz_name, &psz_value ) )
1078     {
1079         if ( psz_value && strcmp( psz_name, "server_port" ) == 0 )
1080         {
1081             p_sys->i_server_port = atoi( psz_value );
1082             break;
1083         }
1084     }
1085
1086     if ( !p_sys->i_server_port )
1087     {
1088         msg_Err( p_this, "Missing 'server_port' during setup" );
1089         i_err = VLC_EGENERIC;
1090         goto error;
1091     }
1092
1093     /* Get jack type */
1094     psz_next = vlc_dictionary_value_for_key( &resp_headers,
1095                                              "Audio-Jack-Status" );
1096     while ( SplitHeader( &psz_next, &psz_name, &psz_value ) )
1097     {
1098         if ( strcmp( psz_name, "type" ) != 0 )
1099             continue;
1100
1101         if ( strcmp( psz_value, "analog" ) == 0 )
1102             p_sys->i_jack_type = JACK_TYPE_ANALOG;
1103
1104         else if ( strcmp( psz_value, "digital" ) == 0 )
1105             p_sys->i_jack_type = JACK_TYPE_DIGITAL;
1106
1107         break;
1108     }
1109
1110 error:
1111     vlc_dictionary_clear( &req_headers, NULL, NULL );
1112     vlc_dictionary_clear( &resp_headers, FreeHeader, NULL );
1113
1114     return i_err;
1115 }
1116
1117 static int SendRecord( vlc_object_t *p_this )
1118 {
1119     sout_stream_t *p_stream = (sout_stream_t*)p_this;
1120     sout_stream_sys_t *p_sys = p_stream->p_sys;
1121     vlc_dictionary_t req_headers;
1122     vlc_dictionary_t resp_headers;
1123     int i_err = VLC_SUCCESS;
1124     char *psz_value;
1125
1126     vlc_dictionary_init( &req_headers, 0 );
1127     vlc_dictionary_init( &resp_headers, 0 );
1128
1129     vlc_dictionary_insert( &req_headers, "Range", (void *)"npt=0-" );
1130     vlc_dictionary_insert( &req_headers, "RTP-Info",
1131                            (void *)"seq=0;rtptime=0" );
1132     vlc_dictionary_insert( &req_headers, "Session",
1133                            (void *)p_sys->psz_session );
1134
1135     i_err = ExecRequest( p_this, "RECORD", NULL, NULL,
1136                          &req_headers, &resp_headers );
1137     if ( i_err != VLC_SUCCESS )
1138         goto error;
1139
1140     psz_value = vlc_dictionary_value_for_key( &resp_headers, "Audio-Latency" );
1141     if ( psz_value )
1142         p_sys->i_audio_latency = atoi( psz_value );
1143     else
1144         p_sys->i_audio_latency = 0;
1145
1146 error:
1147     vlc_dictionary_clear( &req_headers, NULL, NULL );
1148     vlc_dictionary_clear( &resp_headers, FreeHeader, NULL );
1149
1150     return i_err;
1151 }
1152
1153 static int SendFlush( vlc_object_t *p_this )
1154 {
1155     VLC_UNUSED( p_this );
1156     vlc_dictionary_t resp_headers;
1157     vlc_dictionary_t req_headers;
1158     int i_err = VLC_SUCCESS;
1159
1160     vlc_dictionary_init( &req_headers, 0 );
1161     vlc_dictionary_init( &resp_headers, 0 );
1162
1163     vlc_dictionary_insert( &req_headers, "RTP-Info",
1164                            (void *)"seq=0;rtptime=0" );
1165
1166     i_err = ExecRequest( p_this, "FLUSH", NULL, NULL,
1167                          &req_headers, &resp_headers );
1168     if ( i_err != VLC_SUCCESS )
1169         goto error;
1170
1171 error:
1172     vlc_dictionary_clear( &req_headers, NULL, NULL );
1173     vlc_dictionary_clear( &resp_headers, FreeHeader, NULL );
1174
1175     return i_err;
1176 }
1177
1178 static int SendTeardown( vlc_object_t *p_this )
1179 {
1180     vlc_dictionary_t resp_headers;
1181     vlc_dictionary_t req_headers;
1182     int i_err = VLC_SUCCESS;
1183
1184     vlc_dictionary_init( &req_headers, 0 );
1185     vlc_dictionary_init( &resp_headers, 0 );
1186
1187     i_err = ExecRequest( p_this, "TEARDOWN", NULL, NULL,
1188                          &req_headers, &resp_headers );
1189     if ( i_err != VLC_SUCCESS )
1190         goto error;
1191
1192 error:
1193     vlc_dictionary_clear( &req_headers, NULL, NULL );
1194     vlc_dictionary_clear( &resp_headers, FreeHeader, NULL );
1195
1196     return i_err;
1197 }
1198
1199 static int UpdateVolume( vlc_object_t *p_this )
1200 {
1201     sout_stream_t *p_stream = (sout_stream_t*)p_this;
1202     sout_stream_sys_t *p_sys = p_stream->p_sys;
1203     vlc_dictionary_t req_headers;
1204     vlc_dictionary_t resp_headers;
1205     char *psz_parameters = NULL;
1206     double d_volume;
1207     int i_err = VLC_SUCCESS;
1208     int i_rc;
1209
1210     vlc_dictionary_init( &req_headers, 0 );
1211     vlc_dictionary_init( &resp_headers, 0 );
1212
1213     /* Our volume is 0..255, RAOP is -144..0 (-144 off, -30..0 on) */
1214
1215     /* Limit range */
1216     p_sys->i_volume = __MAX( 0, __MIN( p_sys->i_volume, 255 ) );
1217
1218     if ( p_sys->i_volume == 0 )
1219         d_volume = -144.0;
1220     else
1221         d_volume = -30 + ( ( (double)p_sys->i_volume ) * 30.0 / 255.0 );
1222
1223     /* Format without using locales */
1224     i_rc = us_asprintf( &psz_parameters, "volume: %0.6f\r\n", d_volume );
1225     if ( i_rc < 0 )
1226     {
1227         i_err = VLC_ENOMEM;
1228         goto error;
1229     }
1230
1231     vlc_dictionary_insert( &req_headers, "Session",
1232                            (void *)p_sys->psz_session );
1233
1234     i_err = ExecRequest( p_this, "SET_PARAMETER",
1235                          "text/parameters", psz_parameters,
1236                          &req_headers, &resp_headers );
1237     if ( i_err != VLC_SUCCESS )
1238         goto error;
1239
1240 error:
1241     vlc_dictionary_clear( &req_headers, NULL, NULL );
1242     vlc_dictionary_clear( &resp_headers, FreeHeader, NULL );
1243     free( psz_parameters );
1244
1245     return i_err;
1246 }
1247
1248 static void LogInfo( vlc_object_t *p_this )
1249 {
1250     sout_stream_t *p_stream = (sout_stream_t*)p_this;
1251     sout_stream_sys_t *p_sys = p_stream->p_sys;
1252     const char *psz_jack_name;
1253
1254     msg_Info( p_this, "Audio latency: %d", p_sys->i_audio_latency );
1255
1256     switch ( p_sys->i_jack_type )
1257     {
1258         case JACK_TYPE_ANALOG:
1259             psz_jack_name = "analog";
1260             break;
1261
1262         case JACK_TYPE_DIGITAL:
1263             psz_jack_name = "digital";
1264             break;
1265
1266         case JACK_TYPE_NONE:
1267         default:
1268             psz_jack_name = "none";
1269             break;
1270     }
1271
1272     msg_Info( p_this, "Jack type: %s", psz_jack_name );
1273 }
1274
1275 static void SendAudio( sout_stream_t *p_stream, block_t *p_buffer )
1276 {
1277     sout_stream_sys_t *p_sys = p_stream->p_sys;
1278     gcry_error_t i_gcrypt_err;
1279     block_t *p_next;
1280     size_t i_len;
1281     size_t i_payload_len;
1282     size_t i_realloc_len;
1283     int rc;
1284
1285     const uint8_t header[16] = {
1286         0x24, 0x00, 0x00, 0x00,
1287         0xf0, 0xff, 0x00, 0x00,
1288         0x00, 0x00, 0x00, 0x00,
1289         0x00, 0x00, 0x00, 0x00,
1290     };
1291
1292     while ( p_buffer )
1293     {
1294         i_len = sizeof( header ) + p_buffer->i_buffer;
1295
1296         /* Buffer resize needed? */
1297         if ( i_len > p_sys->i_sendbuf_len || p_sys->p_sendbuf == NULL )
1298         {
1299             /* Grow in blocks of 4K */
1300             i_realloc_len = (1 + (i_len / 4096)) * 4096;
1301
1302             p_sys->p_sendbuf = realloc( p_sys->p_sendbuf, i_realloc_len );
1303             if ( p_sys->p_sendbuf == NULL )
1304                 goto error;
1305
1306             p_sys->i_sendbuf_len = i_realloc_len;
1307         }
1308
1309         /* Fill buffer */
1310         memcpy( p_sys->p_sendbuf, header, sizeof( header ) );
1311         memcpy( p_sys->p_sendbuf + sizeof( header ),
1312                 p_buffer->p_buffer, p_buffer->i_buffer );
1313
1314         /* Calculate payload length and update header */
1315         i_payload_len = i_len - 4;
1316         if ( i_payload_len > 0xffff )
1317         {
1318             msg_Err( p_stream, "Buffer is too long (%u bytes)",
1319                      (unsigned int)i_payload_len );
1320             goto error;
1321         }
1322
1323         p_sys->p_sendbuf[2] = ( i_payload_len >> 8 ) & 0xff;
1324         p_sys->p_sendbuf[3] = i_payload_len & 0xff;
1325
1326         /* Reset cipher */
1327         i_gcrypt_err = gcry_cipher_reset( p_sys->aes_ctx );
1328         if ( CheckForGcryptError( p_stream, i_gcrypt_err ) )
1329             goto error;
1330
1331         /* Set IV */
1332         i_gcrypt_err = gcry_cipher_setiv( p_sys->aes_ctx, p_sys->ps_aes_iv,
1333                                           sizeof( p_sys->ps_aes_iv ) );
1334         if ( CheckForGcryptError( p_stream, i_gcrypt_err ) )
1335             goto error;
1336
1337         /* Encrypt in place. Only full blocks of 16 bytes are encrypted,
1338          * the rest (0-15 bytes) is left unencrypted.
1339          */
1340         i_gcrypt_err =
1341             gcry_cipher_encrypt( p_sys->aes_ctx,
1342                                  p_sys->p_sendbuf + sizeof( header ),
1343                                  ( p_buffer->i_buffer / 16 ) * 16,
1344                                  NULL, 0 );
1345         if ( CheckForGcryptError( p_stream, i_gcrypt_err ) )
1346             goto error;
1347
1348         /* Send data */
1349         rc = net_Write( p_stream, p_sys->i_stream_fd, NULL,
1350                         p_sys->p_sendbuf, i_len );
1351         if ( rc < 0 )
1352             goto error;
1353
1354         p_next = p_buffer->p_next;
1355         block_Release( p_buffer );
1356         p_buffer = p_next;
1357     }
1358
1359 error:
1360     block_ChainRelease( p_buffer );
1361     return;
1362 }
1363
1364
1365 /*****************************************************************************
1366  * Open:
1367  *****************************************************************************/
1368 static int Open( vlc_object_t *p_this )
1369 {
1370     sout_stream_t *p_stream = (sout_stream_t*)p_this;
1371     sout_stream_sys_t *p_sys;
1372     char psz_local[NI_MAXNUMERICHOST];
1373     char *psz_pwfile = NULL;
1374     gcry_error_t i_gcrypt_err;
1375     int i_err = VLC_SUCCESS;
1376     uint32_t i_session_id;
1377     uint64_t i_client_instance;
1378
1379     vlc_gcrypt_init();
1380
1381     config_ChainParse( p_stream, SOUT_CFG_PREFIX, ppsz_sout_options,
1382                        p_stream->p_cfg );
1383
1384     p_sys = calloc( 1, sizeof( *p_sys ) );
1385     if ( p_sys == NULL )
1386     {
1387         i_err = VLC_ENOMEM;
1388         goto error;
1389     }
1390
1391     p_stream->p_sys = p_sys;
1392     p_stream->pf_add = Add;
1393     p_stream->pf_del = Del;
1394     p_stream->pf_send = Send;
1395     p_stream->p_sout->i_out_pace_nocontrol++;
1396
1397     p_sys->i_control_fd = -1;
1398     p_sys->i_stream_fd = -1;
1399     p_sys->i_volume = var_GetInteger( p_stream, SOUT_CFG_PREFIX "volume");
1400     p_sys->i_jack_type = JACK_TYPE_NONE;
1401
1402     http_auth_Init( &p_sys->auth );
1403
1404     p_sys->psz_host = var_GetNonEmptyString( p_stream,
1405                                              SOUT_CFG_PREFIX "host" );
1406     if ( p_sys->psz_host == NULL )
1407     {
1408         msg_Err( p_this, "Missing host" );
1409         i_err = VLC_EGENERIC;
1410         goto error;
1411     }
1412
1413     p_sys->psz_password = var_GetNonEmptyString( p_stream,
1414                                                  SOUT_CFG_PREFIX "password" );
1415     if ( p_sys->psz_password == NULL )
1416     {
1417         /* Try password file instead */
1418         psz_pwfile = var_GetNonEmptyString( p_stream,
1419                                             SOUT_CFG_PREFIX "password-file" );
1420         if ( psz_pwfile != NULL )
1421         {
1422             p_sys->psz_password = ReadPasswordFile( p_this, psz_pwfile );
1423             if ( p_sys->psz_password == NULL )
1424             {
1425                 i_err = VLC_EGENERIC;
1426                 goto error;
1427             }
1428         }
1429     }
1430
1431     if ( p_sys->psz_password != NULL )
1432         msg_Info( p_this, "Using password authentication" );
1433
1434     var_AddCallback( p_stream, SOUT_CFG_PREFIX "volume",
1435                      VolumeCallback, NULL );
1436     p_sys->b_volume_callback = true;
1437
1438     /* Open control connection */
1439     p_sys->i_control_fd = net_ConnectTCP( p_stream, p_sys->psz_host,
1440                                           RAOP_PORT );
1441     if ( p_sys->i_control_fd < 0 )
1442     {
1443         msg_Err( p_this, "Cannot establish control connection to %s:%d (%m)",
1444                  p_sys->psz_host, RAOP_PORT );
1445         i_err = VLC_EGENERIC;
1446         goto error;
1447     }
1448
1449     /* Get local IP address */
1450     if ( net_GetSockAddress( p_sys->i_control_fd, psz_local, NULL ) )
1451     {
1452         msg_Err( p_this, "cannot get local IP address" );
1453         i_err = VLC_EGENERIC;
1454         goto error;
1455     }
1456
1457     /* Random session ID */
1458     gcry_randomize( &i_session_id, sizeof( i_session_id ),
1459                     GCRY_STRONG_RANDOM );
1460
1461     /* Random client instance */
1462     gcry_randomize( &i_client_instance, sizeof( i_client_instance ),
1463                     GCRY_STRONG_RANDOM );
1464     if ( asprintf( &p_sys->psz_client_instance, "%016"PRIX64,
1465                    i_client_instance ) < 0 )
1466     {
1467         i_err = VLC_ENOMEM;
1468         goto error;
1469     }
1470
1471     /* Build session URL */
1472     if ( asprintf( &p_sys->psz_url, "rtsp://%s/%u",
1473                    psz_local, i_session_id ) < 0 )
1474     {
1475         i_err = VLC_ENOMEM;
1476         goto error;
1477     }
1478
1479     /* Generate AES key and IV */
1480     gcry_randomize( p_sys->ps_aes_key, sizeof( p_sys->ps_aes_key ),
1481                     GCRY_STRONG_RANDOM );
1482     gcry_randomize( p_sys->ps_aes_iv, sizeof( p_sys->ps_aes_iv ),
1483                     GCRY_STRONG_RANDOM );
1484
1485     /* Setup AES */
1486     i_gcrypt_err = gcry_cipher_open( &p_sys->aes_ctx, GCRY_CIPHER_AES,
1487                                      GCRY_CIPHER_MODE_CBC, 0 );
1488     if ( CheckForGcryptError( p_stream, i_gcrypt_err ) )
1489     {
1490         i_err = VLC_EGENERIC;
1491         goto error;
1492     }
1493
1494     /* Set key */
1495     i_gcrypt_err = gcry_cipher_setkey( p_sys->aes_ctx, p_sys->ps_aes_key,
1496                                        sizeof( p_sys->ps_aes_key ) );
1497     if ( CheckForGcryptError( p_stream, i_gcrypt_err ) )
1498     {
1499         i_err = VLC_EGENERIC;
1500         goto error;
1501     }
1502
1503     /* Protocol handshake */
1504     i_err = AnnounceSDP( p_this, psz_local, i_session_id );
1505     if ( i_err != VLC_SUCCESS )
1506         goto error;
1507
1508     i_err = SendSetup( p_this );
1509     if ( i_err != VLC_SUCCESS )
1510         goto error;
1511
1512     i_err = SendRecord( p_this );
1513     if ( i_err != VLC_SUCCESS )
1514         goto error;
1515
1516     i_err = UpdateVolume( p_this );
1517     if ( i_err != VLC_SUCCESS )
1518         goto error;
1519
1520     LogInfo( p_this );
1521
1522     /* Open stream connection */
1523     p_sys->i_stream_fd = net_ConnectTCP( p_stream, p_sys->psz_host,
1524                                          p_sys->i_server_port );
1525     if ( p_sys->i_stream_fd < 0 )
1526     {
1527         msg_Err( p_this, "Cannot establish stream connection to %s:%d (%m)",
1528                  p_sys->psz_host, p_sys->i_server_port );
1529         i_err = VLC_EGENERIC;
1530         goto error;
1531     }
1532
1533 error:
1534     free( psz_pwfile );
1535
1536     if ( i_err != VLC_SUCCESS )
1537         FreeSys( p_this, p_sys );
1538
1539     return i_err;
1540 }
1541
1542
1543 /*****************************************************************************
1544  * Close:
1545  *****************************************************************************/
1546 static void Close( vlc_object_t *p_this )
1547 {
1548     sout_stream_t *p_stream = (sout_stream_t*)p_this;
1549     sout_stream_sys_t *p_sys = p_stream->p_sys;
1550
1551     SendFlush( p_this );
1552     SendTeardown( p_this );
1553
1554     FreeSys( p_this, p_sys );
1555
1556     p_stream->p_sout->i_out_pace_nocontrol--;
1557 }
1558
1559
1560 /*****************************************************************************
1561  * Add:
1562  *****************************************************************************/
1563 static sout_stream_id_t *Add( sout_stream_t *p_stream, es_format_t *p_fmt )
1564 {
1565     sout_stream_sys_t *p_sys = p_stream->p_sys;
1566     sout_stream_id_t *id = NULL;
1567
1568     id = calloc( 1, sizeof( *id ) );
1569     if ( id == NULL )
1570         goto error;
1571
1572     es_format_Copy( &id->fmt, p_fmt );
1573
1574     switch ( id->fmt.i_cat )
1575     {
1576     case AUDIO_ES:
1577         if ( id->fmt.i_codec == VLC_CODEC_ALAC )
1578         {
1579             if ( p_sys->p_audio_stream )
1580             {
1581                 msg_Warn( p_stream, "Only the first Apple Lossless audio "
1582                                     "stream is used" );
1583             }
1584             else if ( id->fmt.audio.i_rate != 44100 ||
1585                       id->fmt.audio.i_channels != 2 )
1586             {
1587                 msg_Err( p_stream, "The Apple Lossless audio stream must be "
1588                                    "encoded with 44100 Hz and 2 channels" );
1589             }
1590             else
1591             {
1592                 /* Use this stream */
1593                 p_sys->p_audio_stream = id;
1594             }
1595         }
1596         else if ( !p_sys->b_alac_warning )
1597         {
1598             msg_Err( p_stream, "Apple Lossless is the only codec supported. "
1599                                "Use the \"transcode\" module for conversion "
1600                                "(e.g. \"transcode{acodec=alac,"
1601                                "channels=2}\")." );
1602             p_sys->b_alac_warning = true;
1603         }
1604
1605         break;
1606
1607     default:
1608         /* Leave other stream types alone */
1609         break;
1610     }
1611
1612     return id;
1613
1614 error:
1615     FreeId( id );
1616
1617     return NULL;
1618 }
1619
1620
1621 /*****************************************************************************
1622  * Del:
1623  *****************************************************************************/
1624 static int Del( sout_stream_t *p_stream, sout_stream_id_t *id )
1625 {
1626     sout_stream_sys_t *p_sys = p_stream->p_sys;
1627     int i_err = VLC_SUCCESS;
1628
1629     if ( p_sys->p_audio_stream == id )
1630         p_sys->p_audio_stream = NULL;
1631
1632     FreeId( id );
1633
1634     return i_err;
1635 }
1636
1637
1638 /*****************************************************************************
1639  * Send:
1640  *****************************************************************************/
1641 static int Send( sout_stream_t *p_stream, sout_stream_id_t *id,
1642                  block_t *p_buffer )
1643 {
1644     sout_stream_sys_t *p_sys = p_stream->p_sys;
1645
1646     if ( id->fmt.i_cat == AUDIO_ES && id == p_sys->p_audio_stream )
1647     {
1648         /* SendAudio takes care of releasing the buffers */
1649         SendAudio( p_stream, p_buffer );
1650     }
1651     else
1652     {
1653         block_ChainRelease( p_buffer );
1654     }
1655
1656     return VLC_SUCCESS;
1657 }
1658
1659
1660 /*****************************************************************************
1661  * VolumeCallback: called when the volume is changed on the fly.
1662  *****************************************************************************/
1663 static int VolumeCallback( vlc_object_t *p_this, char const *psz_cmd,
1664                            vlc_value_t oldval, vlc_value_t newval,
1665                            void *p_data )
1666 {
1667     VLC_UNUSED(psz_cmd);
1668     VLC_UNUSED(oldval);
1669     VLC_UNUSED(p_data);
1670     VLC_UNUSED(newval);
1671     sout_stream_t *p_stream = (sout_stream_t*)p_this;
1672     sout_stream_sys_t *p_sys = p_stream->p_sys;
1673
1674     /* TODO: Implement volume change */
1675     VLC_UNUSED(p_sys);
1676
1677     return VLC_SUCCESS;
1678 }