pm1_decoder.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  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. // Decoder for -pm1- compressed files.
  17. //
  18. // This was difficult to put together. I can't find any versions of
  19. // PMarc that will generate -pm1- encoded files (only -pm2-); however,
  20. // the extraction tool, PMext, will extract them. I have therefore been
  21. // able to reverse engineer the format and write a decoder. I am
  22. // indebted to Alwin Henseler for publishing the Z80 assembly source to
  23. // his UNPMA10 tool, which was apparently decompiled from the original
  24. // PMarc and includes the -pm1- decoding code.
  25. #include <stdlib.h>
  26. #include <string.h>
  27. #include <inttypes.h>
  28. #include "lha_decoder.h"
  29. #include "bit_stream_reader.c"
  30. #include "pma_common.c"
  31. // Size of the ring buffer used to hold the history.
  32. #define RING_BUFFER_SIZE 16384
  33. // Maximum length of a command representing a block of bytes:
  34. #define MAX_BYTE_BLOCK_LEN 216
  35. // Maximum number of bytes that can be copied by a single copy command.
  36. #define MAX_COPY_BLOCK_LEN 244
  37. // Output buffer length. A single call to lha_pm1_read can perform one
  38. // byte block output followed by a copy command.
  39. #define OUTPUT_BUFFER_SIZE (MAX_BYTE_BLOCK_LEN + MAX_COPY_BLOCK_LEN)
  40. typedef struct {
  41. BitStreamReader bit_stream_reader;
  42. // Position in output stream, in bytes.
  43. unsigned int output_stream_pos;
  44. // Pointer to the entry in byte_decode_table used to decode
  45. // byte value indices.
  46. const uint8_t *byte_decode_tree;
  47. // History ring buffer.
  48. uint8_t ringbuf[RING_BUFFER_SIZE];
  49. unsigned int ringbuf_pos;
  50. // History linked list, for adaptively encoding byte values.
  51. HistoryLinkedList history_list;
  52. // Callback to read more compressed data from the input (see
  53. // read_callback_wrapper below).
  54. LHADecoderCallback callback;
  55. void *callback_data;
  56. } LHAPM1Decoder;
  57. // Table used to decode distance into history buffer to copy data.
  58. static const VariableLengthTable copy_ranges[] = {
  59. { 0, 6 }, // 0 + (1 << 6) = 64
  60. { 64, 8 }, // 64 + (1 << 8) = 320
  61. { 0, 6 }, // 0 + (1 << 6) = 64
  62. { 64, 9 }, // 64 + (1 << 9) = 576
  63. { 576, 11 }, // 576 + (1 << 11) = 2624
  64. { 2624, 13 }, // 2624 + (1 << 13) = 10816
  65. // The above table entries are used after a certain number of
  66. // bytes have been decoded.
  67. // Early in the stream, some of the copy ranges are more limited
  68. // in their range, so that fewer bits are needed. The above
  69. // table entries are redirected to these entries instead.
  70. // Table entry #3 (64):
  71. { 64, 8 }, // < 320 bytes
  72. // Table entry #4 (576):
  73. { 576, 8 }, // < 832 bytes
  74. { 576, 9 }, // < 1088 bytes
  75. { 576, 10 }, // < 1600 bytes
  76. // Table entry #5 (2624):
  77. { 2624, 8 }, // < 2880 bytes
  78. { 2624, 9 }, // < 3136 bytes
  79. { 2624, 10 }, // < 3648 bytes
  80. { 2624, 11 }, // < 4672 bytes
  81. { 2624, 12 }, // < 6720 bytes
  82. };
  83. // Table used to decode byte values.
  84. static const VariableLengthTable byte_ranges[] = {
  85. { 0, 4 }, // 0 + (1 << 4) = 16
  86. { 16, 4 }, // 16 + (1 << 4) = 32
  87. { 32, 5 }, // 32 + (1 << 5) = 64
  88. { 64, 6 }, // 64 + (1 << 6) = 128
  89. { 128, 6 }, // 128 + (1 << 6) = 191
  90. { 192, 6 }, // 192 + (1 << 6) = 255
  91. };
  92. // This table is a list of trees to decode indices into byte_ranges.
  93. // Each line is actually a mini binary tree, starting with the first
  94. // byte as the root node. Each nybble of the byte is one of the two
  95. // branches: either a leaf value (a-f) or an offset to the child node.
  96. // Expanded representation is shown in comments below.
  97. static const uint8_t byte_decode_trees[][5] = {
  98. { 0x12, 0x2d, 0xef, 0x1c, 0xab }, // ((((a b) c) d) (e f))
  99. { 0x12, 0x23, 0xde, 0xab, 0xcf }, // (((a b) (c f)) (d e))
  100. { 0x12, 0x2c, 0xd2, 0xab, 0xef }, // (((a b) c) (d (e f)))
  101. { 0x12, 0xa2, 0xd2, 0xbc, 0xef }, // ((a (b c)) (d (e f)))
  102. { 0x12, 0xa2, 0xc2, 0xbd, 0xef }, // ((a (b d)) (c (e f)))
  103. { 0x12, 0xa2, 0xcd, 0xb1, 0xef }, // ((a (b (e f))) (c d))
  104. { 0x12, 0xab, 0x12, 0xcd, 0xef }, // ((a b) ((c d) (e f)))
  105. { 0x12, 0xab, 0x1d, 0xc1, 0xef }, // ((a b) ((c (e f)) d))
  106. { 0x12, 0xab, 0xc1, 0xd1, 0xef }, // ((a b) (c (d (e f))))
  107. { 0xa1, 0x12, 0x2c, 0xde, 0xbf }, // (a (((b f) c) (d e)))
  108. { 0xa1, 0x1d, 0x1c, 0xb1, 0xef }, // (a (((b (e f)) c) d))
  109. { 0xa1, 0x12, 0x2d, 0xef, 0xbc }, // (a (((b c) d) (e f)))
  110. { 0xa1, 0x12, 0xb2, 0xde, 0xcf }, // (a ((b (c f)) (d e)))
  111. { 0xa1, 0x12, 0xbc, 0xd1, 0xef }, // (a ((b c) (d (e f))))
  112. { 0xa1, 0x1c, 0xb1, 0xd1, 0xef }, // (a ((b (d (e f))) c))
  113. { 0xa1, 0xb1, 0x12, 0xcd, 0xef }, // (a (b ((c d) (e f))))
  114. { 0xa1, 0xb1, 0xc1, 0xd1, 0xef }, // (a (b (c (d (e f)))))
  115. { 0x12, 0x1c, 0xde, 0xab }, // (((d e) c) (d e)) <- BROKEN!
  116. { 0x12, 0xa2, 0xcd, 0xbe }, // ((a (b e)) (c d))
  117. { 0x12, 0xab, 0xc1, 0xde }, // ((a b) (c (d e)))
  118. { 0xa1, 0x1d, 0x1c, 0xbe }, // (a (((b e) c) d))
  119. { 0xa1, 0x12, 0xbc, 0xde }, // (a ((b c) (d e)))
  120. { 0xa1, 0x1c, 0xb1, 0xde }, // (a ((b (d e)) c))
  121. { 0xa1, 0xb1, 0xc1, 0xde }, // (a (b (c (d e))))
  122. { 0x1d, 0x1c, 0xab }, // (((a b) c) d)
  123. { 0x1c, 0xa1, 0xbd }, // ((a (b d)) c)
  124. { 0x12, 0xab, 0xcd }, // ((a b) (c d))
  125. { 0xa1, 0x1c, 0xbd }, // (a ((b d) c))
  126. { 0xa1, 0xb1, 0xcd }, // (a (b (c d)))
  127. { 0xa1, 0xbc }, // (a (b c))
  128. { 0xab }, // (a b)
  129. { 0x00 }, // -- special entry: 0, no tree
  130. };
  131. // Wrapper function invoked to read more data from the input. This mostly just
  132. // calls the real function that does the read. However, when the end of file
  133. // is reached, instead of returning zero, the buffer is filled with zero bytes
  134. // instead. There seem to be archive files that actually depend on this
  135. // ability to read "beyond" the length of the compressed data.
  136. static size_t read_callback_wrapper(void *buf, size_t buf_len, void *user_data)
  137. {
  138. LHAPM1Decoder *decoder = user_data;
  139. size_t result;
  140. result = decoder->callback(buf, buf_len, decoder->callback_data);
  141. if (result == 0) {
  142. memset(buf, 0, buf_len);
  143. result = buf_len;
  144. }
  145. return result;
  146. }
  147. static int lha_pm1_init(void *data, LHADecoderCallback callback,
  148. void *callback_data)
  149. {
  150. LHAPM1Decoder *decoder = data;
  151. memset(decoder, 0, sizeof(LHAPM1Decoder));
  152. // Unlike other decoders, the bitstream code must call the wrapper
  153. // function above to read data.
  154. decoder->callback = callback;
  155. decoder->callback_data = callback_data;
  156. bit_stream_reader_init(&decoder->bit_stream_reader,
  157. read_callback_wrapper, decoder);
  158. decoder->output_stream_pos = 0;
  159. decoder->byte_decode_tree = NULL;
  160. decoder->ringbuf_pos = 0;
  161. init_history_list(&decoder->history_list);
  162. return 1;
  163. }
  164. // Read the 5-bit header from the start of the input stream. This
  165. // specifies the table entry to use for byte decodes.
  166. static int read_start_header(LHAPM1Decoder *decoder)
  167. {
  168. int index;
  169. index = read_bits(&decoder->bit_stream_reader, 5);
  170. if (index < 0) {
  171. return 0;
  172. }
  173. decoder->byte_decode_tree = byte_decode_trees[index];
  174. return 1;
  175. }
  176. // Function called when a new byte is outputted, to update the
  177. // appropriate data structures.
  178. static void outputted_byte(LHAPM1Decoder *decoder, uint8_t b)
  179. {
  180. // Add to history ring buffer.
  181. decoder->ringbuf[decoder->ringbuf_pos] = b;
  182. decoder->ringbuf_pos
  183. = (decoder->ringbuf_pos + 1) % RING_BUFFER_SIZE;
  184. // Other updates: history linked list, output stream position:
  185. update_history_list(&decoder->history_list, b);
  186. ++decoder->output_stream_pos;
  187. }
  188. // Decode a count of the number of bytes to copy in a copy command.
  189. // Returns -1 for failure.
  190. static int read_copy_byte_count(LHAPM1Decoder *decoder)
  191. {
  192. int x;
  193. // This is a form of static huffman encoding that uses less bits
  194. // to encode short copy amounts (again).
  195. // Value in the range 3..5?
  196. // Length values start at 3: if it was 2, a different copy
  197. // range would have been used and this function would not
  198. // have been called.
  199. x = read_bits(&decoder->bit_stream_reader, 2);
  200. if (x < 0) {
  201. return -1;
  202. } else if (x < 3) {
  203. return x + 3;
  204. }
  205. // Value in range 6..10?
  206. x = read_bits(&decoder->bit_stream_reader, 3);
  207. if (x < 0) {
  208. return -1;
  209. } else if (x < 5) {
  210. return x + 6;
  211. }
  212. // Value in range 11..14?
  213. else if (x == 5) {
  214. x = read_bits(&decoder->bit_stream_reader, 2);
  215. if (x < 0) {
  216. return -1;
  217. } else {
  218. return x + 11;
  219. }
  220. }
  221. // Value in range 15..22?
  222. else if (x == 6) {
  223. x = read_bits(&decoder->bit_stream_reader, 3);
  224. if (x < 0) {
  225. return -1;
  226. } else {
  227. return x + 15;
  228. }
  229. }
  230. // else x == 7...
  231. x = read_bits(&decoder->bit_stream_reader, 6);
  232. if (x < 0) {
  233. return -1;
  234. } else if (x < 62) {
  235. return x + 23;
  236. }
  237. // Value in range 85..116?
  238. else if (x == 62) {
  239. x = read_bits(&decoder->bit_stream_reader, 5);
  240. if (x < 0) {
  241. return -1;
  242. } else {
  243. return x + 85;
  244. }
  245. }
  246. // Value in range 117..244?
  247. else { // a = 63
  248. x = read_bits(&decoder->bit_stream_reader, 7);
  249. if (x < 0) {
  250. return -1;
  251. } else {
  252. return x + 117;
  253. }
  254. }
  255. }
  256. // Read a single bit from the input stream, but only once the specified
  257. // point is reached in the output stream. Before that point is reached,
  258. // return the value of 'def' instead. Returns -1 for error.
  259. static int read_bit_after_threshold(LHAPM1Decoder *decoder,
  260. unsigned int threshold,
  261. int def)
  262. {
  263. if (decoder->output_stream_pos >= threshold) {
  264. return read_bit(&decoder->bit_stream_reader);
  265. } else {
  266. return def;
  267. }
  268. }
  269. // Read the range index for the copy type used when performing a copy command.
  270. static int read_copy_type_range(LHAPM1Decoder *decoder)
  271. {
  272. int x;
  273. // This is another static huffman tree, but the path grows as
  274. // more data is decoded. The progression is as follows:
  275. // 1. Initially, only '0' and '2' can be returned.
  276. // 2. After 64 bytes, '1' and '3' can be returned as well.
  277. // 3. After 576 bytes, '4' can be returned.
  278. // 4. After 2624 bytes, '5' can be returned.
  279. x = read_bit(&decoder->bit_stream_reader);
  280. if (x < 0) {
  281. return -1;
  282. } else if (x == 0) {
  283. x = read_bit_after_threshold(decoder, 576, 0);
  284. if (x < 0) {
  285. return -1;
  286. } else if (x != 0) {
  287. return 4;
  288. } else {
  289. // Return either 0 or 1.
  290. return read_bit_after_threshold(decoder, 64, 0);
  291. }
  292. } else {
  293. x = read_bit_after_threshold(decoder, 64, 1);
  294. if (x < 0) {
  295. return -1;
  296. } else if (x == 0) {
  297. return 3;
  298. }
  299. x = read_bit_after_threshold(decoder, 2624, 1);
  300. if (x < 0) {
  301. return -1;
  302. } else if (x != 0) {
  303. return 2;
  304. } else {
  305. return 5;
  306. }
  307. }
  308. }
  309. // Read a copy command from the input stream and copy from history.
  310. // Returns 0 for failure.
  311. static size_t read_copy_command(LHAPM1Decoder *decoder, uint8_t *buf)
  312. {
  313. int range_index;
  314. int history_distance;
  315. int copy_index, i;
  316. int count;
  317. range_index = read_copy_type_range(decoder);
  318. if (range_index < 0) {
  319. return 0;
  320. }
  321. // The first two entries in the copy_ranges table are used as
  322. // a shorthand to copy two bytes. Otherwise, decode the number
  323. // of bytes to copy.
  324. if (range_index < 2) {
  325. count = 2;
  326. } else {
  327. count = read_copy_byte_count(decoder);
  328. if (count < 0) {
  329. return 0;
  330. }
  331. }
  332. // The 'range_index' variable is an index into the copy_ranges
  333. // array. As a special-case hack, early in the output stream
  334. // some history ranges are inaccessible, so fewer bits can be
  335. // used. Redirect range_index to special entries to do this.
  336. if (range_index == 3) {
  337. if (decoder->output_stream_pos < 320) {
  338. range_index = 6;
  339. }
  340. } else if (range_index == 4) {
  341. if (decoder->output_stream_pos < 832) {
  342. range_index = 7;
  343. } else if (decoder->output_stream_pos < 1088) {
  344. range_index = 8;
  345. } else if (decoder->output_stream_pos < 1600) {
  346. range_index = 9;
  347. }
  348. } else if (range_index == 5) {
  349. if (decoder->output_stream_pos < 2880) {
  350. range_index = 10;
  351. } else if (decoder->output_stream_pos < 3136) {
  352. range_index = 11;
  353. } else if (decoder->output_stream_pos < 3648) {
  354. range_index = 12;
  355. } else if (decoder->output_stream_pos < 4672) {
  356. range_index = 13;
  357. } else if (decoder->output_stream_pos < 6720) {
  358. range_index = 14;
  359. }
  360. }
  361. // Calculate the number of bytes back into the history buffer
  362. // to read.
  363. history_distance = decode_variable_length(&decoder->bit_stream_reader,
  364. copy_ranges, range_index);
  365. if (history_distance < 0
  366. || (unsigned) history_distance >= decoder->output_stream_pos) {
  367. return 0;
  368. }
  369. // Copy from the ring buffer.
  370. copy_index = (decoder->ringbuf_pos + RING_BUFFER_SIZE
  371. - history_distance - 1) % RING_BUFFER_SIZE;
  372. for (i = 0; i < count; ++i) {
  373. buf[i] = decoder->ringbuf[copy_index];
  374. outputted_byte(decoder, decoder->ringbuf[copy_index]);
  375. copy_index = (copy_index + 1) % RING_BUFFER_SIZE;
  376. }
  377. return count;
  378. }
  379. // Read the index into the byte decode table, using the byte_decode_tree
  380. // set at the start of the stream. Returns -1 for failure.
  381. static int read_byte_decode_index(LHAPM1Decoder *decoder)
  382. {
  383. const uint8_t *ptr;
  384. unsigned int child;
  385. int bit;
  386. ptr = decoder->byte_decode_tree;
  387. if (ptr[0] == 0) {
  388. return 0;
  389. }
  390. // Walk down the tree, reading a bit at each node to determine
  391. // which path to take.
  392. for (;;) {
  393. bit = read_bit(&decoder->bit_stream_reader);
  394. if (bit < 0) {
  395. return -1;
  396. } else if (bit == 0) {
  397. child = (*ptr >> 4) & 0x0f;
  398. } else {
  399. child = *ptr & 0x0f;
  400. }
  401. // Reached a leaf node?
  402. if (child >= 10) {
  403. return child - 10;
  404. }
  405. ptr += child;
  406. }
  407. }
  408. // Read a single byte value from the input stream.
  409. // Returns -1 for failure.
  410. static int read_byte(LHAPM1Decoder *decoder)
  411. {
  412. int index;
  413. int count;
  414. // Read the index into the byte_ranges table to use.
  415. index = read_byte_decode_index(decoder);
  416. if (index < 0) {
  417. return -1;
  418. }
  419. // Decode value using byte_ranges table. This is actually
  420. // a distance to walk along the history linked list - it
  421. // is static huffman encoding, so that recently used byte
  422. // values use fewer bits.
  423. count = decode_variable_length(&decoder->bit_stream_reader,
  424. byte_ranges, index);
  425. if (count < 0) {
  426. return -1;
  427. }
  428. // Walk through the history linked list to get the actual
  429. // value.
  430. return find_in_history_list(&decoder->history_list, count);
  431. }
  432. // Read the length of a block of bytes.
  433. static int read_byte_block_count(BitStreamReader *reader)
  434. {
  435. int x;
  436. // This is a form of static huffman coding, where smaller
  437. // lengths are encoded using shorter bit sequences.
  438. // Value in the range 1..3?
  439. x = read_bits(reader, 2);
  440. if (x < 0) {
  441. return 0;
  442. } else if (x < 3) {
  443. return x + 1;
  444. }
  445. // Value in the range 4..10?
  446. x = read_bits(reader, 3);
  447. if (x < 0) {
  448. return 0;
  449. } else if (x < 7) {
  450. return x + 4;
  451. }
  452. // Value in the range 11..25?
  453. x = read_bits(reader, 4);
  454. if (x < 0) {
  455. return 0;
  456. } else if (x < 14) {
  457. return x + 11;
  458. } else if (x == 14) {
  459. // Value in the range 25-88:
  460. x = read_bits(reader, 6);
  461. if (x < 0) {
  462. return 0;
  463. } else {
  464. return x + 25;
  465. }
  466. } else { // x = 15
  467. // Value in the range 89-216:
  468. x = read_bits(reader, 7);
  469. if (x < 0) {
  470. return 0;
  471. } else {
  472. return x + 89;
  473. }
  474. }
  475. }
  476. // Read a block of bytes from the input stream.
  477. // Returns 0 for failure.
  478. static size_t read_byte_block(LHAPM1Decoder *decoder, uint8_t *buf)
  479. {
  480. size_t result, result2;
  481. int byteval;
  482. int block_len;
  483. int i;
  484. // How many bytes to decode?
  485. block_len = read_byte_block_count(&decoder->bit_stream_reader);
  486. if (block_len == 0) {
  487. return 0;
  488. }
  489. // Decode the byte values and add them to the output buffer.
  490. for (i = 0; i < block_len; ++i) {
  491. byteval = read_byte(decoder);
  492. if (byteval < 0) {
  493. return 0;
  494. }
  495. buf[i] = byteval;
  496. outputted_byte(decoder, byteval);
  497. }
  498. result = (size_t) block_len;
  499. // Because this is a block of bytes, it can be assumed that the
  500. // block ended for a copy command. The one exception is that if
  501. // the maximum block length was reached, the block may have
  502. // ended just because it could not be any larger.
  503. if (result == MAX_BYTE_BLOCK_LEN) {
  504. return result;
  505. }
  506. result2 = read_copy_command(decoder, buf + result);
  507. if (result2 == 0) {
  508. return 0;
  509. }
  510. return result + result2;
  511. }
  512. static size_t lha_pm1_read(void *data, uint8_t *buf)
  513. {
  514. LHAPM1Decoder *decoder = data;
  515. int command_type;
  516. // Start of input stream? Read the header.
  517. if (decoder->byte_decode_tree == NULL
  518. && !read_start_header(decoder)) {
  519. return 0;
  520. }
  521. // Read what type of commmand this is.
  522. command_type = read_bit(&decoder->bit_stream_reader);
  523. if (command_type == 0) {
  524. return read_copy_command(decoder, buf);
  525. } else {
  526. return read_byte_block(decoder, buf);
  527. }
  528. }
  529. LHADecoderType lha_pm1_decoder = {
  530. lha_pm1_init,
  531. NULL,
  532. lha_pm1_read,
  533. sizeof(LHAPM1Decoder),
  534. OUTPUT_BUFFER_SIZE,
  535. 2048
  536. };