tificc.c 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234
  1. //---------------------------------------------------------------------------------
  2. //
  3. // Little Color Management System
  4. // Copyright (c) 1998-2022 Marti Maria Saguer
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining
  7. // a copy of this software and associated documentation files (the "Software"),
  8. // to deal in the Software without restriction, including without limitation
  9. // the rights to use, copy, modify, merge, publish, distribute, sublicense,
  10. // and/or sell copies of the Software, and to permit persons to whom the Software
  11. // is furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  17. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
  18. // THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  19. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  20. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  21. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  22. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  23. //
  24. //---------------------------------------------------------------------------------
  25. // This program does apply profiles to (some) TIFF files
  26. #include "lcms2_plugin.h"
  27. #include "tiffio.h"
  28. #include "utils.h"
  29. // Fix broken libtiff 4.3.0, thanks to Bob Friesenhahn for uncovering this
  30. #if defined(HAVE_STDINT_H) && (TIFFLIB_VERSION >= 20201219)
  31. #include <stdint.h>
  32. # undef cmsUInt16Number
  33. # define cmsUInt16Number uint16_t
  34. # undef cmsUInt32Number
  35. # define cmsUInt32Number uint32_t
  36. #endif /* TIFFLIB_VERSION */
  37. // Flags
  38. static cmsBool BlackWhiteCompensation = FALSE;
  39. static cmsBool IgnoreEmbedded = FALSE;
  40. static cmsBool EmbedProfile = FALSE;
  41. static int PixelDepth = 8;
  42. static cmsBool GamutCheck = FALSE;
  43. static cmsBool lIsDeviceLink = FALSE;
  44. static cmsBool StoreAsAlpha = FALSE;
  45. static int Intent = INTENT_PERCEPTUAL;
  46. static int ProofingIntent = INTENT_PERCEPTUAL;
  47. static int PrecalcMode = 1;
  48. static cmsFloat64Number InkLimit = 400;
  49. static cmsFloat64Number ObserverAdaptationState = 1.0; // According ICC 4.3 this is the default
  50. static const char *cInpProf = NULL;
  51. static const char *cOutProf = NULL;
  52. static const char *cProofing = NULL;
  53. static const char* SaveEmbedded = NULL;
  54. // Console error & warning
  55. static
  56. void ConsoleWarningHandler(const char* module, const char* fmt, va_list ap)
  57. {
  58. if (Verbose) {
  59. fprintf(stderr, "Warning: ");
  60. if (module != NULL)
  61. fprintf(stderr, "[%s] ", module);
  62. vfprintf(stderr, fmt, ap);
  63. fprintf(stderr, "\n");
  64. fflush(stderr);
  65. }
  66. }
  67. static
  68. void ConsoleErrorHandler(const char* module, const char* fmt, va_list ap)
  69. {
  70. if (Verbose) {
  71. fprintf(stderr, "Error: ");
  72. if (module != NULL)
  73. fprintf(stderr, "[%s] ", module);
  74. vfprintf(stderr, fmt, ap);
  75. fprintf(stderr, "\n");
  76. fflush(stderr);
  77. }
  78. }
  79. // Issue a warning
  80. static
  81. void Warning(const char *frm, ...)
  82. {
  83. va_list args;
  84. va_start(args, frm);
  85. ConsoleWarningHandler("tificc", frm, args);
  86. va_end(args);
  87. }
  88. // Out of memory is a fatal error
  89. static
  90. void OutOfMem(cmsUInt32Number size)
  91. {
  92. FatalError("Out of memory on allocating %d bytes.", size);
  93. }
  94. // -----------------------------------------------------------------------------------------------
  95. // Lab plug-in
  96. // In TIFF, Lab is encoded in a different way, so let's use the plug-in
  97. // capabilities of lcms2 to change the meaning of TYPE_Lab_8.
  98. #define LABTIFF_SH(m) ((m) << 30)
  99. #define T_LABTIFF(m) (((m)>>30)&1)
  100. // * 0xffff / 0xff00 = (255 * 257) / (255 * 256) = 257 / 256
  101. static
  102. int FromLabV2ToLabV4(int x)
  103. {
  104. int a;
  105. a = ((x << 8) | x) >> 8; // * 257 / 256
  106. if ( a > 0xffff) return 0xffff;
  107. return a;
  108. }
  109. // * 0xf00 / 0xffff = * 256 / 257
  110. static
  111. int FromLabV4ToLabV2(int x)
  112. {
  113. return ((x << 8) + 0x80) / 257;
  114. }
  115. // Formatter for 8bit Lab TIFF (photometric 8)
  116. static
  117. unsigned char* UnrollTIFFLab8(struct _cmstransform_struct* CMMcargo,
  118. register cmsUInt16Number wIn[],
  119. register cmsUInt8Number* accum,
  120. register cmsUInt32Number Stride)
  121. {
  122. wIn[0] = (cmsUInt16Number) FromLabV2ToLabV4((accum[0]) << 8);
  123. wIn[1] = (cmsUInt16Number) FromLabV2ToLabV4(((accum[1] > 127) ? (accum[1] - 128) : (accum[1] + 128)) << 8);
  124. wIn[2] = (cmsUInt16Number) FromLabV2ToLabV4(((accum[2] > 127) ? (accum[2] - 128) : (accum[2] + 128)) << 8);
  125. return accum + 3;
  126. UTILS_UNUSED_PARAMETER(Stride);
  127. UTILS_UNUSED_PARAMETER(CMMcargo);
  128. }
  129. // Formatter for 16bit Lab TIFF (photometric 8)
  130. static
  131. unsigned char* UnrollTIFFLab16(struct _cmstransform_struct* CMMcargo,
  132. register cmsUInt16Number wIn[],
  133. register cmsUInt8Number* accum,
  134. register cmsUInt32Number Stride )
  135. {
  136. cmsUInt16Number* accum16 = (cmsUInt16Number*) accum;
  137. wIn[0] = (cmsUInt16Number) FromLabV2ToLabV4(accum16[0]);
  138. wIn[1] = (cmsUInt16Number) FromLabV2ToLabV4(((accum16[1] > 0x7f00) ? (accum16[1] - 0x8000) : (accum16[1] + 0x8000)) );
  139. wIn[2] = (cmsUInt16Number) FromLabV2ToLabV4(((accum16[2] > 0x7f00) ? (accum16[2] - 0x8000) : (accum16[2] + 0x8000)) );
  140. return accum + 3 * sizeof(cmsUInt16Number);
  141. UTILS_UNUSED_PARAMETER(Stride);
  142. UTILS_UNUSED_PARAMETER(CMMcargo);
  143. }
  144. static
  145. unsigned char* PackTIFFLab8(struct _cmstransform_struct* CMMcargo,
  146. register cmsUInt16Number wOut[],
  147. register cmsUInt8Number* output,
  148. register cmsUInt32Number Stride)
  149. {
  150. int a, b;
  151. *output++ = (cmsUInt8Number) (FromLabV4ToLabV2(wOut[0] + 0x0080) >> 8);
  152. a = (FromLabV4ToLabV2(wOut[1]) + 0x0080) >> 8;
  153. b = (FromLabV4ToLabV2(wOut[2]) + 0x0080) >> 8;
  154. *output++ = (cmsUInt8Number) ((a < 128) ? (a + 128) : (a - 128));
  155. *output++ = (cmsUInt8Number) ((b < 128) ? (b + 128) : (b - 128));
  156. return output;
  157. UTILS_UNUSED_PARAMETER(Stride);
  158. UTILS_UNUSED_PARAMETER(CMMcargo);
  159. }
  160. static
  161. unsigned char* PackTIFFLab16(struct _cmstransform_struct* CMMcargo,
  162. register cmsUInt16Number wOut[],
  163. register cmsUInt8Number* output,
  164. register cmsUInt32Number Stride)
  165. {
  166. int a, b;
  167. cmsUInt16Number* output16 = (cmsUInt16Number*) output;
  168. *output16++ = (cmsUInt16Number) FromLabV4ToLabV2(wOut[0]);
  169. a = FromLabV4ToLabV2(wOut[1]);
  170. b = FromLabV4ToLabV2(wOut[2]);
  171. *output16++ = (cmsUInt16Number) ((a < 0x7f00) ? (a + 0x8000) : (a - 0x8000));
  172. *output16++ = (cmsUInt16Number) ((b < 0x7f00) ? (b + 0x8000) : (b - 0x8000));
  173. return (cmsUInt8Number*) output16;
  174. UTILS_UNUSED_PARAMETER(Stride);
  175. UTILS_UNUSED_PARAMETER(CMMcargo);
  176. }
  177. static
  178. cmsFormatter TiffFormatterFactory(cmsUInt32Number Type,
  179. cmsFormatterDirection Dir,
  180. cmsUInt32Number dwFlags)
  181. {
  182. cmsFormatter Result = { NULL };
  183. int bps = T_BYTES(Type);
  184. int IsTiffSpecial = T_LABTIFF(Type);
  185. if (IsTiffSpecial && !(dwFlags & CMS_PACK_FLAGS_FLOAT))
  186. {
  187. if (Dir == cmsFormatterInput)
  188. {
  189. Result.Fmt16 = (bps == 1) ? UnrollTIFFLab8 : UnrollTIFFLab16;
  190. }
  191. else
  192. Result.Fmt16 = (bps == 1) ? PackTIFFLab8 : PackTIFFLab16;
  193. }
  194. return Result;
  195. }
  196. static cmsPluginFormatters TiffLabPlugin = { {cmsPluginMagicNumber, 2000, cmsPluginFormattersSig, NULL}, TiffFormatterFactory };
  197. // -----------------------------------------------------------------------------------------------
  198. // Build up the pixeltype descriptor
  199. static
  200. cmsUInt32Number GetInputPixelType(TIFF *Bank)
  201. {
  202. cmsUInt16Number Photometric, bps, spp, extra, PlanarConfig, *info;
  203. cmsUInt16Number Compression;
  204. int ColorChannels;
  205. int IsPremul = FALSE, IsPlanar = FALSE, IsFlt = FALSE, IsReverse = FALSE;
  206. int labTiffSpecial = FALSE;
  207. int pt = PT_ANY;
  208. TIFFGetFieldDefaulted(Bank, TIFFTAG_BITSPERSAMPLE, &bps);
  209. if (bps == 1)
  210. FatalError("Sorry, bilevel TIFFs has nothing to do with ICC profiles");
  211. if (bps != 8 && bps != 16 && bps != 32)
  212. FatalError("Sorry, 8, 16 or 32 bits per sample only");
  213. TIFFGetFieldDefaulted(Bank, TIFFTAG_PLANARCONFIG, &PlanarConfig);
  214. switch (PlanarConfig) {
  215. case PLANARCONFIG_CONTIG: IsPlanar = 0; break;
  216. case PLANARCONFIG_SEPARATE: IsPlanar = 1; break;
  217. default:
  218. FatalError("Unsupported planar configuration (=%d) ", (int) PlanarConfig);
  219. }
  220. TIFFGetFieldDefaulted(Bank, TIFFTAG_SAMPLESPERPIXEL, &spp);
  221. // If Samples per pixel == 1, PlanarConfiguration is irrelevant and need not to be included.
  222. if (spp == 1) IsPlanar = 0;
  223. // Any alpha?
  224. TIFFGetFieldDefaulted(Bank, TIFFTAG_EXTRASAMPLES, &extra, &info);
  225. // Read alpha channels as colorant?
  226. if (StoreAsAlpha) {
  227. ColorChannels = spp;
  228. extra = 0;
  229. }
  230. else
  231. ColorChannels = spp - extra;
  232. // Is alpha premultiplied ?
  233. IsPremul = ((extra == 1) && (info[0] == EXTRASAMPLE_ASSOCALPHA));
  234. // Get photometric interpretation and proceed accordly
  235. TIFFGetField(Bank, TIFFTAG_PHOTOMETRIC, &Photometric);
  236. switch (Photometric) {
  237. case PHOTOMETRIC_MINISWHITE:
  238. IsReverse = 1;
  239. // ... fall through ...
  240. case PHOTOMETRIC_MINISBLACK:
  241. pt = PT_GRAY;
  242. break;
  243. case PHOTOMETRIC_RGB:
  244. pt = PT_RGB;
  245. if (ColorChannels < 3)
  246. FatalError("Sorry, RGB needs at least 3 samples per pixel");
  247. break;
  248. case PHOTOMETRIC_PALETTE:
  249. FatalError("Sorry, palette images not supported");
  250. break;
  251. case PHOTOMETRIC_SEPARATED:
  252. pt = PixelTypeFromChanCount(ColorChannels);
  253. break;
  254. case PHOTOMETRIC_YCBCR:
  255. TIFFGetField(Bank, TIFFTAG_COMPRESSION, &Compression);
  256. {
  257. cmsUInt16Number subx, suby;
  258. pt = PT_YCbCr;
  259. TIFFGetFieldDefaulted(Bank, TIFFTAG_YCBCRSUBSAMPLING, &subx, &suby);
  260. if (subx != 1 || suby != 1)
  261. FatalError("Sorry, subsampled images are not supported");
  262. }
  263. break;
  264. // Two Lab flavours
  265. case PHOTOMETRIC_ICCLAB:
  266. pt = PT_LabV2;
  267. break;
  268. case PHOTOMETRIC_CIELAB:
  269. pt = PT_Lab;
  270. labTiffSpecial = TRUE;
  271. break;
  272. // CIE Log2(L) (u',v')
  273. case PHOTOMETRIC_LOGLUV:
  274. TIFFSetField(Bank, TIFFTAG_SGILOGDATAFMT, SGILOGDATAFMT_16BIT);
  275. pt = PT_YUV; // *ICCSpace = icSigLuvData;
  276. bps = 16; // 16 bits forced by LibTiff
  277. break;
  278. default:
  279. FatalError("Unsupported TIFF color space (Photometric %d)", Photometric);
  280. }
  281. // Convert bits per sample to bytes per sample
  282. bps >>= 3;
  283. IsFlt = (bps == 0) || (bps == 4);
  284. return (FLOAT_SH(IsFlt) | COLORSPACE_SH(pt) | PLANAR_SH(IsPlanar) | EXTRA_SH(extra) | PREMUL_SH(IsPremul) |
  285. CHANNELS_SH(ColorChannels) | BYTES_SH(bps) | FLAVOR_SH(IsReverse) | LABTIFF_SH(labTiffSpecial));
  286. }
  287. // Rearrange pixel type to build output descriptor
  288. static
  289. cmsUInt32Number ComputeOutputFormatDescriptor(cmsUInt32Number dwInput, int OutColorSpace, int bps)
  290. {
  291. int IsPlanar = T_PLANAR(dwInput);
  292. int Channels = ChanCountFromPixelType(OutColorSpace);
  293. int IsFlt = (bps == 0) || (bps == 4);
  294. int labTiffSpecial = FALSE;
  295. int Extra = T_EXTRA(dwInput);
  296. int IsPremul = T_PREMUL(dwInput);
  297. if (OutColorSpace == PT_Lab)
  298. labTiffSpecial = TRUE;
  299. return (FLOAT_SH(IsFlt) | COLORSPACE_SH(OutColorSpace) | PLANAR_SH(IsPlanar) |
  300. CHANNELS_SH(Channels) | BYTES_SH(bps) | EXTRA_SH(Extra) | PREMUL_SH(IsPremul) |
  301. LABTIFF_SH(labTiffSpecial));
  302. }
  303. // Tile based transforms
  304. static
  305. int TileBasedXform(cmsHTRANSFORM hXForm, TIFF* in, TIFF* out, int nPlanes)
  306. {
  307. tsize_t BufSizeIn = TIFFTileSize(in);
  308. tsize_t BufSizeOut = TIFFTileSize(out);
  309. unsigned char *BufferIn, *BufferOut;
  310. ttile_t i, TileCount = TIFFNumberOfTiles(in) / nPlanes;
  311. cmsUInt32Number tw, tl;
  312. int PixelCount, j;
  313. // Check for bad tiffs
  314. if (BufSizeIn > INT_MAX || BufSizeOut > INT_MAX)
  315. FatalError("Probably corrupted TIFF, tile too big.");
  316. TIFFGetFieldDefaulted(in, TIFFTAG_TILEWIDTH, &tw);
  317. TIFFGetFieldDefaulted(in, TIFFTAG_TILELENGTH, &tl);
  318. PixelCount = (int) tw * tl;
  319. BufferIn = (unsigned char *) _TIFFmalloc(BufSizeIn * nPlanes);
  320. if (!BufferIn) OutOfMem((cmsUInt32Number) BufSizeIn * nPlanes);
  321. BufferOut = (unsigned char *) _TIFFmalloc(BufSizeOut * nPlanes);
  322. if (!BufferOut) OutOfMem((cmsUInt32Number) BufSizeOut * nPlanes);
  323. for (i = 0; i < TileCount; i++) {
  324. for (j=0; j < nPlanes; j++) {
  325. if (TIFFReadEncodedTile(in, i + (j* TileCount),
  326. BufferIn + (j*BufSizeIn), BufSizeIn) < 0) goto cleanup;
  327. }
  328. if (PixelCount < 0)
  329. FatalError("TIFF is corrupted");
  330. cmsDoTransform(hXForm, BufferIn, BufferOut, PixelCount);
  331. for (j=0; j < nPlanes; j++) {
  332. if (TIFFWriteEncodedTile(out, i + (j*TileCount),
  333. BufferOut + (j*BufSizeOut), BufSizeOut) < 0) goto cleanup;
  334. }
  335. }
  336. _TIFFfree(BufferIn);
  337. _TIFFfree(BufferOut);
  338. return 1;
  339. cleanup:
  340. _TIFFfree(BufferIn);
  341. _TIFFfree(BufferOut);
  342. return 0;
  343. }
  344. // Strip based transforms
  345. static
  346. int StripBasedXform(cmsHTRANSFORM hXForm, TIFF* in, TIFF* out, int nPlanes)
  347. {
  348. tsize_t BufSizeIn = TIFFStripSize(in);
  349. tsize_t BufSizeOut = TIFFStripSize(out);
  350. unsigned char *BufferIn, *BufferOut;
  351. ttile_t i, StripCount = TIFFNumberOfStrips(in) / nPlanes;
  352. cmsUInt32Number sw;
  353. cmsUInt32Number sl;
  354. cmsUInt32Number iml;
  355. int j;
  356. int PixelCount;
  357. // Check for bad tiffs
  358. if (BufSizeIn > INT_MAX || BufSizeOut > INT_MAX)
  359. FatalError("Probably corrupted TIFF, strip too big.");
  360. TIFFGetFieldDefaulted(in, TIFFTAG_IMAGEWIDTH, &sw);
  361. TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &sl);
  362. TIFFGetFieldDefaulted(in, TIFFTAG_IMAGELENGTH, &iml);
  363. // It is possible to get infinite rows per strip
  364. if (sl == 0 || sl > iml)
  365. sl = iml; // One strip for whole image
  366. BufferIn = (unsigned char *) _TIFFmalloc(BufSizeIn * nPlanes);
  367. if (!BufferIn) OutOfMem((cmsUInt32Number) BufSizeIn * nPlanes);
  368. BufferOut = (unsigned char *) _TIFFmalloc(BufSizeOut * nPlanes);
  369. if (!BufferOut) OutOfMem((cmsUInt32Number) BufSizeOut * nPlanes);
  370. for (i = 0; i < StripCount; i++) {
  371. for (j=0; j < nPlanes; j++) {
  372. if (TIFFReadEncodedStrip(in, i + (j * StripCount),
  373. BufferIn + (j * BufSizeIn), BufSizeIn) < 0) goto cleanup;
  374. }
  375. PixelCount = (int) sw * (iml < sl ? iml : sl);
  376. iml -= sl;
  377. if (PixelCount < 0)
  378. FatalError("TIFF is corrupted");
  379. cmsDoTransform(hXForm, BufferIn, BufferOut, PixelCount);
  380. for (j=0; j < nPlanes; j++) {
  381. if (TIFFWriteEncodedStrip(out, i + (j * StripCount),
  382. BufferOut + j * BufSizeOut, BufSizeOut) < 0) goto cleanup;
  383. }
  384. }
  385. _TIFFfree(BufferIn);
  386. _TIFFfree(BufferOut);
  387. return 1;
  388. cleanup:
  389. _TIFFfree(BufferIn);
  390. _TIFFfree(BufferOut);
  391. return 0;
  392. }
  393. // Fill the array with a short value
  394. static
  395. void fillArray(cmsInt16Number array[], cmsInt16Number val, cmsUInt32Number size)
  396. {
  397. cmsUInt32Number i;
  398. size /= sizeof(cmsInt16Number);
  399. for (i = 0; i < size; i++)
  400. array[i] = val;
  401. }
  402. // Creates minimum required tags
  403. static
  404. void WriteOutputTags(TIFF* out, int Colorspace, int BytesPerSample, int AlphaChannels, int IsPremul)
  405. {
  406. int BitsPerSample = (8 * BytesPerSample);
  407. int nChannels = ChanCountFromPixelType(Colorspace);
  408. TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, BitsPerSample);
  409. TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, nChannels + AlphaChannels);
  410. if (AlphaChannels > 0)
  411. {
  412. cmsInt16Number Extra[20];
  413. if (IsPremul)
  414. fillArray(Extra, EXTRASAMPLE_ASSOCALPHA, sizeof(Extra));
  415. else
  416. fillArray(Extra, EXTRASAMPLE_UNASSALPHA, sizeof(Extra));
  417. TIFFSetField(out, TIFFTAG_EXTRASAMPLES, AlphaChannels, Extra);
  418. }
  419. switch (Colorspace) {
  420. case PT_GRAY:
  421. TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
  422. break;
  423. case PT_RGB:
  424. TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
  425. break;
  426. case PT_CMY:
  427. TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_SEPARATED);
  428. TIFFSetField(out, TIFFTAG_INKSET, INKSET_MULTIINK);
  429. break;
  430. case PT_CMYK:
  431. TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_SEPARATED);
  432. TIFFSetField(out, TIFFTAG_INKSET, INKSET_CMYK);
  433. break;
  434. case PT_Lab:
  435. if (BitsPerSample == 16)
  436. TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_ICCLAB);
  437. else
  438. TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_CIELAB);
  439. break;
  440. // Multi-ink separations
  441. case PT_MCH2:
  442. case PT_MCH3:
  443. case PT_MCH4:
  444. case PT_MCH5:
  445. case PT_MCH6:
  446. case PT_MCH7:
  447. case PT_MCH8:
  448. case PT_MCH9:
  449. case PT_MCH10:
  450. case PT_MCH11:
  451. case PT_MCH12:
  452. case PT_MCH13:
  453. case PT_MCH14:
  454. case PT_MCH15:
  455. TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_SEPARATED);
  456. if (StoreAsAlpha && nChannels >= 4) {
  457. cmsInt16Number Extra[20];
  458. fillArray(Extra, EXTRASAMPLE_UNASSALPHA, sizeof(Extra));
  459. // CMYK plus extra alpha
  460. TIFFSetField(out, TIFFTAG_EXTRASAMPLES, nChannels - 4, Extra);
  461. TIFFSetField(out, TIFFTAG_INKSET, INKSET_CMYK);
  462. TIFFSetField(out, TIFFTAG_NUMBEROFINKS, 4);
  463. }
  464. else {
  465. TIFFSetField(out, TIFFTAG_INKSET, INKSET_MULTIINK);
  466. TIFFSetField(out, TIFFTAG_NUMBEROFINKS, nChannels);
  467. }
  468. break;
  469. default:
  470. FatalError("Unsupported output colorspace");
  471. }
  472. if (PixelDepth == 32)
  473. TIFFSetField(out, TIFFTAG_SAMPLEFORMAT,
  474. SAMPLEFORMAT_IEEEFP,
  475. SAMPLEFORMAT_IEEEFP,
  476. SAMPLEFORMAT_IEEEFP,
  477. SAMPLEFORMAT_IEEEFP);
  478. }
  479. // Copies a bunch of tags
  480. static
  481. void CopyOtherTags(TIFF* in, TIFF* out)
  482. {
  483. #define CopyField(tag, v) \
  484. if (TIFFGetField(in, tag, &v)) TIFFSetField(out, tag, v)
  485. short shortv;
  486. unsigned short compression;
  487. cmsUInt32Number ow, ol;
  488. cmsFloat32Number floatv;
  489. char *stringv;
  490. cmsUInt32Number longv;
  491. CopyField(TIFFTAG_SUBFILETYPE, longv);
  492. TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &ow);
  493. TIFFGetField(in, TIFFTAG_IMAGELENGTH, &ol);
  494. TIFFSetField(out, TIFFTAG_IMAGEWIDTH, ow);
  495. TIFFSetField(out, TIFFTAG_IMAGELENGTH, ol);
  496. CopyField(TIFFTAG_PLANARCONFIG, shortv);
  497. CopyField(TIFFTAG_COMPRESSION, compression);
  498. // This is tricky, libtiff would access predictor in a wrong way
  499. // if the codec is none of those
  500. if (compression == COMPRESSION_LZW ||
  501. compression == 34925 /*COMPRESSION_LZMA*/ ||
  502. compression == COMPRESSION_PIXARLOG ||
  503. compression == COMPRESSION_DEFLATE ||
  504. compression == COMPRESSION_ADOBE_DEFLATE ||
  505. compression == 50000 /*COMPRESSION_ZSTD*/)
  506. {
  507. if (PixelDepth != 32)
  508. CopyField(TIFFTAG_PREDICTOR, shortv);
  509. }
  510. CopyField(TIFFTAG_THRESHHOLDING, shortv);
  511. CopyField(TIFFTAG_FILLORDER, shortv);
  512. CopyField(TIFFTAG_ORIENTATION, shortv);
  513. CopyField(TIFFTAG_MINSAMPLEVALUE, shortv);
  514. CopyField(TIFFTAG_MAXSAMPLEVALUE, shortv);
  515. CopyField(TIFFTAG_XRESOLUTION, floatv);
  516. CopyField(TIFFTAG_YRESOLUTION, floatv);
  517. CopyField(TIFFTAG_RESOLUTIONUNIT, shortv);
  518. CopyField(TIFFTAG_ROWSPERSTRIP, longv);
  519. CopyField(TIFFTAG_XPOSITION, floatv);
  520. CopyField(TIFFTAG_YPOSITION, floatv);
  521. CopyField(TIFFTAG_IMAGEDEPTH, longv);
  522. CopyField(TIFFTAG_TILEDEPTH, longv);
  523. CopyField(TIFFTAG_TILEWIDTH, longv);
  524. CopyField(TIFFTAG_TILELENGTH, longv);
  525. CopyField(TIFFTAG_ARTIST, stringv);
  526. CopyField(TIFFTAG_IMAGEDESCRIPTION, stringv);
  527. CopyField(TIFFTAG_MAKE, stringv);
  528. CopyField(TIFFTAG_MODEL, stringv);
  529. CopyField(TIFFTAG_DATETIME, stringv);
  530. CopyField(TIFFTAG_HOSTCOMPUTER, stringv);
  531. CopyField(TIFFTAG_PAGENAME, stringv);
  532. CopyField(TIFFTAG_DOCUMENTNAME, stringv);
  533. }
  534. static
  535. void DoEmbedProfile(TIFF* Out, const char* ProfileFile)
  536. {
  537. FILE* f;
  538. cmsInt32Number size;
  539. cmsUInt32Number EmbedLen;
  540. cmsUInt8Number* EmbedBuffer;
  541. f = fopen(ProfileFile, "rb");
  542. if (f == NULL) return;
  543. size = cmsfilelength(f);
  544. if (size < 0) return;
  545. EmbedBuffer = (cmsUInt8Number*) malloc((size_t) size + 1);
  546. if (EmbedBuffer == NULL) {
  547. OutOfMem(size+1);
  548. return;
  549. }
  550. EmbedLen = (cmsUInt32Number) fread(EmbedBuffer, 1, (size_t) size, f);
  551. if (EmbedLen != (cmsUInt32Number) size)
  552. FatalError("Cannot read %ld bytes to %s", (long) size, ProfileFile);
  553. fclose(f);
  554. EmbedBuffer[EmbedLen] = 0;
  555. TIFFSetField(Out, TIFFTAG_ICCPROFILE, EmbedLen, EmbedBuffer);
  556. free(EmbedBuffer);
  557. }
  558. // Read or create a ICC profile from the TIFF data
  559. static
  560. cmsHPROFILE GetTIFFProfile(TIFF* in)
  561. {
  562. cmsCIExyYTRIPLE Primaries;
  563. cmsFloat32Number* chr;
  564. cmsCIExyY WhitePoint;
  565. cmsFloat32Number* wp;
  566. int i;
  567. cmsToneCurve* Curve[3];
  568. cmsUInt16Number *gmr, *gmg, *gmb;
  569. cmsHPROFILE hProfile;
  570. cmsUInt32Number EmbedLen;
  571. cmsUInt8Number* EmbedBuffer;
  572. if (IgnoreEmbedded) return NULL;
  573. if (TIFFGetField(in, TIFFTAG_ICCPROFILE, &EmbedLen, &EmbedBuffer)) {
  574. hProfile = cmsOpenProfileFromMem(EmbedBuffer, EmbedLen);
  575. // Print description found in the profile
  576. if (Verbose && (hProfile != NULL)) {
  577. fprintf(stdout, "\n[Embedded profile]\n");
  578. PrintProfileInformation(hProfile);
  579. fflush(stdout);
  580. }
  581. if (hProfile != NULL && SaveEmbedded != NULL)
  582. SaveMemoryBlock(EmbedBuffer, EmbedLen, SaveEmbedded);
  583. if (hProfile) return hProfile;
  584. }
  585. // Try to see if "colorimetric" tiff
  586. if (TIFFGetField(in, TIFFTAG_PRIMARYCHROMATICITIES, &chr)) {
  587. Primaries.Red.x = chr[0];
  588. Primaries.Red.y = chr[1];
  589. Primaries.Green.x = chr[2];
  590. Primaries.Green.y = chr[3];
  591. Primaries.Blue.x = chr[4];
  592. Primaries.Blue.y = chr[5];
  593. Primaries.Red.Y = Primaries.Green.Y = Primaries.Blue.Y = 1.0;
  594. if (TIFFGetField(in, TIFFTAG_WHITEPOINT, &wp)) {
  595. WhitePoint.x = wp[0];
  596. WhitePoint.y = wp[1];
  597. WhitePoint.Y = 1.0;
  598. // Transfer function is a bit harder....
  599. TIFFGetFieldDefaulted(in, TIFFTAG_TRANSFERFUNCTION,
  600. &gmr,
  601. &gmg,
  602. &gmb);
  603. Curve[0] = cmsBuildTabulatedToneCurve16(NULL, 256, gmr);
  604. Curve[1] = cmsBuildTabulatedToneCurve16(NULL, 256, gmg);
  605. Curve[2] = cmsBuildTabulatedToneCurve16(NULL, 256, gmb);
  606. hProfile = cmsCreateRGBProfileTHR(NULL, &WhitePoint, &Primaries, Curve);
  607. for (i=0; i < 3; i++)
  608. cmsFreeToneCurve(Curve[i]);
  609. if (Verbose) {
  610. fprintf(stdout, "\n[Colorimetric TIFF]\n");
  611. }
  612. return hProfile;
  613. }
  614. }
  615. return NULL;
  616. }
  617. // Transform one image
  618. static
  619. int TransformImage(TIFF* in, TIFF* out, const char *cDefInpProf)
  620. {
  621. cmsHPROFILE hIn, hOut, hProof, hInkLimit = NULL;
  622. cmsHTRANSFORM xform;
  623. cmsUInt32Number wInput, wOutput;
  624. int OutputColorSpace;
  625. int BytesPerSample = PixelDepth / 8;
  626. cmsUInt32Number dwFlags;
  627. int nPlanes;
  628. // Default options
  629. dwFlags = cmsFLAGS_COPY_ALPHA;
  630. // Observer adaptation state (only meaningful on absolute colorimetric intent)
  631. cmsSetAdaptationState(ObserverAdaptationState);
  632. if (EmbedProfile && cOutProf)
  633. DoEmbedProfile(out, cOutProf);
  634. if (BlackWhiteCompensation)
  635. dwFlags |= cmsFLAGS_BLACKPOINTCOMPENSATION;
  636. switch (PrecalcMode) {
  637. case 0: dwFlags |= cmsFLAGS_NOOPTIMIZE; break;
  638. case 2: dwFlags |= cmsFLAGS_HIGHRESPRECALC; break;
  639. case 3: dwFlags |= cmsFLAGS_LOWRESPRECALC; break;
  640. case 1: break;
  641. default: FatalError("Unknown precalculation mode '%d'", PrecalcMode);
  642. }
  643. if (GamutCheck)
  644. dwFlags |= cmsFLAGS_GAMUTCHECK;
  645. hProof = NULL;
  646. hOut = NULL;
  647. if (lIsDeviceLink) {
  648. hIn = cmsOpenProfileFromFile(cDefInpProf, "r");
  649. }
  650. else {
  651. hIn = GetTIFFProfile(in);
  652. if (hIn == NULL)
  653. hIn = OpenStockProfile(NULL, cDefInpProf);
  654. hOut = OpenStockProfile(NULL, cOutProf);
  655. if (cProofing != NULL) {
  656. hProof = OpenStockProfile(NULL, cProofing);
  657. dwFlags |= cmsFLAGS_SOFTPROOFING;
  658. }
  659. }
  660. // Take input color space
  661. wInput = GetInputPixelType(in);
  662. // Assure both, input profile and input TIFF are on same colorspace
  663. if (_cmsLCMScolorSpace(cmsGetColorSpace(hIn)) != (int) T_COLORSPACE(wInput))
  664. FatalError("Input profile is not operating in proper color space");
  665. if (!lIsDeviceLink)
  666. OutputColorSpace = _cmsLCMScolorSpace(cmsGetColorSpace(hOut));
  667. else
  668. OutputColorSpace = _cmsLCMScolorSpace(cmsGetPCS(hIn));
  669. wOutput = ComputeOutputFormatDescriptor(wInput, OutputColorSpace, BytesPerSample);
  670. WriteOutputTags(out, OutputColorSpace, BytesPerSample, T_EXTRA(wOutput), T_PREMUL(wOutput));
  671. CopyOtherTags(in, out);
  672. // Ink limit
  673. if (InkLimit != 400.0 &&
  674. (OutputColorSpace == PT_CMYK || OutputColorSpace == PT_CMY)) {
  675. cmsHPROFILE hProfiles[10];
  676. int nProfiles = 0;
  677. hInkLimit = cmsCreateInkLimitingDeviceLink(cmsGetColorSpace(hOut), InkLimit);
  678. hProfiles[nProfiles++] = hIn;
  679. if (hProof) {
  680. hProfiles[nProfiles++] = hProof;
  681. hProfiles[nProfiles++] = hProof;
  682. }
  683. hProfiles[nProfiles++] = hOut;
  684. hProfiles[nProfiles++] = hInkLimit;
  685. xform = cmsCreateMultiprofileTransform(hProfiles, nProfiles,
  686. wInput, wOutput, Intent, dwFlags);
  687. }
  688. else {
  689. xform = cmsCreateProofingTransform(hIn, wInput,
  690. hOut, wOutput,
  691. hProof, Intent,
  692. ProofingIntent,
  693. dwFlags);
  694. }
  695. cmsCloseProfile(hIn);
  696. cmsCloseProfile(hOut);
  697. if (hInkLimit)
  698. cmsCloseProfile(hInkLimit);
  699. if (hProof)
  700. cmsCloseProfile(hProof);
  701. if (xform == NULL) return 0;
  702. // Planar stuff
  703. if (T_PLANAR(wInput))
  704. nPlanes = T_CHANNELS(wInput) + T_EXTRA(wInput);
  705. else
  706. nPlanes = 1;
  707. // Handle tile by tile or strip by strip
  708. if (TIFFIsTiled(in)) {
  709. TileBasedXform(xform, in, out, nPlanes);
  710. }
  711. else {
  712. StripBasedXform(xform, in, out, nPlanes);
  713. }
  714. cmsDeleteTransform(xform);
  715. TIFFWriteDirectory(out);
  716. return 1;
  717. }
  718. // Print help
  719. static
  720. void Help(int level)
  721. {
  722. UTILS_UNUSED_PARAMETER(level);
  723. fprintf(stderr, "usage: tificc [flags] input.tif output.tif\n");
  724. fprintf(stderr, "\nflags:\n\n");
  725. fprintf(stderr, "-v - Verbose\n");
  726. fprintf(stderr, "-i<profile> - Input profile (defaults to sRGB)\n");
  727. fprintf(stderr, "-o<profile> - Output profile (defaults to sRGB)\n");
  728. fprintf(stderr, "-l<profile> - Transform by device-link profile\n");
  729. PrintBuiltins();
  730. PrintRenderingIntents();
  731. fprintf(stderr, "-b - Black point compensation\n");
  732. fprintf(stderr, "-d<0..1> - Observer adaptation state (abs.col. only)\n");
  733. fprintf(stderr, "-c<0,1,2,3> - Precalculates transform (0=Off, 1=Normal, 2=Hi-res, 3=LoRes)\n");
  734. fprintf(stderr, "\n");
  735. fprintf(stderr, "-w<8,16,32> - Output depth. Use 32 for floating-point\n\n");
  736. fprintf(stderr, "-a - Handle channels > 4 as alpha\n");
  737. fprintf(stderr, "-n - Ignore embedded profile on input\n");
  738. fprintf(stderr, "-e - Embed destination profile\n");
  739. fprintf(stderr, "-s<new profile> - Save embedded profile as <new profile>\n");
  740. fprintf(stderr, "\n");
  741. fprintf(stderr, "-p<profile> - Soft proof profile\n");
  742. fprintf(stderr, "-m<n> - Soft proof intent\n");
  743. fprintf(stderr, "-g - Marks out-of-gamut colors on softproof\n");
  744. fprintf(stderr, "\n");
  745. fprintf(stderr, "-k<0..400> - Ink-limiting in %% (CMYK only)\n");
  746. fprintf(stderr, "\n");
  747. fprintf(stderr, "Examples:\n\n"
  748. "To color correct from scanner to sRGB:\n"
  749. "\ttificc -iscanner.icm in.tif out.tif\n"
  750. "To convert from monitor1 to monitor2:\n"
  751. "\ttificc -imon1.icm -omon2.icm in.tif out.tif\n"
  752. "To make a CMYK separation:\n"
  753. "\ttificc -oprinter.icm inrgb.tif outcmyk.tif\n"
  754. "To recover sRGB from a CMYK separation:\n"
  755. "\ttificc -iprinter.icm incmyk.tif outrgb.tif\n"
  756. "To convert from CIELab TIFF to sRGB\n"
  757. "\ttificc -i*Lab in.tif out.tif\n\n");
  758. fprintf(stderr, "This program is intended to be a demo of the Little CMS\n"
  759. "color engine. Both lcms and this program are open source.\n"
  760. "You can obtain both in source code at https://www.littlecms.com\n"
  761. "For suggestions, comments, bug reports etc. send mail to\n"
  762. "[email protected]\n\n");
  763. exit(0);
  764. }
  765. // The toggles stuff
  766. static
  767. void HandleSwitches(int argc, char *argv[])
  768. {
  769. int s;
  770. while ((s=xgetopt(argc,argv,"aAeEbBw:W:nNvVGgh:H:i:I:o:O:P:p:t:T:c:C:l:L:M:m:K:k:S:s:D:d:-:")) != EOF) {
  771. switch (s) {
  772. case '-':
  773. if (strcmp(xoptarg, "help") == 0)
  774. {
  775. Help(0);
  776. }
  777. else
  778. {
  779. FatalError("Unknown option - run without args to see valid ones.\n");
  780. }
  781. break;
  782. case 'a':
  783. case 'A':
  784. StoreAsAlpha = TRUE;
  785. break;
  786. case 'b':
  787. case 'B':
  788. BlackWhiteCompensation = TRUE;
  789. break;
  790. case 'c':
  791. case 'C':
  792. PrecalcMode = atoi(xoptarg);
  793. if (PrecalcMode < 0 || PrecalcMode > 3)
  794. FatalError("Unknown precalc mode '%d'", PrecalcMode);
  795. break;
  796. case 'd':
  797. case 'D': ObserverAdaptationState = atof(xoptarg);
  798. if (ObserverAdaptationState < 0 ||
  799. ObserverAdaptationState > 1.0)
  800. Warning("Adaptation state should be 0..1");
  801. break;
  802. case 'e':
  803. case 'E':
  804. EmbedProfile = TRUE;
  805. break;
  806. case 'g':
  807. case 'G':
  808. GamutCheck = TRUE;
  809. break;
  810. case 'v':
  811. case 'V':
  812. Verbose = TRUE;
  813. break;
  814. case 'i':
  815. case 'I':
  816. if (lIsDeviceLink)
  817. FatalError("Device-link already specified");
  818. cInpProf = xoptarg;
  819. break;
  820. case 'o':
  821. case 'O':
  822. if (lIsDeviceLink)
  823. FatalError("Device-link already specified");
  824. cOutProf = xoptarg;
  825. break;
  826. case 'l':
  827. case 'L':
  828. if (cInpProf != NULL || cOutProf != NULL)
  829. FatalError("input/output profiles already specified");
  830. cInpProf = xoptarg;
  831. lIsDeviceLink = TRUE;
  832. break;
  833. case 'p':
  834. case 'P':
  835. cProofing = xoptarg;
  836. break;
  837. case 't':
  838. case 'T':
  839. Intent = atoi(xoptarg);
  840. break;
  841. case 'm':
  842. case 'M':
  843. ProofingIntent = atoi(xoptarg);
  844. break;
  845. case 'N':
  846. case 'n':
  847. IgnoreEmbedded = TRUE;
  848. break;
  849. case 'W':
  850. case 'w':
  851. PixelDepth = atoi(xoptarg);
  852. if (PixelDepth != 8 && PixelDepth != 16 && PixelDepth != 32)
  853. FatalError("Only 8, 16 and 32 bps are supported");
  854. break;
  855. case 'k':
  856. case 'K':
  857. InkLimit = atof(xoptarg);
  858. if (InkLimit < 0.0 || InkLimit > 400.0)
  859. FatalError("Ink limit must be 0%%..400%%");
  860. break;
  861. case 's':
  862. case 'S': SaveEmbedded = xoptarg;
  863. break;
  864. case 'H':
  865. case 'h': {
  866. int a = atoi(xoptarg);
  867. Help(a);
  868. }
  869. break;
  870. default:
  871. FatalError("Unknown option - run without args to see valid ones");
  872. }
  873. }
  874. }
  875. // The main sink
  876. int main(int argc, char* argv[])
  877. {
  878. TIFF *in, *out;
  879. fprintf(stderr, "Little CMS ICC profile applier for TIFF - v7.1 [LittleCMS %2.2f]\n\n", cmsGetEncodedCMMversion() / 1000.0);
  880. fprintf(stderr, "Copyright (c) 1998-2022 Marti Maria Saguer. See COPYING file for details.\n");
  881. fflush(stderr);
  882. cmsPlugin(&TiffLabPlugin);
  883. InitUtils("tificc");
  884. HandleSwitches(argc, argv);
  885. if ((argc - xoptind) != 2) {
  886. Help(0);
  887. }
  888. TIFFSetErrorHandler(ConsoleErrorHandler);
  889. TIFFSetWarningHandler(ConsoleWarningHandler);
  890. in = TIFFOpen(argv[xoptind], "r");
  891. if (in == NULL) FatalError("Unable to open '%s'", argv[xoptind]);
  892. out = TIFFOpen(argv[xoptind+1], "w");
  893. if (out == NULL) {
  894. TIFFClose(in);
  895. FatalError("Unable to write '%s'", argv[xoptind+1]);
  896. }
  897. do {
  898. TransformImage(in, out, cInpProf);
  899. } while (TIFFReadDirectory(in));
  900. if (Verbose) { fprintf(stdout, "\n"); fflush(stdout); }
  901. TIFFClose(in);
  902. TIFFClose(out);
  903. return 0;
  904. }