turbojpeg.c 71 KB

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