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