turbojpeg.c 75 KB

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