2 * Apple HTTP Live Streaming demuxer
3 * Copyright (c) 2010 Martin Storsjo
5 * This file is part of FFmpeg.
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.
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.
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
24 * Apple HTTP Live Streaming demuxer
25 * http://tools.ietf.org/html/draft-pantos-http-live-streaming
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"
36 #include "avio_internal.h"
39 #define INITIAL_BUFFER_SIZE 32768
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
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.
60 char url[MAX_URL_SIZE];
61 char key[MAX_URL_SIZE];
62 enum KeyType key_type;
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.
72 char url[MAX_URL_SIZE];
76 AVFormatContext *parent;
83 int64_t target_duration;
86 struct segment **segments;
87 int needed, cur_needed;
89 int64_t last_load_time;
91 char key_url[MAX_URL_SIZE];
98 struct playlist **playlists;
101 typedef struct HLSContext {
103 struct variant **variants;
105 struct playlist **playlists;
110 int64_t first_timestamp;
111 int64_t seek_timestamp;
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
119 static int read_chomp_line(AVIOContext *s, char *buf, int maxlen)
121 int len = ff_get_line(s, buf, maxlen);
122 while (len > 0 && av_isspace(buf[len - 1]))
127 static void free_segment_list(struct playlist *pls)
130 for (i = 0; i < pls->n_segments; i++)
131 av_free(pls->segments[i]);
132 av_freep(&pls->segments);
136 static void free_playlist_list(HLSContext *c)
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);
145 ffurl_close(pls->input);
148 avformat_close_input(&pls->ctx);
152 av_freep(&c->playlists);
153 av_freep(&c->cookies);
154 av_freep(&c->user_agent);
158 static void free_variant_list(HLSContext *c)
161 for (i = 0; i < c->n_variants; i++) {
162 struct variant *var = c->variants[i];
163 av_freep(&var->playlists);
166 av_freep(&c->variants);
171 * Used to reset a statically allocated AVPacket to a clean slate,
172 * containing no data.
174 static void reset_packet(AVPacket *pkt)
180 static struct playlist *new_playlist(HLSContext *c, const char *url,
183 struct playlist *pls = av_mallocz(sizeof(struct playlist));
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);
192 static struct variant *new_variant(HLSContext *c, int bandwidth,
193 const char *url, const char *base)
196 struct playlist *pls;
198 pls = new_playlist(c, url, base);
202 var = av_mallocz(sizeof(struct variant));
206 var->bandwidth = bandwidth;
207 dynarray_add(&c->variants, &c->n_variants, var);
208 dynarray_add(&var->playlists, &var->n_playlists, pls);
212 struct variant_info {
216 static void handle_variant_args(struct variant_info *info, const char *key,
217 int key_len, char **dest, int *dest_len)
219 if (!strncmp(key, "BANDWIDTH=", key_len)) {
220 *dest = info->bandwidth;
221 *dest_len = sizeof(info->bandwidth);
226 char uri[MAX_URL_SIZE];
231 static void handle_key_args(struct key_info *info, const char *key,
232 int key_len, char **dest, int *dest_len)
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)) {
239 *dest_len = sizeof(info->uri);
240 } else if (!strncmp(key, "IV=", key_len)) {
242 *dest_len = sizeof(info->iv);
246 static int parse_playlist(HLSContext *c, const char *url,
247 struct playlist *pls, AVIOContext *in)
249 int ret = 0, is_segment = 0, is_variant = 0, bandwidth = 0;
250 int64_t duration = 0;
251 enum KeyType key_type = KEY_NONE;
254 char key[MAX_URL_SIZE] = "";
255 char line[MAX_URL_SIZE];
258 uint8_t *new_url = NULL;
261 AVDictionary *opts = NULL;
263 /* Some HLS servers don't like being sent the range header */
264 av_dict_set(&opts, "seekable", "0", 0);
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);
271 ret = avio_open2(&in, url, AVIO_FLAG_READ,
272 c->interrupt_callback, &opts);
278 if (av_opt_get(in, "location", AV_OPT_SEARCH_CHILDREN, &new_url) >= 0)
281 read_chomp_line(in, line, sizeof(line));
282 if (strcmp(line, "#EXTM3U")) {
283 ret = AVERROR_INVALIDDATA;
288 free_segment_list(pls);
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}};
296 ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_variant_args,
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,
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);
311 av_strlcpy(key, info.uri, sizeof(key));
312 } else if (av_strstart(line, "#EXT-X-TARGETDURATION:", &ptr)) {
314 if (!new_variant(c, 0, url, NULL)) {
315 ret = AVERROR(ENOMEM);
318 pls = c->playlists[c->n_playlists - 1];
320 pls->target_duration = atoi(ptr) * AV_TIME_BASE;
321 } else if (av_strstart(line, "#EXT-X-MEDIA-SEQUENCE:", &ptr)) {
323 if (!new_variant(c, 0, url, NULL)) {
324 ret = AVERROR(ENOMEM);
327 pls = c->playlists[c->n_playlists - 1];
329 pls->start_seq_no = atoi(ptr);
330 } else if (av_strstart(line, "#EXT-X-ENDLIST", &ptr)) {
333 } else if (av_strstart(line, "#EXTINF:", &ptr)) {
335 duration = atof(ptr) * AV_TIME_BASE;
336 } else if (av_strstart(line, "#", NULL)) {
338 } else if (line[0]) {
340 if (!new_variant(c, bandwidth, line, url)) {
341 ret = AVERROR(ENOMEM);
350 if (!new_variant(c, 0, url, NULL)) {
351 ret = AVERROR(ENOMEM);
354 pls = c->playlists[c->n_playlists - 1];
356 seg = av_malloc(sizeof(struct segment));
358 ret = AVERROR(ENOMEM);
361 seg->duration = duration;
362 seg->key_type = key_type;
364 memcpy(seg->iv, iv, sizeof(iv));
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);
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);
378 pls->last_load_time = av_gettime();
387 static int open_input(HLSContext *c, struct playlist *pls)
389 AVDictionary *opts = NULL;
391 struct segment *seg = pls->segments[pls->cur_seq_no - pls->start_seq_no];
393 // broker prior HTTP options that should be consistent across requests
394 av_dict_set(&opts, "user-agent", c->user_agent, 0);
395 av_dict_set(&opts, "cookies", c->cookies, 0);
396 av_dict_set(&opts, "headers", c->headers, 0);
397 av_dict_set(&opts, "seekable", "0", 0);
399 if (seg->key_type == KEY_NONE) {
400 ret = ffurl_open(&pls->input, seg->url, AVIO_FLAG_READ,
401 &pls->parent->interrupt_callback, &opts);
403 } else if (seg->key_type == KEY_AES_128) {
404 char iv[33], key[33], url[MAX_URL_SIZE];
405 if (strcmp(seg->key, pls->key_url)) {
407 if (ffurl_open(&uc, seg->key, AVIO_FLAG_READ,
408 &pls->parent->interrupt_callback, &opts) == 0) {
409 if (ffurl_read_complete(uc, pls->key, sizeof(pls->key))
410 != sizeof(pls->key)) {
411 av_log(NULL, AV_LOG_ERROR, "Unable to read key file %s\n",
416 av_log(NULL, AV_LOG_ERROR, "Unable to open key file %s\n",
419 av_strlcpy(pls->key_url, seg->key, sizeof(pls->key_url));
421 ff_data_to_hex(iv, seg->iv, sizeof(seg->iv), 0);
422 ff_data_to_hex(key, pls->key, sizeof(pls->key), 0);
423 iv[32] = key[32] = '\0';
424 if (strstr(seg->url, "://"))
425 snprintf(url, sizeof(url), "crypto+%s", seg->url);
427 snprintf(url, sizeof(url), "crypto:%s", seg->url);
428 if ((ret = ffurl_alloc(&pls->input, url, AVIO_FLAG_READ,
429 &pls->parent->interrupt_callback)) < 0)
431 av_opt_set(pls->input->priv_data, "key", key, 0);
432 av_opt_set(pls->input->priv_data, "iv", iv, 0);
433 /* Need to repopulate options */
435 av_dict_set(&opts, "seekable", "0", 0);
436 if ((ret = ffurl_connect(pls->input, &opts)) < 0) {
437 ffurl_close(pls->input);
444 ret = AVERROR(ENOSYS);
451 static int read_data(void *opaque, uint8_t *buf, int buf_size)
453 struct playlist *v = opaque;
454 HLSContext *c = v->parent->priv_data;
459 /* If this is a live stream and the reload interval has elapsed since
460 * the last playlist reload, reload the playlists now. */
461 int64_t reload_interval = v->n_segments > 0 ?
462 v->segments[v->n_segments - 1]->duration :
467 av_gettime() - v->last_load_time >= reload_interval) {
468 if ((ret = parse_playlist(c, v->url, v, NULL)) < 0)
470 /* If we need to reload the playlist again below (if
471 * there's still no more segments), switch to a reload
472 * interval of half the target duration. */
473 reload_interval = v->target_duration / 2;
475 if (v->cur_seq_no < v->start_seq_no) {
476 av_log(NULL, AV_LOG_WARNING,
477 "skipping %d segments ahead, expired from playlists\n",
478 v->start_seq_no - v->cur_seq_no);
479 v->cur_seq_no = v->start_seq_no;
481 if (v->cur_seq_no >= v->start_seq_no + v->n_segments) {
484 while (av_gettime() - v->last_load_time < reload_interval) {
485 if (ff_check_interrupt(c->interrupt_callback))
489 /* Enough time has elapsed since the last reload */
493 ret = open_input(c, v);
497 ret = ffurl_read(v->input, buf, buf_size);
500 ffurl_close(v->input);
504 c->end_of_segment = 1;
505 c->cur_seq_no = v->cur_seq_no;
507 if (v->ctx && v->ctx->nb_streams &&
508 v->parent->nb_streams >= v->stream_offset + v->ctx->nb_streams) {
510 for (i = v->stream_offset; i < v->stream_offset + v->ctx->nb_streams;
512 if (v->parent->streams[i]->discard < AVDISCARD_ALL)
517 av_log(v->parent, AV_LOG_INFO, "No longer receiving playlist %d\n",
524 static int playlist_in_multiple_variants(HLSContext *c, struct playlist *pls)
526 int variant_count = 0;
529 for (i = 0; i < c->n_variants && variant_count < 2; i++) {
530 struct variant *v = c->variants[i];
532 for (j = 0; j < v->n_playlists; j++) {
533 if (v->playlists[j] == pls) {
540 return variant_count >= 2;
543 static int hls_read_header(AVFormatContext *s)
545 URLContext *u = (s->flags & AVFMT_FLAG_CUSTOM_IO) ? NULL : s->pb->opaque;
546 HLSContext *c = s->priv_data;
547 int ret = 0, i, j, stream_offset = 0;
549 c->interrupt_callback = &s->interrupt_callback;
551 // if the URL context is good, read important options we must broker later
552 if (u && u->prot->priv_data_class) {
553 // get the previous user agent & set back to null if string size is zero
554 av_freep(&c->user_agent);
555 av_opt_get(u->priv_data, "user-agent", 0, (uint8_t**)&(c->user_agent));
556 if (c->user_agent && !strlen(c->user_agent))
557 av_freep(&c->user_agent);
559 // get the previous cookies & set back to null if string size is zero
560 av_freep(&c->cookies);
561 av_opt_get(u->priv_data, "cookies", 0, (uint8_t**)&(c->cookies));
562 if (c->cookies && !strlen(c->cookies))
563 av_freep(&c->cookies);
565 // get the previous headers & set back to null if string size is zero
566 av_freep(&c->headers);
567 av_opt_get(u->priv_data, "headers", 0, (uint8_t**)&(c->headers));
568 if (c->headers && !strlen(c->headers))
569 av_freep(&c->headers);
572 if ((ret = parse_playlist(c, s->filename, NULL, s->pb)) < 0)
575 if (c->n_variants == 0) {
576 av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
580 /* If the playlist only contained playlists (Master Playlist),
581 * parse each individual playlist. */
582 if (c->n_playlists > 1 || c->playlists[0]->n_segments == 0) {
583 for (i = 0; i < c->n_playlists; i++) {
584 struct playlist *pls = c->playlists[i];
585 if ((ret = parse_playlist(c, pls->url, pls, NULL)) < 0)
590 if (c->variants[0]->playlists[0]->n_segments == 0) {
591 av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
596 /* If this isn't a live stream, calculate the total duration of the
598 if (c->variants[0]->playlists[0]->finished) {
599 int64_t duration = 0;
600 for (i = 0; i < c->variants[0]->playlists[0]->n_segments; i++)
601 duration += c->variants[0]->playlists[0]->segments[i]->duration;
602 s->duration = duration;
605 /* Open the demuxer for each playlist */
606 for (i = 0; i < c->n_playlists; i++) {
607 struct playlist *pls = c->playlists[i];
608 AVInputFormat *in_fmt = NULL;
610 if (pls->n_segments == 0)
613 if (!(pls->ctx = avformat_alloc_context())) {
614 ret = AVERROR(ENOMEM);
622 /* If this is a live stream with more than 3 segments, start at the
623 * third last segment. */
624 pls->cur_seq_no = pls->start_seq_no;
625 if (!pls->finished && pls->n_segments > 3)
626 pls->cur_seq_no = pls->start_seq_no + pls->n_segments - 3;
628 pls->read_buffer = av_malloc(INITIAL_BUFFER_SIZE);
629 ffio_init_context(&pls->pb, pls->read_buffer, INITIAL_BUFFER_SIZE, 0, pls,
630 read_data, NULL, NULL);
631 pls->pb.seekable = 0;
632 ret = av_probe_input_buffer(&pls->pb, &in_fmt, pls->segments[0]->url,
635 /* Free the ctx - it isn't initialized properly at this point,
636 * so avformat_close_input shouldn't be called. If
637 * avformat_open_input fails below, it frees and zeros the
638 * context, so it doesn't need any special treatment like this. */
639 av_log(s, AV_LOG_ERROR, "Error when loading first segment '%s'\n", pls->segments[0]->url);
640 avformat_free_context(pls->ctx);
644 pls->ctx->pb = &pls->pb;
645 pls->stream_offset = stream_offset;
646 ret = avformat_open_input(&pls->ctx, pls->segments[0]->url, in_fmt, NULL);
650 pls->ctx->ctx_flags &= ~AVFMTCTX_NOHEADER;
651 ret = avformat_find_stream_info(pls->ctx, NULL);
655 /* Create new AVStreams for each stream in this playlist */
656 for (j = 0; j < pls->ctx->nb_streams; j++) {
657 AVStream *st = avformat_new_stream(s, NULL);
658 AVStream *ist = pls->ctx->streams[j];
660 ret = AVERROR(ENOMEM);
664 avpriv_set_pts_info(st, ist->pts_wrap_bits, ist->time_base.num, ist->time_base.den);
665 avcodec_copy_context(st->codec, pls->ctx->streams[j]->codec);
668 stream_offset += pls->ctx->nb_streams;
671 /* Create a program for each variant */
672 for (i = 0; i < c->n_variants; i++) {
673 struct variant *v = c->variants[i];
674 char bitrate_str[20];
677 snprintf(bitrate_str, sizeof(bitrate_str), "%d", v->bandwidth);
679 program = av_new_program(s, i);
682 av_dict_set(&program->metadata, "variant_bitrate", bitrate_str, 0);
684 for (j = 0; j < v->n_playlists; j++) {
685 struct playlist *pls = v->playlists[j];
686 int is_shared = playlist_in_multiple_variants(c, pls);
689 for (k = 0; k < pls->ctx->nb_streams; k++) {
690 struct AVStream *st = s->streams[pls->stream_offset + k];
692 ff_program_add_stream_index(s, i, pls->stream_offset + k);
694 /* Set variant_bitrate for streams unique to this variant */
695 if (!is_shared && v->bandwidth)
696 av_dict_set(&st->metadata, "variant_bitrate", bitrate_str, 0);
702 c->first_timestamp = AV_NOPTS_VALUE;
703 c->seek_timestamp = AV_NOPTS_VALUE;
707 free_playlist_list(c);
708 free_variant_list(c);
712 static int recheck_discard_flags(AVFormatContext *s, int first)
714 HLSContext *c = s->priv_data;
717 /* Check if any new streams are needed */
718 for (i = 0; i < c->n_playlists; i++)
719 c->playlists[i]->cur_needed = 0;
721 for (i = 0; i < s->nb_streams; i++) {
722 AVStream *st = s->streams[i];
723 struct playlist *pls = c->playlists[s->streams[i]->id];
724 if (st->discard < AVDISCARD_ALL)
727 for (i = 0; i < c->n_playlists; i++) {
728 struct playlist *pls = c->playlists[i];
729 if (pls->cur_needed && !pls->needed) {
732 pls->cur_seq_no = c->cur_seq_no;
733 pls->pb.eof_reached = 0;
734 av_log(s, AV_LOG_INFO, "Now receiving playlist %d\n", i);
735 } else if (first && !pls->cur_needed && pls->needed) {
737 ffurl_close(pls->input);
741 av_log(s, AV_LOG_INFO, "No longer receiving playlist %d\n", i);
747 static int hls_read_packet(AVFormatContext *s, AVPacket *pkt)
749 HLSContext *c = s->priv_data;
750 int ret, i, minplaylist = -1;
752 if (c->first_packet) {
753 recheck_discard_flags(s, 1);
758 c->end_of_segment = 0;
759 for (i = 0; i < c->n_playlists; i++) {
760 struct playlist *pls = c->playlists[i];
761 /* Make sure we've got one buffered packet from each open playlist
763 if (pls->needed && !pls->pkt.data) {
767 ret = av_read_frame(pls->ctx, &pls->pkt);
769 if (!url_feof(&pls->pb) && ret != AVERROR_EOF)
771 reset_packet(&pls->pkt);
774 if (c->first_timestamp == AV_NOPTS_VALUE &&
775 pls->pkt.dts != AV_NOPTS_VALUE)
776 c->first_timestamp = av_rescale_q(pls->pkt.dts,
777 pls->ctx->streams[pls->pkt.stream_index]->time_base,
781 if (c->seek_timestamp == AV_NOPTS_VALUE)
784 if (pls->pkt.dts == AV_NOPTS_VALUE) {
785 c->seek_timestamp = AV_NOPTS_VALUE;
789 st = pls->ctx->streams[pls->pkt.stream_index];
790 ts_diff = av_rescale_rnd(pls->pkt.dts, AV_TIME_BASE,
791 st->time_base.den, AV_ROUND_DOWN) -
793 if (ts_diff >= 0 && (c->seek_flags & AVSEEK_FLAG_ANY ||
794 pls->pkt.flags & AV_PKT_FLAG_KEY)) {
795 c->seek_timestamp = AV_NOPTS_VALUE;
798 av_free_packet(&pls->pkt);
799 reset_packet(&pls->pkt);
802 /* Check if this stream still is on an earlier segment number, or
803 * has the packet with the lowest dts */
805 struct playlist *minpls = minplaylist < 0 ?
806 NULL : c->playlists[minplaylist];
807 if (minplaylist < 0 || pls->cur_seq_no < minpls->cur_seq_no) {
809 } else if (pls->cur_seq_no == minpls->cur_seq_no) {
810 int64_t dts = pls->pkt.dts;
811 int64_t mindts = minpls->pkt.dts;
812 AVStream *st = pls->ctx->streams[pls->pkt.stream_index];
813 AVStream *minst = minpls->ctx->streams[minpls->pkt.stream_index];
815 if (dts == AV_NOPTS_VALUE) {
817 } else if (mindts != AV_NOPTS_VALUE) {
818 if (st->start_time != AV_NOPTS_VALUE)
819 dts -= st->start_time;
820 if (minst->start_time != AV_NOPTS_VALUE)
821 mindts -= minst->start_time;
823 if (av_compare_ts(dts, st->time_base,
824 mindts, minst->time_base) < 0)
830 if (c->end_of_segment) {
831 if (recheck_discard_flags(s, 0))
834 /* If we got a packet, return it */
835 if (minplaylist >= 0) {
836 *pkt = c->playlists[minplaylist]->pkt;
837 pkt->stream_index += c->playlists[minplaylist]->stream_offset;
838 reset_packet(&c->playlists[minplaylist]->pkt);
844 static int hls_close(AVFormatContext *s)
846 HLSContext *c = s->priv_data;
848 free_playlist_list(c);
849 free_variant_list(c);
853 static int hls_read_seek(AVFormatContext *s, int stream_index,
854 int64_t timestamp, int flags)
856 HLSContext *c = s->priv_data;
859 if ((flags & AVSEEK_FLAG_BYTE) || !c->variants[0]->playlists[0]->finished)
860 return AVERROR(ENOSYS);
862 c->seek_flags = flags;
863 c->seek_timestamp = stream_index < 0 ? timestamp :
864 av_rescale_rnd(timestamp, AV_TIME_BASE,
865 s->streams[stream_index]->time_base.den,
866 flags & AVSEEK_FLAG_BACKWARD ?
867 AV_ROUND_DOWN : AV_ROUND_UP);
868 timestamp = av_rescale_rnd(timestamp, AV_TIME_BASE, stream_index >= 0 ?
869 s->streams[stream_index]->time_base.den :
870 AV_TIME_BASE, flags & AVSEEK_FLAG_BACKWARD ?
871 AV_ROUND_DOWN : AV_ROUND_UP);
872 if (s->duration < c->seek_timestamp) {
873 c->seek_timestamp = AV_NOPTS_VALUE;
878 for (i = 0; i < c->n_playlists; i++) {
880 struct playlist *pls = c->playlists[i];
881 int64_t pos = c->first_timestamp == AV_NOPTS_VALUE ?
882 0 : c->first_timestamp;
884 ffurl_close(pls->input);
887 av_free_packet(&pls->pkt);
888 reset_packet(&pls->pkt);
889 pls->pb.eof_reached = 0;
890 /* Clear any buffered data */
891 pls->pb.buf_end = pls->pb.buf_ptr = pls->pb.buffer;
892 /* Reset the pos, to let the mpegts demuxer know we've seeked. */
895 /* Locate the segment that contains the target timestamp */
896 for (j = 0; j < pls->n_segments; j++) {
897 if (timestamp >= pos &&
898 timestamp < pos + pls->segments[j]->duration) {
899 pls->cur_seq_no = pls->start_seq_no + j;
903 pos += pls->segments[j]->duration;
906 c->seek_timestamp = AV_NOPTS_VALUE;
911 static int hls_probe(AVProbeData *p)
913 /* Require #EXTM3U at the start, and either one of the ones below
914 * somewhere for a proper match. */
915 if (strncmp(p->buf, "#EXTM3U", 7))
917 if (strstr(p->buf, "#EXT-X-STREAM-INF:") ||
918 strstr(p->buf, "#EXT-X-TARGETDURATION:") ||
919 strstr(p->buf, "#EXT-X-MEDIA-SEQUENCE:"))
920 return AVPROBE_SCORE_MAX;
924 AVInputFormat ff_hls_demuxer = {
925 .name = "hls,applehttp",
926 .long_name = NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming"),
927 .priv_data_size = sizeof(HLSContext),
928 .read_probe = hls_probe,
929 .read_header = hls_read_header,
930 .read_packet = hls_read_packet,
931 .read_close = hls_close,
932 .read_seek = hls_read_seek,