]> git.sesse.net Git - vlc/blob - modules/access_output/udp.c
Add pf_control to 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 #else
47 #   include <sys/socket.h>
48 #endif
49
50 #include <vlc_network.h>
51
52 #if defined (HAVE_NETINET_UDPLITE_H)
53 # include <netinet/udplite.h>
54 #elif defined (__linux__)
55 # define UDPLITE_SEND_CSCOV     10
56 # define UDPLITE_RECV_CSCOV     11
57 #endif
58
59 #ifndef IPPROTO_UDPLITE
60 # define IPPROTO_UDPLITE 136 /* from IANA */
61 #endif
62 #ifndef SOL_UDPLITE
63 # define SOL_UDPLITE IPPROTO_UDPLITE
64 #endif
65
66 #define MAX_EMPTY_BLOCKS 200
67
68 #if defined(WIN32) || defined(UNDER_CE)
69 # define WINSOCK_STRERROR_SIZE 20
70 static const char *winsock_strerror( char *buf )
71 {
72     snprintf( buf, WINSOCK_STRERROR_SIZE, "Winsock error %d",
73               WSAGetLastError( ) );
74     buf[WINSOCK_STRERROR_SIZE - 1] = '\0';
75     return buf;
76 }
77 #endif
78
79 /*****************************************************************************
80  * Module descriptor
81  *****************************************************************************/
82 static int  Open ( vlc_object_t * );
83 static void Close( vlc_object_t * );
84
85 #define SOUT_CFG_PREFIX "sout-udp-"
86
87 #define CACHING_TEXT N_("Caching value (ms)")
88 #define CACHING_LONGTEXT N_( \
89     "Default caching value for outbound UDP streams. This " \
90     "value should be set in milliseconds." )
91
92 #define GROUP_TEXT N_("Group packets")
93 #define GROUP_LONGTEXT N_("Packets can be sent one by one at the right time " \
94                           "or by groups. You can choose the number " \
95                           "of packets that will be sent at a time. It " \
96                           "helps reducing the scheduling load on " \
97                           "heavily-loaded systems." )
98 #define RAW_TEXT N_("Raw write")
99 #define RAW_LONGTEXT N_("Packets will be sent " \
100                        "directly, without trying to fill the MTU (ie, " \
101                        "without trying to make the biggest possible packets " \
102                        "in order to improve streaming)." )
103
104 vlc_module_begin();
105     set_description( _("UDP stream output") );
106     set_shortname( "UDP" );
107     set_category( CAT_SOUT );
108     set_subcategory( SUBCAT_SOUT_ACO );
109     add_integer( SOUT_CFG_PREFIX "caching", DEFAULT_PTS_DELAY / 1000, NULL, CACHING_TEXT, CACHING_LONGTEXT, VLC_TRUE );
110     add_integer( SOUT_CFG_PREFIX "group", 1, NULL, GROUP_TEXT, GROUP_LONGTEXT,
111                                  VLC_TRUE );
112     add_suppressed_integer( SOUT_CFG_PREFIX "late" );
113     add_bool( SOUT_CFG_PREFIX "raw",  0, NULL, RAW_TEXT, RAW_LONGTEXT,
114                                  VLC_TRUE );
115
116     set_capability( "sout access", 100 );
117     add_shortcut( "udp" );
118     add_shortcut( "rtp" ); // Will work only with ts muxer
119     add_shortcut( "udplite" );
120     set_callbacks( Open, Close );
121 vlc_module_end();
122
123 /*****************************************************************************
124  * Exported prototypes
125  *****************************************************************************/
126
127 static const char *ppsz_sout_options[] = {
128     "caching",
129     "group",
130     "raw",
131     NULL
132 };
133
134 /* Options handled by the libvlc network core */
135 static const char *ppsz_core_options[] = {
136     "dscp",
137     "ttl",
138     "miface",
139     "miface-addr",
140     NULL
141 };
142
143 static int  Write   ( sout_access_out_t *, block_t * );
144 static int  WriteRaw( sout_access_out_t *, block_t * );
145 static int  Seek    ( sout_access_out_t *, off_t  );
146
147 static void ThreadWrite( vlc_object_t * );
148 static block_t *NewUDPPacket( sout_access_out_t *, mtime_t );
149
150 typedef struct sout_access_thread_t
151 {
152     VLC_COMMON_MEMBERS
153
154     sout_instance_t *p_sout;
155
156     block_fifo_t *p_fifo;
157
158     int         i_handle;
159
160     int64_t     i_caching;
161     int         i_group;
162
163     block_fifo_t *p_empty_blocks;
164
165 } sout_access_thread_t;
166
167 struct sout_access_out_sys_t
168 {
169     int                 b_rtpts;  // 1 if add rtp/ts header
170     uint16_t            i_sequence_number;
171     uint32_t            i_ssrc;
172
173     int                 i_mtu;
174
175     block_t             *p_buffer;
176
177     sout_access_thread_t *p_thread;
178
179     vlc_bool_t          b_mtu_warning;
180 };
181
182 #define DEFAULT_PORT 1234
183 #define RTP_HEADER_LENGTH 12
184
185 /*****************************************************************************
186  * Open: open the file
187  *****************************************************************************/
188 static int Open( vlc_object_t *p_this )
189 {
190     sout_access_out_t       *p_access = (sout_access_out_t*)p_this;
191     sout_access_out_sys_t   *p_sys;
192
193     char                *psz_parser;
194     char                *psz_dst_addr;
195     int                 i_dst_port, proto = IPPROTO_UDP, cscov = 8;
196     const char          *protoname = "UDP";
197
198     int                 i_handle;
199
200     vlc_value_t         val;
201
202     config_ChainParse( p_access, SOUT_CFG_PREFIX,
203                        ppsz_sout_options, p_access->p_cfg );
204     config_ChainParse( p_access, "",
205                        ppsz_core_options, p_access->p_cfg );
206
207     if( !( p_sys = calloc ( 1, sizeof( sout_access_out_sys_t ) ) ) )
208     {
209         msg_Err( p_access, "not enough memory" );
210         return VLC_EGENERIC;
211     }
212     p_access->p_sys = p_sys;
213
214     if( p_access->psz_access != NULL )
215     {
216         if (strcmp (p_access->psz_access, "rtp") == 0)
217             p_sys->b_rtpts = VLC_TRUE;
218         if (strcmp (p_access->psz_access, "udplite") == 0)
219         {
220             protoname = "UDP-Lite";
221             proto = IPPROTO_UDPLITE;
222             p_sys->b_rtpts = VLC_TRUE;
223         }
224     }
225     if (p_sys->b_rtpts)
226         cscov += RTP_HEADER_LENGTH;
227
228     psz_parser = strdup( p_access->psz_name );
229
230     psz_dst_addr = psz_parser;
231     i_dst_port = 0;
232
233     if ( *psz_parser == '[' )
234     {
235         while( *psz_parser && *psz_parser != ']' )
236         {
237             psz_parser++;
238         }
239     }
240     while( *psz_parser && *psz_parser != ':' )
241     {
242         psz_parser++;
243     }
244     if( *psz_parser == ':' )
245     {
246         *psz_parser = '\0';
247         psz_parser++;
248         i_dst_port = atoi( psz_parser );
249     }
250     if( i_dst_port <= 0 )
251     {
252         i_dst_port = DEFAULT_PORT;
253     }
254
255     p_sys->p_thread =
256         vlc_object_create( p_access, sizeof( sout_access_thread_t ) );
257     if( !p_sys->p_thread )
258     {
259         msg_Err( p_access, "out of memory" );
260         return VLC_EGENERIC;
261     }
262
263     vlc_object_attach( p_sys->p_thread, p_access );
264     p_sys->p_thread->p_sout = p_access->p_sout;
265     p_sys->p_thread->b_die  = 0;
266     p_sys->p_thread->b_error= 0;
267     p_sys->p_thread->p_fifo = block_FifoNew( p_access );
268     p_sys->p_thread->p_empty_blocks = block_FifoNew( p_access );
269
270     i_handle = net_ConnectDgram( p_this, psz_dst_addr, i_dst_port, -1, proto );
271     if( i_handle == -1 )
272     {
273          msg_Err( p_access, "failed to create %s socket", protoname );
274          return VLC_EGENERIC;
275     }
276
277     p_sys->p_thread->i_handle = i_handle;
278     net_StopRecv( i_handle );
279
280 #ifdef UDPLITE_SEND_CSCOV
281     if (proto == IPPROTO_UDPLITE)
282         setsockopt (i_handle, SOL_UDPLITE, UDPLITE_SEND_CSCOV,
283                     &cscov, sizeof (cscov));
284 #endif
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, "%s access output opened(%s:%d)",
314              protoname, 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 }