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