pngwutil.c 82 KB

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