libavformat/hls.c
cd223e0b
 /*
  * Apple HTTP Live Streaming demuxer
  * Copyright (c) 2010 Martin Storsjo
  *
  * This file is part of FFmpeg.
  *
  * FFmpeg is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
  * FFmpeg is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
  * License along with FFmpeg; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 /**
  * @file
  * Apple HTTP Live Streaming demuxer
  * http://tools.ietf.org/html/draft-pantos-http-live-streaming
  */
 
 #include "libavutil/avstring.h"
84465f21
 #include "libavutil/intreadwrite.h"
0ebcdf5c
 #include "libavutil/mathematics.h"
84465f21
 #include "libavutil/opt.h"
d2d67e42
 #include "libavutil/dict.h"
896bb0d7
 #include "libavutil/time.h"
cd223e0b
 #include "avformat.h"
 #include "internal.h"
6cc7f139
 #include "avio_internal.h"
5cec8971
 #include "url.h"
6cc7f139
 
 #define INITIAL_BUFFER_SIZE 32768
cd223e0b
 
 /*
  * An apple http stream consists of a playlist with media segment files,
  * played sequentially. There may be several playlists with the same
  * video content, in different bandwidth variants, that are played in
b22ecbc6
  * parallel (preferably only one bandwidth variant at a time). In this case,
cd223e0b
  * the user supplied the url to a main playlist that only lists the variant
  * playlists.
  *
  * If the main playlist doesn't point at any variants, we still create
  * one anonymous toplevel variant for this, to maintain the structure.
  */
 
84465f21
 enum KeyType {
     KEY_NONE,
     KEY_AES_128,
 };
 
cd223e0b
 struct segment {
c4419103
     int64_t duration;
cd223e0b
     char url[MAX_URL_SIZE];
84465f21
     char key[MAX_URL_SIZE];
     enum KeyType key_type;
     uint8_t iv[16];
cd223e0b
 };
 
 /*
9371d70b
  * Each playlist has its own demuxer. If it currently is active,
471fe57e
  * it has an open AVIOContext too, and potentially an AVPacket
cd223e0b
  * containing the next packet from this stream.
  */
9371d70b
 struct playlist {
cd223e0b
     char url[MAX_URL_SIZE];
6cc7f139
     AVIOContext pb;
     uint8_t* read_buffer;
     URLContext *input;
     AVFormatContext *parent;
     int index;
cd223e0b
     AVFormatContext *ctx;
     AVPacket pkt;
     int stream_offset;
 
d3964da2
     int finished;
c4419103
     int64_t target_duration;
cd223e0b
     int start_seq_no;
     int n_segments;
     struct segment **segments;
6cc7f139
     int needed, cur_needed;
     int cur_seq_no;
     int64_t last_load_time;
84465f21
 
     char key_url[MAX_URL_SIZE];
     uint8_t key[16];
cd223e0b
 };
 
9371d70b
 struct variant {
     int bandwidth;
     int n_playlists;
     struct playlist **playlists;
 };
 
65cd7bf3
 typedef struct HLSContext {
cd223e0b
     int n_variants;
     struct variant **variants;
9371d70b
     int n_playlists;
     struct playlist **playlists;
 
cd223e0b
     int cur_seq_no;
6cc7f139
     int end_of_segment;
     int first_packet;
6f20921d
     int64_t first_timestamp;
811de351
     int64_t seek_timestamp;
     int seek_flags;
9957cdbf
     AVIOInterruptCB *interrupt_callback;
d4e5d8d4
     char *user_agent;                    ///< holds HTTP user agent set as an AVOption to the HTTP protocol context
     char *cookies;                       ///< holds HTTP cookie values set in either the initial response or as an AVOption to the HTTP protocol context
4684539c
     char *headers;                       ///< holds HTTP headers set as an AVOption to the HTTP protocol context
65cd7bf3
 } HLSContext;
cd223e0b
 
471fe57e
 static int read_chomp_line(AVIOContext *s, char *buf, int maxlen)
cd223e0b
 {
     int len = ff_get_line(s, buf, maxlen);
88d55b82
     while (len > 0 && av_isspace(buf[len - 1]))
cd223e0b
         buf[--len] = '\0';
     return len;
 }
 
9371d70b
 static void free_segment_list(struct playlist *pls)
cd223e0b
 {
     int i;
9371d70b
     for (i = 0; i < pls->n_segments; i++)
         av_free(pls->segments[i]);
     av_freep(&pls->segments);
     pls->n_segments = 0;
 }
 
 static void free_playlist_list(HLSContext *c)
 {
     int i;
     for (i = 0; i < c->n_playlists; i++) {
         struct playlist *pls = c->playlists[i];
         free_segment_list(pls);
         av_free_packet(&pls->pkt);
         av_free(pls->pb.buffer);
         if (pls->input)
             ffurl_close(pls->input);
         if (pls->ctx) {
             pls->ctx->pb = NULL;
             avformat_close_input(&pls->ctx);
         }
         av_free(pls);
     }
     av_freep(&c->playlists);
     av_freep(&c->cookies);
     av_freep(&c->user_agent);
     c->n_playlists = 0;
cd223e0b
 }
 
65cd7bf3
 static void free_variant_list(HLSContext *c)
cd223e0b
 {
     int i;
     for (i = 0; i < c->n_variants; i++) {
         struct variant *var = c->variants[i];
9371d70b
         av_freep(&var->playlists);
cd223e0b
         av_free(var);
     }
     av_freep(&c->variants);
     c->n_variants = 0;
 }
 
 /*
  * Used to reset a statically allocated AVPacket to a clean slate,
  * containing no data.
  */
 static void reset_packet(AVPacket *pkt)
 {
     av_init_packet(pkt);
     pkt->data = NULL;
 }
 
9371d70b
 static struct playlist *new_playlist(HLSContext *c, const char *url,
                                      const char *base)
 {
     struct playlist *pls = av_mallocz(sizeof(struct playlist));
     if (!pls)
         return NULL;
     reset_packet(&pls->pkt);
     ff_make_absolute_url(pls->url, sizeof(pls->url), base, url);
     dynarray_add(&c->playlists, &c->n_playlists, pls);
     return pls;
 }
 
65cd7bf3
 static struct variant *new_variant(HLSContext *c, int bandwidth,
cd223e0b
                                    const char *url, const char *base)
 {
9371d70b
     struct variant *var;
     struct playlist *pls;
 
     pls = new_playlist(c, url, base);
     if (!pls)
         return NULL;
 
     var = av_mallocz(sizeof(struct variant));
cd223e0b
     if (!var)
         return NULL;
9371d70b
 
cd223e0b
     var->bandwidth = bandwidth;
     dynarray_add(&c->variants, &c->n_variants, var);
9371d70b
     dynarray_add(&var->playlists, &var->n_playlists, pls);
cd223e0b
     return var;
 }
 
 struct variant_info {
     char bandwidth[20];
 };
 
 static void handle_variant_args(struct variant_info *info, const char *key,
                                 int key_len, char **dest, int *dest_len)
 {
1a172ce6
     if (!strncmp(key, "BANDWIDTH=", key_len)) {
cd223e0b
         *dest     =        info->bandwidth;
         *dest_len = sizeof(info->bandwidth);
     }
 }
 
84465f21
 struct key_info {
      char uri[MAX_URL_SIZE];
      char method[10];
      char iv[35];
 };
 
 static void handle_key_args(struct key_info *info, const char *key,
                             int key_len, char **dest, int *dest_len)
 {
     if (!strncmp(key, "METHOD=", key_len)) {
         *dest     =        info->method;
         *dest_len = sizeof(info->method);
     } else if (!strncmp(key, "URI=", key_len)) {
         *dest     =        info->uri;
         *dest_len = sizeof(info->uri);
     } else if (!strncmp(key, "IV=", key_len)) {
         *dest     =        info->iv;
         *dest_len = sizeof(info->iv);
     }
 }
 
65cd7bf3
 static int parse_playlist(HLSContext *c, const char *url,
9371d70b
                           struct playlist *pls, AVIOContext *in)
cd223e0b
 {
2a5891bb
     int ret = 0, is_segment = 0, is_variant = 0, bandwidth = 0;
c4419103
     int64_t duration = 0;
84465f21
     enum KeyType key_type = KEY_NONE;
     uint8_t iv[16] = "";
     int has_iv = 0;
c41b9842
     char key[MAX_URL_SIZE] = "";
21a2b973
     char line[MAX_URL_SIZE];
cd223e0b
     const char *ptr;
     int close_in = 0;
8c929098
     uint8_t *new_url = NULL;
cd223e0b
 
     if (!in) {
5cdd3b99
         AVDictionary *opts = NULL;
cd223e0b
         close_in = 1;
a9bbf59b
         /* Some HLS servers don't like being sent the range header */
5cdd3b99
         av_dict_set(&opts, "seekable", "0", 0);
d4e5d8d4
 
         // broker prior HTTP options that should be consistent across requests
         av_dict_set(&opts, "user-agent", c->user_agent, 0);
         av_dict_set(&opts, "cookies", c->cookies, 0);
4684539c
         av_dict_set(&opts, "headers", c->headers, 0);
d4e5d8d4
 
5cdd3b99
         ret = avio_open2(&in, url, AVIO_FLAG_READ,
                          c->interrupt_callback, &opts);
         av_dict_free(&opts);
         if (ret < 0)
cd223e0b
             return ret;
     }
 
8c929098
     if (av_opt_get(in, "location", AV_OPT_SEARCH_CHILDREN, &new_url) >= 0)
         url = new_url;
 
cd223e0b
     read_chomp_line(in, line, sizeof(line));
     if (strcmp(line, "#EXTM3U")) {
         ret = AVERROR_INVALIDDATA;
         goto fail;
     }
 
9371d70b
     if (pls) {
         free_segment_list(pls);
         pls->finished = 0;
d3964da2
     }
cd223e0b
     while (!url_feof(in)) {
         read_chomp_line(in, line, sizeof(line));
         if (av_strstart(line, "#EXT-X-STREAM-INF:", &ptr)) {
             struct variant_info info = {{0}};
             is_variant = 1;
             ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_variant_args,
                                &info);
             bandwidth = atoi(info.bandwidth);
84465f21
         } else if (av_strstart(line, "#EXT-X-KEY:", &ptr)) {
             struct key_info info = {{0}};
             ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_key_args,
                                &info);
             key_type = KEY_NONE;
             has_iv = 0;
             if (!strcmp(info.method, "AES-128"))
                 key_type = KEY_AES_128;
             if (!strncmp(info.iv, "0x", 2) || !strncmp(info.iv, "0X", 2)) {
                 ff_hex_to_data(iv, info.iv + 2);
                 has_iv = 1;
             }
             av_strlcpy(key, info.uri, sizeof(key));
cd223e0b
         } else if (av_strstart(line, "#EXT-X-TARGETDURATION:", &ptr)) {
9371d70b
             if (!pls) {
                 if (!new_variant(c, 0, url, NULL)) {
d3964da2
                     ret = AVERROR(ENOMEM);
                     goto fail;
                 }
9371d70b
                 pls = c->playlists[c->n_playlists - 1];
d3964da2
             }
9371d70b
             pls->target_duration = atoi(ptr) * AV_TIME_BASE;
cd223e0b
         } else if (av_strstart(line, "#EXT-X-MEDIA-SEQUENCE:", &ptr)) {
9371d70b
             if (!pls) {
                 if (!new_variant(c, 0, url, NULL)) {
cd223e0b
                     ret = AVERROR(ENOMEM);
                     goto fail;
                 }
9371d70b
                 pls = c->playlists[c->n_playlists - 1];
cd223e0b
             }
9371d70b
             pls->start_seq_no = atoi(ptr);
cd223e0b
         } else if (av_strstart(line, "#EXT-X-ENDLIST", &ptr)) {
9371d70b
             if (pls)
                 pls->finished = 1;
cd223e0b
         } else if (av_strstart(line, "#EXTINF:", &ptr)) {
             is_segment = 1;
c4419103
             duration   = atof(ptr) * AV_TIME_BASE;
cd223e0b
         } else if (av_strstart(line, "#", NULL)) {
             continue;
         } else if (line[0]) {
             if (is_variant) {
                 if (!new_variant(c, bandwidth, line, url)) {
                     ret = AVERROR(ENOMEM);
                     goto fail;
                 }
                 is_variant = 0;
                 bandwidth  = 0;
             }
             if (is_segment) {
                 struct segment *seg;
9371d70b
                 if (!pls) {
                     if (!new_variant(c, 0, url, NULL)) {
cd223e0b
                         ret = AVERROR(ENOMEM);
                         goto fail;
                     }
9371d70b
                     pls = c->playlists[c->n_playlists - 1];
cd223e0b
                 }
                 seg = av_malloc(sizeof(struct segment));
                 if (!seg) {
                     ret = AVERROR(ENOMEM);
                     goto fail;
                 }
                 seg->duration = duration;
84465f21
                 seg->key_type = key_type;
                 if (has_iv) {
                     memcpy(seg->iv, iv, sizeof(iv));
                 } else {
9371d70b
                     int seq = pls->start_seq_no + pls->n_segments;
84465f21
                     memset(seg->iv, 0, sizeof(seg->iv));
                     AV_WB32(seg->iv + 12, seq);
                 }
                 ff_make_absolute_url(seg->key, sizeof(seg->key), url, key);
f1f60f52
                 ff_make_absolute_url(seg->url, sizeof(seg->url), url, line);
9371d70b
                 dynarray_add(&pls->segments, &pls->n_segments, seg);
cd223e0b
                 is_segment = 0;
             }
         }
     }
9371d70b
     if (pls)
         pls->last_load_time = av_gettime();
cd223e0b
 
 fail:
8c929098
     av_free(new_url);
cd223e0b
     if (close_in)
ebb92e07
         avio_close(in);
cd223e0b
     return ret;
 }
 
9371d70b
 static int open_input(HLSContext *c, struct playlist *pls)
84465f21
 {
5cdd3b99
     AVDictionary *opts = NULL;
5846d8a9
     AVDictionary *opts2 = NULL;
5cdd3b99
     int ret;
9371d70b
     struct segment *seg = pls->segments[pls->cur_seq_no - pls->start_seq_no];
d4e5d8d4
 
     // broker prior HTTP options that should be consistent across requests
     av_dict_set(&opts, "user-agent", c->user_agent, 0);
     av_dict_set(&opts, "cookies", c->cookies, 0);
4684539c
     av_dict_set(&opts, "headers", c->headers, 0);
5cdd3b99
     av_dict_set(&opts, "seekable", "0", 0);
d4e5d8d4
 
5846d8a9
     // Same opts for key request (ffurl_open mutilates the opts so it cannot be used twice)
     av_dict_copy(&opts2, opts, 0);
 
84465f21
     if (seg->key_type == KEY_NONE) {
9371d70b
         ret = ffurl_open(&pls->input, seg->url, AVIO_FLAG_READ,
                           &pls->parent->interrupt_callback, &opts);
5cdd3b99
         goto cleanup;
84465f21
     } else if (seg->key_type == KEY_AES_128) {
         char iv[33], key[33], url[MAX_URL_SIZE];
9371d70b
         if (strcmp(seg->key, pls->key_url)) {
84465f21
             URLContext *uc;
6f1b7b39
             if (ffurl_open(&uc, seg->key, AVIO_FLAG_READ,
5846d8a9
                            &pls->parent->interrupt_callback, &opts2) == 0) {
9371d70b
                 if (ffurl_read_complete(uc, pls->key, sizeof(pls->key))
                     != sizeof(pls->key)) {
84465f21
                     av_log(NULL, AV_LOG_ERROR, "Unable to read key file %s\n",
                            seg->key);
                 }
                 ffurl_close(uc);
             } else {
                 av_log(NULL, AV_LOG_ERROR, "Unable to open key file %s\n",
                        seg->key);
             }
9371d70b
             av_strlcpy(pls->key_url, seg->key, sizeof(pls->key_url));
84465f21
         }
         ff_data_to_hex(iv, seg->iv, sizeof(seg->iv), 0);
9371d70b
         ff_data_to_hex(key, pls->key, sizeof(pls->key), 0);
84465f21
         iv[32] = key[32] = '\0';
         if (strstr(seg->url, "://"))
             snprintf(url, sizeof(url), "crypto+%s", seg->url);
         else
             snprintf(url, sizeof(url), "crypto:%s", seg->url);
9371d70b
         if ((ret = ffurl_alloc(&pls->input, url, AVIO_FLAG_READ,
                                &pls->parent->interrupt_callback)) < 0)
5cdd3b99
             goto cleanup;
9371d70b
         av_opt_set(pls->input->priv_data, "key", key, 0);
         av_opt_set(pls->input->priv_data, "iv", iv, 0);
5846d8a9
 
9371d70b
         if ((ret = ffurl_connect(pls->input, &opts)) < 0) {
             ffurl_close(pls->input);
             pls->input = NULL;
5cdd3b99
             goto cleanup;
84465f21
         }
5cdd3b99
         ret = 0;
84465f21
     }
5cdd3b99
     else
       ret = AVERROR(ENOSYS);
 
 cleanup:
     av_dict_free(&opts);
5846d8a9
     av_dict_free(&opts2);
5cdd3b99
     return ret;
84465f21
 }
 
6cc7f139
 static int read_data(void *opaque, uint8_t *buf, int buf_size)
 {
9371d70b
     struct playlist *v = opaque;
65cd7bf3
     HLSContext *c = v->parent->priv_data;
6cc7f139
     int ret, i;
 
 restart:
     if (!v->input) {
356ae5f6
         /* If this is a live stream and the reload interval has elapsed since
9371d70b
          * the last playlist reload, reload the playlists now. */
356ae5f6
         int64_t reload_interval = v->n_segments > 0 ?
                                   v->segments[v->n_segments - 1]->duration :
                                   v->target_duration;
 
617475a9
 reload:
6cc7f139
         if (!v->finished &&
617475a9
             av_gettime() - v->last_load_time >= reload_interval) {
             if ((ret = parse_playlist(c, v->url, v, NULL)) < 0)
6cc7f139
                 return ret;
617475a9
             /* If we need to reload the playlist again below (if
              * there's still no more segments), switch to a reload
              * interval of half the target duration. */
c4419103
             reload_interval = v->target_duration / 2;
617475a9
         }
6cc7f139
         if (v->cur_seq_no < v->start_seq_no) {
             av_log(NULL, AV_LOG_WARNING,
                    "skipping %d segments ahead, expired from playlists\n",
                    v->start_seq_no - v->cur_seq_no);
             v->cur_seq_no = v->start_seq_no;
         }
         if (v->cur_seq_no >= v->start_seq_no + v->n_segments) {
             if (v->finished)
                 return AVERROR_EOF;
356ae5f6
             while (av_gettime() - v->last_load_time < reload_interval) {
9957cdbf
                 if (ff_check_interrupt(c->interrupt_callback))
6cc7f139
                     return AVERROR_EXIT;
896bb0d7
                 av_usleep(100*1000);
6cc7f139
             }
             /* Enough time has elapsed since the last reload */
             goto reload;
         }
 
d4e5d8d4
         ret = open_input(c, v);
6cc7f139
         if (ret < 0)
             return ret;
     }
a6aa7a1a
     ret = ffurl_read(v->input, buf, buf_size);
6cc7f139
     if (ret > 0)
         return ret;
a6aa7a1a
     ffurl_close(v->input);
6cc7f139
     v->input = NULL;
     v->cur_seq_no++;
 
     c->end_of_segment = 1;
     c->cur_seq_no = v->cur_seq_no;
 
cdd2d73d
     if (v->ctx && v->ctx->nb_streams &&
         v->parent->nb_streams >= v->stream_offset + v->ctx->nb_streams) {
a92a7ddc
         v->needed = 0;
         for (i = v->stream_offset; i < v->stream_offset + v->ctx->nb_streams;
              i++) {
             if (v->parent->streams[i]->discard < AVDISCARD_ALL)
                 v->needed = 1;
         }
6cc7f139
     }
     if (!v->needed) {
9371d70b
         av_log(v->parent, AV_LOG_INFO, "No longer receiving playlist %d\n",
6cc7f139
                v->index);
         return AVERROR_EOF;
     }
     goto restart;
 }
 
9371d70b
 static int playlist_in_multiple_variants(HLSContext *c, struct playlist *pls)
 {
     int variant_count = 0;
     int i, j;
 
     for (i = 0; i < c->n_variants && variant_count < 2; i++) {
         struct variant *v = c->variants[i];
 
         for (j = 0; j < v->n_playlists; j++) {
             if (v->playlists[j] == pls) {
                 variant_count++;
                 break;
             }
         }
     }
 
     return variant_count >= 2;
 }
 
65cd7bf3
 static int hls_read_header(AVFormatContext *s)
cd223e0b
 {
db6e2e84
     URLContext *u = (s->flags & AVFMT_FLAG_CUSTOM_IO) ? NULL : s->pb->opaque;
65cd7bf3
     HLSContext *c = s->priv_data;
cd223e0b
     int ret = 0, i, j, stream_offset = 0;
 
9957cdbf
     c->interrupt_callback = &s->interrupt_callback;
 
d4e5d8d4
     // if the URL context is good, read important options we must broker later
665f2d43
     if (u && u->prot->priv_data_class) {
d4e5d8d4
         // get the previous user agent & set back to null if string size is zero
665f2d43
         av_freep(&c->user_agent);
d4e5d8d4
         av_opt_get(u->priv_data, "user-agent", 0, (uint8_t**)&(c->user_agent));
665f2d43
         if (c->user_agent && !strlen(c->user_agent))
d4e5d8d4
             av_freep(&c->user_agent);
 
         // get the previous cookies & set back to null if string size is zero
665f2d43
         av_freep(&c->cookies);
d4e5d8d4
         av_opt_get(u->priv_data, "cookies", 0, (uint8_t**)&(c->cookies));
665f2d43
         if (c->cookies && !strlen(c->cookies))
d4e5d8d4
             av_freep(&c->cookies);
4684539c
 
         // get the previous headers & set back to null if string size is zero
         av_freep(&c->headers);
         av_opt_get(u->priv_data, "headers", 0, (uint8_t**)&(c->headers));
         if (c->headers && !strlen(c->headers))
             av_freep(&c->headers);
d4e5d8d4
     }
 
cd223e0b
     if ((ret = parse_playlist(c, s->filename, NULL, s->pb)) < 0)
         goto fail;
 
     if (c->n_variants == 0) {
         av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
         ret = AVERROR_EOF;
         goto fail;
     }
9371d70b
     /* If the playlist only contained playlists (Master Playlist),
      * parse each individual playlist. */
     if (c->n_playlists > 1 || c->playlists[0]->n_segments == 0) {
         for (i = 0; i < c->n_playlists; i++) {
             struct playlist *pls = c->playlists[i];
             if ((ret = parse_playlist(c, pls->url, pls, NULL)) < 0)
cd223e0b
                 goto fail;
         }
     }
 
9371d70b
     if (c->variants[0]->playlists[0]->n_segments == 0) {
cd223e0b
         av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
         ret = AVERROR_EOF;
         goto fail;
     }
 
     /* If this isn't a live stream, calculate the total duration of the
      * stream. */
9371d70b
     if (c->variants[0]->playlists[0]->finished) {
419a3d8a
         int64_t duration = 0;
9371d70b
         for (i = 0; i < c->variants[0]->playlists[0]->n_segments; i++)
             duration += c->variants[0]->playlists[0]->segments[i]->duration;
419a3d8a
         s->duration = duration;
cd223e0b
     }
 
9371d70b
     /* Open the demuxer for each playlist */
     for (i = 0; i < c->n_playlists; i++) {
         struct playlist *pls = c->playlists[i];
6cc7f139
         AVInputFormat *in_fmt = NULL;
c110cbf6
 
9371d70b
         if (pls->n_segments == 0)
cd223e0b
             continue;
6cc7f139
 
9371d70b
         if (!(pls->ctx = avformat_alloc_context())) {
603b8bc2
             ret = AVERROR(ENOMEM);
             goto fail;
         }
 
9371d70b
         pls->index  = i;
         pls->needed = 1;
         pls->parent = s;
6cc7f139
 
         /* If this is a live stream with more than 3 segments, start at the
          * third last segment. */
9371d70b
         pls->cur_seq_no = pls->start_seq_no;
         if (!pls->finished && pls->n_segments > 3)
             pls->cur_seq_no = pls->start_seq_no + pls->n_segments - 3;
6cc7f139
 
9371d70b
         pls->read_buffer = av_malloc(INITIAL_BUFFER_SIZE);
         ffio_init_context(&pls->pb, pls->read_buffer, INITIAL_BUFFER_SIZE, 0, pls,
6cc7f139
                           read_data, NULL, NULL);
9371d70b
         pls->pb.seekable = 0;
         ret = av_probe_input_buffer(&pls->pb, &in_fmt, pls->segments[0]->url,
6cc7f139
                                     NULL, 0, 0);
115a5730
         if (ret < 0) {
             /* Free the ctx - it isn't initialized properly at this point,
              * so avformat_close_input shouldn't be called. If
              * avformat_open_input fails below, it frees and zeros the
              * context, so it doesn't need any special treatment like this. */
9371d70b
             av_log(s, AV_LOG_ERROR, "Error when loading first segment '%s'\n", pls->segments[0]->url);
             avformat_free_context(pls->ctx);
             pls->ctx = NULL;
6cc7f139
             goto fail;
115a5730
         }
9371d70b
         pls->ctx->pb       = &pls->pb;
         pls->stream_offset = stream_offset;
         ret = avformat_open_input(&pls->ctx, pls->segments[0]->url, in_fmt, NULL);
cd223e0b
         if (ret < 0)
             goto fail;
9696740a
 
9371d70b
         pls->ctx->ctx_flags &= ~AVFMTCTX_NOHEADER;
         ret = avformat_find_stream_info(pls->ctx, NULL);
30051224
         if (ret < 0)
             goto fail;
23db5418
 
9371d70b
         /* Create new AVStreams for each stream in this playlist */
         for (j = 0; j < pls->ctx->nb_streams; j++) {
84ad31ff
             AVStream *st = avformat_new_stream(s, NULL);
9371d70b
             AVStream *ist = pls->ctx->streams[j];
cd223e0b
             if (!st) {
                 ret = AVERROR(ENOMEM);
                 goto fail;
             }
84ad31ff
             st->id = i;
a12a618a
             avpriv_set_pts_info(st, ist->pts_wrap_bits, ist->time_base.num, ist->time_base.den);
9371d70b
             avcodec_copy_context(st->codec, pls->ctx->streams[j]->codec);
         }
 
         stream_offset += pls->ctx->nb_streams;
     }
 
     /* Create a program for each variant */
     for (i = 0; i < c->n_variants; i++) {
         struct variant *v = c->variants[i];
         char bitrate_str[20];
         AVProgram *program;
 
         snprintf(bitrate_str, sizeof(bitrate_str), "%d", v->bandwidth);
 
         program = av_new_program(s, i);
         if (!program)
             goto fail;
         av_dict_set(&program->metadata, "variant_bitrate", bitrate_str, 0);
 
         for (j = 0; j < v->n_playlists; j++) {
             struct playlist *pls = v->playlists[j];
             int is_shared = playlist_in_multiple_variants(c, pls);
             int k;
 
             for (k = 0; k < pls->ctx->nb_streams; k++) {
                 struct AVStream *st = s->streams[pls->stream_offset + k];
 
                 ff_program_add_stream_index(s, i, pls->stream_offset + k);
 
                 /* Set variant_bitrate for streams unique to this variant */
                 if (!is_shared && v->bandwidth)
                     av_dict_set(&st->metadata, "variant_bitrate", bitrate_str, 0);
             }
cd223e0b
         }
     }
 
6cc7f139
     c->first_packet = 1;
6f20921d
     c->first_timestamp = AV_NOPTS_VALUE;
2b3d041c
     c->seek_timestamp  = AV_NOPTS_VALUE;
cd223e0b
 
     return 0;
 fail:
9371d70b
     free_playlist_list(c);
cd223e0b
     free_variant_list(c);
     return ret;
 }
 
6cc7f139
 static int recheck_discard_flags(AVFormatContext *s, int first)
cd223e0b
 {
65cd7bf3
     HLSContext *c = s->priv_data;
6cc7f139
     int i, changed = 0;
cd223e0b
 
6cc7f139
     /* Check if any new streams are needed */
9371d70b
     for (i = 0; i < c->n_playlists; i++)
         c->playlists[i]->cur_needed = 0;
6cc7f139
 
     for (i = 0; i < s->nb_streams; i++) {
         AVStream *st = s->streams[i];
9371d70b
         struct playlist *pls = c->playlists[s->streams[i]->id];
6cc7f139
         if (st->discard < AVDISCARD_ALL)
9371d70b
             pls->cur_needed = 1;
cd223e0b
     }
9371d70b
     for (i = 0; i < c->n_playlists; i++) {
         struct playlist *pls = c->playlists[i];
         if (pls->cur_needed && !pls->needed) {
             pls->needed = 1;
6cc7f139
             changed = 1;
9371d70b
             pls->cur_seq_no = c->cur_seq_no;
             pls->pb.eof_reached = 0;
             av_log(s, AV_LOG_INFO, "Now receiving playlist %d\n", i);
         } else if (first && !pls->cur_needed && pls->needed) {
             if (pls->input)
                 ffurl_close(pls->input);
             pls->input = NULL;
             pls->needed = 0;
6cc7f139
             changed = 1;
9371d70b
             av_log(s, AV_LOG_INFO, "No longer receiving playlist %d\n", i);
cd223e0b
         }
     }
6cc7f139
     return changed;
cd223e0b
 }
 
65cd7bf3
 static int hls_read_packet(AVFormatContext *s, AVPacket *pkt)
cd223e0b
 {
65cd7bf3
     HLSContext *c = s->priv_data;
9371d70b
     int ret, i, minplaylist = -1;
cd223e0b
 
6cc7f139
     if (c->first_packet) {
         recheck_discard_flags(s, 1);
         c->first_packet = 0;
cd223e0b
     }
6cc7f139
 
cd223e0b
 start:
6cc7f139
     c->end_of_segment = 0;
9371d70b
     for (i = 0; i < c->n_playlists; i++) {
         struct playlist *pls = c->playlists[i];
         /* Make sure we've got one buffered packet from each open playlist
cd223e0b
          * stream */
9371d70b
         if (pls->needed && !pls->pkt.data) {
811de351
             while (1) {
                 int64_t ts_diff;
2b3d041c
                 AVStream *st;
9371d70b
                 ret = av_read_frame(pls->ctx, &pls->pkt);
811de351
                 if (ret < 0) {
9371d70b
                     if (!url_feof(&pls->pb) && ret != AVERROR_EOF)
811de351
                         return ret;
9371d70b
                     reset_packet(&pls->pkt);
2b3d041c
                     break;
811de351
                 } else {
e1d5b244
                     if (c->first_timestamp == AV_NOPTS_VALUE &&
9371d70b
                         pls->pkt.dts       != AV_NOPTS_VALUE)
                         c->first_timestamp = av_rescale_q(pls->pkt.dts,
                             pls->ctx->streams[pls->pkt.stream_index]->time_base,
e1d5b244
                             AV_TIME_BASE_Q);
811de351
                 }
 
                 if (c->seek_timestamp == AV_NOPTS_VALUE)
                     break;
 
9371d70b
                 if (pls->pkt.dts == AV_NOPTS_VALUE) {
811de351
                     c->seek_timestamp = AV_NOPTS_VALUE;
                     break;
                 }
 
9371d70b
                 st = pls->ctx->streams[pls->pkt.stream_index];
                 ts_diff = av_rescale_rnd(pls->pkt.dts, AV_TIME_BASE,
2b3d041c
                                          st->time_base.den, AV_ROUND_DOWN) -
                           c->seek_timestamp;
                 if (ts_diff >= 0 && (c->seek_flags  & AVSEEK_FLAG_ANY ||
9371d70b
                                      pls->pkt.flags & AV_PKT_FLAG_KEY)) {
2b3d041c
                     c->seek_timestamp = AV_NOPTS_VALUE;
                     break;
811de351
                 }
9371d70b
                 av_free_packet(&pls->pkt);
                 reset_packet(&pls->pkt);
cd223e0b
             }
         }
eb33ba04
         /* Check if this stream still is on an earlier segment number, or
          * has the packet with the lowest dts */
9371d70b
         if (pls->pkt.data) {
             struct playlist *minpls = minplaylist < 0 ?
                                      NULL : c->playlists[minplaylist];
             if (minplaylist < 0 || pls->cur_seq_no < minpls->cur_seq_no) {
                 minplaylist = i;
             } else if (pls->cur_seq_no == minpls->cur_seq_no) {
                 int64_t dts     =    pls->pkt.dts;
                 int64_t mindts  = minpls->pkt.dts;
                 AVStream *st    =    pls->ctx->streams[pls->pkt.stream_index];
                 AVStream *minst = minpls->ctx->streams[minpls->pkt.stream_index];
3ac754b9
 
9d64f236
                 if (dts == AV_NOPTS_VALUE) {
9371d70b
                     minplaylist = i;
9d64f236
                 } else if (mindts != AV_NOPTS_VALUE) {
                     if (st->start_time    != AV_NOPTS_VALUE)
                         dts    -= st->start_time;
                     if (minst->start_time != AV_NOPTS_VALUE)
                         mindts -= minst->start_time;
 
                     if (av_compare_ts(dts, st->time_base,
                                       mindts, minst->time_base) < 0)
9371d70b
                         minplaylist = i;
9d64f236
                 }
3ac754b9
             }
cd223e0b
         }
     }
6cc7f139
     if (c->end_of_segment) {
         if (recheck_discard_flags(s, 0))
             goto start;
     }
cd223e0b
     /* If we got a packet, return it */
9371d70b
     if (minplaylist >= 0) {
         *pkt = c->playlists[minplaylist]->pkt;
         pkt->stream_index += c->playlists[minplaylist]->stream_offset;
         reset_packet(&c->playlists[minplaylist]->pkt);
cd223e0b
         return 0;
     }
6cc7f139
     return AVERROR_EOF;
cd223e0b
 }
 
65cd7bf3
 static int hls_close(AVFormatContext *s)
cd223e0b
 {
65cd7bf3
     HLSContext *c = s->priv_data;
cd223e0b
 
9371d70b
     free_playlist_list(c);
cd223e0b
     free_variant_list(c);
     return 0;
 }
 
65cd7bf3
 static int hls_read_seek(AVFormatContext *s, int stream_index,
cd223e0b
                                int64_t timestamp, int flags)
 {
65cd7bf3
     HLSContext *c = s->priv_data;
6cc7f139
     int i, j, ret;
cd223e0b
 
9371d70b
     if ((flags & AVSEEK_FLAG_BYTE) || !c->variants[0]->playlists[0]->finished)
cd223e0b
         return AVERROR(ENOSYS);
 
2b3d041c
     c->seek_flags     = flags;
     c->seek_timestamp = stream_index < 0 ? timestamp :
                         av_rescale_rnd(timestamp, AV_TIME_BASE,
                                        s->streams[stream_index]->time_base.den,
                                        flags & AVSEEK_FLAG_BACKWARD ?
                                        AV_ROUND_DOWN : AV_ROUND_UP);
c4419103
     timestamp = av_rescale_rnd(timestamp, AV_TIME_BASE, stream_index >= 0 ?
0d8a33b1
                                s->streams[stream_index]->time_base.den :
                                AV_TIME_BASE, flags & AVSEEK_FLAG_BACKWARD ?
                                AV_ROUND_DOWN : AV_ROUND_UP);
811de351
     if (s->duration < c->seek_timestamp) {
         c->seek_timestamp = AV_NOPTS_VALUE;
         return AVERROR(EIO);
     }
 
0d8a33b1
     ret = AVERROR(EIO);
9371d70b
     for (i = 0; i < c->n_playlists; i++) {
0d8a33b1
         /* Reset reading */
9371d70b
         struct playlist *pls = c->playlists[i];
c4419103
         int64_t pos = c->first_timestamp == AV_NOPTS_VALUE ?
                       0 : c->first_timestamp;
9371d70b
         if (pls->input) {
             ffurl_close(pls->input);
             pls->input = NULL;
cd223e0b
         }
9371d70b
         av_free_packet(&pls->pkt);
         reset_packet(&pls->pkt);
         pls->pb.eof_reached = 0;
a4f97be1
         /* Clear any buffered data */
9371d70b
         pls->pb.buf_end = pls->pb.buf_ptr = pls->pb.buffer;
a4f97be1
         /* Reset the pos, to let the mpegts demuxer know we've seeked. */
9371d70b
         pls->pb.pos = 0;
cd223e0b
 
6cc7f139
         /* Locate the segment that contains the target timestamp */
9371d70b
         for (j = 0; j < pls->n_segments; j++) {
6cc7f139
             if (timestamp >= pos &&
9371d70b
                 timestamp < pos + pls->segments[j]->duration) {
                 pls->cur_seq_no = pls->start_seq_no + j;
6cc7f139
                 ret = 0;
                 break;
             }
9371d70b
             pos += pls->segments[j]->duration;
cd223e0b
         }
2b3d041c
         if (ret)
811de351
             c->seek_timestamp = AV_NOPTS_VALUE;
cd223e0b
     }
6cc7f139
     return ret;
cd223e0b
 }
 
65cd7bf3
 static int hls_probe(AVProbeData *p)
cd223e0b
 {
     /* Require #EXTM3U at the start, and either one of the ones below
      * somewhere for a proper match. */
     if (strncmp(p->buf, "#EXTM3U", 7))
         return 0;
     if (strstr(p->buf, "#EXT-X-STREAM-INF:")     ||
         strstr(p->buf, "#EXT-X-TARGETDURATION:") ||
         strstr(p->buf, "#EXT-X-MEDIA-SEQUENCE:"))
         return AVPROBE_SCORE_MAX;
     return 0;
 }
 
2772258a
 AVInputFormat ff_hls_demuxer = {
c1df37e5
     .name           = "hls,applehttp",
6774247a
     .long_name      = NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming"),
65cd7bf3
     .priv_data_size = sizeof(HLSContext),
     .read_probe     = hls_probe,
     .read_header    = hls_read_header,
     .read_packet    = hls_read_packet,
     .read_close     = hls_close,
     .read_seek      = hls_read_seek,
cd223e0b
 };