]> git.sesse.net Git - vlc/blob - modules/access_output/udp.c
Unduplicate TTL strings
[vlc] / modules / access_output / udp.c
1 /*****************************************************************************
2  * udp.c
3  *****************************************************************************
4  * Copyright (C) 2001-2005 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 #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 #define MAX_EMPTY_BLOCKS 200
55
56 #if defined(WIN32) || defined(UNDER_CE)
57 # define WINSOCK_STRERROR_SIZE 20
58 static const char *winsock_strerror( char *buf )
59 {
60     snprintf( buf, WINSOCK_STRERROR_SIZE, "Winsock error %d",
61               WSAGetLastError( ) );
62     buf[WINSOCK_STRERROR_SIZE - 1] = '\0';
63     return buf;
64 }
65 #endif
66
67 /*****************************************************************************
68  * Module descriptor
69  *****************************************************************************/
70 static int  Open ( vlc_object_t * );
71 static void Close( vlc_object_t * );
72
73 #define SOUT_CFG_PREFIX "sout-udp-"
74
75 #define CACHING_TEXT N_("Caching value (ms)")
76 #define CACHING_LONGTEXT N_( \
77     "Default caching value for outbound UDP streams. This " \
78     "value should be set in milliseconds." )
79
80 #define TTL_TEXT N_("Hop limit (TTL)")
81 #define TTL_LONGTEXT N_( \
82     "This is the hop limit (also known as \"Time-To-Live\" or TTL) of " \
83     "the multicast packets sent by the stream output (0 = use operating " \
84     "system built-in default).")
85
86 #define GROUP_TEXT N_("Group packets")
87 #define GROUP_LONGTEXT N_("Packets can be sent one by one at the right time " \
88                           "or by groups. You can choose the number " \
89                           "of packets that will be sent at a time. It " \
90                           "helps reducing the scheduling load on " \
91                           "heavily-loaded systems." )
92 #define RAW_TEXT N_("Raw write")
93 #define RAW_LONGTEXT N_("Packets will be sent " \
94                        "directly, without trying to fill the MTU (ie, " \
95                        "without trying to make the biggest possible packets " \
96                        "in order to improve streaming)." )
97
98 vlc_module_begin();
99     set_description( _("UDP stream output") );
100     set_shortname( "UDP" );
101     set_category( CAT_SOUT );
102     set_subcategory( SUBCAT_SOUT_ACO );
103     add_integer( SOUT_CFG_PREFIX "caching", DEFAULT_PTS_DELAY / 1000, NULL, CACHING_TEXT, CACHING_LONGTEXT, VLC_TRUE );
104     add_integer( SOUT_CFG_PREFIX "ttl", 0, NULL,TTL_TEXT, TTL_LONGTEXT,
105                                  VLC_TRUE );
106     add_integer( SOUT_CFG_PREFIX "group", 1, NULL, GROUP_TEXT, GROUP_LONGTEXT,
107                                  VLC_TRUE );
108     add_suppressed_integer( SOUT_CFG_PREFIX "late" );
109     add_bool( SOUT_CFG_PREFIX "raw",  0, NULL, RAW_TEXT, RAW_LONGTEXT,
110                                  VLC_TRUE );
111
112     set_capability( "sout access", 100 );
113     add_shortcut( "udp" );
114     add_shortcut( "rtp" ); // Will work only with ts muxer
115     set_callbacks( Open, Close );
116 vlc_module_end();
117
118 /*****************************************************************************
119  * Exported prototypes
120  *****************************************************************************/
121
122 static const char *ppsz_sout_options[] = {
123     "caching",
124     "ttl",
125     "group",
126     "raw",
127     NULL
128 };
129
130 static int  Write   ( sout_access_out_t *, block_t * );
131 static int  WriteRaw( sout_access_out_t *, block_t * );
132 static int  Seek    ( sout_access_out_t *, off_t  );
133
134 static void ThreadWrite( vlc_object_t * );
135 static block_t *NewUDPPacket( sout_access_out_t *, mtime_t );
136
137 typedef struct sout_access_thread_t
138 {
139     VLC_COMMON_MEMBERS
140
141     sout_instance_t *p_sout;
142
143     block_fifo_t *p_fifo;
144
145     int         i_handle;
146
147     int64_t     i_caching;
148     int         i_group;
149
150     block_fifo_t *p_empty_blocks;
151
152 } sout_access_thread_t;
153
154 struct sout_access_out_sys_t
155 {
156     int                 b_rtpts;  // 1 if add rtp/ts header
157     uint16_t            i_sequence_number;
158     uint32_t            i_ssrc;
159
160     int                 i_mtu;
161
162     block_t             *p_buffer;
163
164     sout_access_thread_t *p_thread;
165
166     vlc_bool_t          b_mtu_warning;
167 };
168
169 #define DEFAULT_PORT 1234
170
171 /*****************************************************************************
172  * Open: open the file
173  *****************************************************************************/
174 static int Open( vlc_object_t *p_this )
175 {
176     sout_access_out_t       *p_access = (sout_access_out_t*)p_this;
177     sout_access_out_sys_t   *p_sys;
178
179     char                *psz_parser;
180     char                *psz_dst_addr;
181     int                 i_dst_port;
182
183     int                 i_handle;
184
185     vlc_value_t         val;
186
187     config_ChainParse( p_access, SOUT_CFG_PREFIX,
188                    ppsz_sout_options, p_access->p_cfg );
189
190     if( !( p_sys = malloc( sizeof( sout_access_out_sys_t ) ) ) )
191     {
192         msg_Err( p_access, "not enough memory" );
193         return VLC_EGENERIC;
194     }
195     memset( p_sys, 0, sizeof(sout_access_out_sys_t) );
196     p_access->p_sys = p_sys;
197
198     if( p_access->psz_access != NULL &&
199         !strcmp( p_access->psz_access, "rtp" ) )
200     {
201         p_sys->b_rtpts = 1;
202     }
203     else
204     {
205         p_sys->b_rtpts = 0;
206     }
207
208     psz_parser = strdup( p_access->psz_name );
209
210     psz_dst_addr = psz_parser;
211     i_dst_port = 0;
212
213     if ( *psz_parser == '[' )
214     {
215         while( *psz_parser && *psz_parser != ']' )
216         {
217             psz_parser++;
218         }
219     }
220     while( *psz_parser && *psz_parser != ':' )
221     {
222         psz_parser++;
223     }
224     if( *psz_parser == ':' )
225     {
226         *psz_parser = '\0';
227         psz_parser++;
228         i_dst_port = atoi( psz_parser );
229     }
230     if( i_dst_port <= 0 )
231     {
232         i_dst_port = DEFAULT_PORT;
233     }
234
235     p_sys->p_thread =
236         vlc_object_create( p_access, sizeof( sout_access_thread_t ) );
237     if( !p_sys->p_thread )
238     {
239         msg_Err( p_access, "out of memory" );
240         return VLC_EGENERIC;
241     }
242
243     vlc_object_attach( p_sys->p_thread, p_access );
244     p_sys->p_thread->p_sout = p_access->p_sout;
245     p_sys->p_thread->b_die  = 0;
246     p_sys->p_thread->b_error= 0;
247     p_sys->p_thread->p_fifo = block_FifoNew( p_access );
248     p_sys->p_thread->p_empty_blocks = block_FifoNew( p_access );
249
250     var_Get( p_access, SOUT_CFG_PREFIX "ttl", &val );
251     i_handle = net_ConnectUDP( p_this, psz_dst_addr, i_dst_port, val.i_int );
252     if( i_handle == -1 )
253     {
254          msg_Err( p_access, "failed to open a connection (udp)" );
255          return VLC_EGENERIC;
256     }
257
258     p_sys->p_thread->i_handle = i_handle;
259     net_StopRecv( i_handle );
260
261     var_Get( p_access, SOUT_CFG_PREFIX "caching", &val );
262     p_sys->p_thread->i_caching = (int64_t)val.i_int * 1000;
263
264     var_Get( p_access, SOUT_CFG_PREFIX "group", &val );
265     p_sys->p_thread->i_group = val.i_int;
266
267     p_sys->i_mtu = var_CreateGetInteger( p_this, "mtu" );
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         vlc_object_destroy( p_sys->p_thread );
274         return VLC_EGENERIC;
275     }
276
277     srand( (uint32_t)mdate());
278     p_sys->p_buffer          = NULL;
279     p_sys->i_sequence_number = rand()&0xffff;
280     p_sys->i_ssrc            = rand()&0xffffffff;
281
282     var_Get( p_access, SOUT_CFG_PREFIX "raw", &val );
283     if( val.b_bool )  p_access->pf_write = WriteRaw;
284     else p_access->pf_write = Write;
285
286     p_access->pf_seek = Seek;
287
288     msg_Dbg( p_access, "udp access output opened(%s:%d)",
289              psz_dst_addr, i_dst_port );
290
291     free( psz_dst_addr );
292
293     /* update p_sout->i_out_pace_nocontrol */
294     p_access->p_sout->i_out_pace_nocontrol++;
295
296     return VLC_SUCCESS;
297 }
298
299 /*****************************************************************************
300  * Close: close the target
301  *****************************************************************************/
302 static void Close( vlc_object_t * p_this )
303 {
304     sout_access_out_t     *p_access = (sout_access_out_t*)p_this;
305     sout_access_out_sys_t *p_sys = p_access->p_sys;
306     int i;
307
308     p_sys->p_thread->b_die = 1;
309     for( i = 0; i < 10; i++ )
310     {
311         block_t *p_dummy = block_New( p_access, p_sys->i_mtu );
312         p_dummy->i_dts = 0;
313         p_dummy->i_pts = 0;
314         p_dummy->i_length = 0;
315         memset( p_dummy->p_buffer, 0, p_dummy->i_buffer );
316         block_FifoPut( p_sys->p_thread->p_fifo, p_dummy );
317     }
318     vlc_thread_join( p_sys->p_thread );
319
320     block_FifoRelease( p_sys->p_thread->p_fifo );
321     block_FifoRelease( p_sys->p_thread->p_empty_blocks );
322
323     if( p_sys->p_buffer ) block_Release( p_sys->p_buffer );
324
325     net_Close( p_sys->p_thread->i_handle );
326
327     vlc_object_detach( p_sys->p_thread );
328     vlc_object_destroy( p_sys->p_thread );
329     /* update p_sout->i_out_pace_nocontrol */
330     p_access->p_sout->i_out_pace_nocontrol--;
331
332     msg_Dbg( p_access, "udp access output closed" );
333     free( p_sys );
334 }
335
336 /*****************************************************************************
337  * Write: standard write on a file descriptor.
338  *****************************************************************************/
339 static int Write( sout_access_out_t *p_access, block_t *p_buffer )
340 {
341     sout_access_out_sys_t *p_sys = p_access->p_sys;
342
343     while( p_buffer )
344     {
345         block_t *p_next;
346         int i_packets = 0;
347
348         if( !p_sys->b_mtu_warning && p_buffer->i_buffer > p_sys->i_mtu )
349         {
350             msg_Warn( p_access, "packet size > MTU, you should probably "
351                       "increase the MTU" );
352             p_sys->b_mtu_warning = VLC_TRUE;
353         }
354
355         /* Check if there is enough space in the buffer */
356         if( p_sys->p_buffer &&
357             p_sys->p_buffer->i_buffer + p_buffer->i_buffer > p_sys->i_mtu )
358         {
359             if( p_sys->p_buffer->i_dts + p_sys->p_thread->i_caching < mdate() )
360             {
361                 msg_Dbg( p_access, "late packet for udp input (" I64Fd ")",
362                          mdate() - p_sys->p_buffer->i_dts
363                           - p_sys->p_thread->i_caching );
364             }
365             block_FifoPut( p_sys->p_thread->p_fifo, p_sys->p_buffer );
366             p_sys->p_buffer = NULL;
367         }
368
369         while( p_buffer->i_buffer )
370         {
371             int i_write = __MIN( p_buffer->i_buffer, p_sys->i_mtu );
372
373             i_packets++;
374
375             if( !p_sys->p_buffer )
376             {
377                 p_sys->p_buffer = NewUDPPacket( p_access, p_buffer->i_dts );
378                 if( !p_sys->p_buffer ) break;
379             }
380
381             memcpy( p_sys->p_buffer->p_buffer + p_sys->p_buffer->i_buffer,
382                     p_buffer->p_buffer, i_write );
383
384             p_sys->p_buffer->i_buffer += i_write;
385             p_buffer->p_buffer += i_write;
386             p_buffer->i_buffer -= i_write;
387             if ( p_buffer->i_flags & BLOCK_FLAG_CLOCK )
388             {
389                 if ( p_sys->p_buffer->i_flags & BLOCK_FLAG_CLOCK )
390                     msg_Warn( p_access, "putting two PCRs at once" );
391                 p_sys->p_buffer->i_flags |= BLOCK_FLAG_CLOCK;
392             }
393
394             if( p_sys->p_buffer->i_buffer == p_sys->i_mtu || i_packets > 1 )
395             {
396                 /* Flush */
397                 if( p_sys->p_buffer->i_dts + p_sys->p_thread->i_caching
398                       < mdate() )
399                 {
400                     msg_Dbg( p_access, "late packet for udp input (" I64Fd ")",
401                              mdate() - p_sys->p_buffer->i_dts
402                               - p_sys->p_thread->i_caching );
403                 }
404                 block_FifoPut( p_sys->p_thread->p_fifo, p_sys->p_buffer );
405                 p_sys->p_buffer = NULL;
406             }
407         }
408
409         p_next = p_buffer->p_next;
410         block_Release( p_buffer );
411         p_buffer = p_next;
412     }
413
414     return( p_sys->p_thread->b_error ? -1 : 0 );
415 }
416
417 /*****************************************************************************
418  * WriteRaw: write p_buffer without trying to fill mtu
419  *****************************************************************************/
420 static int WriteRaw( sout_access_out_t *p_access, block_t *p_buffer )
421 {
422     sout_access_out_sys_t   *p_sys = p_access->p_sys;
423     block_t *p_buf;
424
425     while ( p_sys->p_thread->p_empty_blocks->i_depth >= MAX_EMPTY_BLOCKS )
426     {
427         p_buf = block_FifoGet(p_sys->p_thread->p_empty_blocks);
428         block_Release( p_buf );
429     }
430
431     block_FifoPut( p_sys->p_thread->p_fifo, p_buffer );
432
433     return( p_sys->p_thread->b_error ? -1 : 0 );
434 }
435
436 /*****************************************************************************
437  * Seek: seek to a specific location in a file
438  *****************************************************************************/
439 static int Seek( sout_access_out_t *p_access, off_t i_pos )
440 {
441     msg_Err( p_access, "UDP sout access cannot seek" );
442     return -1;
443 }
444
445 /*****************************************************************************
446  * NewUDPPacket: allocate a new UDP packet of size p_sys->i_mtu
447  *****************************************************************************/
448 static block_t *NewUDPPacket( sout_access_out_t *p_access, mtime_t i_dts)
449 {
450     sout_access_out_sys_t *p_sys = p_access->p_sys;
451     block_t *p_buffer;
452
453     while ( p_sys->p_thread->p_empty_blocks->i_depth > MAX_EMPTY_BLOCKS )
454     {
455         p_buffer = block_FifoGet( p_sys->p_thread->p_empty_blocks );
456         block_Release( p_buffer );
457     }
458
459     if( p_sys->p_thread->p_empty_blocks->i_depth == 0 )
460     {
461         p_buffer = block_New( p_access->p_sout, p_sys->i_mtu );
462     }
463     else
464     {
465         p_buffer = block_FifoGet(p_sys->p_thread->p_empty_blocks );       
466         p_buffer->i_flags = 0;
467         p_buffer = block_Realloc( p_buffer, 0, p_sys->i_mtu );
468     }
469
470     p_buffer->i_dts = i_dts;
471     p_buffer->i_buffer = 0;
472
473     if( p_sys->b_rtpts )
474     {
475         mtime_t i_timestamp = p_buffer->i_dts * 9 / 100;
476
477         /* add rtp/ts header */
478         p_buffer->p_buffer[0] = 0x80;
479         p_buffer->p_buffer[1] = 0x21; // mpeg2-ts
480
481         p_buffer->p_buffer[2] = ( p_sys->i_sequence_number >> 8 )&0xff;
482         p_buffer->p_buffer[3] = p_sys->i_sequence_number&0xff;
483         p_sys->i_sequence_number++;
484
485         p_buffer->p_buffer[4] = ( i_timestamp >> 24 )&0xff;
486         p_buffer->p_buffer[5] = ( i_timestamp >> 16 )&0xff;
487         p_buffer->p_buffer[6] = ( i_timestamp >>  8 )&0xff;
488         p_buffer->p_buffer[7] = i_timestamp&0xff;
489
490         p_buffer->p_buffer[ 8] = ( p_sys->i_ssrc >> 24 )&0xff;
491         p_buffer->p_buffer[ 9] = ( p_sys->i_ssrc >> 16 )&0xff;
492         p_buffer->p_buffer[10] = ( p_sys->i_ssrc >>  8 )&0xff;
493         p_buffer->p_buffer[11] = p_sys->i_ssrc&0xff;
494
495         p_buffer->i_buffer = 12;
496     }
497
498     return p_buffer;
499 }
500
501 /*****************************************************************************
502  * ThreadWrite: Write a packet on the network at the good time.
503  *****************************************************************************/
504 static void ThreadWrite( vlc_object_t *p_this )
505 {
506     sout_access_thread_t *p_thread = (sout_access_thread_t*)p_this;
507     mtime_t              i_date_last = -1;
508     mtime_t              i_to_send = p_thread->i_group;
509     int                  i_dropped_packets = 0;
510 #if defined(WIN32) || defined(UNDER_CE)
511     char strerror_buf[WINSOCK_STRERROR_SIZE];
512 # define strerror( x ) winsock_strerror( strerror_buf )
513 #endif
514
515     while( !p_thread->b_die )
516     {
517         block_t *p_pk;
518         mtime_t       i_date, i_sent;
519 #if 0
520         if( (i++ % 1000)==0 ) {
521           int i = 0;
522           int j = 0;
523           block_t *p_tmp = p_thread->p_empty_blocks->p_first;
524           while( p_tmp ) { p_tmp = p_tmp->p_next; i++;}
525           p_tmp = p_thread->p_fifo->p_first;
526           while( p_tmp ) { p_tmp = p_tmp->p_next; j++;}
527           msg_Err( p_thread, "fifo depth: %d/%d, empty blocks: %d/%d",
528                    p_thread->p_fifo->i_depth, j,p_thread->p_empty_blocks->i_depth,i );
529         }
530 #endif
531         p_pk = block_FifoGet( p_thread->p_fifo );
532
533         i_date = p_thread->i_caching + p_pk->i_dts;
534         if( i_date_last > 0 )
535         {
536             if( i_date - i_date_last > 2000000 )
537             {
538                 if( !i_dropped_packets )
539                     msg_Dbg( p_thread, "mmh, hole ("I64Fd" > 2s) -> drop",
540                              i_date - i_date_last );
541
542                 block_FifoPut( p_thread->p_empty_blocks, p_pk );
543
544                 i_date_last = i_date;
545                 i_dropped_packets++;
546                 continue;
547             }
548             else if( i_date - i_date_last < -1000 )
549             {
550                 if( !i_dropped_packets )
551                     msg_Dbg( p_thread, "mmh, packets in the past ("I64Fd")",
552                              i_date_last - i_date );
553             }
554         }
555
556         i_to_send--;
557         if( !i_to_send || (p_pk->i_flags & BLOCK_FLAG_CLOCK) )
558         {
559             mwait( i_date );
560             i_to_send = p_thread->i_group;
561         }
562         if( send( p_thread->i_handle, p_pk->p_buffer, p_pk->i_buffer, 0 )
563               == -1 )
564         {
565             msg_Warn( p_thread, "send error: %s", strerror(errno) );
566         }
567
568         if( i_dropped_packets )
569         {
570             msg_Dbg( p_thread, "dropped %i packets", i_dropped_packets );
571             i_dropped_packets = 0;
572         }
573
574 #if 1
575         i_sent = mdate();
576         if ( i_sent > i_date + 20000 )
577         {
578             msg_Dbg( p_thread, "packet has been sent too late (" I64Fd ")",
579                      i_sent - i_date );
580         }
581 #endif
582
583         block_FifoPut( p_thread->p_empty_blocks, p_pk );
584
585         i_date_last = i_date;
586     }
587 }