codec: subsdec: fix variable shadowing
[vlc.git] / modules / access / srt.c
blobd8d8cbe659b3a9f9494cd6b7dbf04b016fa069f8
1 /*****************************************************************************
2 * srt.c: SRT (Secure Reliable Transport) input module
3 *****************************************************************************
4 * Copyright (C) 2017-2018, Collabora Ltd.
5 * Copyright (C) 2018, Haivision Systems Inc.
7 * Authors: Justin Kim <justin.kim@collabora.com>
8 * Roman Diouskine <rdiouskine@haivision.com>
10 * This program is free software; you can redistribute it and/or modify it
11 * under the terms of the GNU Lesser General Public License as published by
12 * the Free Software Foundation; either version 2.1 of the License, or
13 * (at your option) any later version.
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 Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public License
21 * along with this program; if not, write to the Free Software Foundation,
22 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23 *****************************************************************************/
25 #ifdef HAVE_CONFIG_H
26 # include "config.h"
27 #endif
29 #include <vlc_common.h>
30 #include <vlc_interrupt.h>
31 #include <vlc_fs.h>
32 #include <vlc_plugin.h>
33 #include <vlc_access.h>
35 #include <vlc_network.h>
36 #include <vlc_url.h>
38 #include <srt/srt.h>
40 /* libsrt defines default packet size as 1316 internally
41 * so srt module takes same value. */
42 #define SRT_DEFAULT_CHUNK_SIZE 1316
43 /* Minimum/Maximum chunks to allow reading at a time from libsrt */
44 #define SRT_MIN_CHUNKS_TRYREAD 10
45 #define SRT_MAX_CHUNKS_TRYREAD 100
46 /* The default timeout is -1 (infinite) */
47 #define SRT_DEFAULT_POLL_TIMEOUT -1
48 /* The default latency is 125
49 * which uses srt library internally */
50 #define SRT_DEFAULT_LATENCY 125
51 /* Crypto key length in bytes. */
52 #define SRT_KEY_LENGTH_TEXT N_("Crypto key length in bytes")
53 #define SRT_DEFAULT_KEY_LENGTH 16
54 static const int srt_key_lengths[] = {
55 16, 24, 32,
58 static const char *const srt_key_length_names[] = {
59 N_("16 bytes"), N_("24 bytes"), N_("32 bytes"),
62 typedef struct
64 SRTSOCKET sock;
65 int i_poll_id;
66 vlc_mutex_t lock;
67 bool b_interrupted;
68 char *psz_host;
69 int i_port;
70 int i_chunks; /* Number of chunks to allocate in the next read */
71 } stream_sys_t;
73 static void srt_wait_interrupted(void *p_data)
75 stream_t *p_stream = p_data;
76 stream_sys_t *p_sys = p_stream->p_sys;
78 vlc_mutex_lock( &p_sys->lock );
79 if ( p_sys->i_poll_id >= 0 && p_sys->sock != SRT_INVALID_SOCK )
81 p_sys->b_interrupted = true;
83 msg_Dbg( p_stream, "Waking up srt_epoll_wait");
85 /* Removing all socket descriptors from the monitoring list
86 * wakes up SRT's threads. We only have one to remove. */
87 srt_epoll_remove_usock( p_sys->i_poll_id, p_sys->sock );
89 vlc_mutex_unlock( &p_sys->lock );
92 static int Control(stream_t *p_stream, int i_query, va_list args)
94 int i_ret = VLC_SUCCESS;
96 switch( i_query )
98 case STREAM_CAN_SEEK:
99 case STREAM_CAN_FASTSEEK:
100 case STREAM_CAN_PAUSE:
101 case STREAM_CAN_CONTROL_PACE:
102 *va_arg( args, bool * ) = false;
103 break;
104 case STREAM_GET_PTS_DELAY:
105 *va_arg( args, vlc_tick_t * ) = VLC_TICK_FROM_MS(
106 var_InheritInteger(p_stream, "network-caching") );
107 break;
108 default:
109 i_ret = VLC_EGENERIC;
110 break;
113 return i_ret;
116 static bool srt_schedule_reconnect(stream_t *p_stream)
118 int i_latency;
119 int stat;
120 char *psz_passphrase = NULL;
122 struct addrinfo hints = {
123 .ai_socktype = SOCK_DGRAM,
124 }, *res = NULL;
126 stream_sys_t *p_sys = p_stream->p_sys;
127 bool failed = false;
129 stat = vlc_getaddrinfo( p_sys->psz_host, p_sys->i_port, &hints, &res );
130 if ( stat )
132 msg_Err( p_stream, "Cannot resolve [%s]:%d (reason: %s)",
133 p_sys->psz_host,
134 p_sys->i_port,
135 gai_strerror( stat ) );
137 failed = true;
138 goto out;
141 /* Always start with a fresh socket */
142 if (p_sys->sock != SRT_INVALID_SOCK)
144 srt_epoll_remove_usock( p_sys->i_poll_id, p_sys->sock );
145 srt_close( p_sys->sock );
148 p_sys->sock = srt_socket( res->ai_family, SOCK_DGRAM, 0 );
149 if ( p_sys->sock == SRT_INVALID_SOCK )
151 msg_Err( p_stream, "Failed to open socket." );
152 failed = true;
153 goto out;
156 /* Make SRT non-blocking */
157 srt_setsockopt( p_sys->sock, 0, SRTO_SNDSYN,
158 &(bool) { false }, sizeof( bool ) );
159 srt_setsockopt( p_sys->sock, 0, SRTO_RCVSYN,
160 &(bool) { false }, sizeof( bool ) );
162 /* Make sure TSBPD mode is enable (SRT mode) */
163 srt_setsockopt( p_sys->sock, 0, SRTO_TSBPDMODE,
164 &(int) { 1 }, sizeof( int ) );
166 /* This is an access module so it is always a receiver */
167 srt_setsockopt( p_sys->sock, 0, SRTO_SENDER,
168 &(int) { 0 }, sizeof( int ) );
170 /* Set latency */
171 i_latency = var_InheritInteger( p_stream, "latency" );
172 srt_setsockopt( p_sys->sock, 0, SRTO_TSBPDDELAY,
173 &i_latency, sizeof( int ) );
175 psz_passphrase = var_InheritString( p_stream, "passphrase" );
176 if ( psz_passphrase != NULL && psz_passphrase[0] != '\0')
178 int i_key_length = var_InheritInteger( p_stream, "key-length" );
179 srt_setsockopt( p_sys->sock, 0, SRTO_PASSPHRASE,
180 psz_passphrase, strlen( psz_passphrase ) );
181 srt_setsockopt( p_sys->sock, 0, SRTO_PBKEYLEN,
182 &i_key_length, sizeof( int ) );
185 srt_epoll_add_usock( p_sys->i_poll_id, p_sys->sock,
186 &(int) { SRT_EPOLL_ERR | SRT_EPOLL_IN });
188 /* Schedule a connect */
189 msg_Dbg( p_stream, "Schedule SRT connect (dest addresss: %s, port: %d).",
190 p_sys->psz_host, p_sys->i_port);
192 stat = srt_connect( p_sys->sock, res->ai_addr, res->ai_addrlen);
193 if ( stat == SRT_ERROR )
195 msg_Err( p_stream, "Failed to connect to server (reason: %s)",
196 srt_getlasterror_str() );
197 failed = true;
200 /* Reset the number of chunks to allocate as the bitrate of
201 * the stream may have changed.
203 p_sys->i_chunks = SRT_MIN_CHUNKS_TRYREAD;
205 out:
206 if (failed && p_sys->sock != SRT_INVALID_SOCK)
208 srt_epoll_remove_usock( p_sys->i_poll_id, p_sys->sock );
209 srt_close(p_sys->sock);
210 p_sys->sock = SRT_INVALID_SOCK;
213 freeaddrinfo( res );
214 free( psz_passphrase );
216 return !failed;
219 static block_t *BlockSRT(stream_t *p_stream, bool *restrict eof)
221 stream_sys_t *p_sys = p_stream->p_sys;
222 int i_chunk_size = var_InheritInteger( p_stream, "chunk-size" );
223 int i_poll_timeout = var_InheritInteger( p_stream, "poll-timeout" );
224 /* SRT doesn't have a concept of EOF for live streams. */
225 VLC_UNUSED(eof);
227 if ( vlc_killed() )
229 /* We are told to stop. Stop. */
230 return NULL;
233 if ( p_sys->i_chunks == 0 )
234 p_sys->i_chunks = SRT_MIN_CHUNKS_TRYREAD;
236 size_t i_chunk_size_actual = ( i_chunk_size > 0 )
237 ? i_chunk_size : SRT_DEFAULT_CHUNK_SIZE;
238 size_t bufsize = i_chunk_size_actual * p_sys->i_chunks;
239 block_t *pkt = block_Alloc( bufsize );
240 if ( unlikely( pkt == NULL ) )
242 return NULL;
245 vlc_interrupt_register( srt_wait_interrupted, p_stream);
247 SRTSOCKET ready[1];
248 int readycnt = 1;
249 while ( srt_epoll_wait( p_sys->i_poll_id,
250 ready, &readycnt, 0, 0,
251 i_poll_timeout, NULL, 0, NULL, 0 ) >= 0)
253 if ( readycnt < 0 || ready[0] != p_sys->sock )
255 /* should never happen, force recovery */
256 srt_close(p_sys->sock);
257 p_sys->sock = SRT_INVALID_SOCK;
260 switch( srt_getsockstate( p_sys->sock ) )
262 case SRTS_CONNECTED:
263 /* Good to go */
264 break;
265 case SRTS_BROKEN:
266 case SRTS_NONEXIST:
267 case SRTS_CLOSED:
268 /* Failed. Schedule recovery. */
269 if ( !srt_schedule_reconnect( p_stream ) )
270 msg_Err( p_stream, "Failed to schedule connect" );
271 /* Fall-through */
272 default:
273 /* Not ready */
274 continue;
277 /* Try to get as much data as possible out of the lib, if there
278 * is still some left, increase the number of chunks to read so that
279 * it will read faster on the next iteration. This way the buffer will
280 * grow until it reads fast enough to keep the library empty after
281 * each iteration.
283 pkt->i_buffer = 0;
284 while ( ( bufsize - pkt->i_buffer ) >= i_chunk_size_actual )
286 int stat = srt_recvmsg( p_sys->sock,
287 (char *)( pkt->p_buffer + pkt->i_buffer ),
288 bufsize - pkt->i_buffer );
289 if ( stat <= 0 )
291 break;
293 pkt->i_buffer += (size_t)stat;
296 msg_Dbg ( p_stream, "Read %zu bytes out of a max of %zu"
297 " (%d chunks of %zu bytes)", pkt->i_buffer,
298 p_sys->i_chunks * i_chunk_size_actual, p_sys->i_chunks,
299 i_chunk_size_actual );
302 /* Gradually adjust number of chunks we read at a time
303 * up to a predefined maximum. The actual number we might
304 * settle on depends on stream's bit rate.
306 size_t rem = bufsize - pkt->i_buffer;
307 if ( rem < i_chunk_size_actual )
309 if ( p_sys->i_chunks < SRT_MAX_CHUNKS_TRYREAD )
311 p_sys->i_chunks++;
315 goto out;
318 /* if the poll reports errors for any reason at all,
319 * including a timeout, we skip the turn.
321 pkt->i_buffer = 0;
323 out:
324 if (pkt->i_buffer == 0) {
325 block_Release(pkt);
326 pkt = NULL;
329 vlc_interrupt_unregister();
331 /* Re-add the socket to the poll if we were interrupted */
332 vlc_mutex_lock( &p_sys->lock );
333 if ( p_sys->b_interrupted )
335 srt_epoll_add_usock( p_sys->i_poll_id, p_sys->sock,
336 &(int) { SRT_EPOLL_ERR | SRT_EPOLL_IN } );
337 p_sys->b_interrupted = false;
339 vlc_mutex_unlock( &p_sys->lock );
341 return pkt;
344 static int Open(vlc_object_t *p_this)
346 stream_t *p_stream = (stream_t*)p_this;
347 stream_sys_t *p_sys = NULL;
348 vlc_url_t parsed_url = { 0 };
350 p_sys = vlc_obj_calloc( p_this, 1, sizeof( *p_sys ) );
351 if( unlikely( p_sys == NULL ) )
352 return VLC_ENOMEM;
354 srt_startup();
356 vlc_mutex_init( &p_sys->lock );
358 p_stream->p_sys = p_sys;
360 if ( vlc_UrlParse( &parsed_url, p_stream->psz_url ) == -1 )
362 msg_Err( p_stream, "Failed to parse input URL (%s)",
363 p_stream->psz_url );
364 goto failed;
367 p_sys->psz_host = vlc_obj_strdup( p_this, parsed_url.psz_host );
368 p_sys->i_port = parsed_url.i_port;
370 vlc_UrlClean( &parsed_url );
372 p_sys->i_poll_id = srt_epoll_create();
373 if ( p_sys->i_poll_id == -1 )
375 msg_Err( p_stream, "Failed to create poll id for SRT socket." );
376 goto failed;
379 if ( !srt_schedule_reconnect( p_stream ) )
381 msg_Err( p_stream, "Failed to schedule connect");
383 goto failed;
386 p_stream->pf_block = BlockSRT;
387 p_stream->pf_control = Control;
389 return VLC_SUCCESS;
391 failed:
392 vlc_mutex_destroy( &p_sys->lock );
394 if ( p_sys->sock != -1 ) srt_close( p_sys->sock );
395 if ( p_sys->i_poll_id != -1 ) srt_epoll_release( p_sys->i_poll_id );
397 return VLC_EGENERIC;
400 static void Close(vlc_object_t *p_this)
402 stream_t *p_stream = (stream_t*)p_this;
403 stream_sys_t *p_sys = p_stream->p_sys;
405 vlc_mutex_destroy( &p_sys->lock );
407 srt_epoll_remove_usock( p_sys->i_poll_id, p_sys->sock );
408 srt_close( p_sys->sock );
409 srt_epoll_release( p_sys->i_poll_id );
411 srt_cleanup();
414 /* Module descriptor */
415 vlc_module_begin ()
416 set_shortname( N_("SRT") )
417 set_description( N_("SRT input") )
418 set_category( CAT_INPUT )
419 set_subcategory( SUBCAT_INPUT_ACCESS )
421 add_integer( "chunk-size", SRT_DEFAULT_CHUNK_SIZE,
422 N_("SRT chunk size (bytes)"), NULL, true )
423 add_integer( "poll-timeout", SRT_DEFAULT_POLL_TIMEOUT,
424 N_("Return poll wait after timeout milliseconds (-1 = infinite)"), NULL, true )
425 add_integer( "latency", SRT_DEFAULT_LATENCY, N_("SRT latency (ms)"), NULL, true )
426 add_password("passphrase", "", N_("Password for stream encryption"), NULL)
427 add_integer( "key-length", SRT_DEFAULT_KEY_LENGTH,
428 SRT_KEY_LENGTH_TEXT, SRT_KEY_LENGTH_TEXT, false )
429 change_integer_list( srt_key_lengths, srt_key_length_names )
431 set_capability( "access", 0 )
432 add_shortcut( "srt" )
434 set_callbacks( Open, Close )
435 vlc_module_end ()