Statistics
| Branch: | Revision:

ffmpeg / libavformat / applehttp.c @ b79c3df0

History | View | Annotate | Download (18.7 KB)

1
/*
2
 * Apple HTTP Live Streaming demuxer
3
 * Copyright (c) 2010 Martin Storsjo
4
 *
5
 * This file is part of FFmpeg.
6
 *
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.
11
 *
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.
16
 *
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
20
 */
21

    
22
/**
23
 * @file
24
 * Apple HTTP Live Streaming demuxer
25
 * http://tools.ietf.org/html/draft-pantos-http-live-streaming
26
 */
27

    
28
#define _XOPEN_SOURCE 600
29
#include "libavutil/avstring.h"
30
#include "avformat.h"
31
#include "internal.h"
32
#include <unistd.h>
33

    
34
/*
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
40
 * playlists.
41
 *
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.
44
 */
45

    
46
struct segment {
47
    int duration;
48
    char url[MAX_URL_SIZE];
49
};
50

    
51
/*
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.
55
 */
56
struct variant {
57
    int bandwidth;
58
    char url[MAX_URL_SIZE];
59
    ByteIOContext *pb;
60
    AVFormatContext *ctx;
61
    AVPacket pkt;
62
    int stream_offset;
63

    
64
    int start_seq_no;
65
    int n_segments;
66
    struct segment **segments;
67
    int needed;
68
};
69

    
70
typedef struct AppleHTTPContext {
71
    int target_duration;
72
    int finished;
73
    int n_variants;
74
    struct variant **variants;
75
    int cur_seq_no;
76
    int64_t last_load_time;
77
    int64_t last_packet_dts;
78
    int max_start_seq, min_end_seq;
79
} AppleHTTPContext;
80

    
81
static int read_chomp_line(ByteIOContext *s, char *buf, int maxlen)
82
{
83
    int len = ff_get_line(s, buf, maxlen);
84
    while (len > 0 && isspace(buf[len - 1]))
85
        buf[--len] = '\0';
86
    return len;
87
}
88

    
89
static void make_absolute_url(char *buf, int size, const char *base,
90
                              const char *rel)
91
{
92
    char *sep;
93
    /* If rel actually is an absolute url, just copy it */
94
    if (!base || strstr(rel, "://") || rel[0] == '/') {
95
        av_strlcpy(buf, rel, size);
96
        return;
97
    }
98
    if (base != buf)
99
        av_strlcpy(buf, base, size);
100
    /* Remove the file name from the base url */
101
    sep = strrchr(buf, '/');
102
    if (sep)
103
        sep[1] = '\0';
104
    else
105
        buf[0] = '\0';
106
    while (av_strstart(rel, "../", NULL) && sep) {
107
        /* Remove the path delimiter at the end */
108
        sep[0] = '\0';
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);
114
            break;
115
        }
116
        /* Cut off the directory name */
117
        if (sep)
118
            sep[1] = '\0';
119
        else
120
            buf[0] = '\0';
121
        rel += 3;
122
    }
123
    av_strlcat(buf, rel, size);
124
}
125

    
126
static void free_segment_list(struct variant *var)
127
{
128
    int i;
129
    for (i = 0; i < var->n_segments; i++)
130
        av_free(var->segments[i]);
131
    av_freep(&var->segments);
132
    var->n_segments = 0;
133
}
134

    
135
static void free_variant_list(AppleHTTPContext *c)
136
{
137
    int i;
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);
142
        if (var->pb)
143
            url_fclose(var->pb);
144
        if (var->ctx) {
145
            var->ctx->pb = NULL;
146
            av_close_input_file(var->ctx);
147
        }
148
        av_free(var);
149
    }
150
    av_freep(&c->variants);
151
    c->n_variants = 0;
152
}
153

    
154
/*
155
 * Used to reset a statically allocated AVPacket to a clean slate,
156
 * containing no data.
157
 */
158
static void reset_packet(AVPacket *pkt)
159
{
160
    av_init_packet(pkt);
161
    pkt->data = NULL;
162
}
163

    
164
static struct variant *new_variant(AppleHTTPContext *c, int bandwidth,
165
                                   const char *url, const char *base)
166
{
167
    struct variant *var = av_mallocz(sizeof(struct variant));
168
    if (!var)
169
        return NULL;
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);
174
    return var;
175
}
176

    
177
struct variant_info {
178
    char bandwidth[20];
179
};
180

    
181
static void handle_variant_args(struct variant_info *info, const char *key,
182
                                int key_len, char **dest, int *dest_len)
183
{
184
    if (strncmp(key, "BANDWIDTH", key_len)) {
185
        *dest     =        info->bandwidth;
186
        *dest_len = sizeof(info->bandwidth);
187
    }
188
}
189

    
190
static int parse_playlist(AppleHTTPContext *c, const char *url,
191
                          struct variant *var, ByteIOContext *in)
192
{
193
    int ret = 0, duration = 0, is_segment = 0, is_variant = 0, bandwidth = 0;
194
    char line[1024];
195
    const char *ptr;
196
    int close_in = 0;
197

    
198
    if (!in) {
199
        close_in = 1;
200
        if ((ret = url_fopen(&in, url, URL_RDONLY)) < 0)
201
            return ret;
202
    }
203

    
204
    read_chomp_line(in, line, sizeof(line));
205
    if (strcmp(line, "#EXTM3U")) {
206
        ret = AVERROR_INVALIDDATA;
207
        goto fail;
208
    }
209

    
210
    if (var)
211
        free_segment_list(var);
212
    c->finished = 0;
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}};
217
            is_variant = 1;
218
            ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_variant_args,
219
                               &info);
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)) {
224
            if (!var) {
225
                var = new_variant(c, 0, url, NULL);
226
                if (!var) {
227
                    ret = AVERROR(ENOMEM);
228
                    goto fail;
229
                }
230
            }
231
            var->start_seq_no = atoi(ptr);
232
        } else if (av_strstart(line, "#EXT-X-ENDLIST", &ptr)) {
233
            c->finished = 1;
234
        } else if (av_strstart(line, "#EXTINF:", &ptr)) {
235
            is_segment = 1;
236
            duration   = atoi(ptr);
237
        } else if (av_strstart(line, "#", NULL)) {
238
            continue;
239
        } else if (line[0]) {
240
            if (is_variant) {
241
                if (!new_variant(c, bandwidth, line, url)) {
242
                    ret = AVERROR(ENOMEM);
243
                    goto fail;
244
                }
245
                is_variant = 0;
246
                bandwidth  = 0;
247
            }
248
            if (is_segment) {
249
                struct segment *seg;
250
                if (!var) {
251
                    var = new_variant(c, 0, url, NULL);
252
                    if (!var) {
253
                        ret = AVERROR(ENOMEM);
254
                        goto fail;
255
                    }
256
                }
257
                seg = av_malloc(sizeof(struct segment));
258
                if (!seg) {
259
                    ret = AVERROR(ENOMEM);
260
                    goto fail;
261
                }
262
                seg->duration = duration;
263
                make_absolute_url(seg->url, sizeof(seg->url), url, line);
264
                dynarray_add(&var->segments, &var->n_segments, seg);
265
                is_segment = 0;
266
            }
267
        }
268
    }
269
    c->last_load_time = av_gettime();
270

    
271
fail:
272
    if (close_in)
273
        url_fclose(in);
274
    return ret;
275
}
276

    
277
static int applehttp_read_header(AVFormatContext *s, AVFormatParameters *ap)
278
{
279
    AppleHTTPContext *c = s->priv_data;
280
    int ret = 0, i, j, stream_offset = 0;
281

    
282
    if ((ret = parse_playlist(c, s->filename, NULL, s->pb)) < 0)
283
        goto fail;
284

    
285
    if (c->n_variants == 0) {
286
        av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
287
        ret = AVERROR_EOF;
288
        goto fail;
289
    }
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)
296
                goto fail;
297
        }
298
    }
299

    
300
    if (c->variants[0]->n_segments == 0) {
301
        av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
302
        ret = AVERROR_EOF;
303
        goto fail;
304
    }
305

    
306
    /* If this isn't a live stream, calculate the total duration of the
307
     * stream. */
308
    if (c->finished) {
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;
313
    }
314

    
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)
320
            continue;
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 +
323
                                                   v->n_segments);
324
        ret = av_open_input_file(&v->ctx, v->segments[0]->url, NULL, 0, NULL);
325
        if (ret < 0)
326
            goto fail;
327
        url_fclose(v->ctx->pb);
328
        v->ctx->pb = NULL;
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);
333
            if (!st) {
334
                ret = AVERROR(ENOMEM);
335
                goto fail;
336
            }
337
            avcodec_copy_context(st->codec, v->ctx->streams[j]->codec);
338
        }
339
        stream_offset += v->ctx->nb_streams;
340
    }
341
    c->last_packet_dts = AV_NOPTS_VALUE;
342

    
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;
348

    
349
    return 0;
350
fail:
351
    free_variant_list(c);
352
    return ret;
353
}
354

    
355
static int open_variant(AppleHTTPContext *c, struct variant *var, int skip)
356
{
357
    int ret;
358

    
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);
363
        return 0;
364
    }
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,
369
                    URL_RDONLY);
370
    if (ret < 0)
371
        return ret;
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) {
376
        while (1) {
377
            ret = av_read_frame(var->ctx, &var->pkt);
378
            if (ret < 0) {
379
                if (ret == AVERROR_EOF) {
380
                    reset_packet(&var->pkt);
381
                    return 0;
382
                }
383
                return ret;
384
            }
385
            if (var->pkt.dts >= c->last_packet_dts)
386
                break;
387
            av_free_packet(&var->pkt);
388
        }
389
    }
390
    return 0;
391
}
392

    
393
static int applehttp_read_packet(AVFormatContext *s, AVPacket *pkt)
394
{
395
    AppleHTTPContext *c = s->priv_data;
396
    int ret, i, minvariant = -1, first = 1, needed = 0, changed = 0,
397
        variants = 0;
398

    
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) {
406
            var->needed = 1;
407
            needed++;
408
        }
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;
412
    }
413
    if (!needed)
414
        return AVERROR_EOF;
415
start:
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);
424
            url_fclose(var->pb);
425
            var->pb = NULL;
426
            changed = 1;
427
        } else if (!var->pb && var->needed) {
428
            if (first)
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)
432
                    return ret;
433
            ret = open_variant(c, var, first);
434
            if (ret < 0)
435
                return ret;
436
            changed = 1;
437
        }
438
        /* Count the number of open variants */
439
        if (var->pb)
440
            variants++;
441
        /* Make sure we've got one buffered packet from each open variant
442
         * stream */
443
        if (var->pb && !var->pkt.data) {
444
            ret = av_read_frame(var->ctx, &var->pkt);
445
            if (ret < 0) {
446
                if (!url_feof(var->pb))
447
                    return ret;
448
                reset_packet(&var->pkt);
449
            }
450
        }
451
        /* Check if this stream has the packet with the lowest dts */
452
        if (var->pkt.data) {
453
            if (minvariant < 0 ||
454
                var->pkt.dts < c->variants[minvariant]->pkt.dts)
455
                minvariant = i;
456
        }
457
    }
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;
466
        return 0;
467
    }
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];
472
        if (var->pb) {
473
            url_fclose(var->pb);
474
            var->pb = NULL;
475
        }
476
    }
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. */
479
    first = 0;
480
    c->cur_seq_no++;
481
reload:
482
    if (!c->finished) {
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];
491
                if (var->needed) {
492
                    if ((ret = parse_playlist(c, var->url, var, NULL)) < 0)
493
                        return ret;
494
                    c->max_start_seq = FFMAX(c->max_start_seq,
495
                                             var->start_seq_no);
496
                    c->min_end_seq   = FFMIN(c->min_end_seq,
497
                                             var->start_seq_no + var->n_segments);
498
                }
499
            }
500
        }
501
    }
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;
507
    }
508
    /* If more segments exit, open the next one */
509
    if (c->cur_seq_no < c->min_end_seq)
510
        goto start;
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. */
513
    if (c->finished)
514
        return AVERROR_EOF;
515
    while (av_gettime() - c->last_load_time < c->target_duration*1000000) {
516
        if (url_interrupt_cb())
517
            return AVERROR(EINTR);
518
        usleep(100*1000);
519
    }
520
    /* Enough time has elapsed since the last reload */
521
    goto reload;
522
}
523

    
524
static int applehttp_close(AVFormatContext *s)
525
{
526
    AppleHTTPContext *c = s->priv_data;
527

    
528
    free_variant_list(c);
529
    return 0;
530
}
531

    
532
static int applehttp_read_seek(AVFormatContext *s, int stream_index,
533
                               int64_t timestamp, int flags)
534
{
535
    AppleHTTPContext *c = s->priv_data;
536
    int pos = 0, i;
537
    struct variant *var = c->variants[0];
538

    
539
    if ((flags & AVSEEK_FLAG_BYTE) || !c->finished)
540
        return AVERROR(ENOSYS);
541

    
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];
546
        if (var->pb) {
547
            url_fclose(var->pb);
548
            var->pb = NULL;
549
        }
550
        av_free_packet(&var->pkt);
551
        reset_packet(&var->pkt);
552
    }
553

    
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;
562
            return 0;
563
        }
564
        pos += var->segments[i]->duration;
565
    }
566
    return AVERROR(EIO);
567
}
568

    
569
static int applehttp_probe(AVProbeData *p)
570
{
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))
574
        return 0;
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;
579
    return 0;
580
}
581

    
582
AVInputFormat applehttp_demuxer = {
583
    "applehttp",
584
    NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming format"),
585
    sizeof(AppleHTTPContext),
586
    applehttp_probe,
587
    applehttp_read_header,
588
    applehttp_read_packet,
589
    applehttp_close,
590
    applehttp_read_seek,
591
};