Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 
 
 
 

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