cache.c 8.65 KB
Newer Older
Michael Niedermayer's avatar
Michael Niedermayer committed
1 2
/*
 * Input cache protocol.
3
 * Copyright (c) 2011,2014 Michael Niedermayer
Michael Niedermayer's avatar
Michael Niedermayer committed
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
 *
 * 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
 *
 * Based on file.c by Fabrice Bellard
 */

24 25 26 27 28 29
/**
 * @TODO
 *      support keeping files
 *      support filling with a background thread
 */

Michael Niedermayer's avatar
Michael Niedermayer committed
30 31 32
#include "libavutil/avassert.h"
#include "libavutil/avstring.h"
#include "libavutil/file.h"
33
#include "libavutil/opt.h"
34
#include "libavutil/tree.h"
Michael Niedermayer's avatar
Michael Niedermayer committed
35 36
#include "avformat.h"
#include <fcntl.h>
37
#if HAVE_IO_H
Michael Niedermayer's avatar
Michael Niedermayer committed
38 39
#include <io.h>
#endif
40
#if HAVE_UNISTD_H
Michael Niedermayer's avatar
Michael Niedermayer committed
41
#include <unistd.h>
42
#endif
Michael Niedermayer's avatar
Michael Niedermayer committed
43 44 45 46 47
#include <sys/stat.h>
#include <stdlib.h>
#include "os_support.h"
#include "url.h"

48 49 50 51 52 53
typedef struct CacheEntry {
    int64_t logical_pos;
    int64_t physical_pos;
    int size;
} CacheEntry;

Michael Niedermayer's avatar
Michael Niedermayer committed
54
typedef struct Context {
55
    AVClass *class;
Michael Niedermayer's avatar
Michael Niedermayer committed
56
    int fd;
57 58 59 60
    struct AVTreeNode *root;
    int64_t logical_pos;
    int64_t cache_pos;
    int64_t inner_pos;
Michael Niedermayer's avatar
Michael Niedermayer committed
61
    int64_t end;
62
    int is_true_eof;
Michael Niedermayer's avatar
Michael Niedermayer committed
63
    URLContext *inner;
64
    int64_t cache_hit, cache_miss;
65
    int read_ahead_limit;
Michael Niedermayer's avatar
Michael Niedermayer committed
66 67
} Context;

68
static int cmp(const void *key, const void *node)
69
{
70
    return FFDIFFSIGN(*(const int64_t *)key, ((const CacheEntry *) node)->logical_pos);
71 72
}

73
static int cache_open(URLContext *h, const char *arg, int flags, AVDictionary **options)
Michael Niedermayer's avatar
Michael Niedermayer committed
74
{
75
    char *buffername;
76
    Context *c= h->priv_data;
Michael Niedermayer's avatar
Michael Niedermayer committed
77 78 79

    av_strstart(arg, "cache:", &arg);

80
    c->fd = av_tempfile("ffcache", &buffername, 0, h);
Michael Niedermayer's avatar
Michael Niedermayer committed
81 82 83 84 85 86
    if (c->fd < 0){
        av_log(h, AV_LOG_ERROR, "Failed to create tempfile\n");
        return c->fd;
    }

    unlink(buffername);
87
    av_freep(&buffername);
Michael Niedermayer's avatar
Michael Niedermayer committed
88

89
    return ffurl_open(&c->inner, arg, flags, &h->interrupt_callback, options);
Michael Niedermayer's avatar
Michael Niedermayer committed
90 91
}

92 93 94
static int add_entry(URLContext *h, const unsigned char *buf, int size)
{
    Context *c= h->priv_data;
95
    int64_t pos = -1;
96
    int ret;
97
    CacheEntry *entry = NULL, *next[2] = {NULL, NULL};
98
    CacheEntry *entry_ret;
99
    struct AVTreeNode *node = NULL;
100 101 102 103 104 105 106 107

    //FIXME avoid lseek
    pos = lseek(c->fd, 0, SEEK_END);
    if (pos < 0) {
        ret = AVERROR(errno);
        av_log(h, AV_LOG_ERROR, "seek in cache failed\n");
        goto fail;
    }
108
    c->cache_pos = pos;
109 110 111 112 113 114 115

    ret = write(c->fd, buf, size);
    if (ret < 0) {
        ret = AVERROR(errno);
        av_log(h, AV_LOG_ERROR, "write in cache failed\n");
        goto fail;
    }
116
    c->cache_pos += ret;
117

118
    entry = av_tree_find(c->root, &c->logical_pos, cmp, (void**)next);
119

120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
    if (!entry)
        entry = next[0];

    if (!entry ||
        entry->logical_pos  + entry->size != c->logical_pos ||
        entry->physical_pos + entry->size != pos
    ) {
        entry = av_malloc(sizeof(*entry));
        node = av_tree_node_alloc();
        if (!entry || !node) {
            ret = AVERROR(ENOMEM);
            goto fail;
        }
        entry->logical_pos = c->logical_pos;
        entry->physical_pos = pos;
        entry->size = ret;

        entry_ret = av_tree_insert(&c->root, entry, cmp, &node);
        if (entry_ret && entry_ret != entry) {
            ret = -1;
            av_log(h, AV_LOG_ERROR, "av_tree_insert failed\n");
            goto fail;
        }
    } else
        entry->size += ret;
145 146 147

    return 0;
fail:
Andreas Cadhalpun's avatar
Andreas Cadhalpun committed
148
    //we could truncate the file to pos here if pos >=0 but ftruncate isn't available in VS so
149
    //for simplicty we just leave the file a bit larger
150 151 152 153 154
    av_free(entry);
    av_free(node);
    return ret;
}

Michael Niedermayer's avatar
Michael Niedermayer committed
155 156 157
static int cache_read(URLContext *h, unsigned char *buf, int size)
{
    Context *c= h->priv_data;
158
    CacheEntry *entry, *next[2] = {NULL, NULL};
159
    int64_t r;
Michael Niedermayer's avatar
Michael Niedermayer committed
160

161 162 163 164 165 166 167 168 169 170
    entry = av_tree_find(c->root, &c->logical_pos, cmp, (void**)next);

    if (!entry)
        entry = next[0];

    if (entry) {
        int64_t in_block_pos = c->logical_pos - entry->logical_pos;
        av_assert0(entry->logical_pos <= c->logical_pos);
        if (in_block_pos < entry->size) {
            int64_t physical_target = entry->physical_pos + in_block_pos;
171 172 173 174 175 176

            if (c->cache_pos != physical_target) {
                r = lseek(c->fd, physical_target, SEEK_SET);
            } else
                r = c->cache_pos;

177 178
            if (r >= 0) {
                c->cache_pos = r;
179
                r = read(c->fd, buf, FFMIN(size, entry->size - in_block_pos));
180
            }
181 182

            if (r > 0) {
183
                c->cache_pos += r;
184 185 186 187
                c->logical_pos += r;
                c->cache_hit ++;
                return r;
            }
Michael Niedermayer's avatar
Michael Niedermayer committed
188 189
        }
    }
190 191 192 193 194 195 196 197 198 199 200 201 202

    // Cache miss or some kind of fault with the cache

    if (c->logical_pos != c->inner_pos) {
        r = ffurl_seek(c->inner, c->logical_pos, SEEK_SET);
        if (r<0) {
            av_log(h, AV_LOG_ERROR, "Failed to perform internal seek\n");
            return r;
        }
        c->inner_pos = r;
    }

    r = ffurl_read(c->inner, buf, size);
203 204 205 206
    if (r == 0 && size>0) {
        c->is_true_eof = 1;
        av_assert0(c->end >= c->logical_pos);
    }
207 208 209 210 211 212 213 214 215 216 217
    if (r<=0)
        return r;
    c->inner_pos += r;

    c->cache_miss ++;

    add_entry(h, buf, r);
    c->logical_pos += r;
    c->end = FFMAX(c->end, c->logical_pos);

    return r;
Michael Niedermayer's avatar
Michael Niedermayer committed
218 219 220 221 222
}

static int64_t cache_seek(URLContext *h, int64_t pos, int whence)
{
    Context *c= h->priv_data;
223
    int64_t ret;
Michael Niedermayer's avatar
Michael Niedermayer committed
224 225

    if (whence == AVSEEK_SIZE) {
226 227 228
        pos= ffurl_seek(c->inner, pos, whence);
        if(pos <= 0){
            pos= ffurl_seek(c->inner, -1, SEEK_END);
229
            if (ffurl_seek(c->inner, c->inner_pos, SEEK_SET) < 0)
230
                av_log(h, AV_LOG_ERROR, "Inner protocol failed to seekback end : %"PRId64"\n", pos);
231
        }
232 233
        if (pos > 0)
            c->is_true_eof = 1;
234
        c->end = FFMAX(c->end, pos);
235
        return pos;
Michael Niedermayer's avatar
Michael Niedermayer committed
236 237
    }

238 239 240
    if (whence == SEEK_CUR) {
        whence = SEEK_SET;
        pos += c->logical_pos;
241
    } else if (whence == SEEK_END && c->is_true_eof) {
242
resolve_eof:
243 244
        whence = SEEK_SET;
        pos += c->end;
245 246 247 248 249
    }

    if (whence == SEEK_SET && pos >= 0 && pos < c->end) {
        //Seems within filesize, assume it will not fail.
        c->logical_pos = pos;
Michael Niedermayer's avatar
Michael Niedermayer committed
250 251
        return pos;
    }
252 253

    //cache miss
254
    ret= ffurl_seek(c->inner, pos, whence);
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
    if ((whence == SEEK_SET && pos >= c->logical_pos ||
         whence == SEEK_END && pos <= 0) && ret < 0) {
        if (   (whence == SEEK_SET && c->read_ahead_limit >= pos - c->logical_pos)
            || c->read_ahead_limit < 0) {
            uint8_t tmp[32768];
            while (c->logical_pos < pos || whence == SEEK_END) {
                int size = sizeof(tmp);
                if (whence == SEEK_SET)
                    size = FFMIN(sizeof(tmp), pos - c->logical_pos);
                ret = cache_read(h, tmp, size);
                if (ret == 0 && whence == SEEK_END) {
                    av_assert0(c->is_true_eof);
                    goto resolve_eof;
                }
                if (ret < 0) {
                    return ret;
                }
            }
            return c->logical_pos;
        }
    }
276 277 278 279

    if (ret >= 0) {
        c->logical_pos = ret;
        c->end = FFMAX(c->end, ret);
280 281
    }

282
    return ret;
Michael Niedermayer's avatar
Michael Niedermayer committed
283 284 285 286 287
}

static int cache_close(URLContext *h)
{
    Context *c= h->priv_data;
288 289 290 291

    av_log(h, AV_LOG_INFO, "Statistics, cache hits:%"PRId64" cache misses:%"PRId64"\n",
           c->cache_hit, c->cache_miss);

Michael Niedermayer's avatar
Michael Niedermayer committed
292 293
    close(c->fd);
    ffurl_close(c->inner);
294 295
    av_tree_destroy(c->root);

Michael Niedermayer's avatar
Michael Niedermayer committed
296 297 298
    return 0;
}

299 300 301 302
#define OFFSET(x) offsetof(Context, x)
#define D AV_OPT_FLAG_DECODING_PARAM

static const AVOption options[] = {
Andreas Cadhalpun's avatar
Andreas Cadhalpun committed
303
    { "read_ahead_limit", "Amount in bytes that may be read ahead when seeking isn't supported, -1 for unlimited", OFFSET(read_ahead_limit), AV_OPT_TYPE_INT, { .i64 = 65536 }, -1, INT_MAX, D },
304 305 306 307 308 309 310 311 312 313
    {NULL},
};

static const AVClass cache_context_class = {
    .class_name = "Cache",
    .item_name  = av_default_item_name,
    .option     = options,
    .version    = LIBAVUTIL_VERSION_INT,
};

Michael Niedermayer's avatar
Michael Niedermayer committed
314 315
URLProtocol ff_cache_protocol = {
    .name                = "cache",
316
    .url_open2           = cache_open,
Michael Niedermayer's avatar
Michael Niedermayer committed
317 318 319
    .url_read            = cache_read,
    .url_seek            = cache_seek,
    .url_close           = cache_close,
320
    .priv_data_size      = sizeof(Context),
321
    .priv_data_class     = &cache_context_class,
Michael Niedermayer's avatar
Michael Niedermayer committed
322
};