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