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