]> git.sesse.net Git - vlc/blob - modules/access_output/udp.c
misc/objects.c: Don't rely on vlc_object_destroy() to destroy objects, but expects...
[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, VLC_TRUE );
87     add_integer( SOUT_CFG_PREFIX "group", 1, NULL, GROUP_TEXT, GROUP_LONGTEXT,
88                                  VLC_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", VLC_FALSE, NULL, AUTO_MCAST_TEXT,
92               AUTO_MCAST_LONGTEXT, VLC_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     vlc_bool_t          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 #define RTP_HEADER_LENGTH 12
155
156 /*****************************************************************************
157  * Open: open the file
158  *****************************************************************************/
159 static int Open( vlc_object_t *p_this )
160 {
161     sout_access_out_t       *p_access = (sout_access_out_t*)p_this;
162     sout_access_out_sys_t   *p_sys;
163
164     char                *psz_dst_addr = NULL;
165     int                 i_dst_port;
166
167     int                 i_handle;
168
169     config_ChainParse( p_access, SOUT_CFG_PREFIX,
170                        ppsz_sout_options, p_access->p_cfg );
171     config_ChainParse( p_access, "",
172                        ppsz_core_options, p_access->p_cfg );
173
174     if (var_Create (p_access, "dst-port", VLC_VAR_INTEGER)
175      || var_Create (p_access, "src-port", VLC_VAR_INTEGER)
176      || var_Create (p_access, "dst-addr", VLC_VAR_STRING)
177      || var_Create (p_access, "src-addr", VLC_VAR_STRING))
178     {
179         return VLC_ENOMEM;
180     }
181
182     if( !( p_sys = calloc ( 1, sizeof( sout_access_out_sys_t ) ) ) )
183     {
184         msg_Err( p_access, "not enough memory" );
185         return VLC_ENOMEM;
186     }
187     p_access->p_sys = p_sys;
188
189     i_dst_port = DEFAULT_PORT;
190     if (var_GetBool (p_access, SOUT_CFG_PREFIX"auto-mcast"))
191     {
192         char buf[INET6_ADDRSTRLEN];
193         if (MakeRandMulticast (AF_INET, buf, sizeof (buf)) != NULL)
194             psz_dst_addr = strdup (buf);
195     }
196     else
197     {
198         char *psz_parser = psz_dst_addr = strdup( p_access->psz_path );
199
200         if (psz_parser[0] == '[')
201             psz_parser = strchr (psz_parser, ']');
202
203         psz_parser = strchr (psz_parser ?: psz_dst_addr, ':');
204         if (psz_parser != NULL)
205         {
206             *psz_parser++ = '\0';
207             i_dst_port = atoi (psz_parser);
208         }
209     }
210
211     p_sys->p_thread =
212         vlc_object_create( p_access, sizeof( sout_access_thread_t ) );
213     if( !p_sys->p_thread )
214     {
215         msg_Err( p_access, "out of memory" );
216         free (p_sys);
217         free (psz_dst_addr);
218         return VLC_ENOMEM;
219     }
220
221     vlc_object_attach( p_sys->p_thread, p_access );
222     p_sys->p_thread->p_sout = p_access->p_sout;
223     p_sys->p_thread->b_die  = 0;
224     p_sys->p_thread->b_error= 0;
225     p_sys->p_thread->p_fifo = block_FifoNew( p_access );
226     p_sys->p_thread->p_empty_blocks = block_FifoNew( p_access );
227
228     i_handle = net_ConnectDgram( p_this, psz_dst_addr, i_dst_port, -1,
229                                  IPPROTO_UDP );
230     free (psz_dst_addr);
231
232     if( i_handle == -1 )
233     {
234          msg_Err( p_access, "failed to create raw UDP socket" );
235          vlc_object_release (p_sys->p_thread);
236          free (p_sys);
237          return VLC_EGENERIC;
238     }
239     else
240     {
241         char addr[NI_MAXNUMERICHOST];
242         int port;
243
244         if (net_GetSockAddress (i_handle, addr, &port) == 0)
245         {
246             msg_Dbg (p_access, "source: %s port %d", addr, port);
247             var_SetString (p_access, "src-addr", addr);
248             var_SetInteger (p_access, "src-port", port);
249         }
250
251         if (net_GetPeerAddress (i_handle, addr, &port) == 0)
252         {
253             msg_Dbg (p_access, "destination: %s port %d", addr, port);
254             var_SetString (p_access, "dst-addr", addr);
255             var_SetInteger (p_access, "dst-port", port);
256         }
257     }
258     p_sys->p_thread->i_handle = i_handle;
259     shutdown( i_handle, SHUT_RD );
260
261     p_sys->p_thread->i_caching =
262         (int64_t)1000 * var_GetInteger( p_access, SOUT_CFG_PREFIX "caching");
263     p_sys->p_thread->i_group =
264         var_GetInteger( p_access, SOUT_CFG_PREFIX "group" );
265
266     p_sys->i_mtu = var_CreateGetInteger( p_this, "mtu" );
267     p_sys->p_buffer = NULL;
268
269     if( vlc_thread_create( p_sys->p_thread, "sout write thread", ThreadWrite,
270                            VLC_THREAD_PRIORITY_HIGHEST, VLC_FALSE ) )
271     {
272         msg_Err( p_access->p_sout, "cannot spawn sout access thread" );
273         net_Close (i_handle);
274         vlc_object_release( p_sys->p_thread );
275         free (p_sys);
276         return VLC_EGENERIC;
277     }
278
279     p_access->pf_write = Write;
280     p_access->pf_seek = Seek;
281
282     /* update p_sout->i_out_pace_nocontrol */
283     p_access->p_sout->i_out_pace_nocontrol++;
284
285     return VLC_SUCCESS;
286 }
287
288 /*****************************************************************************
289  * Close: close the target
290  *****************************************************************************/
291 static void Close( vlc_object_t * p_this )
292 {
293     sout_access_out_t     *p_access = (sout_access_out_t*)p_this;
294     sout_access_out_sys_t *p_sys = p_access->p_sys;
295     int i;
296
297     vlc_object_kill( p_sys->p_thread );
298     block_FifoWake( p_sys->p_thread->p_fifo );
299
300     for( i = 0; i < 10; i++ )
301     {
302         block_t *p_dummy = block_New( p_access, p_sys->i_mtu );
303         p_dummy->i_dts = 0;
304         p_dummy->i_pts = 0;
305         p_dummy->i_length = 0;
306         memset( p_dummy->p_buffer, 0, p_dummy->i_buffer );
307         block_FifoPut( p_sys->p_thread->p_fifo, p_dummy );
308     }
309     vlc_thread_join( p_sys->p_thread );
310
311     block_FifoRelease( p_sys->p_thread->p_fifo );
312     block_FifoRelease( p_sys->p_thread->p_empty_blocks );
313
314     if( p_sys->p_buffer ) block_Release( p_sys->p_buffer );
315
316     net_Close( p_sys->p_thread->i_handle );
317
318     vlc_object_detach( p_sys->p_thread );
319     vlc_object_release( p_sys->p_thread );
320     /* update p_sout->i_out_pace_nocontrol */
321     p_access->p_sout->i_out_pace_nocontrol--;
322
323     msg_Dbg( p_access, "UDP access output closed" );
324     free( p_sys );
325 }
326
327 /*****************************************************************************
328  * Write: standard write on a file descriptor.
329  *****************************************************************************/
330 static ssize_t Write( sout_access_out_t *p_access, block_t *p_buffer )
331 {
332     sout_access_out_sys_t *p_sys = p_access->p_sys;
333     int i_len = 0;
334
335     while( p_buffer )
336     {
337         block_t *p_next;
338         int i_packets = 0;
339         mtime_t now = mdate();
340
341         if( !p_sys->b_mtu_warning && p_buffer->i_buffer > p_sys->i_mtu )
342         {
343             msg_Warn( p_access, "packet size > MTU, you should probably "
344                       "increase the MTU" );
345             p_sys->b_mtu_warning = VLC_TRUE;
346         }
347
348         /* Check if there is enough space in the buffer */
349         if( p_sys->p_buffer &&
350             p_sys->p_buffer->i_buffer + p_buffer->i_buffer > p_sys->i_mtu )
351         {
352             if( p_sys->p_buffer->i_dts + p_sys->p_thread->i_caching < now )
353             {
354                 msg_Dbg( p_access, "late packet for UDP input (" I64Fd ")",
355                          now - p_sys->p_buffer->i_dts
356                           - p_sys->p_thread->i_caching );
357             }
358             block_FifoPut( p_sys->p_thread->p_fifo, p_sys->p_buffer );
359             p_sys->p_buffer = NULL;
360         }
361
362         i_len += p_buffer->i_buffer;
363         while( p_buffer->i_buffer )
364         {
365             int i_payload_size = p_sys->i_mtu;
366
367             int i_write = __MIN( p_buffer->i_buffer, i_payload_size );
368
369             i_packets++;
370
371             if( !p_sys->p_buffer )
372             {
373                 p_sys->p_buffer = NewUDPPacket( p_access, p_buffer->i_dts );
374                 if( !p_sys->p_buffer ) break;
375             }
376
377             memcpy( p_sys->p_buffer->p_buffer + p_sys->p_buffer->i_buffer,
378                     p_buffer->p_buffer, i_write );
379
380             p_sys->p_buffer->i_buffer += i_write;
381             p_buffer->p_buffer += i_write;
382             p_buffer->i_buffer -= i_write;
383             if ( p_buffer->i_flags & BLOCK_FLAG_CLOCK )
384             {
385                 if ( p_sys->p_buffer->i_flags & BLOCK_FLAG_CLOCK )
386                     msg_Warn( p_access, "putting two PCRs at once" );
387                 p_sys->p_buffer->i_flags |= BLOCK_FLAG_CLOCK;
388             }
389
390             if( p_sys->p_buffer->i_buffer == p_sys->i_mtu || i_packets > 1 )
391             {
392                 /* Flush */
393                 if( p_sys->p_buffer->i_dts + p_sys->p_thread->i_caching < now )
394                 {
395                     msg_Dbg( p_access, "late packet for udp input (" I64Fd ")",
396                              mdate() - p_sys->p_buffer->i_dts
397                               - p_sys->p_thread->i_caching );
398                 }
399                 block_FifoPut( p_sys->p_thread->p_fifo, p_sys->p_buffer );
400                 p_sys->p_buffer = NULL;
401             }
402         }
403
404         p_next = p_buffer->p_next;
405         block_Release( p_buffer );
406         p_buffer = p_next;
407     }
408
409     return( p_sys->p_thread->b_error ? -1 : i_len );
410 }
411
412 /*****************************************************************************
413  * Seek: seek to a specific location in a file
414  *****************************************************************************/
415 static int Seek( sout_access_out_t *p_access, off_t i_pos )
416 {
417     msg_Err( p_access, "UDP sout access cannot seek" );
418     return -1;
419 }
420
421 /*****************************************************************************
422  * NewUDPPacket: allocate a new UDP packet of size p_sys->i_mtu
423  *****************************************************************************/
424 static block_t *NewUDPPacket( sout_access_out_t *p_access, mtime_t i_dts)
425 {
426     sout_access_out_sys_t *p_sys = p_access->p_sys;
427     block_t *p_buffer;
428
429     while ( block_FifoCount( p_sys->p_thread->p_empty_blocks ) > MAX_EMPTY_BLOCKS )
430     {
431         p_buffer = block_FifoGet( p_sys->p_thread->p_empty_blocks );
432         block_Release( p_buffer );
433     }
434
435     if( block_FifoCount( p_sys->p_thread->p_empty_blocks ) == 0 )
436     {
437         p_buffer = block_New( p_access->p_sout, p_sys->i_mtu );
438     }
439     else
440     {
441         p_buffer = block_FifoGet(p_sys->p_thread->p_empty_blocks );
442         p_buffer->i_flags = 0;
443         p_buffer = block_Realloc( p_buffer, 0, p_sys->i_mtu );
444     }
445
446     p_buffer->i_dts = i_dts;
447     p_buffer->i_buffer = 0;
448
449     return p_buffer;
450 }
451
452 /*****************************************************************************
453  * ThreadWrite: Write a packet on the network at the good time.
454  *****************************************************************************/
455 static void ThreadWrite( vlc_object_t *p_this )
456 {
457     sout_access_thread_t *p_thread = (sout_access_thread_t*)p_this;
458     mtime_t              i_date_last = -1;
459     mtime_t              i_to_send = p_thread->i_group;
460     int                  i_dropped_packets = 0;
461
462     while( !p_thread->b_die )
463     {
464         block_t *p_pk;
465         mtime_t       i_date, i_sent;
466 #if 0
467         if( (i++ % 1000)==0 ) {
468           int i = 0;
469           int j = 0;
470           block_t *p_tmp = p_thread->p_empty_blocks->p_first;
471           while( p_tmp ) { p_tmp = p_tmp->p_next; i++;}
472           p_tmp = p_thread->p_fifo->p_first;
473           while( p_tmp ) { p_tmp = p_tmp->p_next; j++;}
474           msg_Dbg( p_thread, "fifo depth: %d/%d, empty blocks: %d/%d",
475                    p_thread->p_fifo->i_depth, j,p_thread->p_empty_blocks->i_depth,i );
476         }
477 #endif
478         p_pk = block_FifoGet( p_thread->p_fifo );
479         if( p_pk == NULL )
480             continue; /* forced wake-up */
481
482         i_date = p_thread->i_caching + p_pk->i_dts;
483         if( i_date_last > 0 )
484         {
485             if( i_date - i_date_last > 2000000 )
486             {
487                 if( !i_dropped_packets )
488                     msg_Dbg( p_thread, "mmh, hole ("I64Fd" > 2s) -> drop",
489                              i_date - i_date_last );
490
491                 block_FifoPut( p_thread->p_empty_blocks, p_pk );
492
493                 i_date_last = i_date;
494                 i_dropped_packets++;
495                 continue;
496             }
497             else if( i_date - i_date_last < -1000 )
498             {
499                 if( !i_dropped_packets )
500                     msg_Dbg( p_thread, "mmh, packets in the past ("I64Fd")",
501                              i_date_last - i_date );
502             }
503         }
504
505         i_to_send--;
506         if( !i_to_send || (p_pk->i_flags & BLOCK_FLAG_CLOCK) )
507         {
508             mwait( i_date );
509             i_to_send = p_thread->i_group;
510         }
511         ssize_t val = send( p_thread->i_handle, p_pk->p_buffer,
512                             p_pk->i_buffer, 0 );
513         if (val == -1)
514         {
515             msg_Warn( p_thread, "send error: %m" );
516         }
517
518         if( i_dropped_packets )
519         {
520             msg_Dbg( p_thread, "dropped %i packets", i_dropped_packets );
521             i_dropped_packets = 0;
522         }
523
524 #if 1
525         i_sent = mdate();
526         if ( i_sent > i_date + 20000 )
527         {
528             msg_Dbg( p_thread, "packet has been sent too late (" I64Fd ")",
529                      i_sent - i_date );
530         }
531 #endif
532
533         block_FifoPut( p_thread->p_empty_blocks, p_pk );
534
535         i_date_last = i_date;
536     }
537 }
538
539
540 static const char *MakeRandMulticast (int family, char *buf, size_t buflen)
541 {
542     uint32_t rand = (getpid() & 0xffff)
543                   | (uint32_t)(((mdate () >> 10) & 0xffff) << 16);
544
545     switch (family)
546     {
547 #ifdef AF_INET6
548         case AF_INET6:
549         {
550             struct in6_addr addr;
551             memcpy (&addr, "\xff\x38\x00\x00" "\x00\x00\x00\x00"
552                            "\x00\x00\x00\x00", 12);
553             rand |= 0x80000000;
554             memcpy (addr.s6_addr + 12, &(uint32_t){ htonl (rand) }, 4);
555             return inet_ntop (family, &addr, buf, buflen);
556         }
557 #endif
558
559         case AF_INET:
560         {
561             struct in_addr addr;
562             addr.s_addr = htonl ((rand & 0xffffff) | 0xe8000000);
563             return inet_ntop (family, &addr, buf, buflen);
564         }
565     }
566 #ifdef EAFNOSUPPORT
567     errno = EAFNOSUPPORT;
568 #endif
569     return NULL;
570 }