tiny_jpeg.c 43 KB

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