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 &var->parent->interrupt_callback, NULL);
328 } else if (seg->key_type == KEY_AES_128) {
329 char iv[33], key[33], url[MAX_URL_SIZE];
331 if (strcmp(seg->key, var->key_url)) {
333 if (ffurl_open(&uc, seg->key, AVIO_FLAG_READ,
334 &var->parent->interrupt_callback, NULL) == 0) {
335 if (ffurl_read_complete(uc, var->key, sizeof(var->key))
336 != sizeof(var->key)) {
337 av_log(NULL, AV_LOG_ERROR, "Unable to read key file %s\n",
342 av_log(NULL, AV_LOG_ERROR, "Unable to open key file %s\n",
345 av_strlcpy(var->key_url, seg->key, sizeof(var->key_url));
347 ff_data_to_hex(iv, seg->iv, sizeof(seg->iv), 0);
348 ff_data_to_hex(key, var->key, sizeof(var->key), 0);
349 iv[32] = key[32] = '\0';
350 if (strstr(seg->url, "://"))
351 snprintf(url, sizeof(url), "crypto+%s", seg->url);
353 snprintf(url, sizeof(url), "crypto:%s", seg->url);
354 if ((ret = ffurl_alloc(&var->input, url, AVIO_FLAG_READ,
355 &var->parent->interrupt_callback)) < 0)
357 av_opt_set(var->input->priv_data, "key", key, 0);
358 av_opt_set(var->input->priv_data, "iv", iv, 0);
359 if ((ret = ffurl_connect(var->input, NULL)) < 0) {
360 ffurl_close(var->input);
366 return AVERROR(ENOSYS);
369 static int read_data(void *opaque, uint8_t *buf, int buf_size)
371 struct variant *v = opaque;
372 AppleHTTPContext *c = v->parent->priv_data;
378 /* If this is a live stream and target_duration has elapsed since
379 * the last playlist reload, reload the variant playlists now. */
381 av_gettime() - v->last_load_time >= v->target_duration*1000000 &&
382 (ret = parse_playlist(c, v->url, v, NULL)) < 0)
384 if (v->cur_seq_no < v->start_seq_no) {
385 av_log(NULL, AV_LOG_WARNING,
386 "skipping %d segments ahead, expired from playlists\n",
387 v->start_seq_no - v->cur_seq_no);
388 v->cur_seq_no = v->start_seq_no;
390 if (v->cur_seq_no >= v->start_seq_no + v->n_segments) {
393 while (av_gettime() - v->last_load_time <
394 v->target_duration*1000000) {
395 if (ff_check_interrupt(c->interrupt_callback))
399 /* Enough time has elapsed since the last reload */
407 ret = ffurl_read(v->input, buf, buf_size);
410 if (ret < 0 && ret != AVERROR_EOF)
412 ffurl_close(v->input);
416 c->end_of_segment = 1;
417 c->cur_seq_no = v->cur_seq_no;
419 if (v->ctx && v->ctx->nb_streams) {
421 for (i = v->stream_offset; i < v->stream_offset + v->ctx->nb_streams;
423 if (v->parent->streams[i]->discard < AVDISCARD_ALL)
428 av_log(v->parent, AV_LOG_INFO, "No longer receiving variant %d\n",
435 static int applehttp_read_header(AVFormatContext *s, AVFormatParameters *ap)
437 AppleHTTPContext *c = s->priv_data;
438 int ret = 0, i, j, stream_offset = 0;
440 c->interrupt_callback = &s->interrupt_callback;
442 if ((ret = parse_playlist(c, s->filename, NULL, s->pb)) < 0)
445 if (c->n_variants == 0) {
446 av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
450 /* If the playlist only contained variants, parse each individual
451 * variant playlist. */
452 if (c->n_variants > 1 || c->variants[0]->n_segments == 0) {
453 for (i = 0; i < c->n_variants; i++) {
454 struct variant *v = c->variants[i];
455 if ((ret = parse_playlist(c, v->url, v, NULL)) < 0)
460 if (c->variants[0]->n_segments == 0) {
461 av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
466 /* If this isn't a live stream, calculate the total duration of the
468 if (c->variants[0]->finished) {
469 int64_t duration = 0;
470 for (i = 0; i < c->variants[0]->n_segments; i++)
471 duration += c->variants[0]->segments[i]->duration;
472 s->duration = duration * AV_TIME_BASE;
475 /* Open the demuxer for each variant */
476 for (i = 0; i < c->n_variants; i++) {
477 struct variant *v = c->variants[i];
478 AVInputFormat *in_fmt = NULL;
479 char bitrate_str[20];
480 if (v->n_segments == 0)
483 if (!(v->ctx = avformat_alloc_context())) {
484 ret = AVERROR(ENOMEM);
492 /* If this is a live stream with more than 3 segments, start at the
493 * third last segment. */
494 v->cur_seq_no = v->start_seq_no;
495 if (!v->finished && v->n_segments > 3)
496 v->cur_seq_no = v->start_seq_no + v->n_segments - 3;
498 v->read_buffer = av_malloc(INITIAL_BUFFER_SIZE);
499 ffio_init_context(&v->pb, v->read_buffer, INITIAL_BUFFER_SIZE, 0, v,
500 read_data, NULL, NULL);
502 ret = av_probe_input_buffer(&v->pb, &in_fmt, v->segments[0]->url,
507 ret = avformat_open_input(&v->ctx, v->segments[0]->url, in_fmt, NULL);
510 v->stream_offset = stream_offset;
511 snprintf(bitrate_str, sizeof(bitrate_str), "%d", v->bandwidth);
512 /* Create new AVStreams for each stream in this variant */
513 for (j = 0; j < v->ctx->nb_streams; j++) {
514 AVStream *st = avformat_new_stream(s, NULL);
516 ret = AVERROR(ENOMEM);
520 avcodec_copy_context(st->codec, v->ctx->streams[j]->codec);
522 av_dict_set(&st->metadata, "variant_bitrate", bitrate_str,
525 stream_offset += v->ctx->nb_streams;
532 free_variant_list(c);
536 static int recheck_discard_flags(AVFormatContext *s, int first)
538 AppleHTTPContext *c = s->priv_data;
541 /* Check if any new streams are needed */
542 for (i = 0; i < c->n_variants; i++)
543 c->variants[i]->cur_needed = 0;;
545 for (i = 0; i < s->nb_streams; i++) {
546 AVStream *st = s->streams[i];
547 struct variant *var = c->variants[s->streams[i]->id];
548 if (st->discard < AVDISCARD_ALL)
551 for (i = 0; i < c->n_variants; i++) {
552 struct variant *v = c->variants[i];
553 if (v->cur_needed && !v->needed) {
556 v->cur_seq_no = c->cur_seq_no;
557 v->pb.eof_reached = 0;
558 av_log(s, AV_LOG_INFO, "Now receiving variant %d\n", i);
559 } else if (first && !v->cur_needed && v->needed) {
561 ffurl_close(v->input);
565 av_log(s, AV_LOG_INFO, "No longer receiving variant %d\n", i);
571 static int applehttp_read_packet(AVFormatContext *s, AVPacket *pkt)
573 AppleHTTPContext *c = s->priv_data;
574 int ret, i, minvariant = -1;
576 if (c->first_packet) {
577 recheck_discard_flags(s, 1);
582 c->end_of_segment = 0;
583 for (i = 0; i < c->n_variants; i++) {
584 struct variant *var = c->variants[i];
585 /* Make sure we've got one buffered packet from each open variant
587 if (var->needed && !var->pkt.data) {
588 ret = av_read_frame(var->ctx, &var->pkt);
590 if (!var->pb.eof_reached)
592 reset_packet(&var->pkt);
595 /* Check if this stream has the packet with the lowest dts */
597 if (minvariant < 0 ||
598 var->pkt.dts < c->variants[minvariant]->pkt.dts)
602 if (c->end_of_segment) {
603 if (recheck_discard_flags(s, 0))
606 /* If we got a packet, return it */
607 if (minvariant >= 0) {
608 *pkt = c->variants[minvariant]->pkt;
609 pkt->stream_index += c->variants[minvariant]->stream_offset;
610 reset_packet(&c->variants[minvariant]->pkt);
616 static int applehttp_close(AVFormatContext *s)
618 AppleHTTPContext *c = s->priv_data;
620 free_variant_list(c);
624 static int applehttp_read_seek(AVFormatContext *s, int stream_index,
625 int64_t timestamp, int flags)
627 AppleHTTPContext *c = s->priv_data;
630 if ((flags & AVSEEK_FLAG_BYTE) || !c->variants[0]->finished)
631 return AVERROR(ENOSYS);
633 timestamp = av_rescale_rnd(timestamp, 1, stream_index >= 0 ?
634 s->streams[stream_index]->time_base.den :
635 AV_TIME_BASE, flags & AVSEEK_FLAG_BACKWARD ?
636 AV_ROUND_DOWN : AV_ROUND_UP);
638 for (i = 0; i < c->n_variants; i++) {
640 struct variant *var = c->variants[i];
643 ffurl_close(var->input);
646 av_free_packet(&var->pkt);
647 reset_packet(&var->pkt);
648 var->pb.eof_reached = 0;
650 /* Locate the segment that contains the target timestamp */
651 for (j = 0; j < var->n_segments; j++) {
652 if (timestamp >= pos &&
653 timestamp < pos + var->segments[j]->duration) {
654 var->cur_seq_no = var->start_seq_no + j;
658 pos += var->segments[j]->duration;
664 static int applehttp_probe(AVProbeData *p)
666 /* Require #EXTM3U at the start, and either one of the ones below
667 * somewhere for a proper match. */
668 if (strncmp(p->buf, "#EXTM3U", 7))
670 if (strstr(p->buf, "#EXT-X-STREAM-INF:") ||
671 strstr(p->buf, "#EXT-X-TARGETDURATION:") ||
672 strstr(p->buf, "#EXT-X-MEDIA-SEQUENCE:"))
673 return AVPROBE_SCORE_MAX;
677 AVInputFormat ff_applehttp_demuxer = {
679 .long_name = NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming format"),
680 .priv_data_size = sizeof(AppleHTTPContext),
681 .read_probe = applehttp_probe,
682 .read_header = applehttp_read_header,
683 .read_packet = applehttp_read_packet,
684 .read_close = applehttp_close,
685 .read_seek = applehttp_read_seek,