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