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