]> git.sesse.net Git - vlc/blob - src/stream_output/sap.c
Backport of [11125]
[vlc] / src / stream_output / sap.c
1 /*****************************************************************************
2  * sap.c : SAP announce handler
3  *****************************************************************************
4  * Copyright (C) 2002-2004 VideoLAN
5  * $Id$
6  *
7  * Authors: ClĂ©ment Stenac <zorglub@videolan.org>
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., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27 #include <stdlib.h>                                                /* free() */
28 #include <stdio.h>                                              /* sprintf() */
29 #include <string.h>                                            /* strerror() */
30
31 #include <vlc/vlc.h>
32 #include <vlc/sout.h>
33
34 #include <network.h>
35 #include "charset.h"
36
37 #define SAP_IPV4_ADDR "224.2.127.254" /* Standard port and address for SAP */
38 #define SAP_PORT 9875
39
40 #define SAP_IPV6_ADDR_1 "FF0"
41 #define SAP_IPV6_ADDR_2 "::2:7FFE"
42
43 #define DEFAULT_IPV6_SCOPE '8'
44
45 #define DEFAULT_PORT "1234"
46
47 #undef EXTRA_DEBUG
48
49 /*****************************************************************************
50  * Local prototypes
51  *****************************************************************************/
52 static void RunThread( vlc_object_t *p_this);
53 static int CalculateRate( sap_handler_t *p_sap, sap_address_t *p_address );
54 static int SDPGenerate( sap_handler_t *p_sap, session_descriptor_t *p_session );
55
56 static int announce_SendSAPAnnounce( sap_handler_t *p_sap,
57                                      sap_session_t *p_session );
58
59
60 static int announce_SAPAnnounceAdd( sap_handler_t *p_sap,
61                              session_descriptor_t *p_session,
62                              announce_method_t *p_method );
63
64 static int announce_SAPAnnounceDel( sap_handler_t *p_sap,
65                              session_descriptor_t *p_session );
66 static char *convert_to_utf8( struct sap_handler_t *p_this, char *psz_local );
67
68 #define FREE( p ) if( p ) { free( p ); (p) = NULL; }
69
70
71 /**
72  * Create the SAP handler
73  *
74  * \param p_announce the parent announce_handler
75  * \return the newly created SAP handler or NULL on error
76  */
77 sap_handler_t *announce_SAPHandlerCreate( announce_handler_t *p_announce )
78 {
79     sap_handler_t *p_sap;
80     char *psz_charset;
81
82     p_sap = vlc_object_create( p_announce, sizeof( sap_handler_t ) );
83
84     if( !p_sap )
85     {
86         msg_Err( p_announce, "out of memory" );
87         return NULL;
88     }
89
90     vlc_mutex_init( p_sap, &p_sap->object_lock );
91
92     vlc_current_charset( &psz_charset );
93     p_sap->iconvHandle = vlc_iconv_open( "UTF-8", psz_charset );
94     free( psz_charset );
95     if( p_sap->iconvHandle == (vlc_iconv_t)(-1) )
96     {
97         msg_Warn( p_sap, "Unable to do requested conversion" );
98     }
99
100     p_sap->pf_add = announce_SAPAnnounceAdd;
101     p_sap->pf_del = announce_SAPAnnounceDel;
102
103     p_sap->i_sessions = 0;
104     p_sap->i_addresses = 0;
105     p_sap->i_current_session = 0;
106
107     p_sap->b_control = config_GetInt( p_sap, "sap-flow-control");
108
109     if( vlc_thread_create( p_sap, "sap handler", RunThread,
110                        VLC_THREAD_PRIORITY_LOW, VLC_FALSE ) )
111     {
112         msg_Dbg( p_announce, "Unable to spawn SAP handler thread");
113         free( p_sap );
114         return NULL;
115     };
116     msg_Dbg( p_announce, "thread created, %i sessions", p_sap->i_sessions);
117     return p_sap;
118 }
119
120 /**
121  *  Destroy the SAP handler
122  *  \param p_this the SAP Handler to destroy
123  *  \return nothing
124  */
125 void announce_SAPHandlerDestroy( sap_handler_t *p_sap )
126 {
127     int i;
128
129     vlc_mutex_destroy( &p_sap->object_lock );
130
131     /* Free the remaining sessions */
132     for( i = 0 ; i< p_sap->i_sessions ; i++)
133     {
134         sap_session_t *p_session = p_sap->pp_sessions[i];
135         FREE( p_session->psz_sdp );
136         FREE( p_session->psz_data );
137         REMOVE_ELEM( p_sap->pp_sessions, p_sap->i_sessions , i );
138         FREE( p_session );
139     }
140
141     /* Free the remaining addresses */
142     for( i = 0 ; i< p_sap->i_addresses ; i++)
143     {
144         sap_address_t *p_address = p_sap->pp_addresses[i];
145         FREE( p_address->psz_address );
146         if( p_address->i_rfd > -1 )
147         {
148             net_Close( p_address->i_rfd );
149         }
150         if( p_address->i_wfd > -1 && p_sap->b_control )
151         {
152             net_Close( p_address->i_wfd );
153         }
154         REMOVE_ELEM( p_sap->pp_addresses, p_sap->i_addresses, i );
155         FREE( p_address );
156     }
157
158     if( p_sap->iconvHandle != (vlc_iconv_t)(-1) )
159         vlc_iconv_close( p_sap->iconvHandle );
160
161     /* Free the structure */
162     vlc_object_destroy( p_sap );
163 }
164
165 /**
166  * main SAP handler thread
167  * \param p_this the SAP Handler object
168  * \return nothing
169  */
170 static void RunThread( vlc_object_t *p_this)
171 {
172     sap_handler_t *p_sap = (sap_handler_t*)p_this;
173     sap_session_t *p_session;
174
175     while( !p_sap->b_die )
176     {
177         int i;
178
179         /* If needed, get the rate info */
180         if( p_sap->b_control == VLC_TRUE )
181         {
182             for( i = 0 ; i< p_sap->i_addresses ; i++)
183             {
184                 if( p_sap->pp_addresses[i]->b_enabled == VLC_TRUE )
185                 {
186                     CalculateRate( p_sap, p_sap->pp_addresses[i] );
187                 }
188             }
189         }
190
191         /* Find the session to announce */
192         vlc_mutex_lock( &p_sap->object_lock );
193         if( p_sap->i_sessions > p_sap->i_current_session + 1)
194         {
195             p_sap->i_current_session++;
196         }
197         else if( p_sap->i_sessions > 0)
198         {
199             p_sap->i_current_session = 0;
200         }
201         else
202         {
203             vlc_mutex_unlock( &p_sap->object_lock );
204             msleep( SAP_IDLE );
205             continue;
206         }
207         p_session = p_sap->pp_sessions[p_sap->i_current_session];
208         vlc_mutex_unlock( &p_sap->object_lock );
209
210         /* And announce it */
211         if( p_session->p_address->b_enabled == VLC_TRUE &&
212             p_session->p_address->b_ready == VLC_TRUE )
213         {
214             announce_SendSAPAnnounce( p_sap, p_session );
215         }
216
217         msleep( SAP_IDLE );
218     }
219 }
220
221 /* Add a SAP announce */
222 static int announce_SAPAnnounceAdd( sap_handler_t *p_sap,
223                              session_descriptor_t *p_session,
224                              announce_method_t *p_method )
225 {
226     int i;
227     char *psz_type = "application/sdp";
228     int i_header_size;
229     char *psz_head;
230     vlc_bool_t b_found = VLC_FALSE;
231     sap_session_t *p_sap_session;
232     mtime_t i_hash;
233
234     vlc_mutex_lock( &p_sap->object_lock );
235
236     /* If needed, build the SDP */
237     if( !p_session->psz_sdp )
238     {
239         if ( SDPGenerate( p_sap, p_session ) != VLC_SUCCESS )
240         {
241             vlc_mutex_unlock( &p_sap->object_lock );
242             return VLC_EGENERIC;
243         }
244     }
245
246     if( !p_method->psz_address )
247     {
248         if( p_method->i_ip_version == 6 )
249         {
250             char sz_scope;
251             if( p_method->sz_ipv6_scope )
252             {
253                 sz_scope = p_method->sz_ipv6_scope;
254             }
255             else
256             {
257                 sz_scope = DEFAULT_IPV6_SCOPE;
258             }
259             p_method->psz_address = (char*)malloc( 30*sizeof(char ));
260             sprintf( p_method->psz_address, "%s%c%s",
261                             SAP_IPV6_ADDR_1, sz_scope, SAP_IPV6_ADDR_2 );
262         }
263         else
264         {
265             /* IPv4 */
266             p_method->psz_address = (char*)malloc( 15*sizeof(char) );
267             snprintf(p_method->psz_address, 15, SAP_IPV4_ADDR );
268         }
269     }
270     msg_Dbg( p_sap, "using SAP address: %s",p_method->psz_address);
271
272     /* XXX: Check for dupes */
273     p_sap_session = (sap_session_t*)malloc(sizeof(sap_session_t));
274
275     p_sap_session->psz_sdp = strdup( p_session->psz_sdp );
276     p_sap_session->i_last = 0;
277
278     /* Add the address to the buffer */
279     for( i = 0; i< p_sap->i_addresses; i++)
280     {
281         if( !strcmp( p_method->psz_address,
282              p_sap->pp_addresses[i]->psz_address ) )
283         {
284             p_sap_session->p_address = p_sap->pp_addresses[i];
285             b_found = VLC_TRUE;
286             break;
287         }
288     }
289     if( b_found == VLC_FALSE )
290     {
291         sap_address_t *p_address = (sap_address_t *)
292                                     malloc( sizeof(sap_address_t) );
293         if( !p_address )
294         {
295             msg_Err( p_sap, "out of memory" );
296             return VLC_ENOMEM;
297         }
298         p_address->psz_address = strdup( p_method->psz_address );
299         p_address->i_ip_version = p_method->i_ip_version;
300         p_address->i_port  =  9875;
301         p_address->i_wfd = net_OpenUDP( p_sap, "", 0,
302                                         p_address->psz_address,
303                                         p_address->i_port );
304
305         if( p_sap->b_control == VLC_TRUE )
306         {
307             p_address->i_rfd = net_OpenUDP( p_sap, p_method->psz_address,
308                                             p_address->i_port,
309                                             "", 0 );
310             p_address->i_buff = 0;
311             p_address->b_enabled = VLC_TRUE;
312             p_address->b_ready = VLC_FALSE;
313             p_address->i_limit = 10000; /* 10000 bps */
314             p_address->t1 = 0;
315         }
316         else
317         {
318             p_address->b_enabled = VLC_TRUE;
319             p_address->b_ready = VLC_TRUE;
320             p_address->i_interval = config_GetInt( p_sap,"sap-interval");
321             p_address->i_rfd = -1;
322         }
323
324         if( p_address->i_wfd == -1 || (p_address->i_rfd == -1
325                                         && p_sap->b_control ) )
326         {
327             msg_Warn( p_sap, "disabling address" );
328             p_address->b_enabled = VLC_FALSE;
329         }
330
331         INSERT_ELEM( p_sap->pp_addresses,
332                      p_sap->i_addresses,
333                      p_sap->i_addresses,
334                      p_address );
335         p_sap_session->p_address = p_address;
336     }
337
338     /* Build the SAP Headers */
339     i_header_size = ( p_method->i_ip_version == 6 ? 20 : 8 ) + strlen( psz_type ) + 1;
340     psz_head = (char *) malloc( i_header_size * sizeof( char ) );
341     if( ! psz_head )
342     {
343         msg_Err( p_sap, "out of memory" );
344         return VLC_ENOMEM;
345     }
346
347     psz_head[0] = 0x20; /* Means SAPv1, IPv4, not encrypted, not compressed */
348     psz_head[1] = 0x00; /* No authentification length */
349
350     i_hash = mdate();
351     psz_head[2] = (i_hash & 0xFF00) >> 8; /* Msg id hash */
352     psz_head[3] = (i_hash & 0xFF);        /* Msg id hash 2 */
353
354     if( p_method->i_ip_version == 6 )
355     {
356         /* in_addr_t ip_server = inet_addr( ip ); */
357         psz_head[0] |= 0x10; /* Set IPv6 */
358
359         psz_head[4] = 0x01; /* Source IP  FIXME: we should get the real address */
360         psz_head[5] = 0x02; /* idem */
361         psz_head[6] = 0x03; /* idem */
362         psz_head[7] = 0x04; /* idem */
363
364         psz_head[8] = 0x01; /* Source IP  FIXME: we should get the real address */
365         psz_head[9] = 0x02; /* idem */
366         psz_head[10] = 0x03; /* idem */
367         psz_head[11] = 0x04; /* idem */
368
369         psz_head[12] = 0x01; /* Source IP  FIXME: we should get the real address */
370         psz_head[13] = 0x02; /* idem */
371         psz_head[14] = 0x03; /* idem */
372         psz_head[15] = 0x04; /* idem */
373
374         psz_head[16] = 0x01; /* Source IP  FIXME: we should get the real address */
375         psz_head[17] = 0x02; /* idem */
376         psz_head[18] = 0x03; /* idem */
377         psz_head[19] = 0x04; /* idem */
378
379         strncpy( psz_head + 20, psz_type, 15 );
380     }
381     else
382     {
383         /* in_addr_t ip_server = inet_addr( ip) */
384         /* Source IP  FIXME: we should get the real address */
385         psz_head[4] = 0x01; /* ip_server */
386         psz_head[5] = 0x02; /* ip_server>>8 */
387         psz_head[6] = 0x03; /* ip_server>>16 */
388         psz_head[7] = 0x04; /* ip_server>>24 */
389
390         strncpy( psz_head + 8, psz_type, 15 );
391     }
392
393     psz_head[ i_header_size-1 ] = '\0';
394     p_sap_session->i_length = i_header_size + strlen( p_sap_session->psz_sdp);
395
396     p_sap_session->psz_data = (char *)malloc( sizeof(char)*
397                                               p_sap_session->i_length );
398
399     /* Build the final message */
400     memcpy( p_sap_session->psz_data, psz_head, i_header_size );
401     memcpy( p_sap_session->psz_data+i_header_size, p_sap_session->psz_sdp,
402             strlen( p_sap_session->psz_sdp) );
403
404     free( psz_head );
405
406     /* Enqueue the announce */
407     INSERT_ELEM( p_sap->pp_sessions,
408                  p_sap->i_sessions,
409                  p_sap->i_sessions,
410                  p_sap_session );
411     msg_Dbg( p_sap,"Addresses: %i  Sessions: %i",
412                    p_sap->i_addresses,p_sap->i_sessions);
413
414     /* Remember the SAP session for later deletion */
415     p_session->p_sap = p_sap_session;
416
417     vlc_mutex_unlock( &p_sap->object_lock );
418
419     return VLC_SUCCESS;
420 }
421
422 /* Remove a SAP Announce */
423 static int announce_SAPAnnounceDel( sap_handler_t *p_sap,
424                              session_descriptor_t *p_session )
425 {
426     int i;
427     vlc_mutex_lock( &p_sap->object_lock );
428
429     msg_Dbg( p_sap,"removing SAP announce %p",p_session->p_sap);
430
431     /* Dequeue the announce */
432     for( i = 0; i< p_sap->i_sessions; i++)
433     {
434         if( p_session->p_sap == p_sap->pp_sessions[i] )
435         {
436             REMOVE_ELEM( p_sap->pp_sessions,
437                          p_sap->i_sessions,
438                          i );
439
440             FREE( p_session->p_sap->psz_sdp );
441             FREE( p_session->p_sap->psz_data );
442             free( p_session->p_sap );
443             break;
444         }
445     }
446
447     /* XXX: Dequeue the address too if it is not used anymore
448      * TODO: - address refcount
449              - send a SAP deletion packet */
450
451     msg_Dbg( p_sap,"%i announces remaining", p_sap->i_sessions );
452
453     vlc_mutex_unlock( &p_sap->object_lock );
454
455     return VLC_SUCCESS;
456 }
457
458 static int announce_SendSAPAnnounce( sap_handler_t *p_sap,
459                                      sap_session_t *p_session )
460 {
461     int i_ret;
462
463     /* This announce has never been sent yet */
464     if( p_session->i_last == 0 )
465     {
466         p_session->i_next = mdate()+ p_session->p_address->i_interval*1000000;
467         p_session->i_last = 1;
468         return VLC_SUCCESS;
469     }
470
471     if( p_session->i_next < mdate() )
472     {
473 #ifdef EXTRA_DEBUG
474         msg_Dbg( p_sap, "Sending announce");
475 #endif
476         i_ret = net_Write( p_sap, p_session->p_address->i_wfd, NULL,
477                            p_session->psz_data,
478                            p_session->i_length );
479         if( i_ret  != p_session->i_length )
480         {
481             msg_Warn( p_sap, "SAP send failed on address %s (%i %i)",
482                    p_session->p_address->psz_address,
483                    i_ret, p_session->i_length );
484         }
485         p_session->i_last = p_session->i_next;
486         p_session->i_next = p_session->i_last
487                             + p_session->p_address->i_interval*1000000;
488     }
489     else
490     {
491         return VLC_SUCCESS;
492     }
493     return VLC_SUCCESS;
494 }
495
496 static int SDPGenerate( sap_handler_t *p_sap, session_descriptor_t *p_session )
497 {
498     int64_t i_sdp_id = mdate();
499     int     i_sdp_version = 1 + p_sap->i_sessions + (rand()&0xfff);
500     char *psz_group, *psz_name;
501
502     psz_group = convert_to_utf8( p_sap, p_session->psz_group );
503     psz_name = convert_to_utf8( p_sap, p_session->psz_name );
504
505     /* see the lists in modules/stream_out/rtp.c for compliance stuff */
506     p_session->psz_sdp = (char *)malloc(
507                             sizeof("v=0\r\n"
508                                    "o=- 45383436098 45398  IN IP4 127.0.0.1\r\n" /* FIXME */
509                                    "s=\r\n"
510                                    "t=0 0\r\n"
511                                    "c=IN IP4 /\r\n"
512                                    "m=video  udp\r\n"
513                                    "a=tool:"PACKAGE_STRING"\r\n"
514                                    "a=type:broadcast\r\n")
515                            + strlen( psz_name )
516                            + strlen( p_session->psz_uri ) + 300
517                            + ( psz_group ? strlen( psz_group ) : 0 ) );
518
519     if( p_session->psz_sdp == NULL || psz_name == NULL )
520     {
521         msg_Err( p_sap, "out of memory" );
522         FREE( psz_name );
523         FREE( psz_group );
524         return VLC_ENOMEM;
525     }
526     sprintf( p_session->psz_sdp,
527                             "v=0\r\n"
528                             "o=- "I64Fd" %d IN IP4 127.0.0.1\r\n"
529                             "s=%s\r\n"
530                             "t=0 0\r\n"
531                             "c=IN IP4 %s/%d\r\n"
532                             "m=video %d udp %d\r\n"
533                             "a=tool:"PACKAGE_STRING"\r\n"
534                             "a=type:broadcast\r\n",
535                             i_sdp_id, i_sdp_version,
536                             psz_name,
537                             p_session->psz_uri, p_session->i_ttl,
538                             p_session->i_port, p_session->i_payload );
539     free( psz_name );
540
541     if( psz_group )
542     {
543         sprintf( p_session->psz_sdp, "%sa=x-plgroup:%s\r\n",
544                                      p_session->psz_sdp, psz_group );
545         free( psz_group );
546     }
547
548     msg_Dbg( p_sap, "Generated SDP (%i bytes):\n%s", strlen(p_session->psz_sdp),
549                     p_session->psz_sdp );
550     return VLC_SUCCESS;
551 }
552
553 static int CalculateRate( sap_handler_t *p_sap, sap_address_t *p_address )
554 {
555     int i_read;
556     char buffer[SAP_MAX_BUFFER];
557     int i_tot = 0;
558     mtime_t i_temp;
559     int i_rate;
560
561     if( p_address->t1 == 0 )
562     {
563         p_address->t1 = mdate();
564         return VLC_SUCCESS;
565     }
566     do
567     {
568         /* Might be too slow if we have huge data */
569         i_read = net_ReadNonBlock( p_sap, p_address->i_rfd, NULL, buffer,
570                                    SAP_MAX_BUFFER, 0 );
571         i_tot += i_read;
572     } while( i_read > 0 && i_tot < SAP_MAX_BUFFER );
573
574     i_temp = mdate();
575
576     /* We calculate the rate every 5 seconds */
577     if( i_temp - p_address->t1 < 5000000 )
578     {
579         p_address->i_buff += i_tot;
580         return VLC_SUCCESS;
581     }
582
583     /* Bits/second */
584     i_rate = (int)(8*1000000*((mtime_t)p_address->i_buff + (mtime_t)i_tot ) /
585                         (i_temp - p_address->t1 ));
586
587     p_address->i_limit = 10000;
588
589     p_address->i_interval = ((1000*i_rate / p_address->i_limit) *
590                             (MAX_INTERVAL - MIN_INTERVAL))/1000 + MIN_INTERVAL;
591
592     if( p_address->i_interval > MAX_INTERVAL || p_address->i_interval < 0 )
593     {
594         p_address->i_interval = MAX_INTERVAL;
595     }
596 #ifdef EXTRA_DEBUG
597     msg_Dbg( p_sap,"%s:%i : Rate=%i, Interval = %i s",
598                     p_address->psz_address,p_address->i_port,
599                     i_rate,
600                     p_address->i_interval );
601 #endif
602
603     p_address->b_ready = VLC_TRUE;
604
605     p_address->t1 = i_temp;
606     p_address->i_buff = 0;
607
608     return VLC_SUCCESS;
609 }
610
611
612 static char *convert_to_utf8( struct sap_handler_t *p_this, char *psz_local )
613 {
614     char *psz_unicode, *psz_in, *psz_out;
615     size_t ret, i_in, i_out;
616
617     if( psz_local == NULL )
618         return NULL;
619     if ( p_this->iconvHandle == (vlc_iconv_t)(-1) )
620         return strdup( psz_local );
621
622     psz_in = psz_local;
623     i_in = strlen( psz_local );
624
625     i_out = 6 * i_in;
626     psz_unicode = malloc( i_out + 1 );
627     if( psz_unicode == NULL )
628         return strdup( psz_local );
629     psz_out = psz_unicode;
630
631     ret = vlc_iconv( p_this->iconvHandle,
632                      &psz_in, &i_in, &psz_out, &i_out);
633     if( ret == (size_t)(-1) || i_in )
634     {
635         msg_Warn( p_this, "Failed to convert \"%s\" to UTF-8", psz_local );
636         return strdup( psz_local );
637     }
638     *psz_out = '\0';
639     return psz_unicode;
640 }