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 (!base || strstr(rel, "://") || rel[0] == '/') {
94 av_strlcpy(buf, rel, size);
98 av_strlcpy(buf, base, size);
99 sep = strrchr(buf, '/');
104 while (av_strstart(rel, "../", NULL) && sep) {
106 sep = strrchr(buf, '/');
113 av_strlcat(buf, rel, size);
116 static void free_segment_list(struct variant *var)
119 for (i = 0; i < var->n_segments; i++)
120 av_free(var->segments[i]);
121 av_freep(&var->segments);
125 static void free_variant_list(AppleHTTPContext *c)
128 for (i = 0; i < c->n_variants; i++) {
129 struct variant *var = c->variants[i];
130 free_segment_list(var);
131 av_free_packet(&var->pkt);
136 av_close_input_file(var->ctx);
140 av_freep(&c->variants);
145 * Used to reset a statically allocated AVPacket to a clean slate,
146 * containing no data.
148 static void reset_packet(AVPacket *pkt)
154 static struct variant *new_variant(AppleHTTPContext *c, int bandwidth,
155 const char *url, const char *base)
157 struct variant *var = av_mallocz(sizeof(struct variant));
160 reset_packet(&var->pkt);
161 var->bandwidth = bandwidth;
162 make_absolute_url(var->url, sizeof(var->url), base, url);
163 dynarray_add(&c->variants, &c->n_variants, var);
167 struct variant_info {
171 static void handle_variant_args(struct variant_info *info, const char *key,
172 int key_len, char **dest, int *dest_len)
174 if (strncmp(key, "BANDWIDTH", key_len)) {
175 *dest = info->bandwidth;
176 *dest_len = sizeof(info->bandwidth);
180 static int parse_playlist(AppleHTTPContext *c, const char *url,
181 struct variant *var, ByteIOContext *in)
183 int ret = 0, duration = 0, is_segment = 0, is_variant = 0, bandwidth = 0;
190 if ((ret = url_fopen(&in, url, URL_RDONLY)) < 0)
194 read_chomp_line(in, line, sizeof(line));
195 if (strcmp(line, "#EXTM3U")) {
196 ret = AVERROR_INVALIDDATA;
201 free_segment_list(var);
203 while (!url_feof(in)) {
204 read_chomp_line(in, line, sizeof(line));
205 if (av_strstart(line, "#EXT-X-STREAM-INF:", &ptr)) {
206 struct variant_info info = {{0}};
208 ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_variant_args,
210 bandwidth = atoi(info.bandwidth);
211 } else if (av_strstart(line, "#EXT-X-TARGETDURATION:", &ptr)) {
212 c->target_duration = atoi(ptr);
213 } else if (av_strstart(line, "#EXT-X-MEDIA-SEQUENCE:", &ptr)) {
215 var = new_variant(c, 0, url, NULL);
217 ret = AVERROR(ENOMEM);
221 var->start_seq_no = atoi(ptr);
222 } else if (av_strstart(line, "#EXT-X-ENDLIST", &ptr)) {
224 } else if (av_strstart(line, "#EXTINF:", &ptr)) {
226 duration = atoi(ptr);
227 } else if (av_strstart(line, "#", NULL)) {
229 } else if (line[0]) {
231 if (!new_variant(c, bandwidth, line, url)) {
232 ret = AVERROR(ENOMEM);
241 var = new_variant(c, 0, url, NULL);
243 ret = AVERROR(ENOMEM);
247 seg = av_malloc(sizeof(struct segment));
249 ret = AVERROR(ENOMEM);
252 seg->duration = duration;
253 make_absolute_url(seg->url, sizeof(seg->url), url, line);
254 dynarray_add(&var->segments, &var->n_segments, seg);
259 c->last_load_time = av_gettime();
267 static int applehttp_read_header(AVFormatContext *s, AVFormatParameters *ap)
269 AppleHTTPContext *c = s->priv_data;
270 int ret = 0, i, j, stream_offset = 0;
272 if ((ret = parse_playlist(c, s->filename, NULL, s->pb)) < 0)
275 if (c->n_variants == 0) {
276 av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
280 /* If the playlist only contained variants, parse each individual
281 * variant playlist. */
282 if (c->n_variants > 1 || c->variants[0]->n_segments == 0) {
283 for (i = 0; i < c->n_variants; i++) {
284 struct variant *v = c->variants[i];
285 if ((ret = parse_playlist(c, v->url, v, NULL)) < 0)
290 if (c->variants[0]->n_segments == 0) {
291 av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
296 /* If this isn't a live stream, calculate the total duration of the
300 for (i = 0; i < c->variants[0]->n_segments; i++)
301 duration += c->variants[0]->segments[i]->duration;
302 s->duration = duration * AV_TIME_BASE;
305 c->min_end_seq = INT_MAX;
306 /* Open the demuxer for each variant */
307 for (i = 0; i < c->n_variants; i++) {
308 struct variant *v = c->variants[i];
309 if (v->n_segments == 0)
311 c->max_start_seq = FFMAX(c->max_start_seq, v->start_seq_no);
312 c->min_end_seq = FFMIN(c->min_end_seq, v->start_seq_no +
314 ret = av_open_input_file(&v->ctx, v->segments[0]->url, NULL, 0, NULL);
317 url_fclose(v->ctx->pb);
319 v->stream_offset = stream_offset;
320 /* Create new AVStreams for each stream in this variant */
321 for (j = 0; j < v->ctx->nb_streams; j++) {
322 AVStream *st = av_new_stream(s, i);
324 ret = AVERROR(ENOMEM);
327 avcodec_copy_context(st->codec, v->ctx->streams[j]->codec);
329 stream_offset += v->ctx->nb_streams;
331 c->last_packet_dts = AV_NOPTS_VALUE;
333 c->cur_seq_no = c->max_start_seq;
334 /* If this is a live stream with more than 3 segments, start at the
335 * third last segment. */
336 if (!c->finished && c->min_end_seq - c->max_start_seq > 3)
337 c->cur_seq_no = c->min_end_seq - 2;
341 free_variant_list(c);
345 static int open_variant(AppleHTTPContext *c, struct variant *var, int skip)
349 if (c->cur_seq_no < var->start_seq_no) {
350 av_log(NULL, AV_LOG_WARNING,
351 "seq %d not available in variant %s, skipping\n",
352 var->start_seq_no, var->url);
355 if (c->cur_seq_no - var->start_seq_no >= var->n_segments)
356 return c->finished ? AVERROR_EOF : 0;
357 ret = url_fopen(&var->pb,
358 var->segments[c->cur_seq_no - var->start_seq_no]->url,
362 var->ctx->pb = var->pb;
363 /* If this is a new segment in parallel with another one already opened,
364 * skip ahead so they're all at the same dts. */
365 if (skip && c->last_packet_dts != AV_NOPTS_VALUE) {
367 ret = av_read_frame(var->ctx, &var->pkt);
369 if (ret == AVERROR_EOF) {
370 reset_packet(&var->pkt);
375 if (var->pkt.dts >= c->last_packet_dts)
377 av_free_packet(&var->pkt);
383 static int applehttp_read_packet(AVFormatContext *s, AVPacket *pkt)
385 AppleHTTPContext *c = s->priv_data;
386 int ret, i, minvariant = -1, first = 1, needed = 0, changed = 0,
389 /* Recheck the discard flags - which streams are desired at the moment */
390 for (i = 0; i < c->n_variants; i++)
391 c->variants[i]->needed = 0;
392 for (i = 0; i < s->nb_streams; i++) {
393 AVStream *st = s->streams[i];
394 struct variant *var = c->variants[s->streams[i]->id];
395 if (st->discard < AVDISCARD_ALL) {
399 /* Copy the discard flag to the chained demuxer, to indicate which
400 * streams are desired. */
401 var->ctx->streams[i - var->stream_offset]->discard = st->discard;
406 for (i = 0; i < c->n_variants; i++) {
407 struct variant *var = c->variants[i];
408 /* Close unneeded streams, open newly requested streams */
409 if (var->pb && !var->needed) {
410 av_log(s, AV_LOG_DEBUG,
411 "Closing variant stream %d, no longer needed\n", i);
412 av_free_packet(&var->pkt);
413 reset_packet(&var->pkt);
417 } else if (!var->pb && var->needed) {
419 av_log(s, AV_LOG_DEBUG, "Opening variant stream %d\n", i);
420 if (first && !c->finished)
421 if ((ret = parse_playlist(c, var->url, var, NULL)) < 0)
423 ret = open_variant(c, var, first);
428 /* Count the number of open variants */
431 /* Make sure we've got one buffered packet from each open variant
433 if (var->pb && !var->pkt.data) {
434 ret = av_read_frame(var->ctx, &var->pkt);
436 if (!url_feof(var->pb))
438 reset_packet(&var->pkt);
441 /* Check if this stream has the packet with the lowest dts */
443 if (minvariant < 0 ||
444 var->pkt.dts < c->variants[minvariant]->pkt.dts)
448 if (first && changed)
449 av_log(s, AV_LOG_INFO, "Receiving %d variant streams\n", variants);
450 /* If we got a packet, return it */
451 if (minvariant >= 0) {
452 *pkt = c->variants[minvariant]->pkt;
453 pkt->stream_index += c->variants[minvariant]->stream_offset;
454 reset_packet(&c->variants[minvariant]->pkt);
455 c->last_packet_dts = pkt->dts;
458 /* No more packets - eof reached in all variant streams, close the
459 * current segments. */
460 for (i = 0; i < c->n_variants; i++) {
461 struct variant *var = c->variants[i];
467 /* Indicate that we're opening the next segment, not opening a new
468 * variant stream in parallel, so we shouldn't try to skip ahead. */
473 /* If this is a live stream and target_duration has elapsed since
474 * the last playlist reload, reload the variant playlists now. */
475 int64_t now = av_gettime();
476 if (now - c->last_load_time >= c->target_duration*1000000) {
477 c->max_start_seq = 0;
478 c->min_end_seq = INT_MAX;
479 for (i = 0; i < c->n_variants; i++) {
480 struct variant *var = c->variants[i];
482 if ((ret = parse_playlist(c, var->url, var, NULL)) < 0)
484 c->max_start_seq = FFMAX(c->max_start_seq,
486 c->min_end_seq = FFMIN(c->min_end_seq,
487 var->start_seq_no + var->n_segments);
492 if (c->cur_seq_no < c->max_start_seq) {
493 av_log(NULL, AV_LOG_WARNING,
494 "skipping %d segments ahead, expired from playlists\n",
495 c->max_start_seq - c->cur_seq_no);
496 c->cur_seq_no = c->max_start_seq;
498 /* If more segments exit, open the next one */
499 if (c->cur_seq_no < c->min_end_seq)
501 /* We've reached the end of the playlists - return eof if this is a
502 * non-live stream, wait until the next playlist reload if it is live. */
505 while (av_gettime() - c->last_load_time < c->target_duration*1000000) {
506 if (url_interrupt_cb())
507 return AVERROR(EINTR);
510 /* Enough time has elapsed since the last reload */
514 static int applehttp_close(AVFormatContext *s)
516 AppleHTTPContext *c = s->priv_data;
518 free_variant_list(c);
522 static int applehttp_read_seek(AVFormatContext *s, int stream_index,
523 int64_t timestamp, int flags)
525 AppleHTTPContext *c = s->priv_data;
527 struct variant *var = c->variants[0];
529 if ((flags & AVSEEK_FLAG_BYTE) || !c->finished)
530 return AVERROR(ENOSYS);
532 /* Reset the variants */
533 c->last_packet_dts = AV_NOPTS_VALUE;
534 for (i = 0; i < c->n_variants; i++) {
535 struct variant *var = c->variants[i];
540 av_free_packet(&var->pkt);
541 reset_packet(&var->pkt);
544 timestamp = av_rescale_rnd(timestamp, 1, stream_index >= 0 ?
545 s->streams[stream_index]->time_base.den :
546 AV_TIME_BASE, flags & AVSEEK_FLAG_BACKWARD ?
547 AV_ROUND_DOWN : AV_ROUND_UP);
548 /* Locate the segment that contains the target timestamp */
549 for (i = 0; i < var->n_segments; i++) {
550 if (timestamp >= pos && timestamp < pos + var->segments[i]->duration) {
551 c->cur_seq_no = var->start_seq_no + i;
554 pos += var->segments[i]->duration;
559 static int applehttp_probe(AVProbeData *p)
561 /* Require #EXTM3U at the start, and either one of the ones below
562 * somewhere for a proper match. */
563 if (strncmp(p->buf, "#EXTM3U", 7))
565 if (strstr(p->buf, "#EXT-X-STREAM-INF:") ||
566 strstr(p->buf, "#EXT-X-TARGETDURATION:") ||
567 strstr(p->buf, "#EXT-X-MEDIA-SEQUENCE:"))
568 return AVPROBE_SCORE_MAX;
572 AVInputFormat applehttp_demuxer = {
574 NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming format"),
575 sizeof(AppleHTTPContext),
577 applehttp_read_header,
578 applehttp_read_packet,