1 /*****************************************************************************
2 * hds.c: Http Dynamic Streaming (HDS) stream filter
3 *****************************************************************************
5 * Author: Jonathan Thambidurai <jonathan _AT_ fastly _DOT_ com>
6 * Heavily inspired by SMooth module of Frédéric Yhuel <fyhuel _AT_ viotech _DOT_ net>
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library 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 GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 *****************************************************************************/
27 #include <limits.h> /* INT_MAX */
29 #include <vlc_common.h>
30 #include <vlc_plugin.h>
31 #include <vlc_stream.h>
32 #include <vlc_strings.h> /* b64_decode */
34 #include <vlc_charset.h> /* FromCharset */
35 #include <vlc_es.h> /* UNKNOWN_ES */
37 typedef struct chunk_s
39 int64_t duration; /* chunk duration in afrt timescale units */
43 uint32_t frun_entry; /* Used to speed things up in vod situations */
47 uint32_t mdat_pos; /* position in the mdat */
58 typedef struct segment_run_s
60 uint32_t first_segment;
61 uint32_t fragments_per_segment;
64 typedef struct fragment_run_s
66 uint32_t fragment_number_start;
67 uint32_t fragment_duration;
68 uint64_t fragment_timestamp;
72 typedef struct hds_stream_s
74 /* linked-list of chunks */
76 chunk_t *chunks_livereadpos;
77 chunk_t *chunks_downloadpos;
79 char* quality_segment_modifier;
81 /* we can make this configurable */
82 uint64_t download_leadtime;
84 /* in timescale units */
85 uint32_t total_duration;
87 uint32_t afrt_timescale;
89 /* these two values come from the abst */
91 uint64_t live_current_time;
93 vlc_mutex_t abst_lock;
98 /* can be left as null */
101 /* this comes from the manifest media section */
104 /* this comes from the bootstrap info */
107 #define MAX_HDS_SERVERS 10
108 char* server_entries[MAX_HDS_SERVERS];
109 uint8_t server_entry_count;
111 #define MAX_HDS_SEGMENT_RUNS 256
112 segment_run_t segment_runs[MAX_HDS_SEGMENT_RUNS];
113 uint8_t segment_run_count;
115 #define MAX_HDS_FRAGMENT_RUNS 10000
116 fragment_run_t fragment_runs[MAX_HDS_FRAGMENT_RUNS];
117 uint32_t fragment_run_count;
120 /* this is effectively just a sanity check mechanism */
121 #define MAX_REQUEST_SIZE (50*1024*1024)
125 char *base_url; /* URL common part for chunks */
126 vlc_thread_t live_thread;
127 vlc_thread_t dl_thread;
129 /* we pend on peek until some number of segments arrives; otherwise
130 * the downstream system dies in case of playback */
131 uint64_t chunk_count;
133 vlc_array_t *hds_streams; /* available streams */
135 uint32_t flv_header_bytes_sent;
136 uint64_t duration_seconds;
142 typedef struct _bootstrap_info {
150 typedef struct _media_info {
156 /*****************************************************************************
158 *****************************************************************************/
159 static int Open( vlc_object_t * );
160 static void Close( vlc_object_t * );
163 set_category( CAT_INPUT )
164 set_subcategory( SUBCAT_INPUT_STREAM_FILTER )
165 set_description( N_("HTTP Dynamic Streaming") )
166 set_shortname( "Dynamic Streaming")
167 add_shortcut( "hds" )
168 set_capability( "stream_filter", 30 )
169 set_callbacks( Open, Close )
172 static int Read( stream_t *, void *, unsigned );
173 static int Peek( stream_t *, const uint8_t **, unsigned );
174 static int Control( stream_t *, int , va_list );
176 static inline bool isFQUrl( char* url )
178 return ( NULL != vlc_strcasestr( url, "https://") ||
179 NULL != vlc_strcasestr( url, "http://" ) );
182 static bool isHDS( stream_t *s )
185 int i_size = stream_Peek( s->p_source, (const uint8_t**) &peek, 200 );
191 if( !memcmp( peek, "\xFF\xFE", 2 ) )
193 str = FromCharset( "UTF-16LE", peek, 512 );
195 else if( !memcmp( peek, "\xFE\xFF", 2 ) )
197 str = FromCharset( "UTF-16BE", peek, 512 );
205 bool ret = strstr( str, "<manifest" ) != NULL;
209 static uint8_t* parse_asrt( vlc_object_t* p_this,
214 uint8_t* data_p = data;
216 uint32_t asrt_len = 0;
217 asrt_len = U32_AT( data_p );
218 if( asrt_len > data_end - data ||
219 data_end - data < 14 )
221 msg_Err( p_this, "Not enough asrt data (%"PRIu32", %lu)", asrt_len, data_end - data );
225 data_p += sizeof(asrt_len);
227 if( 0 != memcmp( "asrt", data_p, 4 ) )
229 msg_Err( p_this, "Cant find asrt in bootstrap" );
234 /* ignore flags and versions (we don't handle multiple updates) */
237 uint8_t quality_entry_count = *data_p;
238 bool quality_found = false;
241 if( ! s->quality_segment_modifier )
243 quality_found = true;
246 while( quality_entry_count-- > 0 )
248 char* str_start = (char*) data_p;
249 data_p = memchr( data_p, '\0', data_end - data_p );
252 msg_Err( p_this, "Couldn't find quality entry string in asrt" );
257 if( ! quality_found )
259 if( ! strncmp( str_start, s->quality_segment_modifier,
260 strlen(s->quality_segment_modifier) ) )
262 quality_found = true;
266 if( data_p >= data_end )
268 msg_Err( p_this, "Premature end of asrt in quality entries" );
273 if( data_end - data_p < 4 )
275 msg_Err( p_this, "Premature end of asrt after quality entries" );
279 uint32_t segment_run_entry_count = U32_AT( data_p );
280 data_p += sizeof(segment_run_entry_count);
282 if( data_end - data_p < 8 * segment_run_entry_count )
284 msg_Err( p_this, "Not enough data in asrt for segment run entries" );
288 if( segment_run_entry_count >= MAX_HDS_SEGMENT_RUNS )
290 msg_Err( p_this, "Too many segment runs" );
294 while( segment_run_entry_count-- > 0 )
298 s->segment_runs[s->segment_run_count].first_segment = U32_AT(data_p);
304 s->segment_runs[s->segment_run_count].fragments_per_segment = U32_AT(data_p);
308 s->segment_run_count++;
314 static uint8_t* parse_afrt( vlc_object_t* p_this,
319 uint8_t* data_p = data;
321 uint32_t afrt_len = U32_AT( data_p );
322 if( afrt_len > data_end - data ||
323 data_end - data < 9 )
325 msg_Err( p_this, "Not enough afrt data %u, %ld", afrt_len, data_end - data );
328 data_p += sizeof(afrt_len);
330 if( 0 != memcmp( data_p, "afrt", 4 ) )
332 msg_Err( p_this, "Cant find afrt in bootstrap" );
337 /* ignore flags and versions (we don't handle multiple updates) */
340 if( data_end - data_p < 9 )
342 msg_Err( p_this, "afrt is too short" );
346 s->afrt_timescale = U32_AT( data_p );
349 bool quality_found = false;
350 if( ! s->quality_segment_modifier )
352 quality_found = true;
355 uint32_t quality_entry_count = *data_p;
357 while( quality_entry_count-- > 0 )
359 char* str_start = (char*)data_p;
360 data_p = memchr( data_p, '\0', data_end - data_p );
363 msg_Err( p_this, "Couldn't find quality entry string in afrt" );
368 if( ! quality_found )
370 if( ! strncmp( str_start, s->quality_segment_modifier,
371 strlen(s->quality_segment_modifier) ) )
373 quality_found = true;
378 if( data_end - data_p < 5 )
380 msg_Err( p_this, "No more space in afrt after quality entries" );
384 uint32_t fragment_run_entry_count = U32_AT( data_p );
385 data_p += sizeof(uint32_t);
387 while(fragment_run_entry_count-- > 0)
389 if( data_end - data_p < 16 )
391 msg_Err( p_this, "Not enough data in afrt" );
395 if( s->fragment_run_count >= MAX_HDS_FRAGMENT_RUNS )
397 msg_Err( p_this, "Too many fragment runs, exiting" );
401 s->fragment_runs[s->fragment_run_count].fragment_number_start = U32_AT(data_p);
404 s->fragment_runs[s->fragment_run_count].fragment_timestamp = U64_AT( data_p );
407 s->fragment_runs[s->fragment_run_count].fragment_duration = U32_AT( data_p );
410 s->fragment_runs[s->fragment_run_count].discont = 0;
411 if( s->fragment_runs[s->fragment_run_count].fragment_duration == 0 )
413 /* discontinuity flag */
414 s->fragment_runs[s->fragment_run_count].discont = *(data_p++);
417 s->fragment_run_count++;
423 static inline chunk_t* chunk_new()
425 chunk_t* chunk = calloc(1, sizeof(chunk_t));
429 static void chunk_free( chunk_t * chunk )
431 FREENULL( chunk->data );
435 static void parse_BootstrapData( vlc_object_t* p_this,
440 uint8_t* data_p = data;
442 uint32_t abst_len = U32_AT( data_p );
443 if( abst_len > data_end - data
444 || data_end - data < 29 /* min size of data */ )
446 msg_Warn( p_this, "Not enough bootstrap data" );
449 data_p += sizeof(abst_len);
451 if( 0 != memcmp( data_p, "abst", 4 ) )
453 msg_Warn( p_this, "Cant find abst in bootstrap" );
461 /* we ignore the version */
464 /* some flags we don't care about here because they are
470 s->timescale = U32_AT( data_p );
471 data_p += sizeof(s->timescale);
473 s->live_current_time = U64_AT( data_p );
474 data_p += sizeof(s->live_current_time);
476 /* smtpe time code offset */
479 s->movie_id = strndup( (char*)data_p, data_end - data_p );
480 data_p += ( strlen( s->movie_id ) + 1 );
482 if( data_end - data_p < 4 ) {
483 msg_Warn( p_this, "Not enough bootstrap after Movie Identifier" );
487 uint8_t server_entry_count = 0;
488 server_entry_count = (uint8_t) *data_p;
491 s->server_entry_count = 0;
492 while( server_entry_count-- > 0 )
494 if( s->server_entry_count < MAX_HDS_SERVERS )
496 s->server_entries[s->server_entry_count++] = strndup( (char*)data_p,
498 data_p += strlen( s->server_entries[s->server_entry_count-1] ) + 1;
502 msg_Warn( p_this, "Too many servers" );
503 data_p = memchr( data_p, '\0', data_end - data_p );
506 msg_Err( p_this, "Couldn't find server entry" );
512 if( data_p >= data_end )
514 msg_Warn( p_this, "Premature end of bootstrap info while reading servers" );
519 if( data_end - data_p < 3 ) {
520 msg_Warn( p_this, "Not enough bootstrap after Servers" );
524 s->quality_segment_modifier = NULL;
526 uint8_t quality_entry_count = *data_p;
529 if( quality_entry_count > 1 )
531 msg_Err( p_this, "I don't know what to do with multiple quality levels in the bootstrap - shouldn't this be handled at the manifest level?" );
535 s->quality_segment_modifier = NULL;
536 while( quality_entry_count-- > 0 )
538 if( s->quality_segment_modifier )
540 s->quality_segment_modifier = strndup( (char*)data_p, data_end - data_p );
542 data_p += strnlen( (char*)data_p, data_end - data_p ) + 1;
545 if( data_end - data_p < 2 ) {
546 msg_Warn( p_this, "Not enough bootstrap after quality entries" );
550 /* ignoring "DrmData" */
551 data_p = memchr( data_p, '\0', data_end - data_p );
554 msg_Err( p_this, "Couldn't find DRM Data" );
559 if( data_end - data_p < 2 ) {
560 msg_Warn( p_this, "Not enough bootstrap after drm data" );
564 /* ignoring "metadata" */
565 data_p = memchr( data_p, '\0', data_end - data_p );
568 msg_Err( p_this, "Couldn't find metadata");
573 if( data_end - data_p < 2 ) {
574 msg_Warn( p_this, "Not enough bootstrap after drm data" );
578 uint8_t asrt_count = *data_p;
581 s->segment_run_count = 0;
582 while( asrt_count-- > 0 &&
584 (data_p = parse_asrt( p_this, s, data_p, data_end )) );
586 uint8_t afrt_count = *data_p;
589 s->fragment_run_count = 0;
590 while( afrt_count-- > 0 &&
592 (data_p = parse_afrt( p_this, s, data_p, data_end )) );
595 /* this only works with ANSI characters - this is ok
596 for the bootstrapinfo field which this function is
597 exclusively used for since it is merely a base64 encoding
599 static bool is_whitespace( char c )
609 /* see above note for is_whitespace */
610 static void whitespace_substr( char** start,
613 while( is_whitespace( **start ) && *start != *end ) {
620 while( is_whitespace(*(*end - 1) ) ) {
625 /* returns length (could be zero, indicating all of remaining data) */
626 /* ptr is to start of data, right after 'mdat' string */
627 static uint32_t find_chunk_mdat( vlc_object_t* p_this,
628 uint8_t* chunkdata, uint8_t* chunkdata_end,
631 uint8_t* boxname = NULL;
632 uint8_t* boxdata = NULL;
633 uint64_t boxsize = 0;
636 if( chunkdata_end < chunkdata ||
637 chunkdata_end - chunkdata < 8 )
639 msg_Err( p_this, "Couldn't find mdat in box 1!" );
644 boxsize = (uint64_t)U32_AT( chunkdata );
652 if( chunkdata_end - chunkdata >= 12 )
654 boxsize = U64_AT(chunkdata);
659 msg_Err( p_this, "Couldn't find mdat in box 2!");
664 chunkdata += (boxsize - 16);
669 chunkdata += (boxsize - 8);
671 } while ( 0 != memcmp( boxname, "mdat", 4 ) );
675 return chunkdata_end - ((uint8_t*)boxdata);
678 /* returns data ptr if valid (updating the chunk itself
679 tells the reader that the chunk is safe to read, which is not yet correct)*/
680 static uint8_t* download_chunk( stream_t *s,
682 hds_stream_t* stream, chunk_t* chunk )
684 const char* quality = "";
685 char* server_base = sys->base_url;
686 if( stream->server_entry_count > 0 &&
687 strlen(stream->server_entries[0]) > 0 )
689 server_base = stream->server_entries[0];
692 if( stream->quality_segment_modifier )
694 quality = stream->quality_segment_modifier;
697 const char* movie_id = "";
698 if( stream->url && strlen(stream->url) > 0 )
700 if( isFQUrl( stream->url ) )
702 server_base = stream->url;
706 movie_id = stream->url;
711 if( 0 > asprintf( &fragment_url, "%s/%s%sSeg%u-Frag%u",
716 chunk->frag_num ) ) {
717 msg_Err(s, "Failed to allocate memory for fragment url" );
721 msg_Info(s, "Downloading fragment %s", fragment_url );
723 stream_t* download_stream = stream_UrlNew( s, fragment_url );
724 if( ! download_stream )
726 msg_Err(s, "Failed to download fragment %s", fragment_url );
727 free( fragment_url );
728 chunk->failed = true;
731 free( fragment_url );
733 int64_t size = stream_Size( download_stream );
734 chunk->data_len = (uint32_t) size;
736 if( size > MAX_REQUEST_SIZE )
738 msg_Err(s, "Strangely-large chunk of %"PRIi64" Bytes", size );
742 uint8_t* data = malloc( size );
745 msg_Err(s, "Couldn't allocate chunk" );
749 int read = stream_Read( download_stream, data,
751 chunk->data_len = read;
755 msg_Err( s, "Requested %"PRIi64" bytes, "\
756 "but only got %d", size, read );
757 data = realloc( chunk->data, read );
758 chunk->failed = true;
763 chunk->failed = false;
766 stream_Delete( download_stream );
770 static void* download_thread( void* p )
772 vlc_object_t* p_this = (vlc_object_t*)p;
773 stream_t* s = (stream_t*) p_this;
774 stream_sys_t* sys = s->p_sys;
776 if ( vlc_array_count( sys->hds_streams ) == 0 )
779 // TODO: Change here for selectable stream
780 hds_stream_t* hds_stream = sys->hds_streams->pp_elems[0];
782 int canc = vlc_savecancel();
784 vlc_mutex_lock( & hds_stream->dl_lock );
786 while( ! sys->closed )
788 if( ! hds_stream->chunks_downloadpos )
790 chunk_t* chunk = hds_stream->chunks_head;
791 while(chunk && chunk->data )
796 if( chunk && ! chunk->data )
797 hds_stream->chunks_downloadpos = chunk;
800 while( hds_stream->chunks_downloadpos )
802 chunk_t *chunk = hds_stream->chunks_downloadpos;
804 uint8_t *data = download_chunk( (stream_t*)p_this,
809 if( ! chunk->failed )
812 find_chunk_mdat( p_this,
814 data + chunk->data_len,
815 & chunk->mdat_data );
816 if( chunk->mdat_len == 0 ) {
817 chunk->mdat_len = chunk->data_len - (chunk->mdat_data - data);
819 hds_stream->chunks_downloadpos = chunk->next;
826 vlc_cond_wait( & hds_stream->dl_cond,
827 & hds_stream->dl_lock );
830 vlc_mutex_unlock( & hds_stream->dl_lock );
832 vlc_restorecancel( canc );
836 static chunk_t* generate_new_chunk(
837 vlc_object_t* p_this,
839 hds_stream_t* hds_stream )
841 stream_t* s = (stream_t*) p_this;
842 stream_sys_t *sys = s->p_sys;
843 chunk_t *chunk = chunk_new();
844 unsigned int frun_entry = 0;
847 msg_Err( p_this, "Couldn't allocate new chunk!" );
853 chunk->timestamp = last_chunk->timestamp + last_chunk->duration;
854 chunk->frag_num = last_chunk->frag_num + 1;
858 frun_entry = last_chunk->frun_entry;
863 fragment_run_t* first_frun = hds_stream->fragment_runs;
866 chunk->timestamp = (hds_stream->live_current_time * ((uint64_t)hds_stream->afrt_timescale)) / ((uint64_t)hds_stream->timescale);
870 chunk->timestamp = first_frun->fragment_timestamp;
871 chunk->frag_num = first_frun->fragment_number_start;
875 for( ; frun_entry < hds_stream->fragment_run_count;
878 /* check for discontinuity first */
879 if( hds_stream->fragment_runs[frun_entry].fragment_duration == 0 )
881 if( frun_entry == hds_stream->fragment_run_count - 1 )
883 msg_Err( p_this, "Discontinuity but can't find next timestamp!");
887 chunk->frag_num = hds_stream->fragment_runs[frun_entry+1].fragment_number_start;
888 chunk->duration = hds_stream->fragment_runs[frun_entry+1].fragment_duration;
889 chunk->timestamp = hds_stream->fragment_runs[frun_entry+1].fragment_timestamp;
895 if( chunk->frag_num == 0 )
897 if( frun_entry == hds_stream->fragment_run_count - 1 ||
898 ( chunk->timestamp >= hds_stream->fragment_runs[frun_entry].fragment_timestamp &&
899 chunk->timestamp < hds_stream->fragment_runs[frun_entry+1].fragment_timestamp )
902 fragment_run_t* frun = hds_stream->fragment_runs + frun_entry;
903 chunk->frag_num = frun->fragment_number_start + ( (chunk->timestamp - frun->fragment_timestamp) /
904 frun->fragment_duration );
905 chunk->duration = frun->fragment_duration;
910 if( hds_stream->fragment_runs[frun_entry].fragment_number_start <=
912 (frun_entry == hds_stream->fragment_run_count - 1 ||
913 hds_stream->fragment_runs[frun_entry+1].fragment_number_start > chunk->frag_num ) )
915 chunk->duration = hds_stream->fragment_runs[frun_entry].fragment_duration;
916 chunk->timestamp = hds_stream->fragment_runs[frun_entry].fragment_timestamp +
917 chunk->duration * (chunk->frag_num - hds_stream->fragment_runs[frun_entry].fragment_number_start);
922 if( frun_entry == hds_stream->fragment_run_count )
924 msg_Err( p_this, "Couldn'd find the fragment run!" );
930 unsigned int segment = 0;
931 uint64_t fragments_accum = chunk->frag_num;
932 for( srun_entry = 0; srun_entry < hds_stream->segment_run_count;
935 segment = hds_stream->segment_runs[srun_entry].first_segment +
936 (chunk->frag_num - fragments_accum ) / hds_stream->segment_runs[srun_entry].fragments_per_segment;
938 if( srun_entry + 1 == hds_stream->segment_run_count ||
939 hds_stream->segment_runs[srun_entry+1].first_segment > segment )
945 (hds_stream->segment_runs[srun_entry+1].first_segment -
946 hds_stream->segment_runs[srun_entry].first_segment) *
947 hds_stream->segment_runs[srun_entry].fragments_per_segment );
950 chunk->seg_num = segment;
951 chunk->frun_entry = frun_entry;
955 if( (chunk->timestamp + chunk->duration) / hds_stream->afrt_timescale >= sys->duration_seconds )
964 static void maintain_live_chunks(
965 vlc_object_t* p_this,
966 hds_stream_t* hds_stream
969 if( ! hds_stream->chunks_head )
971 /* just start with the earliest in the abst
972 * maybe it would be better to use the currentMediaTime?
973 * but then we are right on the edge of buffering, esp for
975 hds_stream->chunks_head = generate_new_chunk(
976 p_this, 0, hds_stream );
977 hds_stream->chunks_livereadpos = hds_stream->chunks_head;
980 chunk_t* chunk = hds_stream->chunks_head;
982 while( chunk && ( chunk->timestamp * ((uint64_t)hds_stream->timescale) )
983 / ((uint64_t)hds_stream->afrt_timescale)
984 <= hds_stream->live_current_time )
992 chunk->next = generate_new_chunk( p_this, chunk, hds_stream );
999 vlc_cond_signal( & hds_stream->dl_cond );
1001 chunk = hds_stream->chunks_head;
1002 while( chunk && chunk->data && chunk->mdat_pos >= chunk->mdat_len && chunk->next )
1004 chunk_t* next_chunk = chunk->next;
1005 chunk_free( chunk );
1009 if( ! hds_stream->chunks_livereadpos )
1010 hds_stream->chunks_livereadpos = hds_stream->chunks_head;
1012 hds_stream->chunks_head = chunk;
1016 static void* live_thread( void* p )
1018 vlc_object_t* p_this = (vlc_object_t*)p;
1019 stream_t* s = (stream_t*) p_this;
1020 stream_sys_t* sys = s->p_sys;
1022 if ( vlc_array_count( sys->hds_streams ) == 0 )
1025 // TODO: Change here for selectable stream
1026 hds_stream_t* hds_stream = sys->hds_streams->pp_elems[0];
1028 int canc = vlc_savecancel();
1032 if( hds_stream->abst_url &&
1033 ( isFQUrl( hds_stream->abst_url ) ) )
1035 if( !( abst_url = strdup( hds_stream->abst_url ) ) )
1040 char* server_base = sys->base_url;
1043 if( 0 > asprintf( &abst_url, "%s/%s",
1045 hds_stream->abst_url ) )
1051 mtime_t last_dl_start_time;
1053 while( ! sys->closed )
1055 last_dl_start_time = mdate();
1056 stream_t* download_stream = stream_UrlNew( p_this, abst_url );
1057 if( ! download_stream )
1059 msg_Err( p_this, "Failed to download abst %s", abst_url );
1063 int64_t size = stream_Size( download_stream );
1064 uint8_t* data = malloc( size );
1065 int read = stream_Read( download_stream, data,
1069 msg_Err( p_this, "Requested %"PRIi64" bytes, " \
1070 "but only got %d", size, read );
1075 vlc_mutex_lock( & hds_stream->abst_lock );
1076 parse_BootstrapData( p_this, hds_stream,
1077 data, data + read );
1078 vlc_mutex_unlock( & hds_stream->abst_lock );
1079 maintain_live_chunks( p_this, hds_stream );
1084 stream_Delete( download_stream );
1087 mwait( last_dl_start_time + ( ((int64_t)hds_stream->fragment_runs[hds_stream->fragment_run_count-1].fragment_duration) * 1000000LL) / ((int64_t)hds_stream->afrt_timescale) );
1094 vlc_restorecancel( canc );
1098 static int parse_Manifest( stream_t *s )
1100 xml_t *vlc_xml = NULL;
1101 xml_reader_t *vlc_reader = NULL;
1102 int type = UNKNOWN_ES;
1103 stream_t *st = s->p_source;
1105 msg_Dbg( s, "Manifest parsing\n" );
1107 vlc_xml = xml_Create( st );
1110 msg_Err( s, "Failed to open XML parser" );
1111 return VLC_EGENERIC;
1114 vlc_reader = xml_ReaderCreate( vlc_xml, st );
1117 msg_Err( s, "Failed to open source for parsing" );
1118 xml_Delete( vlc_xml );
1119 return VLC_EGENERIC;
1124 stream_sys_t *sys = s->p_sys;
1126 sys->duration_seconds = 0;
1128 #define MAX_BOOTSTRAP_INFO 10
1129 bootstrap_info bootstraps[MAX_BOOTSTRAP_INFO];
1130 uint8_t bootstrap_idx = 0;
1131 memset( bootstraps, 0, sizeof(bootstrap_info) * MAX_BOOTSTRAP_INFO );
1133 #define MAX_MEDIA_ELEMENTS 10
1134 media_info medias[MAX_MEDIA_ELEMENTS];
1135 uint8_t media_idx = 0;
1136 memset( medias, 0, sizeof(media_info) * MAX_MEDIA_ELEMENTS );
1138 #define MAX_XML_DEPTH 256
1139 char* element_stack[256];
1140 uint8_t current_element_idx = 0;
1141 char* current_element = NULL;
1142 memset( element_stack, 0, sizeof(char*) * MAX_XML_DEPTH );
1144 const char* attr_name;
1145 const char* attr_value;
1147 char* media_id = NULL;
1149 #define TIMESCALE 10000000
1150 while( (type = xml_ReaderNextNode( vlc_reader, (const char**) &node )) > 0 )
1154 case XML_READER_STARTELEM:
1155 if( current_element_idx == 0 && element_stack[current_element_idx] == 0 ) {
1156 if( !( element_stack[current_element_idx] = strdup( node ) ) )
1159 if ( !( element_stack[++current_element_idx] = strdup( node ) ) )
1164 case XML_READER_ENDELEM:
1165 if( ! strcmp( current_element, "bootstrapInfo") ) {
1166 if( bootstrap_idx + 1 == MAX_BOOTSTRAP_INFO ) {
1167 msg_Warn( (vlc_object_t*) s, "Too many bootstraps, ignoring" );
1173 free( current_element );
1174 element_stack[current_element_idx--] = 0;
1178 if( ! element_stack[current_element_idx] ) {
1182 current_element = element_stack[current_element_idx];
1184 if( type == XML_READER_STARTELEM && ! strcmp( current_element, "media") )
1186 if( media_idx == MAX_MEDIA_ELEMENTS )
1188 msg_Err( (vlc_object_t*) s, "Too many media elements, quitting" );
1189 return VLC_EGENERIC;
1192 while( ( attr_name = xml_ReaderNextAttr( vlc_reader, &attr_value )) )
1194 if( !strcmp(attr_name, "streamId" ) )
1196 if( !( medias[media_idx].stream_id = strdup( attr_value ) ) )
1199 if( !strcmp(attr_name, "url" ) )
1201 if( !( medias[media_idx].media_url = strdup( attr_value ) ) )
1204 if( !strcmp(attr_name, "bootstrapInfoId" ) )
1206 if( !( medias[media_idx].bootstrap_id = strdup( attr_value ) ) )
1214 if( type == XML_READER_STARTELEM && ! strcmp( current_element, "bootstrapInfo") )
1216 while( ( attr_name = xml_ReaderNextAttr( vlc_reader, &attr_value )) )
1218 if( !strcmp(attr_name, "url" ) )
1220 if( !( bootstraps[bootstrap_idx].url = strdup( attr_value ) ) )
1223 if( !strcmp(attr_name, "id" ) )
1225 if( !( bootstraps[bootstrap_idx].id = strdup( attr_value ) ) )
1228 if( !strcmp(attr_name, "profile" ) )
1230 if( !( bootstraps[bootstrap_idx].profile = strdup( attr_value ) ) )
1236 if( type == XML_READER_TEXT )
1238 if( ! strcmp( current_element, "bootstrapInfo" ) )
1241 char* end = start + strlen(start);
1242 whitespace_substr( &start, &end );
1245 bootstraps[bootstrap_idx].data_len =
1246 vlc_b64_decode_binary( (uint8_t**)&bootstraps[bootstrap_idx].data, start );
1247 if( ! bootstraps[bootstrap_idx].data )
1249 msg_Err( (vlc_object_t*) s, "Couldn't decode bootstrap info" );
1252 if( ! strcmp( current_element, "duration" ) )
1254 double shutup_gcc = atof( node );
1255 sys->duration_seconds = (uint64_t) shutup_gcc;
1257 if( ! strcmp( current_element, "id" ) )
1259 if( current_element &&
1260 ! strcmp( element_stack[current_element_idx-1], "manifest" ) )
1262 if( !( media_id = strdup( node ) ) )
1269 xml_ReaderDelete( vlc_reader );
1270 xml_Delete( vlc_xml );
1272 for( int i = 0; i <= media_idx; i++ )
1274 for( int j = 0; j < bootstrap_idx; j++ )
1276 if( ( ! medias[i].bootstrap_id && ! bootstraps[j].id ) ||
1277 (medias[i].bootstrap_id && bootstraps[j].id &&
1278 ! strcmp( medias[i].bootstrap_id, bootstraps[j].id ) ) )
1280 hds_stream_t* new_stream = malloc(sizeof(hds_stream_t));
1281 memset( new_stream, 0, sizeof(hds_stream_t));
1283 vlc_mutex_init( & new_stream->abst_lock );
1284 vlc_mutex_init( & new_stream->dl_lock );
1285 vlc_cond_init( & new_stream->dl_cond );
1287 if( sys->duration_seconds )
1296 if( medias[i].media_url )
1298 if( !(new_stream->url = strdup( medias[i].media_url ) ) )
1307 parse_BootstrapData( (vlc_object_t*)s,
1310 bootstraps[j].data + bootstraps[j].data_len );
1312 new_stream->download_leadtime = 15;
1314 new_stream->chunks_head = generate_new_chunk(
1315 (vlc_object_t*) s, 0, new_stream );
1316 chunk_t* chunk = new_stream->chunks_head;
1317 uint64_t total_duration = chunk->duration;
1318 while( chunk && total_duration/new_stream->afrt_timescale < new_stream->download_leadtime )
1320 chunk->next = generate_new_chunk(
1321 (vlc_object_t*) s, chunk, new_stream );
1322 chunk = chunk->next;
1324 total_duration += chunk->duration;
1329 if( !(new_stream->abst_url = strdup( bootstraps[j].url ) ) )
1336 vlc_array_append( sys->hds_streams, new_stream );
1338 msg_Info( (vlc_object_t*)s, "New track with quality_segment(%s), timescale(%u), movie_id(%s), segment_run_count(%d), fragment_run_count(%u)",
1339 new_stream->quality_segment_modifier?"":new_stream->quality_segment_modifier, new_stream->timescale,
1340 new_stream->movie_id, new_stream->segment_run_count, new_stream->fragment_run_count );
1346 for( int i = 0; i < MAX_MEDIA_ELEMENTS; i++ )
1348 FREENULL( medias[media_idx].stream_id );
1349 FREENULL( medias[media_idx].media_url );
1350 FREENULL( medias[media_idx].bootstrap_id );
1353 for( int i = 0; i < MAX_BOOTSTRAP_INFO; i++ )
1355 FREENULL( bootstraps[i].data );
1356 FREENULL( bootstraps[i].id );
1357 FREENULL( bootstraps[i].url );
1358 FREENULL( bootstraps[i].profile );
1361 FREENULL( media_id );
1367 static void hds_free( hds_stream_t *p_stream )
1369 FREENULL( p_stream->quality_segment_modifier );
1371 FREENULL( p_stream->abst_url );
1373 FREENULL( p_stream->url );
1374 FREENULL( p_stream->movie_id );
1375 for( int i = 0; i < p_stream->server_entry_count; i++ )
1377 FREENULL( p_stream->server_entries[i] );
1380 chunk_t* chunk = p_stream->chunks_head;
1383 chunk_t* next = chunk->next;
1384 chunk_free( chunk );
1391 static void SysCleanup( stream_sys_t *p_sys )
1393 if ( p_sys->hds_streams )
1395 for ( int i=0; i< p_sys->hds_streams->i_count ; i++ )
1396 hds_free( p_sys->hds_streams->pp_elems[i] );
1397 vlc_array_destroy( p_sys->hds_streams );
1399 free( p_sys->base_url );
1402 static int Open( vlc_object_t *p_this )
1404 stream_t *s = (stream_t*)p_this;
1405 stream_sys_t *p_sys;
1408 return VLC_EGENERIC;
1410 msg_Info( p_this, "HTTP Dynamic Streaming (%s)", s->psz_path );
1412 s->p_sys = p_sys = calloc( 1, sizeof(*p_sys ) );
1413 if( unlikely( p_sys == NULL ) )
1416 char *uri_without_query = NULL;
1417 size_t pathlen = strcspn( s->psz_path, "?" );
1418 if( unlikely( ( pathlen > INT_MAX ) ||
1419 ( asprintf( &uri_without_query, "%s://%.*s", s->psz_access,
1420 (int)pathlen, s->psz_path ) < 0 ) ) )
1426 /* remove the last part of the url */
1427 char *pos = strrchr( uri_without_query, '/');
1429 p_sys->base_url = uri_without_query;
1431 p_sys->flv_header_bytes_sent = 0;
1433 p_sys->hds_streams = vlc_array_new();
1435 if( parse_Manifest( s ) != VLC_SUCCESS )
1442 s->pf_control = Control;
1444 if( vlc_clone( &p_sys->dl_thread, download_thread, s, VLC_THREAD_PRIORITY_INPUT ) )
1450 msg_Info( p_this, "Live stream detected" );
1452 if( vlc_clone( &p_sys->live_thread, live_thread, s, VLC_THREAD_PRIORITY_INPUT ) )
1461 SysCleanup( p_sys );
1463 return VLC_EGENERIC;
1466 static void Close( vlc_object_t *p_this )
1468 stream_t *s = (stream_t*)p_this;
1469 stream_sys_t *p_sys = s->p_sys;
1471 // TODO: Change here for selectable stream
1472 hds_stream_t *stream = vlc_array_count(p_sys->hds_streams) ?
1473 s->p_sys->hds_streams->pp_elems[0] : NULL;
1475 p_sys->closed = true;
1477 vlc_cond_signal( & stream->dl_cond );
1479 vlc_join( p_sys->dl_thread, NULL );
1483 vlc_mutex_destroy( &stream->dl_lock );
1484 vlc_cond_destroy( &stream->dl_cond );
1485 vlc_mutex_destroy( &stream->abst_lock );
1490 vlc_join( p_sys->live_thread, NULL );
1493 SysCleanup( p_sys );
1497 static unsigned char flv_header[] = {
1502 0x5, //indicates audio and video
1506 0x9, // length of header
1510 0x0, // initial "trailer"
1513 static int send_flv_header( stream_sys_t* p_sys, void* buffer, unsigned i_read,
1516 uint32_t to_be_read = i_read;
1517 if( to_be_read > 13 - p_sys->flv_header_bytes_sent ) {
1518 to_be_read = 13 - p_sys->flv_header_bytes_sent;
1521 memcpy( buffer, flv_header + p_sys->flv_header_bytes_sent, to_be_read );
1525 p_sys->flv_header_bytes_sent += to_be_read;
1530 static unsigned read_chunk_data(
1531 vlc_object_t* p_this,
1532 uint8_t* buffer, unsigned read_len,
1533 hds_stream_t* stream,
1537 stream_t* s = (stream_t*) p_this;
1538 stream_sys_t* sys = s->p_sys;
1539 chunk_t* chunk = stream->chunks_head;
1540 uint8_t* buffer_start = buffer;
1543 if( chunk && chunk->eof && chunk->mdat_pos >= chunk->mdat_len ) {
1548 while( chunk && chunk->data && read_len > 0 && ! (chunk->eof && chunk->mdat_pos >= chunk->mdat_len ) )
1550 /* in the live case, it is necessary to store the next
1551 * pointer here, since as soon as we increment the mdat_pos, that
1552 * chunk may be deleted */
1553 chunk_t* next = chunk->next;
1555 if( chunk->mdat_pos < chunk->mdat_len )
1557 unsigned cp_len = chunk->mdat_len - chunk->mdat_pos;
1558 if( cp_len > read_len )
1560 memcpy( buffer, chunk->mdat_data + chunk->mdat_pos,
1565 chunk->mdat_pos += cp_len;
1568 if( ! sys->live && (chunk->mdat_pos >= chunk->mdat_len || chunk->failed) )
1575 /* make sure there is at least one chunk in the queue */
1576 if( ! chunk->next && ! chunk->eof )
1578 chunk->next = generate_new_chunk( p_this, chunk, stream );
1584 chunk_free( chunk );
1586 stream->chunks_head = chunk;
1589 else if( sys->live && (chunk->mdat_pos >= chunk->mdat_len || chunk->failed) )
1597 stream->chunks_livereadpos = chunk;
1600 /* new chunk generation is handled by a different thread in live case */
1603 chunk = stream->chunks_head;
1606 uint64_t total_duration = chunk->duration;
1607 while( chunk && total_duration/stream->afrt_timescale < stream->download_leadtime && ! chunk->eof )
1609 if( ! chunk->next && ! chunk->eof )
1611 chunk->next = generate_new_chunk( p_this, chunk, stream );
1617 chunk = chunk->next;
1620 total_duration += chunk->duration;
1627 vlc_cond_signal( & stream->dl_cond );
1630 return ( ((uint8_t*)buffer) - ((uint8_t*)buffer_start));
1633 static int Read( stream_t *s, void *buffer, unsigned i_read )
1635 stream_sys_t *p_sys = s->p_sys;
1637 if ( vlc_array_count( p_sys->hds_streams ) == 0 )
1640 // TODO: change here for selectable stream
1641 hds_stream_t *stream = s->p_sys->hds_streams->pp_elems[0];
1644 uint8_t *buffer_uint8 = (uint8_t*) buffer;
1646 unsigned hdr_bytes = send_flv_header( p_sys, buffer, i_read, false );
1647 length += hdr_bytes;
1648 i_read -= hdr_bytes;
1649 buffer_uint8 += hdr_bytes;
1652 while( i_read > 0 && ! eof )
1654 int tmp_length = read_chunk_data( (vlc_object_t*)s, buffer_uint8, i_read, stream, &eof );
1655 buffer_uint8 += tmp_length;
1656 i_read -= tmp_length;
1657 length += tmp_length;
1663 static int Peek( stream_t *s, const uint8_t **pp_peek, unsigned i_peek )
1665 stream_sys_t *p_sys = s->p_sys;
1667 if ( vlc_array_count( p_sys->hds_streams ) == 0 )
1670 // TODO: change here for selectable stream
1671 hds_stream_t *stream = p_sys->hds_streams->pp_elems[0];
1673 if( p_sys->flv_header_bytes_sent < 13 )
1675 *pp_peek = flv_header + p_sys->flv_header_bytes_sent;
1676 return 13 - p_sys->flv_header_bytes_sent;
1679 if( stream->chunks_head && ! stream->chunks_head->failed && stream->chunks_head->data )
1681 // TODO: change here for selectable stream
1682 chunk_t* chunk = stream->chunks_head;
1683 *pp_peek = chunk->mdat_data + chunk->mdat_pos;
1684 if( chunk->mdat_len - chunk->mdat_pos < i_peek )
1686 return chunk->mdat_len - chunk->mdat_pos;
1698 static int Control( stream_t *s, int i_query, va_list args )
1702 case STREAM_CAN_SEEK:
1703 *(va_arg( args, bool * )) = false;
1705 case STREAM_CAN_FASTSEEK:
1706 case STREAM_CAN_PAUSE: /* TODO */
1707 *(va_arg( args, bool * )) = false;
1709 case STREAM_CAN_CONTROL_PACE:
1710 *(va_arg( args, bool * )) = true;
1712 case STREAM_GET_PTS_DELAY:
1713 *va_arg (args, int64_t *) = INT64_C(1000) *
1714 var_InheritInteger(s, "network-caching");
1717 return VLC_EGENERIC;