53647ba084ccfb498eb64be2db71ebedbe5bcc6a
[vlc.git] / modules / access / rtmp / access.c
1 /*****************************************************************************
2  * access.c: RTMP input.
3  *****************************************************************************
4  * Copyright (C) URJC - LADyR - Luis Lopez Fernandez
5  *
6  * Author: Miguel Angel Cabrera Moya
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
21  *****************************************************************************/
22
23 /*****************************************************************************
24  * Preamble
25  *****************************************************************************/
26 #ifdef HAVE_CONFIG_H
27 # include "config.h"
28 #endif
29
30 #include <vlc_common.h>
31 #include <vlc_plugin.h>
32 #include <vlc_access.h>
33
34 #include <vlc_network.h> /* DOWN: #include <network.h> */
35 #include <vlc_url.h>
36 #include <vlc_block.h>
37
38 #include "rtmp_amf_flv.h"
39
40 /*****************************************************************************
41  * Module descriptor
42  *****************************************************************************/
43 #define CACHING_TEXT N_("Caching value in ms")
44 #define CACHING_LONGTEXT N_( \
45     "Caching value for RTMP streams. This " \
46     "value should be set in milliseconds." )
47
48 static int  Open ( vlc_object_t * );
49 static void Close( vlc_object_t * );
50
51 vlc_module_begin ()
52     set_description( N_("RTMP input") )
53     set_shortname( N_("RTMP") )
54     set_category( CAT_INPUT )
55     set_subcategory( SUBCAT_INPUT_ACCESS )
56
57     add_integer( "rtmp-caching", DEFAULT_PTS_DELAY / 1000, NULL, CACHING_TEXT,
58                  CACHING_LONGTEXT, true )
59
60     set_capability( "access", 0 )
61     set_callbacks( Open, Close )
62     add_shortcut( "rtmp" )
63 vlc_module_end ()
64
65
66 /*****************************************************************************
67  * Local prototypes
68  *****************************************************************************/
69 static ssize_t  Read( access_t *, uint8_t *, size_t );
70 static int Seek( access_t *, int64_t );
71 static int Control( access_t *, int, va_list );
72
73 static void* ThreadControl( vlc_object_t * );
74
75 /*****************************************************************************
76  * Open: open the rtmp connection
77  *****************************************************************************/
78 static int Open( vlc_object_t *p_this )
79 {
80     access_t *p_access = (access_t *) p_this;
81     access_sys_t *p_sys;
82     char *psz, *p; 
83     int length_path, length_media_name;
84     int i;
85
86     STANDARD_READ_ACCESS_INIT
87
88     p_sys->p_thread =
89         vlc_object_create( p_access, sizeof( rtmp_control_thread_t ) );
90     if( !p_sys->p_thread )
91         return VLC_ENOMEM;
92     vlc_object_attach( p_sys->p_thread, p_access );
93
94     /* Parse URI - remove spaces */
95     p = psz = strdup( p_access->psz_path );
96     while( (p = strchr( p, ' ' )) != NULL )
97         *p = '+';
98     vlc_UrlParse( &p_sys->p_thread->url, psz, 0 );
99     free( psz );
100
101     if( p_sys->p_thread->url.psz_host == NULL
102         || *p_sys->p_thread->url.psz_host == '\0' )
103     {
104         msg_Warn( p_access, "invalid host" );
105         goto error;
106     }
107
108     if( p_sys->p_thread->url.i_port <= 0 )
109         p_sys->p_thread->url.i_port = 1935;
110
111     if( p_sys->p_thread->url.psz_path == NULL )
112     {
113         msg_Warn( p_access, "invalid path" );
114         goto error;
115     }
116
117     length_path = strlen( p_sys->p_thread->url.psz_path );
118     char* psz_tmp = strrchr( p_sys->p_thread->url.psz_path, '/' );
119     if( !psz_tmp )
120         goto error;
121     length_media_name = strlen( psz_tmp ) - 1;
122
123     p_sys->p_thread->psz_application = strndup( p_sys->p_thread->url.psz_path + 1, length_path - length_media_name - 2 );
124     p_sys->p_thread->psz_media = strdup( p_sys->p_thread->url.psz_path + ( length_path - length_media_name ) );
125
126     msg_Dbg( p_access, "rtmp: host='%s' port=%d path='%s'",
127              p_sys->p_thread->url.psz_host, p_sys->p_thread->url.i_port, p_sys->p_thread->url.psz_path );
128
129     if( p_sys->p_thread->url.psz_username && *p_sys->p_thread->url.psz_username )
130     {
131         msg_Dbg( p_access, "      user='%s'", p_sys->p_thread->url.psz_username );
132     }
133
134     /* Initialize thread variables */
135     p_sys->p_thread->b_die = 0;
136     p_sys->p_thread->b_error= 0;
137     p_sys->p_thread->p_fifo_input = block_FifoNew();
138     p_sys->p_thread->p_empty_blocks = block_FifoNew();
139     p_sys->p_thread->has_audio = 0;
140     p_sys->p_thread->has_video = 0;
141     p_sys->p_thread->metadata_received = 0;
142     p_sys->p_thread->first_media_packet = 1;
143     p_sys->p_thread->flv_tag_previous_tag_size = 0x00000000; /* FLV_TAG_FIRST_PREVIOUS_TAG_SIZE */
144     p_sys->p_thread->chunk_size_recv = 128; /* RTMP_DEFAULT_CHUNK_SIZE */
145     p_sys->p_thread->chunk_size_send = 128; /* RTMP_DEFAULT_CHUNK_SIZE */
146     for(i = 0; i < 64; i++)
147     {
148         memset( &p_sys->p_thread->rtmp_headers_recv[i], 0, sizeof( rtmp_packet_t ) );
149         p_sys->p_thread->rtmp_headers_send[i].length_header = -1;
150         p_sys->p_thread->rtmp_headers_send[i].stream_index = -1;
151         p_sys->p_thread->rtmp_headers_send[i].timestamp = -1;
152         p_sys->p_thread->rtmp_headers_send[i].timestamp_relative = -1;
153         p_sys->p_thread->rtmp_headers_send[i].length_encoded = -1;
154         p_sys->p_thread->rtmp_headers_send[i].length_body = -1;
155         p_sys->p_thread->rtmp_headers_send[i].content_type = -1;
156         p_sys->p_thread->rtmp_headers_send[i].src_dst = -1;
157         p_sys->p_thread->rtmp_headers_send[i].body = NULL;
158     }
159
160     p_sys->p_thread->p_base_object = p_this;
161
162     vlc_cond_init( &p_sys->p_thread->wait );
163
164     vlc_mutex_init( &p_sys->p_thread->lock );
165
166     p_sys->p_thread->result_connect = 1;
167     p_sys->p_thread->result_play = 1;
168     p_sys->p_thread->result_stop = 0;
169
170     /* Open connection */
171     p_sys->p_thread->fd = net_ConnectTCP( p_access, p_sys->p_thread->url.psz_host, p_sys->p_thread->url.i_port );
172     if( p_sys->p_thread->fd == -1 )
173     {
174         int *p_fd_listen;
175
176         msg_Warn( p_access, "cannot connect to %s:%d", p_sys->p_thread->url.psz_host, p_sys->p_thread->url.i_port );
177         msg_Dbg( p_access, "switching to passive mode" );
178
179         p_sys->active = 0;
180
181         p_fd_listen = net_ListenTCP( p_access, p_sys->p_thread->url.psz_host, p_sys->p_thread->url.i_port );
182         if( p_fd_listen == NULL )
183         {
184             msg_Err( p_access, "cannot listen to %s port %i", p_sys->p_thread->url.psz_host, p_sys->p_thread->url.i_port );
185             goto error2;
186         }
187
188         p_sys->p_thread->fd = net_Accept( p_access, p_fd_listen, -1 );
189
190         net_ListenClose( p_fd_listen );
191
192         if( rtmp_handshake_passive( p_this, p_sys->p_thread->fd ) < 0 )
193         {
194             msg_Err( p_access, "handshake passive failed");
195             goto error2;
196         }
197
198         p_sys->p_thread->result_publish = 1;
199     }
200     else
201     {
202         p_sys->active = 1;
203
204         if( rtmp_handshake_active( p_this, p_sys->p_thread->fd ) < 0 )
205         {
206             msg_Err( p_access, "handshake active failed");
207             goto error2;
208         }
209
210         p_sys->p_thread->result_publish = 0;
211     }
212
213     if( vlc_thread_create( p_sys->p_thread, "rtmp control thread", ThreadControl,
214                            VLC_THREAD_PRIORITY_INPUT ) )
215     {
216         msg_Err( p_access, "cannot spawn rtmp control thread" );
217         goto error2;
218     }
219
220     if( p_sys->active )
221     {
222         if( rtmp_connect_active( p_sys->p_thread ) < 0 )
223         {
224             msg_Err( p_access, "connect active failed");
225             /* Kill the running thread */
226             vlc_object_kill( p_sys->p_thread );
227             block_FifoWake( p_sys->p_thread->p_fifo_input );
228             vlc_thread_join( p_sys->p_thread );
229             goto error2;
230         }
231     }
232
233     /* Set vars for reading from fifo */
234     p_access->p_sys->flv_packet = NULL;
235     p_access->p_sys->read_packet = 1;
236
237     /* Update default_pts to a suitable value for rtmp access */
238     var_Create( p_access, "rtmp-caching", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
239
240     return VLC_SUCCESS;
241
242 error2:
243     vlc_cond_destroy( &p_sys->p_thread->wait );
244     vlc_mutex_destroy( &p_sys->p_thread->lock );
245
246     block_FifoRelease( p_sys->p_thread->p_fifo_input );
247     block_FifoRelease( p_sys->p_thread->p_empty_blocks );
248
249     free( p_sys->p_thread->psz_application );
250     free( p_sys->p_thread->psz_media );
251
252     net_Close( p_sys->p_thread->fd );
253 error:
254     vlc_UrlClean( &p_sys->p_thread->url );
255
256     vlc_object_detach( p_sys->p_thread );
257     vlc_object_release( p_sys->p_thread );
258
259     free( p_sys );
260
261     return VLC_EGENERIC;
262 }
263
264 /*****************************************************************************
265  * Close: close the rtmp connection
266  *****************************************************************************/
267 static void Close( vlc_object_t * p_this )
268 {
269     access_t     *p_access = (access_t *) p_this;
270     access_sys_t *p_sys = p_access->p_sys;
271     int i;
272
273 /*    p_sys->p_thread->b_die = true;*/
274     vlc_object_kill( p_sys->p_thread );
275     block_FifoWake( p_sys->p_thread->p_fifo_input );
276
277     vlc_thread_join( p_sys->p_thread );
278
279     vlc_cond_destroy( &p_sys->p_thread->wait );
280     vlc_mutex_destroy( &p_sys->p_thread->lock );
281
282     block_FifoRelease( p_sys->p_thread->p_fifo_input );
283     block_FifoRelease( p_sys->p_thread->p_empty_blocks );
284
285     for( i = 0; i < 64; i++ ) /* RTMP_HEADER_STREAM_INDEX_MASK */
286     {
287         if( p_sys->p_thread->rtmp_headers_recv[i].body != NULL )
288         {
289             free( p_sys->p_thread->rtmp_headers_recv[i].body->body );
290             free( p_sys->p_thread->rtmp_headers_recv[i].body );
291         }
292     }
293
294     net_Close( p_sys->p_thread->fd );
295
296     var_Destroy( p_access, "rtmp-caching" );
297
298     vlc_UrlClean( &p_sys->p_thread->url );
299     free( p_sys->p_thread->psz_application );
300     free( p_sys->p_thread->psz_media );
301
302     vlc_object_detach( p_sys->p_thread );
303     vlc_object_release( p_sys->p_thread );
304     free( p_sys );
305 }
306
307 /*****************************************************************************
308  * Read: standard read on a file descriptor.
309  *****************************************************************************/
310 static ssize_t Read( access_t *p_access, uint8_t *p_buffer, size_t i_len )
311 {
312     access_sys_t *p_sys = p_access->p_sys;
313     rtmp_packet_t *rtmp_packet;
314     uint8_t *tmp_buffer;
315     ssize_t i_ret;
316     size_t i_len_tmp;
317
318     i_len_tmp = 0;
319
320     while( i_len_tmp < i_len )
321     {
322         if( p_sys->p_thread->result_stop || p_access->info.b_eof || !vlc_object_alive (p_access) )
323         {
324             p_access->info.b_eof = true;
325             return 0;
326         }
327
328         if( p_sys->read_packet )
329         {
330             if( !p_sys->p_thread->metadata_received )
331             {
332                 /* Wait until enough data is received for extracting metadata */
333                 if( block_FifoCount( p_sys->p_thread->p_fifo_input ) < 10 )
334                 {
335                     msleep(100000);
336                     continue;
337                 }
338
339                 p_sys->flv_packet = flv_get_metadata( p_access );
340
341                 p_sys->p_thread->metadata_received = 1;
342             }
343             else
344             {
345                 p_sys->flv_packet = block_FifoGet( p_sys->p_thread->p_fifo_input );
346                 if( p_sys->flv_packet == NULL )
347                     continue; /* Forced wake-up */
348             }
349
350             if( p_sys->p_thread->first_media_packet )
351             {
352                 p_sys->flv_packet = flv_insert_header( p_access, p_sys->flv_packet );
353
354                 p_sys->p_thread->first_media_packet = 0;
355             }
356         }
357         if( i_len - i_len_tmp >= p_sys->flv_packet->i_buffer )
358         {
359             p_sys->read_packet = 1;
360
361             memcpy( p_buffer + i_len_tmp, p_sys->flv_packet->p_buffer, p_sys->flv_packet->i_buffer );
362             block_FifoPut( p_sys->p_thread->p_empty_blocks, p_sys->flv_packet );
363
364             i_len_tmp += p_sys->flv_packet->i_buffer;
365         }
366         else
367         {
368             p_sys->read_packet = 0;
369
370             memcpy( p_buffer + i_len_tmp, p_sys->flv_packet->p_buffer, i_len - i_len_tmp);
371             p_sys->flv_packet->i_buffer -= i_len - i_len_tmp;
372             memmove( p_sys->flv_packet->p_buffer, p_sys->flv_packet->p_buffer + i_len - i_len_tmp, p_sys->flv_packet->i_buffer );
373
374             i_len_tmp += i_len - i_len_tmp;
375         }
376     }
377     if( i_len_tmp > 0 )
378     {
379         if( p_sys->p_thread->result_publish )
380         {
381             /* Send publish onStatus event only once */
382             p_sys->p_thread->result_publish = 0;
383
384             rtmp_packet = rtmp_build_publish_start( p_sys->p_thread );
385
386             tmp_buffer = rtmp_encode_packet( p_sys->p_thread, rtmp_packet );
387
388             i_ret = net_Write( p_sys->p_thread, p_sys->p_thread->fd, NULL, tmp_buffer, rtmp_packet->length_encoded );
389             if( i_ret != rtmp_packet->length_encoded )
390             {
391                 free( rtmp_packet->body->body );
392                 free( rtmp_packet->body );
393                 free( rtmp_packet );
394                 free( tmp_buffer );
395                 msg_Err( p_access, "failed send publish start" );
396                 return -1;
397             }
398             free( rtmp_packet->body->body );
399             free( rtmp_packet->body );
400             free( rtmp_packet );
401             free( tmp_buffer );
402         }
403
404         p_access->info.i_pos += i_len_tmp;
405
406         rtmp_packet = rtmp_build_bytes_read( p_sys->p_thread, p_access->info.i_pos );
407
408         tmp_buffer = rtmp_encode_packet( p_sys->p_thread, rtmp_packet );
409  
410         i_ret = net_Write( p_sys->p_thread, p_sys->p_thread->fd, NULL, tmp_buffer, rtmp_packet->length_encoded );
411         if( i_ret != rtmp_packet->length_encoded )
412         {
413             free( rtmp_packet->body->body );
414             free( rtmp_packet->body );
415             free( rtmp_packet );
416             free( tmp_buffer );
417             msg_Err( p_access, "failed send bytes read" );
418             return -1;
419         }
420         free( rtmp_packet->body->body );
421         free( rtmp_packet->body );
422         free( rtmp_packet );
423         free( tmp_buffer );
424     }
425
426     return i_len_tmp;
427 }
428
429 /*****************************************************************************
430  * Seek: seek to a specific location in a file
431  *****************************************************************************/
432 static int Seek( access_t *p_access, int64_t i_pos )
433 {
434     VLC_UNUSED( p_access );
435     VLC_UNUSED( i_pos );
436 /*msg_Warn ( p_access, "Seek to %lld", i_pos);
437     switch( rtmp_seek( p_access, i_pos ) )
438     {
439         case -1:
440             return VLC_EGENERIC;
441         case 0:
442             break;
443         default:
444             msg_Err( p_access, "You should not be here" );
445             abort();
446     }
447 */
448     return VLC_EGENERIC;
449 }
450
451 /*****************************************************************************
452  * Control:
453  *****************************************************************************/
454 static int Control( access_t *p_access, int i_query, va_list args )
455 {
456     bool    *pb_bool;
457     int64_t *pi_64;
458
459     switch( i_query )
460     {
461         /* */
462         case ACCESS_CAN_SEEK:
463         case ACCESS_CAN_FASTSEEK:
464             pb_bool = (bool*) va_arg( args, bool* );
465             *pb_bool = false; /* TODO */
466             break;
467
468         case ACCESS_CAN_PAUSE:
469             pb_bool = (bool*) va_arg( args, bool* );
470             *pb_bool = false; /* TODO */
471             break;
472
473         case ACCESS_CAN_CONTROL_PACE:
474             pb_bool = (bool*) va_arg( args, bool* );
475             *pb_bool = true;
476             break;
477
478         /* */
479         case ACCESS_GET_PTS_DELAY:
480             pi_64 = (int64_t*) va_arg( args, int64_t * );
481             *pi_64 = var_GetInteger( p_access, "rtmp-caching" ) * INT64_C(1000);
482             break;
483
484         /* */
485         case ACCESS_SET_PAUSE_STATE:
486             /* Nothing to do */
487             break;
488
489         case ACCESS_GET_TITLE_INFO:
490         case ACCESS_SET_TITLE:
491         case ACCESS_SET_SEEKPOINT:
492         case ACCESS_SET_PRIVATE_ID_STATE:
493         case ACCESS_GET_META:
494         case ACCESS_GET_CONTENT_TYPE: /* DOWN: comment this line */
495             return VLC_EGENERIC;
496
497         default:
498             msg_Warn( p_access, "unimplemented query in control" );
499             return VLC_EGENERIC;
500     }
501
502     return VLC_SUCCESS;
503 }
504
505 /*****************************************************************************
506  * ThreadControl: manage control messages and pipe media to Read
507  *****************************************************************************/
508 static void* ThreadControl( vlc_object_t *p_this )
509 {
510     rtmp_control_thread_t *p_thread = (rtmp_control_thread_t *) p_this;
511     rtmp_packet_t *rtmp_packet;
512     int canc = vlc_savecancel ();
513
514     rtmp_init_handler( p_thread->rtmp_handler );
515
516     while( vlc_object_alive (p_thread) )
517     {
518         rtmp_packet = rtmp_read_net_packet( p_thread );
519         if( rtmp_packet != NULL )
520         {
521             if( rtmp_packet->content_type < 0x01 /* RTMP_CONTENT_TYPE_CHUNK_SIZE */
522                 || rtmp_packet->content_type > 0x14 ) /* RTMP_CONTENT_TYPE_INVOKE */
523             {
524                 free( rtmp_packet->body->body );
525                 free( rtmp_packet->body );
526                 free( rtmp_packet );
527
528                 msg_Warn( p_thread, "unknown content type received" );
529             }
530             else
531                 p_thread->rtmp_handler[rtmp_packet->content_type]( p_thread, rtmp_packet );
532         }
533         else
534         {
535             /* Sometimes server close connection too soon */
536             if( p_thread->result_connect )
537             {
538                 vlc_mutex_lock( &p_thread->lock );
539                 vlc_cond_signal( &p_thread->wait );
540                 vlc_mutex_unlock( &p_thread->lock );
541             }
542
543             p_thread->b_die = 1;
544             ((access_t *) p_thread->p_base_object)->info.b_eof = true;
545
546             block_FifoWake( p_thread->p_fifo_input );
547         }
548     }
549     vlc_restorecancel (canc);
550     return NULL;
551 }