2 * Apple HTTP Live Streaming demuxer
3 * Copyright (c) 2010 Martin Storsjo
4 * Copyright (c) 2013 Anssi Hannula
6 * This file is part of FFmpeg.
8 * FFmpeg is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * FFmpeg is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with FFmpeg; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25 * Apple HTTP Live Streaming demuxer
26 * http://tools.ietf.org/html/draft-pantos-http-live-streaming
29 #include "libavutil/avstring.h"
30 #include "libavutil/avassert.h"
31 #include "libavutil/intreadwrite.h"
32 #include "libavutil/mathematics.h"
33 #include "libavutil/opt.h"
34 #include "libavutil/dict.h"
35 #include "libavutil/time.h"
38 #include "avio_internal.h"
42 #define INITIAL_BUFFER_SIZE 32768
44 #define MAX_FIELD_LEN 64
45 #define MAX_CHARACTERISTICS_LEN 512
47 #define MPEG_TIME_BASE 90000
48 #define MPEG_TIME_BASE_Q (AVRational){1, MPEG_TIME_BASE}
51 * An apple http stream consists of a playlist with media segment files,
52 * played sequentially. There may be several playlists with the same
53 * video content, in different bandwidth variants, that are played in
54 * parallel (preferably only one bandwidth variant at a time). In this case,
55 * the user supplied the url to a main playlist that only lists the variant
58 * If the main playlist doesn't point at any variants, we still create
59 * one anonymous toplevel variant for this, to maintain the structure.
71 char url[MAX_URL_SIZE];
72 char key[MAX_URL_SIZE];
73 enum KeyType key_type;
80 * Each playlist has its own demuxer. If it currently is active,
81 * it has an open AVIOContext too, and potentially an AVPacket
82 * containing the next packet from this stream.
85 char url[MAX_URL_SIZE];
89 AVFormatContext *parent;
96 int64_t target_duration;
99 struct segment **segments;
100 int needed, cur_needed;
102 int64_t cur_seg_offset;
103 int64_t last_load_time;
105 char key_url[MAX_URL_SIZE];
108 /* ID3 timestamp handling (elementary audio streams have ID3 timestamps
109 * (and possibly other ID3 tags) in the beginning of each segment) */
110 int is_id3_timestamped; /* -1: not yet known */
111 int64_t id3_mpegts_timestamp; /* in mpegts tb */
112 int64_t id3_offset; /* in stream original tb */
113 uint8_t* id3_buf; /* temp buffer for id3 parsing */
114 unsigned int id3_buf_size;
115 AVDictionary *id3_initial; /* data from first id3 tag */
116 int id3_found; /* ID3 tag found at some point */
117 int id3_changed; /* ID3 tag data has changed at some point */
118 ID3v2ExtraMeta *id3_deferred_extra; /* stored here until subdemuxer is opened */
120 int64_t seek_timestamp;
123 /* Renditions associated with this playlist, if any.
124 * Alternative rendition playlists have a single rendition associated
125 * with them, and variant main Media Playlists may have
126 * multiple (playlist-less) renditions associated with them. */
128 struct rendition **renditions;
132 * Renditions are e.g. alternative subtitle or audio streams.
133 * The rendition may either be an external playlist or it may be
134 * contained in the main Media Playlist of the variant (in which case
138 enum AVMediaType type;
139 struct playlist *playlist;
140 char group_id[MAX_FIELD_LEN];
141 char language[MAX_FIELD_LEN];
142 char name[MAX_FIELD_LEN];
149 /* every variant contains at least the main Media Playlist in index 0 */
151 struct playlist **playlists;
153 char audio_group[MAX_FIELD_LEN];
154 char video_group[MAX_FIELD_LEN];
155 char subtitles_group[MAX_FIELD_LEN];
158 typedef struct HLSContext {
160 struct variant **variants;
162 struct playlist **playlists;
164 struct rendition **renditions;
169 int64_t first_timestamp;
170 int64_t cur_timestamp;
171 AVIOInterruptCB *interrupt_callback;
172 char *user_agent; ///< holds HTTP user agent set as an AVOption to the HTTP protocol context
173 char *cookies; ///< holds HTTP cookie values set in either the initial response or as an AVOption to the HTTP protocol context
174 char *headers; ///< holds HTTP headers set as an AVOption to the HTTP protocol context
177 static int read_chomp_line(AVIOContext *s, char *buf, int maxlen)
179 int len = ff_get_line(s, buf, maxlen);
180 while (len > 0 && av_isspace(buf[len - 1]))
185 static void free_segment_list(struct playlist *pls)
188 for (i = 0; i < pls->n_segments; i++)
189 av_free(pls->segments[i]);
190 av_freep(&pls->segments);
194 static void free_playlist_list(HLSContext *c)
197 for (i = 0; i < c->n_playlists; i++) {
198 struct playlist *pls = c->playlists[i];
199 free_segment_list(pls);
200 av_freep(&pls->renditions);
201 av_freep(&pls->id3_buf);
202 av_dict_free(&pls->id3_initial);
203 ff_id3v2_free_extra_meta(&pls->id3_deferred_extra);
204 av_free_packet(&pls->pkt);
205 av_free(pls->pb.buffer);
207 ffurl_close(pls->input);
210 avformat_close_input(&pls->ctx);
214 av_freep(&c->playlists);
215 av_freep(&c->cookies);
216 av_freep(&c->user_agent);
220 static void free_variant_list(HLSContext *c)
223 for (i = 0; i < c->n_variants; i++) {
224 struct variant *var = c->variants[i];
225 av_freep(&var->playlists);
228 av_freep(&c->variants);
232 static void free_rendition_list(HLSContext *c)
235 for (i = 0; i < c->n_renditions; i++)
236 av_free(c->renditions[i]);
237 av_freep(&c->renditions);
242 * Used to reset a statically allocated AVPacket to a clean slate,
243 * containing no data.
245 static void reset_packet(AVPacket *pkt)
251 static struct playlist *new_playlist(HLSContext *c, const char *url,
254 struct playlist *pls = av_mallocz(sizeof(struct playlist));
257 reset_packet(&pls->pkt);
258 ff_make_absolute_url(pls->url, sizeof(pls->url), base, url);
259 pls->seek_timestamp = AV_NOPTS_VALUE;
261 pls->is_id3_timestamped = -1;
262 pls->id3_mpegts_timestamp = AV_NOPTS_VALUE;
264 dynarray_add(&c->playlists, &c->n_playlists, pls);
268 struct variant_info {
270 /* variant group ids: */
271 char audio[MAX_FIELD_LEN];
272 char video[MAX_FIELD_LEN];
273 char subtitles[MAX_FIELD_LEN];
276 static struct variant *new_variant(HLSContext *c, struct variant_info *info,
277 const char *url, const char *base)
280 struct playlist *pls;
282 pls = new_playlist(c, url, base);
286 var = av_mallocz(sizeof(struct variant));
291 var->bandwidth = atoi(info->bandwidth);
292 strcpy(var->audio_group, info->audio);
293 strcpy(var->video_group, info->video);
294 strcpy(var->subtitles_group, info->subtitles);
297 dynarray_add(&c->variants, &c->n_variants, var);
298 dynarray_add(&var->playlists, &var->n_playlists, pls);
302 static void handle_variant_args(struct variant_info *info, const char *key,
303 int key_len, char **dest, int *dest_len)
305 if (!strncmp(key, "BANDWIDTH=", key_len)) {
306 *dest = info->bandwidth;
307 *dest_len = sizeof(info->bandwidth);
308 } else if (!strncmp(key, "AUDIO=", key_len)) {
310 *dest_len = sizeof(info->audio);
311 } else if (!strncmp(key, "VIDEO=", key_len)) {
313 *dest_len = sizeof(info->video);
314 } else if (!strncmp(key, "SUBTITLES=", key_len)) {
315 *dest = info->subtitles;
316 *dest_len = sizeof(info->subtitles);
321 char uri[MAX_URL_SIZE];
326 static void handle_key_args(struct key_info *info, const char *key,
327 int key_len, char **dest, int *dest_len)
329 if (!strncmp(key, "METHOD=", key_len)) {
330 *dest = info->method;
331 *dest_len = sizeof(info->method);
332 } else if (!strncmp(key, "URI=", key_len)) {
334 *dest_len = sizeof(info->uri);
335 } else if (!strncmp(key, "IV=", key_len)) {
337 *dest_len = sizeof(info->iv);
341 struct rendition_info {
343 char uri[MAX_URL_SIZE];
344 char group_id[MAX_FIELD_LEN];
345 char language[MAX_FIELD_LEN];
346 char assoc_language[MAX_FIELD_LEN];
347 char name[MAX_FIELD_LEN];
350 char characteristics[MAX_CHARACTERISTICS_LEN];
353 static struct rendition *new_rendition(HLSContext *c, struct rendition_info *info,
354 const char *url_base)
356 struct rendition *rend;
357 enum AVMediaType type = AVMEDIA_TYPE_UNKNOWN;
358 char *characteristic;
362 if (!strcmp(info->type, "AUDIO"))
363 type = AVMEDIA_TYPE_AUDIO;
364 else if (!strcmp(info->type, "VIDEO"))
365 type = AVMEDIA_TYPE_VIDEO;
366 else if (!strcmp(info->type, "SUBTITLES"))
367 type = AVMEDIA_TYPE_SUBTITLE;
368 else if (!strcmp(info->type, "CLOSED-CAPTIONS"))
369 /* CLOSED-CAPTIONS is ignored since we do not support CEA-608 CC in
370 * AVC SEI RBSP anyway */
373 if (type == AVMEDIA_TYPE_UNKNOWN)
376 /* URI is mandatory for subtitles as per spec */
377 if (type == AVMEDIA_TYPE_SUBTITLE && !info->uri[0])
380 /* TODO: handle subtitles (each segment has to parsed separately) */
381 if (type == AVMEDIA_TYPE_SUBTITLE)
384 rend = av_mallocz(sizeof(struct rendition));
388 dynarray_add(&c->renditions, &c->n_renditions, rend);
391 strcpy(rend->group_id, info->group_id);
392 strcpy(rend->language, info->language);
393 strcpy(rend->name, info->name);
395 /* add the playlist if this is an external rendition */
397 rend->playlist = new_playlist(c, info->uri, url_base);
399 dynarray_add(&rend->playlist->renditions,
400 &rend->playlist->n_renditions, rend);
403 if (info->assoc_language[0]) {
404 int langlen = strlen(rend->language);
405 if (langlen < sizeof(rend->language) - 3) {
406 rend->language[langlen] = ',';
407 strncpy(rend->language + langlen + 1, info->assoc_language,
408 sizeof(rend->language) - langlen - 2);
412 if (!strcmp(info->defaultr, "YES"))
413 rend->disposition |= AV_DISPOSITION_DEFAULT;
414 if (!strcmp(info->forced, "YES"))
415 rend->disposition |= AV_DISPOSITION_FORCED;
417 chr_ptr = info->characteristics;
418 while ((characteristic = av_strtok(chr_ptr, ",", &saveptr))) {
419 if (!strcmp(characteristic, "public.accessibility.describes-music-and-sound"))
420 rend->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
421 else if (!strcmp(characteristic, "public.accessibility.describes-video"))
422 rend->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED;
430 static void handle_rendition_args(struct rendition_info *info, const char *key,
431 int key_len, char **dest, int *dest_len)
433 if (!strncmp(key, "TYPE=", key_len)) {
435 *dest_len = sizeof(info->type);
436 } else if (!strncmp(key, "URI=", key_len)) {
438 *dest_len = sizeof(info->uri);
439 } else if (!strncmp(key, "GROUP-ID=", key_len)) {
440 *dest = info->group_id;
441 *dest_len = sizeof(info->group_id);
442 } else if (!strncmp(key, "LANGUAGE=", key_len)) {
443 *dest = info->language;
444 *dest_len = sizeof(info->language);
445 } else if (!strncmp(key, "ASSOC-LANGUAGE=", key_len)) {
446 *dest = info->assoc_language;
447 *dest_len = sizeof(info->assoc_language);
448 } else if (!strncmp(key, "NAME=", key_len)) {
450 *dest_len = sizeof(info->name);
451 } else if (!strncmp(key, "DEFAULT=", key_len)) {
452 *dest = info->defaultr;
453 *dest_len = sizeof(info->defaultr);
454 } else if (!strncmp(key, "FORCED=", key_len)) {
455 *dest = info->forced;
456 *dest_len = sizeof(info->forced);
457 } else if (!strncmp(key, "CHARACTERISTICS=", key_len)) {
458 *dest = info->characteristics;
459 *dest_len = sizeof(info->characteristics);
463 * - AUTOSELECT: client may autoselect based on e.g. system language
464 * - INSTREAM-ID: EIA-608 closed caption number ("CC1".."CC4")
468 static int parse_playlist(HLSContext *c, const char *url,
469 struct playlist *pls, AVIOContext *in)
471 int ret = 0, is_segment = 0, is_variant = 0;
472 int64_t duration = 0;
473 enum KeyType key_type = KEY_NONE;
476 char key[MAX_URL_SIZE] = "";
477 char line[MAX_URL_SIZE];
480 int64_t seg_offset = 0;
481 int64_t seg_size = -1;
482 uint8_t *new_url = NULL;
483 struct variant_info variant_info;
486 AVDictionary *opts = NULL;
488 /* Some HLS servers don't like being sent the range header */
489 av_dict_set(&opts, "seekable", "0", 0);
491 // broker prior HTTP options that should be consistent across requests
492 av_dict_set(&opts, "user-agent", c->user_agent, 0);
493 av_dict_set(&opts, "cookies", c->cookies, 0);
494 av_dict_set(&opts, "headers", c->headers, 0);
496 ret = avio_open2(&in, url, AVIO_FLAG_READ,
497 c->interrupt_callback, &opts);
503 if (av_opt_get(in, "location", AV_OPT_SEARCH_CHILDREN, &new_url) >= 0)
506 read_chomp_line(in, line, sizeof(line));
507 if (strcmp(line, "#EXTM3U")) {
508 ret = AVERROR_INVALIDDATA;
513 free_segment_list(pls);
516 while (!url_feof(in)) {
517 read_chomp_line(in, line, sizeof(line));
518 if (av_strstart(line, "#EXT-X-STREAM-INF:", &ptr)) {
520 memset(&variant_info, 0, sizeof(variant_info));
521 ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_variant_args,
523 } else if (av_strstart(line, "#EXT-X-KEY:", &ptr)) {
524 struct key_info info = {{0}};
525 ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_key_args,
529 if (!strcmp(info.method, "AES-128"))
530 key_type = KEY_AES_128;
531 if (!strncmp(info.iv, "0x", 2) || !strncmp(info.iv, "0X", 2)) {
532 ff_hex_to_data(iv, info.iv + 2);
535 av_strlcpy(key, info.uri, sizeof(key));
536 } else if (av_strstart(line, "#EXT-X-MEDIA:", &ptr)) {
537 struct rendition_info info = {{0}};
538 ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_rendition_args,
540 new_rendition(c, &info, url);
541 } else if (av_strstart(line, "#EXT-X-TARGETDURATION:", &ptr)) {
543 if (!new_variant(c, NULL, url, NULL)) {
544 ret = AVERROR(ENOMEM);
547 pls = c->playlists[c->n_playlists - 1];
549 pls->target_duration = atoi(ptr) * AV_TIME_BASE;
550 } else if (av_strstart(line, "#EXT-X-MEDIA-SEQUENCE:", &ptr)) {
552 if (!new_variant(c, NULL, url, NULL)) {
553 ret = AVERROR(ENOMEM);
556 pls = c->playlists[c->n_playlists - 1];
558 pls->start_seq_no = atoi(ptr);
559 } else if (av_strstart(line, "#EXT-X-ENDLIST", &ptr)) {
562 } else if (av_strstart(line, "#EXTINF:", &ptr)) {
564 duration = atof(ptr) * AV_TIME_BASE;
565 } else if (av_strstart(line, "#EXT-X-BYTERANGE:", &ptr)) {
566 seg_size = atoi(ptr);
567 ptr = strchr(ptr, '@');
569 seg_offset = atoi(ptr+1);
570 } else if (av_strstart(line, "#", NULL)) {
572 } else if (line[0]) {
574 if (!new_variant(c, &variant_info, line, url)) {
575 ret = AVERROR(ENOMEM);
583 if (!new_variant(c, 0, url, NULL)) {
584 ret = AVERROR(ENOMEM);
587 pls = c->playlists[c->n_playlists - 1];
589 seg = av_malloc(sizeof(struct segment));
591 ret = AVERROR(ENOMEM);
594 seg->duration = duration;
595 seg->key_type = key_type;
597 memcpy(seg->iv, iv, sizeof(iv));
599 int seq = pls->start_seq_no + pls->n_segments;
600 memset(seg->iv, 0, sizeof(seg->iv));
601 AV_WB32(seg->iv + 12, seq);
603 ff_make_absolute_url(seg->key, sizeof(seg->key), url, key);
604 ff_make_absolute_url(seg->url, sizeof(seg->url), url, line);
605 dynarray_add(&pls->segments, &pls->n_segments, seg);
608 seg->size = seg_size;
610 seg->url_offset = seg_offset;
611 seg_offset += seg_size;
621 pls->last_load_time = av_gettime();
630 enum ReadFromURLMode {
635 /* read from URLContext, limiting read to current segment */
636 static int read_from_url(struct playlist *pls, uint8_t *buf, int buf_size,
637 enum ReadFromURLMode mode)
640 struct segment *seg = pls->segments[pls->cur_seq_no - pls->start_seq_no];
642 /* limit read if the segment was only a part of a file */
644 buf_size = FFMIN(buf_size, seg->size - pls->cur_seg_offset);
646 if (mode == READ_COMPLETE)
647 ret = ffurl_read_complete(pls->input, buf, buf_size);
649 ret = ffurl_read(pls->input, buf, buf_size);
652 pls->cur_seg_offset += ret;
657 /* Parse the raw ID3 data and pass contents to caller */
658 static void parse_id3(AVFormatContext *s, AVIOContext *pb,
659 AVDictionary **metadata, int64_t *dts,
660 ID3v2ExtraMetaAPIC **apic, ID3v2ExtraMeta **extra_meta)
662 static const char id3_priv_owner_ts[] = "com.apple.streaming.transportStreamTimestamp";
663 ID3v2ExtraMeta *meta;
665 ff_id3v2_read_dict(pb, metadata, ID3v2_DEFAULT_MAGIC, extra_meta);
666 for (meta = *extra_meta; meta; meta = meta->next) {
667 if (!strcmp(meta->tag, "PRIV")) {
668 ID3v2ExtraMetaPRIV *priv = meta->data;
669 if (priv->datasize == 8 && !strcmp(priv->owner, id3_priv_owner_ts)) {
670 /* 33-bit MPEG timestamp */
671 int64_t ts = AV_RB64(priv->data);
672 av_log(s, AV_LOG_DEBUG, "HLS ID3 audio timestamp %"PRId64"\n", ts);
673 if ((ts & ~((1ULL << 33) - 1)) == 0)
676 av_log(s, AV_LOG_ERROR, "Invalid HLS ID3 audio timestamp %"PRId64"\n", ts);
678 } else if (!strcmp(meta->tag, "APIC") && apic)
683 /* Check if the ID3 metadata contents have changed */
684 static int id3_has_changed_values(struct playlist *pls, AVDictionary *metadata,
685 ID3v2ExtraMetaAPIC *apic)
687 AVDictionaryEntry *entry = NULL;
688 AVDictionaryEntry *oldentry;
689 /* check that no keys have changed values */
690 while ((entry = av_dict_get(metadata, "", entry, AV_DICT_IGNORE_SUFFIX))) {
691 oldentry = av_dict_get(pls->id3_initial, entry->key, NULL, AV_DICT_MATCH_CASE);
692 if (!oldentry || strcmp(oldentry->value, entry->value) != 0)
696 /* check if apic appeared */
697 if (apic && (pls->ctx->nb_streams != 2 || !pls->ctx->streams[1]->attached_pic.data))
701 int size = pls->ctx->streams[1]->attached_pic.size;
702 if (size != apic->buf->size - FF_INPUT_BUFFER_PADDING_SIZE)
705 if (memcmp(apic->buf->data, pls->ctx->streams[1]->attached_pic.data, size) != 0)
712 /* Parse ID3 data and handle the found data */
713 static void handle_id3(AVIOContext *pb, struct playlist *pls)
715 AVDictionary *metadata = NULL;
716 ID3v2ExtraMetaAPIC *apic = NULL;
717 ID3v2ExtraMeta *extra_meta = NULL;
718 int64_t timestamp = AV_NOPTS_VALUE;
720 parse_id3(pls->ctx, pb, &metadata, ×tamp, &apic, &extra_meta);
722 if (timestamp != AV_NOPTS_VALUE) {
723 pls->id3_mpegts_timestamp = timestamp;
727 if (!pls->id3_found) {
728 /* initial ID3 tags */
729 av_assert0(!pls->id3_deferred_extra);
732 /* get picture attachment and set text metadata */
733 if (pls->ctx->nb_streams)
734 ff_id3v2_parse_apic(pls->ctx, &extra_meta);
736 /* demuxer not yet opened, defer picture attachment */
737 pls->id3_deferred_extra = extra_meta;
739 av_dict_copy(&pls->ctx->metadata, metadata, 0);
740 pls->id3_initial = metadata;
743 if (!pls->id3_changed && id3_has_changed_values(pls, metadata, apic)) {
744 avpriv_report_missing_feature(pls->ctx, "Changing ID3 metadata in HLS audio elementary stream");
745 pls->id3_changed = 1;
747 av_dict_free(&metadata);
750 if (!pls->id3_deferred_extra)
751 ff_id3v2_free_extra_meta(&extra_meta);
754 /* Intercept and handle ID3 tags between URLContext and AVIOContext */
755 static void intercept_id3(struct playlist *pls, uint8_t *buf,
756 int buf_size, int *len)
758 /* intercept id3 tags, we do not want to pass them to the raw
759 * demuxer on all segment switches */
764 /* gather all the id3 tags */
766 /* see if we can retrieve enough data for ID3 header */
767 if (*len < ID3v2_HEADER_SIZE && buf_size >= ID3v2_HEADER_SIZE) {
768 bytes = read_from_url(pls, buf + *len, ID3v2_HEADER_SIZE - *len, READ_COMPLETE);
771 if (bytes == ID3v2_HEADER_SIZE - *len)
772 /* no EOF yet, so fill the caller buffer again after
773 * we have stripped the ID3 tags */
778 } else if (*len <= 0) {
785 if (*len < ID3v2_HEADER_SIZE)
788 if (ff_id3v2_match(buf, ID3v2_DEFAULT_MAGIC)) {
789 struct segment *seg = pls->segments[pls->cur_seq_no - pls->start_seq_no];
790 int64_t segsize = seg->size >= 0 ? seg->size : ffurl_size(pls->input);
791 int taglen = ff_id3v2_tag_len(buf);
792 int tag_got_bytes = FFMIN(taglen, *len);
793 int remaining = taglen - tag_got_bytes;
795 if (taglen > segsize) {
796 av_log(pls->ctx, AV_LOG_ERROR, "Too large HLS ID3 tag (%d vs %"PRId64")\n",
802 * Copy the id3 tag to our temporary id3 buffer.
803 * We could read a small id3 tag directly without memcpy, but
804 * we would still need to copy the large tags, and handling
805 * both of those cases together with the possibility for multiple
806 * tags would make the handling a bit complex.
808 pls->id3_buf = av_fast_realloc(pls->id3_buf, &pls->id3_buf_size, id3_buf_pos + taglen);
811 memcpy(pls->id3_buf + id3_buf_pos, buf, tag_got_bytes);
812 id3_buf_pos += tag_got_bytes;
814 /* strip the intercepted bytes */
815 *len -= tag_got_bytes;
816 memmove(buf, buf + tag_got_bytes, *len);
817 av_log(pls->ctx, AV_LOG_DEBUG, "Stripped %d HLS ID3 bytes\n", tag_got_bytes);
820 /* read the rest of the tag in */
821 if (read_from_url(pls, pls->id3_buf + id3_buf_pos, remaining, READ_COMPLETE) != remaining)
823 id3_buf_pos += remaining;
824 av_log(pls->ctx, AV_LOG_DEBUG, "Stripped additional %d HLS ID3 bytes\n", remaining);
828 /* no more ID3 tags */
833 /* re-fill buffer for the caller unless EOF */
834 if (*len >= 0 && (fill_buf || *len == 0)) {
835 bytes = read_from_url(pls, buf + *len, buf_size - *len, READ_NORMAL);
837 /* ignore error if we already had some data */
845 /* Now parse all the ID3 tags */
846 AVIOContext id3ioctx;
847 ffio_init_context(&id3ioctx, pls->id3_buf, id3_buf_pos, 0, NULL, NULL, NULL, NULL);
848 handle_id3(&id3ioctx, pls);
851 if (pls->is_id3_timestamped == -1)
852 pls->is_id3_timestamped = (pls->id3_mpegts_timestamp != AV_NOPTS_VALUE);
855 static int open_input(HLSContext *c, struct playlist *pls)
857 AVDictionary *opts = NULL;
858 AVDictionary *opts2 = NULL;
860 struct segment *seg = pls->segments[pls->cur_seq_no - pls->start_seq_no];
862 // broker prior HTTP options that should be consistent across requests
863 av_dict_set(&opts, "user-agent", c->user_agent, 0);
864 av_dict_set(&opts, "cookies", c->cookies, 0);
865 av_dict_set(&opts, "headers", c->headers, 0);
866 av_dict_set(&opts, "seekable", "0", 0);
868 // Same opts for key request (ffurl_open mutilates the opts so it cannot be used twice)
869 av_dict_copy(&opts2, opts, 0);
871 if (seg->size >= 0) {
872 /* try to restrict the HTTP request to the part we want
873 * (if this is in fact a HTTP request) */
874 char offset[24] = { 0 };
875 char end_offset[24] = { 0 };
876 snprintf(offset, sizeof(offset) - 1, "%"PRId64,
878 snprintf(end_offset, sizeof(end_offset) - 1, "%"PRId64,
879 seg->url_offset + seg->size);
880 av_dict_set(&opts, "offset", offset, 0);
881 av_dict_set(&opts, "end_offset", end_offset, 0);
884 av_log(pls->parent, AV_LOG_VERBOSE, "HLS request for url '%s', offset %"PRId64", playlist %d\n",
885 seg->url, seg->url_offset, pls->index);
887 if (seg->key_type == KEY_NONE) {
888 ret = ffurl_open(&pls->input, seg->url, AVIO_FLAG_READ,
889 &pls->parent->interrupt_callback, &opts);
891 } else if (seg->key_type == KEY_AES_128) {
892 char iv[33], key[33], url[MAX_URL_SIZE];
893 if (strcmp(seg->key, pls->key_url)) {
895 if (ffurl_open(&uc, seg->key, AVIO_FLAG_READ,
896 &pls->parent->interrupt_callback, &opts2) == 0) {
897 if (ffurl_read_complete(uc, pls->key, sizeof(pls->key))
898 != sizeof(pls->key)) {
899 av_log(NULL, AV_LOG_ERROR, "Unable to read key file %s\n",
904 av_log(NULL, AV_LOG_ERROR, "Unable to open key file %s\n",
907 av_strlcpy(pls->key_url, seg->key, sizeof(pls->key_url));
909 ff_data_to_hex(iv, seg->iv, sizeof(seg->iv), 0);
910 ff_data_to_hex(key, pls->key, sizeof(pls->key), 0);
911 iv[32] = key[32] = '\0';
912 if (strstr(seg->url, "://"))
913 snprintf(url, sizeof(url), "crypto+%s", seg->url);
915 snprintf(url, sizeof(url), "crypto:%s", seg->url);
916 if ((ret = ffurl_alloc(&pls->input, url, AVIO_FLAG_READ,
917 &pls->parent->interrupt_callback)) < 0)
919 av_opt_set(pls->input->priv_data, "key", key, 0);
920 av_opt_set(pls->input->priv_data, "iv", iv, 0);
922 if ((ret = ffurl_connect(pls->input, &opts)) < 0) {
923 ffurl_close(pls->input);
930 ret = AVERROR(ENOSYS);
932 /* Seek to the requested position. If this was a HTTP request, the offset
933 * should already be where want it to, but this allows e.g. local testing
934 * without a HTTP server. */
936 int seekret = ffurl_seek(pls->input, seg->url_offset, SEEK_SET);
938 av_log(pls->parent, AV_LOG_ERROR, "Unable to seek to offset %"PRId64" of HLS segment '%s'\n", seg->url_offset, seg->url);
940 ffurl_close(pls->input);
947 av_dict_free(&opts2);
948 pls->cur_seg_offset = 0;
952 static int64_t default_reload_interval(struct playlist *pls)
954 return pls->n_segments > 0 ?
955 pls->segments[pls->n_segments - 1]->duration :
956 pls->target_duration;
959 static int read_data(void *opaque, uint8_t *buf, int buf_size)
961 struct playlist *v = opaque;
962 HLSContext *c = v->parent->priv_data;
971 int64_t reload_interval;
973 /* Check that the playlist is still needed before opening a new
975 if (v->ctx && v->ctx->nb_streams &&
976 v->parent->nb_streams >= v->stream_offset + v->ctx->nb_streams) {
978 for (i = v->stream_offset; i < v->stream_offset + v->ctx->nb_streams;
980 if (v->parent->streams[i]->discard < AVDISCARD_ALL)
985 av_log(v->parent, AV_LOG_INFO, "No longer receiving playlist %d\n",
990 /* If this is a live stream and the reload interval has elapsed since
991 * the last playlist reload, reload the playlists now. */
992 reload_interval = default_reload_interval(v);
996 av_gettime() - v->last_load_time >= reload_interval) {
997 if ((ret = parse_playlist(c, v->url, v, NULL)) < 0) {
998 av_log(v->parent, AV_LOG_WARNING, "Failed to reload playlist %d\n",
1002 /* If we need to reload the playlist again below (if
1003 * there's still no more segments), switch to a reload
1004 * interval of half the target duration. */
1005 reload_interval = v->target_duration / 2;
1007 if (v->cur_seq_no < v->start_seq_no) {
1008 av_log(NULL, AV_LOG_WARNING,
1009 "skipping %d segments ahead, expired from playlists\n",
1010 v->start_seq_no - v->cur_seq_no);
1011 v->cur_seq_no = v->start_seq_no;
1013 if (v->cur_seq_no >= v->start_seq_no + v->n_segments) {
1016 while (av_gettime() - v->last_load_time < reload_interval) {
1017 if (ff_check_interrupt(c->interrupt_callback))
1018 return AVERROR_EXIT;
1019 av_usleep(100*1000);
1021 /* Enough time has elapsed since the last reload */
1025 ret = open_input(c, v);
1027 av_log(v->parent, AV_LOG_WARNING, "Failed to open segment of playlist %d\n",
1034 ret = read_from_url(v, buf, buf_size, READ_NORMAL);
1036 if (just_opened && v->is_id3_timestamped != 0) {
1037 /* Intercept ID3 tags here, elementary audio streams are required
1038 * to convey timestamps using them in the beginning of each segment. */
1039 intercept_id3(v, buf, buf_size, &ret);
1044 ffurl_close(v->input);
1048 c->end_of_segment = 1;
1049 c->cur_seq_no = v->cur_seq_no;
1054 static int playlist_in_multiple_variants(HLSContext *c, struct playlist *pls)
1056 int variant_count = 0;
1059 for (i = 0; i < c->n_variants && variant_count < 2; i++) {
1060 struct variant *v = c->variants[i];
1062 for (j = 0; j < v->n_playlists; j++) {
1063 if (v->playlists[j] == pls) {
1070 return variant_count >= 2;
1073 static void add_renditions_to_variant(HLSContext *c, struct variant *var,
1074 enum AVMediaType type, const char *group_id)
1078 for (i = 0; i < c->n_renditions; i++) {
1079 struct rendition *rend = c->renditions[i];
1081 if (rend->type == type && !strcmp(rend->group_id, group_id)) {
1084 /* rendition is an external playlist
1085 * => add the playlist to the variant */
1086 dynarray_add(&var->playlists, &var->n_playlists, rend->playlist);
1088 /* rendition is part of the variant main Media Playlist
1089 * => add the rendition to the main Media Playlist */
1090 dynarray_add(&var->playlists[0]->renditions,
1091 &var->playlists[0]->n_renditions,
1097 static void add_metadata_from_renditions(AVFormatContext *s, struct playlist *pls,
1098 enum AVMediaType type)
1103 for (i = 0; i < pls->ctx->nb_streams; i++) {
1104 AVStream *st = s->streams[pls->stream_offset + i];
1106 if (st->codec->codec_type != type)
1109 for (; rend_idx < pls->n_renditions; rend_idx++) {
1110 struct rendition *rend = pls->renditions[rend_idx];
1112 if (rend->type != type)
1115 if (rend->language[0])
1116 av_dict_set(&st->metadata, "language", rend->language, 0);
1118 av_dict_set(&st->metadata, "comment", rend->name, 0);
1120 st->disposition |= rend->disposition;
1122 if (rend_idx >=pls->n_renditions)
1127 /* if timestamp was in valid range: returns 1 and sets seq_no
1128 * if not: returns 0 and sets seq_no to closest segment */
1129 static int find_timestamp_in_playlist(HLSContext *c, struct playlist *pls,
1130 int64_t timestamp, int *seq_no)
1133 int64_t pos = c->first_timestamp == AV_NOPTS_VALUE ?
1134 0 : c->first_timestamp;
1136 if (timestamp < pos) {
1137 *seq_no = pls->start_seq_no;
1141 for (i = 0; i < pls->n_segments; i++) {
1142 int64_t diff = pos + pls->segments[i]->duration - timestamp;
1144 *seq_no = pls->start_seq_no + i;
1147 pos += pls->segments[i]->duration;
1150 *seq_no = pls->start_seq_no + pls->n_segments - 1;
1155 static int select_cur_seq_no(HLSContext *c, struct playlist *pls)
1159 if (!pls->finished && !c->first_packet &&
1160 av_gettime() - pls->last_load_time >= default_reload_interval(pls))
1161 /* reload the playlist since it was suspended */
1162 parse_playlist(c, pls->url, pls, NULL);
1164 /* If playback is already in progress (we are just selecting a new
1165 * playlist) and this is a complete file, find the matching segment
1166 * by counting durations. */
1167 if (pls->finished && c->cur_timestamp != AV_NOPTS_VALUE) {
1168 find_timestamp_in_playlist(c, pls, c->cur_timestamp, &seq_no);
1172 if (!pls->finished) {
1173 if (!c->first_packet && /* we are doing a segment selection during playback */
1174 c->cur_seq_no >= pls->start_seq_no &&
1175 c->cur_seq_no < pls->start_seq_no + pls->n_segments)
1176 /* While spec 3.4.3 says that we cannot assume anything about the
1177 * content at the same sequence number on different playlists,
1178 * in practice this seems to work and doing it otherwise would
1179 * require us to download a segment to inspect its timestamps. */
1180 return c->cur_seq_no;
1182 /* If this is a live stream with more than 3 segments, start at the
1183 * third last segment. */
1184 if (pls->n_segments > 3)
1185 return pls->start_seq_no + pls->n_segments - 3;
1188 /* Otherwise just start on the first segment. */
1189 return pls->start_seq_no;
1192 static int hls_read_header(AVFormatContext *s)
1194 URLContext *u = (s->flags & AVFMT_FLAG_CUSTOM_IO) ? NULL : s->pb->opaque;
1195 HLSContext *c = s->priv_data;
1196 int ret = 0, i, j, stream_offset = 0;
1198 c->interrupt_callback = &s->interrupt_callback;
1200 c->first_packet = 1;
1201 c->first_timestamp = AV_NOPTS_VALUE;
1202 c->cur_timestamp = AV_NOPTS_VALUE;
1204 // if the URL context is good, read important options we must broker later
1205 if (u && u->prot->priv_data_class) {
1206 // get the previous user agent & set back to null if string size is zero
1207 av_freep(&c->user_agent);
1208 av_opt_get(u->priv_data, "user-agent", 0, (uint8_t**)&(c->user_agent));
1209 if (c->user_agent && !strlen(c->user_agent))
1210 av_freep(&c->user_agent);
1212 // get the previous cookies & set back to null if string size is zero
1213 av_freep(&c->cookies);
1214 av_opt_get(u->priv_data, "cookies", 0, (uint8_t**)&(c->cookies));
1215 if (c->cookies && !strlen(c->cookies))
1216 av_freep(&c->cookies);
1218 // get the previous headers & set back to null if string size is zero
1219 av_freep(&c->headers);
1220 av_opt_get(u->priv_data, "headers", 0, (uint8_t**)&(c->headers));
1221 if (c->headers && !strlen(c->headers))
1222 av_freep(&c->headers);
1225 if ((ret = parse_playlist(c, s->filename, NULL, s->pb)) < 0)
1228 if (c->n_variants == 0) {
1229 av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
1233 /* If the playlist only contained playlists (Master Playlist),
1234 * parse each individual playlist. */
1235 if (c->n_playlists > 1 || c->playlists[0]->n_segments == 0) {
1236 for (i = 0; i < c->n_playlists; i++) {
1237 struct playlist *pls = c->playlists[i];
1238 if ((ret = parse_playlist(c, pls->url, pls, NULL)) < 0)
1243 if (c->variants[0]->playlists[0]->n_segments == 0) {
1244 av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
1249 /* If this isn't a live stream, calculate the total duration of the
1251 if (c->variants[0]->playlists[0]->finished) {
1252 int64_t duration = 0;
1253 for (i = 0; i < c->variants[0]->playlists[0]->n_segments; i++)
1254 duration += c->variants[0]->playlists[0]->segments[i]->duration;
1255 s->duration = duration;
1258 /* Associate renditions with variants */
1259 for (i = 0; i < c->n_variants; i++) {
1260 struct variant *var = c->variants[i];
1262 if (var->audio_group[0])
1263 add_renditions_to_variant(c, var, AVMEDIA_TYPE_AUDIO, var->audio_group);
1264 if (var->video_group[0])
1265 add_renditions_to_variant(c, var, AVMEDIA_TYPE_VIDEO, var->video_group);
1266 if (var->subtitles_group[0])
1267 add_renditions_to_variant(c, var, AVMEDIA_TYPE_SUBTITLE, var->subtitles_group);
1270 /* Open the demuxer for each playlist */
1271 for (i = 0; i < c->n_playlists; i++) {
1272 struct playlist *pls = c->playlists[i];
1273 AVInputFormat *in_fmt = NULL;
1275 if (pls->n_segments == 0)
1278 if (!(pls->ctx = avformat_alloc_context())) {
1279 ret = AVERROR(ENOMEM);
1286 pls->cur_seq_no = select_cur_seq_no(c, pls);
1288 pls->read_buffer = av_malloc(INITIAL_BUFFER_SIZE);
1289 ffio_init_context(&pls->pb, pls->read_buffer, INITIAL_BUFFER_SIZE, 0, pls,
1290 read_data, NULL, NULL);
1291 pls->pb.seekable = 0;
1292 ret = av_probe_input_buffer(&pls->pb, &in_fmt, pls->segments[0]->url,
1295 /* Free the ctx - it isn't initialized properly at this point,
1296 * so avformat_close_input shouldn't be called. If
1297 * avformat_open_input fails below, it frees and zeros the
1298 * context, so it doesn't need any special treatment like this. */
1299 av_log(s, AV_LOG_ERROR, "Error when loading first segment '%s'\n", pls->segments[0]->url);
1300 avformat_free_context(pls->ctx);
1304 pls->ctx->pb = &pls->pb;
1305 pls->stream_offset = stream_offset;
1306 ret = avformat_open_input(&pls->ctx, pls->segments[0]->url, in_fmt, NULL);
1310 if (pls->id3_deferred_extra && pls->ctx->nb_streams == 1) {
1311 ff_id3v2_parse_apic(pls->ctx, &pls->id3_deferred_extra);
1312 avformat_queue_attached_pictures(pls->ctx);
1313 ff_id3v2_free_extra_meta(&pls->id3_deferred_extra);
1314 pls->id3_deferred_extra = NULL;
1317 pls->ctx->ctx_flags &= ~AVFMTCTX_NOHEADER;
1318 ret = avformat_find_stream_info(pls->ctx, NULL);
1322 if (pls->is_id3_timestamped == -1)
1323 av_log(s, AV_LOG_WARNING, "No expected HTTP requests have been made\n");
1325 /* Create new AVStreams for each stream in this playlist */
1326 for (j = 0; j < pls->ctx->nb_streams; j++) {
1327 AVStream *st = avformat_new_stream(s, NULL);
1328 AVStream *ist = pls->ctx->streams[j];
1330 ret = AVERROR(ENOMEM);
1335 avcodec_copy_context(st->codec, pls->ctx->streams[j]->codec);
1337 if (pls->is_id3_timestamped) /* custom timestamps via id3 */
1338 avpriv_set_pts_info(st, 33, 1, MPEG_TIME_BASE);
1340 avpriv_set_pts_info(st, ist->pts_wrap_bits, ist->time_base.num, ist->time_base.den);
1343 add_metadata_from_renditions(s, pls, AVMEDIA_TYPE_AUDIO);
1344 add_metadata_from_renditions(s, pls, AVMEDIA_TYPE_VIDEO);
1345 add_metadata_from_renditions(s, pls, AVMEDIA_TYPE_SUBTITLE);
1347 stream_offset += pls->ctx->nb_streams;
1350 /* Create a program for each variant */
1351 for (i = 0; i < c->n_variants; i++) {
1352 struct variant *v = c->variants[i];
1353 char bitrate_str[20];
1356 snprintf(bitrate_str, sizeof(bitrate_str), "%d", v->bandwidth);
1358 program = av_new_program(s, i);
1361 av_dict_set(&program->metadata, "variant_bitrate", bitrate_str, 0);
1363 for (j = 0; j < v->n_playlists; j++) {
1364 struct playlist *pls = v->playlists[j];
1365 int is_shared = playlist_in_multiple_variants(c, pls);
1368 for (k = 0; k < pls->ctx->nb_streams; k++) {
1369 struct AVStream *st = s->streams[pls->stream_offset + k];
1371 ff_program_add_stream_index(s, i, pls->stream_offset + k);
1373 /* Set variant_bitrate for streams unique to this variant */
1374 if (!is_shared && v->bandwidth)
1375 av_dict_set(&st->metadata, "variant_bitrate", bitrate_str, 0);
1382 free_playlist_list(c);
1383 free_variant_list(c);
1384 free_rendition_list(c);
1388 static int recheck_discard_flags(AVFormatContext *s, int first)
1390 HLSContext *c = s->priv_data;
1393 /* Check if any new streams are needed */
1394 for (i = 0; i < c->n_playlists; i++)
1395 c->playlists[i]->cur_needed = 0;
1397 for (i = 0; i < s->nb_streams; i++) {
1398 AVStream *st = s->streams[i];
1399 struct playlist *pls = c->playlists[s->streams[i]->id];
1400 if (st->discard < AVDISCARD_ALL)
1401 pls->cur_needed = 1;
1403 for (i = 0; i < c->n_playlists; i++) {
1404 struct playlist *pls = c->playlists[i];
1405 if (pls->cur_needed && !pls->needed) {
1408 pls->cur_seq_no = select_cur_seq_no(c, pls);
1409 pls->pb.eof_reached = 0;
1410 if (c->cur_timestamp != AV_NOPTS_VALUE) {
1412 pls->seek_timestamp = c->cur_timestamp;
1413 pls->seek_flags = AVSEEK_FLAG_ANY;
1415 av_log(s, AV_LOG_INFO, "Now receiving playlist %d, segment %d\n", i, pls->cur_seq_no);
1416 } else if (first && !pls->cur_needed && pls->needed) {
1418 ffurl_close(pls->input);
1422 av_log(s, AV_LOG_INFO, "No longer receiving playlist %d\n", i);
1428 static void fill_timing_for_id3_timestamped_stream(struct playlist *pls)
1430 if (pls->id3_offset >= 0) {
1431 pls->pkt.dts = pls->id3_mpegts_timestamp +
1432 av_rescale_q(pls->id3_offset,
1433 pls->ctx->streams[pls->pkt.stream_index]->time_base,
1435 if (pls->pkt.duration)
1436 pls->id3_offset += pls->pkt.duration;
1438 pls->id3_offset = -1;
1440 /* there have been packets with unknown duration
1441 * since the last id3 tag, should not normally happen */
1442 pls->pkt.dts = AV_NOPTS_VALUE;
1445 if (pls->pkt.duration)
1446 pls->pkt.duration = av_rescale_q(pls->pkt.duration,
1447 pls->ctx->streams[pls->pkt.stream_index]->time_base,
1450 pls->pkt.pts = AV_NOPTS_VALUE;
1453 static AVRational get_timebase(struct playlist *pls)
1455 if (pls->is_id3_timestamped)
1456 return MPEG_TIME_BASE_Q;
1458 return pls->ctx->streams[pls->pkt.stream_index]->time_base;
1461 static int hls_read_packet(AVFormatContext *s, AVPacket *pkt)
1463 HLSContext *c = s->priv_data;
1464 int ret, i, minplaylist = -1;
1466 if (c->first_packet) {
1467 recheck_discard_flags(s, 1);
1468 c->first_packet = 0;
1472 c->end_of_segment = 0;
1473 for (i = 0; i < c->n_playlists; i++) {
1474 struct playlist *pls = c->playlists[i];
1475 /* Make sure we've got one buffered packet from each open playlist
1477 if (pls->needed && !pls->pkt.data) {
1481 ret = av_read_frame(pls->ctx, &pls->pkt);
1483 if (!url_feof(&pls->pb) && ret != AVERROR_EOF)
1485 reset_packet(&pls->pkt);
1488 /* stream_index check prevents matching picture attachments etc. */
1489 if (pls->is_id3_timestamped && pls->pkt.stream_index == 0) {
1490 /* audio elementary streams are id3 timestamped */
1491 fill_timing_for_id3_timestamped_stream(pls);
1494 if (c->first_timestamp == AV_NOPTS_VALUE &&
1495 pls->pkt.dts != AV_NOPTS_VALUE)
1496 c->first_timestamp = av_rescale_q(pls->pkt.dts,
1497 get_timebase(pls), AV_TIME_BASE_Q);
1500 if (pls->seek_timestamp == AV_NOPTS_VALUE)
1503 if (pls->pkt.dts == AV_NOPTS_VALUE) {
1504 pls->seek_timestamp = AV_NOPTS_VALUE;
1508 tb = get_timebase(pls);
1509 ts_diff = av_rescale_rnd(pls->pkt.dts, AV_TIME_BASE,
1510 tb.den, AV_ROUND_DOWN) -
1511 pls->seek_timestamp;
1512 if (ts_diff >= 0 && (pls->seek_flags & AVSEEK_FLAG_ANY ||
1513 pls->pkt.flags & AV_PKT_FLAG_KEY)) {
1514 pls->seek_timestamp = AV_NOPTS_VALUE;
1517 av_free_packet(&pls->pkt);
1518 reset_packet(&pls->pkt);
1521 /* Check if this stream still is on an earlier segment number, or
1522 * has the packet with the lowest dts */
1523 if (pls->pkt.data) {
1524 struct playlist *minpls = minplaylist < 0 ?
1525 NULL : c->playlists[minplaylist];
1526 if (minplaylist < 0 || pls->cur_seq_no < minpls->cur_seq_no) {
1528 } else if (pls->cur_seq_no == minpls->cur_seq_no) {
1529 int64_t dts = pls->pkt.dts;
1530 int64_t mindts = minpls->pkt.dts;
1531 AVRational tb = get_timebase( pls);
1532 AVRational mintb = get_timebase(minpls);
1534 if (dts == AV_NOPTS_VALUE) {
1536 } else if (mindts != AV_NOPTS_VALUE) {
1537 if (av_compare_ts(dts, tb,
1544 if (c->end_of_segment) {
1545 if (recheck_discard_flags(s, 0))
1548 /* If we got a packet, return it */
1549 if (minplaylist >= 0) {
1550 struct playlist *pls = c->playlists[minplaylist];
1552 pkt->stream_index += pls->stream_offset;
1553 reset_packet(&c->playlists[minplaylist]->pkt);
1555 if (pkt->dts != AV_NOPTS_VALUE)
1556 c->cur_timestamp = av_rescale_q(pkt->dts,
1557 pls->ctx->streams[pls->pkt.stream_index]->time_base,
1565 static int hls_close(AVFormatContext *s)
1567 HLSContext *c = s->priv_data;
1569 free_playlist_list(c);
1570 free_variant_list(c);
1571 free_rendition_list(c);
1575 static int hls_read_seek(AVFormatContext *s, int stream_index,
1576 int64_t timestamp, int flags)
1578 HLSContext *c = s->priv_data;
1580 int64_t seek_timestamp;
1583 if ((flags & AVSEEK_FLAG_BYTE) || !c->variants[0]->playlists[0]->finished)
1584 return AVERROR(ENOSYS);
1586 seek_timestamp = stream_index < 0 ? timestamp :
1587 av_rescale_rnd(timestamp, AV_TIME_BASE,
1588 s->streams[stream_index]->time_base.den,
1589 flags & AVSEEK_FLAG_BACKWARD ?
1590 AV_ROUND_DOWN : AV_ROUND_UP);
1592 if (s->duration < seek_timestamp)
1593 return AVERROR(EIO);
1595 for (i = 0; i < c->n_playlists; i++) {
1596 /* check first that the timestamp is valid for some playlist */
1597 struct playlist *pls = c->playlists[i];
1599 if (find_timestamp_in_playlist(c, pls, seek_timestamp, &seq_no)) {
1600 /* set segment now so we do not need to search again below */
1601 pls->cur_seq_no = seq_no;
1608 return AVERROR(EIO);
1610 for (i = 0; i < c->n_playlists; i++) {
1612 struct playlist *pls = c->playlists[i];
1614 ffurl_close(pls->input);
1617 av_free_packet(&pls->pkt);
1618 reset_packet(&pls->pkt);
1619 pls->pb.eof_reached = 0;
1620 /* Clear any buffered data */
1621 pls->pb.buf_end = pls->pb.buf_ptr = pls->pb.buffer;
1622 /* Reset the pos, to let the mpegts demuxer know we've seeked. */
1625 pls->seek_timestamp = seek_timestamp;
1626 pls->seek_flags = flags;
1628 /* set closest segment seq_no for playlists not handled above */
1630 find_timestamp_in_playlist(c, pls, seek_timestamp, &pls->cur_seq_no);
1633 c->cur_timestamp = seek_timestamp;
1638 static int hls_probe(AVProbeData *p)
1640 /* Require #EXTM3U at the start, and either one of the ones below
1641 * somewhere for a proper match. */
1642 if (strncmp(p->buf, "#EXTM3U", 7))
1644 if (strstr(p->buf, "#EXT-X-STREAM-INF:") ||
1645 strstr(p->buf, "#EXT-X-TARGETDURATION:") ||
1646 strstr(p->buf, "#EXT-X-MEDIA-SEQUENCE:"))
1647 return AVPROBE_SCORE_MAX;
1651 AVInputFormat ff_hls_demuxer = {
1652 .name = "hls,applehttp",
1653 .long_name = NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming"),
1654 .priv_data_size = sizeof(HLSContext),
1655 .read_probe = hls_probe,
1656 .read_header = hls_read_header,
1657 .read_packet = hls_read_packet,
1658 .read_close = hls_close,
1659 .read_seek = hls_read_seek,