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