summaryrefslogtreecommitdiff
path: root/core/io/file_access_compressed.cpp
blob: ade4b2c1acd36b018d946ec49d58ee37625259f0 (plain)
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
/*************************************************************************/
/*  file_access_compressed.cpp                                           */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#include "file_access_compressed.h"

#include "core/string/print_string.h"

void FileAccessCompressed::configure(const String &p_magic, Compression::Mode p_mode, int p_block_size) {
	magic = p_magic.ascii().get_data();
	if (magic.length() > 4) {
		magic = magic.substr(0, 4);
	} else {
		while (magic.length() < 4) {
			magic += " ";
		}
	}

	cmode = p_mode;
	block_size = p_block_size;
}

#define WRITE_FIT(m_bytes)                                  \
	{                                                       \
		if (write_pos + (m_bytes) > write_max) {            \
			write_max = write_pos + (m_bytes);              \
		}                                                   \
		if (write_max > write_buffer_size) {                \
			write_buffer_size = next_power_of_2(write_max); \
			buffer.resize(write_buffer_size);               \
			write_ptr = buffer.ptrw();                      \
		}                                                   \
	}

Error FileAccessCompressed::open_after_magic(FileAccess *p_base) {
	f = p_base;
	cmode = (Compression::Mode)f->get_32();
	block_size = f->get_32();
	if (block_size == 0) {
		f = nullptr; // Let the caller to handle the FileAccess object if failed to open as compressed file.
		ERR_FAIL_V_MSG(ERR_FILE_CORRUPT, "Can't open compressed file '" + p_base->get_path() + "' with block size 0, it is corrupted.");
	}
	read_total = f->get_32();
	int bc = (read_total / block_size) + 1;
	int acc_ofs = f->get_position() + bc * 4;
	int max_bs = 0;
	for (int i = 0; i < bc; i++) {
		ReadBlock rb;
		rb.offset = acc_ofs;
		rb.csize = f->get_32();
		acc_ofs += rb.csize;
		max_bs = MAX(max_bs, rb.csize);
		read_blocks.push_back(rb);
	}

	comp_buffer.resize(max_bs);
	buffer.resize(block_size);
	read_ptr = buffer.ptrw();
	f->get_buffer(comp_buffer.ptrw(), read_blocks[0].csize);
	at_end = false;
	read_eof = false;
	read_block_count = bc;
	read_block_size = read_blocks.size() == 1 ? read_total : block_size;

	Compression::decompress(buffer.ptrw(), read_block_size, comp_buffer.ptr(), read_blocks[0].csize, cmode);
	read_block = 0;
	read_pos = 0;

	return OK;
}

Error FileAccessCompressed::_open(const String &p_path, int p_mode_flags) {
	ERR_FAIL_COND_V(p_mode_flags == READ_WRITE, ERR_UNAVAILABLE);

	if (f) {
		close();
	}

	Error err;
	f = FileAccess::open(p_path, p_mode_flags, &err);
	if (err != OK) {
		//not openable

		f = nullptr;
		return err;
	}

	if (p_mode_flags & WRITE) {
		buffer.clear();
		writing = true;
		write_pos = 0;
		write_buffer_size = 256;
		buffer.resize(256);
		write_max = 0;
		write_ptr = buffer.ptrw();

		//don't store anything else unless it's done saving!
	} else {
		char rmagic[5];
		f->get_buffer((uint8_t *)rmagic, 4);
		rmagic[4] = 0;
		if (magic != rmagic || open_after_magic(f) != OK) {
			memdelete(f);
			f = nullptr;
			return ERR_FILE_UNRECOGNIZED;
		}
	}

	return OK;
}

void FileAccessCompressed::close() {
	if (!f) {
		return;
	}

	if (writing) {
		//save block table and all compressed blocks

		CharString mgc = magic.utf8();
		f->store_buffer((const uint8_t *)mgc.get_data(), mgc.length()); //write header 4
		f->store_32(cmode); //write compression mode 4
		f->store_32(block_size); //write block size 4
		f->store_32(write_max); //max amount of data written 4
		int bc = (write_max / block_size) + 1;

		for (int i = 0; i < bc; i++) {
			f->store_32(0); //compressed sizes, will update later
		}

		Vector<int> block_sizes;
		for (int i = 0; i < bc; i++) {
			int bl = i == (bc - 1) ? write_max % block_size : block_size;
			uint8_t *bp = &write_ptr[i * block_size];

			Vector<uint8_t> cblock;
			cblock.resize(Compression::get_max_compressed_buffer_size(bl, cmode));
			int s = Compression::compress(cblock.ptrw(), bp, bl, cmode);

			f->store_buffer(cblock.ptr(), s);
			block_sizes.push_back(s);
		}

		f->seek(16); //ok write block sizes
		for (int i = 0; i < bc; i++) {
			f->store_32(block_sizes[i]);
		}
		f->seek_end();
		f->store_buffer((const uint8_t *)mgc.get_data(), mgc.length()); //magic at the end too

		buffer.clear();

	} else {
		comp_buffer.clear();
		buffer.clear();
		read_blocks.clear();
	}

	memdelete(f);
	f = nullptr;
}

bool FileAccessCompressed::is_open() const {
	return f != nullptr;
}

void FileAccessCompressed::seek(size_t p_position) {
	ERR_FAIL_COND_MSG(!f, "File must be opened before use.");
	if (writing) {
		ERR_FAIL_COND(p_position > write_max);

		write_pos = p_position;

	} else {
		ERR_FAIL_COND(p_position > read_total);
		if (p_position == read_total) {
			at_end = true;
		} else {
			at_end = false;
			read_eof = false;
			int block_idx = p_position / block_size;
			if (block_idx != read_block) {
				read_block = block_idx;
				f->seek(read_blocks[read_block].offset);
				f->get_buffer(comp_buffer.ptrw(), read_blocks[read_block].csize);
				Compression::decompress(buffer.ptrw(), read_blocks.size() == 1 ? read_total : block_size, comp_buffer.ptr(), read_blocks[read_block].csize, cmode);
				read_block_size = read_block == read_block_count - 1 ? read_total % block_size : block_size;
			}

			read_pos = p_position % block_size;
		}
	}
}

void FileAccessCompressed::seek_end(int64_t p_position) {
	ERR_FAIL_COND_MSG(!f, "File must be opened before use.");
	if (writing) {
		seek(write_max + p_position);
	} else {
		seek(read_total + p_position);
	}
}

size_t FileAccessCompressed::get_position() const {
	ERR_FAIL_COND_V_MSG(!f, 0, "File must be opened before use.");
	if (writing) {
		return write_pos;
	} else {
		return read_block * block_size + read_pos;
	}
}

size_t FileAccessCompressed::get_len() const {
	ERR_FAIL_COND_V_MSG(!f, 0, "File must be opened before use.");
	if (writing) {
		return write_max;
	} else {
		return read_total;
	}
}

bool FileAccessCompressed::eof_reached() const {
	ERR_FAIL_COND_V_MSG(!f, false, "File must be opened before use.");
	if (writing) {
		return false;
	} else {
		return read_eof;
	}
}

uint8_t FileAccessCompressed::get_8() const {
	ERR_FAIL_COND_V_MSG(!f, 0, "File must be opened before use.");
	ERR_FAIL_COND_V_MSG(writing, 0, "File has not been opened in read mode.");

	if (at_end) {
		read_eof = true;
		return 0;
	}

	uint8_t ret = read_ptr[read_pos];

	read_pos++;
	if (read_pos >= read_block_size) {
		read_block++;

		if (read_block < read_block_count) {
			//read another block of compressed data
			f->get_buffer(comp_buffer.ptrw(), read_blocks[read_block].csize);
			Compression::decompress(buffer.ptrw(), read_blocks.size() == 1 ? read_total : block_size, comp_buffer.ptr(), read_blocks[read_block].csize, cmode);
			read_block_size = read_block == read_block_count - 1 ? read_total % block_size : block_size;
			read_pos = 0;

		} else {
			read_block--;
			at_end = true;
		}
	}

	return ret;
}

int FileAccessCompressed::get_buffer(uint8_t *p_dst, int p_length) const {
	ERR_FAIL_COND_V(!p_dst, -1);
	ERR_FAIL_COND_V(p_length < 0, -1);
	ERR_FAIL_COND_V_MSG(!f, -1, "File must be opened before use.");
	ERR_FAIL_COND_V_MSG(writing, -1, "File has not been opened in read mode.");

	if (at_end) {
		read_eof = true;
		return 0;
	}

	for (int i = 0; i < p_length; i++) {
		p_dst[i] = read_ptr[read_pos];
		read_pos++;
		if (read_pos >= read_block_size) {
			read_block++;

			if (read_block < read_block_count) {
				//read another block of compressed data
				f->get_buffer(comp_buffer.ptrw(), read_blocks[read_block].csize);
				Compression::decompress(buffer.ptrw(), read_blocks.size() == 1 ? read_total : block_size, comp_buffer.ptr(), read_blocks[read_block].csize, cmode);
				read_block_size = read_block == read_block_count - 1 ? read_total % block_size : block_size;
				read_pos = 0;

			} else {
				read_block--;
				at_end = true;
				if (i < p_length - 1) {
					read_eof = true;
				}
				return i;
			}
		}
	}

	return p_length;
}

Error FileAccessCompressed::get_error() const {
	return read_eof ? ERR_FILE_EOF : OK;
}

void FileAccessCompressed::flush() {
	ERR_FAIL_COND_MSG(!f, "File must be opened before use.");
	ERR_FAIL_COND_MSG(!writing, "File has not been opened in write mode.");

	// compressed files keep data in memory till close()
}

void FileAccessCompressed::store_8(uint8_t p_dest) {
	ERR_FAIL_COND_MSG(!f, "File must be opened before use.");
	ERR_FAIL_COND_MSG(!writing, "File has not been opened in write mode.");

	WRITE_FIT(1);
	write_ptr[write_pos++] = p_dest;
}

bool FileAccessCompressed::file_exists(const String &p_name) {
	FileAccess *fa = FileAccess::open(p_name, FileAccess::READ);
	if (!fa) {
		return false;
	}
	memdelete(fa);
	return true;
}

uint64_t FileAccessCompressed::_get_modified_time(const String &p_file) {
	if (f) {
		return f->get_modified_time(p_file);
	} else {
		return 0;
	}
}

uint32_t FileAccessCompressed::_get_unix_permissions(const String &p_file) {
	if (f) {
		return f->_get_unix_permissions(p_file);
	}
	return 0;
}

Error FileAccessCompressed::_set_unix_permissions(const String &p_file, uint32_t p_permissions) {
	if (f) {
		return f->_set_unix_permissions(p_file, p_permissions);
	}
	return FAILED;
}

FileAccessCompressed::~FileAccessCompressed() {
	if (f) {
		close();
	}
}