pngwutil.c 76 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680
  1. /* pngwutil.c - utilities to write a PNG file
  2. *
  3. * Last changed in libpng 1.5.26 [December 17, 2015]
  4. * Copyright (c) 1998-2002,2004,2006-2015 Glenn Randers-Pehrson
  5. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  6. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  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. #include "pngpriv.h"
  13. #ifdef PNG_WRITE_SUPPORTED
  14. #ifdef PNG_WRITE_INT_FUNCTIONS_SUPPORTED
  15. /* Place a 32-bit number into a buffer in PNG byte order. We work
  16. * with unsigned numbers for convenience, although one supported
  17. * ancillary chunk uses signed (two's complement) numbers.
  18. */
  19. void PNGAPI
  20. png_save_uint_32(png_bytep buf, png_uint_32 i)
  21. {
  22. buf[0] = (png_byte)((i >> 24) & 0xff);
  23. buf[1] = (png_byte)((i >> 16) & 0xff);
  24. buf[2] = (png_byte)((i >> 8) & 0xff);
  25. buf[3] = (png_byte)(i & 0xff);
  26. }
  27. #ifdef PNG_SAVE_INT_32_SUPPORTED
  28. /* PNG signed integers are saved in 32-bit 2's complement format. ANSI C-90
  29. * defines a cast of a signed integer to an unsigned integer either to preserve
  30. * the value, if it is positive, or to calculate:
  31. *
  32. * (UNSIGNED_MAX+1) + integer
  33. *
  34. * Where UNSIGNED_MAX is the appropriate maximum unsigned value, so when the
  35. * negative integral value is added the result will be an unsigned value
  36. * correspnding to the 2's complement representation.
  37. */
  38. void PNGAPI
  39. png_save_int_32(png_bytep buf, png_int_32 i)
  40. {
  41. png_save_uint_32(buf, i);
  42. }
  43. #endif
  44. /* Place a 16-bit number into a buffer in PNG byte order.
  45. * The parameter is declared unsigned int, not png_uint_16,
  46. * just to avoid potential problems on pre-ANSI C compilers.
  47. */
  48. void PNGAPI
  49. png_save_uint_16(png_bytep buf, unsigned int i)
  50. {
  51. buf[0] = (png_byte)((i >> 8) & 0xff);
  52. buf[1] = (png_byte)(i & 0xff);
  53. }
  54. #endif
  55. /* Simple function to write the signature. If we have already written
  56. * the magic bytes of the signature, or more likely, the PNG stream is
  57. * being embedded into another stream and doesn't need its own signature,
  58. * we should call png_set_sig_bytes() to tell libpng how many of the
  59. * bytes have already been written.
  60. */
  61. void PNGAPI
  62. png_write_sig(png_structp png_ptr)
  63. {
  64. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  65. #ifdef PNG_IO_STATE_SUPPORTED
  66. /* Inform the I/O callback that the signature is being written */
  67. png_ptr->io_state = PNG_IO_WRITING | PNG_IO_SIGNATURE;
  68. #endif
  69. /* Write the rest of the 8 byte signature */
  70. png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
  71. (png_size_t)(8 - png_ptr->sig_bytes));
  72. if (png_ptr->sig_bytes < 3)
  73. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  74. }
  75. /* Write the start of a PNG chunk. The type is the chunk type.
  76. * The total_length is the sum of the lengths of all the data you will be
  77. * passing in png_write_chunk_data().
  78. */
  79. static void
  80. png_write_chunk_header(png_structp png_ptr, png_uint_32 chunk_name,
  81. png_uint_32 length)
  82. {
  83. png_byte buf[8];
  84. #if defined(PNG_DEBUG) && (PNG_DEBUG > 0)
  85. PNG_CSTRING_FROM_CHUNK(buf, chunk_name);
  86. png_debug2(0, "Writing %s chunk, length = %lu", buf, (unsigned long)length);
  87. #endif
  88. if (png_ptr == NULL)
  89. return;
  90. #ifdef PNG_IO_STATE_SUPPORTED
  91. /* Inform the I/O callback that the chunk header is being written.
  92. * PNG_IO_CHUNK_HDR requires a single I/O call.
  93. */
  94. png_ptr->io_state = PNG_IO_WRITING | PNG_IO_CHUNK_HDR;
  95. #endif
  96. /* Write the length and the chunk name */
  97. png_save_uint_32(buf, length);
  98. png_save_uint_32(buf + 4, chunk_name);
  99. png_write_data(png_ptr, buf, 8);
  100. /* Put the chunk name into png_ptr->chunk_name */
  101. png_ptr->chunk_name = chunk_name;
  102. /* Reset the crc and run it over the chunk name */
  103. png_reset_crc(png_ptr);
  104. png_calculate_crc(png_ptr, buf + 4, 4);
  105. #ifdef PNG_IO_STATE_SUPPORTED
  106. /* Inform the I/O callback that chunk data will (possibly) be written.
  107. * PNG_IO_CHUNK_DATA does NOT require a specific number of I/O calls.
  108. */
  109. png_ptr->io_state = PNG_IO_WRITING | PNG_IO_CHUNK_DATA;
  110. #endif
  111. }
  112. void PNGAPI
  113. png_write_chunk_start(png_structp png_ptr, png_const_bytep chunk_string,
  114. png_uint_32 length)
  115. {
  116. png_write_chunk_header(png_ptr, PNG_CHUNK_FROM_STRING(chunk_string), length);
  117. }
  118. /* Write the data of a PNG chunk started with png_write_chunk_header().
  119. * Note that multiple calls to this function are allowed, and that the
  120. * sum of the lengths from these calls *must* add up to the total_length
  121. * given to png_write_chunk_header().
  122. */
  123. void PNGAPI
  124. png_write_chunk_data(png_structp png_ptr, png_const_bytep data,
  125. png_size_t length)
  126. {
  127. /* Write the data, and run the CRC over it */
  128. if (png_ptr == NULL)
  129. return;
  130. if (data != NULL && length > 0)
  131. {
  132. png_write_data(png_ptr, data, length);
  133. /* Update the CRC after writing the data,
  134. * in case that the user I/O routine alters it.
  135. */
  136. png_calculate_crc(png_ptr, data, length);
  137. }
  138. }
  139. /* Finish a chunk started with png_write_chunk_header(). */
  140. void PNGAPI
  141. png_write_chunk_end(png_structp png_ptr)
  142. {
  143. png_byte buf[4];
  144. if (png_ptr == NULL) return;
  145. #ifdef PNG_IO_STATE_SUPPORTED
  146. /* Inform the I/O callback that the chunk CRC is being written.
  147. * PNG_IO_CHUNK_CRC requires a single I/O function call.
  148. */
  149. png_ptr->io_state = PNG_IO_WRITING | PNG_IO_CHUNK_CRC;
  150. #endif
  151. /* Write the crc in a single operation */
  152. png_save_uint_32(buf, png_ptr->crc);
  153. png_write_data(png_ptr, buf, (png_size_t)4);
  154. }
  155. /* Write a PNG chunk all at once. The type is an array of ASCII characters
  156. * representing the chunk name. The array must be at least 4 bytes in
  157. * length, and does not need to be null terminated. To be safe, pass the
  158. * pre-defined chunk names here, and if you need a new one, define it
  159. * where the others are defined. The length is the length of the data.
  160. * All the data must be present. If that is not possible, use the
  161. * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
  162. * functions instead.
  163. */
  164. static void
  165. png_write_complete_chunk(png_structp png_ptr, png_uint_32 chunk_name,
  166. png_const_bytep data, png_size_t length)
  167. {
  168. if (png_ptr == NULL)
  169. return;
  170. /* On 64 bit architectures 'length' may not fit in a png_uint_32. */
  171. if (length > PNG_UINT_32_MAX)
  172. png_error(png_ptr, "length exceeds PNG maxima");
  173. png_write_chunk_header(png_ptr, chunk_name, (png_uint_32)length);
  174. png_write_chunk_data(png_ptr, data, length);
  175. png_write_chunk_end(png_ptr);
  176. }
  177. /* This is the API that calls the internal function above. */
  178. void PNGAPI
  179. png_write_chunk(png_structp png_ptr, png_const_bytep chunk_string,
  180. png_const_bytep data, png_size_t length)
  181. {
  182. png_write_complete_chunk(png_ptr, PNG_CHUNK_FROM_STRING(chunk_string), data,
  183. length);
  184. }
  185. /* Initialize the compressor for the appropriate type of compression. */
  186. static void
  187. png_zlib_claim(png_structp png_ptr, png_uint_32 state)
  188. {
  189. if (!(png_ptr->zlib_state & PNG_ZLIB_IN_USE))
  190. {
  191. /* If already initialized for 'state' do not re-init. */
  192. if (png_ptr->zlib_state != state)
  193. {
  194. int ret = Z_OK;
  195. png_const_charp who = "-";
  196. /* If actually initialized for another state do a deflateEnd. */
  197. if (png_ptr->zlib_state != PNG_ZLIB_UNINITIALIZED)
  198. {
  199. ret = deflateEnd(&png_ptr->zstream);
  200. who = "end";
  201. png_ptr->zlib_state = PNG_ZLIB_UNINITIALIZED;
  202. }
  203. /* zlib itself detects an incomplete state on deflateEnd */
  204. if (ret == Z_OK) switch (state)
  205. {
  206. # ifdef PNG_WRITE_COMPRESSED_TEXT_SUPPORTED
  207. case PNG_ZLIB_FOR_TEXT:
  208. ret = deflateInit2(&png_ptr->zstream,
  209. png_ptr->zlib_text_level, png_ptr->zlib_text_method,
  210. png_ptr->zlib_text_window_bits,
  211. png_ptr->zlib_text_mem_level, png_ptr->zlib_text_strategy);
  212. who = "text";
  213. break;
  214. # endif
  215. case PNG_ZLIB_FOR_IDAT:
  216. ret = deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
  217. png_ptr->zlib_method, png_ptr->zlib_window_bits,
  218. png_ptr->zlib_mem_level, png_ptr->zlib_strategy);
  219. who = "IDAT";
  220. break;
  221. default:
  222. png_error(png_ptr, "invalid zlib state");
  223. }
  224. if (ret == Z_OK)
  225. png_ptr->zlib_state = state;
  226. else /* an error in deflateEnd or deflateInit2 */
  227. {
  228. size_t pos = 0;
  229. char msg[64];
  230. pos = png_safecat(msg, sizeof msg, pos,
  231. "zlib failed to initialize compressor (");
  232. pos = png_safecat(msg, sizeof msg, pos, who);
  233. switch (ret)
  234. {
  235. case Z_VERSION_ERROR:
  236. pos = png_safecat(msg, sizeof msg, pos, ") version error");
  237. break;
  238. case Z_STREAM_ERROR:
  239. pos = png_safecat(msg, sizeof msg, pos, ") stream error");
  240. break;
  241. case Z_MEM_ERROR:
  242. pos = png_safecat(msg, sizeof msg, pos, ") memory error");
  243. break;
  244. default:
  245. pos = png_safecat(msg, sizeof msg, pos, ") unknown error");
  246. break;
  247. }
  248. png_error(png_ptr, msg);
  249. }
  250. }
  251. /* Here on success, claim the zstream: */
  252. png_ptr->zlib_state |= PNG_ZLIB_IN_USE;
  253. }
  254. else
  255. png_error(png_ptr, "zstream already in use (internal error)");
  256. }
  257. /* The opposite: release the stream. It is also reset, this API will warn on
  258. * error but will not fail.
  259. */
  260. static void
  261. png_zlib_release(png_structp png_ptr)
  262. {
  263. if (png_ptr->zlib_state & PNG_ZLIB_IN_USE)
  264. {
  265. int ret = deflateReset(&png_ptr->zstream);
  266. png_ptr->zlib_state &= ~PNG_ZLIB_IN_USE;
  267. if (ret != Z_OK)
  268. {
  269. #ifdef PNG_WARNINGS_SUPPORTED
  270. png_const_charp err;
  271. PNG_WARNING_PARAMETERS(p)
  272. switch (ret)
  273. {
  274. case Z_VERSION_ERROR:
  275. err = "version";
  276. break;
  277. case Z_STREAM_ERROR:
  278. err = "stream";
  279. break;
  280. case Z_MEM_ERROR:
  281. err = "memory";
  282. break;
  283. default:
  284. err = "unknown";
  285. break;
  286. }
  287. png_warning_parameter_signed(p, 1, PNG_NUMBER_FORMAT_d, ret);
  288. png_warning_parameter(p, 2, err);
  289. if (png_ptr->zstream.msg)
  290. err = png_ptr->zstream.msg;
  291. else
  292. err = "[no zlib message]";
  293. png_warning_parameter(p, 3, err);
  294. png_formatted_warning(png_ptr, p,
  295. "zlib failed to reset compressor: @1(@2): @3");
  296. #endif
  297. }
  298. }
  299. else
  300. png_warning(png_ptr, "zstream not in use (internal error)");
  301. }
  302. #ifdef PNG_WRITE_COMPRESSED_TEXT_SUPPORTED
  303. /* This pair of functions encapsulates the operation of (a) compressing a
  304. * text string, and (b) issuing it later as a series of chunk data writes.
  305. * The compression_state structure is shared context for these functions
  306. * set up by the caller in order to make the whole mess thread-safe.
  307. */
  308. typedef struct
  309. {
  310. png_const_bytep input; /* The uncompressed input data */
  311. png_size_t input_len; /* Its length */
  312. int num_output_ptr; /* Number of output pointers used */
  313. int max_output_ptr; /* Size of output_ptr */
  314. png_bytep *output_ptr; /* Array of pointers to output */
  315. } compression_state;
  316. /* Compress given text into storage in the png_ptr structure */
  317. static int /* PRIVATE */
  318. png_text_compress(png_structp png_ptr,
  319. png_const_charp text, png_size_t text_len, int compression,
  320. compression_state *comp)
  321. {
  322. int ret;
  323. comp->num_output_ptr = 0;
  324. comp->max_output_ptr = 0;
  325. comp->output_ptr = NULL;
  326. comp->input = NULL;
  327. comp->input_len = text_len;
  328. /* We may just want to pass the text right through */
  329. if (compression == PNG_TEXT_COMPRESSION_NONE)
  330. {
  331. comp->input = (png_const_bytep)text;
  332. return((int)text_len);
  333. }
  334. if (compression >= PNG_TEXT_COMPRESSION_LAST)
  335. {
  336. PNG_WARNING_PARAMETERS(p)
  337. png_warning_parameter_signed(p, 1, PNG_NUMBER_FORMAT_d,
  338. compression);
  339. png_formatted_warning(png_ptr, p, "Unknown compression type @1");
  340. }
  341. /* We can't write the chunk until we find out how much data we have,
  342. * which means we need to run the compressor first and save the
  343. * output. This shouldn't be a problem, as the vast majority of
  344. * comments should be reasonable, but we will set up an array of
  345. * malloc'd pointers to be sure.
  346. *
  347. * If we knew the application was well behaved, we could simplify this
  348. * greatly by assuming we can always malloc an output buffer large
  349. * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
  350. * and malloc this directly. The only time this would be a bad idea is
  351. * if we can't malloc more than 64K and we have 64K of random input
  352. * data, or if the input string is incredibly large (although this
  353. * wouldn't cause a failure, just a slowdown due to swapping).
  354. */
  355. png_zlib_claim(png_ptr, PNG_ZLIB_FOR_TEXT);
  356. /* Set up the compression buffers */
  357. /* TODO: the following cast hides a potential overflow problem. */
  358. png_ptr->zstream.avail_in = (uInt)text_len;
  359. /* NOTE: assume zlib doesn't overwrite the input */
  360. png_ptr->zstream.next_in = (Bytef *)text;
  361. png_ptr->zstream.avail_out = png_ptr->zbuf_size;
  362. png_ptr->zstream.next_out = png_ptr->zbuf;
  363. /* This is the same compression loop as in png_write_row() */
  364. do
  365. {
  366. /* Compress the data */
  367. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  368. if (ret != Z_OK)
  369. {
  370. /* Error */
  371. if (png_ptr->zstream.msg != NULL)
  372. png_error(png_ptr, png_ptr->zstream.msg);
  373. else
  374. png_error(png_ptr, "zlib error");
  375. }
  376. /* Check to see if we need more room */
  377. if (!(png_ptr->zstream.avail_out))
  378. {
  379. /* Make sure the output array has room */
  380. if (comp->num_output_ptr >= comp->max_output_ptr)
  381. {
  382. int old_max;
  383. old_max = comp->max_output_ptr;
  384. comp->max_output_ptr = comp->num_output_ptr + 4;
  385. if (comp->output_ptr != NULL)
  386. {
  387. png_bytepp old_ptr;
  388. old_ptr = comp->output_ptr;
  389. comp->output_ptr = (png_bytepp)png_malloc(png_ptr,
  390. (comp->max_output_ptr * png_sizeof(png_bytep)));
  391. png_memcpy(comp->output_ptr, old_ptr, old_max
  392. * png_sizeof(png_bytep));
  393. png_free(png_ptr, old_ptr);
  394. }
  395. else
  396. comp->output_ptr = (png_bytepp)png_malloc(png_ptr,
  397. (comp->max_output_ptr * png_sizeof(png_bytep)));
  398. }
  399. /* Save the data */
  400. comp->output_ptr[comp->num_output_ptr] =
  401. (png_bytep)png_malloc(png_ptr, png_ptr->zbuf_size);
  402. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  403. png_ptr->zbuf_size);
  404. comp->num_output_ptr++;
  405. /* and reset the buffer */
  406. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  407. png_ptr->zstream.next_out = png_ptr->zbuf;
  408. }
  409. /* Continue until we don't have any more to compress */
  410. } while (png_ptr->zstream.avail_in);
  411. /* Finish the compression */
  412. do
  413. {
  414. /* Tell zlib we are finished */
  415. ret = deflate(&png_ptr->zstream, Z_FINISH);
  416. if (ret == Z_OK)
  417. {
  418. /* Check to see if we need more room */
  419. if (!(png_ptr->zstream.avail_out))
  420. {
  421. /* Check to make sure our output array has room */
  422. if (comp->num_output_ptr >= comp->max_output_ptr)
  423. {
  424. int old_max;
  425. old_max = comp->max_output_ptr;
  426. comp->max_output_ptr = comp->num_output_ptr + 4;
  427. if (comp->output_ptr != NULL)
  428. {
  429. png_bytepp old_ptr;
  430. old_ptr = comp->output_ptr;
  431. /* This could be optimized to realloc() */
  432. comp->output_ptr = (png_bytepp)png_malloc(png_ptr,
  433. (png_alloc_size_t)(comp->max_output_ptr *
  434. png_sizeof(png_charp)));
  435. png_memcpy(comp->output_ptr, old_ptr,
  436. old_max * png_sizeof(png_charp));
  437. png_free(png_ptr, old_ptr);
  438. }
  439. else
  440. comp->output_ptr = (png_bytepp)png_malloc(png_ptr,
  441. (png_alloc_size_t)(comp->max_output_ptr *
  442. png_sizeof(png_charp)));
  443. }
  444. /* Save the data */
  445. comp->output_ptr[comp->num_output_ptr] =
  446. (png_bytep)png_malloc(png_ptr,
  447. (png_alloc_size_t)png_ptr->zbuf_size);
  448. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  449. png_ptr->zbuf_size);
  450. comp->num_output_ptr++;
  451. /* and reset the buffer pointers */
  452. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  453. png_ptr->zstream.next_out = png_ptr->zbuf;
  454. }
  455. }
  456. else if (ret != Z_STREAM_END)
  457. {
  458. /* We got an error */
  459. if (png_ptr->zstream.msg != NULL)
  460. png_error(png_ptr, png_ptr->zstream.msg);
  461. else
  462. png_error(png_ptr, "zlib error");
  463. }
  464. } while (ret != Z_STREAM_END);
  465. /* Text length is number of buffers plus last buffer */
  466. text_len = png_ptr->zbuf_size * comp->num_output_ptr;
  467. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  468. text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
  469. return((int)text_len);
  470. }
  471. /* Ship the compressed text out via chunk writes */
  472. static void /* PRIVATE */
  473. png_write_compressed_data_out(png_structp png_ptr, compression_state *comp,
  474. png_size_t data_len)
  475. {
  476. int i;
  477. /* Handle the no-compression case */
  478. if (comp->input)
  479. {
  480. png_write_chunk_data(png_ptr, comp->input, data_len);
  481. return;
  482. }
  483. #ifdef PNG_WRITE_OPTIMIZE_CMF_SUPPORTED
  484. /* The zbuf_size test is because the code below doesn't work if zbuf_size is
  485. * '1'; simply skip it to avoid memory overwrite.
  486. */
  487. if (data_len >= 2 && comp->input_len < 16384 && png_ptr->zbuf_size > 1)
  488. {
  489. unsigned int z_cmf; /* zlib compression method and flags */
  490. /* Optimize the CMF field in the zlib stream. This hack of the zlib
  491. * stream is compliant to the stream specification.
  492. */
  493. if (comp->num_output_ptr)
  494. z_cmf = comp->output_ptr[0][0];
  495. else
  496. z_cmf = png_ptr->zbuf[0];
  497. if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
  498. {
  499. unsigned int z_cinfo;
  500. unsigned int half_z_window_size;
  501. png_size_t uncompressed_text_size = comp->input_len;
  502. z_cinfo = z_cmf >> 4;
  503. half_z_window_size = 1 << (z_cinfo + 7);
  504. while (uncompressed_text_size <= half_z_window_size &&
  505. half_z_window_size >= 256)
  506. {
  507. z_cinfo--;
  508. half_z_window_size >>= 1;
  509. }
  510. z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
  511. if (comp->num_output_ptr)
  512. {
  513. if (comp->output_ptr[0][0] != z_cmf)
  514. {
  515. int tmp;
  516. comp->output_ptr[0][0] = (png_byte)z_cmf;
  517. tmp = comp->output_ptr[0][1] & 0xe0;
  518. tmp += 0x1f - ((z_cmf << 8) + tmp) % 0x1f;
  519. comp->output_ptr[0][1] = (png_byte)tmp;
  520. }
  521. }
  522. else
  523. {
  524. int tmp;
  525. png_ptr->zbuf[0] = (png_byte)z_cmf;
  526. tmp = png_ptr->zbuf[1] & 0xe0;
  527. tmp += 0x1f - ((z_cmf << 8) + tmp) % 0x1f;
  528. png_ptr->zbuf[1] = (png_byte)tmp;
  529. }
  530. }
  531. else
  532. png_error(png_ptr,
  533. "Invalid zlib compression method or flags in non-IDAT chunk");
  534. }
  535. #endif /* PNG_WRITE_OPTIMIZE_CMF_SUPPORTED */
  536. /* Write saved output buffers, if any */
  537. for (i = 0; i < comp->num_output_ptr; i++)
  538. {
  539. png_write_chunk_data(png_ptr, comp->output_ptr[i],
  540. (png_size_t)png_ptr->zbuf_size);
  541. png_free(png_ptr, comp->output_ptr[i]);
  542. }
  543. if (comp->max_output_ptr != 0)
  544. png_free(png_ptr, comp->output_ptr);
  545. /* Write anything left in zbuf */
  546. if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
  547. png_write_chunk_data(png_ptr, png_ptr->zbuf,
  548. (png_size_t)(png_ptr->zbuf_size - png_ptr->zstream.avail_out));
  549. /* Reset zlib for another zTXt/iTXt or image data */
  550. png_zlib_release(png_ptr);
  551. }
  552. #endif /* PNG_WRITE_COMPRESSED_TEXT_SUPPORTED */
  553. /* Write the IHDR chunk, and update the png_struct with the necessary
  554. * information. Note that the rest of this code depends upon this
  555. * information being correct.
  556. */
  557. void /* PRIVATE */
  558. png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
  559. int bit_depth, int color_type, int compression_type, int filter_type,
  560. int interlace_type)
  561. {
  562. png_byte buf[13]; /* Buffer to store the IHDR info */
  563. png_debug(1, "in png_write_IHDR");
  564. /* Check that we have valid input data from the application info */
  565. switch (color_type)
  566. {
  567. case PNG_COLOR_TYPE_GRAY:
  568. switch (bit_depth)
  569. {
  570. case 1:
  571. case 2:
  572. case 4:
  573. case 8:
  574. #ifdef PNG_WRITE_16BIT_SUPPORTED
  575. case 16:
  576. #endif
  577. png_ptr->channels = 1; break;
  578. default:
  579. png_error(png_ptr,
  580. "Invalid bit depth for grayscale image");
  581. }
  582. break;
  583. case PNG_COLOR_TYPE_RGB:
  584. #ifdef PNG_WRITE_16BIT_SUPPORTED
  585. if (bit_depth != 8 && bit_depth != 16)
  586. #else
  587. if (bit_depth != 8)
  588. #endif
  589. png_error(png_ptr, "Invalid bit depth for RGB image");
  590. png_ptr->channels = 3;
  591. break;
  592. case PNG_COLOR_TYPE_PALETTE:
  593. switch (bit_depth)
  594. {
  595. case 1:
  596. case 2:
  597. case 4:
  598. case 8:
  599. png_ptr->channels = 1;
  600. break;
  601. default:
  602. png_error(png_ptr, "Invalid bit depth for paletted image");
  603. }
  604. break;
  605. case PNG_COLOR_TYPE_GRAY_ALPHA:
  606. if (bit_depth != 8 && bit_depth != 16)
  607. png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
  608. png_ptr->channels = 2;
  609. break;
  610. case PNG_COLOR_TYPE_RGB_ALPHA:
  611. #ifdef PNG_WRITE_16BIT_SUPPORTED
  612. if (bit_depth != 8 && bit_depth != 16)
  613. #else
  614. if (bit_depth != 8)
  615. #endif
  616. png_error(png_ptr, "Invalid bit depth for RGBA image");
  617. png_ptr->channels = 4;
  618. break;
  619. default:
  620. png_error(png_ptr, "Invalid image color type specified");
  621. }
  622. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  623. {
  624. png_warning(png_ptr, "Invalid compression type specified");
  625. compression_type = PNG_COMPRESSION_TYPE_BASE;
  626. }
  627. /* Write filter_method 64 (intrapixel differencing) only if
  628. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  629. * 2. Libpng did not write a PNG signature (this filter_method is only
  630. * used in PNG datastreams that are embedded in MNG datastreams) and
  631. * 3. The application called png_permit_mng_features with a mask that
  632. * included PNG_FLAG_MNG_FILTER_64 and
  633. * 4. The filter_method is 64 and
  634. * 5. The color_type is RGB or RGBA
  635. */
  636. if (
  637. #ifdef PNG_MNG_FEATURES_SUPPORTED
  638. !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  639. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  640. (color_type == PNG_COLOR_TYPE_RGB ||
  641. color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
  642. (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
  643. #endif
  644. filter_type != PNG_FILTER_TYPE_BASE)
  645. {
  646. png_warning(png_ptr, "Invalid filter type specified");
  647. filter_type = PNG_FILTER_TYPE_BASE;
  648. }
  649. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  650. if (interlace_type != PNG_INTERLACE_NONE &&
  651. interlace_type != PNG_INTERLACE_ADAM7)
  652. {
  653. png_warning(png_ptr, "Invalid interlace type specified");
  654. interlace_type = PNG_INTERLACE_ADAM7;
  655. }
  656. #else
  657. interlace_type=PNG_INTERLACE_NONE;
  658. #endif
  659. /* Save the relevent information */
  660. png_ptr->bit_depth = (png_byte)bit_depth;
  661. png_ptr->color_type = (png_byte)color_type;
  662. png_ptr->interlaced = (png_byte)interlace_type;
  663. #ifdef PNG_MNG_FEATURES_SUPPORTED
  664. png_ptr->filter_type = (png_byte)filter_type;
  665. #endif
  666. png_ptr->compression_type = (png_byte)compression_type;
  667. png_ptr->width = width;
  668. png_ptr->height = height;
  669. png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
  670. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
  671. /* Set the usr info, so any transformations can modify it */
  672. png_ptr->usr_width = png_ptr->width;
  673. png_ptr->usr_bit_depth = png_ptr->bit_depth;
  674. png_ptr->usr_channels = png_ptr->channels;
  675. /* Pack the header information into the buffer */
  676. png_save_uint_32(buf, width);
  677. png_save_uint_32(buf + 4, height);
  678. buf[8] = (png_byte)bit_depth;
  679. buf[9] = (png_byte)color_type;
  680. buf[10] = (png_byte)compression_type;
  681. buf[11] = (png_byte)filter_type;
  682. buf[12] = (png_byte)interlace_type;
  683. /* Write the chunk */
  684. png_write_complete_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
  685. /* Initialize zlib with PNG info */
  686. png_ptr->zstream.zalloc = png_zalloc;
  687. png_ptr->zstream.zfree = png_zfree;
  688. png_ptr->zstream.opaque = (voidpf)png_ptr;
  689. if ((png_ptr->do_filter) == PNG_NO_FILTERS)
  690. {
  691. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
  692. png_ptr->bit_depth < 8)
  693. png_ptr->do_filter = PNG_FILTER_NONE;
  694. else
  695. png_ptr->do_filter = PNG_ALL_FILTERS;
  696. }
  697. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
  698. {
  699. if (png_ptr->do_filter != PNG_FILTER_NONE)
  700. png_ptr->zlib_strategy = Z_FILTERED;
  701. else
  702. png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
  703. }
  704. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
  705. png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
  706. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
  707. png_ptr->zlib_mem_level = 8;
  708. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
  709. png_ptr->zlib_window_bits = 15;
  710. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
  711. png_ptr->zlib_method = 8;
  712. #ifdef PNG_WRITE_COMPRESSED_TEXT_SUPPORTED
  713. #ifdef PNG_WRITE_CUSTOMIZE_ZTXT_COMPRESSION_SUPPORTED
  714. if (!(png_ptr->flags & PNG_FLAG_ZTXT_CUSTOM_STRATEGY))
  715. png_ptr->zlib_text_strategy = Z_DEFAULT_STRATEGY;
  716. if (!(png_ptr->flags & PNG_FLAG_ZTXT_CUSTOM_LEVEL))
  717. png_ptr->zlib_text_level = png_ptr->zlib_level;
  718. if (!(png_ptr->flags & PNG_FLAG_ZTXT_CUSTOM_MEM_LEVEL))
  719. png_ptr->zlib_text_mem_level = png_ptr->zlib_mem_level;
  720. if (!(png_ptr->flags & PNG_FLAG_ZTXT_CUSTOM_WINDOW_BITS))
  721. png_ptr->zlib_text_window_bits = png_ptr->zlib_window_bits;
  722. if (!(png_ptr->flags & PNG_FLAG_ZTXT_CUSTOM_METHOD))
  723. png_ptr->zlib_text_method = png_ptr->zlib_method;
  724. #else
  725. png_ptr->zlib_text_strategy = Z_DEFAULT_STRATEGY;
  726. png_ptr->zlib_text_level = png_ptr->zlib_level;
  727. png_ptr->zlib_text_mem_level = png_ptr->zlib_mem_level;
  728. png_ptr->zlib_text_window_bits = png_ptr->zlib_window_bits;
  729. png_ptr->zlib_text_method = png_ptr->zlib_method;
  730. #endif /* PNG_WRITE_CUSTOMIZE_ZTXT_COMPRESSION_SUPPORTED */
  731. #endif /* PNG_WRITE_COMPRESSED_TEXT_SUPPORTED */
  732. /* Record that the compressor has not yet been initialized. */
  733. png_ptr->zlib_state = PNG_ZLIB_UNINITIALIZED;
  734. png_ptr->mode = PNG_HAVE_IHDR; /* not READY_FOR_ZTXT */
  735. }
  736. /* Write the palette. We are careful not to trust png_color to be in the
  737. * correct order for PNG, so people can redefine it to any convenient
  738. * structure.
  739. */
  740. void /* PRIVATE */
  741. png_write_PLTE(png_structp png_ptr, png_const_colorp palette,
  742. png_uint_32 num_pal)
  743. {
  744. png_uint_32 max_palette_length, i;
  745. png_const_colorp pal_ptr;
  746. png_byte buf[3];
  747. png_debug(1, "in png_write_PLTE");
  748. max_palette_length = (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ?
  749. (1 << png_ptr->bit_depth) : PNG_MAX_PALETTE_LENGTH;
  750. if ((
  751. #ifdef PNG_MNG_FEATURES_SUPPORTED
  752. !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
  753. #endif
  754. num_pal == 0) || num_pal > max_palette_length)
  755. {
  756. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  757. {
  758. png_error(png_ptr, "Invalid number of colors in palette");
  759. }
  760. else
  761. {
  762. png_warning(png_ptr, "Invalid number of colors in palette");
  763. return;
  764. }
  765. }
  766. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  767. {
  768. png_warning(png_ptr,
  769. "Ignoring request to write a PLTE chunk in grayscale PNG");
  770. return;
  771. }
  772. png_ptr->num_palette = (png_uint_16)num_pal;
  773. png_debug1(3, "num_palette = %d", png_ptr->num_palette);
  774. png_write_chunk_header(png_ptr, png_PLTE, (png_uint_32)(num_pal * 3));
  775. #ifdef PNG_POINTER_INDEXING_SUPPORTED
  776. for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
  777. {
  778. buf[0] = pal_ptr->red;
  779. buf[1] = pal_ptr->green;
  780. buf[2] = pal_ptr->blue;
  781. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  782. }
  783. #else
  784. /* This is a little slower but some buggy compilers need to do this
  785. * instead
  786. */
  787. pal_ptr=palette;
  788. for (i = 0; i < num_pal; i++)
  789. {
  790. buf[0] = pal_ptr[i].red;
  791. buf[1] = pal_ptr[i].green;
  792. buf[2] = pal_ptr[i].blue;
  793. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  794. }
  795. #endif
  796. png_write_chunk_end(png_ptr);
  797. png_ptr->mode |= PNG_HAVE_PLTE;
  798. }
  799. /* Write an IDAT chunk */
  800. void /* PRIVATE */
  801. png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
  802. {
  803. png_debug(1, "in png_write_IDAT");
  804. #ifdef PNG_WRITE_OPTIMIZE_CMF_SUPPORTED
  805. if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
  806. png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
  807. {
  808. /* Optimize the CMF field in the zlib stream. This hack of the zlib
  809. * stream is compliant to the stream specification.
  810. */
  811. unsigned int z_cmf = data[0]; /* zlib compression method and flags */
  812. if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
  813. {
  814. /* Avoid memory underflows and multiplication overflows.
  815. *
  816. * The conditions below are practically always satisfied;
  817. * however, they still must be checked.
  818. */
  819. if (length >= 2 &&
  820. png_ptr->height < 16384 && png_ptr->width < 16384)
  821. {
  822. /* Compute the maximum possible length of the datastream */
  823. /* Number of pixels, plus for each row a filter byte
  824. * and possibly a padding byte, so increase the maximum
  825. * size to account for these.
  826. */
  827. unsigned int z_cinfo;
  828. unsigned int half_z_window_size;
  829. png_uint_32 uncompressed_idat_size = png_ptr->height *
  830. ((png_ptr->width *
  831. png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
  832. /* If it's interlaced, each block of 8 rows is sent as up to
  833. * 14 rows, i.e., 6 additional rows, each with a filter byte
  834. * and possibly a padding byte
  835. */
  836. if (png_ptr->interlaced)
  837. uncompressed_idat_size += ((png_ptr->height + 7)/8) *
  838. (png_ptr->bit_depth < 8 ? 12 : 6);
  839. z_cinfo = z_cmf >> 4;
  840. half_z_window_size = 1 << (z_cinfo + 7);
  841. while (uncompressed_idat_size <= half_z_window_size &&
  842. half_z_window_size >= 256)
  843. {
  844. z_cinfo--;
  845. half_z_window_size >>= 1;
  846. }
  847. z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
  848. if (data[0] != z_cmf)
  849. {
  850. int tmp;
  851. data[0] = (png_byte)z_cmf;
  852. tmp = data[1] & 0xe0;
  853. tmp += 0x1f - ((z_cmf << 8) + tmp) % 0x1f;
  854. data[1] = (png_byte)tmp;
  855. }
  856. }
  857. }
  858. else
  859. png_error(png_ptr,
  860. "Invalid zlib compression method or flags in IDAT");
  861. }
  862. #endif /* PNG_WRITE_OPTIMIZE_CMF_SUPPORTED */
  863. png_write_complete_chunk(png_ptr, png_IDAT, data, length);
  864. png_ptr->mode |= PNG_HAVE_IDAT;
  865. /* Prior to 1.5.4 this code was replicated in every caller (except at the
  866. * end, where it isn't technically necessary). Since this function has
  867. * flushed the data we can safely reset the zlib output buffer here.
  868. */
  869. png_ptr->zstream.next_out = png_ptr->zbuf;
  870. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  871. }
  872. /* Write an IEND chunk */
  873. void /* PRIVATE */
  874. png_write_IEND(png_structp png_ptr)
  875. {
  876. png_debug(1, "in png_write_IEND");
  877. png_write_complete_chunk(png_ptr, png_IEND, NULL, (png_size_t)0);
  878. png_ptr->mode |= PNG_HAVE_IEND;
  879. }
  880. #ifdef PNG_WRITE_gAMA_SUPPORTED
  881. /* Write a gAMA chunk */
  882. void /* PRIVATE */
  883. png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
  884. {
  885. png_byte buf[4];
  886. png_debug(1, "in png_write_gAMA");
  887. /* file_gamma is saved in 1/100,000ths */
  888. png_save_uint_32(buf, (png_uint_32)file_gamma);
  889. png_write_complete_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  890. }
  891. #endif
  892. #ifdef PNG_WRITE_sRGB_SUPPORTED
  893. /* Write a sRGB chunk */
  894. void /* PRIVATE */
  895. png_write_sRGB(png_structp png_ptr, int srgb_intent)
  896. {
  897. png_byte buf[1];
  898. png_debug(1, "in png_write_sRGB");
  899. if (srgb_intent >= PNG_sRGB_INTENT_LAST)
  900. png_warning(png_ptr,
  901. "Invalid sRGB rendering intent specified");
  902. buf[0]=(png_byte)srgb_intent;
  903. png_write_complete_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
  904. }
  905. #endif
  906. #ifdef PNG_WRITE_iCCP_SUPPORTED
  907. /* Write an iCCP chunk */
  908. void /* PRIVATE */
  909. png_write_iCCP(png_structp png_ptr, png_const_charp name, int compression_type,
  910. png_const_charp profile, int profile_len)
  911. {
  912. png_size_t name_len;
  913. compression_state comp;
  914. int embedded_profile_len = 0;
  915. png_debug(1, "in png_write_iCCP");
  916. comp.num_output_ptr = 0;
  917. comp.max_output_ptr = 0;
  918. comp.output_ptr = NULL;
  919. comp.input = NULL;
  920. comp.input_len = 0;
  921. name_len = png_strlen(name);
  922. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  923. png_warning(png_ptr, "Unknown compression type in iCCP chunk");
  924. if (profile == NULL)
  925. profile_len = 0;
  926. if (profile_len > 3)
  927. embedded_profile_len =
  928. ((*( (png_const_bytep)profile ))<<24) |
  929. ((*( (png_const_bytep)profile + 1))<<16) |
  930. ((*( (png_const_bytep)profile + 2))<< 8) |
  931. ((*( (png_const_bytep)profile + 3)) );
  932. if (embedded_profile_len < 0)
  933. {
  934. png_warning(png_ptr,
  935. "Embedded profile length in iCCP chunk is negative");
  936. return;
  937. }
  938. if (profile_len < embedded_profile_len)
  939. {
  940. png_warning(png_ptr,
  941. "Embedded profile length too large in iCCP chunk");
  942. return;
  943. }
  944. if (profile_len > embedded_profile_len)
  945. {
  946. png_warning(png_ptr,
  947. "Truncating profile to actual length in iCCP chunk");
  948. profile_len = embedded_profile_len;
  949. }
  950. if (profile_len != 0)
  951. profile_len = png_text_compress(png_ptr, profile,
  952. (png_size_t)profile_len, PNG_COMPRESSION_TYPE_BASE, &comp);
  953. /* Make sure we include the NULL after the name and the compression type */
  954. png_write_chunk_header(png_ptr, png_iCCP,
  955. (png_uint_32)(name_len + profile_len + 2));
  956. png_write_chunk_data(png_ptr, (png_bytep)name, name_len);
  957. {
  958. png_byte buffer[2];
  959. buffer[0] = 0; /* terminate name */
  960. buffer[1] = 0xFFU & compression_type;
  961. png_write_chunk_data(png_ptr, buffer, 2);
  962. }
  963. if (profile_len != 0)
  964. {
  965. png_write_compressed_data_out(png_ptr, &comp, profile_len);
  966. }
  967. png_write_chunk_end(png_ptr);
  968. }
  969. #endif
  970. #ifdef PNG_WRITE_sPLT_SUPPORTED
  971. /* Write a sPLT chunk */
  972. void /* PRIVATE */
  973. png_write_sPLT(png_structp png_ptr, png_const_sPLT_tp spalette)
  974. {
  975. png_size_t name_len;
  976. png_byte entrybuf[10];
  977. png_size_t entry_size = (spalette->depth == 8 ? 6 : 10);
  978. png_size_t palette_size = entry_size * spalette->nentries;
  979. png_sPLT_entryp ep;
  980. #ifndef PNG_POINTER_INDEXING_SUPPORTED
  981. int i;
  982. #endif
  983. png_debug(1, "in png_write_sPLT");
  984. name_len = png_strlen(spalette->name);
  985. /* Make sure we include the NULL after the name */
  986. png_write_chunk_header(png_ptr, png_sPLT,
  987. (png_uint_32)(name_len + 2 + palette_size));
  988. png_write_chunk_data(png_ptr, (png_bytep)spalette->name,
  989. (png_size_t)(name_len + 1));
  990. png_write_chunk_data(png_ptr, &spalette->depth, (png_size_t)1);
  991. /* Loop through each palette entry, writing appropriately */
  992. #ifdef PNG_POINTER_INDEXING_SUPPORTED
  993. for (ep = spalette->entries; ep<spalette->entries + spalette->nentries; ep++)
  994. {
  995. if (spalette->depth == 8)
  996. {
  997. entrybuf[0] = (png_byte)ep->red;
  998. entrybuf[1] = (png_byte)ep->green;
  999. entrybuf[2] = (png_byte)ep->blue;
  1000. entrybuf[3] = (png_byte)ep->alpha;
  1001. png_save_uint_16(entrybuf + 4, ep->frequency);
  1002. }
  1003. else
  1004. {
  1005. png_save_uint_16(entrybuf + 0, ep->red);
  1006. png_save_uint_16(entrybuf + 2, ep->green);
  1007. png_save_uint_16(entrybuf + 4, ep->blue);
  1008. png_save_uint_16(entrybuf + 6, ep->alpha);
  1009. png_save_uint_16(entrybuf + 8, ep->frequency);
  1010. }
  1011. png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  1012. }
  1013. #else
  1014. ep=spalette->entries;
  1015. for (i = 0; i>spalette->nentries; i++)
  1016. {
  1017. if (spalette->depth == 8)
  1018. {
  1019. entrybuf[0] = (png_byte)ep[i].red;
  1020. entrybuf[1] = (png_byte)ep[i].green;
  1021. entrybuf[2] = (png_byte)ep[i].blue;
  1022. entrybuf[3] = (png_byte)ep[i].alpha;
  1023. png_save_uint_16(entrybuf + 4, ep[i].frequency);
  1024. }
  1025. else
  1026. {
  1027. png_save_uint_16(entrybuf + 0, ep[i].red);
  1028. png_save_uint_16(entrybuf + 2, ep[i].green);
  1029. png_save_uint_16(entrybuf + 4, ep[i].blue);
  1030. png_save_uint_16(entrybuf + 6, ep[i].alpha);
  1031. png_save_uint_16(entrybuf + 8, ep[i].frequency);
  1032. }
  1033. png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  1034. }
  1035. #endif
  1036. png_write_chunk_end(png_ptr);
  1037. }
  1038. #endif
  1039. #ifdef PNG_WRITE_sBIT_SUPPORTED
  1040. /* Write the sBIT chunk */
  1041. void /* PRIVATE */
  1042. png_write_sBIT(png_structp png_ptr, png_const_color_8p sbit, int color_type)
  1043. {
  1044. png_byte buf[4];
  1045. png_size_t size;
  1046. png_debug(1, "in png_write_sBIT");
  1047. /* Make sure we don't depend upon the order of PNG_COLOR_8 */
  1048. if (color_type & PNG_COLOR_MASK_COLOR)
  1049. {
  1050. png_byte maxbits;
  1051. maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
  1052. png_ptr->usr_bit_depth);
  1053. if (sbit->red == 0 || sbit->red > maxbits ||
  1054. sbit->green == 0 || sbit->green > maxbits ||
  1055. sbit->blue == 0 || sbit->blue > maxbits)
  1056. {
  1057. png_warning(png_ptr, "Invalid sBIT depth specified");
  1058. return;
  1059. }
  1060. buf[0] = sbit->red;
  1061. buf[1] = sbit->green;
  1062. buf[2] = sbit->blue;
  1063. size = 3;
  1064. }
  1065. else
  1066. {
  1067. if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
  1068. {
  1069. png_warning(png_ptr, "Invalid sBIT depth specified");
  1070. return;
  1071. }
  1072. buf[0] = sbit->gray;
  1073. size = 1;
  1074. }
  1075. if (color_type & PNG_COLOR_MASK_ALPHA)
  1076. {
  1077. if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
  1078. {
  1079. png_warning(png_ptr, "Invalid sBIT depth specified");
  1080. return;
  1081. }
  1082. buf[size++] = sbit->alpha;
  1083. }
  1084. png_write_complete_chunk(png_ptr, png_sBIT, buf, size);
  1085. }
  1086. #endif
  1087. #ifdef PNG_WRITE_cHRM_SUPPORTED
  1088. /* Write the cHRM chunk */
  1089. void /* PRIVATE */
  1090. png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
  1091. png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
  1092. png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
  1093. png_fixed_point blue_y)
  1094. {
  1095. png_byte buf[32];
  1096. png_debug(1, "in png_write_cHRM");
  1097. /* Each value is saved in 1/100,000ths */
  1098. #ifdef PNG_CHECK_cHRM_SUPPORTED
  1099. if (png_check_cHRM_fixed(png_ptr, white_x, white_y, red_x, red_y,
  1100. green_x, green_y, blue_x, blue_y))
  1101. #endif
  1102. {
  1103. png_save_uint_32(buf, (png_uint_32)white_x);
  1104. png_save_uint_32(buf + 4, (png_uint_32)white_y);
  1105. png_save_uint_32(buf + 8, (png_uint_32)red_x);
  1106. png_save_uint_32(buf + 12, (png_uint_32)red_y);
  1107. png_save_uint_32(buf + 16, (png_uint_32)green_x);
  1108. png_save_uint_32(buf + 20, (png_uint_32)green_y);
  1109. png_save_uint_32(buf + 24, (png_uint_32)blue_x);
  1110. png_save_uint_32(buf + 28, (png_uint_32)blue_y);
  1111. png_write_complete_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  1112. }
  1113. }
  1114. #endif
  1115. #ifdef PNG_WRITE_tRNS_SUPPORTED
  1116. /* Write the tRNS chunk */
  1117. void /* PRIVATE */
  1118. png_write_tRNS(png_structp png_ptr, png_const_bytep trans_alpha,
  1119. png_const_color_16p tran, int num_trans, int color_type)
  1120. {
  1121. png_byte buf[6];
  1122. png_debug(1, "in png_write_tRNS");
  1123. if (color_type == PNG_COLOR_TYPE_PALETTE)
  1124. {
  1125. if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
  1126. {
  1127. png_warning(png_ptr, "Invalid number of transparent colors specified");
  1128. return;
  1129. }
  1130. /* Write the chunk out as it is */
  1131. png_write_complete_chunk(png_ptr, png_tRNS, trans_alpha,
  1132. (png_size_t)num_trans);
  1133. }
  1134. else if (color_type == PNG_COLOR_TYPE_GRAY)
  1135. {
  1136. /* One 16 bit value */
  1137. if (tran->gray >= (1 << png_ptr->bit_depth))
  1138. {
  1139. png_warning(png_ptr,
  1140. "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
  1141. return;
  1142. }
  1143. png_save_uint_16(buf, tran->gray);
  1144. png_write_complete_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
  1145. }
  1146. else if (color_type == PNG_COLOR_TYPE_RGB)
  1147. {
  1148. /* Three 16 bit values */
  1149. png_save_uint_16(buf, tran->red);
  1150. png_save_uint_16(buf + 2, tran->green);
  1151. png_save_uint_16(buf + 4, tran->blue);
  1152. #ifdef PNG_WRITE_16BIT_SUPPORTED
  1153. if (png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  1154. #else
  1155. if (buf[0] | buf[2] | buf[4])
  1156. #endif
  1157. {
  1158. png_warning(png_ptr,
  1159. "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
  1160. return;
  1161. }
  1162. png_write_complete_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
  1163. }
  1164. else
  1165. {
  1166. png_warning(png_ptr, "Can't write tRNS with an alpha channel");
  1167. }
  1168. }
  1169. #endif
  1170. #ifdef PNG_WRITE_bKGD_SUPPORTED
  1171. /* Write the background chunk */
  1172. void /* PRIVATE */
  1173. png_write_bKGD(png_structp png_ptr, png_const_color_16p back, int color_type)
  1174. {
  1175. png_byte buf[6];
  1176. png_debug(1, "in png_write_bKGD");
  1177. if (color_type == PNG_COLOR_TYPE_PALETTE)
  1178. {
  1179. if (
  1180. #ifdef PNG_MNG_FEATURES_SUPPORTED
  1181. (png_ptr->num_palette ||
  1182. (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
  1183. #endif
  1184. back->index >= png_ptr->num_palette)
  1185. {
  1186. png_warning(png_ptr, "Invalid background palette index");
  1187. return;
  1188. }
  1189. buf[0] = back->index;
  1190. png_write_complete_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
  1191. }
  1192. else if (color_type & PNG_COLOR_MASK_COLOR)
  1193. {
  1194. png_save_uint_16(buf, back->red);
  1195. png_save_uint_16(buf + 2, back->green);
  1196. png_save_uint_16(buf + 4, back->blue);
  1197. #ifdef PNG_WRITE_16BIT_SUPPORTED
  1198. if (png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  1199. #else
  1200. if (buf[0] | buf[2] | buf[4])
  1201. #endif
  1202. {
  1203. png_warning(png_ptr,
  1204. "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
  1205. return;
  1206. }
  1207. png_write_complete_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
  1208. }
  1209. else
  1210. {
  1211. if (back->gray >= (1 << png_ptr->bit_depth))
  1212. {
  1213. png_warning(png_ptr,
  1214. "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
  1215. return;
  1216. }
  1217. png_save_uint_16(buf, back->gray);
  1218. png_write_complete_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
  1219. }
  1220. }
  1221. #endif
  1222. #ifdef PNG_WRITE_hIST_SUPPORTED
  1223. /* Write the histogram */
  1224. void /* PRIVATE */
  1225. png_write_hIST(png_structp png_ptr, png_const_uint_16p hist, int num_hist)
  1226. {
  1227. int i;
  1228. png_byte buf[3];
  1229. png_debug(1, "in png_write_hIST");
  1230. if (num_hist > (int)png_ptr->num_palette)
  1231. {
  1232. png_debug2(3, "num_hist = %d, num_palette = %d", num_hist,
  1233. png_ptr->num_palette);
  1234. png_warning(png_ptr, "Invalid number of histogram entries specified");
  1235. return;
  1236. }
  1237. png_write_chunk_header(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
  1238. for (i = 0; i < num_hist; i++)
  1239. {
  1240. png_save_uint_16(buf, hist[i]);
  1241. png_write_chunk_data(png_ptr, buf, (png_size_t)2);
  1242. }
  1243. png_write_chunk_end(png_ptr);
  1244. }
  1245. #endif
  1246. #ifdef PNG_WRITE_tEXt_SUPPORTED
  1247. /* Write a tEXt chunk */
  1248. void /* PRIVATE */
  1249. png_write_tEXt(png_structp png_ptr, png_const_charp key, png_const_charp text,
  1250. png_size_t text_len)
  1251. {
  1252. png_size_t key_len;
  1253. png_debug(1, "in png_write_tEXt");
  1254. key_len = strlen(key);
  1255. if (text == NULL || *text == '\0')
  1256. text_len = 0;
  1257. else
  1258. text_len = png_strlen(text);
  1259. /* Make sure we include the 0 after the key */
  1260. png_write_chunk_header(png_ptr, png_tEXt,
  1261. (png_uint_32)(key_len + text_len + 1));
  1262. /*
  1263. * We leave it to the application to meet PNG-1.0 requirements on the
  1264. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  1265. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  1266. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  1267. */
  1268. png_write_chunk_data(png_ptr, (png_bytep)key,
  1269. (png_size_t)(key_len + 1));
  1270. if (text_len != 0)
  1271. png_write_chunk_data(png_ptr, (png_const_bytep)text,
  1272. (png_size_t)text_len);
  1273. png_write_chunk_end(png_ptr);
  1274. }
  1275. #endif
  1276. #ifdef PNG_WRITE_zTXt_SUPPORTED
  1277. /* Write a compressed text chunk */
  1278. void /* PRIVATE */
  1279. png_write_zTXt(png_structp png_ptr, png_const_charp key, png_const_charp text,
  1280. png_size_t text_len, int compression)
  1281. {
  1282. png_size_t key_len;
  1283. png_byte buf;
  1284. compression_state comp;
  1285. png_debug(1, "in png_write_zTXt");
  1286. comp.num_output_ptr = 0;
  1287. comp.max_output_ptr = 0;
  1288. comp.output_ptr = NULL;
  1289. comp.input = NULL;
  1290. comp.input_len = 0;
  1291. key_len = strlen(key);
  1292. if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
  1293. {
  1294. png_write_tEXt(png_ptr, key, text, (png_size_t)0);
  1295. return;
  1296. }
  1297. text_len = png_strlen(text);
  1298. /* Compute the compressed data; do it now for the length */
  1299. text_len = png_text_compress(png_ptr, text, text_len, compression,
  1300. &comp);
  1301. /* Write start of chunk */
  1302. png_write_chunk_header(png_ptr, png_zTXt,
  1303. (png_uint_32)(key_len+text_len + 2));
  1304. /* Write key */
  1305. png_write_chunk_data(png_ptr, (png_bytep)key,
  1306. (png_size_t)(key_len + 1));
  1307. buf = (png_byte)compression;
  1308. /* Write compression */
  1309. png_write_chunk_data(png_ptr, &buf, (png_size_t)1);
  1310. /* Write the compressed data */
  1311. png_write_compressed_data_out(png_ptr, &comp, text_len);
  1312. /* Close the chunk */
  1313. png_write_chunk_end(png_ptr);
  1314. }
  1315. #endif
  1316. #ifdef PNG_WRITE_iTXt_SUPPORTED
  1317. /* Write an iTXt chunk */
  1318. void /* PRIVATE */
  1319. png_write_iTXt(png_structp png_ptr, int compression, png_const_charp key,
  1320. png_const_charp lang, png_const_charp lang_key, png_const_charp text)
  1321. {
  1322. png_size_t lang_len, key_len, lang_key_len, text_len;
  1323. png_byte cbuf[2];
  1324. compression_state comp;
  1325. png_debug(1, "in png_write_iTXt");
  1326. comp.num_output_ptr = 0;
  1327. comp.max_output_ptr = 0;
  1328. comp.output_ptr = NULL;
  1329. comp.input = NULL;
  1330. key_len = png_strlen(key);
  1331. if (lang == NULL)
  1332. lang_len = 0;
  1333. else
  1334. lang_len = png_strlen(lang);
  1335. if (lang_key == NULL)
  1336. lang_key_len = 0;
  1337. else
  1338. lang_key_len = png_strlen(lang_key);
  1339. if (text == NULL)
  1340. text_len = 0;
  1341. else
  1342. text_len = png_strlen(text);
  1343. /* Compute the compressed data; do it now for the length */
  1344. text_len = png_text_compress(png_ptr, text, text_len, compression - 2,
  1345. &comp);
  1346. /* Make sure we include the compression flag, the compression byte,
  1347. * and the NULs after the key, lang, and lang_key parts
  1348. */
  1349. png_write_chunk_header(png_ptr, png_iTXt, (png_uint_32)(
  1350. 5 /* comp byte, comp flag, terminators for key, lang and lang_key */
  1351. + key_len
  1352. + lang_len
  1353. + lang_key_len
  1354. + text_len));
  1355. /* We leave it to the application to meet PNG-1.0 requirements on the
  1356. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  1357. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  1358. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  1359. */
  1360. png_write_chunk_data(png_ptr, (png_bytep)key, (png_size_t)(key_len + 1));
  1361. /* Set the compression flag */
  1362. if (compression == PNG_ITXT_COMPRESSION_NONE ||
  1363. compression == PNG_TEXT_COMPRESSION_NONE)
  1364. cbuf[0] = 0;
  1365. else /* compression == PNG_ITXT_COMPRESSION_zTXt */
  1366. cbuf[0] = 1;
  1367. /* Set the compression method */
  1368. cbuf[1] = 0;
  1369. png_write_chunk_data(png_ptr, cbuf, (png_size_t)2);
  1370. cbuf[0] = 0;
  1371. png_write_chunk_data(png_ptr, (lang ? (png_const_bytep)lang : cbuf),
  1372. (png_size_t)(lang_len + 1));
  1373. png_write_chunk_data(png_ptr, (lang_key ? (png_const_bytep)lang_key : cbuf),
  1374. (png_size_t)(lang_key_len + 1));
  1375. png_write_compressed_data_out(png_ptr, &comp, text_len);
  1376. png_write_chunk_end(png_ptr);
  1377. }
  1378. #endif
  1379. #ifdef PNG_WRITE_oFFs_SUPPORTED
  1380. /* Write the oFFs chunk */
  1381. void /* PRIVATE */
  1382. png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
  1383. int unit_type)
  1384. {
  1385. png_byte buf[9];
  1386. png_debug(1, "in png_write_oFFs");
  1387. if (unit_type >= PNG_OFFSET_LAST)
  1388. png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
  1389. png_save_int_32(buf, x_offset);
  1390. png_save_int_32(buf + 4, y_offset);
  1391. buf[8] = (png_byte)unit_type;
  1392. png_write_complete_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
  1393. }
  1394. #endif
  1395. #ifdef PNG_WRITE_pCAL_SUPPORTED
  1396. /* Write the pCAL chunk (described in the PNG extensions document) */
  1397. void /* PRIVATE */
  1398. png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
  1399. png_int_32 X1, int type, int nparams, png_const_charp units,
  1400. png_charpp params)
  1401. {
  1402. png_size_t purpose_len, units_len, total_len;
  1403. png_size_tp params_len;
  1404. png_byte buf[10];
  1405. int i;
  1406. png_debug1(1, "in png_write_pCAL (%d parameters)", nparams);
  1407. if (type >= PNG_EQUATION_LAST)
  1408. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  1409. purpose_len = strlen(purpose) + 1;
  1410. png_debug1(3, "pCAL purpose length = %d", (int)purpose_len);
  1411. units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
  1412. png_debug1(3, "pCAL units length = %d", (int)units_len);
  1413. total_len = purpose_len + units_len + 10;
  1414. params_len = (png_size_tp)png_malloc(png_ptr,
  1415. (png_alloc_size_t)(nparams * png_sizeof(png_size_t)));
  1416. /* Find the length of each parameter, making sure we don't count the
  1417. * null terminator for the last parameter.
  1418. */
  1419. for (i = 0; i < nparams; i++)
  1420. {
  1421. params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
  1422. png_debug2(3, "pCAL parameter %d length = %lu", i,
  1423. (unsigned long)params_len[i]);
  1424. total_len += params_len[i];
  1425. }
  1426. png_debug1(3, "pCAL total length = %d", (int)total_len);
  1427. png_write_chunk_header(png_ptr, png_pCAL, (png_uint_32)total_len);
  1428. png_write_chunk_data(png_ptr, (png_const_bytep)purpose, purpose_len);
  1429. png_save_int_32(buf, X0);
  1430. png_save_int_32(buf + 4, X1);
  1431. buf[8] = (png_byte)type;
  1432. buf[9] = (png_byte)nparams;
  1433. png_write_chunk_data(png_ptr, buf, (png_size_t)10);
  1434. png_write_chunk_data(png_ptr, (png_const_bytep)units, (png_size_t)units_len);
  1435. for (i = 0; i < nparams; i++)
  1436. {
  1437. png_write_chunk_data(png_ptr, (png_const_bytep)params[i], params_len[i]);
  1438. }
  1439. png_free(png_ptr, params_len);
  1440. png_write_chunk_end(png_ptr);
  1441. }
  1442. #endif
  1443. #ifdef PNG_WRITE_sCAL_SUPPORTED
  1444. /* Write the sCAL chunk */
  1445. void /* PRIVATE */
  1446. png_write_sCAL_s(png_structp png_ptr, int unit, png_const_charp width,
  1447. png_const_charp height)
  1448. {
  1449. png_byte buf[64];
  1450. png_size_t wlen, hlen, total_len;
  1451. png_debug(1, "in png_write_sCAL_s");
  1452. wlen = png_strlen(width);
  1453. hlen = png_strlen(height);
  1454. total_len = wlen + hlen + 2;
  1455. if (total_len > 64)
  1456. {
  1457. png_warning(png_ptr, "Can't write sCAL (buffer too small)");
  1458. return;
  1459. }
  1460. buf[0] = (png_byte)unit;
  1461. png_memcpy(buf + 1, width, wlen + 1); /* Append the '\0' here */
  1462. png_memcpy(buf + wlen + 2, height, hlen); /* Do NOT append the '\0' here */
  1463. png_debug1(3, "sCAL total length = %u", (unsigned int)total_len);
  1464. png_write_complete_chunk(png_ptr, png_sCAL, buf, total_len);
  1465. }
  1466. #endif
  1467. #ifdef PNG_WRITE_pHYs_SUPPORTED
  1468. /* Write the pHYs chunk */
  1469. void /* PRIVATE */
  1470. png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
  1471. png_uint_32 y_pixels_per_unit,
  1472. int unit_type)
  1473. {
  1474. png_byte buf[9];
  1475. png_debug(1, "in png_write_pHYs");
  1476. if (unit_type >= PNG_RESOLUTION_LAST)
  1477. png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
  1478. png_save_uint_32(buf, x_pixels_per_unit);
  1479. png_save_uint_32(buf + 4, y_pixels_per_unit);
  1480. buf[8] = (png_byte)unit_type;
  1481. png_write_complete_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
  1482. }
  1483. #endif
  1484. #ifdef PNG_WRITE_tIME_SUPPORTED
  1485. /* Write the tIME chunk. Use either png_convert_from_struct_tm()
  1486. * or png_convert_from_time_t(), or fill in the structure yourself.
  1487. */
  1488. void /* PRIVATE */
  1489. png_write_tIME(png_structp png_ptr, png_const_timep mod_time)
  1490. {
  1491. png_byte buf[7];
  1492. png_debug(1, "in png_write_tIME");
  1493. if (mod_time->month > 12 || mod_time->month < 1 ||
  1494. mod_time->day > 31 || mod_time->day < 1 ||
  1495. mod_time->hour > 23 || mod_time->second > 60)
  1496. {
  1497. png_warning(png_ptr, "Invalid time specified for tIME chunk");
  1498. return;
  1499. }
  1500. png_save_uint_16(buf, mod_time->year);
  1501. buf[2] = mod_time->month;
  1502. buf[3] = mod_time->day;
  1503. buf[4] = mod_time->hour;
  1504. buf[5] = mod_time->minute;
  1505. buf[6] = mod_time->second;
  1506. png_write_complete_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
  1507. }
  1508. #endif
  1509. /* Initializes the row writing capability of libpng */
  1510. void /* PRIVATE */
  1511. png_write_start_row(png_structp png_ptr)
  1512. {
  1513. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  1514. /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  1515. /* Start of interlace block */
  1516. static PNG_CONST png_byte png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  1517. /* Offset to next interlace block */
  1518. static PNG_CONST png_byte png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  1519. /* Start of interlace block in the y direction */
  1520. static PNG_CONST png_byte png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  1521. /* Offset to next interlace block in the y direction */
  1522. static PNG_CONST png_byte png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  1523. #endif
  1524. png_alloc_size_t buf_size;
  1525. int usr_pixel_depth;
  1526. png_debug(1, "in png_write_start_row");
  1527. usr_pixel_depth = png_ptr->usr_channels * png_ptr->usr_bit_depth;
  1528. buf_size = PNG_ROWBYTES(usr_pixel_depth, png_ptr->width) + 1;
  1529. /* 1.5.6: added to allow checking in the row write code. */
  1530. png_ptr->transformed_pixel_depth = png_ptr->pixel_depth;
  1531. png_ptr->maximum_pixel_depth = (png_byte)usr_pixel_depth;
  1532. /* Set up row buffer */
  1533. png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, buf_size);
  1534. png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
  1535. #ifdef PNG_WRITE_FILTER_SUPPORTED
  1536. /* Set up filtering buffer, if using this filter */
  1537. if (png_ptr->do_filter & PNG_FILTER_SUB)
  1538. {
  1539. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr, png_ptr->rowbytes + 1);
  1540. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  1541. }
  1542. /* We only need to keep the previous row if we are using one of these. */
  1543. if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
  1544. {
  1545. /* Set up previous row buffer */
  1546. png_ptr->prev_row = (png_bytep)png_calloc(png_ptr, buf_size);
  1547. if (png_ptr->do_filter & PNG_FILTER_UP)
  1548. {
  1549. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  1550. png_ptr->rowbytes + 1);
  1551. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  1552. }
  1553. if (png_ptr->do_filter & PNG_FILTER_AVG)
  1554. {
  1555. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  1556. png_ptr->rowbytes + 1);
  1557. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  1558. }
  1559. if (png_ptr->do_filter & PNG_FILTER_PAETH)
  1560. {
  1561. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  1562. png_ptr->rowbytes + 1);
  1563. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  1564. }
  1565. }
  1566. #endif /* PNG_WRITE_FILTER_SUPPORTED */
  1567. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  1568. /* If interlaced, we need to set up width and height of pass */
  1569. if (png_ptr->interlaced)
  1570. {
  1571. if (!(png_ptr->transformations & PNG_INTERLACE))
  1572. {
  1573. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  1574. png_pass_ystart[0]) / png_pass_yinc[0];
  1575. png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
  1576. png_pass_start[0]) / png_pass_inc[0];
  1577. }
  1578. else
  1579. {
  1580. png_ptr->num_rows = png_ptr->height;
  1581. png_ptr->usr_width = png_ptr->width;
  1582. }
  1583. }
  1584. else
  1585. #endif
  1586. {
  1587. png_ptr->num_rows = png_ptr->height;
  1588. png_ptr->usr_width = png_ptr->width;
  1589. }
  1590. png_zlib_claim(png_ptr, PNG_ZLIB_FOR_IDAT);
  1591. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  1592. png_ptr->zstream.next_out = png_ptr->zbuf;
  1593. }
  1594. /* Internal use only. Called when finished processing a row of data. */
  1595. void /* PRIVATE */
  1596. png_write_finish_row(png_structp png_ptr)
  1597. {
  1598. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  1599. /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  1600. /* Start of interlace block */
  1601. static PNG_CONST png_byte png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  1602. /* Offset to next interlace block */
  1603. static PNG_CONST png_byte png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  1604. /* Start of interlace block in the y direction */
  1605. static PNG_CONST png_byte png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  1606. /* Offset to next interlace block in the y direction */
  1607. static PNG_CONST png_byte png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  1608. #endif
  1609. int ret;
  1610. png_debug(1, "in png_write_finish_row");
  1611. /* Next row */
  1612. png_ptr->row_number++;
  1613. /* See if we are done */
  1614. if (png_ptr->row_number < png_ptr->num_rows)
  1615. return;
  1616. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  1617. /* If interlaced, go to next pass */
  1618. if (png_ptr->interlaced)
  1619. {
  1620. png_ptr->row_number = 0;
  1621. if (png_ptr->transformations & PNG_INTERLACE)
  1622. {
  1623. png_ptr->pass++;
  1624. }
  1625. else
  1626. {
  1627. /* Loop until we find a non-zero width or height pass */
  1628. do
  1629. {
  1630. png_ptr->pass++;
  1631. if (png_ptr->pass >= 7)
  1632. break;
  1633. png_ptr->usr_width = (png_ptr->width +
  1634. png_pass_inc[png_ptr->pass] - 1 -
  1635. png_pass_start[png_ptr->pass]) /
  1636. png_pass_inc[png_ptr->pass];
  1637. png_ptr->num_rows = (png_ptr->height +
  1638. png_pass_yinc[png_ptr->pass] - 1 -
  1639. png_pass_ystart[png_ptr->pass]) /
  1640. png_pass_yinc[png_ptr->pass];
  1641. if (png_ptr->transformations & PNG_INTERLACE)
  1642. break;
  1643. } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
  1644. }
  1645. /* Reset the row above the image for the next pass */
  1646. if (png_ptr->pass < 7)
  1647. {
  1648. if (png_ptr->prev_row != NULL)
  1649. png_memset(png_ptr->prev_row, 0,
  1650. (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
  1651. png_ptr->usr_bit_depth, png_ptr->width)) + 1);
  1652. return;
  1653. }
  1654. }
  1655. #endif
  1656. /* If we get here, we've just written the last row, so we need
  1657. to flush the compressor */
  1658. do
  1659. {
  1660. /* Tell the compressor we are done */
  1661. ret = deflate(&png_ptr->zstream, Z_FINISH);
  1662. /* Check for an error */
  1663. if (ret == Z_OK)
  1664. {
  1665. /* Check to see if we need more room */
  1666. if (!(png_ptr->zstream.avail_out))
  1667. {
  1668. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  1669. png_ptr->zstream.next_out = png_ptr->zbuf;
  1670. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  1671. }
  1672. }
  1673. else if (ret != Z_STREAM_END)
  1674. {
  1675. if (png_ptr->zstream.msg != NULL)
  1676. png_error(png_ptr, png_ptr->zstream.msg);
  1677. else
  1678. png_error(png_ptr, "zlib error");
  1679. }
  1680. } while (ret != Z_STREAM_END);
  1681. /* Write any extra space */
  1682. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  1683. {
  1684. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
  1685. png_ptr->zstream.avail_out);
  1686. }
  1687. png_zlib_release(png_ptr);
  1688. png_ptr->zstream.data_type = Z_BINARY;
  1689. }
  1690. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  1691. /* Pick out the correct pixels for the interlace pass.
  1692. * The basic idea here is to go through the row with a source
  1693. * pointer and a destination pointer (sp and dp), and copy the
  1694. * correct pixels for the pass. As the row gets compacted,
  1695. * sp will always be >= dp, so we should never overwrite anything.
  1696. * See the default: case for the easiest code to understand.
  1697. */
  1698. void /* PRIVATE */
  1699. png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
  1700. {
  1701. /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  1702. /* Start of interlace block */
  1703. static PNG_CONST png_byte png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  1704. /* Offset to next interlace block */
  1705. static PNG_CONST png_byte png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  1706. png_debug(1, "in png_do_write_interlace");
  1707. /* We don't have to do anything on the last pass (6) */
  1708. if (pass < 6)
  1709. {
  1710. /* Each pixel depth is handled separately */
  1711. switch (row_info->pixel_depth)
  1712. {
  1713. case 1:
  1714. {
  1715. png_bytep sp;
  1716. png_bytep dp;
  1717. int shift;
  1718. int d;
  1719. int value;
  1720. png_uint_32 i;
  1721. png_uint_32 row_width = row_info->width;
  1722. dp = row;
  1723. d = 0;
  1724. shift = 7;
  1725. for (i = png_pass_start[pass]; i < row_width;
  1726. i += png_pass_inc[pass])
  1727. {
  1728. sp = row + (png_size_t)(i >> 3);
  1729. value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
  1730. d |= (value << shift);
  1731. if (shift == 0)
  1732. {
  1733. shift = 7;
  1734. *dp++ = (png_byte)d;
  1735. d = 0;
  1736. }
  1737. else
  1738. shift--;
  1739. }
  1740. if (shift != 7)
  1741. *dp = (png_byte)d;
  1742. break;
  1743. }
  1744. case 2:
  1745. {
  1746. png_bytep sp;
  1747. png_bytep dp;
  1748. int shift;
  1749. int d;
  1750. int value;
  1751. png_uint_32 i;
  1752. png_uint_32 row_width = row_info->width;
  1753. dp = row;
  1754. shift = 6;
  1755. d = 0;
  1756. for (i = png_pass_start[pass]; i < row_width;
  1757. i += png_pass_inc[pass])
  1758. {
  1759. sp = row + (png_size_t)(i >> 2);
  1760. value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
  1761. d |= (value << shift);
  1762. if (shift == 0)
  1763. {
  1764. shift = 6;
  1765. *dp++ = (png_byte)d;
  1766. d = 0;
  1767. }
  1768. else
  1769. shift -= 2;
  1770. }
  1771. if (shift != 6)
  1772. *dp = (png_byte)d;
  1773. break;
  1774. }
  1775. case 4:
  1776. {
  1777. png_bytep sp;
  1778. png_bytep dp;
  1779. int shift;
  1780. int d;
  1781. int value;
  1782. png_uint_32 i;
  1783. png_uint_32 row_width = row_info->width;
  1784. dp = row;
  1785. shift = 4;
  1786. d = 0;
  1787. for (i = png_pass_start[pass]; i < row_width;
  1788. i += png_pass_inc[pass])
  1789. {
  1790. sp = row + (png_size_t)(i >> 1);
  1791. value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
  1792. d |= (value << shift);
  1793. if (shift == 0)
  1794. {
  1795. shift = 4;
  1796. *dp++ = (png_byte)d;
  1797. d = 0;
  1798. }
  1799. else
  1800. shift -= 4;
  1801. }
  1802. if (shift != 4)
  1803. *dp = (png_byte)d;
  1804. break;
  1805. }
  1806. default:
  1807. {
  1808. png_bytep sp;
  1809. png_bytep dp;
  1810. png_uint_32 i;
  1811. png_uint_32 row_width = row_info->width;
  1812. png_size_t pixel_bytes;
  1813. /* Start at the beginning */
  1814. dp = row;
  1815. /* Find out how many bytes each pixel takes up */
  1816. pixel_bytes = (row_info->pixel_depth >> 3);
  1817. /* Loop through the row, only looking at the pixels that matter */
  1818. for (i = png_pass_start[pass]; i < row_width;
  1819. i += png_pass_inc[pass])
  1820. {
  1821. /* Find out where the original pixel is */
  1822. sp = row + (png_size_t)i * pixel_bytes;
  1823. /* Move the pixel */
  1824. if (dp != sp)
  1825. png_memcpy(dp, sp, pixel_bytes);
  1826. /* Next pixel */
  1827. dp += pixel_bytes;
  1828. }
  1829. break;
  1830. }
  1831. }
  1832. /* Set new row width */
  1833. row_info->width = (row_info->width +
  1834. png_pass_inc[pass] - 1 -
  1835. png_pass_start[pass]) /
  1836. png_pass_inc[pass];
  1837. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  1838. row_info->width);
  1839. }
  1840. }
  1841. #endif
  1842. /* This filters the row, chooses which filter to use, if it has not already
  1843. * been specified by the application, and then writes the row out with the
  1844. * chosen filter.
  1845. */
  1846. static void png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row,
  1847. png_size_t row_bytes);
  1848. #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
  1849. #define PNG_HISHIFT 10
  1850. #define PNG_LOMASK ((png_uint_32)0xffffL)
  1851. #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
  1852. void /* PRIVATE */
  1853. png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
  1854. {
  1855. png_bytep best_row;
  1856. #ifdef PNG_WRITE_FILTER_SUPPORTED
  1857. png_bytep prev_row, row_buf;
  1858. png_uint_32 mins, bpp;
  1859. png_byte filter_to_do = png_ptr->do_filter;
  1860. png_size_t row_bytes = row_info->rowbytes;
  1861. png_debug(1, "in png_write_find_filter");
  1862. /* Find out how many bytes offset each pixel is */
  1863. bpp = (row_info->pixel_depth + 7) >> 3;
  1864. prev_row = png_ptr->prev_row;
  1865. #endif
  1866. best_row = png_ptr->row_buf;
  1867. #ifdef PNG_WRITE_FILTER_SUPPORTED
  1868. row_buf = best_row;
  1869. mins = PNG_MAXSUM;
  1870. /* The prediction method we use is to find which method provides the
  1871. * smallest value when summing the absolute values of the distances
  1872. * from zero, using anything >= 128 as negative numbers. This is known
  1873. * as the "minimum sum of absolute differences" heuristic. Other
  1874. * heuristics are the "weighted minimum sum of absolute differences"
  1875. * (experimental and can in theory improve compression), and the "zlib
  1876. * predictive" method (not implemented yet), which does test compressions
  1877. * of lines using different filter methods, and then chooses the
  1878. * (series of) filter(s) that give minimum compressed data size (VERY
  1879. * computationally expensive).
  1880. *
  1881. * GRR 980525: consider also
  1882. *
  1883. * (1) minimum sum of absolute differences from running average (i.e.,
  1884. * keep running sum of non-absolute differences & count of bytes)
  1885. * [track dispersion, too? restart average if dispersion too large?]
  1886. *
  1887. * (1b) minimum sum of absolute differences from sliding average, probably
  1888. * with window size <= deflate window (usually 32K)
  1889. *
  1890. * (2) minimum sum of squared differences from zero or running average
  1891. * (i.e., ~ root-mean-square approach)
  1892. */
  1893. /* We don't need to test the 'no filter' case if this is the only filter
  1894. * that has been chosen, as it doesn't actually do anything to the data.
  1895. */
  1896. if ((filter_to_do & PNG_FILTER_NONE) && filter_to_do != PNG_FILTER_NONE)
  1897. {
  1898. png_bytep rp;
  1899. png_uint_32 sum = 0;
  1900. png_size_t i;
  1901. int v;
  1902. for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
  1903. {
  1904. v = *rp;
  1905. sum += (v < 128) ? v : 256 - v;
  1906. }
  1907. mins = sum;
  1908. }
  1909. /* Sub filter */
  1910. if (filter_to_do == PNG_FILTER_SUB)
  1911. /* It's the only filter so no testing is needed */
  1912. {
  1913. png_bytep rp, lp, dp;
  1914. png_size_t i;
  1915. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  1916. i++, rp++, dp++)
  1917. {
  1918. *dp = *rp;
  1919. }
  1920. for (lp = row_buf + 1; i < row_bytes;
  1921. i++, rp++, lp++, dp++)
  1922. {
  1923. *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  1924. }
  1925. best_row = png_ptr->sub_row;
  1926. }
  1927. else if (filter_to_do & PNG_FILTER_SUB)
  1928. {
  1929. png_bytep rp, dp, lp;
  1930. png_uint_32 sum = 0, lmins = mins;
  1931. png_size_t i;
  1932. int v;
  1933. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  1934. i++, rp++, dp++)
  1935. {
  1936. v = *dp = *rp;
  1937. sum += (v < 128) ? v : 256 - v;
  1938. }
  1939. for (lp = row_buf + 1; i < row_bytes;
  1940. i++, rp++, lp++, dp++)
  1941. {
  1942. v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  1943. sum += (v < 128) ? v : 256 - v;
  1944. if (sum > lmins) /* We are already worse, don't continue. */
  1945. break;
  1946. }
  1947. if (sum < mins)
  1948. {
  1949. mins = sum;
  1950. best_row = png_ptr->sub_row;
  1951. }
  1952. }
  1953. /* Up filter */
  1954. if (filter_to_do == PNG_FILTER_UP)
  1955. {
  1956. png_bytep rp, dp, pp;
  1957. png_size_t i;
  1958. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  1959. pp = prev_row + 1; i < row_bytes;
  1960. i++, rp++, pp++, dp++)
  1961. {
  1962. *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
  1963. }
  1964. best_row = png_ptr->up_row;
  1965. }
  1966. else if (filter_to_do & PNG_FILTER_UP)
  1967. {
  1968. png_bytep rp, dp, pp;
  1969. png_uint_32 sum = 0, lmins = mins;
  1970. png_size_t i;
  1971. int v;
  1972. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  1973. pp = prev_row + 1; i < row_bytes; i++)
  1974. {
  1975. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  1976. sum += (v < 128) ? v : 256 - v;
  1977. if (sum > lmins) /* We are already worse, don't continue. */
  1978. break;
  1979. }
  1980. if (sum < mins)
  1981. {
  1982. mins = sum;
  1983. best_row = png_ptr->up_row;
  1984. }
  1985. }
  1986. /* Avg filter */
  1987. if (filter_to_do == PNG_FILTER_AVG)
  1988. {
  1989. png_bytep rp, dp, pp, lp;
  1990. png_uint_32 i;
  1991. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  1992. pp = prev_row + 1; i < bpp; i++)
  1993. {
  1994. *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  1995. }
  1996. for (lp = row_buf + 1; i < row_bytes; i++)
  1997. {
  1998. *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
  1999. & 0xff);
  2000. }
  2001. best_row = png_ptr->avg_row;
  2002. }
  2003. else if (filter_to_do & PNG_FILTER_AVG)
  2004. {
  2005. png_bytep rp, dp, pp, lp;
  2006. png_uint_32 sum = 0, lmins = mins;
  2007. png_size_t i;
  2008. int v;
  2009. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  2010. pp = prev_row + 1; i < bpp; i++)
  2011. {
  2012. v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  2013. sum += (v < 128) ? v : 256 - v;
  2014. }
  2015. for (lp = row_buf + 1; i < row_bytes; i++)
  2016. {
  2017. v = *dp++ =
  2018. (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
  2019. sum += (v < 128) ? v : 256 - v;
  2020. if (sum > lmins) /* We are already worse, don't continue. */
  2021. break;
  2022. }
  2023. if (sum < mins)
  2024. {
  2025. mins = sum;
  2026. best_row = png_ptr->avg_row;
  2027. }
  2028. }
  2029. /* Paeth filter */
  2030. if (filter_to_do == PNG_FILTER_PAETH)
  2031. {
  2032. png_bytep rp, dp, pp, cp, lp;
  2033. png_size_t i;
  2034. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  2035. pp = prev_row + 1; i < bpp; i++)
  2036. {
  2037. *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  2038. }
  2039. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  2040. {
  2041. int a, b, c, pa, pb, pc, p;
  2042. b = *pp++;
  2043. c = *cp++;
  2044. a = *lp++;
  2045. p = b - c;
  2046. pc = a - c;
  2047. #ifdef PNG_USE_ABS
  2048. pa = abs(p);
  2049. pb = abs(pc);
  2050. pc = abs(p + pc);
  2051. #else
  2052. pa = p < 0 ? -p : p;
  2053. pb = pc < 0 ? -pc : pc;
  2054. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  2055. #endif
  2056. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  2057. *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  2058. }
  2059. best_row = png_ptr->paeth_row;
  2060. }
  2061. else if (filter_to_do & PNG_FILTER_PAETH)
  2062. {
  2063. png_bytep rp, dp, pp, cp, lp;
  2064. png_uint_32 sum = 0, lmins = mins;
  2065. png_size_t i;
  2066. int v;
  2067. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  2068. pp = prev_row + 1; i < bpp; i++)
  2069. {
  2070. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  2071. sum += (v < 128) ? v : 256 - v;
  2072. }
  2073. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  2074. {
  2075. int a, b, c, pa, pb, pc, p;
  2076. b = *pp++;
  2077. c = *cp++;
  2078. a = *lp++;
  2079. #ifndef PNG_SLOW_PAETH
  2080. p = b - c;
  2081. pc = a - c;
  2082. #ifdef PNG_USE_ABS
  2083. pa = abs(p);
  2084. pb = abs(pc);
  2085. pc = abs(p + pc);
  2086. #else
  2087. pa = p < 0 ? -p : p;
  2088. pb = pc < 0 ? -pc : pc;
  2089. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  2090. #endif
  2091. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  2092. #else /* PNG_SLOW_PAETH */
  2093. p = a + b - c;
  2094. pa = abs(p - a);
  2095. pb = abs(p - b);
  2096. pc = abs(p - c);
  2097. if (pa <= pb && pa <= pc)
  2098. p = a;
  2099. else if (pb <= pc)
  2100. p = b;
  2101. else
  2102. p = c;
  2103. #endif /* PNG_SLOW_PAETH */
  2104. v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  2105. sum += (v < 128) ? v : 256 - v;
  2106. if (sum > lmins) /* We are already worse, don't continue. */
  2107. break;
  2108. }
  2109. if (sum < mins)
  2110. {
  2111. best_row = png_ptr->paeth_row;
  2112. }
  2113. }
  2114. #endif /* PNG_WRITE_FILTER_SUPPORTED */
  2115. /* Do the actual writing of the filtered row data from the chosen filter. */
  2116. png_write_filtered_row(png_ptr, best_row, row_info->rowbytes+1);
  2117. }
  2118. /* Do the actual writing of a previously filtered row. */
  2119. static void
  2120. png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row,
  2121. png_size_t avail/*includes filter byte*/)
  2122. {
  2123. png_debug(1, "in png_write_filtered_row");
  2124. png_debug1(2, "filter = %d", filtered_row[0]);
  2125. /* Set up the zlib input buffer */
  2126. png_ptr->zstream.next_in = filtered_row;
  2127. png_ptr->zstream.avail_in = 0;
  2128. /* Repeat until we have compressed all the data */
  2129. do
  2130. {
  2131. int ret; /* Return of zlib */
  2132. /* Record the number of bytes available - zlib supports at least 65535
  2133. * bytes at one step, depending on the size of the zlib type 'uInt', the
  2134. * maximum size zlib can write at once is ZLIB_IO_MAX (from pngpriv.h).
  2135. * Use this because on 16 bit systems 'rowbytes' can be up to 65536 (i.e.
  2136. * one more than 16 bits) and, in this case 'rowbytes+1' can overflow a
  2137. * uInt. ZLIB_IO_MAX can be safely reduced to cause zlib to be called
  2138. * with smaller chunks of data.
  2139. */
  2140. if (png_ptr->zstream.avail_in == 0)
  2141. {
  2142. if (avail > ZLIB_IO_MAX)
  2143. {
  2144. png_ptr->zstream.avail_in = ZLIB_IO_MAX;
  2145. avail -= ZLIB_IO_MAX;
  2146. }
  2147. else
  2148. {
  2149. /* So this will fit in the available uInt space: */
  2150. png_ptr->zstream.avail_in = (uInt)avail;
  2151. avail = 0;
  2152. }
  2153. }
  2154. /* Compress the data */
  2155. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  2156. /* Check for compression errors */
  2157. if (ret != Z_OK)
  2158. {
  2159. if (png_ptr->zstream.msg != NULL)
  2160. png_error(png_ptr, png_ptr->zstream.msg);
  2161. else
  2162. png_error(png_ptr, "zlib error");
  2163. }
  2164. /* See if it is time to write another IDAT */
  2165. if (!(png_ptr->zstream.avail_out))
  2166. {
  2167. /* Write the IDAT and reset the zlib output buffer */
  2168. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  2169. }
  2170. /* Repeat until all data has been compressed */
  2171. } while (avail > 0 || png_ptr->zstream.avail_in > 0);
  2172. /* Swap the current and previous rows */
  2173. if (png_ptr->prev_row != NULL)
  2174. {
  2175. png_bytep tptr;
  2176. tptr = png_ptr->prev_row;
  2177. png_ptr->prev_row = png_ptr->row_buf;
  2178. png_ptr->row_buf = tptr;
  2179. }
  2180. /* Finish row - updates counters and flushes zlib if last row */
  2181. png_write_finish_row(png_ptr);
  2182. #ifdef PNG_WRITE_FLUSH_SUPPORTED
  2183. png_ptr->flush_rows++;
  2184. if (png_ptr->flush_dist > 0 &&
  2185. png_ptr->flush_rows >= png_ptr->flush_dist)
  2186. {
  2187. png_write_flush(png_ptr);
  2188. }
  2189. #endif
  2190. }
  2191. #endif /* PNG_WRITE_SUPPORTED */