source: libpipi/trunk/examples/img2twit.cpp @ 3522

Last change on this file since 3522 was 3522, checked in by Sam Hocevar, 11 years ago

Make img2twit more configurable: iterations per second and debug mode can
now be chosen at runtime. Message length will soon be.

  • Property svn:keywords set to Id
File size: 32.3 KB
RevLine 
[3518]1#include "config.h"
2
3#include <stdio.h>
4#include <stdlib.h>
5#include <string.h>
6#include <math.h>
7
8#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
9#include <CGAL/Delaunay_triangulation_2.h>
10#include <CGAL/natural_neighbor_coordinates_2.h>
11
12#include <pipi.h>
13
[3522]14#include "../genethumb/mygetopt.h"
15
[3520]16/*
17 * User-definable settings.
18 */
19
[3521]20/* The Unicode characters at disposal - XXX: must be _ordered_ */
21static const uint32_t unichars[] =
22{
23    /* Printable ASCII (except space) */
[3522]24    //0x0021, 0x007f,
[3520]25
[3521]26    /* Stupid symbols and Dingbats shit */
27    //0x25a0, 0x2600, /* Geometric Shapes */
28    //0x2600, 0x269e, 0x26a0, 0x26bd, 0x26c0, 0x26c4, /* Misc. Symbols */
29    //0x2701, 0x2705, 0x2706, 0x270a, 0x270c, 0x2728, 0x2729, 0x274c,
30    //  0x274d, 0x274e, 0x274f, 0x2753, 0x2756, 0x2757, 0x2758, 0x275f,
31    //  0x2761, 0x2795, 0x2798, 0x27b0, 0x27b1, 0x27bf, /* Dingbats */
32
33    /* Chinese-looking stuff */
34    //0x2e80, 0x2e9a, 0x2e9b, 0x2ef4, /* CJK Radicals Supplement */
35    //0x2f00, 0x2fd6, /* Kangxi Radicals */
36    //0x3400, 0x4db6, /* CJK Unified Ideographs Extension A */
[3522]37    0x4e00, 0x9fa6, /* CJK Unified Ideographs */
[3521]38
39    /* Korean - most people don't know the difference anyway */
[3522]40    //0xac00, 0xd7a4, /* Hangul Syllables */
[3521]41
42    /* More Chinese */
43    //0xf900, 0xfa2e, 0xfa30, 0xfa6b, 0xfa70, 0xfada, /* CJK Compat. Idgphs. */
44
45    /* TODO: there's also the U+20000 and U+2f800 planes, but they're
46     * not supported by the Twitter Javascript filter (yet?). */
47
48    /* End of list marker - XXX: don't remove! */
49    0x0000, 0x0000
50};
51
[3520]52/* The maximum image size we want to support */
53#define MAX_W 4000
54#define MAX_H 4000
55
56/* How does the algorithm work: one point per cell, or two */
[3518]57#define POINTS_PER_CELL 2
58
[3520]59/* The range value for point parameters: X Y, red/green/blue, "strength"
60 * Tested values (on Mona Lisa) are:
61 *  16 16 5 5 5 2 -> 0.06511725914
62 *  16 16 6 7 6 1 -> 0.05731491348 *
63 *  16 16 7 6 6 1 -> 0.06450513783
64 *  14 14 7 7 6 1 -> 0.0637207893
65 *  19 19 6 6 5 1 -> 0.06801999094 */
66static unsigned int RANGE_X = 16;
67static unsigned int RANGE_Y = 16;
68static unsigned int RANGE_R = 6;
69static unsigned int RANGE_G = 6;
70static unsigned int RANGE_B = 6;
71static unsigned int RANGE_S = 1;
[3518]72
[3520]73/*
[3522]74 * These values can be overwritten at runtime
75 */
76
77static bool DEBUG = false;
78
79/* The maximum message length */
80static int MAX_MSG_LEN = 1140;
81
82static int ITERATIONS_PER_POINT = 50;
83
84/*
[3520]85 * These values are computed at runtime
86 */
87
88static float TOTAL_BITS;
89static float HEADER_BITS;
90static float DATA_BITS;
[3521]91static float CELL_BITS;
[3520]92
[3521]93static int NUM_CHARACTERS;
[3522]94static int MAX_ITERATIONS;
[3520]95static unsigned int TOTAL_CELLS;
96
[3518]97#define RANGE_SY (RANGE_S*RANGE_Y)
98#define RANGE_SYX (RANGE_S*RANGE_Y*RANGE_X)
99#define RANGE_SYXR (RANGE_S*RANGE_Y*RANGE_X*RANGE_R)
100#define RANGE_SYXRG (RANGE_S*RANGE_Y*RANGE_X*RANGE_R*RANGE_G)
101#define RANGE_SYXRGB (RANGE_S*RANGE_Y*RANGE_X*RANGE_R*RANGE_G*RANGE_B)
102
103struct K : CGAL::Exact_predicates_inexact_constructions_kernel {};
104typedef CGAL::Delaunay_triangulation_2<K> Delaunay_triangulation;
105typedef std::vector<std::pair<K::Point_2, K::FT> > Point_coordinate_vector;
106
107/* Global aspect ratio */
[3520]108static unsigned int dw, dh;
[3518]109
110/* Global point encoding */
[3522]111static uint32_t points[4096]; /* FIXME: allocate this dynamically */
[3518]112static int npoints = 0;
113
114/* Global triangulation */
115static Delaunay_triangulation dt;
116
[3521]117/*
118 * Unicode stuff handling
119 */
120
121/* Return the number of chars in the unichars table */
122static int count_unichars(void)
123{
124    int ret = 0;
125
126    for(int u = 0; unichars[u] != unichars[u + 1]; u += 2)
127        ret += unichars[u + 1] - unichars[u];
128
129    return ret;
130}
131
132/* Get the ith Unicode character in our list */
133static uint32_t index2uni(uint32_t i)
134{
135    for(int u = 0; unichars[u] != unichars[u + 1]; u += 2)
136        if(i < unichars[u + 1] - unichars[u])
137            return unichars[u] + i;
138        else
139            i -= unichars[u + 1] - unichars[u];
140
141    return 0; /* Should not happen! */
142}
143
144/* Convert a Unicode character to its position in the compact list */
145static uint32_t uni2index(uint32_t x)
146{
147    uint32_t ret = 0;
148
149    for(int u = 0; unichars[u] != unichars[u + 1]; u += 2)
150        if(x < unichars[u + 1])
151            return ret + x - unichars[u];
152        else
153            ret += unichars[u + 1] - unichars[u];
154
155    return ret; /* Should not happen! */
156}
157
158static uint8_t const utf8_trailing[256] =
159{
160    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
161    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
162    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
163    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
164    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
165    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
166    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
167    2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5
168};
169
170static uint32_t const utf8_offsets[6] =
171{
172    0x00000000UL, 0x00003080UL, 0x000E2080UL,
173    0x03C82080UL, 0xFA082080UL, 0x82082080UL
174};
175
176static uint32_t fread_utf8(FILE *f)
177{
178    int ch, i = 0, todo = -1;
179    uint32_t ret = 0;
180
181    for(;;)
182    {
183        ch = fgetc(f);
184        if(!ch)
185            return 0;
186        if(todo == -1)
187            todo = utf8_trailing[ch];
188        ret += ((uint32_t)ch) << (6 * (todo - i));
189        if(todo == i++)
190            return ret - utf8_offsets[todo];
191    }
192}
193
194static void fwrite_utf8(FILE *f, uint32_t x)
195{
196    static const uint8_t mark[7] =
197    {
198        0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC
199    };
200
201    char buf[8];
202    char *parser = buf;
203    size_t bytes;
204
205    if(x < 0x80)
206    {
207        fprintf(f, "%c", x);
208        return;
209    }
210
211    bytes = (x < 0x800) ? 2 : (x < 0x10000) ? 3 : 4;
212    parser += bytes;
213    *parser = '\0';
214
215    switch(bytes)
216    {
217        case 4: *--parser = (x | 0x80) & 0xbf; x >>= 6;
218        case 3: *--parser = (x | 0x80) & 0xbf; x >>= 6;
219        case 2: *--parser = (x | 0x80) & 0xbf; x >>= 6;
220    }
221    *--parser = x | mark[bytes];
222
223    fprintf(f, "%s", buf);
224}
225
226/*
227 * Our nifty non-power-of-two bitstack handling
228 */
229
230class bitstack
231{
232public:
[3522]233    bitstack() { alloc(); init(0); }
[3521]234
[3522]235    ~bitstack() { delete[] digits; delete[] str; }
236
[3521]237    char const *tostring()
238    {
239        int pos = sprintf(str, "0x%x", digits[msb]);
240
241        for(int i = msb - 1; i >= 0; i--)
242            pos += sprintf(str + pos, "%08x", digits[i]);
243
244        return str;
245    }
246
247    void push(uint32_t val, uint32_t range)
248    {
249        if(!range)
250            return;
251
252        mul(range);
253        add(val % range);
254    }
255
256    uint32_t pop(uint32_t range)
257    {
258        if(!range)
259            return 0;
260
261        return div(range);
262    }
263
264    bool isempty()
265    {
266        for(int i = msb; i >= 0; i--)
267            if(digits[i])
268                return false;
269
270        return true;
271    }
272
273private:
[3522]274    bitstack(uint32_t i) { alloc(); init(i); }
[3521]275
[3522]276    bitstack(bitstack const &b)
277    {
278        alloc();
279        msb = b.msb;
280        memcpy(digits, b.digits, (MAX_MSG_LEN + 1) * sizeof(uint32_t));
281    }
282
283    void alloc()
284    {
285        digits = new uint32_t[MAX_MSG_LEN + 1];
286        str = new char[(MAX_MSG_LEN + 1) * 8 + 1];
287    }
288
[3521]289    void init(uint32_t i)
290    {
[3522]291        msb = 0;
292        memset(digits, 0, (MAX_MSG_LEN + 1) * sizeof(uint32_t));
[3521]293        digits[0] = i;
294    }
295
296    /* Could be done much faster, but we don't care! */
297    void add(uint32_t x) { add(bitstack(x)); }
298    void sub(uint32_t x) { sub(bitstack(x)); }
299
300    void add(bitstack const &_b)
301    {
302        /* Copy the operand in case we get added to ourselves */
[3522]303        bitstack b(_b);
[3521]304        uint64_t x = 0;
305
306        if(msb < b.msb)
307            msb = b.msb;
308
309        for(int i = 0; i <= msb; i++)
310        {
311            uint64_t tmp = (uint64_t)digits[i] + (uint64_t)b.digits[i] + x;
312            digits[i] = tmp;
313            if((uint64_t)digits[i] == tmp)
314                x = 0;
315            else
316            {
317                x = 1;
318                if(i == msb)
319                    msb++;
320            }
321        }
322    }
323
324    void sub(bitstack const &_b)
325    {
326        /* Copy the operand in case we get substracted from ourselves */
[3522]327        bitstack b(_b);
[3521]328        uint64_t x = 0;
329
330        /* We cannot substract a larger number! */
331        if(msb < b.msb)
332        {
333            init(0);
334            return;
335        }
336
337        for(int i = 0; i <= msb; i++)
338        {
339            uint64_t tmp = (uint64_t)digits[i] - (uint64_t)b.digits[i] - x;
340            digits[i] = tmp;
341            if((uint64_t)digits[i] == tmp)
342                x = 0;
343            else
344            {
345                x = 1;
346                if(i == msb)
347                {
348                    /* Error: carry into MSB! */
349                    init(0);
350                    return;
351                }
352            }
353        }
354
355        while(msb > 0 && digits[msb] == 0) msb--;
356    }
357
358    void mul(uint32_t x)
359    {
[3522]360        bitstack b(*this);
[3521]361        init(0);
362
363        while(x)
364        {
365            if(x & 1)
366                add(b);
367            x /= 2;
368            b.add(b);
369        }
370    }
371
372    uint32_t div(uint32_t x)
373    {
[3522]374        bitstack b(*this);
[3521]375
376        for(int i = msb; i >= 0; i--)
377        {
378            uint64_t tmp = b.digits[i] + (((uint64_t)b.digits[i + 1]) << 32);
379            uint32_t res = tmp / x;
380            uint32_t rem = tmp % x;
381            digits[i]= res;
382            b.digits[i + 1] = 0;
383            b.digits[i] = rem;
384        }
385
386        while(msb > 0 && digits[msb] == 0) msb--;
387
388        return b.digits[0];
389    }
390
391    int msb;
[3522]392    uint32_t *digits;
393    char *str;
[3521]394};
395
396/*
397 * Point handling
398 */
399
[3518]400static unsigned int det_rand(unsigned int mod)
401{
402    static unsigned long next = 1;
403    next = next * 1103515245 + 12345;
404    return ((unsigned)(next / 65536) % 32768) % mod;
405}
406
[3520]407static inline int range2int(float val, int range)
[3518]408{
409    int ret = (int)(val * ((float)range - 0.0001));
[3520]410    return ret < 0 ? 0 : ret > range - 1 ? range - 1 : ret;
[3518]411}
412
[3520]413static inline float int2midrange(int val, int range)
[3518]414{
415    return (float)(1 + 2 * val) / (float)(2 * range);
416}
417
[3520]418static inline float int2fullrange(int val, int range)
[3518]419{
[3520]420    return range > 1 ? (float)val / (float)(range - 1) : 0.0;
421}
422
423static inline void set_point(int index, float x, float y, float r,
424                             float g, float b, float s)
425{
[3518]426    int dx = (index / POINTS_PER_CELL) % dw;
427    int dy = (index / POINTS_PER_CELL) / dw;
428
429    float fx = (x - dx * RANGE_X) / RANGE_X;
430    float fy = (y - dy * RANGE_Y) / RANGE_Y;
431
[3520]432    int is = range2int(s, RANGE_S);
[3518]433
[3520]434    int ix = range2int(fx, RANGE_X);
435    int iy = range2int(fy, RANGE_Y);
[3518]436
[3520]437    int ir = range2int(r, RANGE_R);
438    int ig = range2int(g, RANGE_G);
439    int ib = range2int(b, RANGE_B);
[3518]440
441    points[index] = is + RANGE_S * (iy + RANGE_Y * (ix + RANGE_X *
442                               (ib + RANGE_B * (ig + (RANGE_R * ir)))));
443}
444
445static inline void get_point(int index, float *x, float *y, float *r,
446                             float *g, float *b, float *s)
447{
448    uint32_t pt = points[index];
449
450    unsigned int dx = (index / POINTS_PER_CELL) % dw;
451    unsigned int dy = (index / POINTS_PER_CELL) / dw;
452
[3520]453    *s = int2fullrange(pt % RANGE_S, RANGE_S); pt /= RANGE_S;
[3518]454
[3520]455    float fy = int2midrange(pt % RANGE_Y, RANGE_Y); pt /= RANGE_Y;
456    float fx = int2midrange(pt % RANGE_X, RANGE_X); pt /= RANGE_X;
[3518]457
[3522]458    *x = (fx + dx) * RANGE_X /*+ 0.5 * (index & 1)*/;
459    *y = (fy + dy) * RANGE_Y /*+ 0.5 * (index & 1)*/;
[3518]460
[3520]461    *b = int2midrange(pt % RANGE_R, RANGE_R); pt /= RANGE_R;
462    *g = int2midrange(pt % RANGE_G, RANGE_G); pt /= RANGE_G;
463    *r = int2midrange(pt % RANGE_B, RANGE_B); pt /= RANGE_B;
[3518]464}
465
466static inline float clip(float x, int modulo)
467{
468    float mul = (float)modulo + 0.9999;
469    int round = (int)(x * mul);
470    return (float)round / (float)modulo;
471}
472
473static void add_point(float x, float y, float r, float g, float b, float s)
474{
475    set_point(npoints, x, y, r, g, b, s);
476    npoints++;
477}
478
[3521]479#if 0
[3520]480static void add_random_point()
481{
482    points[npoints] = det_rand(RANGE_SYXRGB);
483    npoints++;
484}
[3521]485#endif
[3518]486
[3520]487#define NB_OPS 20
488
489static uint8_t rand_op(void)
490{
491    uint8_t x = det_rand(NB_OPS);
492
493    /* Randomly ignore statistically less efficient ops */
494    if(x == 0)
495        return rand_op();
496    if(x == 1 && (RANGE_S == 1 || det_rand(2)))
497        return rand_op();
498    if(x <= 5 && det_rand(2))
499        return rand_op();
500    //if((x < 10 || x > 15) && !det_rand(4)) /* Favour colour changes */
501    //    return rand_op();
502
503    return x;
504}
505
[3518]506static uint32_t apply_op(uint8_t op, uint32_t val)
507{
508    uint32_t rem, ext;
509
510    switch(op)
511    {
512    case 0: /* Flip strength value */
[3520]513    case 1:
514        /* Statistics show that this helps often, but does not reduce
515         * the error significantly. */
[3518]516        return val ^ 1;
[3520]517    case 2: /* Move up; if impossible, down */
[3518]518        rem = val % RANGE_S;
519        ext = (val / RANGE_S) % RANGE_Y;
520        ext = ext > 0 ? ext - 1 : ext + 1;
521        return (val / RANGE_SY * RANGE_Y + ext) * RANGE_S + rem;
[3520]522    case 3: /* Move down; if impossible, up */
[3518]523        rem = val % RANGE_S;
524        ext = (val / RANGE_S) % RANGE_Y;
525        ext = ext < RANGE_Y - 1 ? ext + 1 : ext - 1;
526        return (val / RANGE_SY * RANGE_Y + ext) * RANGE_S + rem;
[3520]527    case 4: /* Move left; if impossible, right */
[3518]528        rem = val % RANGE_SY;
529        ext = (val / RANGE_SY) % RANGE_X;
530        ext = ext > 0 ? ext - 1 : ext + 1;
531        return (val / RANGE_SYX * RANGE_X + ext) * RANGE_SY + rem;
[3520]532    case 5: /* Move left; if impossible, right */
[3518]533        rem = val % RANGE_SY;
534        ext = (val / RANGE_SY) % RANGE_X;
535        ext = ext < RANGE_X - 1 ? ext + 1 : ext - 1;
536        return (val / RANGE_SYX * RANGE_X + ext) * RANGE_SY + rem;
[3520]537    case 6: /* Corner 1 */
[3518]538        return apply_op(2, apply_op(4, val));
[3520]539    case 7: /* Corner 2 */
540        return apply_op(2, apply_op(5, val));
541    case 8: /* Corner 3 */
542        return apply_op(3, apply_op(5, val));
543    case 9: /* Corner 4 */
544        return apply_op(3, apply_op(4, val));
545    case 16: /* Double up */
546        return apply_op(2, apply_op(2, val));
547    case 17: /* Double down */
548        return apply_op(3, apply_op(3, val));
549    case 18: /* Double left */
550        return apply_op(4, apply_op(4, val));
551    case 19: /* Double right */
552        return apply_op(5, apply_op(5, val));
553    case 10: /* R-- (or R++) */
[3518]554        rem = val % RANGE_SYX;
555        ext = (val / RANGE_SYX) % RANGE_R;
556        ext = ext > 0 ? ext - 1 : ext + 1;
557        return (val / RANGE_SYXR * RANGE_R + ext) * RANGE_SYX + rem;
[3520]558    case 11: /* R++ (or R--) */
[3518]559        rem = val % RANGE_SYX;
560        ext = (val / RANGE_SYX) % RANGE_R;
561        ext = ext < RANGE_R - 1 ? ext + 1 : ext - 1;
562        return (val / RANGE_SYXR * RANGE_R + ext) * RANGE_SYX + rem;
[3520]563    case 12: /* G-- (or G++) */
[3518]564        rem = val % RANGE_SYXR;
565        ext = (val / RANGE_SYXR) % RANGE_G;
566        ext = ext > 0 ? ext - 1 : ext + 1;
567        return (val / RANGE_SYXRG * RANGE_G + ext) * RANGE_SYXR + rem;
[3520]568    case 13: /* G++ (or G--) */
[3518]569        rem = val % RANGE_SYXR;
570        ext = (val / RANGE_SYXR) % RANGE_G;
571        ext = ext < RANGE_G - 1 ? ext + 1 : ext - 1;
572        return (val / RANGE_SYXRG * RANGE_G + ext) * RANGE_SYXR + rem;
[3520]573    case 14: /* B-- (or B++) */
[3518]574        rem = val % RANGE_SYXRG;
575        ext = (val / RANGE_SYXRG) % RANGE_B;
576        ext = ext > 0 ? ext - 1 : ext + 1;
577        return ext * RANGE_SYXRG + rem;
[3520]578    case 15: /* B++ (or B--) */
[3518]579        rem = val % RANGE_SYXRG;
580        ext = (val / RANGE_SYXRG) % RANGE_B;
581        ext = ext < RANGE_B - 1 ? ext + 1 : ext - 1;
582        return ext * RANGE_SYXRG + rem;
583#if 0
584    case 15: /* Brightness-- */
585        return apply_op(9, apply_op(11, apply_op(13, val)));
586    case 16: /* Brightness++ */
587        return apply_op(10, apply_op(12, apply_op(14, val)));
588    case 17: /* RG-- */
589        return apply_op(9, apply_op(11, val));
590    case 18: /* RG++ */
591        return apply_op(10, apply_op(12, val));
592    case 19: /* GB-- */
593        return apply_op(11, apply_op(13, val));
594    case 20: /* GB++ */
595        return apply_op(12, apply_op(14, val));
596    case 21: /* RB-- */
597        return apply_op(9, apply_op(13, val));
598    case 22: /* RB++ */
599        return apply_op(10, apply_op(14, val));
600#endif
601    default:
602        return val;
603    }
604}
605
606static void render(pipi_image_t *dst, int rx, int ry, int rw, int rh)
607{
[3522]608    int lookup[dw * RANGE_X * 2 * dh * RANGE_Y * 2];
[3518]609    pipi_pixels_t *p = pipi_get_pixels(dst, PIPI_PIXELS_RGBA_F32);
610    float *data = (float *)p->pixels;
[3522]611    int x, y;
[3518]612
613    memset(lookup, 0, sizeof(lookup));
614    dt.clear();
[3522]615    for(int i = 0; i < npoints; i++)
[3518]616    {
[3520]617        float fx, fy, fr, fg, fb, fs;
[3518]618        get_point(i, &fx, &fy, &fr, &fg, &fb, &fs);
619        dt.insert(K::Point_2(fx, fy));
[3522]620        /* Keep link to point */
621        lookup[(int)(fx * 2) + dw * RANGE_X * 2 * (int)(fy * 2)] = i;
[3518]622    }
623
624    /* Add fake points to close the triangulation */
625    dt.insert(K::Point_2(-p->w, -p->h));
626    dt.insert(K::Point_2(2 * p->w, -p->h));
627    dt.insert(K::Point_2(-p->w, 2 * p->h));
628    dt.insert(K::Point_2(2 * p->w, 2 * p->h));
629
630    for(y = ry; y < ry + rh; y++)
631    {
632        for(x = rx; x < rx + rw; x++)
633        {
634            K::Point_2 m(x, y);
635            Point_coordinate_vector coords;
636            CGAL::Triple<
637              std::back_insert_iterator<Point_coordinate_vector>,
638              K::FT, bool> result =
639              CGAL::natural_neighbor_coordinates_2(dt, m,
640                                                   std::back_inserter(coords));
641
[3522]642            float r = 0.0f, g = 0.0f, b = 0.0f, norm = 0.000000000000001f;
[3518]643
644            Point_coordinate_vector::iterator it;
645            for(it = coords.begin(); it != coords.end(); ++it)
646            {
[3520]647                float fx, fy, fr, fg, fb, fs;
[3518]648
[3520]649                fx = (*it).first.x();
650                fy = (*it).first.y();
651
[3518]652                if(fx < 0 || fy < 0 || fx > p->w - 1 || fy > p->h - 1)
653                    continue;
654
[3522]655                int index = lookup[(int)(fx * 2)
656                                    + dw * RANGE_X * 2 * (int)(fy * 2)];
[3518]657
658                get_point(index, &fx, &fy, &fr, &fg, &fb, &fs);
659
[3520]660                //float k = pow((*it).second * (1.0 + fs), 1.2);
661                float k = (*it).second * (1.00f + fs);
662                //float k = (*it).second * (0.60f + fs);
663                //float k = pow((*it).second, (1.0f + fs));
[3518]664
665                r += k * fr;
666                g += k * fg;
667                b += k * fb;
668                norm += k;
669            }
670
671            data[4 * (x + y * p->w) + 0] = r / norm;
672            data[4 * (x + y * p->w) + 1] = g / norm;
673            data[4 * (x + y * p->w) + 2] = b / norm;
674            data[4 * (x + y * p->w) + 3] = 0.0;
675        }
676    }
677
678    pipi_release_pixels(dst, p);
679}
680
681static void analyse(pipi_image_t *src)
682{
683    pipi_pixels_t *p = pipi_get_pixels(src, PIPI_PIXELS_RGBA_F32);
684    float *data = (float *)p->pixels;
685
[3520]686    for(unsigned int dy = 0; dy < dh; dy++)
687        for(unsigned int dx = 0; dx < dw; dx++)
[3518]688        {
689            float min = 1.1f, max = -0.1f;
690            float total = 0.0;
691            int xmin = 0, xmax = 0, ymin = 0, ymax = 0;
692            int npixels = 0;
693
[3520]694            for(unsigned int iy = RANGE_Y * dy; iy < RANGE_Y * (dy + 1); iy++)
695                for(unsigned int ix = RANGE_X * dx; ix < RANGE_X * (dx + 1); ix++)
[3518]696                {
697                    float lum = 0.0f;
698
699                    lum += data[4 * (ix + iy * p->w) + 0];
700                    lum += data[4 * (ix + iy * p->w) + 1];
701                    lum += data[4 * (ix + iy * p->w) + 2];
702
703                    if(lum < min)
704                    {
705                        min = lum;
706                        xmin = ix;
707                        ymin = iy;
708                    }
709
710                    if(lum > max)
711                    {
712                        max = lum;
713                        xmax = ix;
714                        ymax = iy;
715                    }
716
717                    total += lum;
718                    npixels++;
719                }
720
721            total /= npixels;
722
723            float wmin, wmax;
724
725            if(total < min + (max - min) / 4)
726                wmin = 1.0, wmax = 0.0;
727            else if(total < min + (max - min) / 4 * 3)
728                wmin = 0.0, wmax = 0.0;
729            else
730                wmin = 0.0, wmax = 1.0;
731
[3520]732#if 0
733add_random_point();
734add_random_point();
735#else
736#if POINTS_PER_CELL == 1
737            if(total < min + (max - min) / 2)
738            {
739#endif
[3518]740            add_point(xmin, ymin,
741                      data[4 * (xmin + ymin * p->w) + 0],
742                      data[4 * (xmin + ymin * p->w) + 1],
743                      data[4 * (xmin + ymin * p->w) + 2],
744                      wmin);
[3520]745#if POINTS_PER_CELL == 1
746            }
747            else
748            {
749#endif
[3518]750            add_point(xmax, ymax,
751                      data[4 * (xmax + ymax * p->w) + 0],
752                      data[4 * (xmax + ymax * p->w) + 1],
753                      data[4 * (xmax + ymax * p->w) + 2],
754                      wmax);
[3520]755#if POINTS_PER_CELL == 1
756            }
757#endif
758#endif
[3518]759        }
760}
761
[3522]762#define MOREINFO "Try `%s --help' for more information.\n"
763
[3518]764int main(int argc, char *argv[])
765{
[3520]766    int opstats[2 * NB_OPS];
[3521]767    bitstack b;
[3522]768    char const *srcname = NULL, *dstname = NULL;
[3518]769    pipi_image_t *src, *tmp, *dst;
770    double error = 1.0;
771    int width, height, ret = 0;
772
[3522]773    /* Parse command-line options */
774    for(;;)
[3521]775    {
[3522]776        int option_index = 0;
777        static struct myoption long_options[] =
778        {
779            { "output",      1, NULL, 'o' },
780            { "quality",     1, NULL, 'q' },
781            { "debug",       0, NULL, 'd' },
782            { "help",        0, NULL, 'h' },
783            { NULL,          0, NULL, 0   },
784        };
785        int c = mygetopt(argc, argv, "o:q:dh", long_options, &option_index);
786
787        if(c == -1)
788            break;
789
790        switch(c)
791        {
792        case 'o':
793            dstname = myoptarg;
794            break;
795        case 'q':
796            ITERATIONS_PER_POINT = 10 * atoi(myoptarg);
797            if(ITERATIONS_PER_POINT < 0)
798                ITERATIONS_PER_POINT = 0;
799            else if(ITERATIONS_PER_POINT > 10)
800                ITERATIONS_PER_POINT = 10;
801            break;
802        case 'd':
803            DEBUG = true;
804            break;
805        case 'h':
806            printf("Usage: img2twit [OPTIONS] SOURCE\n");
807            printf("       img2twit [OPTIONS] -o DESTINATION\n");
808            printf("Encode SOURCE image to stdout or decode stdin to DESTINATION.\n");
809            printf("\n");
810            printf("Mandatory arguments to long options are mandatory for short options too.\n");
811            printf("  -o, --output <filename>   output resulting image to filename\n");
812            printf("  -q, --quality <rate>      set image quality (0 - 10) (default 5)\n");
813            printf("  -d, --debug               print debug information\n");
814            printf("  -h, --help                display this help and exit\n");
815            printf("\n");
816            printf("Written by Sam Hocevar. Report bugs to <sam@hocevar.net>.\n");
817            return EXIT_SUCCESS;
818        default:
819            fprintf(stderr, "%s: invalid option -- %c\n", argv[0], c);
820            printf(MOREINFO, argv[0]);
821            return EXIT_FAILURE;
822        }
823    }
824
825    if(myoptind == argc && !dstname)
826    {
827        fprintf(stderr, "%s: too few arguments\n", argv[0]);
828        printf(MOREINFO, argv[0]);
[3521]829        return EXIT_FAILURE;
830    }
831
[3522]832    if((myoptind == argc - 1 && dstname) || myoptind < argc - 1)
833    {
834        fprintf(stderr, "%s: too many arguments\n", argv[0]);
835        printf(MOREINFO, argv[0]);
836        return EXIT_FAILURE;
837    }
838
839    if(myoptind == argc - 1)
840        srcname = argv[myoptind];
841
[3521]842    pipi_set_gamma(1.0);
843
844    /* Precompute bit allocation */
845    NUM_CHARACTERS = count_unichars();
[3520]846    TOTAL_BITS = MAX_MSG_LEN * logf(NUM_CHARACTERS) / logf(2);
847    HEADER_BITS = logf(MAX_W * MAX_H) / logf(2);
848    DATA_BITS = TOTAL_BITS - HEADER_BITS;
849#if POINTS_PER_CELL == 1
[3521]850    CELL_BITS = logf(RANGE_SYXRGB) / logf(2);
[3520]851#else
[3521]852    // TODO: implement the following shit
853    //float coord_bits = logf((RANGE_Y * RANGE_X) * (RANGE_Y * RANGE_X + 1) / 2);
854    //float other_bits = logf(RANGE_R * RANGE_G * RANGE_B * RANGE_S);
855    //CELL_BITS = (coord_bits + 2 * other_bits) / logf(2);
856    CELL_BITS = 2 * logf(RANGE_SYXRGB) / logf(2);
[3520]857#endif
[3521]858    TOTAL_CELLS = (int)(DATA_BITS / CELL_BITS);
[3522]859    MAX_ITERATIONS = ITERATIONS_PER_POINT * POINTS_PER_CELL * TOTAL_CELLS;
[3520]860
[3522]861    if(dstname)
[3521]862    {
863        /* Decoding mode: read UTF-8 text from stdin, find each
864         * character's index in our character list, and push it to our
865         * wonderful custom bitstream. */
866        uint32_t data[MAX_MSG_LEN];
867        for(int i = 0; i < MAX_MSG_LEN; i++)
868            data[i] = uni2index(fread_utf8(stdin));
869        for(int i = MAX_MSG_LEN; i--; )
870            b.push(data[i], NUM_CHARACTERS);
[3518]871
[3521]872        /* Read width and height from bitstream */
873        src = NULL;
874        width = b.pop(MAX_W);
875        height = b.pop(MAX_H);
876    }
877    else
878    {
879        /* Argument given: open image for encoding */
[3522]880        src = pipi_load(srcname);
[3521]881
882        if(!src)
883        {
[3522]884            fprintf(stderr, "Error loading %s\n", srcname);
[3521]885            return EXIT_FAILURE;
886        }
887
888        width = pipi_get_image_width(src);
889        height = pipi_get_image_height(src);
890    }
891
[3518]892    /* Compute best w/h ratio */
[3520]893    dw = 1; dh = TOTAL_CELLS;
894    for(unsigned int i = 1; i <= TOTAL_CELLS; i++)
[3518]895    {
[3520]896        int j = TOTAL_CELLS / i;
897
[3518]898        float r = (float)width / (float)height;
[3520]899        float ir = (float)i / (float)j;
900        float dwr = (float)dw / (float)dh;
[3518]901
902        if(fabs(logf(r / ir)) < fabs(logf(r / dwr)))
[3520]903        {
[3518]904            dw = i;
[3520]905            dh = TOTAL_CELLS / dw;
906        }
[3518]907    }
[3520]908    while((dh + 1) * dw <= TOTAL_CELLS) dh++;
909    while(dw * (dh + 1) <= TOTAL_CELLS) dw++;
[3521]910
911    /* Print debug information */
[3522]912    if(DEBUG)
913    {
914        fprintf(stderr, "Maximum message size: %i\n", MAX_MSG_LEN);
915        fprintf(stderr, "Available characters: %i\n", NUM_CHARACTERS);
916        fprintf(stderr, "Available bits: %f\n", TOTAL_BITS);
917        fprintf(stderr, "Maximum image resolution: %ix%i\n", MAX_W, MAX_H);
918        fprintf(stderr, "Image resolution: %ix%i\n", width, height);
919        fprintf(stderr, "Header bits: %f\n", HEADER_BITS);
920        fprintf(stderr, "Bits available for data: %f\n", DATA_BITS);
921        fprintf(stderr, "Cell bits: %f\n", CELL_BITS);
922        fprintf(stderr, "Available cells: %i\n", TOTAL_CELLS);
923        fprintf(stderr, "Wasted bits: %f\n",
924                DATA_BITS - CELL_BITS * TOTAL_CELLS);
925        fprintf(stderr, "Chosen image ratio: %i:%i (wasting %i point cells)\n",
926                dw, dh, TOTAL_CELLS - dw * dh);
927        fprintf(stderr, "Total wasted bits: %f\n",
928                DATA_BITS - CELL_BITS * dw * dh);
929    }
[3521]930
[3522]931    if(srcname)
[3521]932    {
933        /* Resize and filter image to better state */
934        tmp = pipi_resize(src, dw * RANGE_X, dh * RANGE_Y);
935        pipi_free(src);
936        src = pipi_median_ext(tmp, 1, 1);
937        pipi_free(tmp);
[3522]938pipi_save(src, "lol.bmp");
[3518]939
[3521]940        /* Analyse image */
941        analyse(src);
[3518]942
[3521]943        /* Render what we just computed */
944        tmp = pipi_new(dw * RANGE_X, dh * RANGE_Y);
945        render(tmp, 0, 0, dw * RANGE_X, dh * RANGE_Y);
[3522]946pipi_save(tmp, "lol2.bmp");
[3521]947        error = pipi_measure_rmsd(src, tmp);
[3518]948
[3522]949        if(DEBUG)
950            fprintf(stderr, "Initial distance: %2.10g\n", error);
[3518]951
[3521]952        memset(opstats, 0, sizeof(opstats));
953        for(int iter = 0, stuck = 0, failures = 0, success = 0;
954            iter < MAX_ITERATIONS /* && stuck < 5 && */;
955            iter++)
[3520]956        {
[3521]957            if(failures > 500)
958            {
959                stuck++;
960                failures = 0;
961            }
[3520]962
[3522]963            if(!DEBUG && !(iter % 16))
[3521]964                fprintf(stderr, "\rEncoding... %i%%",
965                        iter * 100 / MAX_ITERATIONS);
[3518]966
[3521]967            pipi_image_t *scrap = pipi_copy(tmp);
[3518]968
[3521]969            /* Choose a point at random */
970            int pt = det_rand(npoints);
971            uint32_t oldval = points[pt];
[3518]972
[3521]973            /* Compute the affected image zone */
974            float fx, fy, fr, fg, fb, fs;
975            get_point(pt, &fx, &fy, &fr, &fg, &fb, &fs);
976            int zonex = (int)fx / RANGE_X - 1;
977            int zoney = (int)fy / RANGE_Y - 1;
978            int zonew = 3;
979            int zoneh = 3;
980            if(zonex < 0) { zonex = 0; zonew--; }
981            if(zoney < 0) { zoney = 0; zoneh--; }
982            if(zonex + zonew >= (int)dw) { zonew--; }
983            if(zoney + zoneh >= (int)dh) { zoneh--; }
[3518]984
[3521]985            /* Choose random operations and measure their effect */
986            uint8_t op1 = rand_op();
987            //uint8_t op2 = rand_op();
[3520]988
[3521]989            uint32_t candidates[3];
990            double besterr = error + 1.0;
991            int bestop = -1;
992            candidates[0] = apply_op(op1, oldval);
993            //candidates[1] = apply_op(op2, oldval);
994            //candidates[2] = apply_op(op1, apply_op(op2, oldval));
[3520]995
[3521]996            for(int i = 0; i < 1; i++)
997            //for(int i = 0; i < 3; i++)
998            {
999                if(oldval == candidates[i])
1000                    continue;
[3520]1001
[3521]1002                points[pt] = candidates[i];
[3520]1003
[3521]1004                render(scrap, zonex * RANGE_X, zoney * RANGE_Y,
1005                       zonew * RANGE_X, zoneh * RANGE_Y);
1006
1007                double newerr = pipi_measure_rmsd(src, scrap);
1008                if(newerr < besterr)
1009                {
1010                    besterr = newerr;
1011                    bestop = i;
1012                }
1013            }
1014
1015            opstats[op1 * 2]++;
1016            //opstats[op2 * 2]++;
1017
1018            if(besterr < error)
[3520]1019            {
[3521]1020                points[pt] = candidates[bestop];
1021                /* Redraw image if the last check wasn't the best one */
1022                if(bestop != 2)
1023                    render(scrap, zonex * RANGE_X, zoney * RANGE_Y,
1024                           zonew * RANGE_X, zoneh * RANGE_Y);
1025
1026                pipi_free(tmp);
1027                tmp = scrap;
[3522]1028
1029                if(DEBUG)
1030                    fprintf(stderr, "%08i -.%08i %2.010g after op%i(%i)\n",
1031                            iter, (int)((error - besterr) * 100000000), error,
1032                            op1, pt);
1033
[3521]1034                error = besterr;
1035                opstats[op1 * 2 + 1]++;
1036                //opstats[op2 * 2 + 1]++;
1037                failures = 0;
1038                success++;
1039
1040                /* Save image! */
1041                //char buf[128];
1042                //sprintf(buf, "twit%08i.bmp", success);
1043                //if((success % 10) == 0)
1044                //    pipi_save(tmp, buf);
[3520]1045            }
[3521]1046            else
1047            {
1048                pipi_free(scrap);
1049                points[pt] = oldval;
1050                failures++;
1051            }
[3520]1052        }
1053
[3522]1054        if(DEBUG)
1055        {
1056            for(int j = 0; j < 2; j++)
1057            {
1058                fprintf(stderr,   "operation: ");
1059                for(int i = NB_OPS / 2 * j; i < NB_OPS / 2 * (j + 1); i++)
1060                    fprintf(stderr, "%4i ", i);
1061                fprintf(stderr, "\nattempts:  ");
1062                for(int i = NB_OPS / 2 * j; i < NB_OPS / 2 * (j + 1); i++)
1063                    fprintf(stderr, "%4i ", opstats[i * 2]);
1064                fprintf(stderr, "\nsuccesses: ");
1065                for(int i = NB_OPS / 2 * j; i < NB_OPS / 2 * (j + 1); i++)
1066                    fprintf(stderr, "%4i ", opstats[i * 2 + 1]);
1067                fprintf(stderr, "\n");
1068            }
[3520]1069
[3522]1070            fprintf(stderr, "Distance: %2.10g\n", error);
[3521]1071        }
[3522]1072        else
1073            fprintf(stderr, "\r                    \r");
[3520]1074
[3521]1075#if 0
1076        dst = pipi_resize(tmp, width, height);
1077        pipi_free(tmp);
1078
1079        /* Save image and bail out */
1080        pipi_save(dst, "lol.bmp");
1081        pipi_free(dst);
1082#endif
1083
1084        /* Push our points to the bitstream */
1085        for(int i = 0; i < npoints; i++)
1086            b.push(points[i], RANGE_SYXRGB);
1087        b.push(height, MAX_H);
1088        b.push(width, MAX_W);
1089
1090        /* Pop Unicode characters from the bitstream and print them */
1091        for(int i = 0; i < MAX_MSG_LEN; i++)
1092            fwrite_utf8(stdout, index2uni(b.pop(NUM_CHARACTERS)));
1093        fprintf(stdout, "\n");
1094    }
1095    else
1096    {
1097        /* Pop points from the bitstream */
1098        for(int i = dw * dh; i--; )
[3518]1099        {
[3521]1100#if POINTS_PER_CELL == 2
1101            points[i * 2 + 1] = b.pop(RANGE_SYXRGB);
1102            points[i * 2] = b.pop(RANGE_SYXRGB);
1103#else
1104            points[i] = b.pop(RANGE_SYXRGB);
1105#endif
[3518]1106        }
[3521]1107        npoints = dw * dh * POINTS_PER_CELL;
[3518]1108
[3521]1109        /* Render these points to a new image */
1110        tmp = pipi_new(dw * RANGE_X, dh * RANGE_Y);
1111        render(tmp, 0, 0, dw * RANGE_X, dh * RANGE_Y);
[3518]1112
[3521]1113        /* TODO: render directly to the final image; scaling sucks */
1114        dst = pipi_resize(tmp, width, height);
1115        pipi_free(tmp);
[3518]1116
[3521]1117        /* Save image and bail out */
[3522]1118        pipi_save(dst, dstname);
[3521]1119        pipi_free(dst);
1120    }
[3518]1121
1122    return ret;
1123}
1124
Note: See TracBrowser for help on using the repository browser.