encode.c 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382
  1. /*
  2. * The Python Imaging Library.
  3. *
  4. * standard encoder interfaces for the Imaging library
  5. *
  6. * History:
  7. * 1996-04-19 fl Based on decoders.c
  8. * 1996-05-12 fl Compile cleanly as C++
  9. * 1996-12-30 fl Plugged potential memory leak for tiled images
  10. * 1997-01-03 fl Added GIF encoder
  11. * 1997-01-05 fl Plugged encoder buffer leaks
  12. * 1997-01-11 fl Added encode_to_file method
  13. * 1998-03-09 fl Added mode/rawmode argument to encoders
  14. * 1998-07-09 fl Added interlace argument to GIF encoder
  15. * 1999-02-07 fl Added PCX encoder
  16. *
  17. * Copyright (c) 1997-2001 by Secret Labs AB
  18. * Copyright (c) 1996-1997 by Fredrik Lundh
  19. *
  20. * See the README file for information on usage and redistribution.
  21. */
  22. /* FIXME: make these pluggable! */
  23. #define PY_SSIZE_T_CLEAN
  24. #include "Python.h"
  25. #include "libImaging/Imaging.h"
  26. #include "libImaging/Gif.h"
  27. #ifdef HAVE_UNISTD_H
  28. #include <unistd.h> /* write */
  29. #endif
  30. /* -------------------------------------------------------------------- */
  31. /* Common */
  32. /* -------------------------------------------------------------------- */
  33. typedef struct {
  34. PyObject_HEAD int (*encode)(
  35. Imaging im, ImagingCodecState state, UINT8 *buffer, int bytes);
  36. int (*cleanup)(ImagingCodecState state);
  37. struct ImagingCodecStateInstance state;
  38. Imaging im;
  39. PyObject *lock;
  40. int pushes_fd;
  41. } ImagingEncoderObject;
  42. static PyTypeObject ImagingEncoderType;
  43. static ImagingEncoderObject *
  44. PyImaging_EncoderNew(int contextsize) {
  45. ImagingEncoderObject *encoder;
  46. void *context;
  47. if (PyType_Ready(&ImagingEncoderType) < 0) {
  48. return NULL;
  49. }
  50. encoder = PyObject_New(ImagingEncoderObject, &ImagingEncoderType);
  51. if (encoder == NULL) {
  52. return NULL;
  53. }
  54. /* Clear the encoder state */
  55. memset(&encoder->state, 0, sizeof(encoder->state));
  56. /* Allocate encoder context */
  57. if (contextsize > 0) {
  58. context = (void *)calloc(1, contextsize);
  59. if (!context) {
  60. Py_DECREF(encoder);
  61. (void)ImagingError_MemoryError();
  62. return NULL;
  63. }
  64. } else {
  65. context = 0;
  66. }
  67. /* Initialize encoder context */
  68. encoder->state.context = context;
  69. /* Most encoders don't need this */
  70. encoder->cleanup = NULL;
  71. /* Target image */
  72. encoder->lock = NULL;
  73. encoder->im = NULL;
  74. encoder->pushes_fd = 0;
  75. return encoder;
  76. }
  77. static void
  78. _dealloc(ImagingEncoderObject *encoder) {
  79. if (encoder->cleanup) {
  80. encoder->cleanup(&encoder->state);
  81. }
  82. free(encoder->state.buffer);
  83. free(encoder->state.context);
  84. Py_XDECREF(encoder->lock);
  85. Py_XDECREF(encoder->state.fd);
  86. PyObject_Del(encoder);
  87. }
  88. static PyObject *
  89. _encode_cleanup(ImagingEncoderObject *encoder, PyObject *args) {
  90. int status = 0;
  91. if (encoder->cleanup) {
  92. status = encoder->cleanup(&encoder->state);
  93. }
  94. return Py_BuildValue("i", status);
  95. }
  96. static PyObject *
  97. _encode(ImagingEncoderObject *encoder, PyObject *args) {
  98. PyObject *buf;
  99. PyObject *result;
  100. int status;
  101. /* Encode to a Python string (allocated by this method) */
  102. Py_ssize_t bufsize = 16384;
  103. if (!PyArg_ParseTuple(args, "|n", &bufsize)) {
  104. return NULL;
  105. }
  106. buf = PyBytes_FromStringAndSize(NULL, bufsize);
  107. if (!buf) {
  108. return NULL;
  109. }
  110. status = encoder->encode(
  111. encoder->im, &encoder->state, (UINT8 *)PyBytes_AsString(buf), bufsize);
  112. /* adjust string length to avoid slicing in encoder */
  113. if (_PyBytes_Resize(&buf, (status > 0) ? status : 0) < 0) {
  114. return NULL;
  115. }
  116. result = Py_BuildValue("iiO", status, encoder->state.errcode, buf);
  117. Py_DECREF(buf); /* must release buffer!!! */
  118. return result;
  119. }
  120. static PyObject *
  121. _encode_to_pyfd(ImagingEncoderObject *encoder) {
  122. PyObject *result;
  123. int status;
  124. if (!encoder->pushes_fd) {
  125. // UNDONE, appropriate errcode???
  126. result = Py_BuildValue("ii", 0, IMAGING_CODEC_CONFIG);
  127. return result;
  128. }
  129. status = encoder->encode(encoder->im, &encoder->state, (UINT8 *)NULL, 0);
  130. result = Py_BuildValue("ii", status, encoder->state.errcode);
  131. return result;
  132. }
  133. static PyObject *
  134. _encode_to_file(ImagingEncoderObject *encoder, PyObject *args) {
  135. UINT8 *buf;
  136. int status;
  137. ImagingSectionCookie cookie;
  138. /* Encode to a file handle */
  139. Py_ssize_t fh;
  140. Py_ssize_t bufsize = 16384;
  141. if (!PyArg_ParseTuple(args, "n|n", &fh, &bufsize)) {
  142. return NULL;
  143. }
  144. /* Allocate an encoder buffer */
  145. /* malloc check ok, either constant int, or checked by PyArg_ParseTuple */
  146. buf = (UINT8 *)malloc(bufsize);
  147. if (!buf) {
  148. return ImagingError_MemoryError();
  149. }
  150. ImagingSectionEnter(&cookie);
  151. do {
  152. /* This replaces the inner loop in the ImageFile _save
  153. function. */
  154. status = encoder->encode(encoder->im, &encoder->state, buf, bufsize);
  155. if (status > 0) {
  156. if (write(fh, buf, status) < 0) {
  157. ImagingSectionLeave(&cookie);
  158. free(buf);
  159. return PyErr_SetFromErrno(PyExc_OSError);
  160. }
  161. }
  162. } while (encoder->state.errcode == 0);
  163. ImagingSectionLeave(&cookie);
  164. free(buf);
  165. return Py_BuildValue("i", encoder->state.errcode);
  166. }
  167. extern Imaging
  168. PyImaging_AsImaging(PyObject *op);
  169. static PyObject *
  170. _setimage(ImagingEncoderObject *encoder, PyObject *args) {
  171. PyObject *op;
  172. Imaging im;
  173. ImagingCodecState state;
  174. Py_ssize_t x0, y0, x1, y1;
  175. /* Define where image data should be stored */
  176. x0 = y0 = x1 = y1 = 0;
  177. /* FIXME: should publish the ImagingType descriptor */
  178. if (!PyArg_ParseTuple(args, "O|(nnnn)", &op, &x0, &y0, &x1, &y1)) {
  179. return NULL;
  180. }
  181. im = PyImaging_AsImaging(op);
  182. if (!im) {
  183. return NULL;
  184. }
  185. encoder->im = im;
  186. state = &encoder->state;
  187. if (x0 == 0 && x1 == 0) {
  188. state->xsize = im->xsize;
  189. state->ysize = im->ysize;
  190. } else {
  191. state->xoff = x0;
  192. state->yoff = y0;
  193. state->xsize = x1 - x0;
  194. state->ysize = y1 - y0;
  195. }
  196. if (state->xsize <= 0 || state->xsize + state->xoff > im->xsize ||
  197. state->ysize <= 0 || state->ysize + state->yoff > im->ysize) {
  198. PyErr_SetString(PyExc_SystemError, "tile cannot extend outside image");
  199. return NULL;
  200. }
  201. /* Allocate memory buffer (if bits field is set) */
  202. if (state->bits > 0) {
  203. if (state->xsize > ((INT_MAX / state->bits) - 7)) {
  204. return ImagingError_MemoryError();
  205. }
  206. state->bytes = (state->bits * state->xsize + 7) / 8;
  207. /* malloc check ok, overflow checked above */
  208. state->buffer = (UINT8 *)calloc(1, state->bytes);
  209. if (!state->buffer) {
  210. return ImagingError_MemoryError();
  211. }
  212. }
  213. /* Keep a reference to the image object, to make sure it doesn't
  214. go away before we do */
  215. Py_INCREF(op);
  216. Py_XDECREF(encoder->lock);
  217. encoder->lock = op;
  218. Py_INCREF(Py_None);
  219. return Py_None;
  220. }
  221. static PyObject *
  222. _setfd(ImagingEncoderObject *encoder, PyObject *args) {
  223. PyObject *fd;
  224. ImagingCodecState state;
  225. if (!PyArg_ParseTuple(args, "O", &fd)) {
  226. return NULL;
  227. }
  228. state = &encoder->state;
  229. Py_XINCREF(fd);
  230. state->fd = fd;
  231. Py_INCREF(Py_None);
  232. return Py_None;
  233. }
  234. static PyObject *
  235. _get_pushes_fd(ImagingEncoderObject *encoder, void *closure) {
  236. return PyBool_FromLong(encoder->pushes_fd);
  237. }
  238. static struct PyMethodDef methods[] = {
  239. {"encode", (PyCFunction)_encode, METH_VARARGS},
  240. {"cleanup", (PyCFunction)_encode_cleanup, METH_VARARGS},
  241. {"encode_to_file", (PyCFunction)_encode_to_file, METH_VARARGS},
  242. {"encode_to_pyfd", (PyCFunction)_encode_to_pyfd, METH_NOARGS},
  243. {"setimage", (PyCFunction)_setimage, METH_VARARGS},
  244. {"setfd", (PyCFunction)_setfd, METH_VARARGS},
  245. {NULL, NULL} /* sentinel */
  246. };
  247. static struct PyGetSetDef getseters[] = {
  248. {"pushes_fd",
  249. (getter)_get_pushes_fd,
  250. NULL,
  251. "True if this decoder expects to push directly to self.fd",
  252. NULL},
  253. {NULL, NULL, NULL, NULL, NULL} /* sentinel */
  254. };
  255. static PyTypeObject ImagingEncoderType = {
  256. PyVarObject_HEAD_INIT(NULL, 0) "ImagingEncoder", /*tp_name*/
  257. sizeof(ImagingEncoderObject), /*tp_basicsize*/
  258. 0, /*tp_itemsize*/
  259. /* methods */
  260. (destructor)_dealloc, /*tp_dealloc*/
  261. 0, /*tp_vectorcall_offset*/
  262. 0, /*tp_getattr*/
  263. 0, /*tp_setattr*/
  264. 0, /*tp_as_async*/
  265. 0, /*tp_repr*/
  266. 0, /*tp_as_number*/
  267. 0, /*tp_as_sequence*/
  268. 0, /*tp_as_mapping*/
  269. 0, /*tp_hash*/
  270. 0, /*tp_call*/
  271. 0, /*tp_str*/
  272. 0, /*tp_getattro*/
  273. 0, /*tp_setattro*/
  274. 0, /*tp_as_buffer*/
  275. Py_TPFLAGS_DEFAULT, /*tp_flags*/
  276. 0, /*tp_doc*/
  277. 0, /*tp_traverse*/
  278. 0, /*tp_clear*/
  279. 0, /*tp_richcompare*/
  280. 0, /*tp_weaklistoffset*/
  281. 0, /*tp_iter*/
  282. 0, /*tp_iternext*/
  283. methods, /*tp_methods*/
  284. 0, /*tp_members*/
  285. getseters, /*tp_getset*/
  286. };
  287. /* -------------------------------------------------------------------- */
  288. int
  289. get_packer(ImagingEncoderObject *encoder, const char *mode, const char *rawmode) {
  290. int bits;
  291. ImagingShuffler pack;
  292. pack = ImagingFindPacker(mode, rawmode, &bits);
  293. if (!pack) {
  294. Py_DECREF(encoder);
  295. PyErr_Format(PyExc_ValueError, "No packer found from %s to %s", mode, rawmode);
  296. return -1;
  297. }
  298. encoder->state.shuffle = pack;
  299. encoder->state.bits = bits;
  300. return 0;
  301. }
  302. /* -------------------------------------------------------------------- */
  303. /* EPS */
  304. /* -------------------------------------------------------------------- */
  305. PyObject *
  306. PyImaging_EpsEncoderNew(PyObject *self, PyObject *args) {
  307. ImagingEncoderObject *encoder;
  308. encoder = PyImaging_EncoderNew(0);
  309. if (encoder == NULL) {
  310. return NULL;
  311. }
  312. encoder->encode = ImagingEpsEncode;
  313. return (PyObject *)encoder;
  314. }
  315. /* -------------------------------------------------------------------- */
  316. /* GIF */
  317. /* -------------------------------------------------------------------- */
  318. PyObject *
  319. PyImaging_GifEncoderNew(PyObject *self, PyObject *args) {
  320. ImagingEncoderObject *encoder;
  321. char *mode;
  322. char *rawmode;
  323. Py_ssize_t bits = 8;
  324. Py_ssize_t interlace = 0;
  325. if (!PyArg_ParseTuple(args, "ss|nn", &mode, &rawmode, &bits, &interlace)) {
  326. return NULL;
  327. }
  328. encoder = PyImaging_EncoderNew(sizeof(GIFENCODERSTATE));
  329. if (encoder == NULL) {
  330. return NULL;
  331. }
  332. if (get_packer(encoder, mode, rawmode) < 0) {
  333. return NULL;
  334. }
  335. encoder->encode = ImagingGifEncode;
  336. ((GIFENCODERSTATE *)encoder->state.context)->bits = bits;
  337. ((GIFENCODERSTATE *)encoder->state.context)->interlace = interlace;
  338. return (PyObject *)encoder;
  339. }
  340. /* -------------------------------------------------------------------- */
  341. /* PCX */
  342. /* -------------------------------------------------------------------- */
  343. PyObject *
  344. PyImaging_PcxEncoderNew(PyObject *self, PyObject *args) {
  345. ImagingEncoderObject *encoder;
  346. char *mode;
  347. char *rawmode;
  348. Py_ssize_t bits = 8;
  349. if (!PyArg_ParseTuple(args, "ss|n", &mode, &rawmode, &bits)) {
  350. return NULL;
  351. }
  352. encoder = PyImaging_EncoderNew(0);
  353. if (encoder == NULL) {
  354. return NULL;
  355. }
  356. if (get_packer(encoder, mode, rawmode) < 0) {
  357. return NULL;
  358. }
  359. encoder->encode = ImagingPcxEncode;
  360. return (PyObject *)encoder;
  361. }
  362. /* -------------------------------------------------------------------- */
  363. /* RAW */
  364. /* -------------------------------------------------------------------- */
  365. PyObject *
  366. PyImaging_RawEncoderNew(PyObject *self, PyObject *args) {
  367. ImagingEncoderObject *encoder;
  368. char *mode;
  369. char *rawmode;
  370. Py_ssize_t stride = 0;
  371. Py_ssize_t ystep = 1;
  372. if (!PyArg_ParseTuple(args, "ss|nn", &mode, &rawmode, &stride, &ystep)) {
  373. return NULL;
  374. }
  375. encoder = PyImaging_EncoderNew(0);
  376. if (encoder == NULL) {
  377. return NULL;
  378. }
  379. if (get_packer(encoder, mode, rawmode) < 0) {
  380. return NULL;
  381. }
  382. encoder->encode = ImagingRawEncode;
  383. encoder->state.ystep = ystep;
  384. encoder->state.count = stride;
  385. return (PyObject *)encoder;
  386. }
  387. /* -------------------------------------------------------------------- */
  388. /* TGA */
  389. /* -------------------------------------------------------------------- */
  390. PyObject *
  391. PyImaging_TgaRleEncoderNew(PyObject *self, PyObject *args) {
  392. ImagingEncoderObject *encoder;
  393. char *mode;
  394. char *rawmode;
  395. Py_ssize_t ystep = 1;
  396. if (!PyArg_ParseTuple(args, "ss|n", &mode, &rawmode, &ystep)) {
  397. return NULL;
  398. }
  399. encoder = PyImaging_EncoderNew(0);
  400. if (encoder == NULL) {
  401. return NULL;
  402. }
  403. if (get_packer(encoder, mode, rawmode) < 0) {
  404. return NULL;
  405. }
  406. encoder->encode = ImagingTgaRleEncode;
  407. encoder->state.ystep = ystep;
  408. return (PyObject *)encoder;
  409. }
  410. /* -------------------------------------------------------------------- */
  411. /* XBM */
  412. /* -------------------------------------------------------------------- */
  413. PyObject *
  414. PyImaging_XbmEncoderNew(PyObject *self, PyObject *args) {
  415. ImagingEncoderObject *encoder;
  416. encoder = PyImaging_EncoderNew(0);
  417. if (encoder == NULL) {
  418. return NULL;
  419. }
  420. if (get_packer(encoder, "1", "1;R") < 0) {
  421. return NULL;
  422. }
  423. encoder->encode = ImagingXbmEncode;
  424. return (PyObject *)encoder;
  425. }
  426. /* -------------------------------------------------------------------- */
  427. /* ZIP */
  428. /* -------------------------------------------------------------------- */
  429. #ifdef HAVE_LIBZ
  430. #include "libImaging/ZipCodecs.h"
  431. PyObject *
  432. PyImaging_ZipEncoderNew(PyObject *self, PyObject *args) {
  433. ImagingEncoderObject *encoder;
  434. char *mode;
  435. char *rawmode;
  436. Py_ssize_t optimize = 0;
  437. Py_ssize_t compress_level = -1;
  438. Py_ssize_t compress_type = -1;
  439. char *dictionary = NULL;
  440. Py_ssize_t dictionary_size = 0;
  441. if (!PyArg_ParseTuple(
  442. args,
  443. "ss|nnny#",
  444. &mode,
  445. &rawmode,
  446. &optimize,
  447. &compress_level,
  448. &compress_type,
  449. &dictionary,
  450. &dictionary_size)) {
  451. return NULL;
  452. }
  453. /* Copy to avoid referencing Python's memory */
  454. if (dictionary && dictionary_size > 0) {
  455. /* malloc check ok, size comes from PyArg_ParseTuple */
  456. char *p = malloc(dictionary_size);
  457. if (!p) {
  458. return ImagingError_MemoryError();
  459. }
  460. memcpy(p, dictionary, dictionary_size);
  461. dictionary = p;
  462. } else {
  463. dictionary = NULL;
  464. }
  465. encoder = PyImaging_EncoderNew(sizeof(ZIPSTATE));
  466. if (encoder == NULL) {
  467. free(dictionary);
  468. return NULL;
  469. }
  470. if (get_packer(encoder, mode, rawmode) < 0) {
  471. free(dictionary);
  472. return NULL;
  473. }
  474. encoder->encode = ImagingZipEncode;
  475. encoder->cleanup = ImagingZipEncodeCleanup;
  476. if (rawmode[0] == 'P') {
  477. /* disable filtering */
  478. ((ZIPSTATE *)encoder->state.context)->mode = ZIP_PNG_PALETTE;
  479. }
  480. ((ZIPSTATE *)encoder->state.context)->optimize = optimize;
  481. ((ZIPSTATE *)encoder->state.context)->compress_level = compress_level;
  482. ((ZIPSTATE *)encoder->state.context)->compress_type = compress_type;
  483. ((ZIPSTATE *)encoder->state.context)->dictionary = dictionary;
  484. ((ZIPSTATE *)encoder->state.context)->dictionary_size = dictionary_size;
  485. return (PyObject *)encoder;
  486. }
  487. #endif
  488. /* -------------------------------------------------------------------- */
  489. /* LibTiff */
  490. /* -------------------------------------------------------------------- */
  491. #ifdef HAVE_LIBTIFF
  492. #include "libImaging/TiffDecode.h"
  493. #include <string.h>
  494. PyObject *
  495. PyImaging_LibTiffEncoderNew(PyObject *self, PyObject *args) {
  496. ImagingEncoderObject *encoder;
  497. char *mode;
  498. char *rawmode;
  499. char *compname;
  500. char *filename;
  501. Py_ssize_t fp;
  502. PyObject *tags, *types;
  503. PyObject *key, *value;
  504. Py_ssize_t pos = 0;
  505. int key_int, status, is_core_tag, is_var_length, num_core_tags, i;
  506. TIFFDataType type = TIFF_NOTYPE;
  507. // This list also exists in TiffTags.py
  508. const int core_tags[] = {256, 257, 258, 259, 262, 263, 266, 269, 274,
  509. 277, 278, 280, 281, 340, 341, 282, 283, 284,
  510. 286, 287, 296, 297, 320, 321, 338, 32995, 32998,
  511. 32996, 339, 32997, 330, 531, 530, 65537, 301, 532};
  512. Py_ssize_t tags_size;
  513. PyObject *item;
  514. if (!PyArg_ParseTuple(
  515. args,
  516. "sssnsOO",
  517. &mode,
  518. &rawmode,
  519. &compname,
  520. &fp,
  521. &filename,
  522. &tags,
  523. &types)) {
  524. return NULL;
  525. }
  526. if (!PyList_Check(tags)) {
  527. PyErr_SetString(PyExc_ValueError, "Invalid tags list");
  528. return NULL;
  529. } else {
  530. tags_size = PyList_Size(tags);
  531. TRACE(("tags size: %d\n", (int)tags_size));
  532. for (pos = 0; pos < tags_size; pos++) {
  533. item = PyList_GetItem(tags, pos);
  534. if (!PyTuple_Check(item) || PyTuple_Size(item) != 2) {
  535. PyErr_SetString(PyExc_ValueError, "Invalid tags list");
  536. return NULL;
  537. }
  538. }
  539. pos = 0;
  540. }
  541. if (!PyDict_Check(types)) {
  542. PyErr_SetString(PyExc_ValueError, "Invalid types dictionary");
  543. return NULL;
  544. }
  545. TRACE(("new tiff encoder %s fp: %d, filename: %s \n", compname, fp, filename));
  546. encoder = PyImaging_EncoderNew(sizeof(TIFFSTATE));
  547. if (encoder == NULL) {
  548. return NULL;
  549. }
  550. if (get_packer(encoder, mode, rawmode) < 0) {
  551. return NULL;
  552. }
  553. if (!ImagingLibTiffEncodeInit(&encoder->state, filename, fp)) {
  554. Py_DECREF(encoder);
  555. PyErr_SetString(PyExc_RuntimeError, "tiff codec initialization failed");
  556. return NULL;
  557. }
  558. num_core_tags = sizeof(core_tags) / sizeof(int);
  559. for (pos = 0; pos < tags_size; pos++) {
  560. item = PyList_GetItem(tags, pos);
  561. // We already checked that tags is a 2-tuple list.
  562. key = PyTuple_GetItem(item, 0);
  563. key_int = (int)PyLong_AsLong(key);
  564. value = PyTuple_GetItem(item, 1);
  565. status = 0;
  566. is_core_tag = 0;
  567. is_var_length = 0;
  568. type = TIFF_NOTYPE;
  569. for (i = 0; i < num_core_tags; i++) {
  570. if (core_tags[i] == key_int) {
  571. is_core_tag = 1;
  572. break;
  573. }
  574. }
  575. if (!is_core_tag) {
  576. PyObject *tag_type = PyDict_GetItem(types, key);
  577. if (tag_type) {
  578. int type_int = PyLong_AsLong(tag_type);
  579. if (type_int >= TIFF_BYTE && type_int <= TIFF_DOUBLE) {
  580. type = (TIFFDataType)type_int;
  581. }
  582. }
  583. }
  584. if (type == TIFF_NOTYPE) {
  585. // Autodetect type. Types should not be changed for backwards
  586. // compatibility.
  587. if (PyLong_Check(value)) {
  588. type = TIFF_LONG;
  589. } else if (PyFloat_Check(value)) {
  590. type = TIFF_DOUBLE;
  591. } else if (PyBytes_Check(value)) {
  592. type = TIFF_ASCII;
  593. }
  594. }
  595. if (PyTuple_Check(value)) {
  596. Py_ssize_t len;
  597. len = PyTuple_Size(value);
  598. is_var_length = 1;
  599. if (!len) {
  600. continue;
  601. }
  602. if (type == TIFF_NOTYPE) {
  603. // Autodetect type based on first item. Types should not be
  604. // changed for backwards compatibility.
  605. if (PyLong_Check(PyTuple_GetItem(value, 0))) {
  606. type = TIFF_LONG;
  607. } else if (PyFloat_Check(PyTuple_GetItem(value, 0))) {
  608. type = TIFF_FLOAT;
  609. }
  610. }
  611. }
  612. if (!is_core_tag) {
  613. // Register field for non core tags.
  614. if (type == TIFF_BYTE) {
  615. is_var_length = 1;
  616. }
  617. if (ImagingLibTiffMergeFieldInfo(
  618. &encoder->state, type, key_int, is_var_length)) {
  619. continue;
  620. }
  621. }
  622. if (type == TIFF_BYTE || type == TIFF_UNDEFINED) {
  623. status = ImagingLibTiffSetField(
  624. &encoder->state,
  625. (ttag_t)key_int,
  626. PyBytes_Size(value),
  627. PyBytes_AsString(value));
  628. } else if (is_var_length) {
  629. Py_ssize_t len, i;
  630. TRACE(("Setting from Tuple: %d \n", key_int));
  631. len = PyTuple_Size(value);
  632. if (key_int == TIFFTAG_COLORMAP) {
  633. int stride = 256;
  634. if (len != 768) {
  635. PyErr_SetString(
  636. PyExc_ValueError, "Requiring 768 items for Colormap");
  637. return NULL;
  638. }
  639. UINT16 *av;
  640. /* malloc check ok, calloc checks for overflow */
  641. av = calloc(len, sizeof(UINT16));
  642. if (av) {
  643. for (i = 0; i < len; i++) {
  644. av[i] = (UINT16)PyLong_AsLong(PyTuple_GetItem(value, i));
  645. }
  646. status = ImagingLibTiffSetField(
  647. &encoder->state,
  648. (ttag_t)key_int,
  649. av,
  650. av + stride,
  651. av + stride * 2);
  652. free(av);
  653. }
  654. } else if (key_int == TIFFTAG_YCBCRSUBSAMPLING) {
  655. status = ImagingLibTiffSetField(
  656. &encoder->state,
  657. (ttag_t)key_int,
  658. (UINT16)PyLong_AsLong(PyTuple_GetItem(value, 0)),
  659. (UINT16)PyLong_AsLong(PyTuple_GetItem(value, 1)));
  660. } else if (type == TIFF_SHORT) {
  661. UINT16 *av;
  662. /* malloc check ok, calloc checks for overflow */
  663. av = calloc(len, sizeof(UINT16));
  664. if (av) {
  665. for (i = 0; i < len; i++) {
  666. av[i] = (UINT16)PyLong_AsLong(PyTuple_GetItem(value, i));
  667. }
  668. status = ImagingLibTiffSetField(
  669. &encoder->state, (ttag_t)key_int, len, av);
  670. free(av);
  671. }
  672. } else if (type == TIFF_LONG) {
  673. UINT32 *av;
  674. /* malloc check ok, calloc checks for overflow */
  675. av = calloc(len, sizeof(UINT32));
  676. if (av) {
  677. for (i = 0; i < len; i++) {
  678. av[i] = (UINT32)PyLong_AsLong(PyTuple_GetItem(value, i));
  679. }
  680. status = ImagingLibTiffSetField(
  681. &encoder->state, (ttag_t)key_int, len, av);
  682. free(av);
  683. }
  684. } else if (type == TIFF_SBYTE) {
  685. INT8 *av;
  686. /* malloc check ok, calloc checks for overflow */
  687. av = calloc(len, sizeof(INT8));
  688. if (av) {
  689. for (i = 0; i < len; i++) {
  690. av[i] = (INT8)PyLong_AsLong(PyTuple_GetItem(value, i));
  691. }
  692. status = ImagingLibTiffSetField(
  693. &encoder->state, (ttag_t)key_int, len, av);
  694. free(av);
  695. }
  696. } else if (type == TIFF_SSHORT) {
  697. INT16 *av;
  698. /* malloc check ok, calloc checks for overflow */
  699. av = calloc(len, sizeof(INT16));
  700. if (av) {
  701. for (i = 0; i < len; i++) {
  702. av[i] = (INT16)PyLong_AsLong(PyTuple_GetItem(value, i));
  703. }
  704. status = ImagingLibTiffSetField(
  705. &encoder->state, (ttag_t)key_int, len, av);
  706. free(av);
  707. }
  708. } else if (type == TIFF_SLONG) {
  709. INT32 *av;
  710. /* malloc check ok, calloc checks for overflow */
  711. av = calloc(len, sizeof(INT32));
  712. if (av) {
  713. for (i = 0; i < len; i++) {
  714. av[i] = (INT32)PyLong_AsLong(PyTuple_GetItem(value, i));
  715. }
  716. status = ImagingLibTiffSetField(
  717. &encoder->state, (ttag_t)key_int, len, av);
  718. free(av);
  719. }
  720. } else if (type == TIFF_FLOAT) {
  721. FLOAT32 *av;
  722. /* malloc check ok, calloc checks for overflow */
  723. av = calloc(len, sizeof(FLOAT32));
  724. if (av) {
  725. for (i = 0; i < len; i++) {
  726. av[i] = (FLOAT32)PyFloat_AsDouble(PyTuple_GetItem(value, i));
  727. }
  728. status = ImagingLibTiffSetField(
  729. &encoder->state, (ttag_t)key_int, len, av);
  730. free(av);
  731. }
  732. } else if (type == TIFF_DOUBLE) {
  733. FLOAT64 *av;
  734. /* malloc check ok, calloc checks for overflow */
  735. av = calloc(len, sizeof(FLOAT64));
  736. if (av) {
  737. for (i = 0; i < len; i++) {
  738. av[i] = PyFloat_AsDouble(PyTuple_GetItem(value, i));
  739. }
  740. status = ImagingLibTiffSetField(
  741. &encoder->state, (ttag_t)key_int, len, av);
  742. free(av);
  743. }
  744. }
  745. } else {
  746. if (type == TIFF_SHORT) {
  747. status = ImagingLibTiffSetField(
  748. &encoder->state, (ttag_t)key_int, (UINT16)PyLong_AsLong(value));
  749. } else if (type == TIFF_LONG) {
  750. status = ImagingLibTiffSetField(
  751. &encoder->state, (ttag_t)key_int, PyLong_AsLongLong(value));
  752. } else if (type == TIFF_SSHORT) {
  753. status = ImagingLibTiffSetField(
  754. &encoder->state, (ttag_t)key_int, (INT16)PyLong_AsLong(value));
  755. } else if (type == TIFF_SLONG) {
  756. status = ImagingLibTiffSetField(
  757. &encoder->state, (ttag_t)key_int, (INT32)PyLong_AsLong(value));
  758. } else if (type == TIFF_FLOAT) {
  759. status = ImagingLibTiffSetField(
  760. &encoder->state, (ttag_t)key_int, (FLOAT32)PyFloat_AsDouble(value));
  761. } else if (type == TIFF_DOUBLE) {
  762. status = ImagingLibTiffSetField(
  763. &encoder->state, (ttag_t)key_int, (FLOAT64)PyFloat_AsDouble(value));
  764. } else if (type == TIFF_SBYTE) {
  765. status = ImagingLibTiffSetField(
  766. &encoder->state, (ttag_t)key_int, (INT8)PyLong_AsLong(value));
  767. } else if (type == TIFF_ASCII) {
  768. status = ImagingLibTiffSetField(
  769. &encoder->state, (ttag_t)key_int, PyBytes_AsString(value));
  770. } else if (type == TIFF_RATIONAL) {
  771. status = ImagingLibTiffSetField(
  772. &encoder->state, (ttag_t)key_int, (FLOAT64)PyFloat_AsDouble(value));
  773. } else {
  774. TRACE(
  775. ("Unhandled type for key %d : %s \n",
  776. key_int,
  777. PyBytes_AsString(PyObject_Str(value))));
  778. }
  779. }
  780. if (!status) {
  781. TRACE(("Error setting Field\n"));
  782. Py_DECREF(encoder);
  783. PyErr_SetString(PyExc_RuntimeError, "Error setting from dictionary");
  784. return NULL;
  785. }
  786. }
  787. encoder->encode = ImagingLibTiffEncode;
  788. return (PyObject *)encoder;
  789. }
  790. #endif
  791. /* -------------------------------------------------------------------- */
  792. /* JPEG */
  793. /* -------------------------------------------------------------------- */
  794. #ifdef HAVE_LIBJPEG
  795. /* We better define this encoder last in this file, so the following
  796. undef's won't mess things up for the Imaging library proper. */
  797. #undef HAVE_PROTOTYPES
  798. #undef HAVE_STDDEF_H
  799. #undef HAVE_STDLIB_H
  800. #undef UINT8
  801. #undef UINT16
  802. #undef UINT32
  803. #undef INT8
  804. #undef INT16
  805. #undef INT32
  806. #include "libImaging/Jpeg.h"
  807. static unsigned int *
  808. get_qtables_arrays(PyObject *qtables, int *qtablesLen) {
  809. PyObject *tables;
  810. PyObject *table;
  811. PyObject *table_data;
  812. int i, j, num_tables;
  813. unsigned int *qarrays;
  814. if ((qtables == NULL) || (qtables == Py_None)) {
  815. return NULL;
  816. }
  817. if (!PySequence_Check(qtables)) {
  818. PyErr_SetString(PyExc_ValueError, "Invalid quantization tables");
  819. return NULL;
  820. }
  821. tables = PySequence_Fast(qtables, "expected a sequence");
  822. num_tables = PySequence_Size(qtables);
  823. if (num_tables < 1 || num_tables > NUM_QUANT_TBLS) {
  824. PyErr_SetString(
  825. PyExc_ValueError,
  826. "Not a valid number of quantization tables. Should be between 1 and 4.");
  827. Py_DECREF(tables);
  828. return NULL;
  829. }
  830. /* malloc check ok, num_tables <4, DCTSIZE2 == 64 from jpeglib.h */
  831. qarrays = (unsigned int *)malloc(num_tables * DCTSIZE2 * sizeof(unsigned int));
  832. if (!qarrays) {
  833. Py_DECREF(tables);
  834. return ImagingError_MemoryError();
  835. }
  836. for (i = 0; i < num_tables; i++) {
  837. table = PySequence_Fast_GET_ITEM(tables, i);
  838. if (!PySequence_Check(table)) {
  839. PyErr_SetString(PyExc_ValueError, "Invalid quantization tables");
  840. goto JPEG_QTABLES_ERR;
  841. }
  842. if (PySequence_Size(table) != DCTSIZE2) {
  843. PyErr_SetString(PyExc_ValueError, "Invalid quantization table size");
  844. goto JPEG_QTABLES_ERR;
  845. }
  846. table_data = PySequence_Fast(table, "expected a sequence");
  847. for (j = 0; j < DCTSIZE2; j++) {
  848. qarrays[i * DCTSIZE2 + j] =
  849. PyLong_AS_LONG(PySequence_Fast_GET_ITEM(table_data, j));
  850. }
  851. Py_DECREF(table_data);
  852. }
  853. *qtablesLen = num_tables;
  854. JPEG_QTABLES_ERR:
  855. Py_DECREF(tables); // Run on both error and not error
  856. if (PyErr_Occurred()) {
  857. free(qarrays);
  858. qarrays = NULL;
  859. return NULL;
  860. }
  861. return qarrays;
  862. }
  863. PyObject *
  864. PyImaging_JpegEncoderNew(PyObject *self, PyObject *args) {
  865. ImagingEncoderObject *encoder;
  866. char *mode;
  867. char *rawmode;
  868. Py_ssize_t quality = 0;
  869. Py_ssize_t progressive = 0;
  870. Py_ssize_t smooth = 0;
  871. Py_ssize_t optimize = 0;
  872. int keep_rgb = 0;
  873. Py_ssize_t streamtype = 0; /* 0=interchange, 1=tables only, 2=image only */
  874. Py_ssize_t xdpi = 0, ydpi = 0;
  875. Py_ssize_t subsampling = -1; /* -1=default, 0=none, 1=medium, 2=high */
  876. Py_ssize_t restart_marker_blocks = 0;
  877. Py_ssize_t restart_marker_rows = 0;
  878. PyObject *qtables = NULL;
  879. unsigned int *qarrays = NULL;
  880. int qtablesLen = 0;
  881. char *comment = NULL;
  882. Py_ssize_t comment_size;
  883. char *extra = NULL;
  884. Py_ssize_t extra_size;
  885. char *rawExif = NULL;
  886. Py_ssize_t rawExifLen = 0;
  887. if (!PyArg_ParseTuple(
  888. args,
  889. "ss|nnnnpnnnnnnOz#y#y#",
  890. &mode,
  891. &rawmode,
  892. &quality,
  893. &progressive,
  894. &smooth,
  895. &optimize,
  896. &keep_rgb,
  897. &streamtype,
  898. &xdpi,
  899. &ydpi,
  900. &subsampling,
  901. &restart_marker_blocks,
  902. &restart_marker_rows,
  903. &qtables,
  904. &comment,
  905. &comment_size,
  906. &extra,
  907. &extra_size,
  908. &rawExif,
  909. &rawExifLen)) {
  910. return NULL;
  911. }
  912. encoder = PyImaging_EncoderNew(sizeof(JPEGENCODERSTATE));
  913. if (encoder == NULL) {
  914. return NULL;
  915. }
  916. // libjpeg-turbo supports different output formats.
  917. // We are choosing Pillow's native format (3 color bytes + 1 padding)
  918. // to avoid extra conversion in Pack.c.
  919. if (ImagingJpegUseJCSExtensions() && strcmp(rawmode, "RGB") == 0) {
  920. rawmode = "RGBX";
  921. }
  922. if (get_packer(encoder, mode, rawmode) < 0) {
  923. return NULL;
  924. }
  925. // Freed in JpegEncode, Case 6
  926. qarrays = get_qtables_arrays(qtables, &qtablesLen);
  927. if (comment && comment_size > 0) {
  928. /* malloc check ok, length is from python parsearg */
  929. char *p = malloc(comment_size); // Freed in JpegEncode, Case 6
  930. if (!p) {
  931. return ImagingError_MemoryError();
  932. }
  933. memcpy(p, comment, comment_size);
  934. comment = p;
  935. } else {
  936. comment = NULL;
  937. }
  938. if (extra && extra_size > 0) {
  939. /* malloc check ok, length is from python parsearg */
  940. char *p = malloc(extra_size); // Freed in JpegEncode, Case 6
  941. if (!p) {
  942. if (comment) {
  943. free(comment);
  944. }
  945. return ImagingError_MemoryError();
  946. }
  947. memcpy(p, extra, extra_size);
  948. extra = p;
  949. } else {
  950. extra = NULL;
  951. }
  952. if (rawExif && rawExifLen > 0) {
  953. /* malloc check ok, length is from python parsearg */
  954. char *pp = malloc(rawExifLen); // Freed in JpegEncode, Case 6
  955. if (!pp) {
  956. if (comment) {
  957. free(comment);
  958. }
  959. if (extra) {
  960. free(extra);
  961. }
  962. return ImagingError_MemoryError();
  963. }
  964. memcpy(pp, rawExif, rawExifLen);
  965. rawExif = pp;
  966. } else {
  967. rawExif = NULL;
  968. }
  969. encoder->encode = ImagingJpegEncode;
  970. strncpy(((JPEGENCODERSTATE *)encoder->state.context)->rawmode, rawmode, 8);
  971. ((JPEGENCODERSTATE *)encoder->state.context)->keep_rgb = keep_rgb;
  972. ((JPEGENCODERSTATE *)encoder->state.context)->quality = quality;
  973. ((JPEGENCODERSTATE *)encoder->state.context)->qtables = qarrays;
  974. ((JPEGENCODERSTATE *)encoder->state.context)->qtablesLen = qtablesLen;
  975. ((JPEGENCODERSTATE *)encoder->state.context)->subsampling = subsampling;
  976. ((JPEGENCODERSTATE *)encoder->state.context)->progressive = progressive;
  977. ((JPEGENCODERSTATE *)encoder->state.context)->smooth = smooth;
  978. ((JPEGENCODERSTATE *)encoder->state.context)->optimize = optimize;
  979. ((JPEGENCODERSTATE *)encoder->state.context)->streamtype = streamtype;
  980. ((JPEGENCODERSTATE *)encoder->state.context)->xdpi = xdpi;
  981. ((JPEGENCODERSTATE *)encoder->state.context)->ydpi = ydpi;
  982. ((JPEGENCODERSTATE *)encoder->state.context)->restart_marker_blocks = restart_marker_blocks;
  983. ((JPEGENCODERSTATE *)encoder->state.context)->restart_marker_rows = restart_marker_rows;
  984. ((JPEGENCODERSTATE *)encoder->state.context)->comment = comment;
  985. ((JPEGENCODERSTATE *)encoder->state.context)->comment_size = comment_size;
  986. ((JPEGENCODERSTATE *)encoder->state.context)->extra = extra;
  987. ((JPEGENCODERSTATE *)encoder->state.context)->extra_size = extra_size;
  988. ((JPEGENCODERSTATE *)encoder->state.context)->rawExif = rawExif;
  989. ((JPEGENCODERSTATE *)encoder->state.context)->rawExifLen = rawExifLen;
  990. return (PyObject *)encoder;
  991. }
  992. #endif
  993. /* -------------------------------------------------------------------- */
  994. /* JPEG 2000 */
  995. /* -------------------------------------------------------------------- */
  996. #ifdef HAVE_OPENJPEG
  997. #include "libImaging/Jpeg2K.h"
  998. static void
  999. j2k_decode_coord_tuple(PyObject *tuple, int *x, int *y) {
  1000. *x = *y = 0;
  1001. if (tuple && PyTuple_Check(tuple) && PyTuple_GET_SIZE(tuple) == 2) {
  1002. *x = (int)PyLong_AsLong(PyTuple_GET_ITEM(tuple, 0));
  1003. *y = (int)PyLong_AsLong(PyTuple_GET_ITEM(tuple, 1));
  1004. if (*x < 0) {
  1005. *x = 0;
  1006. }
  1007. if (*y < 0) {
  1008. *y = 0;
  1009. }
  1010. }
  1011. }
  1012. PyObject *
  1013. PyImaging_Jpeg2KEncoderNew(PyObject *self, PyObject *args) {
  1014. ImagingEncoderObject *encoder;
  1015. JPEG2KENCODESTATE *context;
  1016. char *mode;
  1017. char *format;
  1018. OPJ_CODEC_FORMAT codec_format;
  1019. PyObject *offset = NULL, *tile_offset = NULL, *tile_size = NULL;
  1020. char *quality_mode = "rates";
  1021. PyObject *quality_layers = NULL;
  1022. Py_ssize_t num_resolutions = 0;
  1023. PyObject *cblk_size = NULL, *precinct_size = NULL;
  1024. PyObject *irreversible = NULL;
  1025. char *progression = "LRCP";
  1026. OPJ_PROG_ORDER prog_order;
  1027. char *cinema_mode = "no";
  1028. OPJ_CINEMA_MODE cine_mode;
  1029. char mct = 0;
  1030. int sgnd = 0;
  1031. Py_ssize_t fd = -1;
  1032. char *comment;
  1033. Py_ssize_t comment_size;
  1034. int plt = 0;
  1035. if (!PyArg_ParseTuple(
  1036. args,
  1037. "ss|OOOsOnOOOssbbnz#p",
  1038. &mode,
  1039. &format,
  1040. &offset,
  1041. &tile_offset,
  1042. &tile_size,
  1043. &quality_mode,
  1044. &quality_layers,
  1045. &num_resolutions,
  1046. &cblk_size,
  1047. &precinct_size,
  1048. &irreversible,
  1049. &progression,
  1050. &cinema_mode,
  1051. &mct,
  1052. &sgnd,
  1053. &fd,
  1054. &comment,
  1055. &comment_size,
  1056. &plt)) {
  1057. return NULL;
  1058. }
  1059. if (strcmp(format, "j2k") == 0) {
  1060. codec_format = OPJ_CODEC_J2K;
  1061. } else if (strcmp(format, "jpt") == 0) {
  1062. codec_format = OPJ_CODEC_JPT;
  1063. } else if (strcmp(format, "jp2") == 0) {
  1064. codec_format = OPJ_CODEC_JP2;
  1065. } else {
  1066. return NULL;
  1067. }
  1068. if (strcmp(progression, "LRCP") == 0) {
  1069. prog_order = OPJ_LRCP;
  1070. } else if (strcmp(progression, "RLCP") == 0) {
  1071. prog_order = OPJ_RLCP;
  1072. } else if (strcmp(progression, "RPCL") == 0) {
  1073. prog_order = OPJ_RPCL;
  1074. } else if (strcmp(progression, "PCRL") == 0) {
  1075. prog_order = OPJ_PCRL;
  1076. } else if (strcmp(progression, "CPRL") == 0) {
  1077. prog_order = OPJ_CPRL;
  1078. } else {
  1079. return NULL;
  1080. }
  1081. if (strcmp(cinema_mode, "no") == 0) {
  1082. cine_mode = OPJ_OFF;
  1083. } else if (strcmp(cinema_mode, "cinema2k-24") == 0) {
  1084. cine_mode = OPJ_CINEMA2K_24;
  1085. } else if (strcmp(cinema_mode, "cinema2k-48") == 0) {
  1086. cine_mode = OPJ_CINEMA2K_48;
  1087. } else if (strcmp(cinema_mode, "cinema4k-24") == 0) {
  1088. cine_mode = OPJ_CINEMA4K_24;
  1089. } else {
  1090. return NULL;
  1091. }
  1092. encoder = PyImaging_EncoderNew(sizeof(JPEG2KENCODESTATE));
  1093. if (!encoder) {
  1094. return NULL;
  1095. }
  1096. encoder->encode = ImagingJpeg2KEncode;
  1097. encoder->cleanup = ImagingJpeg2KEncodeCleanup;
  1098. encoder->pushes_fd = 1;
  1099. context = (JPEG2KENCODESTATE *)encoder->state.context;
  1100. context->fd = fd;
  1101. context->format = codec_format;
  1102. context->offset_x = context->offset_y = 0;
  1103. j2k_decode_coord_tuple(offset, &context->offset_x, &context->offset_y);
  1104. j2k_decode_coord_tuple(
  1105. tile_offset, &context->tile_offset_x, &context->tile_offset_y);
  1106. j2k_decode_coord_tuple(tile_size, &context->tile_size_x, &context->tile_size_y);
  1107. /* Error on illegal tile offsets */
  1108. if (context->tile_size_x && context->tile_size_y) {
  1109. if (context->tile_offset_x <= context->offset_x - context->tile_size_x ||
  1110. context->tile_offset_y <= context->offset_y - context->tile_size_y) {
  1111. PyErr_SetString(
  1112. PyExc_ValueError,
  1113. "JPEG 2000 tile offset too small; top left tile must "
  1114. "intersect image area");
  1115. Py_DECREF(encoder);
  1116. return NULL;
  1117. }
  1118. if (context->tile_offset_x > context->offset_x ||
  1119. context->tile_offset_y > context->offset_y) {
  1120. PyErr_SetString(
  1121. PyExc_ValueError,
  1122. "JPEG 2000 tile offset too large to cover image area");
  1123. Py_DECREF(encoder);
  1124. return NULL;
  1125. }
  1126. }
  1127. if (comment && comment_size > 0) {
  1128. /* Size is stored as as an uint16, subtract 4 bytes for the header */
  1129. if (comment_size >= 65532) {
  1130. PyErr_SetString(
  1131. PyExc_ValueError,
  1132. "JPEG 2000 comment is too long");
  1133. Py_DECREF(encoder);
  1134. return NULL;
  1135. }
  1136. char *p = malloc(comment_size + 1);
  1137. if (!p) {
  1138. Py_DECREF(encoder);
  1139. return ImagingError_MemoryError();
  1140. }
  1141. memcpy(p, comment, comment_size);
  1142. p[comment_size] = '\0';
  1143. context->comment = p;
  1144. }
  1145. if (quality_layers && PySequence_Check(quality_layers)) {
  1146. context->quality_is_in_db = strcmp(quality_mode, "dB") == 0;
  1147. context->quality_layers = quality_layers;
  1148. Py_INCREF(quality_layers);
  1149. }
  1150. context->num_resolutions = num_resolutions;
  1151. j2k_decode_coord_tuple(cblk_size, &context->cblk_width, &context->cblk_height);
  1152. j2k_decode_coord_tuple(
  1153. precinct_size, &context->precinct_width, &context->precinct_height);
  1154. context->irreversible = PyObject_IsTrue(irreversible);
  1155. context->progression = prog_order;
  1156. context->cinema_mode = cine_mode;
  1157. context->mct = mct;
  1158. context->sgnd = sgnd;
  1159. context->plt = plt;
  1160. return (PyObject *)encoder;
  1161. }
  1162. #endif
  1163. /*
  1164. * Local Variables:
  1165. * c-basic-offset: 4
  1166. * End:
  1167. *
  1168. */