]> git.sesse.net Git - vlc/blob - modules/access_output/udp.c
Remove dead RTCP code
[vlc] / modules / access_output / udp.c
1 /*****************************************************************************
2  * udp.c
3  *****************************************************************************
4  * Copyright (C) 2001-2007 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *          Eric Petit <titer@videolan.org>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23  *****************************************************************************/
24
25 /*****************************************************************************
26  * Preamble
27  *****************************************************************************/
28 #include <vlc/vlc.h>
29
30 #include <sys/types.h>
31 #include <sys/stat.h>
32 #include <errno.h>
33 #include <fcntl.h>
34 #include <assert.h>
35
36 #include <vlc_sout.h>
37 #include <vlc_block.h>
38
39 #ifdef HAVE_UNISTD_H
40 #   include <unistd.h>
41 #endif
42
43 #ifdef WIN32
44 #   include <winsock2.h>
45 #   include <ws2tcpip.h>
46 #else
47 #   include <sys/socket.h>
48 #endif
49
50 #include <vlc_network.h>
51
52 #if defined (HAVE_NETINET_UDPLITE_H)
53 # include <netinet/udplite.h>
54 #elif defined (__linux__)
55 # define UDPLITE_SEND_CSCOV     10
56 # define UDPLITE_RECV_CSCOV     11
57 #endif
58
59 #ifndef IPPROTO_UDPLITE
60 # define IPPROTO_UDPLITE 136 /* from IANA */
61 #endif
62 #ifndef SOL_UDPLITE
63 # define SOL_UDPLITE IPPROTO_UDPLITE
64 #endif
65
66 #define MAX_EMPTY_BLOCKS 200
67
68 #if defined(WIN32) || defined(UNDER_CE)
69 # define WINSOCK_STRERROR_SIZE 20
70 static const char *winsock_strerror( char *buf )
71 {
72     snprintf( buf, WINSOCK_STRERROR_SIZE, "Winsock error %d",
73               WSAGetLastError( ) );
74     buf[WINSOCK_STRERROR_SIZE - 1] = '\0';
75     return buf;
76 }
77 #endif
78
79 /*****************************************************************************
80  * Module descriptor
81  *****************************************************************************/
82 static int  Open ( vlc_object_t * );
83 static void Close( vlc_object_t * );
84
85 #define SOUT_CFG_PREFIX "sout-udp-"
86
87 #define CACHING_TEXT N_("Caching value (ms)")
88 #define CACHING_LONGTEXT N_( \
89     "Default caching value for outbound UDP streams. This " \
90     "value should be set in milliseconds." )
91
92 #define GROUP_TEXT N_("Group packets")
93 #define GROUP_LONGTEXT N_("Packets can be sent one by one at the right time " \
94                           "or by groups. You can choose the number " \
95                           "of packets that will be sent at a time. It " \
96                           "helps reducing the scheduling load on " \
97                           "heavily-loaded systems." )
98 #define AUTO_MCAST_TEXT N_("Automatic multicast streaming")
99 #define AUTO_MCAST_LONGTEXT N_("Allocates an outbound multicast address " \
100                                "automatically.")
101 #define UDPLITE_TEXT N_("UDP-Lite")
102 #define UDPLITE_LONGTEXT N_("Use UDP-Lite/IP instead of normal UDP/IP")
103 #define CSCOV_TEXT N_("Checksum coverage")
104 #define CSCOV_LONGTEXT N_("Payload bytes covered by layer-4 checksum")
105
106 vlc_module_begin();
107     set_description( _("UDP stream output") );
108     set_shortname( "UDP" );
109     set_category( CAT_SOUT );
110     set_subcategory( SUBCAT_SOUT_ACO );
111     add_integer( SOUT_CFG_PREFIX "caching", DEFAULT_PTS_DELAY / 1000, NULL, CACHING_TEXT, CACHING_LONGTEXT, VLC_TRUE );
112     add_integer( SOUT_CFG_PREFIX "group", 1, NULL, GROUP_TEXT, GROUP_LONGTEXT,
113                                  VLC_TRUE );
114     add_obsolete_integer( SOUT_CFG_PREFIX "late" );
115     add_obsolete_bool( SOUT_CFG_PREFIX "raw" );
116     add_bool( SOUT_CFG_PREFIX "auto-mcast", VLC_FALSE, NULL, AUTO_MCAST_TEXT,
117               AUTO_MCAST_LONGTEXT, VLC_TRUE );
118     add_bool( SOUT_CFG_PREFIX "udplite", VLC_FALSE, NULL, UDPLITE_TEXT, UDPLITE_LONGTEXT, VLC_TRUE );
119     add_integer( SOUT_CFG_PREFIX "cscov", 12, NULL, CSCOV_TEXT, CSCOV_LONGTEXT, VLC_TRUE );
120
121     set_capability( "sout access", 100 );
122     add_shortcut( "udp" );
123     set_callbacks( Open, Close );
124 vlc_module_end();
125
126 /*****************************************************************************
127  * Exported prototypes
128  *****************************************************************************/
129
130 static const char *const ppsz_sout_options[] = {
131     "auto-mcast",
132     "caching",
133     "group",
134     "lite",
135     "cscov",
136     NULL
137 };
138
139 /* Options handled by the libvlc network core */
140 static const char *const ppsz_core_options[] = {
141     "dscp",
142     "ttl",
143     "miface",
144     "miface-addr",
145     NULL
146 };
147
148 static int  Write   ( sout_access_out_t *, block_t * );
149 static int  Seek    ( sout_access_out_t *, off_t  );
150
151 static void ThreadWrite( vlc_object_t * );
152 static block_t *NewUDPPacket( sout_access_out_t *, mtime_t );
153 static const char *MakeRandMulticast (int family, char *buf, size_t buflen);
154
155 typedef struct sout_access_thread_t
156 {
157     VLC_COMMON_MEMBERS
158
159     sout_instance_t *p_sout;
160
161     block_fifo_t *p_fifo;
162
163     int         i_handle;
164
165     int64_t     i_caching;
166     int         i_group;
167
168     block_fifo_t *p_empty_blocks;
169 } sout_access_thread_t;
170
171 struct sout_access_out_sys_t
172 {
173     int                 i_mtu;
174     vlc_bool_t          b_mtu_warning;
175
176     block_t             *p_buffer;
177
178     sout_access_thread_t *p_thread;
179
180 };
181
182 #define DEFAULT_PORT 1234
183 #define RTP_HEADER_LENGTH 12
184
185 /*****************************************************************************
186  * Open: open the file
187  *****************************************************************************/
188 static int Open( vlc_object_t *p_this )
189 {
190     sout_access_out_t       *p_access = (sout_access_out_t*)p_this;
191     sout_access_out_sys_t   *p_sys;
192
193     char                *psz_dst_addr = NULL;
194     int                 i_dst_port, proto = IPPROTO_UDP;
195     const char          *protoname = "UDP";
196
197     int                 i_handle;
198
199     config_ChainParse( p_access, SOUT_CFG_PREFIX,
200                        ppsz_sout_options, p_access->p_cfg );
201     config_ChainParse( p_access, "",
202                        ppsz_core_options, p_access->p_cfg );
203
204     if (var_Create (p_access, "dst-port", VLC_VAR_INTEGER)
205      || var_Create (p_access, "src-port", VLC_VAR_INTEGER)
206      || var_Create (p_access, "dst-addr", VLC_VAR_STRING)
207      || var_Create (p_access, "src-addr", VLC_VAR_STRING))
208     {
209         return VLC_ENOMEM;
210     }
211
212     if( !( p_sys = calloc ( 1, sizeof( sout_access_out_sys_t ) ) ) )
213     {
214         msg_Err( p_access, "not enough memory" );
215         return VLC_ENOMEM;
216     }
217     p_access->p_sys = p_sys;
218
219     if (var_GetBool (p_access, SOUT_CFG_PREFIX"lite"))
220     {
221         protoname = "UDP-Lite";
222         proto = IPPROTO_UDPLITE;
223     }
224
225     i_dst_port = DEFAULT_PORT;
226     if (var_GetBool (p_access, SOUT_CFG_PREFIX"auto-mcast"))
227     {
228         char buf[INET6_ADDRSTRLEN];
229         if (MakeRandMulticast (AF_INET, buf, sizeof (buf)) != NULL)
230             psz_dst_addr = strdup (buf);
231     }
232     else
233     {
234         char *psz_parser = psz_dst_addr = strdup( p_access->psz_path );
235
236         if (psz_parser[0] == '[')
237             psz_parser = strchr (psz_parser, ']');
238
239         psz_parser = strchr (psz_parser ?: psz_dst_addr, ':');
240         if (psz_parser != NULL)
241         {
242             *psz_parser++ = '\0';
243             i_dst_port = atoi (psz_parser);
244         }
245     }
246
247     p_sys->p_thread =
248         vlc_object_create( p_access, sizeof( sout_access_thread_t ) );
249     if( !p_sys->p_thread )
250     {
251         msg_Err( p_access, "out of memory" );
252         free (p_sys);
253         free (psz_dst_addr);
254         return VLC_ENOMEM;
255     }
256
257     vlc_object_attach( p_sys->p_thread, p_access );
258     p_sys->p_thread->p_sout = p_access->p_sout;
259     p_sys->p_thread->b_die  = 0;
260     p_sys->p_thread->b_error= 0;
261     p_sys->p_thread->p_fifo = block_FifoNew( p_access );
262     p_sys->p_thread->p_empty_blocks = block_FifoNew( p_access );
263
264     i_handle = net_ConnectDgram( p_this, psz_dst_addr, i_dst_port, -1, proto );
265     free (psz_dst_addr);
266
267     if( i_handle == -1 )
268     {
269          msg_Err( p_access, "failed to create %s socket", protoname );
270          vlc_object_destroy (p_sys->p_thread);
271          free (p_sys);
272          return VLC_EGENERIC;
273     }
274     else
275     {
276         char addr[NI_MAXNUMERICHOST];
277         int port;
278
279         if (net_GetSockAddress (i_handle, addr, &port) == 0)
280         {
281             msg_Dbg (p_access, "source: %s port %d", addr, port);
282             var_SetString (p_access, "src-addr", addr);
283             var_SetInteger (p_access, "src-port", port);
284         }
285
286         if (net_GetPeerAddress (i_handle, addr, &port) == 0)
287         {
288             msg_Dbg (p_access, "destination: %s port %d", addr, port);
289             var_SetString (p_access, "dst-addr", addr);
290             var_SetInteger (p_access, "dst-port", port);
291         }
292     }
293     p_sys->p_thread->i_handle = i_handle;
294     shutdown( i_handle, SHUT_RD );
295
296     int cscov = var_GetInteger (p_access, SOUT_CFG_PREFIX"cscov");
297     if (cscov)
298     {
299         switch (proto)
300         {
301 #ifdef UDPLITE_SEND_CSCOV
302             case IPPROTO_UDPLITE:
303                 cscov += 8;
304                 setsockopt (i_handle, SOL_UDPLITE, UDPLITE_SEND_CSCOV,
305                             &(int){ cscov }, sizeof (cscov));
306                 break;
307 #endif
308 #ifdef DCCP_SOCKOPT_RECV_CSCOV
309             /* FIXME: ^^is this the right name ? */
310             /* FIXME: is this inherited by accept() ? */
311             case IPPROTO_DCCP:
312                 cscov = ((cscov + 3) >> 2) + 1;
313                 if (cscov > 15)
314                     break; /* out of DCCP cscov range */
315                 setsockopt (i_handle, SOL_DCCP, DCCP_SOCKOPT_RECV_CSCOV,
316                             &(int){ cscov }, sizeof (cscov));
317                 break;
318 #endif
319         }
320     }
321
322     p_sys->p_thread->i_caching =
323         (int64_t)1000 * var_GetInteger( p_access, SOUT_CFG_PREFIX "caching");
324     p_sys->p_thread->i_group =
325         var_GetInteger( p_access, SOUT_CFG_PREFIX "group" );
326
327     p_sys->i_mtu = var_CreateGetInteger( p_this, "mtu" );
328     p_sys->p_buffer = NULL;
329
330     if( vlc_thread_create( p_sys->p_thread, "sout write thread", ThreadWrite,
331                            VLC_THREAD_PRIORITY_HIGHEST, VLC_FALSE ) )
332     {
333         msg_Err( p_access->p_sout, "cannot spawn sout access thread" );
334         net_Close (i_handle);
335         vlc_object_destroy( p_sys->p_thread );
336         free (p_sys);
337         return VLC_EGENERIC;
338     }
339
340     p_access->pf_write = Write;
341     p_access->pf_seek = Seek;
342
343     /* update p_sout->i_out_pace_nocontrol */
344     p_access->p_sout->i_out_pace_nocontrol++;
345
346     return VLC_SUCCESS;
347 }
348
349 /*****************************************************************************
350  * Close: close the target
351  *****************************************************************************/
352 static void Close( vlc_object_t * p_this )
353 {
354     sout_access_out_t     *p_access = (sout_access_out_t*)p_this;
355     sout_access_out_sys_t *p_sys = p_access->p_sys;
356     int i;
357
358     vlc_object_kill( p_sys->p_thread );
359     for( i = 0; i < 10; i++ )
360     {
361         block_t *p_dummy = block_New( p_access, p_sys->i_mtu );
362         p_dummy->i_dts = 0;
363         p_dummy->i_pts = 0;
364         p_dummy->i_length = 0;
365         memset( p_dummy->p_buffer, 0, p_dummy->i_buffer );
366         block_FifoPut( p_sys->p_thread->p_fifo, p_dummy );
367     }
368     vlc_thread_join( p_sys->p_thread );
369
370     block_FifoRelease( p_sys->p_thread->p_fifo );
371     block_FifoRelease( p_sys->p_thread->p_empty_blocks );
372
373     if( p_sys->p_buffer ) block_Release( p_sys->p_buffer );
374
375     net_Close( p_sys->p_thread->i_handle );
376
377     vlc_object_detach( p_sys->p_thread );
378     vlc_object_destroy( p_sys->p_thread );
379     /* update p_sout->i_out_pace_nocontrol */
380     p_access->p_sout->i_out_pace_nocontrol--;
381
382     msg_Dbg( p_access, "UDP access output closed" );
383     free( p_sys );
384 }
385
386 /*****************************************************************************
387  * Write: standard write on a file descriptor.
388  *****************************************************************************/
389 static int Write( sout_access_out_t *p_access, block_t *p_buffer )
390 {
391     sout_access_out_sys_t *p_sys = p_access->p_sys;
392     int i_len = 0;
393
394     while( p_buffer )
395     {
396         block_t *p_next;
397         int i_packets = 0;
398         mtime_t now = mdate();
399
400         if( !p_sys->b_mtu_warning && p_buffer->i_buffer > p_sys->i_mtu )
401         {
402             msg_Warn( p_access, "packet size > MTU, you should probably "
403                       "increase the MTU" );
404             p_sys->b_mtu_warning = VLC_TRUE;
405         }
406
407         /* Check if there is enough space in the buffer */
408         if( p_sys->p_buffer &&
409             p_sys->p_buffer->i_buffer + p_buffer->i_buffer > p_sys->i_mtu )
410         {
411             if( p_sys->p_buffer->i_dts + p_sys->p_thread->i_caching < now )
412             {
413                 msg_Dbg( p_access, "late packet for UDP input (" I64Fd ")",
414                          now - p_sys->p_buffer->i_dts
415                           - p_sys->p_thread->i_caching );
416             }
417             block_FifoPut( p_sys->p_thread->p_fifo, p_sys->p_buffer );
418             p_sys->p_buffer = NULL;
419         }
420
421         i_len += p_buffer->i_buffer;
422         while( p_buffer->i_buffer )
423         {
424             int i_payload_size = p_sys->i_mtu;
425
426             int i_write = __MIN( p_buffer->i_buffer, i_payload_size );
427
428             i_packets++;
429
430             if( !p_sys->p_buffer )
431             {
432                 p_sys->p_buffer = NewUDPPacket( p_access, p_buffer->i_dts );
433                 if( !p_sys->p_buffer ) break;
434             }
435
436             memcpy( p_sys->p_buffer->p_buffer + p_sys->p_buffer->i_buffer,
437                     p_buffer->p_buffer, i_write );
438
439             p_sys->p_buffer->i_buffer += i_write;
440             p_buffer->p_buffer += i_write;
441             p_buffer->i_buffer -= i_write;
442             if ( p_buffer->i_flags & BLOCK_FLAG_CLOCK )
443             {
444                 if ( p_sys->p_buffer->i_flags & BLOCK_FLAG_CLOCK )
445                     msg_Warn( p_access, "putting two PCRs at once" );
446                 p_sys->p_buffer->i_flags |= BLOCK_FLAG_CLOCK;
447             }
448
449             if( p_sys->p_buffer->i_buffer == p_sys->i_mtu || i_packets > 1 )
450             {
451                 /* Flush */
452                 if( p_sys->p_buffer->i_dts + p_sys->p_thread->i_caching < now )
453                 {
454                     msg_Dbg( p_access, "late packet for udp input (" I64Fd ")",
455                              mdate() - p_sys->p_buffer->i_dts
456                               - p_sys->p_thread->i_caching );
457                 }
458                 block_FifoPut( p_sys->p_thread->p_fifo, p_sys->p_buffer );
459                 p_sys->p_buffer = NULL;
460             }
461         }
462
463         p_next = p_buffer->p_next;
464         block_Release( p_buffer );
465         p_buffer = p_next;
466     }
467
468     return( p_sys->p_thread->b_error ? -1 : i_len );
469 }
470
471 /*****************************************************************************
472  * Seek: seek to a specific location in a file
473  *****************************************************************************/
474 static int Seek( sout_access_out_t *p_access, off_t i_pos )
475 {
476     msg_Err( p_access, "UDP sout access cannot seek" );
477     return -1;
478 }
479
480 /*****************************************************************************
481  * NewUDPPacket: allocate a new UDP packet of size p_sys->i_mtu
482  *****************************************************************************/
483 static block_t *NewUDPPacket( sout_access_out_t *p_access, mtime_t i_dts)
484 {
485     sout_access_out_sys_t *p_sys = p_access->p_sys;
486     block_t *p_buffer;
487
488     while ( p_sys->p_thread->p_empty_blocks->i_depth > MAX_EMPTY_BLOCKS )
489     {
490         p_buffer = block_FifoGet( p_sys->p_thread->p_empty_blocks );
491         block_Release( p_buffer );
492     }
493
494     if( p_sys->p_thread->p_empty_blocks->i_depth == 0 )
495     {
496         p_buffer = block_New( p_access->p_sout, p_sys->i_mtu );
497     }
498     else
499     {
500         p_buffer = block_FifoGet(p_sys->p_thread->p_empty_blocks );
501         p_buffer->i_flags = 0;
502         p_buffer = block_Realloc( p_buffer, 0, p_sys->i_mtu );
503     }
504
505     p_buffer->i_dts = i_dts;
506     p_buffer->i_buffer = 0;
507
508     return p_buffer;
509 }
510
511 /*****************************************************************************
512  * ThreadWrite: Write a packet on the network at the good time.
513  *****************************************************************************/
514 static void ThreadWrite( vlc_object_t *p_this )
515 {
516     sout_access_thread_t *p_thread = (sout_access_thread_t*)p_this;
517     mtime_t              i_date_last = -1;
518     mtime_t              i_to_send = p_thread->i_group;
519     int                  i_dropped_packets = 0;
520 #if defined(WIN32) || defined(UNDER_CE)
521     char strerror_buf[WINSOCK_STRERROR_SIZE];
522 # define strerror( x ) winsock_strerror( strerror_buf )
523 #endif
524
525     while( !p_thread->b_die )
526     {
527         block_t *p_pk;
528         mtime_t       i_date, i_sent;
529 #if 0
530         if( (i++ % 1000)==0 ) {
531           int i = 0;
532           int j = 0;
533           block_t *p_tmp = p_thread->p_empty_blocks->p_first;
534           while( p_tmp ) { p_tmp = p_tmp->p_next; i++;}
535           p_tmp = p_thread->p_fifo->p_first;
536           while( p_tmp ) { p_tmp = p_tmp->p_next; j++;}
537           msg_Dbg( p_thread, "fifo depth: %d/%d, empty blocks: %d/%d",
538                    p_thread->p_fifo->i_depth, j,p_thread->p_empty_blocks->i_depth,i );
539         }
540 #endif
541         p_pk = block_FifoGet( p_thread->p_fifo );
542
543         i_date = p_thread->i_caching + p_pk->i_dts;
544         if( i_date_last > 0 )
545         {
546             if( i_date - i_date_last > 2000000 )
547             {
548                 if( !i_dropped_packets )
549                     msg_Dbg( p_thread, "mmh, hole ("I64Fd" > 2s) -> drop",
550                              i_date - i_date_last );
551
552                 block_FifoPut( p_thread->p_empty_blocks, p_pk );
553
554                 i_date_last = i_date;
555                 i_dropped_packets++;
556                 continue;
557             }
558             else if( i_date - i_date_last < -1000 )
559             {
560                 if( !i_dropped_packets )
561                     msg_Dbg( p_thread, "mmh, packets in the past ("I64Fd")",
562                              i_date_last - i_date );
563             }
564         }
565
566         i_to_send--;
567         if( !i_to_send || (p_pk->i_flags & BLOCK_FLAG_CLOCK) )
568         {
569             mwait( i_date );
570             i_to_send = p_thread->i_group;
571         }
572         ssize_t val = send( p_thread->i_handle, p_pk->p_buffer,
573                             p_pk->i_buffer, 0 );
574         if (val == -1)
575         {
576             msg_Warn( p_thread, "send error: %s", strerror(errno) );
577         }
578
579         if( i_dropped_packets )
580         {
581             msg_Dbg( p_thread, "dropped %i packets", i_dropped_packets );
582             i_dropped_packets = 0;
583         }
584
585 #if 1
586         i_sent = mdate();
587         if ( i_sent > i_date + 20000 )
588         {
589             msg_Dbg( p_thread, "packet has been sent too late (" I64Fd ")",
590                      i_sent - i_date );
591         }
592 #endif
593
594         block_FifoPut( p_thread->p_empty_blocks, p_pk );
595
596         i_date_last = i_date;
597     }
598 }
599
600
601 static const char *MakeRandMulticast (int family, char *buf, size_t buflen)
602 {
603     uint32_t rand = (getpid() & 0xffff)
604                   | (uint32_t)(((mdate () >> 10) & 0xffff) << 16);
605
606     switch (family)
607     {
608 #ifdef AF_INET6
609         case AF_INET6:
610         {
611             struct in6_addr addr;
612             memcpy (&addr, "\xff\x38\x00\x00" "\x00\x00\x00\x00"
613                            "\x00\x00\x00\x00", 12);
614             rand |= 0x80000000;
615             memcpy (addr.s6_addr + 12, &(uint32_t){ htonl (rand) }, 4);
616             return inet_ntop (family, &addr, buf, buflen);
617         }
618 #endif
619
620         case AF_INET:
621         {
622             struct in_addr addr;
623             addr.s_addr = htonl ((rand & 0xffffff) | 0xe8000000);
624             return inet_ntop (family, &addr, buf, buflen);
625         }
626     }
627 #ifdef EAFNOSUPPORT
628     errno = EAFNOSUPPORT;
629 #endif
630     return NULL;
631 }
632
633