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 AVIOContext 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(AVIOContext *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 /* Absolute path, relative to the current server */
94 if (base && strstr(base, "://") && rel[0] == '/') {
96 av_strlcpy(buf, base, size);
97 sep = strstr(buf, "://");
100 sep = strchr(sep, '/');
104 av_strlcat(buf, rel, size);
107 /* If rel actually is an absolute url, just copy it */
108 if (!base || strstr(rel, "://") || rel[0] == '/') {
109 av_strlcpy(buf, rel, size);
113 av_strlcpy(buf, base, size);
114 /* Remove the file name from the base url */
115 sep = strrchr(buf, '/');
120 while (av_strstart(rel, "../", NULL) && sep) {
121 /* Remove the path delimiter at the end */
123 sep = strrchr(buf, '/');
124 /* If the next directory name to pop off is "..", break here */
125 if (!strcmp(sep ? &sep[1] : buf, "..")) {
126 /* Readd the slash we just removed */
127 av_strlcat(buf, "/", size);
130 /* Cut off the directory name */
137 av_strlcat(buf, rel, size);
140 static void free_segment_list(struct variant *var)
143 for (i = 0; i < var->n_segments; i++)
144 av_free(var->segments[i]);
145 av_freep(&var->segments);
149 static void free_variant_list(AppleHTTPContext *c)
152 for (i = 0; i < c->n_variants; i++) {
153 struct variant *var = c->variants[i];
154 free_segment_list(var);
155 av_free_packet(&var->pkt);
160 av_close_input_file(var->ctx);
164 av_freep(&c->variants);
169 * Used to reset a statically allocated AVPacket to a clean slate,
170 * containing no data.
172 static void reset_packet(AVPacket *pkt)
178 static struct variant *new_variant(AppleHTTPContext *c, int bandwidth,
179 const char *url, const char *base)
181 struct variant *var = av_mallocz(sizeof(struct variant));
184 reset_packet(&var->pkt);
185 var->bandwidth = bandwidth;
186 make_absolute_url(var->url, sizeof(var->url), base, url);
187 dynarray_add(&c->variants, &c->n_variants, var);
191 struct variant_info {
195 static void handle_variant_args(struct variant_info *info, const char *key,
196 int key_len, char **dest, int *dest_len)
198 if (!strncmp(key, "BANDWIDTH=", key_len)) {
199 *dest = info->bandwidth;
200 *dest_len = sizeof(info->bandwidth);
204 static int parse_playlist(AppleHTTPContext *c, const char *url,
205 struct variant *var, AVIOContext *in)
207 int ret = 0, duration = 0, is_segment = 0, is_variant = 0, bandwidth = 0;
214 if ((ret = avio_open(&in, url, URL_RDONLY)) < 0)
218 read_chomp_line(in, line, sizeof(line));
219 if (strcmp(line, "#EXTM3U")) {
220 ret = AVERROR_INVALIDDATA;
225 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-TARGETDURATION:", &ptr)) {
236 c->target_duration = atoi(ptr);
237 } else if (av_strstart(line, "#EXT-X-MEDIA-SEQUENCE:", &ptr)) {
239 var = new_variant(c, 0, url, NULL);
241 ret = AVERROR(ENOMEM);
245 var->start_seq_no = atoi(ptr);
246 } else if (av_strstart(line, "#EXT-X-ENDLIST", &ptr)) {
248 } else if (av_strstart(line, "#EXTINF:", &ptr)) {
250 duration = atoi(ptr);
251 } else if (av_strstart(line, "#", NULL)) {
253 } else if (line[0]) {
255 if (!new_variant(c, bandwidth, line, url)) {
256 ret = AVERROR(ENOMEM);
265 var = new_variant(c, 0, url, NULL);
267 ret = AVERROR(ENOMEM);
271 seg = av_malloc(sizeof(struct segment));
273 ret = AVERROR(ENOMEM);
276 seg->duration = duration;
277 make_absolute_url(seg->url, sizeof(seg->url), url, line);
278 dynarray_add(&var->segments, &var->n_segments, seg);
283 c->last_load_time = av_gettime();
291 static int applehttp_read_header(AVFormatContext *s, AVFormatParameters *ap)
293 AppleHTTPContext *c = s->priv_data;
294 int ret = 0, i, j, stream_offset = 0;
296 if ((ret = parse_playlist(c, s->filename, NULL, s->pb)) < 0)
299 if (c->n_variants == 0) {
300 av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
304 /* If the playlist only contained variants, parse each individual
305 * variant playlist. */
306 if (c->n_variants > 1 || c->variants[0]->n_segments == 0) {
307 for (i = 0; i < c->n_variants; i++) {
308 struct variant *v = c->variants[i];
309 if ((ret = parse_playlist(c, v->url, v, NULL)) < 0)
314 if (c->variants[0]->n_segments == 0) {
315 av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
320 /* If this isn't a live stream, calculate the total duration of the
323 int64_t duration = 0;
324 for (i = 0; i < c->variants[0]->n_segments; i++)
325 duration += c->variants[0]->segments[i]->duration;
326 s->duration = duration * AV_TIME_BASE;
329 c->min_end_seq = INT_MAX;
330 /* Open the demuxer for each variant */
331 for (i = 0; i < c->n_variants; i++) {
332 struct variant *v = c->variants[i];
333 if (v->n_segments == 0)
335 c->max_start_seq = FFMAX(c->max_start_seq, v->start_seq_no);
336 c->min_end_seq = FFMIN(c->min_end_seq, v->start_seq_no +
338 ret = av_open_input_file(&v->ctx, v->segments[0]->url, NULL, 0, NULL);
341 avio_close(v->ctx->pb);
343 v->stream_offset = stream_offset;
344 /* Create new AVStreams for each stream in this variant */
345 for (j = 0; j < v->ctx->nb_streams; j++) {
346 AVStream *st = av_new_stream(s, i);
348 ret = AVERROR(ENOMEM);
351 avcodec_copy_context(st->codec, v->ctx->streams[j]->codec);
353 stream_offset += v->ctx->nb_streams;
355 c->last_packet_dts = AV_NOPTS_VALUE;
357 c->cur_seq_no = c->max_start_seq;
358 /* If this is a live stream with more than 3 segments, start at the
359 * third last segment. */
360 if (!c->finished && c->min_end_seq - c->max_start_seq > 3)
361 c->cur_seq_no = c->min_end_seq - 2;
365 free_variant_list(c);
369 static int open_variant(AppleHTTPContext *c, struct variant *var, int skip)
373 if (c->cur_seq_no < var->start_seq_no) {
374 av_log(NULL, AV_LOG_WARNING,
375 "seq %d not available in variant %s, skipping\n",
376 var->start_seq_no, var->url);
379 if (c->cur_seq_no - var->start_seq_no >= var->n_segments)
380 return c->finished ? AVERROR_EOF : 0;
381 ret = avio_open(&var->pb,
382 var->segments[c->cur_seq_no - var->start_seq_no]->url,
386 var->ctx->pb = var->pb;
387 /* If this is a new segment in parallel with another one already opened,
388 * skip ahead so they're all at the same dts. */
389 if (skip && c->last_packet_dts != AV_NOPTS_VALUE) {
391 ret = av_read_frame(var->ctx, &var->pkt);
393 if (ret == AVERROR_EOF) {
394 reset_packet(&var->pkt);
399 if (var->pkt.dts >= c->last_packet_dts)
401 av_free_packet(&var->pkt);
407 static int applehttp_read_packet(AVFormatContext *s, AVPacket *pkt)
409 AppleHTTPContext *c = s->priv_data;
410 int ret, i, minvariant = -1, first = 1, needed = 0, changed = 0,
413 /* Recheck the discard flags - which streams are desired at the moment */
414 for (i = 0; i < c->n_variants; i++)
415 c->variants[i]->needed = 0;
416 for (i = 0; i < s->nb_streams; i++) {
417 AVStream *st = s->streams[i];
418 struct variant *var = c->variants[s->streams[i]->id];
419 if (st->discard < AVDISCARD_ALL) {
423 /* Copy the discard flag to the chained demuxer, to indicate which
424 * streams are desired. */
425 var->ctx->streams[i - var->stream_offset]->discard = st->discard;
430 for (i = 0; i < c->n_variants; i++) {
431 struct variant *var = c->variants[i];
432 /* Close unneeded streams, open newly requested streams */
433 if (var->pb && !var->needed) {
434 av_log(s, AV_LOG_DEBUG,
435 "Closing variant stream %d, no longer needed\n", i);
436 av_free_packet(&var->pkt);
437 reset_packet(&var->pkt);
441 } else if (!var->pb && var->needed) {
443 av_log(s, AV_LOG_DEBUG, "Opening variant stream %d\n", i);
444 if (first && !c->finished)
445 if ((ret = parse_playlist(c, var->url, var, NULL)) < 0)
447 ret = open_variant(c, var, first);
452 /* Count the number of open variants */
455 /* Make sure we've got one buffered packet from each open variant
457 if (var->pb && !var->pkt.data) {
458 ret = av_read_frame(var->ctx, &var->pkt);
460 if (!var->pb->eof_reached)
462 reset_packet(&var->pkt);
465 /* Check if this stream has the packet with the lowest dts */
467 if (minvariant < 0 ||
468 var->pkt.dts < c->variants[minvariant]->pkt.dts)
472 if (first && changed)
473 av_log(s, AV_LOG_INFO, "Receiving %d variant streams\n", variants);
474 /* If we got a packet, return it */
475 if (minvariant >= 0) {
476 *pkt = c->variants[minvariant]->pkt;
477 pkt->stream_index += c->variants[minvariant]->stream_offset;
478 reset_packet(&c->variants[minvariant]->pkt);
479 c->last_packet_dts = pkt->dts;
482 /* No more packets - eof reached in all variant streams, close the
483 * current segments. */
484 for (i = 0; i < c->n_variants; i++) {
485 struct variant *var = c->variants[i];
491 /* Indicate that we're opening the next segment, not opening a new
492 * variant stream in parallel, so we shouldn't try to skip ahead. */
497 /* If this is a live stream and target_duration has elapsed since
498 * the last playlist reload, reload the variant playlists now. */
499 int64_t now = av_gettime();
500 if (now - c->last_load_time >= c->target_duration*1000000) {
501 c->max_start_seq = 0;
502 c->min_end_seq = INT_MAX;
503 for (i = 0; i < c->n_variants; i++) {
504 struct variant *var = c->variants[i];
506 if ((ret = parse_playlist(c, var->url, var, NULL)) < 0)
508 c->max_start_seq = FFMAX(c->max_start_seq,
510 c->min_end_seq = FFMIN(c->min_end_seq,
511 var->start_seq_no + var->n_segments);
516 if (c->cur_seq_no < c->max_start_seq) {
517 av_log(NULL, AV_LOG_WARNING,
518 "skipping %d segments ahead, expired from playlists\n",
519 c->max_start_seq - c->cur_seq_no);
520 c->cur_seq_no = c->max_start_seq;
522 /* If more segments exist, open the next one */
523 if (c->cur_seq_no < c->min_end_seq)
525 /* We've reached the end of the playlists - return eof if this is a
526 * non-live stream, wait until the next playlist reload if it is live. */
529 while (av_gettime() - c->last_load_time < c->target_duration*1000000) {
530 if (url_interrupt_cb())
534 /* Enough time has elapsed since the last reload */
538 static int applehttp_close(AVFormatContext *s)
540 AppleHTTPContext *c = s->priv_data;
542 free_variant_list(c);
546 static int applehttp_read_seek(AVFormatContext *s, int stream_index,
547 int64_t timestamp, int flags)
549 AppleHTTPContext *c = s->priv_data;
551 struct variant *var = c->variants[0];
553 if ((flags & AVSEEK_FLAG_BYTE) || !c->finished)
554 return AVERROR(ENOSYS);
556 /* Reset the variants */
557 c->last_packet_dts = AV_NOPTS_VALUE;
558 for (i = 0; i < c->n_variants; i++) {
559 struct variant *var = c->variants[i];
564 av_free_packet(&var->pkt);
565 reset_packet(&var->pkt);
568 timestamp = av_rescale_rnd(timestamp, 1, stream_index >= 0 ?
569 s->streams[stream_index]->time_base.den :
570 AV_TIME_BASE, flags & AVSEEK_FLAG_BACKWARD ?
571 AV_ROUND_DOWN : AV_ROUND_UP);
572 /* Locate the segment that contains the target timestamp */
573 for (i = 0; i < var->n_segments; i++) {
574 if (timestamp >= pos && timestamp < pos + var->segments[i]->duration) {
575 c->cur_seq_no = var->start_seq_no + i;
578 pos += var->segments[i]->duration;
583 static int applehttp_probe(AVProbeData *p)
585 /* Require #EXTM3U at the start, and either one of the ones below
586 * somewhere for a proper match. */
587 if (strncmp(p->buf, "#EXTM3U", 7))
589 if (strstr(p->buf, "#EXT-X-STREAM-INF:") ||
590 strstr(p->buf, "#EXT-X-TARGETDURATION:") ||
591 strstr(p->buf, "#EXT-X-MEDIA-SEQUENCE:"))
592 return AVPROBE_SCORE_MAX;
596 AVInputFormat ff_applehttp_demuxer = {
598 NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming format"),
599 sizeof(AppleHTTPContext),
601 applehttp_read_header,
602 applehttp_read_packet,