]> git.sesse.net Git - ffmpeg/blob - libavformat/cache.c
avformat/cache: cleanup cache file on cache write failure
[ffmpeg] / libavformat / cache.c
1 /*
2  * Input cache protocol.
3  * Copyright (c) 2011,2014 Michael Niedermayer
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  * Based on file.c by Fabrice Bellard
22  */
23
24 /**
25  * @TODO
26  *      support keeping files
27  *      support filling with a background thread
28  */
29
30 #include "libavutil/avassert.h"
31 #include "libavutil/avstring.h"
32 #include "libavutil/file.h"
33 #include "libavutil/opt.h"
34 #include "libavutil/tree.h"
35 #include "avformat.h"
36 #include <fcntl.h>
37 #if HAVE_IO_H
38 #include <io.h>
39 #endif
40 #if HAVE_UNISTD_H
41 #include <unistd.h>
42 #endif
43 #include <sys/stat.h>
44 #include <stdlib.h>
45 #include "os_support.h"
46 #include "url.h"
47
48 typedef struct CacheEntry {
49     int64_t logical_pos;
50     int64_t physical_pos;
51     int size;
52 } CacheEntry;
53
54 typedef struct Context {
55     AVClass *class;
56     int fd;
57     struct AVTreeNode *root;
58     int64_t logical_pos;
59     int64_t cache_pos;
60     int64_t inner_pos;
61     int64_t end;
62     int is_true_eof;
63     URLContext *inner;
64     int64_t cache_hit, cache_miss;
65     int read_ahead_limit;
66 } Context;
67
68 static int cmp(void *key, const void *node)
69 {
70     return (*(int64_t *) key) - ((const CacheEntry *) node)->logical_pos;
71 }
72
73 static int cache_open(URLContext *h, const char *arg, int flags)
74 {
75     char *buffername;
76     Context *c= h->priv_data;
77
78     av_strstart(arg, "cache:", &arg);
79
80     c->fd = av_tempfile("ffcache", &buffername, 0, h);
81     if (c->fd < 0){
82         av_log(h, AV_LOG_ERROR, "Failed to create tempfile\n");
83         return c->fd;
84     }
85
86     unlink(buffername);
87     av_freep(&buffername);
88
89     return ffurl_open(&c->inner, arg, flags, &h->interrupt_callback, NULL);
90 }
91
92 static int add_entry(URLContext *h, const unsigned char *buf, int size)
93 {
94     Context *c= h->priv_data;
95     int64_t pos = -1;
96     int ret;
97     CacheEntry *entry = av_malloc(sizeof(*entry));
98     CacheEntry *entry_ret;
99     struct AVTreeNode *node = av_tree_node_alloc();
100
101     if (!entry || !node) {
102         ret = AVERROR(ENOMEM);
103         goto fail;
104     }
105
106     //FIXME avoid lseek
107     pos = lseek(c->fd, 0, SEEK_END);
108     if (pos < 0) {
109         ret = AVERROR(errno);
110         av_log(h, AV_LOG_ERROR, "seek in cache failed\n");
111         goto fail;
112     }
113
114     ret = write(c->fd, buf, size);
115     if (ret < 0) {
116         ret = AVERROR(errno);
117         av_log(h, AV_LOG_ERROR, "write in cache failed\n");
118         goto fail;
119     }
120
121     entry->logical_pos = c->logical_pos;
122     entry->physical_pos = pos;
123     entry->size = ret;
124
125     entry_ret = av_tree_insert(&c->root, entry, cmp, &node);
126     if (entry_ret && entry_ret != entry) {
127         ret = -1;
128         av_log(h, AV_LOG_ERROR, "av_tree_insert failed\n");
129         goto fail;
130     }
131     c->cache_pos = entry->physical_pos + entry->size;
132
133     return 0;
134 fail:
135     if (pos >= 0)
136         ftruncate(c->fd, pos);
137     av_free(entry);
138     av_free(node);
139     return ret;
140 }
141
142 static int cache_read(URLContext *h, unsigned char *buf, int size)
143 {
144     Context *c= h->priv_data;
145     CacheEntry *entry, *next[2] = {NULL, NULL};
146     int r;
147
148     entry = av_tree_find(c->root, &c->logical_pos, cmp, (void**)next);
149
150     if (!entry)
151         entry = next[0];
152
153     if (entry) {
154         int64_t in_block_pos = c->logical_pos - entry->logical_pos;
155         av_assert0(entry->logical_pos <= c->logical_pos);
156         if (in_block_pos < entry->size) {
157             int64_t physical_target = entry->physical_pos + in_block_pos;
158             //FIXME avoid seek if unneeded
159             r = lseek(c->fd, physical_target, SEEK_SET);
160             if (r >= 0)
161                 r = read(c->fd, buf, FFMIN(size, entry->size - in_block_pos));
162
163             if (r > 0) {
164                 c->logical_pos += r;
165                 c->cache_hit ++;
166                 return r;
167             }
168         }
169     }
170
171     // Cache miss or some kind of fault with the cache
172
173     if (c->logical_pos != c->inner_pos) {
174         r = ffurl_seek(c->inner, c->logical_pos, SEEK_SET);
175         if (r<0) {
176             av_log(h, AV_LOG_ERROR, "Failed to perform internal seek\n");
177             return r;
178         }
179         c->inner_pos = r;
180     }
181
182     r = ffurl_read(c->inner, buf, size);
183     if (r == 0 && size>0) {
184         c->is_true_eof = 1;
185         av_assert0(c->end >= c->logical_pos);
186     }
187     if (r<=0)
188         return r;
189     c->inner_pos += r;
190
191     c->cache_miss ++;
192
193     add_entry(h, buf, r);
194     c->logical_pos += r;
195     c->end = FFMAX(c->end, c->logical_pos);
196
197     return r;
198 }
199
200 static int64_t cache_seek(URLContext *h, int64_t pos, int whence)
201 {
202     Context *c= h->priv_data;
203     int64_t ret;
204
205     if (whence == AVSEEK_SIZE) {
206         pos= ffurl_seek(c->inner, pos, whence);
207         if(pos <= 0){
208             pos= ffurl_seek(c->inner, -1, SEEK_END);
209             if (ffurl_seek(c->inner, c->inner_pos, SEEK_SET) < 0)
210                 av_log(h, AV_LOG_ERROR, "Inner protocol failed to seekback end : %"PRId64"\n", pos);
211         }
212         if (pos > 0)
213             c->is_true_eof = 1;
214         c->end = FFMAX(c->end, pos);
215         return pos;
216     }
217
218     if (whence == SEEK_CUR) {
219         whence = SEEK_SET;
220         pos += c->logical_pos;
221     } else if (whence == SEEK_END && c->is_true_eof) {
222 resolve_eof:
223         whence = SEEK_SET;
224         pos += c->end;
225     }
226
227     if (whence == SEEK_SET && pos >= 0 && pos < c->end) {
228         //Seems within filesize, assume it will not fail.
229         c->logical_pos = pos;
230         return pos;
231     }
232
233     //cache miss
234     ret= ffurl_seek(c->inner, pos, whence);
235     if ((whence == SEEK_SET && pos >= c->logical_pos ||
236          whence == SEEK_END && pos <= 0) && ret < 0) {
237         if (   (whence == SEEK_SET && c->read_ahead_limit >= pos - c->logical_pos)
238             || c->read_ahead_limit < 0) {
239             uint8_t tmp[32768];
240             while (c->logical_pos < pos || whence == SEEK_END) {
241                 int size = sizeof(tmp);
242                 if (whence == SEEK_SET)
243                     size = FFMIN(sizeof(tmp), pos - c->logical_pos);
244                 ret = cache_read(h, tmp, size);
245                 if (ret == 0 && whence == SEEK_END) {
246                     av_assert0(c->is_true_eof);
247                     goto resolve_eof;
248                 }
249                 if (ret < 0) {
250                     return ret;
251                 }
252             }
253             return c->logical_pos;
254         }
255     }
256
257     if (ret >= 0) {
258         c->logical_pos = ret;
259         c->end = FFMAX(c->end, ret);
260     }
261
262     return ret;
263 }
264
265 static int cache_close(URLContext *h)
266 {
267     Context *c= h->priv_data;
268
269     av_log(h, AV_LOG_INFO, "Statistics, cache hits:%"PRId64" cache misses:%"PRId64"\n",
270            c->cache_hit, c->cache_miss);
271
272     close(c->fd);
273     ffurl_close(c->inner);
274     av_tree_destroy(c->root);
275
276     return 0;
277 }
278
279 #define OFFSET(x) offsetof(Context, x)
280 #define D AV_OPT_FLAG_DECODING_PARAM
281
282 static const AVOption options[] = {
283     { "read_ahead_limit", "Amount in bytes that may be read ahead when seeking isnt supported, -1 for unlimited", OFFSET(read_ahead_limit), AV_OPT_TYPE_INT, { .i64 = 65536 }, -1, INT_MAX, D },
284     {NULL},
285 };
286
287 static const AVClass cache_context_class = {
288     .class_name = "Cache",
289     .item_name  = av_default_item_name,
290     .option     = options,
291     .version    = LIBAVUTIL_VERSION_INT,
292 };
293
294 URLProtocol ff_cache_protocol = {
295     .name                = "cache",
296     .url_open            = cache_open,
297     .url_read            = cache_read,
298     .url_seek            = cache_seek,
299     .url_close           = cache_close,
300     .priv_data_size      = sizeof(Context),
301     .priv_data_class     = &cache_context_class,
302 };