2 * Apple HTTP Live Streaming demuxer
3 * Copyright (c) 2010 Martin Storsjo
5 * This file is part of FFmpeg.
7 * FFmpeg 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 * FFmpeg 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 FFmpeg; 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 #define _XOPEN_SOURCE 600
29 #include "libavutil/avstring.h"
35 * An apple http stream consists of a playlist with media segment files,
36 * played sequentially. There may be several playlists with the same
37 * video content, in different bandwidth variants, that are played in
38 * parallel (preferrably only one bandwidth variant at a time). In this case,
39 * the user supplied the url to a main playlist that only lists the variant
42 * If the main playlist doesn't point at any variants, we still create
43 * one anonymous toplevel variant for this, to maintain the structure.
48 char url[MAX_URL_SIZE];
52 * Each variant has its own demuxer. If it currently is active,
53 * it has an open ByteIOContext too, and potentially an AVPacket
54 * containing the next packet from this stream.
58 char url[MAX_URL_SIZE];
66 struct segment **segments;
70 typedef struct AppleHTTPContext {
74 struct variant **variants;
76 int64_t last_load_time;
77 int64_t last_packet_dts;
78 int max_start_seq, min_end_seq;
81 static int read_chomp_line(ByteIOContext *s, char *buf, int maxlen)
83 int len = ff_get_line(s, buf, maxlen);
84 while (len > 0 && isspace(buf[len - 1]))
89 static void make_absolute_url(char *buf, int size, const char *base,
93 /* If rel actually is an absolute url, just copy it */
94 if (!base || strstr(rel, "://") || rel[0] == '/') {
95 av_strlcpy(buf, rel, size);
99 av_strlcpy(buf, base, size);
100 /* Remove the file name from the base url */
101 sep = strrchr(buf, '/');
106 while (av_strstart(rel, "../", NULL) && sep) {
107 /* Remove the path delimiter at the end */
109 sep = strrchr(buf, '/');
110 /* If the next directory name to pop off is "..", break here */
111 if (!strcmp(sep ? &sep[1] : buf, "..")) {
112 /* Readd the slash we just removed */
113 av_strlcat(buf, "/", size);
116 /* Cut off the directory name */
123 av_strlcat(buf, rel, size);
126 static void free_segment_list(struct variant *var)
129 for (i = 0; i < var->n_segments; i++)
130 av_free(var->segments[i]);
131 av_freep(&var->segments);
135 static void free_variant_list(AppleHTTPContext *c)
138 for (i = 0; i < c->n_variants; i++) {
139 struct variant *var = c->variants[i];
140 free_segment_list(var);
141 av_free_packet(&var->pkt);
146 av_close_input_file(var->ctx);
150 av_freep(&c->variants);
155 * Used to reset a statically allocated AVPacket to a clean slate,
156 * containing no data.
158 static void reset_packet(AVPacket *pkt)
164 static struct variant *new_variant(AppleHTTPContext *c, int bandwidth,
165 const char *url, const char *base)
167 struct variant *var = av_mallocz(sizeof(struct variant));
170 reset_packet(&var->pkt);
171 var->bandwidth = bandwidth;
172 make_absolute_url(var->url, sizeof(var->url), base, url);
173 dynarray_add(&c->variants, &c->n_variants, var);
177 struct variant_info {
181 static void handle_variant_args(struct variant_info *info, const char *key,
182 int key_len, char **dest, int *dest_len)
184 if (!strncmp(key, "BANDWIDTH=", key_len)) {
185 *dest = info->bandwidth;
186 *dest_len = sizeof(info->bandwidth);
190 static int parse_playlist(AppleHTTPContext *c, const char *url,
191 struct variant *var, ByteIOContext *in)
193 int ret = 0, duration = 0, is_segment = 0, is_variant = 0, bandwidth = 0;
200 if ((ret = url_fopen(&in, url, URL_RDONLY)) < 0)
204 read_chomp_line(in, line, sizeof(line));
205 if (strcmp(line, "#EXTM3U")) {
206 ret = AVERROR_INVALIDDATA;
211 free_segment_list(var);
213 while (!url_feof(in)) {
214 read_chomp_line(in, line, sizeof(line));
215 if (av_strstart(line, "#EXT-X-STREAM-INF:", &ptr)) {
216 struct variant_info info = {{0}};
218 ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_variant_args,
220 bandwidth = atoi(info.bandwidth);
221 } else if (av_strstart(line, "#EXT-X-TARGETDURATION:", &ptr)) {
222 c->target_duration = atoi(ptr);
223 } else if (av_strstart(line, "#EXT-X-MEDIA-SEQUENCE:", &ptr)) {
225 var = new_variant(c, 0, url, NULL);
227 ret = AVERROR(ENOMEM);
231 var->start_seq_no = atoi(ptr);
232 } else if (av_strstart(line, "#EXT-X-ENDLIST", &ptr)) {
234 } else if (av_strstart(line, "#EXTINF:", &ptr)) {
236 duration = atoi(ptr);
237 } else if (av_strstart(line, "#", NULL)) {
239 } else if (line[0]) {
241 if (!new_variant(c, bandwidth, line, url)) {
242 ret = AVERROR(ENOMEM);
251 var = new_variant(c, 0, url, NULL);
253 ret = AVERROR(ENOMEM);
257 seg = av_malloc(sizeof(struct segment));
259 ret = AVERROR(ENOMEM);
262 seg->duration = duration;
263 make_absolute_url(seg->url, sizeof(seg->url), url, line);
264 dynarray_add(&var->segments, &var->n_segments, seg);
269 c->last_load_time = av_gettime();
277 static int applehttp_read_header(AVFormatContext *s, AVFormatParameters *ap)
279 AppleHTTPContext *c = s->priv_data;
280 int ret = 0, i, j, stream_offset = 0;
282 if ((ret = parse_playlist(c, s->filename, NULL, s->pb)) < 0)
285 if (c->n_variants == 0) {
286 av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
290 /* If the playlist only contained variants, parse each individual
291 * variant playlist. */
292 if (c->n_variants > 1 || c->variants[0]->n_segments == 0) {
293 for (i = 0; i < c->n_variants; i++) {
294 struct variant *v = c->variants[i];
295 if ((ret = parse_playlist(c, v->url, v, NULL)) < 0)
300 if (c->variants[0]->n_segments == 0) {
301 av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
306 /* If this isn't a live stream, calculate the total duration of the
309 int64_t duration = 0;
310 for (i = 0; i < c->variants[0]->n_segments; i++)
311 duration += c->variants[0]->segments[i]->duration;
312 s->duration = duration * AV_TIME_BASE;
315 c->min_end_seq = INT_MAX;
316 /* Open the demuxer for each variant */
317 for (i = 0; i < c->n_variants; i++) {
318 struct variant *v = c->variants[i];
319 if (v->n_segments == 0)
321 c->max_start_seq = FFMAX(c->max_start_seq, v->start_seq_no);
322 c->min_end_seq = FFMIN(c->min_end_seq, v->start_seq_no +
324 ret = av_open_input_file(&v->ctx, v->segments[0]->url, NULL, 0, NULL);
327 url_fclose(v->ctx->pb);
329 v->stream_offset = stream_offset;
330 /* Create new AVStreams for each stream in this variant */
331 for (j = 0; j < v->ctx->nb_streams; j++) {
332 AVStream *st = av_new_stream(s, i);
334 ret = AVERROR(ENOMEM);
337 avcodec_copy_context(st->codec, v->ctx->streams[j]->codec);
339 stream_offset += v->ctx->nb_streams;
341 c->last_packet_dts = AV_NOPTS_VALUE;
343 c->cur_seq_no = c->max_start_seq;
344 /* If this is a live stream with more than 3 segments, start at the
345 * third last segment. */
346 if (!c->finished && c->min_end_seq - c->max_start_seq > 3)
347 c->cur_seq_no = c->min_end_seq - 2;
351 free_variant_list(c);
355 static int open_variant(AppleHTTPContext *c, struct variant *var, int skip)
359 if (c->cur_seq_no < var->start_seq_no) {
360 av_log(NULL, AV_LOG_WARNING,
361 "seq %d not available in variant %s, skipping\n",
362 var->start_seq_no, var->url);
365 if (c->cur_seq_no - var->start_seq_no >= var->n_segments)
366 return c->finished ? AVERROR_EOF : 0;
367 ret = url_fopen(&var->pb,
368 var->segments[c->cur_seq_no - var->start_seq_no]->url,
372 var->ctx->pb = var->pb;
373 /* If this is a new segment in parallel with another one already opened,
374 * skip ahead so they're all at the same dts. */
375 if (skip && c->last_packet_dts != AV_NOPTS_VALUE) {
377 ret = av_read_frame(var->ctx, &var->pkt);
379 if (ret == AVERROR_EOF) {
380 reset_packet(&var->pkt);
385 if (var->pkt.dts >= c->last_packet_dts)
387 av_free_packet(&var->pkt);
393 static int applehttp_read_packet(AVFormatContext *s, AVPacket *pkt)
395 AppleHTTPContext *c = s->priv_data;
396 int ret, i, minvariant = -1, first = 1, needed = 0, changed = 0,
399 /* Recheck the discard flags - which streams are desired at the moment */
400 for (i = 0; i < c->n_variants; i++)
401 c->variants[i]->needed = 0;
402 for (i = 0; i < s->nb_streams; i++) {
403 AVStream *st = s->streams[i];
404 struct variant *var = c->variants[s->streams[i]->id];
405 if (st->discard < AVDISCARD_ALL) {
409 /* Copy the discard flag to the chained demuxer, to indicate which
410 * streams are desired. */
411 var->ctx->streams[i - var->stream_offset]->discard = st->discard;
416 for (i = 0; i < c->n_variants; i++) {
417 struct variant *var = c->variants[i];
418 /* Close unneeded streams, open newly requested streams */
419 if (var->pb && !var->needed) {
420 av_log(s, AV_LOG_DEBUG,
421 "Closing variant stream %d, no longer needed\n", i);
422 av_free_packet(&var->pkt);
423 reset_packet(&var->pkt);
427 } else if (!var->pb && var->needed) {
429 av_log(s, AV_LOG_DEBUG, "Opening variant stream %d\n", i);
430 if (first && !c->finished)
431 if ((ret = parse_playlist(c, var->url, var, NULL)) < 0)
433 ret = open_variant(c, var, first);
438 /* Count the number of open variants */
441 /* Make sure we've got one buffered packet from each open variant
443 if (var->pb && !var->pkt.data) {
444 ret = av_read_frame(var->ctx, &var->pkt);
446 if (!url_feof(var->pb))
448 reset_packet(&var->pkt);
451 /* Check if this stream has the packet with the lowest dts */
453 if (minvariant < 0 ||
454 var->pkt.dts < c->variants[minvariant]->pkt.dts)
458 if (first && changed)
459 av_log(s, AV_LOG_INFO, "Receiving %d variant streams\n", variants);
460 /* If we got a packet, return it */
461 if (minvariant >= 0) {
462 *pkt = c->variants[minvariant]->pkt;
463 pkt->stream_index += c->variants[minvariant]->stream_offset;
464 reset_packet(&c->variants[minvariant]->pkt);
465 c->last_packet_dts = pkt->dts;
468 /* No more packets - eof reached in all variant streams, close the
469 * current segments. */
470 for (i = 0; i < c->n_variants; i++) {
471 struct variant *var = c->variants[i];
477 /* Indicate that we're opening the next segment, not opening a new
478 * variant stream in parallel, so we shouldn't try to skip ahead. */
483 /* If this is a live stream and target_duration has elapsed since
484 * the last playlist reload, reload the variant playlists now. */
485 int64_t now = av_gettime();
486 if (now - c->last_load_time >= c->target_duration*1000000) {
487 c->max_start_seq = 0;
488 c->min_end_seq = INT_MAX;
489 for (i = 0; i < c->n_variants; i++) {
490 struct variant *var = c->variants[i];
492 if ((ret = parse_playlist(c, var->url, var, NULL)) < 0)
494 c->max_start_seq = FFMAX(c->max_start_seq,
496 c->min_end_seq = FFMIN(c->min_end_seq,
497 var->start_seq_no + var->n_segments);
502 if (c->cur_seq_no < c->max_start_seq) {
503 av_log(NULL, AV_LOG_WARNING,
504 "skipping %d segments ahead, expired from playlists\n",
505 c->max_start_seq - c->cur_seq_no);
506 c->cur_seq_no = c->max_start_seq;
508 /* If more segments exit, open the next one */
509 if (c->cur_seq_no < c->min_end_seq)
511 /* We've reached the end of the playlists - return eof if this is a
512 * non-live stream, wait until the next playlist reload if it is live. */
515 while (av_gettime() - c->last_load_time < c->target_duration*1000000) {
516 if (url_interrupt_cb())
517 return AVERROR(EINTR);
520 /* Enough time has elapsed since the last reload */
524 static int applehttp_close(AVFormatContext *s)
526 AppleHTTPContext *c = s->priv_data;
528 free_variant_list(c);
532 static int applehttp_read_seek(AVFormatContext *s, int stream_index,
533 int64_t timestamp, int flags)
535 AppleHTTPContext *c = s->priv_data;
537 struct variant *var = c->variants[0];
539 if ((flags & AVSEEK_FLAG_BYTE) || !c->finished)
540 return AVERROR(ENOSYS);
542 /* Reset the variants */
543 c->last_packet_dts = AV_NOPTS_VALUE;
544 for (i = 0; i < c->n_variants; i++) {
545 struct variant *var = c->variants[i];
550 av_free_packet(&var->pkt);
551 reset_packet(&var->pkt);
554 timestamp = av_rescale_rnd(timestamp, 1, stream_index >= 0 ?
555 s->streams[stream_index]->time_base.den :
556 AV_TIME_BASE, flags & AVSEEK_FLAG_BACKWARD ?
557 AV_ROUND_DOWN : AV_ROUND_UP);
558 /* Locate the segment that contains the target timestamp */
559 for (i = 0; i < var->n_segments; i++) {
560 if (timestamp >= pos && timestamp < pos + var->segments[i]->duration) {
561 c->cur_seq_no = var->start_seq_no + i;
564 pos += var->segments[i]->duration;
569 static int applehttp_probe(AVProbeData *p)
571 /* Require #EXTM3U at the start, and either one of the ones below
572 * somewhere for a proper match. */
573 if (strncmp(p->buf, "#EXTM3U", 7))
575 if (strstr(p->buf, "#EXT-X-STREAM-INF:") ||
576 strstr(p->buf, "#EXT-X-TARGETDURATION:") ||
577 strstr(p->buf, "#EXT-X-MEDIA-SEQUENCE:"))
578 return AVPROBE_SCORE_MAX;
582 AVInputFormat applehttp_demuxer = {
584 NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming format"),
585 sizeof(AppleHTTPContext),
587 applehttp_read_header,
588 applehttp_read_packet,