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