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