makepng.c 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942
  1. /* makepng.c */
  2. #define _ISOC99_SOURCE
  3. /* Copyright: */
  4. #define COPYRIGHT "\251 2013,2015 John Cunningham Bowler"
  5. /*
  6. * Last changed in libpng 1.7.0 [(PENDING RELEASE)]
  7. *
  8. * This code is released under the libpng license.
  9. * For conditions of distribution and use, see the disclaimer
  10. * and license in png.h
  11. *
  12. * Make a test PNG image. The arguments are as follows:
  13. *
  14. * makepng [--sRGB|--linear|--1.8] [--tRNS] [--nofilters] \
  15. * color-type bit-depth [file-name]
  16. *
  17. * The color-type may be numeric (and must match the numbers used by the PNG
  18. * specification) or one of the format names listed below. The bit-depth is the
  19. * component bit depth, or the pixel bit-depth for a color-mapped image.
  20. *
  21. * Without any options no color-space information is written, with the options
  22. * an sRGB or the appropriate gAMA chunk is written. "1.8" refers to the
  23. * display system used on older Apple computers to correct for high ambient
  24. * light levels in the viewing environment; it applies a transform of
  25. * approximately value^(1/1.45) to the color values and so a gAMA chunk of 65909
  26. * is written (1.45/2.2).
  27. *
  28. * The image data is generated internally. Unless --color is given the images
  29. * used are as follows:
  30. *
  31. * 1 channel: a square image with a diamond, the least luminous colors are on
  32. * the edge of the image, the most luminous in the center.
  33. *
  34. * 2 channels: the color channel increases in luminosity from top to bottom, the
  35. * alpha channel increases in opacity from left to right.
  36. *
  37. * 3 channels: linear combinations of, from the top-left corner clockwise,
  38. * black, green, white, red.
  39. *
  40. * 4 channels: linear combinations of, from the top-left corner clockwise,
  41. * transparent, red, green, blue.
  42. *
  43. * For color-mapped images a four channel color-map is used and if --tRNS is
  44. * given the PNG file has a tRNS chunk, as follows:
  45. *
  46. * 1-bit: entry 0 is transparent-red, entry 1 is opaque-white
  47. * 2-bit: entry 0: transparent-green
  48. * entry 1: 40%-red
  49. * entry 2: 80%-blue
  50. * entry 3: opaque-white
  51. * 4-bit: the 16 combinations of the 2-bit case
  52. * 8-bit: the 256 combinations of the 4-bit case
  53. *
  54. * The palette always has 2^bit-depth entries and the tRNS chunk one fewer. The
  55. * image is the 1-channel diamond, but using palette index, not luminosity.
  56. *
  57. * For formats other than color-mapped ones if --tRNS is specified a tRNS chunk
  58. * is generated with all channels equal to the low bits of 0x0101.
  59. *
  60. * Image size is determined by the final pixel depth in bits, i.e. channels x
  61. * bit-depth, as follows:
  62. *
  63. * 8 bits or less: 64x64
  64. * 16 bits: 256x256
  65. * More than 16 bits: 1024x1024
  66. *
  67. * Row filtering is the libpng default but may be turned off (the 'none' filter
  68. * is used on every row) with the --nofilters option.
  69. *
  70. * The images are not interlaced.
  71. *
  72. * If file-name is given then the PNG is written to that file, else it is
  73. * written to stdout. Notice that stdout is not supported on systems where, by
  74. * default, it assumes text output; this program makes no attempt to change the
  75. * text mode of stdout!
  76. *
  77. * makepng --color=<color> ...
  78. *
  79. * If --color is given then the whole image has that color, color-mapped images
  80. * will have exactly one palette entry and all image files with be 16x16 in
  81. * size. The color value is 1 to 4 decimal numbers as appropriate for the color
  82. * type.
  83. *
  84. * makepng --small ...
  85. *
  86. * If --small is given the images are no larger than required to include every
  87. * possible pixel value for the format.
  88. *
  89. * For formats with pixels 8 bits or fewer in size the images consist of a
  90. * single row with 2^pixel-depth pixels, one of every possible value.
  91. *
  92. * For formats with 16-bit pixels a 256x256 image is generated containing every
  93. * possible pixel value.
  94. *
  95. * For larger pixel sizes a 256x256 image is generated where the first row
  96. * consists of each pixel that has identical byte values throughout the pixel
  97. * followed by rows where the byte values differ within the pixel.
  98. *
  99. * In all cases the pixel values are arranged in such a way that the SUB and UP
  100. * filters give byte sequences for maximal zlib compression. By default (if
  101. * --nofilters is not given) the SUB filter is used on the first row and the UP
  102. * filter on all following rows.
  103. *
  104. * The --small option is meant to provide good test-case coverage, however the
  105. * images are not easy to examine visually. Without the --small option the
  106. * images contain identical color values; the pixel values are adjusted
  107. * according to the gamma encoding with no gamma encoding being interpreted as
  108. * sRGB.
  109. *
  110. * LICENSING
  111. * =========
  112. *
  113. * This code is copyright of the authors, see the COPYRIGHT define above. The
  114. * code is licensed as above, using the libpng license. The code generates
  115. * images which are solely the product of the code; the options choose which of
  116. * the many possibilities to generate. The images that result (but not the code
  117. * which generates them) are licensed as defined here:
  118. *
  119. * IMPORTANT: the COPYRIGHT #define must contain ISO-Latin-1 characters, the
  120. * IMAGE_LICENSING #define must contain UTF-8 characters. The 'copyright'
  121. * symbol 0xA9U (\251) in ISO-Latin-1 encoding and 0xC20xA9 (\302\251) in UTF-8.
  122. */
  123. #define IMAGE_LICENSING "Dedicated to the public domain per Creative Commons "\
  124. "license \"CC0 1.0\"; https://creativecommons.org/publicdomain/zero/1.0/"
  125. #include <stddef.h> /* for offsetof */
  126. #include <stdlib.h>
  127. #include <stdio.h>
  128. #include <string.h>
  129. #include <ctype.h>
  130. #include <math.h>
  131. #include <errno.h>
  132. #include <assert.h>
  133. #include <stdint.h>
  134. #if defined(HAVE_CONFIG_H) && !defined(PNG_NO_CONFIG_H)
  135. # include <config.h>
  136. #endif
  137. /* Define the following to use this test against your installed libpng, rather
  138. * than the one being built here:
  139. */
  140. #ifdef PNG_FREESTANDING_TESTS
  141. # include <png.h>
  142. #else
  143. # include "../../png.h"
  144. #endif
  145. #include <zlib.h>
  146. /* Work round for GCC complaints about casting a (double) function result to
  147. * an unsigned:
  148. */
  149. static unsigned int
  150. flooru(double d)
  151. {
  152. d = floor(d);
  153. return (unsigned int)d;
  154. }
  155. static png_byte
  156. floorb(double d)
  157. {
  158. d = floor(d);
  159. return (png_byte)d;
  160. }
  161. /* This structure is used for inserting extra chunks (the --insert argument, not
  162. * documented above.)
  163. */
  164. typedef struct chunk_insert
  165. {
  166. struct chunk_insert *next;
  167. void (*insert)(png_structp, png_infop, int, png_charpp);
  168. int nparams;
  169. png_charp parameters[1];
  170. } chunk_insert;
  171. static unsigned int
  172. channels_of_type(int color_type)
  173. {
  174. if (color_type & PNG_COLOR_MASK_PALETTE)
  175. return 1;
  176. else
  177. {
  178. int channels = 1;
  179. if (color_type & PNG_COLOR_MASK_COLOR)
  180. channels = 3;
  181. if (color_type & PNG_COLOR_MASK_ALPHA)
  182. return channels + 1;
  183. else
  184. return channels;
  185. }
  186. }
  187. static unsigned int
  188. pixel_depth_of_type(int color_type, int bit_depth)
  189. {
  190. return channels_of_type(color_type) * bit_depth;
  191. }
  192. static unsigned int
  193. image_size_of_type(int color_type, int bit_depth, unsigned int *colors,
  194. int small)
  195. {
  196. if (*colors)
  197. return 16;
  198. else
  199. {
  200. int pixel_depth = pixel_depth_of_type(color_type, bit_depth);
  201. if (small)
  202. {
  203. if (pixel_depth <= 8) /* there will be one row */
  204. return 1 << pixel_depth;
  205. else
  206. return 256;
  207. }
  208. else if (pixel_depth < 8)
  209. return 64;
  210. else if (pixel_depth > 16)
  211. return 1024;
  212. else
  213. return 256;
  214. }
  215. }
  216. static void
  217. set_color(png_colorp color, png_bytep trans, unsigned int red,
  218. unsigned int green, unsigned int blue, unsigned int alpha,
  219. png_const_bytep gamma_table)
  220. {
  221. color->red = gamma_table[red];
  222. color->green = gamma_table[green];
  223. color->blue = gamma_table[blue];
  224. *trans = (png_byte)alpha;
  225. }
  226. static int
  227. generate_palette(png_colorp palette, png_bytep trans, int bit_depth,
  228. png_const_bytep gamma_table, unsigned int *colors)
  229. {
  230. /*
  231. * 1-bit: entry 0 is transparent-red, entry 1 is opaque-white
  232. * 2-bit: entry 0: transparent-green
  233. * entry 1: 40%-red
  234. * entry 2: 80%-blue
  235. * entry 3: opaque-white
  236. * 4-bit: the 16 combinations of the 2-bit case
  237. * 8-bit: the 256 combinations of the 4-bit case
  238. */
  239. switch (colors[0])
  240. {
  241. default:
  242. fprintf(stderr, "makepng: --colors=...: invalid count %u\n",
  243. colors[0]);
  244. exit(1);
  245. case 1:
  246. set_color(palette+0, trans+0, colors[1], colors[1], colors[1], 255,
  247. gamma_table);
  248. return 1;
  249. case 2:
  250. set_color(palette+0, trans+0, colors[1], colors[1], colors[1],
  251. colors[2], gamma_table);
  252. return 1;
  253. case 3:
  254. set_color(palette+0, trans+0, colors[1], colors[2], colors[3], 255,
  255. gamma_table);
  256. return 1;
  257. case 4:
  258. set_color(palette+0, trans+0, colors[1], colors[2], colors[3],
  259. colors[4], gamma_table);
  260. return 1;
  261. case 0:
  262. if (bit_depth == 1)
  263. {
  264. set_color(palette+0, trans+0, 255, 0, 0, 0, gamma_table);
  265. set_color(palette+1, trans+1, 255, 255, 255, 255, gamma_table);
  266. return 2;
  267. }
  268. else
  269. {
  270. unsigned int size = 1U << (bit_depth/2); /* 2, 4 or 16 */
  271. unsigned int x, y;
  272. volatile unsigned int ip = 0;
  273. for (x=0; x<size; ++x) for (y=0; y<size; ++y)
  274. {
  275. ip = x + (size * y);
  276. /* size is at most 16, so the scaled value below fits in 16 bits
  277. */
  278. # define interp(pos, c1, c2) ((pos * c1) + ((size-pos) * c2))
  279. # define xyinterp(x, y, c1, c2, c3, c4) (((size * size / 2) +\
  280. (interp(x, c1, c2) * y + (size-y) * interp(x, c3, c4))) /\
  281. (size*size))
  282. set_color(palette+ip, trans+ip,
  283. /* color: green, red,blue,white */
  284. xyinterp(x, y, 0, 255, 0, 255),
  285. xyinterp(x, y, 255, 0, 0, 255),
  286. xyinterp(x, y, 0, 0, 255, 255),
  287. /* alpha: 0, 102, 204, 255) */
  288. xyinterp(x, y, 0, 102, 204, 255),
  289. gamma_table);
  290. }
  291. return ip+1;
  292. }
  293. }
  294. }
  295. static void
  296. set_value(png_bytep row, size_t rowbytes, png_uint_32 x, unsigned int bit_depth,
  297. png_uint_32 value, png_const_bytep gamma_table, double conv)
  298. {
  299. unsigned int mask = (1U << bit_depth)-1;
  300. x *= bit_depth; /* Maximum x is 4*1024, maximum bit_depth is 16 */
  301. if (value <= mask)
  302. {
  303. png_uint_32 offset = x >> 3;
  304. if (offset < rowbytes && (bit_depth < 16 || offset+1 < rowbytes))
  305. {
  306. row += offset;
  307. switch (bit_depth)
  308. {
  309. case 1:
  310. case 2:
  311. case 4:
  312. /* Don't gamma correct - values get smashed */
  313. {
  314. unsigned int shift = (8 - bit_depth) - (x & 0x7U);
  315. mask <<= shift;
  316. value = (value << shift) & mask;
  317. *row = (png_byte)((*row & ~mask) | value);
  318. }
  319. return;
  320. default:
  321. fprintf(stderr, "makepng: bad bit depth (internal error)\n");
  322. exit(1);
  323. case 16:
  324. value = flooru(65535*pow(value/65535.,conv)+.5);
  325. *row++ = (png_byte)(value >> 8);
  326. *row = (png_byte)value;
  327. return;
  328. case 8:
  329. *row = gamma_table[value];
  330. return;
  331. }
  332. }
  333. else
  334. {
  335. fprintf(stderr, "makepng: row buffer overflow (internal error)\n");
  336. exit(1);
  337. }
  338. }
  339. else
  340. {
  341. fprintf(stderr, "makepng: component overflow (internal error)\n");
  342. exit(1);
  343. }
  344. }
  345. static int /* filter mask for row */
  346. generate_row(png_bytep row, size_t rowbytes, unsigned int y, int color_type,
  347. int bit_depth, png_const_bytep gamma_table, double conv,
  348. unsigned int *colors, int small)
  349. {
  350. int filters = 0; /* file *MASK*, 0 means the default, not NONE */
  351. png_uint_32 size_max =
  352. image_size_of_type(color_type, bit_depth, colors, small)-1;
  353. png_uint_32 depth_max = (1U << bit_depth)-1; /* up to 65536 */
  354. if (colors[0] == 0) if (small)
  355. {
  356. unsigned int pixel_depth = pixel_depth_of_type(color_type, bit_depth);
  357. /* For pixel depths less than 16 generate a single row containing all the
  358. * possible pixel values. For 16 generate all 65536 byte pair
  359. * combinations in a 256x256 pixel array.
  360. */
  361. switch (pixel_depth)
  362. {
  363. case 1:
  364. assert(y == 0 && rowbytes == 1 && size_max == 1);
  365. row[0] = 0x6CU; /* binary: 01101100, only top 2 bits used */
  366. filters = PNG_FILTER_NONE;
  367. break;
  368. case 2:
  369. assert(y == 0 && rowbytes == 1 && size_max == 3);
  370. row[0] = 0x1BU; /* binary 00011011, all bits used */
  371. filters = PNG_FILTER_NONE;
  372. break;
  373. case 4:
  374. assert(y == 0 && rowbytes == 8 && size_max == 15);
  375. row[0] = 0x01U;
  376. row[1] = 0x23U; /* SUB gives 0x22U for all following bytes */
  377. row[2] = 0x45U;
  378. row[3] = 0x67U;
  379. row[4] = 0x89U;
  380. row[5] = 0xABU;
  381. row[6] = 0xCDU;
  382. row[7] = 0xEFU;
  383. filters = PNG_FILTER_SUB;
  384. break;
  385. case 8:
  386. /* The row will have all the pixel values in order starting with
  387. * '1', the SUB filter will change every byte into '1' (including
  388. * the last, which generates pixel value '0'). Since the SUB filter
  389. * has value 1 this should result in maximum compression.
  390. */
  391. assert(y == 0 && rowbytes == 256 && size_max == 255);
  392. for (;;)
  393. {
  394. row[size_max] = 0xFFU & (size_max+1);
  395. if (size_max == 0)
  396. break;
  397. --size_max;
  398. }
  399. filters = PNG_FILTER_SUB;
  400. break;
  401. case 16:
  402. /* Rows are generated such that each row has a constant difference
  403. * between the first and second byte of each pixel and so that the
  404. * difference increases by 1 at each row. The rows start with the
  405. * first byte value of 0 and the value increases to 255 across the
  406. * row.
  407. *
  408. * The difference starts at 1, so the first row is:
  409. *
  410. * 0 1 1 2 2 3 3 4 ... 254 255 255 0
  411. *
  412. * This means that running the SUB filter on the first row produces:
  413. *
  414. * [SUB==1] 0 1 0 1 0 1...
  415. *
  416. * Then the difference is 2 on the next row, giving:
  417. *
  418. * 0 2 1 3 2 4 3 5 ... 254 0 255 1
  419. *
  420. * When the UP filter is run on this libpng produces:
  421. *
  422. * [UP ==2] 0 1 0 1 0 1...
  423. *
  424. * And so on for all the remain rows to the final two * rows:
  425. *
  426. * row 254: 0 255 1 0 2 1 3 2 4 3 ... 254 253 255 254
  427. * row 255: 0 0 1 1 2 2 3 3 4 4 ... 254 254 255 255
  428. */
  429. assert(rowbytes == 512 && size_max == 255);
  430. for (;;)
  431. {
  432. row[2*size_max ] = 0xFFU & size_max;
  433. row[2*size_max+1] = 0xFFU & (size_max+y+1);
  434. if (size_max == 0)
  435. break;
  436. --size_max;
  437. }
  438. /* The first row must include PNG_FILTER_UP so that libpng knows we
  439. * need to keep it for the following row:
  440. */
  441. filters = (y == 0 ? PNG_FILTER_SUB+PNG_FILTER_UP : PNG_FILTER_UP);
  442. break;
  443. case 24:
  444. case 32:
  445. case 48:
  446. case 64:
  447. /* The rows are filled by an alogorithm similar to the above, in the
  448. * first row pixel bytes are all equal, increasing from 0 by 1 for
  449. * each pixel. In the second row the bytes within a pixel are
  450. * incremented 1,3,5,7,... from the previous row byte. Using an odd
  451. * number ensures all the possible byte values are used.
  452. */
  453. assert(size_max == 255 && rowbytes == 256*(pixel_depth>>3));
  454. pixel_depth >>= 3; /* now in bytes */
  455. while (rowbytes > 0)
  456. {
  457. const size_t pixel_index = --rowbytes/pixel_depth;
  458. if (y == 0)
  459. row[rowbytes] = 0xFFU & pixel_index;
  460. else
  461. {
  462. const size_t byte_offset =
  463. rowbytes - pixel_index * pixel_depth;
  464. row[rowbytes] =
  465. 0xFFU & (pixel_index + (byte_offset * 2*y) + 1);
  466. }
  467. }
  468. filters = (y == 0 ? PNG_FILTER_SUB+PNG_FILTER_UP : PNG_FILTER_UP);
  469. break;
  470. default:
  471. assert(0/*NOT REACHED*/);
  472. }
  473. }
  474. else switch (channels_of_type(color_type))
  475. {
  476. /* 1 channel: a square image with a diamond, the least luminous colors are on
  477. * the edge of the image, the most luminous in the center.
  478. */
  479. case 1:
  480. {
  481. png_uint_32 x;
  482. png_uint_32 base = 2*size_max - abs(2*y-size_max);
  483. for (x=0; x<=size_max; ++x)
  484. {
  485. png_uint_32 luma = base - abs(2*x-size_max);
  486. /* 'luma' is now in the range 0..2*size_max, we need
  487. * 0..depth_max
  488. */
  489. luma = (luma*depth_max + size_max) / (2*size_max);
  490. set_value(row, rowbytes, x, bit_depth, luma, gamma_table, conv);
  491. }
  492. }
  493. break;
  494. /* 2 channels: the color channel increases in luminosity from top to bottom,
  495. * the alpha channel increases in opacity from left to right.
  496. */
  497. case 2:
  498. {
  499. png_uint_32 alpha = (depth_max * y * 2 + size_max) / (2 * size_max);
  500. png_uint_32 x;
  501. for (x=0; x<=size_max; ++x)
  502. {
  503. set_value(row, rowbytes, 2*x, bit_depth,
  504. (depth_max * x * 2 + size_max) / (2 * size_max), gamma_table,
  505. conv);
  506. set_value(row, rowbytes, 2*x+1, bit_depth, alpha, gamma_table,
  507. conv);
  508. }
  509. }
  510. break;
  511. /* 3 channels: linear combinations of, from the top-left corner clockwise,
  512. * black, green, white, red.
  513. */
  514. case 3:
  515. {
  516. /* x0: the black->red scale (the value of the red component) at the
  517. * start of the row (blue and green are 0).
  518. * x1: the green->white scale (the value of the red and blue
  519. * components at the end of the row; green is depth_max).
  520. */
  521. png_uint_32 Y = (depth_max * y * 2 + size_max) / (2 * size_max);
  522. png_uint_32 x;
  523. /* Interpolate x/depth_max from start to end:
  524. *
  525. * start end difference
  526. * red: Y Y 0
  527. * green: 0 depth_max depth_max
  528. * blue: 0 Y Y
  529. */
  530. for (x=0; x<=size_max; ++x)
  531. {
  532. set_value(row, rowbytes, 3*x+0, bit_depth, /* red */ Y,
  533. gamma_table, conv);
  534. set_value(row, rowbytes, 3*x+1, bit_depth, /* green */
  535. (depth_max * x * 2 + size_max) / (2 * size_max),
  536. gamma_table, conv);
  537. set_value(row, rowbytes, 3*x+2, bit_depth, /* blue */
  538. (Y * x * 2 + size_max) / (2 * size_max),
  539. gamma_table, conv);
  540. }
  541. }
  542. break;
  543. /* 4 channels: linear combinations of, from the top-left corner clockwise,
  544. * transparent, red, green, blue.
  545. */
  546. case 4:
  547. {
  548. /* x0: the transparent->blue scale (the value of the blue and alpha
  549. * components) at the start of the row (red and green are 0).
  550. * x1: the red->green scale (the value of the red and green
  551. * components at the end of the row; blue is 0 and alpha is
  552. * depth_max).
  553. */
  554. png_uint_32 Y = (depth_max * y * 2 + size_max) / (2 * size_max);
  555. png_uint_32 x;
  556. /* Interpolate x/depth_max from start to end:
  557. *
  558. * start end difference
  559. * red: 0 depth_max-Y depth_max-Y
  560. * green: 0 Y Y
  561. * blue: Y 0 -Y
  562. * alpha: Y depth_max depth_max-Y
  563. */
  564. for (x=0; x<=size_max; ++x)
  565. {
  566. set_value(row, rowbytes, 4*x+0, bit_depth, /* red */
  567. ((depth_max-Y) * x * 2 + size_max) / (2 * size_max),
  568. gamma_table, conv);
  569. set_value(row, rowbytes, 4*x+1, bit_depth, /* green */
  570. (Y * x * 2 + size_max) / (2 * size_max),
  571. gamma_table, conv);
  572. set_value(row, rowbytes, 4*x+2, bit_depth, /* blue */
  573. Y - (Y * x * 2 + size_max) / (2 * size_max),
  574. gamma_table, conv);
  575. set_value(row, rowbytes, 4*x+3, bit_depth, /* alpha */
  576. Y + ((depth_max-Y) * x * 2 + size_max) / (2 * size_max),
  577. gamma_table, conv);
  578. }
  579. }
  580. break;
  581. default:
  582. fprintf(stderr, "makepng: internal bad channel count\n");
  583. exit(2);
  584. }
  585. else if (color_type & PNG_COLOR_MASK_PALETTE)
  586. {
  587. /* Palette with fixed color: the image rows are all 0 and the image width
  588. * is 16.
  589. */
  590. memset(row, 0, rowbytes);
  591. }
  592. else if (colors[0] == channels_of_type(color_type))
  593. switch (channels_of_type(color_type))
  594. {
  595. case 1:
  596. {
  597. const png_uint_32 luma = colors[1];
  598. png_uint_32 x;
  599. for (x=0; x<=size_max; ++x)
  600. set_value(row, rowbytes, x, bit_depth, luma, gamma_table,
  601. conv);
  602. }
  603. break;
  604. case 2:
  605. {
  606. const png_uint_32 luma = colors[1];
  607. const png_uint_32 alpha = colors[2];
  608. png_uint_32 x;
  609. for (x=0; x<size_max; ++x)
  610. {
  611. set_value(row, rowbytes, 2*x, bit_depth, luma, gamma_table,
  612. conv);
  613. set_value(row, rowbytes, 2*x+1, bit_depth, alpha, gamma_table,
  614. conv);
  615. }
  616. }
  617. break;
  618. case 3:
  619. {
  620. const png_uint_32 red = colors[1];
  621. const png_uint_32 green = colors[2];
  622. const png_uint_32 blue = colors[3];
  623. png_uint_32 x;
  624. for (x=0; x<=size_max; ++x)
  625. {
  626. set_value(row, rowbytes, 3*x+0, bit_depth, red, gamma_table,
  627. conv);
  628. set_value(row, rowbytes, 3*x+1, bit_depth, green, gamma_table,
  629. conv);
  630. set_value(row, rowbytes, 3*x+2, bit_depth, blue, gamma_table,
  631. conv);
  632. }
  633. }
  634. break;
  635. case 4:
  636. {
  637. const png_uint_32 red = colors[1];
  638. const png_uint_32 green = colors[2];
  639. const png_uint_32 blue = colors[3];
  640. const png_uint_32 alpha = colors[4];
  641. png_uint_32 x;
  642. for (x=0; x<=size_max; ++x)
  643. {
  644. set_value(row, rowbytes, 4*x+0, bit_depth, red, gamma_table,
  645. conv);
  646. set_value(row, rowbytes, 4*x+1, bit_depth, green, gamma_table,
  647. conv);
  648. set_value(row, rowbytes, 4*x+2, bit_depth, blue, gamma_table,
  649. conv);
  650. set_value(row, rowbytes, 4*x+3, bit_depth, alpha, gamma_table,
  651. conv);
  652. }
  653. }
  654. break;
  655. default:
  656. fprintf(stderr, "makepng: internal bad channel count\n");
  657. exit(2);
  658. }
  659. else
  660. {
  661. fprintf(stderr,
  662. "makepng: --color: count(%u) does not match channels(%u)\n",
  663. colors[0], channels_of_type(color_type));
  664. exit(1);
  665. }
  666. return filters;
  667. }
  668. static void PNGCBAPI
  669. makepng_warning(png_structp png_ptr, png_const_charp message)
  670. {
  671. const char **ep = png_get_error_ptr(png_ptr);
  672. const char *name;
  673. if (ep != NULL && *ep != NULL)
  674. name = *ep;
  675. else
  676. name = "makepng";
  677. fprintf(stderr, "%s: warning: %s\n", name, message);
  678. }
  679. static void PNGCBAPI
  680. makepng_error(png_structp png_ptr, png_const_charp message)
  681. {
  682. makepng_warning(png_ptr, message);
  683. png_longjmp(png_ptr, 1);
  684. }
  685. static int /* 0 on success, else an error code */
  686. write_png(const char **name, FILE *fp, int color_type, int bit_depth,
  687. volatile png_fixed_point gamma, chunk_insert * volatile insert,
  688. unsigned int filters, unsigned int *colors, int small, int tRNS)
  689. {
  690. png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,
  691. name, makepng_error, makepng_warning);
  692. volatile png_infop info_ptr = NULL;
  693. volatile png_bytep row = NULL;
  694. if (png_ptr == NULL)
  695. {
  696. fprintf(stderr, "makepng: OOM allocating write structure\n");
  697. return 1;
  698. }
  699. if (setjmp(png_jmpbuf(png_ptr)))
  700. {
  701. png_structp nv_ptr = png_ptr;
  702. png_infop nv_info = info_ptr;
  703. png_ptr = NULL;
  704. info_ptr = NULL;
  705. png_destroy_write_struct(&nv_ptr, &nv_info);
  706. if (row != NULL) free(row);
  707. return 1;
  708. }
  709. /* Allow benign errors so that we can write PNGs with errors */
  710. png_set_benign_errors(png_ptr, 1/*allowed*/);
  711. /* Max out the text compression level in an attempt to make the license
  712. * small. If --small then do the same for the IDAT.
  713. */
  714. if (small)
  715. png_set_compression_level(png_ptr, Z_BEST_COMPRESSION);
  716. png_set_text_compression_level(png_ptr, Z_BEST_COMPRESSION);
  717. png_init_io(png_ptr, fp);
  718. info_ptr = png_create_info_struct(png_ptr);
  719. if (info_ptr == NULL)
  720. png_error(png_ptr, "OOM allocating info structure");
  721. {
  722. const unsigned int size =
  723. image_size_of_type(color_type, bit_depth, colors, small);
  724. unsigned int ysize;
  725. png_fixed_point real_gamma = 45455; /* For sRGB */
  726. png_byte gamma_table[256];
  727. double conv;
  728. /* Normally images are square, but with 'small' we want to simply generate
  729. * all the pixel values, or all that we reasonably can:
  730. */
  731. if (small)
  732. {
  733. const unsigned int pixel_depth =
  734. pixel_depth_of_type(color_type, bit_depth);
  735. if (pixel_depth <= 8U)
  736. {
  737. assert(size == (1U<<pixel_depth));
  738. ysize = 1U;
  739. }
  740. else
  741. {
  742. assert(size == 256U);
  743. ysize = 256U;
  744. }
  745. }
  746. else
  747. ysize = size;
  748. /* This function uses the libpng values used on read to carry extra
  749. * information about the gamma:
  750. */
  751. if (gamma == PNG_GAMMA_MAC_18)
  752. gamma = 65909;
  753. else if (gamma > 0 && gamma < 1000)
  754. gamma = PNG_FP_1;
  755. if (gamma > 0)
  756. real_gamma = gamma;
  757. {
  758. unsigned int i;
  759. if (real_gamma == 45455) for (i=0; i<256; ++i)
  760. {
  761. gamma_table[i] = (png_byte)i;
  762. conv = 1.;
  763. }
  764. else
  765. {
  766. /* Convert 'i' from sRGB (45455) to real_gamma, this makes
  767. * the images look the same regardless of the gAMA chunk.
  768. */
  769. conv = real_gamma;
  770. conv /= 45455;
  771. gamma_table[0] = 0;
  772. for (i=1; i<255; ++i)
  773. gamma_table[i] = floorb(pow(i/255.,conv) * 255 + .5);
  774. gamma_table[255] = 255;
  775. }
  776. }
  777. png_set_IHDR(png_ptr, info_ptr, size, ysize, bit_depth, color_type,
  778. PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
  779. if (color_type & PNG_COLOR_MASK_PALETTE)
  780. {
  781. int npalette;
  782. png_color palette[256];
  783. png_byte trans[256];
  784. npalette = generate_palette(palette, trans, bit_depth, gamma_table,
  785. colors);
  786. png_set_PLTE(png_ptr, info_ptr, palette, npalette);
  787. if (tRNS)
  788. png_set_tRNS(png_ptr, info_ptr, trans, npalette-1,
  789. NULL/*transparent color*/);
  790. /* Reset gamma_table to prevent the image rows being changed */
  791. for (npalette=0; npalette<256; ++npalette)
  792. gamma_table[npalette] = (png_byte)npalette;
  793. }
  794. else if (tRNS)
  795. {
  796. png_color_16 col;
  797. col.red = col.green = col.blue = col.gray =
  798. 0x0101U & ((1U<<bit_depth)-1U);
  799. col.index = 0U;
  800. png_set_tRNS(png_ptr, info_ptr, NULL/*trans*/, 1U, &col);
  801. }
  802. if (gamma == PNG_DEFAULT_sRGB)
  803. png_set_sRGB(png_ptr, info_ptr, PNG_sRGB_INTENT_ABSOLUTE);
  804. else if (gamma > 0) /* Else don't set color space information */
  805. {
  806. png_set_gAMA_fixed(png_ptr, info_ptr, real_gamma);
  807. /* Just use the sRGB values here. */
  808. png_set_cHRM_fixed(png_ptr, info_ptr,
  809. /* color x y */
  810. /* white */ 31270, 32900,
  811. /* red */ 64000, 33000,
  812. /* green */ 30000, 60000,
  813. /* blue */ 15000, 6000
  814. );
  815. }
  816. /* Insert extra information. */
  817. while (insert != NULL)
  818. {
  819. insert->insert(png_ptr, info_ptr, insert->nparams, insert->parameters);
  820. insert = insert->next;
  821. }
  822. /* Write the file header. */
  823. png_write_info(png_ptr, info_ptr);
  824. /* Restrict the filters */
  825. png_set_filter(png_ptr, PNG_FILTER_TYPE_BASE, filters);
  826. {
  827. # ifdef PNG_WRITE_INTERLACING_SUPPORTED
  828. int passes = png_set_interlace_handling(png_ptr);
  829. # else /* !WRITE_INTERLACING */
  830. int passes = 1;
  831. # endif /* !WRITE_INTERLACING */
  832. int pass;
  833. png_size_t rowbytes = png_get_rowbytes(png_ptr, info_ptr);
  834. row = malloc(rowbytes);
  835. if (row == NULL)
  836. png_error(png_ptr, "OOM allocating row buffer");
  837. for (pass = 0; pass < passes; ++pass)
  838. {
  839. unsigned int y;
  840. for (y=0; y<ysize; ++y)
  841. {
  842. unsigned int row_filters =
  843. generate_row(row, rowbytes, y, color_type, bit_depth,
  844. gamma_table, conv, colors, small);
  845. if (row_filters != 0 && filters == PNG_ALL_FILTERS)
  846. png_set_filter(png_ptr, PNG_FILTER_TYPE_BASE, row_filters);
  847. png_write_row(png_ptr, row);
  848. }
  849. }
  850. }
  851. }
  852. /* Finish writing the file. */
  853. png_write_end(png_ptr, info_ptr);
  854. {
  855. png_structp nv_ptr = png_ptr;
  856. png_infop nv_info = info_ptr;
  857. png_ptr = NULL;
  858. info_ptr = NULL;
  859. png_destroy_write_struct(&nv_ptr, &nv_info);
  860. }
  861. free(row);
  862. return 0;
  863. }
  864. static size_t
  865. load_file(png_const_charp name, png_bytepp result)
  866. {
  867. FILE *fp = tmpfile();
  868. if (fp != NULL)
  869. {
  870. FILE *ip = fopen(name, "rb");
  871. if (ip != NULL)
  872. {
  873. size_t total = 0;
  874. int ch;
  875. for (;;)
  876. {
  877. ch = getc(ip);
  878. if (ch == EOF) break;
  879. putc(ch, fp);
  880. ++total;
  881. }
  882. if (ferror(ip))
  883. {
  884. perror(name);
  885. fprintf(stderr, "%s: read error\n", name);
  886. (void)fclose(ip);
  887. }
  888. else
  889. {
  890. (void)fclose(ip);
  891. if (ferror(fp))
  892. {
  893. perror("temporary file");
  894. fprintf(stderr, "temporary file write error\n");
  895. }
  896. else
  897. {
  898. rewind(fp);
  899. if (total > 0)
  900. {
  901. /* Round up to a multiple of 4 here to allow an iCCP profile
  902. * to be padded to a 4x boundary.
  903. */
  904. png_bytep data = malloc((total+3)&~3);
  905. if (data != NULL)
  906. {
  907. size_t new_size = 0;
  908. for (;;)
  909. {
  910. ch = getc(fp);
  911. if (ch == EOF) break;
  912. data[new_size++] = (png_byte)ch;
  913. }
  914. if (ferror(fp) || new_size != total)
  915. {
  916. perror("temporary file");
  917. fprintf(stderr, "temporary file read error\n");
  918. free(data);
  919. }
  920. else
  921. {
  922. (void)fclose(fp);
  923. *result = data;
  924. return total;
  925. }
  926. }
  927. else
  928. fprintf(stderr, "%s: out of memory loading file\n", name);
  929. }
  930. else
  931. fprintf(stderr, "%s: empty file\n", name);
  932. }
  933. }
  934. }
  935. else
  936. {
  937. perror(name);
  938. fprintf(stderr, "%s: open failed\n", name);
  939. }
  940. fclose(fp);
  941. }
  942. else
  943. fprintf(stderr, "makepng: %s: could not open temporary file\n", name);
  944. exit(1);
  945. return 0;
  946. }
  947. static png_size_t
  948. load_fake(png_charp param, png_bytepp profile)
  949. {
  950. char *endptr = NULL;
  951. uint64_t size = strtoull(param, &endptr, 0/*base*/);
  952. /* The 'fake' format is <number>*[string] */
  953. if (endptr != NULL && *endptr == '*')
  954. {
  955. size_t len = strlen(++endptr);
  956. size_t result = (size_t)size;
  957. if (len == 0) len = 1; /* capture the terminating '\0' */
  958. /* Now repeat that string to fill 'size' bytes. */
  959. if (result == size && (*profile = malloc(result)) != NULL)
  960. {
  961. png_bytep out = *profile;
  962. if (len == 1)
  963. memset(out, *endptr, result);
  964. else
  965. {
  966. while (size >= len)
  967. {
  968. memcpy(out, endptr, len);
  969. out += len;
  970. size -= len;
  971. }
  972. memcpy(out, endptr, size);
  973. }
  974. return result;
  975. }
  976. else
  977. {
  978. fprintf(stderr, "%s: size exceeds system limits\n", param);
  979. exit(1);
  980. }
  981. }
  982. return 0;
  983. }
  984. static void
  985. check_param_count(int nparams, int expect)
  986. {
  987. if (nparams != expect)
  988. {
  989. fprintf(stderr, "bad parameter count (internal error)\n");
  990. exit(1);
  991. }
  992. }
  993. static void
  994. insert_iCCP(png_structp png_ptr, png_infop info_ptr, int nparams,
  995. png_charpp params)
  996. {
  997. png_bytep profile = NULL;
  998. png_uint_32 proflen = 0;
  999. int result;
  1000. check_param_count(nparams, 2);
  1001. switch (params[1][0])
  1002. {
  1003. case '<':
  1004. {
  1005. png_size_t filelen = load_file(params[1]+1, &profile);
  1006. if (filelen > 0xfffffffc) /* Maximum profile length */
  1007. {
  1008. fprintf(stderr, "%s: file too long (%lu) for an ICC profile\n",
  1009. params[1]+1, (unsigned long)filelen);
  1010. exit(1);
  1011. }
  1012. proflen = (png_uint_32)filelen;
  1013. }
  1014. break;
  1015. case '0': case '1': case '2': case '3': case '4':
  1016. case '5': case '6': case '7': case '8': case '9':
  1017. {
  1018. png_size_t fake_len = load_fake(params[1], &profile);
  1019. if (fake_len > 0) /* else a simple parameter */
  1020. {
  1021. if (fake_len > 0xffffffff) /* Maximum profile length */
  1022. {
  1023. fprintf(stderr,
  1024. "%s: fake data too long (%lu) for an ICC profile\n",
  1025. params[1], (unsigned long)fake_len);
  1026. exit(1);
  1027. }
  1028. proflen = (png_uint_32)(fake_len & ~3U);
  1029. /* Always fix up the profile length. */
  1030. png_save_uint_32(profile, proflen);
  1031. break;
  1032. }
  1033. }
  1034. default:
  1035. fprintf(stderr, "--insert iCCP \"%s\": unrecognized\n", params[1]);
  1036. fprintf(stderr, " use '<' to read a file: \"<filename\"\n");
  1037. exit(1);
  1038. }
  1039. result = 1;
  1040. if (proflen & 3)
  1041. {
  1042. fprintf(stderr,
  1043. "makepng: --insert iCCP %s: profile length made a multiple of 4\n",
  1044. params[1]);
  1045. /* load_file allocates extra space for this padding, the ICC spec requires
  1046. * padding with zero bytes.
  1047. */
  1048. while (proflen & 3)
  1049. profile[proflen++] = 0;
  1050. }
  1051. if (profile != NULL && proflen > 3)
  1052. {
  1053. png_uint_32 prof_header = png_get_uint_32(profile);
  1054. if (prof_header != proflen)
  1055. {
  1056. fprintf(stderr, "--insert iCCP %s: profile length field wrong:\n",
  1057. params[1]);
  1058. fprintf(stderr, " actual %lu, recorded value %lu (corrected)\n",
  1059. (unsigned long)proflen, (unsigned long)prof_header);
  1060. png_save_uint_32(profile, proflen);
  1061. }
  1062. }
  1063. if (result && profile != NULL && proflen >=4)
  1064. png_set_iCCP(png_ptr, info_ptr, params[0], PNG_COMPRESSION_TYPE_BASE,
  1065. profile, proflen);
  1066. if (profile)
  1067. free(profile);
  1068. if (!result)
  1069. exit(1);
  1070. }
  1071. static void
  1072. clear_text(png_text *text, png_charp keyword)
  1073. {
  1074. text->compression = -1; /* none */
  1075. text->key = keyword;
  1076. text->text = NULL;
  1077. text->text_length = 0; /* libpng calculates this */
  1078. text->itxt_length = 0; /* libpng calculates this */
  1079. text->lang = NULL;
  1080. text->lang_key = NULL;
  1081. }
  1082. static void
  1083. set_text(png_structp png_ptr, png_infop info_ptr, png_textp text,
  1084. png_charp param)
  1085. {
  1086. switch (param[0])
  1087. {
  1088. case '<':
  1089. {
  1090. png_bytep file = NULL;
  1091. text->text_length = load_file(param+1, &file);
  1092. text->text = (png_charp)file;
  1093. }
  1094. break;
  1095. case '0': case '1': case '2': case '3': case '4':
  1096. case '5': case '6': case '7': case '8': case '9':
  1097. {
  1098. png_bytep data = NULL;
  1099. png_size_t fake_len = load_fake(param, &data);
  1100. if (fake_len > 0) /* else a simple parameter */
  1101. {
  1102. text->text_length = fake_len;
  1103. text->text = (png_charp)data;
  1104. break;
  1105. }
  1106. }
  1107. default:
  1108. text->text = param;
  1109. break;
  1110. }
  1111. png_set_text(png_ptr, info_ptr, text, 1);
  1112. if (text->text != param)
  1113. free(text->text);
  1114. }
  1115. static void
  1116. insert_tEXt(png_structp png_ptr, png_infop info_ptr, int nparams,
  1117. png_charpp params)
  1118. {
  1119. png_text text;
  1120. check_param_count(nparams, 2);
  1121. clear_text(&text, params[0]);
  1122. set_text(png_ptr, info_ptr, &text, params[1]);
  1123. }
  1124. static void
  1125. insert_zTXt(png_structp png_ptr, png_infop info_ptr, int nparams,
  1126. png_charpp params)
  1127. {
  1128. png_text text;
  1129. check_param_count(nparams, 2);
  1130. clear_text(&text, params[0]);
  1131. text.compression = 0; /* deflate */
  1132. set_text(png_ptr, info_ptr, &text, params[1]);
  1133. }
  1134. static void
  1135. insert_iTXt(png_structp png_ptr, png_infop info_ptr, int nparams,
  1136. png_charpp params)
  1137. {
  1138. png_text text;
  1139. check_param_count(nparams, 4);
  1140. clear_text(&text, params[0]);
  1141. text.compression = 2; /* iTXt + deflate */
  1142. text.lang = params[1];/* language tag */
  1143. text.lang_key = params[2]; /* translated keyword */
  1144. set_text(png_ptr, info_ptr, &text, params[3]);
  1145. }
  1146. static void
  1147. insert_hIST(png_structp png_ptr, png_infop info_ptr, int nparams,
  1148. png_charpp params)
  1149. {
  1150. int i;
  1151. png_uint_16 freq[256];
  1152. /* libpng takes the count from the PLTE count; we don't check it here but we
  1153. * do set the array to 0 for unspecified entries.
  1154. */
  1155. memset(freq, 0, sizeof freq);
  1156. for (i=0; i<nparams; ++i)
  1157. {
  1158. char *endptr = NULL;
  1159. unsigned long int l = strtoul(params[i], &endptr, 0/*base*/);
  1160. if (params[i][0] && *endptr == 0 && l <= 65535)
  1161. freq[i] = (png_uint_16)l;
  1162. else
  1163. {
  1164. fprintf(stderr, "hIST[%d]: %s: invalid frequency\n", i, params[i]);
  1165. exit(1);
  1166. }
  1167. }
  1168. png_set_hIST(png_ptr, info_ptr, freq);
  1169. }
  1170. static png_byte
  1171. bval(png_const_structrp png_ptr, png_charp param, unsigned int maxval)
  1172. {
  1173. char *endptr = NULL;
  1174. unsigned long int l = strtoul(param, &endptr, 0/*base*/);
  1175. if (param[0] && *endptr == 0 && l <= maxval)
  1176. return (png_byte)l;
  1177. else
  1178. png_error(png_ptr, "sBIT: invalid sBIT value");
  1179. }
  1180. static void
  1181. insert_sBIT(png_structp png_ptr, png_infop info_ptr, int nparams,
  1182. png_charpp params)
  1183. {
  1184. const int ct = png_get_color_type(png_ptr, info_ptr);
  1185. const int c = (ct & PNG_COLOR_MASK_COLOR ? 3 : 1) +
  1186. (ct & PNG_COLOR_MASK_ALPHA ? 1 : 0);
  1187. const unsigned int maxval =
  1188. ct & PNG_COLOR_MASK_PALETTE ? 8U : png_get_bit_depth(png_ptr, info_ptr);
  1189. png_color_8 sBIT;
  1190. if (nparams != c)
  1191. png_error(png_ptr, "sBIT: incorrect parameter count");
  1192. if (ct & PNG_COLOR_MASK_COLOR)
  1193. {
  1194. sBIT.red = bval(png_ptr, params[0], maxval);
  1195. sBIT.green = bval(png_ptr, params[1], maxval);
  1196. sBIT.blue = bval(png_ptr, params[2], maxval);
  1197. sBIT.gray = 42;
  1198. }
  1199. else
  1200. {
  1201. sBIT.red = sBIT.green = sBIT.blue = 42;
  1202. sBIT.gray = bval(png_ptr, params[0], maxval);
  1203. }
  1204. if (ct & PNG_COLOR_MASK_ALPHA)
  1205. sBIT.alpha = bval(png_ptr, params[nparams-1], maxval);
  1206. else
  1207. sBIT.alpha = 42;
  1208. png_set_sBIT(png_ptr, info_ptr, &sBIT);
  1209. }
  1210. #if 0
  1211. static void
  1212. insert_sPLT(png_structp png_ptr, png_infop info_ptr, int nparams, png_charpp params)
  1213. {
  1214. fprintf(stderr, "insert sPLT: NYI\n");
  1215. }
  1216. #endif
  1217. static int
  1218. find_parameters(png_const_charp what, png_charp param, png_charp *list,
  1219. int nparams)
  1220. {
  1221. /* Parameters are separated by '\n' or ':' characters, up to nparams are
  1222. * accepted (more is an error) and the number found is returned.
  1223. */
  1224. int i;
  1225. for (i=0; *param && i<nparams; ++i)
  1226. {
  1227. list[i] = param;
  1228. while (*++param) if (*param == '\n' || *param == ':')
  1229. {
  1230. *param++ = 0; /* Terminate last parameter */
  1231. break; /* And start a new one. */
  1232. }
  1233. }
  1234. if (*param)
  1235. {
  1236. fprintf(stderr, "--insert %s: too many parameters (%s)\n", what, param);
  1237. exit(1);
  1238. }
  1239. list[i] = NULL; /* terminates list */
  1240. return i; /* number of parameters filled in */
  1241. }
  1242. static void
  1243. bad_parameter_count(png_const_charp what, int nparams)
  1244. {
  1245. fprintf(stderr, "--insert %s: bad parameter count %d\n", what, nparams);
  1246. exit(1);
  1247. }
  1248. static chunk_insert *
  1249. make_insert(png_const_charp what,
  1250. void (*insert)(png_structp, png_infop, int, png_charpp),
  1251. int nparams, png_charpp list)
  1252. {
  1253. int i;
  1254. chunk_insert *cip;
  1255. cip = malloc(offsetof(chunk_insert,parameters) +
  1256. nparams * sizeof (png_charp));
  1257. if (cip == NULL)
  1258. {
  1259. fprintf(stderr, "--insert %s: out of memory allocating %d parameters\n",
  1260. what, nparams);
  1261. exit(1);
  1262. }
  1263. cip->next = NULL;
  1264. cip->insert = insert;
  1265. cip->nparams = nparams;
  1266. for (i=0; i<nparams; ++i)
  1267. cip->parameters[i] = list[i];
  1268. return cip;
  1269. }
  1270. static chunk_insert *
  1271. find_insert(png_const_charp what, png_charp param)
  1272. {
  1273. png_uint_32 chunk = 0;
  1274. png_charp parameter_list[1024];
  1275. int i, nparams;
  1276. /* Assemble the chunk name */
  1277. for (i=0; i<4; ++i)
  1278. {
  1279. char ch = what[i];
  1280. if ((ch >= 65 && ch <= 90) || (ch >= 97 && ch <= 122))
  1281. chunk = (chunk << 8) + what[i];
  1282. else
  1283. break;
  1284. }
  1285. if (i < 4 || what[4] != 0)
  1286. {
  1287. fprintf(stderr, "makepng --insert \"%s\": invalid chunk name\n", what);
  1288. exit(1);
  1289. }
  1290. /* Assemble the parameter list. */
  1291. nparams = find_parameters(what, param, parameter_list, 1024);
  1292. # define CHUNK(a,b,c,d) (((a)<<24)+((b)<<16)+((c)<<8)+(d))
  1293. switch (chunk)
  1294. {
  1295. case CHUNK(105,67,67,80): /* iCCP */
  1296. if (nparams == 2)
  1297. return make_insert(what, insert_iCCP, nparams, parameter_list);
  1298. break;
  1299. case CHUNK(116,69,88,116): /* tEXt */
  1300. if (nparams == 2)
  1301. return make_insert(what, insert_tEXt, nparams, parameter_list);
  1302. break;
  1303. case CHUNK(122,84,88,116): /* zTXt */
  1304. if (nparams == 2)
  1305. return make_insert(what, insert_zTXt, nparams, parameter_list);
  1306. break;
  1307. case CHUNK(105,84,88,116): /* iTXt */
  1308. if (nparams == 4)
  1309. return make_insert(what, insert_iTXt, nparams, parameter_list);
  1310. break;
  1311. case CHUNK(104,73,83,84): /* hIST */
  1312. if (nparams <= 256)
  1313. return make_insert(what, insert_hIST, nparams, parameter_list);
  1314. break;
  1315. case CHUNK(115,66,73,84): /* sBIT */
  1316. if (nparams <= 4)
  1317. return make_insert(what, insert_sBIT, nparams, parameter_list);
  1318. break;
  1319. #if 0
  1320. case CHUNK(115,80,76,84): /* sPLT */
  1321. return make_insert(what, insert_sPLT, nparams, parameter_list);
  1322. #endif
  1323. default:
  1324. fprintf(stderr, "makepng --insert \"%s\": unrecognized chunk name\n",
  1325. what);
  1326. exit(1);
  1327. }
  1328. bad_parameter_count(what, nparams);
  1329. return NULL;
  1330. }
  1331. /* This is necessary because libpng expects writeable strings for things like
  1332. * text chunks (maybe this should be fixed...)
  1333. */
  1334. static png_charp
  1335. strstash(png_const_charp foo)
  1336. {
  1337. /* The program indicates a memory allocation error by crashing, this is by
  1338. * design.
  1339. */
  1340. if (foo != NULL)
  1341. {
  1342. png_charp bar = malloc(strlen(foo)+1);
  1343. return strcpy(bar, foo);
  1344. }
  1345. return NULL;
  1346. }
  1347. static png_charp
  1348. strstash_list(const png_const_charp *text)
  1349. {
  1350. size_t foo = 0;
  1351. png_charp result, bar;
  1352. const png_const_charp *line = text;
  1353. while (*line != NULL)
  1354. foo += strlen(*line++);
  1355. result = bar = malloc(foo+1);
  1356. line = text;
  1357. while (*line != NULL)
  1358. {
  1359. foo = strlen(*line);
  1360. memcpy(bar, *line++, foo);
  1361. bar += foo;
  1362. }
  1363. *bar = 0;
  1364. return result;
  1365. }
  1366. /* These are used to insert Copyright and Licence fields, they allow the text to
  1367. * have \n unlike the --insert option.
  1368. */
  1369. static chunk_insert *
  1370. add_tEXt(const char *key, const png_const_charp *text)
  1371. {
  1372. static char what[5] = { 116, 69, 88, 116, 0 };
  1373. png_charp parameter_list[3];
  1374. parameter_list[0] = strstash(key);
  1375. parameter_list[1] = strstash_list(text);
  1376. parameter_list[2] = NULL;
  1377. return make_insert(what, insert_tEXt, 2, parameter_list);
  1378. }
  1379. static chunk_insert *
  1380. add_iTXt(const char *key, const char *language, const char *language_key,
  1381. const png_const_charp *text)
  1382. {
  1383. static char what[5] = { 105, 84, 88, 116, 0 };
  1384. png_charp parameter_list[5];
  1385. parameter_list[0] = strstash(key);
  1386. parameter_list[1] = strstash(language);
  1387. parameter_list[2] = strstash(language_key);
  1388. parameter_list[3] = strstash_list(text);
  1389. parameter_list[4] = NULL;
  1390. return make_insert(what, insert_iTXt, 4, parameter_list);
  1391. }
  1392. /* This is a not-very-good parser for a sequence of numbers (including 0). It
  1393. * doesn't accept some apparently valid things, but it accepts all the sensible
  1394. * combinations.
  1395. */
  1396. static void
  1397. parse_color(char *arg, unsigned int *colors)
  1398. {
  1399. unsigned int ncolors = 0;
  1400. while (*arg && ncolors < 4)
  1401. {
  1402. char *ep = arg;
  1403. unsigned long ul = strtoul(arg, &ep, 0);
  1404. if (ul > 65535)
  1405. {
  1406. fprintf(stderr, "makepng --color=...'%s': too big\n", arg);
  1407. exit(1);
  1408. }
  1409. if (ep == arg)
  1410. {
  1411. fprintf(stderr, "makepng --color=...'%s': not a valid color\n", arg);
  1412. exit(1);
  1413. }
  1414. if (*ep) ++ep; /* skip a separator */
  1415. arg = ep;
  1416. colors[++ncolors] = (unsigned int)ul; /* checked above */
  1417. }
  1418. if (*arg)
  1419. {
  1420. fprintf(stderr, "makepng --color=...'%s': too many values\n", arg);
  1421. exit(1);
  1422. }
  1423. *colors = ncolors;
  1424. }
  1425. int
  1426. main(int argc, char **argv)
  1427. {
  1428. FILE *fp = stdout;
  1429. const char *file_name = NULL;
  1430. int color_type = 8; /* invalid */
  1431. int bit_depth = 32; /* invalid */
  1432. int small = 0; /* make full size images */
  1433. int tRNS = 0; /* don't output a tRNS chunk */
  1434. unsigned int colors[5];
  1435. unsigned int filters = PNG_ALL_FILTERS;
  1436. png_fixed_point gamma = 0; /* not set */
  1437. chunk_insert *head_insert = NULL;
  1438. chunk_insert **insert_ptr = &head_insert;
  1439. memset(colors, 0, sizeof colors);
  1440. while (--argc > 0)
  1441. {
  1442. char *arg = *++argv;
  1443. if (strcmp(arg, "--small") == 0)
  1444. {
  1445. small = 1;
  1446. continue;
  1447. }
  1448. if (strcmp(arg, "--tRNS") == 0)
  1449. {
  1450. tRNS = 1;
  1451. continue;
  1452. }
  1453. if (strcmp(arg, "--sRGB") == 0)
  1454. {
  1455. gamma = PNG_DEFAULT_sRGB;
  1456. continue;
  1457. }
  1458. if (strcmp(arg, "--linear") == 0)
  1459. {
  1460. gamma = PNG_FP_1;
  1461. continue;
  1462. }
  1463. if (strcmp(arg, "--1.8") == 0)
  1464. {
  1465. gamma = PNG_GAMMA_MAC_18;
  1466. continue;
  1467. }
  1468. if (strcmp(arg, "--nofilters") == 0)
  1469. {
  1470. filters = PNG_FILTER_NONE;
  1471. continue;
  1472. }
  1473. if (strncmp(arg, "--color=", 8) == 0)
  1474. {
  1475. parse_color(arg+8, colors);
  1476. continue;
  1477. }
  1478. if (argc >= 3 && strcmp(arg, "--insert") == 0)
  1479. {
  1480. png_const_charp what = *++argv;
  1481. png_charp param = *++argv;
  1482. chunk_insert *new_insert;
  1483. argc -= 2;
  1484. new_insert = find_insert(what, param);
  1485. if (new_insert != NULL)
  1486. {
  1487. *insert_ptr = new_insert;
  1488. insert_ptr = &new_insert->next;
  1489. }
  1490. continue;
  1491. }
  1492. if (arg[0] == '-')
  1493. {
  1494. fprintf(stderr, "makepng: %s: invalid option\n", arg);
  1495. exit(1);
  1496. }
  1497. if (strcmp(arg, "palette") == 0)
  1498. {
  1499. color_type = PNG_COLOR_TYPE_PALETTE;
  1500. continue;
  1501. }
  1502. if (strncmp(arg, "gray", 4) == 0)
  1503. {
  1504. if (arg[4] == 0)
  1505. {
  1506. color_type = PNG_COLOR_TYPE_GRAY;
  1507. continue;
  1508. }
  1509. else if (strcmp(arg+4, "a") == 0 ||
  1510. strcmp(arg+4, "alpha") == 0 ||
  1511. strcmp(arg+4, "-alpha") == 0)
  1512. {
  1513. color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  1514. continue;
  1515. }
  1516. }
  1517. if (strncmp(arg, "rgb", 3) == 0)
  1518. {
  1519. if (arg[3] == 0)
  1520. {
  1521. color_type = PNG_COLOR_TYPE_RGB;
  1522. continue;
  1523. }
  1524. else if (strcmp(arg+3, "a") == 0 ||
  1525. strcmp(arg+3, "alpha") == 0 ||
  1526. strcmp(arg+3, "-alpha") == 0)
  1527. {
  1528. color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  1529. continue;
  1530. }
  1531. }
  1532. if (color_type == 8 && isdigit(arg[0]))
  1533. {
  1534. color_type = atoi(arg);
  1535. if (color_type < 0 || color_type > 6 || color_type == 1 ||
  1536. color_type == 5)
  1537. {
  1538. fprintf(stderr, "makepng: %s: not a valid color type\n", arg);
  1539. exit(1);
  1540. }
  1541. continue;
  1542. }
  1543. if (bit_depth == 32 && isdigit(arg[0]))
  1544. {
  1545. bit_depth = atoi(arg);
  1546. if (bit_depth <= 0 || bit_depth > 16 ||
  1547. (bit_depth & -bit_depth) != bit_depth)
  1548. {
  1549. fprintf(stderr, "makepng: %s: not a valid bit depth\n", arg);
  1550. exit(1);
  1551. }
  1552. continue;
  1553. }
  1554. if (argc == 1) /* It's the file name */
  1555. {
  1556. fp = fopen(arg, "wb");
  1557. if (fp == NULL)
  1558. {
  1559. fprintf(stderr, "%s: %s: could not open\n", arg, strerror(errno));
  1560. exit(1);
  1561. }
  1562. file_name = arg;
  1563. continue;
  1564. }
  1565. fprintf(stderr, "makepng: %s: unknown argument\n", arg);
  1566. exit(1);
  1567. } /* argument while loop */
  1568. if (color_type == 8 || bit_depth == 32)
  1569. {
  1570. fprintf(stderr, "usage: makepng [--small] [--sRGB|--linear|--1.8] "
  1571. "[--color=...] color-type bit-depth [file-name]\n"
  1572. " Make a test PNG file, by default writes to stdout.\n"
  1573. " Other options are available, UTSL.\n");
  1574. exit(1);
  1575. }
  1576. /* Check the colors */
  1577. {
  1578. const unsigned int lim = (color_type == PNG_COLOR_TYPE_PALETTE ? 255U :
  1579. (1U<<bit_depth)-1);
  1580. unsigned int i;
  1581. for (i=1; i<=colors[0]; ++i)
  1582. if (colors[i] > lim)
  1583. {
  1584. fprintf(stderr, "makepng: --color=...: %u out of range [0..%u]\n",
  1585. colors[i], lim);
  1586. exit(1);
  1587. }
  1588. }
  1589. /* small and colors are incomparible (will probably crash if both are used at
  1590. * the same time!)
  1591. */
  1592. if (small && colors[0] != 0)
  1593. {
  1594. fprintf(stderr, "makepng: --color --small: only one at a time!\n");
  1595. exit(1);
  1596. }
  1597. /* Restrict the filters for more speed to those we know are used for the
  1598. * generated images.
  1599. */
  1600. if (filters == PNG_ALL_FILTERS && !small/*small provides defaults*/)
  1601. {
  1602. if ((color_type & PNG_COLOR_MASK_PALETTE) != 0 || bit_depth < 8)
  1603. filters = PNG_FILTER_NONE;
  1604. else if (color_type & PNG_COLOR_MASK_COLOR) /* rgb */
  1605. {
  1606. if (bit_depth == 8)
  1607. filters &= ~(PNG_FILTER_NONE | PNG_FILTER_AVG);
  1608. else
  1609. filters = PNG_FILTER_SUB | PNG_FILTER_PAETH;
  1610. }
  1611. else /* gray 8 or 16-bit */
  1612. filters &= ~PNG_FILTER_NONE;
  1613. }
  1614. /* Insert standard copyright and licence text. */
  1615. {
  1616. static png_const_charp copyright[] =
  1617. {
  1618. COPYRIGHT, /* ISO-Latin-1 */
  1619. NULL
  1620. };
  1621. static png_const_charp licensing[] =
  1622. {
  1623. IMAGE_LICENSING, /* UTF-8 */
  1624. NULL
  1625. };
  1626. chunk_insert *new_insert;
  1627. new_insert = add_tEXt("Copyright", copyright);
  1628. if (new_insert != NULL)
  1629. {
  1630. *insert_ptr = new_insert;
  1631. insert_ptr = &new_insert->next;
  1632. }
  1633. new_insert = add_iTXt("Licensing", "en", NULL, licensing);
  1634. if (new_insert != NULL)
  1635. {
  1636. *insert_ptr = new_insert;
  1637. insert_ptr = &new_insert->next;
  1638. }
  1639. }
  1640. {
  1641. int ret = write_png(&file_name, fp, color_type, bit_depth, gamma,
  1642. head_insert, filters, colors, small, tRNS);
  1643. if (ret != 0 && file_name != NULL)
  1644. remove(file_name);
  1645. return ret;
  1646. }
  1647. }