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