]> git.sesse.net Git - ffmpeg/blob - libavformat/hls.c
Merge commit '9d218d573f8088c606d873e80df572582e6773ef'
[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 "url.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     URLContext *input;
98     AVFormatContext *parent;
99     int index;
100     AVFormatContext *ctx;
101     AVPacket pkt;
102     int stream_offset;
103
104     int finished;
105     enum PlaylistType type;
106     int64_t target_duration;
107     int start_seq_no;
108     int n_segments;
109     struct segment **segments;
110     int needed, cur_needed;
111     int cur_seq_no;
112     int64_t cur_seg_offset;
113     int64_t last_load_time;
114
115     /* Currently active Media Initialization Section */
116     struct segment *cur_init_section;
117     uint8_t *init_sec_buf;
118     unsigned int init_sec_buf_size;
119     unsigned int init_sec_data_len;
120     unsigned int init_sec_buf_read_offset;
121
122     char key_url[MAX_URL_SIZE];
123     uint8_t key[16];
124
125     /* ID3 timestamp handling (elementary audio streams have ID3 timestamps
126      * (and possibly other ID3 tags) in the beginning of each segment) */
127     int is_id3_timestamped; /* -1: not yet known */
128     int64_t id3_mpegts_timestamp; /* in mpegts tb */
129     int64_t id3_offset; /* in stream original tb */
130     uint8_t* id3_buf; /* temp buffer for id3 parsing */
131     unsigned int id3_buf_size;
132     AVDictionary *id3_initial; /* data from first id3 tag */
133     int id3_found; /* ID3 tag found at some point */
134     int id3_changed; /* ID3 tag data has changed at some point */
135     ID3v2ExtraMeta *id3_deferred_extra; /* stored here until subdemuxer is opened */
136
137     int64_t seek_timestamp;
138     int seek_flags;
139     int seek_stream_index; /* into subdemuxer stream array */
140
141     /* Renditions associated with this playlist, if any.
142      * Alternative rendition playlists have a single rendition associated
143      * with them, and variant main Media Playlists may have
144      * multiple (playlist-less) renditions associated with them. */
145     int n_renditions;
146     struct rendition **renditions;
147
148     /* Media Initialization Sections (EXT-X-MAP) associated with this
149      * playlist, if any. */
150     int n_init_sections;
151     struct segment **init_sections;
152 };
153
154 /*
155  * Renditions are e.g. alternative subtitle or audio streams.
156  * The rendition may either be an external playlist or it may be
157  * contained in the main Media Playlist of the variant (in which case
158  * playlist is NULL).
159  */
160 struct rendition {
161     enum AVMediaType type;
162     struct playlist *playlist;
163     char group_id[MAX_FIELD_LEN];
164     char language[MAX_FIELD_LEN];
165     char name[MAX_FIELD_LEN];
166     int disposition;
167 };
168
169 struct variant {
170     int bandwidth;
171
172     /* every variant contains at least the main Media Playlist in index 0 */
173     int n_playlists;
174     struct playlist **playlists;
175
176     char audio_group[MAX_FIELD_LEN];
177     char video_group[MAX_FIELD_LEN];
178     char subtitles_group[MAX_FIELD_LEN];
179 };
180
181 typedef struct HLSContext {
182     AVClass *class;
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             ffurl_close(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 int url_connect(struct playlist *pls, AVDictionary *opts, AVDictionary *opts2)
585 {
586     AVDictionary *tmp = NULL;
587     int ret;
588
589     av_dict_copy(&tmp, opts, 0);
590     av_dict_copy(&tmp, opts2, 0);
591
592     if ((ret = ffurl_connect(pls->input, &tmp)) < 0) {
593         ffurl_close(pls->input);
594         pls->input = NULL;
595     }
596
597     av_dict_free(&tmp);
598     return ret;
599 }
600
601 static void update_options(char **dest, const char *name, void *src)
602 {
603     av_freep(dest);
604     av_opt_get(src, name, 0, (uint8_t**)dest);
605     if (*dest && !strlen(*dest))
606         av_freep(dest);
607 }
608
609 static int open_url(HLSContext *c, URLContext **uc, const char *url, AVDictionary *opts)
610 {
611     AVDictionary *tmp = NULL;
612     int ret;
613
614     av_dict_copy(&tmp, c->avio_opts, 0);
615     av_dict_copy(&tmp, opts, 0);
616
617     ret = ffurl_open(uc, url, AVIO_FLAG_READ, c->interrupt_callback, &tmp);
618     if( ret >= 0) {
619         // update cookies on http response with setcookies.
620         URLContext *u = *uc;
621         update_options(&c->cookies, "cookies", u->priv_data);
622         av_dict_set(&opts, "cookies", c->cookies, 0);
623     }
624
625     av_dict_free(&tmp);
626
627     return ret;
628 }
629
630 static int parse_playlist(HLSContext *c, const char *url,
631                           struct playlist *pls, AVIOContext *in)
632 {
633     int ret = 0, is_segment = 0, is_variant = 0;
634     int64_t duration = 0;
635     enum KeyType key_type = KEY_NONE;
636     uint8_t iv[16] = "";
637     int has_iv = 0;
638     char key[MAX_URL_SIZE] = "";
639     char line[MAX_URL_SIZE];
640     const char *ptr;
641     int close_in = 0;
642     int64_t seg_offset = 0;
643     int64_t seg_size = -1;
644     uint8_t *new_url = NULL;
645     struct variant_info variant_info;
646     char tmp_str[MAX_URL_SIZE];
647     struct segment *cur_init_section = NULL;
648
649     if (!in) {
650 #if 1
651         AVDictionary *opts = NULL;
652         close_in = 1;
653         /* Some HLS servers don't like being sent the range header */
654         av_dict_set(&opts, "seekable", "0", 0);
655
656         // broker prior HTTP options that should be consistent across requests
657         av_dict_set(&opts, "user-agent", c->user_agent, 0);
658         av_dict_set(&opts, "cookies", c->cookies, 0);
659         av_dict_set(&opts, "headers", c->headers, 0);
660         av_dict_set(&opts, "http_proxy", c->http_proxy, 0);
661
662         ret = avio_open2(&in, url, AVIO_FLAG_READ,
663                          c->interrupt_callback, &opts);
664         av_dict_free(&opts);
665         if (ret < 0)
666             return ret;
667 #else
668         ret = open_in(c, &in, url);
669         if (ret < 0)
670             return ret;
671         close_in = 1;
672 #endif
673     }
674
675     if (av_opt_get(in, "location", AV_OPT_SEARCH_CHILDREN, &new_url) >= 0)
676         url = new_url;
677
678     read_chomp_line(in, line, sizeof(line));
679     if (strcmp(line, "#EXTM3U")) {
680         ret = AVERROR_INVALIDDATA;
681         goto fail;
682     }
683
684     if (pls) {
685         free_segment_list(pls);
686         pls->finished = 0;
687         pls->type = PLS_TYPE_UNSPECIFIED;
688     }
689     while (!avio_feof(in)) {
690         read_chomp_line(in, line, sizeof(line));
691         if (av_strstart(line, "#EXT-X-STREAM-INF:", &ptr)) {
692             is_variant = 1;
693             memset(&variant_info, 0, sizeof(variant_info));
694             ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_variant_args,
695                                &variant_info);
696         } else if (av_strstart(line, "#EXT-X-KEY:", &ptr)) {
697             struct key_info info = {{0}};
698             ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_key_args,
699                                &info);
700             key_type = KEY_NONE;
701             has_iv = 0;
702             if (!strcmp(info.method, "AES-128"))
703                 key_type = KEY_AES_128;
704             if (!strcmp(info.method, "SAMPLE-AES"))
705                 key_type = KEY_SAMPLE_AES;
706             if (!strncmp(info.iv, "0x", 2) || !strncmp(info.iv, "0X", 2)) {
707                 ff_hex_to_data(iv, info.iv + 2);
708                 has_iv = 1;
709             }
710             av_strlcpy(key, info.uri, sizeof(key));
711         } else if (av_strstart(line, "#EXT-X-MEDIA:", &ptr)) {
712             struct rendition_info info = {{0}};
713             ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_rendition_args,
714                                &info);
715             new_rendition(c, &info, url);
716         } else if (av_strstart(line, "#EXT-X-TARGETDURATION:", &ptr)) {
717             ret = ensure_playlist(c, &pls, url);
718             if (ret < 0)
719                 goto fail;
720             pls->target_duration = atoi(ptr) * AV_TIME_BASE;
721         } else if (av_strstart(line, "#EXT-X-MEDIA-SEQUENCE:", &ptr)) {
722             ret = ensure_playlist(c, &pls, url);
723             if (ret < 0)
724                 goto fail;
725             pls->start_seq_no = atoi(ptr);
726         } else if (av_strstart(line, "#EXT-X-PLAYLIST-TYPE:", &ptr)) {
727             ret = ensure_playlist(c, &pls, url);
728             if (ret < 0)
729                 goto fail;
730             if (!strcmp(ptr, "EVENT"))
731                 pls->type = PLS_TYPE_EVENT;
732             else if (!strcmp(ptr, "VOD"))
733                 pls->type = PLS_TYPE_VOD;
734         } else if (av_strstart(line, "#EXT-X-MAP:", &ptr)) {
735             struct init_section_info info = {{0}};
736             ret = ensure_playlist(c, &pls, url);
737             if (ret < 0)
738                 goto fail;
739             ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_init_section_args,
740                                &info);
741             cur_init_section = new_init_section(pls, &info, url);
742         } else if (av_strstart(line, "#EXT-X-ENDLIST", &ptr)) {
743             if (pls)
744                 pls->finished = 1;
745         } else if (av_strstart(line, "#EXTINF:", &ptr)) {
746             is_segment = 1;
747             duration   = atof(ptr) * AV_TIME_BASE;
748         } else if (av_strstart(line, "#EXT-X-BYTERANGE:", &ptr)) {
749             seg_size = atoi(ptr);
750             ptr = strchr(ptr, '@');
751             if (ptr)
752                 seg_offset = atoi(ptr+1);
753         } else if (av_strstart(line, "#", NULL)) {
754             continue;
755         } else if (line[0]) {
756             if (is_variant) {
757                 if (!new_variant(c, &variant_info, line, url)) {
758                     ret = AVERROR(ENOMEM);
759                     goto fail;
760                 }
761                 is_variant = 0;
762             }
763             if (is_segment) {
764                 struct segment *seg;
765                 if (!pls) {
766                     if (!new_variant(c, 0, url, NULL)) {
767                         ret = AVERROR(ENOMEM);
768                         goto fail;
769                     }
770                     pls = c->playlists[c->n_playlists - 1];
771                 }
772                 seg = av_malloc(sizeof(struct segment));
773                 if (!seg) {
774                     ret = AVERROR(ENOMEM);
775                     goto fail;
776                 }
777                 seg->duration = duration;
778                 seg->key_type = key_type;
779                 if (has_iv) {
780                     memcpy(seg->iv, iv, sizeof(iv));
781                 } else {
782                     int seq = pls->start_seq_no + pls->n_segments;
783                     memset(seg->iv, 0, sizeof(seg->iv));
784                     AV_WB32(seg->iv + 12, seq);
785                 }
786
787                 if (key_type != KEY_NONE) {
788                     ff_make_absolute_url(tmp_str, sizeof(tmp_str), url, key);
789                     seg->key = av_strdup(tmp_str);
790                     if (!seg->key) {
791                         av_free(seg);
792                         ret = AVERROR(ENOMEM);
793                         goto fail;
794                     }
795                 } else {
796                     seg->key = NULL;
797                 }
798
799                 ff_make_absolute_url(tmp_str, sizeof(tmp_str), url, line);
800                 seg->url = av_strdup(tmp_str);
801                 if (!seg->url) {
802                     av_free(seg->key);
803                     av_free(seg);
804                     ret = AVERROR(ENOMEM);
805                     goto fail;
806                 }
807
808                 dynarray_add(&pls->segments, &pls->n_segments, seg);
809                 is_segment = 0;
810
811                 seg->size = seg_size;
812                 if (seg_size >= 0) {
813                     seg->url_offset = seg_offset;
814                     seg_offset += seg_size;
815                     seg_size = -1;
816                 } else {
817                     seg->url_offset = 0;
818                     seg_offset = 0;
819                 }
820
821                 seg->init_section = cur_init_section;
822             }
823         }
824     }
825     if (pls)
826         pls->last_load_time = av_gettime_relative();
827
828 fail:
829     av_free(new_url);
830     if (close_in)
831         avio_close(in);
832     return ret;
833 }
834
835 static struct segment *current_segment(struct playlist *pls)
836 {
837     return pls->segments[pls->cur_seq_no - pls->start_seq_no];
838 }
839
840 enum ReadFromURLMode {
841     READ_NORMAL,
842     READ_COMPLETE,
843 };
844
845 /* read from URLContext, limiting read to current segment */
846 static int read_from_url(struct playlist *pls, struct segment *seg,
847                          uint8_t *buf, int buf_size,
848                          enum ReadFromURLMode mode)
849 {
850     int ret;
851
852      /* limit read if the segment was only a part of a file */
853     if (seg->size >= 0)
854         buf_size = FFMIN(buf_size, seg->size - pls->cur_seg_offset);
855
856     if (mode == READ_COMPLETE)
857         ret = ffurl_read_complete(pls->input, buf, buf_size);
858     else
859         ret = ffurl_read(pls->input, buf, buf_size);
860
861     if (ret > 0)
862         pls->cur_seg_offset += ret;
863
864     return ret;
865 }
866
867 /* Parse the raw ID3 data and pass contents to caller */
868 static void parse_id3(AVFormatContext *s, AVIOContext *pb,
869                       AVDictionary **metadata, int64_t *dts,
870                       ID3v2ExtraMetaAPIC **apic, ID3v2ExtraMeta **extra_meta)
871 {
872     static const char id3_priv_owner_ts[] = "com.apple.streaming.transportStreamTimestamp";
873     ID3v2ExtraMeta *meta;
874
875     ff_id3v2_read_dict(pb, metadata, ID3v2_DEFAULT_MAGIC, extra_meta);
876     for (meta = *extra_meta; meta; meta = meta->next) {
877         if (!strcmp(meta->tag, "PRIV")) {
878             ID3v2ExtraMetaPRIV *priv = meta->data;
879             if (priv->datasize == 8 && !strcmp(priv->owner, id3_priv_owner_ts)) {
880                 /* 33-bit MPEG timestamp */
881                 int64_t ts = AV_RB64(priv->data);
882                 av_log(s, AV_LOG_DEBUG, "HLS ID3 audio timestamp %"PRId64"\n", ts);
883                 if ((ts & ~((1ULL << 33) - 1)) == 0)
884                     *dts = ts;
885                 else
886                     av_log(s, AV_LOG_ERROR, "Invalid HLS ID3 audio timestamp %"PRId64"\n", ts);
887             }
888         } else if (!strcmp(meta->tag, "APIC") && apic)
889             *apic = meta->data;
890     }
891 }
892
893 /* Check if the ID3 metadata contents have changed */
894 static int id3_has_changed_values(struct playlist *pls, AVDictionary *metadata,
895                                   ID3v2ExtraMetaAPIC *apic)
896 {
897     AVDictionaryEntry *entry = NULL;
898     AVDictionaryEntry *oldentry;
899     /* check that no keys have changed values */
900     while ((entry = av_dict_get(metadata, "", entry, AV_DICT_IGNORE_SUFFIX))) {
901         oldentry = av_dict_get(pls->id3_initial, entry->key, NULL, AV_DICT_MATCH_CASE);
902         if (!oldentry || strcmp(oldentry->value, entry->value) != 0)
903             return 1;
904     }
905
906     /* check if apic appeared */
907     if (apic && (pls->ctx->nb_streams != 2 || !pls->ctx->streams[1]->attached_pic.data))
908         return 1;
909
910     if (apic) {
911         int size = pls->ctx->streams[1]->attached_pic.size;
912         if (size != apic->buf->size - AV_INPUT_BUFFER_PADDING_SIZE)
913             return 1;
914
915         if (memcmp(apic->buf->data, pls->ctx->streams[1]->attached_pic.data, size) != 0)
916             return 1;
917     }
918
919     return 0;
920 }
921
922 /* Parse ID3 data and handle the found data */
923 static void handle_id3(AVIOContext *pb, struct playlist *pls)
924 {
925     AVDictionary *metadata = NULL;
926     ID3v2ExtraMetaAPIC *apic = NULL;
927     ID3v2ExtraMeta *extra_meta = NULL;
928     int64_t timestamp = AV_NOPTS_VALUE;
929
930     parse_id3(pls->ctx, pb, &metadata, &timestamp, &apic, &extra_meta);
931
932     if (timestamp != AV_NOPTS_VALUE) {
933         pls->id3_mpegts_timestamp = timestamp;
934         pls->id3_offset = 0;
935     }
936
937     if (!pls->id3_found) {
938         /* initial ID3 tags */
939         av_assert0(!pls->id3_deferred_extra);
940         pls->id3_found = 1;
941
942         /* get picture attachment and set text metadata */
943         if (pls->ctx->nb_streams)
944             ff_id3v2_parse_apic(pls->ctx, &extra_meta);
945         else
946             /* demuxer not yet opened, defer picture attachment */
947             pls->id3_deferred_extra = extra_meta;
948
949         av_dict_copy(&pls->ctx->metadata, metadata, 0);
950         pls->id3_initial = metadata;
951
952     } else {
953         if (!pls->id3_changed && id3_has_changed_values(pls, metadata, apic)) {
954             avpriv_report_missing_feature(pls->ctx, "Changing ID3 metadata in HLS audio elementary stream");
955             pls->id3_changed = 1;
956         }
957         av_dict_free(&metadata);
958     }
959
960     if (!pls->id3_deferred_extra)
961         ff_id3v2_free_extra_meta(&extra_meta);
962 }
963
964 /* Intercept and handle ID3 tags between URLContext and AVIOContext */
965 static void intercept_id3(struct playlist *pls, uint8_t *buf,
966                          int buf_size, int *len)
967 {
968     /* intercept id3 tags, we do not want to pass them to the raw
969      * demuxer on all segment switches */
970     int bytes;
971     int id3_buf_pos = 0;
972     int fill_buf = 0;
973     struct segment *seg = current_segment(pls);
974
975     /* gather all the id3 tags */
976     while (1) {
977         /* see if we can retrieve enough data for ID3 header */
978         if (*len < ID3v2_HEADER_SIZE && buf_size >= ID3v2_HEADER_SIZE) {
979             bytes = read_from_url(pls, seg, buf + *len, ID3v2_HEADER_SIZE - *len, READ_COMPLETE);
980             if (bytes > 0) {
981
982                 if (bytes == ID3v2_HEADER_SIZE - *len)
983                     /* no EOF yet, so fill the caller buffer again after
984                      * we have stripped the ID3 tags */
985                     fill_buf = 1;
986
987                 *len += bytes;
988
989             } else if (*len <= 0) {
990                 /* error/EOF */
991                 *len = bytes;
992                 fill_buf = 0;
993             }
994         }
995
996         if (*len < ID3v2_HEADER_SIZE)
997             break;
998
999         if (ff_id3v2_match(buf, ID3v2_DEFAULT_MAGIC)) {
1000             int64_t maxsize = seg->size >= 0 ? seg->size : 1024*1024;
1001             int taglen = ff_id3v2_tag_len(buf);
1002             int tag_got_bytes = FFMIN(taglen, *len);
1003             int remaining = taglen - tag_got_bytes;
1004
1005             if (taglen > maxsize) {
1006                 av_log(pls->ctx, AV_LOG_ERROR, "Too large HLS ID3 tag (%d > %"PRId64" bytes)\n",
1007                        taglen, maxsize);
1008                 break;
1009             }
1010
1011             /*
1012              * Copy the id3 tag to our temporary id3 buffer.
1013              * We could read a small id3 tag directly without memcpy, but
1014              * we would still need to copy the large tags, and handling
1015              * both of those cases together with the possibility for multiple
1016              * tags would make the handling a bit complex.
1017              */
1018             pls->id3_buf = av_fast_realloc(pls->id3_buf, &pls->id3_buf_size, id3_buf_pos + taglen);
1019             if (!pls->id3_buf)
1020                 break;
1021             memcpy(pls->id3_buf + id3_buf_pos, buf, tag_got_bytes);
1022             id3_buf_pos += tag_got_bytes;
1023
1024             /* strip the intercepted bytes */
1025             *len -= tag_got_bytes;
1026             memmove(buf, buf + tag_got_bytes, *len);
1027             av_log(pls->ctx, AV_LOG_DEBUG, "Stripped %d HLS ID3 bytes\n", tag_got_bytes);
1028
1029             if (remaining > 0) {
1030                 /* read the rest of the tag in */
1031                 if (read_from_url(pls, seg, pls->id3_buf + id3_buf_pos, remaining, READ_COMPLETE) != remaining)
1032                     break;
1033                 id3_buf_pos += remaining;
1034                 av_log(pls->ctx, AV_LOG_DEBUG, "Stripped additional %d HLS ID3 bytes\n", remaining);
1035             }
1036
1037         } else {
1038             /* no more ID3 tags */
1039             break;
1040         }
1041     }
1042
1043     /* re-fill buffer for the caller unless EOF */
1044     if (*len >= 0 && (fill_buf || *len == 0)) {
1045         bytes = read_from_url(pls, seg, buf + *len, buf_size - *len, READ_NORMAL);
1046
1047         /* ignore error if we already had some data */
1048         if (bytes >= 0)
1049             *len += bytes;
1050         else if (*len == 0)
1051             *len = bytes;
1052     }
1053
1054     if (pls->id3_buf) {
1055         /* Now parse all the ID3 tags */
1056         AVIOContext id3ioctx;
1057         ffio_init_context(&id3ioctx, pls->id3_buf, id3_buf_pos, 0, NULL, NULL, NULL, NULL);
1058         handle_id3(&id3ioctx, pls);
1059     }
1060
1061     if (pls->is_id3_timestamped == -1)
1062         pls->is_id3_timestamped = (pls->id3_mpegts_timestamp != AV_NOPTS_VALUE);
1063 }
1064
1065 static int open_input(HLSContext *c, struct playlist *pls, struct segment *seg)
1066 {
1067     AVDictionary *opts = NULL;
1068     int ret;
1069
1070     // broker prior HTTP options that should be consistent across requests
1071     av_dict_set(&opts, "user-agent", c->user_agent, 0);
1072     av_dict_set(&opts, "cookies", c->cookies, 0);
1073     av_dict_set(&opts, "headers", c->headers, 0);
1074     av_dict_set(&opts, "http_proxy", c->http_proxy, 0);
1075     av_dict_set(&opts, "seekable", "0", 0);
1076
1077     if (seg->size >= 0) {
1078         /* try to restrict the HTTP request to the part we want
1079          * (if this is in fact a HTTP request) */
1080         av_dict_set_int(&opts, "offset", seg->url_offset, 0);
1081         av_dict_set_int(&opts, "end_offset", seg->url_offset + seg->size, 0);
1082     }
1083
1084     av_log(pls->parent, AV_LOG_VERBOSE, "HLS request for url '%s', offset %"PRId64", playlist %d\n",
1085            seg->url, seg->url_offset, pls->index);
1086
1087     if (seg->key_type == KEY_NONE) {
1088         ret = open_url(pls->parent->priv_data, &pls->input, seg->url, opts);
1089     } else if (seg->key_type == KEY_AES_128) {
1090 //         HLSContext *c = var->parent->priv_data;
1091         char iv[33], key[33], url[MAX_URL_SIZE];
1092         if (strcmp(seg->key, pls->key_url)) {
1093             URLContext *uc;
1094             if (open_url(pls->parent->priv_data, &uc, seg->key, opts) == 0) {
1095                 if (ffurl_read_complete(uc, pls->key, sizeof(pls->key))
1096                     != sizeof(pls->key)) {
1097                     av_log(NULL, AV_LOG_ERROR, "Unable to read key file %s\n",
1098                            seg->key);
1099                 }
1100                 ffurl_close(uc);
1101             } else {
1102                 av_log(NULL, AV_LOG_ERROR, "Unable to open key file %s\n",
1103                        seg->key);
1104             }
1105             av_strlcpy(pls->key_url, seg->key, sizeof(pls->key_url));
1106         }
1107         ff_data_to_hex(iv, seg->iv, sizeof(seg->iv), 0);
1108         ff_data_to_hex(key, pls->key, sizeof(pls->key), 0);
1109         iv[32] = key[32] = '\0';
1110         if (strstr(seg->url, "://"))
1111             snprintf(url, sizeof(url), "crypto+%s", seg->url);
1112         else
1113             snprintf(url, sizeof(url), "crypto:%s", seg->url);
1114
1115         if ((ret = ffurl_alloc(&pls->input, url, AVIO_FLAG_READ,
1116                                &pls->parent->interrupt_callback)) < 0)
1117             goto cleanup;
1118         av_opt_set(pls->input->priv_data, "key", key, 0);
1119         av_opt_set(pls->input->priv_data, "iv", iv, 0);
1120
1121         if ((ret = url_connect(pls, c->avio_opts, opts)) < 0) {
1122             goto cleanup;
1123         }
1124         ret = 0;
1125     } else if (seg->key_type == KEY_SAMPLE_AES) {
1126         av_log(pls->parent, AV_LOG_ERROR,
1127                "SAMPLE-AES encryption is not supported yet\n");
1128         ret = AVERROR_PATCHWELCOME;
1129     }
1130     else
1131       ret = AVERROR(ENOSYS);
1132
1133     /* Seek to the requested position. If this was a HTTP request, the offset
1134      * should already be where want it to, but this allows e.g. local testing
1135      * without a HTTP server. */
1136     if (ret == 0 && seg->key_type == KEY_NONE && seg->url_offset) {
1137         int seekret = ffurl_seek(pls->input, seg->url_offset, SEEK_SET);
1138         if (seekret < 0) {
1139             av_log(pls->parent, AV_LOG_ERROR, "Unable to seek to offset %"PRId64" of HLS segment '%s'\n", seg->url_offset, seg->url);
1140             ret = seekret;
1141             ffurl_close(pls->input);
1142             pls->input = NULL;
1143         }
1144     }
1145
1146 cleanup:
1147     av_dict_free(&opts);
1148     pls->cur_seg_offset = 0;
1149     return ret;
1150 }
1151
1152 static int update_init_section(struct playlist *pls, struct segment *seg)
1153 {
1154     static const int max_init_section_size = 1024*1024;
1155     HLSContext *c = pls->parent->priv_data;
1156     int64_t sec_size;
1157     int64_t urlsize;
1158     int ret;
1159
1160     if (seg->init_section == pls->cur_init_section)
1161         return 0;
1162
1163     pls->cur_init_section = NULL;
1164
1165     if (!seg->init_section)
1166         return 0;
1167
1168     /* this will clobber playlist URLContext stuff, so this should be
1169      * called between segments only */
1170     ret = open_input(c, pls, seg->init_section);
1171     if (ret < 0) {
1172         av_log(pls->parent, AV_LOG_WARNING,
1173                "Failed to open an initialization section in playlist %d\n",
1174                pls->index);
1175         return ret;
1176     }
1177
1178     if (seg->init_section->size >= 0)
1179         sec_size = seg->init_section->size;
1180     else if ((urlsize = ffurl_size(pls->input)) >= 0)
1181         sec_size = urlsize;
1182     else
1183         sec_size = max_init_section_size;
1184
1185     av_log(pls->parent, AV_LOG_DEBUG,
1186            "Downloading an initialization section of size %"PRId64"\n",
1187            sec_size);
1188
1189     sec_size = FFMIN(sec_size, max_init_section_size);
1190
1191     av_fast_malloc(&pls->init_sec_buf, &pls->init_sec_buf_size, sec_size);
1192
1193     ret = read_from_url(pls, seg->init_section, pls->init_sec_buf,
1194                         pls->init_sec_buf_size, READ_COMPLETE);
1195     ffurl_close(pls->input);
1196     pls->input = NULL;
1197
1198     if (ret < 0)
1199         return ret;
1200
1201     pls->cur_init_section = seg->init_section;
1202     pls->init_sec_data_len = ret;
1203     pls->init_sec_buf_read_offset = 0;
1204
1205     /* spec says audio elementary streams do not have media initialization
1206      * sections, so there should be no ID3 timestamps */
1207     pls->is_id3_timestamped = 0;
1208
1209     return 0;
1210 }
1211
1212 static int64_t default_reload_interval(struct playlist *pls)
1213 {
1214     return pls->n_segments > 0 ?
1215                           pls->segments[pls->n_segments - 1]->duration :
1216                           pls->target_duration;
1217 }
1218
1219 static int read_data(void *opaque, uint8_t *buf, int buf_size)
1220 {
1221     struct playlist *v = opaque;
1222     HLSContext *c = v->parent->priv_data;
1223     int ret, i;
1224     int just_opened = 0;
1225
1226 restart:
1227     if (!v->needed)
1228         return AVERROR_EOF;
1229
1230     if (!v->input) {
1231         int64_t reload_interval;
1232         struct segment *seg;
1233
1234         /* Check that the playlist is still needed before opening a new
1235          * segment. */
1236         if (v->ctx && v->ctx->nb_streams &&
1237             v->parent->nb_streams >= v->stream_offset + v->ctx->nb_streams) {
1238             v->needed = 0;
1239             for (i = v->stream_offset; i < v->stream_offset + v->ctx->nb_streams;
1240                 i++) {
1241                 if (v->parent->streams[i]->discard < AVDISCARD_ALL)
1242                     v->needed = 1;
1243             }
1244         }
1245         if (!v->needed) {
1246             av_log(v->parent, AV_LOG_INFO, "No longer receiving playlist %d\n",
1247                 v->index);
1248             return AVERROR_EOF;
1249         }
1250
1251         /* If this is a live stream and the reload interval has elapsed since
1252          * the last playlist reload, reload the playlists now. */
1253         reload_interval = default_reload_interval(v);
1254
1255 reload:
1256         if (!v->finished &&
1257             av_gettime_relative() - v->last_load_time >= reload_interval) {
1258             if ((ret = parse_playlist(c, v->url, v, NULL)) < 0) {
1259                 av_log(v->parent, AV_LOG_WARNING, "Failed to reload playlist %d\n",
1260                        v->index);
1261                 return ret;
1262             }
1263             /* If we need to reload the playlist again below (if
1264              * there's still no more segments), switch to a reload
1265              * interval of half the target duration. */
1266             reload_interval = v->target_duration / 2;
1267         }
1268         if (v->cur_seq_no < v->start_seq_no) {
1269             av_log(NULL, AV_LOG_WARNING,
1270                    "skipping %d segments ahead, expired from playlists\n",
1271                    v->start_seq_no - v->cur_seq_no);
1272             v->cur_seq_no = v->start_seq_no;
1273         }
1274         if (v->cur_seq_no >= v->start_seq_no + v->n_segments) {
1275             if (v->finished)
1276                 return AVERROR_EOF;
1277             while (av_gettime_relative() - v->last_load_time < reload_interval) {
1278                 if (ff_check_interrupt(c->interrupt_callback))
1279                     return AVERROR_EXIT;
1280                 av_usleep(100*1000);
1281             }
1282             /* Enough time has elapsed since the last reload */
1283             goto reload;
1284         }
1285
1286         seg = current_segment(v);
1287
1288         /* load/update Media Initialization Section, if any */
1289         ret = update_init_section(v, seg);
1290         if (ret)
1291             return ret;
1292
1293         ret = open_input(c, v, seg);
1294         if (ret < 0) {
1295             if (ff_check_interrupt(c->interrupt_callback))
1296                 return AVERROR_EXIT;
1297             av_log(v->parent, AV_LOG_WARNING, "Failed to open segment of playlist %d\n",
1298                    v->index);
1299             v->cur_seq_no += 1;
1300             goto reload;
1301         }
1302         just_opened = 1;
1303     }
1304
1305     if (v->init_sec_buf_read_offset < v->init_sec_data_len) {
1306         /* Push init section out first before first actual segment */
1307         int copy_size = FFMIN(v->init_sec_data_len - v->init_sec_buf_read_offset, buf_size);
1308         memcpy(buf, v->init_sec_buf, copy_size);
1309         v->init_sec_buf_read_offset += copy_size;
1310         return copy_size;
1311     }
1312
1313     ret = read_from_url(v, current_segment(v), buf, buf_size, READ_NORMAL);
1314     if (ret > 0) {
1315         if (just_opened && v->is_id3_timestamped != 0) {
1316             /* Intercept ID3 tags here, elementary audio streams are required
1317              * to convey timestamps using them in the beginning of each segment. */
1318             intercept_id3(v, buf, buf_size, &ret);
1319         }
1320
1321         return ret;
1322     }
1323     ffurl_close(v->input);
1324     v->input = NULL;
1325     v->cur_seq_no++;
1326
1327     c->cur_seq_no = v->cur_seq_no;
1328
1329     goto restart;
1330 }
1331
1332 static int playlist_in_multiple_variants(HLSContext *c, struct playlist *pls)
1333 {
1334     int variant_count = 0;
1335     int i, j;
1336
1337     for (i = 0; i < c->n_variants && variant_count < 2; i++) {
1338         struct variant *v = c->variants[i];
1339
1340         for (j = 0; j < v->n_playlists; j++) {
1341             if (v->playlists[j] == pls) {
1342                 variant_count++;
1343                 break;
1344             }
1345         }
1346     }
1347
1348     return variant_count >= 2;
1349 }
1350
1351 static void add_renditions_to_variant(HLSContext *c, struct variant *var,
1352                                       enum AVMediaType type, const char *group_id)
1353 {
1354     int i;
1355
1356     for (i = 0; i < c->n_renditions; i++) {
1357         struct rendition *rend = c->renditions[i];
1358
1359         if (rend->type == type && !strcmp(rend->group_id, group_id)) {
1360
1361             if (rend->playlist)
1362                 /* rendition is an external playlist
1363                  * => add the playlist to the variant */
1364                 dynarray_add(&var->playlists, &var->n_playlists, rend->playlist);
1365             else
1366                 /* rendition is part of the variant main Media Playlist
1367                  * => add the rendition to the main Media Playlist */
1368                 dynarray_add(&var->playlists[0]->renditions,
1369                              &var->playlists[0]->n_renditions,
1370                              rend);
1371         }
1372     }
1373 }
1374
1375 static void add_metadata_from_renditions(AVFormatContext *s, struct playlist *pls,
1376                                          enum AVMediaType type)
1377 {
1378     int rend_idx = 0;
1379     int i;
1380
1381     for (i = 0; i < pls->ctx->nb_streams; i++) {
1382         AVStream *st = s->streams[pls->stream_offset + i];
1383
1384         if (st->codec->codec_type != type)
1385             continue;
1386
1387         for (; rend_idx < pls->n_renditions; rend_idx++) {
1388             struct rendition *rend = pls->renditions[rend_idx];
1389
1390             if (rend->type != type)
1391                 continue;
1392
1393             if (rend->language[0])
1394                 av_dict_set(&st->metadata, "language", rend->language, 0);
1395             if (rend->name[0])
1396                 av_dict_set(&st->metadata, "comment", rend->name, 0);
1397
1398             st->disposition |= rend->disposition;
1399         }
1400         if (rend_idx >=pls->n_renditions)
1401             break;
1402     }
1403 }
1404
1405 /* if timestamp was in valid range: returns 1 and sets seq_no
1406  * if not: returns 0 and sets seq_no to closest segment */
1407 static int find_timestamp_in_playlist(HLSContext *c, struct playlist *pls,
1408                                       int64_t timestamp, int *seq_no)
1409 {
1410     int i;
1411     int64_t pos = c->first_timestamp == AV_NOPTS_VALUE ?
1412                   0 : c->first_timestamp;
1413
1414     if (timestamp < pos) {
1415         *seq_no = pls->start_seq_no;
1416         return 0;
1417     }
1418
1419     for (i = 0; i < pls->n_segments; i++) {
1420         int64_t diff = pos + pls->segments[i]->duration - timestamp;
1421         if (diff > 0) {
1422             *seq_no = pls->start_seq_no + i;
1423             return 1;
1424         }
1425         pos += pls->segments[i]->duration;
1426     }
1427
1428     *seq_no = pls->start_seq_no + pls->n_segments - 1;
1429
1430     return 0;
1431 }
1432
1433 static int select_cur_seq_no(HLSContext *c, struct playlist *pls)
1434 {
1435     int seq_no;
1436
1437     if (!pls->finished && !c->first_packet &&
1438         av_gettime_relative() - pls->last_load_time >= default_reload_interval(pls))
1439         /* reload the playlist since it was suspended */
1440         parse_playlist(c, pls->url, pls, NULL);
1441
1442     /* If playback is already in progress (we are just selecting a new
1443      * playlist) and this is a complete file, find the matching segment
1444      * by counting durations. */
1445     if (pls->finished && c->cur_timestamp != AV_NOPTS_VALUE) {
1446         find_timestamp_in_playlist(c, pls, c->cur_timestamp, &seq_no);
1447         return seq_no;
1448     }
1449
1450     if (!pls->finished) {
1451         if (!c->first_packet && /* we are doing a segment selection during playback */
1452             c->cur_seq_no >= pls->start_seq_no &&
1453             c->cur_seq_no < pls->start_seq_no + pls->n_segments)
1454             /* While spec 3.4.3 says that we cannot assume anything about the
1455              * content at the same sequence number on different playlists,
1456              * in practice this seems to work and doing it otherwise would
1457              * require us to download a segment to inspect its timestamps. */
1458             return c->cur_seq_no;
1459
1460         /* If this is a live stream, start live_start_index segments from the
1461          * start or end */
1462         if (c->live_start_index < 0)
1463             return pls->start_seq_no + FFMAX(pls->n_segments + c->live_start_index, 0);
1464         else
1465             return pls->start_seq_no + FFMIN(c->live_start_index, pls->n_segments - 1);
1466     }
1467
1468     /* Otherwise just start on the first segment. */
1469     return pls->start_seq_no;
1470 }
1471
1472 static int save_avio_options(AVFormatContext *s)
1473 {
1474     HLSContext *c = s->priv_data;
1475     const char *opts[] = {
1476         "headers", "http_proxy", "user_agent", "user-agent", "cookies", NULL };
1477     const char **opt = opts;
1478     uint8_t *buf;
1479     int ret = 0;
1480
1481     while (*opt) {
1482         if (av_opt_get(s->pb, *opt, AV_OPT_SEARCH_CHILDREN | AV_OPT_ALLOW_NULL, &buf) >= 0) {
1483             ret = av_dict_set(&c->avio_opts, *opt, buf,
1484                               AV_DICT_DONT_STRDUP_VAL);
1485             if (ret < 0)
1486                 return ret;
1487         }
1488         opt++;
1489     }
1490
1491     return ret;
1492 }
1493
1494 static int hls_read_header(AVFormatContext *s)
1495 {
1496     URLContext *u = (s->flags & AVFMT_FLAG_CUSTOM_IO) ? NULL : s->pb->opaque;
1497     HLSContext *c = s->priv_data;
1498     int ret = 0, i, j, stream_offset = 0;
1499
1500     c->interrupt_callback = &s->interrupt_callback;
1501     c->strict_std_compliance = s->strict_std_compliance;
1502
1503     c->first_packet = 1;
1504     c->first_timestamp = AV_NOPTS_VALUE;
1505     c->cur_timestamp = AV_NOPTS_VALUE;
1506
1507     // if the URL context is good, read important options we must broker later
1508     if (u && u->prot->priv_data_class) {
1509         // get the previous user agent & set back to null if string size is zero
1510         update_options(&c->user_agent, "user-agent", u->priv_data);
1511
1512         // get the previous cookies & set back to null if string size is zero
1513         update_options(&c->cookies, "cookies", u->priv_data);
1514
1515         // get the previous headers & set back to null if string size is zero
1516         update_options(&c->headers, "headers", u->priv_data);
1517
1518         // get the previous http proxt & set back to null if string size is zero
1519         update_options(&c->http_proxy, "http_proxy", u->priv_data);
1520     }
1521
1522     if ((ret = parse_playlist(c, s->filename, NULL, s->pb)) < 0)
1523         goto fail;
1524
1525     if ((ret = save_avio_options(s)) < 0)
1526         goto fail;
1527
1528     /* Some HLS servers don't like being sent the range header */
1529     av_dict_set(&c->avio_opts, "seekable", "0", 0);
1530
1531     if (c->n_variants == 0) {
1532         av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
1533         ret = AVERROR_EOF;
1534         goto fail;
1535     }
1536     /* If the playlist only contained playlists (Master Playlist),
1537      * parse each individual playlist. */
1538     if (c->n_playlists > 1 || c->playlists[0]->n_segments == 0) {
1539         for (i = 0; i < c->n_playlists; i++) {
1540             struct playlist *pls = c->playlists[i];
1541             if ((ret = parse_playlist(c, pls->url, pls, NULL)) < 0)
1542                 goto fail;
1543         }
1544     }
1545
1546     if (c->variants[0]->playlists[0]->n_segments == 0) {
1547         av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
1548         ret = AVERROR_EOF;
1549         goto fail;
1550     }
1551
1552     /* If this isn't a live stream, calculate the total duration of the
1553      * stream. */
1554     if (c->variants[0]->playlists[0]->finished) {
1555         int64_t duration = 0;
1556         for (i = 0; i < c->variants[0]->playlists[0]->n_segments; i++)
1557             duration += c->variants[0]->playlists[0]->segments[i]->duration;
1558         s->duration = duration;
1559     }
1560
1561     /* Associate renditions with variants */
1562     for (i = 0; i < c->n_variants; i++) {
1563         struct variant *var = c->variants[i];
1564
1565         if (var->audio_group[0])
1566             add_renditions_to_variant(c, var, AVMEDIA_TYPE_AUDIO, var->audio_group);
1567         if (var->video_group[0])
1568             add_renditions_to_variant(c, var, AVMEDIA_TYPE_VIDEO, var->video_group);
1569         if (var->subtitles_group[0])
1570             add_renditions_to_variant(c, var, AVMEDIA_TYPE_SUBTITLE, var->subtitles_group);
1571     }
1572
1573     /* Open the demuxer for each playlist */
1574     for (i = 0; i < c->n_playlists; i++) {
1575         struct playlist *pls = c->playlists[i];
1576         AVInputFormat *in_fmt = NULL;
1577
1578         if (!(pls->ctx = avformat_alloc_context())) {
1579             ret = AVERROR(ENOMEM);
1580             goto fail;
1581         }
1582
1583         if (pls->n_segments == 0)
1584             continue;
1585
1586         pls->index  = i;
1587         pls->needed = 1;
1588         pls->parent = s;
1589         pls->cur_seq_no = select_cur_seq_no(c, pls);
1590
1591         pls->read_buffer = av_malloc(INITIAL_BUFFER_SIZE);
1592         if (!pls->read_buffer){
1593             ret = AVERROR(ENOMEM);
1594             avformat_free_context(pls->ctx);
1595             pls->ctx = NULL;
1596             goto fail;
1597         }
1598         ffio_init_context(&pls->pb, pls->read_buffer, INITIAL_BUFFER_SIZE, 0, pls,
1599                           read_data, NULL, NULL);
1600         pls->pb.seekable = 0;
1601         ret = av_probe_input_buffer(&pls->pb, &in_fmt, pls->segments[0]->url,
1602                                     NULL, 0, 0);
1603         if (ret < 0) {
1604             /* Free the ctx - it isn't initialized properly at this point,
1605              * so avformat_close_input shouldn't be called. If
1606              * avformat_open_input fails below, it frees and zeros the
1607              * context, so it doesn't need any special treatment like this. */
1608             av_log(s, AV_LOG_ERROR, "Error when loading first segment '%s'\n", pls->segments[0]->url);
1609             avformat_free_context(pls->ctx);
1610             pls->ctx = NULL;
1611             goto fail;
1612         }
1613         pls->ctx->pb       = &pls->pb;
1614         pls->stream_offset = stream_offset;
1615
1616         if ((ret = ff_copy_whitelists(pls->ctx, s)) < 0)
1617             goto fail;
1618
1619         ret = avformat_open_input(&pls->ctx, pls->segments[0]->url, in_fmt, NULL);
1620         if (ret < 0)
1621             goto fail;
1622
1623         if (pls->id3_deferred_extra && pls->ctx->nb_streams == 1) {
1624             ff_id3v2_parse_apic(pls->ctx, &pls->id3_deferred_extra);
1625             avformat_queue_attached_pictures(pls->ctx);
1626             ff_id3v2_free_extra_meta(&pls->id3_deferred_extra);
1627             pls->id3_deferred_extra = NULL;
1628         }
1629
1630         pls->ctx->ctx_flags &= ~AVFMTCTX_NOHEADER;
1631         ret = avformat_find_stream_info(pls->ctx, NULL);
1632         if (ret < 0)
1633             goto fail;
1634
1635         if (pls->is_id3_timestamped == -1)
1636             av_log(s, AV_LOG_WARNING, "No expected HTTP requests have been made\n");
1637
1638         /* Create new AVStreams for each stream in this playlist */
1639         for (j = 0; j < pls->ctx->nb_streams; j++) {
1640             AVStream *st = avformat_new_stream(s, NULL);
1641             AVStream *ist = pls->ctx->streams[j];
1642             if (!st) {
1643                 ret = AVERROR(ENOMEM);
1644                 goto fail;
1645             }
1646             st->id = i;
1647
1648             avcodec_copy_context(st->codec, pls->ctx->streams[j]->codec);
1649
1650             if (pls->is_id3_timestamped) /* custom timestamps via id3 */
1651                 avpriv_set_pts_info(st, 33, 1, MPEG_TIME_BASE);
1652             else
1653                 avpriv_set_pts_info(st, ist->pts_wrap_bits, ist->time_base.num, ist->time_base.den);
1654         }
1655
1656         add_metadata_from_renditions(s, pls, AVMEDIA_TYPE_AUDIO);
1657         add_metadata_from_renditions(s, pls, AVMEDIA_TYPE_VIDEO);
1658         add_metadata_from_renditions(s, pls, AVMEDIA_TYPE_SUBTITLE);
1659
1660         stream_offset += pls->ctx->nb_streams;
1661     }
1662
1663     /* Create a program for each variant */
1664     for (i = 0; i < c->n_variants; i++) {
1665         struct variant *v = c->variants[i];
1666         AVProgram *program;
1667
1668         program = av_new_program(s, i);
1669         if (!program)
1670             goto fail;
1671         av_dict_set_int(&program->metadata, "variant_bitrate", v->bandwidth, 0);
1672
1673         for (j = 0; j < v->n_playlists; j++) {
1674             struct playlist *pls = v->playlists[j];
1675             int is_shared = playlist_in_multiple_variants(c, pls);
1676             int k;
1677
1678             for (k = 0; k < pls->ctx->nb_streams; k++) {
1679                 struct AVStream *st = s->streams[pls->stream_offset + k];
1680
1681                 av_program_add_stream_index(s, i, pls->stream_offset + k);
1682
1683                 /* Set variant_bitrate for streams unique to this variant */
1684                 if (!is_shared && v->bandwidth)
1685                     av_dict_set_int(&st->metadata, "variant_bitrate", v->bandwidth, 0);
1686             }
1687         }
1688     }
1689
1690     return 0;
1691 fail:
1692     free_playlist_list(c);
1693     free_variant_list(c);
1694     free_rendition_list(c);
1695     return ret;
1696 }
1697
1698 static int recheck_discard_flags(AVFormatContext *s, int first)
1699 {
1700     HLSContext *c = s->priv_data;
1701     int i, changed = 0;
1702
1703     /* Check if any new streams are needed */
1704     for (i = 0; i < c->n_playlists; i++)
1705         c->playlists[i]->cur_needed = 0;
1706
1707     for (i = 0; i < s->nb_streams; i++) {
1708         AVStream *st = s->streams[i];
1709         struct playlist *pls = c->playlists[s->streams[i]->id];
1710         if (st->discard < AVDISCARD_ALL)
1711             pls->cur_needed = 1;
1712     }
1713     for (i = 0; i < c->n_playlists; i++) {
1714         struct playlist *pls = c->playlists[i];
1715         if (pls->cur_needed && !pls->needed) {
1716             pls->needed = 1;
1717             changed = 1;
1718             pls->cur_seq_no = select_cur_seq_no(c, pls);
1719             pls->pb.eof_reached = 0;
1720             if (c->cur_timestamp != AV_NOPTS_VALUE) {
1721                 /* catch up */
1722                 pls->seek_timestamp = c->cur_timestamp;
1723                 pls->seek_flags = AVSEEK_FLAG_ANY;
1724                 pls->seek_stream_index = -1;
1725             }
1726             av_log(s, AV_LOG_INFO, "Now receiving playlist %d, segment %d\n", i, pls->cur_seq_no);
1727         } else if (first && !pls->cur_needed && pls->needed) {
1728             if (pls->input)
1729                 ffurl_close(pls->input);
1730             pls->input = NULL;
1731             pls->needed = 0;
1732             changed = 1;
1733             av_log(s, AV_LOG_INFO, "No longer receiving playlist %d\n", i);
1734         }
1735     }
1736     return changed;
1737 }
1738
1739 static void fill_timing_for_id3_timestamped_stream(struct playlist *pls)
1740 {
1741     if (pls->id3_offset >= 0) {
1742         pls->pkt.dts = pls->id3_mpegts_timestamp +
1743                                  av_rescale_q(pls->id3_offset,
1744                                               pls->ctx->streams[pls->pkt.stream_index]->time_base,
1745                                               MPEG_TIME_BASE_Q);
1746         if (pls->pkt.duration)
1747             pls->id3_offset += pls->pkt.duration;
1748         else
1749             pls->id3_offset = -1;
1750     } else {
1751         /* there have been packets with unknown duration
1752          * since the last id3 tag, should not normally happen */
1753         pls->pkt.dts = AV_NOPTS_VALUE;
1754     }
1755
1756     if (pls->pkt.duration)
1757         pls->pkt.duration = av_rescale_q(pls->pkt.duration,
1758                                          pls->ctx->streams[pls->pkt.stream_index]->time_base,
1759                                          MPEG_TIME_BASE_Q);
1760
1761     pls->pkt.pts = AV_NOPTS_VALUE;
1762 }
1763
1764 static AVRational get_timebase(struct playlist *pls)
1765 {
1766     if (pls->is_id3_timestamped)
1767         return MPEG_TIME_BASE_Q;
1768
1769     return pls->ctx->streams[pls->pkt.stream_index]->time_base;
1770 }
1771
1772 static int compare_ts_with_wrapdetect(int64_t ts_a, struct playlist *pls_a,
1773                                       int64_t ts_b, struct playlist *pls_b)
1774 {
1775     int64_t scaled_ts_a = av_rescale_q(ts_a, get_timebase(pls_a), MPEG_TIME_BASE_Q);
1776     int64_t scaled_ts_b = av_rescale_q(ts_b, get_timebase(pls_b), MPEG_TIME_BASE_Q);
1777
1778     return av_compare_mod(scaled_ts_a, scaled_ts_b, 1LL << 33);
1779 }
1780
1781 static int hls_read_packet(AVFormatContext *s, AVPacket *pkt)
1782 {
1783     HLSContext *c = s->priv_data;
1784     int ret, i, minplaylist = -1;
1785
1786     recheck_discard_flags(s, c->first_packet);
1787     c->first_packet = 0;
1788
1789     for (i = 0; i < c->n_playlists; i++) {
1790         struct playlist *pls = c->playlists[i];
1791         /* Make sure we've got one buffered packet from each open playlist
1792          * stream */
1793         if (pls->needed && !pls->pkt.data) {
1794             while (1) {
1795                 int64_t ts_diff;
1796                 AVRational tb;
1797                 ret = av_read_frame(pls->ctx, &pls->pkt);
1798                 if (ret < 0) {
1799                     if (!avio_feof(&pls->pb) && ret != AVERROR_EOF)
1800                         return ret;
1801                     reset_packet(&pls->pkt);
1802                     break;
1803                 } else {
1804                     /* stream_index check prevents matching picture attachments etc. */
1805                     if (pls->is_id3_timestamped && pls->pkt.stream_index == 0) {
1806                         /* audio elementary streams are id3 timestamped */
1807                         fill_timing_for_id3_timestamped_stream(pls);
1808                     }
1809
1810                     if (c->first_timestamp == AV_NOPTS_VALUE &&
1811                         pls->pkt.dts       != AV_NOPTS_VALUE)
1812                         c->first_timestamp = av_rescale_q(pls->pkt.dts,
1813                             get_timebase(pls), AV_TIME_BASE_Q);
1814                 }
1815
1816                 if (pls->seek_timestamp == AV_NOPTS_VALUE)
1817                     break;
1818
1819                 if (pls->seek_stream_index < 0 ||
1820                     pls->seek_stream_index == pls->pkt.stream_index) {
1821
1822                     if (pls->pkt.dts == AV_NOPTS_VALUE) {
1823                         pls->seek_timestamp = AV_NOPTS_VALUE;
1824                         break;
1825                     }
1826
1827                     tb = get_timebase(pls);
1828                     ts_diff = av_rescale_rnd(pls->pkt.dts, AV_TIME_BASE,
1829                                             tb.den, AV_ROUND_DOWN) -
1830                             pls->seek_timestamp;
1831                     if (ts_diff >= 0 && (pls->seek_flags  & AVSEEK_FLAG_ANY ||
1832                                         pls->pkt.flags & AV_PKT_FLAG_KEY)) {
1833                         pls->seek_timestamp = AV_NOPTS_VALUE;
1834                         break;
1835                     }
1836                 }
1837                 av_packet_unref(&pls->pkt);
1838                 reset_packet(&pls->pkt);
1839             }
1840         }
1841         /* Check if this stream has the packet with the lowest dts */
1842         if (pls->pkt.data) {
1843             struct playlist *minpls = minplaylist < 0 ?
1844                                      NULL : c->playlists[minplaylist];
1845             if (minplaylist < 0) {
1846                 minplaylist = i;
1847             } else {
1848                 int64_t dts     =    pls->pkt.dts;
1849                 int64_t mindts  = minpls->pkt.dts;
1850
1851                 if (dts == AV_NOPTS_VALUE ||
1852                     (mindts != AV_NOPTS_VALUE && compare_ts_with_wrapdetect(dts, pls, mindts, minpls) < 0))
1853                     minplaylist = i;
1854             }
1855         }
1856     }
1857
1858     /* If we got a packet, return it */
1859     if (minplaylist >= 0) {
1860         struct playlist *pls = c->playlists[minplaylist];
1861         *pkt = pls->pkt;
1862         pkt->stream_index += pls->stream_offset;
1863         reset_packet(&c->playlists[minplaylist]->pkt);
1864
1865         if (pkt->dts != AV_NOPTS_VALUE)
1866             c->cur_timestamp = av_rescale_q(pkt->dts,
1867                                             pls->ctx->streams[pls->pkt.stream_index]->time_base,
1868                                             AV_TIME_BASE_Q);
1869
1870         return 0;
1871     }
1872     return AVERROR_EOF;
1873 }
1874
1875 static int hls_close(AVFormatContext *s)
1876 {
1877     HLSContext *c = s->priv_data;
1878
1879     free_playlist_list(c);
1880     free_variant_list(c);
1881     free_rendition_list(c);
1882
1883     av_dict_free(&c->avio_opts);
1884
1885     return 0;
1886 }
1887
1888 static int hls_read_seek(AVFormatContext *s, int stream_index,
1889                                int64_t timestamp, int flags)
1890 {
1891     HLSContext *c = s->priv_data;
1892     struct playlist *seek_pls = NULL;
1893     int i, seq_no;
1894     int64_t first_timestamp, seek_timestamp, duration;
1895
1896     if ((flags & AVSEEK_FLAG_BYTE) ||
1897         !(c->variants[0]->playlists[0]->finished || c->variants[0]->playlists[0]->type == PLS_TYPE_EVENT))
1898         return AVERROR(ENOSYS);
1899
1900     first_timestamp = c->first_timestamp == AV_NOPTS_VALUE ?
1901                       0 : c->first_timestamp;
1902
1903     seek_timestamp = av_rescale_rnd(timestamp, AV_TIME_BASE,
1904                                     s->streams[stream_index]->time_base.den,
1905                                     flags & AVSEEK_FLAG_BACKWARD ?
1906                                     AV_ROUND_DOWN : AV_ROUND_UP);
1907
1908     duration = s->duration == AV_NOPTS_VALUE ?
1909                0 : s->duration;
1910
1911     if (0 < duration && duration < seek_timestamp - first_timestamp)
1912         return AVERROR(EIO);
1913
1914     /* find the playlist with the specified stream */
1915     for (i = 0; i < c->n_playlists; i++) {
1916         struct playlist *pls = c->playlists[i];
1917         if (stream_index >= pls->stream_offset &&
1918             stream_index - pls->stream_offset < pls->ctx->nb_streams) {
1919             seek_pls = pls;
1920             break;
1921         }
1922     }
1923     /* check if the timestamp is valid for the playlist with the
1924      * specified stream index */
1925     if (!seek_pls || !find_timestamp_in_playlist(c, seek_pls, seek_timestamp, &seq_no))
1926         return AVERROR(EIO);
1927
1928     /* set segment now so we do not need to search again below */
1929     seek_pls->cur_seq_no = seq_no;
1930     seek_pls->seek_stream_index = stream_index - seek_pls->stream_offset;
1931
1932     for (i = 0; i < c->n_playlists; i++) {
1933         /* Reset reading */
1934         struct playlist *pls = c->playlists[i];
1935         if (pls->input) {
1936             ffurl_close(pls->input);
1937             pls->input = NULL;
1938         }
1939         av_packet_unref(&pls->pkt);
1940         reset_packet(&pls->pkt);
1941         pls->pb.eof_reached = 0;
1942         /* Clear any buffered data */
1943         pls->pb.buf_end = pls->pb.buf_ptr = pls->pb.buffer;
1944         /* Reset the pos, to let the mpegts demuxer know we've seeked. */
1945         pls->pb.pos = 0;
1946         /* Flush the packet queue of the subdemuxer. */
1947         ff_read_frame_flush(pls->ctx);
1948
1949         pls->seek_timestamp = seek_timestamp;
1950         pls->seek_flags = flags;
1951
1952         if (pls != seek_pls) {
1953             /* set closest segment seq_no for playlists not handled above */
1954             find_timestamp_in_playlist(c, pls, seek_timestamp, &pls->cur_seq_no);
1955             /* seek the playlist to the given position without taking
1956              * keyframes into account since this playlist does not have the
1957              * specified stream where we should look for the keyframes */
1958             pls->seek_stream_index = -1;
1959             pls->seek_flags |= AVSEEK_FLAG_ANY;
1960         }
1961     }
1962
1963     c->cur_timestamp = seek_timestamp;
1964
1965     return 0;
1966 }
1967
1968 static int hls_probe(AVProbeData *p)
1969 {
1970     /* Require #EXTM3U at the start, and either one of the ones below
1971      * somewhere for a proper match. */
1972     if (strncmp(p->buf, "#EXTM3U", 7))
1973         return 0;
1974     if (strstr(p->buf, "#EXT-X-STREAM-INF:")     ||
1975         strstr(p->buf, "#EXT-X-TARGETDURATION:") ||
1976         strstr(p->buf, "#EXT-X-MEDIA-SEQUENCE:"))
1977         return AVPROBE_SCORE_MAX;
1978     return 0;
1979 }
1980
1981 #define OFFSET(x) offsetof(HLSContext, x)
1982 #define FLAGS AV_OPT_FLAG_DECODING_PARAM
1983 static const AVOption hls_options[] = {
1984     {"live_start_index", "segment index to start live streams at (negative values are from the end)",
1985         OFFSET(live_start_index), AV_OPT_TYPE_INT, {.i64 = -3}, INT_MIN, INT_MAX, FLAGS},
1986     {NULL}
1987 };
1988
1989 static const AVClass hls_class = {
1990     .class_name = "hls,applehttp",
1991     .item_name  = av_default_item_name,
1992     .option     = hls_options,
1993     .version    = LIBAVUTIL_VERSION_INT,
1994 };
1995
1996 AVInputFormat ff_hls_demuxer = {
1997     .name           = "hls,applehttp",
1998     .long_name      = NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming"),
1999     .priv_class     = &hls_class,
2000     .priv_data_size = sizeof(HLSContext),
2001     .read_probe     = hls_probe,
2002     .read_header    = hls_read_header,
2003     .read_packet    = hls_read_packet,
2004     .read_close     = hls_close,
2005     .read_seek      = hls_read_seek,
2006 };