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