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"
41 #define INITIAL_BUFFER_SIZE 32768
43 #define MAX_FIELD_LEN 64
44 #define MAX_CHARACTERISTICS_LEN 512
46 #define MPEG_TIME_BASE 90000
47 #define MPEG_TIME_BASE_Q (AVRational){1, MPEG_TIME_BASE}
50 * An apple http stream consists of a playlist with media segment files,
51 * played sequentially. There may be several playlists with the same
52 * video content, in different bandwidth variants, that are played in
53 * parallel (preferably only one bandwidth variant at a time). In this case,
54 * the user supplied the url to a main playlist that only lists the variant
57 * If the main playlist doesn't point at any variants, we still create
58 * one anonymous toplevel variant for this, to maintain the structure.
73 enum KeyType key_type;
75 /* associated Media Initialization Section, treated as a segment */
76 struct segment *init_section;
88 * Each playlist has its own demuxer. If it currently is active,
89 * it has an open AVIOContext too, and potentially an AVPacket
90 * containing the next packet from this stream.
93 char url[MAX_URL_SIZE];
97 AVFormatContext *parent;
102 /* main demuxer streams associated with this playlist
103 * indexed by the subdemuxer stream indexes */
104 AVStream **main_streams;
108 enum PlaylistType type;
109 int64_t target_duration;
112 struct segment **segments;
113 int needed, cur_needed;
115 int64_t cur_seg_offset;
116 int64_t last_load_time;
118 /* Currently active Media Initialization Section */
119 struct segment *cur_init_section;
120 uint8_t *init_sec_buf;
121 unsigned int init_sec_buf_size;
122 unsigned int init_sec_data_len;
123 unsigned int init_sec_buf_read_offset;
125 char key_url[MAX_URL_SIZE];
128 /* ID3 timestamp handling (elementary audio streams have ID3 timestamps
129 * (and possibly other ID3 tags) in the beginning of each segment) */
130 int is_id3_timestamped; /* -1: not yet known */
131 int64_t id3_mpegts_timestamp; /* in mpegts tb */
132 int64_t id3_offset; /* in stream original tb */
133 uint8_t* id3_buf; /* temp buffer for id3 parsing */
134 unsigned int id3_buf_size;
135 AVDictionary *id3_initial; /* data from first id3 tag */
136 int id3_found; /* ID3 tag found at some point */
137 int id3_changed; /* ID3 tag data has changed at some point */
138 ID3v2ExtraMeta *id3_deferred_extra; /* stored here until subdemuxer is opened */
140 int64_t seek_timestamp;
142 int seek_stream_index; /* into subdemuxer stream array */
144 /* Renditions associated with this playlist, if any.
145 * Alternative rendition playlists have a single rendition associated
146 * with them, and variant main Media Playlists may have
147 * multiple (playlist-less) renditions associated with them. */
149 struct rendition **renditions;
151 /* Media Initialization Sections (EXT-X-MAP) associated with this
152 * playlist, if any. */
154 struct segment **init_sections;
158 * Renditions are e.g. alternative subtitle or audio streams.
159 * The rendition may either be an external playlist or it may be
160 * contained in the main Media Playlist of the variant (in which case
164 enum AVMediaType type;
165 struct playlist *playlist;
166 char group_id[MAX_FIELD_LEN];
167 char language[MAX_FIELD_LEN];
168 char name[MAX_FIELD_LEN];
175 /* every variant contains at least the main Media Playlist in index 0 */
177 struct playlist **playlists;
179 char audio_group[MAX_FIELD_LEN];
180 char video_group[MAX_FIELD_LEN];
181 char subtitles_group[MAX_FIELD_LEN];
184 typedef struct HLSContext {
186 AVFormatContext *ctx;
188 struct variant **variants;
190 struct playlist **playlists;
192 struct rendition **renditions;
195 int live_start_index;
197 int64_t first_timestamp;
198 int64_t cur_timestamp;
199 AVIOInterruptCB *interrupt_callback;
200 char *user_agent; ///< holds HTTP user agent set as an AVOption to the HTTP protocol context
201 char *cookies; ///< holds HTTP cookie values set in either the initial response or as an AVOption to the HTTP protocol context
202 char *headers; ///< holds HTTP headers set as an AVOption to the HTTP protocol context
203 char *http_proxy; ///< holds the address of the HTTP proxy server
204 AVDictionary *avio_opts;
205 int strict_std_compliance;
208 static int read_chomp_line(AVIOContext *s, char *buf, int maxlen)
210 int len = ff_get_line(s, buf, maxlen);
211 while (len > 0 && av_isspace(buf[len - 1]))
216 static void free_segment_list(struct playlist *pls)
219 for (i = 0; i < pls->n_segments; i++) {
220 av_freep(&pls->segments[i]->key);
221 av_freep(&pls->segments[i]->url);
222 av_freep(&pls->segments[i]);
224 av_freep(&pls->segments);
228 static void free_init_section_list(struct playlist *pls)
231 for (i = 0; i < pls->n_init_sections; i++) {
232 av_freep(&pls->init_sections[i]->url);
233 av_freep(&pls->init_sections[i]);
235 av_freep(&pls->init_sections);
236 pls->n_init_sections = 0;
239 static void free_playlist_list(HLSContext *c)
242 for (i = 0; i < c->n_playlists; i++) {
243 struct playlist *pls = c->playlists[i];
244 free_segment_list(pls);
245 free_init_section_list(pls);
246 av_freep(&pls->main_streams);
247 av_freep(&pls->renditions);
248 av_freep(&pls->id3_buf);
249 av_dict_free(&pls->id3_initial);
250 ff_id3v2_free_extra_meta(&pls->id3_deferred_extra);
251 av_freep(&pls->init_sec_buf);
252 av_packet_unref(&pls->pkt);
253 av_freep(&pls->pb.buffer);
255 ff_format_io_close(c->ctx, &pls->input);
258 avformat_close_input(&pls->ctx);
262 av_freep(&c->playlists);
263 av_freep(&c->cookies);
264 av_freep(&c->user_agent);
265 av_freep(&c->headers);
266 av_freep(&c->http_proxy);
270 static void free_variant_list(HLSContext *c)
273 for (i = 0; i < c->n_variants; i++) {
274 struct variant *var = c->variants[i];
275 av_freep(&var->playlists);
278 av_freep(&c->variants);
282 static void free_rendition_list(HLSContext *c)
285 for (i = 0; i < c->n_renditions; i++)
286 av_freep(&c->renditions[i]);
287 av_freep(&c->renditions);
292 * Used to reset a statically allocated AVPacket to a clean slate,
293 * containing no data.
295 static void reset_packet(AVPacket *pkt)
301 static struct playlist *new_playlist(HLSContext *c, const char *url,
304 struct playlist *pls = av_mallocz(sizeof(struct playlist));
307 reset_packet(&pls->pkt);
308 ff_make_absolute_url(pls->url, sizeof(pls->url), base, url);
309 pls->seek_timestamp = AV_NOPTS_VALUE;
311 pls->is_id3_timestamped = -1;
312 pls->id3_mpegts_timestamp = AV_NOPTS_VALUE;
314 dynarray_add(&c->playlists, &c->n_playlists, pls);
318 struct variant_info {
320 /* variant group ids: */
321 char audio[MAX_FIELD_LEN];
322 char video[MAX_FIELD_LEN];
323 char subtitles[MAX_FIELD_LEN];
326 static struct variant *new_variant(HLSContext *c, struct variant_info *info,
327 const char *url, const char *base)
330 struct playlist *pls;
332 pls = new_playlist(c, url, base);
336 var = av_mallocz(sizeof(struct variant));
341 var->bandwidth = atoi(info->bandwidth);
342 strcpy(var->audio_group, info->audio);
343 strcpy(var->video_group, info->video);
344 strcpy(var->subtitles_group, info->subtitles);
347 dynarray_add(&c->variants, &c->n_variants, var);
348 dynarray_add(&var->playlists, &var->n_playlists, pls);
352 static void handle_variant_args(struct variant_info *info, const char *key,
353 int key_len, char **dest, int *dest_len)
355 if (!strncmp(key, "BANDWIDTH=", key_len)) {
356 *dest = info->bandwidth;
357 *dest_len = sizeof(info->bandwidth);
358 } else if (!strncmp(key, "AUDIO=", key_len)) {
360 *dest_len = sizeof(info->audio);
361 } else if (!strncmp(key, "VIDEO=", key_len)) {
363 *dest_len = sizeof(info->video);
364 } else if (!strncmp(key, "SUBTITLES=", key_len)) {
365 *dest = info->subtitles;
366 *dest_len = sizeof(info->subtitles);
371 char uri[MAX_URL_SIZE];
376 static void handle_key_args(struct key_info *info, const char *key,
377 int key_len, char **dest, int *dest_len)
379 if (!strncmp(key, "METHOD=", key_len)) {
380 *dest = info->method;
381 *dest_len = sizeof(info->method);
382 } else if (!strncmp(key, "URI=", key_len)) {
384 *dest_len = sizeof(info->uri);
385 } else if (!strncmp(key, "IV=", key_len)) {
387 *dest_len = sizeof(info->iv);
391 struct init_section_info {
392 char uri[MAX_URL_SIZE];
396 static struct segment *new_init_section(struct playlist *pls,
397 struct init_section_info *info,
398 const char *url_base)
402 char tmp_str[MAX_URL_SIZE];
407 sec = av_mallocz(sizeof(*sec));
411 ff_make_absolute_url(tmp_str, sizeof(tmp_str), url_base, info->uri);
412 sec->url = av_strdup(tmp_str);
418 if (info->byterange[0]) {
419 sec->size = atoi(info->byterange);
420 ptr = strchr(info->byterange, '@');
422 sec->url_offset = atoi(ptr+1);
424 /* the entire file is the init section */
428 dynarray_add(&pls->init_sections, &pls->n_init_sections, sec);
433 static void handle_init_section_args(struct init_section_info *info, const char *key,
434 int key_len, char **dest, int *dest_len)
436 if (!strncmp(key, "URI=", key_len)) {
438 *dest_len = sizeof(info->uri);
439 } else if (!strncmp(key, "BYTERANGE=", key_len)) {
440 *dest = info->byterange;
441 *dest_len = sizeof(info->byterange);
445 struct rendition_info {
447 char uri[MAX_URL_SIZE];
448 char group_id[MAX_FIELD_LEN];
449 char language[MAX_FIELD_LEN];
450 char assoc_language[MAX_FIELD_LEN];
451 char name[MAX_FIELD_LEN];
454 char characteristics[MAX_CHARACTERISTICS_LEN];
457 static struct rendition *new_rendition(HLSContext *c, struct rendition_info *info,
458 const char *url_base)
460 struct rendition *rend;
461 enum AVMediaType type = AVMEDIA_TYPE_UNKNOWN;
462 char *characteristic;
466 if (!strcmp(info->type, "AUDIO"))
467 type = AVMEDIA_TYPE_AUDIO;
468 else if (!strcmp(info->type, "VIDEO"))
469 type = AVMEDIA_TYPE_VIDEO;
470 else if (!strcmp(info->type, "SUBTITLES"))
471 type = AVMEDIA_TYPE_SUBTITLE;
472 else if (!strcmp(info->type, "CLOSED-CAPTIONS"))
473 /* CLOSED-CAPTIONS is ignored since we do not support CEA-608 CC in
474 * AVC SEI RBSP anyway */
477 if (type == AVMEDIA_TYPE_UNKNOWN)
480 /* URI is mandatory for subtitles as per spec */
481 if (type == AVMEDIA_TYPE_SUBTITLE && !info->uri[0])
484 /* TODO: handle subtitles (each segment has to parsed separately) */
485 if (c->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL)
486 if (type == AVMEDIA_TYPE_SUBTITLE)
489 rend = av_mallocz(sizeof(struct rendition));
493 dynarray_add(&c->renditions, &c->n_renditions, rend);
496 strcpy(rend->group_id, info->group_id);
497 strcpy(rend->language, info->language);
498 strcpy(rend->name, info->name);
500 /* add the playlist if this is an external rendition */
502 rend->playlist = new_playlist(c, info->uri, url_base);
504 dynarray_add(&rend->playlist->renditions,
505 &rend->playlist->n_renditions, rend);
508 if (info->assoc_language[0]) {
509 int langlen = strlen(rend->language);
510 if (langlen < sizeof(rend->language) - 3) {
511 rend->language[langlen] = ',';
512 strncpy(rend->language + langlen + 1, info->assoc_language,
513 sizeof(rend->language) - langlen - 2);
517 if (!strcmp(info->defaultr, "YES"))
518 rend->disposition |= AV_DISPOSITION_DEFAULT;
519 if (!strcmp(info->forced, "YES"))
520 rend->disposition |= AV_DISPOSITION_FORCED;
522 chr_ptr = info->characteristics;
523 while ((characteristic = av_strtok(chr_ptr, ",", &saveptr))) {
524 if (!strcmp(characteristic, "public.accessibility.describes-music-and-sound"))
525 rend->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
526 else if (!strcmp(characteristic, "public.accessibility.describes-video"))
527 rend->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED;
535 static void handle_rendition_args(struct rendition_info *info, const char *key,
536 int key_len, char **dest, int *dest_len)
538 if (!strncmp(key, "TYPE=", key_len)) {
540 *dest_len = sizeof(info->type);
541 } else if (!strncmp(key, "URI=", key_len)) {
543 *dest_len = sizeof(info->uri);
544 } else if (!strncmp(key, "GROUP-ID=", key_len)) {
545 *dest = info->group_id;
546 *dest_len = sizeof(info->group_id);
547 } else if (!strncmp(key, "LANGUAGE=", key_len)) {
548 *dest = info->language;
549 *dest_len = sizeof(info->language);
550 } else if (!strncmp(key, "ASSOC-LANGUAGE=", key_len)) {
551 *dest = info->assoc_language;
552 *dest_len = sizeof(info->assoc_language);
553 } else if (!strncmp(key, "NAME=", key_len)) {
555 *dest_len = sizeof(info->name);
556 } else if (!strncmp(key, "DEFAULT=", key_len)) {
557 *dest = info->defaultr;
558 *dest_len = sizeof(info->defaultr);
559 } else if (!strncmp(key, "FORCED=", key_len)) {
560 *dest = info->forced;
561 *dest_len = sizeof(info->forced);
562 } else if (!strncmp(key, "CHARACTERISTICS=", key_len)) {
563 *dest = info->characteristics;
564 *dest_len = sizeof(info->characteristics);
568 * - AUTOSELECT: client may autoselect based on e.g. system language
569 * - INSTREAM-ID: EIA-608 closed caption number ("CC1".."CC4")
573 /* used by parse_playlist to allocate a new variant+playlist when the
574 * playlist is detected to be a Media Playlist (not Master Playlist)
575 * and we have no parent Master Playlist (parsing of which would have
576 * allocated the variant and playlist already)
577 * *pls == NULL => Master Playlist or parentless Media Playlist
578 * *pls != NULL => parented Media Playlist, playlist+variant allocated */
579 static int ensure_playlist(HLSContext *c, struct playlist **pls, const char *url)
583 if (!new_variant(c, NULL, url, NULL))
584 return AVERROR(ENOMEM);
585 *pls = c->playlists[c->n_playlists - 1];
589 static void update_options(char **dest, const char *name, void *src)
592 av_opt_get(src, name, AV_OPT_SEARCH_CHILDREN, (uint8_t**)dest);
593 if (*dest && !strlen(*dest))
597 static int open_url(AVFormatContext *s, AVIOContext **pb, const char *url,
598 AVDictionary *opts, AVDictionary *opts2, int *is_http)
600 HLSContext *c = s->priv_data;
601 AVDictionary *tmp = NULL;
602 const char *proto_name = NULL;
605 av_dict_copy(&tmp, opts, 0);
606 av_dict_copy(&tmp, opts2, 0);
608 if (av_strstart(url, "crypto", NULL)) {
609 if (url[6] == '+' || url[6] == ':')
610 proto_name = avio_find_protocol_name(url + 7);
614 proto_name = avio_find_protocol_name(url);
617 return AVERROR_INVALIDDATA;
619 // only http(s) & file are allowed
620 if (!av_strstart(proto_name, "http", NULL) && !av_strstart(proto_name, "file", NULL))
621 return AVERROR_INVALIDDATA;
622 if (!strncmp(proto_name, url, strlen(proto_name)) && url[strlen(proto_name)] == ':')
624 else if (av_strstart(url, "crypto", NULL) && !strncmp(proto_name, url + 7, strlen(proto_name)) && url[7 + strlen(proto_name)] == ':')
626 else if (strcmp(proto_name, "file") || !strncmp(url, "file,", 5))
627 return AVERROR_INVALIDDATA;
629 ret = s->io_open(s, pb, url, AVIO_FLAG_READ, &tmp);
631 // update cookies on http response with setcookies.
632 void *u = (s->flags & AVFMT_FLAG_CUSTOM_IO) ? NULL : s->pb;
633 update_options(&c->cookies, "cookies", u);
634 av_dict_set(&opts, "cookies", c->cookies, 0);
640 *is_http = av_strstart(proto_name, "http", NULL);
645 static int parse_playlist(HLSContext *c, const char *url,
646 struct playlist *pls, AVIOContext *in)
648 int ret = 0, is_segment = 0, is_variant = 0;
649 int64_t duration = 0;
650 enum KeyType key_type = KEY_NONE;
653 char key[MAX_URL_SIZE] = "";
654 char line[MAX_URL_SIZE];
657 int64_t seg_offset = 0;
658 int64_t seg_size = -1;
659 uint8_t *new_url = NULL;
660 struct variant_info variant_info;
661 char tmp_str[MAX_URL_SIZE];
662 struct segment *cur_init_section = NULL;
666 AVDictionary *opts = NULL;
668 /* Some HLS servers don't like being sent the range header */
669 av_dict_set(&opts, "seekable", "0", 0);
671 // broker prior HTTP options that should be consistent across requests
672 av_dict_set(&opts, "user-agent", c->user_agent, 0);
673 av_dict_set(&opts, "cookies", c->cookies, 0);
674 av_dict_set(&opts, "headers", c->headers, 0);
675 av_dict_set(&opts, "http_proxy", c->http_proxy, 0);
677 ret = c->ctx->io_open(c->ctx, &in, url, AVIO_FLAG_READ, &opts);
682 ret = open_in(c, &in, url);
689 if (av_opt_get(in, "location", AV_OPT_SEARCH_CHILDREN, &new_url) >= 0)
692 read_chomp_line(in, line, sizeof(line));
693 if (strcmp(line, "#EXTM3U")) {
694 ret = AVERROR_INVALIDDATA;
699 free_segment_list(pls);
701 pls->type = PLS_TYPE_UNSPECIFIED;
703 while (!avio_feof(in)) {
704 read_chomp_line(in, line, sizeof(line));
705 if (av_strstart(line, "#EXT-X-STREAM-INF:", &ptr)) {
707 memset(&variant_info, 0, sizeof(variant_info));
708 ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_variant_args,
710 } else if (av_strstart(line, "#EXT-X-KEY:", &ptr)) {
711 struct key_info info = {{0}};
712 ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_key_args,
716 if (!strcmp(info.method, "AES-128"))
717 key_type = KEY_AES_128;
718 if (!strcmp(info.method, "SAMPLE-AES"))
719 key_type = KEY_SAMPLE_AES;
720 if (!strncmp(info.iv, "0x", 2) || !strncmp(info.iv, "0X", 2)) {
721 ff_hex_to_data(iv, info.iv + 2);
724 av_strlcpy(key, info.uri, sizeof(key));
725 } else if (av_strstart(line, "#EXT-X-MEDIA:", &ptr)) {
726 struct rendition_info info = {{0}};
727 ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_rendition_args,
729 new_rendition(c, &info, url);
730 } else if (av_strstart(line, "#EXT-X-TARGETDURATION:", &ptr)) {
731 ret = ensure_playlist(c, &pls, url);
734 pls->target_duration = atoi(ptr) * AV_TIME_BASE;
735 } else if (av_strstart(line, "#EXT-X-MEDIA-SEQUENCE:", &ptr)) {
736 ret = ensure_playlist(c, &pls, url);
739 pls->start_seq_no = atoi(ptr);
740 } else if (av_strstart(line, "#EXT-X-PLAYLIST-TYPE:", &ptr)) {
741 ret = ensure_playlist(c, &pls, url);
744 if (!strcmp(ptr, "EVENT"))
745 pls->type = PLS_TYPE_EVENT;
746 else if (!strcmp(ptr, "VOD"))
747 pls->type = PLS_TYPE_VOD;
748 } else if (av_strstart(line, "#EXT-X-MAP:", &ptr)) {
749 struct init_section_info info = {{0}};
750 ret = ensure_playlist(c, &pls, url);
753 ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_init_section_args,
755 cur_init_section = new_init_section(pls, &info, url);
756 } else if (av_strstart(line, "#EXT-X-ENDLIST", &ptr)) {
759 } else if (av_strstart(line, "#EXTINF:", &ptr)) {
761 duration = atof(ptr) * AV_TIME_BASE;
762 } else if (av_strstart(line, "#EXT-X-BYTERANGE:", &ptr)) {
763 seg_size = atoi(ptr);
764 ptr = strchr(ptr, '@');
766 seg_offset = atoi(ptr+1);
767 } else if (av_strstart(line, "#", NULL)) {
769 } else if (line[0]) {
771 if (!new_variant(c, &variant_info, line, url)) {
772 ret = AVERROR(ENOMEM);
780 if (!new_variant(c, 0, url, NULL)) {
781 ret = AVERROR(ENOMEM);
784 pls = c->playlists[c->n_playlists - 1];
786 seg = av_malloc(sizeof(struct segment));
788 ret = AVERROR(ENOMEM);
791 seg->duration = duration;
792 seg->key_type = key_type;
794 memcpy(seg->iv, iv, sizeof(iv));
796 int seq = pls->start_seq_no + pls->n_segments;
797 memset(seg->iv, 0, sizeof(seg->iv));
798 AV_WB32(seg->iv + 12, seq);
801 if (key_type != KEY_NONE) {
802 ff_make_absolute_url(tmp_str, sizeof(tmp_str), url, key);
803 seg->key = av_strdup(tmp_str);
806 ret = AVERROR(ENOMEM);
813 ff_make_absolute_url(tmp_str, sizeof(tmp_str), url, line);
814 seg->url = av_strdup(tmp_str);
818 ret = AVERROR(ENOMEM);
822 dynarray_add(&pls->segments, &pls->n_segments, seg);
825 seg->size = seg_size;
827 seg->url_offset = seg_offset;
828 seg_offset += seg_size;
835 seg->init_section = cur_init_section;
840 pls->last_load_time = av_gettime_relative();
845 ff_format_io_close(c->ctx, &in);
849 static struct segment *current_segment(struct playlist *pls)
851 return pls->segments[pls->cur_seq_no - pls->start_seq_no];
854 enum ReadFromURLMode {
859 static int read_from_url(struct playlist *pls, struct segment *seg,
860 uint8_t *buf, int buf_size,
861 enum ReadFromURLMode mode)
865 /* limit read if the segment was only a part of a file */
867 buf_size = FFMIN(buf_size, seg->size - pls->cur_seg_offset);
869 if (mode == READ_COMPLETE) {
870 ret = avio_read(pls->input, buf, buf_size);
872 av_log(NULL, AV_LOG_ERROR, "Could not read complete segment.\n");
874 ret = avio_read(pls->input, buf, buf_size);
877 pls->cur_seg_offset += ret;
882 /* Parse the raw ID3 data and pass contents to caller */
883 static void parse_id3(AVFormatContext *s, AVIOContext *pb,
884 AVDictionary **metadata, int64_t *dts,
885 ID3v2ExtraMetaAPIC **apic, ID3v2ExtraMeta **extra_meta)
887 static const char id3_priv_owner_ts[] = "com.apple.streaming.transportStreamTimestamp";
888 ID3v2ExtraMeta *meta;
890 ff_id3v2_read_dict(pb, metadata, ID3v2_DEFAULT_MAGIC, extra_meta);
891 for (meta = *extra_meta; meta; meta = meta->next) {
892 if (!strcmp(meta->tag, "PRIV")) {
893 ID3v2ExtraMetaPRIV *priv = meta->data;
894 if (priv->datasize == 8 && !strcmp(priv->owner, id3_priv_owner_ts)) {
895 /* 33-bit MPEG timestamp */
896 int64_t ts = AV_RB64(priv->data);
897 av_log(s, AV_LOG_DEBUG, "HLS ID3 audio timestamp %"PRId64"\n", ts);
898 if ((ts & ~((1ULL << 33) - 1)) == 0)
901 av_log(s, AV_LOG_ERROR, "Invalid HLS ID3 audio timestamp %"PRId64"\n", ts);
903 } else if (!strcmp(meta->tag, "APIC") && apic)
908 /* Check if the ID3 metadata contents have changed */
909 static int id3_has_changed_values(struct playlist *pls, AVDictionary *metadata,
910 ID3v2ExtraMetaAPIC *apic)
912 AVDictionaryEntry *entry = NULL;
913 AVDictionaryEntry *oldentry;
914 /* check that no keys have changed values */
915 while ((entry = av_dict_get(metadata, "", entry, AV_DICT_IGNORE_SUFFIX))) {
916 oldentry = av_dict_get(pls->id3_initial, entry->key, NULL, AV_DICT_MATCH_CASE);
917 if (!oldentry || strcmp(oldentry->value, entry->value) != 0)
921 /* check if apic appeared */
922 if (apic && (pls->ctx->nb_streams != 2 || !pls->ctx->streams[1]->attached_pic.data))
926 int size = pls->ctx->streams[1]->attached_pic.size;
927 if (size != apic->buf->size - AV_INPUT_BUFFER_PADDING_SIZE)
930 if (memcmp(apic->buf->data, pls->ctx->streams[1]->attached_pic.data, size) != 0)
937 /* Parse ID3 data and handle the found data */
938 static void handle_id3(AVIOContext *pb, struct playlist *pls)
940 AVDictionary *metadata = NULL;
941 ID3v2ExtraMetaAPIC *apic = NULL;
942 ID3v2ExtraMeta *extra_meta = NULL;
943 int64_t timestamp = AV_NOPTS_VALUE;
945 parse_id3(pls->ctx, pb, &metadata, ×tamp, &apic, &extra_meta);
947 if (timestamp != AV_NOPTS_VALUE) {
948 pls->id3_mpegts_timestamp = timestamp;
952 if (!pls->id3_found) {
953 /* initial ID3 tags */
954 av_assert0(!pls->id3_deferred_extra);
957 /* get picture attachment and set text metadata */
958 if (pls->ctx->nb_streams)
959 ff_id3v2_parse_apic(pls->ctx, &extra_meta);
961 /* demuxer not yet opened, defer picture attachment */
962 pls->id3_deferred_extra = extra_meta;
964 av_dict_copy(&pls->ctx->metadata, metadata, 0);
965 pls->id3_initial = metadata;
968 if (!pls->id3_changed && id3_has_changed_values(pls, metadata, apic)) {
969 avpriv_report_missing_feature(pls->ctx, "Changing ID3 metadata in HLS audio elementary stream");
970 pls->id3_changed = 1;
972 av_dict_free(&metadata);
975 if (!pls->id3_deferred_extra)
976 ff_id3v2_free_extra_meta(&extra_meta);
979 static void intercept_id3(struct playlist *pls, uint8_t *buf,
980 int buf_size, int *len)
982 /* intercept id3 tags, we do not want to pass them to the raw
983 * demuxer on all segment switches */
987 struct segment *seg = current_segment(pls);
989 /* gather all the id3 tags */
991 /* see if we can retrieve enough data for ID3 header */
992 if (*len < ID3v2_HEADER_SIZE && buf_size >= ID3v2_HEADER_SIZE) {
993 bytes = read_from_url(pls, seg, buf + *len, ID3v2_HEADER_SIZE - *len, READ_COMPLETE);
996 if (bytes == ID3v2_HEADER_SIZE - *len)
997 /* no EOF yet, so fill the caller buffer again after
998 * we have stripped the ID3 tags */
1003 } else if (*len <= 0) {
1010 if (*len < ID3v2_HEADER_SIZE)
1013 if (ff_id3v2_match(buf, ID3v2_DEFAULT_MAGIC)) {
1014 int64_t maxsize = seg->size >= 0 ? seg->size : 1024*1024;
1015 int taglen = ff_id3v2_tag_len(buf);
1016 int tag_got_bytes = FFMIN(taglen, *len);
1017 int remaining = taglen - tag_got_bytes;
1019 if (taglen > maxsize) {
1020 av_log(pls->ctx, AV_LOG_ERROR, "Too large HLS ID3 tag (%d > %"PRId64" bytes)\n",
1026 * Copy the id3 tag to our temporary id3 buffer.
1027 * We could read a small id3 tag directly without memcpy, but
1028 * we would still need to copy the large tags, and handling
1029 * both of those cases together with the possibility for multiple
1030 * tags would make the handling a bit complex.
1032 pls->id3_buf = av_fast_realloc(pls->id3_buf, &pls->id3_buf_size, id3_buf_pos + taglen);
1035 memcpy(pls->id3_buf + id3_buf_pos, buf, tag_got_bytes);
1036 id3_buf_pos += tag_got_bytes;
1038 /* strip the intercepted bytes */
1039 *len -= tag_got_bytes;
1040 memmove(buf, buf + tag_got_bytes, *len);
1041 av_log(pls->ctx, AV_LOG_DEBUG, "Stripped %d HLS ID3 bytes\n", tag_got_bytes);
1043 if (remaining > 0) {
1044 /* read the rest of the tag in */
1045 if (read_from_url(pls, seg, pls->id3_buf + id3_buf_pos, remaining, READ_COMPLETE) != remaining)
1047 id3_buf_pos += remaining;
1048 av_log(pls->ctx, AV_LOG_DEBUG, "Stripped additional %d HLS ID3 bytes\n", remaining);
1052 /* no more ID3 tags */
1057 /* re-fill buffer for the caller unless EOF */
1058 if (*len >= 0 && (fill_buf || *len == 0)) {
1059 bytes = read_from_url(pls, seg, buf + *len, buf_size - *len, READ_NORMAL);
1061 /* ignore error if we already had some data */
1069 /* Now parse all the ID3 tags */
1070 AVIOContext id3ioctx;
1071 ffio_init_context(&id3ioctx, pls->id3_buf, id3_buf_pos, 0, NULL, NULL, NULL, NULL);
1072 handle_id3(&id3ioctx, pls);
1075 if (pls->is_id3_timestamped == -1)
1076 pls->is_id3_timestamped = (pls->id3_mpegts_timestamp != AV_NOPTS_VALUE);
1079 static int open_input(HLSContext *c, struct playlist *pls, struct segment *seg)
1081 AVDictionary *opts = NULL;
1085 // broker prior HTTP options that should be consistent across requests
1086 av_dict_set(&opts, "user-agent", c->user_agent, 0);
1087 av_dict_set(&opts, "cookies", c->cookies, 0);
1088 av_dict_set(&opts, "headers", c->headers, 0);
1089 av_dict_set(&opts, "http_proxy", c->http_proxy, 0);
1090 av_dict_set(&opts, "seekable", "0", 0);
1092 if (seg->size >= 0) {
1093 /* try to restrict the HTTP request to the part we want
1094 * (if this is in fact a HTTP request) */
1095 av_dict_set_int(&opts, "offset", seg->url_offset, 0);
1096 av_dict_set_int(&opts, "end_offset", seg->url_offset + seg->size, 0);
1099 av_log(pls->parent, AV_LOG_VERBOSE, "HLS request for url '%s', offset %"PRId64", playlist %d\n",
1100 seg->url, seg->url_offset, pls->index);
1102 if (seg->key_type == KEY_NONE) {
1103 ret = open_url(pls->parent, &pls->input, seg->url, c->avio_opts, opts, &is_http);
1104 } else if (seg->key_type == KEY_AES_128) {
1105 AVDictionary *opts2 = NULL;
1106 char iv[33], key[33], url[MAX_URL_SIZE];
1107 if (strcmp(seg->key, pls->key_url)) {
1109 if (open_url(pls->parent, &pb, seg->key, c->avio_opts, opts, NULL) == 0) {
1110 ret = avio_read(pb, pls->key, sizeof(pls->key));
1111 if (ret != sizeof(pls->key)) {
1112 av_log(NULL, AV_LOG_ERROR, "Unable to read key file %s\n",
1115 ff_format_io_close(pls->parent, &pb);
1117 av_log(NULL, AV_LOG_ERROR, "Unable to open key file %s\n",
1120 av_strlcpy(pls->key_url, seg->key, sizeof(pls->key_url));
1122 ff_data_to_hex(iv, seg->iv, sizeof(seg->iv), 0);
1123 ff_data_to_hex(key, pls->key, sizeof(pls->key), 0);
1124 iv[32] = key[32] = '\0';
1125 if (strstr(seg->url, "://"))
1126 snprintf(url, sizeof(url), "crypto+%s", seg->url);
1128 snprintf(url, sizeof(url), "crypto:%s", seg->url);
1130 av_dict_copy(&opts2, c->avio_opts, 0);
1131 av_dict_set(&opts2, "key", key, 0);
1132 av_dict_set(&opts2, "iv", iv, 0);
1134 ret = open_url(pls->parent, &pls->input, url, opts2, opts, &is_http);
1136 av_dict_free(&opts2);
1142 } else if (seg->key_type == KEY_SAMPLE_AES) {
1143 av_log(pls->parent, AV_LOG_ERROR,
1144 "SAMPLE-AES encryption is not supported yet\n");
1145 ret = AVERROR_PATCHWELCOME;
1148 ret = AVERROR(ENOSYS);
1150 /* Seek to the requested position. If this was a HTTP request, the offset
1151 * should already be where want it to, but this allows e.g. local testing
1152 * without a HTTP server.
1154 * This is not done for HTTP at all as avio_seek() does internal bookkeeping
1155 * of file offset which is out-of-sync with the actual offset when "offset"
1156 * AVOption is used with http protocol, causing the seek to not be a no-op
1157 * as would be expected. Wrong offset received from the server will not be
1158 * noticed without the call, though.
1160 if (ret == 0 && !is_http && seg->key_type == KEY_NONE && seg->url_offset) {
1161 int64_t seekret = avio_seek(pls->input, seg->url_offset, SEEK_SET);
1163 av_log(pls->parent, AV_LOG_ERROR, "Unable to seek to offset %"PRId64" of HLS segment '%s'\n", seg->url_offset, seg->url);
1165 ff_format_io_close(pls->parent, &pls->input);
1170 av_dict_free(&opts);
1171 pls->cur_seg_offset = 0;
1175 static int update_init_section(struct playlist *pls, struct segment *seg)
1177 static const int max_init_section_size = 1024*1024;
1178 HLSContext *c = pls->parent->priv_data;
1183 if (seg->init_section == pls->cur_init_section)
1186 pls->cur_init_section = NULL;
1188 if (!seg->init_section)
1191 ret = open_input(c, pls, seg->init_section);
1193 av_log(pls->parent, AV_LOG_WARNING,
1194 "Failed to open an initialization section in playlist %d\n",
1199 if (seg->init_section->size >= 0)
1200 sec_size = seg->init_section->size;
1201 else if ((urlsize = avio_size(pls->input)) >= 0)
1204 sec_size = max_init_section_size;
1206 av_log(pls->parent, AV_LOG_DEBUG,
1207 "Downloading an initialization section of size %"PRId64"\n",
1210 sec_size = FFMIN(sec_size, max_init_section_size);
1212 av_fast_malloc(&pls->init_sec_buf, &pls->init_sec_buf_size, sec_size);
1214 ret = read_from_url(pls, seg->init_section, pls->init_sec_buf,
1215 pls->init_sec_buf_size, READ_COMPLETE);
1216 ff_format_io_close(pls->parent, &pls->input);
1221 pls->cur_init_section = seg->init_section;
1222 pls->init_sec_data_len = ret;
1223 pls->init_sec_buf_read_offset = 0;
1225 /* spec says audio elementary streams do not have media initialization
1226 * sections, so there should be no ID3 timestamps */
1227 pls->is_id3_timestamped = 0;
1232 static int64_t default_reload_interval(struct playlist *pls)
1234 return pls->n_segments > 0 ?
1235 pls->segments[pls->n_segments - 1]->duration :
1236 pls->target_duration;
1239 static int read_data(void *opaque, uint8_t *buf, int buf_size)
1241 struct playlist *v = opaque;
1242 HLSContext *c = v->parent->priv_data;
1244 int just_opened = 0;
1251 int64_t reload_interval;
1252 struct segment *seg;
1254 /* Check that the playlist is still needed before opening a new
1256 if (v->ctx && v->ctx->nb_streams) {
1258 for (i = 0; i < v->n_main_streams; i++) {
1259 if (v->main_streams[i]->discard < AVDISCARD_ALL) {
1266 av_log(v->parent, AV_LOG_INFO, "No longer receiving playlist %d\n",
1271 /* If this is a live stream and the reload interval has elapsed since
1272 * the last playlist reload, reload the playlists now. */
1273 reload_interval = default_reload_interval(v);
1277 av_gettime_relative() - v->last_load_time >= reload_interval) {
1278 if ((ret = parse_playlist(c, v->url, v, NULL)) < 0) {
1279 av_log(v->parent, AV_LOG_WARNING, "Failed to reload playlist %d\n",
1283 /* If we need to reload the playlist again below (if
1284 * there's still no more segments), switch to a reload
1285 * interval of half the target duration. */
1286 reload_interval = v->target_duration / 2;
1288 if (v->cur_seq_no < v->start_seq_no) {
1289 av_log(NULL, AV_LOG_WARNING,
1290 "skipping %d segments ahead, expired from playlists\n",
1291 v->start_seq_no - v->cur_seq_no);
1292 v->cur_seq_no = v->start_seq_no;
1294 if (v->cur_seq_no >= v->start_seq_no + v->n_segments) {
1297 while (av_gettime_relative() - v->last_load_time < reload_interval) {
1298 if (ff_check_interrupt(c->interrupt_callback))
1299 return AVERROR_EXIT;
1300 av_usleep(100*1000);
1302 /* Enough time has elapsed since the last reload */
1306 seg = current_segment(v);
1308 /* load/update Media Initialization Section, if any */
1309 ret = update_init_section(v, seg);
1313 ret = open_input(c, v, seg);
1315 if (ff_check_interrupt(c->interrupt_callback))
1316 return AVERROR_EXIT;
1317 av_log(v->parent, AV_LOG_WARNING, "Failed to open segment of playlist %d\n",
1325 if (v->init_sec_buf_read_offset < v->init_sec_data_len) {
1326 /* Push init section out first before first actual segment */
1327 int copy_size = FFMIN(v->init_sec_data_len - v->init_sec_buf_read_offset, buf_size);
1328 memcpy(buf, v->init_sec_buf, copy_size);
1329 v->init_sec_buf_read_offset += copy_size;
1333 ret = read_from_url(v, current_segment(v), buf, buf_size, READ_NORMAL);
1335 if (just_opened && v->is_id3_timestamped != 0) {
1336 /* Intercept ID3 tags here, elementary audio streams are required
1337 * to convey timestamps using them in the beginning of each segment. */
1338 intercept_id3(v, buf, buf_size, &ret);
1343 ff_format_io_close(v->parent, &v->input);
1346 c->cur_seq_no = v->cur_seq_no;
1351 static void add_renditions_to_variant(HLSContext *c, struct variant *var,
1352 enum AVMediaType type, const char *group_id)
1356 for (i = 0; i < c->n_renditions; i++) {
1357 struct rendition *rend = c->renditions[i];
1359 if (rend->type == type && !strcmp(rend->group_id, group_id)) {
1362 /* rendition is an external playlist
1363 * => add the playlist to the variant */
1364 dynarray_add(&var->playlists, &var->n_playlists, rend->playlist);
1366 /* rendition is part of the variant main Media Playlist
1367 * => add the rendition to the main Media Playlist */
1368 dynarray_add(&var->playlists[0]->renditions,
1369 &var->playlists[0]->n_renditions,
1375 static void add_metadata_from_renditions(AVFormatContext *s, struct playlist *pls,
1376 enum AVMediaType type)
1381 for (i = 0; i < pls->n_main_streams; i++) {
1382 AVStream *st = pls->main_streams[i];
1384 if (st->codecpar->codec_type != type)
1387 for (; rend_idx < pls->n_renditions; rend_idx++) {
1388 struct rendition *rend = pls->renditions[rend_idx];
1390 if (rend->type != type)
1393 if (rend->language[0])
1394 av_dict_set(&st->metadata, "language", rend->language, 0);
1396 av_dict_set(&st->metadata, "comment", rend->name, 0);
1398 st->disposition |= rend->disposition;
1400 if (rend_idx >=pls->n_renditions)
1405 /* if timestamp was in valid range: returns 1 and sets seq_no
1406 * if not: returns 0 and sets seq_no to closest segment */
1407 static int find_timestamp_in_playlist(HLSContext *c, struct playlist *pls,
1408 int64_t timestamp, int *seq_no)
1411 int64_t pos = c->first_timestamp == AV_NOPTS_VALUE ?
1412 0 : c->first_timestamp;
1414 if (timestamp < pos) {
1415 *seq_no = pls->start_seq_no;
1419 for (i = 0; i < pls->n_segments; i++) {
1420 int64_t diff = pos + pls->segments[i]->duration - timestamp;
1422 *seq_no = pls->start_seq_no + i;
1425 pos += pls->segments[i]->duration;
1428 *seq_no = pls->start_seq_no + pls->n_segments - 1;
1433 static int select_cur_seq_no(HLSContext *c, struct playlist *pls)
1437 if (!pls->finished && !c->first_packet &&
1438 av_gettime_relative() - pls->last_load_time >= default_reload_interval(pls))
1439 /* reload the playlist since it was suspended */
1440 parse_playlist(c, pls->url, pls, NULL);
1442 /* If playback is already in progress (we are just selecting a new
1443 * playlist) and this is a complete file, find the matching segment
1444 * by counting durations. */
1445 if (pls->finished && c->cur_timestamp != AV_NOPTS_VALUE) {
1446 find_timestamp_in_playlist(c, pls, c->cur_timestamp, &seq_no);
1450 if (!pls->finished) {
1451 if (!c->first_packet && /* we are doing a segment selection during playback */
1452 c->cur_seq_no >= pls->start_seq_no &&
1453 c->cur_seq_no < pls->start_seq_no + pls->n_segments)
1454 /* While spec 3.4.3 says that we cannot assume anything about the
1455 * content at the same sequence number on different playlists,
1456 * in practice this seems to work and doing it otherwise would
1457 * require us to download a segment to inspect its timestamps. */
1458 return c->cur_seq_no;
1460 /* If this is a live stream, start live_start_index segments from the
1462 if (c->live_start_index < 0)
1463 return pls->start_seq_no + FFMAX(pls->n_segments + c->live_start_index, 0);
1465 return pls->start_seq_no + FFMIN(c->live_start_index, pls->n_segments - 1);
1468 /* Otherwise just start on the first segment. */
1469 return pls->start_seq_no;
1472 static int save_avio_options(AVFormatContext *s)
1474 HLSContext *c = s->priv_data;
1475 static const char *opts[] = {
1476 "headers", "http_proxy", "user_agent", "user-agent", "cookies", NULL };
1477 const char **opt = opts;
1482 if (av_opt_get(s->pb, *opt, AV_OPT_SEARCH_CHILDREN | AV_OPT_ALLOW_NULL, &buf) >= 0) {
1483 ret = av_dict_set(&c->avio_opts, *opt, buf,
1484 AV_DICT_DONT_STRDUP_VAL);
1494 static int nested_io_open(AVFormatContext *s, AVIOContext **pb, const char *url,
1495 int flags, AVDictionary **opts)
1497 av_log(s, AV_LOG_ERROR,
1498 "A HLS playlist item '%s' referred to an external file '%s'. "
1499 "Opening this file was forbidden for security reasons\n",
1501 return AVERROR(EPERM);
1504 static void add_stream_to_programs(AVFormatContext *s, struct playlist *pls, AVStream *stream)
1506 HLSContext *c = s->priv_data;
1510 for (i = 0; i < c->n_variants; i++) {
1511 struct variant *v = c->variants[i];
1513 for (j = 0; j < v->n_playlists; j++) {
1514 if (v->playlists[j] != pls)
1517 av_program_add_stream_index(s, i, stream->index);
1520 bandwidth = v->bandwidth;
1521 else if (bandwidth != v->bandwidth)
1522 bandwidth = -1; /* stream in multiple variants with different bandwidths */
1527 av_dict_set_int(&stream->metadata, "variant_bitrate", bandwidth, 0);
1530 /* add new subdemuxer streams to our context, if any */
1531 static int update_streams_from_subdemuxer(AVFormatContext *s, struct playlist *pls)
1533 while (pls->n_main_streams < pls->ctx->nb_streams) {
1534 int ist_idx = pls->n_main_streams;
1535 AVStream *st = avformat_new_stream(s, NULL);
1536 AVStream *ist = pls->ctx->streams[ist_idx];
1539 return AVERROR(ENOMEM);
1541 st->id = pls->index;
1543 avcodec_parameters_copy(st->codecpar, ist->codecpar);
1545 if (pls->is_id3_timestamped) /* custom timestamps via id3 */
1546 avpriv_set_pts_info(st, 33, 1, MPEG_TIME_BASE);
1548 avpriv_set_pts_info(st, ist->pts_wrap_bits, ist->time_base.num, ist->time_base.den);
1550 dynarray_add(&pls->main_streams, &pls->n_main_streams, st);
1552 add_stream_to_programs(s, pls, st);
1558 static int hls_read_header(AVFormatContext *s)
1560 void *u = (s->flags & AVFMT_FLAG_CUSTOM_IO) ? NULL : s->pb;
1561 HLSContext *c = s->priv_data;
1563 int highest_cur_seq_no = 0;
1566 c->interrupt_callback = &s->interrupt_callback;
1567 c->strict_std_compliance = s->strict_std_compliance;
1569 c->first_packet = 1;
1570 c->first_timestamp = AV_NOPTS_VALUE;
1571 c->cur_timestamp = AV_NOPTS_VALUE;
1574 // get the previous user agent & set back to null if string size is zero
1575 update_options(&c->user_agent, "user-agent", u);
1577 // get the previous cookies & set back to null if string size is zero
1578 update_options(&c->cookies, "cookies", u);
1580 // get the previous headers & set back to null if string size is zero
1581 update_options(&c->headers, "headers", u);
1583 // get the previous http proxt & set back to null if string size is zero
1584 update_options(&c->http_proxy, "http_proxy", u);
1587 if ((ret = parse_playlist(c, s->filename, NULL, s->pb)) < 0)
1590 if ((ret = save_avio_options(s)) < 0)
1593 /* Some HLS servers don't like being sent the range header */
1594 av_dict_set(&c->avio_opts, "seekable", "0", 0);
1596 if (c->n_variants == 0) {
1597 av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
1601 /* If the playlist only contained playlists (Master Playlist),
1602 * parse each individual playlist. */
1603 if (c->n_playlists > 1 || c->playlists[0]->n_segments == 0) {
1604 for (i = 0; i < c->n_playlists; i++) {
1605 struct playlist *pls = c->playlists[i];
1606 if ((ret = parse_playlist(c, pls->url, pls, NULL)) < 0)
1611 if (c->variants[0]->playlists[0]->n_segments == 0) {
1612 av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
1617 /* If this isn't a live stream, calculate the total duration of the
1619 if (c->variants[0]->playlists[0]->finished) {
1620 int64_t duration = 0;
1621 for (i = 0; i < c->variants[0]->playlists[0]->n_segments; i++)
1622 duration += c->variants[0]->playlists[0]->segments[i]->duration;
1623 s->duration = duration;
1626 /* Associate renditions with variants */
1627 for (i = 0; i < c->n_variants; i++) {
1628 struct variant *var = c->variants[i];
1630 if (var->audio_group[0])
1631 add_renditions_to_variant(c, var, AVMEDIA_TYPE_AUDIO, var->audio_group);
1632 if (var->video_group[0])
1633 add_renditions_to_variant(c, var, AVMEDIA_TYPE_VIDEO, var->video_group);
1634 if (var->subtitles_group[0])
1635 add_renditions_to_variant(c, var, AVMEDIA_TYPE_SUBTITLE, var->subtitles_group);
1638 /* Create a program for each variant */
1639 for (i = 0; i < c->n_variants; i++) {
1640 struct variant *v = c->variants[i];
1643 program = av_new_program(s, i);
1646 av_dict_set_int(&program->metadata, "variant_bitrate", v->bandwidth, 0);
1649 /* Select the starting segments */
1650 for (i = 0; i < c->n_playlists; i++) {
1651 struct playlist *pls = c->playlists[i];
1653 if (pls->n_segments == 0)
1656 pls->cur_seq_no = select_cur_seq_no(c, pls);
1657 highest_cur_seq_no = FFMAX(highest_cur_seq_no, pls->cur_seq_no);
1660 /* Open the demuxer for each playlist */
1661 for (i = 0; i < c->n_playlists; i++) {
1662 struct playlist *pls = c->playlists[i];
1663 AVInputFormat *in_fmt = NULL;
1665 if (!(pls->ctx = avformat_alloc_context())) {
1666 ret = AVERROR(ENOMEM);
1670 if (pls->n_segments == 0)
1678 * If this is a live stream and this playlist looks like it is one segment
1679 * behind, try to sync it up so that every substream starts at the same
1680 * time position (so e.g. avformat_find_stream_info() will see packets from
1681 * all active streams within the first few seconds). This is not very generic,
1682 * though, as the sequence numbers are technically independent.
1684 if (!pls->finished && pls->cur_seq_no == highest_cur_seq_no - 1 &&
1685 highest_cur_seq_no < pls->start_seq_no + pls->n_segments) {
1686 pls->cur_seq_no = highest_cur_seq_no;
1689 pls->read_buffer = av_malloc(INITIAL_BUFFER_SIZE);
1690 if (!pls->read_buffer){
1691 ret = AVERROR(ENOMEM);
1692 avformat_free_context(pls->ctx);
1696 ffio_init_context(&pls->pb, pls->read_buffer, INITIAL_BUFFER_SIZE, 0, pls,
1697 read_data, NULL, NULL);
1698 pls->pb.seekable = 0;
1699 ret = av_probe_input_buffer(&pls->pb, &in_fmt, pls->segments[0]->url,
1702 /* Free the ctx - it isn't initialized properly at this point,
1703 * so avformat_close_input shouldn't be called. If
1704 * avformat_open_input fails below, it frees and zeros the
1705 * context, so it doesn't need any special treatment like this. */
1706 av_log(s, AV_LOG_ERROR, "Error when loading first segment '%s'\n", pls->segments[0]->url);
1707 avformat_free_context(pls->ctx);
1711 pls->ctx->pb = &pls->pb;
1712 pls->ctx->io_open = nested_io_open;
1714 if ((ret = ff_copy_whiteblacklists(pls->ctx, s)) < 0)
1717 ret = avformat_open_input(&pls->ctx, pls->segments[0]->url, in_fmt, NULL);
1721 if (pls->id3_deferred_extra && pls->ctx->nb_streams == 1) {
1722 ff_id3v2_parse_apic(pls->ctx, &pls->id3_deferred_extra);
1723 avformat_queue_attached_pictures(pls->ctx);
1724 ff_id3v2_free_extra_meta(&pls->id3_deferred_extra);
1725 pls->id3_deferred_extra = NULL;
1728 pls->ctx->ctx_flags &= ~AVFMTCTX_NOHEADER;
1729 ret = avformat_find_stream_info(pls->ctx, NULL);
1733 if (pls->is_id3_timestamped == -1)
1734 av_log(s, AV_LOG_WARNING, "No expected HTTP requests have been made\n");
1736 /* Create new AVStreams for each stream in this playlist */
1737 ret = update_streams_from_subdemuxer(s, pls);
1741 add_metadata_from_renditions(s, pls, AVMEDIA_TYPE_AUDIO);
1742 add_metadata_from_renditions(s, pls, AVMEDIA_TYPE_VIDEO);
1743 add_metadata_from_renditions(s, pls, AVMEDIA_TYPE_SUBTITLE);
1748 free_playlist_list(c);
1749 free_variant_list(c);
1750 free_rendition_list(c);
1754 static int recheck_discard_flags(AVFormatContext *s, int first)
1756 HLSContext *c = s->priv_data;
1759 /* Check if any new streams are needed */
1760 for (i = 0; i < c->n_playlists; i++)
1761 c->playlists[i]->cur_needed = 0;
1763 for (i = 0; i < s->nb_streams; i++) {
1764 AVStream *st = s->streams[i];
1765 struct playlist *pls = c->playlists[s->streams[i]->id];
1766 if (st->discard < AVDISCARD_ALL)
1767 pls->cur_needed = 1;
1769 for (i = 0; i < c->n_playlists; i++) {
1770 struct playlist *pls = c->playlists[i];
1771 if (pls->cur_needed && !pls->needed) {
1774 pls->cur_seq_no = select_cur_seq_no(c, pls);
1775 pls->pb.eof_reached = 0;
1776 if (c->cur_timestamp != AV_NOPTS_VALUE) {
1778 pls->seek_timestamp = c->cur_timestamp;
1779 pls->seek_flags = AVSEEK_FLAG_ANY;
1780 pls->seek_stream_index = -1;
1782 av_log(s, AV_LOG_INFO, "Now receiving playlist %d, segment %d\n", i, pls->cur_seq_no);
1783 } else if (first && !pls->cur_needed && pls->needed) {
1785 ff_format_io_close(pls->parent, &pls->input);
1788 av_log(s, AV_LOG_INFO, "No longer receiving playlist %d\n", i);
1794 static void fill_timing_for_id3_timestamped_stream(struct playlist *pls)
1796 if (pls->id3_offset >= 0) {
1797 pls->pkt.dts = pls->id3_mpegts_timestamp +
1798 av_rescale_q(pls->id3_offset,
1799 pls->ctx->streams[pls->pkt.stream_index]->time_base,
1801 if (pls->pkt.duration)
1802 pls->id3_offset += pls->pkt.duration;
1804 pls->id3_offset = -1;
1806 /* there have been packets with unknown duration
1807 * since the last id3 tag, should not normally happen */
1808 pls->pkt.dts = AV_NOPTS_VALUE;
1811 if (pls->pkt.duration)
1812 pls->pkt.duration = av_rescale_q(pls->pkt.duration,
1813 pls->ctx->streams[pls->pkt.stream_index]->time_base,
1816 pls->pkt.pts = AV_NOPTS_VALUE;
1819 static AVRational get_timebase(struct playlist *pls)
1821 if (pls->is_id3_timestamped)
1822 return MPEG_TIME_BASE_Q;
1824 return pls->ctx->streams[pls->pkt.stream_index]->time_base;
1827 static int compare_ts_with_wrapdetect(int64_t ts_a, struct playlist *pls_a,
1828 int64_t ts_b, struct playlist *pls_b)
1830 int64_t scaled_ts_a = av_rescale_q(ts_a, get_timebase(pls_a), MPEG_TIME_BASE_Q);
1831 int64_t scaled_ts_b = av_rescale_q(ts_b, get_timebase(pls_b), MPEG_TIME_BASE_Q);
1833 return av_compare_mod(scaled_ts_a, scaled_ts_b, 1LL << 33);
1836 static int hls_read_packet(AVFormatContext *s, AVPacket *pkt)
1838 HLSContext *c = s->priv_data;
1839 int ret, i, minplaylist = -1;
1841 recheck_discard_flags(s, c->first_packet);
1842 c->first_packet = 0;
1844 for (i = 0; i < c->n_playlists; i++) {
1845 struct playlist *pls = c->playlists[i];
1846 /* Make sure we've got one buffered packet from each open playlist
1848 if (pls->needed && !pls->pkt.data) {
1852 ret = av_read_frame(pls->ctx, &pls->pkt);
1854 if (!avio_feof(&pls->pb) && ret != AVERROR_EOF)
1856 reset_packet(&pls->pkt);
1859 /* stream_index check prevents matching picture attachments etc. */
1860 if (pls->is_id3_timestamped && pls->pkt.stream_index == 0) {
1861 /* audio elementary streams are id3 timestamped */
1862 fill_timing_for_id3_timestamped_stream(pls);
1865 if (c->first_timestamp == AV_NOPTS_VALUE &&
1866 pls->pkt.dts != AV_NOPTS_VALUE)
1867 c->first_timestamp = av_rescale_q(pls->pkt.dts,
1868 get_timebase(pls), AV_TIME_BASE_Q);
1871 if (pls->seek_timestamp == AV_NOPTS_VALUE)
1874 if (pls->seek_stream_index < 0 ||
1875 pls->seek_stream_index == pls->pkt.stream_index) {
1877 if (pls->pkt.dts == AV_NOPTS_VALUE) {
1878 pls->seek_timestamp = AV_NOPTS_VALUE;
1882 tb = get_timebase(pls);
1883 ts_diff = av_rescale_rnd(pls->pkt.dts, AV_TIME_BASE,
1884 tb.den, AV_ROUND_DOWN) -
1885 pls->seek_timestamp;
1886 if (ts_diff >= 0 && (pls->seek_flags & AVSEEK_FLAG_ANY ||
1887 pls->pkt.flags & AV_PKT_FLAG_KEY)) {
1888 pls->seek_timestamp = AV_NOPTS_VALUE;
1892 av_packet_unref(&pls->pkt);
1893 reset_packet(&pls->pkt);
1896 /* Check if this stream has the packet with the lowest dts */
1897 if (pls->pkt.data) {
1898 struct playlist *minpls = minplaylist < 0 ?
1899 NULL : c->playlists[minplaylist];
1900 if (minplaylist < 0) {
1903 int64_t dts = pls->pkt.dts;
1904 int64_t mindts = minpls->pkt.dts;
1906 if (dts == AV_NOPTS_VALUE ||
1907 (mindts != AV_NOPTS_VALUE && compare_ts_with_wrapdetect(dts, pls, mindts, minpls) < 0))
1913 /* If we got a packet, return it */
1914 if (minplaylist >= 0) {
1915 struct playlist *pls = c->playlists[minplaylist];
1917 if (pls->pkt.stream_index >= pls->n_main_streams) {
1918 av_log(s, AV_LOG_ERROR, "stream index inconsistency: index %d, %d main streams, %d subdemuxer streams\n",
1919 pls->pkt.stream_index, pls->n_main_streams, pls->ctx->nb_streams);
1920 av_packet_unref(&pls->pkt);
1921 reset_packet(&pls->pkt);
1926 pkt->stream_index = pls->main_streams[pls->pkt.stream_index]->index;
1927 reset_packet(&c->playlists[minplaylist]->pkt);
1929 if (pkt->dts != AV_NOPTS_VALUE)
1930 c->cur_timestamp = av_rescale_q(pkt->dts,
1931 pls->ctx->streams[pls->pkt.stream_index]->time_base,
1939 static int hls_close(AVFormatContext *s)
1941 HLSContext *c = s->priv_data;
1943 free_playlist_list(c);
1944 free_variant_list(c);
1945 free_rendition_list(c);
1947 av_dict_free(&c->avio_opts);
1952 static int hls_read_seek(AVFormatContext *s, int stream_index,
1953 int64_t timestamp, int flags)
1955 HLSContext *c = s->priv_data;
1956 struct playlist *seek_pls = NULL;
1959 int stream_subdemuxer_index;
1960 int64_t first_timestamp, seek_timestamp, duration;
1962 if ((flags & AVSEEK_FLAG_BYTE) ||
1963 !(c->variants[0]->playlists[0]->finished || c->variants[0]->playlists[0]->type == PLS_TYPE_EVENT))
1964 return AVERROR(ENOSYS);
1966 first_timestamp = c->first_timestamp == AV_NOPTS_VALUE ?
1967 0 : c->first_timestamp;
1969 seek_timestamp = av_rescale_rnd(timestamp, AV_TIME_BASE,
1970 s->streams[stream_index]->time_base.den,
1971 flags & AVSEEK_FLAG_BACKWARD ?
1972 AV_ROUND_DOWN : AV_ROUND_UP);
1974 duration = s->duration == AV_NOPTS_VALUE ?
1977 if (0 < duration && duration < seek_timestamp - first_timestamp)
1978 return AVERROR(EIO);
1980 /* find the playlist with the specified stream */
1981 for (i = 0; i < c->n_playlists; i++) {
1982 struct playlist *pls = c->playlists[i];
1983 for (j = 0; j < pls->n_main_streams; j++) {
1984 if (pls->main_streams[j] == s->streams[stream_index]) {
1986 stream_subdemuxer_index = j;
1991 /* check if the timestamp is valid for the playlist with the
1992 * specified stream index */
1993 if (!seek_pls || !find_timestamp_in_playlist(c, seek_pls, seek_timestamp, &seq_no))
1994 return AVERROR(EIO);
1996 /* set segment now so we do not need to search again below */
1997 seek_pls->cur_seq_no = seq_no;
1998 seek_pls->seek_stream_index = stream_subdemuxer_index;
2000 for (i = 0; i < c->n_playlists; i++) {
2002 struct playlist *pls = c->playlists[i];
2004 ff_format_io_close(pls->parent, &pls->input);
2005 av_packet_unref(&pls->pkt);
2006 reset_packet(&pls->pkt);
2007 pls->pb.eof_reached = 0;
2008 /* Clear any buffered data */
2009 pls->pb.buf_end = pls->pb.buf_ptr = pls->pb.buffer;
2010 /* Reset the pos, to let the mpegts demuxer know we've seeked. */
2012 /* Flush the packet queue of the subdemuxer. */
2013 ff_read_frame_flush(pls->ctx);
2015 pls->seek_timestamp = seek_timestamp;
2016 pls->seek_flags = flags;
2018 if (pls != seek_pls) {
2019 /* set closest segment seq_no for playlists not handled above */
2020 find_timestamp_in_playlist(c, pls, seek_timestamp, &pls->cur_seq_no);
2021 /* seek the playlist to the given position without taking
2022 * keyframes into account since this playlist does not have the
2023 * specified stream where we should look for the keyframes */
2024 pls->seek_stream_index = -1;
2025 pls->seek_flags |= AVSEEK_FLAG_ANY;
2029 c->cur_timestamp = seek_timestamp;
2034 static int hls_probe(AVProbeData *p)
2036 /* Require #EXTM3U at the start, and either one of the ones below
2037 * somewhere for a proper match. */
2038 if (strncmp(p->buf, "#EXTM3U", 7))
2041 if (strstr(p->buf, "#EXT-X-STREAM-INF:") ||
2042 strstr(p->buf, "#EXT-X-TARGETDURATION:") ||
2043 strstr(p->buf, "#EXT-X-MEDIA-SEQUENCE:"))
2044 return AVPROBE_SCORE_MAX;
2048 #define OFFSET(x) offsetof(HLSContext, x)
2049 #define FLAGS AV_OPT_FLAG_DECODING_PARAM
2050 static const AVOption hls_options[] = {
2051 {"live_start_index", "segment index to start live streams at (negative values are from the end)",
2052 OFFSET(live_start_index), AV_OPT_TYPE_INT, {.i64 = -3}, INT_MIN, INT_MAX, FLAGS},
2056 static const AVClass hls_class = {
2057 .class_name = "hls,applehttp",
2058 .item_name = av_default_item_name,
2059 .option = hls_options,
2060 .version = LIBAVUTIL_VERSION_INT,
2063 AVInputFormat ff_hls_demuxer = {
2064 .name = "hls,applehttp",
2065 .long_name = NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming"),
2066 .priv_class = &hls_class,
2067 .priv_data_size = sizeof(HLSContext),
2068 .read_probe = hls_probe,
2069 .read_header = hls_read_header,
2070 .read_packet = hls_read_packet,
2071 .read_close = hls_close,
2072 .read_seek = hls_read_seek,