]> git.sesse.net Git - vlc/blob - modules/access_output/udp.c
x264: fix open-gop -> opengop, thanks for TypX for nagging
[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_common.h>
33 #include <vlc_plugin.h>
34
35 #include <sys/types.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 #define MAX_EMPTY_BLOCKS 200
55
56 /*****************************************************************************
57  * Module descriptor
58  *****************************************************************************/
59 static int  Open ( vlc_object_t * );
60 static void Close( vlc_object_t * );
61
62 #define SOUT_CFG_PREFIX "sout-udp-"
63
64 #define CACHING_TEXT N_("Caching value (ms)")
65 #define CACHING_LONGTEXT N_( \
66     "Default caching value for outbound UDP streams. This " \
67     "value should be set in milliseconds." )
68
69 #define GROUP_TEXT N_("Group packets")
70 #define GROUP_LONGTEXT N_("Packets can be sent one by one at the right time " \
71                           "or by groups. You can choose the number " \
72                           "of packets that will be sent at a time. It " \
73                           "helps reducing the scheduling load on " \
74                           "heavily-loaded systems." )
75
76 vlc_module_begin ()
77     set_description( N_("UDP stream output") )
78     set_shortname( "UDP" )
79     set_category( CAT_SOUT )
80     set_subcategory( SUBCAT_SOUT_ACO )
81     add_integer( SOUT_CFG_PREFIX "caching", DEFAULT_PTS_DELAY / 1000, CACHING_TEXT, CACHING_LONGTEXT, true )
82     add_integer( SOUT_CFG_PREFIX "group", 1, GROUP_TEXT, GROUP_LONGTEXT,
83                                  true )
84
85     set_capability( "sout access", 0 )
86     add_shortcut( "udp" )
87     set_callbacks( Open, Close )
88 vlc_module_end ()
89
90 /*****************************************************************************
91  * Exported prototypes
92  *****************************************************************************/
93
94 static const char *const ppsz_sout_options[] = {
95     "caching",
96     "group",
97     NULL
98 };
99
100 /* Options handled by the libvlc network core */
101 static const char *const ppsz_core_options[] = {
102     "dscp",
103     "ttl",
104     "miface",
105     "miface-addr",
106     NULL
107 };
108
109 static ssize_t Write   ( sout_access_out_t *, block_t * );
110 static int  Seek    ( sout_access_out_t *, off_t  );
111 static int Control( sout_access_out_t *, int, va_list );
112
113 static void* ThreadWrite( void * );
114 static block_t *NewUDPPacket( sout_access_out_t *, mtime_t );
115
116 struct sout_access_out_sys_t
117 {
118     mtime_t       i_caching;
119     int           i_handle;
120     bool          b_mtu_warning;
121     size_t        i_mtu;
122
123     block_fifo_t *p_fifo;
124     block_fifo_t *p_empty_blocks;
125     block_t      *p_buffer;
126
127     vlc_thread_t  thread;
128 };
129
130 #define DEFAULT_PORT 1234
131
132 /*****************************************************************************
133  * Open: open the file
134  *****************************************************************************/
135 static int Open( vlc_object_t *p_this )
136 {
137     sout_access_out_t       *p_access = (sout_access_out_t*)p_this;
138     sout_access_out_sys_t   *p_sys;
139
140     char                *psz_dst_addr = NULL;
141     int                 i_dst_port;
142
143     int                 i_handle;
144
145     config_ChainParse( p_access, SOUT_CFG_PREFIX,
146                        ppsz_sout_options, p_access->p_cfg );
147     config_ChainParse( p_access, "",
148                        ppsz_core_options, p_access->p_cfg );
149
150     if (var_Create (p_access, "dst-port", VLC_VAR_INTEGER)
151      || var_Create (p_access, "src-port", VLC_VAR_INTEGER)
152      || var_Create (p_access, "dst-addr", VLC_VAR_STRING)
153      || var_Create (p_access, "src-addr", VLC_VAR_STRING))
154     {
155         return VLC_ENOMEM;
156     }
157
158     if( !( p_sys = malloc ( sizeof( *p_sys ) ) ) )
159         return VLC_ENOMEM;
160     p_access->p_sys = p_sys;
161
162     i_dst_port = DEFAULT_PORT;
163     char *psz_parser = psz_dst_addr = strdup( p_access->psz_path );
164     if( !psz_dst_addr )
165     {
166         free( p_sys );
167         return VLC_ENOMEM;
168     }
169
170     if (psz_parser[0] == '[')
171         psz_parser = strchr (psz_parser, ']');
172
173     psz_parser = strchr (psz_parser ? psz_parser : psz_dst_addr, ':');
174     if (psz_parser != NULL)
175     {
176         *psz_parser++ = '\0';
177         i_dst_port = atoi (psz_parser);
178     }
179
180     i_handle = net_ConnectDgram( p_this, psz_dst_addr, i_dst_port, -1,
181                                  IPPROTO_UDP );
182     free (psz_dst_addr);
183
184     if( i_handle == -1 )
185     {
186          msg_Err( p_access, "failed to create raw UDP socket" );
187          free (p_sys);
188          return VLC_EGENERIC;
189     }
190     else
191     {
192         char addr[NI_MAXNUMERICHOST];
193         int port;
194
195         if (net_GetSockAddress (i_handle, addr, &port) == 0)
196         {
197             msg_Dbg (p_access, "source: %s port %d", addr, port);
198             var_SetString (p_access, "src-addr", addr);
199             var_SetInteger (p_access, "src-port", port);
200         }
201
202         if (net_GetPeerAddress (i_handle, addr, &port) == 0)
203         {
204             msg_Dbg (p_access, "destination: %s port %d", addr, port);
205             var_SetString (p_access, "dst-addr", addr);
206             var_SetInteger (p_access, "dst-port", port);
207         }
208     }
209     shutdown( i_handle, SHUT_RD );
210
211     p_sys->i_caching = UINT64_C(1000)
212                      * var_GetInteger( p_access, SOUT_CFG_PREFIX "caching");
213     p_sys->i_handle = i_handle;
214     p_sys->i_mtu = var_CreateGetInteger( p_this, "mtu" );
215     p_sys->b_mtu_warning = false;
216     p_sys->p_fifo = block_FifoNew();
217     p_sys->p_empty_blocks = block_FifoNew();
218     p_sys->p_buffer = NULL;
219
220     if( vlc_clone( &p_sys->thread, ThreadWrite, p_access,
221                            VLC_THREAD_PRIORITY_HIGHEST ) )
222     {
223         msg_Err( p_access, "cannot spawn sout access thread" );
224         block_FifoRelease( p_sys->p_fifo );
225         block_FifoRelease( p_sys->p_empty_blocks );
226         net_Close (i_handle);
227         free (p_sys);
228         return VLC_EGENERIC;
229     }
230
231     p_access->pf_write = Write;
232     p_access->pf_seek = Seek;
233     p_access->pf_control = Control;
234
235     return VLC_SUCCESS;
236 }
237
238 /*****************************************************************************
239  * Close: close the target
240  *****************************************************************************/
241 static void Close( vlc_object_t * p_this )
242 {
243     sout_access_out_t     *p_access = (sout_access_out_t*)p_this;
244     sout_access_out_sys_t *p_sys = p_access->p_sys;
245
246     vlc_cancel( p_sys->thread );
247     vlc_join( p_sys->thread, NULL );
248     block_FifoRelease( p_sys->p_fifo );
249     block_FifoRelease( p_sys->p_empty_blocks );
250
251     if( p_sys->p_buffer ) block_Release( p_sys->p_buffer );
252
253     net_Close( p_sys->i_handle );
254     free( p_sys );
255 }
256
257 static int Control( sout_access_out_t *p_access, int i_query, va_list args )
258 {
259     (void)p_access;
260
261     switch( i_query )
262     {
263         case ACCESS_OUT_CONTROLS_PACE:
264             *va_arg( args, bool * ) = false;
265             break;
266
267         default:
268             return VLC_EGENERIC;
269     }
270     return VLC_SUCCESS;
271 }
272
273 /*****************************************************************************
274  * Write: standard write on a file descriptor.
275  *****************************************************************************/
276 static ssize_t Write( sout_access_out_t *p_access, block_t *p_buffer )
277 {
278     sout_access_out_sys_t *p_sys = p_access->p_sys;
279     int i_len = 0;
280
281     while( p_buffer )
282     {
283         block_t *p_next;
284         int i_packets = 0;
285         mtime_t now = mdate();
286
287         if( !p_sys->b_mtu_warning && p_buffer->i_buffer > p_sys->i_mtu )
288         {
289             msg_Warn( p_access, "packet size > MTU, you should probably "
290                       "increase the MTU" );
291             p_sys->b_mtu_warning = true;
292         }
293
294         /* Check if there is enough space in the buffer */
295         if( p_sys->p_buffer &&
296             p_sys->p_buffer->i_buffer + p_buffer->i_buffer > p_sys->i_mtu )
297         {
298             if( p_sys->p_buffer->i_dts + p_sys->i_caching < now )
299             {
300                 msg_Dbg( p_access, "late packet for UDP input (%"PRId64 ")",
301                          now - p_sys->p_buffer->i_dts
302                           - p_sys->i_caching );
303             }
304             block_FifoPut( p_sys->p_fifo, p_sys->p_buffer );
305             p_sys->p_buffer = NULL;
306         }
307
308         i_len += p_buffer->i_buffer;
309         while( p_buffer->i_buffer )
310         {
311             size_t i_payload_size = p_sys->i_mtu;
312             size_t i_write = __MIN( p_buffer->i_buffer, i_payload_size );
313
314             i_packets++;
315
316             if( !p_sys->p_buffer )
317             {
318                 p_sys->p_buffer = NewUDPPacket( p_access, p_buffer->i_dts );
319                 if( !p_sys->p_buffer ) break;
320             }
321
322             memcpy( p_sys->p_buffer->p_buffer + p_sys->p_buffer->i_buffer,
323                     p_buffer->p_buffer, i_write );
324
325             p_sys->p_buffer->i_buffer += i_write;
326             p_buffer->p_buffer += i_write;
327             p_buffer->i_buffer -= i_write;
328             if ( p_buffer->i_flags & BLOCK_FLAG_CLOCK )
329             {
330                 if ( p_sys->p_buffer->i_flags & BLOCK_FLAG_CLOCK )
331                     msg_Warn( p_access, "putting two PCRs at once" );
332                 p_sys->p_buffer->i_flags |= BLOCK_FLAG_CLOCK;
333             }
334
335             if( p_sys->p_buffer->i_buffer == p_sys->i_mtu || i_packets > 1 )
336             {
337                 /* Flush */
338                 if( p_sys->p_buffer->i_dts + p_sys->i_caching < now )
339                 {
340                     msg_Dbg( p_access, "late packet for udp input (%"PRId64 ")",
341                              mdate() - p_sys->p_buffer->i_dts
342                               - p_sys->i_caching );
343                 }
344                 block_FifoPut( p_sys->p_fifo, p_sys->p_buffer );
345                 p_sys->p_buffer = NULL;
346             }
347         }
348
349         p_next = p_buffer->p_next;
350         block_Release( p_buffer );
351         p_buffer = p_next;
352     }
353
354     return i_len;
355 }
356
357 /*****************************************************************************
358  * Seek: seek to a specific location in a file
359  *****************************************************************************/
360 static int Seek( sout_access_out_t *p_access, off_t i_pos )
361 {
362     (void) i_pos;
363     msg_Err( p_access, "UDP sout access cannot seek" );
364     return -1;
365 }
366
367 /*****************************************************************************
368  * NewUDPPacket: allocate a new UDP packet of size p_sys->i_mtu
369  *****************************************************************************/
370 static block_t *NewUDPPacket( sout_access_out_t *p_access, mtime_t i_dts)
371 {
372     sout_access_out_sys_t *p_sys = p_access->p_sys;
373     block_t *p_buffer;
374
375     while ( block_FifoCount( p_sys->p_empty_blocks ) > MAX_EMPTY_BLOCKS )
376     {
377         p_buffer = block_FifoGet( p_sys->p_empty_blocks );
378         block_Release( p_buffer );
379     }
380
381     if( block_FifoCount( p_sys->p_empty_blocks ) == 0 )
382     {
383         p_buffer = block_Alloc( p_sys->i_mtu );
384     }
385     else
386     {
387         p_buffer = block_FifoGet(p_sys->p_empty_blocks );
388         p_buffer->i_flags = 0;
389         p_buffer = block_Realloc( p_buffer, 0, p_sys->i_mtu );
390     }
391
392     p_buffer->i_dts = i_dts;
393     p_buffer->i_buffer = 0;
394
395     return p_buffer;
396 }
397
398 /*****************************************************************************
399  * ThreadWrite: Write a packet on the network at the good time.
400  *****************************************************************************/
401 static void* ThreadWrite( void *data )
402 {
403     sout_access_out_t *p_access = data;
404     sout_access_out_sys_t *p_sys = p_access->p_sys;
405     mtime_t i_date_last = -1;
406     const unsigned i_group = var_GetInteger( p_access,
407                                              SOUT_CFG_PREFIX "group" );
408     mtime_t i_to_send = i_group;
409     unsigned i_dropped_packets = 0;
410
411     for (;;)
412     {
413         block_t *p_pk = block_FifoGet( p_sys->p_fifo );
414         mtime_t       i_date, i_sent;
415
416         i_date = p_sys->i_caching + p_pk->i_dts;
417         if( i_date_last > 0 )
418         {
419             if( i_date - i_date_last > 2000000 )
420             {
421                 if( !i_dropped_packets )
422                     msg_Dbg( p_access, "mmh, hole (%"PRId64" > 2s) -> drop",
423                              i_date - i_date_last );
424
425                 block_FifoPut( p_sys->p_empty_blocks, p_pk );
426
427                 i_date_last = i_date;
428                 i_dropped_packets++;
429                 continue;
430             }
431             else if( i_date - i_date_last < -1000 )
432             {
433                 if( !i_dropped_packets )
434                     msg_Dbg( p_access, "mmh, packets in the past (%"PRId64")",
435                              i_date_last - i_date );
436             }
437         }
438
439         block_cleanup_push( p_pk );
440         i_to_send--;
441         if( !i_to_send || (p_pk->i_flags & BLOCK_FLAG_CLOCK) )
442         {
443             mwait( i_date );
444             i_to_send = i_group;
445         }
446         if ( send( p_sys->i_handle, p_pk->p_buffer, p_pk->i_buffer, 0 ) == -1 )
447             msg_Warn( p_access, "send error: %m" );
448         vlc_cleanup_pop();
449
450         if( i_dropped_packets )
451         {
452             msg_Dbg( p_access, "dropped %i packets", i_dropped_packets );
453             i_dropped_packets = 0;
454         }
455
456 #if 1
457         i_sent = mdate();
458         if ( i_sent > i_date + 20000 )
459         {
460             msg_Dbg( p_access, "packet has been sent too late (%"PRId64 ")",
461                      i_sent - i_date );
462         }
463 #endif
464
465         block_FifoPut( p_sys->p_empty_blocks, p_pk );
466
467         i_date_last = i_date;
468     }
469     return NULL;
470 }