]> git.sesse.net Git - vlc/blob - modules/access_output/udp.c
Merge branch 'master' of git@git.videolan.org:vlc
[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 #ifdef HAVE_CONFIG_H
29 # include "config.h"
30 #endif
31
32 #include <vlc/vlc.h>
33
34 #include <sys/types.h>
35 #include <sys/stat.h>
36 #include <errno.h>
37 #include <fcntl.h>
38 #include <assert.h>
39
40 #include <vlc_sout.h>
41 #include <vlc_block.h>
42
43 #ifdef HAVE_UNISTD_H
44 #   include <unistd.h>
45 #endif
46
47 #ifdef WIN32
48 #   include <winsock2.h>
49 #   include <ws2tcpip.h>
50 #else
51 #   include <sys/socket.h>
52 #endif
53
54 #include <vlc_network.h>
55
56 #define MAX_EMPTY_BLOCKS 200
57
58 /*****************************************************************************
59  * Module descriptor
60  *****************************************************************************/
61 static int  Open ( vlc_object_t * );
62 static void Close( vlc_object_t * );
63
64 #define SOUT_CFG_PREFIX "sout-udp-"
65
66 #define CACHING_TEXT N_("Caching value (ms)")
67 #define CACHING_LONGTEXT N_( \
68     "Default caching value for outbound UDP streams. This " \
69     "value should be set in milliseconds." )
70
71 #define GROUP_TEXT N_("Group packets")
72 #define GROUP_LONGTEXT N_("Packets can be sent one by one at the right time " \
73                           "or by groups. You can choose the number " \
74                           "of packets that will be sent at a time. It " \
75                           "helps reducing the scheduling load on " \
76                           "heavily-loaded systems." )
77 #define AUTO_MCAST_TEXT N_("Automatic multicast streaming")
78 #define AUTO_MCAST_LONGTEXT N_("Allocates an outbound multicast address " \
79                                "automatically.")
80
81 vlc_module_begin();
82     set_description( _("UDP stream output") );
83     set_shortname( "UDP" );
84     set_category( CAT_SOUT );
85     set_subcategory( SUBCAT_SOUT_ACO );
86     add_integer( SOUT_CFG_PREFIX "caching", DEFAULT_PTS_DELAY / 1000, NULL, CACHING_TEXT, CACHING_LONGTEXT, true );
87     add_integer( SOUT_CFG_PREFIX "group", 1, NULL, GROUP_TEXT, GROUP_LONGTEXT,
88                                  true );
89     add_obsolete_integer( SOUT_CFG_PREFIX "late" );
90     add_obsolete_bool( SOUT_CFG_PREFIX "raw" );
91     add_bool( SOUT_CFG_PREFIX "auto-mcast", false, NULL, AUTO_MCAST_TEXT,
92               AUTO_MCAST_LONGTEXT, true );
93
94     set_capability( "sout access", 100 );
95     add_shortcut( "udp" );
96     set_callbacks( Open, Close );
97 vlc_module_end();
98
99 /*****************************************************************************
100  * Exported prototypes
101  *****************************************************************************/
102
103 static const char *const ppsz_sout_options[] = {
104     "auto-mcast",
105     "caching",
106     "group",
107     NULL
108 };
109
110 /* Options handled by the libvlc network core */
111 static const char *const ppsz_core_options[] = {
112     "dscp",
113     "ttl",
114     "miface",
115     "miface-addr",
116     NULL
117 };
118
119 static ssize_t Write   ( sout_access_out_t *, block_t * );
120 static int  Seek    ( sout_access_out_t *, off_t  );
121
122 static void ThreadWrite( vlc_object_t * );
123 static block_t *NewUDPPacket( sout_access_out_t *, mtime_t );
124 static const char *MakeRandMulticast (int family, char *buf, size_t buflen);
125
126 typedef struct sout_access_thread_t
127 {
128     VLC_COMMON_MEMBERS
129
130     sout_instance_t *p_sout;
131
132     block_fifo_t *p_fifo;
133
134     int         i_handle;
135
136     int64_t     i_caching;
137     int         i_group;
138
139     block_fifo_t *p_empty_blocks;
140 } sout_access_thread_t;
141
142 struct sout_access_out_sys_t
143 {
144     int                 i_mtu;
145     bool          b_mtu_warning;
146
147     block_t             *p_buffer;
148
149     sout_access_thread_t *p_thread;
150
151 };
152
153 #define DEFAULT_PORT 1234
154
155 /*****************************************************************************
156  * Open: open the file
157  *****************************************************************************/
158 static int Open( vlc_object_t *p_this )
159 {
160     sout_access_out_t       *p_access = (sout_access_out_t*)p_this;
161     sout_access_out_sys_t   *p_sys;
162
163     char                *psz_dst_addr = NULL;
164     int                 i_dst_port;
165
166     int                 i_handle;
167
168     config_ChainParse( p_access, SOUT_CFG_PREFIX,
169                        ppsz_sout_options, p_access->p_cfg );
170     config_ChainParse( p_access, "",
171                        ppsz_core_options, p_access->p_cfg );
172
173     if (var_Create (p_access, "dst-port", VLC_VAR_INTEGER)
174      || var_Create (p_access, "src-port", VLC_VAR_INTEGER)
175      || var_Create (p_access, "dst-addr", VLC_VAR_STRING)
176      || var_Create (p_access, "src-addr", VLC_VAR_STRING))
177     {
178         return VLC_ENOMEM;
179     }
180
181     if( !( p_sys = calloc ( 1, sizeof( sout_access_out_sys_t ) ) ) )
182     {
183         msg_Err( p_access, "not enough memory" );
184         return VLC_ENOMEM;
185     }
186     p_access->p_sys = p_sys;
187
188     i_dst_port = DEFAULT_PORT;
189     if (var_GetBool (p_access, SOUT_CFG_PREFIX"auto-mcast"))
190     {
191         char buf[INET6_ADDRSTRLEN];
192         if (MakeRandMulticast (AF_INET, buf, sizeof (buf)) != NULL)
193             psz_dst_addr = strdup (buf);
194     }
195     else
196     {
197         char *psz_parser = psz_dst_addr = strdup( p_access->psz_path );
198
199         if (psz_parser[0] == '[')
200             psz_parser = strchr (psz_parser, ']');
201
202         psz_parser = strchr (psz_parser ?: psz_dst_addr, ':');
203         if (psz_parser != NULL)
204         {
205             *psz_parser++ = '\0';
206             i_dst_port = atoi (psz_parser);
207         }
208     }
209
210     p_sys->p_thread =
211         vlc_object_create( p_access, sizeof( sout_access_thread_t ) );
212     if( !p_sys->p_thread )
213     {
214         msg_Err( p_access, "out of memory" );
215         free (p_sys);
216         free (psz_dst_addr);
217         return VLC_ENOMEM;
218     }
219
220     vlc_object_attach( p_sys->p_thread, p_access );
221     p_sys->p_thread->p_sout = p_access->p_sout;
222     p_sys->p_thread->b_die  = 0;
223     p_sys->p_thread->b_error= 0;
224     p_sys->p_thread->p_fifo = block_FifoNew( p_access );
225     p_sys->p_thread->p_empty_blocks = block_FifoNew( p_access );
226
227     i_handle = net_ConnectDgram( p_this, psz_dst_addr, i_dst_port, -1,
228                                  IPPROTO_UDP );
229     free (psz_dst_addr);
230
231     if( i_handle == -1 )
232     {
233          msg_Err( p_access, "failed to create raw UDP socket" );
234          vlc_object_release (p_sys->p_thread);
235          free (p_sys);
236          return VLC_EGENERIC;
237     }
238     else
239     {
240         char addr[NI_MAXNUMERICHOST];
241         int port;
242
243         if (net_GetSockAddress (i_handle, addr, &port) == 0)
244         {
245             msg_Dbg (p_access, "source: %s port %d", addr, port);
246             var_SetString (p_access, "src-addr", addr);
247             var_SetInteger (p_access, "src-port", port);
248         }
249
250         if (net_GetPeerAddress (i_handle, addr, &port) == 0)
251         {
252             msg_Dbg (p_access, "destination: %s port %d", addr, port);
253             var_SetString (p_access, "dst-addr", addr);
254             var_SetInteger (p_access, "dst-port", port);
255         }
256     }
257     p_sys->p_thread->i_handle = i_handle;
258     shutdown( i_handle, SHUT_RD );
259
260     p_sys->p_thread->i_caching =
261         (int64_t)1000 * var_GetInteger( p_access, SOUT_CFG_PREFIX "caching");
262     p_sys->p_thread->i_group =
263         var_GetInteger( p_access, SOUT_CFG_PREFIX "group" );
264
265     p_sys->i_mtu = var_CreateGetInteger( p_this, "mtu" );
266     p_sys->p_buffer = NULL;
267
268     if( vlc_thread_create( p_sys->p_thread, "sout write thread", ThreadWrite,
269                            VLC_THREAD_PRIORITY_HIGHEST, false ) )
270     {
271         msg_Err( p_access->p_sout, "cannot spawn sout access thread" );
272         net_Close (i_handle);
273         vlc_object_release( p_sys->p_thread );
274         free (p_sys);
275         return VLC_EGENERIC;
276     }
277
278     p_access->pf_write = Write;
279     p_access->pf_seek = Seek;
280
281     /* update p_sout->i_out_pace_nocontrol */
282     p_access->p_sout->i_out_pace_nocontrol++;
283
284     return VLC_SUCCESS;
285 }
286
287 /*****************************************************************************
288  * Close: close the target
289  *****************************************************************************/
290 static void Close( vlc_object_t * p_this )
291 {
292     sout_access_out_t     *p_access = (sout_access_out_t*)p_this;
293     sout_access_out_sys_t *p_sys = p_access->p_sys;
294     int i;
295
296     vlc_object_kill( p_sys->p_thread );
297     block_FifoWake( p_sys->p_thread->p_fifo );
298
299     for( i = 0; i < 10; i++ )
300     {
301         block_t *p_dummy = block_New( p_access, p_sys->i_mtu );
302         p_dummy->i_dts = 0;
303         p_dummy->i_pts = 0;
304         p_dummy->i_length = 0;
305         memset( p_dummy->p_buffer, 0, p_dummy->i_buffer );
306         block_FifoPut( p_sys->p_thread->p_fifo, p_dummy );
307     }
308     vlc_thread_join( p_sys->p_thread );
309
310     block_FifoRelease( p_sys->p_thread->p_fifo );
311     block_FifoRelease( p_sys->p_thread->p_empty_blocks );
312
313     if( p_sys->p_buffer ) block_Release( p_sys->p_buffer );
314
315     net_Close( p_sys->p_thread->i_handle );
316
317     vlc_object_detach( p_sys->p_thread );
318     vlc_object_release( p_sys->p_thread );
319     /* update p_sout->i_out_pace_nocontrol */
320     p_access->p_sout->i_out_pace_nocontrol--;
321
322     msg_Dbg( p_access, "UDP access output closed" );
323     free( p_sys );
324 }
325
326 /*****************************************************************************
327  * Write: standard write on a file descriptor.
328  *****************************************************************************/
329 static ssize_t Write( sout_access_out_t *p_access, block_t *p_buffer )
330 {
331     sout_access_out_sys_t *p_sys = p_access->p_sys;
332     int i_len = 0;
333
334     while( p_buffer )
335     {
336         block_t *p_next;
337         int i_packets = 0;
338         mtime_t now = mdate();
339
340         if( !p_sys->b_mtu_warning && p_buffer->i_buffer > p_sys->i_mtu )
341         {
342             msg_Warn( p_access, "packet size > MTU, you should probably "
343                       "increase the MTU" );
344             p_sys->b_mtu_warning = true;
345         }
346
347         /* Check if there is enough space in the buffer */
348         if( p_sys->p_buffer &&
349             p_sys->p_buffer->i_buffer + p_buffer->i_buffer > p_sys->i_mtu )
350         {
351             if( p_sys->p_buffer->i_dts + p_sys->p_thread->i_caching < now )
352             {
353                 msg_Dbg( p_access, "late packet for UDP input (" I64Fd ")",
354                          now - p_sys->p_buffer->i_dts
355                           - p_sys->p_thread->i_caching );
356             }
357             block_FifoPut( p_sys->p_thread->p_fifo, p_sys->p_buffer );
358             p_sys->p_buffer = NULL;
359         }
360
361         i_len += p_buffer->i_buffer;
362         while( p_buffer->i_buffer )
363         {
364             int i_payload_size = p_sys->i_mtu;
365
366             int i_write = __MIN( p_buffer->i_buffer, i_payload_size );
367
368             i_packets++;
369
370             if( !p_sys->p_buffer )
371             {
372                 p_sys->p_buffer = NewUDPPacket( p_access, p_buffer->i_dts );
373                 if( !p_sys->p_buffer ) break;
374             }
375
376             memcpy( p_sys->p_buffer->p_buffer + p_sys->p_buffer->i_buffer,
377                     p_buffer->p_buffer, i_write );
378
379             p_sys->p_buffer->i_buffer += i_write;
380             p_buffer->p_buffer += i_write;
381             p_buffer->i_buffer -= i_write;
382             if ( p_buffer->i_flags & BLOCK_FLAG_CLOCK )
383             {
384                 if ( p_sys->p_buffer->i_flags & BLOCK_FLAG_CLOCK )
385                     msg_Warn( p_access, "putting two PCRs at once" );
386                 p_sys->p_buffer->i_flags |= BLOCK_FLAG_CLOCK;
387             }
388
389             if( p_sys->p_buffer->i_buffer == p_sys->i_mtu || i_packets > 1 )
390             {
391                 /* Flush */
392                 if( p_sys->p_buffer->i_dts + p_sys->p_thread->i_caching < now )
393                 {
394                     msg_Dbg( p_access, "late packet for udp input (" I64Fd ")",
395                              mdate() - p_sys->p_buffer->i_dts
396                               - p_sys->p_thread->i_caching );
397                 }
398                 block_FifoPut( p_sys->p_thread->p_fifo, p_sys->p_buffer );
399                 p_sys->p_buffer = NULL;
400             }
401         }
402
403         p_next = p_buffer->p_next;
404         block_Release( p_buffer );
405         p_buffer = p_next;
406     }
407
408     return( p_sys->p_thread->b_error ? -1 : i_len );
409 }
410
411 /*****************************************************************************
412  * Seek: seek to a specific location in a file
413  *****************************************************************************/
414 static int Seek( sout_access_out_t *p_access, off_t i_pos )
415 {
416     msg_Err( p_access, "UDP sout access cannot seek" );
417     return -1;
418 }
419
420 /*****************************************************************************
421  * NewUDPPacket: allocate a new UDP packet of size p_sys->i_mtu
422  *****************************************************************************/
423 static block_t *NewUDPPacket( sout_access_out_t *p_access, mtime_t i_dts)
424 {
425     sout_access_out_sys_t *p_sys = p_access->p_sys;
426     block_t *p_buffer;
427
428     while ( block_FifoCount( p_sys->p_thread->p_empty_blocks ) > MAX_EMPTY_BLOCKS )
429     {
430         p_buffer = block_FifoGet( p_sys->p_thread->p_empty_blocks );
431         block_Release( p_buffer );
432     }
433
434     if( block_FifoCount( p_sys->p_thread->p_empty_blocks ) == 0 )
435     {
436         p_buffer = block_New( p_access->p_sout, p_sys->i_mtu );
437     }
438     else
439     {
440         p_buffer = block_FifoGet(p_sys->p_thread->p_empty_blocks );
441         p_buffer->i_flags = 0;
442         p_buffer = block_Realloc( p_buffer, 0, p_sys->i_mtu );
443     }
444
445     p_buffer->i_dts = i_dts;
446     p_buffer->i_buffer = 0;
447
448     return p_buffer;
449 }
450
451 /*****************************************************************************
452  * ThreadWrite: Write a packet on the network at the good time.
453  *****************************************************************************/
454 static void ThreadWrite( vlc_object_t *p_this )
455 {
456     sout_access_thread_t *p_thread = (sout_access_thread_t*)p_this;
457     mtime_t              i_date_last = -1;
458     mtime_t              i_to_send = p_thread->i_group;
459     int                  i_dropped_packets = 0;
460
461     while( !p_thread->b_die )
462     {
463         block_t *p_pk;
464         mtime_t       i_date, i_sent;
465 #if 0
466         if( (i++ % 1000)==0 ) {
467           int i = 0;
468           int j = 0;
469           block_t *p_tmp = p_thread->p_empty_blocks->p_first;
470           while( p_tmp ) { p_tmp = p_tmp->p_next; i++;}
471           p_tmp = p_thread->p_fifo->p_first;
472           while( p_tmp ) { p_tmp = p_tmp->p_next; j++;}
473           msg_Dbg( p_thread, "fifo depth: %d/%d, empty blocks: %d/%d",
474                    p_thread->p_fifo->i_depth, j,p_thread->p_empty_blocks->i_depth,i );
475         }
476 #endif
477         p_pk = block_FifoGet( p_thread->p_fifo );
478         if( p_pk == NULL )
479             continue; /* forced wake-up */
480
481         i_date = p_thread->i_caching + p_pk->i_dts;
482         if( i_date_last > 0 )
483         {
484             if( i_date - i_date_last > 2000000 )
485             {
486                 if( !i_dropped_packets )
487                     msg_Dbg( p_thread, "mmh, hole ("I64Fd" > 2s) -> drop",
488                              i_date - i_date_last );
489
490                 block_FifoPut( p_thread->p_empty_blocks, p_pk );
491
492                 i_date_last = i_date;
493                 i_dropped_packets++;
494                 continue;
495             }
496             else if( i_date - i_date_last < -1000 )
497             {
498                 if( !i_dropped_packets )
499                     msg_Dbg( p_thread, "mmh, packets in the past ("I64Fd")",
500                              i_date_last - i_date );
501             }
502         }
503
504         i_to_send--;
505         if( !i_to_send || (p_pk->i_flags & BLOCK_FLAG_CLOCK) )
506         {
507             mwait( i_date );
508             i_to_send = p_thread->i_group;
509         }
510         ssize_t val = send( p_thread->i_handle, p_pk->p_buffer,
511                             p_pk->i_buffer, 0 );
512         if (val == -1)
513         {
514             msg_Warn( p_thread, "send error: %m" );
515         }
516
517         if( i_dropped_packets )
518         {
519             msg_Dbg( p_thread, "dropped %i packets", i_dropped_packets );
520             i_dropped_packets = 0;
521         }
522
523 #if 1
524         i_sent = mdate();
525         if ( i_sent > i_date + 20000 )
526         {
527             msg_Dbg( p_thread, "packet has been sent too late (" I64Fd ")",
528                      i_sent - i_date );
529         }
530 #endif
531
532         block_FifoPut( p_thread->p_empty_blocks, p_pk );
533
534         i_date_last = i_date;
535     }
536 }
537
538
539 static const char *MakeRandMulticast (int family, char *buf, size_t buflen)
540 {
541     uint32_t rand = (getpid() & 0xffff)
542                   | (uint32_t)(((mdate () >> 10) & 0xffff) << 16);
543
544     switch (family)
545     {
546 #ifdef AF_INET6
547         case AF_INET6:
548         {
549             struct in6_addr addr;
550             memcpy (&addr, "\xff\x38\x00\x00" "\x00\x00\x00\x00"
551                            "\x00\x00\x00\x00", 12);
552             rand |= 0x80000000;
553             memcpy (addr.s6_addr + 12, &(uint32_t){ htonl (rand) }, 4);
554             return inet_ntop (family, &addr, buf, buflen);
555         }
556 #endif
557
558         case AF_INET:
559         {
560             struct in_addr addr;
561             addr.s_addr = htonl ((rand & 0xffffff) | 0xe8000000);
562             return inet_ntop (family, &addr, buf, buflen);
563         }
564     }
565 #ifdef EAFNOSUPPORT
566     errno = EAFNOSUPPORT;
567 #endif
568     return NULL;
569 }