You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1036 lines
29 KiB

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