tiny_jpeg.c 42 KB

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