turbojpeg.c 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161
  1. /*
  2. * Copyright (C)2009-2020 D. R. Commander. All Rights Reserved.
  3. * mozjpeg Modifications:
  4. * Copyright (C) 2014, Mozilla Corporation.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions are met:
  8. *
  9. * - Redistributions of source code must retain the above copyright notice,
  10. * this list of conditions and the following disclaimer.
  11. * - Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. * - Neither the name of the libjpeg-turbo Project nor the names of its
  15. * contributors may be used to endorse or promote products derived from this
  16. * software without specific prior written permission.
  17. *
  18. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS",
  19. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  20. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  21. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
  22. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  23. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  24. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  25. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  26. * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  27. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  28. * POSSIBILITY OF SUCH DAMAGE.
  29. */
  30. /* TurboJPEG/LJT: this implements the TurboJPEG API using libjpeg or
  31. libjpeg-turbo */
  32. #include <stdio.h>
  33. #include <stdlib.h>
  34. #include <ctype.h>
  35. #include <jinclude.h>
  36. #define JPEG_INTERNALS
  37. #include <jpeglib.h>
  38. #include <jerror.h>
  39. #include <setjmp.h>
  40. #include <errno.h>
  41. #include "./turbojpeg.h"
  42. #include "./tjutil.h"
  43. #include "transupp.h"
  44. #include "./jpegcomp.h"
  45. #include "./cdjpeg.h"
  46. #include "jconfigint.h"
  47. extern void jpeg_mem_dest_tj(j_compress_ptr, unsigned char **, unsigned long *,
  48. boolean);
  49. extern void jpeg_mem_src_tj(j_decompress_ptr, const unsigned char *,
  50. unsigned long);
  51. #define PAD(v, p) ((v + (p) - 1) & (~((p) - 1)))
  52. #define IS_POW2(x) (((x) & (x - 1)) == 0)
  53. /* Error handling (based on example in example.txt) */
  54. static THREAD_LOCAL char errStr[JMSG_LENGTH_MAX] = "No error";
  55. struct my_error_mgr {
  56. struct jpeg_error_mgr pub;
  57. jmp_buf setjmp_buffer;
  58. void (*emit_message) (j_common_ptr, int);
  59. boolean warning, stopOnWarning;
  60. };
  61. typedef struct my_error_mgr *my_error_ptr;
  62. #define JMESSAGE(code, string) string,
  63. static const char *turbojpeg_message_table[] = {
  64. #include "cderror.h"
  65. NULL
  66. };
  67. static void my_error_exit(j_common_ptr cinfo)
  68. {
  69. my_error_ptr myerr = (my_error_ptr)cinfo->err;
  70. (*cinfo->err->output_message) (cinfo);
  71. longjmp(myerr->setjmp_buffer, 1);
  72. }
  73. /* Based on output_message() in jerror.c */
  74. static void my_output_message(j_common_ptr cinfo)
  75. {
  76. (*cinfo->err->format_message) (cinfo, errStr);
  77. }
  78. static void my_emit_message(j_common_ptr cinfo, int msg_level)
  79. {
  80. my_error_ptr myerr = (my_error_ptr)cinfo->err;
  81. myerr->emit_message(cinfo, msg_level);
  82. if (msg_level < 0) {
  83. myerr->warning = TRUE;
  84. if (myerr->stopOnWarning) longjmp(myerr->setjmp_buffer, 1);
  85. }
  86. }
  87. /* Global structures, macros, etc. */
  88. enum { COMPRESS = 1, DECOMPRESS = 2 };
  89. typedef struct _tjinstance {
  90. struct jpeg_compress_struct cinfo;
  91. struct jpeg_decompress_struct dinfo;
  92. struct my_error_mgr jerr;
  93. int init, headerRead;
  94. char errStr[JMSG_LENGTH_MAX];
  95. boolean isInstanceError;
  96. } tjinstance;
  97. static const int pixelsize[TJ_NUMSAMP] = { 3, 3, 3, 1, 3, 3 };
  98. static const JXFORM_CODE xformtypes[TJ_NUMXOP] = {
  99. JXFORM_NONE, JXFORM_FLIP_H, JXFORM_FLIP_V, JXFORM_TRANSPOSE,
  100. JXFORM_TRANSVERSE, JXFORM_ROT_90, JXFORM_ROT_180, JXFORM_ROT_270
  101. };
  102. #define NUMSF 16
  103. static const tjscalingfactor sf[NUMSF] = {
  104. { 2, 1 },
  105. { 15, 8 },
  106. { 7, 4 },
  107. { 13, 8 },
  108. { 3, 2 },
  109. { 11, 8 },
  110. { 5, 4 },
  111. { 9, 8 },
  112. { 1, 1 },
  113. { 7, 8 },
  114. { 3, 4 },
  115. { 5, 8 },
  116. { 1, 2 },
  117. { 3, 8 },
  118. { 1, 4 },
  119. { 1, 8 }
  120. };
  121. static J_COLOR_SPACE pf2cs[TJ_NUMPF] = {
  122. JCS_EXT_RGB, JCS_EXT_BGR, JCS_EXT_RGBX, JCS_EXT_BGRX, JCS_EXT_XBGR,
  123. JCS_EXT_XRGB, JCS_GRAYSCALE, JCS_EXT_RGBA, JCS_EXT_BGRA, JCS_EXT_ABGR,
  124. JCS_EXT_ARGB, JCS_CMYK
  125. };
  126. static int cs2pf[JPEG_NUMCS] = {
  127. TJPF_UNKNOWN, TJPF_GRAY,
  128. #if RGB_RED == 0 && RGB_GREEN == 1 && RGB_BLUE == 2 && RGB_PIXELSIZE == 3
  129. TJPF_RGB,
  130. #elif RGB_RED == 2 && RGB_GREEN == 1 && RGB_BLUE == 0 && RGB_PIXELSIZE == 3
  131. TJPF_BGR,
  132. #elif RGB_RED == 0 && RGB_GREEN == 1 && RGB_BLUE == 2 && RGB_PIXELSIZE == 4
  133. TJPF_RGBX,
  134. #elif RGB_RED == 2 && RGB_GREEN == 1 && RGB_BLUE == 0 && RGB_PIXELSIZE == 4
  135. TJPF_BGRX,
  136. #elif RGB_RED == 3 && RGB_GREEN == 2 && RGB_BLUE == 1 && RGB_PIXELSIZE == 4
  137. TJPF_XBGR,
  138. #elif RGB_RED == 1 && RGB_GREEN == 2 && RGB_BLUE == 3 && RGB_PIXELSIZE == 4
  139. TJPF_XRGB,
  140. #endif
  141. TJPF_UNKNOWN, TJPF_CMYK, TJPF_UNKNOWN, TJPF_RGB, TJPF_RGBX, TJPF_BGR,
  142. TJPF_BGRX, TJPF_XBGR, TJPF_XRGB, TJPF_RGBA, TJPF_BGRA, TJPF_ABGR, TJPF_ARGB,
  143. TJPF_UNKNOWN
  144. };
  145. #define THROWG(m) { \
  146. snprintf(errStr, JMSG_LENGTH_MAX, "%s", m); \
  147. retval = -1; goto bailout; \
  148. }
  149. #define THROW_UNIX(m) { \
  150. snprintf(errStr, JMSG_LENGTH_MAX, "%s\n%s", m, strerror(errno)); \
  151. retval = -1; goto bailout; \
  152. }
  153. #define THROW(m) { \
  154. snprintf(this->errStr, JMSG_LENGTH_MAX, "%s", m); \
  155. this->isInstanceError = TRUE; THROWG(m) \
  156. }
  157. #define GET_INSTANCE(handle) \
  158. tjinstance *this = (tjinstance *)handle; \
  159. j_compress_ptr cinfo = NULL; \
  160. j_decompress_ptr dinfo = NULL; \
  161. \
  162. if (!this) { \
  163. snprintf(errStr, JMSG_LENGTH_MAX, "Invalid handle"); \
  164. return -1; \
  165. } \
  166. cinfo = &this->cinfo; dinfo = &this->dinfo; \
  167. this->jerr.warning = FALSE; \
  168. this->isInstanceError = FALSE;
  169. #define GET_CINSTANCE(handle) \
  170. tjinstance *this = (tjinstance *)handle; \
  171. j_compress_ptr cinfo = NULL; \
  172. \
  173. if (!this) { \
  174. snprintf(errStr, JMSG_LENGTH_MAX, "Invalid handle"); \
  175. return -1; \
  176. } \
  177. cinfo = &this->cinfo; \
  178. this->jerr.warning = FALSE; \
  179. this->isInstanceError = FALSE;
  180. #define GET_DINSTANCE(handle) \
  181. tjinstance *this = (tjinstance *)handle; \
  182. j_decompress_ptr dinfo = NULL; \
  183. \
  184. if (!this) { \
  185. snprintf(errStr, JMSG_LENGTH_MAX, "Invalid handle"); \
  186. return -1; \
  187. } \
  188. dinfo = &this->dinfo; \
  189. this->jerr.warning = FALSE; \
  190. this->isInstanceError = FALSE;
  191. static int getPixelFormat(int pixelSize, int flags)
  192. {
  193. if (pixelSize == 1) return TJPF_GRAY;
  194. if (pixelSize == 3) {
  195. if (flags & TJ_BGR) return TJPF_BGR;
  196. else return TJPF_RGB;
  197. }
  198. if (pixelSize == 4) {
  199. if (flags & TJ_ALPHAFIRST) {
  200. if (flags & TJ_BGR) return TJPF_XBGR;
  201. else return TJPF_XRGB;
  202. } else {
  203. if (flags & TJ_BGR) return TJPF_BGRX;
  204. else return TJPF_RGBX;
  205. }
  206. }
  207. return -1;
  208. }
  209. static int setCompDefaults(struct jpeg_compress_struct *cinfo, int pixelFormat,
  210. int subsamp, int jpegQual, int flags)
  211. {
  212. int retval = 0;
  213. #ifndef NO_GETENV
  214. char *env = NULL;
  215. #endif
  216. cinfo->in_color_space = pf2cs[pixelFormat];
  217. cinfo->input_components = tjPixelSize[pixelFormat];
  218. if((env=getenv("TJ_REVERT"))!=NULL && strlen(env)>0 && !strcmp(env, "1"))
  219. cinfo->master->compress_profile=JCP_FASTEST;
  220. jpeg_set_defaults(cinfo);
  221. #ifndef NO_GETENV
  222. if ((env = getenv("TJ_OPTIMIZE")) != NULL && strlen(env) > 0 &&
  223. !strcmp(env, "1"))
  224. cinfo->optimize_coding = TRUE;
  225. if ((env = getenv("TJ_ARITHMETIC")) != NULL && strlen(env) > 0 &&
  226. !strcmp(env, "1"))
  227. cinfo->arith_code = TRUE;
  228. if ((env = getenv("TJ_RESTART")) != NULL && strlen(env) > 0) {
  229. int temp = -1;
  230. char tempc = 0;
  231. if (sscanf(env, "%d%c", &temp, &tempc) >= 1 && temp >= 0 &&
  232. temp <= 65535) {
  233. if (toupper(tempc) == 'B') {
  234. cinfo->restart_interval = temp;
  235. cinfo->restart_in_rows = 0;
  236. } else
  237. cinfo->restart_in_rows = temp;
  238. }
  239. }
  240. #endif
  241. if (jpegQual >= 0) {
  242. jpeg_set_quality(cinfo, jpegQual, TRUE);
  243. if (jpegQual >= 96 || flags & TJFLAG_ACCURATEDCT)
  244. cinfo->dct_method = JDCT_ISLOW;
  245. else
  246. cinfo->dct_method = JDCT_FASTEST;
  247. }
  248. if (subsamp == TJSAMP_GRAY)
  249. jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
  250. else if (pixelFormat == TJPF_CMYK)
  251. jpeg_set_colorspace(cinfo, JCS_YCCK);
  252. else
  253. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  254. if (flags & TJFLAG_PROGRESSIVE)
  255. jpeg_simple_progression(cinfo);
  256. #ifndef NO_GETENV
  257. else if ((env = getenv("TJ_PROGRESSIVE")) != NULL && strlen(env) > 0 &&
  258. !strcmp(env, "1"))
  259. jpeg_simple_progression(cinfo);
  260. #endif
  261. /* Set scan pattern again as colorspace might have changed */
  262. if(cinfo->master->compress_profile == JCP_MAX_COMPRESSION)
  263. jpeg_simple_progression(cinfo);
  264. cinfo->comp_info[0].h_samp_factor = tjMCUWidth[subsamp] / 8;
  265. cinfo->comp_info[1].h_samp_factor = 1;
  266. cinfo->comp_info[2].h_samp_factor = 1;
  267. if (cinfo->num_components > 3)
  268. cinfo->comp_info[3].h_samp_factor = tjMCUWidth[subsamp] / 8;
  269. cinfo->comp_info[0].v_samp_factor = tjMCUHeight[subsamp] / 8;
  270. cinfo->comp_info[1].v_samp_factor = 1;
  271. cinfo->comp_info[2].v_samp_factor = 1;
  272. if (cinfo->num_components > 3)
  273. cinfo->comp_info[3].v_samp_factor = tjMCUHeight[subsamp] / 8;
  274. return retval;
  275. }
  276. static int getSubsamp(j_decompress_ptr dinfo)
  277. {
  278. int retval = -1, i, k;
  279. /* The sampling factors actually have no meaning with grayscale JPEG files,
  280. and in fact it's possible to generate grayscale JPEGs with sampling
  281. factors > 1 (even though those sampling factors are ignored by the
  282. decompressor.) Thus, we need to treat grayscale as a special case. */
  283. if (dinfo->num_components == 1 && dinfo->jpeg_color_space == JCS_GRAYSCALE)
  284. return TJSAMP_GRAY;
  285. for (i = 0; i < NUMSUBOPT; i++) {
  286. if (dinfo->num_components == pixelsize[i] ||
  287. ((dinfo->jpeg_color_space == JCS_YCCK ||
  288. dinfo->jpeg_color_space == JCS_CMYK) &&
  289. pixelsize[i] == 3 && dinfo->num_components == 4)) {
  290. if (dinfo->comp_info[0].h_samp_factor == tjMCUWidth[i] / 8 &&
  291. dinfo->comp_info[0].v_samp_factor == tjMCUHeight[i] / 8) {
  292. int match = 0;
  293. for (k = 1; k < dinfo->num_components; k++) {
  294. int href = 1, vref = 1;
  295. if ((dinfo->jpeg_color_space == JCS_YCCK ||
  296. dinfo->jpeg_color_space == JCS_CMYK) && k == 3) {
  297. href = tjMCUWidth[i] / 8; vref = tjMCUHeight[i] / 8;
  298. }
  299. if (dinfo->comp_info[k].h_samp_factor == href &&
  300. dinfo->comp_info[k].v_samp_factor == vref)
  301. match++;
  302. }
  303. if (match == dinfo->num_components - 1) {
  304. retval = i; break;
  305. }
  306. }
  307. /* Handle 4:2:2 and 4:4:0 images whose sampling factors are specified
  308. in non-standard ways. */
  309. if (dinfo->comp_info[0].h_samp_factor == 2 &&
  310. dinfo->comp_info[0].v_samp_factor == 2 &&
  311. (i == TJSAMP_422 || i == TJSAMP_440)) {
  312. int match = 0;
  313. for (k = 1; k < dinfo->num_components; k++) {
  314. int href = tjMCUHeight[i] / 8, vref = tjMCUWidth[i] / 8;
  315. if ((dinfo->jpeg_color_space == JCS_YCCK ||
  316. dinfo->jpeg_color_space == JCS_CMYK) && k == 3) {
  317. href = vref = 2;
  318. }
  319. if (dinfo->comp_info[k].h_samp_factor == href &&
  320. dinfo->comp_info[k].v_samp_factor == vref)
  321. match++;
  322. }
  323. if (match == dinfo->num_components - 1) {
  324. retval = i; break;
  325. }
  326. }
  327. /* Handle 4:4:4 images whose sampling factors are specified in
  328. non-standard ways. */
  329. if (dinfo->comp_info[0].h_samp_factor *
  330. dinfo->comp_info[0].v_samp_factor <=
  331. D_MAX_BLOCKS_IN_MCU / pixelsize[i] && i == TJSAMP_444) {
  332. int match = 0;
  333. for (k = 1; k < dinfo->num_components; k++) {
  334. if (dinfo->comp_info[k].h_samp_factor ==
  335. dinfo->comp_info[0].h_samp_factor &&
  336. dinfo->comp_info[k].v_samp_factor ==
  337. dinfo->comp_info[0].v_samp_factor)
  338. match++;
  339. if (match == dinfo->num_components - 1) {
  340. retval = i; break;
  341. }
  342. }
  343. }
  344. }
  345. }
  346. return retval;
  347. }
  348. /* General API functions */
  349. DLLEXPORT char *tjGetErrorStr2(tjhandle handle)
  350. {
  351. tjinstance *this = (tjinstance *)handle;
  352. if (this && this->isInstanceError) {
  353. this->isInstanceError = FALSE;
  354. return this->errStr;
  355. } else
  356. return errStr;
  357. }
  358. DLLEXPORT char *tjGetErrorStr(void)
  359. {
  360. return errStr;
  361. }
  362. DLLEXPORT int tjGetErrorCode(tjhandle handle)
  363. {
  364. tjinstance *this = (tjinstance *)handle;
  365. if (this && this->jerr.warning) return TJERR_WARNING;
  366. else return TJERR_FATAL;
  367. }
  368. DLLEXPORT int tjDestroy(tjhandle handle)
  369. {
  370. GET_INSTANCE(handle);
  371. if (setjmp(this->jerr.setjmp_buffer)) return -1;
  372. if (this->init & COMPRESS) jpeg_destroy_compress(cinfo);
  373. if (this->init & DECOMPRESS) jpeg_destroy_decompress(dinfo);
  374. free(this);
  375. return 0;
  376. }
  377. /* These are exposed mainly because Windows can't malloc() and free() across
  378. DLL boundaries except when the CRT DLL is used, and we don't use the CRT DLL
  379. with turbojpeg.dll for compatibility reasons. However, these functions
  380. can potentially be used for other purposes by different implementations. */
  381. DLLEXPORT void tjFree(unsigned char *buf)
  382. {
  383. free(buf);
  384. }
  385. DLLEXPORT unsigned char *tjAlloc(int bytes)
  386. {
  387. return (unsigned char *)malloc(bytes);
  388. }
  389. /* Compressor */
  390. static tjhandle _tjInitCompress(tjinstance *this)
  391. {
  392. static unsigned char buffer[1];
  393. unsigned char *buf = buffer;
  394. unsigned long size = 1;
  395. /* This is also straight out of example.txt */
  396. this->cinfo.err = jpeg_std_error(&this->jerr.pub);
  397. this->jerr.pub.error_exit = my_error_exit;
  398. this->jerr.pub.output_message = my_output_message;
  399. this->jerr.emit_message = this->jerr.pub.emit_message;
  400. this->jerr.pub.emit_message = my_emit_message;
  401. this->jerr.pub.addon_message_table = turbojpeg_message_table;
  402. this->jerr.pub.first_addon_message = JMSG_FIRSTADDONCODE;
  403. this->jerr.pub.last_addon_message = JMSG_LASTADDONCODE;
  404. if (setjmp(this->jerr.setjmp_buffer)) {
  405. /* If we get here, the JPEG code has signaled an error. */
  406. free(this);
  407. return NULL;
  408. }
  409. jpeg_create_compress(&this->cinfo);
  410. /* Make an initial call so it will create the destination manager */
  411. jpeg_mem_dest_tj(&this->cinfo, &buf, &size, 0);
  412. this->init |= COMPRESS;
  413. return (tjhandle)this;
  414. }
  415. DLLEXPORT tjhandle tjInitCompress(void)
  416. {
  417. tjinstance *this = NULL;
  418. if ((this = (tjinstance *)malloc(sizeof(tjinstance))) == NULL) {
  419. snprintf(errStr, JMSG_LENGTH_MAX,
  420. "tjInitCompress(): Memory allocation failure");
  421. return NULL;
  422. }
  423. MEMZERO(this, sizeof(tjinstance));
  424. snprintf(this->errStr, JMSG_LENGTH_MAX, "No error");
  425. return _tjInitCompress(this);
  426. }
  427. DLLEXPORT unsigned long tjBufSize(int width, int height, int jpegSubsamp)
  428. {
  429. unsigned long long retval = 0;
  430. int mcuw, mcuh, chromasf;
  431. if (width < 1 || height < 1 || jpegSubsamp < 0 || jpegSubsamp >= NUMSUBOPT)
  432. THROWG("tjBufSize(): Invalid argument");
  433. /* This allows for rare corner cases in which a JPEG image can actually be
  434. larger than the uncompressed input (we wouldn't mention it if it hadn't
  435. happened before.) */
  436. mcuw = tjMCUWidth[jpegSubsamp];
  437. mcuh = tjMCUHeight[jpegSubsamp];
  438. chromasf = jpegSubsamp == TJSAMP_GRAY ? 0 : 4 * 64 / (mcuw * mcuh);
  439. retval = PAD(width, mcuw) * PAD(height, mcuh) * (2ULL + chromasf) + 2048ULL;
  440. if (retval > (unsigned long long)((unsigned long)-1))
  441. THROWG("tjBufSize(): Image is too large");
  442. bailout:
  443. return (unsigned long)retval;
  444. }
  445. DLLEXPORT unsigned long TJBUFSIZE(int width, int height)
  446. {
  447. unsigned long long retval = 0;
  448. if (width < 1 || height < 1)
  449. THROWG("TJBUFSIZE(): Invalid argument");
  450. /* This allows for rare corner cases in which a JPEG image can actually be
  451. larger than the uncompressed input (we wouldn't mention it if it hadn't
  452. happened before.) */
  453. retval = PAD(width, 16) * PAD(height, 16) * 6ULL + 2048ULL;
  454. if (retval > (unsigned long long)((unsigned long)-1))
  455. THROWG("TJBUFSIZE(): Image is too large");
  456. bailout:
  457. return (unsigned long)retval;
  458. }
  459. DLLEXPORT unsigned long tjBufSizeYUV2(int width, int pad, int height,
  460. int subsamp)
  461. {
  462. unsigned long long retval = 0;
  463. int nc, i;
  464. if (subsamp < 0 || subsamp >= NUMSUBOPT)
  465. THROWG("tjBufSizeYUV2(): Invalid argument");
  466. nc = (subsamp == TJSAMP_GRAY ? 1 : 3);
  467. for (i = 0; i < nc; i++) {
  468. int pw = tjPlaneWidth(i, width, subsamp);
  469. int stride = PAD(pw, pad);
  470. int ph = tjPlaneHeight(i, height, subsamp);
  471. if (pw < 0 || ph < 0) return -1;
  472. else retval += (unsigned long long)stride * ph;
  473. }
  474. if (retval > (unsigned long long)((unsigned long)-1))
  475. THROWG("tjBufSizeYUV2(): Image is too large");
  476. bailout:
  477. return (unsigned long)retval;
  478. }
  479. DLLEXPORT unsigned long tjBufSizeYUV(int width, int height, int subsamp)
  480. {
  481. return tjBufSizeYUV2(width, 4, height, subsamp);
  482. }
  483. DLLEXPORT unsigned long TJBUFSIZEYUV(int width, int height, int subsamp)
  484. {
  485. return tjBufSizeYUV(width, height, subsamp);
  486. }
  487. DLLEXPORT int tjPlaneWidth(int componentID, int width, int subsamp)
  488. {
  489. int pw, nc, retval = 0;
  490. if (width < 1 || subsamp < 0 || subsamp >= TJ_NUMSAMP)
  491. THROWG("tjPlaneWidth(): Invalid argument");
  492. nc = (subsamp == TJSAMP_GRAY ? 1 : 3);
  493. if (componentID < 0 || componentID >= nc)
  494. THROWG("tjPlaneWidth(): Invalid argument");
  495. pw = PAD(width, tjMCUWidth[subsamp] / 8);
  496. if (componentID == 0)
  497. retval = pw;
  498. else
  499. retval = pw * 8 / tjMCUWidth[subsamp];
  500. bailout:
  501. return retval;
  502. }
  503. DLLEXPORT int tjPlaneHeight(int componentID, int height, int subsamp)
  504. {
  505. int ph, nc, retval = 0;
  506. if (height < 1 || subsamp < 0 || subsamp >= TJ_NUMSAMP)
  507. THROWG("tjPlaneHeight(): Invalid argument");
  508. nc = (subsamp == TJSAMP_GRAY ? 1 : 3);
  509. if (componentID < 0 || componentID >= nc)
  510. THROWG("tjPlaneHeight(): Invalid argument");
  511. ph = PAD(height, tjMCUHeight[subsamp] / 8);
  512. if (componentID == 0)
  513. retval = ph;
  514. else
  515. retval = ph * 8 / tjMCUHeight[subsamp];
  516. bailout:
  517. return retval;
  518. }
  519. DLLEXPORT unsigned long tjPlaneSizeYUV(int componentID, int width, int stride,
  520. int height, int subsamp)
  521. {
  522. unsigned long long retval = 0;
  523. int pw, ph;
  524. if (width < 1 || height < 1 || subsamp < 0 || subsamp >= NUMSUBOPT)
  525. THROWG("tjPlaneSizeYUV(): Invalid argument");
  526. pw = tjPlaneWidth(componentID, width, subsamp);
  527. ph = tjPlaneHeight(componentID, height, subsamp);
  528. if (pw < 0 || ph < 0) return -1;
  529. if (stride == 0) stride = pw;
  530. else stride = abs(stride);
  531. retval = (unsigned long long)stride * (ph - 1) + pw;
  532. if (retval > (unsigned long long)((unsigned long)-1))
  533. THROWG("tjPlaneSizeYUV(): Image is too large");
  534. bailout:
  535. return (unsigned long)retval;
  536. }
  537. DLLEXPORT int tjCompress2(tjhandle handle, const unsigned char *srcBuf,
  538. int width, int pitch, int height, int pixelFormat,
  539. unsigned char **jpegBuf, unsigned long *jpegSize,
  540. int jpegSubsamp, int jpegQual, int flags)
  541. {
  542. int i, retval = 0, alloc = 1;
  543. JSAMPROW *row_pointer = NULL;
  544. GET_CINSTANCE(handle)
  545. this->jerr.stopOnWarning = (flags & TJFLAG_STOPONWARNING) ? TRUE : FALSE;
  546. if ((this->init & COMPRESS) == 0)
  547. THROW("tjCompress2(): Instance has not been initialized for compression");
  548. if (srcBuf == NULL || width <= 0 || pitch < 0 || height <= 0 ||
  549. pixelFormat < 0 || pixelFormat >= TJ_NUMPF || jpegBuf == NULL ||
  550. jpegSize == NULL || jpegSubsamp < 0 || jpegSubsamp >= NUMSUBOPT ||
  551. jpegQual < 0 || jpegQual > 100)
  552. THROW("tjCompress2(): Invalid argument");
  553. if (pitch == 0) pitch = width * tjPixelSize[pixelFormat];
  554. if ((row_pointer = (JSAMPROW *)malloc(sizeof(JSAMPROW) * height)) == NULL)
  555. THROW("tjCompress2(): Memory allocation failure");
  556. if (setjmp(this->jerr.setjmp_buffer)) {
  557. /* If we get here, the JPEG code has signaled an error. */
  558. retval = -1; goto bailout;
  559. }
  560. cinfo->image_width = width;
  561. cinfo->image_height = height;
  562. #ifndef NO_PUTENV
  563. if (flags & TJFLAG_FORCEMMX) putenv("JSIMD_FORCEMMX=1");
  564. else if (flags & TJFLAG_FORCESSE) putenv("JSIMD_FORCESSE=1");
  565. else if (flags & TJFLAG_FORCESSE2) putenv("JSIMD_FORCESSE2=1");
  566. #endif
  567. if (flags & TJFLAG_NOREALLOC) {
  568. alloc = 0; *jpegSize = tjBufSize(width, height, jpegSubsamp);
  569. }
  570. jpeg_mem_dest_tj(cinfo, jpegBuf, jpegSize, alloc);
  571. if (setCompDefaults(cinfo, pixelFormat, jpegSubsamp, jpegQual, flags) == -1)
  572. return -1;
  573. jpeg_start_compress(cinfo, TRUE);
  574. for (i = 0; i < height; i++) {
  575. if (flags & TJFLAG_BOTTOMUP)
  576. row_pointer[i] = (JSAMPROW)&srcBuf[(height - i - 1) * (size_t)pitch];
  577. else
  578. row_pointer[i] = (JSAMPROW)&srcBuf[i * (size_t)pitch];
  579. }
  580. while (cinfo->next_scanline < cinfo->image_height)
  581. jpeg_write_scanlines(cinfo, &row_pointer[cinfo->next_scanline],
  582. cinfo->image_height - cinfo->next_scanline);
  583. jpeg_finish_compress(cinfo);
  584. bailout:
  585. if (cinfo->global_state > CSTATE_START) jpeg_abort_compress(cinfo);
  586. free(row_pointer);
  587. if (this->jerr.warning) retval = -1;
  588. this->jerr.stopOnWarning = FALSE;
  589. return retval;
  590. }
  591. DLLEXPORT int tjCompress(tjhandle handle, unsigned char *srcBuf, int width,
  592. int pitch, int height, int pixelSize,
  593. unsigned char *jpegBuf, unsigned long *jpegSize,
  594. int jpegSubsamp, int jpegQual, int flags)
  595. {
  596. int retval = 0;
  597. unsigned long size;
  598. if (flags & TJ_YUV) {
  599. size = tjBufSizeYUV(width, height, jpegSubsamp);
  600. retval = tjEncodeYUV2(handle, srcBuf, width, pitch, height,
  601. getPixelFormat(pixelSize, flags), jpegBuf,
  602. jpegSubsamp, flags);
  603. } else {
  604. retval = tjCompress2(handle, srcBuf, width, pitch, height,
  605. getPixelFormat(pixelSize, flags), &jpegBuf, &size,
  606. jpegSubsamp, jpegQual, flags | TJFLAG_NOREALLOC);
  607. }
  608. *jpegSize = size;
  609. return retval;
  610. }
  611. DLLEXPORT int tjEncodeYUVPlanes(tjhandle handle, const unsigned char *srcBuf,
  612. int width, int pitch, int height,
  613. int pixelFormat, unsigned char **dstPlanes,
  614. int *strides, int subsamp, int flags)
  615. {
  616. JSAMPROW *row_pointer = NULL;
  617. JSAMPLE *_tmpbuf[MAX_COMPONENTS], *_tmpbuf2[MAX_COMPONENTS];
  618. JSAMPROW *tmpbuf[MAX_COMPONENTS], *tmpbuf2[MAX_COMPONENTS];
  619. JSAMPROW *outbuf[MAX_COMPONENTS];
  620. int i, retval = 0, row, pw0, ph0, pw[MAX_COMPONENTS], ph[MAX_COMPONENTS];
  621. JSAMPLE *ptr;
  622. jpeg_component_info *compptr;
  623. GET_CINSTANCE(handle);
  624. this->jerr.stopOnWarning = (flags & TJFLAG_STOPONWARNING) ? TRUE : FALSE;
  625. for (i = 0; i < MAX_COMPONENTS; i++) {
  626. tmpbuf[i] = NULL; _tmpbuf[i] = NULL;
  627. tmpbuf2[i] = NULL; _tmpbuf2[i] = NULL; outbuf[i] = NULL;
  628. }
  629. if ((this->init & COMPRESS) == 0)
  630. THROW("tjEncodeYUVPlanes(): Instance has not been initialized for compression");
  631. if (srcBuf == NULL || width <= 0 || pitch < 0 || height <= 0 ||
  632. pixelFormat < 0 || pixelFormat >= TJ_NUMPF || !dstPlanes ||
  633. !dstPlanes[0] || subsamp < 0 || subsamp >= NUMSUBOPT)
  634. THROW("tjEncodeYUVPlanes(): Invalid argument");
  635. if (subsamp != TJSAMP_GRAY && (!dstPlanes[1] || !dstPlanes[2]))
  636. THROW("tjEncodeYUVPlanes(): Invalid argument");
  637. if (pixelFormat == TJPF_CMYK)
  638. THROW("tjEncodeYUVPlanes(): Cannot generate YUV images from CMYK pixels");
  639. if (pitch == 0) pitch = width * tjPixelSize[pixelFormat];
  640. if (setjmp(this->jerr.setjmp_buffer)) {
  641. /* If we get here, the JPEG code has signaled an error. */
  642. retval = -1; goto bailout;
  643. }
  644. cinfo->image_width = width;
  645. cinfo->image_height = height;
  646. #ifndef NO_PUTENV
  647. if (flags & TJFLAG_FORCEMMX) putenv("JSIMD_FORCEMMX=1");
  648. else if (flags & TJFLAG_FORCESSE) putenv("JSIMD_FORCESSE=1");
  649. else if (flags & TJFLAG_FORCESSE2) putenv("JSIMD_FORCESSE2=1");
  650. #endif
  651. if (setCompDefaults(cinfo, pixelFormat, subsamp, -1, flags) == -1) return -1;
  652. /* Execute only the parts of jpeg_start_compress() that we need. If we
  653. were to call the whole jpeg_start_compress() function, then it would try
  654. to write the file headers, which could overflow the output buffer if the
  655. YUV image were very small. */
  656. if (cinfo->global_state != CSTATE_START)
  657. THROW("tjEncodeYUVPlanes(): libjpeg API is in the wrong state");
  658. (*cinfo->err->reset_error_mgr) ((j_common_ptr)cinfo);
  659. jinit_c_master_control(cinfo, FALSE);
  660. jinit_color_converter(cinfo);
  661. jinit_downsampler(cinfo);
  662. (*cinfo->cconvert->start_pass) (cinfo);
  663. pw0 = PAD(width, cinfo->max_h_samp_factor);
  664. ph0 = PAD(height, cinfo->max_v_samp_factor);
  665. if ((row_pointer = (JSAMPROW *)malloc(sizeof(JSAMPROW) * ph0)) == NULL)
  666. THROW("tjEncodeYUVPlanes(): Memory allocation failure");
  667. for (i = 0; i < height; i++) {
  668. if (flags & TJFLAG_BOTTOMUP)
  669. row_pointer[i] = (JSAMPROW)&srcBuf[(height - i - 1) * (size_t)pitch];
  670. else
  671. row_pointer[i] = (JSAMPROW)&srcBuf[i * (size_t)pitch];
  672. }
  673. if (height < ph0)
  674. for (i = height; i < ph0; i++) row_pointer[i] = row_pointer[height - 1];
  675. for (i = 0; i < cinfo->num_components; i++) {
  676. compptr = &cinfo->comp_info[i];
  677. _tmpbuf[i] = (JSAMPLE *)malloc(
  678. PAD((compptr->width_in_blocks * cinfo->max_h_samp_factor * DCTSIZE) /
  679. compptr->h_samp_factor, 32) *
  680. cinfo->max_v_samp_factor + 32);
  681. if (!_tmpbuf[i])
  682. THROW("tjEncodeYUVPlanes(): Memory allocation failure");
  683. tmpbuf[i] =
  684. (JSAMPROW *)malloc(sizeof(JSAMPROW) * cinfo->max_v_samp_factor);
  685. if (!tmpbuf[i])
  686. THROW("tjEncodeYUVPlanes(): Memory allocation failure");
  687. for (row = 0; row < cinfo->max_v_samp_factor; row++) {
  688. unsigned char *_tmpbuf_aligned =
  689. (unsigned char *)PAD((size_t)_tmpbuf[i], 32);
  690. tmpbuf[i][row] = &_tmpbuf_aligned[
  691. PAD((compptr->width_in_blocks * cinfo->max_h_samp_factor * DCTSIZE) /
  692. compptr->h_samp_factor, 32) * row];
  693. }
  694. _tmpbuf2[i] =
  695. (JSAMPLE *)malloc(PAD(compptr->width_in_blocks * DCTSIZE, 32) *
  696. compptr->v_samp_factor + 32);
  697. if (!_tmpbuf2[i])
  698. THROW("tjEncodeYUVPlanes(): Memory allocation failure");
  699. tmpbuf2[i] = (JSAMPROW *)malloc(sizeof(JSAMPROW) * compptr->v_samp_factor);
  700. if (!tmpbuf2[i])
  701. THROW("tjEncodeYUVPlanes(): Memory allocation failure");
  702. for (row = 0; row < compptr->v_samp_factor; row++) {
  703. unsigned char *_tmpbuf2_aligned =
  704. (unsigned char *)PAD((size_t)_tmpbuf2[i], 32);
  705. tmpbuf2[i][row] =
  706. &_tmpbuf2_aligned[PAD(compptr->width_in_blocks * DCTSIZE, 32) * row];
  707. }
  708. pw[i] = pw0 * compptr->h_samp_factor / cinfo->max_h_samp_factor;
  709. ph[i] = ph0 * compptr->v_samp_factor / cinfo->max_v_samp_factor;
  710. outbuf[i] = (JSAMPROW *)malloc(sizeof(JSAMPROW) * ph[i]);
  711. if (!outbuf[i])
  712. THROW("tjEncodeYUVPlanes(): Memory allocation failure");
  713. ptr = dstPlanes[i];
  714. for (row = 0; row < ph[i]; row++) {
  715. outbuf[i][row] = ptr;
  716. ptr += (strides && strides[i] != 0) ? strides[i] : pw[i];
  717. }
  718. }
  719. if (setjmp(this->jerr.setjmp_buffer)) {
  720. /* If we get here, the JPEG code has signaled an error. */
  721. retval = -1; goto bailout;
  722. }
  723. for (row = 0; row < ph0; row += cinfo->max_v_samp_factor) {
  724. (*cinfo->cconvert->color_convert) (cinfo, &row_pointer[row], tmpbuf, 0,
  725. cinfo->max_v_samp_factor);
  726. (cinfo->downsample->downsample) (cinfo, tmpbuf, 0, tmpbuf2, 0);
  727. for (i = 0, compptr = cinfo->comp_info; i < cinfo->num_components;
  728. i++, compptr++)
  729. jcopy_sample_rows(tmpbuf2[i], 0, outbuf[i],
  730. row * compptr->v_samp_factor / cinfo->max_v_samp_factor,
  731. compptr->v_samp_factor, pw[i]);
  732. }
  733. cinfo->next_scanline += height;
  734. jpeg_abort_compress(cinfo);
  735. bailout:
  736. if (cinfo->global_state > CSTATE_START) jpeg_abort_compress(cinfo);
  737. free(row_pointer);
  738. for (i = 0; i < MAX_COMPONENTS; i++) {
  739. free(tmpbuf[i]);
  740. free(_tmpbuf[i]);
  741. free(tmpbuf2[i]);
  742. free(_tmpbuf2[i]);
  743. free(outbuf[i]);
  744. }
  745. if (this->jerr.warning) retval = -1;
  746. this->jerr.stopOnWarning = FALSE;
  747. return retval;
  748. }
  749. DLLEXPORT int tjEncodeYUV3(tjhandle handle, const unsigned char *srcBuf,
  750. int width, int pitch, int height, int pixelFormat,
  751. unsigned char *dstBuf, int pad, int subsamp,
  752. int flags)
  753. {
  754. unsigned char *dstPlanes[3];
  755. int pw0, ph0, strides[3], retval = -1;
  756. tjinstance *this = (tjinstance *)handle;
  757. if (!this) THROWG("tjEncodeYUV3(): Invalid handle");
  758. this->isInstanceError = FALSE;
  759. if (width <= 0 || height <= 0 || dstBuf == NULL || pad < 0 ||
  760. !IS_POW2(pad) || subsamp < 0 || subsamp >= NUMSUBOPT)
  761. THROW("tjEncodeYUV3(): Invalid argument");
  762. pw0 = tjPlaneWidth(0, width, subsamp);
  763. ph0 = tjPlaneHeight(0, height, subsamp);
  764. dstPlanes[0] = dstBuf;
  765. strides[0] = PAD(pw0, pad);
  766. if (subsamp == TJSAMP_GRAY) {
  767. strides[1] = strides[2] = 0;
  768. dstPlanes[1] = dstPlanes[2] = NULL;
  769. } else {
  770. int pw1 = tjPlaneWidth(1, width, subsamp);
  771. int ph1 = tjPlaneHeight(1, height, subsamp);
  772. strides[1] = strides[2] = PAD(pw1, pad);
  773. dstPlanes[1] = dstPlanes[0] + strides[0] * ph0;
  774. dstPlanes[2] = dstPlanes[1] + strides[1] * ph1;
  775. }
  776. return tjEncodeYUVPlanes(handle, srcBuf, width, pitch, height, pixelFormat,
  777. dstPlanes, strides, subsamp, flags);
  778. bailout:
  779. return retval;
  780. }
  781. DLLEXPORT int tjEncodeYUV2(tjhandle handle, unsigned char *srcBuf, int width,
  782. int pitch, int height, int pixelFormat,
  783. unsigned char *dstBuf, int subsamp, int flags)
  784. {
  785. return tjEncodeYUV3(handle, srcBuf, width, pitch, height, pixelFormat,
  786. dstBuf, 4, subsamp, flags);
  787. }
  788. DLLEXPORT int tjEncodeYUV(tjhandle handle, unsigned char *srcBuf, int width,
  789. int pitch, int height, int pixelSize,
  790. unsigned char *dstBuf, int subsamp, int flags)
  791. {
  792. return tjEncodeYUV2(handle, srcBuf, width, pitch, height,
  793. getPixelFormat(pixelSize, flags), dstBuf, subsamp,
  794. flags);
  795. }
  796. DLLEXPORT int tjCompressFromYUVPlanes(tjhandle handle,
  797. const unsigned char **srcPlanes,
  798. int width, const int *strides,
  799. int height, int subsamp,
  800. unsigned char **jpegBuf,
  801. unsigned long *jpegSize, int jpegQual,
  802. int flags)
  803. {
  804. int i, row, retval = 0, alloc = 1;
  805. int pw[MAX_COMPONENTS], ph[MAX_COMPONENTS], iw[MAX_COMPONENTS],
  806. tmpbufsize = 0, usetmpbuf = 0, th[MAX_COMPONENTS];
  807. JSAMPLE *_tmpbuf = NULL, *ptr;
  808. JSAMPROW *inbuf[MAX_COMPONENTS], *tmpbuf[MAX_COMPONENTS];
  809. GET_CINSTANCE(handle)
  810. this->jerr.stopOnWarning = (flags & TJFLAG_STOPONWARNING) ? TRUE : FALSE;
  811. for (i = 0; i < MAX_COMPONENTS; i++) {
  812. tmpbuf[i] = NULL; inbuf[i] = NULL;
  813. }
  814. if ((this->init & COMPRESS) == 0)
  815. THROW("tjCompressFromYUVPlanes(): Instance has not been initialized for compression");
  816. if (!srcPlanes || !srcPlanes[0] || width <= 0 || height <= 0 ||
  817. subsamp < 0 || subsamp >= NUMSUBOPT || jpegBuf == NULL ||
  818. jpegSize == NULL || jpegQual < 0 || jpegQual > 100)
  819. THROW("tjCompressFromYUVPlanes(): Invalid argument");
  820. if (subsamp != TJSAMP_GRAY && (!srcPlanes[1] || !srcPlanes[2]))
  821. THROW("tjCompressFromYUVPlanes(): Invalid argument");
  822. if (setjmp(this->jerr.setjmp_buffer)) {
  823. /* If we get here, the JPEG code has signaled an error. */
  824. retval = -1; goto bailout;
  825. }
  826. cinfo->image_width = width;
  827. cinfo->image_height = height;
  828. #ifndef NO_PUTENV
  829. if (flags & TJFLAG_FORCEMMX) putenv("JSIMD_FORCEMMX=1");
  830. else if (flags & TJFLAG_FORCESSE) putenv("JSIMD_FORCESSE=1");
  831. else if (flags & TJFLAG_FORCESSE2) putenv("JSIMD_FORCESSE2=1");
  832. #endif
  833. if (flags & TJFLAG_NOREALLOC) {
  834. alloc = 0; *jpegSize = tjBufSize(width, height, subsamp);
  835. }
  836. jpeg_mem_dest_tj(cinfo, jpegBuf, jpegSize, alloc);
  837. if (setCompDefaults(cinfo, TJPF_RGB, subsamp, jpegQual, flags) == -1)
  838. return -1;
  839. cinfo->raw_data_in = TRUE;
  840. jpeg_start_compress(cinfo, TRUE);
  841. for (i = 0; i < cinfo->num_components; i++) {
  842. jpeg_component_info *compptr = &cinfo->comp_info[i];
  843. int ih;
  844. iw[i] = compptr->width_in_blocks * DCTSIZE;
  845. ih = compptr->height_in_blocks * DCTSIZE;
  846. pw[i] = PAD(cinfo->image_width, cinfo->max_h_samp_factor) *
  847. compptr->h_samp_factor / cinfo->max_h_samp_factor;
  848. ph[i] = PAD(cinfo->image_height, cinfo->max_v_samp_factor) *
  849. compptr->v_samp_factor / cinfo->max_v_samp_factor;
  850. if (iw[i] != pw[i] || ih != ph[i]) usetmpbuf = 1;
  851. th[i] = compptr->v_samp_factor * DCTSIZE;
  852. tmpbufsize += iw[i] * th[i];
  853. if ((inbuf[i] = (JSAMPROW *)malloc(sizeof(JSAMPROW) * ph[i])) == NULL)
  854. THROW("tjCompressFromYUVPlanes(): Memory allocation failure");
  855. ptr = (JSAMPLE *)srcPlanes[i];
  856. for (row = 0; row < ph[i]; row++) {
  857. inbuf[i][row] = ptr;
  858. ptr += (strides && strides[i] != 0) ? strides[i] : pw[i];
  859. }
  860. }
  861. if (usetmpbuf) {
  862. if ((_tmpbuf = (JSAMPLE *)malloc(sizeof(JSAMPLE) * tmpbufsize)) == NULL)
  863. THROW("tjCompressFromYUVPlanes(): Memory allocation failure");
  864. ptr = _tmpbuf;
  865. for (i = 0; i < cinfo->num_components; i++) {
  866. if ((tmpbuf[i] = (JSAMPROW *)malloc(sizeof(JSAMPROW) * th[i])) == NULL)
  867. THROW("tjCompressFromYUVPlanes(): Memory allocation failure");
  868. for (row = 0; row < th[i]; row++) {
  869. tmpbuf[i][row] = ptr;
  870. ptr += iw[i];
  871. }
  872. }
  873. }
  874. if (setjmp(this->jerr.setjmp_buffer)) {
  875. /* If we get here, the JPEG code has signaled an error. */
  876. retval = -1; goto bailout;
  877. }
  878. for (row = 0; row < (int)cinfo->image_height;
  879. row += cinfo->max_v_samp_factor * DCTSIZE) {
  880. JSAMPARRAY yuvptr[MAX_COMPONENTS];
  881. int crow[MAX_COMPONENTS];
  882. for (i = 0; i < cinfo->num_components; i++) {
  883. jpeg_component_info *compptr = &cinfo->comp_info[i];
  884. crow[i] = row * compptr->v_samp_factor / cinfo->max_v_samp_factor;
  885. if (usetmpbuf) {
  886. int j, k;
  887. for (j = 0; j < MIN(th[i], ph[i] - crow[i]); j++) {
  888. memcpy(tmpbuf[i][j], inbuf[i][crow[i] + j], pw[i]);
  889. /* Duplicate last sample in row to fill out MCU */
  890. for (k = pw[i]; k < iw[i]; k++)
  891. tmpbuf[i][j][k] = tmpbuf[i][j][pw[i] - 1];
  892. }
  893. /* Duplicate last row to fill out MCU */
  894. for (j = ph[i] - crow[i]; j < th[i]; j++)
  895. memcpy(tmpbuf[i][j], tmpbuf[i][ph[i] - crow[i] - 1], iw[i]);
  896. yuvptr[i] = tmpbuf[i];
  897. } else
  898. yuvptr[i] = &inbuf[i][crow[i]];
  899. }
  900. jpeg_write_raw_data(cinfo, yuvptr, cinfo->max_v_samp_factor * DCTSIZE);
  901. }
  902. jpeg_finish_compress(cinfo);
  903. bailout:
  904. if (cinfo->global_state > CSTATE_START) jpeg_abort_compress(cinfo);
  905. for (i = 0; i < MAX_COMPONENTS; i++) {
  906. free(tmpbuf[i]);
  907. free(inbuf[i]);
  908. }
  909. free(_tmpbuf);
  910. if (this->jerr.warning) retval = -1;
  911. this->jerr.stopOnWarning = FALSE;
  912. return retval;
  913. }
  914. DLLEXPORT int tjCompressFromYUV(tjhandle handle, const unsigned char *srcBuf,
  915. int width, int pad, int height, int subsamp,
  916. unsigned char **jpegBuf,
  917. unsigned long *jpegSize, int jpegQual,
  918. int flags)
  919. {
  920. const unsigned char *srcPlanes[3];
  921. int pw0, ph0, strides[3], retval = -1;
  922. tjinstance *this = (tjinstance *)handle;
  923. if (!this) THROWG("tjCompressFromYUV(): Invalid handle");
  924. this->isInstanceError = FALSE;
  925. if (srcBuf == NULL || width <= 0 || pad < 1 || height <= 0 || subsamp < 0 ||
  926. subsamp >= NUMSUBOPT)
  927. THROW("tjCompressFromYUV(): Invalid argument");
  928. pw0 = tjPlaneWidth(0, width, subsamp);
  929. ph0 = tjPlaneHeight(0, height, subsamp);
  930. srcPlanes[0] = srcBuf;
  931. strides[0] = PAD(pw0, pad);
  932. if (subsamp == TJSAMP_GRAY) {
  933. strides[1] = strides[2] = 0;
  934. srcPlanes[1] = srcPlanes[2] = NULL;
  935. } else {
  936. int pw1 = tjPlaneWidth(1, width, subsamp);
  937. int ph1 = tjPlaneHeight(1, height, subsamp);
  938. strides[1] = strides[2] = PAD(pw1, pad);
  939. srcPlanes[1] = srcPlanes[0] + strides[0] * ph0;
  940. srcPlanes[2] = srcPlanes[1] + strides[1] * ph1;
  941. }
  942. return tjCompressFromYUVPlanes(handle, srcPlanes, width, strides, height,
  943. subsamp, jpegBuf, jpegSize, jpegQual, flags);
  944. bailout:
  945. return retval;
  946. }
  947. /* Decompressor */
  948. static tjhandle _tjInitDecompress(tjinstance *this)
  949. {
  950. static unsigned char buffer[1];
  951. /* This is also straight out of example.txt */
  952. this->dinfo.err = jpeg_std_error(&this->jerr.pub);
  953. this->jerr.pub.error_exit = my_error_exit;
  954. this->jerr.pub.output_message = my_output_message;
  955. this->jerr.emit_message = this->jerr.pub.emit_message;
  956. this->jerr.pub.emit_message = my_emit_message;
  957. this->jerr.pub.addon_message_table = turbojpeg_message_table;
  958. this->jerr.pub.first_addon_message = JMSG_FIRSTADDONCODE;
  959. this->jerr.pub.last_addon_message = JMSG_LASTADDONCODE;
  960. if (setjmp(this->jerr.setjmp_buffer)) {
  961. /* If we get here, the JPEG code has signaled an error. */
  962. free(this);
  963. return NULL;
  964. }
  965. jpeg_create_decompress(&this->dinfo);
  966. /* Make an initial call so it will create the source manager */
  967. jpeg_mem_src_tj(&this->dinfo, buffer, 1);
  968. this->init |= DECOMPRESS;
  969. return (tjhandle)this;
  970. }
  971. DLLEXPORT tjhandle tjInitDecompress(void)
  972. {
  973. tjinstance *this;
  974. if ((this = (tjinstance *)malloc(sizeof(tjinstance))) == NULL) {
  975. snprintf(errStr, JMSG_LENGTH_MAX,
  976. "tjInitDecompress(): Memory allocation failure");
  977. return NULL;
  978. }
  979. MEMZERO(this, sizeof(tjinstance));
  980. snprintf(this->errStr, JMSG_LENGTH_MAX, "No error");
  981. return _tjInitDecompress(this);
  982. }
  983. DLLEXPORT int tjDecompressHeader3(tjhandle handle,
  984. const unsigned char *jpegBuf,
  985. unsigned long jpegSize, int *width,
  986. int *height, int *jpegSubsamp,
  987. int *jpegColorspace)
  988. {
  989. int retval = 0;
  990. GET_DINSTANCE(handle);
  991. if ((this->init & DECOMPRESS) == 0)
  992. THROW("tjDecompressHeader3(): Instance has not been initialized for decompression");
  993. if (jpegBuf == NULL || jpegSize <= 0 || width == NULL || height == NULL ||
  994. jpegSubsamp == NULL || jpegColorspace == NULL)
  995. THROW("tjDecompressHeader3(): Invalid argument");
  996. if (setjmp(this->jerr.setjmp_buffer)) {
  997. /* If we get here, the JPEG code has signaled an error. */
  998. return -1;
  999. }
  1000. jpeg_mem_src_tj(dinfo, jpegBuf, jpegSize);
  1001. jpeg_read_header(dinfo, TRUE);
  1002. *width = dinfo->image_width;
  1003. *height = dinfo->image_height;
  1004. *jpegSubsamp = getSubsamp(dinfo);
  1005. switch (dinfo->jpeg_color_space) {
  1006. case JCS_GRAYSCALE: *jpegColorspace = TJCS_GRAY; break;
  1007. case JCS_RGB: *jpegColorspace = TJCS_RGB; break;
  1008. case JCS_YCbCr: *jpegColorspace = TJCS_YCbCr; break;
  1009. case JCS_CMYK: *jpegColorspace = TJCS_CMYK; break;
  1010. case JCS_YCCK: *jpegColorspace = TJCS_YCCK; break;
  1011. default: *jpegColorspace = -1; break;
  1012. }
  1013. jpeg_abort_decompress(dinfo);
  1014. if (*jpegSubsamp < 0)
  1015. THROW("tjDecompressHeader3(): Could not determine subsampling type for JPEG image");
  1016. if (*jpegColorspace < 0)
  1017. THROW("tjDecompressHeader3(): Could not determine colorspace of JPEG image");
  1018. if (*width < 1 || *height < 1)
  1019. THROW("tjDecompressHeader3(): Invalid data returned in header");
  1020. bailout:
  1021. if (this->jerr.warning) retval = -1;
  1022. return retval;
  1023. }
  1024. DLLEXPORT int tjDecompressHeader2(tjhandle handle, unsigned char *jpegBuf,
  1025. unsigned long jpegSize, int *width,
  1026. int *height, int *jpegSubsamp)
  1027. {
  1028. int jpegColorspace;
  1029. return tjDecompressHeader3(handle, jpegBuf, jpegSize, width, height,
  1030. jpegSubsamp, &jpegColorspace);
  1031. }
  1032. DLLEXPORT int tjDecompressHeader(tjhandle handle, unsigned char *jpegBuf,
  1033. unsigned long jpegSize, int *width,
  1034. int *height)
  1035. {
  1036. int jpegSubsamp;
  1037. return tjDecompressHeader2(handle, jpegBuf, jpegSize, width, height,
  1038. &jpegSubsamp);
  1039. }
  1040. DLLEXPORT tjscalingfactor *tjGetScalingFactors(int *numscalingfactors)
  1041. {
  1042. if (numscalingfactors == NULL) {
  1043. snprintf(errStr, JMSG_LENGTH_MAX,
  1044. "tjGetScalingFactors(): Invalid argument");
  1045. return NULL;
  1046. }
  1047. *numscalingfactors = NUMSF;
  1048. return (tjscalingfactor *)sf;
  1049. }
  1050. DLLEXPORT int tjDecompress2(tjhandle handle, const unsigned char *jpegBuf,
  1051. unsigned long jpegSize, unsigned char *dstBuf,
  1052. int width, int pitch, int height, int pixelFormat,
  1053. int flags)
  1054. {
  1055. JSAMPROW *row_pointer = NULL;
  1056. int i, retval = 0, jpegwidth, jpegheight, scaledw, scaledh;
  1057. GET_DINSTANCE(handle);
  1058. this->jerr.stopOnWarning = (flags & TJFLAG_STOPONWARNING) ? TRUE : FALSE;
  1059. if ((this->init & DECOMPRESS) == 0)
  1060. THROW("tjDecompress2(): Instance has not been initialized for decompression");
  1061. if (jpegBuf == NULL || jpegSize <= 0 || dstBuf == NULL || width < 0 ||
  1062. pitch < 0 || height < 0 || pixelFormat < 0 || pixelFormat >= TJ_NUMPF)
  1063. THROW("tjDecompress2(): Invalid argument");
  1064. #ifndef NO_PUTENV
  1065. if (flags & TJFLAG_FORCEMMX) putenv("JSIMD_FORCEMMX=1");
  1066. else if (flags & TJFLAG_FORCESSE) putenv("JSIMD_FORCESSE=1");
  1067. else if (flags & TJFLAG_FORCESSE2) putenv("JSIMD_FORCESSE2=1");
  1068. #endif
  1069. if (setjmp(this->jerr.setjmp_buffer)) {
  1070. /* If we get here, the JPEG code has signaled an error. */
  1071. retval = -1; goto bailout;
  1072. }
  1073. jpeg_mem_src_tj(dinfo, jpegBuf, jpegSize);
  1074. jpeg_read_header(dinfo, TRUE);
  1075. this->dinfo.out_color_space = pf2cs[pixelFormat];
  1076. if (flags & TJFLAG_FASTDCT) this->dinfo.dct_method = JDCT_FASTEST;
  1077. if (flags & TJFLAG_FASTUPSAMPLE) dinfo->do_fancy_upsampling = FALSE;
  1078. jpegwidth = dinfo->image_width; jpegheight = dinfo->image_height;
  1079. if (width == 0) width = jpegwidth;
  1080. if (height == 0) height = jpegheight;
  1081. for (i = 0; i < NUMSF; i++) {
  1082. scaledw = TJSCALED(jpegwidth, sf[i]);
  1083. scaledh = TJSCALED(jpegheight, sf[i]);
  1084. if (scaledw <= width && scaledh <= height)
  1085. break;
  1086. }
  1087. if (i >= NUMSF)
  1088. THROW("tjDecompress2(): Could not scale down to desired image dimensions");
  1089. width = scaledw; height = scaledh;
  1090. dinfo->scale_num = sf[i].num;
  1091. dinfo->scale_denom = sf[i].denom;
  1092. jpeg_start_decompress(dinfo);
  1093. if (pitch == 0) pitch = dinfo->output_width * tjPixelSize[pixelFormat];
  1094. if ((row_pointer =
  1095. (JSAMPROW *)malloc(sizeof(JSAMPROW) * dinfo->output_height)) == NULL)
  1096. THROW("tjDecompress2(): Memory allocation failure");
  1097. if (setjmp(this->jerr.setjmp_buffer)) {
  1098. /* If we get here, the JPEG code has signaled an error. */
  1099. retval = -1; goto bailout;
  1100. }
  1101. for (i = 0; i < (int)dinfo->output_height; i++) {
  1102. if (flags & TJFLAG_BOTTOMUP)
  1103. row_pointer[i] = &dstBuf[(dinfo->output_height - i - 1) * (size_t)pitch];
  1104. else
  1105. row_pointer[i] = &dstBuf[i * (size_t)pitch];
  1106. }
  1107. while (dinfo->output_scanline < dinfo->output_height)
  1108. jpeg_read_scanlines(dinfo, &row_pointer[dinfo->output_scanline],
  1109. dinfo->output_height - dinfo->output_scanline);
  1110. jpeg_finish_decompress(dinfo);
  1111. bailout:
  1112. if (dinfo->global_state > DSTATE_START) jpeg_abort_decompress(dinfo);
  1113. free(row_pointer);
  1114. if (this->jerr.warning) retval = -1;
  1115. this->jerr.stopOnWarning = FALSE;
  1116. return retval;
  1117. }
  1118. DLLEXPORT int tjDecompress(tjhandle handle, unsigned char *jpegBuf,
  1119. unsigned long jpegSize, unsigned char *dstBuf,
  1120. int width, int pitch, int height, int pixelSize,
  1121. int flags)
  1122. {
  1123. if (flags & TJ_YUV)
  1124. return tjDecompressToYUV(handle, jpegBuf, jpegSize, dstBuf, flags);
  1125. else
  1126. return tjDecompress2(handle, jpegBuf, jpegSize, dstBuf, width, pitch,
  1127. height, getPixelFormat(pixelSize, flags), flags);
  1128. }
  1129. static int setDecodeDefaults(struct jpeg_decompress_struct *dinfo,
  1130. int pixelFormat, int subsamp, int flags)
  1131. {
  1132. int i;
  1133. dinfo->scale_num = dinfo->scale_denom = 1;
  1134. if (subsamp == TJSAMP_GRAY) {
  1135. dinfo->num_components = dinfo->comps_in_scan = 1;
  1136. dinfo->jpeg_color_space = JCS_GRAYSCALE;
  1137. } else {
  1138. dinfo->num_components = dinfo->comps_in_scan = 3;
  1139. dinfo->jpeg_color_space = JCS_YCbCr;
  1140. }
  1141. dinfo->comp_info = (jpeg_component_info *)
  1142. (*dinfo->mem->alloc_small) ((j_common_ptr)dinfo, JPOOL_IMAGE,
  1143. dinfo->num_components *
  1144. sizeof(jpeg_component_info));
  1145. for (i = 0; i < dinfo->num_components; i++) {
  1146. jpeg_component_info *compptr = &dinfo->comp_info[i];
  1147. compptr->h_samp_factor = (i == 0) ? tjMCUWidth[subsamp] / 8 : 1;
  1148. compptr->v_samp_factor = (i == 0) ? tjMCUHeight[subsamp] / 8 : 1;
  1149. compptr->component_index = i;
  1150. compptr->component_id = i + 1;
  1151. compptr->quant_tbl_no = compptr->dc_tbl_no =
  1152. compptr->ac_tbl_no = (i == 0) ? 0 : 1;
  1153. dinfo->cur_comp_info[i] = compptr;
  1154. }
  1155. dinfo->data_precision = 8;
  1156. for (i = 0; i < 2; i++) {
  1157. if (dinfo->quant_tbl_ptrs[i] == NULL)
  1158. dinfo->quant_tbl_ptrs[i] = jpeg_alloc_quant_table((j_common_ptr)dinfo);
  1159. }
  1160. return 0;
  1161. }
  1162. static int my_read_markers(j_decompress_ptr dinfo)
  1163. {
  1164. return JPEG_REACHED_SOS;
  1165. }
  1166. static void my_reset_marker_reader(j_decompress_ptr dinfo)
  1167. {
  1168. }
  1169. DLLEXPORT int tjDecodeYUVPlanes(tjhandle handle,
  1170. const unsigned char **srcPlanes,
  1171. const int *strides, int subsamp,
  1172. unsigned char *dstBuf, int width, int pitch,
  1173. int height, int pixelFormat, int flags)
  1174. {
  1175. JSAMPROW *row_pointer = NULL;
  1176. JSAMPLE *_tmpbuf[MAX_COMPONENTS];
  1177. JSAMPROW *tmpbuf[MAX_COMPONENTS], *inbuf[MAX_COMPONENTS];
  1178. int i, retval = 0, row, pw0, ph0, pw[MAX_COMPONENTS], ph[MAX_COMPONENTS];
  1179. JSAMPLE *ptr;
  1180. jpeg_component_info *compptr;
  1181. int (*old_read_markers) (j_decompress_ptr);
  1182. void (*old_reset_marker_reader) (j_decompress_ptr);
  1183. GET_DINSTANCE(handle);
  1184. this->jerr.stopOnWarning = (flags & TJFLAG_STOPONWARNING) ? TRUE : FALSE;
  1185. for (i = 0; i < MAX_COMPONENTS; i++) {
  1186. tmpbuf[i] = NULL; _tmpbuf[i] = NULL; inbuf[i] = NULL;
  1187. }
  1188. if ((this->init & DECOMPRESS) == 0)
  1189. THROW("tjDecodeYUVPlanes(): Instance has not been initialized for decompression");
  1190. if (!srcPlanes || !srcPlanes[0] || subsamp < 0 || subsamp >= NUMSUBOPT ||
  1191. dstBuf == NULL || width <= 0 || pitch < 0 || height <= 0 ||
  1192. pixelFormat < 0 || pixelFormat >= TJ_NUMPF)
  1193. THROW("tjDecodeYUVPlanes(): Invalid argument");
  1194. if (subsamp != TJSAMP_GRAY && (!srcPlanes[1] || !srcPlanes[2]))
  1195. THROW("tjDecodeYUVPlanes(): Invalid argument");
  1196. if (setjmp(this->jerr.setjmp_buffer)) {
  1197. /* If we get here, the JPEG code has signaled an error. */
  1198. retval = -1; goto bailout;
  1199. }
  1200. if (pixelFormat == TJPF_CMYK)
  1201. THROW("tjDecodeYUVPlanes(): Cannot decode YUV images into CMYK pixels.");
  1202. if (pitch == 0) pitch = width * tjPixelSize[pixelFormat];
  1203. dinfo->image_width = width;
  1204. dinfo->image_height = height;
  1205. #ifndef NO_PUTENV
  1206. if (flags & TJFLAG_FORCEMMX) putenv("JSIMD_FORCEMMX=1");
  1207. else if (flags & TJFLAG_FORCESSE) putenv("JSIMD_FORCESSE=1");
  1208. else if (flags & TJFLAG_FORCESSE2) putenv("JSIMD_FORCESSE2=1");
  1209. #endif
  1210. dinfo->progressive_mode = dinfo->inputctl->has_multiple_scans = FALSE;
  1211. dinfo->Ss = dinfo->Ah = dinfo->Al = 0;
  1212. dinfo->Se = DCTSIZE2 - 1;
  1213. if (setDecodeDefaults(dinfo, pixelFormat, subsamp, flags) == -1) {
  1214. retval = -1; goto bailout;
  1215. }
  1216. old_read_markers = dinfo->marker->read_markers;
  1217. dinfo->marker->read_markers = my_read_markers;
  1218. old_reset_marker_reader = dinfo->marker->reset_marker_reader;
  1219. dinfo->marker->reset_marker_reader = my_reset_marker_reader;
  1220. jpeg_read_header(dinfo, TRUE);
  1221. dinfo->marker->read_markers = old_read_markers;
  1222. dinfo->marker->reset_marker_reader = old_reset_marker_reader;
  1223. this->dinfo.out_color_space = pf2cs[pixelFormat];
  1224. if (flags & TJFLAG_FASTDCT) this->dinfo.dct_method = JDCT_FASTEST;
  1225. dinfo->do_fancy_upsampling = FALSE;
  1226. dinfo->Se = DCTSIZE2 - 1;
  1227. jinit_master_decompress(dinfo);
  1228. (*dinfo->upsample->start_pass) (dinfo);
  1229. pw0 = PAD(width, dinfo->max_h_samp_factor);
  1230. ph0 = PAD(height, dinfo->max_v_samp_factor);
  1231. if (pitch == 0) pitch = dinfo->output_width * tjPixelSize[pixelFormat];
  1232. if ((row_pointer = (JSAMPROW *)malloc(sizeof(JSAMPROW) * ph0)) == NULL)
  1233. THROW("tjDecodeYUVPlanes(): Memory allocation failure");
  1234. for (i = 0; i < height; i++) {
  1235. if (flags & TJFLAG_BOTTOMUP)
  1236. row_pointer[i] = &dstBuf[(height - i - 1) * (size_t)pitch];
  1237. else
  1238. row_pointer[i] = &dstBuf[i * (size_t)pitch];
  1239. }
  1240. if (height < ph0)
  1241. for (i = height; i < ph0; i++) row_pointer[i] = row_pointer[height - 1];
  1242. for (i = 0; i < dinfo->num_components; i++) {
  1243. compptr = &dinfo->comp_info[i];
  1244. _tmpbuf[i] =
  1245. (JSAMPLE *)malloc(PAD(compptr->width_in_blocks * DCTSIZE, 32) *
  1246. compptr->v_samp_factor + 32);
  1247. if (!_tmpbuf[i])
  1248. THROW("tjDecodeYUVPlanes(): Memory allocation failure");
  1249. tmpbuf[i] = (JSAMPROW *)malloc(sizeof(JSAMPROW) * compptr->v_samp_factor);
  1250. if (!tmpbuf[i])
  1251. THROW("tjDecodeYUVPlanes(): Memory allocation failure");
  1252. for (row = 0; row < compptr->v_samp_factor; row++) {
  1253. unsigned char *_tmpbuf_aligned =
  1254. (unsigned char *)PAD((size_t)_tmpbuf[i], 32);
  1255. tmpbuf[i][row] =
  1256. &_tmpbuf_aligned[PAD(compptr->width_in_blocks * DCTSIZE, 32) * row];
  1257. }
  1258. pw[i] = pw0 * compptr->h_samp_factor / dinfo->max_h_samp_factor;
  1259. ph[i] = ph0 * compptr->v_samp_factor / dinfo->max_v_samp_factor;
  1260. inbuf[i] = (JSAMPROW *)malloc(sizeof(JSAMPROW) * ph[i]);
  1261. if (!inbuf[i])
  1262. THROW("tjDecodeYUVPlanes(): Memory allocation failure");
  1263. ptr = (JSAMPLE *)srcPlanes[i];
  1264. for (row = 0; row < ph[i]; row++) {
  1265. inbuf[i][row] = ptr;
  1266. ptr += (strides && strides[i] != 0) ? strides[i] : pw[i];
  1267. }
  1268. }
  1269. if (setjmp(this->jerr.setjmp_buffer)) {
  1270. /* If we get here, the JPEG code has signaled an error. */
  1271. retval = -1; goto bailout;
  1272. }
  1273. for (row = 0; row < ph0; row += dinfo->max_v_samp_factor) {
  1274. JDIMENSION inrow = 0, outrow = 0;
  1275. for (i = 0, compptr = dinfo->comp_info; i < dinfo->num_components;
  1276. i++, compptr++)
  1277. jcopy_sample_rows(inbuf[i],
  1278. row * compptr->v_samp_factor / dinfo->max_v_samp_factor, tmpbuf[i], 0,
  1279. compptr->v_samp_factor, pw[i]);
  1280. (dinfo->upsample->upsample) (dinfo, tmpbuf, &inrow,
  1281. dinfo->max_v_samp_factor, &row_pointer[row],
  1282. &outrow, dinfo->max_v_samp_factor);
  1283. }
  1284. jpeg_abort_decompress(dinfo);
  1285. bailout:
  1286. if (dinfo->global_state > DSTATE_START) jpeg_abort_decompress(dinfo);
  1287. free(row_pointer);
  1288. for (i = 0; i < MAX_COMPONENTS; i++) {
  1289. free(tmpbuf[i]);
  1290. free(_tmpbuf[i]);
  1291. free(inbuf[i]);
  1292. }
  1293. if (this->jerr.warning) retval = -1;
  1294. this->jerr.stopOnWarning = FALSE;
  1295. return retval;
  1296. }
  1297. DLLEXPORT int tjDecodeYUV(tjhandle handle, const unsigned char *srcBuf,
  1298. int pad, int subsamp, unsigned char *dstBuf,
  1299. int width, int pitch, int height, int pixelFormat,
  1300. int flags)
  1301. {
  1302. const unsigned char *srcPlanes[3];
  1303. int pw0, ph0, strides[3], retval = -1;
  1304. tjinstance *this = (tjinstance *)handle;
  1305. if (!this) THROWG("tjDecodeYUV(): Invalid handle");
  1306. this->isInstanceError = FALSE;
  1307. if (srcBuf == NULL || pad < 0 || !IS_POW2(pad) || subsamp < 0 ||
  1308. subsamp >= NUMSUBOPT || width <= 0 || height <= 0)
  1309. THROW("tjDecodeYUV(): Invalid argument");
  1310. pw0 = tjPlaneWidth(0, width, subsamp);
  1311. ph0 = tjPlaneHeight(0, height, subsamp);
  1312. srcPlanes[0] = srcBuf;
  1313. strides[0] = PAD(pw0, pad);
  1314. if (subsamp == TJSAMP_GRAY) {
  1315. strides[1] = strides[2] = 0;
  1316. srcPlanes[1] = srcPlanes[2] = NULL;
  1317. } else {
  1318. int pw1 = tjPlaneWidth(1, width, subsamp);
  1319. int ph1 = tjPlaneHeight(1, height, subsamp);
  1320. strides[1] = strides[2] = PAD(pw1, pad);
  1321. srcPlanes[1] = srcPlanes[0] + strides[0] * ph0;
  1322. srcPlanes[2] = srcPlanes[1] + strides[1] * ph1;
  1323. }
  1324. return tjDecodeYUVPlanes(handle, srcPlanes, strides, subsamp, dstBuf, width,
  1325. pitch, height, pixelFormat, flags);
  1326. bailout:
  1327. return retval;
  1328. }
  1329. DLLEXPORT int tjDecompressToYUVPlanes(tjhandle handle,
  1330. const unsigned char *jpegBuf,
  1331. unsigned long jpegSize,
  1332. unsigned char **dstPlanes, int width,
  1333. int *strides, int height, int flags)
  1334. {
  1335. int i, sfi, row, retval = 0;
  1336. int jpegwidth, jpegheight, jpegSubsamp, scaledw, scaledh;
  1337. int pw[MAX_COMPONENTS], ph[MAX_COMPONENTS], iw[MAX_COMPONENTS],
  1338. tmpbufsize = 0, usetmpbuf = 0, th[MAX_COMPONENTS];
  1339. JSAMPLE *_tmpbuf = NULL, *ptr;
  1340. JSAMPROW *outbuf[MAX_COMPONENTS], *tmpbuf[MAX_COMPONENTS];
  1341. int dctsize;
  1342. GET_DINSTANCE(handle);
  1343. this->jerr.stopOnWarning = (flags & TJFLAG_STOPONWARNING) ? TRUE : FALSE;
  1344. for (i = 0; i < MAX_COMPONENTS; i++) {
  1345. tmpbuf[i] = NULL; outbuf[i] = NULL;
  1346. }
  1347. if ((this->init & DECOMPRESS) == 0)
  1348. THROW("tjDecompressToYUVPlanes(): Instance has not been initialized for decompression");
  1349. if (jpegBuf == NULL || jpegSize <= 0 || !dstPlanes || !dstPlanes[0] ||
  1350. width < 0 || height < 0)
  1351. THROW("tjDecompressToYUVPlanes(): Invalid argument");
  1352. #ifndef NO_PUTENV
  1353. if (flags & TJFLAG_FORCEMMX) putenv("JSIMD_FORCEMMX=1");
  1354. else if (flags & TJFLAG_FORCESSE) putenv("JSIMD_FORCESSE=1");
  1355. else if (flags & TJFLAG_FORCESSE2) putenv("JSIMD_FORCESSE2=1");
  1356. #endif
  1357. if (setjmp(this->jerr.setjmp_buffer)) {
  1358. /* If we get here, the JPEG code has signaled an error. */
  1359. retval = -1; goto bailout;
  1360. }
  1361. if (!this->headerRead) {
  1362. jpeg_mem_src_tj(dinfo, jpegBuf, jpegSize);
  1363. jpeg_read_header(dinfo, TRUE);
  1364. }
  1365. this->headerRead = 0;
  1366. jpegSubsamp = getSubsamp(dinfo);
  1367. if (jpegSubsamp < 0)
  1368. THROW("tjDecompressToYUVPlanes(): Could not determine subsampling type for JPEG image");
  1369. if (jpegSubsamp != TJSAMP_GRAY && (!dstPlanes[1] || !dstPlanes[2]))
  1370. THROW("tjDecompressToYUVPlanes(): Invalid argument");
  1371. jpegwidth = dinfo->image_width; jpegheight = dinfo->image_height;
  1372. if (width == 0) width = jpegwidth;
  1373. if (height == 0) height = jpegheight;
  1374. for (i = 0; i < NUMSF; i++) {
  1375. scaledw = TJSCALED(jpegwidth, sf[i]);
  1376. scaledh = TJSCALED(jpegheight, sf[i]);
  1377. if (scaledw <= width && scaledh <= height)
  1378. break;
  1379. }
  1380. if (i >= NUMSF)
  1381. THROW("tjDecompressToYUVPlanes(): Could not scale down to desired image dimensions");
  1382. if (dinfo->num_components > 3)
  1383. THROW("tjDecompressToYUVPlanes(): JPEG image must have 3 or fewer components");
  1384. width = scaledw; height = scaledh;
  1385. dinfo->scale_num = sf[i].num;
  1386. dinfo->scale_denom = sf[i].denom;
  1387. sfi = i;
  1388. jpeg_calc_output_dimensions(dinfo);
  1389. dctsize = DCTSIZE * sf[sfi].num / sf[sfi].denom;
  1390. for (i = 0; i < dinfo->num_components; i++) {
  1391. jpeg_component_info *compptr = &dinfo->comp_info[i];
  1392. int ih;
  1393. iw[i] = compptr->width_in_blocks * dctsize;
  1394. ih = compptr->height_in_blocks * dctsize;
  1395. pw[i] = tjPlaneWidth(i, dinfo->output_width, jpegSubsamp);
  1396. ph[i] = tjPlaneHeight(i, dinfo->output_height, jpegSubsamp);
  1397. if (iw[i] != pw[i] || ih != ph[i]) usetmpbuf = 1;
  1398. th[i] = compptr->v_samp_factor * dctsize;
  1399. tmpbufsize += iw[i] * th[i];
  1400. if ((outbuf[i] = (JSAMPROW *)malloc(sizeof(JSAMPROW) * ph[i])) == NULL)
  1401. THROW("tjDecompressToYUVPlanes(): Memory allocation failure");
  1402. ptr = dstPlanes[i];
  1403. for (row = 0; row < ph[i]; row++) {
  1404. outbuf[i][row] = ptr;
  1405. ptr += (strides && strides[i] != 0) ? strides[i] : pw[i];
  1406. }
  1407. }
  1408. if (usetmpbuf) {
  1409. if ((_tmpbuf = (JSAMPLE *)malloc(sizeof(JSAMPLE) * tmpbufsize)) == NULL)
  1410. THROW("tjDecompressToYUVPlanes(): Memory allocation failure");
  1411. ptr = _tmpbuf;
  1412. for (i = 0; i < dinfo->num_components; i++) {
  1413. if ((tmpbuf[i] = (JSAMPROW *)malloc(sizeof(JSAMPROW) * th[i])) == NULL)
  1414. THROW("tjDecompressToYUVPlanes(): Memory allocation failure");
  1415. for (row = 0; row < th[i]; row++) {
  1416. tmpbuf[i][row] = ptr;
  1417. ptr += iw[i];
  1418. }
  1419. }
  1420. }
  1421. if (setjmp(this->jerr.setjmp_buffer)) {
  1422. /* If we get here, the JPEG code has signaled an error. */
  1423. retval = -1; goto bailout;
  1424. }
  1425. if (flags & TJFLAG_FASTUPSAMPLE) dinfo->do_fancy_upsampling = FALSE;
  1426. if (flags & TJFLAG_FASTDCT) dinfo->dct_method = JDCT_FASTEST;
  1427. dinfo->raw_data_out = TRUE;
  1428. jpeg_start_decompress(dinfo);
  1429. for (row = 0; row < (int)dinfo->output_height;
  1430. row += dinfo->max_v_samp_factor * dinfo->_min_DCT_scaled_size) {
  1431. JSAMPARRAY yuvptr[MAX_COMPONENTS];
  1432. int crow[MAX_COMPONENTS];
  1433. for (i = 0; i < dinfo->num_components; i++) {
  1434. jpeg_component_info *compptr = &dinfo->comp_info[i];
  1435. if (jpegSubsamp == TJ_420) {
  1436. /* When 4:2:0 subsampling is used with IDCT scaling, libjpeg will try
  1437. to be clever and use the IDCT to perform upsampling on the U and V
  1438. planes. For instance, if the output image is to be scaled by 1/2
  1439. relative to the JPEG image, then the scaling factor and upsampling
  1440. effectively cancel each other, so a normal 8x8 IDCT can be used.
  1441. However, this is not desirable when using the decompress-to-YUV
  1442. functionality in TurboJPEG, since we want to output the U and V
  1443. planes in their subsampled form. Thus, we have to override some
  1444. internal libjpeg parameters to force it to use the "scaled" IDCT
  1445. functions on the U and V planes. */
  1446. compptr->_DCT_scaled_size = dctsize;
  1447. compptr->MCU_sample_width = tjMCUWidth[jpegSubsamp] *
  1448. sf[sfi].num / sf[sfi].denom *
  1449. compptr->v_samp_factor / dinfo->max_v_samp_factor;
  1450. dinfo->idct->inverse_DCT[i] = dinfo->idct->inverse_DCT[0];
  1451. }
  1452. crow[i] = row * compptr->v_samp_factor / dinfo->max_v_samp_factor;
  1453. if (usetmpbuf) yuvptr[i] = tmpbuf[i];
  1454. else yuvptr[i] = &outbuf[i][crow[i]];
  1455. }
  1456. jpeg_read_raw_data(dinfo, yuvptr,
  1457. dinfo->max_v_samp_factor * dinfo->_min_DCT_scaled_size);
  1458. if (usetmpbuf) {
  1459. int j;
  1460. for (i = 0; i < dinfo->num_components; i++) {
  1461. for (j = 0; j < MIN(th[i], ph[i] - crow[i]); j++) {
  1462. memcpy(outbuf[i][crow[i] + j], tmpbuf[i][j], pw[i]);
  1463. }
  1464. }
  1465. }
  1466. }
  1467. jpeg_finish_decompress(dinfo);
  1468. bailout:
  1469. if (dinfo->global_state > DSTATE_START) jpeg_abort_decompress(dinfo);
  1470. for (i = 0; i < MAX_COMPONENTS; i++) {
  1471. free(tmpbuf[i]);
  1472. free(outbuf[i]);
  1473. }
  1474. free(_tmpbuf);
  1475. if (this->jerr.warning) retval = -1;
  1476. this->jerr.stopOnWarning = FALSE;
  1477. return retval;
  1478. }
  1479. DLLEXPORT int tjDecompressToYUV2(tjhandle handle, const unsigned char *jpegBuf,
  1480. unsigned long jpegSize, unsigned char *dstBuf,
  1481. int width, int pad, int height, int flags)
  1482. {
  1483. unsigned char *dstPlanes[3];
  1484. int pw0, ph0, strides[3], retval = -1, jpegSubsamp = -1;
  1485. int i, jpegwidth, jpegheight, scaledw, scaledh;
  1486. GET_DINSTANCE(handle);
  1487. this->jerr.stopOnWarning = (flags & TJFLAG_STOPONWARNING) ? TRUE : FALSE;
  1488. if (jpegBuf == NULL || jpegSize <= 0 || dstBuf == NULL || width < 0 ||
  1489. pad < 1 || !IS_POW2(pad) || height < 0)
  1490. THROW("tjDecompressToYUV2(): Invalid argument");
  1491. if (setjmp(this->jerr.setjmp_buffer)) {
  1492. /* If we get here, the JPEG code has signaled an error. */
  1493. return -1;
  1494. }
  1495. jpeg_mem_src_tj(dinfo, jpegBuf, jpegSize);
  1496. jpeg_read_header(dinfo, TRUE);
  1497. jpegSubsamp = getSubsamp(dinfo);
  1498. if (jpegSubsamp < 0)
  1499. THROW("tjDecompressToYUV2(): Could not determine subsampling type for JPEG image");
  1500. jpegwidth = dinfo->image_width; jpegheight = dinfo->image_height;
  1501. if (width == 0) width = jpegwidth;
  1502. if (height == 0) height = jpegheight;
  1503. for (i = 0; i < NUMSF; i++) {
  1504. scaledw = TJSCALED(jpegwidth, sf[i]);
  1505. scaledh = TJSCALED(jpegheight, sf[i]);
  1506. if (scaledw <= width && scaledh <= height)
  1507. break;
  1508. }
  1509. if (i >= NUMSF)
  1510. THROW("tjDecompressToYUV2(): Could not scale down to desired image dimensions");
  1511. pw0 = tjPlaneWidth(0, width, jpegSubsamp);
  1512. ph0 = tjPlaneHeight(0, height, jpegSubsamp);
  1513. dstPlanes[0] = dstBuf;
  1514. strides[0] = PAD(pw0, pad);
  1515. if (jpegSubsamp == TJSAMP_GRAY) {
  1516. strides[1] = strides[2] = 0;
  1517. dstPlanes[1] = dstPlanes[2] = NULL;
  1518. } else {
  1519. int pw1 = tjPlaneWidth(1, width, jpegSubsamp);
  1520. int ph1 = tjPlaneHeight(1, height, jpegSubsamp);
  1521. strides[1] = strides[2] = PAD(pw1, pad);
  1522. dstPlanes[1] = dstPlanes[0] + strides[0] * ph0;
  1523. dstPlanes[2] = dstPlanes[1] + strides[1] * ph1;
  1524. }
  1525. this->headerRead = 1;
  1526. return tjDecompressToYUVPlanes(handle, jpegBuf, jpegSize, dstPlanes, width,
  1527. strides, height, flags);
  1528. bailout:
  1529. this->jerr.stopOnWarning = FALSE;
  1530. return retval;
  1531. }
  1532. DLLEXPORT int tjDecompressToYUV(tjhandle handle, unsigned char *jpegBuf,
  1533. unsigned long jpegSize, unsigned char *dstBuf,
  1534. int flags)
  1535. {
  1536. return tjDecompressToYUV2(handle, jpegBuf, jpegSize, dstBuf, 0, 4, 0, flags);
  1537. }
  1538. /* Transformer */
  1539. DLLEXPORT tjhandle tjInitTransform(void)
  1540. {
  1541. tjinstance *this = NULL;
  1542. tjhandle handle = NULL;
  1543. if ((this = (tjinstance *)malloc(sizeof(tjinstance))) == NULL) {
  1544. snprintf(errStr, JMSG_LENGTH_MAX,
  1545. "tjInitTransform(): Memory allocation failure");
  1546. return NULL;
  1547. }
  1548. MEMZERO(this, sizeof(tjinstance));
  1549. snprintf(this->errStr, JMSG_LENGTH_MAX, "No error");
  1550. handle = _tjInitCompress(this);
  1551. if (!handle) return NULL;
  1552. handle = _tjInitDecompress(this);
  1553. return handle;
  1554. }
  1555. DLLEXPORT int tjTransform(tjhandle handle, const unsigned char *jpegBuf,
  1556. unsigned long jpegSize, int n,
  1557. unsigned char **dstBufs, unsigned long *dstSizes,
  1558. tjtransform *t, int flags)
  1559. {
  1560. jpeg_transform_info *xinfo = NULL;
  1561. jvirt_barray_ptr *srccoefs, *dstcoefs;
  1562. int retval = 0, i, jpegSubsamp, saveMarkers = 0;
  1563. GET_INSTANCE(handle);
  1564. this->jerr.stopOnWarning = (flags & TJFLAG_STOPONWARNING) ? TRUE : FALSE;
  1565. if ((this->init & COMPRESS) == 0 || (this->init & DECOMPRESS) == 0)
  1566. THROW("tjTransform(): Instance has not been initialized for transformation");
  1567. if (jpegBuf == NULL || jpegSize <= 0 || n < 1 || dstBufs == NULL ||
  1568. dstSizes == NULL || t == NULL || flags < 0)
  1569. THROW("tjTransform(): Invalid argument");
  1570. #ifndef NO_PUTENV
  1571. if (flags & TJFLAG_FORCEMMX) putenv("JSIMD_FORCEMMX=1");
  1572. else if (flags & TJFLAG_FORCESSE) putenv("JSIMD_FORCESSE=1");
  1573. else if (flags & TJFLAG_FORCESSE2) putenv("JSIMD_FORCESSE2=1");
  1574. #endif
  1575. if ((xinfo =
  1576. (jpeg_transform_info *)malloc(sizeof(jpeg_transform_info) * n)) == NULL)
  1577. THROW("tjTransform(): Memory allocation failure");
  1578. MEMZERO(xinfo, sizeof(jpeg_transform_info) * n);
  1579. if (setjmp(this->jerr.setjmp_buffer)) {
  1580. /* If we get here, the JPEG code has signaled an error. */
  1581. retval = -1; goto bailout;
  1582. }
  1583. jpeg_mem_src_tj(dinfo, jpegBuf, jpegSize);
  1584. for (i = 0; i < n; i++) {
  1585. xinfo[i].transform = xformtypes[t[i].op];
  1586. xinfo[i].perfect = (t[i].options & TJXOPT_PERFECT) ? 1 : 0;
  1587. xinfo[i].trim = (t[i].options & TJXOPT_TRIM) ? 1 : 0;
  1588. xinfo[i].force_grayscale = (t[i].options & TJXOPT_GRAY) ? 1 : 0;
  1589. xinfo[i].crop = (t[i].options & TJXOPT_CROP) ? 1 : 0;
  1590. if (n != 1 && t[i].op == TJXOP_HFLIP) xinfo[i].slow_hflip = 1;
  1591. else xinfo[i].slow_hflip = 0;
  1592. if (xinfo[i].crop) {
  1593. xinfo[i].crop_xoffset = t[i].r.x; xinfo[i].crop_xoffset_set = JCROP_POS;
  1594. xinfo[i].crop_yoffset = t[i].r.y; xinfo[i].crop_yoffset_set = JCROP_POS;
  1595. if (t[i].r.w != 0) {
  1596. xinfo[i].crop_width = t[i].r.w; xinfo[i].crop_width_set = JCROP_POS;
  1597. } else
  1598. xinfo[i].crop_width = JCROP_UNSET;
  1599. if (t[i].r.h != 0) {
  1600. xinfo[i].crop_height = t[i].r.h; xinfo[i].crop_height_set = JCROP_POS;
  1601. } else
  1602. xinfo[i].crop_height = JCROP_UNSET;
  1603. }
  1604. if (!(t[i].options & TJXOPT_COPYNONE)) saveMarkers = 1;
  1605. }
  1606. jcopy_markers_setup(dinfo, saveMarkers ? JCOPYOPT_ALL : JCOPYOPT_NONE);
  1607. jpeg_read_header(dinfo, TRUE);
  1608. jpegSubsamp = getSubsamp(dinfo);
  1609. if (jpegSubsamp < 0)
  1610. THROW("tjTransform(): Could not determine subsampling type for JPEG image");
  1611. for (i = 0; i < n; i++) {
  1612. if (!jtransform_request_workspace(dinfo, &xinfo[i]))
  1613. THROW("tjTransform(): Transform is not perfect");
  1614. if (xinfo[i].crop) {
  1615. if ((t[i].r.x % xinfo[i].iMCU_sample_width) != 0 ||
  1616. (t[i].r.y % xinfo[i].iMCU_sample_height) != 0) {
  1617. snprintf(this->errStr, JMSG_LENGTH_MAX,
  1618. "To crop this JPEG image, x must be a multiple of %d\n"
  1619. "and y must be a multiple of %d.\n",
  1620. xinfo[i].iMCU_sample_width, xinfo[i].iMCU_sample_height);
  1621. this->isInstanceError = TRUE;
  1622. retval = -1; goto bailout;
  1623. }
  1624. }
  1625. }
  1626. srccoefs = jpeg_read_coefficients(dinfo);
  1627. for (i = 0; i < n; i++) {
  1628. int w, h, alloc = 1;
  1629. if (!xinfo[i].crop) {
  1630. w = dinfo->image_width; h = dinfo->image_height;
  1631. } else {
  1632. w = xinfo[i].crop_width; h = xinfo[i].crop_height;
  1633. }
  1634. if (flags & TJFLAG_NOREALLOC) {
  1635. alloc = 0; dstSizes[i] = tjBufSize(w, h, jpegSubsamp);
  1636. }
  1637. if (!(t[i].options & TJXOPT_NOOUTPUT))
  1638. jpeg_mem_dest_tj(cinfo, &dstBufs[i], &dstSizes[i], alloc);
  1639. jpeg_copy_critical_parameters(dinfo, cinfo);
  1640. dstcoefs = jtransform_adjust_parameters(dinfo, cinfo, srccoefs, &xinfo[i]);
  1641. if (flags & TJFLAG_PROGRESSIVE || t[i].options & TJXOPT_PROGRESSIVE)
  1642. jpeg_simple_progression(cinfo);
  1643. if (!(t[i].options & TJXOPT_NOOUTPUT)) {
  1644. jpeg_write_coefficients(cinfo, dstcoefs);
  1645. jcopy_markers_execute(dinfo, cinfo, t[i].options & TJXOPT_COPYNONE ?
  1646. JCOPYOPT_NONE : JCOPYOPT_ALL);
  1647. } else
  1648. jinit_c_master_control(cinfo, TRUE);
  1649. jtransform_execute_transformation(dinfo, cinfo, srccoefs, &xinfo[i]);
  1650. if (t[i].customFilter) {
  1651. int ci, y;
  1652. JDIMENSION by;
  1653. for (ci = 0; ci < cinfo->num_components; ci++) {
  1654. jpeg_component_info *compptr = &cinfo->comp_info[ci];
  1655. tjregion arrayRegion = {
  1656. 0, 0, compptr->width_in_blocks * DCTSIZE, DCTSIZE
  1657. };
  1658. tjregion planeRegion = {
  1659. 0, 0, compptr->width_in_blocks * DCTSIZE,
  1660. compptr->height_in_blocks * DCTSIZE
  1661. };
  1662. for (by = 0; by < compptr->height_in_blocks;
  1663. by += compptr->v_samp_factor) {
  1664. JBLOCKARRAY barray = (dinfo->mem->access_virt_barray)
  1665. ((j_common_ptr)dinfo, dstcoefs[ci], by, compptr->v_samp_factor,
  1666. TRUE);
  1667. for (y = 0; y < compptr->v_samp_factor; y++) {
  1668. if (t[i].customFilter(barray[y][0], arrayRegion, planeRegion, ci,
  1669. i, &t[i]) == -1)
  1670. THROW("tjTransform(): Error in custom filter");
  1671. arrayRegion.y += DCTSIZE;
  1672. }
  1673. }
  1674. }
  1675. }
  1676. if (!(t[i].options & TJXOPT_NOOUTPUT)) jpeg_finish_compress(cinfo);
  1677. }
  1678. jpeg_finish_decompress(dinfo);
  1679. bailout:
  1680. if (cinfo->global_state > CSTATE_START) jpeg_abort_compress(cinfo);
  1681. if (dinfo->global_state > DSTATE_START) jpeg_abort_decompress(dinfo);
  1682. free(xinfo);
  1683. if (this->jerr.warning) retval = -1;
  1684. this->jerr.stopOnWarning = FALSE;
  1685. return retval;
  1686. }
  1687. DLLEXPORT unsigned char *tjLoadImage(const char *filename, int *width,
  1688. int align, int *height, int *pixelFormat,
  1689. int flags)
  1690. {
  1691. int retval = 0, tempc;
  1692. size_t pitch;
  1693. tjhandle handle = NULL;
  1694. tjinstance *this;
  1695. j_compress_ptr cinfo = NULL;
  1696. cjpeg_source_ptr src;
  1697. unsigned char *dstBuf = NULL;
  1698. FILE *file = NULL;
  1699. boolean invert;
  1700. if (!filename || !width || align < 1 || !height || !pixelFormat ||
  1701. *pixelFormat < TJPF_UNKNOWN || *pixelFormat >= TJ_NUMPF)
  1702. THROWG("tjLoadImage(): Invalid argument");
  1703. if ((align & (align - 1)) != 0)
  1704. THROWG("tjLoadImage(): Alignment must be a power of 2");
  1705. if ((handle = tjInitCompress()) == NULL) return NULL;
  1706. this = (tjinstance *)handle;
  1707. cinfo = &this->cinfo;
  1708. if ((file = fopen(filename, "rb")) == NULL)
  1709. THROW_UNIX("tjLoadImage(): Cannot open input file");
  1710. if ((tempc = getc(file)) < 0 || ungetc(tempc, file) == EOF)
  1711. THROW_UNIX("tjLoadImage(): Could not read input file")
  1712. else if (tempc == EOF)
  1713. THROWG("tjLoadImage(): Input file contains no data");
  1714. if (setjmp(this->jerr.setjmp_buffer)) {
  1715. /* If we get here, the JPEG code has signaled an error. */
  1716. retval = -1; goto bailout;
  1717. }
  1718. if (*pixelFormat == TJPF_UNKNOWN) cinfo->in_color_space = JCS_UNKNOWN;
  1719. else cinfo->in_color_space = pf2cs[*pixelFormat];
  1720. if (tempc == 'B') {
  1721. if ((src = jinit_read_bmp(cinfo, FALSE)) == NULL)
  1722. THROWG("tjLoadImage(): Could not initialize bitmap loader");
  1723. invert = (flags & TJFLAG_BOTTOMUP) == 0;
  1724. } else if (tempc == 'P') {
  1725. if ((src = jinit_read_ppm(cinfo)) == NULL)
  1726. THROWG("tjLoadImage(): Could not initialize bitmap loader");
  1727. invert = (flags & TJFLAG_BOTTOMUP) != 0;
  1728. } else
  1729. THROWG("tjLoadImage(): Unsupported file type");
  1730. src->input_file = file;
  1731. (*src->start_input) (cinfo, src);
  1732. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr)cinfo);
  1733. *width = cinfo->image_width; *height = cinfo->image_height;
  1734. *pixelFormat = cs2pf[cinfo->in_color_space];
  1735. pitch = PAD((*width) * tjPixelSize[*pixelFormat], align);
  1736. if ((unsigned long long)pitch * (unsigned long long)(*height) >
  1737. (unsigned long long)((size_t)-1) ||
  1738. (dstBuf = (unsigned char *)malloc(pitch * (*height))) == NULL)
  1739. THROWG("tjLoadImage(): Memory allocation failure");
  1740. if (setjmp(this->jerr.setjmp_buffer)) {
  1741. /* If we get here, the JPEG code has signaled an error. */
  1742. retval = -1; goto bailout;
  1743. }
  1744. while (cinfo->next_scanline < cinfo->image_height) {
  1745. int i, nlines = (*src->get_pixel_rows) (cinfo, src);
  1746. for (i = 0; i < nlines; i++) {
  1747. unsigned char *dstptr;
  1748. int row;
  1749. row = cinfo->next_scanline + i;
  1750. if (invert) dstptr = &dstBuf[((*height) - row - 1) * pitch];
  1751. else dstptr = &dstBuf[row * pitch];
  1752. memcpy(dstptr, src->buffer[i], (*width) * tjPixelSize[*pixelFormat]);
  1753. }
  1754. cinfo->next_scanline += nlines;
  1755. }
  1756. (*src->finish_input) (cinfo, src);
  1757. bailout:
  1758. if (handle) tjDestroy(handle);
  1759. if (file) fclose(file);
  1760. if (retval < 0) { free(dstBuf); dstBuf = NULL; }
  1761. return dstBuf;
  1762. }
  1763. DLLEXPORT int tjSaveImage(const char *filename, unsigned char *buffer,
  1764. int width, int pitch, int height, int pixelFormat,
  1765. int flags)
  1766. {
  1767. int retval = 0;
  1768. tjhandle handle = NULL;
  1769. tjinstance *this;
  1770. j_decompress_ptr dinfo = NULL;
  1771. djpeg_dest_ptr dst;
  1772. FILE *file = NULL;
  1773. char *ptr = NULL;
  1774. boolean invert;
  1775. if (!filename || !buffer || width < 1 || pitch < 0 || height < 1 ||
  1776. pixelFormat < 0 || pixelFormat >= TJ_NUMPF)
  1777. THROWG("tjSaveImage(): Invalid argument");
  1778. if ((handle = tjInitDecompress()) == NULL)
  1779. return -1;
  1780. this = (tjinstance *)handle;
  1781. dinfo = &this->dinfo;
  1782. if ((file = fopen(filename, "wb")) == NULL)
  1783. THROW_UNIX("tjSaveImage(): Cannot open output file");
  1784. if (setjmp(this->jerr.setjmp_buffer)) {
  1785. /* If we get here, the JPEG code has signaled an error. */
  1786. retval = -1; goto bailout;
  1787. }
  1788. this->dinfo.out_color_space = pf2cs[pixelFormat];
  1789. dinfo->image_width = width; dinfo->image_height = height;
  1790. dinfo->global_state = DSTATE_READY;
  1791. dinfo->scale_num = dinfo->scale_denom = 1;
  1792. ptr = strrchr(filename, '.');
  1793. if (ptr && !strcasecmp(ptr, ".bmp")) {
  1794. if ((dst = jinit_write_bmp(dinfo, FALSE, FALSE)) == NULL)
  1795. THROWG("tjSaveImage(): Could not initialize bitmap writer");
  1796. invert = (flags & TJFLAG_BOTTOMUP) == 0;
  1797. } else {
  1798. if ((dst = jinit_write_ppm(dinfo)) == NULL)
  1799. THROWG("tjSaveImage(): Could not initialize PPM writer");
  1800. invert = (flags & TJFLAG_BOTTOMUP) != 0;
  1801. }
  1802. dst->output_file = file;
  1803. (*dst->start_output) (dinfo, dst);
  1804. (*dinfo->mem->realize_virt_arrays) ((j_common_ptr)dinfo);
  1805. if (pitch == 0) pitch = width * tjPixelSize[pixelFormat];
  1806. while (dinfo->output_scanline < dinfo->output_height) {
  1807. unsigned char *rowptr;
  1808. if (invert)
  1809. rowptr = &buffer[(height - dinfo->output_scanline - 1) * pitch];
  1810. else
  1811. rowptr = &buffer[dinfo->output_scanline * pitch];
  1812. memcpy(dst->buffer[0], rowptr, width * tjPixelSize[pixelFormat]);
  1813. (*dst->put_pixel_rows) (dinfo, dst, 1);
  1814. dinfo->output_scanline++;
  1815. }
  1816. (*dst->finish_output) (dinfo, dst);
  1817. bailout:
  1818. if (handle) tjDestroy(handle);
  1819. if (file) fclose(file);
  1820. return retval;
  1821. }