You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

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