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