hlsproto.c 9.82 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
/*
 * Apple HTTP Live Streaming Protocol Handler
 * Copyright (c) 2010 Martin Storsjo
 *
 * This file is part of FFmpeg.
 *
 * FFmpeg is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * FFmpeg is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with FFmpeg; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

/**
 * @file
 * Apple HTTP Live Streaming Protocol Handler
 * http://tools.ietf.org/html/draft-pantos-http-live-streaming
 */

#include "libavutil/avstring.h"
29
#include "libavutil/time.h"
30 31
#include "avformat.h"
#include "internal.h"
32
#include "url.h"
33
#include "version.h"
34 35 36 37 38

/*
 * An apple http stream consists of a playlist with media segment files,
 * played sequentially. There may be several playlists with the same
 * video content, in different bandwidth variants, that are played in
39
 * parallel (preferably only one bandwidth variant at a time). In this case,
40 41 42 43 44 45 46 47
 * the user supplied the url to a main playlist that only lists the variant
 * playlists.
 *
 * If the main playlist doesn't point at any variants, we still create
 * one anonymous toplevel variant for this, to maintain the structure.
 */

struct segment {
48
    int64_t duration;
49 50 51 52 53 54 55 56
    char url[MAX_URL_SIZE];
};

struct variant {
    int bandwidth;
    char url[MAX_URL_SIZE];
};

57
typedef struct HLSContext {
58
    char playlisturl[MAX_URL_SIZE];
59
    int64_t target_duration;
60 61 62 63 64 65 66 67 68
    int start_seq_no;
    int finished;
    int n_segments;
    struct segment **segments;
    int n_variants;
    struct variant **variants;
    int cur_seq_no;
    URLContext *seg_hd;
    int64_t last_load_time;
69
} HLSContext;
70 71 72 73

static int read_chomp_line(AVIOContext *s, char *buf, int maxlen)
{
    int len = ff_get_line(s, buf, maxlen);
74
    while (len > 0 && av_isspace(buf[len - 1]))
75 76 77 78
        buf[--len] = '\0';
    return len;
}

79
static void free_segment_list(HLSContext *s)
80 81 82 83 84 85 86 87
{
    int i;
    for (i = 0; i < s->n_segments; i++)
        av_free(s->segments[i]);
    av_freep(&s->segments);
    s->n_segments = 0;
}

88
static void free_variant_list(HLSContext *s)
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
{
    int i;
    for (i = 0; i < s->n_variants; i++)
        av_free(s->variants[i]);
    av_freep(&s->variants);
    s->n_variants = 0;
}

struct variant_info {
    char bandwidth[20];
};

static void handle_variant_args(struct variant_info *info, const char *key,
                                int key_len, char **dest, int *dest_len)
{
    if (!strncmp(key, "BANDWIDTH=", key_len)) {
        *dest     =        info->bandwidth;
        *dest_len = sizeof(info->bandwidth);
    }
}

static int parse_playlist(URLContext *h, const char *url)
{
112
    HLSContext *s = h->priv_data;
113
    AVIOContext *in;
114 115
    int ret = 0, is_segment = 0, is_variant = 0, bandwidth = 0;
    int64_t duration = 0;
116 117 118
    char line[1024];
    const char *ptr;

119 120
    if ((ret = avio_open2(&in, url, AVIO_FLAG_READ,
                          &h->interrupt_callback, NULL)) < 0)
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
        return ret;

    read_chomp_line(in, line, sizeof(line));
    if (strcmp(line, "#EXTM3U"))
        return AVERROR_INVALIDDATA;

    free_segment_list(s);
    s->finished = 0;
    while (!url_feof(in)) {
        read_chomp_line(in, line, sizeof(line));
        if (av_strstart(line, "#EXT-X-STREAM-INF:", &ptr)) {
            struct variant_info info = {{0}};
            is_variant = 1;
            ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_variant_args,
                               &info);
            bandwidth = atoi(info.bandwidth);
        } else if (av_strstart(line, "#EXT-X-TARGETDURATION:", &ptr)) {
138
            s->target_duration = atoi(ptr) * AV_TIME_BASE;
139 140 141 142 143 144
        } else if (av_strstart(line, "#EXT-X-MEDIA-SEQUENCE:", &ptr)) {
            s->start_seq_no = atoi(ptr);
        } else if (av_strstart(line, "#EXT-X-ENDLIST", &ptr)) {
            s->finished = 1;
        } else if (av_strstart(line, "#EXTINF:", &ptr)) {
            is_segment = 1;
145
            duration = atof(ptr) * AV_TIME_BASE;
146 147 148 149 150 151 152 153 154 155
        } else if (av_strstart(line, "#", NULL)) {
            continue;
        } else if (line[0]) {
            if (is_segment) {
                struct segment *seg = av_malloc(sizeof(struct segment));
                if (!seg) {
                    ret = AVERROR(ENOMEM);
                    goto fail;
                }
                seg->duration = duration;
156
                ff_make_absolute_url(seg->url, sizeof(seg->url), url, line);
157 158 159 160 161 162 163 164 165
                dynarray_add(&s->segments, &s->n_segments, seg);
                is_segment = 0;
            } else if (is_variant) {
                struct variant *var = av_malloc(sizeof(struct variant));
                if (!var) {
                    ret = AVERROR(ENOMEM);
                    goto fail;
                }
                var->bandwidth = bandwidth;
166
                ff_make_absolute_url(var->url, sizeof(var->url), url, line);
167 168 169 170 171 172 173 174 175 176 177 178
                dynarray_add(&s->variants, &s->n_variants, var);
                is_variant = 0;
            }
        }
    }
    s->last_load_time = av_gettime();

fail:
    avio_close(in);
    return ret;
}

179
static int hls_close(URLContext *h)
180
{
181
    HLSContext *s = h->priv_data;
182 183 184 185 186 187 188

    free_segment_list(s);
    free_variant_list(s);
    ffurl_close(s->seg_hd);
    return 0;
}

189
static int hls_open(URLContext *h, const char *uri, int flags)
190
{
191
    HLSContext *s = h->priv_data;
192 193 194
    int ret, i;
    const char *nested_url;

195
    if (flags & AVIO_FLAG_WRITE)
196
        return AVERROR(ENOSYS);
197 198 199

    h->is_streamed = 1;

200
    if (av_strstart(uri, "hls+", &nested_url)) {
201
        av_strlcpy(s->playlisturl, nested_url, sizeof(s->playlisturl));
202 203 204 205 206 207
    } else if (av_strstart(uri, "hls://", &nested_url)) {
        av_log(h, AV_LOG_ERROR,
               "No nested protocol specified. Specify e.g. hls+http://%s\n",
               nested_url);
        ret = AVERROR(EINVAL);
        goto fail;
208
    } else {
209
        av_log(h, AV_LOG_ERROR, "Unsupported url %s\n", uri);
210 211 212
        ret = AVERROR(EINVAL);
        goto fail;
    }
213 214 215 216 217 218
    av_log(h, AV_LOG_WARNING,
           "Using the hls protocol is discouraged, please try using the "
           "hls demuxer instead. The hls demuxer should be more complete "
           "and work as well as the protocol implementation. (If not, "
           "please report it.) To use the demuxer, simply use %s as url.\n",
           s->playlisturl);
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237

    if ((ret = parse_playlist(h, s->playlisturl)) < 0)
        goto fail;

    if (s->n_segments == 0 && s->n_variants > 0) {
        int max_bandwidth = 0, maxvar = -1;
        for (i = 0; i < s->n_variants; i++) {
            if (s->variants[i]->bandwidth > max_bandwidth || i == 0) {
                max_bandwidth = s->variants[i]->bandwidth;
                maxvar = i;
            }
        }
        av_strlcpy(s->playlisturl, s->variants[maxvar]->url,
                   sizeof(s->playlisturl));
        if ((ret = parse_playlist(h, s->playlisturl)) < 0)
            goto fail;
    }

    if (s->n_segments == 0) {
238
        av_log(h, AV_LOG_WARNING, "Empty playlist\n");
239 240 241 242 243 244 245 246 247 248
        ret = AVERROR(EIO);
        goto fail;
    }
    s->cur_seq_no = s->start_seq_no;
    if (!s->finished && s->n_segments >= 3)
        s->cur_seq_no = s->start_seq_no + s->n_segments - 3;

    return 0;

fail:
249
    hls_close(h);
250 251 252
    return ret;
}

253
static int hls_read(URLContext *h, uint8_t *buf, int size)
254
{
255
    HLSContext *s = h->priv_data;
256 257
    const char *url;
    int ret;
258
    int64_t reload_interval;
259 260 261

start:
    if (s->seg_hd) {
262
        ret = ffurl_read(s->seg_hd, buf, size);
263 264 265 266
        if (ret > 0)
            return ret;
    }
    if (s->seg_hd) {
267
        ffurl_close(s->seg_hd);
268 269 270
        s->seg_hd = NULL;
        s->cur_seq_no++;
    }
271 272 273
    reload_interval = s->n_segments > 0 ?
                      s->segments[s->n_segments - 1]->duration :
                      s->target_duration;
274 275 276
retry:
    if (!s->finished) {
        int64_t now = av_gettime();
277
        if (now - s->last_load_time >= reload_interval) {
278 279
            if ((ret = parse_playlist(h, s->playlisturl)) < 0)
                return ret;
280 281 282
            /* If we need to reload the playlist again below (if
             * there's still no more segments), switch to a reload
             * interval of half the target duration. */
283
            reload_interval = s->target_duration / 2;
284
        }
285 286
    }
    if (s->cur_seq_no < s->start_seq_no) {
287
        av_log(h, AV_LOG_WARNING,
288 289 290 291 292 293 294
               "skipping %d segments ahead, expired from playlist\n",
               s->start_seq_no - s->cur_seq_no);
        s->cur_seq_no = s->start_seq_no;
    }
    if (s->cur_seq_no - s->start_seq_no >= s->n_segments) {
        if (s->finished)
            return AVERROR_EOF;
295
        while (av_gettime() - s->last_load_time < reload_interval) {
296
            if (ff_check_interrupt(&h->interrupt_callback))
297
                return AVERROR_EXIT;
298
            av_usleep(100*1000);
299 300 301 302
        }
        goto retry;
    }
    url = s->segments[s->cur_seq_no - s->start_seq_no]->url,
303
    av_log(h, AV_LOG_DEBUG, "opening %s\n", url);
304
    ret = ffurl_open(&s->seg_hd, url, AVIO_FLAG_READ,
305
                     &h->interrupt_callback, NULL);
306
    if (ret < 0) {
307
        if (ff_check_interrupt(&h->interrupt_callback))
308
            return AVERROR_EXIT;
309
        av_log(h, AV_LOG_WARNING, "Unable to open %s\n", url);
310 311 312 313 314 315
        s->cur_seq_no++;
        goto retry;
    }
    goto start;
}

316 317
URLProtocol ff_hls_protocol = {
    .name           = "hls",
318 319 320
    .url_open       = hls_open,
    .url_read       = hls_read,
    .url_close      = hls_close,
321
    .flags          = URL_PROTOCOL_FLAG_NESTED_SCHEME,
322
    .priv_data_size = sizeof(HLSContext),
323
};