pngwutil.c 82 KB

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