2 * Apple HTTP Live Streaming demuxer
3 * Copyright (c) 2010 Martin Storsjo
5 * This file is part of Libav.
7 * Libav is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * Libav is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with Libav; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24 * Apple HTTP Live Streaming demuxer
25 * http://tools.ietf.org/html/draft-pantos-http-live-streaming
28 #include "libavutil/avstring.h"
29 #include "libavutil/intreadwrite.h"
30 #include "libavutil/mathematics.h"
31 #include "libavutil/opt.h"
32 #include "libavutil/dict.h"
36 #include "avio_internal.h"
39 #define INITIAL_BUFFER_SIZE 32768
42 * An apple http stream consists of a playlist with media segment files,
43 * played sequentially. There may be several playlists with the same
44 * video content, in different bandwidth variants, that are played in
45 * parallel (preferrably only one bandwidth variant at a time). In this case,
46 * the user supplied the url to a main playlist that only lists the variant
49 * If the main playlist doesn't point at any variants, we still create
50 * one anonymous toplevel variant for this, to maintain the structure.
60 char url[MAX_URL_SIZE];
61 char key[MAX_URL_SIZE];
62 enum KeyType key_type;
67 * Each variant has its own demuxer. If it currently is active,
68 * it has an open AVIOContext too, and potentially an AVPacket
69 * containing the next packet from this stream.
73 char url[MAX_URL_SIZE];
77 AVFormatContext *parent;
87 struct segment **segments;
88 int needed, cur_needed;
90 int64_t last_load_time;
92 char key_url[MAX_URL_SIZE];
96 typedef struct AppleHTTPContext {
98 struct variant **variants;
104 static int read_chomp_line(AVIOContext *s, char *buf, int maxlen)
106 int len = ff_get_line(s, buf, maxlen);
107 while (len > 0 && isspace(buf[len - 1]))
112 static void free_segment_list(struct variant *var)
115 for (i = 0; i < var->n_segments; i++)
116 av_free(var->segments[i]);
117 av_freep(&var->segments);
121 static void free_variant_list(AppleHTTPContext *c)
124 for (i = 0; i < c->n_variants; i++) {
125 struct variant *var = c->variants[i];
126 free_segment_list(var);
127 av_free_packet(&var->pkt);
128 av_free(var->pb.buffer);
130 ffurl_close(var->input);
133 av_close_input_file(var->ctx);
137 av_freep(&c->variants);
142 * Used to reset a statically allocated AVPacket to a clean slate,
143 * containing no data.
145 static void reset_packet(AVPacket *pkt)
151 static struct variant *new_variant(AppleHTTPContext *c, int bandwidth,
152 const char *url, const char *base)
154 struct variant *var = av_mallocz(sizeof(struct variant));
157 reset_packet(&var->pkt);
158 var->bandwidth = bandwidth;
159 ff_make_absolute_url(var->url, sizeof(var->url), base, url);
160 dynarray_add(&c->variants, &c->n_variants, var);
164 struct variant_info {
168 static void handle_variant_args(struct variant_info *info, const char *key,
169 int key_len, char **dest, int *dest_len)
171 if (!strncmp(key, "BANDWIDTH=", key_len)) {
172 *dest = info->bandwidth;
173 *dest_len = sizeof(info->bandwidth);
178 char uri[MAX_URL_SIZE];
183 static void handle_key_args(struct key_info *info, const char *key,
184 int key_len, char **dest, int *dest_len)
186 if (!strncmp(key, "METHOD=", key_len)) {
187 *dest = info->method;
188 *dest_len = sizeof(info->method);
189 } else if (!strncmp(key, "URI=", key_len)) {
191 *dest_len = sizeof(info->uri);
192 } else if (!strncmp(key, "IV=", key_len)) {
194 *dest_len = sizeof(info->iv);
198 static int parse_playlist(AppleHTTPContext *c, const char *url,
199 struct variant *var, AVIOContext *in)
201 int ret = 0, duration = 0, is_segment = 0, is_variant = 0, bandwidth = 0;
202 enum KeyType key_type = KEY_NONE;
205 char key[MAX_URL_SIZE];
212 if ((ret = avio_open(&in, url, AVIO_FLAG_READ)) < 0)
216 read_chomp_line(in, line, sizeof(line));
217 if (strcmp(line, "#EXTM3U")) {
218 ret = AVERROR_INVALIDDATA;
223 free_segment_list(var);
226 while (!in->eof_reached) {
227 read_chomp_line(in, line, sizeof(line));
228 if (av_strstart(line, "#EXT-X-STREAM-INF:", &ptr)) {
229 struct variant_info info = {{0}};
231 ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_variant_args,
233 bandwidth = atoi(info.bandwidth);
234 } else if (av_strstart(line, "#EXT-X-KEY:", &ptr)) {
235 struct key_info info = {{0}};
236 ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_key_args,
240 if (!strcmp(info.method, "AES-128"))
241 key_type = KEY_AES_128;
242 if (!strncmp(info.iv, "0x", 2) || !strncmp(info.iv, "0X", 2)) {
243 ff_hex_to_data(iv, info.iv + 2);
246 av_strlcpy(key, info.uri, sizeof(key));
247 } else if (av_strstart(line, "#EXT-X-TARGETDURATION:", &ptr)) {
249 var = new_variant(c, 0, url, NULL);
251 ret = AVERROR(ENOMEM);
255 var->target_duration = atoi(ptr);
256 } else if (av_strstart(line, "#EXT-X-MEDIA-SEQUENCE:", &ptr)) {
258 var = new_variant(c, 0, url, NULL);
260 ret = AVERROR(ENOMEM);
264 var->start_seq_no = atoi(ptr);
265 } else if (av_strstart(line, "#EXT-X-ENDLIST", &ptr)) {
268 } else if (av_strstart(line, "#EXTINF:", &ptr)) {
270 duration = atoi(ptr);
271 } else if (av_strstart(line, "#", NULL)) {
273 } else if (line[0]) {
275 if (!new_variant(c, bandwidth, line, url)) {
276 ret = AVERROR(ENOMEM);
285 var = new_variant(c, 0, url, NULL);
287 ret = AVERROR(ENOMEM);
291 seg = av_malloc(sizeof(struct segment));
293 ret = AVERROR(ENOMEM);
296 seg->duration = duration;
297 seg->key_type = key_type;
299 memcpy(seg->iv, iv, sizeof(iv));
301 int seq = var->start_seq_no + var->n_segments;
302 memset(seg->iv, 0, sizeof(seg->iv));
303 AV_WB32(seg->iv + 12, seq);
305 ff_make_absolute_url(seg->key, sizeof(seg->key), url, key);
306 ff_make_absolute_url(seg->url, sizeof(seg->url), url, line);
307 dynarray_add(&var->segments, &var->n_segments, seg);
313 var->last_load_time = av_gettime();
321 static int open_input(struct variant *var)
323 struct segment *seg = var->segments[var->cur_seq_no - var->start_seq_no];
324 if (seg->key_type == KEY_NONE) {
325 return ffurl_open(&var->input, seg->url, AVIO_FLAG_READ);
326 } else if (seg->key_type == KEY_AES_128) {
327 char iv[33], key[33], url[MAX_URL_SIZE];
329 if (strcmp(seg->key, var->key_url)) {
331 if (ffurl_open(&uc, seg->key, AVIO_FLAG_READ) == 0) {
332 if (ffurl_read_complete(uc, var->key, sizeof(var->key))
333 != sizeof(var->key)) {
334 av_log(NULL, AV_LOG_ERROR, "Unable to read key file %s\n",
339 av_log(NULL, AV_LOG_ERROR, "Unable to open key file %s\n",
342 av_strlcpy(var->key_url, seg->key, sizeof(var->key_url));
344 ff_data_to_hex(iv, seg->iv, sizeof(seg->iv), 0);
345 ff_data_to_hex(key, var->key, sizeof(var->key), 0);
346 iv[32] = key[32] = '\0';
347 if (strstr(seg->url, "://"))
348 snprintf(url, sizeof(url), "crypto+%s", seg->url);
350 snprintf(url, sizeof(url), "crypto:%s", seg->url);
351 if ((ret = ffurl_alloc(&var->input, url, AVIO_FLAG_READ)) < 0)
353 av_set_string3(var->input->priv_data, "key", key, 0, NULL);
354 av_set_string3(var->input->priv_data, "iv", iv, 0, NULL);
355 if ((ret = ffurl_connect(var->input)) < 0) {
356 ffurl_close(var->input);
362 return AVERROR(ENOSYS);
365 static int read_data(void *opaque, uint8_t *buf, int buf_size)
367 struct variant *v = opaque;
368 AppleHTTPContext *c = v->parent->priv_data;
374 /* If this is a live stream and target_duration has elapsed since
375 * the last playlist reload, reload the variant playlists now. */
377 av_gettime() - v->last_load_time >= v->target_duration*1000000 &&
378 (ret = parse_playlist(c, v->url, v, NULL)) < 0)
380 if (v->cur_seq_no < v->start_seq_no) {
381 av_log(NULL, AV_LOG_WARNING,
382 "skipping %d segments ahead, expired from playlists\n",
383 v->start_seq_no - v->cur_seq_no);
384 v->cur_seq_no = v->start_seq_no;
386 if (v->cur_seq_no >= v->start_seq_no + v->n_segments) {
389 while (av_gettime() - v->last_load_time <
390 v->target_duration*1000000) {
391 if (url_interrupt_cb())
395 /* Enough time has elapsed since the last reload */
403 ret = ffurl_read(v->input, buf, buf_size);
406 if (ret < 0 && ret != AVERROR_EOF)
408 ffurl_close(v->input);
412 c->end_of_segment = 1;
413 c->cur_seq_no = v->cur_seq_no;
417 for (i = v->stream_offset; i < v->stream_offset + v->ctx->nb_streams;
419 if (v->parent->streams[i]->discard < AVDISCARD_ALL)
424 av_log(v->parent, AV_LOG_INFO, "No longer receiving variant %d\n",
431 static int applehttp_read_header(AVFormatContext *s, AVFormatParameters *ap)
433 AppleHTTPContext *c = s->priv_data;
434 int ret = 0, i, j, stream_offset = 0;
436 if ((ret = parse_playlist(c, s->filename, NULL, s->pb)) < 0)
439 if (c->n_variants == 0) {
440 av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
444 /* If the playlist only contained variants, parse each individual
445 * variant playlist. */
446 if (c->n_variants > 1 || c->variants[0]->n_segments == 0) {
447 for (i = 0; i < c->n_variants; i++) {
448 struct variant *v = c->variants[i];
449 if ((ret = parse_playlist(c, v->url, v, NULL)) < 0)
454 if (c->variants[0]->n_segments == 0) {
455 av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
460 /* If this isn't a live stream, calculate the total duration of the
462 if (c->variants[0]->finished) {
463 int64_t duration = 0;
464 for (i = 0; i < c->variants[0]->n_segments; i++)
465 duration += c->variants[0]->segments[i]->duration;
466 s->duration = duration * AV_TIME_BASE;
469 /* Open the demuxer for each variant */
470 for (i = 0; i < c->n_variants; i++) {
471 struct variant *v = c->variants[i];
472 AVInputFormat *in_fmt = NULL;
473 char bitrate_str[20];
474 if (v->n_segments == 0)
477 if (!(v->ctx = avformat_alloc_context())) {
478 ret = AVERROR(ENOMEM);
486 /* If this is a live stream with more than 3 segments, start at the
487 * third last segment. */
488 v->cur_seq_no = v->start_seq_no;
489 if (!v->finished && v->n_segments > 3)
490 v->cur_seq_no = v->start_seq_no + v->n_segments - 3;
492 v->read_buffer = av_malloc(INITIAL_BUFFER_SIZE);
493 ffio_init_context(&v->pb, v->read_buffer, INITIAL_BUFFER_SIZE, 0, v,
494 read_data, NULL, NULL);
496 ret = av_probe_input_buffer(&v->pb, &in_fmt, v->segments[0]->url,
501 ret = avformat_open_input(&v->ctx, v->segments[0]->url, in_fmt, NULL);
504 v->stream_offset = stream_offset;
505 snprintf(bitrate_str, sizeof(bitrate_str), "%d", v->bandwidth);
506 /* Create new AVStreams for each stream in this variant */
507 for (j = 0; j < v->ctx->nb_streams; j++) {
508 AVStream *st = av_new_stream(s, i);
510 ret = AVERROR(ENOMEM);
513 avcodec_copy_context(st->codec, v->ctx->streams[j]->codec);
515 av_dict_set(&st->metadata, "variant_bitrate", bitrate_str,
518 stream_offset += v->ctx->nb_streams;
525 free_variant_list(c);
529 static int recheck_discard_flags(AVFormatContext *s, int first)
531 AppleHTTPContext *c = s->priv_data;
534 /* Check if any new streams are needed */
535 for (i = 0; i < c->n_variants; i++)
536 c->variants[i]->cur_needed = 0;;
538 for (i = 0; i < s->nb_streams; i++) {
539 AVStream *st = s->streams[i];
540 struct variant *var = c->variants[s->streams[i]->id];
541 if (st->discard < AVDISCARD_ALL)
544 for (i = 0; i < c->n_variants; i++) {
545 struct variant *v = c->variants[i];
546 if (v->cur_needed && !v->needed) {
549 v->cur_seq_no = c->cur_seq_no;
550 v->pb.eof_reached = 0;
551 av_log(s, AV_LOG_INFO, "Now receiving variant %d\n", i);
552 } else if (first && !v->cur_needed && v->needed) {
554 ffurl_close(v->input);
558 av_log(s, AV_LOG_INFO, "No longer receiving variant %d\n", i);
564 static int applehttp_read_packet(AVFormatContext *s, AVPacket *pkt)
566 AppleHTTPContext *c = s->priv_data;
567 int ret, i, minvariant = -1;
569 if (c->first_packet) {
570 recheck_discard_flags(s, 1);
575 c->end_of_segment = 0;
576 for (i = 0; i < c->n_variants; i++) {
577 struct variant *var = c->variants[i];
578 /* Make sure we've got one buffered packet from each open variant
580 if (var->needed && !var->pkt.data) {
581 ret = av_read_frame(var->ctx, &var->pkt);
583 if (!var->pb.eof_reached)
585 reset_packet(&var->pkt);
588 /* Check if this stream has the packet with the lowest dts */
590 if (minvariant < 0 ||
591 var->pkt.dts < c->variants[minvariant]->pkt.dts)
595 if (c->end_of_segment) {
596 if (recheck_discard_flags(s, 0))
599 /* If we got a packet, return it */
600 if (minvariant >= 0) {
601 *pkt = c->variants[minvariant]->pkt;
602 pkt->stream_index += c->variants[minvariant]->stream_offset;
603 reset_packet(&c->variants[minvariant]->pkt);
609 static int applehttp_close(AVFormatContext *s)
611 AppleHTTPContext *c = s->priv_data;
613 free_variant_list(c);
617 static int applehttp_read_seek(AVFormatContext *s, int stream_index,
618 int64_t timestamp, int flags)
620 AppleHTTPContext *c = s->priv_data;
623 if ((flags & AVSEEK_FLAG_BYTE) || !c->variants[0]->finished)
624 return AVERROR(ENOSYS);
626 timestamp = av_rescale_rnd(timestamp, 1, stream_index >= 0 ?
627 s->streams[stream_index]->time_base.den :
628 AV_TIME_BASE, flags & AVSEEK_FLAG_BACKWARD ?
629 AV_ROUND_DOWN : AV_ROUND_UP);
631 for (i = 0; i < c->n_variants; i++) {
633 struct variant *var = c->variants[i];
636 ffurl_close(var->input);
639 av_free_packet(&var->pkt);
640 reset_packet(&var->pkt);
641 var->pb.eof_reached = 0;
643 /* Locate the segment that contains the target timestamp */
644 for (j = 0; j < var->n_segments; j++) {
645 if (timestamp >= pos &&
646 timestamp < pos + var->segments[j]->duration) {
647 var->cur_seq_no = var->start_seq_no + j;
651 pos += var->segments[j]->duration;
657 static int applehttp_probe(AVProbeData *p)
659 /* Require #EXTM3U at the start, and either one of the ones below
660 * somewhere for a proper match. */
661 if (strncmp(p->buf, "#EXTM3U", 7))
663 if (strstr(p->buf, "#EXT-X-STREAM-INF:") ||
664 strstr(p->buf, "#EXT-X-TARGETDURATION:") ||
665 strstr(p->buf, "#EXT-X-MEDIA-SEQUENCE:"))
666 return AVPROBE_SCORE_MAX;
670 AVInputFormat ff_applehttp_demuxer = {
672 .long_name = NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming format"),
673 .priv_data_size = sizeof(AppleHTTPContext),
674 .read_probe = applehttp_probe,
675 .read_header = applehttp_read_header,
676 .read_packet = applehttp_read_packet,
677 .read_close = applehttp_close,
678 .read_seek = applehttp_read_seek,