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.
 
 
 
 
 
 

1205 lignes
36 KiB

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