]> git.sesse.net Git - ffmpeg/blob - libavformat/hls.c
Merge commit '2142b2efcd631db05e4c7c26785e337ecf1258ff'
[ffmpeg] / libavformat / hls.c
1 /*
2  * Apple HTTP Live Streaming demuxer
3  * Copyright (c) 2010 Martin Storsjo
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 /**
23  * @file
24  * Apple HTTP Live Streaming demuxer
25  * http://tools.ietf.org/html/draft-pantos-http-live-streaming
26  */
27
28 #include "libavutil/avstring.h"
29 #include "libavutil/intreadwrite.h"
30 #include "libavutil/mathematics.h"
31 #include "libavutil/opt.h"
32 #include "libavutil/dict.h"
33 #include "libavutil/time.h"
34 #include "avformat.h"
35 #include "internal.h"
36 #include "avio_internal.h"
37 #include "url.h"
38
39 #define INITIAL_BUFFER_SIZE 32768
40
41 /*
42  * An apple http stream consists of a playlist with media segment files,
43  * played sequentially. There may be several playlists with the same
44  * video content, in different bandwidth variants, that are played in
45  * parallel (preferably only one bandwidth variant at a time). In this case,
46  * the user supplied the url to a main playlist that only lists the variant
47  * playlists.
48  *
49  * If the main playlist doesn't point at any variants, we still create
50  * one anonymous toplevel variant for this, to maintain the structure.
51  */
52
53 enum KeyType {
54     KEY_NONE,
55     KEY_AES_128,
56 };
57
58 struct segment {
59     int64_t duration;
60     char url[MAX_URL_SIZE];
61     char key[MAX_URL_SIZE];
62     enum KeyType key_type;
63     uint8_t iv[16];
64 };
65
66 /*
67  * Each playlist has its own demuxer. If it currently is active,
68  * it has an open AVIOContext too, and potentially an AVPacket
69  * containing the next packet from this stream.
70  */
71 struct playlist {
72     char url[MAX_URL_SIZE];
73     AVIOContext pb;
74     uint8_t* read_buffer;
75     URLContext *input;
76     AVFormatContext *parent;
77     int index;
78     AVFormatContext *ctx;
79     AVPacket pkt;
80     int stream_offset;
81
82     int finished;
83     int64_t target_duration;
84     int start_seq_no;
85     int n_segments;
86     struct segment **segments;
87     int needed, cur_needed;
88     int cur_seq_no;
89     int64_t last_load_time;
90
91     char key_url[MAX_URL_SIZE];
92     uint8_t key[16];
93 };
94
95 struct variant {
96     int bandwidth;
97     int n_playlists;
98     struct playlist **playlists;
99 };
100
101 typedef struct HLSContext {
102     int n_variants;
103     struct variant **variants;
104     int n_playlists;
105     struct playlist **playlists;
106
107     int cur_seq_no;
108     int end_of_segment;
109     int first_packet;
110     int64_t first_timestamp;
111     int64_t seek_timestamp;
112     int seek_flags;
113     AVIOInterruptCB *interrupt_callback;
114     char *user_agent;                    ///< holds HTTP user agent set as an AVOption to the HTTP protocol context
115     char *cookies;                       ///< holds HTTP cookie values set in either the initial response or as an AVOption to the HTTP protocol context
116     char *headers;                       ///< holds HTTP headers set as an AVOption to the HTTP protocol context
117 } HLSContext;
118
119 static int read_chomp_line(AVIOContext *s, char *buf, int maxlen)
120 {
121     int len = ff_get_line(s, buf, maxlen);
122     while (len > 0 && av_isspace(buf[len - 1]))
123         buf[--len] = '\0';
124     return len;
125 }
126
127 static void free_segment_list(struct playlist *pls)
128 {
129     int i;
130     for (i = 0; i < pls->n_segments; i++)
131         av_free(pls->segments[i]);
132     av_freep(&pls->segments);
133     pls->n_segments = 0;
134 }
135
136 static void free_playlist_list(HLSContext *c)
137 {
138     int i;
139     for (i = 0; i < c->n_playlists; i++) {
140         struct playlist *pls = c->playlists[i];
141         free_segment_list(pls);
142         av_free_packet(&pls->pkt);
143         av_free(pls->pb.buffer);
144         if (pls->input)
145             ffurl_close(pls->input);
146         if (pls->ctx) {
147             pls->ctx->pb = NULL;
148             avformat_close_input(&pls->ctx);
149         }
150         av_free(pls);
151     }
152     av_freep(&c->playlists);
153     av_freep(&c->cookies);
154     av_freep(&c->user_agent);
155     c->n_playlists = 0;
156 }
157
158 static void free_variant_list(HLSContext *c)
159 {
160     int i;
161     for (i = 0; i < c->n_variants; i++) {
162         struct variant *var = c->variants[i];
163         av_freep(&var->playlists);
164         av_free(var);
165     }
166     av_freep(&c->variants);
167     c->n_variants = 0;
168 }
169
170 /*
171  * Used to reset a statically allocated AVPacket to a clean slate,
172  * containing no data.
173  */
174 static void reset_packet(AVPacket *pkt)
175 {
176     av_init_packet(pkt);
177     pkt->data = NULL;
178 }
179
180 static struct playlist *new_playlist(HLSContext *c, const char *url,
181                                      const char *base)
182 {
183     struct playlist *pls = av_mallocz(sizeof(struct playlist));
184     if (!pls)
185         return NULL;
186     reset_packet(&pls->pkt);
187     ff_make_absolute_url(pls->url, sizeof(pls->url), base, url);
188     dynarray_add(&c->playlists, &c->n_playlists, pls);
189     return pls;
190 }
191
192 static struct variant *new_variant(HLSContext *c, int bandwidth,
193                                    const char *url, const char *base)
194 {
195     struct variant *var;
196     struct playlist *pls;
197
198     pls = new_playlist(c, url, base);
199     if (!pls)
200         return NULL;
201
202     var = av_mallocz(sizeof(struct variant));
203     if (!var)
204         return NULL;
205
206     var->bandwidth = bandwidth;
207     dynarray_add(&c->variants, &c->n_variants, var);
208     dynarray_add(&var->playlists, &var->n_playlists, pls);
209     return var;
210 }
211
212 struct variant_info {
213     char bandwidth[20];
214 };
215
216 static void handle_variant_args(struct variant_info *info, const char *key,
217                                 int key_len, char **dest, int *dest_len)
218 {
219     if (!strncmp(key, "BANDWIDTH=", key_len)) {
220         *dest     =        info->bandwidth;
221         *dest_len = sizeof(info->bandwidth);
222     }
223 }
224
225 struct key_info {
226      char uri[MAX_URL_SIZE];
227      char method[10];
228      char iv[35];
229 };
230
231 static void handle_key_args(struct key_info *info, const char *key,
232                             int key_len, char **dest, int *dest_len)
233 {
234     if (!strncmp(key, "METHOD=", key_len)) {
235         *dest     =        info->method;
236         *dest_len = sizeof(info->method);
237     } else if (!strncmp(key, "URI=", key_len)) {
238         *dest     =        info->uri;
239         *dest_len = sizeof(info->uri);
240     } else if (!strncmp(key, "IV=", key_len)) {
241         *dest     =        info->iv;
242         *dest_len = sizeof(info->iv);
243     }
244 }
245
246 static int parse_playlist(HLSContext *c, const char *url,
247                           struct playlist *pls, AVIOContext *in)
248 {
249     int ret = 0, is_segment = 0, is_variant = 0, bandwidth = 0;
250     int64_t duration = 0;
251     enum KeyType key_type = KEY_NONE;
252     uint8_t iv[16] = "";
253     int has_iv = 0;
254     char key[MAX_URL_SIZE] = "";
255     char line[MAX_URL_SIZE];
256     const char *ptr;
257     int close_in = 0;
258     uint8_t *new_url = NULL;
259
260     if (!in) {
261         AVDictionary *opts = NULL;
262         close_in = 1;
263         /* Some HLS servers don't like being sent the range header */
264         av_dict_set(&opts, "seekable", "0", 0);
265
266         // broker prior HTTP options that should be consistent across requests
267         av_dict_set(&opts, "user-agent", c->user_agent, 0);
268         av_dict_set(&opts, "cookies", c->cookies, 0);
269         av_dict_set(&opts, "headers", c->headers, 0);
270
271         ret = avio_open2(&in, url, AVIO_FLAG_READ,
272                          c->interrupt_callback, &opts);
273         av_dict_free(&opts);
274         if (ret < 0)
275             return ret;
276     }
277
278     if (av_opt_get(in, "location", AV_OPT_SEARCH_CHILDREN, &new_url) >= 0)
279         url = new_url;
280
281     read_chomp_line(in, line, sizeof(line));
282     if (strcmp(line, "#EXTM3U")) {
283         ret = AVERROR_INVALIDDATA;
284         goto fail;
285     }
286
287     if (pls) {
288         free_segment_list(pls);
289         pls->finished = 0;
290     }
291     while (!url_feof(in)) {
292         read_chomp_line(in, line, sizeof(line));
293         if (av_strstart(line, "#EXT-X-STREAM-INF:", &ptr)) {
294             struct variant_info info = {{0}};
295             is_variant = 1;
296             ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_variant_args,
297                                &info);
298             bandwidth = atoi(info.bandwidth);
299         } else if (av_strstart(line, "#EXT-X-KEY:", &ptr)) {
300             struct key_info info = {{0}};
301             ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_key_args,
302                                &info);
303             key_type = KEY_NONE;
304             has_iv = 0;
305             if (!strcmp(info.method, "AES-128"))
306                 key_type = KEY_AES_128;
307             if (!strncmp(info.iv, "0x", 2) || !strncmp(info.iv, "0X", 2)) {
308                 ff_hex_to_data(iv, info.iv + 2);
309                 has_iv = 1;
310             }
311             av_strlcpy(key, info.uri, sizeof(key));
312         } else if (av_strstart(line, "#EXT-X-TARGETDURATION:", &ptr)) {
313             if (!pls) {
314                 if (!new_variant(c, 0, url, NULL)) {
315                     ret = AVERROR(ENOMEM);
316                     goto fail;
317                 }
318                 pls = c->playlists[c->n_playlists - 1];
319             }
320             pls->target_duration = atoi(ptr) * AV_TIME_BASE;
321         } else if (av_strstart(line, "#EXT-X-MEDIA-SEQUENCE:", &ptr)) {
322             if (!pls) {
323                 if (!new_variant(c, 0, url, NULL)) {
324                     ret = AVERROR(ENOMEM);
325                     goto fail;
326                 }
327                 pls = c->playlists[c->n_playlists - 1];
328             }
329             pls->start_seq_no = atoi(ptr);
330         } else if (av_strstart(line, "#EXT-X-ENDLIST", &ptr)) {
331             if (pls)
332                 pls->finished = 1;
333         } else if (av_strstart(line, "#EXTINF:", &ptr)) {
334             is_segment = 1;
335             duration   = atof(ptr) * AV_TIME_BASE;
336         } else if (av_strstart(line, "#", NULL)) {
337             continue;
338         } else if (line[0]) {
339             if (is_variant) {
340                 if (!new_variant(c, bandwidth, line, url)) {
341                     ret = AVERROR(ENOMEM);
342                     goto fail;
343                 }
344                 is_variant = 0;
345                 bandwidth  = 0;
346             }
347             if (is_segment) {
348                 struct segment *seg;
349                 if (!pls) {
350                     if (!new_variant(c, 0, url, NULL)) {
351                         ret = AVERROR(ENOMEM);
352                         goto fail;
353                     }
354                     pls = c->playlists[c->n_playlists - 1];
355                 }
356                 seg = av_malloc(sizeof(struct segment));
357                 if (!seg) {
358                     ret = AVERROR(ENOMEM);
359                     goto fail;
360                 }
361                 seg->duration = duration;
362                 seg->key_type = key_type;
363                 if (has_iv) {
364                     memcpy(seg->iv, iv, sizeof(iv));
365                 } else {
366                     int seq = pls->start_seq_no + pls->n_segments;
367                     memset(seg->iv, 0, sizeof(seg->iv));
368                     AV_WB32(seg->iv + 12, seq);
369                 }
370                 ff_make_absolute_url(seg->key, sizeof(seg->key), url, key);
371                 ff_make_absolute_url(seg->url, sizeof(seg->url), url, line);
372                 dynarray_add(&pls->segments, &pls->n_segments, seg);
373                 is_segment = 0;
374             }
375         }
376     }
377     if (pls)
378         pls->last_load_time = av_gettime();
379
380 fail:
381     av_free(new_url);
382     if (close_in)
383         avio_close(in);
384     return ret;
385 }
386
387 static int open_input(HLSContext *c, struct playlist *pls)
388 {
389     AVDictionary *opts = NULL;
390     AVDictionary *opts2 = NULL;
391     int ret;
392     struct segment *seg = pls->segments[pls->cur_seq_no - pls->start_seq_no];
393
394     // broker prior HTTP options that should be consistent across requests
395     av_dict_set(&opts, "user-agent", c->user_agent, 0);
396     av_dict_set(&opts, "cookies", c->cookies, 0);
397     av_dict_set(&opts, "headers", c->headers, 0);
398     av_dict_set(&opts, "seekable", "0", 0);
399
400     // Same opts for key request (ffurl_open mutilates the opts so it cannot be used twice)
401     av_dict_copy(&opts2, opts, 0);
402
403     if (seg->key_type == KEY_NONE) {
404         ret = ffurl_open(&pls->input, seg->url, AVIO_FLAG_READ,
405                           &pls->parent->interrupt_callback, &opts);
406         goto cleanup;
407     } else if (seg->key_type == KEY_AES_128) {
408         char iv[33], key[33], url[MAX_URL_SIZE];
409         if (strcmp(seg->key, pls->key_url)) {
410             URLContext *uc;
411             if (ffurl_open(&uc, seg->key, AVIO_FLAG_READ,
412                            &pls->parent->interrupt_callback, &opts2) == 0) {
413                 if (ffurl_read_complete(uc, pls->key, sizeof(pls->key))
414                     != sizeof(pls->key)) {
415                     av_log(NULL, AV_LOG_ERROR, "Unable to read key file %s\n",
416                            seg->key);
417                 }
418                 ffurl_close(uc);
419             } else {
420                 av_log(NULL, AV_LOG_ERROR, "Unable to open key file %s\n",
421                        seg->key);
422             }
423             av_strlcpy(pls->key_url, seg->key, sizeof(pls->key_url));
424         }
425         ff_data_to_hex(iv, seg->iv, sizeof(seg->iv), 0);
426         ff_data_to_hex(key, pls->key, sizeof(pls->key), 0);
427         iv[32] = key[32] = '\0';
428         if (strstr(seg->url, "://"))
429             snprintf(url, sizeof(url), "crypto+%s", seg->url);
430         else
431             snprintf(url, sizeof(url), "crypto:%s", seg->url);
432         if ((ret = ffurl_alloc(&pls->input, url, AVIO_FLAG_READ,
433                                &pls->parent->interrupt_callback)) < 0)
434             goto cleanup;
435         av_opt_set(pls->input->priv_data, "key", key, 0);
436         av_opt_set(pls->input->priv_data, "iv", iv, 0);
437
438         if ((ret = ffurl_connect(pls->input, &opts)) < 0) {
439             ffurl_close(pls->input);
440             pls->input = NULL;
441             goto cleanup;
442         }
443         ret = 0;
444     }
445     else
446       ret = AVERROR(ENOSYS);
447
448 cleanup:
449     av_dict_free(&opts);
450     av_dict_free(&opts2);
451     return ret;
452 }
453
454 static int read_data(void *opaque, uint8_t *buf, int buf_size)
455 {
456     struct playlist *v = opaque;
457     HLSContext *c = v->parent->priv_data;
458     int ret, i;
459
460 restart:
461     if (!v->input) {
462         /* If this is a live stream and the reload interval has elapsed since
463          * the last playlist reload, reload the playlists now. */
464         int64_t reload_interval = v->n_segments > 0 ?
465                                   v->segments[v->n_segments - 1]->duration :
466                                   v->target_duration;
467
468 reload:
469         if (!v->finished &&
470             av_gettime() - v->last_load_time >= reload_interval) {
471             if ((ret = parse_playlist(c, v->url, v, NULL)) < 0)
472                 return ret;
473             /* If we need to reload the playlist again below (if
474              * there's still no more segments), switch to a reload
475              * interval of half the target duration. */
476             reload_interval = v->target_duration / 2;
477         }
478         if (v->cur_seq_no < v->start_seq_no) {
479             av_log(NULL, AV_LOG_WARNING,
480                    "skipping %d segments ahead, expired from playlists\n",
481                    v->start_seq_no - v->cur_seq_no);
482             v->cur_seq_no = v->start_seq_no;
483         }
484         if (v->cur_seq_no >= v->start_seq_no + v->n_segments) {
485             if (v->finished)
486                 return AVERROR_EOF;
487             while (av_gettime() - v->last_load_time < reload_interval) {
488                 if (ff_check_interrupt(c->interrupt_callback))
489                     return AVERROR_EXIT;
490                 av_usleep(100*1000);
491             }
492             /* Enough time has elapsed since the last reload */
493             goto reload;
494         }
495
496         ret = open_input(c, v);
497         if (ret < 0)
498             return ret;
499     }
500     ret = ffurl_read(v->input, buf, buf_size);
501     if (ret > 0)
502         return ret;
503     ffurl_close(v->input);
504     v->input = NULL;
505     v->cur_seq_no++;
506
507     c->end_of_segment = 1;
508     c->cur_seq_no = v->cur_seq_no;
509
510     if (v->ctx && v->ctx->nb_streams &&
511         v->parent->nb_streams >= v->stream_offset + v->ctx->nb_streams) {
512         v->needed = 0;
513         for (i = v->stream_offset; i < v->stream_offset + v->ctx->nb_streams;
514              i++) {
515             if (v->parent->streams[i]->discard < AVDISCARD_ALL)
516                 v->needed = 1;
517         }
518     }
519     if (!v->needed) {
520         av_log(v->parent, AV_LOG_INFO, "No longer receiving playlist %d\n",
521                v->index);
522         return AVERROR_EOF;
523     }
524     goto restart;
525 }
526
527 static int playlist_in_multiple_variants(HLSContext *c, struct playlist *pls)
528 {
529     int variant_count = 0;
530     int i, j;
531
532     for (i = 0; i < c->n_variants && variant_count < 2; i++) {
533         struct variant *v = c->variants[i];
534
535         for (j = 0; j < v->n_playlists; j++) {
536             if (v->playlists[j] == pls) {
537                 variant_count++;
538                 break;
539             }
540         }
541     }
542
543     return variant_count >= 2;
544 }
545
546 static int hls_read_header(AVFormatContext *s)
547 {
548     URLContext *u = (s->flags & AVFMT_FLAG_CUSTOM_IO) ? NULL : s->pb->opaque;
549     HLSContext *c = s->priv_data;
550     int ret = 0, i, j, stream_offset = 0;
551
552     c->interrupt_callback = &s->interrupt_callback;
553
554     // if the URL context is good, read important options we must broker later
555     if (u && u->prot->priv_data_class) {
556         // get the previous user agent & set back to null if string size is zero
557         av_freep(&c->user_agent);
558         av_opt_get(u->priv_data, "user-agent", 0, (uint8_t**)&(c->user_agent));
559         if (c->user_agent && !strlen(c->user_agent))
560             av_freep(&c->user_agent);
561
562         // get the previous cookies & set back to null if string size is zero
563         av_freep(&c->cookies);
564         av_opt_get(u->priv_data, "cookies", 0, (uint8_t**)&(c->cookies));
565         if (c->cookies && !strlen(c->cookies))
566             av_freep(&c->cookies);
567
568         // get the previous headers & set back to null if string size is zero
569         av_freep(&c->headers);
570         av_opt_get(u->priv_data, "headers", 0, (uint8_t**)&(c->headers));
571         if (c->headers && !strlen(c->headers))
572             av_freep(&c->headers);
573     }
574
575     if ((ret = parse_playlist(c, s->filename, NULL, s->pb)) < 0)
576         goto fail;
577
578     if (c->n_variants == 0) {
579         av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
580         ret = AVERROR_EOF;
581         goto fail;
582     }
583     /* If the playlist only contained playlists (Master Playlist),
584      * parse each individual playlist. */
585     if (c->n_playlists > 1 || c->playlists[0]->n_segments == 0) {
586         for (i = 0; i < c->n_playlists; i++) {
587             struct playlist *pls = c->playlists[i];
588             if ((ret = parse_playlist(c, pls->url, pls, NULL)) < 0)
589                 goto fail;
590         }
591     }
592
593     if (c->variants[0]->playlists[0]->n_segments == 0) {
594         av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
595         ret = AVERROR_EOF;
596         goto fail;
597     }
598
599     /* If this isn't a live stream, calculate the total duration of the
600      * stream. */
601     if (c->variants[0]->playlists[0]->finished) {
602         int64_t duration = 0;
603         for (i = 0; i < c->variants[0]->playlists[0]->n_segments; i++)
604             duration += c->variants[0]->playlists[0]->segments[i]->duration;
605         s->duration = duration;
606     }
607
608     /* Open the demuxer for each playlist */
609     for (i = 0; i < c->n_playlists; i++) {
610         struct playlist *pls = c->playlists[i];
611         AVInputFormat *in_fmt = NULL;
612
613         if (pls->n_segments == 0)
614             continue;
615
616         if (!(pls->ctx = avformat_alloc_context())) {
617             ret = AVERROR(ENOMEM);
618             goto fail;
619         }
620
621         pls->index  = i;
622         pls->needed = 1;
623         pls->parent = s;
624
625         /* If this is a live stream with more than 3 segments, start at the
626          * third last segment. */
627         pls->cur_seq_no = pls->start_seq_no;
628         if (!pls->finished && pls->n_segments > 3)
629             pls->cur_seq_no = pls->start_seq_no + pls->n_segments - 3;
630
631         pls->read_buffer = av_malloc(INITIAL_BUFFER_SIZE);
632         ffio_init_context(&pls->pb, pls->read_buffer, INITIAL_BUFFER_SIZE, 0, pls,
633                           read_data, NULL, NULL);
634         pls->pb.seekable = 0;
635         ret = av_probe_input_buffer(&pls->pb, &in_fmt, pls->segments[0]->url,
636                                     NULL, 0, 0);
637         if (ret < 0) {
638             /* Free the ctx - it isn't initialized properly at this point,
639              * so avformat_close_input shouldn't be called. If
640              * avformat_open_input fails below, it frees and zeros the
641              * context, so it doesn't need any special treatment like this. */
642             av_log(s, AV_LOG_ERROR, "Error when loading first segment '%s'\n", pls->segments[0]->url);
643             avformat_free_context(pls->ctx);
644             pls->ctx = NULL;
645             goto fail;
646         }
647         pls->ctx->pb       = &pls->pb;
648         pls->stream_offset = stream_offset;
649         ret = avformat_open_input(&pls->ctx, pls->segments[0]->url, in_fmt, NULL);
650         if (ret < 0)
651             goto fail;
652
653         pls->ctx->ctx_flags &= ~AVFMTCTX_NOHEADER;
654         ret = avformat_find_stream_info(pls->ctx, NULL);
655         if (ret < 0)
656             goto fail;
657
658         /* Create new AVStreams for each stream in this playlist */
659         for (j = 0; j < pls->ctx->nb_streams; j++) {
660             AVStream *st = avformat_new_stream(s, NULL);
661             AVStream *ist = pls->ctx->streams[j];
662             if (!st) {
663                 ret = AVERROR(ENOMEM);
664                 goto fail;
665             }
666             st->id = i;
667             avpriv_set_pts_info(st, ist->pts_wrap_bits, ist->time_base.num, ist->time_base.den);
668             avcodec_copy_context(st->codec, pls->ctx->streams[j]->codec);
669         }
670
671         stream_offset += pls->ctx->nb_streams;
672     }
673
674     /* Create a program for each variant */
675     for (i = 0; i < c->n_variants; i++) {
676         struct variant *v = c->variants[i];
677         char bitrate_str[20];
678         AVProgram *program;
679
680         snprintf(bitrate_str, sizeof(bitrate_str), "%d", v->bandwidth);
681
682         program = av_new_program(s, i);
683         if (!program)
684             goto fail;
685         av_dict_set(&program->metadata, "variant_bitrate", bitrate_str, 0);
686
687         for (j = 0; j < v->n_playlists; j++) {
688             struct playlist *pls = v->playlists[j];
689             int is_shared = playlist_in_multiple_variants(c, pls);
690             int k;
691
692             for (k = 0; k < pls->ctx->nb_streams; k++) {
693                 struct AVStream *st = s->streams[pls->stream_offset + k];
694
695                 ff_program_add_stream_index(s, i, pls->stream_offset + k);
696
697                 /* Set variant_bitrate for streams unique to this variant */
698                 if (!is_shared && v->bandwidth)
699                     av_dict_set(&st->metadata, "variant_bitrate", bitrate_str, 0);
700             }
701         }
702     }
703
704     c->first_packet = 1;
705     c->first_timestamp = AV_NOPTS_VALUE;
706     c->seek_timestamp  = AV_NOPTS_VALUE;
707
708     return 0;
709 fail:
710     free_playlist_list(c);
711     free_variant_list(c);
712     return ret;
713 }
714
715 static int recheck_discard_flags(AVFormatContext *s, int first)
716 {
717     HLSContext *c = s->priv_data;
718     int i, changed = 0;
719
720     /* Check if any new streams are needed */
721     for (i = 0; i < c->n_playlists; i++)
722         c->playlists[i]->cur_needed = 0;
723
724     for (i = 0; i < s->nb_streams; i++) {
725         AVStream *st = s->streams[i];
726         struct playlist *pls = c->playlists[s->streams[i]->id];
727         if (st->discard < AVDISCARD_ALL)
728             pls->cur_needed = 1;
729     }
730     for (i = 0; i < c->n_playlists; i++) {
731         struct playlist *pls = c->playlists[i];
732         if (pls->cur_needed && !pls->needed) {
733             pls->needed = 1;
734             changed = 1;
735             pls->cur_seq_no = c->cur_seq_no;
736             pls->pb.eof_reached = 0;
737             av_log(s, AV_LOG_INFO, "Now receiving playlist %d\n", i);
738         } else if (first && !pls->cur_needed && pls->needed) {
739             if (pls->input)
740                 ffurl_close(pls->input);
741             pls->input = NULL;
742             pls->needed = 0;
743             changed = 1;
744             av_log(s, AV_LOG_INFO, "No longer receiving playlist %d\n", i);
745         }
746     }
747     return changed;
748 }
749
750 static int hls_read_packet(AVFormatContext *s, AVPacket *pkt)
751 {
752     HLSContext *c = s->priv_data;
753     int ret, i, minplaylist = -1;
754
755     if (c->first_packet) {
756         recheck_discard_flags(s, 1);
757         c->first_packet = 0;
758     }
759
760 start:
761     c->end_of_segment = 0;
762     for (i = 0; i < c->n_playlists; i++) {
763         struct playlist *pls = c->playlists[i];
764         /* Make sure we've got one buffered packet from each open playlist
765          * stream */
766         if (pls->needed && !pls->pkt.data) {
767             while (1) {
768                 int64_t ts_diff;
769                 AVStream *st;
770                 ret = av_read_frame(pls->ctx, &pls->pkt);
771                 if (ret < 0) {
772                     if (!url_feof(&pls->pb) && ret != AVERROR_EOF)
773                         return ret;
774                     reset_packet(&pls->pkt);
775                     break;
776                 } else {
777                     if (c->first_timestamp == AV_NOPTS_VALUE &&
778                         pls->pkt.dts       != AV_NOPTS_VALUE)
779                         c->first_timestamp = av_rescale_q(pls->pkt.dts,
780                             pls->ctx->streams[pls->pkt.stream_index]->time_base,
781                             AV_TIME_BASE_Q);
782                 }
783
784                 if (c->seek_timestamp == AV_NOPTS_VALUE)
785                     break;
786
787                 if (pls->pkt.dts == AV_NOPTS_VALUE) {
788                     c->seek_timestamp = AV_NOPTS_VALUE;
789                     break;
790                 }
791
792                 st = pls->ctx->streams[pls->pkt.stream_index];
793                 ts_diff = av_rescale_rnd(pls->pkt.dts, AV_TIME_BASE,
794                                          st->time_base.den, AV_ROUND_DOWN) -
795                           c->seek_timestamp;
796                 if (ts_diff >= 0 && (c->seek_flags  & AVSEEK_FLAG_ANY ||
797                                      pls->pkt.flags & AV_PKT_FLAG_KEY)) {
798                     c->seek_timestamp = AV_NOPTS_VALUE;
799                     break;
800                 }
801                 av_free_packet(&pls->pkt);
802                 reset_packet(&pls->pkt);
803             }
804         }
805         /* Check if this stream still is on an earlier segment number, or
806          * has the packet with the lowest dts */
807         if (pls->pkt.data) {
808             struct playlist *minpls = minplaylist < 0 ?
809                                      NULL : c->playlists[minplaylist];
810             if (minplaylist < 0 || pls->cur_seq_no < minpls->cur_seq_no) {
811                 minplaylist = i;
812             } else if (pls->cur_seq_no == minpls->cur_seq_no) {
813                 int64_t dts     =    pls->pkt.dts;
814                 int64_t mindts  = minpls->pkt.dts;
815                 AVStream *st    =    pls->ctx->streams[pls->pkt.stream_index];
816                 AVStream *minst = minpls->ctx->streams[minpls->pkt.stream_index];
817
818                 if (dts == AV_NOPTS_VALUE) {
819                     minplaylist = i;
820                 } else if (mindts != AV_NOPTS_VALUE) {
821                     if (st->start_time    != AV_NOPTS_VALUE)
822                         dts    -= st->start_time;
823                     if (minst->start_time != AV_NOPTS_VALUE)
824                         mindts -= minst->start_time;
825
826                     if (av_compare_ts(dts, st->time_base,
827                                       mindts, minst->time_base) < 0)
828                         minplaylist = i;
829                 }
830             }
831         }
832     }
833     if (c->end_of_segment) {
834         if (recheck_discard_flags(s, 0))
835             goto start;
836     }
837     /* If we got a packet, return it */
838     if (minplaylist >= 0) {
839         *pkt = c->playlists[minplaylist]->pkt;
840         pkt->stream_index += c->playlists[minplaylist]->stream_offset;
841         reset_packet(&c->playlists[minplaylist]->pkt);
842         return 0;
843     }
844     return AVERROR_EOF;
845 }
846
847 static int hls_close(AVFormatContext *s)
848 {
849     HLSContext *c = s->priv_data;
850
851     free_playlist_list(c);
852     free_variant_list(c);
853     return 0;
854 }
855
856 static int hls_read_seek(AVFormatContext *s, int stream_index,
857                                int64_t timestamp, int flags)
858 {
859     HLSContext *c = s->priv_data;
860     int i, j, ret;
861
862     if ((flags & AVSEEK_FLAG_BYTE) || !c->variants[0]->playlists[0]->finished)
863         return AVERROR(ENOSYS);
864
865     c->seek_flags     = flags;
866     c->seek_timestamp = stream_index < 0 ? timestamp :
867                         av_rescale_rnd(timestamp, AV_TIME_BASE,
868                                        s->streams[stream_index]->time_base.den,
869                                        flags & AVSEEK_FLAG_BACKWARD ?
870                                        AV_ROUND_DOWN : AV_ROUND_UP);
871     timestamp = av_rescale_rnd(timestamp, AV_TIME_BASE, stream_index >= 0 ?
872                                s->streams[stream_index]->time_base.den :
873                                AV_TIME_BASE, flags & AVSEEK_FLAG_BACKWARD ?
874                                AV_ROUND_DOWN : AV_ROUND_UP);
875     if (s->duration < c->seek_timestamp) {
876         c->seek_timestamp = AV_NOPTS_VALUE;
877         return AVERROR(EIO);
878     }
879
880     ret = AVERROR(EIO);
881     for (i = 0; i < c->n_playlists; i++) {
882         /* Reset reading */
883         struct playlist *pls = c->playlists[i];
884         int64_t pos = c->first_timestamp == AV_NOPTS_VALUE ?
885                       0 : c->first_timestamp;
886         if (pls->input) {
887             ffurl_close(pls->input);
888             pls->input = NULL;
889         }
890         av_free_packet(&pls->pkt);
891         reset_packet(&pls->pkt);
892         pls->pb.eof_reached = 0;
893         /* Clear any buffered data */
894         pls->pb.buf_end = pls->pb.buf_ptr = pls->pb.buffer;
895         /* Reset the pos, to let the mpegts demuxer know we've seeked. */
896         pls->pb.pos = 0;
897
898         /* Locate the segment that contains the target timestamp */
899         for (j = 0; j < pls->n_segments; j++) {
900             if (timestamp >= pos &&
901                 timestamp < pos + pls->segments[j]->duration) {
902                 pls->cur_seq_no = pls->start_seq_no + j;
903                 ret = 0;
904                 break;
905             }
906             pos += pls->segments[j]->duration;
907         }
908         if (ret)
909             c->seek_timestamp = AV_NOPTS_VALUE;
910     }
911     return ret;
912 }
913
914 static int hls_probe(AVProbeData *p)
915 {
916     /* Require #EXTM3U at the start, and either one of the ones below
917      * somewhere for a proper match. */
918     if (strncmp(p->buf, "#EXTM3U", 7))
919         return 0;
920     if (strstr(p->buf, "#EXT-X-STREAM-INF:")     ||
921         strstr(p->buf, "#EXT-X-TARGETDURATION:") ||
922         strstr(p->buf, "#EXT-X-MEDIA-SEQUENCE:"))
923         return AVPROBE_SCORE_MAX;
924     return 0;
925 }
926
927 AVInputFormat ff_hls_demuxer = {
928     .name           = "hls,applehttp",
929     .long_name      = NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming"),
930     .priv_data_size = sizeof(HLSContext),
931     .read_probe     = hls_probe,
932     .read_header    = hls_read_header,
933     .read_packet    = hls_read_packet,
934     .read_close     = hls_close,
935     .read_seek      = hls_read_seek,
936 };