]> git.sesse.net Git - vlc/blob - modules/access_output/udp.c
cc32019f359336f929b17236e8e49ad93df9a4cf
[vlc] / modules / access_output / udp.c
1 /*****************************************************************************
2  * udp.c
3  *****************************************************************************
4  * Copyright (C) 2001, 2002 VideoLAN
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., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
23  *****************************************************************************/
24
25 /*****************************************************************************
26  * Preamble
27  *****************************************************************************/
28 #include <stdlib.h>
29 #include <sys/types.h>
30 #include <sys/stat.h>
31 #include <string.h>
32 #include <errno.h>
33 #include <fcntl.h>
34
35 #include <vlc/vlc.h>
36 #include <vlc/sout.h>
37
38 #ifdef HAVE_UNISTD_H
39 #   include <unistd.h>
40 #endif
41
42 #ifdef WIN32
43 #   include <winsock2.h>
44 #   include <ws2tcpip.h>
45 #   ifndef IN_MULTICAST
46 #       define IN_MULTICAST(a) IN_CLASSD(a)
47 #   endif
48 #else
49 #   include <sys/socket.h>
50 #endif
51
52 #include "network.h"
53
54
55 /*****************************************************************************
56  * Module descriptor
57  *****************************************************************************/
58 static int  Open ( vlc_object_t * );
59 static void Close( vlc_object_t * );
60
61 #define SOUT_CFG_PREFIX "sout-udp-"
62
63 #define CACHING_TEXT N_("Caching value (ms)")
64 #define CACHING_LONGTEXT N_( \
65     "Allows you to modify the default caching value for UDP streams. This " \
66     "value should be set in millisecond units." )
67
68 #define TTL_TEXT N_("Time To Live")
69 #define TTL_LONGTEXT N_("Allows you to define the time to live of the " \
70                         "outgoing stream.")
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. This allows you to give 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 #define LATE_TEXT N_("Late delay (ms)" )
79 #define LATE_LONGTEXT N_("Late packets are dropped. This allows you to give " \
80                        "the time (in milliseconds) a packet is allowed to be" \
81                        " late.")
82 #define RAW_TEXT N_("Raw write")
83 #define RAW_LONGTEXT N_("If you enable this option, packets will be sent " \
84                        "directly, without trying to fill the MTU (ie, " \
85                        "without trying to make the biggest possible packets " \
86                        "in order to improve streaming)." )
87
88 vlc_module_begin();
89     set_description( _("UDP stream output") );
90     add_integer( SOUT_CFG_PREFIX "caching", DEFAULT_PTS_DELAY / 1000, NULL, CACHING_TEXT, CACHING_LONGTEXT, VLC_TRUE );
91     add_integer( SOUT_CFG_PREFIX "ttl", 0, NULL,TTL_TEXT, TTL_LONGTEXT,
92                                  VLC_TRUE );
93     add_integer( SOUT_CFG_PREFIX "group", 1, NULL, GROUP_TEXT, GROUP_LONGTEXT,
94                                  VLC_TRUE );
95     add_integer( SOUT_CFG_PREFIX "late", 0, NULL, LATE_TEXT, LATE_LONGTEXT,
96                                  VLC_TRUE );
97     add_bool( SOUT_CFG_PREFIX "raw",  0, NULL, RAW_TEXT, RAW_LONGTEXT,
98                                  VLC_TRUE );
99
100     set_capability( "sout access", 100 );
101     add_shortcut( "udp" );
102     add_shortcut( "rtp" ); // Will work only with ts muxer
103     set_callbacks( Open, Close );
104 vlc_module_end();
105
106 /*****************************************************************************
107  * Exported prototypes
108  *****************************************************************************/
109
110 static const char *ppsz_sout_options[] = {
111     "caching",
112     "ttl",
113     "group",
114     "late",
115     "raw",
116     NULL
117 };
118
119 static int  Write   ( sout_access_out_t *, block_t * );
120 static int  WriteRaw( sout_access_out_t *, block_t * );
121 static int  Seek    ( sout_access_out_t *, off_t  );
122
123 static void ThreadWrite( vlc_object_t * );
124 static block_t *NewUDPPacket( sout_access_out_t *, mtime_t );
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     int64_t     i_late;
138     int         i_group;
139
140 } sout_access_thread_t;
141
142 struct sout_access_out_sys_t
143 {
144     int                 b_rtpts;  // 1 if add rtp/ts header
145     uint16_t            i_sequence_number;
146     uint32_t            i_ssrc;
147
148     int                 i_mtu;
149
150     block_t             *p_buffer;
151
152     sout_access_thread_t *p_thread;
153
154     vlc_bool_t          b_mtu_warning;
155 };
156
157 #define DEFAULT_PORT 1234
158
159 /*****************************************************************************
160  * Open: open the file
161  *****************************************************************************/
162 static int Open( vlc_object_t *p_this )
163 {
164     sout_access_out_t       *p_access = (sout_access_out_t*)p_this;
165     sout_access_out_sys_t   *p_sys;
166
167     char                *psz_parser;
168     char                *psz_dst_addr;
169     int                 i_dst_port;
170
171     module_t            *p_network;
172     network_socket_t    socket_desc;
173
174     vlc_value_t         val;
175
176     sout_CfgParse( p_access, SOUT_CFG_PREFIX,
177                    ppsz_sout_options, p_access->p_cfg );
178
179     if( !( p_sys = malloc( sizeof( sout_access_out_sys_t ) ) ) )
180     {
181         msg_Err( p_access, "not enough memory" );
182         return VLC_EGENERIC;
183     }
184     memset( p_sys, 0, sizeof(sout_access_out_sys_t) );
185     p_access->p_sys = p_sys;
186
187     if( p_access->psz_access != NULL &&
188         !strcmp( p_access->psz_access, "rtp" ) )
189     {
190         msg_Warn( p_access, "be careful that rtp output only works with ts "
191                   "payload (not an error)" );
192         p_sys->b_rtpts = 1;
193     }
194     else
195     {
196         p_sys->b_rtpts = 0;
197     }
198
199     psz_parser = strdup( p_access->psz_name );
200
201     psz_dst_addr = psz_parser;
202     i_dst_port = 0;
203
204     if ( *psz_parser == '[' )
205     {
206         while( *psz_parser && *psz_parser != ']' )
207         {
208             psz_parser++;
209         }
210     }
211     while( *psz_parser && *psz_parser != ':' )
212     {
213         psz_parser++;
214     }
215     if( *psz_parser == ':' )
216     {
217         *psz_parser = '\0';
218         psz_parser++;
219         i_dst_port = atoi( psz_parser );
220     }
221     if( i_dst_port <= 0 )
222     {
223         i_dst_port = DEFAULT_PORT;
224     }
225
226     p_sys->p_thread =
227         vlc_object_create( p_access, sizeof( sout_access_thread_t ) );
228     if( !p_sys->p_thread )
229     {
230         msg_Err( p_access, "out of memory" );
231         return VLC_EGENERIC;
232     }
233
234     p_sys->p_thread->p_sout = p_access->p_sout;
235     p_sys->p_thread->b_die  = 0;
236     p_sys->p_thread->b_error= 0;
237     p_sys->p_thread->p_fifo = block_FifoNew( p_access );
238
239     socket_desc.i_type = NETWORK_UDP;
240     socket_desc.psz_server_addr = psz_dst_addr;
241     socket_desc.i_server_port   = i_dst_port;
242     socket_desc.psz_bind_addr   = "";
243     socket_desc.i_bind_port     = 0;
244
245     var_Get( p_access, SOUT_CFG_PREFIX "ttl", &val );
246     socket_desc.i_ttl = val.i_int;
247
248     p_sys->p_thread->p_private = (void*)&socket_desc;
249     if( !( p_network = module_Need( p_sys->p_thread, "network", NULL, 0 ) ) )
250     {
251         msg_Err( p_access, "failed to open a connection (udp)" );
252         return VLC_EGENERIC;
253     }
254     module_Unneed( p_sys->p_thread, p_network );
255
256     p_sys->p_thread->i_handle = socket_desc.i_handle;
257
258     var_Get( p_access, SOUT_CFG_PREFIX "caching", &val );
259     p_sys->p_thread->i_caching = (int64_t)val.i_int * 1000;
260
261     var_Get( p_access, SOUT_CFG_PREFIX "group", &val );
262     p_sys->p_thread->i_group = val.i_int;
263
264     var_Get( p_access, SOUT_CFG_PREFIX "late", &val );
265     p_sys->p_thread->i_late = (int64_t)val.i_int * 1000;
266
267     p_sys->i_mtu = socket_desc.i_mtu;
268
269 #ifdef WIN32
270     if( vlc_thread_create( p_sys->p_thread, "sout write thread", ThreadWrite,
271                            VLC_THREAD_PRIORITY_HIGHEST, VLC_FALSE ) )
272 #else
273     if( vlc_thread_create( p_sys->p_thread, "sout write thread", ThreadWrite,
274                            VLC_THREAD_PRIORITY_OUTPUT, VLC_FALSE ) )
275 #endif
276     {
277         msg_Err( p_access->p_sout, "cannot spawn sout access thread" );
278         vlc_object_destroy( p_sys->p_thread );
279         return VLC_EGENERIC;
280     }
281
282     srand( (uint32_t)mdate());
283     p_sys->p_buffer          = NULL;
284     p_sys->i_sequence_number = rand()&0xffff;
285     p_sys->i_ssrc            = rand()&0xffffffff;
286
287     var_Get( p_access, SOUT_CFG_PREFIX "raw", &val );
288     if( val.b_bool )  p_access->pf_write = WriteRaw;
289     else p_access->pf_write = Write;
290
291     p_access->pf_seek = Seek;
292
293     msg_Dbg( p_access, "udp access output opened(%s:%d)",
294              psz_dst_addr, i_dst_port );
295
296     free( psz_dst_addr );
297
298     /* update p_sout->i_out_pace_nocontrol */
299     p_access->p_sout->i_out_pace_nocontrol++;
300
301     return VLC_SUCCESS;
302 }
303
304 /*****************************************************************************
305  * Close: close the target
306  *****************************************************************************/
307 static void Close( vlc_object_t * p_this )
308 {
309     sout_access_out_t     *p_access = (sout_access_out_t*)p_this;
310     sout_access_out_sys_t *p_sys = p_access->p_sys;
311     int i;
312
313     p_sys->p_thread->b_die = 1;
314     for( i = 0; i < 10; i++ )
315     {
316         block_t *p_dummy = block_New( p_access, p_sys->i_mtu );
317         p_dummy->i_dts = 0;
318         p_dummy->i_pts = 0;
319         p_dummy->i_length = 0;
320         block_FifoPut( p_sys->p_thread->p_fifo, p_dummy );
321     }
322     vlc_thread_join( p_sys->p_thread );
323
324     block_FifoRelease( p_sys->p_thread->p_fifo );
325
326     if( p_sys->p_buffer ) block_Release( p_sys->p_buffer );
327
328     net_Close( p_sys->p_thread->i_handle );
329
330     /* update p_sout->i_out_pace_nocontrol */
331     p_access->p_sout->i_out_pace_nocontrol--;
332
333     msg_Dbg( p_access, "udp access output closed" );
334     free( p_sys );
335 }
336
337 /*****************************************************************************
338  * Write: standard write on a file descriptor.
339  *****************************************************************************/
340 static int Write( sout_access_out_t *p_access, block_t *p_buffer )
341 {
342     sout_access_out_sys_t *p_sys = p_access->p_sys;
343
344     while( p_buffer )
345     {
346         block_t *p_next;
347         int i_packets = 0;
348
349         if( !p_sys->b_mtu_warning && p_buffer->i_buffer > p_sys->i_mtu )
350         {
351             msg_Warn( p_access, "packet size > MTU, you should probably "
352                       "increase the MTU" );
353             p_sys->b_mtu_warning = VLC_TRUE;
354         }
355
356         /* Check if there is enough space in the buffer */
357         if( p_sys->p_buffer &&
358             p_sys->p_buffer->i_buffer + p_buffer->i_buffer > p_sys->i_mtu )
359         {
360             block_FifoPut( p_sys->p_thread->p_fifo, p_sys->p_buffer );
361             p_sys->p_buffer = NULL;
362         }
363
364         while( p_buffer->i_buffer )
365         {
366             int i_write = __MIN( p_buffer->i_buffer, p_sys->i_mtu );
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
383             if( p_sys->p_buffer->i_buffer == p_sys->i_mtu || i_packets > 1 )
384             {
385                 /* Flush */
386                 block_FifoPut( p_sys->p_thread->p_fifo, p_sys->p_buffer );
387                 p_sys->p_buffer = NULL;
388             }
389         }
390
391         p_next = p_buffer->p_next;
392         block_Release( p_buffer );
393         p_buffer = p_next;
394     }
395
396     return( p_sys->p_thread->b_error ? -1 : 0 );
397 }
398
399 /*****************************************************************************
400  * WriteRaw: write p_buffer without trying to fill mtu
401  *****************************************************************************/
402 static int WriteRaw( sout_access_out_t *p_access, block_t *p_buffer )
403 {
404     sout_access_out_sys_t   *p_sys = p_access->p_sys;
405
406     block_FifoPut( p_sys->p_thread->p_fifo, p_buffer );
407
408     return( p_sys->p_thread->b_error ? -1 : 0 );
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     p_buffer = block_New( p_access->p_sout, p_sys->i_mtu );
429     p_buffer->i_dts = i_dts;
430     p_buffer->i_buffer = 0;
431
432     if( p_sys->b_rtpts )
433     {
434         mtime_t i_timestamp = p_buffer->i_dts * 9 / 100;
435
436         /* add rtp/ts header */
437         p_buffer->p_buffer[0] = 0x80;
438         p_buffer->p_buffer[1] = 0x21; // mpeg2-ts
439
440         p_buffer->p_buffer[2] = ( p_sys->i_sequence_number >> 8 )&0xff;
441         p_buffer->p_buffer[3] = p_sys->i_sequence_number&0xff;
442         p_sys->i_sequence_number++;
443
444         p_buffer->p_buffer[4] = ( i_timestamp >> 24 )&0xff;
445         p_buffer->p_buffer[5] = ( i_timestamp >> 16 )&0xff;
446         p_buffer->p_buffer[6] = ( i_timestamp >>  8 )&0xff;
447         p_buffer->p_buffer[7] = i_timestamp&0xff;
448
449         p_buffer->p_buffer[ 8] = ( p_sys->i_ssrc >> 24 )&0xff;
450         p_buffer->p_buffer[ 9] = ( p_sys->i_ssrc >> 16 )&0xff;
451         p_buffer->p_buffer[10] = ( p_sys->i_ssrc >>  8 )&0xff;
452         p_buffer->p_buffer[11] = p_sys->i_ssrc&0xff;
453
454         p_buffer->i_buffer = 12;
455     }
456
457     return p_buffer;
458 }
459
460 /*****************************************************************************
461  * ThreadWrite: Write a packet on the network at the good time.
462  *****************************************************************************/
463 static void ThreadWrite( vlc_object_t *p_this )
464 {
465     sout_access_thread_t *p_thread = (sout_access_thread_t*)p_this;
466     mtime_t              i_date_last = -1;
467     mtime_t              i_to_send = p_thread->i_group;
468     int                  i_dropped_packets = 0;
469
470     while( !p_thread->b_die )
471     {
472         block_t *p_pk;
473         mtime_t       i_date, i_sent;
474
475         p_pk = block_FifoGet( p_thread->p_fifo );
476
477         i_date = p_thread->i_caching + p_pk->i_dts;
478         if( i_date_last > 0 )
479         {
480             if( i_date - i_date_last > 2000000 )
481             {
482                 if( !i_dropped_packets )
483                     msg_Dbg( p_thread, "mmh, hole ("I64Fd" > 2s) -> drop",
484                              i_date - i_date_last );
485
486                 block_Release( p_pk  );
487                 i_date_last = i_date;
488                 i_dropped_packets++;
489                 continue;
490             }
491             else if( i_date - i_date_last < 0 )
492             {
493                 if( !i_dropped_packets )
494                     msg_Dbg( p_thread, "mmh, packets in the past ("I64Fd")"
495                              " -> drop", i_date - i_date_last );
496
497                 block_Release( p_pk  );
498                 i_date_last = i_date;
499                 i_dropped_packets++;
500                 continue;
501             }
502         }
503
504         i_sent = mdate();
505         if( p_thread->i_late > 0 && i_sent > i_date + p_thread->i_late )
506         {
507             if( !i_dropped_packets )
508             {
509                 msg_Dbg( p_thread, "late packet to send (" I64Fd ") -> drop",
510                          i_sent - i_date );
511             }
512             block_Release( p_pk  );
513             i_date_last = i_date;
514             i_dropped_packets++;
515             continue;
516         }
517
518         i_to_send--;
519         if ( !i_to_send )
520         {
521             mwait( i_date );
522             i_to_send = p_thread->i_group;
523         }
524         send( p_thread->i_handle, p_pk->p_buffer, p_pk->i_buffer, 0 );
525
526         if( i_dropped_packets )
527         {
528             msg_Dbg( p_thread, "dropped %i packets", i_dropped_packets );
529             i_dropped_packets = 0;
530         }
531
532 #if 0
533         i_sent = mdate();
534         if ( i_sent > i_date + 20000 )
535         {
536             msg_Dbg( p_thread, "packet has been sent too late (" I64Fd ")",
537                      i_sent - i_date );
538         }
539 #endif
540
541         block_Release( p_pk  );
542         i_date_last = i_date;
543     }
544 }