]> git.sesse.net Git - vlc/blob - modules/stream_filter/smooth/downloader.c
stream_filter: dash: fix iteration on different lists
[vlc] / modules / stream_filter / smooth / downloader.c
1 /*****************************************************************************
2  * downloader.c: download thread
3  *****************************************************************************
4  * Copyright (C) 1996-2012 VLC authors and VideoLAN
5  * $Id$
6  *
7  * Author: Frédéric Yhuel <fyhuel _AT_ viotech _DOT_ net>
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA
22  *****************************************************************************/
23
24 #include "smooth.h"
25
26 #include <assert.h>
27 #include <vlc_stream.h>
28 #include <vlc_charset.h>
29
30 #include "../../demux/mp4/libmp4.h"
31
32 static bool Replace( char **ppsz_string, off_t off, const char *psz_old,
33                      const char *psz_new )
34 {
35     const size_t i_oldlen = strlen( psz_old );
36     const size_t i_newlen = strlen( psz_new );
37     size_t i_stringlen = strlen( *ppsz_string );
38
39     if ( i_newlen > i_oldlen )
40     {
41         i_stringlen += i_newlen - i_oldlen;
42         char *psz_realloc = realloc( *ppsz_string, i_stringlen + 1 );
43         if( !psz_realloc )
44             return false;
45         *ppsz_string = psz_realloc;
46     }
47     memmove( *ppsz_string + off + i_newlen,
48              *ppsz_string + off + i_oldlen,
49              i_stringlen - off - i_newlen );
50     strncpy( *ppsz_string + off, psz_new, i_newlen );
51     (*ppsz_string)[i_stringlen] = 0;
52
53     return true;
54 }
55
56 static char *ConstructUrl( const char *psz_template, const char *psz_base_url,
57                            const quality_level_t *p_qlevel, const uint64_t i_start_time )
58 {
59     char *psz_path = strdup( psz_template );
60     if ( !psz_path )
61         return NULL;
62
63     char *psz_start;
64     while( true )
65     {
66         if ( (psz_start = strstr( psz_path, "{bitrate}" )) )
67         {
68             char *psz_bitrate = NULL;
69             if ( us_asprintf( &psz_bitrate, "%u", p_qlevel->Bitrate ) < 0 ||
70                  ! Replace( &psz_path, psz_start - psz_path, "{bitrate}", psz_bitrate ) )
71             {
72                 free( psz_bitrate );
73                 free( psz_path );
74                 return false;
75             }
76             free( psz_bitrate );
77         }
78         else if ( (psz_start = strstr( psz_path, "{start time}" )) ||
79                   (psz_start = strstr( psz_path, "{start_time}" )) )
80         {
81             psz_start[6] = ' ';
82             char *psz_starttime = NULL;
83             if ( us_asprintf( &psz_starttime, "%"PRIu64, i_start_time ) < 0 ||
84                  ! Replace( &psz_path, psz_start - psz_path, "{start time}", psz_starttime ) )
85             {
86                 free( psz_starttime );
87                 free( psz_path );
88                 return false;
89             }
90             free( psz_starttime );
91         }
92         else if ( (psz_start = strstr( psz_path, "{CustomAttributes}" )) )
93         {
94             char *psz_attributes = NULL;
95             FOREACH_ARRAY( const custom_attrs_t *p_attrs, p_qlevel->custom_attrs )
96             if ( asprintf( &psz_attributes,
97                            psz_attributes ? "%s,%s=%s" : "%s%s=%s",
98                            psz_attributes ? psz_attributes : "",
99                            p_attrs->psz_key, p_attrs->psz_value ) < 0 )
100                     break;
101             FOREACH_END()
102             if ( !psz_attributes ||
103                  ! Replace( &psz_path, psz_start - psz_path, "{CustomAttributes}", psz_attributes ) )
104             {
105                 free( psz_attributes );
106                 free( psz_path );
107                 return false;
108             }
109             free( psz_attributes );
110         }
111         else
112             break;
113     }
114
115     char *psz_url;
116     if( asprintf( &psz_url, "%s/%s", psz_base_url, psz_path ) < 0 )
117     {
118         free( psz_path );
119         return NULL;
120     }
121     free( psz_path );
122     return psz_url;
123 }
124
125 static chunk_t * chunk_Get( sms_stream_t *sms, const uint64_t start_time )
126 {
127     chunk_t *p_chunk = sms->p_chunks;
128     while( p_chunk )
129     {
130         if( p_chunk->start_time <= start_time &&
131                 p_chunk->start_time + p_chunk->duration > start_time )
132             break;
133         p_chunk = p_chunk->p_next;
134     }
135     return p_chunk;
136 }
137
138 static int sms_Download( stream_t *s, chunk_t *chunk, char *url )
139 {
140     stream_t *p_ts = stream_UrlNew( s, url );
141     free( url );
142     if( p_ts == NULL )
143         return VLC_EGENERIC;
144
145     int64_t size = stream_Size( p_ts );
146     if ( size < 0 )
147     {
148         stream_Delete( p_ts );
149         return VLC_EGENERIC;
150     }
151
152     uint8_t *p_data = malloc( size );
153     if( p_data == NULL )
154     {
155         stream_Delete( p_ts );
156         return VLC_ENOMEM;
157     }
158
159     int read = stream_Read( p_ts, p_data, size );
160     if( read < size && read > 0 )
161     {
162         msg_Warn( s, "sms_Download: I requested %"PRIi64" bytes, "\
163                 "but I got only %i", size, read );
164         p_data = realloc( p_data, read );
165     }
166
167     chunk->data = p_data;
168     chunk->size = (uint64_t) (read > 0 ? read : 0);
169
170     stream_Delete( p_ts );
171
172     return VLC_SUCCESS;
173 }
174
175 #ifdef DISABLE_BANDWIDTH_ADAPTATION
176 static quality_level_t *
177 BandwidthAdaptation( stream_t *s, sms_stream_t *sms,
178                      uint64_t obw, uint64_t i_duration,
179                      bool b_starved )
180 {
181     VLC_UNUSED(obw);
182     VLC_UNUSED(s);
183     VLC_UNUSED(i_duration);
184     VLC_UNUSED(b_starved);
185     return sms->current_qlvl;
186 }
187 #else
188
189 static quality_level_t *
190 BandwidthAdaptation( stream_t *s, sms_stream_t *sms,
191                      uint64_t obw, uint64_t i_duration,
192                      bool b_starved )
193 {
194     quality_level_t *ret = NULL;
195
196     assert( sms->current_qlvl );
197     if ( sms->qlevels.i_size < 2 )
198         return sms->qlevels.p_elems[0];
199
200     if ( b_starved )
201     {
202         //TODO: do something on starvation post first buffering
203         //   s->p_sys->i_probe_length *= 2;
204     }
205
206     /* PASS 1 */
207     quality_level_t *lowest = sms->qlevels.p_elems[0];
208     FOREACH_ARRAY( quality_level_t *qlevel, sms->qlevels );
209     if ( qlevel->Bitrate >= obw )
210     {
211         qlevel->i_validation_length -= i_duration;
212         qlevel->i_validation_length = __MAX(qlevel->i_validation_length, - s->p_sys->i_probe_length);
213     }
214     else
215     {
216         qlevel->i_validation_length += i_duration;
217         qlevel->i_validation_length = __MIN(qlevel->i_validation_length, s->p_sys->i_probe_length);
218     }
219     if ( qlevel->Bitrate < lowest->Bitrate )
220         lowest = qlevel;
221     FOREACH_END();
222
223     /* PASS 2 */
224     if ( sms->current_qlvl->i_validation_length == s->p_sys->i_probe_length )
225     {
226         /* might upgrade */
227         ret = sms->current_qlvl;
228     }
229     else if ( sms->current_qlvl->i_validation_length >= 0 )
230     {
231         /* do nothing */
232         ret = sms->current_qlvl;
233         msg_Dbg( s, "bw current:%uKB/s avg:%"PRIu64"KB/s qualified %"PRId64"%%",
234                 (ret->Bitrate) / (8 * 1024),
235                  obw / (8 * 1024),
236                  ( ret->i_validation_length*1000 / s->p_sys->i_probe_length ) /10 );
237         return ret;
238     }
239     else
240     {
241         /* downgrading */
242         ret = lowest;
243     }
244
245     /* might upgrade */
246     FOREACH_ARRAY( quality_level_t *qlevel, sms->qlevels );
247     if( qlevel->Bitrate <= obw &&
248             ret->Bitrate <= qlevel->Bitrate &&
249             qlevel->i_validation_length >= 0 &&
250             qlevel->i_validation_length >= ret->i_validation_length )
251     {
252         ret = qlevel;
253     }
254     FOREACH_END();
255
256     msg_Dbg( s, "bw reselected:%uKB/s avg:%"PRIu64"KB/s qualified %"PRId64"%%",
257             (ret->Bitrate) / (8 * 1024),
258              obw / (8 * 1024),
259              ( ret->i_validation_length*1000 / s->p_sys->i_probe_length ) /10 );
260
261     return ret;
262 }
263 #endif
264
265 static int parse_chunk( stream_t *s, chunk_t *ck, sms_stream_t *sms )
266 {
267     if( ck->size < 24 )
268         return VLC_EGENERIC;
269
270     stream_t *ck_s = stream_MemoryNew( s, ck->data, ck->size, true );
271     if ( !ck_s )
272         return VLC_EGENERIC;
273
274     MP4_Box_t root_box = { 0 };
275     root_box.i_type = ATOM_root;
276     root_box.i_size = ck->size;
277     if ( MP4_ReadBoxContainerChildren( ck_s, &root_box, 0 ) != 1 )
278     {
279         stream_Delete( ck_s );
280         return VLC_EGENERIC;
281     }
282 #ifndef NDEBUG
283     MP4_BoxDumpStructure( ck_s, &root_box );
284 #endif
285
286     /* Do track ID fixup */
287     const MP4_Box_t *tfhd_box = MP4_BoxGet( &root_box, "moof/traf/tfhd" );
288     if ( tfhd_box )
289         SetDWBE( &ck->data[tfhd_box->i_pos + 8 + 4], sms->id );
290
291     if ( s->p_sys->b_live )
292     {
293         const MP4_Box_t *uuid_box = MP4_BoxGet( &root_box, "moof/traf/uuid" );
294         while( uuid_box && uuid_box->i_type == ATOM_uuid )
295         {
296             if ( !CmpUUID( &uuid_box->i_uuid, &TfrfBoxUUID ) )
297                 break;
298             uuid_box = uuid_box->p_next;
299         }
300
301         if ( uuid_box )
302         {
303             const MP4_Box_data_tfrf_t *p_tfrfdata = uuid_box->data.p_tfrf;
304             for ( uint8_t i=0; i<p_tfrfdata->i_fragment_count; i++ )
305             {
306                 uint64_t dur = p_tfrfdata->p_tfrf_data_fields[i].i_fragment_duration;
307                 uint64_t stime = p_tfrfdata->p_tfrf_data_fields[i].i_fragment_abs_time;
308                 msg_Dbg( s, "\"tfrf\" fragment duration %"PRIu64", "
309                             "fragment abs time %"PRIu64, dur, stime );
310                 if( !chunk_Get( sms, stime + dur ) )
311                     chunk_AppendNew( sms, dur, stime );
312             }
313         }
314     }
315
316     MP4_Box_t *p_box = root_box.p_first;
317     while( p_box )
318     {
319         MP4_BoxFree( ck_s, p_box );
320         p_box = p_box->p_next;
321     }
322     stream_Delete( ck_s );
323
324     return VLC_SUCCESS;
325 }
326
327 #define STRA_SIZE 334
328 //#define SMOO_SIZE (STRA_SIZE * 3 + 24) /* 1026 */
329
330 /* SmooBox is a very simple MP4 box, used only to pass information
331  * to the demux layer. As this box is not aimed to travel accross networks,
332  * simplicity of the design is better than compactness */
333 static int build_smoo_box( stream_t *s, chunk_t *p_chunk )
334 {
335     stream_sys_t *p_sys = s->p_sys;
336     uint32_t FourCC;
337
338     /* smoo */
339     assert(p_sys->sms_selected.i_size);
340     size_t i_size = p_sys->sms_selected.i_size * STRA_SIZE + 24;
341     p_chunk->data = calloc( 1, i_size );
342     if ( !p_chunk->data )
343         return VLC_EGENERIC;
344     p_chunk->size = i_size;
345     uint8_t *smoo_box = p_chunk->data;
346
347     SetWBE( &smoo_box[2], i_size );
348     smoo_box[4] = 'u';
349     smoo_box[5] = 'u';
350     smoo_box[6] = 'i';
351     smoo_box[7] = 'd';
352
353     uint32_t *smoo_box32 = (uint32_t *)smoo_box;
354     /* UUID is e1da72ba-24d7-43c3-a6a5-1b5759a1a92c */
355     SetDWBE( &smoo_box32[2], 0xe1da72ba );
356     SetDWBE( &smoo_box32[3], 0x24d743c3 );
357     SetDWBE( &smoo_box32[4], 0xa6a51b57 );
358     SetDWBE( &smoo_box32[5], 0x59a1a92c );
359
360     int i = 0;
361     FOREACH_ARRAY( sms_stream_t *sms, p_sys->sms_selected );
362     uint8_t *stra_box = smoo_box + i++ * STRA_SIZE;
363     uint16_t *stra_box16 = (uint16_t *)stra_box;
364     uint32_t *stra_box32 = (uint32_t *)stra_box;
365     uint64_t *stra_box64 = (uint64_t *)stra_box;
366
367     SetWBE( &stra_box[26], STRA_SIZE );
368     stra_box[28] = 'u';
369     stra_box[29] = 'u';
370     stra_box[30] = 'i';
371     stra_box[31] = 'd';
372
373     /* UUID is b03ef770-33bd-4bac-96c7-bf25f97e2447 */
374     SetDWBE( &stra_box32[8], 0xb03ef770 );
375     SetDWBE( &stra_box32[9], 0x33bd4bac );
376     SetDWBE( &stra_box32[10], 0x96c7bf25 );
377     SetDWBE( &stra_box32[11], 0xf97e2447 );
378
379     stra_box[48] = sms->type;
380     stra_box[49] = 0; /* reserved */
381     SetWBE( &stra_box[50], sms->id );
382
383     SetDWBE( &stra_box32[13], sms->timescale );
384     SetQWBE( &stra_box64[7], p_sys->vod_duration );
385
386     const quality_level_t *qlvl = sms->current_qlvl;
387     if ( qlvl )
388     {
389         FourCC = qlvl->FourCC ? qlvl->FourCC : sms->default_FourCC;
390         SetDWBE( &stra_box32[16], FourCC );
391         SetDWBE( &stra_box32[17], qlvl->Bitrate );
392         SetDWBE( &stra_box32[18], qlvl->MaxWidth );
393         SetDWBE( &stra_box32[19], qlvl->MaxHeight );
394         SetDWBE( &stra_box32[20], qlvl->SamplingRate );
395         SetDWBE( &stra_box32[21], qlvl->Channels );
396         SetDWBE( &stra_box32[22], qlvl->BitsPerSample );
397         SetDWBE( &stra_box32[23], qlvl->AudioTag );
398         SetWBE( &stra_box16[48], qlvl->nBlockAlign );
399
400         if( !qlvl->CodecPrivateData )
401             continue;
402         stra_box[98] = stra_box[99] = stra_box[100] = 0; /* reserved */
403         stra_box[101] = strlen( qlvl->CodecPrivateData ) / 2;
404         if ( stra_box[101] > STRA_SIZE - 102 )
405             stra_box[101] = STRA_SIZE - 102;
406         uint8_t *binary_cpd = decode_string_hex_to_binary( qlvl->CodecPrivateData );
407         memcpy( stra_box + 102, binary_cpd, stra_box[101] );
408         free( binary_cpd );
409     }
410     FOREACH_END();
411
412     return VLC_SUCCESS;
413 }
414
415 static chunk_t *build_init_chunk( stream_t *s )
416 {
417     chunk_t *ret = calloc( 1, sizeof( chunk_t ) );
418     if( unlikely( ret == NULL ) )
419         goto build_init_chunk_error;
420
421     if( build_smoo_box( s, ret ) == VLC_SUCCESS )
422         return ret;
423
424 build_init_chunk_error:
425     free( ret );
426     msg_Err( s, "build_init_chunk failed" );
427     return NULL;
428 }
429
430 static int Download( stream_t *s, sms_stream_t *sms )
431 {
432     stream_sys_t *p_sys = s->p_sys;
433
434     assert( sms->p_nextdownload );
435     assert( sms->p_nextdownload->data == NULL );
436     assert( sms->current_qlvl );
437
438     chunk_t *chunk = sms->p_nextdownload;
439     if( !chunk )
440     {
441         msg_Warn( s, "Could not find a chunk for stream %s", sms->name );
442         return VLC_EGENERIC;
443     }
444     if( chunk->data != NULL )
445     {
446         /* Segment already downloaded */
447         msg_Warn( s, "Segment already downloaded" );
448         return VLC_SUCCESS;
449     }
450
451     chunk->type = sms->type;
452
453     char *url = ConstructUrl( sms->url_template, p_sys->download.base_url,
454                               sms->current_qlvl, chunk->start_time );
455     if( !url )
456     {
457         msg_Err( s, "ConstructUrl returned NULL" );
458         return VLC_EGENERIC;
459     }
460
461     /* sanity check - can we download this chunk on time? */
462     if( (sms->i_obw > 0) && (sms->current_qlvl->Bitrate > 0) )
463     {
464         /* duration in ms */
465         unsigned chunk_duration = chunk->duration * 1000 / sms->timescale;
466         uint64_t size = chunk_duration * sms->current_qlvl->Bitrate / 1000; /* bits */
467         unsigned estimated = size * 1000 / sms->i_obw;
468         if( estimated > chunk_duration )
469         {
470             msg_Warn( s,"downloading of chunk @%"PRIu64" would take %d ms, "
471                         "which is longer than its playback (%d ms)",
472                         chunk->start_time, estimated, chunk_duration );
473         }
474     }
475
476     mtime_t duration = mdate();
477     if( sms_Download( s, chunk, url ) != VLC_SUCCESS )
478     {
479         msg_Err( s, "downloaded chunk @%"PRIu64" from stream %s at quality"
480                     " %u *failed*", chunk->start_time, sms->name, sms->current_qlvl->Bitrate );
481         return VLC_EGENERIC;
482     }
483     duration = mdate() - duration;
484
485     parse_chunk( s, chunk, sms );
486
487     msg_Info( s, "downloaded chunk @%"PRIu64" from stream %s at quality %u",
488                  chunk->start_time, sms->name, sms->current_qlvl->Bitrate );
489
490     if (likely( duration ))
491         bw_stats_put( sms, chunk->size * 8 * CLOCK_FREQ / duration ); /* bits / s */
492
493     /* Track could get disabled in mp4 demux if we trigger adaption too soon.
494        And we don't need adaptation on last chunk */
495     if( sms->p_chunks == NULL || sms->p_chunks == sms->p_lastchunk )
496         return VLC_SUCCESS;
497
498     bool b_starved = false;
499     vlc_mutex_lock( &p_sys->playback.lock );
500     if ( &p_sys->playback.b_underrun )
501     {
502         p_sys->playback.b_underrun = false;
503         bw_stats_underrun( sms );
504         b_starved = true;
505     }
506     vlc_mutex_unlock( &p_sys->playback.lock );
507
508     quality_level_t *new_qlevel = BandwidthAdaptation( s, sms, sms->i_obw,
509                                                        duration, b_starved );
510     assert(new_qlevel);
511
512     if( sms->qlevels.i_size < 2 )
513     {
514         assert(new_qlevel == sms->current_qlvl);
515         return VLC_SUCCESS;
516     }
517
518     vlc_mutex_lock( &p_sys->playback.lock );
519     if ( p_sys->playback.init.p_datachunk == NULL && /* Don't chain/nest reinits */
520          new_qlevel != sms->current_qlvl )
521     {
522         msg_Warn( s, "detected %s bandwidth (%u) stream",
523                   (new_qlevel->Bitrate >= sms->current_qlvl->Bitrate) ? "faster" : "lower",
524                   new_qlevel->Bitrate );
525
526         quality_level_t *qlvl_backup = sms->current_qlvl;
527         sms->current_qlvl = new_qlevel;
528         chunk_t *new_init_ck = build_init_chunk( s );
529         if( new_init_ck )
530         {
531             p_sys->playback.init.p_datachunk = new_init_ck;
532             p_sys->playback.init.p_startchunk = chunk->p_next; /* to send before that one */
533             assert( chunk->p_next && chunk != sms->p_lastchunk );
534         }
535         else
536             sms->current_qlvl = qlvl_backup;
537     }
538     vlc_mutex_unlock( &p_sys->playback.lock );
539
540     return VLC_SUCCESS;
541 }
542
543 static inline bool reached_download_limit( sms_stream_t *sms, unsigned int i_max_chunks,
544                                            uint64_t i_max_time )
545 {
546     if ( !sms->p_nextdownload )
547         return true;
548
549     if ( sms->p_playback == sms->p_nextdownload ) /* chunk can be > max_time */
550         return false;
551
552     const chunk_t *p_head = sms->p_playback;
553     if ( !p_head )
554         return true;
555
556     unsigned int i_chunk_count = 0;
557     uint64_t i_total_time = 0;
558     const chunk_t *p_tail = sms->p_nextdownload;
559     while( p_head )
560     {
561         i_total_time += p_head->duration * CLOCK_FREQ / sms->timescale;
562         if ( i_max_time && i_total_time >= i_max_time )
563         {
564             return true;
565         }
566         else if ( i_max_chunks && i_chunk_count >= i_max_chunks )
567         {
568             return true;
569         }
570
571         if ( p_head == p_tail )
572             break;
573
574         p_head = p_head->p_next;
575         i_chunk_count += 1;
576     }
577
578     return false;
579 }
580
581 static bool all_reached_download_limit( stream_sys_t *p_sys, unsigned int i_max_chunks,
582                                         uint64_t i_max_time )
583 {
584     FOREACH_ARRAY( sms_stream_t *sms, p_sys->sms_selected );
585     vlc_mutex_lock( &sms->chunks_lock );
586     bool b_ret = reached_download_limit( sms, i_max_chunks, i_max_time );
587     vlc_mutex_unlock( &sms->chunks_lock );
588     if ( ! b_ret )
589         return false;
590     FOREACH_END();
591     return true;
592 }
593
594 /* Returns the first download chunk by time in the download queue */
595 static sms_stream_t *next_download_stream( stream_sys_t *p_sys )
596 {
597     sms_stream_t *p_candidate = NULL;
598     FOREACH_ARRAY( sms_stream_t *sms, p_sys->sms_selected );
599     vlc_mutex_lock( &sms->chunks_lock );
600     if ( !sms->p_nextdownload )
601     {
602         vlc_mutex_unlock( &sms->chunks_lock );
603         continue;
604     }
605     if ( p_candidate == NULL ||
606          sms->p_nextdownload->start_time < p_candidate->p_nextdownload->start_time )
607         p_candidate = sms;
608     vlc_mutex_unlock( &sms->chunks_lock );
609     FOREACH_END();
610     return p_candidate;
611 }
612
613 void* sms_Thread( void *p_this )
614 {
615     stream_t *s = (stream_t *)p_this;
616     stream_sys_t *p_sys = s->p_sys;
617
618     int canc = vlc_savecancel();
619
620     chunk_t *init_ck = build_init_chunk( s );
621     if( !init_ck )
622         goto cancel;
623
624     vlc_mutex_lock( &p_sys->playback.lock );
625     p_sys->playback.init.p_datachunk = init_ck;
626     p_sys->playback.init.p_startchunk = NULL; /* before any */
627     vlc_mutex_unlock( &p_sys->playback.lock );
628     vlc_cond_signal( &p_sys->playback.wait ); /* demuxer in Open() can start reading */
629
630     int64_t i_pts_delay = 0;
631
632     /* Buffer up first chunks */
633     int i_initial_buffering = p_sys->download.lookahead_count;
634     if ( !i_initial_buffering )
635         i_initial_buffering = 3;
636     for( int i = 0; i < i_initial_buffering; i++ )
637     {
638         FOREACH_ARRAY( sms_stream_t *sms, p_sys->sms_selected );
639         vlc_mutex_lock( &sms->chunks_lock );
640         if ( sms->p_nextdownload )
641         {
642             mtime_t duration = mdate();
643             if( Download( s, sms ) != VLC_SUCCESS )
644             {
645                 vlc_mutex_unlock( &sms->chunks_lock );
646                 goto cancel;
647             }
648             duration = mdate() - duration;
649             if (likely( duration ))
650                 bw_stats_put( sms, sms->p_nextdownload->size * 8 * CLOCK_FREQ / duration ); /* bits / s */
651             sms->p_nextdownload = sms->p_nextdownload->p_next;
652         }
653         vlc_mutex_unlock( &sms->chunks_lock );
654         FOREACH_END();
655     }
656     vlc_cond_signal( &p_sys->playback.wait );
657
658     while( !p_sys->b_close )
659     {
660         if ( !p_sys->b_live || !p_sys->download.lookahead_count )
661             stream_Control( s, STREAM_GET_PTS_DELAY, &i_pts_delay );
662
663         vlc_mutex_lock( &p_sys->lock );
664         while( all_reached_download_limit( p_sys,
665                                            p_sys->download.lookahead_count,
666                                            i_pts_delay ) )
667         {
668             vlc_cond_wait( &p_sys->download.wait, &p_sys->lock );
669             if( p_sys->b_close )
670                 break;
671         }
672
673         if( p_sys->b_close )
674         {
675             vlc_mutex_unlock( &p_sys->lock );
676             break;
677         }
678
679         sms_stream_t *sms = next_download_stream( p_sys );
680         if ( sms )
681         {
682             vlc_mutex_lock( &sms->chunks_lock );
683             vlc_mutex_unlock( &p_sys->lock );
684
685             if( Download( s, sms ) != VLC_SUCCESS )
686             {
687                 vlc_mutex_unlock( &sms->chunks_lock );
688                 break;
689             }
690             vlc_cond_signal( &p_sys->playback.wait );
691
692             if ( sms->p_nextdownload ) /* could have been modified by seek */
693                 sms->p_nextdownload = sms->p_nextdownload->p_next;
694
695             vlc_mutex_unlock( &sms->chunks_lock );
696         }
697         else
698             vlc_mutex_unlock( &p_sys->lock );
699
700         vlc_testcancel();
701     }
702
703 cancel:
704     p_sys->b_error = true;
705     msg_Dbg(s, "Canceling download thread!");
706     vlc_restorecancel( canc );
707     return NULL;
708 }