aboutsummaryrefslogtreecommitdiffstats
path: root/tools/mcufontencoder/src/optimize_rlefont.cc
blob: 20c340db1fd4de58c82022362a8e807b1acb2d2a (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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
#include "optimize_rlefont.hh"
#include "encode_rlefont.hh"
#include <random>
#include <iostream>
#include <set>
#include <thread>
#include <algorithm>
#include "ccfixes.hh"

namespace mcufont {
namespace rlefont {

typedef std::mt19937 rnd_t;

// Select a random substring among all the glyphs in the datafile.
std::unique_ptr<DataFile::pixels_t> random_substring(const DataFile &datafile, rnd_t &rnd)
{
    std::uniform_int_distribution<size_t> dist1(0, datafile.GetGlyphCount() - 1);
    size_t index = dist1(rnd);
    
    const DataFile::pixels_t &pixels = datafile.GetGlyphEntry(index).data;
    
    std::uniform_int_distribution<size_t> dist2(2, pixels.size());
    size_t length = dist2(rnd);
    
    std::uniform_int_distribution<size_t> dist3(0, pixels.size() - length);
    size_t start = dist3(rnd);
    
    std::unique_ptr<DataFile::pixels_t> result;
    result.reset(new DataFile::pixels_t(pixels.begin() + start,
                                        pixels.begin() + start + length));
    return result;
}

// Try to replace the worst dictionary entry with a better one.
void optimize_worst(DataFile &datafile, size_t &size, rnd_t &rnd, bool verbose)
{
    std::uniform_int_distribution<size_t> dist(0, 1);
    
    DataFile trial = datafile;
    size_t worst = trial.GetLowScoreIndex();
    DataFile::dictentry_t d = trial.GetDictionaryEntry(worst);
    d.replacement = *random_substring(datafile, rnd);
    d.ref_encode = dist(rnd);
    trial.SetDictionaryEntry(worst, d);
    
    size_t newsize = get_encoded_size(trial);
    
    if (newsize < size)
    {
        d.score = size - newsize;
        datafile.SetDictionaryEntry(worst, d);
        size = newsize;
        
        if (verbose)
            std::cout << "optimize_worst: replaced " << worst
                      << " score " << d.score << std::endl;
    }
}

// Try to replace random dictionary entry with another one.
void optimize_any(DataFile &datafile, size_t &size, rnd_t &rnd, bool verbose)
{
    DataFile trial = datafile;
    std::uniform_int_distribution<size_t> dist(0, DataFile::dictionarysize - 1);
    size_t index = dist(rnd);
    DataFile::dictentry_t d = trial.GetDictionaryEntry(index);
    d.replacement = *random_substring(datafile, rnd);
    trial.SetDictionaryEntry(index, d);
    
    size_t newsize = get_encoded_size(trial);
    
    if (newsize < size)
    {
        d.score = size - newsize;
        datafile.SetDictionaryEntry(index, d);
        size = newsize;
        
        if (verbose)
            std::cout << "optimize_any: replaced " << index
                      << " score " << d.score << std::endl;
    }
}

// Try to append or prepend random dictionary entry.
void optimize_expand(DataFile &datafile, size_t &size, rnd_t &rnd, bool verbose, bool binary_only)
{
    DataFile trial = datafile;
    std::uniform_int_distribution<size_t> dist1(0, DataFile::dictionarysize - 1);
    size_t index = dist1(rnd);
    DataFile::dictentry_t d = trial.GetDictionaryEntry(index);
    
    std::uniform_int_distribution<size_t> dist3(1, 3);
    size_t count = dist3(rnd);
    
    for (size_t i = 0; i < count; i++)
    {
        std::uniform_int_distribution<size_t> booldist(0, 1);
        std::uniform_int_distribution<size_t> pixeldist(0, 15);
        uint8_t pixel;
        
        if (binary_only)
        {
            pixel = booldist(rnd) ? 15 : 0;
        }
        else
        {
            pixel = pixeldist(rnd);
        }
        
        bool prepend = booldist(rnd);
        
        if (prepend)
        {
            d.replacement.insert(d.replacement.begin(), pixel);
        }
        else
        {
            d.replacement.push_back(pixel);
        }
    }
    
    trial.SetDictionaryEntry(index, d);
    
    size_t newsize = get_encoded_size(trial);
    
    if (newsize < size)
    {
        d.score = size - newsize;
        datafile.SetDictionaryEntry(index, d);
        size = newsize;
        
        if (verbose)
            std::cout << "optimize_expand: expanded " << index
                      << " by " << count << " pixels, score " << d.score << std::endl;
    }
}

// Try to trim random dictionary entry.
void optimize_trim(DataFile &datafile, size_t &size, rnd_t &rnd, bool verbose)
{
    DataFile trial = datafile;
    std::uniform_int_distribution<size_t> dist1(0, DataFile::dictionarysize - 1);
    size_t index = dist1(rnd);
    DataFile::dictentry_t d = trial.GetDictionaryEntry(index);
    
    if (d.replacement.size() <= 2) return;
    
    std::uniform_int_distribution<size_t> dist2(0, std::min((int)d.replacement.size() / 2, 5));
    size_t start = dist2(rnd);
    size_t end = dist2(rnd);
    
    if (start)
    {
        d.replacement.erase(d.replacement.begin(), d.replacement.begin() + start);
    }
    
    if (end)
    {
        d.replacement.erase(d.replacement.end() - end, d.replacement.end() - 1);
    }
    
    trial.SetDictionaryEntry(index, d);
    
    size_t newsize = get_encoded_size(trial);
    
    if (newsize < size)
    {
        d.score = size - newsize;
        datafile.SetDictionaryEntry(index, d);
        size = newsize;
        
        if (verbose)
            std::cout << "optimize_trim: trimmed " << index
                      << " by " << start << " pixels from start and "
                      << end << " pixels from end, score " << d.score << std::endl;
    }
}

// Switch random dictionary entry to use ref encoding or back to rle.
void optimize_refdict(DataFile &datafile, size_t &size, rnd_t &rnd, bool verbose)
{
    DataFile trial = datafile;
    std::uniform_int_distribution<size_t> dist1(0, DataFile::dictionarysize - 1);
    size_t index = dist1(rnd);
    DataFile::dictentry_t d = trial.GetDictionaryEntry(index);
    
    d.ref_encode = !d.ref_encode;
    
    trial.SetDictionaryEntry(index, d);
    
    size_t newsize = get_encoded_size(trial);
    
    if (newsize < size)
    {
        d.score = size - newsize;
        datafile.SetDictionaryEntry(index, d);
        size = newsize;
        
        if (verbose)
            std::cout << "optimize_refdict: switched " << index
                      << " to " << (d.ref_encode ? "ref" : "RLE")
                      << ", score " << d.score << std::endl;
    }
}

// Combine two random dictionary entries.
void optimize_combine(DataFile &datafile, size_t &size, rnd_t &rnd, bool verbose)
{
    DataFile trial = datafile;
    std::uniform_int_distribution<size_t> dist1(0, DataFile::dictionarysize - 1);
    size_t worst = datafile.GetLowScoreIndex();
    size_t index1 = dist1(rnd);
    size_t index2 = dist1(rnd);
    
    const DataFile::pixels_t &part1 = datafile.GetDictionaryEntry(index1).replacement;
    const DataFile::pixels_t &part2 = datafile.GetDictionaryEntry(index2).replacement;
    
    DataFile::dictentry_t d;
    d.replacement = part1;
    d.replacement.insert(d.replacement.end(), part2.begin(), part2.end());
    d.ref_encode = true;
    trial.SetDictionaryEntry(worst, d);
    
    size_t newsize = get_encoded_size(trial);
    
    if (newsize < size)
    {
        d.score = size - newsize;
        datafile.SetDictionaryEntry(worst, d);
        size = newsize;
        
        if (verbose)
            std::cout << "optimize_combine: combined " << index1
                      << " and " << index2 << " to replace " << worst
                      << ", score " << d.score << std::endl;
    }
}

// Pick a random part of an encoded glyph and encode it as a ref dict.
void optimize_encpart(DataFile &datafile, size_t &size, rnd_t &rnd, bool verbose)
{
    std::unique_ptr<encoded_font_t> e = encode_font(datafile);
    
    // Pick a random encoded glyph
    std::uniform_int_distribution<size_t> dist1(0, datafile.GetGlyphCount() - 1);
    size_t index = dist1(rnd);
    const encoded_font_t::refstring_t &refstr = e->glyphs.at(index);
    
    if (refstr.size() < 2)
        return;
    
    // Pick a random part of it
    std::uniform_int_distribution<size_t> dist2(2, refstr.size());
    size_t length = dist2(rnd);
    std::uniform_int_distribution<size_t> dist3(0, refstr.size() - length);
    size_t start = dist3(rnd);
    
    // Decode that part
    encoded_font_t::refstring_t substr(refstr.begin() + start,
                                       refstr.begin() + start + length);
    std::unique_ptr<DataFile::pixels_t> decoded =
        decode_glyph(*e, substr, datafile.GetFontInfo());
    
    // Add that as a new dictionary entry
    DataFile trial = datafile;
    size_t worst = trial.GetLowScoreIndex();
    DataFile::dictentry_t d = trial.GetDictionaryEntry(worst);
    d.replacement = *decoded;
    d.ref_encode = true;
    trial.SetDictionaryEntry(worst, d);
    
    size_t newsize = get_encoded_size(trial);
    
    if (newsize < size)
    {
        d.score = size - newsize;
        datafile.SetDictionaryEntry(worst, d);
        size = newsize;
        
        if (verbose)
            std::cout << "optimize_encpart: replaced " << worst
                      << " score " << d.score << std::endl;
    }
}

// Execute all the optimization algorithms once.
void optimize_pass(DataFile &datafile, size_t &size, rnd_t &rnd, bool verbose)
{
    optimize_worst(datafile, size, rnd, verbose);
    optimize_any(datafile, size, rnd, verbose);
    optimize_expand(datafile, size, rnd, verbose, false);
    optimize_expand(datafile, size, rnd, verbose, true);
    optimize_trim(datafile, size, rnd, verbose);
    optimize_refdict(datafile, size, rnd, verbose);
    optimize_combine(datafile, size, rnd, verbose);
    optimize_encpart(datafile, size, rnd, verbose);
}

// Execute multiple passes in parallel and take the one with the best result.
// The amount of parallelism is hardcoded in order to retain deterministic
// behaviour.
void optimize_parallel(DataFile &datafile, size_t &size, rnd_t &rnd, bool verbose, int num_threads = 4)
{
    std::vector<DataFile> datafiles;
    std::vector<size_t> sizes;
    std::vector<rnd_t> rnds;
    std::vector<std::unique_ptr<std::thread> > threads;
    
    for (int i = 0; i < num_threads; i++)
    {
        datafiles.emplace_back(datafile);
        sizes.emplace_back(size);
        rnds.emplace_back(rnd());
    }
    
    for (int i = 0; i < num_threads; i++)
    {
        threads.emplace_back(new std::thread(optimize_pass,
                                             std::ref(datafiles.at(i)),
                                             std::ref(sizes.at(i)),
                                             std::ref(rnds.at(i)),
                                             verbose));
    }
    
    for (int i = 0; i < num_threads; i++)
    {
        threads.at(i)->join();
    }
    
    int best = std::min_element(sizes.begin(), sizes.end()) - sizes.begin();
    size = sizes.at(best);
    datafile = datafiles.at(best);
}

// Go through all the dictionary entries and check what it costs to remove
// them. Removes any entries with negative or zero score.
void update_scores(DataFile &datafile, bool verbose)
{
    size_t oldsize = get_encoded_size(datafile);
    
    for (size_t i = 0; i < DataFile::dictionarysize; i++)
    {
        DataFile trial = datafile;
        DataFile::dictentry_t dummy = {};
        trial.SetDictionaryEntry(i, dummy);
        size_t newsize = get_encoded_size(trial);
        
        DataFile::dictentry_t d = datafile.GetDictionaryEntry(i);
        d.score = newsize - oldsize;
        
        if (d.score > 0)
        {
            datafile.SetDictionaryEntry(i, d);
        }
        else
        {
            datafile.SetDictionaryEntry(i, dummy);
            
            if (verbose && d.replacement.size() != 0)
                std::cout << "update_scores: dropped " << i
                        << " score " << -d.score << std::endl;
        }
    }
}

void init_dictionary(DataFile &datafile)
{
    rnd_t rnd(datafile.GetSeed());
    
    if (datafile.GetGlyphCount() == 0)
        return;
    
    std::set<DataFile::pixels_t> seen_substrings;
    std::set<DataFile::pixels_t> added_substrings;
    
    size_t i = 0;
    while (i < DataFile::dictionarysize)
    {
        DataFile::pixels_t substring = *random_substring(datafile, rnd);
        
        if (!seen_substrings.count(substring))
        {
            seen_substrings.insert(substring);
        }
        else if (!added_substrings.count(substring))
        {
            // When we see a substring second time, add it.
            DataFile::dictentry_t d;
            d.score = 0;
            d.replacement = substring;
            datafile.SetDictionaryEntry(i, d);
            i++;
            added_substrings.insert(substring);
        }
    }
}

void optimize(DataFile &datafile, size_t iterations)
{
    bool verbose = false;
    rnd_t rnd(datafile.GetSeed());
    
    update_scores(datafile, verbose);
    
    size_t size = get_encoded_size(datafile);
    
    for (size_t i = 0; i < iterations; i++)
    {
        optimize_parallel(datafile, size, rnd, verbose);
    }
    
    std::uniform_int_distribution<size_t> dist(0, std::numeric_limits<uint32_t>::max());
    datafile.SetSeed(dist(rnd));
}

}}