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