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.
 
 
 
 
 
 

1236 line
36 KiB

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