/
chd.c
2518 lines (2065 loc) · 74.8 KB
/
chd.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***************************************************************************
chd.c
MAME Compressed Hunks of Data file format
****************************************************************************
Copyright Aaron Giles
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
* Neither the name 'MAME' nor the names of its contributors may be
used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY AARON GILES ''AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL AARON GILES BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
***************************************************************************/
#define DONT_SET_BYTE
typedef unsigned char Byte;
#include "chd.h"
#include "cdrom.h"
#include "huffman.h"
#include "flac.h"
#include "md5.h"
#include "sha1.h"
#include "LzmaEnc.h"
#include "LzmaDec.h"
#include <string.h>
#include <zlib.h>
#include <time.h>
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include <retro_inline.h>
#include "../deps/crypto/md5.h"
#define TRUE 1
#define FALSE 0
#define MAX(x, y) (((x) > (y)) ? (x) : (y))
#define MIN(x, y) (((x) < (y)) ? (x) : (y))
#define SHA1_DIGEST_SIZE 20
#define CHD_MAKE_TAG(a,b,c,d) (((a) << 24) | ((b) << 16) | ((c) << 8) | (d))
/***************************************************************************
DEBUGGING
***************************************************************************/
#define PRINTF_MAX_HUNK (0)
/***************************************************************************
CONSTANTS
***************************************************************************/
#define MAP_STACK_ENTRIES 512 /* max number of entries to use on the stack */
#define MAP_ENTRY_SIZE 16 /* V3 and later */
#define OLD_MAP_ENTRY_SIZE 8 /* V1-V2 */
#define METADATA_HEADER_SIZE 16 /* metadata header size */
#define CRCMAP_HASH_SIZE 4095 /* number of CRC hashtable entries */
#define MAP_ENTRY_FLAG_TYPE_MASK 0x0f /* what type of hunk */
#define MAP_ENTRY_FLAG_NO_CRC 0x10 /* no CRC is present */
#define CHD_V1_SECTOR_SIZE 512 /* size of a "sector" in the V1 header */
#define COOKIE_VALUE 0xbaadf00d
#define MAX_ZLIB_ALLOCS 64
#define END_OF_LIST_COOKIE "EndOfListCookie"
#define NO_MATCH (~0)
static const uint8_t s_cd_sync_header[12] = { 0x00,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x00 };
// V3-V4 entry types
enum
{
V34_MAP_ENTRY_TYPE_INVALID = 0, // invalid type
V34_MAP_ENTRY_TYPE_COMPRESSED = 1, // standard compression
V34_MAP_ENTRY_TYPE_UNCOMPRESSED = 2, // uncompressed data
V34_MAP_ENTRY_TYPE_MINI = 3, // mini: use offset as raw data
V34_MAP_ENTRY_TYPE_SELF_HUNK = 4, // same as another hunk in this file
V34_MAP_ENTRY_TYPE_PARENT_HUNK = 5, // same as a hunk in the parent file
V34_MAP_ENTRY_TYPE_2ND_COMPRESSED = 6 // compressed with secondary algorithm (usually FLAC CDDA)
};
// V5 compression types
enum
{
///< codec #0
// these types are live when running
COMPRESSION_TYPE_0 = 0,
///< codec #1
COMPRESSION_TYPE_1 = 1,
///< codec #2
COMPRESSION_TYPE_2 = 2,
///< codec #3
COMPRESSION_TYPE_3 = 3,
///< no compression; implicit length = hunkbytes
COMPRESSION_NONE = 4,
///< same as another block in this chd
COMPRESSION_SELF = 5,
///< same as a hunk's worth of units in the parent chd
COMPRESSION_PARENT = 6,
///< start of small RLE run (4-bit length)
// these additional pseudo-types are used for compressed encodings:
COMPRESSION_RLE_SMALL,
///< start of large RLE run (8-bit length)
COMPRESSION_RLE_LARGE,
///< same as the last COMPRESSION_SELF block
COMPRESSION_SELF_0,
///< same as the last COMPRESSION_SELF block + 1
COMPRESSION_SELF_1,
///< same block in the parent
COMPRESSION_PARENT_SELF,
///< same as the last COMPRESSION_PARENT block
COMPRESSION_PARENT_0,
///< same as the last COMPRESSION_PARENT block + 1
COMPRESSION_PARENT_1
};
/***************************************************************************
MACROS
***************************************************************************/
#define EARLY_EXIT(x) do { (void)(x); goto cleanup; } while (0)
/***************************************************************************
TYPE DEFINITIONS
***************************************************************************/
/* interface to a codec */
typedef struct _codec_interface codec_interface;
struct _codec_interface
{
UINT32 compression; /* type of compression */
const char *compname; /* name of the algorithm */
UINT8 lossy; /* is this a lossy algorithm? */
chd_error (*init)(void *codec, UINT32 hunkbytes); /* codec initialize */
void (*free)(void *codec); /* codec free */
chd_error (*decompress)(void *codec, const uint8_t *src, uint32_t complen, uint8_t *dest, uint32_t destlen); /* decompress data */
chd_error (*config)(void *codec, int param, void *config); /* configure */
};
/* a single map entry */
typedef struct _map_entry map_entry;
struct _map_entry
{
UINT64 offset; /* offset within the file of the data */
UINT32 crc; /* 32-bit CRC of the data */
UINT32 length; /* length of the data */
UINT8 flags; /* misc flags */
};
/* simple linked-list of hunks used for our CRC map */
typedef struct _crcmap_entry crcmap_entry;
struct _crcmap_entry
{
UINT32 hunknum; /* hunk number */
crcmap_entry * next; /* next entry in list */
};
/* a single metadata entry */
typedef struct _metadata_entry metadata_entry;
struct _metadata_entry
{
UINT64 offset; /* offset within the file of the header */
UINT64 next; /* offset within the file of the next header */
UINT64 prev; /* offset within the file of the previous header */
UINT32 length; /* length of the metadata */
UINT32 metatag; /* metadata tag */
UINT8 flags; /* flag bits */
};
/* codec-private data for the ZLIB codec */
typedef struct _zlib_allocator zlib_allocator;
struct _zlib_allocator
{
UINT32 * allocptr[MAX_ZLIB_ALLOCS];
};
typedef struct _zlib_codec_data zlib_codec_data;
struct _zlib_codec_data
{
z_stream inflater;
zlib_allocator allocator;
};
/* codec-private data for the LZMA codec */
#define MAX_LZMA_ALLOCS 64
typedef struct _lzma_allocator lzma_allocator;
struct _lzma_allocator
{
void *(*Alloc)(void *p, size_t size);
void (*Free)(void *p, void *address); /* address can be 0 */
void (*FreeSz)(void *p, void *address, size_t size); /* address can be 0 */
uint32_t* allocptr[MAX_LZMA_ALLOCS];
};
typedef struct _lzma_codec_data lzma_codec_data;
struct _lzma_codec_data
{
CLzmaDec decoder;
lzma_allocator allocator;
};
/* codec-private data for the CDZL codec */
typedef struct _cdzl_codec_data cdzl_codec_data;
struct _cdzl_codec_data {
// internal state
zlib_codec_data base_decompressor;
zlib_codec_data subcode_decompressor;
uint8_t* buffer;
};
/* codec-private data for the CDLZ codec */
typedef struct _cdlz_codec_data cdlz_codec_data;
struct _cdlz_codec_data {
// internal state
lzma_codec_data base_decompressor;
zlib_codec_data subcode_decompressor;
uint8_t* buffer;
};
/* codec-private data for the CDFL codec */
typedef struct _cdfl_codec_data cdfl_codec_data;
struct _cdfl_codec_data {
// internal state
int swap_endian;
flac_decoder decoder;
z_stream inflater;
zlib_allocator allocator;
uint8_t* buffer;
};
/* internal representation of an open CHD file */
struct _chd_file
{
UINT32 cookie; /* cookie, should equal COOKIE_VALUE */
core_file * file; /* handle to the open core file */
UINT8 owns_file; /* flag indicating if this file should be closed on chd_close() */
chd_header header; /* header, extracted from file */
chd_file * parent; /* pointer to parent file, or NULL */
map_entry * map; /* array of map entries */
UINT8 * cache; /* hunk cache pointer */
UINT32 cachehunk; /* index of currently cached hunk */
UINT8 * compare; /* hunk compare pointer */
UINT32 comparehunk; /* index of current compare data */
UINT8 * compressed; /* pointer to buffer for compressed data */
const codec_interface * codecintf[4]; /* interface to the codec */
zlib_codec_data zlib_codec_data; /* zlib codec data */
cdzl_codec_data cdzl_codec_data; /* cdzl codec data */
cdlz_codec_data cdlz_codec_data; /* cdlz codec data */
cdfl_codec_data cdfl_codec_data; /* cdfl codec data */
crcmap_entry * crcmap; /* CRC map entries */
crcmap_entry * crcfree; /* free list CRC entries */
crcmap_entry ** crctable; /* table of CRC entries */
UINT32 maxhunk; /* maximum hunk accessed */
UINT8 compressing; /* are we compressing? */
MD5_CTX compmd5; /* running MD5 during compression */
SHA1_CTX compsha1; /* running SHA1 during compression */
UINT32 comphunk; /* next hunk we will compress */
UINT8 verifying; /* are we verifying? */
MD5_CTX vermd5; /* running MD5 during verification */
SHA1_CTX versha1; /* running SHA1 during verification */
UINT32 verhunk; /* next hunk we will verify */
UINT32 async_hunknum; /* hunk index for asynchronous operations */
void * async_buffer; /* buffer pointer for asynchronous operations */
UINT8 * file_cache; /* cache of underlying file */
};
/* a single metadata hash entry */
typedef struct _metadata_hash metadata_hash;
struct _metadata_hash
{
UINT8 tag[4]; /* tag of the metadata in big-endian */
UINT8 sha1[CHD_SHA1_BYTES]; /* hash */
};
/***************************************************************************
GLOBAL VARIABLES
***************************************************************************/
static const UINT8 nullmd5[CHD_MD5_BYTES] = { 0 };
static const UINT8 nullsha1[CHD_SHA1_BYTES] = { 0 };
/***************************************************************************
PROTOTYPES
***************************************************************************/
/* internal header operations */
static chd_error header_validate(const chd_header *header);
static chd_error header_read(core_file *file, chd_header *header);
/* internal hunk read/write */
static chd_error hunk_read_into_cache(chd_file *chd, UINT32 hunknum);
static chd_error hunk_read_into_memory(chd_file *chd, UINT32 hunknum, UINT8 *dest);
/* internal map access */
static chd_error map_read(chd_file *chd);
/* metadata management */
static chd_error metadata_find_entry(chd_file *chd, UINT32 metatag, UINT32 metaindex, metadata_entry *metaentry);
/* zlib compression codec */
static chd_error zlib_codec_init(void *codec, uint32_t hunkbytes);
static void zlib_codec_free(void *codec);
static chd_error zlib_codec_decompress(void *codec, const uint8_t *src, uint32_t complen, uint8_t *dest, uint32_t destlen);
static voidpf zlib_fast_alloc(voidpf opaque, uInt items, uInt size);
static void zlib_fast_free(voidpf opaque, voidpf address);
/* lzma compression codec */
static chd_error lzma_codec_init(void *codec, uint32_t hunkbytes);
static void lzma_codec_free(void *codec);
static chd_error lzma_codec_decompress(void *codec, const uint8_t *src, uint32_t complen, uint8_t *dest, uint32_t destlen);
/* cdzl compression codec */
static chd_error cdzl_codec_init(void* codec, uint32_t hunkbytes);
static void cdzl_codec_free(void* codec);
static chd_error cdzl_codec_decompress(void *codec, const uint8_t *src, uint32_t complen, uint8_t *dest, uint32_t destlen);
/* cdlz compression codec */
static chd_error cdlz_codec_init(void* codec, uint32_t hunkbytes);
static void cdlz_codec_free(void* codec);
static chd_error cdlz_codec_decompress(void *codec, const uint8_t *src, uint32_t complen, uint8_t *dest, uint32_t destlen);
/* cdfl compression codec */
static chd_error cdfl_codec_init(void* codec, uint32_t hunkbytes);
static void cdfl_codec_free(void* codec);
static chd_error cdfl_codec_decompress(void *codec, const uint8_t *src, uint32_t complen, uint8_t *dest, uint32_t destlen);
//**************************************************************************
// LZMA ALLOCATOR HELPER
//**************************************************************************
void *lzma_fast_alloc(void *p, size_t size);
void lzma_fast_free(void *p, void *address);
//-------------------------------------------------
// lzma_allocator_init
//-------------------------------------------------
void lzma_allocator_init(void* p)
{
lzma_allocator *codec = (lzma_allocator *)(p);
// reset pointer list
memset(codec->allocptr, 0, sizeof(codec->allocptr));
codec->Alloc = lzma_fast_alloc;
codec->Free = lzma_fast_free;
}
//-------------------------------------------------
// lzma_allocator_free
//-------------------------------------------------
void lzma_allocator_free(void* p )
{
int i;
lzma_allocator *codec = (lzma_allocator *)(p);
// free our memory
for (i = 0 ; i < MAX_LZMA_ALLOCS ; i++)
{
if (codec->allocptr[i] != NULL)
free(codec->allocptr[i]);
}
}
//-------------------------------------------------
// lzma_fast_alloc - fast malloc for lzma, which
// allocates and frees memory frequently
//-------------------------------------------------
void *lzma_fast_alloc(void *p, size_t size)
{
int scan;
uint32_t *addr = NULL;
lzma_allocator *codec = (lzma_allocator *)(p);
// compute the size, rounding to the nearest 1k
size = (size + 0x3ff) & ~0x3ff;
// reuse a hunk if we can
for (scan = 0; scan < MAX_LZMA_ALLOCS; scan++)
{
uint32_t *ptr = codec->allocptr[scan];
if (ptr != NULL && size == *ptr)
{
// set the low bit of the size so we don't match next time
*ptr |= 1;
return ptr + 1;
}
}
// alloc a new one and put it into the list
addr = (uint32_t *)malloc(sizeof(uint8_t) * (size + sizeof(uint32_t)));
if (addr==NULL)
return NULL;
for (scan = 0; scan < MAX_LZMA_ALLOCS; scan++)
{
if (codec->allocptr[scan] == NULL)
{
codec->allocptr[scan] = addr;
break;
}
}
// set the low bit of the size so we don't match next time
*addr = size | 1;
return addr + 1;
}
//-------------------------------------------------
// lzma_fast_free - fast free for lzma, which
// allocates and frees memory frequently
//-------------------------------------------------
void lzma_fast_free(void *p, void *address)
{
int scan;
uint32_t *ptr;
lzma_allocator *codec;
if (address == NULL)
return;
codec = (lzma_allocator *)(p);
// find the hunk
ptr = (uint32_t *)(address) - 1;
for (scan = 0; scan < MAX_LZMA_ALLOCS; scan++)
{
if (ptr == codec->allocptr[scan])
{
// clear the low bit of the size to allow matches
*ptr &= ~1;
return;
}
}
}
//**************************************************************************
// LZMA DECOMPRESSOR
//**************************************************************************
//-------------------------------------------------
// lzma_codec_init - constructor
//-------------------------------------------------
chd_error lzma_codec_init(void* codec, uint32_t hunkbytes)
{
CLzmaEncHandle enc;
CLzmaEncProps encoder_props;
Byte decoder_props[LZMA_PROPS_SIZE];
SizeT props_size;
lzma_allocator* alloc;
lzma_codec_data* lzma_codec = (lzma_codec_data*) codec;
// construct the decoder
LzmaDec_Construct(&lzma_codec->decoder);
// FIXME: this code is written in a way that makes it impossible to safely upgrade the LZMA SDK
// This code assumes that the current version of the encoder imposes the same requirements on the
// decoder as the encoder used to produce the file. This is not necessarily true. The format
// needs to be changed so the encoder properties are written to the file.
// configure the properties like the compressor did
LzmaEncProps_Init(&encoder_props);
encoder_props.level = 9;
encoder_props.reduceSize = hunkbytes;
LzmaEncProps_Normalize(&encoder_props);
// convert to decoder properties
alloc = &lzma_codec->allocator;
lzma_allocator_init(alloc);
enc = LzmaEnc_Create((ISzAlloc*)alloc);
if (!enc)
return CHDERR_DECOMPRESSION_ERROR;
if (LzmaEnc_SetProps(enc, &encoder_props) != SZ_OK)
{
LzmaEnc_Destroy(enc, (ISzAlloc*)&alloc, (ISzAlloc*)&alloc);
return CHDERR_DECOMPRESSION_ERROR;
}
props_size = sizeof(decoder_props);
if (LzmaEnc_WriteProperties(enc, decoder_props, &props_size) != SZ_OK)
{
LzmaEnc_Destroy(enc, (ISzAlloc*)alloc, (ISzAlloc*)alloc);
return CHDERR_DECOMPRESSION_ERROR;
}
LzmaEnc_Destroy(enc, (ISzAlloc*)alloc, (ISzAlloc*)alloc);
// do memory allocations
if (LzmaDec_Allocate(&lzma_codec->decoder, decoder_props, LZMA_PROPS_SIZE, (ISzAlloc*)alloc) != SZ_OK)
return CHDERR_DECOMPRESSION_ERROR;
// Okay
return CHDERR_NONE;
}
//-------------------------------------------------
// lzma_codec_free
//-------------------------------------------------
void lzma_codec_free(void* codec)
{
lzma_codec_data* lzma_codec = (lzma_codec_data*) codec;
// free memory
LzmaDec_Free(&lzma_codec->decoder, (ISzAlloc*)&lzma_codec->allocator);
}
//-------------------------------------------------
// decompress - decompress data using the LZMA
// codec
//-------------------------------------------------
chd_error lzma_codec_decompress(void* codec, const uint8_t *src, uint32_t complen, uint8_t *dest, uint32_t destlen)
{
ELzmaStatus status;
SRes res;
SizeT consumedlen, decodedlen;
// initialize
lzma_codec_data* lzma_codec = (lzma_codec_data*) codec;
LzmaDec_Init(&lzma_codec->decoder);
// decode
consumedlen = complen;
decodedlen = destlen;
res = LzmaDec_DecodeToBuf(&lzma_codec->decoder, dest, &decodedlen, src, &consumedlen, LZMA_FINISH_END, &status);
if ((res != SZ_OK && res != LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK) || consumedlen != complen || decodedlen != destlen)
return CHDERR_DECOMPRESSION_ERROR;
return CHDERR_NONE;
}
// cdlz
chd_error cdlz_codec_init(void* codec, uint32_t hunkbytes)
{
cdlz_codec_data* cdlz = (cdlz_codec_data*) codec;
// allocate buffer
cdlz->buffer = (uint8_t*)malloc(sizeof(uint8_t) * hunkbytes);
// make sure the CHD's hunk size is an even multiple of the frame size
lzma_codec_init(&cdlz->base_decompressor, (hunkbytes / CD_FRAME_SIZE) * CD_MAX_SECTOR_DATA);
zlib_codec_init(&cdlz->subcode_decompressor, (hunkbytes / CD_FRAME_SIZE) * CD_MAX_SUBCODE_DATA);
if (hunkbytes % CD_FRAME_SIZE != 0)
return CHDERR_CODEC_ERROR;
return CHDERR_NONE;
}
void cdlz_codec_free(void* codec)
{
// TODO
}
chd_error cdlz_codec_decompress(void *codec, const uint8_t *src, uint32_t complen, uint8_t *dest, uint32_t destlen)
{
uint32_t framenum;
cdlz_codec_data* cdlz = (cdlz_codec_data*)codec;
// determine header bytes
uint32_t frames = destlen / CD_FRAME_SIZE;
uint32_t complen_bytes = (destlen < 65536) ? 2 : 3;
uint32_t ecc_bytes = (frames + 7) / 8;
uint32_t header_bytes = ecc_bytes + complen_bytes;
// extract compressed length of base
uint32_t complen_base = (src[ecc_bytes + 0] << 8) | src[ecc_bytes + 1];
if (complen_bytes > 2)
complen_base = (complen_base << 8) | src[ecc_bytes + 2];
// reset and decode
lzma_codec_decompress(&cdlz->base_decompressor, &src[header_bytes], complen_base, &cdlz->buffer[0], frames * CD_MAX_SECTOR_DATA);
zlib_codec_decompress(&cdlz->subcode_decompressor, &src[header_bytes + complen_base], complen - complen_base - header_bytes, &cdlz->buffer[frames * CD_MAX_SECTOR_DATA], frames * CD_MAX_SUBCODE_DATA);
// reassemble the data
for (framenum = 0; framenum < frames; framenum++)
{
uint8_t *sector;
memcpy(&dest[framenum * CD_FRAME_SIZE], &cdlz->buffer[framenum * CD_MAX_SECTOR_DATA], CD_MAX_SECTOR_DATA);
memcpy(&dest[framenum * CD_FRAME_SIZE + CD_MAX_SECTOR_DATA], &cdlz->buffer[frames * CD_MAX_SECTOR_DATA + framenum * CD_MAX_SUBCODE_DATA], CD_MAX_SUBCODE_DATA);
// reconstitute the ECC data and sync header
sector = &dest[framenum * CD_FRAME_SIZE];
if ((src[framenum / 8] & (1 << (framenum % 8))) != 0)
{
memcpy(sector, s_cd_sync_header, sizeof(s_cd_sync_header));
ecc_generate(sector);
}
}
return CHDERR_NONE;
}
// cdzl
chd_error cdzl_codec_init(void *codec, uint32_t hunkbytes)
{
cdzl_codec_data* cdzl = (cdzl_codec_data*)codec;
// make sure the CHD's hunk size is an even multiple of the frame size
zlib_codec_init(&cdzl->base_decompressor, (hunkbytes / CD_FRAME_SIZE) * CD_MAX_SECTOR_DATA);
zlib_codec_init(&cdzl->subcode_decompressor, (hunkbytes / CD_FRAME_SIZE) * CD_MAX_SUBCODE_DATA);
cdzl->buffer = (uint8_t*)malloc(sizeof(uint8_t) * hunkbytes);
if (hunkbytes % CD_FRAME_SIZE != 0)
return CHDERR_CODEC_ERROR;
return CHDERR_NONE;
}
void cdzl_codec_free(void *codec)
{
// TODO
}
chd_error cdzl_codec_decompress(void *codec, const uint8_t *src, uint32_t complen, uint8_t *dest, uint32_t destlen)
{
uint32_t framenum;
cdzl_codec_data* cdzl = (cdzl_codec_data*)codec;
// determine header bytes
uint32_t frames = destlen / CD_FRAME_SIZE;
uint32_t complen_bytes = (destlen < 65536) ? 2 : 3;
uint32_t ecc_bytes = (frames + 7) / 8;
uint32_t header_bytes = ecc_bytes + complen_bytes;
// extract compressed length of base
uint32_t complen_base = (src[ecc_bytes + 0] << 8) | src[ecc_bytes + 1];
if (complen_bytes > 2)
complen_base = (complen_base << 8) | src[ecc_bytes + 2];
// reset and decode
zlib_codec_decompress(&cdzl->base_decompressor, &src[header_bytes], complen_base, &cdzl->buffer[0], frames * CD_MAX_SECTOR_DATA);
zlib_codec_decompress(&cdzl->subcode_decompressor, &src[header_bytes + complen_base], complen - complen_base - header_bytes, &cdzl->buffer[frames * CD_MAX_SECTOR_DATA], frames * CD_MAX_SUBCODE_DATA);
// reassemble the data
for (framenum = 0; framenum < frames; framenum++)
{
uint8_t *sector;
memcpy(&dest[framenum * CD_FRAME_SIZE], &cdzl->buffer[framenum * CD_MAX_SECTOR_DATA], CD_MAX_SECTOR_DATA);
memcpy(&dest[framenum * CD_FRAME_SIZE + CD_MAX_SECTOR_DATA], &cdzl->buffer[frames * CD_MAX_SECTOR_DATA + framenum * CD_MAX_SUBCODE_DATA], CD_MAX_SUBCODE_DATA);
// reconstitute the ECC data and sync header
sector = &dest[framenum * CD_FRAME_SIZE];
if ((src[framenum / 8] & (1 << (framenum % 8))) != 0)
{
memcpy(sector, s_cd_sync_header, sizeof(s_cd_sync_header));
ecc_generate(sector);
}
}
return CHDERR_NONE;
}
//**************************************************************************
// CD FLAC DECOMPRESSOR
//**************************************************************************
//------------------------------------------------------
// cdfl_codec_blocksize - return the optimal block size
//------------------------------------------------------
static uint32_t cdfl_codec_blocksize(uint32_t bytes)
{
// determine FLAC block size, which must be 16-65535
// clamp to 2k since that's supposed to be the sweet spot
uint32_t hunkbytes = bytes / 4;
while (hunkbytes > 2048)
hunkbytes /= 2;
return hunkbytes;
}
chd_error cdfl_codec_init(void *codec, uint32_t hunkbytes)
{
int zerr;
uint16_t native_endian = 0;
cdfl_codec_data *cdfl = (cdfl_codec_data*)codec;
cdfl->buffer = (uint8_t*)malloc(sizeof(uint8_t) * hunkbytes);
// make sure the CHD's hunk size is an even multiple of the frame size
if (hunkbytes % CD_FRAME_SIZE != 0)
return CHDERR_CODEC_ERROR;
// determine whether we want native or swapped samples
*(uint8_t *)(&native_endian) = 1;
cdfl->swap_endian = (native_endian & 1);
// init the inflater
cdfl->inflater.next_in = (Bytef *)cdfl; // bogus, but that's ok
cdfl->inflater.avail_in = 0;
//cdfl->allocator.install(cdfl->inflater);
cdfl->inflater.zalloc = zlib_fast_alloc;
cdfl->inflater.zfree = zlib_fast_free;
cdfl->inflater.opaque = &cdfl->allocator;
zerr = inflateInit2(&cdfl->inflater, -MAX_WBITS);
// convert errors
if (zerr == Z_MEM_ERROR)
return CHDERR_OUT_OF_MEMORY;
else if (zerr != Z_OK)
return CHDERR_CODEC_ERROR;
// init flac decoder
flac_decoder_init(&cdfl->decoder);
return CHDERR_NONE;
}
void cdfl_codec_free(void *codec)
{
cdfl_codec_data *cdfl = (cdfl_codec_data*)codec;
inflateEnd(&cdfl->inflater);
}
chd_error cdfl_codec_decompress(void *codec, const uint8_t *src, uint32_t complen, uint8_t *dest, uint32_t destlen)
{
int zerr;
uint8_t *buffer;
uint32_t framenum, offset;
cdfl_codec_data *cdfl = (cdfl_codec_data*)codec;
// reset and decode
uint32_t frames = destlen / CD_FRAME_SIZE;
if (!flac_decoder_reset(&cdfl->decoder, 44100, 2, cdfl_codec_blocksize(frames * CD_MAX_SECTOR_DATA), src, complen))
return CHDERR_DECOMPRESSION_ERROR;
buffer = &cdfl->buffer[0];
if (!flac_decoder_decode_interleaved(&cdfl->decoder, (int16_t *)(buffer), frames * CD_MAX_SECTOR_DATA/4, cdfl->swap_endian))
return CHDERR_DECOMPRESSION_ERROR;
// inflate the subcode data
offset = flac_decoder_finish(&cdfl->decoder);
cdfl->inflater.next_in = (Bytef *)(src + offset);
cdfl->inflater.avail_in = complen - offset;
cdfl->inflater.total_in = 0;
cdfl->inflater.next_out = &cdfl->buffer[frames * CD_MAX_SECTOR_DATA];
cdfl->inflater.avail_out = frames * CD_MAX_SUBCODE_DATA;
cdfl->inflater.total_out = 0;
zerr = inflateReset(&cdfl->inflater);
if (zerr != Z_OK)
return CHDERR_DECOMPRESSION_ERROR;
// do it
zerr = inflate(&cdfl->inflater, Z_FINISH);
if (zerr != Z_STREAM_END)
return CHDERR_DECOMPRESSION_ERROR;
if (cdfl->inflater.total_out != frames * CD_MAX_SUBCODE_DATA)
return CHDERR_DECOMPRESSION_ERROR;
// reassemble the data
for (framenum = 0; framenum < frames; framenum++)
{
memcpy(&dest[framenum * CD_FRAME_SIZE], &cdfl->buffer[framenum * CD_MAX_SECTOR_DATA], CD_MAX_SECTOR_DATA);
memcpy(&dest[framenum * CD_FRAME_SIZE + CD_MAX_SECTOR_DATA], &cdfl->buffer[frames * CD_MAX_SECTOR_DATA + framenum * CD_MAX_SUBCODE_DATA], CD_MAX_SUBCODE_DATA);
}
return CHDERR_NONE;
}
/***************************************************************************
CODEC INTERFACES
***************************************************************************/
#define CHD_MAKE_TAG(a,b,c,d) (((a) << 24) | ((b) << 16) | ((c) << 8) | (d))
// general codecs with CD frontend
#define CHD_CODEC_CD_ZLIB CHD_MAKE_TAG('c','d','z','l')
#define CHD_CODEC_CD_LZMA CHD_MAKE_TAG('c','d','l','z')
#define CHD_CODEC_CD_FLAC CHD_MAKE_TAG('c','d','f','l')
static const codec_interface codec_interfaces[] =
{
/* "none" or no compression */
{
CHDCOMPRESSION_NONE,
"none",
FALSE,
NULL,
NULL,
NULL,
NULL
},
/* standard zlib compression */
{
CHDCOMPRESSION_ZLIB,
"zlib",
FALSE,
zlib_codec_init,
zlib_codec_free,
zlib_codec_decompress,
NULL
},
/* zlib+ compression */
{
CHDCOMPRESSION_ZLIB_PLUS,
"zlib+",
FALSE,
zlib_codec_init,
zlib_codec_free,
zlib_codec_decompress,
NULL
},
/* V5 CD zlib compression */
{
CHD_CODEC_CD_ZLIB,
"cdzl (CD Deflate)",
FALSE,
cdzl_codec_init,
cdzl_codec_free,
cdzl_codec_decompress,
NULL
},
/* V5 CD lzma compression */
{
CHD_CODEC_CD_LZMA,
"cdlz (CD LZMA)",
FALSE,
cdlz_codec_init,
cdlz_codec_free,
cdlz_codec_decompress,
NULL
},
/* V5 CD flac compression */
{
CHD_CODEC_CD_FLAC,
"cdfl (CD FLAC)",
FALSE,
cdfl_codec_init,
cdfl_codec_free,
cdfl_codec_decompress,
NULL
},
};
/***************************************************************************
INLINE FUNCTIONS
***************************************************************************/
/*-------------------------------------------------
get_bigendian_uint64 - fetch a UINT64 from
the data stream in bigendian order
-------------------------------------------------*/
static INLINE UINT64 get_bigendian_uint64(const UINT8 *base)
{
return ((UINT64)base[0] << 56) | ((UINT64)base[1] << 48) | ((UINT64)base[2] << 40) | ((UINT64)base[3] << 32) |
((UINT64)base[4] << 24) | ((UINT64)base[5] << 16) | ((UINT64)base[6] << 8) | (UINT64)base[7];
}
/*-------------------------------------------------
put_bigendian_uint64 - write a UINT64 to
the data stream in bigendian order
-------------------------------------------------*/
static INLINE void put_bigendian_uint64(UINT8 *base, UINT64 value)
{
base[0] = value >> 56;
base[1] = value >> 48;
base[2] = value >> 40;
base[3] = value >> 32;
base[4] = value >> 24;
base[5] = value >> 16;
base[6] = value >> 8;
base[7] = value;
}
/*-------------------------------------------------
get_bigendian_uint48 - fetch a UINT48 from
the data stream in bigendian order
-------------------------------------------------*/
static INLINE UINT64 get_bigendian_uint48(const UINT8 *base)
{
return ((UINT64)base[0] << 40) | ((UINT64)base[1] << 32) |
((UINT64)base[2] << 24) | ((UINT64)base[3] << 16) | ((UINT64)base[4] << 8) | (UINT64)base[5];
}
/*-------------------------------------------------
put_bigendian_uint48 - write a UINT48 to
the data stream in bigendian order
-------------------------------------------------*/
static INLINE void put_bigendian_uint48(UINT8 *base, UINT64 value)
{
value &= 0xffffffffffff;
base[0] = value >> 40;
base[1] = value >> 32;
base[2] = value >> 24;
base[3] = value >> 16;
base[4] = value >> 8;
base[5] = value;
}
/*-------------------------------------------------
get_bigendian_uint32 - fetch a UINT32 from
the data stream in bigendian order
-------------------------------------------------*/
static INLINE UINT32 get_bigendian_uint32(const UINT8 *base)
{
return (base[0] << 24) | (base[1] << 16) | (base[2] << 8) | base[3];
}
/*-------------------------------------------------
put_bigendian_uint32 - write a UINT32 to
the data stream in bigendian order
-------------------------------------------------*/
static INLINE void put_bigendian_uint24(UINT8 *base, UINT32 value)
{
value &= 0xffffff;
base[0] = value >> 16;
base[1] = value >> 8;
base[2] = value;
}
/*-------------------------------------------------
put_bigendian_uint24 - write a UINT24 to
the data stream in bigendian order
-------------------------------------------------*/
static INLINE void put_bigendian_uint32(UINT8 *base, UINT32 value)
{
value &= 0xffffff;
base[0] = value >> 16;