summaryrefslogtreecommitdiff
path: root/rolling-hash-2d.c
blob: c8968cdd0e54b681a04f0a31a63f7cf71a9998ba (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
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <assert.h>
#include <error.h>
#include <errno.h>
#include <cairo.h>

/*
 * Ideas:
 *
 * - Caching.  Keep blocks from previous images (button prelight, when
 *   prelight turns off, reuse the blocks from the un-prelight image).
 *   Avoid keeping blocks that have been detected as displaced, those
 *   pixels are going to be in the new image.  Can't tell displaced
 *   from "reused somewhere else in the new picture" however.  Detect
 *   when we overwrite a block in the old image and push the original
 *   block to a cache?
 *
 * - Use different hash primes for vertical and horizontal hashes?  Or
 *   use prime^size?
 *
 * - Use top bits of uint32_t hash value for indexing into hash table?
 *   For LCG RNGs the top bits are "higher quality" so perhaps we get
 *   better hashing if we use those?  Update: much better it turns out!
 *
 * - Use smaller blocks but coalesce or run-length encode adjacent
 *   blocks?  For adjacent blocks, we can test if the blocks are
 *   adjacent in the source frame and then join the two blocks into a
 *   32x16 block.  Impacts hash table size and complicates caching.
 *
 * - Make an adjacent match that matches the block adjacent to the
 *   previous match in the old frame override an 'unaligned' earlier
 *   match?  As a heuristic to avoid breaking up big continuous
 *   scrolling areas.
 *
 * - Doing partial updates of a surface makes it tricky to keep the
 *   hash table up to date.
 */

#define ARRAY_LENGTH(a) (sizeof (a) / sizeof (a)[0])

struct entry {
	int count;
	int matches;
	uint32_t hash;
};

struct block_ref {
	int x, y;
	uint32_t hash;
};

struct frame {
	cairo_surface_t *surface;
	struct entry *hash_table;
	int length, block_count, shift;

	struct block_ref *refs;
	int ref_count;
};

/* nice big primes: 0x5b6d745d 0x1f821e2d 0xd5de4c37 */
const uint32_t prime = 0x1f821e2d;
const vprime = 0x0137b89d;
const uint32_t step = 0x0ac93019;
const int size = 32, mask = 31;

static struct entry *
lookup_block(struct frame *prev, uint32_t h)
{
	uint32_t i;
	struct entry *entry;
	int shift = prev->shift;

	for (i = h;
	     entry = &prev->hash_table[i >> shift], entry->count > 0;
	     i += step)
		if (entry->hash == h)
			return entry;

	return NULL;
}

static void
mark_blocks(struct frame *frame)
{
	int i;
	cairo_t *cr;
	struct block_ref *ref;

	cr = cairo_create(frame->surface);
	
	for (i = 0; i < frame->ref_count; i++) {
		double b = random() / 3 / (double) RAND_MAX + 0.2;

		ref = &frame->refs[i];
		cairo_rectangle(cr, ref->x, ref->y, size, size);
		cairo_set_source_rgba(cr, 0.1, 0.1, b, 0.85);
		cairo_fill(cr);
	}
	cairo_destroy(cr);
}

static struct frame *
block_hash(const char *filename, struct frame *prev)
{
	uint32_t end_prime, end_vprime;
	uint32_t *block_hashes;
	uint32_t hash, top_hash, h, *line, *top;
	void *data;
	int i, j, k, collision, stats[100], *skyline, skyline_pixels;
	int x0, x1, y0, y1;
	int width, height, stride, shift;
	FILE *fp;
	struct entry *entry;
	struct frame *frame;
	struct block_ref *ref;

	frame = malloc(sizeof *frame);
	frame->surface = cairo_image_surface_create_from_png(filename);
	if (cairo_surface_status(frame->surface) != CAIRO_STATUS_SUCCESS)
		error(1, errno, "could not load %s", filename);

	data = cairo_image_surface_get_data(frame->surface);
	width = cairo_image_surface_get_width(frame->surface);
	height = cairo_image_surface_get_height(frame->surface);
	stride = cairo_image_surface_get_stride(frame->surface);

	frame->block_count =
		((width + size - 1) / size) * ((height + size - 1) / size);
	frame->length = 1 << (31 - __builtin_clz(frame->block_count * 4));
	frame->shift = __builtin_clz(frame->length) + 1;
	printf("image %s, %dx%d, %d 32x32 blocks, %d hash table "
	       "entries, shift %d\n",
	       filename, width, height,
	       frame->block_count, frame->length, frame->shift);

	frame->refs = malloc(frame->block_count * sizeof frame->refs[0]);
	frame->ref_count = 0;

	frame->hash_table =
		malloc(frame->length * sizeof frame->hash_table[0]);
	memset(frame->hash_table, 0,
	       frame->length * sizeof frame->hash_table[0]);
	memset(stats, 0, sizeof stats);

	skyline = malloc((width + size) * sizeof skyline[0]);
	memset(skyline, 0, width * sizeof skyline[0]);

	end_prime = 1;
	for (i = 0; i < size; i++)
		end_prime *= prime;

	end_vprime = 1;
	for (i = 0; i < size; i++)
		end_vprime *= vprime;

	block_hashes = malloc(width * sizeof block_hashes[0]);
	for (j = 0; j < width; j++)
		block_hashes[j] = 0;

	x0 = 0;
	x1 = width;
	y0 = 0;
	y1 = height;
#if 0
	if (prev) {
		x0 = 200;
		x1 = 600;
		y0 = 100;
		y1 = 500;
	}
#endif

	for (i = y0; i < y0 + size; i++) {
		line = data + i * stride;
		hash = 0;
		for (j = x0; j < x0 + size; j++)
			hash = hash * prime + line[j];
		for (j = x0; j < x1; j++) {
			block_hashes[j] =
				block_hashes[j] * vprime + hash;
			hash = hash * prime - line[j] * end_prime;
			if (j + size < width)
				hash += line[j + size];
		}
	}

	shift = frame->shift;
	for (i = y0; i < y1; i++) {
		line = data + (i + size) * stride;
		top = data + i * stride;
		hash = 0;
		top_hash = 0;
		skyline_pixels = 0;
		for (j = x0; j < x0 + size; j++) {
			if (i + size < height)
				hash = hash * prime + line[j];
			top_hash = top_hash * prime + top[j];

			if (i < skyline[j])
				skyline_pixels = 0;
			else
				skyline_pixels++;
		}
		
		for (j = x0; j < x1; j++) {
			if (i < skyline[j]) {

			    /* TODO: Within a recognized block, encode
			     * no change*/
			} else if (prev) {
				h = block_hashes[j];
				entry = lookup_block(prev, h);
				if (entry && skyline_pixels >= size) {
					ref = &frame->refs[frame->ref_count++];
					ref->x = j;
					ref->y = i;
					ref->hash = h;;
					entry->matches++;
					for (k = 0; k < size; k++)
						skyline[j + k] = i + size;
				} else {
					/* TODO delta encode pixel diffs */
				}

			}

			if (i < skyline[j + size])
				skyline_pixels = 0;
			else
				skyline_pixels++;

			if ((i & mask) == 0 && (j & mask) == 0) {
				/* insert block in hash table for new frame */;
				h = block_hashes[j];
				entry = &frame->hash_table[h >> shift];
				for (k = step, collision = 0;
				     entry->count > 0 && entry->hash != h;
				     k += step) {
					entry = &frame->hash_table[(h + k) >> shift];
					collision++;
				}

				/* TODO: Compare blocks where the full
				 * hash is equal to see if they're
				 * actually equal. */

#if 0
				printf("block at %3d, %3d:\t%08x %3d count, %3d collisions\n",
				       i, j, h,
				       entry->count, collision);
#endif

				entry->hash = h;
				entry->count++;
				stats[collision]++;
			}

			/* Update sliding block hash */
			block_hashes[j] =
				block_hashes[j] * vprime + hash -
				top_hash * end_vprime;

			if (i + size < height) {
				hash = hash * prime - line[j] * end_prime;
				if (j + size < width)
					hash += line[j + size];
			}
			top_hash = top_hash * prime + top[j + size] -
				top[j] * end_prime;
		}
	}

	printf("collision stats:\n");
	for (i = 0; i < 10; i++)
		printf("%2d steps: %4d\n", i, stats[i]);

	return frame;
}

/*
 * RLE Format:
 *
 * 0xxxrrggbb: xx in [1; 127]   : xx next pixels differ rrggbb
 *             xx in [128; 144] : 2^(xx-121) next pixels differ rrggbb
 *             xx = 145: put block number rrggbb here
 *             xx = 146: put cached block number rrggbb here
 * Alpha?
 */

int main (int argc, char *argv[])
{
	struct frame *f0, *f1;
	int i, total;

	f0 = block_hash(argv[1], NULL);
	f1 = block_hash(argv[2], f0);

	total = 0;
	for (i = 0; i < f0->length; i++) {
		if (f0->hash_table[i].matches > 0) {
			printf("%3d matches for %08x\n",
			       f0->hash_table[i].matches,
			       f0->hash_table[i].hash);
		}
		total += f0->hash_table[i].matches;
	}

	printf("%3d total matches out of %d blocks\n", total, f1->block_count);

	mark_blocks(f1);

	cairo_surface_write_to_png(f1->surface, "debug.png");

	return 0;
}