pngwutil.c 93 KB

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