pngwutil.c 90 KB

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