467a4913a53c8168d688906ea86d372b76d6d109
[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 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 AVDictionary *avio_opts;
107 } HLSContext;
108
109 static int read_chomp_line(AVIOContext *s, char *buf, int maxlen)
110 {
111 int len = ff_get_line(s, buf, maxlen);
112 while (len > 0 && av_isspace(buf[len - 1]))
113 buf[--len] = '\0';
114 return len;
115 }
116
117 static void free_segment_list(struct variant *var)
118 {
119 int i;
120 for (i = 0; i < var->n_segments; i++)
121 av_free(var->segments[i]);
122 av_freep(&var->segments);
123 var->n_segments = 0;
124 }
125
126 static void free_variant_list(HLSContext *c)
127 {
128 int i;
129 for (i = 0; i < c->n_variants; i++) {
130 struct variant *var = c->variants[i];
131 free_segment_list(var);
132 av_free_packet(&var->pkt);
133 av_free(var->pb.buffer);
134 if (var->input)
135 ffurl_close(var->input);
136 if (var->ctx) {
137 var->ctx->pb = NULL;
138 avformat_close_input(&var->ctx);
139 }
140 av_free(var);
141 }
142 av_freep(&c->variants);
143 c->n_variants = 0;
144 }
145
146 /*
147 * Used to reset a statically allocated AVPacket to a clean slate,
148 * containing no data.
149 */
150 static void reset_packet(AVPacket *pkt)
151 {
152 av_init_packet(pkt);
153 pkt->data = NULL;
154 }
155
156 static struct variant *new_variant(HLSContext *c, int bandwidth,
157 const char *url, const char *base)
158 {
159 struct variant *var = av_mallocz(sizeof(struct variant));
160 if (!var)
161 return NULL;
162 reset_packet(&var->pkt);
163 var->bandwidth = bandwidth;
164 ff_make_absolute_url(var->url, sizeof(var->url), base, url);
165 dynarray_add(&c->variants, &c->n_variants, var);
166 return var;
167 }
168
169 struct variant_info {
170 char bandwidth[20];
171 };
172
173 static void handle_variant_args(struct variant_info *info, const char *key,
174 int key_len, char **dest, int *dest_len)
175 {
176 if (!strncmp(key, "BANDWIDTH=", key_len)) {
177 *dest = info->bandwidth;
178 *dest_len = sizeof(info->bandwidth);
179 }
180 }
181
182 struct key_info {
183 char uri[MAX_URL_SIZE];
184 char method[10];
185 char iv[35];
186 };
187
188 static void handle_key_args(struct key_info *info, const char *key,
189 int key_len, char **dest, int *dest_len)
190 {
191 if (!strncmp(key, "METHOD=", key_len)) {
192 *dest = info->method;
193 *dest_len = sizeof(info->method);
194 } else if (!strncmp(key, "URI=", key_len)) {
195 *dest = info->uri;
196 *dest_len = sizeof(info->uri);
197 } else if (!strncmp(key, "IV=", key_len)) {
198 *dest = info->iv;
199 *dest_len = sizeof(info->iv);
200 }
201 }
202
203 static int open_in(HLSContext *c, AVIOContext **in, const char *url)
204 {
205 AVDictionary *tmp = NULL;
206 int ret;
207
208 av_dict_copy(&tmp, c->avio_opts, 0);
209
210 ret = avio_open2(in, url, AVIO_FLAG_READ, c->interrupt_callback, &tmp);
211
212 av_dict_free(&tmp);
213 return ret;
214 }
215
216 static int url_connect(struct variant *var, AVDictionary *opts)
217 {
218 AVDictionary *tmp = NULL;
219 int ret;
220
221 av_dict_copy(&tmp, opts, 0);
222
223 av_opt_set_dict(var->input, &tmp);
224
225 if ((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 avio_close(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->interrupt_callback = &s->interrupt_callback;
519
520 if ((ret = parse_playlist(c, s->filename, NULL, s->pb)) < 0)
521 goto fail;
522
523 if ((ret = save_avio_options(s)) < 0)
524 goto fail;
525
526 if (c->n_variants == 0) {
527 av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
528 ret = AVERROR_EOF;
529 goto fail;
530 }
531 /* If the playlist only contained variants, parse each individual
532 * variant playlist. */
533 if (c->n_variants > 1 || c->variants[0]->n_segments == 0) {
534 for (i = 0; i < c->n_variants; i++) {
535 struct variant *v = c->variants[i];
536 if ((ret = parse_playlist(c, v->url, v, NULL)) < 0)
537 goto fail;
538 }
539 }
540
541 if (c->variants[0]->n_segments == 0) {
542 av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
543 ret = AVERROR_EOF;
544 goto fail;
545 }
546
547 /* If this isn't a live stream, calculate the total duration of the
548 * stream. */
549 if (c->variants[0]->finished) {
550 int64_t duration = 0;
551 for (i = 0; i < c->variants[0]->n_segments; i++)
552 duration += c->variants[0]->segments[i]->duration;
553 s->duration = duration;
554 }
555
556 /* Open the demuxer for each variant */
557 for (i = 0; i < c->n_variants; i++) {
558 struct variant *v = c->variants[i];
559 AVInputFormat *in_fmt = NULL;
560 char bitrate_str[20];
561 AVProgram *program;
562
563 if (v->n_segments == 0)
564 continue;
565
566 if (!(v->ctx = avformat_alloc_context())) {
567 ret = AVERROR(ENOMEM);
568 goto fail;
569 }
570
571 v->index = i;
572 v->needed = 1;
573 v->parent = s;
574
575 /* If this is a live stream with more than 3 segments, start at the
576 * third last segment. */
577 v->cur_seq_no = v->start_seq_no;
578 if (!v->finished && v->n_segments > 3)
579 v->cur_seq_no = v->start_seq_no + v->n_segments - 3;
580
581 v->read_buffer = av_malloc(INITIAL_BUFFER_SIZE);
582 ffio_init_context(&v->pb, v->read_buffer, INITIAL_BUFFER_SIZE, 0, v,
583 read_data, NULL, NULL);
584 v->pb.seekable = 0;
585 ret = av_probe_input_buffer(&v->pb, &in_fmt, v->segments[0]->url,
586 NULL, 0, 0);
587 if (ret < 0) {
588 /* Free the ctx - it isn't initialized properly at this point,
589 * so avformat_close_input shouldn't be called. If
590 * avformat_open_input fails below, it frees and zeros the
591 * context, so it doesn't need any special treatment like this. */
592 avformat_free_context(v->ctx);
593 v->ctx = NULL;
594 goto fail;
595 }
596 v->ctx->pb = &v->pb;
597 v->stream_offset = stream_offset;
598 ret = avformat_open_input(&v->ctx, v->segments[0]->url, in_fmt, NULL);
599 if (ret < 0)
600 goto fail;
601
602 v->ctx->ctx_flags &= ~AVFMTCTX_NOHEADER;
603 ret = avformat_find_stream_info(v->ctx, NULL);
604 if (ret < 0)
605 goto fail;
606 snprintf(bitrate_str, sizeof(bitrate_str), "%d", v->bandwidth);
607
608 program = av_new_program(s, i);
609 if (!program)
610 goto fail;
611 av_dict_set(&program->metadata, "variant_bitrate", bitrate_str, 0);
612
613 /* Create new AVStreams for each stream in this variant */
614 for (j = 0; j < v->ctx->nb_streams; j++) {
615 AVStream *st = avformat_new_stream(s, NULL);
616 AVStream *ist = v->ctx->streams[j];
617 if (!st) {
618 ret = AVERROR(ENOMEM);
619 goto fail;
620 }
621 ff_program_add_stream_index(s, i, stream_offset + j);
622 st->id = i;
623 avpriv_set_pts_info(st, ist->pts_wrap_bits, ist->time_base.num, ist->time_base.den);
624 avcodec_copy_context(st->codec, v->ctx->streams[j]->codec);
625 if (v->bandwidth)
626 av_dict_set(&st->metadata, "variant_bitrate", bitrate_str,
627 0);
628 }
629 stream_offset += v->ctx->nb_streams;
630 }
631
632 c->first_packet = 1;
633 c->first_timestamp = AV_NOPTS_VALUE;
634 c->seek_timestamp = AV_NOPTS_VALUE;
635
636 return 0;
637 fail:
638 free_variant_list(c);
639 return ret;
640 }
641
642 static int recheck_discard_flags(AVFormatContext *s, int first)
643 {
644 HLSContext *c = s->priv_data;
645 int i, changed = 0;
646
647 /* Check if any new streams are needed */
648 for (i = 0; i < c->n_variants; i++)
649 c->variants[i]->cur_needed = 0;;
650
651 for (i = 0; i < s->nb_streams; i++) {
652 AVStream *st = s->streams[i];
653 struct variant *var = c->variants[s->streams[i]->id];
654 if (st->discard < AVDISCARD_ALL)
655 var->cur_needed = 1;
656 }
657 for (i = 0; i < c->n_variants; i++) {
658 struct variant *v = c->variants[i];
659 if (v->cur_needed && !v->needed) {
660 v->needed = 1;
661 changed = 1;
662 v->cur_seq_no = c->cur_seq_no;
663 v->pb.eof_reached = 0;
664 av_log(s, AV_LOG_INFO, "Now receiving variant %d\n", i);
665 } else if (first && !v->cur_needed && v->needed) {
666 if (v->input)
667 ffurl_close(v->input);
668 v->input = NULL;
669 v->needed = 0;
670 changed = 1;
671 av_log(s, AV_LOG_INFO, "No longer receiving variant %d\n", i);
672 }
673 }
674 return changed;
675 }
676
677 static int hls_read_packet(AVFormatContext *s, AVPacket *pkt)
678 {
679 HLSContext *c = s->priv_data;
680 int ret, i, minvariant = -1;
681
682 if (c->first_packet) {
683 recheck_discard_flags(s, 1);
684 c->first_packet = 0;
685 }
686
687 start:
688 c->end_of_segment = 0;
689 for (i = 0; i < c->n_variants; i++) {
690 struct variant *var = c->variants[i];
691 /* Make sure we've got one buffered packet from each open variant
692 * stream */
693 if (var->needed && !var->pkt.data) {
694 while (1) {
695 int64_t ts_diff;
696 AVStream *st;
697 ret = av_read_frame(var->ctx, &var->pkt);
698 if (ret < 0) {
699 if (!var->pb.eof_reached)
700 return ret;
701 reset_packet(&var->pkt);
702 break;
703 } else {
704 if (c->first_timestamp == AV_NOPTS_VALUE &&
705 var->pkt.dts != AV_NOPTS_VALUE)
706 c->first_timestamp = av_rescale_q(var->pkt.dts,
707 var->ctx->streams[var->pkt.stream_index]->time_base,
708 AV_TIME_BASE_Q);
709 }
710
711 if (c->seek_timestamp == AV_NOPTS_VALUE)
712 break;
713
714 if (var->pkt.dts == AV_NOPTS_VALUE) {
715 c->seek_timestamp = AV_NOPTS_VALUE;
716 break;
717 }
718
719 st = var->ctx->streams[var->pkt.stream_index];
720 ts_diff = av_rescale_rnd(var->pkt.dts, AV_TIME_BASE,
721 st->time_base.den, AV_ROUND_DOWN) -
722 c->seek_timestamp;
723 if (ts_diff >= 0 && (c->seek_flags & AVSEEK_FLAG_ANY ||
724 var->pkt.flags & AV_PKT_FLAG_KEY)) {
725 c->seek_timestamp = AV_NOPTS_VALUE;
726 break;
727 }
728 av_free_packet(&var->pkt);
729 reset_packet(&var->pkt);
730 }
731 }
732 /* Check if this stream still is on an earlier segment number, or
733 * has the packet with the lowest dts */
734 if (var->pkt.data) {
735 struct variant *minvar = minvariant < 0 ?
736 NULL : c->variants[minvariant];
737 if (minvariant < 0 || var->cur_seq_no < minvar->cur_seq_no) {
738 minvariant = i;
739 } else if (var->cur_seq_no == minvar->cur_seq_no) {
740 int64_t dts = var->pkt.dts;
741 int64_t mindts = minvar->pkt.dts;
742 AVStream *st = var->ctx->streams[var->pkt.stream_index];
743 AVStream *minst = minvar->ctx->streams[minvar->pkt.stream_index];
744
745 if (dts == AV_NOPTS_VALUE) {
746 minvariant = i;
747 } else if (mindts != AV_NOPTS_VALUE) {
748 if (st->start_time != AV_NOPTS_VALUE)
749 dts -= st->start_time;
750 if (minst->start_time != AV_NOPTS_VALUE)
751 mindts -= minst->start_time;
752
753 if (av_compare_ts(dts, st->time_base,
754 mindts, minst->time_base) < 0)
755 minvariant = i;
756 }
757 }
758 }
759 }
760 if (c->end_of_segment) {
761 if (recheck_discard_flags(s, 0))
762 goto start;
763 }
764 /* If we got a packet, return it */
765 if (minvariant >= 0) {
766 *pkt = c->variants[minvariant]->pkt;
767 pkt->stream_index += c->variants[minvariant]->stream_offset;
768 reset_packet(&c->variants[minvariant]->pkt);
769 return 0;
770 }
771 return AVERROR_EOF;
772 }
773
774 static int hls_close(AVFormatContext *s)
775 {
776 HLSContext *c = s->priv_data;
777
778 free_variant_list(c);
779
780 av_dict_free(&c->avio_opts);
781
782 return 0;
783 }
784
785 static int hls_read_seek(AVFormatContext *s, int stream_index,
786 int64_t timestamp, int flags)
787 {
788 HLSContext *c = s->priv_data;
789 int i, j, ret;
790
791 if ((flags & AVSEEK_FLAG_BYTE) || !c->variants[0]->finished)
792 return AVERROR(ENOSYS);
793
794 c->seek_flags = flags;
795 c->seek_timestamp = stream_index < 0 ? timestamp :
796 av_rescale_rnd(timestamp, AV_TIME_BASE,
797 s->streams[stream_index]->time_base.den,
798 flags & AVSEEK_FLAG_BACKWARD ?
799 AV_ROUND_DOWN : AV_ROUND_UP);
800 timestamp = av_rescale_rnd(timestamp, AV_TIME_BASE, stream_index >= 0 ?
801 s->streams[stream_index]->time_base.den :
802 AV_TIME_BASE, flags & AVSEEK_FLAG_BACKWARD ?
803 AV_ROUND_DOWN : AV_ROUND_UP);
804 if (s->duration < c->seek_timestamp) {
805 c->seek_timestamp = AV_NOPTS_VALUE;
806 return AVERROR(EIO);
807 }
808
809 ret = AVERROR(EIO);
810 for (i = 0; i < c->n_variants; i++) {
811 /* Reset reading */
812 struct variant *var = c->variants[i];
813 int64_t pos = c->first_timestamp == AV_NOPTS_VALUE ?
814 0 : c->first_timestamp;
815 if (var->input) {
816 ffurl_close(var->input);
817 var->input = NULL;
818 }
819 av_free_packet(&var->pkt);
820 reset_packet(&var->pkt);
821 var->pb.eof_reached = 0;
822 /* Clear any buffered data */
823 var->pb.buf_end = var->pb.buf_ptr = var->pb.buffer;
824 /* Reset the pos, to let the mpegts demuxer know we've seeked. */
825 var->pb.pos = 0;
826
827 /* Locate the segment that contains the target timestamp */
828 for (j = 0; j < var->n_segments; j++) {
829 if (timestamp >= pos &&
830 timestamp < pos + var->segments[j]->duration) {
831 var->cur_seq_no = var->start_seq_no + j;
832 ret = 0;
833 break;
834 }
835 pos += var->segments[j]->duration;
836 }
837 if (ret)
838 c->seek_timestamp = AV_NOPTS_VALUE;
839 }
840 return ret;
841 }
842
843 static int hls_probe(AVProbeData *p)
844 {
845 /* Require #EXTM3U at the start, and either one of the ones below
846 * somewhere for a proper match. */
847 if (strncmp(p->buf, "#EXTM3U", 7))
848 return 0;
849 if (strstr(p->buf, "#EXT-X-STREAM-INF:") ||
850 strstr(p->buf, "#EXT-X-TARGETDURATION:") ||
851 strstr(p->buf, "#EXT-X-MEDIA-SEQUENCE:"))
852 return AVPROBE_SCORE_MAX;
853 return 0;
854 }
855
856 AVInputFormat ff_hls_demuxer = {
857 .name = "hls,applehttp",
858 .long_name = NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming"),
859 .priv_data_size = sizeof(HLSContext),
860 .read_probe = hls_probe,
861 .read_header = hls_read_header,
862 .read_packet = hls_read_packet,
863 .read_close = hls_close,
864 .read_seek = hls_read_seek,
865 };