]> git.sesse.net Git - vlc/blob - modules/access_output/udp.c
Do not assume RTP frequency is that of TS for RTCP
[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, int proto);
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     {
274         free (p_sys);
275         free (psz_dst_addr);
276         return VLC_ENOMEM;
277     }
278
279     p_sys->p_thread =
280         vlc_object_create( p_access, sizeof( sout_access_thread_t ) );
281     if( !p_sys->p_thread )
282     {
283         msg_Err( p_access, "out of memory" );
284         free (p_sys);
285         free (psz_dst_addr);
286         return VLC_ENOMEM;
287     }
288
289     vlc_object_attach( p_sys->p_thread, p_access );
290     p_sys->p_thread->p_sout = p_access->p_sout;
291     p_sys->p_thread->b_die  = 0;
292     p_sys->p_thread->b_error= 0;
293     p_sys->p_thread->p_fifo = block_FifoNew( p_access );
294     p_sys->p_thread->p_empty_blocks = block_FifoNew( p_access );
295
296     i_handle = net_ConnectDgram( p_this, psz_dst_addr, i_dst_port, -1, proto );
297     free (psz_dst_addr);
298
299     if( i_handle == -1 )
300     {
301          msg_Err( p_access, "failed to create %s socket", protoname );
302          vlc_object_destroy (p_sys->p_thread);
303          free (p_sys);
304          return VLC_EGENERIC;
305     }
306     else
307     {
308         char addr[NI_MAXNUMERICHOST];
309         int port;
310
311         if (net_GetSockAddress (i_handle, addr, &port) == 0)
312         {
313             msg_Dbg (p_access, "source: %s port %d", addr, port);
314             var_SetString (p_access, "src-addr", addr);
315             var_SetInteger (p_access, "src-port", port);
316         }
317
318         if (net_GetPeerAddress (i_handle, addr, &port) == 0)
319         {
320             msg_Dbg (p_access, "destination: %s port %d", addr, port);
321             var_SetString (p_access, "dst-addr", addr);
322             var_SetInteger (p_access, "dst-port", port);
323         }
324     }
325     p_sys->p_thread->i_handle = i_handle;
326     shutdown( i_handle, SHUT_RD );
327
328 #ifdef UDPLITE_SEND_CSCOV
329     if (proto == IPPROTO_UDPLITE)
330         setsockopt (i_handle, SOL_UDPLITE, UDPLITE_SEND_CSCOV,
331                     &cscov, sizeof (cscov));
332 #endif
333
334     var_Get( p_access, SOUT_CFG_PREFIX "caching", &val );
335     p_sys->p_thread->i_caching = (int64_t)val.i_int * 1000;
336
337     var_Get( p_access, SOUT_CFG_PREFIX "group", &val );
338     p_sys->p_thread->i_group = val.i_int;
339
340     p_sys->i_mtu = var_CreateGetInteger( p_this, "mtu" );
341
342     srand( (uint32_t)mdate());
343     p_sys->p_buffer          = NULL;
344     p_sys->i_sequence_number = rand()&0xffff;
345     p_sys->i_ssrc            = rand()&0xffffffff;
346
347     if (p_sys->b_rtpts && OpenRTCP (p_access, proto))
348     {
349         msg_Err (p_access, "cannot initialize RTCP sender");
350         net_Close (i_handle);
351         vlc_object_destroy (p_sys->p_thread);
352         free (p_sys);
353         return VLC_EGENERIC;
354     }
355
356     if( vlc_thread_create( p_sys->p_thread, "sout write thread", ThreadWrite,
357                            VLC_THREAD_PRIORITY_HIGHEST, VLC_FALSE ) )
358     {
359         msg_Err( p_access->p_sout, "cannot spawn sout access thread" );
360         net_Close (i_handle);
361         vlc_object_destroy( p_sys->p_thread );
362         free (p_sys);
363         return VLC_EGENERIC;
364     }
365
366     var_Get( p_access, SOUT_CFG_PREFIX "raw", &val );
367     if( val.b_bool )  p_access->pf_write = WriteRaw;
368     else p_access->pf_write = Write;
369
370     p_access->pf_seek = Seek;
371
372     /* update p_sout->i_out_pace_nocontrol */
373     p_access->p_sout->i_out_pace_nocontrol++;
374
375     return VLC_SUCCESS;
376 }
377
378 /*****************************************************************************
379  * Close: close the target
380  *****************************************************************************/
381 static void Close( vlc_object_t * p_this )
382 {
383     sout_access_out_t     *p_access = (sout_access_out_t*)p_this;
384     sout_access_out_sys_t *p_sys = p_access->p_sys;
385     int i;
386
387     p_sys->p_thread->b_die = 1;
388     for( i = 0; i < 10; i++ )
389     {
390         block_t *p_dummy = block_New( p_access, p_sys->i_mtu );
391         p_dummy->i_dts = 0;
392         p_dummy->i_pts = 0;
393         p_dummy->i_length = 0;
394         memset( p_dummy->p_buffer, 0, p_dummy->i_buffer );
395         block_FifoPut( p_sys->p_thread->p_fifo, p_dummy );
396     }
397     vlc_thread_join( p_sys->p_thread );
398
399     block_FifoRelease( p_sys->p_thread->p_fifo );
400     block_FifoRelease( p_sys->p_thread->p_empty_blocks );
401
402     if( p_sys->p_buffer ) block_Release( p_sys->p_buffer );
403
404     net_Close( p_sys->p_thread->i_handle );
405     CloseRTCP (p_sys->p_thread);
406
407     vlc_object_detach( p_sys->p_thread );
408     vlc_object_destroy( p_sys->p_thread );
409     /* update p_sout->i_out_pace_nocontrol */
410     p_access->p_sout->i_out_pace_nocontrol--;
411
412     msg_Dbg( p_access, "UDP access output closed" );
413     free( p_sys );
414 }
415
416 /*****************************************************************************
417  * Write: standard write on a file descriptor.
418  *****************************************************************************/
419 static int Write( sout_access_out_t *p_access, block_t *p_buffer )
420 {
421     sout_access_out_sys_t *p_sys = p_access->p_sys;
422     int i_len = 0;
423
424     while( p_buffer )
425     {
426         block_t *p_next;
427         int i_packets = 0;
428
429         if( !p_sys->b_mtu_warning && p_buffer->i_buffer > p_sys->i_mtu )
430         {
431             msg_Warn( p_access, "packet size > MTU, you should probably "
432                       "increase the MTU" );
433             p_sys->b_mtu_warning = VLC_TRUE;
434         }
435
436         /* Check if there is enough space in the buffer */
437         if( p_sys->p_buffer &&
438             p_sys->p_buffer->i_buffer + p_buffer->i_buffer > p_sys->i_mtu )
439         {
440             if( p_sys->p_buffer->i_dts + p_sys->p_thread->i_caching < mdate() )
441             {
442                 msg_Dbg( p_access, "late packet for UDP input (" I64Fd ")",
443                          mdate() - p_sys->p_buffer->i_dts
444                           - p_sys->p_thread->i_caching );
445             }
446             block_FifoPut( p_sys->p_thread->p_fifo, p_sys->p_buffer );
447             p_sys->p_buffer = NULL;
448         }
449
450         i_len += p_buffer->i_buffer;
451         while( p_buffer->i_buffer )
452         {
453             int i_payload_size = p_sys->i_mtu;
454             if( p_sys->b_rtpts )
455                 i_payload_size -= RTP_HEADER_LENGTH;
456
457             int i_write = __MIN( p_buffer->i_buffer, i_payload_size );
458
459             i_packets++;
460
461             if( !p_sys->p_buffer )
462             {
463                 p_sys->p_buffer = NewUDPPacket( p_access, p_buffer->i_dts );
464                 if( !p_sys->p_buffer ) break;
465             }
466
467             memcpy( p_sys->p_buffer->p_buffer + p_sys->p_buffer->i_buffer,
468                     p_buffer->p_buffer, i_write );
469
470             p_sys->p_buffer->i_buffer += i_write;
471             p_buffer->p_buffer += i_write;
472             p_buffer->i_buffer -= i_write;
473             if ( p_buffer->i_flags & BLOCK_FLAG_CLOCK )
474             {
475                 if ( p_sys->p_buffer->i_flags & BLOCK_FLAG_CLOCK )
476                     msg_Warn( p_access, "putting two PCRs at once" );
477                 p_sys->p_buffer->i_flags |= BLOCK_FLAG_CLOCK;
478             }
479
480             if( p_sys->p_buffer->i_buffer == p_sys->i_mtu || i_packets > 1 )
481             {
482                 /* Flush */
483                 if( p_sys->p_buffer->i_dts + p_sys->p_thread->i_caching
484                       < mdate() )
485                 {
486                     msg_Dbg( p_access, "late packet for udp input (" I64Fd ")",
487                              mdate() - p_sys->p_buffer->i_dts
488                               - p_sys->p_thread->i_caching );
489                 }
490                 block_FifoPut( p_sys->p_thread->p_fifo, p_sys->p_buffer );
491                 p_sys->p_buffer = NULL;
492             }
493         }
494
495         p_next = p_buffer->p_next;
496         block_Release( p_buffer );
497         p_buffer = p_next;
498     }
499
500     return( p_sys->p_thread->b_error ? -1 : i_len );
501 }
502
503 /*****************************************************************************
504  * WriteRaw: write p_buffer without trying to fill mtu
505  *****************************************************************************/
506 static int WriteRaw( sout_access_out_t *p_access, block_t *p_buffer )
507 {
508     sout_access_out_sys_t   *p_sys = p_access->p_sys;
509     block_t *p_buf;
510     int i_len;
511
512     while ( p_sys->p_thread->p_empty_blocks->i_depth >= MAX_EMPTY_BLOCKS )
513     {
514         p_buf = block_FifoGet(p_sys->p_thread->p_empty_blocks);
515         block_Release( p_buf );
516     }
517
518     i_len = p_buffer->i_buffer;
519     block_FifoPut( p_sys->p_thread->p_fifo, p_buffer );
520
521     return( p_sys->p_thread->b_error ? -1 : i_len );
522 }
523
524 /*****************************************************************************
525  * Seek: seek to a specific location in a file
526  *****************************************************************************/
527 static int Seek( sout_access_out_t *p_access, off_t i_pos )
528 {
529     msg_Err( p_access, "UDP sout access cannot seek" );
530     return -1;
531 }
532
533 /*****************************************************************************
534  * NewUDPPacket: allocate a new UDP packet of size p_sys->i_mtu
535  *****************************************************************************/
536 static block_t *NewUDPPacket( sout_access_out_t *p_access, mtime_t i_dts)
537 {
538     sout_access_out_sys_t *p_sys = p_access->p_sys;
539     block_t *p_buffer;
540
541     while ( p_sys->p_thread->p_empty_blocks->i_depth > MAX_EMPTY_BLOCKS )
542     {
543         p_buffer = block_FifoGet( p_sys->p_thread->p_empty_blocks );
544         block_Release( p_buffer );
545     }
546
547     if( p_sys->p_thread->p_empty_blocks->i_depth == 0 )
548     {
549         p_buffer = block_New( p_access->p_sout, p_sys->i_mtu );
550     }
551     else
552     {
553         p_buffer = block_FifoGet(p_sys->p_thread->p_empty_blocks );
554         p_buffer->i_flags = 0;
555         p_buffer = block_Realloc( p_buffer, 0, p_sys->i_mtu );
556     }
557
558     p_buffer->i_dts = i_dts;
559     p_buffer->i_buffer = 0;
560
561     if( p_sys->b_rtpts )
562     {
563         mtime_t i_timestamp = p_buffer->i_dts * 9 / 100;
564
565         /* add rtp/ts header */
566         p_buffer->p_buffer[0] = 0x80;
567         p_buffer->p_buffer[1] = 0x21; // mpeg2-ts
568
569         SetWBE( p_buffer->p_buffer + 2, p_sys->i_sequence_number );
570         p_sys->i_sequence_number++;
571         SetDWBE( p_buffer->p_buffer + 4, i_timestamp );
572         SetDWBE( p_buffer->p_buffer + 8, p_sys->i_ssrc );
573
574         p_buffer->i_buffer = RTP_HEADER_LENGTH;
575     }
576
577     return p_buffer;
578 }
579
580 /*****************************************************************************
581  * ThreadWrite: Write a packet on the network at the good time.
582  *****************************************************************************/
583 static void ThreadWrite( vlc_object_t *p_this )
584 {
585     sout_access_thread_t *p_thread = (sout_access_thread_t*)p_this;
586     mtime_t              i_date_last = -1;
587     mtime_t              i_to_send = p_thread->i_group;
588     int                  i_dropped_packets = 0;
589 #if defined(WIN32) || defined(UNDER_CE)
590     char strerror_buf[WINSOCK_STRERROR_SIZE];
591 # define strerror( x ) winsock_strerror( strerror_buf )
592 #endif
593     size_t rtcp_counter = 0;
594
595     while( !p_thread->b_die )
596     {
597         block_t *p_pk;
598         mtime_t       i_date, i_sent;
599 #if 0
600         if( (i++ % 1000)==0 ) {
601           int i = 0;
602           int j = 0;
603           block_t *p_tmp = p_thread->p_empty_blocks->p_first;
604           while( p_tmp ) { p_tmp = p_tmp->p_next; i++;}
605           p_tmp = p_thread->p_fifo->p_first;
606           while( p_tmp ) { p_tmp = p_tmp->p_next; j++;}
607           msg_Dbg( p_thread, "fifo depth: %d/%d, empty blocks: %d/%d",
608                    p_thread->p_fifo->i_depth, j,p_thread->p_empty_blocks->i_depth,i );
609         }
610 #endif
611         p_pk = block_FifoGet( p_thread->p_fifo );
612
613         i_date = p_thread->i_caching + p_pk->i_dts;
614         if( i_date_last > 0 )
615         {
616             if( i_date - i_date_last > 2000000 )
617             {
618                 if( !i_dropped_packets )
619                     msg_Dbg( p_thread, "mmh, hole ("I64Fd" > 2s) -> drop",
620                              i_date - i_date_last );
621
622                 block_FifoPut( p_thread->p_empty_blocks, p_pk );
623
624                 i_date_last = i_date;
625                 i_dropped_packets++;
626                 continue;
627             }
628             else if( i_date - i_date_last < -1000 )
629             {
630                 if( !i_dropped_packets )
631                     msg_Dbg( p_thread, "mmh, packets in the past ("I64Fd")",
632                              i_date_last - i_date );
633             }
634         }
635
636         i_to_send--;
637         if( !i_to_send || (p_pk->i_flags & BLOCK_FLAG_CLOCK) )
638         {
639             mwait( i_date );
640             i_to_send = p_thread->i_group;
641         }
642         ssize_t val = send( p_thread->i_handle, p_pk->p_buffer,
643                             p_pk->i_buffer, 0 );
644         if (val == -1)
645         {
646             msg_Warn( p_thread, "send error: %s", strerror(errno) );
647         }
648         else
649         {
650             p_thread->sent_pkts++;
651             p_thread->sent_bytes += val;
652             rtcp_counter += val;
653         }
654
655         if( i_dropped_packets )
656         {
657             msg_Dbg( p_thread, "dropped %i packets", i_dropped_packets );
658             i_dropped_packets = 0;
659         }
660
661 #if 1
662         i_sent = mdate();
663         if ( i_sent > i_date + 20000 )
664         {
665             msg_Dbg( p_thread, "packet has been sent too late (" I64Fd ")",
666                      i_sent - i_date );
667         }
668 #endif
669
670         if (p_thread->rtcp_handle != -1)
671         {
672             /* FIXME: this is a very incorrect simplistic RTCP timer */
673             if ((rtcp_counter / 80) >= p_thread->rtcp_size)
674             {
675                 SendRTCP (p_thread, GetDWBE (p_pk->p_buffer + 4));
676                 rtcp_counter = 0;
677             }
678         }
679
680         block_FifoPut( p_thread->p_empty_blocks, p_pk );
681
682         i_date_last = i_date;
683     }
684 }
685
686
687 static const char *MakeRandMulticast (int family, char *buf, size_t buflen)
688 {
689     uint32_t rand = (getpid() & 0xffff)
690                   | (uint32_t)(((mdate () >> 10) & 0xffff) << 16);
691
692     switch (family)
693     {
694 #ifdef AF_INET6
695         case AF_INET6:
696         {
697             struct in6_addr addr;
698             memcpy (&addr, "\xff\x38\x00\x00" "\x00\x00\x00\x00"
699                            "\x00\x00\x00\x00", 12);
700             rand |= 0x80000000;
701             memcpy (addr.s6_addr + 12, &(uint32_t){ htonl (rand) }, 4);
702             return inet_ntop (family, &addr, buf, buflen);
703         }
704 #endif
705
706         case AF_INET:
707         {
708             struct in_addr addr;
709             addr.s_addr = htonl ((rand & 0xffffff) | 0xe8000000);
710             return inet_ntop (family, &addr, buf, buflen);
711         }
712     }
713 #ifdef EAFNOSUPPORT
714     errno = EAFNOSUPPORT;
715 #endif
716     return NULL;
717 }
718
719
720 /*
721  * NOTE on RTCP implementation:
722  * - there is a single sender (us), no conferencing here! => n = sender = 1,
723  * - as such we need not bother to include Receiver Reports,
724  * - in unicast case, there is a single receiver => members = 1 + 1 = 2,
725  *   and obviously n > 25% of members,
726  * - in multicast case, we do not want to maintain the number of receivers
727  *   and we assume it is big (i.e. than 3) because that's what broadcasting is
728  *   all about,
729  * - it is assumed we_sent = true (could be wrong), since we are THE sender,
730  * - we always send SR + SDES, while running,
731  * - FIXME: we do not implement separate rate limiting for SDES,
732  * - we do not implement any profile-specific extensions for the time being.
733  */
734 static int OpenRTCP (sout_access_out_t *obj, int proto)
735 {
736     sout_access_out_sys_t *p_sys = obj->p_sys;
737     uint8_t *ptr;
738     int fd;
739
740     char src[NI_MAXNUMERICHOST], dst[NI_MAXNUMERICHOST];
741     int sport, dport;
742
743     fd = obj->p_sys->p_thread->i_handle;
744     if (net_GetSockAddress (fd, src, &sport)
745      || net_GetPeerAddress (fd, dst, &dport))
746         return VLC_EGENERIC;
747
748     sport++;
749     dport++;
750     fd = net_OpenDgram (obj, src, sport, dst, dport, AF_UNSPEC, proto);
751     if (fd == -1)
752         return VLC_EGENERIC;
753
754     obj->p_sys->p_thread->rtcp_handle = fd;
755
756     ptr = (uint8_t *)strchr (src, '%');
757     if (ptr != NULL)
758         *ptr = '\0'; /* remove scope ID frop IPv6 addresses */
759
760     ptr = obj->p_sys->p_thread->rtcp_data;
761
762     /* Sender report */
763     ptr[0] = 2 << 6; /* V = 2, P = RC = 0 */
764     ptr[1] = 200; /* payload type: Sender Report */
765     SetWBE (ptr + 2, 6); /* length = 6 (7 double words) */
766     SetDWBE (ptr + 4, p_sys->i_ssrc);
767     ptr += 28;
768     /* timestamps and counter are handled later */
769
770     /* Source description */
771     uint8_t *sdes = ptr;
772     ptr[0] = (2 << 6) | 1; /* V = 2, P = 0, SC = 1 */
773     ptr[1] = 202; /* payload type: Source Description */
774     uint8_t *lenptr = ptr + 2;
775     SetDWBE (ptr + 4, p_sys->i_ssrc);
776     ptr += 8;
777
778     ptr[0] = 1; /* CNAME - mandatory */
779     assert (NI_MAXNUMERICHOST <= 256);
780     ptr[1] = strlen (src);
781     memcpy (ptr + 2, src, ptr[1]);
782     ptr += ptr[1] + 2;
783
784     static const char tool[] = PACKAGE_STRING;
785     ptr[0] = 6; /* TOOL */
786     ptr[1] = (sizeof (tool) > 256) ? 255 : (sizeof (tool) - 1);
787     memcpy (ptr + 2, tool, ptr[1]);
788     ptr += ptr[1] + 2;
789
790     while ((ptr - sdes) & 3) /* 32-bits padding */
791         *ptr++ = 0;
792     SetWBE (lenptr, ptr - sdes);
793
794     obj->p_sys->p_thread->rtcp_size = ptr - obj->p_sys->p_thread->rtcp_data;
795     return VLC_SUCCESS;
796 }
797
798 static void CloseRTCP (sout_access_thread_t *obj)
799 {
800     uint8_t *ptr = obj->rtcp_data;
801     /* Bye */
802     ptr[0] = (2 << 6) | 1; /* V = 2, P = 0, SC = 1 */
803     ptr[1] = 203; /* payload type: Bye */
804     SetWBE (ptr + 2, 1);
805     /* SSRC is already there :) */
806
807     /* We are THE sender, so we are more important than anybody else, so
808      * we can afford not to check bandwidth constraints here. */
809     send (obj->rtcp_handle, obj->rtcp_data, 8, 0);
810
811     if (obj->rtcp_handle != -1)
812         net_Close (obj->rtcp_handle);
813 }
814
815 static void SendRTCP (sout_access_thread_t *obj, uint32_t timestamp)
816 {
817     uint8_t *ptr = obj->rtcp_data;
818     SetQWBE (ptr + 8, NTPtime64 ());
819     SetDWBE (ptr + 16, timestamp);
820     SetDWBE (ptr + 20, obj->sent_pkts);
821     SetDWBE (ptr + 24, obj->sent_bytes);
822
823     send (obj->rtcp_handle, ptr, obj->rtcp_size, 0);
824 }