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