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;
102 AVIOInterruptCB *interrupt_callback;
105 static int read_chomp_line(AVIOContext *s, char *buf, int maxlen)
107 int len = ff_get_line(s, buf, maxlen);
108 while (len > 0 && isspace(buf[len - 1]))
113 static void free_segment_list(struct variant *var)
116 for (i = 0; i < var->n_segments; i++)
117 av_free(var->segments[i]);
118 av_freep(&var->segments);
122 static void free_variant_list(AppleHTTPContext *c)
125 for (i = 0; i < c->n_variants; i++) {
126 struct variant *var = c->variants[i];
127 free_segment_list(var);
128 av_free_packet(&var->pkt);
129 av_free(var->pb.buffer);
131 ffurl_close(var->input);
134 av_close_input_file(var->ctx);
138 av_freep(&c->variants);
143 * Used to reset a statically allocated AVPacket to a clean slate,
144 * containing no data.
146 static void reset_packet(AVPacket *pkt)
152 static struct variant *new_variant(AppleHTTPContext *c, int bandwidth,
153 const char *url, const char *base)
155 struct variant *var = av_mallocz(sizeof(struct variant));
158 reset_packet(&var->pkt);
159 var->bandwidth = bandwidth;
160 ff_make_absolute_url(var->url, sizeof(var->url), base, url);
161 dynarray_add(&c->variants, &c->n_variants, var);
165 struct variant_info {
169 static void handle_variant_args(struct variant_info *info, const char *key,
170 int key_len, char **dest, int *dest_len)
172 if (!strncmp(key, "BANDWIDTH=", key_len)) {
173 *dest = info->bandwidth;
174 *dest_len = sizeof(info->bandwidth);
179 char uri[MAX_URL_SIZE];
184 static void handle_key_args(struct key_info *info, const char *key,
185 int key_len, char **dest, int *dest_len)
187 if (!strncmp(key, "METHOD=", key_len)) {
188 *dest = info->method;
189 *dest_len = sizeof(info->method);
190 } else if (!strncmp(key, "URI=", key_len)) {
192 *dest_len = sizeof(info->uri);
193 } else if (!strncmp(key, "IV=", key_len)) {
195 *dest_len = sizeof(info->iv);
199 static int parse_playlist(AppleHTTPContext *c, const char *url,
200 struct variant *var, AVIOContext *in)
202 int ret = 0, duration = 0, is_segment = 0, is_variant = 0, bandwidth = 0;
203 enum KeyType key_type = KEY_NONE;
206 char key[MAX_URL_SIZE];
213 if ((ret = avio_open(&in, url, AVIO_FLAG_READ)) < 0)
217 read_chomp_line(in, line, sizeof(line));
218 if (strcmp(line, "#EXTM3U")) {
219 ret = AVERROR_INVALIDDATA;
224 free_segment_list(var);
227 while (!in->eof_reached) {
228 read_chomp_line(in, line, sizeof(line));
229 if (av_strstart(line, "#EXT-X-STREAM-INF:", &ptr)) {
230 struct variant_info info = {{0}};
232 ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_variant_args,
234 bandwidth = atoi(info.bandwidth);
235 } else if (av_strstart(line, "#EXT-X-KEY:", &ptr)) {
236 struct key_info info = {{0}};
237 ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_key_args,
241 if (!strcmp(info.method, "AES-128"))
242 key_type = KEY_AES_128;
243 if (!strncmp(info.iv, "0x", 2) || !strncmp(info.iv, "0X", 2)) {
244 ff_hex_to_data(iv, info.iv + 2);
247 av_strlcpy(key, info.uri, sizeof(key));
248 } else if (av_strstart(line, "#EXT-X-TARGETDURATION:", &ptr)) {
250 var = new_variant(c, 0, url, NULL);
252 ret = AVERROR(ENOMEM);
256 var->target_duration = atoi(ptr);
257 } else if (av_strstart(line, "#EXT-X-MEDIA-SEQUENCE:", &ptr)) {
259 var = new_variant(c, 0, url, NULL);
261 ret = AVERROR(ENOMEM);
265 var->start_seq_no = atoi(ptr);
266 } else if (av_strstart(line, "#EXT-X-ENDLIST", &ptr)) {
269 } else if (av_strstart(line, "#EXTINF:", &ptr)) {
271 duration = atoi(ptr);
272 } else if (av_strstart(line, "#", NULL)) {
274 } else if (line[0]) {
276 if (!new_variant(c, bandwidth, line, url)) {
277 ret = AVERROR(ENOMEM);
286 var = new_variant(c, 0, url, NULL);
288 ret = AVERROR(ENOMEM);
292 seg = av_malloc(sizeof(struct segment));
294 ret = AVERROR(ENOMEM);
297 seg->duration = duration;
298 seg->key_type = key_type;
300 memcpy(seg->iv, iv, sizeof(iv));
302 int seq = var->start_seq_no + var->n_segments;
303 memset(seg->iv, 0, sizeof(seg->iv));
304 AV_WB32(seg->iv + 12, seq);
306 ff_make_absolute_url(seg->key, sizeof(seg->key), url, key);
307 ff_make_absolute_url(seg->url, sizeof(seg->url), url, line);
308 dynarray_add(&var->segments, &var->n_segments, seg);
314 var->last_load_time = av_gettime();
322 static int open_input(struct variant *var)
324 struct segment *seg = var->segments[var->cur_seq_no - var->start_seq_no];
325 if (seg->key_type == KEY_NONE) {
326 return ffurl_open(&var->input, seg->url, AVIO_FLAG_READ);
327 } else if (seg->key_type == KEY_AES_128) {
328 char iv[33], key[33], url[MAX_URL_SIZE];
330 if (strcmp(seg->key, var->key_url)) {
332 if (ffurl_open(&uc, seg->key, AVIO_FLAG_READ) == 0) {
333 if (ffurl_read_complete(uc, var->key, sizeof(var->key))
334 != sizeof(var->key)) {
335 av_log(NULL, AV_LOG_ERROR, "Unable to read key file %s\n",
340 av_log(NULL, AV_LOG_ERROR, "Unable to open key file %s\n",
343 av_strlcpy(var->key_url, seg->key, sizeof(var->key_url));
345 ff_data_to_hex(iv, seg->iv, sizeof(seg->iv), 0);
346 ff_data_to_hex(key, var->key, sizeof(var->key), 0);
347 iv[32] = key[32] = '\0';
348 if (strstr(seg->url, "://"))
349 snprintf(url, sizeof(url), "crypto+%s", seg->url);
351 snprintf(url, sizeof(url), "crypto:%s", seg->url);
352 if ((ret = ffurl_alloc(&var->input, url, AVIO_FLAG_READ)) < 0)
354 av_opt_set(var->input->priv_data, "key", key, 0);
355 av_opt_set(var->input->priv_data, "iv", iv, 0);
356 if ((ret = ffurl_connect(var->input)) < 0) {
357 ffurl_close(var->input);
363 return AVERROR(ENOSYS);
366 static int read_data(void *opaque, uint8_t *buf, int buf_size)
368 struct variant *v = opaque;
369 AppleHTTPContext *c = v->parent->priv_data;
375 /* If this is a live stream and target_duration has elapsed since
376 * the last playlist reload, reload the variant playlists now. */
378 av_gettime() - v->last_load_time >= v->target_duration*1000000 &&
379 (ret = parse_playlist(c, v->url, v, NULL)) < 0)
381 if (v->cur_seq_no < v->start_seq_no) {
382 av_log(NULL, AV_LOG_WARNING,
383 "skipping %d segments ahead, expired from playlists\n",
384 v->start_seq_no - v->cur_seq_no);
385 v->cur_seq_no = v->start_seq_no;
387 if (v->cur_seq_no >= v->start_seq_no + v->n_segments) {
390 while (av_gettime() - v->last_load_time <
391 v->target_duration*1000000) {
392 if (ff_check_interrupt(c->interrupt_callback))
396 /* Enough time has elapsed since the last reload */
404 ret = ffurl_read(v->input, buf, buf_size);
407 if (ret < 0 && ret != AVERROR_EOF)
409 ffurl_close(v->input);
413 c->end_of_segment = 1;
414 c->cur_seq_no = v->cur_seq_no;
416 if (v->ctx && v->ctx->nb_streams) {
418 for (i = v->stream_offset; i < v->stream_offset + v->ctx->nb_streams;
420 if (v->parent->streams[i]->discard < AVDISCARD_ALL)
425 av_log(v->parent, AV_LOG_INFO, "No longer receiving variant %d\n",
432 static int applehttp_read_header(AVFormatContext *s, AVFormatParameters *ap)
434 AppleHTTPContext *c = s->priv_data;
435 int ret = 0, i, j, stream_offset = 0;
437 c->interrupt_callback = &s->interrupt_callback;
439 if ((ret = parse_playlist(c, s->filename, NULL, s->pb)) < 0)
442 if (c->n_variants == 0) {
443 av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
447 /* If the playlist only contained variants, parse each individual
448 * variant playlist. */
449 if (c->n_variants > 1 || c->variants[0]->n_segments == 0) {
450 for (i = 0; i < c->n_variants; i++) {
451 struct variant *v = c->variants[i];
452 if ((ret = parse_playlist(c, v->url, v, NULL)) < 0)
457 if (c->variants[0]->n_segments == 0) {
458 av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
463 /* If this isn't a live stream, calculate the total duration of the
465 if (c->variants[0]->finished) {
466 int64_t duration = 0;
467 for (i = 0; i < c->variants[0]->n_segments; i++)
468 duration += c->variants[0]->segments[i]->duration;
469 s->duration = duration * AV_TIME_BASE;
472 /* Open the demuxer for each variant */
473 for (i = 0; i < c->n_variants; i++) {
474 struct variant *v = c->variants[i];
475 AVInputFormat *in_fmt = NULL;
476 char bitrate_str[20];
477 if (v->n_segments == 0)
480 if (!(v->ctx = avformat_alloc_context())) {
481 ret = AVERROR(ENOMEM);
489 /* If this is a live stream with more than 3 segments, start at the
490 * third last segment. */
491 v->cur_seq_no = v->start_seq_no;
492 if (!v->finished && v->n_segments > 3)
493 v->cur_seq_no = v->start_seq_no + v->n_segments - 3;
495 v->read_buffer = av_malloc(INITIAL_BUFFER_SIZE);
496 ffio_init_context(&v->pb, v->read_buffer, INITIAL_BUFFER_SIZE, 0, v,
497 read_data, NULL, NULL);
499 ret = av_probe_input_buffer(&v->pb, &in_fmt, v->segments[0]->url,
504 ret = avformat_open_input(&v->ctx, v->segments[0]->url, in_fmt, NULL);
507 v->stream_offset = stream_offset;
508 snprintf(bitrate_str, sizeof(bitrate_str), "%d", v->bandwidth);
509 /* Create new AVStreams for each stream in this variant */
510 for (j = 0; j < v->ctx->nb_streams; j++) {
511 AVStream *st = avformat_new_stream(s, NULL);
513 ret = AVERROR(ENOMEM);
517 avcodec_copy_context(st->codec, v->ctx->streams[j]->codec);
519 av_dict_set(&st->metadata, "variant_bitrate", bitrate_str,
522 stream_offset += v->ctx->nb_streams;
529 free_variant_list(c);
533 static int recheck_discard_flags(AVFormatContext *s, int first)
535 AppleHTTPContext *c = s->priv_data;
538 /* Check if any new streams are needed */
539 for (i = 0; i < c->n_variants; i++)
540 c->variants[i]->cur_needed = 0;;
542 for (i = 0; i < s->nb_streams; i++) {
543 AVStream *st = s->streams[i];
544 struct variant *var = c->variants[s->streams[i]->id];
545 if (st->discard < AVDISCARD_ALL)
548 for (i = 0; i < c->n_variants; i++) {
549 struct variant *v = c->variants[i];
550 if (v->cur_needed && !v->needed) {
553 v->cur_seq_no = c->cur_seq_no;
554 v->pb.eof_reached = 0;
555 av_log(s, AV_LOG_INFO, "Now receiving variant %d\n", i);
556 } else if (first && !v->cur_needed && v->needed) {
558 ffurl_close(v->input);
562 av_log(s, AV_LOG_INFO, "No longer receiving variant %d\n", i);
568 static int applehttp_read_packet(AVFormatContext *s, AVPacket *pkt)
570 AppleHTTPContext *c = s->priv_data;
571 int ret, i, minvariant = -1;
573 if (c->first_packet) {
574 recheck_discard_flags(s, 1);
579 c->end_of_segment = 0;
580 for (i = 0; i < c->n_variants; i++) {
581 struct variant *var = c->variants[i];
582 /* Make sure we've got one buffered packet from each open variant
584 if (var->needed && !var->pkt.data) {
585 ret = av_read_frame(var->ctx, &var->pkt);
587 if (!var->pb.eof_reached)
589 reset_packet(&var->pkt);
592 /* Check if this stream has the packet with the lowest dts */
594 if (minvariant < 0 ||
595 var->pkt.dts < c->variants[minvariant]->pkt.dts)
599 if (c->end_of_segment) {
600 if (recheck_discard_flags(s, 0))
603 /* If we got a packet, return it */
604 if (minvariant >= 0) {
605 *pkt = c->variants[minvariant]->pkt;
606 pkt->stream_index += c->variants[minvariant]->stream_offset;
607 reset_packet(&c->variants[minvariant]->pkt);
613 static int applehttp_close(AVFormatContext *s)
615 AppleHTTPContext *c = s->priv_data;
617 free_variant_list(c);
621 static int applehttp_read_seek(AVFormatContext *s, int stream_index,
622 int64_t timestamp, int flags)
624 AppleHTTPContext *c = s->priv_data;
627 if ((flags & AVSEEK_FLAG_BYTE) || !c->variants[0]->finished)
628 return AVERROR(ENOSYS);
630 timestamp = av_rescale_rnd(timestamp, 1, stream_index >= 0 ?
631 s->streams[stream_index]->time_base.den :
632 AV_TIME_BASE, flags & AVSEEK_FLAG_BACKWARD ?
633 AV_ROUND_DOWN : AV_ROUND_UP);
635 for (i = 0; i < c->n_variants; i++) {
637 struct variant *var = c->variants[i];
640 ffurl_close(var->input);
643 av_free_packet(&var->pkt);
644 reset_packet(&var->pkt);
645 var->pb.eof_reached = 0;
647 /* Locate the segment that contains the target timestamp */
648 for (j = 0; j < var->n_segments; j++) {
649 if (timestamp >= pos &&
650 timestamp < pos + var->segments[j]->duration) {
651 var->cur_seq_no = var->start_seq_no + j;
655 pos += var->segments[j]->duration;
661 static int applehttp_probe(AVProbeData *p)
663 /* Require #EXTM3U at the start, and either one of the ones below
664 * somewhere for a proper match. */
665 if (strncmp(p->buf, "#EXTM3U", 7))
667 if (strstr(p->buf, "#EXT-X-STREAM-INF:") ||
668 strstr(p->buf, "#EXT-X-TARGETDURATION:") ||
669 strstr(p->buf, "#EXT-X-MEDIA-SEQUENCE:"))
670 return AVPROBE_SCORE_MAX;
674 AVInputFormat ff_applehttp_demuxer = {
676 .long_name = NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming format"),
677 .priv_data_size = sizeof(AppleHTTPContext),
678 .read_probe = applehttp_probe,
679 .read_header = applehttp_read_header,
680 .read_packet = applehttp_read_packet,
681 .read_close = applehttp_close,
682 .read_seek = applehttp_read_seek,