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