pngwutil.c 82 KB

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