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.
 
 
 
 
 
 

1247 lines
37 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, bool final = false)
  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. if(final)
  389. {
  390. *b = int2fullrange(pt % RANGE_R, RANGE_R); pt /= RANGE_R;
  391. *g = int2fullrange(pt % RANGE_G, RANGE_G); pt /= RANGE_G;
  392. *r = int2fullrange(pt % RANGE_B, RANGE_B); pt /= RANGE_B;
  393. }
  394. else
  395. {
  396. *b = int2midrange(pt % RANGE_R, RANGE_R); pt /= RANGE_R;
  397. *g = int2midrange(pt % RANGE_G, RANGE_G); pt /= RANGE_G;
  398. *r = int2midrange(pt % RANGE_B, RANGE_B); pt /= RANGE_B;
  399. }
  400. }
  401. static void add_point(float x, float y, float r, float g, float b, float s)
  402. {
  403. set_point(npoints, x, y, r, g, b, s);
  404. npoints++;
  405. }
  406. #if 0
  407. static void add_random_point()
  408. {
  409. points[npoints] = det_rand(RANGE_SYXRGB);
  410. npoints++;
  411. }
  412. #endif
  413. #define NB_OPS 20
  414. static uint8_t rand_op(void)
  415. {
  416. uint8_t x = det_rand(NB_OPS);
  417. /* Randomly ignore statistically less efficient ops */
  418. if(x == 0)
  419. return rand_op();
  420. if(x == 1 && (RANGE_S == 1 || det_rand(2)))
  421. return rand_op();
  422. if(x <= 5 && det_rand(2))
  423. return rand_op();
  424. //if((x < 10 || x > 15) && !det_rand(4)) /* Favour colour changes */
  425. // return rand_op();
  426. return x;
  427. }
  428. static uint32_t apply_op(uint8_t op, uint32_t val)
  429. {
  430. uint32_t rem, ext;
  431. switch(op)
  432. {
  433. case 0: /* Flip strength value */
  434. case 1:
  435. /* Statistics show that this helps often, but does not reduce
  436. * the error significantly. */
  437. return val ^ 1;
  438. case 2: /* Move up; if impossible, down */
  439. rem = val % RANGE_S;
  440. ext = (val / RANGE_S) % RANGE_Y;
  441. ext = ext > 0 ? ext - 1 : ext + 1;
  442. return (val / RANGE_SY * RANGE_Y + ext) * RANGE_S + rem;
  443. case 3: /* Move down; if impossible, up */
  444. rem = val % RANGE_S;
  445. ext = (val / RANGE_S) % RANGE_Y;
  446. ext = ext < RANGE_Y - 1 ? ext + 1 : ext - 1;
  447. return (val / RANGE_SY * RANGE_Y + ext) * RANGE_S + rem;
  448. case 4: /* Move left; if impossible, right */
  449. rem = val % RANGE_SY;
  450. ext = (val / RANGE_SY) % RANGE_X;
  451. ext = ext > 0 ? ext - 1 : ext + 1;
  452. return (val / RANGE_SYX * RANGE_X + ext) * RANGE_SY + rem;
  453. case 5: /* Move left; if impossible, right */
  454. rem = val % RANGE_SY;
  455. ext = (val / RANGE_SY) % RANGE_X;
  456. ext = ext < RANGE_X - 1 ? ext + 1 : ext - 1;
  457. return (val / RANGE_SYX * RANGE_X + ext) * RANGE_SY + rem;
  458. case 6: /* Corner 1 */
  459. return apply_op(2, apply_op(4, val));
  460. case 7: /* Corner 2 */
  461. return apply_op(2, apply_op(5, val));
  462. case 8: /* Corner 3 */
  463. return apply_op(3, apply_op(5, val));
  464. case 9: /* Corner 4 */
  465. return apply_op(3, apply_op(4, val));
  466. case 16: /* Double up */
  467. return apply_op(2, apply_op(2, val));
  468. case 17: /* Double down */
  469. return apply_op(3, apply_op(3, val));
  470. case 18: /* Double left */
  471. return apply_op(4, apply_op(4, val));
  472. case 19: /* Double right */
  473. return apply_op(5, apply_op(5, val));
  474. case 10: /* R-- (or R++) */
  475. rem = val % RANGE_SYX;
  476. ext = (val / RANGE_SYX) % RANGE_R;
  477. ext = ext > 0 ? ext - 1 : ext + 1;
  478. return (val / RANGE_SYXR * RANGE_R + ext) * RANGE_SYX + rem;
  479. case 11: /* R++ (or R--) */
  480. rem = val % RANGE_SYX;
  481. ext = (val / RANGE_SYX) % RANGE_R;
  482. ext = ext < RANGE_R - 1 ? ext + 1 : ext - 1;
  483. return (val / RANGE_SYXR * RANGE_R + ext) * RANGE_SYX + rem;
  484. case 12: /* G-- (or G++) */
  485. rem = val % RANGE_SYXR;
  486. ext = (val / RANGE_SYXR) % RANGE_G;
  487. ext = ext > 0 ? ext - 1 : ext + 1;
  488. return (val / RANGE_SYXRG * RANGE_G + ext) * RANGE_SYXR + rem;
  489. case 13: /* G++ (or G--) */
  490. rem = val % RANGE_SYXR;
  491. ext = (val / RANGE_SYXR) % RANGE_G;
  492. ext = ext < RANGE_G - 1 ? ext + 1 : ext - 1;
  493. return (val / RANGE_SYXRG * RANGE_G + ext) * RANGE_SYXR + rem;
  494. case 14: /* B-- (or B++) */
  495. rem = val % RANGE_SYXRG;
  496. ext = (val / RANGE_SYXRG) % RANGE_B;
  497. ext = ext > 0 ? ext - 1 : ext + 1;
  498. return ext * RANGE_SYXRG + rem;
  499. case 15: /* B++ (or B--) */
  500. rem = val % RANGE_SYXRG;
  501. ext = (val / RANGE_SYXRG) % RANGE_B;
  502. ext = ext < RANGE_B - 1 ? ext + 1 : ext - 1;
  503. return ext * RANGE_SYXRG + rem;
  504. #if 0
  505. case 15: /* Brightness-- */
  506. return apply_op(9, apply_op(11, apply_op(13, val)));
  507. case 16: /* Brightness++ */
  508. return apply_op(10, apply_op(12, apply_op(14, val)));
  509. case 17: /* RG-- */
  510. return apply_op(9, apply_op(11, val));
  511. case 18: /* RG++ */
  512. return apply_op(10, apply_op(12, val));
  513. case 19: /* GB-- */
  514. return apply_op(11, apply_op(13, val));
  515. case 20: /* GB++ */
  516. return apply_op(12, apply_op(14, val));
  517. case 21: /* RB-- */
  518. return apply_op(9, apply_op(13, val));
  519. case 22: /* RB++ */
  520. return apply_op(10, apply_op(14, val));
  521. #endif
  522. default:
  523. return val;
  524. }
  525. }
  526. static void render(pipi_image_t *dst,
  527. int rx, int ry, int rw, int rh, bool final)
  528. {
  529. int lookup[dw * RANGE_X * 2 * dh * RANGE_Y * 2];
  530. pipi_pixels_t *p = pipi_get_pixels(dst, PIPI_PIXELS_RGBA_F32);
  531. float *data = (float *)p->pixels;
  532. int x, y;
  533. memset(lookup, 0, sizeof(lookup));
  534. dt.clear();
  535. for(int i = 0; i < npoints; i++)
  536. {
  537. float fx, fy, fr, fg, fb, fs;
  538. get_point(i, &fx, &fy, &fr, &fg, &fb, &fs);
  539. dt.insert(K::Point_2(fx + dw * RANGE_X, fy + dh * RANGE_Y));
  540. /* Keep link to point */
  541. lookup[(int)(fx * 2) + dw * RANGE_X * 2 * (int)(fy * 2)] = i;
  542. }
  543. /* Add fake points to close the triangulation */
  544. dt.insert(K::Point_2(0, 0));
  545. dt.insert(K::Point_2(3 * dw * RANGE_X, 0));
  546. dt.insert(K::Point_2(0, 3 * dh * RANGE_Y));
  547. dt.insert(K::Point_2(3 * dw * RANGE_X, 3 * dh * RANGE_Y));
  548. for(y = ry; y < ry + rh; y++)
  549. {
  550. for(x = rx; x < rx + rw; x++)
  551. {
  552. float myx = (float)x * dw * RANGE_X / p->w;
  553. float myy = (float)y * dh * RANGE_Y / p->h;
  554. K::Point_2 m(myx + dw * RANGE_X, myy + dh * RANGE_Y);
  555. Point_coordinate_vector coords;
  556. CGAL::Triple<
  557. std::back_insert_iterator<Point_coordinate_vector>,
  558. K::FT, bool> result =
  559. CGAL::natural_neighbor_coordinates_2(dt, m,
  560. std::back_inserter(coords));
  561. float r = 0.0f, g = 0.0f, b = 0.0f, norm = 0.000000000000001f;
  562. Point_coordinate_vector::iterator it;
  563. for(it = coords.begin(); it != coords.end(); ++it)
  564. {
  565. float fx, fy, fr, fg, fb, fs;
  566. fx = (*it).first.x() - dw * RANGE_X;
  567. fy = (*it).first.y() - dh * RANGE_Y;
  568. if(fx < 0 || fy < 0
  569. || fx > dw * RANGE_X - 1 || fy > dh * RANGE_Y - 1)
  570. continue;
  571. int index = lookup[(int)(fx * 2)
  572. + dw * RANGE_X * 2 * (int)(fy * 2)];
  573. get_point(index, &fx, &fy, &fr, &fg, &fb, &fs, final);
  574. //float k = pow((*it).second * (1.0 + fs), 1.2);
  575. float k = (*it).second * (1.00f + fs);
  576. //float k = (*it).second * (0.60f + fs);
  577. //float k = pow((*it).second, (1.0f + fs));
  578. // Try to attenuate peak artifacts
  579. //k /= (0.1 * (RANGE_X * RANGE_X + RANGE_Y * RANGE_Y)
  580. // + (myx - fx) * (myx - fx) + (myy - fy) * (myy - fy));
  581. // Cute circles
  582. //k = 1.0 / (0.015 * (RANGE_X * RANGE_X + RANGE_Y * RANGE_Y)
  583. // + (myx - fx) * (myx - fx) + (myy - fy) * (myy - fy));
  584. r += k * fr;
  585. g += k * fg;
  586. b += k * fb;
  587. norm += k;
  588. }
  589. data[4 * (x + y * p->w) + 0] = r / norm;
  590. data[4 * (x + y * p->w) + 1] = g / norm;
  591. data[4 * (x + y * p->w) + 2] = b / norm;
  592. data[4 * (x + y * p->w) + 3] = 0.0;
  593. }
  594. }
  595. pipi_release_pixels(dst, p);
  596. }
  597. static void analyse(pipi_image_t *src)
  598. {
  599. pipi_pixels_t *p = pipi_get_pixels(src, PIPI_PIXELS_RGBA_F32);
  600. float *data = (float *)p->pixels;
  601. for(unsigned int dy = 0; dy < dh; dy++)
  602. for(unsigned int dx = 0; dx < dw; dx++)
  603. {
  604. float min = 1.1f, max = -0.1f, mr = 0.0f, mg = 0.0f, mb = 0.0f;
  605. float total = 0.0;
  606. int xmin = 0, xmax = 0, ymin = 0, ymax = 0;
  607. int npixels = 0;
  608. for(unsigned int iy = RANGE_Y * dy; iy < RANGE_Y * (dy + 1); iy++)
  609. for(unsigned int ix = RANGE_X * dx; ix < RANGE_X * (dx + 1); ix++)
  610. {
  611. float lum = 0.0f;
  612. lum += data[4 * (ix + iy * p->w) + 0];
  613. lum += data[4 * (ix + iy * p->w) + 1];
  614. lum += data[4 * (ix + iy * p->w) + 2];
  615. lum /= 3;
  616. mr += data[4 * (ix + iy * p->w) + 0];
  617. mg += data[4 * (ix + iy * p->w) + 1];
  618. mb += data[4 * (ix + iy * p->w) + 2];
  619. if(lum < min)
  620. {
  621. min = lum;
  622. xmin = ix;
  623. ymin = iy;
  624. }
  625. if(lum > max)
  626. {
  627. max = lum;
  628. xmax = ix;
  629. ymax = iy;
  630. }
  631. total += lum;
  632. npixels++;
  633. }
  634. total /= npixels;
  635. mr /= npixels;
  636. mg /= npixels;
  637. mb /= npixels;
  638. float wmin, wmax;
  639. if(total < min + (max - min) / 4)
  640. wmin = 1.0, wmax = 0.0;
  641. else if(total < min + (max - min) / 4 * 3)
  642. wmin = 0.0, wmax = 0.0;
  643. else
  644. wmin = 0.0, wmax = 1.0;
  645. #if 0
  646. add_random_point();
  647. add_random_point();
  648. #else
  649. /* 0.80 and 0.20 were chosen empirically, it gives a 10% better
  650. * initial distance. Definitely worth it. */
  651. #if POINTS_PER_CELL == 1
  652. if(total < min + (max - min) / 2)
  653. {
  654. #endif
  655. add_point(xmin, ymin,
  656. data[4 * (xmin + ymin * p->w) + 0] * 0.80 + mr * 0.20,
  657. data[4 * (xmin + ymin * p->w) + 1] * 0.80 + mg * 0.20,
  658. data[4 * (xmin + ymin * p->w) + 2] * 0.80 + mb * 0.20,
  659. wmin);
  660. #if POINTS_PER_CELL == 1
  661. }
  662. else
  663. {
  664. #endif
  665. add_point(xmax, ymax,
  666. data[4 * (xmax + ymax * p->w) + 0] * 0.80 + mr * 0.20,
  667. data[4 * (xmax + ymax * p->w) + 1] * 0.80 + mg * 0.20,
  668. data[4 * (xmax + ymax * p->w) + 2] * 0.80 + mb * 0.20,
  669. wmax);
  670. #if POINTS_PER_CELL == 1
  671. }
  672. #endif
  673. #endif
  674. }
  675. }
  676. #define MOREINFO "Try `%s --help' for more information.\n"
  677. int main(int argc, char *argv[])
  678. {
  679. uint32_t unicode_data[2048];
  680. int opstats[2 * NB_OPS];
  681. char const *srcname = NULL, *dstname = NULL;
  682. pipi_image_t *src, *tmp, *dst;
  683. double error = 1.0;
  684. int width, height;
  685. /* Parse command-line options */
  686. for(;;)
  687. {
  688. int option_index = 0;
  689. static struct myoption long_options[] =
  690. {
  691. { "output", 1, NULL, 'o' },
  692. { "length", 1, NULL, 'l' },
  693. { "charset", 1, NULL, 'c' },
  694. { "quality", 1, NULL, 'q' },
  695. { "debug", 0, NULL, 'd' },
  696. { "help", 0, NULL, 'h' },
  697. { NULL, 0, NULL, 0 },
  698. };
  699. int c = mygetopt(argc, argv, "o:l:c:q:dh", long_options, &option_index);
  700. if(c == -1)
  701. break;
  702. switch(c)
  703. {
  704. case 'o':
  705. dstname = myoptarg;
  706. break;
  707. case 'l':
  708. MAX_MSG_LEN = atoi(myoptarg);
  709. if(MAX_MSG_LEN < 16)
  710. {
  711. fprintf(stderr, "Warning: rounding minimum message length to 16\n");
  712. MAX_MSG_LEN = 16;
  713. }
  714. break;
  715. case 'c':
  716. if(!strcmp(myoptarg, "ascii"))
  717. unichars = unichars_ascii;
  718. else if(!strcmp(myoptarg, "cjk"))
  719. unichars = unichars_cjk;
  720. else if(!strcmp(myoptarg, "symbols"))
  721. unichars = unichars_symbols;
  722. else
  723. {
  724. fprintf(stderr, "Error: invalid char block \"%s\".", myoptarg);
  725. fprintf(stderr, "Valid sets are: ascii, cjk, symbols\n");
  726. return EXIT_FAILURE;
  727. }
  728. break;
  729. case 'q':
  730. ITERATIONS_PER_POINT = 10 * atof(myoptarg);
  731. if(ITERATIONS_PER_POINT < 0)
  732. ITERATIONS_PER_POINT = 0;
  733. else if(ITERATIONS_PER_POINT > 100)
  734. ITERATIONS_PER_POINT = 100;
  735. break;
  736. case 'd':
  737. DEBUG_MODE = true;
  738. break;
  739. case 'h':
  740. printf("Usage: img2twit [OPTIONS] SOURCE\n");
  741. printf(" img2twit [OPTIONS] -o DESTINATION\n");
  742. printf("Encode SOURCE image to stdout or decode stdin to DESTINATION.\n");
  743. printf("\n");
  744. printf("Mandatory arguments to long options are mandatory for short options too.\n");
  745. printf(" -o, --output <filename> output resulting image to filename\n");
  746. printf(" -l, --length <size> message length in characters (default 140)\n");
  747. printf(" -c, --charset <block> character set to use (ascii, [cjk], symbols)\n");
  748. printf(" -q, --quality <rate> set image quality (0 - 10) (default 5)\n");
  749. printf(" -d, --debug print debug information\n");
  750. printf(" -h, --help display this help and exit\n");
  751. printf("\n");
  752. printf("Written by Sam Hocevar. Report bugs to <sam@hocevar.net>.\n");
  753. return EXIT_SUCCESS;
  754. default:
  755. fprintf(stderr, "%s: invalid option -- %c\n", argv[0], c);
  756. printf(MOREINFO, argv[0]);
  757. return EXIT_FAILURE;
  758. }
  759. }
  760. if(myoptind == argc && !dstname)
  761. {
  762. fprintf(stderr, "%s: too few arguments\n", argv[0]);
  763. printf(MOREINFO, argv[0]);
  764. return EXIT_FAILURE;
  765. }
  766. if((myoptind == argc - 1 && dstname) || myoptind < argc - 1)
  767. {
  768. fprintf(stderr, "%s: too many arguments\n", argv[0]);
  769. printf(MOREINFO, argv[0]);
  770. return EXIT_FAILURE;
  771. }
  772. if(myoptind == argc - 1)
  773. srcname = argv[myoptind];
  774. /* Decoding mode: read UTF-8 text from stdin */
  775. if(dstname)
  776. for(MAX_MSG_LEN = 0; ;)
  777. {
  778. uint32_t ch = fread_utf8(stdin);
  779. if(ch == 0xffffffff || ch == '\n')
  780. break;
  781. if(ch <= ' ')
  782. continue;
  783. unicode_data[MAX_MSG_LEN++] = ch;
  784. if(MAX_MSG_LEN >= 2048)
  785. {
  786. fprintf(stderr, "Error: message too long.\n");
  787. return EXIT_FAILURE;
  788. }
  789. }
  790. if(MAX_MSG_LEN == 0)
  791. {
  792. fprintf(stderr, "Error: empty message.\n");
  793. return EXIT_FAILURE;
  794. }
  795. /* Autodetect charset if decoding, otherwise switch to CJK. */
  796. if(dstname)
  797. {
  798. char const *charset;
  799. if(unicode_data[0] >= 0x0021 && unicode_data[0] < 0x007f)
  800. {
  801. unichars = unichars_ascii;
  802. charset = "ascii";
  803. }
  804. else if(unicode_data[0] >= 0x4e00 && unicode_data[0] < 0x9fa6)
  805. {
  806. unichars = unichars_cjk;
  807. charset = "cjk";
  808. }
  809. else if(unicode_data[0] >= 0x25a0 && unicode_data[0] < 0x27bf)
  810. {
  811. unichars = unichars_symbols;
  812. charset = "symbols";
  813. }
  814. else
  815. {
  816. fprintf(stderr, "Error: unable to detect charset\n");
  817. return EXIT_FAILURE;
  818. }
  819. if(DEBUG_MODE)
  820. fprintf(stderr, "Detected charset \"%s\"\n", charset);
  821. }
  822. else if(!unichars)
  823. unichars = unichars_cjk;
  824. pipi_set_gamma(1.0);
  825. /* Precompute bit allocation */
  826. NUM_CHARACTERS = count_unichars();
  827. TOTAL_BITS = MAX_MSG_LEN * logf(NUM_CHARACTERS) / logf(2);
  828. HEADER_BITS = logf(MAX_W * MAX_H) / logf(2);
  829. DATA_BITS = TOTAL_BITS - HEADER_BITS;
  830. #if POINTS_PER_CELL == 1
  831. CELL_BITS = logf(RANGE_SYXRGB) / logf(2);
  832. #else
  833. // TODO: implement the following shit
  834. //float coord_bits = logf((RANGE_Y * RANGE_X) * (RANGE_Y * RANGE_X + 1) / 2);
  835. //float other_bits = logf(RANGE_R * RANGE_G * RANGE_B * RANGE_S);
  836. //CELL_BITS = (coord_bits + 2 * other_bits) / logf(2);
  837. CELL_BITS = 2 * logf(RANGE_SYXRGB) / logf(2);
  838. #endif
  839. TOTAL_CELLS = (int)(DATA_BITS / CELL_BITS);
  840. MAX_ITERATIONS = ITERATIONS_PER_POINT * POINTS_PER_CELL * TOTAL_CELLS;
  841. bitstack b(MAX_MSG_LEN); /* We cannot declare this before, because
  842. * MAX_MSG_LEN wouldn't be defined. */
  843. if(dstname)
  844. {
  845. /* Decoding mode: find each character's index in our character
  846. * list, and push it to our wonderful custom bitstream. */
  847. for(int i = MAX_MSG_LEN; i--; )
  848. b.push(uni2index(unicode_data[i]), NUM_CHARACTERS);
  849. /* Read width and height from bitstream */
  850. src = NULL;
  851. width = b.pop(MAX_W);
  852. height = b.pop(MAX_H);
  853. }
  854. else
  855. {
  856. /* Argument given: open image for encoding */
  857. src = pipi_load(srcname);
  858. if(!src)
  859. {
  860. fprintf(stderr, "Error loading %s\n", srcname);
  861. return EXIT_FAILURE;
  862. }
  863. width = pipi_get_image_width(src);
  864. height = pipi_get_image_height(src);
  865. }
  866. /* Compute "best" w/h ratio */
  867. dw = 1; dh = TOTAL_CELLS;
  868. for(unsigned int i = 1; i <= TOTAL_CELLS; i++)
  869. {
  870. int j = TOTAL_CELLS / i;
  871. float r = (float)width / (float)height;
  872. float ir = (float)i / (float)j;
  873. float dwr = (float)dw / (float)dh;
  874. if(fabs(logf(r / ir)) < fabs(logf(r / dwr)))
  875. {
  876. dw = i;
  877. dh = TOTAL_CELLS / dw;
  878. }
  879. }
  880. while((dh + 1) * dw <= TOTAL_CELLS) dh++;
  881. while(dh * (dw + 1) <= TOTAL_CELLS) dw++;
  882. /* Print debug information */
  883. if(DEBUG_MODE)
  884. {
  885. fprintf(stderr, "Message size: %i\n", MAX_MSG_LEN);
  886. fprintf(stderr, "Available characters: %i\n", NUM_CHARACTERS);
  887. fprintf(stderr, "Available bits: %f\n", TOTAL_BITS);
  888. fprintf(stderr, "Maximum image resolution: %ix%i\n", MAX_W, MAX_H);
  889. fprintf(stderr, "Image resolution: %ix%i\n", width, height);
  890. fprintf(stderr, "Header bits: %f\n", HEADER_BITS);
  891. fprintf(stderr, "Bits available for data: %f\n", DATA_BITS);
  892. fprintf(stderr, "Cell bits: %f\n", CELL_BITS);
  893. fprintf(stderr, "Available cells: %i\n", TOTAL_CELLS);
  894. fprintf(stderr, "Wasted bits: %f\n",
  895. DATA_BITS - CELL_BITS * TOTAL_CELLS);
  896. fprintf(stderr, "Chosen image ratio: %i:%i (wasting %i point cells)\n",
  897. dw, dh, TOTAL_CELLS - dw * dh);
  898. fprintf(stderr, "Total wasted bits: %f\n",
  899. DATA_BITS - CELL_BITS * dw * dh);
  900. }
  901. if(srcname)
  902. {
  903. /* Resize and filter image to better state */
  904. tmp = pipi_resize(src, dw * RANGE_X, dh * RANGE_Y);
  905. pipi_free(src);
  906. src = pipi_median_ext(tmp, 1, 1);
  907. pipi_free(tmp);
  908. /* Analyse image */
  909. analyse(src);
  910. /* Render what we just computed */
  911. tmp = pipi_new(dw * RANGE_X, dh * RANGE_Y);
  912. render(tmp, 0, 0, dw * RANGE_X, dh * RANGE_Y, false);
  913. error = pipi_measure_rmsd(src, tmp);
  914. if(DEBUG_MODE)
  915. fprintf(stderr, "Initial distance: %2.10g\n", error);
  916. memset(opstats, 0, sizeof(opstats));
  917. for(int iter = 0, stuck = 0, failures = 0, success = 0;
  918. iter < MAX_ITERATIONS /* && stuck < 5 && */;
  919. iter++)
  920. {
  921. if(failures > 500)
  922. {
  923. stuck++;
  924. failures = 0;
  925. }
  926. if(!DEBUG_MODE && !(iter % 16))
  927. fprintf(stderr, "\rEncoding... %i%%",
  928. iter * 100 / MAX_ITERATIONS);
  929. pipi_image_t *scrap = pipi_copy(tmp);
  930. /* Choose a point at random */
  931. int pt = det_rand(npoints);
  932. uint32_t oldval = points[pt];
  933. /* Compute the affected image zone */
  934. float fx, fy, fr, fg, fb, fs;
  935. get_point(pt, &fx, &fy, &fr, &fg, &fb, &fs);
  936. int zonex = (int)fx / RANGE_X - 1;
  937. int zoney = (int)fy / RANGE_Y - 1;
  938. int zonew = 3;
  939. int zoneh = 3;
  940. if(zonex < 0) { zonex = 0; zonew--; }
  941. if(zoney < 0) { zoney = 0; zoneh--; }
  942. if(zonex + zonew >= (int)dw) { zonew--; }
  943. if(zoney + zoneh >= (int)dh) { zoneh--; }
  944. /* Choose random operations and measure their effect */
  945. uint8_t op1 = rand_op();
  946. //uint8_t op2 = rand_op();
  947. uint32_t candidates[3];
  948. double besterr = error + 1.0;
  949. int bestop = -1;
  950. candidates[0] = apply_op(op1, oldval);
  951. //candidates[1] = apply_op(op2, oldval);
  952. //candidates[2] = apply_op(op1, apply_op(op2, oldval));
  953. for(int i = 0; i < 1; i++)
  954. //for(int i = 0; i < 3; i++)
  955. {
  956. if(oldval == candidates[i])
  957. continue;
  958. points[pt] = candidates[i];
  959. render(scrap, zonex * RANGE_X, zoney * RANGE_Y,
  960. zonew * RANGE_X, zoneh * RANGE_Y, false);
  961. double newerr = pipi_measure_rmsd(src, scrap);
  962. if(newerr < besterr)
  963. {
  964. besterr = newerr;
  965. bestop = i;
  966. }
  967. }
  968. opstats[op1 * 2]++;
  969. //opstats[op2 * 2]++;
  970. if(besterr < error)
  971. {
  972. points[pt] = candidates[bestop];
  973. /* Redraw image if the last check wasn't the best one */
  974. if(bestop != 0)
  975. render(scrap, zonex * RANGE_X, zoney * RANGE_Y,
  976. zonew * RANGE_X, zoneh * RANGE_Y, false);
  977. pipi_free(tmp);
  978. tmp = scrap;
  979. if(DEBUG_MODE)
  980. fprintf(stderr, "%08i -.%08i %2.010g after op%i(%i)\n",
  981. iter, (int)((error - besterr) * 100000000), error,
  982. op1, pt);
  983. error = besterr;
  984. opstats[op1 * 2 + 1]++;
  985. //opstats[op2 * 2 + 1]++;
  986. failures = 0;
  987. success++;
  988. /* Save image! */
  989. //char buf[128];
  990. //sprintf(buf, "twit%08i.bmp", success);
  991. //if((success % 10) == 0)
  992. // pipi_save(tmp, buf);
  993. }
  994. else
  995. {
  996. pipi_free(scrap);
  997. points[pt] = oldval;
  998. failures++;
  999. }
  1000. }
  1001. if(DEBUG_MODE)
  1002. {
  1003. for(int j = 0; j < 2; j++)
  1004. {
  1005. fprintf(stderr, "operation: ");
  1006. for(int i = NB_OPS / 2 * j; i < NB_OPS / 2 * (j + 1); i++)
  1007. fprintf(stderr, "%4i ", i);
  1008. fprintf(stderr, "\nattempts: ");
  1009. for(int i = NB_OPS / 2 * j; i < NB_OPS / 2 * (j + 1); i++)
  1010. fprintf(stderr, "%4i ", opstats[i * 2]);
  1011. fprintf(stderr, "\nsuccesses: ");
  1012. for(int i = NB_OPS / 2 * j; i < NB_OPS / 2 * (j + 1); i++)
  1013. fprintf(stderr, "%4i ", opstats[i * 2 + 1]);
  1014. fprintf(stderr, "\n");
  1015. }
  1016. fprintf(stderr, "Distance: %2.10g\n", error);
  1017. }
  1018. else
  1019. fprintf(stderr, "\r \r");
  1020. #if 0
  1021. dst = pipi_resize(tmp, width, height);
  1022. pipi_free(tmp);
  1023. /* Save image and bail out */
  1024. pipi_save(dst, "lol.bmp");
  1025. pipi_free(dst);
  1026. #endif
  1027. /* Push our points to the bitstream */
  1028. for(int i = 0; i < npoints; i++)
  1029. b.push(points[i], RANGE_SYXRGB);
  1030. b.push(height, MAX_H);
  1031. b.push(width, MAX_W);
  1032. /* Pop Unicode characters from the bitstream and print them */
  1033. for(int i = 0; i < MAX_MSG_LEN; i++)
  1034. fwrite_utf8(stdout, index2uni(b.pop(NUM_CHARACTERS)));
  1035. fprintf(stdout, "\n");
  1036. }
  1037. else
  1038. {
  1039. /* Pop points from the bitstream */
  1040. for(int i = dw * dh; i--; )
  1041. {
  1042. #if POINTS_PER_CELL == 2
  1043. points[i * 2 + 1] = b.pop(RANGE_SYXRGB);
  1044. points[i * 2] = b.pop(RANGE_SYXRGB);
  1045. #else
  1046. points[i] = b.pop(RANGE_SYXRGB);
  1047. #endif
  1048. }
  1049. npoints = dw * dh * POINTS_PER_CELL;
  1050. /* Render these points to a new image */
  1051. dst = pipi_new(width, height);
  1052. render(dst, 0, 0, width, height, true);
  1053. /* Save image and bail out */
  1054. pipi_save(dst, dstname);
  1055. pipi_free(dst);
  1056. }
  1057. return EXIT_SUCCESS;
  1058. }