pngwutil.c 90 KB

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