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