pngwutil.c 78 KB

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