pngwutil.c 78 KB

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