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;
390 AVDictionary *opts2 = NULL;
392 struct segment *seg = pls->segments[pls->cur_seq_no - pls->start_seq_no];
394 // broker prior HTTP options that should be consistent across requests
395 av_dict_set(&opts, "user-agent", c->user_agent, 0);
396 av_dict_set(&opts, "cookies", c->cookies, 0);
397 av_dict_set(&opts, "headers", c->headers, 0);
398 av_dict_set(&opts, "seekable", "0", 0);
400 // Same opts for key request (ffurl_open mutilates the opts so it cannot be used twice)
401 av_dict_copy(&opts2, opts, 0);
403 if (seg->key_type == KEY_NONE) {
404 ret = ffurl_open(&pls->input, seg->url, AVIO_FLAG_READ,
405 &pls->parent->interrupt_callback, &opts);
407 } else if (seg->key_type == KEY_AES_128) {
408 char iv[33], key[33], url[MAX_URL_SIZE];
409 if (strcmp(seg->key, pls->key_url)) {
411 if (ffurl_open(&uc, seg->key, AVIO_FLAG_READ,
412 &pls->parent->interrupt_callback, &opts2) == 0) {
413 if (ffurl_read_complete(uc, pls->key, sizeof(pls->key))
414 != sizeof(pls->key)) {
415 av_log(NULL, AV_LOG_ERROR, "Unable to read key file %s\n",
420 av_log(NULL, AV_LOG_ERROR, "Unable to open key file %s\n",
423 av_strlcpy(pls->key_url, seg->key, sizeof(pls->key_url));
425 ff_data_to_hex(iv, seg->iv, sizeof(seg->iv), 0);
426 ff_data_to_hex(key, pls->key, sizeof(pls->key), 0);
427 iv[32] = key[32] = '\0';
428 if (strstr(seg->url, "://"))
429 snprintf(url, sizeof(url), "crypto+%s", seg->url);
431 snprintf(url, sizeof(url), "crypto:%s", seg->url);
432 if ((ret = ffurl_alloc(&pls->input, url, AVIO_FLAG_READ,
433 &pls->parent->interrupt_callback)) < 0)
435 av_opt_set(pls->input->priv_data, "key", key, 0);
436 av_opt_set(pls->input->priv_data, "iv", iv, 0);
438 if ((ret = ffurl_connect(pls->input, &opts)) < 0) {
439 ffurl_close(pls->input);
446 ret = AVERROR(ENOSYS);
450 av_dict_free(&opts2);
454 static int read_data(void *opaque, uint8_t *buf, int buf_size)
456 struct playlist *v = opaque;
457 HLSContext *c = v->parent->priv_data;
462 /* If this is a live stream and the reload interval has elapsed since
463 * the last playlist reload, reload the playlists now. */
464 int64_t reload_interval = v->n_segments > 0 ?
465 v->segments[v->n_segments - 1]->duration :
470 av_gettime() - v->last_load_time >= reload_interval) {
471 if ((ret = parse_playlist(c, v->url, v, NULL)) < 0)
473 /* If we need to reload the playlist again below (if
474 * there's still no more segments), switch to a reload
475 * interval of half the target duration. */
476 reload_interval = v->target_duration / 2;
478 if (v->cur_seq_no < v->start_seq_no) {
479 av_log(NULL, AV_LOG_WARNING,
480 "skipping %d segments ahead, expired from playlists\n",
481 v->start_seq_no - v->cur_seq_no);
482 v->cur_seq_no = v->start_seq_no;
484 if (v->cur_seq_no >= v->start_seq_no + v->n_segments) {
487 while (av_gettime() - v->last_load_time < reload_interval) {
488 if (ff_check_interrupt(c->interrupt_callback))
492 /* Enough time has elapsed since the last reload */
496 ret = open_input(c, v);
500 ret = ffurl_read(v->input, buf, buf_size);
503 ffurl_close(v->input);
507 c->end_of_segment = 1;
508 c->cur_seq_no = v->cur_seq_no;
510 if (v->ctx && v->ctx->nb_streams &&
511 v->parent->nb_streams >= v->stream_offset + v->ctx->nb_streams) {
513 for (i = v->stream_offset; i < v->stream_offset + v->ctx->nb_streams;
515 if (v->parent->streams[i]->discard < AVDISCARD_ALL)
520 av_log(v->parent, AV_LOG_INFO, "No longer receiving playlist %d\n",
527 static int playlist_in_multiple_variants(HLSContext *c, struct playlist *pls)
529 int variant_count = 0;
532 for (i = 0; i < c->n_variants && variant_count < 2; i++) {
533 struct variant *v = c->variants[i];
535 for (j = 0; j < v->n_playlists; j++) {
536 if (v->playlists[j] == pls) {
543 return variant_count >= 2;
546 static int hls_read_header(AVFormatContext *s)
548 URLContext *u = (s->flags & AVFMT_FLAG_CUSTOM_IO) ? NULL : s->pb->opaque;
549 HLSContext *c = s->priv_data;
550 int ret = 0, i, j, stream_offset = 0;
552 c->interrupt_callback = &s->interrupt_callback;
554 // if the URL context is good, read important options we must broker later
555 if (u && u->prot->priv_data_class) {
556 // get the previous user agent & set back to null if string size is zero
557 av_freep(&c->user_agent);
558 av_opt_get(u->priv_data, "user-agent", 0, (uint8_t**)&(c->user_agent));
559 if (c->user_agent && !strlen(c->user_agent))
560 av_freep(&c->user_agent);
562 // get the previous cookies & set back to null if string size is zero
563 av_freep(&c->cookies);
564 av_opt_get(u->priv_data, "cookies", 0, (uint8_t**)&(c->cookies));
565 if (c->cookies && !strlen(c->cookies))
566 av_freep(&c->cookies);
568 // get the previous headers & set back to null if string size is zero
569 av_freep(&c->headers);
570 av_opt_get(u->priv_data, "headers", 0, (uint8_t**)&(c->headers));
571 if (c->headers && !strlen(c->headers))
572 av_freep(&c->headers);
575 if ((ret = parse_playlist(c, s->filename, NULL, s->pb)) < 0)
578 if (c->n_variants == 0) {
579 av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
583 /* If the playlist only contained playlists (Master Playlist),
584 * parse each individual playlist. */
585 if (c->n_playlists > 1 || c->playlists[0]->n_segments == 0) {
586 for (i = 0; i < c->n_playlists; i++) {
587 struct playlist *pls = c->playlists[i];
588 if ((ret = parse_playlist(c, pls->url, pls, NULL)) < 0)
593 if (c->variants[0]->playlists[0]->n_segments == 0) {
594 av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
599 /* If this isn't a live stream, calculate the total duration of the
601 if (c->variants[0]->playlists[0]->finished) {
602 int64_t duration = 0;
603 for (i = 0; i < c->variants[0]->playlists[0]->n_segments; i++)
604 duration += c->variants[0]->playlists[0]->segments[i]->duration;
605 s->duration = duration;
608 /* Open the demuxer for each playlist */
609 for (i = 0; i < c->n_playlists; i++) {
610 struct playlist *pls = c->playlists[i];
611 AVInputFormat *in_fmt = NULL;
613 if (pls->n_segments == 0)
616 if (!(pls->ctx = avformat_alloc_context())) {
617 ret = AVERROR(ENOMEM);
625 /* If this is a live stream with more than 3 segments, start at the
626 * third last segment. */
627 pls->cur_seq_no = pls->start_seq_no;
628 if (!pls->finished && pls->n_segments > 3)
629 pls->cur_seq_no = pls->start_seq_no + pls->n_segments - 3;
631 pls->read_buffer = av_malloc(INITIAL_BUFFER_SIZE);
632 ffio_init_context(&pls->pb, pls->read_buffer, INITIAL_BUFFER_SIZE, 0, pls,
633 read_data, NULL, NULL);
634 pls->pb.seekable = 0;
635 ret = av_probe_input_buffer(&pls->pb, &in_fmt, pls->segments[0]->url,
638 /* Free the ctx - it isn't initialized properly at this point,
639 * so avformat_close_input shouldn't be called. If
640 * avformat_open_input fails below, it frees and zeros the
641 * context, so it doesn't need any special treatment like this. */
642 av_log(s, AV_LOG_ERROR, "Error when loading first segment '%s'\n", pls->segments[0]->url);
643 avformat_free_context(pls->ctx);
647 pls->ctx->pb = &pls->pb;
648 pls->stream_offset = stream_offset;
649 ret = avformat_open_input(&pls->ctx, pls->segments[0]->url, in_fmt, NULL);
653 pls->ctx->ctx_flags &= ~AVFMTCTX_NOHEADER;
654 ret = avformat_find_stream_info(pls->ctx, NULL);
658 /* Create new AVStreams for each stream in this playlist */
659 for (j = 0; j < pls->ctx->nb_streams; j++) {
660 AVStream *st = avformat_new_stream(s, NULL);
661 AVStream *ist = pls->ctx->streams[j];
663 ret = AVERROR(ENOMEM);
667 avpriv_set_pts_info(st, ist->pts_wrap_bits, ist->time_base.num, ist->time_base.den);
668 avcodec_copy_context(st->codec, pls->ctx->streams[j]->codec);
671 stream_offset += pls->ctx->nb_streams;
674 /* Create a program for each variant */
675 for (i = 0; i < c->n_variants; i++) {
676 struct variant *v = c->variants[i];
677 char bitrate_str[20];
680 snprintf(bitrate_str, sizeof(bitrate_str), "%d", v->bandwidth);
682 program = av_new_program(s, i);
685 av_dict_set(&program->metadata, "variant_bitrate", bitrate_str, 0);
687 for (j = 0; j < v->n_playlists; j++) {
688 struct playlist *pls = v->playlists[j];
689 int is_shared = playlist_in_multiple_variants(c, pls);
692 for (k = 0; k < pls->ctx->nb_streams; k++) {
693 struct AVStream *st = s->streams[pls->stream_offset + k];
695 ff_program_add_stream_index(s, i, pls->stream_offset + k);
697 /* Set variant_bitrate for streams unique to this variant */
698 if (!is_shared && v->bandwidth)
699 av_dict_set(&st->metadata, "variant_bitrate", bitrate_str, 0);
705 c->first_timestamp = AV_NOPTS_VALUE;
706 c->seek_timestamp = AV_NOPTS_VALUE;
710 free_playlist_list(c);
711 free_variant_list(c);
715 static int recheck_discard_flags(AVFormatContext *s, int first)
717 HLSContext *c = s->priv_data;
720 /* Check if any new streams are needed */
721 for (i = 0; i < c->n_playlists; i++)
722 c->playlists[i]->cur_needed = 0;
724 for (i = 0; i < s->nb_streams; i++) {
725 AVStream *st = s->streams[i];
726 struct playlist *pls = c->playlists[s->streams[i]->id];
727 if (st->discard < AVDISCARD_ALL)
730 for (i = 0; i < c->n_playlists; i++) {
731 struct playlist *pls = c->playlists[i];
732 if (pls->cur_needed && !pls->needed) {
735 pls->cur_seq_no = c->cur_seq_no;
736 pls->pb.eof_reached = 0;
737 av_log(s, AV_LOG_INFO, "Now receiving playlist %d\n", i);
738 } else if (first && !pls->cur_needed && pls->needed) {
740 ffurl_close(pls->input);
744 av_log(s, AV_LOG_INFO, "No longer receiving playlist %d\n", i);
750 static int hls_read_packet(AVFormatContext *s, AVPacket *pkt)
752 HLSContext *c = s->priv_data;
753 int ret, i, minplaylist = -1;
755 if (c->first_packet) {
756 recheck_discard_flags(s, 1);
761 c->end_of_segment = 0;
762 for (i = 0; i < c->n_playlists; i++) {
763 struct playlist *pls = c->playlists[i];
764 /* Make sure we've got one buffered packet from each open playlist
766 if (pls->needed && !pls->pkt.data) {
770 ret = av_read_frame(pls->ctx, &pls->pkt);
772 if (!url_feof(&pls->pb) && ret != AVERROR_EOF)
774 reset_packet(&pls->pkt);
777 if (c->first_timestamp == AV_NOPTS_VALUE &&
778 pls->pkt.dts != AV_NOPTS_VALUE)
779 c->first_timestamp = av_rescale_q(pls->pkt.dts,
780 pls->ctx->streams[pls->pkt.stream_index]->time_base,
784 if (c->seek_timestamp == AV_NOPTS_VALUE)
787 if (pls->pkt.dts == AV_NOPTS_VALUE) {
788 c->seek_timestamp = AV_NOPTS_VALUE;
792 st = pls->ctx->streams[pls->pkt.stream_index];
793 ts_diff = av_rescale_rnd(pls->pkt.dts, AV_TIME_BASE,
794 st->time_base.den, AV_ROUND_DOWN) -
796 if (ts_diff >= 0 && (c->seek_flags & AVSEEK_FLAG_ANY ||
797 pls->pkt.flags & AV_PKT_FLAG_KEY)) {
798 c->seek_timestamp = AV_NOPTS_VALUE;
801 av_free_packet(&pls->pkt);
802 reset_packet(&pls->pkt);
805 /* Check if this stream still is on an earlier segment number, or
806 * has the packet with the lowest dts */
808 struct playlist *minpls = minplaylist < 0 ?
809 NULL : c->playlists[minplaylist];
810 if (minplaylist < 0 || pls->cur_seq_no < minpls->cur_seq_no) {
812 } else if (pls->cur_seq_no == minpls->cur_seq_no) {
813 int64_t dts = pls->pkt.dts;
814 int64_t mindts = minpls->pkt.dts;
815 AVStream *st = pls->ctx->streams[pls->pkt.stream_index];
816 AVStream *minst = minpls->ctx->streams[minpls->pkt.stream_index];
818 if (dts == AV_NOPTS_VALUE) {
820 } else if (mindts != AV_NOPTS_VALUE) {
821 if (st->start_time != AV_NOPTS_VALUE)
822 dts -= st->start_time;
823 if (minst->start_time != AV_NOPTS_VALUE)
824 mindts -= minst->start_time;
826 if (av_compare_ts(dts, st->time_base,
827 mindts, minst->time_base) < 0)
833 if (c->end_of_segment) {
834 if (recheck_discard_flags(s, 0))
837 /* If we got a packet, return it */
838 if (minplaylist >= 0) {
839 *pkt = c->playlists[minplaylist]->pkt;
840 pkt->stream_index += c->playlists[minplaylist]->stream_offset;
841 reset_packet(&c->playlists[minplaylist]->pkt);
847 static int hls_close(AVFormatContext *s)
849 HLSContext *c = s->priv_data;
851 free_playlist_list(c);
852 free_variant_list(c);
856 static int hls_read_seek(AVFormatContext *s, int stream_index,
857 int64_t timestamp, int flags)
859 HLSContext *c = s->priv_data;
862 if ((flags & AVSEEK_FLAG_BYTE) || !c->variants[0]->playlists[0]->finished)
863 return AVERROR(ENOSYS);
865 c->seek_flags = flags;
866 c->seek_timestamp = stream_index < 0 ? timestamp :
867 av_rescale_rnd(timestamp, AV_TIME_BASE,
868 s->streams[stream_index]->time_base.den,
869 flags & AVSEEK_FLAG_BACKWARD ?
870 AV_ROUND_DOWN : AV_ROUND_UP);
871 timestamp = av_rescale_rnd(timestamp, AV_TIME_BASE, stream_index >= 0 ?
872 s->streams[stream_index]->time_base.den :
873 AV_TIME_BASE, flags & AVSEEK_FLAG_BACKWARD ?
874 AV_ROUND_DOWN : AV_ROUND_UP);
875 if (s->duration < c->seek_timestamp) {
876 c->seek_timestamp = AV_NOPTS_VALUE;
881 for (i = 0; i < c->n_playlists; i++) {
883 struct playlist *pls = c->playlists[i];
884 int64_t pos = c->first_timestamp == AV_NOPTS_VALUE ?
885 0 : c->first_timestamp;
887 ffurl_close(pls->input);
890 av_free_packet(&pls->pkt);
891 reset_packet(&pls->pkt);
892 pls->pb.eof_reached = 0;
893 /* Clear any buffered data */
894 pls->pb.buf_end = pls->pb.buf_ptr = pls->pb.buffer;
895 /* Reset the pos, to let the mpegts demuxer know we've seeked. */
898 /* Locate the segment that contains the target timestamp */
899 for (j = 0; j < pls->n_segments; j++) {
900 if (timestamp >= pos &&
901 timestamp < pos + pls->segments[j]->duration) {
902 pls->cur_seq_no = pls->start_seq_no + j;
906 pos += pls->segments[j]->duration;
909 c->seek_timestamp = AV_NOPTS_VALUE;
914 static int hls_probe(AVProbeData *p)
916 /* Require #EXTM3U at the start, and either one of the ones below
917 * somewhere for a proper match. */
918 if (strncmp(p->buf, "#EXTM3U", 7))
920 if (strstr(p->buf, "#EXT-X-STREAM-INF:") ||
921 strstr(p->buf, "#EXT-X-TARGETDURATION:") ||
922 strstr(p->buf, "#EXT-X-MEDIA-SEQUENCE:"))
923 return AVPROBE_SCORE_MAX;
927 AVInputFormat ff_hls_demuxer = {
928 .name = "hls,applehttp",
929 .long_name = NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming"),
930 .priv_data_size = sizeof(HLSContext),
931 .read_probe = hls_probe,
932 .read_header = hls_read_header,
933 .read_packet = hls_read_packet,
934 .read_close = hls_close,
935 .read_seek = hls_read_seek,