]> git.sesse.net Git - ffmpeg/blob - libavformat/hls.c
avformat/hls: enable http_multiple only for http/1.1 servers
[ffmpeg] / libavformat / hls.c
1 /*
2  * Apple HTTP Live Streaming demuxer
3  * Copyright (c) 2010 Martin Storsjo
4  * Copyright (c) 2013 Anssi Hannula
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg 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.
12  *
13  * FFmpeg 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.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 /**
24  * @file
25  * Apple HTTP Live Streaming demuxer
26  * http://tools.ietf.org/html/draft-pantos-http-live-streaming
27  */
28
29 #include "libavformat/http.h"
30 #include "libavutil/avstring.h"
31 #include "libavutil/avassert.h"
32 #include "libavutil/intreadwrite.h"
33 #include "libavutil/mathematics.h"
34 #include "libavutil/opt.h"
35 #include "libavutil/dict.h"
36 #include "libavutil/time.h"
37 #include "avformat.h"
38 #include "internal.h"
39 #include "avio_internal.h"
40 #include "id3v2.h"
41
42 #define INITIAL_BUFFER_SIZE 32768
43
44 #define MAX_FIELD_LEN 64
45 #define MAX_CHARACTERISTICS_LEN 512
46
47 #define MPEG_TIME_BASE 90000
48 #define MPEG_TIME_BASE_Q (AVRational){1, MPEG_TIME_BASE}
49
50 /*
51  * An apple http stream consists of a playlist with media segment files,
52  * played sequentially. There may be several playlists with the same
53  * video content, in different bandwidth variants, that are played in
54  * parallel (preferably only one bandwidth variant at a time). In this case,
55  * the user supplied the url to a main playlist that only lists the variant
56  * playlists.
57  *
58  * If the main playlist doesn't point at any variants, we still create
59  * one anonymous toplevel variant for this, to maintain the structure.
60  */
61
62 enum KeyType {
63     KEY_NONE,
64     KEY_AES_128,
65     KEY_SAMPLE_AES
66 };
67
68 struct segment {
69     int64_t duration;
70     int64_t url_offset;
71     int64_t size;
72     char *url;
73     char *key;
74     enum KeyType key_type;
75     uint8_t iv[16];
76     /* associated Media Initialization Section, treated as a segment */
77     struct segment *init_section;
78 };
79
80 struct rendition;
81
82 enum PlaylistType {
83     PLS_TYPE_UNSPECIFIED,
84     PLS_TYPE_EVENT,
85     PLS_TYPE_VOD
86 };
87
88 /*
89  * Each playlist has its own demuxer. If it currently is active,
90  * it has an open AVIOContext too, and potentially an AVPacket
91  * containing the next packet from this stream.
92  */
93 struct playlist {
94     char url[MAX_URL_SIZE];
95     AVIOContext pb;
96     uint8_t* read_buffer;
97     AVIOContext *input;
98     int input_read_done;
99     AVIOContext *input_next;
100     int input_next_requested;
101     AVFormatContext *parent;
102     int index;
103     AVFormatContext *ctx;
104     AVPacket pkt;
105     int has_noheader_flag;
106
107     /* main demuxer streams associated with this playlist
108      * indexed by the subdemuxer stream indexes */
109     AVStream **main_streams;
110     int n_main_streams;
111
112     int finished;
113     enum PlaylistType type;
114     int64_t target_duration;
115     int start_seq_no;
116     int n_segments;
117     struct segment **segments;
118     int needed;
119     int cur_seq_no;
120     int64_t cur_seg_offset;
121     int64_t last_load_time;
122
123     /* Currently active Media Initialization Section */
124     struct segment *cur_init_section;
125     uint8_t *init_sec_buf;
126     unsigned int init_sec_buf_size;
127     unsigned int init_sec_data_len;
128     unsigned int init_sec_buf_read_offset;
129
130     char key_url[MAX_URL_SIZE];
131     uint8_t key[16];
132
133     /* ID3 timestamp handling (elementary audio streams have ID3 timestamps
134      * (and possibly other ID3 tags) in the beginning of each segment) */
135     int is_id3_timestamped; /* -1: not yet known */
136     int64_t id3_mpegts_timestamp; /* in mpegts tb */
137     int64_t id3_offset; /* in stream original tb */
138     uint8_t* id3_buf; /* temp buffer for id3 parsing */
139     unsigned int id3_buf_size;
140     AVDictionary *id3_initial; /* data from first id3 tag */
141     int id3_found; /* ID3 tag found at some point */
142     int id3_changed; /* ID3 tag data has changed at some point */
143     ID3v2ExtraMeta *id3_deferred_extra; /* stored here until subdemuxer is opened */
144
145     int64_t seek_timestamp;
146     int seek_flags;
147     int seek_stream_index; /* into subdemuxer stream array */
148
149     /* Renditions associated with this playlist, if any.
150      * Alternative rendition playlists have a single rendition associated
151      * with them, and variant main Media Playlists may have
152      * multiple (playlist-less) renditions associated with them. */
153     int n_renditions;
154     struct rendition **renditions;
155
156     /* Media Initialization Sections (EXT-X-MAP) associated with this
157      * playlist, if any. */
158     int n_init_sections;
159     struct segment **init_sections;
160 };
161
162 /*
163  * Renditions are e.g. alternative subtitle or audio streams.
164  * The rendition may either be an external playlist or it may be
165  * contained in the main Media Playlist of the variant (in which case
166  * playlist is NULL).
167  */
168 struct rendition {
169     enum AVMediaType type;
170     struct playlist *playlist;
171     char group_id[MAX_FIELD_LEN];
172     char language[MAX_FIELD_LEN];
173     char name[MAX_FIELD_LEN];
174     int disposition;
175 };
176
177 struct variant {
178     int bandwidth;
179
180     /* every variant contains at least the main Media Playlist in index 0 */
181     int n_playlists;
182     struct playlist **playlists;
183
184     char audio_group[MAX_FIELD_LEN];
185     char video_group[MAX_FIELD_LEN];
186     char subtitles_group[MAX_FIELD_LEN];
187 };
188
189 typedef struct HLSContext {
190     AVClass *class;
191     AVFormatContext *ctx;
192     int n_variants;
193     struct variant **variants;
194     int n_playlists;
195     struct playlist **playlists;
196     int n_renditions;
197     struct rendition **renditions;
198
199     int cur_seq_no;
200     int live_start_index;
201     int first_packet;
202     int64_t first_timestamp;
203     int64_t cur_timestamp;
204     AVIOInterruptCB *interrupt_callback;
205     char *user_agent;                    ///< holds HTTP user agent set as an AVOption to the HTTP protocol context
206     char *cookies;                       ///< holds HTTP cookie values set in either the initial response or as an AVOption to the HTTP protocol context
207     char *headers;                       ///< holds HTTP headers set as an AVOption to the HTTP protocol context
208     char *http_proxy;                    ///< holds the address of the HTTP proxy server
209     AVDictionary *avio_opts;
210     int strict_std_compliance;
211     char *allowed_extensions;
212     int max_reload;
213     int http_persistent;
214     int http_multiple;
215     AVIOContext *playlist_pb;
216 } HLSContext;
217
218 static int read_chomp_line(AVIOContext *s, char *buf, int maxlen)
219 {
220     int len = ff_get_line(s, buf, maxlen);
221     while (len > 0 && av_isspace(buf[len - 1]))
222         buf[--len] = '\0';
223     return len;
224 }
225
226 static void free_segment_list(struct playlist *pls)
227 {
228     int i;
229     for (i = 0; i < pls->n_segments; i++) {
230         av_freep(&pls->segments[i]->key);
231         av_freep(&pls->segments[i]->url);
232         av_freep(&pls->segments[i]);
233     }
234     av_freep(&pls->segments);
235     pls->n_segments = 0;
236 }
237
238 static void free_init_section_list(struct playlist *pls)
239 {
240     int i;
241     for (i = 0; i < pls->n_init_sections; i++) {
242         av_freep(&pls->init_sections[i]->url);
243         av_freep(&pls->init_sections[i]);
244     }
245     av_freep(&pls->init_sections);
246     pls->n_init_sections = 0;
247 }
248
249 static void free_playlist_list(HLSContext *c)
250 {
251     int i;
252     for (i = 0; i < c->n_playlists; i++) {
253         struct playlist *pls = c->playlists[i];
254         free_segment_list(pls);
255         free_init_section_list(pls);
256         av_freep(&pls->main_streams);
257         av_freep(&pls->renditions);
258         av_freep(&pls->id3_buf);
259         av_dict_free(&pls->id3_initial);
260         ff_id3v2_free_extra_meta(&pls->id3_deferred_extra);
261         av_freep(&pls->init_sec_buf);
262         av_packet_unref(&pls->pkt);
263         av_freep(&pls->pb.buffer);
264         if (pls->input)
265             ff_format_io_close(c->ctx, &pls->input);
266         pls->input_read_done = 0;
267         if (pls->input_next)
268             ff_format_io_close(c->ctx, &pls->input_next);
269         pls->input_next_requested = 0;
270         if (pls->ctx) {
271             pls->ctx->pb = NULL;
272             avformat_close_input(&pls->ctx);
273         }
274         av_free(pls);
275     }
276     av_freep(&c->playlists);
277     av_freep(&c->cookies);
278     av_freep(&c->user_agent);
279     av_freep(&c->headers);
280     av_freep(&c->http_proxy);
281     c->n_playlists = 0;
282 }
283
284 static void free_variant_list(HLSContext *c)
285 {
286     int i;
287     for (i = 0; i < c->n_variants; i++) {
288         struct variant *var = c->variants[i];
289         av_freep(&var->playlists);
290         av_free(var);
291     }
292     av_freep(&c->variants);
293     c->n_variants = 0;
294 }
295
296 static void free_rendition_list(HLSContext *c)
297 {
298     int i;
299     for (i = 0; i < c->n_renditions; i++)
300         av_freep(&c->renditions[i]);
301     av_freep(&c->renditions);
302     c->n_renditions = 0;
303 }
304
305 /*
306  * Used to reset a statically allocated AVPacket to a clean slate,
307  * containing no data.
308  */
309 static void reset_packet(AVPacket *pkt)
310 {
311     av_init_packet(pkt);
312     pkt->data = NULL;
313 }
314
315 static struct playlist *new_playlist(HLSContext *c, const char *url,
316                                      const char *base)
317 {
318     struct playlist *pls = av_mallocz(sizeof(struct playlist));
319     if (!pls)
320         return NULL;
321     reset_packet(&pls->pkt);
322     ff_make_absolute_url(pls->url, sizeof(pls->url), base, url);
323     pls->seek_timestamp = AV_NOPTS_VALUE;
324
325     pls->is_id3_timestamped = -1;
326     pls->id3_mpegts_timestamp = AV_NOPTS_VALUE;
327
328     dynarray_add(&c->playlists, &c->n_playlists, pls);
329     return pls;
330 }
331
332 struct variant_info {
333     char bandwidth[20];
334     /* variant group ids: */
335     char audio[MAX_FIELD_LEN];
336     char video[MAX_FIELD_LEN];
337     char subtitles[MAX_FIELD_LEN];
338 };
339
340 static struct variant *new_variant(HLSContext *c, struct variant_info *info,
341                                    const char *url, const char *base)
342 {
343     struct variant *var;
344     struct playlist *pls;
345
346     pls = new_playlist(c, url, base);
347     if (!pls)
348         return NULL;
349
350     var = av_mallocz(sizeof(struct variant));
351     if (!var)
352         return NULL;
353
354     if (info) {
355         var->bandwidth = atoi(info->bandwidth);
356         strcpy(var->audio_group, info->audio);
357         strcpy(var->video_group, info->video);
358         strcpy(var->subtitles_group, info->subtitles);
359     }
360
361     dynarray_add(&c->variants, &c->n_variants, var);
362     dynarray_add(&var->playlists, &var->n_playlists, pls);
363     return var;
364 }
365
366 static void handle_variant_args(struct variant_info *info, const char *key,
367                                 int key_len, char **dest, int *dest_len)
368 {
369     if (!strncmp(key, "BANDWIDTH=", key_len)) {
370         *dest     =        info->bandwidth;
371         *dest_len = sizeof(info->bandwidth);
372     } else if (!strncmp(key, "AUDIO=", key_len)) {
373         *dest     =        info->audio;
374         *dest_len = sizeof(info->audio);
375     } else if (!strncmp(key, "VIDEO=", key_len)) {
376         *dest     =        info->video;
377         *dest_len = sizeof(info->video);
378     } else if (!strncmp(key, "SUBTITLES=", key_len)) {
379         *dest     =        info->subtitles;
380         *dest_len = sizeof(info->subtitles);
381     }
382 }
383
384 struct key_info {
385      char uri[MAX_URL_SIZE];
386      char method[11];
387      char iv[35];
388 };
389
390 static void handle_key_args(struct key_info *info, const char *key,
391                             int key_len, char **dest, int *dest_len)
392 {
393     if (!strncmp(key, "METHOD=", key_len)) {
394         *dest     =        info->method;
395         *dest_len = sizeof(info->method);
396     } else if (!strncmp(key, "URI=", key_len)) {
397         *dest     =        info->uri;
398         *dest_len = sizeof(info->uri);
399     } else if (!strncmp(key, "IV=", key_len)) {
400         *dest     =        info->iv;
401         *dest_len = sizeof(info->iv);
402     }
403 }
404
405 struct init_section_info {
406     char uri[MAX_URL_SIZE];
407     char byterange[32];
408 };
409
410 static struct segment *new_init_section(struct playlist *pls,
411                                         struct init_section_info *info,
412                                         const char *url_base)
413 {
414     struct segment *sec;
415     char *ptr;
416     char tmp_str[MAX_URL_SIZE];
417
418     if (!info->uri[0])
419         return NULL;
420
421     sec = av_mallocz(sizeof(*sec));
422     if (!sec)
423         return NULL;
424
425     ff_make_absolute_url(tmp_str, sizeof(tmp_str), url_base, info->uri);
426     sec->url = av_strdup(tmp_str);
427     if (!sec->url) {
428         av_free(sec);
429         return NULL;
430     }
431
432     if (info->byterange[0]) {
433         sec->size = strtoll(info->byterange, NULL, 10);
434         ptr = strchr(info->byterange, '@');
435         if (ptr)
436             sec->url_offset = strtoll(ptr+1, NULL, 10);
437     } else {
438         /* the entire file is the init section */
439         sec->size = -1;
440     }
441
442     dynarray_add(&pls->init_sections, &pls->n_init_sections, sec);
443
444     return sec;
445 }
446
447 static void handle_init_section_args(struct init_section_info *info, const char *key,
448                                            int key_len, char **dest, int *dest_len)
449 {
450     if (!strncmp(key, "URI=", key_len)) {
451         *dest     =        info->uri;
452         *dest_len = sizeof(info->uri);
453     } else if (!strncmp(key, "BYTERANGE=", key_len)) {
454         *dest     =        info->byterange;
455         *dest_len = sizeof(info->byterange);
456     }
457 }
458
459 struct rendition_info {
460     char type[16];
461     char uri[MAX_URL_SIZE];
462     char group_id[MAX_FIELD_LEN];
463     char language[MAX_FIELD_LEN];
464     char assoc_language[MAX_FIELD_LEN];
465     char name[MAX_FIELD_LEN];
466     char defaultr[4];
467     char forced[4];
468     char characteristics[MAX_CHARACTERISTICS_LEN];
469 };
470
471 static struct rendition *new_rendition(HLSContext *c, struct rendition_info *info,
472                                       const char *url_base)
473 {
474     struct rendition *rend;
475     enum AVMediaType type = AVMEDIA_TYPE_UNKNOWN;
476     char *characteristic;
477     char *chr_ptr;
478     char *saveptr;
479
480     if (!strcmp(info->type, "AUDIO"))
481         type = AVMEDIA_TYPE_AUDIO;
482     else if (!strcmp(info->type, "VIDEO"))
483         type = AVMEDIA_TYPE_VIDEO;
484     else if (!strcmp(info->type, "SUBTITLES"))
485         type = AVMEDIA_TYPE_SUBTITLE;
486     else if (!strcmp(info->type, "CLOSED-CAPTIONS"))
487         /* CLOSED-CAPTIONS is ignored since we do not support CEA-608 CC in
488          * AVC SEI RBSP anyway */
489         return NULL;
490
491     if (type == AVMEDIA_TYPE_UNKNOWN)
492         return NULL;
493
494     /* URI is mandatory for subtitles as per spec */
495     if (type == AVMEDIA_TYPE_SUBTITLE && !info->uri[0])
496         return NULL;
497
498     /* TODO: handle subtitles (each segment has to parsed separately) */
499     if (c->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL)
500         if (type == AVMEDIA_TYPE_SUBTITLE)
501             return NULL;
502
503     rend = av_mallocz(sizeof(struct rendition));
504     if (!rend)
505         return NULL;
506
507     dynarray_add(&c->renditions, &c->n_renditions, rend);
508
509     rend->type = type;
510     strcpy(rend->group_id, info->group_id);
511     strcpy(rend->language, info->language);
512     strcpy(rend->name, info->name);
513
514     /* add the playlist if this is an external rendition */
515     if (info->uri[0]) {
516         rend->playlist = new_playlist(c, info->uri, url_base);
517         if (rend->playlist)
518             dynarray_add(&rend->playlist->renditions,
519                          &rend->playlist->n_renditions, rend);
520     }
521
522     if (info->assoc_language[0]) {
523         int langlen = strlen(rend->language);
524         if (langlen < sizeof(rend->language) - 3) {
525             rend->language[langlen] = ',';
526             strncpy(rend->language + langlen + 1, info->assoc_language,
527                     sizeof(rend->language) - langlen - 2);
528         }
529     }
530
531     if (!strcmp(info->defaultr, "YES"))
532         rend->disposition |= AV_DISPOSITION_DEFAULT;
533     if (!strcmp(info->forced, "YES"))
534         rend->disposition |= AV_DISPOSITION_FORCED;
535
536     chr_ptr = info->characteristics;
537     while ((characteristic = av_strtok(chr_ptr, ",", &saveptr))) {
538         if (!strcmp(characteristic, "public.accessibility.describes-music-and-sound"))
539             rend->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
540         else if (!strcmp(characteristic, "public.accessibility.describes-video"))
541             rend->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED;
542
543         chr_ptr = NULL;
544     }
545
546     return rend;
547 }
548
549 static void handle_rendition_args(struct rendition_info *info, const char *key,
550                                   int key_len, char **dest, int *dest_len)
551 {
552     if (!strncmp(key, "TYPE=", key_len)) {
553         *dest     =        info->type;
554         *dest_len = sizeof(info->type);
555     } else if (!strncmp(key, "URI=", key_len)) {
556         *dest     =        info->uri;
557         *dest_len = sizeof(info->uri);
558     } else if (!strncmp(key, "GROUP-ID=", key_len)) {
559         *dest     =        info->group_id;
560         *dest_len = sizeof(info->group_id);
561     } else if (!strncmp(key, "LANGUAGE=", key_len)) {
562         *dest     =        info->language;
563         *dest_len = sizeof(info->language);
564     } else if (!strncmp(key, "ASSOC-LANGUAGE=", key_len)) {
565         *dest     =        info->assoc_language;
566         *dest_len = sizeof(info->assoc_language);
567     } else if (!strncmp(key, "NAME=", key_len)) {
568         *dest     =        info->name;
569         *dest_len = sizeof(info->name);
570     } else if (!strncmp(key, "DEFAULT=", key_len)) {
571         *dest     =        info->defaultr;
572         *dest_len = sizeof(info->defaultr);
573     } else if (!strncmp(key, "FORCED=", key_len)) {
574         *dest     =        info->forced;
575         *dest_len = sizeof(info->forced);
576     } else if (!strncmp(key, "CHARACTERISTICS=", key_len)) {
577         *dest     =        info->characteristics;
578         *dest_len = sizeof(info->characteristics);
579     }
580     /*
581      * ignored:
582      * - AUTOSELECT: client may autoselect based on e.g. system language
583      * - INSTREAM-ID: EIA-608 closed caption number ("CC1".."CC4")
584      */
585 }
586
587 /* used by parse_playlist to allocate a new variant+playlist when the
588  * playlist is detected to be a Media Playlist (not Master Playlist)
589  * and we have no parent Master Playlist (parsing of which would have
590  * allocated the variant and playlist already)
591  * *pls == NULL  => Master Playlist or parentless Media Playlist
592  * *pls != NULL => parented Media Playlist, playlist+variant allocated */
593 static int ensure_playlist(HLSContext *c, struct playlist **pls, const char *url)
594 {
595     if (*pls)
596         return 0;
597     if (!new_variant(c, NULL, url, NULL))
598         return AVERROR(ENOMEM);
599     *pls = c->playlists[c->n_playlists - 1];
600     return 0;
601 }
602
603 static void update_options(char **dest, const char *name, void *src)
604 {
605     av_freep(dest);
606     av_opt_get(src, name, AV_OPT_SEARCH_CHILDREN, (uint8_t**)dest);
607     if (*dest && !strlen(*dest))
608         av_freep(dest);
609 }
610
611 static int open_url_keepalive(AVFormatContext *s, AVIOContext **pb,
612                               const char *url)
613 {
614 #if !CONFIG_HTTP_PROTOCOL
615     return AVERROR_PROTOCOL_NOT_FOUND;
616 #else
617     int ret;
618     URLContext *uc = ffio_geturlcontext(*pb);
619     av_assert0(uc);
620     (*pb)->eof_reached = 0;
621     ret = ff_http_do_new_request(uc, url);
622     if (ret < 0) {
623         ff_format_io_close(s, pb);
624     }
625     return ret;
626 #endif
627 }
628
629 static int open_url(AVFormatContext *s, AVIOContext **pb, const char *url,
630                     AVDictionary *opts, AVDictionary *opts2, int *is_http_out)
631 {
632     HLSContext *c = s->priv_data;
633     AVDictionary *tmp = NULL;
634     const char *proto_name = NULL;
635     int ret;
636     int is_http = 0;
637
638     av_dict_copy(&tmp, opts, 0);
639     av_dict_copy(&tmp, opts2, 0);
640
641     if (av_strstart(url, "crypto", NULL)) {
642         if (url[6] == '+' || url[6] == ':')
643             proto_name = avio_find_protocol_name(url + 7);
644     }
645
646     if (!proto_name)
647         proto_name = avio_find_protocol_name(url);
648
649     if (!proto_name)
650         return AVERROR_INVALIDDATA;
651
652     // only http(s) & file are allowed
653     if (av_strstart(proto_name, "file", NULL)) {
654         if (strcmp(c->allowed_extensions, "ALL") && !av_match_ext(url, c->allowed_extensions)) {
655             av_log(s, AV_LOG_ERROR,
656                 "Filename extension of \'%s\' is not a common multimedia extension, blocked for security reasons.\n"
657                 "If you wish to override this adjust allowed_extensions, you can set it to \'ALL\' to allow all\n",
658                 url);
659             return AVERROR_INVALIDDATA;
660         }
661     } else if (av_strstart(proto_name, "http", NULL)) {
662         is_http = 1;
663     } else
664         return AVERROR_INVALIDDATA;
665
666     if (!strncmp(proto_name, url, strlen(proto_name)) && url[strlen(proto_name)] == ':')
667         ;
668     else if (av_strstart(url, "crypto", NULL) && !strncmp(proto_name, url + 7, strlen(proto_name)) && url[7 + strlen(proto_name)] == ':')
669         ;
670     else if (strcmp(proto_name, "file") || !strncmp(url, "file,", 5))
671         return AVERROR_INVALIDDATA;
672
673     if (is_http && c->http_persistent && *pb) {
674         ret = open_url_keepalive(c->ctx, pb, url);
675         if (ret == AVERROR_EXIT) {
676             return ret;
677         } else if (ret < 0) {
678             if (ret != AVERROR_EOF)
679                 av_log(s, AV_LOG_WARNING,
680                     "keepalive request failed for '%s', retrying with new connection: %s\n",
681                     url, av_err2str(ret));
682             ret = s->io_open(s, pb, url, AVIO_FLAG_READ, &tmp);
683         }
684     } else {
685         ret = s->io_open(s, pb, url, AVIO_FLAG_READ, &tmp);
686     }
687     if (ret >= 0) {
688         // update cookies on http response with setcookies.
689         char *new_cookies = NULL;
690
691         if (!(s->flags & AVFMT_FLAG_CUSTOM_IO))
692             av_opt_get(*pb, "cookies", AV_OPT_SEARCH_CHILDREN, (uint8_t**)&new_cookies);
693
694         if (new_cookies) {
695             av_free(c->cookies);
696             c->cookies = new_cookies;
697         }
698
699         av_dict_set(&opts, "cookies", c->cookies, 0);
700     }
701
702     av_dict_free(&tmp);
703
704     if (is_http_out)
705         *is_http_out = is_http;
706
707     return ret;
708 }
709
710 static int parse_playlist(HLSContext *c, const char *url,
711                           struct playlist *pls, AVIOContext *in)
712 {
713     int ret = 0, is_segment = 0, is_variant = 0;
714     int64_t duration = 0;
715     enum KeyType key_type = KEY_NONE;
716     uint8_t iv[16] = "";
717     int has_iv = 0;
718     char key[MAX_URL_SIZE] = "";
719     char line[MAX_URL_SIZE];
720     const char *ptr;
721     int close_in = 0;
722     int64_t seg_offset = 0;
723     int64_t seg_size = -1;
724     uint8_t *new_url = NULL;
725     struct variant_info variant_info;
726     char tmp_str[MAX_URL_SIZE];
727     struct segment *cur_init_section = NULL;
728     int is_http = av_strstart(url, "http", NULL);
729
730     if (is_http && !in && c->http_persistent && c->playlist_pb) {
731         in = c->playlist_pb;
732         ret = open_url_keepalive(c->ctx, &c->playlist_pb, url);
733         if (ret == AVERROR_EXIT) {
734             return ret;
735         } else if (ret < 0) {
736             if (ret != AVERROR_EOF)
737                 av_log(c->ctx, AV_LOG_WARNING,
738                     "keepalive request failed for '%s', retrying with new connection: %s\n",
739                     url, av_err2str(ret));
740             in = NULL;
741         }
742     }
743
744     if (!in) {
745 #if 1
746         AVDictionary *opts = NULL;
747         /* Some HLS servers don't like being sent the range header */
748         av_dict_set(&opts, "seekable", "0", 0);
749
750         // broker prior HTTP options that should be consistent across requests
751         av_dict_set(&opts, "user_agent", c->user_agent, 0);
752         av_dict_set(&opts, "cookies", c->cookies, 0);
753         av_dict_set(&opts, "headers", c->headers, 0);
754         av_dict_set(&opts, "http_proxy", c->http_proxy, 0);
755
756         if (c->http_persistent)
757             av_dict_set(&opts, "multiple_requests", "1", 0);
758
759         ret = c->ctx->io_open(c->ctx, &in, url, AVIO_FLAG_READ, &opts);
760         av_dict_free(&opts);
761         if (ret < 0)
762             return ret;
763
764         if (is_http && c->http_persistent)
765             c->playlist_pb = in;
766         else
767             close_in = 1;
768 #else
769         ret = open_in(c, &in, url);
770         if (ret < 0)
771             return ret;
772         close_in = 1;
773 #endif
774     }
775
776     if (av_opt_get(in, "location", AV_OPT_SEARCH_CHILDREN, &new_url) >= 0)
777         url = new_url;
778
779     read_chomp_line(in, line, sizeof(line));
780     if (strcmp(line, "#EXTM3U")) {
781         ret = AVERROR_INVALIDDATA;
782         goto fail;
783     }
784
785     if (pls) {
786         free_segment_list(pls);
787         pls->finished = 0;
788         pls->type = PLS_TYPE_UNSPECIFIED;
789     }
790     while (!avio_feof(in)) {
791         read_chomp_line(in, line, sizeof(line));
792         if (av_strstart(line, "#EXT-X-STREAM-INF:", &ptr)) {
793             is_variant = 1;
794             memset(&variant_info, 0, sizeof(variant_info));
795             ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_variant_args,
796                                &variant_info);
797         } else if (av_strstart(line, "#EXT-X-KEY:", &ptr)) {
798             struct key_info info = {{0}};
799             ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_key_args,
800                                &info);
801             key_type = KEY_NONE;
802             has_iv = 0;
803             if (!strcmp(info.method, "AES-128"))
804                 key_type = KEY_AES_128;
805             if (!strcmp(info.method, "SAMPLE-AES"))
806                 key_type = KEY_SAMPLE_AES;
807             if (!strncmp(info.iv, "0x", 2) || !strncmp(info.iv, "0X", 2)) {
808                 ff_hex_to_data(iv, info.iv + 2);
809                 has_iv = 1;
810             }
811             av_strlcpy(key, info.uri, sizeof(key));
812         } else if (av_strstart(line, "#EXT-X-MEDIA:", &ptr)) {
813             struct rendition_info info = {{0}};
814             ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_rendition_args,
815                                &info);
816             new_rendition(c, &info, url);
817         } else if (av_strstart(line, "#EXT-X-TARGETDURATION:", &ptr)) {
818             ret = ensure_playlist(c, &pls, url);
819             if (ret < 0)
820                 goto fail;
821             pls->target_duration = strtoll(ptr, NULL, 10) * AV_TIME_BASE;
822         } else if (av_strstart(line, "#EXT-X-MEDIA-SEQUENCE:", &ptr)) {
823             ret = ensure_playlist(c, &pls, url);
824             if (ret < 0)
825                 goto fail;
826             pls->start_seq_no = atoi(ptr);
827         } else if (av_strstart(line, "#EXT-X-PLAYLIST-TYPE:", &ptr)) {
828             ret = ensure_playlist(c, &pls, url);
829             if (ret < 0)
830                 goto fail;
831             if (!strcmp(ptr, "EVENT"))
832                 pls->type = PLS_TYPE_EVENT;
833             else if (!strcmp(ptr, "VOD"))
834                 pls->type = PLS_TYPE_VOD;
835         } else if (av_strstart(line, "#EXT-X-MAP:", &ptr)) {
836             struct init_section_info info = {{0}};
837             ret = ensure_playlist(c, &pls, url);
838             if (ret < 0)
839                 goto fail;
840             ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_init_section_args,
841                                &info);
842             cur_init_section = new_init_section(pls, &info, url);
843         } else if (av_strstart(line, "#EXT-X-ENDLIST", &ptr)) {
844             if (pls)
845                 pls->finished = 1;
846         } else if (av_strstart(line, "#EXTINF:", &ptr)) {
847             is_segment = 1;
848             duration   = atof(ptr) * AV_TIME_BASE;
849         } else if (av_strstart(line, "#EXT-X-BYTERANGE:", &ptr)) {
850             seg_size = strtoll(ptr, NULL, 10);
851             ptr = strchr(ptr, '@');
852             if (ptr)
853                 seg_offset = strtoll(ptr+1, NULL, 10);
854         } else if (av_strstart(line, "#", NULL)) {
855             continue;
856         } else if (line[0]) {
857             if (is_variant) {
858                 if (!new_variant(c, &variant_info, line, url)) {
859                     ret = AVERROR(ENOMEM);
860                     goto fail;
861                 }
862                 is_variant = 0;
863             }
864             if (is_segment) {
865                 struct segment *seg;
866                 if (!pls) {
867                     if (!new_variant(c, 0, url, NULL)) {
868                         ret = AVERROR(ENOMEM);
869                         goto fail;
870                     }
871                     pls = c->playlists[c->n_playlists - 1];
872                 }
873                 seg = av_malloc(sizeof(struct segment));
874                 if (!seg) {
875                     ret = AVERROR(ENOMEM);
876                     goto fail;
877                 }
878                 seg->duration = duration;
879                 seg->key_type = key_type;
880                 if (has_iv) {
881                     memcpy(seg->iv, iv, sizeof(iv));
882                 } else {
883                     int seq = pls->start_seq_no + pls->n_segments;
884                     memset(seg->iv, 0, sizeof(seg->iv));
885                     AV_WB32(seg->iv + 12, seq);
886                 }
887
888                 if (key_type != KEY_NONE) {
889                     ff_make_absolute_url(tmp_str, sizeof(tmp_str), url, key);
890                     seg->key = av_strdup(tmp_str);
891                     if (!seg->key) {
892                         av_free(seg);
893                         ret = AVERROR(ENOMEM);
894                         goto fail;
895                     }
896                 } else {
897                     seg->key = NULL;
898                 }
899
900                 ff_make_absolute_url(tmp_str, sizeof(tmp_str), url, line);
901                 seg->url = av_strdup(tmp_str);
902                 if (!seg->url) {
903                     av_free(seg->key);
904                     av_free(seg);
905                     ret = AVERROR(ENOMEM);
906                     goto fail;
907                 }
908
909                 dynarray_add(&pls->segments, &pls->n_segments, seg);
910                 is_segment = 0;
911
912                 seg->size = seg_size;
913                 if (seg_size >= 0) {
914                     seg->url_offset = seg_offset;
915                     seg_offset += seg_size;
916                     seg_size = -1;
917                 } else {
918                     seg->url_offset = 0;
919                     seg_offset = 0;
920                 }
921
922                 seg->init_section = cur_init_section;
923             }
924         }
925     }
926     if (pls)
927         pls->last_load_time = av_gettime_relative();
928
929 fail:
930     av_free(new_url);
931     if (close_in)
932         ff_format_io_close(c->ctx, &in);
933     return ret;
934 }
935
936 static struct segment *current_segment(struct playlist *pls)
937 {
938     return pls->segments[pls->cur_seq_no - pls->start_seq_no];
939 }
940
941 static struct segment *next_segment(struct playlist *pls)
942 {
943     int n = pls->cur_seq_no - pls->start_seq_no + 1;
944     if (n >= pls->n_segments)
945         return NULL;
946     return pls->segments[n];
947 }
948
949 enum ReadFromURLMode {
950     READ_NORMAL,
951     READ_COMPLETE,
952 };
953
954 static int read_from_url(struct playlist *pls, struct segment *seg,
955                          uint8_t *buf, int buf_size,
956                          enum ReadFromURLMode mode)
957 {
958     int ret;
959
960      /* limit read if the segment was only a part of a file */
961     if (seg->size >= 0)
962         buf_size = FFMIN(buf_size, seg->size - pls->cur_seg_offset);
963
964     if (mode == READ_COMPLETE) {
965         ret = avio_read(pls->input, buf, buf_size);
966         if (ret != buf_size)
967             av_log(NULL, AV_LOG_ERROR, "Could not read complete segment.\n");
968     } else
969         ret = avio_read(pls->input, buf, buf_size);
970
971     if (ret > 0)
972         pls->cur_seg_offset += ret;
973
974     return ret;
975 }
976
977 /* Parse the raw ID3 data and pass contents to caller */
978 static void parse_id3(AVFormatContext *s, AVIOContext *pb,
979                       AVDictionary **metadata, int64_t *dts,
980                       ID3v2ExtraMetaAPIC **apic, ID3v2ExtraMeta **extra_meta)
981 {
982     static const char id3_priv_owner_ts[] = "com.apple.streaming.transportStreamTimestamp";
983     ID3v2ExtraMeta *meta;
984
985     ff_id3v2_read_dict(pb, metadata, ID3v2_DEFAULT_MAGIC, extra_meta);
986     for (meta = *extra_meta; meta; meta = meta->next) {
987         if (!strcmp(meta->tag, "PRIV")) {
988             ID3v2ExtraMetaPRIV *priv = meta->data;
989             if (priv->datasize == 8 && !strcmp(priv->owner, id3_priv_owner_ts)) {
990                 /* 33-bit MPEG timestamp */
991                 int64_t ts = AV_RB64(priv->data);
992                 av_log(s, AV_LOG_DEBUG, "HLS ID3 audio timestamp %"PRId64"\n", ts);
993                 if ((ts & ~((1ULL << 33) - 1)) == 0)
994                     *dts = ts;
995                 else
996                     av_log(s, AV_LOG_ERROR, "Invalid HLS ID3 audio timestamp %"PRId64"\n", ts);
997             }
998         } else if (!strcmp(meta->tag, "APIC") && apic)
999             *apic = meta->data;
1000     }
1001 }
1002
1003 /* Check if the ID3 metadata contents have changed */
1004 static int id3_has_changed_values(struct playlist *pls, AVDictionary *metadata,
1005                                   ID3v2ExtraMetaAPIC *apic)
1006 {
1007     AVDictionaryEntry *entry = NULL;
1008     AVDictionaryEntry *oldentry;
1009     /* check that no keys have changed values */
1010     while ((entry = av_dict_get(metadata, "", entry, AV_DICT_IGNORE_SUFFIX))) {
1011         oldentry = av_dict_get(pls->id3_initial, entry->key, NULL, AV_DICT_MATCH_CASE);
1012         if (!oldentry || strcmp(oldentry->value, entry->value) != 0)
1013             return 1;
1014     }
1015
1016     /* check if apic appeared */
1017     if (apic && (pls->ctx->nb_streams != 2 || !pls->ctx->streams[1]->attached_pic.data))
1018         return 1;
1019
1020     if (apic) {
1021         int size = pls->ctx->streams[1]->attached_pic.size;
1022         if (size != apic->buf->size - AV_INPUT_BUFFER_PADDING_SIZE)
1023             return 1;
1024
1025         if (memcmp(apic->buf->data, pls->ctx->streams[1]->attached_pic.data, size) != 0)
1026             return 1;
1027     }
1028
1029     return 0;
1030 }
1031
1032 /* Parse ID3 data and handle the found data */
1033 static void handle_id3(AVIOContext *pb, struct playlist *pls)
1034 {
1035     AVDictionary *metadata = NULL;
1036     ID3v2ExtraMetaAPIC *apic = NULL;
1037     ID3v2ExtraMeta *extra_meta = NULL;
1038     int64_t timestamp = AV_NOPTS_VALUE;
1039
1040     parse_id3(pls->ctx, pb, &metadata, &timestamp, &apic, &extra_meta);
1041
1042     if (timestamp != AV_NOPTS_VALUE) {
1043         pls->id3_mpegts_timestamp = timestamp;
1044         pls->id3_offset = 0;
1045     }
1046
1047     if (!pls->id3_found) {
1048         /* initial ID3 tags */
1049         av_assert0(!pls->id3_deferred_extra);
1050         pls->id3_found = 1;
1051
1052         /* get picture attachment and set text metadata */
1053         if (pls->ctx->nb_streams)
1054             ff_id3v2_parse_apic(pls->ctx, &extra_meta);
1055         else
1056             /* demuxer not yet opened, defer picture attachment */
1057             pls->id3_deferred_extra = extra_meta;
1058
1059         av_dict_copy(&pls->ctx->metadata, metadata, 0);
1060         pls->id3_initial = metadata;
1061
1062     } else {
1063         if (!pls->id3_changed && id3_has_changed_values(pls, metadata, apic)) {
1064             avpriv_report_missing_feature(pls->ctx, "Changing ID3 metadata in HLS audio elementary stream");
1065             pls->id3_changed = 1;
1066         }
1067         av_dict_free(&metadata);
1068     }
1069
1070     if (!pls->id3_deferred_extra)
1071         ff_id3v2_free_extra_meta(&extra_meta);
1072 }
1073
1074 static void intercept_id3(struct playlist *pls, uint8_t *buf,
1075                          int buf_size, int *len)
1076 {
1077     /* intercept id3 tags, we do not want to pass them to the raw
1078      * demuxer on all segment switches */
1079     int bytes;
1080     int id3_buf_pos = 0;
1081     int fill_buf = 0;
1082     struct segment *seg = current_segment(pls);
1083
1084     /* gather all the id3 tags */
1085     while (1) {
1086         /* see if we can retrieve enough data for ID3 header */
1087         if (*len < ID3v2_HEADER_SIZE && buf_size >= ID3v2_HEADER_SIZE) {
1088             bytes = read_from_url(pls, seg, buf + *len, ID3v2_HEADER_SIZE - *len, READ_COMPLETE);
1089             if (bytes > 0) {
1090
1091                 if (bytes == ID3v2_HEADER_SIZE - *len)
1092                     /* no EOF yet, so fill the caller buffer again after
1093                      * we have stripped the ID3 tags */
1094                     fill_buf = 1;
1095
1096                 *len += bytes;
1097
1098             } else if (*len <= 0) {
1099                 /* error/EOF */
1100                 *len = bytes;
1101                 fill_buf = 0;
1102             }
1103         }
1104
1105         if (*len < ID3v2_HEADER_SIZE)
1106             break;
1107
1108         if (ff_id3v2_match(buf, ID3v2_DEFAULT_MAGIC)) {
1109             int64_t maxsize = seg->size >= 0 ? seg->size : 1024*1024;
1110             int taglen = ff_id3v2_tag_len(buf);
1111             int tag_got_bytes = FFMIN(taglen, *len);
1112             int remaining = taglen - tag_got_bytes;
1113
1114             if (taglen > maxsize) {
1115                 av_log(pls->ctx, AV_LOG_ERROR, "Too large HLS ID3 tag (%d > %"PRId64" bytes)\n",
1116                        taglen, maxsize);
1117                 break;
1118             }
1119
1120             /*
1121              * Copy the id3 tag to our temporary id3 buffer.
1122              * We could read a small id3 tag directly without memcpy, but
1123              * we would still need to copy the large tags, and handling
1124              * both of those cases together with the possibility for multiple
1125              * tags would make the handling a bit complex.
1126              */
1127             pls->id3_buf = av_fast_realloc(pls->id3_buf, &pls->id3_buf_size, id3_buf_pos + taglen);
1128             if (!pls->id3_buf)
1129                 break;
1130             memcpy(pls->id3_buf + id3_buf_pos, buf, tag_got_bytes);
1131             id3_buf_pos += tag_got_bytes;
1132
1133             /* strip the intercepted bytes */
1134             *len -= tag_got_bytes;
1135             memmove(buf, buf + tag_got_bytes, *len);
1136             av_log(pls->ctx, AV_LOG_DEBUG, "Stripped %d HLS ID3 bytes\n", tag_got_bytes);
1137
1138             if (remaining > 0) {
1139                 /* read the rest of the tag in */
1140                 if (read_from_url(pls, seg, pls->id3_buf + id3_buf_pos, remaining, READ_COMPLETE) != remaining)
1141                     break;
1142                 id3_buf_pos += remaining;
1143                 av_log(pls->ctx, AV_LOG_DEBUG, "Stripped additional %d HLS ID3 bytes\n", remaining);
1144             }
1145
1146         } else {
1147             /* no more ID3 tags */
1148             break;
1149         }
1150     }
1151
1152     /* re-fill buffer for the caller unless EOF */
1153     if (*len >= 0 && (fill_buf || *len == 0)) {
1154         bytes = read_from_url(pls, seg, buf + *len, buf_size - *len, READ_NORMAL);
1155
1156         /* ignore error if we already had some data */
1157         if (bytes >= 0)
1158             *len += bytes;
1159         else if (*len == 0)
1160             *len = bytes;
1161     }
1162
1163     if (pls->id3_buf) {
1164         /* Now parse all the ID3 tags */
1165         AVIOContext id3ioctx;
1166         ffio_init_context(&id3ioctx, pls->id3_buf, id3_buf_pos, 0, NULL, NULL, NULL, NULL);
1167         handle_id3(&id3ioctx, pls);
1168     }
1169
1170     if (pls->is_id3_timestamped == -1)
1171         pls->is_id3_timestamped = (pls->id3_mpegts_timestamp != AV_NOPTS_VALUE);
1172 }
1173
1174 static int open_input(HLSContext *c, struct playlist *pls, struct segment *seg, AVIOContext **in)
1175 {
1176     AVDictionary *opts = NULL;
1177     int ret;
1178     int is_http = 0;
1179
1180     // broker prior HTTP options that should be consistent across requests
1181     av_dict_set(&opts, "user_agent", c->user_agent, 0);
1182     av_dict_set(&opts, "cookies", c->cookies, 0);
1183     av_dict_set(&opts, "headers", c->headers, 0);
1184     av_dict_set(&opts, "http_proxy", c->http_proxy, 0);
1185     av_dict_set(&opts, "seekable", "0", 0);
1186
1187     if (c->http_persistent)
1188         av_dict_set(&opts, "multiple_requests", "1", 0);
1189
1190     if (seg->size >= 0) {
1191         /* try to restrict the HTTP request to the part we want
1192          * (if this is in fact a HTTP request) */
1193         av_dict_set_int(&opts, "offset", seg->url_offset, 0);
1194         av_dict_set_int(&opts, "end_offset", seg->url_offset + seg->size, 0);
1195     }
1196
1197     av_log(pls->parent, AV_LOG_VERBOSE, "HLS request for url '%s', offset %"PRId64", playlist %d\n",
1198            seg->url, seg->url_offset, pls->index);
1199
1200     if (seg->key_type == KEY_NONE) {
1201         ret = open_url(pls->parent, in, seg->url, c->avio_opts, opts, &is_http);
1202     } else if (seg->key_type == KEY_AES_128) {
1203         AVDictionary *opts2 = NULL;
1204         char iv[33], key[33], url[MAX_URL_SIZE];
1205         if (strcmp(seg->key, pls->key_url)) {
1206             AVIOContext *pb = NULL;
1207             if (open_url(pls->parent, &pb, seg->key, c->avio_opts, opts, NULL) == 0) {
1208                 ret = avio_read(pb, pls->key, sizeof(pls->key));
1209                 if (ret != sizeof(pls->key)) {
1210                     av_log(NULL, AV_LOG_ERROR, "Unable to read key file %s\n",
1211                            seg->key);
1212                 }
1213                 ff_format_io_close(pls->parent, &pb);
1214             } else {
1215                 av_log(NULL, AV_LOG_ERROR, "Unable to open key file %s\n",
1216                        seg->key);
1217             }
1218             av_strlcpy(pls->key_url, seg->key, sizeof(pls->key_url));
1219         }
1220         ff_data_to_hex(iv, seg->iv, sizeof(seg->iv), 0);
1221         ff_data_to_hex(key, pls->key, sizeof(pls->key), 0);
1222         iv[32] = key[32] = '\0';
1223         if (strstr(seg->url, "://"))
1224             snprintf(url, sizeof(url), "crypto+%s", seg->url);
1225         else
1226             snprintf(url, sizeof(url), "crypto:%s", seg->url);
1227
1228         av_dict_copy(&opts2, c->avio_opts, 0);
1229         av_dict_set(&opts2, "key", key, 0);
1230         av_dict_set(&opts2, "iv", iv, 0);
1231
1232         ret = open_url(pls->parent, in, url, opts2, opts, &is_http);
1233
1234         av_dict_free(&opts2);
1235
1236         if (ret < 0) {
1237             goto cleanup;
1238         }
1239         ret = 0;
1240     } else if (seg->key_type == KEY_SAMPLE_AES) {
1241         av_log(pls->parent, AV_LOG_ERROR,
1242                "SAMPLE-AES encryption is not supported yet\n");
1243         ret = AVERROR_PATCHWELCOME;
1244     }
1245     else
1246       ret = AVERROR(ENOSYS);
1247
1248     /* Seek to the requested position. If this was a HTTP request, the offset
1249      * should already be where want it to, but this allows e.g. local testing
1250      * without a HTTP server.
1251      *
1252      * This is not done for HTTP at all as avio_seek() does internal bookkeeping
1253      * of file offset which is out-of-sync with the actual offset when "offset"
1254      * AVOption is used with http protocol, causing the seek to not be a no-op
1255      * as would be expected. Wrong offset received from the server will not be
1256      * noticed without the call, though.
1257      */
1258     if (ret == 0 && !is_http && seg->key_type == KEY_NONE && seg->url_offset) {
1259         int64_t seekret = avio_seek(*in, seg->url_offset, SEEK_SET);
1260         if (seekret < 0) {
1261             av_log(pls->parent, AV_LOG_ERROR, "Unable to seek to offset %"PRId64" of HLS segment '%s'\n", seg->url_offset, seg->url);
1262             ret = seekret;
1263             ff_format_io_close(pls->parent, in);
1264         }
1265     }
1266
1267 cleanup:
1268     av_dict_free(&opts);
1269     pls->cur_seg_offset = 0;
1270     return ret;
1271 }
1272
1273 static int update_init_section(struct playlist *pls, struct segment *seg)
1274 {
1275     static const int max_init_section_size = 1024*1024;
1276     HLSContext *c = pls->parent->priv_data;
1277     int64_t sec_size;
1278     int64_t urlsize;
1279     int ret;
1280
1281     if (seg->init_section == pls->cur_init_section)
1282         return 0;
1283
1284     pls->cur_init_section = NULL;
1285
1286     if (!seg->init_section)
1287         return 0;
1288
1289     ret = open_input(c, pls, seg->init_section, &pls->input);
1290     if (ret < 0) {
1291         av_log(pls->parent, AV_LOG_WARNING,
1292                "Failed to open an initialization section in playlist %d\n",
1293                pls->index);
1294         return ret;
1295     }
1296
1297     if (seg->init_section->size >= 0)
1298         sec_size = seg->init_section->size;
1299     else if ((urlsize = avio_size(pls->input)) >= 0)
1300         sec_size = urlsize;
1301     else
1302         sec_size = max_init_section_size;
1303
1304     av_log(pls->parent, AV_LOG_DEBUG,
1305            "Downloading an initialization section of size %"PRId64"\n",
1306            sec_size);
1307
1308     sec_size = FFMIN(sec_size, max_init_section_size);
1309
1310     av_fast_malloc(&pls->init_sec_buf, &pls->init_sec_buf_size, sec_size);
1311
1312     ret = read_from_url(pls, seg->init_section, pls->init_sec_buf,
1313                         pls->init_sec_buf_size, READ_COMPLETE);
1314     ff_format_io_close(pls->parent, &pls->input);
1315
1316     if (ret < 0)
1317         return ret;
1318
1319     pls->cur_init_section = seg->init_section;
1320     pls->init_sec_data_len = ret;
1321     pls->init_sec_buf_read_offset = 0;
1322
1323     /* spec says audio elementary streams do not have media initialization
1324      * sections, so there should be no ID3 timestamps */
1325     pls->is_id3_timestamped = 0;
1326
1327     return 0;
1328 }
1329
1330 static int64_t default_reload_interval(struct playlist *pls)
1331 {
1332     return pls->n_segments > 0 ?
1333                           pls->segments[pls->n_segments - 1]->duration :
1334                           pls->target_duration;
1335 }
1336
1337 static int playlist_needed(struct playlist *pls)
1338 {
1339     AVFormatContext *s = pls->parent;
1340     int i, j;
1341     int stream_needed = 0;
1342     int first_st;
1343
1344     /* If there is no context or streams yet, the playlist is needed */
1345     if (!pls->ctx || !pls->n_main_streams)
1346         return 1;
1347
1348     /* check if any of the streams in the playlist are needed */
1349     for (i = 0; i < pls->n_main_streams; i++) {
1350         if (pls->main_streams[i]->discard < AVDISCARD_ALL) {
1351             stream_needed = 1;
1352             break;
1353         }
1354     }
1355
1356     /* If all streams in the playlist were discarded, the playlist is not
1357      * needed (regardless of whether whole programs are discarded or not). */
1358     if (!stream_needed)
1359         return 0;
1360
1361     /* Otherwise, check if all the programs (variants) this playlist is in are
1362      * discarded. Since all streams in the playlist are part of the same programs
1363      * we can just check the programs of the first stream. */
1364
1365     first_st = pls->main_streams[0]->index;
1366
1367     for (i = 0; i < s->nb_programs; i++) {
1368         AVProgram *program = s->programs[i];
1369         if (program->discard < AVDISCARD_ALL) {
1370             for (j = 0; j < program->nb_stream_indexes; j++) {
1371                 if (program->stream_index[j] == first_st) {
1372                     /* playlist is in an undiscarded program */
1373                     return 1;
1374                 }
1375             }
1376         }
1377     }
1378
1379     /* some streams were not discarded but all the programs were */
1380     return 0;
1381 }
1382
1383 static int read_data(void *opaque, uint8_t *buf, int buf_size)
1384 {
1385     struct playlist *v = opaque;
1386     HLSContext *c = v->parent->priv_data;
1387     int ret;
1388     int just_opened = 0;
1389     int reload_count = 0;
1390     struct segment *seg;
1391
1392 restart:
1393     if (!v->needed)
1394         return AVERROR_EOF;
1395
1396     if (!v->input || (c->http_persistent && v->input_read_done)) {
1397         int64_t reload_interval;
1398
1399         /* Check that the playlist is still needed before opening a new
1400          * segment. */
1401         v->needed = playlist_needed(v);
1402
1403         if (!v->needed) {
1404             av_log(v->parent, AV_LOG_INFO, "No longer receiving playlist %d\n",
1405                 v->index);
1406             return AVERROR_EOF;
1407         }
1408
1409         /* If this is a live stream and the reload interval has elapsed since
1410          * the last playlist reload, reload the playlists now. */
1411         reload_interval = default_reload_interval(v);
1412
1413 reload:
1414         reload_count++;
1415         if (reload_count > c->max_reload)
1416             return AVERROR_EOF;
1417         if (!v->finished &&
1418             av_gettime_relative() - v->last_load_time >= reload_interval) {
1419             if ((ret = parse_playlist(c, v->url, v, NULL)) < 0) {
1420                 av_log(v->parent, AV_LOG_WARNING, "Failed to reload playlist %d\n",
1421                        v->index);
1422                 return ret;
1423             }
1424             /* If we need to reload the playlist again below (if
1425              * there's still no more segments), switch to a reload
1426              * interval of half the target duration. */
1427             reload_interval = v->target_duration / 2;
1428         }
1429         if (v->cur_seq_no < v->start_seq_no) {
1430             av_log(NULL, AV_LOG_WARNING,
1431                    "skipping %d segments ahead, expired from playlists\n",
1432                    v->start_seq_no - v->cur_seq_no);
1433             v->cur_seq_no = v->start_seq_no;
1434         }
1435         if (v->cur_seq_no >= v->start_seq_no + v->n_segments) {
1436             if (v->finished)
1437                 return AVERROR_EOF;
1438             while (av_gettime_relative() - v->last_load_time < reload_interval) {
1439                 if (ff_check_interrupt(c->interrupt_callback))
1440                     return AVERROR_EXIT;
1441                 av_usleep(100*1000);
1442             }
1443             /* Enough time has elapsed since the last reload */
1444             goto reload;
1445         }
1446
1447         v->input_read_done = 0;
1448         seg = current_segment(v);
1449
1450         /* load/update Media Initialization Section, if any */
1451         ret = update_init_section(v, seg);
1452         if (ret)
1453             return ret;
1454
1455         if (c->http_multiple == 1 && v->input_next_requested) {
1456             FFSWAP(AVIOContext *, v->input, v->input_next);
1457             v->input_next_requested = 0;
1458             ret = 0;
1459         } else {
1460             ret = open_input(c, v, seg, &v->input);
1461         }
1462         if (ret < 0) {
1463             if (ff_check_interrupt(c->interrupt_callback))
1464                 return AVERROR_EXIT;
1465             av_log(v->parent, AV_LOG_WARNING, "Failed to open segment %d of playlist %d\n",
1466                    v->cur_seq_no,
1467                    v->index);
1468             v->cur_seq_no += 1;
1469             goto reload;
1470         }
1471         just_opened = 1;
1472     }
1473
1474     if (c->http_multiple == -1) {
1475         uint8_t *http_version_opt = NULL;
1476         av_opt_get(v->input, "http_version", AV_OPT_SEARCH_CHILDREN, &http_version_opt);
1477         c->http_multiple = http_version_opt && strncmp((const char *)http_version_opt, "1.1", 3) == 0;
1478     }
1479
1480     seg = next_segment(v);
1481     if (c->http_multiple == 1 && !v->input_next_requested &&
1482         seg && av_strstart(seg->url, "http", NULL)) {
1483         ret = open_input(c, v, seg, &v->input_next);
1484         if (ret < 0) {
1485             if (ff_check_interrupt(c->interrupt_callback))
1486                 return AVERROR_EXIT;
1487             av_log(v->parent, AV_LOG_WARNING, "Failed to open segment %d of playlist %d\n",
1488                    v->cur_seq_no + 1,
1489                    v->index);
1490         } else {
1491             v->input_next_requested = 1;
1492         }
1493     }
1494
1495     if (v->init_sec_buf_read_offset < v->init_sec_data_len) {
1496         /* Push init section out first before first actual segment */
1497         int copy_size = FFMIN(v->init_sec_data_len - v->init_sec_buf_read_offset, buf_size);
1498         memcpy(buf, v->init_sec_buf, copy_size);
1499         v->init_sec_buf_read_offset += copy_size;
1500         return copy_size;
1501     }
1502
1503     seg = current_segment(v);
1504     ret = read_from_url(v, seg, buf, buf_size, READ_NORMAL);
1505     if (ret > 0) {
1506         if (just_opened && v->is_id3_timestamped != 0) {
1507             /* Intercept ID3 tags here, elementary audio streams are required
1508              * to convey timestamps using them in the beginning of each segment. */
1509             intercept_id3(v, buf, buf_size, &ret);
1510         }
1511
1512         return ret;
1513     }
1514     if (c->http_persistent && av_strstart(seg->url, "http", NULL)) {
1515         v->input_read_done = 1;
1516     } else {
1517         ff_format_io_close(v->parent, &v->input);
1518     }
1519     v->cur_seq_no++;
1520
1521     c->cur_seq_no = v->cur_seq_no;
1522
1523     goto restart;
1524 }
1525
1526 static void add_renditions_to_variant(HLSContext *c, struct variant *var,
1527                                       enum AVMediaType type, const char *group_id)
1528 {
1529     int i;
1530
1531     for (i = 0; i < c->n_renditions; i++) {
1532         struct rendition *rend = c->renditions[i];
1533
1534         if (rend->type == type && !strcmp(rend->group_id, group_id)) {
1535
1536             if (rend->playlist)
1537                 /* rendition is an external playlist
1538                  * => add the playlist to the variant */
1539                 dynarray_add(&var->playlists, &var->n_playlists, rend->playlist);
1540             else
1541                 /* rendition is part of the variant main Media Playlist
1542                  * => add the rendition to the main Media Playlist */
1543                 dynarray_add(&var->playlists[0]->renditions,
1544                              &var->playlists[0]->n_renditions,
1545                              rend);
1546         }
1547     }
1548 }
1549
1550 static void add_metadata_from_renditions(AVFormatContext *s, struct playlist *pls,
1551                                          enum AVMediaType type)
1552 {
1553     int rend_idx = 0;
1554     int i;
1555
1556     for (i = 0; i < pls->n_main_streams; i++) {
1557         AVStream *st = pls->main_streams[i];
1558
1559         if (st->codecpar->codec_type != type)
1560             continue;
1561
1562         for (; rend_idx < pls->n_renditions; rend_idx++) {
1563             struct rendition *rend = pls->renditions[rend_idx];
1564
1565             if (rend->type != type)
1566                 continue;
1567
1568             if (rend->language[0])
1569                 av_dict_set(&st->metadata, "language", rend->language, 0);
1570             if (rend->name[0])
1571                 av_dict_set(&st->metadata, "comment", rend->name, 0);
1572
1573             st->disposition |= rend->disposition;
1574         }
1575         if (rend_idx >=pls->n_renditions)
1576             break;
1577     }
1578 }
1579
1580 /* if timestamp was in valid range: returns 1 and sets seq_no
1581  * if not: returns 0 and sets seq_no to closest segment */
1582 static int find_timestamp_in_playlist(HLSContext *c, struct playlist *pls,
1583                                       int64_t timestamp, int *seq_no)
1584 {
1585     int i;
1586     int64_t pos = c->first_timestamp == AV_NOPTS_VALUE ?
1587                   0 : c->first_timestamp;
1588
1589     if (timestamp < pos) {
1590         *seq_no = pls->start_seq_no;
1591         return 0;
1592     }
1593
1594     for (i = 0; i < pls->n_segments; i++) {
1595         int64_t diff = pos + pls->segments[i]->duration - timestamp;
1596         if (diff > 0) {
1597             *seq_no = pls->start_seq_no + i;
1598             return 1;
1599         }
1600         pos += pls->segments[i]->duration;
1601     }
1602
1603     *seq_no = pls->start_seq_no + pls->n_segments - 1;
1604
1605     return 0;
1606 }
1607
1608 static int select_cur_seq_no(HLSContext *c, struct playlist *pls)
1609 {
1610     int seq_no;
1611
1612     if (!pls->finished && !c->first_packet &&
1613         av_gettime_relative() - pls->last_load_time >= default_reload_interval(pls))
1614         /* reload the playlist since it was suspended */
1615         parse_playlist(c, pls->url, pls, NULL);
1616
1617     /* If playback is already in progress (we are just selecting a new
1618      * playlist) and this is a complete file, find the matching segment
1619      * by counting durations. */
1620     if (pls->finished && c->cur_timestamp != AV_NOPTS_VALUE) {
1621         find_timestamp_in_playlist(c, pls, c->cur_timestamp, &seq_no);
1622         return seq_no;
1623     }
1624
1625     if (!pls->finished) {
1626         if (!c->first_packet && /* we are doing a segment selection during playback */
1627             c->cur_seq_no >= pls->start_seq_no &&
1628             c->cur_seq_no < pls->start_seq_no + pls->n_segments)
1629             /* While spec 3.4.3 says that we cannot assume anything about the
1630              * content at the same sequence number on different playlists,
1631              * in practice this seems to work and doing it otherwise would
1632              * require us to download a segment to inspect its timestamps. */
1633             return c->cur_seq_no;
1634
1635         /* If this is a live stream, start live_start_index segments from the
1636          * start or end */
1637         if (c->live_start_index < 0)
1638             return pls->start_seq_no + FFMAX(pls->n_segments + c->live_start_index, 0);
1639         else
1640             return pls->start_seq_no + FFMIN(c->live_start_index, pls->n_segments - 1);
1641     }
1642
1643     /* Otherwise just start on the first segment. */
1644     return pls->start_seq_no;
1645 }
1646
1647 static int save_avio_options(AVFormatContext *s)
1648 {
1649     HLSContext *c = s->priv_data;
1650     static const char * const opts[] = {
1651         "headers", "http_proxy", "user_agent", "user-agent", "cookies", NULL };
1652     const char * const * opt = opts;
1653     uint8_t *buf;
1654     int ret = 0;
1655
1656     while (*opt) {
1657         if (av_opt_get(s->pb, *opt, AV_OPT_SEARCH_CHILDREN | AV_OPT_ALLOW_NULL, &buf) >= 0) {
1658             ret = av_dict_set(&c->avio_opts, *opt, buf,
1659                               AV_DICT_DONT_STRDUP_VAL);
1660             if (ret < 0)
1661                 return ret;
1662         }
1663         opt++;
1664     }
1665
1666     return ret;
1667 }
1668
1669 static int nested_io_open(AVFormatContext *s, AVIOContext **pb, const char *url,
1670                           int flags, AVDictionary **opts)
1671 {
1672     av_log(s, AV_LOG_ERROR,
1673            "A HLS playlist item '%s' referred to an external file '%s'. "
1674            "Opening this file was forbidden for security reasons\n",
1675            s->filename, url);
1676     return AVERROR(EPERM);
1677 }
1678
1679 static void add_stream_to_programs(AVFormatContext *s, struct playlist *pls, AVStream *stream)
1680 {
1681     HLSContext *c = s->priv_data;
1682     int i, j;
1683     int bandwidth = -1;
1684
1685     for (i = 0; i < c->n_variants; i++) {
1686         struct variant *v = c->variants[i];
1687
1688         for (j = 0; j < v->n_playlists; j++) {
1689             if (v->playlists[j] != pls)
1690                 continue;
1691
1692             av_program_add_stream_index(s, i, stream->index);
1693
1694             if (bandwidth < 0)
1695                 bandwidth = v->bandwidth;
1696             else if (bandwidth != v->bandwidth)
1697                 bandwidth = -1; /* stream in multiple variants with different bandwidths */
1698         }
1699     }
1700
1701     if (bandwidth >= 0)
1702         av_dict_set_int(&stream->metadata, "variant_bitrate", bandwidth, 0);
1703 }
1704
1705 static int set_stream_info_from_input_stream(AVStream *st, struct playlist *pls, AVStream *ist)
1706 {
1707     int err;
1708
1709     err = avcodec_parameters_copy(st->codecpar, ist->codecpar);
1710     if (err < 0)
1711         return err;
1712
1713     if (pls->is_id3_timestamped) /* custom timestamps via id3 */
1714         avpriv_set_pts_info(st, 33, 1, MPEG_TIME_BASE);
1715     else
1716         avpriv_set_pts_info(st, ist->pts_wrap_bits, ist->time_base.num, ist->time_base.den);
1717
1718     st->internal->need_context_update = 1;
1719
1720     return 0;
1721 }
1722
1723 /* add new subdemuxer streams to our context, if any */
1724 static int update_streams_from_subdemuxer(AVFormatContext *s, struct playlist *pls)
1725 {
1726     int err;
1727
1728     while (pls->n_main_streams < pls->ctx->nb_streams) {
1729         int ist_idx = pls->n_main_streams;
1730         AVStream *st = avformat_new_stream(s, NULL);
1731         AVStream *ist = pls->ctx->streams[ist_idx];
1732
1733         if (!st)
1734             return AVERROR(ENOMEM);
1735
1736         st->id = pls->index;
1737         dynarray_add(&pls->main_streams, &pls->n_main_streams, st);
1738
1739         add_stream_to_programs(s, pls, st);
1740
1741         err = set_stream_info_from_input_stream(st, pls, ist);
1742         if (err < 0)
1743             return err;
1744     }
1745
1746     return 0;
1747 }
1748
1749 static void update_noheader_flag(AVFormatContext *s)
1750 {
1751     HLSContext *c = s->priv_data;
1752     int flag_needed = 0;
1753     int i;
1754
1755     for (i = 0; i < c->n_playlists; i++) {
1756         struct playlist *pls = c->playlists[i];
1757
1758         if (pls->has_noheader_flag) {
1759             flag_needed = 1;
1760             break;
1761         }
1762     }
1763
1764     if (flag_needed)
1765         s->ctx_flags |= AVFMTCTX_NOHEADER;
1766     else
1767         s->ctx_flags &= ~AVFMTCTX_NOHEADER;
1768 }
1769
1770 static int hls_close(AVFormatContext *s)
1771 {
1772     HLSContext *c = s->priv_data;
1773
1774     free_playlist_list(c);
1775     free_variant_list(c);
1776     free_rendition_list(c);
1777
1778     av_dict_free(&c->avio_opts);
1779     ff_format_io_close(c->ctx, &c->playlist_pb);
1780
1781     return 0;
1782 }
1783
1784 static int hls_read_header(AVFormatContext *s)
1785 {
1786     void *u = (s->flags & AVFMT_FLAG_CUSTOM_IO) ? NULL : s->pb;
1787     HLSContext *c = s->priv_data;
1788     int ret = 0, i;
1789     int highest_cur_seq_no = 0;
1790
1791     c->ctx                = s;
1792     c->interrupt_callback = &s->interrupt_callback;
1793     c->strict_std_compliance = s->strict_std_compliance;
1794
1795     c->first_packet = 1;
1796     c->first_timestamp = AV_NOPTS_VALUE;
1797     c->cur_timestamp = AV_NOPTS_VALUE;
1798
1799     if (u) {
1800         // get the previous user agent & set back to null if string size is zero
1801         update_options(&c->user_agent, "user_agent", u);
1802
1803         // get the previous cookies & set back to null if string size is zero
1804         update_options(&c->cookies, "cookies", u);
1805
1806         // get the previous headers & set back to null if string size is zero
1807         update_options(&c->headers, "headers", u);
1808
1809         // get the previous http proxt & set back to null if string size is zero
1810         update_options(&c->http_proxy, "http_proxy", u);
1811     }
1812
1813     if ((ret = parse_playlist(c, s->filename, NULL, s->pb)) < 0)
1814         goto fail;
1815
1816     if ((ret = save_avio_options(s)) < 0)
1817         goto fail;
1818
1819     /* Some HLS servers don't like being sent the range header */
1820     av_dict_set(&c->avio_opts, "seekable", "0", 0);
1821
1822     if (c->n_variants == 0) {
1823         av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
1824         ret = AVERROR_EOF;
1825         goto fail;
1826     }
1827     /* If the playlist only contained playlists (Master Playlist),
1828      * parse each individual playlist. */
1829     if (c->n_playlists > 1 || c->playlists[0]->n_segments == 0) {
1830         for (i = 0; i < c->n_playlists; i++) {
1831             struct playlist *pls = c->playlists[i];
1832             if ((ret = parse_playlist(c, pls->url, pls, NULL)) < 0)
1833                 goto fail;
1834         }
1835     }
1836
1837     if (c->variants[0]->playlists[0]->n_segments == 0) {
1838         av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
1839         ret = AVERROR_EOF;
1840         goto fail;
1841     }
1842
1843     /* If this isn't a live stream, calculate the total duration of the
1844      * stream. */
1845     if (c->variants[0]->playlists[0]->finished) {
1846         int64_t duration = 0;
1847         for (i = 0; i < c->variants[0]->playlists[0]->n_segments; i++)
1848             duration += c->variants[0]->playlists[0]->segments[i]->duration;
1849         s->duration = duration;
1850     }
1851
1852     /* Associate renditions with variants */
1853     for (i = 0; i < c->n_variants; i++) {
1854         struct variant *var = c->variants[i];
1855
1856         if (var->audio_group[0])
1857             add_renditions_to_variant(c, var, AVMEDIA_TYPE_AUDIO, var->audio_group);
1858         if (var->video_group[0])
1859             add_renditions_to_variant(c, var, AVMEDIA_TYPE_VIDEO, var->video_group);
1860         if (var->subtitles_group[0])
1861             add_renditions_to_variant(c, var, AVMEDIA_TYPE_SUBTITLE, var->subtitles_group);
1862     }
1863
1864     /* Create a program for each variant */
1865     for (i = 0; i < c->n_variants; i++) {
1866         struct variant *v = c->variants[i];
1867         AVProgram *program;
1868
1869         program = av_new_program(s, i);
1870         if (!program)
1871             goto fail;
1872         av_dict_set_int(&program->metadata, "variant_bitrate", v->bandwidth, 0);
1873     }
1874
1875     /* Select the starting segments */
1876     for (i = 0; i < c->n_playlists; i++) {
1877         struct playlist *pls = c->playlists[i];
1878
1879         if (pls->n_segments == 0)
1880             continue;
1881
1882         pls->cur_seq_no = select_cur_seq_no(c, pls);
1883         highest_cur_seq_no = FFMAX(highest_cur_seq_no, pls->cur_seq_no);
1884     }
1885
1886     /* Open the demuxer for each playlist */
1887     for (i = 0; i < c->n_playlists; i++) {
1888         struct playlist *pls = c->playlists[i];
1889         AVInputFormat *in_fmt = NULL;
1890
1891         if (!(pls->ctx = avformat_alloc_context())) {
1892             ret = AVERROR(ENOMEM);
1893             goto fail;
1894         }
1895
1896         if (pls->n_segments == 0)
1897             continue;
1898
1899         pls->index  = i;
1900         pls->needed = 1;
1901         pls->parent = s;
1902
1903         /*
1904          * If this is a live stream and this playlist looks like it is one segment
1905          * behind, try to sync it up so that every substream starts at the same
1906          * time position (so e.g. avformat_find_stream_info() will see packets from
1907          * all active streams within the first few seconds). This is not very generic,
1908          * though, as the sequence numbers are technically independent.
1909          */
1910         if (!pls->finished && pls->cur_seq_no == highest_cur_seq_no - 1 &&
1911             highest_cur_seq_no < pls->start_seq_no + pls->n_segments) {
1912             pls->cur_seq_no = highest_cur_seq_no;
1913         }
1914
1915         pls->read_buffer = av_malloc(INITIAL_BUFFER_SIZE);
1916         if (!pls->read_buffer){
1917             ret = AVERROR(ENOMEM);
1918             avformat_free_context(pls->ctx);
1919             pls->ctx = NULL;
1920             goto fail;
1921         }
1922         ffio_init_context(&pls->pb, pls->read_buffer, INITIAL_BUFFER_SIZE, 0, pls,
1923                           read_data, NULL, NULL);
1924         pls->pb.seekable = 0;
1925         ret = av_probe_input_buffer(&pls->pb, &in_fmt, pls->segments[0]->url,
1926                                     NULL, 0, 0);
1927         if (ret < 0) {
1928             /* Free the ctx - it isn't initialized properly at this point,
1929              * so avformat_close_input shouldn't be called. If
1930              * avformat_open_input fails below, it frees and zeros the
1931              * context, so it doesn't need any special treatment like this. */
1932             av_log(s, AV_LOG_ERROR, "Error when loading first segment '%s'\n", pls->segments[0]->url);
1933             avformat_free_context(pls->ctx);
1934             pls->ctx = NULL;
1935             goto fail;
1936         }
1937         pls->ctx->pb       = &pls->pb;
1938         pls->ctx->io_open  = nested_io_open;
1939         pls->ctx->flags   |= s->flags & ~AVFMT_FLAG_CUSTOM_IO;
1940
1941         if ((ret = ff_copy_whiteblacklists(pls->ctx, s)) < 0)
1942             goto fail;
1943
1944         ret = avformat_open_input(&pls->ctx, pls->segments[0]->url, in_fmt, NULL);
1945         if (ret < 0)
1946             goto fail;
1947
1948         if (pls->id3_deferred_extra && pls->ctx->nb_streams == 1) {
1949             ff_id3v2_parse_apic(pls->ctx, &pls->id3_deferred_extra);
1950             avformat_queue_attached_pictures(pls->ctx);
1951             ff_id3v2_free_extra_meta(&pls->id3_deferred_extra);
1952             pls->id3_deferred_extra = NULL;
1953         }
1954
1955         if (pls->is_id3_timestamped == -1)
1956             av_log(s, AV_LOG_WARNING, "No expected HTTP requests have been made\n");
1957
1958         /*
1959          * For ID3 timestamped raw audio streams we need to detect the packet
1960          * durations to calculate timestamps in fill_timing_for_id3_timestamped_stream(),
1961          * but for other streams we can rely on our user calling avformat_find_stream_info()
1962          * on us if they want to.
1963          */
1964         if (pls->is_id3_timestamped) {
1965             ret = avformat_find_stream_info(pls->ctx, NULL);
1966             if (ret < 0)
1967                 goto fail;
1968         }
1969
1970         pls->has_noheader_flag = !!(pls->ctx->ctx_flags & AVFMTCTX_NOHEADER);
1971
1972         /* Create new AVStreams for each stream in this playlist */
1973         ret = update_streams_from_subdemuxer(s, pls);
1974         if (ret < 0)
1975             goto fail;
1976
1977         add_metadata_from_renditions(s, pls, AVMEDIA_TYPE_AUDIO);
1978         add_metadata_from_renditions(s, pls, AVMEDIA_TYPE_VIDEO);
1979         add_metadata_from_renditions(s, pls, AVMEDIA_TYPE_SUBTITLE);
1980     }
1981
1982     update_noheader_flag(s);
1983
1984     return 0;
1985 fail:
1986     hls_close(s);
1987     return ret;
1988 }
1989
1990 static int recheck_discard_flags(AVFormatContext *s, int first)
1991 {
1992     HLSContext *c = s->priv_data;
1993     int i, changed = 0;
1994     int cur_needed;
1995
1996     /* Check if any new streams are needed */
1997     for (i = 0; i < c->n_playlists; i++) {
1998         struct playlist *pls = c->playlists[i];
1999
2000         cur_needed = playlist_needed(c->playlists[i]);
2001
2002         if (cur_needed && !pls->needed) {
2003             pls->needed = 1;
2004             changed = 1;
2005             pls->cur_seq_no = select_cur_seq_no(c, pls);
2006             pls->pb.eof_reached = 0;
2007             if (c->cur_timestamp != AV_NOPTS_VALUE) {
2008                 /* catch up */
2009                 pls->seek_timestamp = c->cur_timestamp;
2010                 pls->seek_flags = AVSEEK_FLAG_ANY;
2011                 pls->seek_stream_index = -1;
2012             }
2013             av_log(s, AV_LOG_INFO, "Now receiving playlist %d, segment %d\n", i, pls->cur_seq_no);
2014         } else if (first && !cur_needed && pls->needed) {
2015             if (pls->input)
2016                 ff_format_io_close(pls->parent, &pls->input);
2017             pls->input_read_done = 0;
2018             if (pls->input_next)
2019                 ff_format_io_close(pls->parent, &pls->input_next);
2020             pls->input_next_requested = 0;
2021             pls->needed = 0;
2022             changed = 1;
2023             av_log(s, AV_LOG_INFO, "No longer receiving playlist %d\n", i);
2024         }
2025     }
2026     return changed;
2027 }
2028
2029 static void fill_timing_for_id3_timestamped_stream(struct playlist *pls)
2030 {
2031     if (pls->id3_offset >= 0) {
2032         pls->pkt.dts = pls->id3_mpegts_timestamp +
2033                                  av_rescale_q(pls->id3_offset,
2034                                               pls->ctx->streams[pls->pkt.stream_index]->time_base,
2035                                               MPEG_TIME_BASE_Q);
2036         if (pls->pkt.duration)
2037             pls->id3_offset += pls->pkt.duration;
2038         else
2039             pls->id3_offset = -1;
2040     } else {
2041         /* there have been packets with unknown duration
2042          * since the last id3 tag, should not normally happen */
2043         pls->pkt.dts = AV_NOPTS_VALUE;
2044     }
2045
2046     if (pls->pkt.duration)
2047         pls->pkt.duration = av_rescale_q(pls->pkt.duration,
2048                                          pls->ctx->streams[pls->pkt.stream_index]->time_base,
2049                                          MPEG_TIME_BASE_Q);
2050
2051     pls->pkt.pts = AV_NOPTS_VALUE;
2052 }
2053
2054 static AVRational get_timebase(struct playlist *pls)
2055 {
2056     if (pls->is_id3_timestamped)
2057         return MPEG_TIME_BASE_Q;
2058
2059     return pls->ctx->streams[pls->pkt.stream_index]->time_base;
2060 }
2061
2062 static int compare_ts_with_wrapdetect(int64_t ts_a, struct playlist *pls_a,
2063                                       int64_t ts_b, struct playlist *pls_b)
2064 {
2065     int64_t scaled_ts_a = av_rescale_q(ts_a, get_timebase(pls_a), MPEG_TIME_BASE_Q);
2066     int64_t scaled_ts_b = av_rescale_q(ts_b, get_timebase(pls_b), MPEG_TIME_BASE_Q);
2067
2068     return av_compare_mod(scaled_ts_a, scaled_ts_b, 1LL << 33);
2069 }
2070
2071 static int hls_read_packet(AVFormatContext *s, AVPacket *pkt)
2072 {
2073     HLSContext *c = s->priv_data;
2074     int ret, i, minplaylist = -1;
2075
2076     recheck_discard_flags(s, c->first_packet);
2077     c->first_packet = 0;
2078
2079     for (i = 0; i < c->n_playlists; i++) {
2080         struct playlist *pls = c->playlists[i];
2081         /* Make sure we've got one buffered packet from each open playlist
2082          * stream */
2083         if (pls->needed && !pls->pkt.data) {
2084             while (1) {
2085                 int64_t ts_diff;
2086                 AVRational tb;
2087                 ret = av_read_frame(pls->ctx, &pls->pkt);
2088                 if (ret < 0) {
2089                     if (!avio_feof(&pls->pb) && ret != AVERROR_EOF)
2090                         return ret;
2091                     reset_packet(&pls->pkt);
2092                     break;
2093                 } else {
2094                     /* stream_index check prevents matching picture attachments etc. */
2095                     if (pls->is_id3_timestamped && pls->pkt.stream_index == 0) {
2096                         /* audio elementary streams are id3 timestamped */
2097                         fill_timing_for_id3_timestamped_stream(pls);
2098                     }
2099
2100                     if (c->first_timestamp == AV_NOPTS_VALUE &&
2101                         pls->pkt.dts       != AV_NOPTS_VALUE)
2102                         c->first_timestamp = av_rescale_q(pls->pkt.dts,
2103                             get_timebase(pls), AV_TIME_BASE_Q);
2104                 }
2105
2106                 if (pls->seek_timestamp == AV_NOPTS_VALUE)
2107                     break;
2108
2109                 if (pls->seek_stream_index < 0 ||
2110                     pls->seek_stream_index == pls->pkt.stream_index) {
2111
2112                     if (pls->pkt.dts == AV_NOPTS_VALUE) {
2113                         pls->seek_timestamp = AV_NOPTS_VALUE;
2114                         break;
2115                     }
2116
2117                     tb = get_timebase(pls);
2118                     ts_diff = av_rescale_rnd(pls->pkt.dts, AV_TIME_BASE,
2119                                             tb.den, AV_ROUND_DOWN) -
2120                             pls->seek_timestamp;
2121                     if (ts_diff >= 0 && (pls->seek_flags  & AVSEEK_FLAG_ANY ||
2122                                         pls->pkt.flags & AV_PKT_FLAG_KEY)) {
2123                         pls->seek_timestamp = AV_NOPTS_VALUE;
2124                         break;
2125                     }
2126                 }
2127                 av_packet_unref(&pls->pkt);
2128                 reset_packet(&pls->pkt);
2129             }
2130         }
2131         /* Check if this stream has the packet with the lowest dts */
2132         if (pls->pkt.data) {
2133             struct playlist *minpls = minplaylist < 0 ?
2134                                      NULL : c->playlists[minplaylist];
2135             if (minplaylist < 0) {
2136                 minplaylist = i;
2137             } else {
2138                 int64_t dts     =    pls->pkt.dts;
2139                 int64_t mindts  = minpls->pkt.dts;
2140
2141                 if (dts == AV_NOPTS_VALUE ||
2142                     (mindts != AV_NOPTS_VALUE && compare_ts_with_wrapdetect(dts, pls, mindts, minpls) < 0))
2143                     minplaylist = i;
2144             }
2145         }
2146     }
2147
2148     /* If we got a packet, return it */
2149     if (minplaylist >= 0) {
2150         struct playlist *pls = c->playlists[minplaylist];
2151         AVStream *ist;
2152         AVStream *st;
2153
2154         ret = update_streams_from_subdemuxer(s, pls);
2155         if (ret < 0) {
2156             av_packet_unref(&pls->pkt);
2157             reset_packet(&pls->pkt);
2158             return ret;
2159         }
2160
2161         /* check if noheader flag has been cleared by the subdemuxer */
2162         if (pls->has_noheader_flag && !(pls->ctx->ctx_flags & AVFMTCTX_NOHEADER)) {
2163             pls->has_noheader_flag = 0;
2164             update_noheader_flag(s);
2165         }
2166
2167         if (pls->pkt.stream_index >= pls->n_main_streams) {
2168             av_log(s, AV_LOG_ERROR, "stream index inconsistency: index %d, %d main streams, %d subdemuxer streams\n",
2169                    pls->pkt.stream_index, pls->n_main_streams, pls->ctx->nb_streams);
2170             av_packet_unref(&pls->pkt);
2171             reset_packet(&pls->pkt);
2172             return AVERROR_BUG;
2173         }
2174
2175         ist = pls->ctx->streams[pls->pkt.stream_index];
2176         st = pls->main_streams[pls->pkt.stream_index];
2177
2178         *pkt = pls->pkt;
2179         pkt->stream_index = st->index;
2180         reset_packet(&c->playlists[minplaylist]->pkt);
2181
2182         if (pkt->dts != AV_NOPTS_VALUE)
2183             c->cur_timestamp = av_rescale_q(pkt->dts,
2184                                             ist->time_base,
2185                                             AV_TIME_BASE_Q);
2186
2187         /* There may be more situations where this would be useful, but this at least
2188          * handles newly probed codecs properly (i.e. request_probe by mpegts). */
2189         if (ist->codecpar->codec_id != st->codecpar->codec_id) {
2190             ret = set_stream_info_from_input_stream(st, pls, ist);
2191             if (ret < 0) {
2192                 av_packet_unref(pkt);
2193                 return ret;
2194             }
2195         }
2196
2197         return 0;
2198     }
2199     return AVERROR_EOF;
2200 }
2201
2202 static int hls_read_seek(AVFormatContext *s, int stream_index,
2203                                int64_t timestamp, int flags)
2204 {
2205     HLSContext *c = s->priv_data;
2206     struct playlist *seek_pls = NULL;
2207     int i, seq_no;
2208     int j;
2209     int stream_subdemuxer_index;
2210     int64_t first_timestamp, seek_timestamp, duration;
2211
2212     if ((flags & AVSEEK_FLAG_BYTE) ||
2213         !(c->variants[0]->playlists[0]->finished || c->variants[0]->playlists[0]->type == PLS_TYPE_EVENT))
2214         return AVERROR(ENOSYS);
2215
2216     first_timestamp = c->first_timestamp == AV_NOPTS_VALUE ?
2217                       0 : c->first_timestamp;
2218
2219     seek_timestamp = av_rescale_rnd(timestamp, AV_TIME_BASE,
2220                                     s->streams[stream_index]->time_base.den,
2221                                     flags & AVSEEK_FLAG_BACKWARD ?
2222                                     AV_ROUND_DOWN : AV_ROUND_UP);
2223
2224     duration = s->duration == AV_NOPTS_VALUE ?
2225                0 : s->duration;
2226
2227     if (0 < duration && duration < seek_timestamp - first_timestamp)
2228         return AVERROR(EIO);
2229
2230     /* find the playlist with the specified stream */
2231     for (i = 0; i < c->n_playlists; i++) {
2232         struct playlist *pls = c->playlists[i];
2233         for (j = 0; j < pls->n_main_streams; j++) {
2234             if (pls->main_streams[j] == s->streams[stream_index]) {
2235                 seek_pls = pls;
2236                 stream_subdemuxer_index = j;
2237                 break;
2238             }
2239         }
2240     }
2241     /* check if the timestamp is valid for the playlist with the
2242      * specified stream index */
2243     if (!seek_pls || !find_timestamp_in_playlist(c, seek_pls, seek_timestamp, &seq_no))
2244         return AVERROR(EIO);
2245
2246     /* set segment now so we do not need to search again below */
2247     seek_pls->cur_seq_no = seq_no;
2248     seek_pls->seek_stream_index = stream_subdemuxer_index;
2249
2250     for (i = 0; i < c->n_playlists; i++) {
2251         /* Reset reading */
2252         struct playlist *pls = c->playlists[i];
2253         if (pls->input)
2254             ff_format_io_close(pls->parent, &pls->input);
2255         pls->input_read_done = 0;
2256         if (pls->input_next)
2257             ff_format_io_close(pls->parent, &pls->input_next);
2258         pls->input_next_requested = 0;
2259         av_packet_unref(&pls->pkt);
2260         reset_packet(&pls->pkt);
2261         pls->pb.eof_reached = 0;
2262         /* Clear any buffered data */
2263         pls->pb.buf_end = pls->pb.buf_ptr = pls->pb.buffer;
2264         /* Reset the pos, to let the mpegts demuxer know we've seeked. */
2265         pls->pb.pos = 0;
2266         /* Flush the packet queue of the subdemuxer. */
2267         ff_read_frame_flush(pls->ctx);
2268
2269         pls->seek_timestamp = seek_timestamp;
2270         pls->seek_flags = flags;
2271
2272         if (pls != seek_pls) {
2273             /* set closest segment seq_no for playlists not handled above */
2274             find_timestamp_in_playlist(c, pls, seek_timestamp, &pls->cur_seq_no);
2275             /* seek the playlist to the given position without taking
2276              * keyframes into account since this playlist does not have the
2277              * specified stream where we should look for the keyframes */
2278             pls->seek_stream_index = -1;
2279             pls->seek_flags |= AVSEEK_FLAG_ANY;
2280         }
2281     }
2282
2283     c->cur_timestamp = seek_timestamp;
2284
2285     return 0;
2286 }
2287
2288 static int hls_probe(AVProbeData *p)
2289 {
2290     /* Require #EXTM3U at the start, and either one of the ones below
2291      * somewhere for a proper match. */
2292     if (strncmp(p->buf, "#EXTM3U", 7))
2293         return 0;
2294
2295     if (strstr(p->buf, "#EXT-X-STREAM-INF:")     ||
2296         strstr(p->buf, "#EXT-X-TARGETDURATION:") ||
2297         strstr(p->buf, "#EXT-X-MEDIA-SEQUENCE:"))
2298         return AVPROBE_SCORE_MAX;
2299     return 0;
2300 }
2301
2302 #define OFFSET(x) offsetof(HLSContext, x)
2303 #define FLAGS AV_OPT_FLAG_DECODING_PARAM
2304 static const AVOption hls_options[] = {
2305     {"live_start_index", "segment index to start live streams at (negative values are from the end)",
2306         OFFSET(live_start_index), AV_OPT_TYPE_INT, {.i64 = -3}, INT_MIN, INT_MAX, FLAGS},
2307     {"allowed_extensions", "List of file extensions that hls is allowed to access",
2308         OFFSET(allowed_extensions), AV_OPT_TYPE_STRING,
2309         {.str = "3gp,aac,avi,flac,mkv,m3u8,m4a,m4s,m4v,mpg,mov,mp2,mp3,mp4,mpeg,mpegts,ogg,ogv,oga,ts,vob,wav"},
2310         INT_MIN, INT_MAX, FLAGS},
2311     {"max_reload", "Maximum number of times a insufficient list is attempted to be reloaded",
2312         OFFSET(max_reload), AV_OPT_TYPE_INT, {.i64 = 1000}, 0, INT_MAX, FLAGS},
2313     {"http_persistent", "Use persistent HTTP connections",
2314         OFFSET(http_persistent), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, FLAGS },
2315     {"http_multiple", "Use multiple HTTP connections for fetching segments",
2316         OFFSET(http_multiple), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, FLAGS},
2317     {NULL}
2318 };
2319
2320 static const AVClass hls_class = {
2321     .class_name = "hls,applehttp",
2322     .item_name  = av_default_item_name,
2323     .option     = hls_options,
2324     .version    = LIBAVUTIL_VERSION_INT,
2325 };
2326
2327 AVInputFormat ff_hls_demuxer = {
2328     .name           = "hls,applehttp",
2329     .long_name      = NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming"),
2330     .priv_class     = &hls_class,
2331     .priv_data_size = sizeof(HLSContext),
2332     .read_probe     = hls_probe,
2333     .read_header    = hls_read_header,
2334     .read_packet    = hls_read_packet,
2335     .read_close     = hls_close,
2336     .read_seek      = hls_read_seek,
2337 };