tiny_jpeg.h 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279
  1. /**
  2. * tiny_jpeg.h
  3. *
  4. * Tiny JPEG Encoder
  5. * - Sergio Gonzalez
  6. *
  7. * This is a readable and simple single-header JPEG encoder.
  8. *
  9. * Features
  10. * - Implements Baseline DCT JPEG compression.
  11. * - No dynamic allocations.
  12. *
  13. * This library is coded in the spirit of the stb libraries and mostly follows
  14. * the stb guidelines.
  15. *
  16. * It is written in C99. And depends on the C standard library.
  17. * Works with C++11
  18. *
  19. *
  20. * ==== Thanks ====
  21. *
  22. * AssociationSirius (Bug reports)
  23. * Bernard van Gastel (Thread-safe defaults, BSD compilation)
  24. *
  25. *
  26. * ==== License ====
  27. *
  28. * This software is in the public domain. Where that dedication is not
  29. * recognized, you are granted a perpetual, irrevocable license to copy and
  30. * modify this file as you see fit.
  31. *
  32. */
  33. // ============================================================
  34. // Usage
  35. // ============================================================
  36. // Include "tiny_jpeg.h" to and use the public interface defined below.
  37. //
  38. // You *must* do:
  39. //
  40. // #define TJE_IMPLEMENTATION
  41. // #include "tiny_jpeg.h"
  42. //
  43. // in exactly one of your C files to actually compile the implementation.
  44. // Here is an example program that loads a bmp with stb_image and writes it
  45. // with Tiny JPEG
  46. /*
  47. #define STB_IMAGE_IMPLEMENTATION
  48. #include "stb_image.h"
  49. #define TJE_IMPLEMENTATION
  50. #include "tiny_jpeg.h"
  51. int main()
  52. {
  53. int width, height, num_components;
  54. unsigned char* data = stbi_load("in.bmp", &width, &height, &num_components, 0);
  55. if ( !data ) {
  56. puts("Could not find file");
  57. return EXIT_FAILURE;
  58. }
  59. if ( !tje_encode_to_file("out.jpg", width, height, num_components, data) ) {
  60. fprintf(stderr, "Could not write JPEG\n");
  61. return EXIT_FAILURE;
  62. }
  63. return EXIT_SUCCESS;
  64. }
  65. */
  66. #ifdef __cplusplus
  67. extern "C"
  68. {
  69. #endif
  70. #if defined(__GNUC__) || defined(__clang__)
  71. #pragma GCC diagnostic push
  72. #pragma GCC diagnostic ignored "-Wmissing-field-initializers" // We use {0}, which will zero-out the struct.
  73. #pragma GCC diagnostic ignored "-Wmissing-braces"
  74. #pragma GCC diagnostic ignored "-Wpadded"
  75. #endif
  76. // ============================================================
  77. // Public interface:
  78. // ============================================================
  79. #ifndef TJE_HEADER_GUARD
  80. #define TJE_HEADER_GUARD
  81. // - tje_encode_to_file -
  82. //
  83. // Usage:
  84. // Takes bitmap data and writes a JPEG-encoded image to disk.
  85. //
  86. // PARAMETERS
  87. // dest_path: filename to which we will write. e.g. "out.jpg"
  88. // width, height: image size in pixels
  89. // num_components: 3 is RGB. 4 is RGBA. Those are the only supported values
  90. // src_data: pointer to the pixel data.
  91. //
  92. // RETURN:
  93. // 0 on error. 1 on success.
  94. int tje_encode_to_file(const char* dest_path,
  95. const int width,
  96. const int height,
  97. const int num_components,
  98. const unsigned char* src_data);
  99. // - tje_encode_to_file_at_quality -
  100. //
  101. // Usage:
  102. // Takes bitmap data and writes a JPEG-encoded image to disk.
  103. //
  104. // PARAMETERS
  105. // dest_path: filename to which we will write. e.g. "out.jpg"
  106. // quality: 3: Highest. Compression varies wildly (between 1/3 and 1/20).
  107. // 2: Very good quality. About 1/2 the size of 3.
  108. // 1: Noticeable. About 1/6 the size of 3, or 1/3 the size of 2.
  109. // width, height: image size in pixels
  110. // num_components: 3 is RGB. 4 is RGBA. Those are the only supported values
  111. // src_data: pointer to the pixel data.
  112. //
  113. // RETURN:
  114. // 0 on error. 1 on success.
  115. int tje_encode_to_file_at_quality(const char* dest_path,
  116. const int quality,
  117. const int width,
  118. const int height,
  119. const int num_components,
  120. const unsigned char* src_data);
  121. // - tje_encode_with_func -
  122. //
  123. // Usage
  124. // Same as tje_encode_to_file_at_quality, but it takes a callback that knows
  125. // how to handle (or ignore) `context`. The callback receives an array `data`
  126. // of `size` bytes, which can be written directly to a file. There is no need
  127. // to free the data.
  128. typedef void tje_write_func(void* context, void* data, int size);
  129. int tje_encode_with_func(tje_write_func* func,
  130. void* context,
  131. const int quality,
  132. const int width,
  133. const int height,
  134. const int num_components,
  135. const unsigned char* src_data);
  136. #endif // TJE_HEADER_GUARD
  137. // Implementation: In exactly one of the source files of your application,
  138. // define TJE_IMPLEMENTATION and include tiny_jpeg.h
  139. // ============================================================
  140. // Internal
  141. // ============================================================
  142. #ifdef TJE_IMPLEMENTATION
  143. #define tjei_min(a, b) ((a) < b) ? (a) : (b);
  144. #define tjei_max(a, b) ((a) < b) ? (b) : (a);
  145. #if defined(_MSC_VER)
  146. #define TJEI_FORCE_INLINE __forceinline
  147. // #define TJEI_FORCE_INLINE __declspec(noinline) // For profiling
  148. #else
  149. #define TJEI_FORCE_INLINE static // TODO: equivalent for gcc & clang
  150. #endif
  151. // Only use zero for debugging and/or inspection.
  152. #define TJE_USE_FAST_DCT 1
  153. // C std lib
  154. #include <assert.h>
  155. #include <inttypes.h>
  156. #include <math.h> // floorf, ceilf
  157. #include <stdio.h> // FILE, puts
  158. #include <string.h> // memcpy
  159. #define TJEI_BUFFER_SIZE 1024
  160. #ifdef _WIN32
  161. #include <windows.h>
  162. #ifndef snprintf
  163. #define snprintf sprintf_s
  164. #endif
  165. // Not quite the same but it works for us. If I am not mistaken, it differs
  166. // only in the return value.
  167. #endif
  168. #ifndef NDEBUG
  169. #ifdef _WIN32
  170. #define tje_log(msg) OutputDebugStringA(msg)
  171. #elif defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
  172. #define tje_log(msg) puts(msg)
  173. #else
  174. #warning "need a tje_log definition for your platform for debugging purposes (not needed if compiling with NDEBUG)"
  175. #endif
  176. #else // NDEBUG
  177. #define tje_log(msg)
  178. #endif // NDEBUG
  179. typedef struct
  180. {
  181. void* context;
  182. tje_write_func* func;
  183. } TJEWriteContext;
  184. typedef struct
  185. {
  186. // Huffman data.
  187. uint8_t ehuffsize[4][257];
  188. uint16_t ehuffcode[4][256];
  189. uint8_t const * ht_bits[4];
  190. uint8_t const * ht_vals[4];
  191. // Cuantization tables.
  192. uint8_t qt_luma[64];
  193. uint8_t qt_chroma[64];
  194. // fwrite by default. User-defined when using tje_encode_with_func.
  195. TJEWriteContext write_context;
  196. // Buffered output. Big performance win when using the usual stdlib implementations.
  197. size_t output_buffer_count;
  198. uint8_t output_buffer[TJEI_BUFFER_SIZE];
  199. } TJEState;
  200. // ============================================================
  201. // Table definitions.
  202. //
  203. // The spec defines tjei_default reasonably good quantization matrices and huffman
  204. // specification tables.
  205. //
  206. //
  207. // Instead of hard-coding the final huffman table, we only hard-code the table
  208. // spec suggested by the specification, and then derive the full table from
  209. // there. This is only for didactic purposes but it might be useful if there
  210. // ever is the case that we need to swap huffman tables from various sources.
  211. // ============================================================
  212. // K.1 - suggested luminance QT
  213. static const uint8_t tjei_default_qt_luma_from_spec[] =
  214. {
  215. 16,11,10,16, 24, 40, 51, 61,
  216. 12,12,14,19, 26, 58, 60, 55,
  217. 14,13,16,24, 40, 57, 69, 56,
  218. 14,17,22,29, 51, 87, 80, 62,
  219. 18,22,37,56, 68,109,103, 77,
  220. 24,35,55,64, 81,104,113, 92,
  221. 49,64,78,87,103,121,120,101,
  222. 72,92,95,98,112,100,103, 99,
  223. };
  224. // Unused
  225. #if 0
  226. static const uint8_t tjei_default_qt_chroma_from_spec[] =
  227. {
  228. // K.1 - suggested chrominance QT
  229. 17,18,24,47,99,99,99,99,
  230. 18,21,26,66,99,99,99,99,
  231. 24,26,56,99,99,99,99,99,
  232. 47,66,99,99,99,99,99,99,
  233. 99,99,99,99,99,99,99,99,
  234. 99,99,99,99,99,99,99,99,
  235. 99,99,99,99,99,99,99,99,
  236. 99,99,99,99,99,99,99,99,
  237. };
  238. #endif
  239. static const uint8_t tjei_default_qt_chroma_from_paper[] =
  240. {
  241. // Example QT from JPEG paper
  242. 16, 12, 14, 14, 18, 24, 49, 72,
  243. 11, 10, 16, 24, 40, 51, 61, 12,
  244. 13, 17, 22, 35, 64, 92, 14, 16,
  245. 22, 37, 55, 78, 95, 19, 24, 29,
  246. 56, 64, 87, 98, 26, 40, 51, 68,
  247. 81, 103, 112, 58, 57, 87, 109, 104,
  248. 121,100, 60, 69, 80, 103, 113, 120,
  249. 103, 55, 56, 62, 77, 92, 101, 99,
  250. };
  251. // == Procedure to 'deflate' the huffman tree: JPEG spec, C.2
  252. // Number of 16 bit values for every code length. (K.3.3.1)
  253. static const uint8_t tjei_default_ht_luma_dc_len[16] =
  254. {
  255. 0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0
  256. };
  257. // values
  258. static const uint8_t tjei_default_ht_luma_dc[12] =
  259. {
  260. 0,1,2,3,4,5,6,7,8,9,10,11
  261. };
  262. // Number of 16 bit values for every code length. (K.3.3.1)
  263. static const uint8_t tjei_default_ht_chroma_dc_len[16] =
  264. {
  265. 0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0
  266. };
  267. // values
  268. static const uint8_t tjei_default_ht_chroma_dc[12] =
  269. {
  270. 0,1,2,3,4,5,6,7,8,9,10,11
  271. };
  272. // Same as above, but AC coefficients.
  273. static const uint8_t tjei_default_ht_luma_ac_len[16] =
  274. {
  275. 0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,0x7d
  276. };
  277. static const uint8_t tjei_default_ht_luma_ac[] =
  278. {
  279. 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
  280. 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xA1, 0x08, 0x23, 0x42, 0xB1, 0xC1, 0x15, 0x52, 0xD1, 0xF0,
  281. 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0A, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x25, 0x26, 0x27, 0x28,
  282. 0x29, 0x2A, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
  283. 0x4A, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
  284. 0x6A, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
  285. 0x8A, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7,
  286. 0xA8, 0xA9, 0xAA, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xC2, 0xC3, 0xC4, 0xC5,
  287. 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xE1, 0xE2,
  288. 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8,
  289. 0xF9, 0xFA
  290. };
  291. static const uint8_t tjei_default_ht_chroma_ac_len[16] =
  292. {
  293. 0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,0x77
  294. };
  295. static const uint8_t tjei_default_ht_chroma_ac[] =
  296. {
  297. 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
  298. 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, 0xA1, 0xB1, 0xC1, 0x09, 0x23, 0x33, 0x52, 0xF0,
  299. 0x15, 0x62, 0x72, 0xD1, 0x0A, 0x16, 0x24, 0x34, 0xE1, 0x25, 0xF1, 0x17, 0x18, 0x19, 0x1A, 0x26,
  300. 0x27, 0x28, 0x29, 0x2A, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
  301. 0x49, 0x4A, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
  302. 0x69, 0x6A, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
  303. 0x88, 0x89, 0x8A, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0xA2, 0xA3, 0xA4, 0xA5,
  304. 0xA6, 0xA7, 0xA8, 0xA9, 0xAA, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xC2, 0xC3,
  305. 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA,
  306. 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8,
  307. 0xF9, 0xFA
  308. };
  309. // ============================================================
  310. // Code
  311. // ============================================================
  312. // Zig-zag order:
  313. static const uint8_t tjei_zig_zag[64] =
  314. {
  315. 0, 1, 5, 6, 14, 15, 27, 28,
  316. 2, 4, 7, 13, 16, 26, 29, 42,
  317. 3, 8, 12, 17, 25, 30, 41, 43,
  318. 9, 11, 18, 24, 31, 40, 44, 53,
  319. 10, 19, 23, 32, 39, 45, 52, 54,
  320. 20, 22, 33, 38, 46, 51, 55, 60,
  321. 21, 34, 37, 47, 50, 56, 59, 61,
  322. 35, 36, 48, 49, 57, 58, 62, 63,
  323. };
  324. // Memory order as big endian. 0xhilo -> 0xlohi which looks as 0xhilo in memory.
  325. static uint16_t tjei_be_word(const uint16_t le_word)
  326. {
  327. uint16_t lo = (le_word & 0x00ff);
  328. uint16_t hi = ((le_word & 0xff00) >> 8);
  329. return (uint16_t)((lo << 8) | hi);
  330. }
  331. // ============================================================
  332. // The following structs exist only for code clarity, debugability, and
  333. // readability. They are used when writing to disk, but it is useful to have
  334. // 1-packed-structs to document how the format works, and to inspect memory
  335. // while developing.
  336. // ============================================================
  337. static const uint8_t tjeik_jfif_id[] = "JFIF";
  338. static const uint8_t tjeik_com_str[] = "Created by Tiny JPEG Encoder";
  339. // TODO: Get rid of packed structs!
  340. #pragma pack(push)
  341. #pragma pack(1)
  342. typedef struct
  343. {
  344. uint16_t SOI;
  345. // JFIF header.
  346. uint16_t APP0;
  347. uint16_t jfif_len;
  348. uint8_t jfif_id[5];
  349. uint16_t version;
  350. uint8_t units;
  351. uint16_t x_density;
  352. uint16_t y_density;
  353. uint8_t x_thumb;
  354. uint8_t y_thumb;
  355. } TJEJPEGHeader;
  356. typedef struct
  357. {
  358. uint16_t com;
  359. uint16_t com_len;
  360. char com_str[sizeof(tjeik_com_str) - 1];
  361. } TJEJPEGComment;
  362. // Helper struct for TJEFrameHeader (below).
  363. typedef struct
  364. {
  365. uint8_t component_id;
  366. uint8_t sampling_factors; // most significant 4 bits: horizontal. 4 LSB: vertical (A.1.1)
  367. uint8_t qt; // Quantization table selector.
  368. } TJEComponentSpec;
  369. typedef struct
  370. {
  371. uint16_t SOF;
  372. uint16_t len; // 8 + 3 * frame.num_components
  373. uint8_t precision; // Sample precision (bits per sample).
  374. uint16_t height;
  375. uint16_t width;
  376. uint8_t num_components; // For this implementation, will be equal to 3.
  377. TJEComponentSpec component_spec[3];
  378. } TJEFrameHeader;
  379. typedef struct
  380. {
  381. uint8_t component_id; // Just as with TJEComponentSpec
  382. uint8_t dc_ac; // (dc|ac)
  383. } TJEFrameComponentSpec;
  384. typedef struct
  385. {
  386. uint16_t SOS;
  387. uint16_t len;
  388. uint8_t num_components; // 3.
  389. TJEFrameComponentSpec component_spec[3];
  390. uint8_t first; // 0
  391. uint8_t last; // 63
  392. uint8_t ah_al; // o
  393. } TJEScanHeader;
  394. #pragma pack(pop)
  395. static void tjei_write(TJEState* state, const void* data, size_t num_bytes, size_t num_elements)
  396. {
  397. size_t to_write = num_bytes * num_elements;
  398. // Cap to the buffer available size and copy memory.
  399. size_t capped_count = tjei_min(to_write, TJEI_BUFFER_SIZE - 1 - state->output_buffer_count);
  400. memcpy(state->output_buffer + state->output_buffer_count, data, capped_count);
  401. state->output_buffer_count += capped_count;
  402. assert (state->output_buffer_count <= TJEI_BUFFER_SIZE - 1);
  403. // Flush the buffer.
  404. if ( state->output_buffer_count == TJEI_BUFFER_SIZE - 1 ) {
  405. state->write_context.func(state->write_context.context, state->output_buffer, (int)state->output_buffer_count);
  406. state->output_buffer_count = 0;
  407. }
  408. // Recursively calling ourselves with the rest of the buffer.
  409. if (capped_count < to_write) {
  410. tjei_write(state, (uint8_t*)data+capped_count, to_write - capped_count, 1);
  411. }
  412. }
  413. static void tjei_write_DQT(TJEState* state, const uint8_t* matrix, uint8_t id)
  414. {
  415. uint16_t DQT = tjei_be_word(0xffdb);
  416. tjei_write(state, &DQT, sizeof(uint16_t), 1);
  417. uint16_t len = tjei_be_word(0x0043); // 2(len) + 1(id) + 64(matrix) = 67 = 0x43
  418. tjei_write(state, &len, sizeof(uint16_t), 1);
  419. assert(id < 4);
  420. uint8_t precision_and_id = id; // 0x0000 8 bits | 0x00id
  421. tjei_write(state, &precision_and_id, sizeof(uint8_t), 1);
  422. // Write matrix
  423. tjei_write(state, matrix, 64*sizeof(uint8_t), 1);
  424. }
  425. typedef enum
  426. {
  427. TJEI_DC = 0,
  428. TJEI_AC = 1
  429. } TJEHuffmanTableClass;
  430. static void tjei_write_DHT(TJEState* state,
  431. uint8_t const * matrix_len,
  432. uint8_t const * matrix_val,
  433. TJEHuffmanTableClass ht_class,
  434. uint8_t id)
  435. {
  436. int num_values = 0;
  437. for ( int i = 0; i < 16; ++i ) {
  438. num_values += matrix_len[i];
  439. }
  440. assert(num_values <= 0xffff);
  441. uint16_t DHT = tjei_be_word(0xffc4);
  442. // 2(len) + 1(Tc|th) + 16 (num lengths) + ?? (num values)
  443. uint16_t len = tjei_be_word(2 + 1 + 16 + (uint16_t)num_values);
  444. assert(id < 4);
  445. uint8_t tc_th = (uint8_t)((((uint8_t)ht_class) << 4) | id);
  446. tjei_write(state, &DHT, sizeof(uint16_t), 1);
  447. tjei_write(state, &len, sizeof(uint16_t), 1);
  448. tjei_write(state, &tc_th, sizeof(uint8_t), 1);
  449. tjei_write(state, matrix_len, sizeof(uint8_t), 16);
  450. tjei_write(state, matrix_val, sizeof(uint8_t), (size_t)num_values);
  451. }
  452. // ============================================================
  453. // Huffman deflation code.
  454. // ============================================================
  455. // Returns all code sizes from the BITS specification (JPEG C.3)
  456. static uint8_t* tjei_huff_get_code_lengths(uint8_t huffsize[/*256*/], uint8_t const * bits)
  457. {
  458. int k = 0;
  459. for ( int i = 0; i < 16; ++i ) {
  460. for ( int j = 0; j < bits[i]; ++j ) {
  461. huffsize[k++] = (uint8_t)(i + 1);
  462. }
  463. huffsize[k] = 0;
  464. }
  465. return huffsize;
  466. }
  467. // Fills out the prefixes for each code.
  468. static uint16_t* tjei_huff_get_codes(uint16_t codes[], uint8_t* huffsize, int64_t count)
  469. {
  470. uint16_t code = 0;
  471. int k = 0;
  472. uint8_t sz = huffsize[0];
  473. for(;;) {
  474. do {
  475. assert(k < count);
  476. codes[k++] = code++;
  477. } while (huffsize[k] == sz);
  478. if (huffsize[k] == 0) {
  479. return codes;
  480. }
  481. do {
  482. code = (uint16_t)(code << 1);
  483. ++sz;
  484. } while( huffsize[k] != sz );
  485. }
  486. }
  487. static void tjei_huff_get_extended(uint8_t* out_ehuffsize,
  488. uint16_t* out_ehuffcode,
  489. uint8_t const * huffval,
  490. uint8_t* huffsize,
  491. uint16_t* huffcode, int64_t count)
  492. {
  493. int k = 0;
  494. do {
  495. uint8_t val = huffval[k];
  496. out_ehuffcode[val] = huffcode[k];
  497. out_ehuffsize[val] = huffsize[k];
  498. k++;
  499. } while ( k < count );
  500. }
  501. // ============================================================
  502. // Returns:
  503. // out[1] : number of bits
  504. // out[0] : bits
  505. TJEI_FORCE_INLINE void tjei_calculate_variable_length_int(int value, uint16_t out[2])
  506. {
  507. int abs_val = value;
  508. if ( value < 0 ) {
  509. abs_val = -abs_val;
  510. --value;
  511. }
  512. out[1] = 1;
  513. while( abs_val >>= 1 ) {
  514. ++out[1];
  515. }
  516. out[0] = (uint16_t)(value & ((1 << out[1]) - 1));
  517. }
  518. // Write bits to file.
  519. TJEI_FORCE_INLINE void tjei_write_bits(TJEState* state,
  520. uint32_t* bitbuffer, uint32_t* location,
  521. uint16_t num_bits, uint16_t bits)
  522. {
  523. // v-- location
  524. // [ ] <-- bit buffer
  525. // 32 0
  526. //
  527. // This call pushes to the bitbuffer and saves the location. Data is pushed
  528. // from most significant to less significant.
  529. // When we can write a full byte, we write a byte and shift.
  530. // Push the stack.
  531. uint32_t nloc = *location + num_bits;
  532. *bitbuffer |= (uint32_t)(bits << (32 - nloc));
  533. *location = nloc;
  534. while ( *location >= 8 ) {
  535. // Grab the most significant byte.
  536. uint8_t c = (uint8_t)((*bitbuffer) >> 24);
  537. // Write it to file.
  538. tjei_write(state, &c, 1, 1);
  539. if ( c == 0xff ) {
  540. // Special case: tell JPEG this is not a marker.
  541. char z = 0;
  542. tjei_write(state, &z, 1, 1);
  543. }
  544. // Pop the stack.
  545. *bitbuffer <<= 8;
  546. *location -= 8;
  547. }
  548. }
  549. // DCT implementation by Thomas G. Lane.
  550. // Obtained through NVIDIA
  551. // http://developer.download.nvidia.com/SDK/9.5/Samples/vidimaging_samples.html#gpgpu_dct
  552. //
  553. // QUOTE:
  554. // This implementation is based on Arai, Agui, and Nakajima's algorithm for
  555. // scaled DCT. Their original paper (Trans. IEICE E-71(11):1095) is in
  556. // Japanese, but the algorithm is described in the Pennebaker & Mitchell
  557. // JPEG textbook (see REFERENCES section in file README). The following code
  558. // is based directly on figure 4-8 in P&M.
  559. //
  560. static void tjei_fdct (float * data)
  561. {
  562. float tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  563. float tmp10, tmp11, tmp12, tmp13;
  564. float z1, z2, z3, z4, z5, z11, z13;
  565. float *dataptr;
  566. int ctr;
  567. /* Pass 1: process rows. */
  568. dataptr = data;
  569. for ( ctr = 7; ctr >= 0; ctr-- ) {
  570. tmp0 = dataptr[0] + dataptr[7];
  571. tmp7 = dataptr[0] - dataptr[7];
  572. tmp1 = dataptr[1] + dataptr[6];
  573. tmp6 = dataptr[1] - dataptr[6];
  574. tmp2 = dataptr[2] + dataptr[5];
  575. tmp5 = dataptr[2] - dataptr[5];
  576. tmp3 = dataptr[3] + dataptr[4];
  577. tmp4 = dataptr[3] - dataptr[4];
  578. /* Even part */
  579. tmp10 = tmp0 + tmp3; /* phase 2 */
  580. tmp13 = tmp0 - tmp3;
  581. tmp11 = tmp1 + tmp2;
  582. tmp12 = tmp1 - tmp2;
  583. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  584. dataptr[4] = tmp10 - tmp11;
  585. z1 = (tmp12 + tmp13) * ((float) 0.707106781); /* c4 */
  586. dataptr[2] = tmp13 + z1; /* phase 5 */
  587. dataptr[6] = tmp13 - z1;
  588. /* Odd part */
  589. tmp10 = tmp4 + tmp5; /* phase 2 */
  590. tmp11 = tmp5 + tmp6;
  591. tmp12 = tmp6 + tmp7;
  592. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  593. z5 = (tmp10 - tmp12) * ((float) 0.382683433); /* c6 */
  594. z2 = ((float) 0.541196100) * tmp10 + z5; /* c2-c6 */
  595. z4 = ((float) 1.306562965) * tmp12 + z5; /* c2+c6 */
  596. z3 = tmp11 * ((float) 0.707106781); /* c4 */
  597. z11 = tmp7 + z3; /* phase 5 */
  598. z13 = tmp7 - z3;
  599. dataptr[5] = z13 + z2; /* phase 6 */
  600. dataptr[3] = z13 - z2;
  601. dataptr[1] = z11 + z4;
  602. dataptr[7] = z11 - z4;
  603. dataptr += 8; /* advance pointer to next row */
  604. }
  605. /* Pass 2: process columns. */
  606. dataptr = data;
  607. for ( ctr = 8-1; ctr >= 0; ctr-- ) {
  608. tmp0 = dataptr[8*0] + dataptr[8*7];
  609. tmp7 = dataptr[8*0] - dataptr[8*7];
  610. tmp1 = dataptr[8*1] + dataptr[8*6];
  611. tmp6 = dataptr[8*1] - dataptr[8*6];
  612. tmp2 = dataptr[8*2] + dataptr[8*5];
  613. tmp5 = dataptr[8*2] - dataptr[8*5];
  614. tmp3 = dataptr[8*3] + dataptr[8*4];
  615. tmp4 = dataptr[8*3] - dataptr[8*4];
  616. /* Even part */
  617. tmp10 = tmp0 + tmp3; /* phase 2 */
  618. tmp13 = tmp0 - tmp3;
  619. tmp11 = tmp1 + tmp2;
  620. tmp12 = tmp1 - tmp2;
  621. dataptr[8*0] = tmp10 + tmp11; /* phase 3 */
  622. dataptr[8*4] = tmp10 - tmp11;
  623. z1 = (tmp12 + tmp13) * ((float) 0.707106781); /* c4 */
  624. dataptr[8*2] = tmp13 + z1; /* phase 5 */
  625. dataptr[8*6] = tmp13 - z1;
  626. /* Odd part */
  627. tmp10 = tmp4 + tmp5; /* phase 2 */
  628. tmp11 = tmp5 + tmp6;
  629. tmp12 = tmp6 + tmp7;
  630. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  631. z5 = (tmp10 - tmp12) * ((float) 0.382683433); /* c6 */
  632. z2 = ((float) 0.541196100) * tmp10 + z5; /* c2-c6 */
  633. z4 = ((float) 1.306562965) * tmp12 + z5; /* c2+c6 */
  634. z3 = tmp11 * ((float) 0.707106781); /* c4 */
  635. z11 = tmp7 + z3; /* phase 5 */
  636. z13 = tmp7 - z3;
  637. dataptr[8*5] = z13 + z2; /* phase 6 */
  638. dataptr[8*3] = z13 - z2;
  639. dataptr[8*1] = z11 + z4;
  640. dataptr[8*7] = z11 - z4;
  641. dataptr++; /* advance pointer to next column */
  642. }
  643. }
  644. #if !TJE_USE_FAST_DCT
  645. static float slow_fdct(int u, int v, float* data)
  646. {
  647. #define kPI 3.14159265f
  648. float res = 0.0f;
  649. float cu = (u == 0) ? 0.70710678118654f : 1;
  650. float cv = (v == 0) ? 0.70710678118654f : 1;
  651. for ( int y = 0; y < 8; ++y ) {
  652. for ( int x = 0; x < 8; ++x ) {
  653. res += (data[y * 8 + x]) *
  654. cosf(((2.0f * x + 1.0f) * u * kPI) / 16.0f) *
  655. cosf(((2.0f * y + 1.0f) * v * kPI) / 16.0f);
  656. }
  657. }
  658. res *= 0.25f * cu * cv;
  659. return res;
  660. #undef kPI
  661. }
  662. #endif
  663. #define ABS(x) ((x) < 0 ? -(x) : (x))
  664. static void tjei_encode_and_write_MCU(TJEState* state,
  665. float* mcu,
  666. #if TJE_USE_FAST_DCT
  667. float* qt, // Pre-processed quantization matrix.
  668. #else
  669. uint8_t* qt,
  670. #endif
  671. uint8_t* huff_dc_len, uint16_t* huff_dc_code, // Huffman tables
  672. uint8_t* huff_ac_len, uint16_t* huff_ac_code,
  673. int* pred, // Previous DC coefficient
  674. uint32_t* bitbuffer, // Bitstack.
  675. uint32_t* location)
  676. {
  677. int du[64]; // Data unit in zig-zag order
  678. float dct_mcu[64];
  679. memcpy(dct_mcu, mcu, 64 * sizeof(float));
  680. #if TJE_USE_FAST_DCT
  681. tjei_fdct(dct_mcu);
  682. for ( int i = 0; i < 64; ++i ) {
  683. float fval = dct_mcu[i];
  684. fval *= qt[i];
  685. #if 0
  686. fval = (fval > 0) ? floorf(fval + 0.5f) : ceilf(fval - 0.5f);
  687. #else
  688. fval = floorf(fval + 1024 + 0.5f);
  689. fval -= 1024;
  690. #endif
  691. int val = (int)fval;
  692. du[tjei_zig_zag[i]] = val;
  693. }
  694. #else
  695. for ( int v = 0; v < 8; ++v ) {
  696. for ( int u = 0; u < 8; ++u ) {
  697. dct_mcu[v * 8 + u] = slow_fdct(u, v, mcu);
  698. }
  699. }
  700. for ( int i = 0; i < 64; ++i ) {
  701. float fval = dct_mcu[i] / (qt[i]);
  702. int val = (int)((fval > 0) ? floorf(fval + 0.5f) : ceilf(fval - 0.5f));
  703. du[tjei_zig_zag[i]] = val;
  704. }
  705. #endif
  706. uint16_t vli[2];
  707. // Encode DC coefficient.
  708. int diff = du[0] - *pred;
  709. *pred = du[0];
  710. if ( diff != 0 ) {
  711. tjei_calculate_variable_length_int(diff, vli);
  712. // Write number of bits with Huffman coding
  713. tjei_write_bits(state, bitbuffer, location, huff_dc_len[vli[1]], huff_dc_code[vli[1]]);
  714. // Write the bits.
  715. tjei_write_bits(state, bitbuffer, location, vli[1], vli[0]);
  716. } else {
  717. tjei_write_bits(state, bitbuffer, location, huff_dc_len[0], huff_dc_code[0]);
  718. }
  719. // ==== Encode AC coefficients ====
  720. int last_non_zero_i = 0;
  721. // Find the last non-zero element.
  722. for ( int i = 63; i > 0; --i ) {
  723. if (du[i] != 0) {
  724. last_non_zero_i = i;
  725. break;
  726. }
  727. }
  728. for ( int i = 1; i <= last_non_zero_i; ++i ) {
  729. // If zero, increase count. If >=15, encode (FF,00)
  730. int zero_count = 0;
  731. while ( du[i] == 0 ) {
  732. ++zero_count;
  733. ++i;
  734. if (zero_count == 16) {
  735. // encode (ff,00) == 0xf0
  736. tjei_write_bits(state, bitbuffer, location, huff_ac_len[0xf0], huff_ac_code[0xf0]);
  737. zero_count = 0;
  738. }
  739. }
  740. tjei_calculate_variable_length_int(du[i], vli);
  741. assert(zero_count < 0x10);
  742. assert(vli[1] <= 10);
  743. uint16_t sym1 = (uint16_t)((uint16_t)zero_count << 4) | vli[1];
  744. assert(huff_ac_len[sym1] != 0);
  745. // Write symbol 1 --- (RUNLENGTH, SIZE)
  746. tjei_write_bits(state, bitbuffer, location, huff_ac_len[sym1], huff_ac_code[sym1]);
  747. // Write symbol 2 --- (AMPLITUDE)
  748. tjei_write_bits(state, bitbuffer, location, vli[1], vli[0]);
  749. }
  750. if (last_non_zero_i != 63) {
  751. // write EOB HUFF(00,00)
  752. tjei_write_bits(state, bitbuffer, location, huff_ac_len[0], huff_ac_code[0]);
  753. }
  754. return;
  755. }
  756. enum {
  757. TJEI_LUMA_DC,
  758. TJEI_LUMA_AC,
  759. TJEI_CHROMA_DC,
  760. TJEI_CHROMA_AC,
  761. };
  762. #if TJE_USE_FAST_DCT
  763. struct TJEProcessedQT
  764. {
  765. float chroma[64];
  766. float luma[64];
  767. };
  768. #endif
  769. // Set up huffman tables in state.
  770. static void tjei_huff_expand(TJEState* state)
  771. {
  772. assert(state);
  773. state->ht_bits[TJEI_LUMA_DC] = tjei_default_ht_luma_dc_len;
  774. state->ht_bits[TJEI_LUMA_AC] = tjei_default_ht_luma_ac_len;
  775. state->ht_bits[TJEI_CHROMA_DC] = tjei_default_ht_chroma_dc_len;
  776. state->ht_bits[TJEI_CHROMA_AC] = tjei_default_ht_chroma_ac_len;
  777. state->ht_vals[TJEI_LUMA_DC] = tjei_default_ht_luma_dc;
  778. state->ht_vals[TJEI_LUMA_AC] = tjei_default_ht_luma_ac;
  779. state->ht_vals[TJEI_CHROMA_DC] = tjei_default_ht_chroma_dc;
  780. state->ht_vals[TJEI_CHROMA_AC] = tjei_default_ht_chroma_ac;
  781. // How many codes in total for each of LUMA_(DC|AC) and CHROMA_(DC|AC)
  782. int32_t spec_tables_len[4] = { 0 };
  783. for ( int i = 0; i < 4; ++i ) {
  784. for ( int k = 0; k < 16; ++k ) {
  785. spec_tables_len[i] += state->ht_bits[i][k];
  786. }
  787. }
  788. // Fill out the extended tables..
  789. static uint8_t huffsize[4][257];
  790. static uint16_t huffcode[4][256];
  791. for ( int i = 0; i < 4; ++i ) {
  792. assert (256 >= spec_tables_len[i]);
  793. tjei_huff_get_code_lengths(huffsize[i], state->ht_bits[i]);
  794. tjei_huff_get_codes(huffcode[i], huffsize[i], spec_tables_len[i]);
  795. }
  796. for ( int i = 0; i < 4; ++i ) {
  797. int64_t count = spec_tables_len[i];
  798. tjei_huff_get_extended(state->ehuffsize[i],
  799. state->ehuffcode[i],
  800. state->ht_vals[i],
  801. &huffsize[i][0],
  802. &huffcode[i][0], count);
  803. }
  804. }
  805. static int tjei_encode_main(TJEState* state,
  806. const unsigned char* src_data,
  807. const int width,
  808. const int height,
  809. const int src_num_components)
  810. {
  811. if (src_num_components != 3 && src_num_components != 4) {
  812. return 0;
  813. }
  814. if (width > 0xffff || height > 0xffff) {
  815. return 0;
  816. }
  817. #if TJE_USE_FAST_DCT
  818. struct TJEProcessedQT pqt;
  819. // Again, taken from classic japanese implementation.
  820. //
  821. /* For float AA&N IDCT method, divisors are equal to quantization
  822. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  823. * scalefactor[0] = 1
  824. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  825. * We apply a further scale factor of 8.
  826. * What's actually stored is 1/divisor so that the inner loop can
  827. * use a multiplication rather than a division.
  828. */
  829. static const float aan_scales[] = {
  830. 1.0f, 1.387039845f, 1.306562965f, 1.175875602f,
  831. 1.0f, 0.785694958f, 0.541196100f, 0.275899379f
  832. };
  833. // build (de)quantization tables
  834. for(int y=0; y<8; y++) {
  835. for(int x=0; x<8; x++) {
  836. int i = y*8 + x;
  837. pqt.luma[y*8+x] = 1.0f / (8 * aan_scales[x] * aan_scales[y] * state->qt_luma[tjei_zig_zag[i]]);
  838. pqt.chroma[y*8+x] = 1.0f / (8 * aan_scales[x] * aan_scales[y] * state->qt_chroma[tjei_zig_zag[i]]);
  839. }
  840. }
  841. #endif
  842. { // Write header
  843. TJEJPEGHeader header;
  844. // JFIF header.
  845. header.SOI = tjei_be_word(0xffd8); // Sequential DCT
  846. header.APP0 = tjei_be_word(0xffe0);
  847. uint16_t jfif_len = sizeof(TJEJPEGHeader) - 4 /*SOI & APP0 markers*/;
  848. header.jfif_len = tjei_be_word(jfif_len);
  849. memcpy(header.jfif_id, (void*)tjeik_jfif_id, 5);
  850. header.version = tjei_be_word(0x0102);
  851. header.units = 0x01; // Dots-per-inch
  852. header.x_density = tjei_be_word(0x0060); // 96 DPI
  853. header.y_density = tjei_be_word(0x0060); // 96 DPI
  854. header.x_thumb = 0;
  855. header.y_thumb = 0;
  856. tjei_write(state, &header, sizeof(TJEJPEGHeader), 1);
  857. }
  858. { // Write comment
  859. TJEJPEGComment com;
  860. uint16_t com_len = 2 + sizeof(tjeik_com_str) - 1;
  861. // Comment
  862. com.com = tjei_be_word(0xfffe);
  863. com.com_len = tjei_be_word(com_len);
  864. memcpy(com.com_str, (void*)tjeik_com_str, sizeof(tjeik_com_str)-1);
  865. tjei_write(state, &com, sizeof(TJEJPEGComment), 1);
  866. }
  867. // Write quantization tables.
  868. tjei_write_DQT(state, state->qt_luma, 0x00);
  869. tjei_write_DQT(state, state->qt_chroma, 0x01);
  870. { // Write the frame marker.
  871. TJEFrameHeader header;
  872. header.SOF = tjei_be_word(0xffc0);
  873. header.len = tjei_be_word(8 + 3 * 3);
  874. header.precision = 8;
  875. assert(width <= 0xffff);
  876. assert(height <= 0xffff);
  877. header.width = tjei_be_word((uint16_t)width);
  878. header.height = tjei_be_word((uint16_t)height);
  879. header.num_components = 3;
  880. uint8_t tables[3] = {
  881. 0, // Luma component gets luma table (see tjei_write_DQT call above.)
  882. 1, // Chroma component gets chroma table
  883. 1, // Chroma component gets chroma table
  884. };
  885. for (int i = 0; i < 3; ++i) {
  886. TJEComponentSpec spec;
  887. spec.component_id = (uint8_t)(i + 1); // No particular reason. Just 1, 2, 3.
  888. spec.sampling_factors = (uint8_t)0x11;
  889. spec.qt = tables[i];
  890. header.component_spec[i] = spec;
  891. }
  892. // Write to file.
  893. tjei_write(state, &header, sizeof(TJEFrameHeader), 1);
  894. }
  895. tjei_write_DHT(state, state->ht_bits[TJEI_LUMA_DC], state->ht_vals[TJEI_LUMA_DC], TJEI_DC, 0);
  896. tjei_write_DHT(state, state->ht_bits[TJEI_LUMA_AC], state->ht_vals[TJEI_LUMA_AC], TJEI_AC, 0);
  897. tjei_write_DHT(state, state->ht_bits[TJEI_CHROMA_DC], state->ht_vals[TJEI_CHROMA_DC], TJEI_DC, 1);
  898. tjei_write_DHT(state, state->ht_bits[TJEI_CHROMA_AC], state->ht_vals[TJEI_CHROMA_AC], TJEI_AC, 1);
  899. // Write start of scan
  900. {
  901. TJEScanHeader header;
  902. header.SOS = tjei_be_word(0xffda);
  903. header.len = tjei_be_word((uint16_t)(6 + (sizeof(TJEFrameComponentSpec) * 3)));
  904. header.num_components = 3;
  905. uint8_t tables[3] = {
  906. 0x00,
  907. 0x11,
  908. 0x11,
  909. };
  910. for (int i = 0; i < 3; ++i) {
  911. TJEFrameComponentSpec cs;
  912. // Must be equal to component_id from frame header above.
  913. cs.component_id = (uint8_t)(i + 1);
  914. cs.dc_ac = (uint8_t)tables[i];
  915. header.component_spec[i] = cs;
  916. }
  917. header.first = 0;
  918. header.last = 63;
  919. header.ah_al = 0;
  920. tjei_write(state, &header, sizeof(TJEScanHeader), 1);
  921. }
  922. // Write compressed data.
  923. float du_y[64];
  924. float du_b[64];
  925. float du_r[64];
  926. // Set diff to 0.
  927. int pred_y = 0;
  928. int pred_b = 0;
  929. int pred_r = 0;
  930. // Bit stack
  931. uint32_t bitbuffer = 0;
  932. uint32_t location = 0;
  933. for ( int y = 0; y < height; y += 8 ) {
  934. for ( int x = 0; x < width; x += 8 ) {
  935. // Block loop: ====
  936. for ( int off_y = 0; off_y < 8; ++off_y ) {
  937. for ( int off_x = 0; off_x < 8; ++off_x ) {
  938. int block_index = (off_y * 8 + off_x);
  939. int src_index = (((y + off_y) * width) + (x + off_x)) * src_num_components;
  940. int col = x + off_x;
  941. int row = y + off_y;
  942. if(row >= height) {
  943. src_index -= (width * (row - height + 1)) * src_num_components;
  944. }
  945. if(col >= width) {
  946. src_index -= (col - width + 1) * src_num_components;
  947. }
  948. assert(src_index < width * height * src_num_components);
  949. uint8_t r = src_data[src_index + 0];
  950. uint8_t g = src_data[src_index + 1];
  951. uint8_t b = src_data[src_index + 2];
  952. float luma = 0.299f * r + 0.587f * g + 0.114f * b - 128;
  953. float cb = -0.1687f * r - 0.3313f * g + 0.5f * b;
  954. float cr = 0.5f * r - 0.4187f * g - 0.0813f * b;
  955. du_y[block_index] = luma;
  956. du_b[block_index] = cb;
  957. du_r[block_index] = cr;
  958. }
  959. }
  960. tjei_encode_and_write_MCU(state, du_y,
  961. #if TJE_USE_FAST_DCT
  962. pqt.luma,
  963. #else
  964. state->qt_luma,
  965. #endif
  966. state->ehuffsize[TJEI_LUMA_DC], state->ehuffcode[TJEI_LUMA_DC],
  967. state->ehuffsize[TJEI_LUMA_AC], state->ehuffcode[TJEI_LUMA_AC],
  968. &pred_y, &bitbuffer, &location);
  969. tjei_encode_and_write_MCU(state, du_b,
  970. #if TJE_USE_FAST_DCT
  971. pqt.chroma,
  972. #else
  973. state->qt_chroma,
  974. #endif
  975. state->ehuffsize[TJEI_CHROMA_DC], state->ehuffcode[TJEI_CHROMA_DC],
  976. state->ehuffsize[TJEI_CHROMA_AC], state->ehuffcode[TJEI_CHROMA_AC],
  977. &pred_b, &bitbuffer, &location);
  978. tjei_encode_and_write_MCU(state, du_r,
  979. #if TJE_USE_FAST_DCT
  980. pqt.chroma,
  981. #else
  982. state->qt_chroma,
  983. #endif
  984. state->ehuffsize[TJEI_CHROMA_DC], state->ehuffcode[TJEI_CHROMA_DC],
  985. state->ehuffsize[TJEI_CHROMA_AC], state->ehuffcode[TJEI_CHROMA_AC],
  986. &pred_r, &bitbuffer, &location);
  987. }
  988. }
  989. // Finish the image.
  990. { // Flush
  991. if (location > 0 && location < 8) {
  992. tjei_write_bits(state, &bitbuffer, &location, (uint16_t)(8 - location), 0);
  993. }
  994. }
  995. uint16_t EOI = tjei_be_word(0xffd9);
  996. tjei_write(state, &EOI, sizeof(uint16_t), 1);
  997. if (state->output_buffer_count) {
  998. state->write_context.func(state->write_context.context, state->output_buffer, (int)state->output_buffer_count);
  999. state->output_buffer_count = 0;
  1000. }
  1001. return 1;
  1002. }
  1003. int tje_encode_to_file(const char* dest_path,
  1004. const int width,
  1005. const int height,
  1006. const int num_components,
  1007. const unsigned char* src_data)
  1008. {
  1009. int res = tje_encode_to_file_at_quality(dest_path, 3, width, height, num_components, src_data);
  1010. return res;
  1011. }
  1012. static void tjei_stdlib_func(void* context, void* data, int size)
  1013. {
  1014. FILE* fd = (FILE*)context;
  1015. fwrite(data, size, 1, fd);
  1016. }
  1017. // Define public interface.
  1018. int tje_encode_to_file_at_quality(const char* dest_path,
  1019. const int quality,
  1020. const int width,
  1021. const int height,
  1022. const int num_components,
  1023. const unsigned char* src_data)
  1024. {
  1025. FILE* fd = fopen(dest_path, "wb");
  1026. if (!fd) {
  1027. tje_log("Could not open file for writing.");
  1028. return 0;
  1029. }
  1030. int result = tje_encode_with_func(tjei_stdlib_func, fd,
  1031. quality, width, height, num_components, src_data);
  1032. result |= 0 == fclose(fd);
  1033. return result;
  1034. }
  1035. int tje_encode_with_func(tje_write_func* func,
  1036. void* context,
  1037. const int quality,
  1038. const int width,
  1039. const int height,
  1040. const int num_components,
  1041. const unsigned char* src_data)
  1042. {
  1043. if (quality < 1 || quality > 3) {
  1044. tje_log("[ERROR] -- Valid 'quality' values are 1 (lowest), 2, or 3 (highest)\n");
  1045. return 0;
  1046. }
  1047. static TJEState state = { 0 };
  1048. uint8_t qt_factor = 1;
  1049. switch(quality) {
  1050. case 3:
  1051. for ( int i = 0; i < 64; ++i ) {
  1052. state.qt_luma[i] = 1;
  1053. state.qt_chroma[i] = 1;
  1054. }
  1055. break;
  1056. case 2:
  1057. qt_factor = 10;
  1058. // don't break. fall through.
  1059. case 1:
  1060. for ( int i = 0; i < 64; ++i ) {
  1061. state.qt_luma[i] = tjei_default_qt_luma_from_spec[i] / qt_factor;
  1062. if (state.qt_luma[i] == 0) {
  1063. state.qt_luma[i] = 1;
  1064. }
  1065. state.qt_chroma[i] = tjei_default_qt_chroma_from_paper[i] / qt_factor;
  1066. if (state.qt_chroma[i] == 0) {
  1067. state.qt_chroma[i] = 1;
  1068. }
  1069. }
  1070. break;
  1071. default:
  1072. assert(!"invalid code path");
  1073. break;
  1074. }
  1075. TJEWriteContext wc = { 0 };
  1076. wc.context = context;
  1077. wc.func = func;
  1078. state.write_context = wc;
  1079. tjei_huff_expand(&state);
  1080. int result = tjei_encode_main(&state, src_data, width, height, num_components);
  1081. return result;
  1082. }
  1083. // ============================================================
  1084. #endif // TJE_IMPLEMENTATION
  1085. // ============================================================
  1086. //
  1087. #if defined(__GNUC__) || defined(__clang__)
  1088. #pragma GCC diagnostic pop
  1089. #endif
  1090. #ifdef __cplusplus
  1091. } // extern C
  1092. #endif