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