]> git.sesse.net Git - vlc/blob - modules/access_output/udp.c
Simplistic RTCP sender for access output
[vlc] / modules / access_output / udp.c
1 /*****************************************************************************
2  * udp.c
3  *****************************************************************************
4  * Copyright (C) 2001-2007 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *          Eric Petit <titer@videolan.org>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23  *****************************************************************************/
24
25 /*****************************************************************************
26  * Preamble
27  *****************************************************************************/
28 #include <vlc/vlc.h>
29
30 #include <stdlib.h>
31 #include <sys/types.h>
32 #include <sys/stat.h>
33 #include <string.h>
34 #include <errno.h>
35 #include <fcntl.h>
36 #include <assert.h>
37
38 #include <vlc_sout.h>
39 #include <vlc_block.h>
40
41 #ifdef HAVE_UNISTD_H
42 #   include <unistd.h>
43 #endif
44
45 #ifdef WIN32
46 #   include <winsock2.h>
47 #   include <ws2tcpip.h>
48 #else
49 #   include <sys/socket.h>
50 #endif
51
52 #include <vlc_network.h>
53
54 #if defined (HAVE_NETINET_UDPLITE_H)
55 # include <netinet/udplite.h>
56 #elif defined (__linux__)
57 # define UDPLITE_SEND_CSCOV     10
58 # define UDPLITE_RECV_CSCOV     11
59 #endif
60
61 #ifndef IPPROTO_UDPLITE
62 # define IPPROTO_UDPLITE 136 /* from IANA */
63 #endif
64 #ifndef SOL_UDPLITE
65 # define SOL_UDPLITE IPPROTO_UDPLITE
66 #endif
67
68 #define MAX_EMPTY_BLOCKS 200
69
70 #if defined(WIN32) || defined(UNDER_CE)
71 # define WINSOCK_STRERROR_SIZE 20
72 static const char *winsock_strerror( char *buf )
73 {
74     snprintf( buf, WINSOCK_STRERROR_SIZE, "Winsock error %d",
75               WSAGetLastError( ) );
76     buf[WINSOCK_STRERROR_SIZE - 1] = '\0';
77     return buf;
78 }
79 #endif
80
81 /*****************************************************************************
82  * Module descriptor
83  *****************************************************************************/
84 static int  Open ( vlc_object_t * );
85 static void Close( vlc_object_t * );
86
87 #define SOUT_CFG_PREFIX "sout-udp-"
88
89 #define CACHING_TEXT N_("Caching value (ms)")
90 #define CACHING_LONGTEXT N_( \
91     "Default caching value for outbound UDP streams. This " \
92     "value should be set in milliseconds." )
93
94 #define GROUP_TEXT N_("Group packets")
95 #define GROUP_LONGTEXT N_("Packets can be sent one by one at the right time " \
96                           "or by groups. You can choose the number " \
97                           "of packets that will be sent at a time. It " \
98                           "helps reducing the scheduling load on " \
99                           "heavily-loaded systems." )
100 #define RAW_TEXT N_("Raw write")
101 #define RAW_LONGTEXT N_("Packets will be sent " \
102                        "directly, without trying to fill the MTU (ie, " \
103                        "without trying to make the biggest possible packets " \
104                        "in order to improve streaming)." )
105 #define AUTO_MCAST_TEXT N_("Automatic multicast streaming")
106 #define AUTO_MCAST_LONGTEXT N_("Allocates an outbound multicast address " \
107                                "automatically.")
108
109 vlc_module_begin();
110     set_description( _("UDP stream output") );
111     set_shortname( "UDP" );
112     set_category( CAT_SOUT );
113     set_subcategory( SUBCAT_SOUT_ACO );
114     add_integer( SOUT_CFG_PREFIX "caching", DEFAULT_PTS_DELAY / 1000, NULL, CACHING_TEXT, CACHING_LONGTEXT, VLC_TRUE );
115     add_integer( SOUT_CFG_PREFIX "group", 1, NULL, GROUP_TEXT, GROUP_LONGTEXT,
116                                  VLC_TRUE );
117     add_suppressed_integer( SOUT_CFG_PREFIX "late" );
118     add_bool( SOUT_CFG_PREFIX "raw",  0, NULL, RAW_TEXT, RAW_LONGTEXT,
119                                  VLC_TRUE );
120     add_bool( SOUT_CFG_PREFIX "auto-mcast", 0, NULL, AUTO_MCAST_TEXT,
121               AUTO_MCAST_LONGTEXT, VLC_TRUE );
122
123     set_capability( "sout access", 100 );
124     add_shortcut( "udp" );
125     add_shortcut( "rtp" ); // Will work only with ts muxer
126     add_shortcut( "udplite" );
127     set_callbacks( Open, Close );
128 vlc_module_end();
129
130 /*****************************************************************************
131  * Exported prototypes
132  *****************************************************************************/
133
134 static const char *ppsz_sout_options[] = {
135     "auto-mcast",
136     "caching",
137     "group",
138     "raw",
139     NULL
140 };
141
142 /* Options handled by the libvlc network core */
143 static const char *ppsz_core_options[] = {
144     "dscp",
145     "ttl",
146     "miface",
147     "miface-addr",
148     NULL
149 };
150
151 static int  Write   ( sout_access_out_t *, block_t * );
152 static int  WriteRaw( sout_access_out_t *, block_t * );
153 static int  Seek    ( sout_access_out_t *, off_t  );
154
155 static void ThreadWrite( vlc_object_t * );
156 static block_t *NewUDPPacket( sout_access_out_t *, mtime_t );
157 static const char *MakeRandMulticast (int family, char *buf, size_t buflen);
158
159 typedef struct sout_access_thread_t
160 {
161     VLC_COMMON_MEMBERS
162
163     sout_instance_t *p_sout;
164
165     block_fifo_t *p_fifo;
166
167     int         i_handle;
168
169     int64_t     i_caching;
170     int         i_group;
171
172     block_fifo_t *p_empty_blocks;
173
174     uint32_t sent_pkts;
175     uint32_t sent_bytes;
176     size_t   rtcp_size;
177     int      rtcp_handle;
178     uint8_t  rtcp_data[28 + 8 + (2 * 257)];
179
180 } sout_access_thread_t;
181
182 struct sout_access_out_sys_t
183 {
184     int                 i_mtu;
185
186     vlc_bool_t          b_rtpts;  // 1 if add rtp/ts header
187     vlc_bool_t          b_mtu_warning;
188     uint16_t            i_sequence_number;
189     uint32_t            i_ssrc;
190
191     block_t             *p_buffer;
192
193     sout_access_thread_t *p_thread;
194
195 };
196
197 #define DEFAULT_PORT 1234
198 #define RTP_HEADER_LENGTH 12
199
200 static int OpenRTCP (sout_access_out_t *obj);
201 static void SendRTCP (sout_access_thread_t *obj, uint32_t timestamp);
202 static void CloseRTCP (sout_access_thread_t *obj);
203
204 /*****************************************************************************
205  * Open: open the file
206  *****************************************************************************/
207 /* FIXME: lots of leaks in error handling here! */
208 static int Open( vlc_object_t *p_this )
209 {
210     sout_access_out_t       *p_access = (sout_access_out_t*)p_this;
211     sout_access_out_sys_t   *p_sys;
212
213     char                *psz_dst_addr = NULL;
214     int                 i_dst_port, proto = IPPROTO_UDP, cscov = 8;
215     const char          *protoname = "UDP";
216
217     int                 i_handle;
218
219     vlc_value_t         val;
220
221     config_ChainParse( p_access, SOUT_CFG_PREFIX,
222                        ppsz_sout_options, p_access->p_cfg );
223     config_ChainParse( p_access, "",
224                        ppsz_core_options, p_access->p_cfg );
225
226     if( !( p_sys = calloc ( 1, sizeof( sout_access_out_sys_t ) ) ) )
227     {
228         msg_Err( p_access, "not enough memory" );
229         return VLC_EGENERIC;
230     }
231     p_access->p_sys = p_sys;
232
233     if( p_access->psz_access != NULL )
234     {
235         if (strcmp (p_access->psz_access, "rtp") == 0)
236             p_sys->b_rtpts = VLC_TRUE;
237         if (strcmp (p_access->psz_access, "udplite") == 0)
238         {
239             protoname = "UDP-Lite";
240             proto = IPPROTO_UDPLITE;
241             p_sys->b_rtpts = VLC_TRUE;
242         }
243     }
244     if (p_sys->b_rtpts)
245         cscov += RTP_HEADER_LENGTH;
246
247     i_dst_port = DEFAULT_PORT;
248     if (var_CreateGetBool (p_access, SOUT_CFG_PREFIX"auto-mcast"))
249     {
250         char buf[INET6_ADDRSTRLEN];
251         if (MakeRandMulticast (AF_INET, buf, sizeof (buf)) != NULL)
252             psz_dst_addr = strdup (buf);
253     }
254     else
255     {
256         char *psz_parser = psz_dst_addr = strdup( p_access->psz_path );
257
258         if (psz_parser[0] == '[')
259             psz_parser = strchr (psz_parser, ']');
260
261         psz_parser = strchr (psz_parser, ':');
262         if (psz_parser != NULL)
263         {
264             *psz_parser++ = '\0';
265             i_dst_port = atoi (psz_parser);
266         }
267     }
268
269     if (var_Create (p_access, "dst-port", VLC_VAR_INTEGER)
270      || var_Create (p_access, "src-port", VLC_VAR_INTEGER)
271      || var_Create (p_access, "dst-addr", VLC_VAR_STRING)
272      || var_Create (p_access, "src-addr", VLC_VAR_STRING))
273         return VLC_ENOMEM;
274
275     p_sys->p_thread =
276         vlc_object_create( p_access, sizeof( sout_access_thread_t ) );
277     if( !p_sys->p_thread )
278     {
279         msg_Err( p_access, "out of memory" );
280         return VLC_ENOMEM;
281     }
282
283     vlc_object_attach( p_sys->p_thread, p_access );
284     p_sys->p_thread->p_sout = p_access->p_sout;
285     p_sys->p_thread->b_die  = 0;
286     p_sys->p_thread->b_error= 0;
287     p_sys->p_thread->p_fifo = block_FifoNew( p_access );
288     p_sys->p_thread->p_empty_blocks = block_FifoNew( p_access );
289
290     i_handle = net_ConnectDgram( p_this, psz_dst_addr, i_dst_port, -1, proto );
291     if( i_handle == -1 )
292     {
293          msg_Err( p_access, "failed to create %s socket", protoname );
294          return VLC_EGENERIC;
295     }
296     else
297     {
298         char addr[NI_MAXNUMERICHOST];
299         int port;
300
301         if (net_GetSockAddress (i_handle, addr, &port) == 0)
302         {
303             msg_Dbg (p_access, "source: %s port %d", addr, port);
304             var_SetString (p_access, "src-addr", addr);
305             var_SetInteger (p_access, "src-port", port);
306         }
307
308         if (net_GetPeerAddress (i_handle, addr, &port) == 0)
309         {
310             msg_Dbg (p_access, "destination: %s port %d", addr, port);
311             var_SetString (p_access, "dst-addr", addr);
312             var_SetInteger (p_access, "dst-port", port);
313         }
314     }
315     p_sys->p_thread->i_handle = i_handle;
316     net_StopRecv( i_handle );
317
318 #ifdef UDPLITE_SEND_CSCOV
319     if (proto == IPPROTO_UDPLITE)
320         setsockopt (i_handle, SOL_UDPLITE, UDPLITE_SEND_CSCOV,
321                     &cscov, sizeof (cscov));
322 #endif
323
324     var_Get( p_access, SOUT_CFG_PREFIX "caching", &val );
325     p_sys->p_thread->i_caching = (int64_t)val.i_int * 1000;
326
327     var_Get( p_access, SOUT_CFG_PREFIX "group", &val );
328     p_sys->p_thread->i_group = val.i_int;
329
330     p_sys->i_mtu = var_CreateGetInteger( p_this, "mtu" );
331
332     srand( (uint32_t)mdate());
333     p_sys->p_buffer          = NULL;
334     p_sys->i_sequence_number = rand()&0xffff;
335     p_sys->i_ssrc            = rand()&0xffffffff;
336
337     if (p_sys->b_rtpts && OpenRTCP (p_access))
338     {
339         msg_Err (p_access, "cannot initialize RTCP sender");
340         return VLC_EGENERIC;
341     }
342
343     if( vlc_thread_create( p_sys->p_thread, "sout write thread", ThreadWrite,
344                            VLC_THREAD_PRIORITY_HIGHEST, VLC_FALSE ) )
345     {
346         msg_Err( p_access->p_sout, "cannot spawn sout access thread" );
347         vlc_object_destroy( p_sys->p_thread );
348         return VLC_EGENERIC;
349     }
350
351     var_Get( p_access, SOUT_CFG_PREFIX "raw", &val );
352     if( val.b_bool )  p_access->pf_write = WriteRaw;
353     else p_access->pf_write = Write;
354
355     p_access->pf_seek = Seek;
356
357     free( psz_dst_addr );
358
359     /* update p_sout->i_out_pace_nocontrol */
360     p_access->p_sout->i_out_pace_nocontrol++;
361
362     return VLC_SUCCESS;
363 }
364
365 /*****************************************************************************
366  * Close: close the target
367  *****************************************************************************/
368 static void Close( vlc_object_t * p_this )
369 {
370     sout_access_out_t     *p_access = (sout_access_out_t*)p_this;
371     sout_access_out_sys_t *p_sys = p_access->p_sys;
372     int i;
373
374     p_sys->p_thread->b_die = 1;
375     for( i = 0; i < 10; i++ )
376     {
377         block_t *p_dummy = block_New( p_access, p_sys->i_mtu );
378         p_dummy->i_dts = 0;
379         p_dummy->i_pts = 0;
380         p_dummy->i_length = 0;
381         memset( p_dummy->p_buffer, 0, p_dummy->i_buffer );
382         block_FifoPut( p_sys->p_thread->p_fifo, p_dummy );
383     }
384     vlc_thread_join( p_sys->p_thread );
385
386     block_FifoRelease( p_sys->p_thread->p_fifo );
387     block_FifoRelease( p_sys->p_thread->p_empty_blocks );
388
389     if( p_sys->p_buffer ) block_Release( p_sys->p_buffer );
390
391     net_Close( p_sys->p_thread->i_handle );
392     CloseRTCP (p_sys->p_thread);
393
394     vlc_object_detach( p_sys->p_thread );
395     vlc_object_destroy( p_sys->p_thread );
396     /* update p_sout->i_out_pace_nocontrol */
397     p_access->p_sout->i_out_pace_nocontrol--;
398
399     msg_Dbg( p_access, "UDP access output closed" );
400     free( p_sys );
401 }
402
403 /*****************************************************************************
404  * Write: standard write on a file descriptor.
405  *****************************************************************************/
406 static int Write( sout_access_out_t *p_access, block_t *p_buffer )
407 {
408     sout_access_out_sys_t *p_sys = p_access->p_sys;
409     int i_len = 0;
410
411     while( p_buffer )
412     {
413         block_t *p_next;
414         int i_packets = 0;
415
416         if( !p_sys->b_mtu_warning && p_buffer->i_buffer > p_sys->i_mtu )
417         {
418             msg_Warn( p_access, "packet size > MTU, you should probably "
419                       "increase the MTU" );
420             p_sys->b_mtu_warning = VLC_TRUE;
421         }
422
423         /* Check if there is enough space in the buffer */
424         if( p_sys->p_buffer &&
425             p_sys->p_buffer->i_buffer + p_buffer->i_buffer > p_sys->i_mtu )
426         {
427             if( p_sys->p_buffer->i_dts + p_sys->p_thread->i_caching < mdate() )
428             {
429                 msg_Dbg( p_access, "late packet for UDP input (" I64Fd ")",
430                          mdate() - p_sys->p_buffer->i_dts
431                           - p_sys->p_thread->i_caching );
432             }
433             block_FifoPut( p_sys->p_thread->p_fifo, p_sys->p_buffer );
434             p_sys->p_buffer = NULL;
435         }
436
437         i_len += p_buffer->i_buffer;
438         while( p_buffer->i_buffer )
439         {
440             int i_payload_size = p_sys->i_mtu;
441             if( p_sys->b_rtpts )
442                 i_payload_size -= RTP_HEADER_LENGTH;
443
444             int i_write = __MIN( p_buffer->i_buffer, i_payload_size );
445
446             i_packets++;
447
448             if( !p_sys->p_buffer )
449             {
450                 p_sys->p_buffer = NewUDPPacket( p_access, p_buffer->i_dts );
451                 if( !p_sys->p_buffer ) break;
452             }
453
454             memcpy( p_sys->p_buffer->p_buffer + p_sys->p_buffer->i_buffer,
455                     p_buffer->p_buffer, i_write );
456
457             p_sys->p_buffer->i_buffer += i_write;
458             p_buffer->p_buffer += i_write;
459             p_buffer->i_buffer -= i_write;
460             if ( p_buffer->i_flags & BLOCK_FLAG_CLOCK )
461             {
462                 if ( p_sys->p_buffer->i_flags & BLOCK_FLAG_CLOCK )
463                     msg_Warn( p_access, "putting two PCRs at once" );
464                 p_sys->p_buffer->i_flags |= BLOCK_FLAG_CLOCK;
465             }
466
467             if( p_sys->p_buffer->i_buffer == p_sys->i_mtu || i_packets > 1 )
468             {
469                 /* Flush */
470                 if( p_sys->p_buffer->i_dts + p_sys->p_thread->i_caching
471                       < mdate() )
472                 {
473                     msg_Dbg( p_access, "late packet for udp input (" I64Fd ")",
474                              mdate() - p_sys->p_buffer->i_dts
475                               - p_sys->p_thread->i_caching );
476                 }
477                 block_FifoPut( p_sys->p_thread->p_fifo, p_sys->p_buffer );
478                 p_sys->p_buffer = NULL;
479             }
480         }
481
482         p_next = p_buffer->p_next;
483         block_Release( p_buffer );
484         p_buffer = p_next;
485     }
486
487     return( p_sys->p_thread->b_error ? -1 : i_len );
488 }
489
490 /*****************************************************************************
491  * WriteRaw: write p_buffer without trying to fill mtu
492  *****************************************************************************/
493 static int WriteRaw( sout_access_out_t *p_access, block_t *p_buffer )
494 {
495     sout_access_out_sys_t   *p_sys = p_access->p_sys;
496     block_t *p_buf;
497     int i_len;
498
499     while ( p_sys->p_thread->p_empty_blocks->i_depth >= MAX_EMPTY_BLOCKS )
500     {
501         p_buf = block_FifoGet(p_sys->p_thread->p_empty_blocks);
502         block_Release( p_buf );
503     }
504
505     i_len = p_buffer->i_buffer;
506     block_FifoPut( p_sys->p_thread->p_fifo, p_buffer );
507
508     return( p_sys->p_thread->b_error ? -1 : i_len );
509 }
510
511 /*****************************************************************************
512  * Seek: seek to a specific location in a file
513  *****************************************************************************/
514 static int Seek( sout_access_out_t *p_access, off_t i_pos )
515 {
516     msg_Err( p_access, "UDP sout access cannot seek" );
517     return -1;
518 }
519
520 /*****************************************************************************
521  * NewUDPPacket: allocate a new UDP packet of size p_sys->i_mtu
522  *****************************************************************************/
523 static block_t *NewUDPPacket( sout_access_out_t *p_access, mtime_t i_dts)
524 {
525     sout_access_out_sys_t *p_sys = p_access->p_sys;
526     block_t *p_buffer;
527
528     while ( p_sys->p_thread->p_empty_blocks->i_depth > MAX_EMPTY_BLOCKS )
529     {
530         p_buffer = block_FifoGet( p_sys->p_thread->p_empty_blocks );
531         block_Release( p_buffer );
532     }
533
534     if( p_sys->p_thread->p_empty_blocks->i_depth == 0 )
535     {
536         p_buffer = block_New( p_access->p_sout, p_sys->i_mtu );
537     }
538     else
539     {
540         p_buffer = block_FifoGet(p_sys->p_thread->p_empty_blocks );
541         p_buffer->i_flags = 0;
542         p_buffer = block_Realloc( p_buffer, 0, p_sys->i_mtu );
543     }
544
545     p_buffer->i_dts = i_dts;
546     p_buffer->i_buffer = 0;
547
548     if( p_sys->b_rtpts )
549     {
550         mtime_t i_timestamp = p_buffer->i_dts * 9 / 100;
551
552         /* add rtp/ts header */
553         p_buffer->p_buffer[0] = 0x80;
554         p_buffer->p_buffer[1] = 0x21; // mpeg2-ts
555
556         SetWBE( p_buffer->p_buffer + 2, p_sys->i_sequence_number );
557         p_sys->i_sequence_number++;
558         SetDWBE( p_buffer->p_buffer + 4, i_timestamp );
559         SetDWBE( p_buffer->p_buffer + 8, p_sys->i_ssrc );
560
561         p_buffer->i_buffer = RTP_HEADER_LENGTH;
562     }
563
564     return p_buffer;
565 }
566
567 /*****************************************************************************
568  * ThreadWrite: Write a packet on the network at the good time.
569  *****************************************************************************/
570 static void ThreadWrite( vlc_object_t *p_this )
571 {
572     sout_access_thread_t *p_thread = (sout_access_thread_t*)p_this;
573     mtime_t              i_date_last = -1;
574     mtime_t              i_to_send = p_thread->i_group;
575     int                  i_dropped_packets = 0;
576 #if defined(WIN32) || defined(UNDER_CE)
577     char strerror_buf[WINSOCK_STRERROR_SIZE];
578 # define strerror( x ) winsock_strerror( strerror_buf )
579 #endif
580     size_t rtcp_counter = 0;
581
582     while( !p_thread->b_die )
583     {
584         block_t *p_pk;
585         mtime_t       i_date, i_sent;
586 #if 0
587         if( (i++ % 1000)==0 ) {
588           int i = 0;
589           int j = 0;
590           block_t *p_tmp = p_thread->p_empty_blocks->p_first;
591           while( p_tmp ) { p_tmp = p_tmp->p_next; i++;}
592           p_tmp = p_thread->p_fifo->p_first;
593           while( p_tmp ) { p_tmp = p_tmp->p_next; j++;}
594           msg_Dbg( p_thread, "fifo depth: %d/%d, empty blocks: %d/%d",
595                    p_thread->p_fifo->i_depth, j,p_thread->p_empty_blocks->i_depth,i );
596         }
597 #endif
598         p_pk = block_FifoGet( p_thread->p_fifo );
599
600         i_date = p_thread->i_caching + p_pk->i_dts;
601         if( i_date_last > 0 )
602         {
603             if( i_date - i_date_last > 2000000 )
604             {
605                 if( !i_dropped_packets )
606                     msg_Dbg( p_thread, "mmh, hole ("I64Fd" > 2s) -> drop",
607                              i_date - i_date_last );
608
609                 block_FifoPut( p_thread->p_empty_blocks, p_pk );
610
611                 i_date_last = i_date;
612                 i_dropped_packets++;
613                 continue;
614             }
615             else if( i_date - i_date_last < -1000 )
616             {
617                 if( !i_dropped_packets )
618                     msg_Dbg( p_thread, "mmh, packets in the past ("I64Fd")",
619                              i_date_last - i_date );
620             }
621         }
622
623         i_to_send--;
624         if( !i_to_send || (p_pk->i_flags & BLOCK_FLAG_CLOCK) )
625         {
626             mwait( i_date );
627             i_to_send = p_thread->i_group;
628         }
629         ssize_t val = send( p_thread->i_handle, p_pk->p_buffer,
630                             p_pk->i_buffer, 0 );
631         if (val == -1)
632         {
633             msg_Warn( p_thread, "send error: %s", strerror(errno) );
634         }
635         else
636         {
637             p_thread->sent_pkts++;
638             p_thread->sent_bytes += val;
639             rtcp_counter += val;
640         }
641
642         if( i_dropped_packets )
643         {
644             msg_Dbg( p_thread, "dropped %i packets", i_dropped_packets );
645             i_dropped_packets = 0;
646         }
647
648 #if 1
649         i_sent = mdate();
650         if ( i_sent > i_date + 20000 )
651         {
652             msg_Dbg( p_thread, "packet has been sent too late (" I64Fd ")",
653                      i_sent - i_date );
654         }
655 #endif
656
657         if (p_thread->rtcp_handle != -1)
658         {
659             /* FIXME: this is a very incorrect simplistic RTCP timer */
660             if ((rtcp_counter / 80) >= p_thread->rtcp_size)
661             {
662                 SendRTCP (p_thread, p_pk->i_dts * 9 / 100);
663                 rtcp_counter = 0;
664             }
665         }
666
667         block_FifoPut( p_thread->p_empty_blocks, p_pk );
668
669         i_date_last = i_date;
670     }
671 }
672
673
674 static const char *MakeRandMulticast (int family, char *buf, size_t buflen)
675 {
676     uint32_t rand = (getpid() & 0xffff)
677                   | (uint32_t)(((mdate () >> 10) & 0xffff) << 16);
678
679     switch (family)
680     {
681 #ifdef AF_INET6
682         case AF_INET6:
683         {
684             struct in6_addr addr;
685             memcpy (&addr, "\xff\x38\x00\x00" "\x00\x00\x00\x00"
686                            "\x00\x00\x00\x00", 12);
687             rand |= 0x80000000;
688             memcpy (addr.s6_addr + 12, &(uint32_t){ htonl (rand) }, 4);
689             return inet_ntop (family, &addr, buf, buflen);
690         }
691 #endif
692
693         case AF_INET:
694         {
695             struct in_addr addr;
696             addr.s_addr = htonl ((rand & 0xffffff) | 0xe8000000);
697             return inet_ntop (family, &addr, buf, buflen);
698         }
699     }
700 #ifdef EAFNOSUPPORT
701     errno = EAFNOSUPPORT;
702 #endif
703     return NULL;
704 }
705
706
707 /*
708  * NOTE on RTCP implementation:
709  * - there is a single sender (us), no conferencing here! => n = sender = 1,
710  * - as such we need not bother to include Receiver Reports,
711  * - in unicast case, there is a single receiver => members = 1 + 1 = 2,
712  *   and obviously n > 25% of members,
713  * - in multicast case, we do not want to maintain the number of receivers
714  *   and we assume it is big (i.e. than 3) because that's what broadcasting is
715  *   all about,
716  * - it is assumed we_sent = true (could be wrong), since we are THE sender,
717  * - we always send SR + SDES, while running,
718  * - FIXME: we do not implement separate rate limiting for SDES,
719  * - FIXME: we should send BYE when stopping,
720  * - we do not implement any profile-specific extensions for the time being.
721  */
722 static int OpenRTCP (sout_access_out_t *obj)
723 {
724     sout_access_out_sys_t *p_sys = obj->p_sys;
725     uint8_t *ptr;
726     int fd;
727
728     char src[NI_MAXNUMERICHOST], dst[NI_MAXNUMERICHOST];
729     int sport, dport;
730
731     fd = obj->p_sys->p_thread->i_handle;
732     if (net_GetSockAddress (fd, src, &sport)
733      || net_GetPeerAddress (fd, dst, &dport))
734         return VLC_EGENERIC;
735
736     sport++;
737     dport++;
738     /* FIXME: should we use UDP for non-UDP protos? */
739     fd = net_OpenDgram (obj, src, sport, dst, dport, AF_UNSPEC, IPPROTO_UDP);
740     if (fd == -1)
741         return VLC_EGENERIC;
742
743     obj->p_sys->p_thread->rtcp_handle = fd;
744
745     ptr = (uint8_t *)strchr (src, '%');
746     if (ptr != NULL)
747         *ptr = '\0'; /* remove scope ID frop IPv6 addresses */
748
749     ptr = obj->p_sys->p_thread->rtcp_data;
750
751     /* Sender report */
752     ptr[0] = 2 << 6; /* V = 2, P = RC = 0 */
753     ptr[1] = 200; /* payload type: Sender Report */
754     SetWBE (ptr + 2, 6); /* length = 6 (7 double words) */
755     SetDWBE (ptr + 4, p_sys->i_ssrc);
756     ptr += 28;
757     /* timestamps and counter are handled later */
758
759     /* Source description */
760     uint8_t *sdes = ptr;
761     ptr[0] = (2 << 6) | 1; /* V = 2, P = 0, SC = 1 */
762     ptr[1] = 202; /* payload type: Source Description */
763     uint8_t *lenptr = ptr + 2;
764     SetDWBE (ptr + 4, p_sys->i_ssrc);
765     ptr += 8;
766
767     ptr[0] = 1; /* CNAME - mandatory */
768     assert (NI_MAXNUMERICHOST <= 256);
769     ptr[1] = strlen (src);
770     memcpy (ptr + 2, src, ptr[1]);
771     ptr += ptr[1] + 2;
772
773     static const char tool[] = PACKAGE_STRING;
774     ptr[0] = 6; /* TOOL */
775     ptr[1] = (sizeof (tool) > 256) ? 255 : (sizeof (tool) - 1);
776     memcpy (ptr + 2, tool, ptr[1]);
777     ptr += ptr[1] + 2;
778
779     while ((ptr - sdes) & 3) /* 32-bits padding */
780         *ptr++ = 0;
781     SetWBE (lenptr, ptr - sdes);
782
783     obj->p_sys->p_thread->rtcp_size = ptr - obj->p_sys->p_thread->rtcp_data;
784     return VLC_SUCCESS;
785 }
786
787 static void CloseRTCP (sout_access_thread_t *obj)
788 {
789     /* TODO: send RTCP BYE */
790     if (obj->rtcp_handle != -1)
791         net_Close (obj->rtcp_handle);
792 }
793
794 static void SendRTCP (sout_access_thread_t *obj, uint32_t timestamp)
795 {
796     uint8_t *ptr = obj->rtcp_data;
797     SetQWBE (ptr + 8, NTPtime64 ());
798     SetDWBE (ptr + 16, timestamp);
799     SetDWBE (ptr + 20, obj->sent_pkts);
800     SetDWBE (ptr + 24, obj->sent_bytes);
801
802     send (obj->rtcp_handle, ptr, obj->rtcp_size, 0);
803 }