pm2_decoder.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. /*
  2. Copyright (c) 2011, 2012, Simon Howard
  3. Permission to use, copy, modify, and/or distribute this software
  4. for any purpose with or without fee is hereby granted, provided
  5. that the above copyright notice and this permission notice appear
  6. in all copies.
  7. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
  8. WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
  9. WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
  10. AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
  11. CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  12. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
  13. NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  14. CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. */
  16. //
  17. // Decoder for PMarc -pm2- compression format. PMarc is a variant
  18. // of LHA commonly used on the MSX computer architecture.
  19. //
  20. #include <stdio.h>
  21. #include <stdlib.h>
  22. #include <string.h>
  23. #include <inttypes.h>
  24. #include "lha_decoder.h"
  25. #include "bit_stream_reader.c"
  26. #include "pma_common.c"
  27. // Include tree decoder.
  28. typedef uint8_t TreeElement;
  29. #include "tree_decode.c"
  30. // Size of the ring buffer (in bytes) used to store past history
  31. // for copies.
  32. #define RING_BUFFER_SIZE 8192
  33. // Maximum number of bytes that might be placed in the output buffer
  34. // from a single call to lha_pm2_decoder_read (largest copy size).
  35. #define OUTPUT_BUFFER_SIZE 256
  36. // Number of tree elements in the code tree.
  37. #define CODE_TREE_ELEMENTS 65
  38. // Number of tree elements in the offset tree.
  39. #define OFFSET_TREE_ELEMENTS 17
  40. typedef enum {
  41. PM2_REBUILD_UNBUILT, // At start of stream
  42. PM2_REBUILD_BUILD1, // After 1KiB
  43. PM2_REBUILD_BUILD2, // After 2KiB
  44. PM2_REBUILD_BUILD3, // After 4KiB
  45. PM2_REBUILD_CONTINUING, // 8KiB onwards...
  46. } PM2RebuildState;
  47. typedef struct {
  48. BitStreamReader bit_stream_reader;
  49. // State of decode tree.
  50. PM2RebuildState tree_state;
  51. // Number of bytes until we initiate a tree rebuild.
  52. size_t tree_rebuild_remaining;
  53. // History ring buffer, for copies:
  54. uint8_t ringbuf[RING_BUFFER_SIZE];
  55. unsigned int ringbuf_pos;
  56. // History linked list, for adaptively encoding byte values.
  57. HistoryLinkedList history_list;
  58. // Array representing the huffman tree used for representing
  59. // code values. A given node of the tree has children
  60. // code_tree[n] and code_tree[n + 1]. code_tree[0] is the
  61. // root node.
  62. TreeElement code_tree[CODE_TREE_ELEMENTS];
  63. // If zero, we don't need an offset tree:
  64. int need_offset_tree;
  65. // Array representing huffman tree used to look up offsets.
  66. // Same format as code_tree[].
  67. TreeElement offset_tree[OFFSET_TREE_ELEMENTS];
  68. } LHAPM2Decoder;
  69. // Decode table for history value. Characters that appeared recently in
  70. // the history are more likely than ones that appeared a long time ago,
  71. // so the history value is huffman coded so that small values require
  72. // fewer bits. The history value is then used to search within the
  73. // history linked list to get the actual character.
  74. static const VariableLengthTable history_decode[] = {
  75. { 0, 3 }, // 0 + (1 << 3) = 8
  76. { 8, 3 }, // 8 + (1 << 3) = 16
  77. { 16, 4 }, // 16 + (1 << 4) = 32
  78. { 32, 5 }, // 32 + (1 << 5) = 64
  79. { 64, 5 }, // 64 + (1 << 5) = 96
  80. { 96, 5 }, // 96 + (1 << 5) = 128
  81. { 128, 6 }, // 128 + (1 << 6) = 192
  82. { 192, 6 }, // 192 + (1 << 6) = 256
  83. };
  84. // Decode table for copies. As with history_decode[], small copies
  85. // are more common, and require fewer bits.
  86. static const VariableLengthTable copy_decode[] = {
  87. { 17, 3 }, // 17 + (1 << 3) = 25
  88. { 25, 3 }, // 25 + (1 << 3) = 33
  89. { 33, 5 }, // 33 + (1 << 5) = 65
  90. { 65, 6 }, // 65 + (1 << 6) = 129
  91. { 129, 7 }, // 129 + (1 << 7) = 256
  92. { 256, 0 }, // 256 (unique value)
  93. };
  94. // Initialize PMA decoder.
  95. static int lha_pm2_decoder_init(void *data, LHADecoderCallback callback,
  96. void *callback_data)
  97. {
  98. LHAPM2Decoder *decoder = data;
  99. bit_stream_reader_init(&decoder->bit_stream_reader,
  100. callback, callback_data);
  101. // Tree has not been built yet. It needs to be built on
  102. // the first call to read().
  103. decoder->tree_state = PM2_REBUILD_UNBUILT;
  104. decoder->tree_rebuild_remaining = 0;
  105. // Initialize ring buffer contents.
  106. memset(&decoder->ringbuf, ' ', RING_BUFFER_SIZE);
  107. decoder->ringbuf_pos = 0;
  108. // Init history lookup list.
  109. init_history_list(&decoder->history_list);
  110. // Initialize the lookup trees to a known state.
  111. init_tree(decoder->code_tree, CODE_TREE_ELEMENTS);
  112. init_tree(decoder->offset_tree, OFFSET_TREE_ELEMENTS);
  113. return 1;
  114. }
  115. // Read the list of code lengths to use for the code tree and construct
  116. // the code_tree structure.
  117. static int read_code_tree(LHAPM2Decoder *decoder)
  118. {
  119. uint8_t code_lengths[31];
  120. int num_codes, min_code_length, length_bits, val;
  121. unsigned int i;
  122. // Read the number of codes in the tree.
  123. num_codes = read_bits(&decoder->bit_stream_reader, 5);
  124. // Read min_code_length, which is used as an offset.
  125. min_code_length = read_bits(&decoder->bit_stream_reader, 3);
  126. if (min_code_length < 0 || num_codes < 0) {
  127. return 0;
  128. }
  129. // Store flag variable indicating whether we want to read
  130. // the offset tree as well.
  131. decoder->need_offset_tree
  132. = num_codes >= 10
  133. && !(num_codes == 29 && min_code_length == 0);
  134. // Minimum length of zero means a tree containing a single code.
  135. if (min_code_length == 0) {
  136. set_tree_single(decoder->code_tree, num_codes - 1);
  137. return 1;
  138. }
  139. // How many bits are used to represent each table entry?
  140. length_bits = read_bits(&decoder->bit_stream_reader, 3);
  141. if (length_bits < 0) {
  142. return 0;
  143. }
  144. // Read table of code lengths:
  145. for (i = 0; i < (unsigned int) num_codes; ++i) {
  146. // Read a table entry. A value of zero represents an
  147. // unused code. Otherwise the value represents
  148. // an offset from the minimum length (previously read).
  149. val = read_bits(&decoder->bit_stream_reader,
  150. (unsigned int) length_bits);
  151. if (val < 0) {
  152. return 0;
  153. } else if (val == 0) {
  154. code_lengths[i] = 0;
  155. } else {
  156. code_lengths[i] = (uint8_t) (min_code_length + val - 1);
  157. }
  158. }
  159. // Build the tree.
  160. build_tree(decoder->code_tree, sizeof(decoder->code_tree),
  161. code_lengths, (unsigned int) num_codes);
  162. return 1;
  163. }
  164. // Read the code lengths for the offset tree and construct the offset
  165. // tree lookup table.
  166. static int read_offset_tree(LHAPM2Decoder *decoder,
  167. unsigned int num_offsets)
  168. {
  169. uint8_t offset_lengths[8];
  170. unsigned int off;
  171. unsigned int single_offset, num_codes;
  172. int len;
  173. if (!decoder->need_offset_tree) {
  174. return 1;
  175. }
  176. // Read 'num_offsets' 3-bit length values. For each offset
  177. // value 'off', offset_lengths[off] is the length of the
  178. // code that will represent 'off', or 0 if it will not
  179. // appear within the tree.
  180. num_codes = 0;
  181. single_offset = 0;
  182. for (off = 0; off < num_offsets; ++off) {
  183. len = read_bits(&decoder->bit_stream_reader, 3);
  184. if (len < 0) {
  185. return 0;
  186. }
  187. offset_lengths[off] = (uint8_t) len;
  188. // Track how many actual codes were in the tree.
  189. if (len != 0) {
  190. single_offset = off;
  191. ++num_codes;
  192. }
  193. }
  194. // If there was a single code, this is a single node tree.
  195. if (num_codes == 1) {
  196. set_tree_single(decoder->offset_tree, single_offset);
  197. return 1;
  198. }
  199. // Build the tree.
  200. build_tree(decoder->offset_tree, sizeof(decoder->offset_tree),
  201. offset_lengths, num_offsets);
  202. return 1;
  203. }
  204. // Rebuild the decode trees used to compress data. This is called when
  205. // decoder->tree_rebuild_remaining reaches zero.
  206. static void rebuild_tree(LHAPM2Decoder *decoder)
  207. {
  208. switch (decoder->tree_state) {
  209. // Initial tree build, from start of stream:
  210. case PM2_REBUILD_UNBUILT:
  211. read_code_tree(decoder);
  212. read_offset_tree(decoder, 5);
  213. decoder->tree_state = PM2_REBUILD_BUILD1;
  214. decoder->tree_rebuild_remaining = 1024;
  215. break;
  216. // Tree rebuild after 1KiB of data has been read:
  217. case PM2_REBUILD_BUILD1:
  218. read_offset_tree(decoder, 6);
  219. decoder->tree_state = PM2_REBUILD_BUILD2;
  220. decoder->tree_rebuild_remaining = 1024;
  221. break;
  222. // Tree rebuild after 2KiB of data has been read:
  223. case PM2_REBUILD_BUILD2:
  224. read_offset_tree(decoder, 7);
  225. decoder->tree_state = PM2_REBUILD_BUILD3;
  226. decoder->tree_rebuild_remaining = 2048;
  227. break;
  228. // Tree rebuild after 4KiB of data has been read:
  229. case PM2_REBUILD_BUILD3:
  230. if (read_bit(&decoder->bit_stream_reader) == 1) {
  231. read_code_tree(decoder);
  232. }
  233. read_offset_tree(decoder, 8);
  234. decoder->tree_state = PM2_REBUILD_CONTINUING;
  235. decoder->tree_rebuild_remaining = 4096;
  236. break;
  237. // Tree rebuild after 8KiB of data has been read,
  238. // and every 4KiB after that:
  239. case PM2_REBUILD_CONTINUING:
  240. if (read_bit(&decoder->bit_stream_reader) == 1) {
  241. read_code_tree(decoder);
  242. read_offset_tree(decoder, 8);
  243. }
  244. decoder->tree_rebuild_remaining = 4096;
  245. break;
  246. }
  247. }
  248. static void output_byte(LHAPM2Decoder *decoder, uint8_t *buf,
  249. size_t *buf_len, uint8_t b)
  250. {
  251. // Add to history ring buffer.
  252. decoder->ringbuf[decoder->ringbuf_pos] = b;
  253. decoder->ringbuf_pos = (decoder->ringbuf_pos + 1) % RING_BUFFER_SIZE;
  254. // Add to output buffer.
  255. buf[*buf_len] = b;
  256. ++*buf_len;
  257. // Update history chain.
  258. update_history_list(&decoder->history_list, b);
  259. // Count down until it is time to perform a rebuild of the
  260. // lookup trees.
  261. --decoder->tree_rebuild_remaining;
  262. if (decoder->tree_rebuild_remaining == 0) {
  263. rebuild_tree(decoder);
  264. }
  265. }
  266. // Read a single byte from the input stream and add it to the output
  267. // buffer.
  268. static void read_single_byte(LHAPM2Decoder *decoder, unsigned int code,
  269. uint8_t *buf, size_t *buf_len)
  270. {
  271. int offset;
  272. uint8_t b;
  273. offset = decode_variable_length(&decoder->bit_stream_reader,
  274. history_decode, code);
  275. if (offset < 0) {
  276. return;
  277. }
  278. b = find_in_history_list(&decoder->history_list, (uint8_t) offset);
  279. output_byte(decoder, buf, buf_len, b);
  280. }
  281. // Calculate how many bytes from history to copy:
  282. static int history_get_count(LHAPM2Decoder *decoder, unsigned int code)
  283. {
  284. // How many bytes to copy? A small value represents the
  285. // literal number of bytes to copy; larger values are a header
  286. // for a variable length value to be decoded.
  287. if (code < 15) {
  288. return (int) code + 2;
  289. } else {
  290. return decode_variable_length(&decoder->bit_stream_reader,
  291. copy_decode, code - 15);
  292. }
  293. }
  294. // Calculate the offset within history at which to start copying:
  295. static int history_get_offset(LHAPM2Decoder *decoder, unsigned int code)
  296. {
  297. unsigned int bits;
  298. int result, val;
  299. result = 0;
  300. // Calculate number of bits to read.
  301. // Code of zero indicates a simple 6-bit value giving the offset.
  302. if (code == 0) {
  303. bits = 6;
  304. }
  305. // Mid-range encoded offset value.
  306. // Read a code using the offset tree, indicating the length
  307. // of the offset value to follow. The code indicates the
  308. // number of bits (values 0-7 = 6-13 bits).
  309. else if (code < 20) {
  310. val = read_from_tree(&decoder->bit_stream_reader,
  311. decoder->offset_tree);
  312. if (val < 0) {
  313. return -1;
  314. } else if (val == 0) {
  315. bits = 6;
  316. } else {
  317. bits = (unsigned int) val + 5;
  318. result = 1 << bits;
  319. }
  320. }
  321. // Large copy values start from offset zero.
  322. else {
  323. return 0;
  324. }
  325. // Read a number of bits representing the offset value. The
  326. // number of length of this value is variable, and is calculated
  327. // above.
  328. val = read_bits(&decoder->bit_stream_reader, bits);
  329. if (val < 0) {
  330. return -1;
  331. }
  332. result += val;
  333. return result;
  334. }
  335. static void copy_from_history(LHAPM2Decoder *decoder, unsigned int code,
  336. uint8_t *buf, size_t *buf_len)
  337. {
  338. int to_copy, offset;
  339. unsigned int i, pos, start;
  340. // Read number of bytes to copy and offset within history to copy
  341. // from.
  342. to_copy = history_get_count(decoder, code);
  343. offset = history_get_offset(decoder, code);
  344. if (to_copy < 0 || offset < 0) {
  345. return;
  346. }
  347. // Sanity check to prevent the potential for buffer overflow.
  348. if (to_copy > OUTPUT_BUFFER_SIZE) {
  349. return;
  350. }
  351. // Perform copy.
  352. start = decoder->ringbuf_pos + RING_BUFFER_SIZE - 1
  353. - (unsigned int) offset;
  354. for (i = 0; i < (unsigned int) to_copy; ++i) {
  355. pos = (start + i) % RING_BUFFER_SIZE;
  356. output_byte(decoder, buf, buf_len, decoder->ringbuf[pos]);
  357. }
  358. }
  359. // Decode data and store it into buf[], returning the number of
  360. // bytes decoded.
  361. static size_t lha_pm2_decoder_read(void *data, uint8_t *buf)
  362. {
  363. LHAPM2Decoder *decoder = data;
  364. size_t result;
  365. int code;
  366. // On first pass through, build initial lookup trees.
  367. if (decoder->tree_state == PM2_REBUILD_UNBUILT) {
  368. // First bit in stream is discarded?
  369. read_bit(&decoder->bit_stream_reader);
  370. rebuild_tree(decoder);
  371. }
  372. result = 0;
  373. code = read_from_tree(&decoder->bit_stream_reader, decoder->code_tree);
  374. if (code < 0) {
  375. return 0;
  376. }
  377. if (code < 8) {
  378. read_single_byte(decoder, (unsigned int) code, buf, &result);
  379. } else {
  380. copy_from_history(decoder, (unsigned int) code - 8,
  381. buf, &result);
  382. }
  383. return result;
  384. }
  385. LHADecoderType lha_pm2_decoder = {
  386. lha_pm2_decoder_init,
  387. NULL,
  388. lha_pm2_decoder_read,
  389. sizeof(LHAPM2Decoder),
  390. OUTPUT_BUFFER_SIZE,
  391. RING_BUFFER_SIZE
  392. };