Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 
 
 

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