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

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

Add proper Unicode handling to img2twit. This includes an UTF-8 encoder/decoder
and a special bit stack that can handle arbitrary bases within its stream. The
image encoder and decoder are now separate code paths.

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