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