pngwutil.c 80 KB

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