]> git.sesse.net Git - vlc/blob - modules/access_output/udp.c
0879830c5ef1c5dc13c0904b5f5f0fd67a05e9e0
[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
283 #ifdef UDPLITE_SEND_CSCOV
284     if (proto == IPPROTO_UDPLITE)
285         setsockopt (i_handle, SOL_UDPLITE, UDPLITE_SEND_CSCOV,
286                     &cscov, sizeof (cscov));
287 #endif
288
289     var_Get( p_access, SOUT_CFG_PREFIX "caching", &val );
290     p_sys->p_thread->i_caching = (int64_t)val.i_int * 1000;
291
292     var_Get( p_access, SOUT_CFG_PREFIX "group", &val );
293     p_sys->p_thread->i_group = val.i_int;
294
295     p_sys->i_mtu = var_CreateGetInteger( p_this, "mtu" );
296
297     if( vlc_thread_create( p_sys->p_thread, "sout write thread", ThreadWrite,
298                            VLC_THREAD_PRIORITY_HIGHEST, VLC_FALSE ) )
299     {
300         msg_Err( p_access->p_sout, "cannot spawn sout access thread" );
301         vlc_object_destroy( p_sys->p_thread );
302         return VLC_EGENERIC;
303     }
304
305     srand( (uint32_t)mdate());
306     p_sys->p_buffer          = NULL;
307     p_sys->i_sequence_number = rand()&0xffff;
308     p_sys->i_ssrc            = rand()&0xffffffff;
309
310     var_Get( p_access, SOUT_CFG_PREFIX "raw", &val );
311     if( val.b_bool )  p_access->pf_write = WriteRaw;
312     else p_access->pf_write = Write;
313
314     p_access->pf_seek = Seek;
315
316     msg_Dbg( p_access, "udp access output opened(%s:%d)",
317              psz_dst_addr, i_dst_port );
318
319     free( psz_dst_addr );
320
321     /* update p_sout->i_out_pace_nocontrol */
322     p_access->p_sout->i_out_pace_nocontrol++;
323
324     return VLC_SUCCESS;
325 }
326
327 /*****************************************************************************
328  * Close: close the target
329  *****************************************************************************/
330 static void Close( vlc_object_t * p_this )
331 {
332     sout_access_out_t     *p_access = (sout_access_out_t*)p_this;
333     sout_access_out_sys_t *p_sys = p_access->p_sys;
334     int i;
335
336     p_sys->p_thread->b_die = 1;
337     for( i = 0; i < 10; i++ )
338     {
339         block_t *p_dummy = block_New( p_access, p_sys->i_mtu );
340         p_dummy->i_dts = 0;
341         p_dummy->i_pts = 0;
342         p_dummy->i_length = 0;
343         memset( p_dummy->p_buffer, 0, p_dummy->i_buffer );
344         block_FifoPut( p_sys->p_thread->p_fifo, p_dummy );
345     }
346     vlc_thread_join( p_sys->p_thread );
347
348     block_FifoRelease( p_sys->p_thread->p_fifo );
349     block_FifoRelease( p_sys->p_thread->p_empty_blocks );
350
351     if( p_sys->p_buffer ) block_Release( p_sys->p_buffer );
352
353     net_Close( p_sys->p_thread->i_handle );
354
355     vlc_object_detach( p_sys->p_thread );
356     vlc_object_destroy( p_sys->p_thread );
357     /* update p_sout->i_out_pace_nocontrol */
358     p_access->p_sout->i_out_pace_nocontrol--;
359
360     msg_Dbg( p_access, "udp access output closed" );
361     free( p_sys );
362 }
363
364 /*****************************************************************************
365  * Write: standard write on a file descriptor.
366  *****************************************************************************/
367 static int Write( sout_access_out_t *p_access, block_t *p_buffer )
368 {
369     sout_access_out_sys_t *p_sys = p_access->p_sys;
370
371     while( p_buffer )
372     {
373         block_t *p_next;
374         int i_packets = 0;
375
376         if( !p_sys->b_mtu_warning && p_buffer->i_buffer > p_sys->i_mtu )
377         {
378             msg_Warn( p_access, "packet size > MTU, you should probably "
379                       "increase the MTU" );
380             p_sys->b_mtu_warning = VLC_TRUE;
381         }
382
383         /* Check if there is enough space in the buffer */
384         if( p_sys->p_buffer &&
385             p_sys->p_buffer->i_buffer + p_buffer->i_buffer > p_sys->i_mtu )
386         {
387             if( p_sys->p_buffer->i_dts + p_sys->p_thread->i_caching < mdate() )
388             {
389                 msg_Dbg( p_access, "late packet for udp input (" I64Fd ")",
390                          mdate() - p_sys->p_buffer->i_dts
391                           - p_sys->p_thread->i_caching );
392             }
393             block_FifoPut( p_sys->p_thread->p_fifo, p_sys->p_buffer );
394             p_sys->p_buffer = NULL;
395         }
396
397         while( p_buffer->i_buffer )
398         {
399             int i_payload_size = p_sys->i_mtu;
400             if( p_sys->b_rtpts )
401                 i_payload_size -= RTP_HEADER_LENGTH;
402             
403             int i_write = __MIN( p_buffer->i_buffer, i_payload_size );
404
405             i_packets++;
406
407             if( !p_sys->p_buffer )
408             {
409                 p_sys->p_buffer = NewUDPPacket( p_access, p_buffer->i_dts );
410                 if( !p_sys->p_buffer ) break;
411             }
412
413             memcpy( p_sys->p_buffer->p_buffer + p_sys->p_buffer->i_buffer,
414                     p_buffer->p_buffer, i_write );
415
416             p_sys->p_buffer->i_buffer += i_write;
417             p_buffer->p_buffer += i_write;
418             p_buffer->i_buffer -= i_write;
419             if ( p_buffer->i_flags & BLOCK_FLAG_CLOCK )
420             {
421                 if ( p_sys->p_buffer->i_flags & BLOCK_FLAG_CLOCK )
422                     msg_Warn( p_access, "putting two PCRs at once" );
423                 p_sys->p_buffer->i_flags |= BLOCK_FLAG_CLOCK;
424             }
425
426             if( p_sys->p_buffer->i_buffer == p_sys->i_mtu || i_packets > 1 )
427             {
428                 /* Flush */
429                 if( p_sys->p_buffer->i_dts + p_sys->p_thread->i_caching
430                       < mdate() )
431                 {
432                     msg_Dbg( p_access, "late packet for udp input (" I64Fd ")",
433                              mdate() - p_sys->p_buffer->i_dts
434                               - p_sys->p_thread->i_caching );
435                 }
436                 block_FifoPut( p_sys->p_thread->p_fifo, p_sys->p_buffer );
437                 p_sys->p_buffer = NULL;
438             }
439         }
440
441         p_next = p_buffer->p_next;
442         block_Release( p_buffer );
443         p_buffer = p_next;
444     }
445
446     return( p_sys->p_thread->b_error ? -1 : 0 );
447 }
448
449 /*****************************************************************************
450  * WriteRaw: write p_buffer without trying to fill mtu
451  *****************************************************************************/
452 static int WriteRaw( sout_access_out_t *p_access, block_t *p_buffer )
453 {
454     sout_access_out_sys_t   *p_sys = p_access->p_sys;
455     block_t *p_buf;
456
457     while ( p_sys->p_thread->p_empty_blocks->i_depth >= MAX_EMPTY_BLOCKS )
458     {
459         p_buf = block_FifoGet(p_sys->p_thread->p_empty_blocks);
460         block_Release( p_buf );
461     }
462
463     block_FifoPut( p_sys->p_thread->p_fifo, p_buffer );
464
465     return( p_sys->p_thread->b_error ? -1 : 0 );
466 }
467
468 /*****************************************************************************
469  * Seek: seek to a specific location in a file
470  *****************************************************************************/
471 static int Seek( sout_access_out_t *p_access, off_t i_pos )
472 {
473     msg_Err( p_access, "UDP sout access cannot seek" );
474     return -1;
475 }
476
477 /*****************************************************************************
478  * NewUDPPacket: allocate a new UDP packet of size p_sys->i_mtu
479  *****************************************************************************/
480 static block_t *NewUDPPacket( sout_access_out_t *p_access, mtime_t i_dts)
481 {
482     sout_access_out_sys_t *p_sys = p_access->p_sys;
483     block_t *p_buffer;
484
485     while ( p_sys->p_thread->p_empty_blocks->i_depth > MAX_EMPTY_BLOCKS )
486     {
487         p_buffer = block_FifoGet( p_sys->p_thread->p_empty_blocks );
488         block_Release( p_buffer );
489     }
490
491     if( p_sys->p_thread->p_empty_blocks->i_depth == 0 )
492     {
493         p_buffer = block_New( p_access->p_sout, p_sys->i_mtu );
494     }
495     else
496     {
497         p_buffer = block_FifoGet(p_sys->p_thread->p_empty_blocks );       
498         p_buffer->i_flags = 0;
499         p_buffer = block_Realloc( p_buffer, 0, p_sys->i_mtu );
500     }
501
502     p_buffer->i_dts = i_dts;
503     p_buffer->i_buffer = 0;
504
505     if( p_sys->b_rtpts )
506     {
507         mtime_t i_timestamp = p_buffer->i_dts * 9 / 100;
508
509         /* add rtp/ts header */
510         p_buffer->p_buffer[0] = 0x80;
511         p_buffer->p_buffer[1] = 0x21; // mpeg2-ts
512
513         p_buffer->p_buffer[2] = ( p_sys->i_sequence_number >> 8 )&0xff;
514         p_buffer->p_buffer[3] = p_sys->i_sequence_number&0xff;
515         p_sys->i_sequence_number++;
516
517         p_buffer->p_buffer[4] = ( i_timestamp >> 24 )&0xff;
518         p_buffer->p_buffer[5] = ( i_timestamp >> 16 )&0xff;
519         p_buffer->p_buffer[6] = ( i_timestamp >>  8 )&0xff;
520         p_buffer->p_buffer[7] = i_timestamp&0xff;
521
522         p_buffer->p_buffer[ 8] = ( p_sys->i_ssrc >> 24 )&0xff;
523         p_buffer->p_buffer[ 9] = ( p_sys->i_ssrc >> 16 )&0xff;
524         p_buffer->p_buffer[10] = ( p_sys->i_ssrc >>  8 )&0xff;
525         p_buffer->p_buffer[11] = p_sys->i_ssrc&0xff;
526
527         p_buffer->i_buffer = RTP_HEADER_LENGTH;
528     }
529
530     return p_buffer;
531 }
532
533 /*****************************************************************************
534  * ThreadWrite: Write a packet on the network at the good time.
535  *****************************************************************************/
536 static void ThreadWrite( vlc_object_t *p_this )
537 {
538     sout_access_thread_t *p_thread = (sout_access_thread_t*)p_this;
539     mtime_t              i_date_last = -1;
540     mtime_t              i_to_send = p_thread->i_group;
541     int                  i_dropped_packets = 0;
542 #if defined(WIN32) || defined(UNDER_CE)
543     char strerror_buf[WINSOCK_STRERROR_SIZE];
544 # define strerror( x ) winsock_strerror( strerror_buf )
545 #endif
546
547     while( !p_thread->b_die )
548     {
549         block_t *p_pk;
550         mtime_t       i_date, i_sent;
551 #if 0
552         if( (i++ % 1000)==0 ) {
553           int i = 0;
554           int j = 0;
555           block_t *p_tmp = p_thread->p_empty_blocks->p_first;
556           while( p_tmp ) { p_tmp = p_tmp->p_next; i++;}
557           p_tmp = p_thread->p_fifo->p_first;
558           while( p_tmp ) { p_tmp = p_tmp->p_next; j++;}
559           msg_Err( p_thread, "fifo depth: %d/%d, empty blocks: %d/%d",
560                    p_thread->p_fifo->i_depth, j,p_thread->p_empty_blocks->i_depth,i );
561         }
562 #endif
563         p_pk = block_FifoGet( p_thread->p_fifo );
564
565         i_date = p_thread->i_caching + p_pk->i_dts;
566         if( i_date_last > 0 )
567         {
568             if( i_date - i_date_last > 2000000 )
569             {
570                 if( !i_dropped_packets )
571                     msg_Dbg( p_thread, "mmh, hole ("I64Fd" > 2s) -> drop",
572                              i_date - i_date_last );
573
574                 block_FifoPut( p_thread->p_empty_blocks, p_pk );
575
576                 i_date_last = i_date;
577                 i_dropped_packets++;
578                 continue;
579             }
580             else if( i_date - i_date_last < -1000 )
581             {
582                 if( !i_dropped_packets )
583                     msg_Dbg( p_thread, "mmh, packets in the past ("I64Fd")",
584                              i_date_last - i_date );
585             }
586         }
587
588         i_to_send--;
589         if( !i_to_send || (p_pk->i_flags & BLOCK_FLAG_CLOCK) )
590         {
591             mwait( i_date );
592             i_to_send = p_thread->i_group;
593         }
594         if( send( p_thread->i_handle, p_pk->p_buffer, p_pk->i_buffer, 0 )
595               == -1 )
596         {
597             msg_Warn( p_thread, "send error: %s", strerror(errno) );
598         }
599
600         if( i_dropped_packets )
601         {
602             msg_Dbg( p_thread, "dropped %i packets", i_dropped_packets );
603             i_dropped_packets = 0;
604         }
605
606 #if 1
607         i_sent = mdate();
608         if ( i_sent > i_date + 20000 )
609         {
610             msg_Dbg( p_thread, "packet has been sent too late (" I64Fd ")",
611                      i_sent - i_date );
612         }
613 #endif
614
615         block_FifoPut( p_thread->p_empty_blocks, p_pk );
616
617         i_date_last = i_date;
618     }
619 }