From 38b5dd6e3fd26a0c6fa7192416a90ee786a6b9bb Mon Sep 17 00:00:00 2001 From: Christopher Snowhill Date: Mon, 6 Apr 2020 23:29:07 -0700 Subject: [PATCH] Updated VGMStream to r1050-2895-g772fe03e --- .../libvgmstream.xcodeproj/project.pbxproj | 76 +- .../vgmstream/src/coding/asf_decoder.c | 5 + .../vgmstream/src/coding/circus_decoder.c | 138 +- .../vgmstream/src/coding/circus_decoder_lib.c | 492 ++ .../vgmstream/src/coding/circus_decoder_lib.h | 16 + .../src/coding/circus_decoder_lib_data.h | 347 + .../src/coding/circus_decoder_lzxpcm.h | 297 + .../src/coding/circus_decoder_miniz.c | 7657 +++++++++++++++++ .../src/coding/circus_decoder_miniz.h | 1346 +++ .../vgmstream/vgmstream/src/coding/coding.h | 11 +- .../vgmstream/src/coding/ima_decoder.c | 11 +- .../vgmstream/src/coding/psv_decoder.c | 20 +- .../vgmstream/src/coding/psx_decoder.c | 33 +- .../src/coding/vorbis_custom_utils_vid1.c | 297 +- Frameworks/vgmstream/vgmstream/src/formats.c | 19 +- .../vgmstream/vgmstream/src/layout/blocked.c | 6 + .../vgmstream/src/layout/blocked_ubi_sce.c | 57 + .../vgmstream/src/layout/blocked_vid1.c | 61 + .../vgmstream/vgmstream/src/layout/layout.h | 2 + .../vgmstream/vgmstream/src/meta/Cstr.c | 338 +- .../vgmstream/vgmstream/src/meta/adx_keys.h | 5 +- Frameworks/vgmstream/vgmstream/src/meta/awc.c | 31 +- .../vgmstream/src/meta/awc_xma_streamfile.h | 359 +- .../vgmstream/vgmstream/src/meta/bkhd.c | 126 + .../vgmstream/vgmstream/src/meta/bnk_sony.c | 193 +- .../vgmstream/vgmstream/src/meta/bnsf.c | 6 +- .../vgmstream/src/meta/deblock_streamfile.c | 5 +- .../vgmstream/vgmstream/src/meta/ea_eaac.c | 4 +- .../vgmstream/vgmstream/src/meta/encrypted.c | 86 + .../vgmstream/vgmstream/src/meta/fsb5.c | 1258 +-- .../src/meta/fsb5_interleave_streamfile.h | 201 - .../vgmstream/src/meta/fsb5_streamfile.h | 21 + .../vgmstream/vgmstream/src/meta/hca_keys.h | 1 + Frameworks/vgmstream/vgmstream/src/meta/isb.c | 118 +- .../vgmstream/vgmstream/src/meta/meta.h | 7 +- Frameworks/vgmstream/vgmstream/src/meta/mp4.c | 2 - Frameworks/vgmstream/vgmstream/src/meta/mul.c | 433 +- .../vgmstream/src/meta/mul_streamfile.h | 65 + .../vgmstream/vgmstream/src/meta/ngc_vid1.c | 75 - Frameworks/vgmstream/vgmstream/src/meta/nps.c | 52 +- .../vgmstream/vgmstream/src/meta/ogg_opus.c | 5 +- .../vgmstream/vgmstream/src/meta/opus.c | 10 +- .../src/meta/opus_interleave_streamfile.h | 183 +- .../vgmstream/vgmstream/src/meta/riff.c | 13 +- .../vgmstream/vgmstream/src/meta/sqex_sead.c | 888 +- .../vgmstream/src/meta/sqex_sead_streamfile.h | 153 +- .../vgmstream/vgmstream/src/meta/txth.c | 53 +- .../vgmstream/vgmstream/src/meta/ubi_ckd.c | 175 +- .../vgmstream/vgmstream/src/meta/ubi_lyn.c | 55 +- .../src/meta/ubi_lyn_ogg_streamfile.h | 92 - .../vgmstream/src/meta/ubi_lyn_streamfile.h | 23 + .../vgmstream/vgmstream/src/meta/ubi_sb.c | 42 +- .../vgmstream/vgmstream/src/meta/vid1.c | 135 + Frameworks/vgmstream/vgmstream/src/meta/vpk.c | 10 +- .../vgmstream/vgmstream/src/meta/wwise.c | 13 +- Frameworks/vgmstream/vgmstream/src/meta/xnb.c | 433 +- .../vgmstream/vgmstream/src/meta/xnb_lz4mg.h | 266 + .../vgmstream/src/meta/xnb_streamfile.h | 300 + .../vgmstream/vgmstream/src/meta/xpcm.c | 151 +- .../src/meta/xwma_konami_streamfile.h | 151 +- .../vgmstream/vgmstream/src/streamfile.c | 60 +- .../vgmstream/vgmstream/src/streamfile.h | 11 +- .../vgmstream/vgmstream/src/vgmstream.c | 31 +- .../vgmstream/vgmstream/src/vgmstream.h | 7 +- 64 files changed, 14431 insertions(+), 3106 deletions(-) create mode 100644 Frameworks/vgmstream/vgmstream/src/coding/circus_decoder_lib.c create mode 100644 Frameworks/vgmstream/vgmstream/src/coding/circus_decoder_lib.h create mode 100644 Frameworks/vgmstream/vgmstream/src/coding/circus_decoder_lib_data.h create mode 100644 Frameworks/vgmstream/vgmstream/src/coding/circus_decoder_lzxpcm.h create mode 100644 Frameworks/vgmstream/vgmstream/src/coding/circus_decoder_miniz.c create mode 100644 Frameworks/vgmstream/vgmstream/src/coding/circus_decoder_miniz.h create mode 100644 Frameworks/vgmstream/vgmstream/src/layout/blocked_ubi_sce.c create mode 100644 Frameworks/vgmstream/vgmstream/src/layout/blocked_vid1.c create mode 100644 Frameworks/vgmstream/vgmstream/src/meta/bkhd.c create mode 100644 Frameworks/vgmstream/vgmstream/src/meta/encrypted.c delete mode 100644 Frameworks/vgmstream/vgmstream/src/meta/fsb5_interleave_streamfile.h create mode 100644 Frameworks/vgmstream/vgmstream/src/meta/fsb5_streamfile.h create mode 100644 Frameworks/vgmstream/vgmstream/src/meta/mul_streamfile.h delete mode 100644 Frameworks/vgmstream/vgmstream/src/meta/ngc_vid1.c delete mode 100644 Frameworks/vgmstream/vgmstream/src/meta/ubi_lyn_ogg_streamfile.h create mode 100644 Frameworks/vgmstream/vgmstream/src/meta/ubi_lyn_streamfile.h create mode 100644 Frameworks/vgmstream/vgmstream/src/meta/vid1.c create mode 100644 Frameworks/vgmstream/vgmstream/src/meta/xnb_lz4mg.h create mode 100644 Frameworks/vgmstream/vgmstream/src/meta/xnb_streamfile.h diff --git a/Frameworks/vgmstream/libvgmstream.xcodeproj/project.pbxproj b/Frameworks/vgmstream/libvgmstream.xcodeproj/project.pbxproj index 184731c31..ffaa23a9a 100644 --- a/Frameworks/vgmstream/libvgmstream.xcodeproj/project.pbxproj +++ b/Frameworks/vgmstream/libvgmstream.xcodeproj/project.pbxproj @@ -11,6 +11,22 @@ 8301659A1F256BD000CA0941 /* txth.c in Sources */ = {isa = PBXBuildFile; fileRef = 830165971F256BD000CA0941 /* txth.c */; }; 8301659B1F256BD000CA0941 /* ea_schl_fixed.c in Sources */ = {isa = PBXBuildFile; fileRef = 830165981F256BD000CA0941 /* ea_schl_fixed.c */; }; 8301659C1F256BD000CA0941 /* nds_strm_ffta2.c in Sources */ = {isa = PBXBuildFile; fileRef = 830165991F256BD000CA0941 /* nds_strm_ffta2.c */; }; + 83031EC4243C50A800C3F3E0 /* circus_decoder_miniz.h in Headers */ = {isa = PBXBuildFile; fileRef = 83031EBE243C50A700C3F3E0 /* circus_decoder_miniz.h */; }; + 83031EC5243C50A800C3F3E0 /* circus_decoder_lib_data.h in Headers */ = {isa = PBXBuildFile; fileRef = 83031EBF243C50A800C3F3E0 /* circus_decoder_lib_data.h */; }; + 83031EC6243C50A800C3F3E0 /* circus_decoder_miniz.c in Sources */ = {isa = PBXBuildFile; fileRef = 83031EC0243C50A800C3F3E0 /* circus_decoder_miniz.c */; }; + 83031EC7243C50A800C3F3E0 /* circus_decoder_lib.h in Headers */ = {isa = PBXBuildFile; fileRef = 83031EC1243C50A800C3F3E0 /* circus_decoder_lib.h */; }; + 83031EC8243C50A800C3F3E0 /* circus_decoder_lib.c in Sources */ = {isa = PBXBuildFile; fileRef = 83031EC2243C50A800C3F3E0 /* circus_decoder_lib.c */; }; + 83031EC9243C50A800C3F3E0 /* circus_decoder_lzxpcm.h in Headers */ = {isa = PBXBuildFile; fileRef = 83031EC3243C50A800C3F3E0 /* circus_decoder_lzxpcm.h */; }; + 83031ECC243C50CC00C3F3E0 /* blocked_ubi_sce.c in Sources */ = {isa = PBXBuildFile; fileRef = 83031ECA243C50CB00C3F3E0 /* blocked_ubi_sce.c */; }; + 83031ECD243C50CC00C3F3E0 /* blocked_vid1.c in Sources */ = {isa = PBXBuildFile; fileRef = 83031ECB243C50CB00C3F3E0 /* blocked_vid1.c */; }; + 83031ED1243C50DF00C3F3E0 /* encrypted.c in Sources */ = {isa = PBXBuildFile; fileRef = 83031ECE243C50DE00C3F3E0 /* encrypted.c */; }; + 83031ED2243C50DF00C3F3E0 /* bkhd.c in Sources */ = {isa = PBXBuildFile; fileRef = 83031ECF243C50DE00C3F3E0 /* bkhd.c */; }; + 83031ED3243C50DF00C3F3E0 /* fsb5_streamfile.h in Headers */ = {isa = PBXBuildFile; fileRef = 83031ED0243C50DF00C3F3E0 /* fsb5_streamfile.h */; }; + 83031ED9243C510500C3F3E0 /* ubi_lyn_streamfile.h in Headers */ = {isa = PBXBuildFile; fileRef = 83031ED4243C510400C3F3E0 /* ubi_lyn_streamfile.h */; }; + 83031EDA243C510500C3F3E0 /* mul_streamfile.h in Headers */ = {isa = PBXBuildFile; fileRef = 83031ED5243C510400C3F3E0 /* mul_streamfile.h */; }; + 83031EDB243C510500C3F3E0 /* xnb_lz4mg.h in Headers */ = {isa = PBXBuildFile; fileRef = 83031ED6243C510400C3F3E0 /* xnb_lz4mg.h */; }; + 83031EDC243C510500C3F3E0 /* vid1.c in Sources */ = {isa = PBXBuildFile; fileRef = 83031ED7243C510400C3F3E0 /* vid1.c */; }; + 83031EDD243C510500C3F3E0 /* xnb_streamfile.h in Headers */ = {isa = PBXBuildFile; fileRef = 83031ED8243C510500C3F3E0 /* xnb_streamfile.h */; }; 8306B08420984518000302D4 /* at3plus_decoder.c in Sources */ = {isa = PBXBuildFile; fileRef = 8306B08120984517000302D4 /* at3plus_decoder.c */; }; 8306B08520984518000302D4 /* yamaha_decoder.c in Sources */ = {isa = PBXBuildFile; fileRef = 8306B08220984517000302D4 /* yamaha_decoder.c */; }; 8306B08620984518000302D4 /* fadpcm_decoder.c in Sources */ = {isa = PBXBuildFile; fileRef = 8306B08320984517000302D4 /* fadpcm_decoder.c */; }; @@ -48,7 +64,6 @@ 8306B0DE20984590000302D4 /* awc_xma_streamfile.h in Headers */ = {isa = PBXBuildFile; fileRef = 8306B0C32098458C000302D4 /* awc_xma_streamfile.h */; }; 8306B0DF20984590000302D4 /* ea_wve_ad10.c in Sources */ = {isa = PBXBuildFile; fileRef = 8306B0C42098458D000302D4 /* ea_wve_ad10.c */; }; 8306B0E020984590000302D4 /* ppst_streamfile.h in Headers */ = {isa = PBXBuildFile; fileRef = 8306B0C52098458D000302D4 /* ppst_streamfile.h */; }; - 8306B0E120984590000302D4 /* ubi_lyn_ogg_streamfile.h in Headers */ = {isa = PBXBuildFile; fileRef = 8306B0C62098458D000302D4 /* ubi_lyn_ogg_streamfile.h */; }; 8306B0E220984590000302D4 /* smv.c in Sources */ = {isa = PBXBuildFile; fileRef = 8306B0C72098458D000302D4 /* smv.c */; }; 8306B0E420984590000302D4 /* wave.c in Sources */ = {isa = PBXBuildFile; fileRef = 8306B0C92098458E000302D4 /* wave.c */; }; 8306B0E520984590000302D4 /* ubi_lyn.c in Sources */ = {isa = PBXBuildFile; fileRef = 8306B0CA2098458E000302D4 /* ubi_lyn.c */; }; @@ -140,7 +155,6 @@ 8349A9101FE6258200E26435 /* ea_eaac.c in Sources */ = {isa = PBXBuildFile; fileRef = 8349A8F71FE6257E00E26435 /* ea_eaac.c */; }; 8349A9111FE6258200E26435 /* bar_streamfile.h in Headers */ = {isa = PBXBuildFile; fileRef = 8349A8F81FE6257E00E26435 /* bar_streamfile.h */; }; 8349A9121FE6258200E26435 /* vsf_tta.c in Sources */ = {isa = PBXBuildFile; fileRef = 8349A8F91FE6257E00E26435 /* vsf_tta.c */; }; - 8349A9131FE6258200E26435 /* ngc_vid1.c in Sources */ = {isa = PBXBuildFile; fileRef = 8349A8FA1FE6257E00E26435 /* ngc_vid1.c */; }; 8349A9141FE6258200E26435 /* omu.c in Sources */ = {isa = PBXBuildFile; fileRef = 8349A8FB1FE6257F00E26435 /* omu.c */; }; 8349A9151FE6258200E26435 /* ps2_xa2_rrp.c in Sources */ = {isa = PBXBuildFile; fileRef = 8349A8FC1FE6257F00E26435 /* ps2_xa2_rrp.c */; }; 8349A9161FE6258200E26435 /* flx.c in Sources */ = {isa = PBXBuildFile; fileRef = 8349A8FD1FE6257F00E26435 /* flx.c */; }; @@ -197,7 +211,6 @@ 834FE107215C79ED000A5D3D /* mib_mih.c in Sources */ = {isa = PBXBuildFile; fileRef = 834FE0DE215C79EB000A5D3D /* mib_mih.c */; }; 834FE108215C79ED000A5D3D /* hd3_bd3.c in Sources */ = {isa = PBXBuildFile; fileRef = 834FE0DF215C79EB000A5D3D /* hd3_bd3.c */; }; 834FE109215C79ED000A5D3D /* idsp_ie.c in Sources */ = {isa = PBXBuildFile; fileRef = 834FE0E0215C79EB000A5D3D /* idsp_ie.c */; }; - 834FE10C215C79ED000A5D3D /* fsb5_interleave_streamfile.h in Headers */ = {isa = PBXBuildFile; fileRef = 834FE0E3215C79EC000A5D3D /* fsb5_interleave_streamfile.h */; }; 834FE10D215C79ED000A5D3D /* vag.c in Sources */ = {isa = PBXBuildFile; fileRef = 834FE0E4215C79EC000A5D3D /* vag.c */; }; 834FE10E215C79ED000A5D3D /* ahv.c in Sources */ = {isa = PBXBuildFile; fileRef = 834FE0E5215C79EC000A5D3D /* ahv.c */; }; 834FE10F215C79ED000A5D3D /* sdf.c in Sources */ = {isa = PBXBuildFile; fileRef = 834FE0E6215C79EC000A5D3D /* sdf.c */; }; @@ -702,6 +715,22 @@ 830165971F256BD000CA0941 /* txth.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = txth.c; sourceTree = ""; }; 830165981F256BD000CA0941 /* ea_schl_fixed.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ea_schl_fixed.c; sourceTree = ""; }; 830165991F256BD000CA0941 /* nds_strm_ffta2.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = nds_strm_ffta2.c; sourceTree = ""; }; + 83031EBE243C50A700C3F3E0 /* circus_decoder_miniz.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = circus_decoder_miniz.h; sourceTree = ""; }; + 83031EBF243C50A800C3F3E0 /* circus_decoder_lib_data.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = circus_decoder_lib_data.h; sourceTree = ""; }; + 83031EC0243C50A800C3F3E0 /* circus_decoder_miniz.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = circus_decoder_miniz.c; sourceTree = ""; }; + 83031EC1243C50A800C3F3E0 /* circus_decoder_lib.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = circus_decoder_lib.h; sourceTree = ""; }; + 83031EC2243C50A800C3F3E0 /* circus_decoder_lib.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = circus_decoder_lib.c; sourceTree = ""; }; + 83031EC3243C50A800C3F3E0 /* circus_decoder_lzxpcm.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = circus_decoder_lzxpcm.h; sourceTree = ""; }; + 83031ECA243C50CB00C3F3E0 /* blocked_ubi_sce.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = blocked_ubi_sce.c; sourceTree = ""; }; + 83031ECB243C50CB00C3F3E0 /* blocked_vid1.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = blocked_vid1.c; sourceTree = ""; }; + 83031ECE243C50DE00C3F3E0 /* encrypted.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = encrypted.c; sourceTree = ""; }; + 83031ECF243C50DE00C3F3E0 /* bkhd.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = bkhd.c; sourceTree = ""; }; + 83031ED0243C50DF00C3F3E0 /* fsb5_streamfile.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = fsb5_streamfile.h; sourceTree = ""; }; + 83031ED4243C510400C3F3E0 /* ubi_lyn_streamfile.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ubi_lyn_streamfile.h; sourceTree = ""; }; + 83031ED5243C510400C3F3E0 /* mul_streamfile.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = mul_streamfile.h; sourceTree = ""; }; + 83031ED6243C510400C3F3E0 /* xnb_lz4mg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = xnb_lz4mg.h; sourceTree = ""; }; + 83031ED7243C510400C3F3E0 /* vid1.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = vid1.c; sourceTree = ""; }; + 83031ED8243C510500C3F3E0 /* xnb_streamfile.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = xnb_streamfile.h; sourceTree = ""; }; 8306B08120984517000302D4 /* at3plus_decoder.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = at3plus_decoder.c; sourceTree = ""; }; 8306B08220984517000302D4 /* yamaha_decoder.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = yamaha_decoder.c; sourceTree = ""; }; 8306B08320984517000302D4 /* fadpcm_decoder.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = fadpcm_decoder.c; sourceTree = ""; }; @@ -739,7 +768,6 @@ 8306B0C32098458C000302D4 /* awc_xma_streamfile.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = awc_xma_streamfile.h; sourceTree = ""; }; 8306B0C42098458D000302D4 /* ea_wve_ad10.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ea_wve_ad10.c; sourceTree = ""; }; 8306B0C52098458D000302D4 /* ppst_streamfile.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ppst_streamfile.h; sourceTree = ""; }; - 8306B0C62098458D000302D4 /* ubi_lyn_ogg_streamfile.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ubi_lyn_ogg_streamfile.h; sourceTree = ""; }; 8306B0C72098458D000302D4 /* smv.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = smv.c; sourceTree = ""; }; 8306B0C92098458E000302D4 /* wave.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = wave.c; sourceTree = ""; }; 8306B0CA2098458E000302D4 /* ubi_lyn.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ubi_lyn.c; sourceTree = ""; }; @@ -830,7 +858,6 @@ 8349A8F71FE6257E00E26435 /* ea_eaac.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ea_eaac.c; sourceTree = ""; }; 8349A8F81FE6257E00E26435 /* bar_streamfile.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = bar_streamfile.h; sourceTree = ""; }; 8349A8F91FE6257E00E26435 /* vsf_tta.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = vsf_tta.c; sourceTree = ""; }; - 8349A8FA1FE6257E00E26435 /* ngc_vid1.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ngc_vid1.c; sourceTree = ""; }; 8349A8FB1FE6257F00E26435 /* omu.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = omu.c; sourceTree = ""; }; 8349A8FC1FE6257F00E26435 /* ps2_xa2_rrp.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ps2_xa2_rrp.c; sourceTree = ""; }; 8349A8FD1FE6257F00E26435 /* flx.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = flx.c; sourceTree = ""; }; @@ -886,7 +913,6 @@ 834FE0DE215C79EB000A5D3D /* mib_mih.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = mib_mih.c; sourceTree = ""; }; 834FE0DF215C79EB000A5D3D /* hd3_bd3.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = hd3_bd3.c; sourceTree = ""; }; 834FE0E0215C79EB000A5D3D /* idsp_ie.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = idsp_ie.c; sourceTree = ""; }; - 834FE0E3215C79EC000A5D3D /* fsb5_interleave_streamfile.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = fsb5_interleave_streamfile.h; sourceTree = ""; }; 834FE0E4215C79EC000A5D3D /* vag.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = vag.c; sourceTree = ""; }; 834FE0E5215C79EC000A5D3D /* ahv.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ahv.c; sourceTree = ""; }; 834FE0E6215C79EC000A5D3D /* sdf.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = sdf.c; sourceTree = ""; }; @@ -1437,6 +1463,12 @@ 8306B08120984517000302D4 /* at3plus_decoder.c */, 830EBE0F2004655D0023AA10 /* atrac9_decoder.c */, 834FE0B2215C798C000A5D3D /* celt_fsb_decoder.c */, + 83031EBF243C50A800C3F3E0 /* circus_decoder_lib_data.h */, + 83031EC2243C50A800C3F3E0 /* circus_decoder_lib.c */, + 83031EC1243C50A800C3F3E0 /* circus_decoder_lib.h */, + 83031EC3243C50A800C3F3E0 /* circus_decoder_lzxpcm.h */, + 83031EC0243C50A800C3F3E0 /* circus_decoder_miniz.c */, + 83031EBE243C50A700C3F3E0 /* circus_decoder_miniz.h */, 832BF7FC21E050B6006F50F1 /* circus_decoder.c */, 831BA6221EAC61CB00CF89B0 /* coding_utils.c */, 836F6DE518BDC2180095E648 /* coding.h */, @@ -1540,8 +1572,10 @@ 8306B09C20984550000302D4 /* blocked_str_snds.c */, 8306B09820984550000302D4 /* blocked_thp.c */, 8306B09920984550000302D4 /* blocked_tra.c */, + 83031ECA243C50CB00C3F3E0 /* blocked_ubi_sce.c */, 8349A8E61FE6253900E26435 /* blocked_vawx.c */, 83AA5D1A1F6E2F7F0020821C /* blocked_vgs.c */, + 83031ECB243C50CB00C3F3E0 /* blocked_vid1.c */, 832BF80321E050DC006F50F1 /* blocked_vs_square.c */, 832BF80421E050DC006F50F1 /* blocked_vs_str.c */, 8306B0A120984551000302D4 /* blocked_vs.c */, @@ -1605,6 +1639,7 @@ 837CEAD723487E8300E62A4A /* bgw_streamfile.h */, 836F6E3818BDC2180095E648 /* bgw.c */, 83299FCE1E7660C7003A3242 /* bik.c */, + 83031ECF243C50DE00C3F3E0 /* bkhd.c */, 837CEAD423487E8300E62A4A /* bmp_konami.c */, 834FE0CA215C79E7000A5D3D /* bnk_sony.c */, 8373342523F60CDC00DE14DC /* bnsf_keys.h */, @@ -1643,6 +1678,7 @@ 83EED5D1203A8BC7008BEB45 /* ea_swvr.c */, 8306B0C42098458D000302D4 /* ea_wve_ad10.c */, 8306B0BF2098458C000302D4 /* ea_wve_au00.c */, + 83031ECE243C50DE00C3F3E0 /* encrypted.c */, 836F6E4918BDC2180095E648 /* exakt_sc.c */, 836F6E4A18BDC2180095E648 /* excitebots.c */, 8349A8EF1FE6257C00E26435 /* ezw.c */, @@ -1657,7 +1693,7 @@ 83A21F7E201D8980000F04B9 /* fsb_keys.h */, 836F6E4C18BDC2180095E648 /* fsb.c */, 83C7280522BC893B00678B4A /* fsb5_fev.c */, - 834FE0E3215C79EC000A5D3D /* fsb5_interleave_streamfile.h */, + 83031ED0243C50DF00C3F3E0 /* fsb5_streamfile.h */, 83F5F8821908D0A400C8E65F /* fsb5.c */, 8373342323F60CDB00DE14DC /* fwse.c */, 834D3A6D19F47C98001C54F6 /* g1l.c */, @@ -1714,6 +1750,7 @@ 83C7280E22BC893D00678B4A /* mta2_streamfile.h */, 83C727FF22BC893900678B4A /* mta2.c */, 83C7280322BC893A00678B4A /* mtaf.c */, + 83031ED5243C510400C3F3E0 /* mul_streamfile.h */, 832BF81221E05149006F50F1 /* mul.c */, 836F6E6218BDC2180095E648 /* mus_acm.c */, 83C7280622BC893B00678B4A /* mus_vc.c */, @@ -1747,7 +1784,6 @@ 8306B0BE2098458C000302D4 /* ngc_str_cauldron.c */, 836F6E7C18BDC2180095E648 /* ngc_tydsp.c */, 831BD11F1EEE1CF200198540 /* ngc_ulw.c */, - 8349A8FA1FE6257E00E26435 /* ngc_vid1.c */, 836F6E7E18BDC2180095E648 /* ngc_ymf.c */, 836F6E7F18BDC2180095E648 /* ngca.c */, 83C727FC22BC893900678B4A /* nps.c */, @@ -1906,7 +1942,7 @@ 836F6EFC18BDC2190095E648 /* ubi_ckd.c */, 837CEAE023487F2A00E62A4A /* ubi_hx.c */, 8306B0D720984590000302D4 /* ubi_jade.c */, - 8306B0C62098458D000302D4 /* ubi_lyn_ogg_streamfile.h */, + 83031ED4243C510400C3F3E0 /* ubi_lyn_streamfile.h */, 8306B0CA2098458E000302D4 /* ubi_lyn.c */, 831BA6131EAC61A500CF89B0 /* ubi_raki.c */, 8375737521F950EC00F01AF5 /* ubi_sb_streamfile.h */, @@ -1917,6 +1953,7 @@ 834FE0D3215C79E9000A5D3D /* vai.c */, 831BA6141EAC61A500CF89B0 /* vawx.c */, 836F6EFD18BDC2190095E648 /* vgs.c */, + 83031ED7243C510400C3F3E0 /* vid1.c */, 834FE0CE215C79E8000A5D3D /* vis.c */, 834FE0D4215C79E9000A5D3D /* vpk.c */, 832BF81821E0514A006F50F1 /* vs_square.c */, @@ -1960,6 +1997,8 @@ 834FE0DC215C79EA000A5D3D /* xmd.c */, 837CEAEC23487F2C00E62A4A /* xmu.c */, 837CEAE323487F2A00E62A4A /* xmv_valve.c */, + 83031ED6243C510400C3F3E0 /* xnb_lz4mg.h */, + 83031ED8243C510500C3F3E0 /* xnb_streamfile.h */, 830EBE112004656E0023AA10 /* xnb.c */, 832BF81921E0514A006F50F1 /* xopus.c */, 832BF80A21E05148006F50F1 /* xpcm.c */, @@ -2012,6 +2051,7 @@ files = ( 836F705518BDC2190095E648 /* streamtypes.h in Headers */, 836F6F3518BDC2190095E648 /* nwa_decoder.h in Headers */, + 83031EC9243C50A800C3F3E0 /* circus_decoder_lzxpcm.h in Headers */, 83C7282222BC893D00678B4A /* mta2_streamfile.h in Headers */, 83A21F87201D8981000F04B9 /* fsb_keys.h in Headers */, 834FE0EC215C79ED000A5D3D /* kma9_streamfile.h in Headers */, @@ -2031,6 +2071,7 @@ 832BF82021E0514B006F50F1 /* zsnd_streamfile.h in Headers */, 8375737721F950ED00F01AF5 /* ubi_sb_streamfile.h in Headers */, 839E21E01F2EDAF100EE54D7 /* vorbis_custom_data_fsb.h in Headers */, + 83031EDB243C510500C3F3E0 /* xnb_lz4mg.h in Headers */, 836F705418BDC2190095E648 /* streamfile.h in Headers */, 83A3F0761E3AD8B900D6A794 /* stack_alloc.h in Headers */, 8373342723F60CDC00DE14DC /* lrmd_streamfile.h in Headers */, @@ -2039,15 +2080,14 @@ 83C7280F22BC893D00678B4A /* xwb_xsb.h in Headers */, 83C7281622BC893D00678B4A /* xwma_konami_streamfile.h in Headers */, 839E21E81F2EDAF100EE54D7 /* mpeg_decoder.h in Headers */, - 834FE10C215C79ED000A5D3D /* fsb5_interleave_streamfile.h in Headers */, 839E21E51F2EDAF100EE54D7 /* vorbis_custom_decoder.h in Headers */, 837CEADB23487E8300E62A4A /* bgw_streamfile.h in Headers */, 837CEB0323487F2C00E62A4A /* xavs_streamfile.h in Headers */, - 8306B0E120984590000302D4 /* ubi_lyn_ogg_streamfile.h in Headers */, 836F705918BDC2190095E648 /* vgmstream.h in Headers */, 8373342623F60CDC00DE14DC /* deblock_streamfile.h in Headers */, 83C7281522BC893D00678B4A /* txth_streamfile.h in Headers */, 8306B0DE20984590000302D4 /* awc_xma_streamfile.h in Headers */, + 83031EC5243C50A800C3F3E0 /* circus_decoder_lib_data.h in Headers */, 834FE0B5215C798C000A5D3D /* acm_decoder_libacm.h in Headers */, 839E21E61F2EDAF100EE54D7 /* vorbis_custom_data_wwise.h in Headers */, 8373342D23F60CDC00DE14DC /* bnsf_keys.h in Headers */, @@ -2059,19 +2099,25 @@ 836F6F9A18BDC2190095E648 /* meta.h in Headers */, 8306B0D820984590000302D4 /* ea_eaac_streamfile.h in Headers */, 837CEB0523487F2C00E62A4A /* sqex_sead_streamfile.h in Headers */, + 83031ED9243C510500C3F3E0 /* ubi_lyn_streamfile.h in Headers */, 8373341D23F60C7B00DE14DC /* g7221_decoder_lib.h in Headers */, 8306B0E820984590000302D4 /* opus_interleave_streamfile.h in Headers */, + 83031EDD243C510500C3F3E0 /* xnb_streamfile.h in Headers */, 8373341623F60C7B00DE14DC /* g7221_decoder_aes.h in Headers */, 8373341923F60C7B00DE14DC /* g7221_decoder_lib_data.h in Headers */, 83AFABBD23795202002F3947 /* ea_eaac_opus_streamfile.h in Headers */, + 83031EDA243C510500C3F3E0 /* mul_streamfile.h in Headers */, 83C7281822BC893D00678B4A /* sfh_streamfile.h in Headers */, 834FE0EF215C79ED000A5D3D /* xvag_streamfile.h in Headers */, 8349A90C1FE6258200E26435 /* sqex_scd_streamfile.h in Headers */, 837CEAF323487F2C00E62A4A /* mzrt_streamfile.h in Headers */, + 83031EC4243C50A800C3F3E0 /* circus_decoder_miniz.h in Headers */, 8349A91B1FE6258200E26435 /* adx_keys.h in Headers */, 836F6F4D18BDC2190095E648 /* layout.h in Headers */, 83269DD22399F5DE00F49FE3 /* nus3bank_streamfile.h in Headers */, 83AA5D251F6E2F9C0020821C /* hca_keys.h in Headers */, + 83031EC7243C50A800C3F3E0 /* circus_decoder_lib.h in Headers */, + 83031ED3243C50DF00C3F3E0 /* fsb5_streamfile.h in Headers */, 836F6F2318BDC2190095E648 /* coding.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; @@ -2435,7 +2481,6 @@ 83299FD11E7660C7003A3242 /* dsp_adx.c in Sources */, 836F704018BDC2190095E648 /* wii_sng.c in Sources */, 834FE10D215C79ED000A5D3D /* vag.c in Sources */, - 8349A9131FE6258200E26435 /* ngc_vid1.c in Sources */, 8350C0551E071881009E0A93 /* xma.c in Sources */, 837CEAF523487F2C00E62A4A /* ubi_hx.c in Sources */, 836F6F3218BDC2190095E648 /* ngc_dsp_decoder.c in Sources */, @@ -2479,6 +2524,7 @@ 8306B0BA20984552000302D4 /* blocked_wsi.c in Sources */, 83BAFB6C19F45EB3005DAB60 /* bfstm.c in Sources */, 836F704418BDC2190095E648 /* ws_aud.c in Sources */, + 83031ED2243C50DF00C3F3E0 /* bkhd.c in Sources */, 8373342F23F60D4100DE14DC /* tgc.c in Sources */, 83709E081ECBC1A4005C03D3 /* ps2_rxws.c in Sources */, 8373342823F60CDC00DE14DC /* fda.c in Sources */, @@ -2513,6 +2559,7 @@ 836F6FE618BDC2190095E648 /* ps2_mcg.c in Sources */, 83AA5D241F6E2F9C0020821C /* awc.c in Sources */, 8349A8E91FE6253900E26435 /* blocked_ea_1snh.c in Sources */, + 83031EC6243C50A800C3F3E0 /* circus_decoder_miniz.c in Sources */, 8306B0E620984590000302D4 /* msb_msh.c in Sources */, 836F702918BDC2190095E648 /* sat_sap.c in Sources */, 8351F3292212B53400A606E4 /* dsa_decoder.c in Sources */, @@ -2521,6 +2568,7 @@ 831BA6281EAC61CB00CF89B0 /* coding_utils.c in Sources */, 8373342B23F60CDC00DE14DC /* fwse.c in Sources */, 837CEAFF23487F2C00E62A4A /* raw_snds.c in Sources */, + 83031EDC243C510500C3F3E0 /* vid1.c in Sources */, 836F700218BDC2190095E648 /* ps2_tk5.c in Sources */, 83AA5D271F6E2F9C0020821C /* stm.c in Sources */, 831BA61D1EAC61A500CF89B0 /* ubi_raki.c in Sources */, @@ -2563,6 +2611,7 @@ 834FE0F5215C79ED000A5D3D /* wv2.c in Sources */, 836F703D18BDC2190095E648 /* wii_mus.c in Sources */, 836F700D18BDC2190095E648 /* ps2_wmus.c in Sources */, + 83031EC8243C50A800C3F3E0 /* circus_decoder_lib.c in Sources */, 831BA61C1EAC61A500CF89B0 /* sxd.c in Sources */, 836F6F8018BDC2190095E648 /* dsp_bdsp.c in Sources */, 836F6F9618BDC2190095E648 /* lsf.c in Sources */, @@ -2576,14 +2625,17 @@ 8306B0B120984552000302D4 /* blocked_halpst.c in Sources */, 836F6FD018BDC2190095E648 /* ps2_b1s.c in Sources */, 83AA5D181F6E2F600020821C /* mpeg_custom_utils_awc.c in Sources */, + 83031ED1243C50DF00C3F3E0 /* encrypted.c in Sources */, 834FE0FE215C79ED000A5D3D /* ps_headerless.c in Sources */, 8306B0BB20984552000302D4 /* blocked_gsb.c in Sources */, + 83031ECC243C50CC00C3F3E0 /* blocked_ubi_sce.c in Sources */, 836F6F7718BDC2190095E648 /* capdsp.c in Sources */, 836F6FB018BDC2190095E648 /* ngc_dsp_ygo.c in Sources */, 836F703318BDC2190095E648 /* str_snds.c in Sources */, 832BF82221E0514B006F50F1 /* vs_str.c in Sources */, 8349A9191FE6258200E26435 /* afc.c in Sources */, 836F703718BDC2190095E648 /* tun.c in Sources */, + 83031ECD243C50CC00C3F3E0 /* blocked_vid1.c in Sources */, 836F700B18BDC2190095E648 /* ps2_wad.c in Sources */, 8349A9161FE6258200E26435 /* flx.c in Sources */, 832BF82921E0514B006F50F1 /* msf_banpresto.c in Sources */, diff --git a/Frameworks/vgmstream/vgmstream/src/coding/asf_decoder.c b/Frameworks/vgmstream/vgmstream/src/coding/asf_decoder.c index 00ee61d71..db81b75ba 100644 --- a/Frameworks/vgmstream/vgmstream/src/coding/asf_decoder.c +++ b/Frameworks/vgmstream/vgmstream/src/coding/asf_decoder.c @@ -54,3 +54,8 @@ void decode_asf(VGMSTREAMCHANNEL *stream, sample_t *outbuf, int channelspacing, stream->adpcm_history1_32 = hist1; stream->adpcm_history2_32 = hist2; } + +int32_t asf_bytes_to_samples(size_t bytes, int channels) { + if (channels <= 0) return 0; + return bytes / channels / 0x11 * 32; +} diff --git a/Frameworks/vgmstream/vgmstream/src/coding/circus_decoder.c b/Frameworks/vgmstream/vgmstream/src/coding/circus_decoder.c index 54dde1a7e..c85293655 100644 --- a/Frameworks/vgmstream/vgmstream/src/coding/circus_decoder.c +++ b/Frameworks/vgmstream/vgmstream/src/coding/circus_decoder.c @@ -1,29 +1,109 @@ -#include "coding.h" - - -/* Circus XPCM mode 2 decoding, verified vs EF.exe (info from foo_adpcm/libpcm and https://github.com/lioncash/ExtractData) */ -void decode_circus_adpcm(VGMSTREAMCHANNEL * stream, sample * outbuf, int channelspacing, int32_t first_sample, int32_t samples_to_do) { - int i, sample_pos = 0; - int32_t hist = stream->adpcm_history1_32; - int scale = stream->adpcm_scale; - off_t frame_offset = stream->offset; /* frame size is 1 */ - - - for (i = first_sample; i < first_sample + samples_to_do; i++) { - int8_t code = read_8bit(frame_offset+i,stream->streamfile); - - hist += code << scale; - if (code == 0) { - if (scale > 0) - scale--; - } - else if (code == 127 || code == -128) { - if (scale < 8) - scale++; - } - outbuf[sample_pos] = hist; - } - - stream->adpcm_history1_32 = hist; - stream->adpcm_scale = scale; -} +#include "coding.h" +#include "circus_decoder_lib.h" + + + +struct circus_codec_data { + STREAMFILE* sf; + int16_t* buf; + int buf_samples_all; + circus_handle_t* handle; +}; + + +circus_codec_data* init_circus_vq(STREAMFILE* sf, off_t start, uint8_t codec, uint8_t flags) { + circus_codec_data* data = NULL; + + data = calloc(1, sizeof(circus_codec_data)); + if (!data) goto fail; + + data->sf = reopen_streamfile(sf, 0); + data->handle = circus_init(start, codec, flags); + if (!data->handle) goto fail; + + return data; +fail: + free_circus_vq(data); + return NULL; +} + +void decode_circus_vq(circus_codec_data* data, sample_t* outbuf, int32_t samples_to_do, int channels) { + int ok, i, samples_to_get; + + while (samples_to_do > 0) { + if (data->buf_samples_all == 0) { + ok = circus_decode_frame(data->handle, data->sf, &data->buf, &data->buf_samples_all); + if (!ok) goto decode_fail; + } + + samples_to_get = data->buf_samples_all / channels; + if (samples_to_get > samples_to_do) + samples_to_get = samples_to_do; + + for (i = 0; i < samples_to_get * channels; i++) { + outbuf[i] = data->buf[i]; + } + + data->buf += samples_to_get * channels; + data->buf_samples_all -= samples_to_get * channels; + outbuf += samples_to_get * channels; + samples_to_do -= samples_to_get; + } + + return; + +decode_fail: + VGM_LOG("CIRCUS: decode error\n"); + memset(outbuf, 0, samples_to_do * channels * sizeof(sample_t)); +} + +void reset_circus_vq(circus_codec_data* data) { + if (!data) return; + + circus_reset(data->handle); + data->buf_samples_all = 0; +} + +void seek_circus_vq(circus_codec_data* data, int32_t num_sample) { + if (!data) return; + + reset_circus_vq(data); + //data->samples_discard = num_sample; //todo (xpcm don't have loop points tho) +} + +void free_circus_vq(circus_codec_data* data) { + if (!data) return; + + close_streamfile(data->sf); + circus_free(data->handle); + free(data); +} + +/* ************************************************************************* */ + +/* Circus XPCM mode 2 decoding, verified vs EF.exe (info from foo_adpcm/libpcm and https://github.com/lioncash/ExtractData) */ +void decode_circus_adpcm(VGMSTREAMCHANNEL* stream, sample_t* outbuf, int channelspacing, int32_t first_sample, int32_t samples_to_do) { + int i, sample_pos = 0; + int32_t hist = stream->adpcm_history1_32; + int scale = stream->adpcm_scale; + off_t frame_offset = stream->offset; /* frame size is 1 */ + + + for (i = first_sample; i < first_sample + samples_to_do; i++) { + int8_t code = read_8bit(frame_offset+i,stream->streamfile); + + hist += code << scale; + if (code == 0) { + if (scale > 0) + scale--; + } + else if (code == 127 || code == -128) { + if (scale < 8) + scale++; + } + outbuf[sample_pos] = hist; + } + + stream->adpcm_history1_32 = hist; + stream->adpcm_scale = scale; +} diff --git a/Frameworks/vgmstream/vgmstream/src/coding/circus_decoder_lib.c b/Frameworks/vgmstream/vgmstream/src/coding/circus_decoder_lib.c new file mode 100644 index 000000000..0a5c5c0df --- /dev/null +++ b/Frameworks/vgmstream/vgmstream/src/coding/circus_decoder_lib.c @@ -0,0 +1,492 @@ +#include +#include +#include +#include + +/* Decodes Circus's audio codec, reverse engineered from various .exe. + * + * Some sources identify this codec as VQ (vector quantization), though vector(?) + * data isn't actually bitpacked and just compressed using custom LZ or standard zlib. + * Channels aren't divided either so decoding results in N-ch interleaved PCM. + * It does seem to be using LPC/speech stuff from VQ codecs though. + * + * Some info from Japanese libpcm.c found in foo_adpcm + * https://bitbucket.org/losnoco/foo_adpcm/src/master/foo_oki/source/libpcm/libpcm.cpp + */ + +#include "circus_decoder_lib.h" +#include "circus_decoder_lib_data.h" + +#include "circus_decoder_lzxpcm.h" + +/* use miniz (API-compatible) to avoid adding external zlib just for this codec + * - https://github.com/richgel999/miniz */ +#include "circus_decoder_miniz.h" +//#include "zlib.h" + + +//#define XPCM_CODEC_PCM 0 +#define XPCM_CODEC_VQ_LZXPCM 1 +//#define XPCM_CODEC_ADPCM 2 +#define XPCM_CODEC_VQ_DEFLATE 3 + +/* frame encodes 4096 PCM samples (all channels) = 4096*2 = 0x2000 bytes, re-interleaved then compressed */ +#define XPCM_FRAME_SIZE (4096 * 2) +#define XPCM_FRAME_CODES 4096 +#define XPCM_FRAME_SAMPLES_ALL 4064 +#define XPCM_FRAME_OVERLAP_ALL 32 +#define XPCM_INPUT_SIZE 0x8000 + +/* ************************************************************************* */ +/* DECODE */ +/* ************************************************************************* */ + +struct circus_handle_t { + /* config */ + off_t start; + uint8_t codec; + uint8_t flags; + const int* scales; + + /* temp buffers */ + uint8_t srcbuf[XPCM_INPUT_SIZE]; /* compressed input data (arbitrary size) */ + uint8_t decbuf[XPCM_FRAME_SIZE]; /* single decompressed frame */ + uint8_t intbuf[XPCM_FRAME_SIZE]; /* re-interleaved frame */ + int32_t invbuf[XPCM_FRAME_CODES]; /* main LPC data (may need less) */ + int32_t tmpbuf[XPCM_FRAME_CODES]; /* temp LPC data (may need less) */ + + /* output samples (original code reuses decbuf though) */ + int16_t pcmbuf[XPCM_FRAME_SAMPLES_ALL + XPCM_FRAME_OVERLAP_ALL]; /* final output samples and extra overlap samples */ + + /* sample filter state */ + int hist1; + int hist2; + int frame; + + /* lz/deflate decompression state */ + lzxpcm_stream_t lstrm; + z_stream dstrm; + off_t offset; +}; + + +static void convert(uint8_t flags, int32_t* invbuf, int16_t* pcmbuf, int* p_hist1, int* p_hist2, int frame) { + int i; + int sample, hist1, hist2; + + hist1 = *p_hist1; + hist2 = *p_hist2; + + /* some ops below would use SHRs (>>), but there is some rounding in the original + * ASM that decompiles and I think corresponds do DIVs (right shift and divs of + * negative values isn't equivalent). Similarly the filters seem to use CDQ tricks + * to simulate s64 ops, but I'm not sure casting is 100% equivalent (sounds ok tho). */ + + /* do final filtering and conversion to PCM */ + for (i = 0; i < XPCM_FRAME_SAMPLES_ALL + XPCM_FRAME_OVERLAP_ALL; i++) { + sample = *invbuf++; + if (flags & 0x10) + sample = (3 * (int64_t)sample / 2) / 1024; //>> 10; + else + sample = sample / 1024; //>> 10; + + sample = ((27 * (int64_t)sample + 4 * hist1 + hist2) << 11) / 65536; //>> 16 + + hist2 = hist1; + hist1 = sample; + + /* last 32 decoded samples aren't output, but are used next frame to overlap + * with beginning samples (filters(?) windowing, not too noticeable though) */ + if (i < XPCM_FRAME_OVERLAP_ALL && frame > 0) { + sample = ((i * (int64_t)sample) + ((XPCM_FRAME_OVERLAP_ALL - i) * pcmbuf[XPCM_FRAME_SAMPLES_ALL + i])) / 32; //>> 5 + } + + if (sample > 32767) + sample = 32767; + else if (sample < -32768) + sample = -32768; + + pcmbuf[i] = sample; + } + + *p_hist1 = hist1; + *p_hist2 = hist2; +} + +static void transform(int32_t* invbuf, int32_t* tmpbuf) { + int lpc1, lpc2, lpc3, lpc4; + int step1, step2, step3; + int sc1, sc2; + + /* bits were originally configurable (passed arg), but actually called with const 12, + * and removed in later games along with superfluous ifs (coefs > 0, bits >= 3, etc) */ + //const int frame_bits = 12; + + step1 = 4096; /* 1 << 12 */ + step2 = step1 >> 1; + step3 = step2 >> 1; + sc1 = 1; + + /* inverse transform of LPC(?) coefs */ + for (lpc1 = 0; lpc1 < 12 - 2; lpc1++) { + int sub1, sub2; + int i1, i2, i3, i4; + int64_t cos1, sin1, cos2, sin2; /* needs i64 to force 64b ops (avoid overflows) */ + + cos1 = (int64_t)sincos_table[sc1 + 1024]; + sin1 = (int64_t)sincos_table[sc1 + 0]; + + i1 = 0; + i2 = step2; + i3 = step3; + i4 = step2 + step3; + + for (lpc2 = 0; lpc2 < 4096; lpc2 += step1) { + sub1 = invbuf[i1 + 0] - invbuf[i2 + 0]; + sub2 = tmpbuf[i1 + 0] - tmpbuf[i2 + 0]; + invbuf[i1 + 0] += invbuf[i2 + 0]; + tmpbuf[i1 + 0] += tmpbuf[i2 + 0]; + invbuf[i2 + 0] = sub1; + tmpbuf[i2 + 0] = sub2; + + sub1 = invbuf[i1 + 1] - invbuf[i2 + 1]; + sub2 = tmpbuf[i1 + 1] - tmpbuf[i2 + 1]; + invbuf[i1 + 1] += invbuf[i2 + 1]; + tmpbuf[i1 + 1] += tmpbuf[i2 + 1]; + invbuf[i2 + 1] = ((sub1 * cos1) >> 12) + ((sub2 * sin1) >> 12); + tmpbuf[i2 + 1] = ((sub2 * cos1) >> 12) - ((sub1 * sin1) >> 12); + + sub1 = invbuf[i3 + 0] - invbuf[i4 + 0]; + sub2 = tmpbuf[i3 + 0] - tmpbuf[i4 + 0]; + invbuf[i3 + 0] += invbuf[i4 + 0]; + tmpbuf[i3 + 0] += tmpbuf[i4 + 0]; + invbuf[i4 + 0] = sub2; + tmpbuf[i4 + 0] = -sub1; + + sub1 = invbuf[i3 + 1] - invbuf[i4 + 1]; + sub2 = tmpbuf[i3 + 1] - tmpbuf[i4 + 1]; + invbuf[i3 + 1] += invbuf[i4 + 1]; + tmpbuf[i3 + 1] += tmpbuf[i4 + 1]; + invbuf[i4 + 1] = ((sub2 * cos1) >> 12) - ((sub1 * sin1) >> 12); + tmpbuf[i4 + 1] = -(((sub1 * cos1) >> 12) + ((sub2 * sin1) >> 12)); + + i1 += step1; + i2 += step1; + i3 += step1; + i4 += step1; + } + + if (step3 > 2) { + sc2 = sc1 * 2; + + for (lpc3 = 2; lpc3 < step3; lpc3++) { + cos2 = (int64_t)sincos_table[sc2 + 1024]; + sin2 = (int64_t)sincos_table[sc2 + 0]; + sc2 += sc1; + + i1 = 0 + lpc3; + i2 = step2 + lpc3; + i3 = step3 + lpc3; + i4 = step2 + step3 + lpc3; + + for (lpc4 = 0; lpc4 < 4096; lpc4 += step1) { + sub1 = invbuf[i1] - invbuf[i2]; + sub2 = tmpbuf[i1] - tmpbuf[i2]; + invbuf[i1] += invbuf[i2]; + tmpbuf[i1] += tmpbuf[i2]; + invbuf[i2] = ((sub1 * cos2) >> 12) + ((sub2 * sin2) >> 12); + tmpbuf[i2] = ((sub2 * cos2) >> 12) - ((sub1 * sin2) >> 12); + + sub1 = invbuf[i3] - invbuf[i4]; + sub2 = tmpbuf[i3] - tmpbuf[i4]; + invbuf[i3] += invbuf[i4]; + tmpbuf[i3] += tmpbuf[i4]; + invbuf[i4] = ((sub2 * cos2) >> 12) - ((sub1 * sin2) >> 12); + tmpbuf[i4] = -(((sub1 * cos2) >> 12) + ((sub2 * sin2) >> 12)); + + i1 += step1; + i2 += step1; + i3 += step1; + i4 += step1; + } + } + } + + step1 = step2; // step1 >>= 1; + step2 = step3; // step2 >>= 1; + step3 >>= 1; + sc1 *= 2; + } + + { + int i, j; + int sub1, sub2, pow; + + for (i = 0; i < 4096; i += 4) { + sub1 = invbuf[i + 0] - invbuf[i + 2]; + invbuf[i + 0] += invbuf[i + 2]; + invbuf[i + 2] = sub1; + + sub2 = tmpbuf[i + 0] - tmpbuf[i + 2]; + tmpbuf[i + 0] += tmpbuf[i + 2]; + tmpbuf[i + 2] = sub2; + + sub1 = invbuf[i + 3] - invbuf[i + 1]; + sub2 = tmpbuf[i + 1] - tmpbuf[i + 3]; + invbuf[i + 1] += invbuf[i + 3]; + invbuf[i + 3] = sub2; + tmpbuf[i + 1] += tmpbuf[i + 3]; + tmpbuf[i + 3] = sub1; + } + + for (i = 0; i < 4096; i += 2) { + sub1 = invbuf[i + 0] - invbuf[i + 1]; + invbuf[i + 0] += invbuf[i + 1]; + invbuf[i + 1] = sub1; + + sub2 = tmpbuf[i + 0] - tmpbuf[i + 1]; + tmpbuf[i + 0] += tmpbuf[i + 1]; + tmpbuf[i + 1] = sub2; + } + + for (i = 1, j = 0; i < 4096 - 1; i++) { + for (pow = 4096 / 2; pow <= j; pow /= 2) { + j -= pow; + } + j += pow; + + if (i < j) { + sub1 = invbuf[j]; + invbuf[j] = invbuf[i]; + invbuf[i] = sub1; + + sub2 = tmpbuf[j]; + tmpbuf[j] = tmpbuf[i]; + tmpbuf[i] = sub2; + } + } + } +} + +static void scale(const uint8_t* intbuf, const int* scales, int32_t* invbuf, int32_t* tmpbuf) { + int i, j; + + /* reinterleave and scale intbuf into invbuf and tmpbuf */ + for (i = 0, j = 0; i < 4096 / 2; i++, j += 16) { + int scale, qv1, qv2; + + scale = scales[j / 4096]; + + qv1 = (intbuf[i*4 + 0] << 0) | (intbuf[i*4 + 1] << 8); /* get_u16le */ + qv2 = (intbuf[i*4 + 2] << 0) | (intbuf[i*4 + 3] << 8); /* get_u16le */ + + /* lowest bit is short of "positive" flag, or rather: even=0..-32767, odd=1..32768 + * (originally done through a LUT init at runtime with all 65536 indexes) */ + qv1 = (qv1 & 1) ? (qv1 >> 1) + 1 : -(qv1 >> 1); + qv2 = (qv2 & 1) ? (qv2 >> 1) + 1 : -(qv2 >> 1); + + invbuf[i] = scale * qv1; + tmpbuf[i] = scale * qv2; + } + + /* reset rest of invbuf/tmpbuf */ + for (i = 4096 / 2; i < 4096; i++) { + invbuf[i] = 0; + tmpbuf[i] = 0; + } +} + +static void interleave(const uint8_t* decbuf, uint8_t* intbuf) { + int i, j; + + /* reorder odd decbuf bytes into intbuf */ + for (i = 0, j = 1; i < 0x1000; i++, j += 2) { + intbuf[j] = decbuf[i]; + } + + /* reorder even decbuf bytes into intbuf */ + for (i = 0x1000, j = 0; i < 0x1800; i++, j += 4) { + uint8_t lo = decbuf[i + 0x800]; + uint8_t hi = decbuf[i]; + + intbuf[j + 0] = (hi & 0xF0) | (lo >> 4); + intbuf[j + 2] = (hi << 4) | (lo & 0x0F); + } +} + +/* ************************************************************ */ +/* API */ +/* ************************************************************ */ + +circus_handle_t* circus_init(off_t start, uint8_t codec, uint8_t flags) { + circus_handle_t* handle = NULL; + int scale_index, err; + + handle = malloc(sizeof(circus_handle_t)); + if (!handle) goto fail; + + handle->start = start; + handle->codec = codec; //(config >> 0) & 0xFF; + handle->flags = flags; //(config >> 8) & 0xFF; + + scale_index = (handle->flags & 0xF); + if (scale_index > 5) goto fail; + handle->scales = scale_table[scale_index]; + + if (handle->codec == XPCM_CODEC_VQ_DEFLATE) { + memset(&handle->dstrm, 0, sizeof(z_stream)); + err = inflateInit(&handle->dstrm); + if (err < 0) goto fail; + } + + circus_reset(handle); + + return handle; +fail: + circus_free(handle); + return NULL; +} + +void circus_free(circus_handle_t* handle) { + if (!handle) + return; + + if (handle->codec == XPCM_CODEC_VQ_DEFLATE) { + inflateEnd(&handle->dstrm); + } + + free(handle); +} + +void circus_reset(circus_handle_t* handle) { + if (!handle) + return; + handle->hist1 = 0; + handle->hist2 = 0; + handle->frame = 0; + + if (handle->codec == XPCM_CODEC_VQ_LZXPCM) { + lzxpcm_reset(&handle->lstrm); + } else if (handle->codec == XPCM_CODEC_VQ_DEFLATE) { + inflateReset(&handle->dstrm); + } + handle->offset = handle->start; +} + +static int decompress_frame_lzxpcm(circus_handle_t* handle, STREAMFILE* sf) { + int res; + + handle->lstrm.next_out = handle->decbuf; + handle->lstrm.avail_out = sizeof(handle->decbuf); + handle->lstrm.total_out = 0; + do { + if (handle->lstrm.avail_in == 0) { + handle->lstrm.next_in = handle->srcbuf; + handle->lstrm.avail_in = read_streamfile(handle->srcbuf, handle->offset, sizeof(handle->srcbuf), sf); + handle->offset += handle->lstrm.avail_in; + + /* EOF (game reserves some extra buf so memset'ing is probably equivalent) */ + if (handle->lstrm.avail_in == 0) { + memset(handle->decbuf + handle->lstrm.total_out, 0, sizeof(handle->decbuf) - handle->dstrm.total_out); + break; + } + } + + res = lzxpcm_decompress(&handle->lstrm); + if (res != LZXPCM_OK) + goto fail; + } + while(handle->lstrm.avail_out != 0); + + return 1; +fail: + return 0; +} + +static int decompress_frame_deflate(circus_handle_t* handle, STREAMFILE* sf) { + int res; + + handle->dstrm.next_out = handle->decbuf; + handle->dstrm.avail_out = sizeof(handle->decbuf); + handle->dstrm.total_out = 0; + do { + if (handle->dstrm.avail_in == 0) { + handle->dstrm.next_in = handle->srcbuf; + handle->dstrm.avail_in = read_streamfile(handle->srcbuf, handle->offset, sizeof(handle->srcbuf), sf); + handle->offset += handle->dstrm.avail_in; + + /* EOF (game reserves some extra buf so memset'ing is probably equivalent) */ + if (handle->dstrm.avail_in == 0) { + memset(handle->decbuf + handle->dstrm.total_out, 0, sizeof(handle->decbuf) - handle->dstrm.total_out); + break; + } + } + + res = inflate(&handle->dstrm, Z_NO_FLUSH); + if (res != Z_OK && res != Z_STREAM_END) + goto fail; + } + while(handle->dstrm.avail_out != 0); + + return 1; +fail: + return 0; +} + +#ifdef XPCM_ALT +/* original code uses zlib 1.2.1 to decompress the full stream into memory */ +static int deflate_decompress_full(uint8_t* dst, size_t dst_size, const uint8_t* src, size_t src_size) { + int err; + z_stream strm = {0}; + strm.next_in = src; + strm.avail_in = src_size; + strm.next_out = dst; + strm.avail_out = dst_size; + + err = inflateInit(&strm); + if (err < 0) { + //printf("inflateInit error: %i\n", err); + return 0; + } + + err = inflate(&strm, Z_FINISH); + if (err < 0) { + //printf("inflate error: %i\n", err); + //return 0; + } + + err = inflateEnd(&strm); + if (err < 0) { + //printf("inflateEnd error: %i\n", err); + return 0; + } + + return 0; +} +#endif + +int circus_decode_frame(circus_handle_t* handle, STREAMFILE* sf, int16_t** p_buf, int* p_buf_samples_all) { + int ok; + + if (handle->codec == XPCM_CODEC_VQ_LZXPCM) { + ok = decompress_frame_lzxpcm(handle, sf); + } else if (handle->codec == XPCM_CODEC_VQ_DEFLATE) { + ok = decompress_frame_deflate(handle, sf); + } else { + ok = 0; + } + if (!ok) + goto fail; + + interleave(handle->decbuf, handle->intbuf); + scale(handle->intbuf, handle->scales, handle->invbuf, handle->tmpbuf); + transform(handle->invbuf, handle->tmpbuf); + convert(handle->flags, handle->invbuf, handle->pcmbuf, &handle->hist1, &handle->hist2, handle->frame); + handle->frame++; + + *p_buf = handle->pcmbuf; + *p_buf_samples_all = XPCM_FRAME_SAMPLES_ALL; + return 1; +fail: + return 0; +} diff --git a/Frameworks/vgmstream/vgmstream/src/coding/circus_decoder_lib.h b/Frameworks/vgmstream/vgmstream/src/coding/circus_decoder_lib.h new file mode 100644 index 000000000..bc02d839e --- /dev/null +++ b/Frameworks/vgmstream/vgmstream/src/coding/circus_decoder_lib.h @@ -0,0 +1,16 @@ +#ifndef _CIRCUS_DECODER_LIB_H_ +#define _CIRCUS_DECODER_LIB_H_ + +#include "../streamfile.h" + +typedef struct circus_handle_t circus_handle_t; + +circus_handle_t* circus_init(off_t start, uint8_t codec, uint8_t flags); + +void circus_free(circus_handle_t* handle); + +void circus_reset(circus_handle_t* handle); + +int circus_decode_frame(circus_handle_t* handle, STREAMFILE* sf, int16_t** p_buf, int* p_buf_samples_all); + +#endif diff --git a/Frameworks/vgmstream/vgmstream/src/coding/circus_decoder_lib_data.h b/Frameworks/vgmstream/vgmstream/src/coding/circus_decoder_lib_data.h new file mode 100644 index 000000000..6893d145a --- /dev/null +++ b/Frameworks/vgmstream/vgmstream/src/coding/circus_decoder_lib_data.h @@ -0,0 +1,347 @@ +#ifndef _CIRCUS_DECODER_LIB_DATA_H_ +#define _CIRCUS_DECODER_LIB_DATA_H_ + +#include + + +/* sin-cosine LUT, seems generated with: */ +/* table[i] = round( sin(2.0 * PI * i / 1024.0) * 1000.0 ) */ +static const int sincos_table[1024*5 + 1] = { + 0, 6, 12, 18, 25, 31, 37, 43, 50, 56, 62, 69, 75, 81, 87, 94, + 100, 106, 113, 119, 125, 131, 138, 144, 150, 157, 163, 169, 175, 182, 188, 194, + 200, 207, 213, 219, 226, 232, 238, 244, 251, 257, 263, 269, 276, 282, 288, 295, + 301, 307, 313, 320, 326, 332, 338, 345, 351, 357, 363, 370, 376, 382, 388, 395, + 401, 407, 413, 420, 426, 432, 438, 445, 451, 457, 463, 470, 476, 482, 488, 495, + 501, 507, 513, 520, 526, 532, 538, 545, 551, 557, 563, 569, 576, 582, 588, 594, + 601, 607, 613, 619, 625, 632, 638, 644, 650, 656, 663, 669, 675, 681, 687, 694, + 700, 706, 712, 718, 725, 731, 737, 743, 749, 755, 762, 768, 774, 780, 786, 792, + 799, 805, 811, 817, 823, 829, 836, 842, 848, 854, 860, 866, 872, 879, 885, 891, + 897, 903, 909, 915, 921, 928, 934, 940, 946, 952, 958, 964, 970, 976, 983, 989, + 995, 1001, 1007, 1013, 1019, 1025, 1031, 1037, 1043, 1050, 1056, 1062, 1068, 1074, 1080, 1086, + 1092, 1098, 1104, 1110, 1116, 1122, 1128, 1134, 1140, 1146, 1152, 1158, 1164, 1170, 1176, 1182, + 1189, 1195, 1201, 1207, 1213, 1219, 1225, 1231, 1237, 1243, 1248, 1254, 1260, 1266, 1272, 1278, + 1284, 1290, 1296, 1302, 1308, 1314, 1320, 1326, 1332, 1338, 1344, 1350, 1356, 1362, 1368, 1373, + 1379, 1385, 1391, 1397, 1403, 1409, 1415, 1421, 1427, 1433, 1438, 1444, 1450, 1456, 1462, 1468, + 1474, 1479, 1485, 1491, 1497, 1503, 1509, 1515, 1520, 1526, 1532, 1538, 1544, 1550, 1555, 1561, + 1567, 1573, 1579, 1584, 1590, 1596, 1602, 1608, 1613, 1619, 1625, 1631, 1636, 1642, 1648, 1654, + 1659, 1665, 1671, 1677, 1682, 1688, 1694, 1699, 1705, 1711, 1717, 1722, 1728, 1734, 1739, 1745, + 1751, 1756, 1762, 1768, 1773, 1779, 1785, 1790, 1796, 1802, 1807, 1813, 1819, 1824, 1830, 1835, + 1841, 1847, 1852, 1858, 1864, 1869, 1875, 1880, 1886, 1891, 1897, 1903, 1908, 1914, 1919, 1925, + 1930, 1936, 1941, 1947, 1952, 1958, 1964, 1969, 1975, 1980, 1986, 1991, 1997, 2002, 2007, 2013, + 2018, 2024, 2029, 2035, 2040, 2046, 2051, 2057, 2062, 2067, 2073, 2078, 2084, 2089, 2094, 2100, + 2105, 2111, 2116, 2121, 2127, 2132, 2138, 2143, 2148, 2154, 2159, 2164, 2170, 2175, 2180, 2186, + 2191, 2196, 2201, 2207, 2212, 2217, 2223, 2228, 2233, 2238, 2244, 2249, 2254, 2259, 2265, 2270, + 2275, 2280, 2286, 2291, 2296, 2301, 2306, 2312, 2317, 2322, 2327, 2332, 2337, 2343, 2348, 2353, + 2358, 2363, 2368, 2373, 2379, 2384, 2389, 2394, 2399, 2404, 2409, 2414, 2419, 2424, 2429, 2434, + 2439, 2445, 2450, 2455, 2460, 2465, 2470, 2475, 2480, 2485, 2490, 2495, 2500, 2505, 2510, 2515, + 2519, 2524, 2529, 2534, 2539, 2544, 2549, 2554, 2559, 2564, 2569, 2574, 2578, 2583, 2588, 2593, + 2598, 2603, 2608, 2613, 2617, 2622, 2627, 2632, 2637, 2641, 2646, 2651, 2656, 2661, 2665, 2670, + 2675, 2680, 2684, 2689, 2694, 2699, 2703, 2708, 2713, 2717, 2722, 2727, 2732, 2736, 2741, 2746, + 2750, 2755, 2760, 2764, 2769, 2773, 2778, 2783, 2787, 2792, 2796, 2801, 2806, 2810, 2815, 2819, + 2824, 2828, 2833, 2837, 2842, 2847, 2851, 2856, 2860, 2865, 2869, 2874, 2878, 2882, 2887, 2891, + 2896, 2900, 2905, 2909, 2914, 2918, 2922, 2927, 2931, 2936, 2940, 2944, 2949, 2953, 2957, 2962, + 2966, 2970, 2975, 2979, 2983, 2988, 2992, 2996, 3000, 3005, 3009, 3013, 3018, 3022, 3026, 3030, + 3034, 3039, 3043, 3047, 3051, 3055, 3060, 3064, 3068, 3072, 3076, 3080, 3085, 3089, 3093, 3097, + 3101, 3105, 3109, 3113, 3117, 3121, 3126, 3130, 3134, 3138, 3142, 3146, 3150, 3154, 3158, 3162, + 3166, 3170, 3174, 3178, 3182, 3186, 3190, 3193, 3197, 3201, 3205, 3209, 3213, 3217, 3221, 3225, + 3229, 3232, 3236, 3240, 3244, 3248, 3252, 3255, 3259, 3263, 3267, 3271, 3274, 3278, 3282, 3286, + 3289, 3293, 3297, 3301, 3304, 3308, 3312, 3315, 3319, 3323, 3326, 3330, 3334, 3337, 3341, 3345, + 3348, 3352, 3356, 3359, 3363, 3366, 3370, 3373, 3377, 3381, 3384, 3388, 3391, 3395, 3398, 3402, + 3405, 3409, 3412, 3416, 3419, 3423, 3426, 3429, 3433, 3436, 3440, 3443, 3447, 3450, 3453, 3457, + 3460, 3463, 3467, 3470, 3473, 3477, 3480, 3483, 3487, 3490, 3493, 3497, 3500, 3503, 3506, 3510, + 3513, 3516, 3519, 3522, 3526, 3529, 3532, 3535, 3538, 3541, 3545, 3548, 3551, 3554, 3557, 3560, + 3563, 3566, 3570, 3573, 3576, 3579, 3582, 3585, 3588, 3591, 3594, 3597, 3600, 3603, 3606, 3609, + 3612, 3615, 3618, 3621, 3624, 3627, 3629, 3632, 3635, 3638, 3641, 3644, 3647, 3650, 3652, 3655, + 3658, 3661, 3664, 3667, 3669, 3672, 3675, 3678, 3680, 3683, 3686, 3689, 3691, 3694, 3697, 3700, + 3702, 3705, 3708, 3710, 3713, 3716, 3718, 3721, 3723, 3726, 3729, 3731, 3734, 3736, 3739, 3742, + 3744, 3747, 3749, 3752, 3754, 3757, 3759, 3762, 3764, 3767, 3769, 3772, 3774, 3776, 3779, 3781, + 3784, 3786, 3789, 3791, 3793, 3796, 3798, 3800, 3803, 3805, 3807, 3810, 3812, 3814, 3816, 3819, + 3821, 3823, 3826, 3828, 3830, 3832, 3834, 3837, 3839, 3841, 3843, 3845, 3848, 3850, 3852, 3854, + 3856, 3858, 3860, 3862, 3864, 3867, 3869, 3871, 3873, 3875, 3877, 3879, 3881, 3883, 3885, 3887, + 3889, 3891, 3893, 3895, 3897, 3899, 3900, 3902, 3904, 3906, 3908, 3910, 3912, 3914, 3915, 3917, + 3919, 3921, 3923, 3925, 3926, 3928, 3930, 3932, 3933, 3935, 3937, 3939, 3940, 3942, 3944, 3945, + 3947, 3949, 3950, 3952, 3954, 3955, 3957, 3959, 3960, 3962, 3963, 3965, 3967, 3968, 3970, 3971, + 3973, 3974, 3976, 3977, 3979, 3980, 3982, 3983, 3985, 3986, 3988, 3989, 3990, 3992, 3993, 3995, + 3996, 3997, 3999, 4000, 4001, 4003, 4004, 4005, 4007, 4008, 4009, 4011, 4012, 4013, 4014, 4016, + 4017, 4018, 4019, 4020, 4022, 4023, 4024, 4025, 4026, 4027, 4029, 4030, 4031, 4032, 4033, 4034, + 4035, 4036, 4037, 4038, 4039, 4040, 4041, 4042, 4043, 4044, 4045, 4046, 4047, 4048, 4049, 4050, + 4051, 4052, 4053, 4054, 4055, 4056, 4057, 4057, 4058, 4059, 4060, 4061, 4062, 4062, 4063, 4064, + 4065, 4065, 4066, 4067, 4068, 4068, 4069, 4070, 4071, 4071, 4072, 4073, 4073, 4074, 4075, 4075, + 4076, 4076, 4077, 4078, 4078, 4079, 4079, 4080, 4080, 4081, 4081, 4082, 4082, 4083, 4083, 4084, + 4084, 4085, 4085, 4086, 4086, 4087, 4087, 4087, 4088, 4088, 4089, 4089, 4089, 4090, 4090, 4090, + 4091, 4091, 4091, 4091, 4092, 4092, 4092, 4092, 4093, 4093, 4093, 4093, 4094, 4094, 4094, 4094, + 4094, 4094, 4095, 4095, 4095, 4095, 4095, 4095, 4095, 4095, 4095, 4095, 4095, 4095, 4095, 4095, + + 4096, 4095, 4095, 4095, 4095, 4095, 4095, 4095, 4095, 4095, 4095, 4095, 4095, 4095, 4095, 4094, + 4094, 4094, 4094, 4094, 4094, 4093, 4093, 4093, 4093, 4092, 4092, 4092, 4092, 4091, 4091, 4091, + 4091, 4090, 4090, 4090, 4089, 4089, 4089, 4088, 4088, 4087, 4087, 4087, 4086, 4086, 4085, 4085, + 4084, 4084, 4083, 4083, 4082, 4082, 4081, 4081, 4080, 4080, 4079, 4079, 4078, 4078, 4077, 4076, + 4076, 4075, 4075, 4074, 4073, 4073, 4072, 4071, 4071, 4070, 4069, 4068, 4068, 4067, 4066, 4065, + 4065, 4064, 4063, 4062, 4062, 4061, 4060, 4059, 4058, 4057, 4057, 4056, 4055, 4054, 4053, 4052, + 4051, 4050, 4049, 4048, 4047, 4046, 4045, 4044, 4043, 4042, 4041, 4040, 4039, 4038, 4037, 4036, + 4035, 4034, 4033, 4032, 4031, 4030, 4029, 4027, 4026, 4025, 4024, 4023, 4022, 4020, 4019, 4018, + 4017, 4016, 4014, 4013, 4012, 4011, 4009, 4008, 4007, 4005, 4004, 4003, 4001, 4000, 3999, 3997, + 3996, 3995, 3993, 3992, 3990, 3989, 3988, 3986, 3985, 3983, 3982, 3980, 3979, 3977, 3976, 3974, + 3973, 3971, 3970, 3968, 3967, 3965, 3963, 3962, 3960, 3959, 3957, 3955, 3954, 3952, 3950, 3949, + 3947, 3945, 3944, 3942, 3940, 3939, 3937, 3935, 3933, 3932, 3930, 3928, 3926, 3925, 3923, 3921, + 3919, 3917, 3915, 3914, 3912, 3910, 3908, 3906, 3904, 3902, 3900, 3899, 3897, 3895, 3893, 3891, + 3889, 3887, 3885, 3883, 3881, 3879, 3877, 3875, 3873, 3871, 3869, 3867, 3864, 3862, 3860, 3858, + 3856, 3854, 3852, 3850, 3848, 3845, 3843, 3841, 3839, 3837, 3834, 3832, 3830, 3828, 3826, 3823, + 3821, 3819, 3816, 3814, 3812, 3810, 3807, 3805, 3803, 3800, 3798, 3796, 3793, 3791, 3789, 3786, + 3784, 3781, 3779, 3776, 3774, 3772, 3769, 3767, 3764, 3762, 3759, 3757, 3754, 3752, 3749, 3747, + 3744, 3742, 3739, 3736, 3734, 3731, 3729, 3726, 3723, 3721, 3718, 3716, 3713, 3710, 3708, 3705, + 3702, 3700, 3697, 3694, 3691, 3689, 3686, 3683, 3680, 3678, 3675, 3672, 3669, 3667, 3664, 3661, + 3658, 3655, 3652, 3650, 3647, 3644, 3641, 3638, 3635, 3632, 3629, 3627, 3624, 3621, 3618, 3615, + 3612, 3609, 3606, 3603, 3600, 3597, 3594, 3591, 3588, 3585, 3582, 3579, 3576, 3573, 3570, 3566, + 3563, 3560, 3557, 3554, 3551, 3548, 3545, 3541, 3538, 3535, 3532, 3529, 3526, 3522, 3519, 3516, + 3513, 3510, 3506, 3503, 3500, 3497, 3493, 3490, 3487, 3483, 3480, 3477, 3473, 3470, 3467, 3463, + 3460, 3457, 3453, 3450, 3447, 3443, 3440, 3436, 3433, 3429, 3426, 3423, 3419, 3416, 3412, 3409, + 3405, 3402, 3398, 3395, 3391, 3388, 3384, 3381, 3377, 3373, 3370, 3366, 3363, 3359, 3356, 3352, + 3348, 3345, 3341, 3337, 3334, 3330, 3326, 3323, 3319, 3315, 3312, 3308, 3304, 3301, 3297, 3293, + 3289, 3286, 3282, 3278, 3274, 3271, 3267, 3263, 3259, 3255, 3252, 3248, 3244, 3240, 3236, 3232, + 3229, 3225, 3221, 3217, 3213, 3209, 3205, 3201, 3197, 3193, 3190, 3186, 3182, 3178, 3174, 3170, + 3166, 3162, 3158, 3154, 3150, 3146, 3142, 3138, 3134, 3130, 3126, 3121, 3117, 3113, 3109, 3105, + 3101, 3097, 3093, 3089, 3085, 3080, 3076, 3072, 3068, 3064, 3060, 3055, 3051, 3047, 3043, 3039, + 3034, 3030, 3026, 3022, 3018, 3013, 3009, 3005, 3000, 2996, 2992, 2988, 2983, 2979, 2975, 2970, + 2966, 2962, 2957, 2953, 2949, 2944, 2940, 2936, 2931, 2927, 2922, 2918, 2914, 2909, 2905, 2900, + 2896, 2891, 2887, 2882, 2878, 2874, 2869, 2865, 2860, 2856, 2851, 2847, 2842, 2837, 2833, 2828, + 2824, 2819, 2815, 2810, 2806, 2801, 2796, 2792, 2787, 2783, 2778, 2773, 2769, 2764, 2760, 2755, + 2750, 2746, 2741, 2736, 2732, 2727, 2722, 2717, 2713, 2708, 2703, 2699, 2694, 2689, 2684, 2680, + 2675, 2670, 2665, 2661, 2656, 2651, 2646, 2641, 2637, 2632, 2627, 2622, 2617, 2613, 2608, 2603, + 2598, 2593, 2588, 2583, 2578, 2574, 2569, 2564, 2559, 2554, 2549, 2544, 2539, 2534, 2529, 2524, + 2519, 2515, 2510, 2505, 2500, 2495, 2490, 2485, 2480, 2475, 2470, 2465, 2460, 2455, 2450, 2445, + 2439, 2434, 2429, 2424, 2419, 2414, 2409, 2404, 2399, 2394, 2389, 2384, 2379, 2373, 2368, 2363, + 2358, 2353, 2348, 2343, 2337, 2332, 2327, 2322, 2317, 2312, 2306, 2301, 2296, 2291, 2286, 2280, + 2275, 2270, 2265, 2259, 2254, 2249, 2244, 2238, 2233, 2228, 2223, 2217, 2212, 2207, 2201, 2196, + 2191, 2186, 2180, 2175, 2170, 2164, 2159, 2154, 2148, 2143, 2138, 2132, 2127, 2121, 2116, 2111, + 2105, 2100, 2094, 2089, 2084, 2078, 2073, 2067, 2062, 2057, 2051, 2046, 2040, 2035, 2029, 2024, + 2018, 2013, 2007, 2002, 1997, 1991, 1986, 1980, 1975, 1969, 1964, 1958, 1952, 1947, 1941, 1936, + 1930, 1925, 1919, 1914, 1908, 1903, 1897, 1891, 1886, 1880, 1875, 1869, 1864, 1858, 1852, 1847, + 1841, 1835, 1830, 1824, 1819, 1813, 1807, 1802, 1796, 1790, 1785, 1779, 1773, 1768, 1762, 1756, + 1751, 1745, 1739, 1734, 1728, 1722, 1717, 1711, 1705, 1699, 1694, 1688, 1682, 1677, 1671, 1665, + 1659, 1654, 1648, 1642, 1636, 1631, 1625, 1619, 1613, 1608, 1602, 1596, 1590, 1584, 1579, 1573, + 1567, 1561, 1555, 1550, 1544, 1538, 1532, 1526, 1520, 1515, 1509, 1503, 1497, 1491, 1485, 1479, + 1474, 1468, 1462, 1456, 1450, 1444, 1438, 1433, 1427, 1421, 1415, 1409, 1403, 1397, 1391, 1385, + 1379, 1373, 1368, 1362, 1356, 1350, 1344, 1338, 1332, 1326, 1320, 1314, 1308, 1302, 1296, 1290, + 1284, 1278, 1272, 1266, 1260, 1254, 1248, 1243, 1237, 1231, 1225, 1219, 1213, 1207, 1201, 1195, + 1189, 1182, 1176, 1170, 1164, 1158, 1152, 1146, 1140, 1134, 1128, 1122, 1116, 1110, 1104, 1098, + 1092, 1086, 1080, 1074, 1068, 1062, 1056, 1050, 1043, 1037, 1031, 1025, 1019, 1013, 1007, 1001, + 995, 989, 983, 976, 970, 964, 958, 952, 946, 940, 934, 928, 921, 915, 909, 903, + 897, 891, 885, 879, 872, 866, 860, 854, 848, 842, 836, 829, 823, 817, 811, 805, + 799, 792, 786, 780, 774, 768, 762, 755, 749, 743, 737, 731, 725, 718, 712, 706, + 700, 694, 687, 681, 675, 669, 663, 656, 650, 644, 638, 632, 625, 619, 613, 607, + 601, 594, 588, 582, 576, 569, 563, 557, 551, 545, 538, 532, 526, 520, 513, 507, + 501, 495, 488, 482, 476, 470, 463, 457, 451, 445, 438, 432, 426, 420, 413, 407, + 401, 395, 388, 382, 376, 370, 363, 357, 351, 345, 338, 332, 326, 320, 313, 307, + 301, 295, 288, 282, 276, 269, 263, 257, 251, 244, 238, 232, 226, 219, 213, 207, + 200, 194, 188, 182, 175, 169, 163, 157, 150, 144, 138, 131, 125, 119, 113, 106, + 100, 94, 87, 81, 75, 69, 62, 56, 50, 43, 37, 31, 25, 18, 12, 6, + + 0, -6, -12, -18, -25, -31, -37, -43, -50, -56, -62, -69, -75, -81, -87, -94, + -100, -106, -113, -119, -125, -131, -138, -144, -150, -157, -163, -169, -175, -182, -188, -194, + -200, -207, -213, -219, -226, -232, -238, -244, -251, -257, -263, -269, -276, -282, -288, -295, + -301, -307, -313, -320, -326, -332, -338, -345, -351, -357, -363, -370, -376, -382, -388, -395, + -401, -407, -413, -420, -426, -432, -438, -445, -451, -457, -463, -470, -476, -482, -488, -495, + -501, -507, -513, -520, -526, -532, -538, -545, -551, -557, -563, -569, -576, -582, -588, -594, + -601, -607, -613, -619, -625, -632, -638, -644, -650, -656, -663, -669, -675, -681, -687, -694, + -700, -706, -712, -718, -725, -731, -737, -743, -749, -755, -762, -768, -774, -780, -786, -792, + -799, -805, -811, -817, -823, -829, -836, -842, -848, -854, -860, -866, -872, -879, -885, -891, + -897, -903, -909, -915, -921, -928, -934, -940, -946, -952, -958, -964, -970, -976, -983, -989, + -995,-1001,-1007,-1013,-1019,-1025,-1031,-1037,-1043,-1050,-1056,-1062,-1068,-1074,-1080,-1086, + -1092,-1098,-1104,-1110,-1116,-1122,-1128,-1134,-1140,-1146,-1152,-1158,-1164,-1170,-1176,-1182, + -1189,-1195,-1201,-1207,-1213,-1219,-1225,-1231,-1237,-1243,-1248,-1254,-1260,-1266,-1272,-1278, + -1284,-1290,-1296,-1302,-1308,-1314,-1320,-1326,-1332,-1338,-1344,-1350,-1356,-1362,-1368,-1373, + -1379,-1385,-1391,-1397,-1403,-1409,-1415,-1421,-1427,-1433,-1438,-1444,-1450,-1456,-1462,-1468, + -1474,-1479,-1485,-1491,-1497,-1503,-1509,-1515,-1520,-1526,-1532,-1538,-1544,-1550,-1555,-1561, + -1567,-1573,-1579,-1584,-1590,-1596,-1602,-1608,-1613,-1619,-1625,-1631,-1636,-1642,-1648,-1654, + -1659,-1665,-1671,-1677,-1682,-1688,-1694,-1699,-1705,-1711,-1717,-1722,-1728,-1734,-1739,-1745, + -1751,-1756,-1762,-1768,-1773,-1779,-1785,-1790,-1796,-1802,-1807,-1813,-1819,-1824,-1830,-1835, + -1841,-1847,-1852,-1858,-1864,-1869,-1875,-1880,-1886,-1891,-1897,-1903,-1908,-1914,-1919,-1925, + -1930,-1936,-1941,-1947,-1952,-1958,-1964,-1969,-1975,-1980,-1986,-1991,-1997,-2002,-2007,-2013, + -2018,-2024,-2029,-2035,-2040,-2046,-2051,-2057,-2062,-2067,-2073,-2078,-2084,-2089,-2094,-2100, + -2105,-2111,-2116,-2121,-2127,-2132,-2138,-2143,-2148,-2154,-2159,-2164,-2170,-2175,-2180,-2186, + -2191,-2196,-2201,-2207,-2212,-2217,-2223,-2228,-2233,-2238,-2244,-2249,-2254,-2259,-2265,-2270, + -2275,-2280,-2286,-2291,-2296,-2301,-2306,-2312,-2317,-2322,-2327,-2332,-2337,-2343,-2348,-2353, + -2358,-2363,-2368,-2373,-2379,-2384,-2389,-2394,-2399,-2404,-2409,-2414,-2419,-2424,-2429,-2434, + -2439,-2445,-2450,-2455,-2460,-2465,-2470,-2475,-2480,-2485,-2490,-2495,-2500,-2505,-2510,-2515, + -2519,-2524,-2529,-2534,-2539,-2544,-2549,-2554,-2559,-2564,-2569,-2574,-2578,-2583,-2588,-2593, + -2598,-2603,-2608,-2613,-2617,-2622,-2627,-2632,-2637,-2641,-2646,-2651,-2656,-2661,-2665,-2670, + -2675,-2680,-2684,-2689,-2694,-2699,-2703,-2708,-2713,-2717,-2722,-2727,-2732,-2736,-2741,-2746, + -2750,-2755,-2760,-2764,-2769,-2773,-2778,-2783,-2787,-2792,-2796,-2801,-2806,-2810,-2815,-2819, + -2824,-2828,-2833,-2837,-2842,-2847,-2851,-2856,-2860,-2865,-2869,-2874,-2878,-2882,-2887,-2891, + -2896,-2900,-2905,-2909,-2914,-2918,-2922,-2927,-2931,-2936,-2940,-2944,-2949,-2953,-2957,-2962, + -2966,-2970,-2975,-2979,-2983,-2988,-2992,-2996,-3000,-3005,-3009,-3013,-3018,-3022,-3026,-3030, + -3034,-3039,-3043,-3047,-3051,-3055,-3060,-3064,-3068,-3072,-3076,-3080,-3085,-3089,-3093,-3097, + -3101,-3105,-3109,-3113,-3117,-3121,-3126,-3130,-3134,-3138,-3142,-3146,-3150,-3154,-3158,-3162, + -3166,-3170,-3174,-3178,-3182,-3186,-3190,-3193,-3197,-3201,-3205,-3209,-3213,-3217,-3221,-3225, + -3229,-3232,-3236,-3240,-3244,-3248,-3252,-3255,-3259,-3263,-3267,-3271,-3274,-3278,-3282,-3286, + -3289,-3293,-3297,-3301,-3304,-3308,-3312,-3315,-3319,-3323,-3326,-3330,-3334,-3337,-3341,-3345, + -3348,-3352,-3356,-3359,-3363,-3366,-3370,-3373,-3377,-3381,-3384,-3388,-3391,-3395,-3398,-3402, + -3405,-3409,-3412,-3416,-3419,-3423,-3426,-3429,-3433,-3436,-3440,-3443,-3447,-3450,-3453,-3457, + -3460,-3463,-3467,-3470,-3473,-3477,-3480,-3483,-3487,-3490,-3493,-3497,-3500,-3503,-3506,-3510, + -3513,-3516,-3519,-3522,-3526,-3529,-3532,-3535,-3538,-3541,-3545,-3548,-3551,-3554,-3557,-3560, + -3563,-3566,-3570,-3573,-3576,-3579,-3582,-3585,-3588,-3591,-3594,-3597,-3600,-3603,-3606,-3609, + -3612,-3615,-3618,-3621,-3624,-3627,-3629,-3632,-3635,-3638,-3641,-3644,-3647,-3650,-3652,-3655, + -3658,-3661,-3664,-3667,-3669,-3672,-3675,-3678,-3680,-3683,-3686,-3689,-3691,-3694,-3697,-3700, + -3702,-3705,-3708,-3710,-3713,-3716,-3718,-3721,-3723,-3726,-3729,-3731,-3734,-3736,-3739,-3742, + -3744,-3747,-3749,-3752,-3754,-3757,-3759,-3762,-3764,-3767,-3769,-3772,-3774,-3776,-3779,-3781, + -3784,-3786,-3789,-3791,-3793,-3796,-3798,-3800,-3803,-3805,-3807,-3810,-3812,-3814,-3816,-3819, + -3821,-3823,-3826,-3828,-3830,-3832,-3834,-3837,-3839,-3841,-3843,-3845,-3848,-3850,-3852,-3854, + -3856,-3858,-3860,-3862,-3864,-3867,-3869,-3871,-3873,-3875,-3877,-3879,-3881,-3883,-3885,-3887, + -3889,-3891,-3893,-3895,-3897,-3899,-3900,-3902,-3904,-3906,-3908,-3910,-3912,-3914,-3915,-3917, + -3919,-3921,-3923,-3925,-3926,-3928,-3930,-3932,-3933,-3935,-3937,-3939,-3940,-3942,-3944,-3945, + -3947,-3949,-3950,-3952,-3954,-3955,-3957,-3959,-3960,-3962,-3963,-3965,-3967,-3968,-3970,-3971, + -3973,-3974,-3976,-3977,-3979,-3980,-3982,-3983,-3985,-3986,-3988,-3989,-3990,-3992,-3993,-3995, + -3996,-3997,-3999,-4000,-4001,-4003,-4004,-4005,-4007,-4008,-4009,-4011,-4012,-4013,-4014,-4016, + -4017,-4018,-4019,-4020,-4022,-4023,-4024,-4025,-4026,-4027,-4029,-4030,-4031,-4032,-4033,-4034, + -4035,-4036,-4037,-4038,-4039,-4040,-4041,-4042,-4043,-4044,-4045,-4046,-4047,-4048,-4049,-4050, + -4051,-4052,-4053,-4054,-4055,-4056,-4057,-4057,-4058,-4059,-4060,-4061,-4062,-4062,-4063,-4064, + -4065,-4065,-4066,-4067,-4068,-4068,-4069,-4070,-4071,-4071,-4072,-4073,-4073,-4074,-4075,-4075, + -4076,-4076,-4077,-4078,-4078,-4079,-4079,-4080,-4080,-4081,-4081,-4082,-4082,-4083,-4083,-4084, + -4084,-4085,-4085,-4086,-4086,-4087,-4087,-4087,-4088,-4088,-4089,-4089,-4089,-4090,-4090,-4090, + -4091,-4091,-4091,-4091,-4092,-4092,-4092,-4092,-4093,-4093,-4093,-4093,-4094,-4094,-4094,-4094, + -4094,-4094,-4095,-4095,-4095,-4095,-4095,-4095,-4095,-4095,-4095,-4095,-4095,-4095,-4095,-4095, + + -4096,-4095,-4095,-4095,-4095,-4095,-4095,-4095,-4095,-4095,-4095,-4095,-4095,-4095,-4095,-4094, + -4094,-4094,-4094,-4094,-4094,-4093,-4093,-4093,-4093,-4092,-4092,-4092,-4092,-4091,-4091,-4091, + -4091,-4090,-4090,-4090,-4089,-4089,-4089,-4088,-4088,-4087,-4087,-4087,-4086,-4086,-4085,-4085, + -4084,-4084,-4083,-4083,-4082,-4082,-4081,-4081,-4080,-4080,-4079,-4079,-4078,-4078,-4077,-4076, + -4076,-4075,-4075,-4074,-4073,-4073,-4072,-4071,-4071,-4070,-4069,-4068,-4068,-4067,-4066,-4065, + -4065,-4064,-4063,-4062,-4062,-4061,-4060,-4059,-4058,-4057,-4057,-4056,-4055,-4054,-4053,-4052, + -4051,-4050,-4049,-4048,-4047,-4046,-4045,-4044,-4043,-4042,-4041,-4040,-4039,-4038,-4037,-4036, + -4035,-4034,-4033,-4032,-4031,-4030,-4029,-4027,-4026,-4025,-4024,-4023,-4022,-4020,-4019,-4018, + -4017,-4016,-4014,-4013,-4012,-4011,-4009,-4008,-4007,-4005,-4004,-4003,-4001,-4000,-3999,-3997, + -3996,-3995,-3993,-3992,-3990,-3989,-3988,-3986,-3985,-3983,-3982,-3980,-3979,-3977,-3976,-3974, + -3973,-3971,-3970,-3968,-3967,-3965,-3963,-3962,-3960,-3959,-3957,-3955,-3954,-3952,-3950,-3949, + -3947,-3945,-3944,-3942,-3940,-3939,-3937,-3935,-3933,-3932,-3930,-3928,-3926,-3925,-3923,-3921, + -3919,-3917,-3915,-3914,-3912,-3910,-3908,-3906,-3904,-3902,-3900,-3899,-3897,-3895,-3893,-3891, + -3889,-3887,-3885,-3883,-3881,-3879,-3877,-3875,-3873,-3871,-3869,-3867,-3864,-3862,-3860,-3858, + -3856,-3854,-3852,-3850,-3848,-3845,-3843,-3841,-3839,-3837,-3834,-3832,-3830,-3828,-3826,-3823, + -3821,-3819,-3816,-3814,-3812,-3810,-3807,-3805,-3803,-3800,-3798,-3796,-3793,-3791,-3789,-3786, + -3784,-3781,-3779,-3776,-3774,-3772,-3769,-3767,-3764,-3762,-3759,-3757,-3754,-3752,-3749,-3747, + -3744,-3742,-3739,-3736,-3734,-3731,-3729,-3726,-3723,-3721,-3718,-3716,-3713,-3710,-3708,-3705, + -3702,-3700,-3697,-3694,-3691,-3689,-3686,-3683,-3680,-3678,-3675,-3672,-3669,-3667,-3664,-3661, + -3658,-3655,-3652,-3650,-3647,-3644,-3641,-3638,-3635,-3632,-3629,-3627,-3624,-3621,-3618,-3615, + -3612,-3609,-3606,-3603,-3600,-3597,-3594,-3591,-3588,-3585,-3582,-3579,-3576,-3573,-3570,-3566, + -3563,-3560,-3557,-3554,-3551,-3548,-3545,-3541,-3538,-3535,-3532,-3529,-3526,-3522,-3519,-3516, + -3513,-3510,-3506,-3503,-3500,-3497,-3493,-3490,-3487,-3483,-3480,-3477,-3473,-3470,-3467,-3463, + -3460,-3457,-3453,-3450,-3447,-3443,-3440,-3436,-3433,-3429,-3426,-3423,-3419,-3416,-3412,-3409, + -3405,-3402,-3398,-3395,-3391,-3388,-3384,-3381,-3377,-3373,-3370,-3366,-3363,-3359,-3356,-3352, + -3348,-3345,-3341,-3337,-3334,-3330,-3326,-3323,-3319,-3315,-3312,-3308,-3304,-3301,-3297,-3293, + -3289,-3286,-3282,-3278,-3274,-3271,-3267,-3263,-3259,-3255,-3252,-3248,-3244,-3240,-3236,-3232, + -3229,-3225,-3221,-3217,-3213,-3209,-3205,-3201,-3197,-3193,-3190,-3186,-3182,-3178,-3174,-3170, + -3166,-3162,-3158,-3154,-3150,-3146,-3142,-3138,-3134,-3130,-3126,-3121,-3117,-3113,-3109,-3105, + -3101,-3097,-3093,-3089,-3085,-3080,-3076,-3072,-3068,-3064,-3060,-3055,-3051,-3047,-3043,-3039, + -3034,-3030,-3026,-3022,-3018,-3013,-3009,-3005,-3000,-2996,-2992,-2988,-2983,-2979,-2975,-2970, + -2966,-2962,-2957,-2953,-2949,-2944,-2940,-2936,-2931,-2927,-2922,-2918,-2914,-2909,-2905,-2900, + -2896,-2891,-2887,-2882,-2878,-2874,-2869,-2865,-2860,-2856,-2851,-2847,-2842,-2837,-2833,-2828, + -2824,-2819,-2815,-2810,-2806,-2801,-2796,-2792,-2787,-2783,-2778,-2773,-2769,-2764,-2760,-2755, + -2750,-2746,-2741,-2736,-2732,-2727,-2722,-2717,-2713,-2708,-2703,-2699,-2694,-2689,-2684,-2680, + -2675,-2670,-2665,-2661,-2656,-2651,-2646,-2641,-2637,-2632,-2627,-2622,-2617,-2613,-2608,-2603, + -2598,-2593,-2588,-2583,-2578,-2574,-2569,-2564,-2559,-2554,-2549,-2544,-2539,-2534,-2529,-2524, + -2519,-2515,-2510,-2505,-2500,-2495,-2490,-2485,-2480,-2475,-2470,-2465,-2460,-2455,-2450,-2445, + -2439,-2434,-2429,-2424,-2419,-2414,-2409,-2404,-2399,-2394,-2389,-2384,-2379,-2373,-2368,-2363, + -2358,-2353,-2348,-2343,-2337,-2332,-2327,-2322,-2317,-2312,-2306,-2301,-2296,-2291,-2286,-2280, + -2275,-2270,-2265,-2259,-2254,-2249,-2244,-2238,-2233,-2228,-2223,-2217,-2212,-2207,-2201,-2196, + -2191,-2186,-2180,-2175,-2170,-2164,-2159,-2154,-2148,-2143,-2138,-2132,-2127,-2121,-2116,-2111, + -2105,-2100,-2094,-2089,-2084,-2078,-2073,-2067,-2062,-2057,-2051,-2046,-2040,-2035,-2029,-2024, + -2018,-2013,-2007,-2002,-1997,-1991,-1986,-1980,-1975,-1969,-1964,-1958,-1952,-1947,-1941,-1936, + -1930,-1925,-1919,-1914,-1908,-1903,-1897,-1891,-1886,-1880,-1875,-1869,-1864,-1858,-1852,-1847, + -1841,-1835,-1830,-1824,-1819,-1813,-1807,-1802,-1796,-1790,-1785,-1779,-1773,-1768,-1762,-1756, + -1751,-1745,-1739,-1734,-1728,-1722,-1717,-1711,-1705,-1699,-1694,-1688,-1682,-1677,-1671,-1665, + -1659,-1654,-1648,-1642,-1636,-1631,-1625,-1619,-1613,-1608,-1602,-1596,-1590,-1584,-1579,-1573, + -1567,-1561,-1555,-1550,-1544,-1538,-1532,-1526,-1520,-1515,-1509,-1503,-1497,-1491,-1485,-1479, + -1474,-1468,-1462,-1456,-1450,-1444,-1438,-1433,-1427,-1421,-1415,-1409,-1403,-1397,-1391,-1385, + -1379,-1373,-1368,-1362,-1356,-1350,-1344,-1338,-1332,-1326,-1320,-1314,-1308,-1302,-1296,-1290, + -1284,-1278,-1272,-1266,-1260,-1254,-1248,-1243,-1237,-1231,-1225,-1219,-1213,-1207,-1201,-1195, + -1189,-1182,-1176,-1170,-1164,-1158,-1152,-1146,-1140,-1134,-1128,-1122,-1116,-1110,-1104,-1098, + -1092,-1086,-1080,-1074,-1068,-1062,-1056,-1050,-1043,-1037,-1031,-1025,-1019,-1013,-1007,-1001, + -995, -989, -983, -976, -970, -964, -958, -952, -946, -940, -934, -928, -921, -915, -909, -903, + -897, -891, -885, -879, -872, -866, -860, -854, -848, -842, -836, -829, -823, -817, -811, -805, + -799, -792, -786, -780, -774, -768, -762, -755, -749, -743, -737, -731, -725, -718, -712, -706, + -700, -694, -687, -681, -675, -669, -663, -656, -650, -644, -638, -632, -625, -619, -613, -607, + -601, -594, -588, -582, -576, -569, -563, -557, -551, -545, -538, -532, -526, -520, -513, -507, + -501, -495, -488, -482, -476, -470, -463, -457, -451, -445, -438, -432, -426, -420, -413, -407, + -401, -395, -388, -382, -376, -370, -363, -357, -351, -345, -338, -332, -326, -320, -313, -307, + -301, -295, -288, -282, -276, -269, -263, -257, -251, -244, -238, -232, -226, -219, -213, -207, + -200, -194, -188, -182, -175, -169, -163, -157, -150, -144, -138, -131, -125, -119, -113, -106, + -100, -94, -87, -81, -75, -69, -62, -56, -50, -43, -37, -31, -25, -18, -12, -6, + + 0, 6, 12, 18, 25, 31, 37, 43, 50, 56, 62, 69, 75, 81, 87, 94, + 100, 106, 113, 119, 125, 131, 138, 144, 150, 157, 163, 169, 175, 182, 188, 194, + 200, 207, 213, 219, 226, 232, 238, 244, 251, 257, 263, 269, 276, 282, 288, 295, + 301, 307, 313, 320, 326, 332, 338, 345, 351, 357, 363, 370, 376, 382, 388, 395, + 401, 407, 413, 420, 426, 432, 438, 445, 451, 457, 463, 470, 476, 482, 488, 495, + 501, 507, 513, 520, 526, 532, 538, 545, 551, 557, 563, 569, 576, 582, 588, 594, + 601, 607, 613, 619, 625, 632, 638, 644, 650, 656, 663, 669, 675, 681, 687, 694, + 700, 706, 712, 718, 725, 731, 737, 743, 749, 755, 762, 768, 774, 780, 786, 792, + 799, 805, 811, 817, 823, 829, 836, 842, 848, 854, 860, 866, 872, 879, 885, 891, + 897, 903, 909, 915, 921, 928, 934, 940, 946, 952, 958, 964, 970, 976, 983, 989, + 995, 1001, 1007, 1013, 1019, 1025, 1031, 1037, 1043, 1050, 1056, 1062, 1068, 1074, 1080, 1086, + 1092, 1098, 1104, 1110, 1116, 1122, 1128, 1134, 1140, 1146, 1152, 1158, 1164, 1170, 1176, 1182, + 1189, 1195, 1201, 1207, 1213, 1219, 1225, 1231, 1237, 1243, 1248, 1254, 1260, 1266, 1272, 1278, + 1284, 1290, 1296, 1302, 1308, 1314, 1320, 1326, 1332, 1338, 1344, 1350, 1356, 1362, 1368, 1373, + 1379, 1385, 1391, 1397, 1403, 1409, 1415, 1421, 1427, 1433, 1438, 1444, 1450, 1456, 1462, 1468, + 1474, 1479, 1485, 1491, 1497, 1503, 1509, 1515, 1520, 1526, 1532, 1538, 1544, 1550, 1555, 1561, + 1567, 1573, 1579, 1584, 1590, 1596, 1602, 1608, 1613, 1619, 1625, 1631, 1636, 1642, 1648, 1654, + 1659, 1665, 1671, 1677, 1682, 1688, 1694, 1699, 1705, 1711, 1717, 1722, 1728, 1734, 1739, 1745, + 1751, 1756, 1762, 1768, 1773, 1779, 1785, 1790, 1796, 1802, 1807, 1813, 1819, 1824, 1830, 1835, + 1841, 1847, 1852, 1858, 1864, 1869, 1875, 1880, 1886, 1891, 1897, 1903, 1908, 1914, 1919, 1925, + 1930, 1936, 1941, 1947, 1952, 1958, 1964, 1969, 1975, 1980, 1986, 1991, 1997, 2002, 2007, 2013, + 2018, 2024, 2029, 2035, 2040, 2046, 2051, 2057, 2062, 2067, 2073, 2078, 2084, 2089, 2094, 2100, + 2105, 2111, 2116, 2121, 2127, 2132, 2138, 2143, 2148, 2154, 2159, 2164, 2170, 2175, 2180, 2186, + 2191, 2196, 2201, 2207, 2212, 2217, 2223, 2228, 2233, 2238, 2244, 2249, 2254, 2259, 2265, 2270, + 2275, 2280, 2286, 2291, 2296, 2301, 2306, 2312, 2317, 2322, 2327, 2332, 2337, 2343, 2348, 2353, + 2358, 2363, 2368, 2373, 2379, 2384, 2389, 2394, 2399, 2404, 2409, 2414, 2419, 2424, 2429, 2434, + 2439, 2445, 2450, 2455, 2460, 2465, 2470, 2475, 2480, 2485, 2490, 2495, 2500, 2505, 2510, 2515, + 2519, 2524, 2529, 2534, 2539, 2544, 2549, 2554, 2559, 2564, 2569, 2574, 2578, 2583, 2588, 2593, + 2598, 2603, 2608, 2613, 2617, 2622, 2627, 2632, 2637, 2641, 2646, 2651, 2656, 2661, 2665, 2670, + 2675, 2680, 2684, 2689, 2694, 2699, 2703, 2708, 2713, 2717, 2722, 2727, 2732, 2736, 2741, 2746, + 2750, 2755, 2760, 2764, 2769, 2773, 2778, 2783, 2787, 2792, 2796, 2801, 2806, 2810, 2815, 2819, + 2824, 2828, 2833, 2837, 2842, 2847, 2851, 2856, 2860, 2865, 2869, 2874, 2878, 2882, 2887, 2891, + 2896, 2900, 2905, 2909, 2914, 2918, 2922, 2927, 2931, 2936, 2940, 2944, 2949, 2953, 2957, 2962, + 2966, 2970, 2975, 2979, 2983, 2988, 2992, 2996, 3000, 3005, 3009, 3013, 3018, 3022, 3026, 3030, + 3034, 3039, 3043, 3047, 3051, 3055, 3060, 3064, 3068, 3072, 3076, 3080, 3085, 3089, 3093, 3097, + 3101, 3105, 3109, 3113, 3117, 3121, 3126, 3130, 3134, 3138, 3142, 3146, 3150, 3154, 3158, 3162, + 3166, 3170, 3174, 3178, 3182, 3186, 3190, 3193, 3197, 3201, 3205, 3209, 3213, 3217, 3221, 3225, + 3229, 3232, 3236, 3240, 3244, 3248, 3252, 3255, 3259, 3263, 3267, 3271, 3274, 3278, 3282, 3286, + 3289, 3293, 3297, 3301, 3304, 3308, 3312, 3315, 3319, 3323, 3326, 3330, 3334, 3337, 3341, 3345, + 3348, 3352, 3356, 3359, 3363, 3366, 3370, 3373, 3377, 3381, 3384, 3388, 3391, 3395, 3398, 3402, + 3405, 3409, 3412, 3416, 3419, 3423, 3426, 3429, 3433, 3436, 3440, 3443, 3447, 3450, 3453, 3457, + 3460, 3463, 3467, 3470, 3473, 3477, 3480, 3483, 3487, 3490, 3493, 3497, 3500, 3503, 3506, 3510, + 3513, 3516, 3519, 3522, 3526, 3529, 3532, 3535, 3538, 3541, 3545, 3548, 3551, 3554, 3557, 3560, + 3563, 3566, 3570, 3573, 3576, 3579, 3582, 3585, 3588, 3591, 3594, 3597, 3600, 3603, 3606, 3609, + 3612, 3615, 3618, 3621, 3624, 3627, 3629, 3632, 3635, 3638, 3641, 3644, 3647, 3650, 3652, 3655, + 3658, 3661, 3664, 3667, 3669, 3672, 3675, 3678, 3680, 3683, 3686, 3689, 3691, 3694, 3697, 3700, + 3702, 3705, 3708, 3710, 3713, 3716, 3718, 3721, 3723, 3726, 3729, 3731, 3734, 3736, 3739, 3742, + 3744, 3747, 3749, 3752, 3754, 3757, 3759, 3762, 3764, 3767, 3769, 3772, 3774, 3776, 3779, 3781, + 3784, 3786, 3789, 3791, 3793, 3796, 3798, 3800, 3803, 3805, 3807, 3810, 3812, 3814, 3816, 3819, + 3821, 3823, 3826, 3828, 3830, 3832, 3834, 3837, 3839, 3841, 3843, 3845, 3848, 3850, 3852, 3854, + 3856, 3858, 3860, 3862, 3864, 3867, 3869, 3871, 3873, 3875, 3877, 3879, 3881, 3883, 3885, 3887, + 3889, 3891, 3893, 3895, 3897, 3899, 3900, 3902, 3904, 3906, 3908, 3910, 3912, 3914, 3915, 3917, + 3919, 3921, 3923, 3925, 3926, 3928, 3930, 3932, 3933, 3935, 3937, 3939, 3940, 3942, 3944, 3945, + 3947, 3949, 3950, 3952, 3954, 3955, 3957, 3959, 3960, 3962, 3963, 3965, 3967, 3968, 3970, 3971, + 3973, 3974, 3976, 3977, 3979, 3980, 3982, 3983, 3985, 3986, 3988, 3989, 3990, 3992, 3993, 3995, + 3996, 3997, 3999, 4000, 4001, 4003, 4004, 4005, 4007, 4008, 4009, 4011, 4012, 4013, 4014, 4016, + 4017, 4018, 4019, 4020, 4022, 4023, 4024, 4025, 4026, 4027, 4029, 4030, 4031, 4032, 4033, 4034, + 4035, 4036, 4037, 4038, 4039, 4040, 4041, 4042, 4043, 4044, 4045, 4046, 4047, 4048, 4049, 4050, + 4051, 4052, 4053, 4054, 4055, 4056, 4057, 4057, 4058, 4059, 4060, 4061, 4062, 4062, 4063, 4064, + 4065, 4065, 4066, 4067, 4068, 4068, 4069, 4070, 4071, 4071, 4072, 4073, 4073, 4074, 4075, 4075, + 4076, 4076, 4077, 4078, 4078, 4079, 4079, 4080, 4080, 4081, 4081, 4082, 4082, 4083, 4083, 4084, + 4084, 4085, 4085, 4086, 4086, 4087, 4087, 4087, 4088, 4088, 4089, 4089, 4089, 4090, 4090, 4090, + 4091, 4091, 4091, 4091, 4092, 4092, 4092, 4092, 4093, 4093, 4093, 4093, 4094, 4094, 4094, 4094, + 4094, 4094, 4095, 4095, 4095, 4095, 4095, 4095, 4095, 4095, 4095, 4095, 4095, 4095, 4095, 4095, + + 4096, +}; + +/* code can't actually access 2nd index >8 though */ +static const int scale_table[5][8*2] = { + { 2048, 2048, 4096, 4096, 8192, 8192,16384,16384, 1, 1, 1, 1, 1, 1, 1, 1, }, + { 2048, 2048, 2048, 4096, 4096, 4096, 8192,16384, 1, 1, 1, 1, 1, 1, 1, 1, }, + { 2048, 2048, 2048, 2048, 2048, 4096, 4096, 8192, 1, 1, 1, 1, 1, 1, 1, 1, }, + { 1024, 1024, 1024, 2048, 2048, 2048, 2048, 2048, 1, 1, 1, 1, 1, 1, 1, 1, }, + { 1365, 1365, 2048, 2730, 2730, 4096, 4096, 4096, 1, 1, 1, 1, 1, 1, 1, 1, }, +}; + +#endif diff --git a/Frameworks/vgmstream/vgmstream/src/coding/circus_decoder_lzxpcm.h b/Frameworks/vgmstream/vgmstream/src/coding/circus_decoder_lzxpcm.h new file mode 100644 index 000000000..b457f700d --- /dev/null +++ b/Frameworks/vgmstream/vgmstream/src/coding/circus_decoder_lzxpcm.h @@ -0,0 +1,297 @@ +#include +#include +#include +#include + +/* Decompresses Circus's custom LZ used in XPCM as a machine state for streaming, + * that may break during any step. Original code decompress at once the full thing + * into memory so it's simpler. */ + +#define LZXPCM_OK 0 +#define LZXPCM_ERROR -1 +#define LZXPCM_WINDOW_SIZE (1 << 16) + + +typedef enum { + READ_FLAGS, + COPY_LITERAL, + READ_TOKEN, + PARSE_TOKEN, + SET_MATCH, + COPY_MATCH +} lzxpcm_state_t; + +typedef struct { + lzxpcm_state_t state; + + uint32_t flags; + uint8_t token; + int values_pos; + int offset_pos; + int match_len; + int match_pos; + + int window_pos; + uint8_t window[LZXPCM_WINDOW_SIZE]; +} lzxpcm_context_t; + +typedef struct { + lzxpcm_context_t ctx; + + uint8_t *next_out; /* next bytes to write (reassign when avail is 0) */ + int avail_out; /* bytes available at next_out */ + int total_out; /* written bytes, for reference (set to 0 per call if needed) */ + + const uint8_t *next_in; /* next bytes to read (reassign when avail is 0) */ + int avail_in; /* bytes available at next_in */ + int total_in; /* read bytes, for reference (set to 0 per call if needed) */ +} lzxpcm_stream_t; + + +static void lzxpcm_reset(lzxpcm_stream_t* strm) { + memset(strm, 0, sizeof(lzxpcm_stream_t)); +} + +/* Decompress src into dst, returning a code and number of bytes used. Caller must handle + * stop (when no more input data or all data has been decompressed) as LZXPCM has no end marker. */ +static int lzxpcm_decompress(lzxpcm_stream_t* strm) { + lzxpcm_context_t* ctx = &strm->ctx; + uint8_t* dst = strm->next_out; + const uint8_t* src = strm->next_in; + int dst_size = strm->avail_out; + int src_size = strm->avail_in; + int dst_pos = 0; + int src_pos = 0; + uint8_t next_val; + + + while (1) { + /* mostly linear state machine, but it may break anytime when reaching dst or src + * end, and resume from same state in next call */ + switch(ctx->state) { + + case READ_FLAGS: + if (src_pos >= src_size) + goto buffer_end; + + ctx->flags >>= 1; + + if ((ctx->flags & 0x0100) == 0) { + ctx->flags = 0xFF00 | src[src_pos++]; + } + + if (ctx->flags & 1) + ctx->state = COPY_LITERAL; + else + ctx->state = READ_TOKEN; + break; + + case COPY_LITERAL: + if (src_pos >= src_size || dst_pos >= dst_size) + goto buffer_end; + next_val = src[src_pos++]; + + dst[dst_pos++] = next_val; + + ctx->window[ctx->window_pos++] = next_val; + if (ctx->window_pos == LZXPCM_WINDOW_SIZE) + ctx->window_pos = 0; + + ctx->state = READ_FLAGS; + break; + + case READ_TOKEN: + if (src_pos >= src_size) + goto buffer_end; + ctx->token = src[src_pos++]; + + ctx->values_pos = 0; + + ctx->state = PARSE_TOKEN; + break; + + case PARSE_TOKEN: + if (ctx->token >= 0xC0) { + ctx->match_len = ((ctx->token >> 2) & 0x0F) + 4; /* 6b */ + + if (src_pos >= src_size) + goto buffer_end; + ctx->offset_pos = src[src_pos++]; /* upper 2b + lower 8b */ + ctx->offset_pos |= ((ctx->token & 3) << 8); + + } + else if (ctx->token >= 0x80) { + ctx->match_len = ((ctx->token >> 5) & 3) + 2; /* 2b */ + + ctx->offset_pos = ctx->token & 0x1F; /* 5b */ + if (ctx->offset_pos == 0) { + if (src_pos >= src_size) + goto buffer_end; + ctx->offset_pos = src[src_pos++]; + } + } + else if (ctx->token == 0x7F) { + if (ctx->values_pos == 0) { + if (src_pos >= src_size) + goto buffer_end; + ctx->match_len = (src[src_pos++] << 0u); + ctx->values_pos++; + } + + if (ctx->values_pos == 1) { + if (src_pos >= src_size) + goto buffer_end; + ctx->match_len |= (src[src_pos++] << 8u); + ctx->match_len += 2; + ctx->values_pos++; + } + + if (ctx->values_pos == 2) { + if (src_pos >= src_size) + goto buffer_end; + ctx->offset_pos = (src[src_pos++] << 0u); + ctx->values_pos++; + } + + if (ctx->values_pos == 3) { + if (src_pos >= src_size) + goto buffer_end; + ctx->offset_pos |= (src[src_pos++] << 8u); + ctx->values_pos++; + } + } + else { + ctx->match_len = ctx->token + 4; + + if (ctx->values_pos == 0) { + if (src_pos >= src_size) + goto buffer_end; + ctx->offset_pos = (src[src_pos++] << 0u); + ctx->values_pos++; + } + + if (ctx->values_pos == 1) { + if (src_pos >= src_size) + goto buffer_end; + ctx->offset_pos |= (src[src_pos++] << 8u); + ctx->values_pos++; + } + } + + ctx->state = SET_MATCH; + break; + + case SET_MATCH: + ctx->match_pos = ctx->window_pos - ctx->offset_pos; + if (ctx->match_pos < 0) /* circular buffer so negative is from window end */ + ctx->match_pos = LZXPCM_WINDOW_SIZE + ctx->match_pos; + + ctx->state = COPY_MATCH; + break; + + case COPY_MATCH: + while (ctx->match_len > 0) { + if (dst_pos >= dst_size) + goto buffer_end; + + next_val = ctx->window[ctx->match_pos++]; + if (ctx->match_pos == LZXPCM_WINDOW_SIZE) + ctx->match_pos = 0; + + dst[dst_pos++] = next_val; + + ctx->window[ctx->window_pos++] = next_val; + if (ctx->window_pos == LZXPCM_WINDOW_SIZE) + ctx->window_pos = 0; + + ctx->match_len--; + }; + + ctx->state = READ_FLAGS; + break; + + default: + goto fail; + } + } + +buffer_end: + strm->next_out += dst_pos; + strm->next_in += src_pos; + strm->avail_out -= dst_pos; + strm->avail_in -= src_pos; + strm->total_out += dst_pos; + strm->total_in += src_pos; + + return LZXPCM_OK; +fail: + return LZXPCM_ERROR; +} + + +#if 0 +/* non-streamed form that XPCM originally uses, assumes buffers are big enough */ +static int lzxpcm_decompress_full(uint8_t* dst, size_t dst_size, const uint8_t* src, size_t src_size) { + int src_pos = 0; + int dst_pos = 0; + uint32_t flags = 0; + + + while (src_pos < src_size && dst_pos < dst_size) { + flags >>= 1; + + if ((flags & 0x0100) == 0) { + flags = 0xFF00 | src[src_pos++]; + } + + if (flags & 1) { + /* uncompressed byte per bit */ + dst[dst_pos++] = src[src_pos++]; + } + else { + /* compressed data */ + uint32_t length; + uint32_t offset; + const uint32_t token = src[src_pos++]; + + if (token >= 0xC0) { + length = ((token >> 2) & 0x0F) + 4; /* 6b */ + + offset = ((token & 3) << 8) | src[src_pos++]; /* upper 2b + lower 8b */ + } + else if (token >= 0x80) { + length = ((token >> 5) & 3) + 2; /* 2b */ + + offset = token & 0x1F; /* 5b */ + if (offset == 0) { + offset = src[src_pos++]; + } + } + else if (token == 0x7F) { + length = (uint16_t)(src[src_pos] | src[src_pos+1] << 8u) + 2; + src_pos += 2; + + offset = (uint16_t)(src[src_pos] | src[src_pos+1] << 8u); + src_pos += 2; + } + else { + length = token + 4; + + offset = (uint16_t)(src[src_pos] | src[src_pos+1] << 8u); + src_pos += 2; + } + + if (dst_pos + length > dst_size) { + length = dst_size - dst_pos; + } + + for (int i = 0; i < length; i++) { + dst[dst_pos] = dst[dst_pos - offset]; + dst_pos++; + } + } + } + + return 0; +} +#endif diff --git a/Frameworks/vgmstream/vgmstream/src/coding/circus_decoder_miniz.c b/Frameworks/vgmstream/vgmstream/src/coding/circus_decoder_miniz.c new file mode 100644 index 000000000..bede01593 --- /dev/null +++ b/Frameworks/vgmstream/vgmstream/src/coding/circus_decoder_miniz.c @@ -0,0 +1,7657 @@ +/************************************************************************** + * + * Copyright 2013-2014 RAD Game Tools and Valve Software + * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC + * All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + **************************************************************************/ + +#include "circus_decoder_miniz.h" + +typedef unsigned char mz_validate_uint16[sizeof(mz_uint16) == 2 ? 1 : -1]; +typedef unsigned char mz_validate_uint32[sizeof(mz_uint32) == 4 ? 1 : -1]; +typedef unsigned char mz_validate_uint64[sizeof(mz_uint64) == 8 ? 1 : -1]; + +#ifdef __cplusplus +extern "C" { +#endif + +/* ------------------- zlib-style API's */ + +mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len) +{ + mz_uint32 i, s1 = (mz_uint32)(adler & 0xffff), s2 = (mz_uint32)(adler >> 16); + size_t block_len = buf_len % 5552; + if (!ptr) + return MZ_ADLER32_INIT; + while (buf_len) + { + for (i = 0; i + 7 < block_len; i += 8, ptr += 8) + { + s1 += ptr[0], s2 += s1; + s1 += ptr[1], s2 += s1; + s1 += ptr[2], s2 += s1; + s1 += ptr[3], s2 += s1; + s1 += ptr[4], s2 += s1; + s1 += ptr[5], s2 += s1; + s1 += ptr[6], s2 += s1; + s1 += ptr[7], s2 += s1; + } + for (; i < block_len; ++i) + s1 += *ptr++, s2 += s1; + s1 %= 65521U, s2 %= 65521U; + buf_len -= block_len; + block_len = 5552; + } + return (s2 << 16) + s1; +} + +/* Karl Malbrain's compact CRC-32. See "A compact CCITT crc16 and crc32 C implementation that balances processor cache usage against speed": http://www.geocities.com/malbrain/ */ +#if 0 + mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len) + { + static const mz_uint32 s_crc32[16] = { 0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c, + 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c }; + mz_uint32 crcu32 = (mz_uint32)crc; + if (!ptr) + return MZ_CRC32_INIT; + crcu32 = ~crcu32; + while (buf_len--) + { + mz_uint8 b = *ptr++; + crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b & 0xF)]; + crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b >> 4)]; + } + return ~crcu32; + } +#else +/* Faster, but larger CPU cache footprint. + */ +mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len) +{ + static const mz_uint32 s_crc_table[256] = + { + 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, + 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, + 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, + 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, + 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, + 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, + 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, + 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, + 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, + 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, + 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, + 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, + 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, + 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, + 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, + 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, + 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, + 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, + 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, + 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, + 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, + 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, + 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, + 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, + 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, + 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, + 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, + 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, + 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, + 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, + 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, + 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, + 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, + 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, + 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, + 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, + 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D + }; + + mz_uint32 crc32 = (mz_uint32)crc ^ 0xFFFFFFFF; + const mz_uint8 *pByte_buf = (const mz_uint8 *)ptr; + + while (buf_len >= 4) + { + crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[0]) & 0xFF]; + crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[1]) & 0xFF]; + crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[2]) & 0xFF]; + crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[3]) & 0xFF]; + pByte_buf += 4; + buf_len -= 4; + } + + while (buf_len) + { + crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[0]) & 0xFF]; + ++pByte_buf; + --buf_len; + } + + return ~crc32; +} +#endif + +void mz_free(void *p) +{ + MZ_FREE(p); +} + +void *miniz_def_alloc_func(void *opaque, size_t items, size_t size) +{ + (void)opaque, (void)items, (void)size; + return MZ_MALLOC(items * size); +} +void miniz_def_free_func(void *opaque, void *address) +{ + (void)opaque, (void)address; + MZ_FREE(address); +} +void *miniz_def_realloc_func(void *opaque, void *address, size_t items, size_t size) +{ + (void)opaque, (void)address, (void)items, (void)size; + return MZ_REALLOC(address, items * size); +} + +const char *mz_version(void) +{ + return MZ_VERSION; +} + +#ifndef MINIZ_NO_ZLIB_APIS + +int mz_deflateInit(mz_streamp pStream, int level) +{ + return mz_deflateInit2(pStream, level, MZ_DEFLATED, MZ_DEFAULT_WINDOW_BITS, 9, MZ_DEFAULT_STRATEGY); +} + +int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy) +{ + tdefl_compressor *pComp; + mz_uint comp_flags = TDEFL_COMPUTE_ADLER32 | tdefl_create_comp_flags_from_zip_params(level, window_bits, strategy); + + if (!pStream) + return MZ_STREAM_ERROR; + if ((method != MZ_DEFLATED) || ((mem_level < 1) || (mem_level > 9)) || ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS))) + return MZ_PARAM_ERROR; + + pStream->data_type = 0; + pStream->adler = MZ_ADLER32_INIT; + pStream->msg = NULL; + pStream->reserved = 0; + pStream->total_in = 0; + pStream->total_out = 0; + if (!pStream->zalloc) + pStream->zalloc = miniz_def_alloc_func; + if (!pStream->zfree) + pStream->zfree = miniz_def_free_func; + + pComp = (tdefl_compressor *)pStream->zalloc(pStream->opaque, 1, sizeof(tdefl_compressor)); + if (!pComp) + return MZ_MEM_ERROR; + + pStream->state = (struct mz_internal_state *)pComp; + + if (tdefl_init(pComp, NULL, NULL, comp_flags) != TDEFL_STATUS_OKAY) + { + mz_deflateEnd(pStream); + return MZ_PARAM_ERROR; + } + + return MZ_OK; +} + +int mz_deflateReset(mz_streamp pStream) +{ + if ((!pStream) || (!pStream->state) || (!pStream->zalloc) || (!pStream->zfree)) + return MZ_STREAM_ERROR; + pStream->total_in = pStream->total_out = 0; + tdefl_init((tdefl_compressor *)pStream->state, NULL, NULL, ((tdefl_compressor *)pStream->state)->m_flags); + return MZ_OK; +} + +int mz_deflate(mz_streamp pStream, int flush) +{ + size_t in_bytes, out_bytes; + mz_ulong orig_total_in, orig_total_out; + int mz_status = MZ_OK; + + if ((!pStream) || (!pStream->state) || (flush < 0) || (flush > MZ_FINISH) || (!pStream->next_out)) + return MZ_STREAM_ERROR; + if (!pStream->avail_out) + return MZ_BUF_ERROR; + + if (flush == MZ_PARTIAL_FLUSH) + flush = MZ_SYNC_FLUSH; + + if (((tdefl_compressor *)pStream->state)->m_prev_return_status == TDEFL_STATUS_DONE) + return (flush == MZ_FINISH) ? MZ_STREAM_END : MZ_BUF_ERROR; + + orig_total_in = pStream->total_in; + orig_total_out = pStream->total_out; + for (;;) + { + tdefl_status defl_status; + in_bytes = pStream->avail_in; + out_bytes = pStream->avail_out; + + defl_status = tdefl_compress((tdefl_compressor *)pStream->state, pStream->next_in, &in_bytes, pStream->next_out, &out_bytes, (tdefl_flush)flush); + pStream->next_in += (mz_uint)in_bytes; + pStream->avail_in -= (mz_uint)in_bytes; + pStream->total_in += (mz_uint)in_bytes; + pStream->adler = tdefl_get_adler32((tdefl_compressor *)pStream->state); + + pStream->next_out += (mz_uint)out_bytes; + pStream->avail_out -= (mz_uint)out_bytes; + pStream->total_out += (mz_uint)out_bytes; + + if (defl_status < 0) + { + mz_status = MZ_STREAM_ERROR; + break; + } + else if (defl_status == TDEFL_STATUS_DONE) + { + mz_status = MZ_STREAM_END; + break; + } + else if (!pStream->avail_out) + break; + else if ((!pStream->avail_in) && (flush != MZ_FINISH)) + { + if ((flush) || (pStream->total_in != orig_total_in) || (pStream->total_out != orig_total_out)) + break; + return MZ_BUF_ERROR; /* Can't make forward progress without some input. + */ + } + } + return mz_status; +} + +int mz_deflateEnd(mz_streamp pStream) +{ + if (!pStream) + return MZ_STREAM_ERROR; + if (pStream->state) + { + pStream->zfree(pStream->opaque, pStream->state); + pStream->state = NULL; + } + return MZ_OK; +} + +mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len) +{ + (void)pStream; + /* This is really over conservative. (And lame, but it's actually pretty tricky to compute a true upper bound given the way tdefl's blocking works.) */ + return MZ_MAX(128 + (source_len * 110) / 100, 128 + source_len + ((source_len / (31 * 1024)) + 1) * 5); +} + +int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level) +{ + int status; + mz_stream stream; + memset(&stream, 0, sizeof(stream)); + + /* In case mz_ulong is 64-bits (argh I hate longs). */ + if ((source_len | *pDest_len) > 0xFFFFFFFFU) + return MZ_PARAM_ERROR; + + stream.next_in = pSource; + stream.avail_in = (mz_uint32)source_len; + stream.next_out = pDest; + stream.avail_out = (mz_uint32)*pDest_len; + + status = mz_deflateInit(&stream, level); + if (status != MZ_OK) + return status; + + status = mz_deflate(&stream, MZ_FINISH); + if (status != MZ_STREAM_END) + { + mz_deflateEnd(&stream); + return (status == MZ_OK) ? MZ_BUF_ERROR : status; + } + + *pDest_len = stream.total_out; + return mz_deflateEnd(&stream); +} + +int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len) +{ + return mz_compress2(pDest, pDest_len, pSource, source_len, MZ_DEFAULT_COMPRESSION); +} + +mz_ulong mz_compressBound(mz_ulong source_len) +{ + return mz_deflateBound(NULL, source_len); +} + +typedef struct +{ + tinfl_decompressor m_decomp; + mz_uint m_dict_ofs, m_dict_avail, m_first_call, m_has_flushed; + int m_window_bits; + mz_uint8 m_dict[TINFL_LZ_DICT_SIZE]; + tinfl_status m_last_status; +} inflate_state; + +int mz_inflateInit2(mz_streamp pStream, int window_bits) +{ + inflate_state *pDecomp; + if (!pStream) + return MZ_STREAM_ERROR; + if ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS)) + return MZ_PARAM_ERROR; + + pStream->data_type = 0; + pStream->adler = 0; + pStream->msg = NULL; + pStream->total_in = 0; + pStream->total_out = 0; + pStream->reserved = 0; + if (!pStream->zalloc) + pStream->zalloc = miniz_def_alloc_func; + if (!pStream->zfree) + pStream->zfree = miniz_def_free_func; + + pDecomp = (inflate_state *)pStream->zalloc(pStream->opaque, 1, sizeof(inflate_state)); + if (!pDecomp) + return MZ_MEM_ERROR; + + pStream->state = (struct mz_internal_state *)pDecomp; + + tinfl_init(&pDecomp->m_decomp); + pDecomp->m_dict_ofs = 0; + pDecomp->m_dict_avail = 0; + pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT; + pDecomp->m_first_call = 1; + pDecomp->m_has_flushed = 0; + pDecomp->m_window_bits = window_bits; + + return MZ_OK; +} + +int mz_inflateInit(mz_streamp pStream) +{ + return mz_inflateInit2(pStream, MZ_DEFAULT_WINDOW_BITS); +} + +int mz_inflateReset(mz_streamp pStream) +{ + inflate_state *pDecomp; + if (!pStream) + return MZ_STREAM_ERROR; + + pStream->data_type = 0; + pStream->adler = 0; + pStream->msg = NULL; + pStream->total_in = 0; + pStream->total_out = 0; + pStream->reserved = 0; + + pDecomp = (inflate_state *)pStream->state; + + tinfl_init(&pDecomp->m_decomp); + pDecomp->m_dict_ofs = 0; + pDecomp->m_dict_avail = 0; + pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT; + pDecomp->m_first_call = 1; + pDecomp->m_has_flushed = 0; + /* pDecomp->m_window_bits = window_bits */; + + return MZ_OK; +} + +int mz_inflate(mz_streamp pStream, int flush) +{ + inflate_state *pState; + mz_uint n, first_call, decomp_flags = TINFL_FLAG_COMPUTE_ADLER32; + size_t in_bytes, out_bytes, orig_avail_in; + tinfl_status status; + + if ((!pStream) || (!pStream->state)) + return MZ_STREAM_ERROR; + if (flush == MZ_PARTIAL_FLUSH) + flush = MZ_SYNC_FLUSH; + if ((flush) && (flush != MZ_SYNC_FLUSH) && (flush != MZ_FINISH)) + return MZ_STREAM_ERROR; + + pState = (inflate_state *)pStream->state; + if (pState->m_window_bits > 0) + decomp_flags |= TINFL_FLAG_PARSE_ZLIB_HEADER; + orig_avail_in = pStream->avail_in; + + first_call = pState->m_first_call; + pState->m_first_call = 0; + if (pState->m_last_status < 0) + return MZ_DATA_ERROR; + + if (pState->m_has_flushed && (flush != MZ_FINISH)) + return MZ_STREAM_ERROR; + pState->m_has_flushed |= (flush == MZ_FINISH); + + if ((flush == MZ_FINISH) && (first_call)) + { + /* MZ_FINISH on the first call implies that the input and output buffers are large enough to hold the entire compressed/decompressed file. */ + decomp_flags |= TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF; + in_bytes = pStream->avail_in; + out_bytes = pStream->avail_out; + status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pStream->next_out, pStream->next_out, &out_bytes, decomp_flags); + pState->m_last_status = status; + pStream->next_in += (mz_uint)in_bytes; + pStream->avail_in -= (mz_uint)in_bytes; + pStream->total_in += (mz_uint)in_bytes; + pStream->adler = tinfl_get_adler32(&pState->m_decomp); + pStream->next_out += (mz_uint)out_bytes; + pStream->avail_out -= (mz_uint)out_bytes; + pStream->total_out += (mz_uint)out_bytes; + + if (status < 0) + return MZ_DATA_ERROR; + else if (status != TINFL_STATUS_DONE) + { + pState->m_last_status = TINFL_STATUS_FAILED; + return MZ_BUF_ERROR; + } + return MZ_STREAM_END; + } + /* flush != MZ_FINISH then we must assume there's more input. */ + if (flush != MZ_FINISH) + decomp_flags |= TINFL_FLAG_HAS_MORE_INPUT; + + if (pState->m_dict_avail) + { + n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); + memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); + pStream->next_out += n; + pStream->avail_out -= n; + pStream->total_out += n; + pState->m_dict_avail -= n; + pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); + return ((pState->m_last_status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; + } + + for (;;) + { + in_bytes = pStream->avail_in; + out_bytes = TINFL_LZ_DICT_SIZE - pState->m_dict_ofs; + + status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pState->m_dict, pState->m_dict + pState->m_dict_ofs, &out_bytes, decomp_flags); + pState->m_last_status = status; + + pStream->next_in += (mz_uint)in_bytes; + pStream->avail_in -= (mz_uint)in_bytes; + pStream->total_in += (mz_uint)in_bytes; + pStream->adler = tinfl_get_adler32(&pState->m_decomp); + + pState->m_dict_avail = (mz_uint)out_bytes; + + n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); + memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); + pStream->next_out += n; + pStream->avail_out -= n; + pStream->total_out += n; + pState->m_dict_avail -= n; + pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); + + if (status < 0) + return MZ_DATA_ERROR; /* Stream is corrupted (there could be some uncompressed data left in the output dictionary - oh well). */ + else if ((status == TINFL_STATUS_NEEDS_MORE_INPUT) && (!orig_avail_in)) + return MZ_BUF_ERROR; /* Signal caller that we can't make forward progress without supplying more input or by setting flush to MZ_FINISH. */ + else if (flush == MZ_FINISH) + { + /* The output buffer MUST be large to hold the remaining uncompressed data when flush==MZ_FINISH. */ + if (status == TINFL_STATUS_DONE) + return pState->m_dict_avail ? MZ_BUF_ERROR : MZ_STREAM_END; + /* status here must be TINFL_STATUS_HAS_MORE_OUTPUT, which means there's at least 1 more byte on the way. If there's no more room left in the output buffer then something is wrong. */ + else if (!pStream->avail_out) + return MZ_BUF_ERROR; + } + else if ((status == TINFL_STATUS_DONE) || (!pStream->avail_in) || (!pStream->avail_out) || (pState->m_dict_avail)) + break; + } + + return ((status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; +} + +int mz_inflateEnd(mz_streamp pStream) +{ + if (!pStream) + return MZ_STREAM_ERROR; + if (pStream->state) + { + pStream->zfree(pStream->opaque, pStream->state); + pStream->state = NULL; + } + return MZ_OK; +} + +int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len) +{ + mz_stream stream; + int status; + memset(&stream, 0, sizeof(stream)); + + /* In case mz_ulong is 64-bits (argh I hate longs). */ + if ((source_len | *pDest_len) > 0xFFFFFFFFU) + return MZ_PARAM_ERROR; + + stream.next_in = pSource; + stream.avail_in = (mz_uint32)source_len; + stream.next_out = pDest; + stream.avail_out = (mz_uint32)*pDest_len; + + status = mz_inflateInit(&stream); + if (status != MZ_OK) + return status; + + status = mz_inflate(&stream, MZ_FINISH); + if (status != MZ_STREAM_END) + { + mz_inflateEnd(&stream); + return ((status == MZ_BUF_ERROR) && (!stream.avail_in)) ? MZ_DATA_ERROR : status; + } + *pDest_len = stream.total_out; + + return mz_inflateEnd(&stream); +} + +const char *mz_error(int err) +{ + static struct + { + int m_err; + const char *m_pDesc; + } s_error_descs[] = + { + { MZ_OK, "" }, { MZ_STREAM_END, "stream end" }, { MZ_NEED_DICT, "need dictionary" }, { MZ_ERRNO, "file error" }, { MZ_STREAM_ERROR, "stream error" }, { MZ_DATA_ERROR, "data error" }, { MZ_MEM_ERROR, "out of memory" }, { MZ_BUF_ERROR, "buf error" }, { MZ_VERSION_ERROR, "version error" }, { MZ_PARAM_ERROR, "parameter error" } + }; + mz_uint i; + for (i = 0; i < sizeof(s_error_descs) / sizeof(s_error_descs[0]); ++i) + if (s_error_descs[i].m_err == err) + return s_error_descs[i].m_pDesc; + return NULL; +} + +#endif /*MINIZ_NO_ZLIB_APIS */ + +#ifdef __cplusplus +} +#endif + +/* + This is free and unencumbered software released into the public domain. + + Anyone is free to copy, modify, publish, use, compile, sell, or + distribute this software, either in source code form or as a compiled + binary, for any purpose, commercial or non-commercial, and by any + means. + + In jurisdictions that recognize copyright laws, the author or authors + of this software dedicate any and all copyright interest in the + software to the public domain. We make this dedication for the benefit + of the public at large and to the detriment of our heirs and + successors. We intend this dedication to be an overt act of + relinquishment in perpetuity of all present and future rights to this + software under copyright law. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + + For more information, please refer to +*/ +/************************************************************************** + * + * Copyright 2013-2014 RAD Game Tools and Valve Software + * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC + * All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + **************************************************************************/ + + + + +#ifdef __cplusplus +extern "C" { +#endif + +/* ------------------- Low-level Compression (independent from all decompression API's) */ + +/* Purposely making these tables static for faster init and thread safety. */ +static const mz_uint16 s_tdefl_len_sym[256] = + { + 257, 258, 259, 260, 261, 262, 263, 264, 265, 265, 266, 266, 267, 267, 268, 268, 269, 269, 269, 269, 270, 270, 270, 270, 271, 271, 271, 271, 272, 272, 272, 272, + 273, 273, 273, 273, 273, 273, 273, 273, 274, 274, 274, 274, 274, 274, 274, 274, 275, 275, 275, 275, 275, 275, 275, 275, 276, 276, 276, 276, 276, 276, 276, 276, + 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, + 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, + 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, + 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, + 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, + 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 285 + }; + +static const mz_uint8 s_tdefl_len_extra[256] = + { + 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0 + }; + +static const mz_uint8 s_tdefl_small_dist_sym[512] = + { + 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, + 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, + 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, + 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, + 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, + 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, + 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, + 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, + 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17 + }; + +static const mz_uint8 s_tdefl_small_dist_extra[512] = + { + 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7 + }; + +static const mz_uint8 s_tdefl_large_dist_sym[128] = + { + 0, 0, 18, 19, 20, 20, 21, 21, 22, 22, 22, 22, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, + 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, + 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29 + }; + +static const mz_uint8 s_tdefl_large_dist_extra[128] = + { + 0, 0, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, + 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, + 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13 + }; + +/* Radix sorts tdefl_sym_freq[] array by 16-bit key m_key. Returns ptr to sorted values. */ +typedef struct +{ + mz_uint16 m_key, m_sym_index; +} tdefl_sym_freq; +static tdefl_sym_freq *tdefl_radix_sort_syms(mz_uint num_syms, tdefl_sym_freq *pSyms0, tdefl_sym_freq *pSyms1) +{ + mz_uint32 total_passes = 2, pass_shift, pass, i, hist[256 * 2]; + tdefl_sym_freq *pCur_syms = pSyms0, *pNew_syms = pSyms1; + MZ_CLEAR_OBJ(hist); + for (i = 0; i < num_syms; i++) + { + mz_uint freq = pSyms0[i].m_key; + hist[freq & 0xFF]++; + hist[256 + ((freq >> 8) & 0xFF)]++; + } + while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256])) + total_passes--; + for (pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8) + { + const mz_uint32 *pHist = &hist[pass << 8]; + mz_uint offsets[256], cur_ofs = 0; + for (i = 0; i < 256; i++) + { + offsets[i] = cur_ofs; + cur_ofs += pHist[i]; + } + for (i = 0; i < num_syms; i++) + pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] = pCur_syms[i]; + { + tdefl_sym_freq *t = pCur_syms; + pCur_syms = pNew_syms; + pNew_syms = t; + } + } + return pCur_syms; +} + +/* tdefl_calculate_minimum_redundancy() originally written by: Alistair Moffat, alistair@cs.mu.oz.au, Jyrki Katajainen, jyrki@diku.dk, November 1996. */ +static void tdefl_calculate_minimum_redundancy(tdefl_sym_freq *A, int n) +{ + int root, leaf, next, avbl, used, dpth; + if (n == 0) + return; + else if (n == 1) + { + A[0].m_key = 1; + return; + } + A[0].m_key += A[1].m_key; + root = 0; + leaf = 2; + for (next = 1; next < n - 1; next++) + { + if (leaf >= n || A[root].m_key < A[leaf].m_key) + { + A[next].m_key = A[root].m_key; + A[root++].m_key = (mz_uint16)next; + } + else + A[next].m_key = A[leaf++].m_key; + if (leaf >= n || (root < next && A[root].m_key < A[leaf].m_key)) + { + A[next].m_key = (mz_uint16)(A[next].m_key + A[root].m_key); + A[root++].m_key = (mz_uint16)next; + } + else + A[next].m_key = (mz_uint16)(A[next].m_key + A[leaf++].m_key); + } + A[n - 2].m_key = 0; + for (next = n - 3; next >= 0; next--) + A[next].m_key = A[A[next].m_key].m_key + 1; + avbl = 1; + used = dpth = 0; + root = n - 2; + next = n - 1; + while (avbl > 0) + { + while (root >= 0 && (int)A[root].m_key == dpth) + { + used++; + root--; + } + while (avbl > used) + { + A[next--].m_key = (mz_uint16)(dpth); + avbl--; + } + avbl = 2 * used; + dpth++; + used = 0; + } +} + +/* Limits canonical Huffman code table's max code size. */ +enum +{ + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE = 32 +}; +static void tdefl_huffman_enforce_max_code_size(int *pNum_codes, int code_list_len, int max_code_size) +{ + int i; + mz_uint32 total = 0; + if (code_list_len <= 1) + return; + for (i = max_code_size + 1; i <= TDEFL_MAX_SUPPORTED_HUFF_CODESIZE; i++) + pNum_codes[max_code_size] += pNum_codes[i]; + for (i = max_code_size; i > 0; i--) + total += (((mz_uint32)pNum_codes[i]) << (max_code_size - i)); + while (total != (1UL << max_code_size)) + { + pNum_codes[max_code_size]--; + for (i = max_code_size - 1; i > 0; i--) + if (pNum_codes[i]) + { + pNum_codes[i]--; + pNum_codes[i + 1] += 2; + break; + } + total--; + } +} + +static void tdefl_optimize_huffman_table(tdefl_compressor *d, int table_num, int table_len, int code_size_limit, int static_table) +{ + int i, j, l, num_codes[1 + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE]; + mz_uint next_code[TDEFL_MAX_SUPPORTED_HUFF_CODESIZE + 1]; + MZ_CLEAR_OBJ(num_codes); + if (static_table) + { + for (i = 0; i < table_len; i++) + num_codes[d->m_huff_code_sizes[table_num][i]]++; + } + else + { + tdefl_sym_freq syms0[TDEFL_MAX_HUFF_SYMBOLS], syms1[TDEFL_MAX_HUFF_SYMBOLS], *pSyms; + int num_used_syms = 0; + const mz_uint16 *pSym_count = &d->m_huff_count[table_num][0]; + for (i = 0; i < table_len; i++) + if (pSym_count[i]) + { + syms0[num_used_syms].m_key = (mz_uint16)pSym_count[i]; + syms0[num_used_syms++].m_sym_index = (mz_uint16)i; + } + + pSyms = tdefl_radix_sort_syms(num_used_syms, syms0, syms1); + tdefl_calculate_minimum_redundancy(pSyms, num_used_syms); + + for (i = 0; i < num_used_syms; i++) + num_codes[pSyms[i].m_key]++; + + tdefl_huffman_enforce_max_code_size(num_codes, num_used_syms, code_size_limit); + + MZ_CLEAR_OBJ(d->m_huff_code_sizes[table_num]); + MZ_CLEAR_OBJ(d->m_huff_codes[table_num]); + for (i = 1, j = num_used_syms; i <= code_size_limit; i++) + for (l = num_codes[i]; l > 0; l--) + d->m_huff_code_sizes[table_num][pSyms[--j].m_sym_index] = (mz_uint8)(i); + } + + next_code[1] = 0; + for (j = 0, i = 2; i <= code_size_limit; i++) + next_code[i] = j = ((j + num_codes[i - 1]) << 1); + + for (i = 0; i < table_len; i++) + { + mz_uint rev_code = 0, code, code_size; + if ((code_size = d->m_huff_code_sizes[table_num][i]) == 0) + continue; + code = next_code[code_size]++; + for (l = code_size; l > 0; l--, code >>= 1) + rev_code = (rev_code << 1) | (code & 1); + d->m_huff_codes[table_num][i] = (mz_uint16)rev_code; + } +} + +#define TDEFL_PUT_BITS(b, l) \ + do \ + { \ + mz_uint bits = b; \ + mz_uint len = l; \ + MZ_ASSERT(bits <= ((1U << len) - 1U)); \ + d->m_bit_buffer |= (bits << d->m_bits_in); \ + d->m_bits_in += len; \ + while (d->m_bits_in >= 8) \ + { \ + if (d->m_pOutput_buf < d->m_pOutput_buf_end) \ + *d->m_pOutput_buf++ = (mz_uint8)(d->m_bit_buffer); \ + d->m_bit_buffer >>= 8; \ + d->m_bits_in -= 8; \ + } \ + } \ + MZ_MACRO_END + +#define TDEFL_RLE_PREV_CODE_SIZE() \ + { \ + if (rle_repeat_count) \ + { \ + if (rle_repeat_count < 3) \ + { \ + d->m_huff_count[2][prev_code_size] = (mz_uint16)(d->m_huff_count[2][prev_code_size] + rle_repeat_count); \ + while (rle_repeat_count--) \ + packed_code_sizes[num_packed_code_sizes++] = prev_code_size; \ + } \ + else \ + { \ + d->m_huff_count[2][16] = (mz_uint16)(d->m_huff_count[2][16] + 1); \ + packed_code_sizes[num_packed_code_sizes++] = 16; \ + packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_repeat_count - 3); \ + } \ + rle_repeat_count = 0; \ + } \ + } + +#define TDEFL_RLE_ZERO_CODE_SIZE() \ + { \ + if (rle_z_count) \ + { \ + if (rle_z_count < 3) \ + { \ + d->m_huff_count[2][0] = (mz_uint16)(d->m_huff_count[2][0] + rle_z_count); \ + while (rle_z_count--) \ + packed_code_sizes[num_packed_code_sizes++] = 0; \ + } \ + else if (rle_z_count <= 10) \ + { \ + d->m_huff_count[2][17] = (mz_uint16)(d->m_huff_count[2][17] + 1); \ + packed_code_sizes[num_packed_code_sizes++] = 17; \ + packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 3); \ + } \ + else \ + { \ + d->m_huff_count[2][18] = (mz_uint16)(d->m_huff_count[2][18] + 1); \ + packed_code_sizes[num_packed_code_sizes++] = 18; \ + packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 11); \ + } \ + rle_z_count = 0; \ + } \ + } + +static mz_uint8 s_tdefl_packed_code_size_syms_swizzle[] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; + +static void tdefl_start_dynamic_block(tdefl_compressor *d) +{ + int num_lit_codes, num_dist_codes, num_bit_lengths; + mz_uint i, total_code_sizes_to_pack, num_packed_code_sizes, rle_z_count, rle_repeat_count, packed_code_sizes_index; + mz_uint8 code_sizes_to_pack[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], packed_code_sizes[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], prev_code_size = 0xFF; + + d->m_huff_count[0][256] = 1; + + tdefl_optimize_huffman_table(d, 0, TDEFL_MAX_HUFF_SYMBOLS_0, 15, MZ_FALSE); + tdefl_optimize_huffman_table(d, 1, TDEFL_MAX_HUFF_SYMBOLS_1, 15, MZ_FALSE); + + for (num_lit_codes = 286; num_lit_codes > 257; num_lit_codes--) + if (d->m_huff_code_sizes[0][num_lit_codes - 1]) + break; + for (num_dist_codes = 30; num_dist_codes > 1; num_dist_codes--) + if (d->m_huff_code_sizes[1][num_dist_codes - 1]) + break; + + memcpy(code_sizes_to_pack, &d->m_huff_code_sizes[0][0], num_lit_codes); + memcpy(code_sizes_to_pack + num_lit_codes, &d->m_huff_code_sizes[1][0], num_dist_codes); + total_code_sizes_to_pack = num_lit_codes + num_dist_codes; + num_packed_code_sizes = 0; + rle_z_count = 0; + rle_repeat_count = 0; + + memset(&d->m_huff_count[2][0], 0, sizeof(d->m_huff_count[2][0]) * TDEFL_MAX_HUFF_SYMBOLS_2); + for (i = 0; i < total_code_sizes_to_pack; i++) + { + mz_uint8 code_size = code_sizes_to_pack[i]; + if (!code_size) + { + TDEFL_RLE_PREV_CODE_SIZE(); + if (++rle_z_count == 138) + { + TDEFL_RLE_ZERO_CODE_SIZE(); + } + } + else + { + TDEFL_RLE_ZERO_CODE_SIZE(); + if (code_size != prev_code_size) + { + TDEFL_RLE_PREV_CODE_SIZE(); + d->m_huff_count[2][code_size] = (mz_uint16)(d->m_huff_count[2][code_size] + 1); + packed_code_sizes[num_packed_code_sizes++] = code_size; + } + else if (++rle_repeat_count == 6) + { + TDEFL_RLE_PREV_CODE_SIZE(); + } + } + prev_code_size = code_size; + } + if (rle_repeat_count) + { + TDEFL_RLE_PREV_CODE_SIZE(); + } + else + { + TDEFL_RLE_ZERO_CODE_SIZE(); + } + + tdefl_optimize_huffman_table(d, 2, TDEFL_MAX_HUFF_SYMBOLS_2, 7, MZ_FALSE); + + TDEFL_PUT_BITS(2, 2); + + TDEFL_PUT_BITS(num_lit_codes - 257, 5); + TDEFL_PUT_BITS(num_dist_codes - 1, 5); + + for (num_bit_lengths = 18; num_bit_lengths >= 0; num_bit_lengths--) + if (d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[num_bit_lengths]]) + break; + num_bit_lengths = MZ_MAX(4, (num_bit_lengths + 1)); + TDEFL_PUT_BITS(num_bit_lengths - 4, 4); + for (i = 0; (int)i < num_bit_lengths; i++) + TDEFL_PUT_BITS(d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[i]], 3); + + for (packed_code_sizes_index = 0; packed_code_sizes_index < num_packed_code_sizes;) + { + mz_uint code = packed_code_sizes[packed_code_sizes_index++]; + MZ_ASSERT(code < TDEFL_MAX_HUFF_SYMBOLS_2); + TDEFL_PUT_BITS(d->m_huff_codes[2][code], d->m_huff_code_sizes[2][code]); + if (code >= 16) + TDEFL_PUT_BITS(packed_code_sizes[packed_code_sizes_index++], "\02\03\07"[code - 16]); + } +} + +static void tdefl_start_static_block(tdefl_compressor *d) +{ + mz_uint i; + mz_uint8 *p = &d->m_huff_code_sizes[0][0]; + + for (i = 0; i <= 143; ++i) + *p++ = 8; + for (; i <= 255; ++i) + *p++ = 9; + for (; i <= 279; ++i) + *p++ = 7; + for (; i <= 287; ++i) + *p++ = 8; + + memset(d->m_huff_code_sizes[1], 5, 32); + + tdefl_optimize_huffman_table(d, 0, 288, 15, MZ_TRUE); + tdefl_optimize_huffman_table(d, 1, 32, 15, MZ_TRUE); + + TDEFL_PUT_BITS(1, 2); +} + +static const mz_uint mz_bitmasks[17] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF }; + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS +static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) +{ + mz_uint flags; + mz_uint8 *pLZ_codes; + mz_uint8 *pOutput_buf = d->m_pOutput_buf; + mz_uint8 *pLZ_code_buf_end = d->m_pLZ_code_buf; + mz_uint64 bit_buffer = d->m_bit_buffer; + mz_uint bits_in = d->m_bits_in; + +#define TDEFL_PUT_BITS_FAST(b, l) \ + { \ + bit_buffer |= (((mz_uint64)(b)) << bits_in); \ + bits_in += (l); \ + } + + flags = 1; + for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < pLZ_code_buf_end; flags >>= 1) + { + if (flags == 1) + flags = *pLZ_codes++ | 0x100; + + if (flags & 1) + { + mz_uint s0, s1, n0, n1, sym, num_extra_bits; + mz_uint match_len = pLZ_codes[0], match_dist = *(const mz_uint16 *)(pLZ_codes + 1); + pLZ_codes += 3; + + MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); + TDEFL_PUT_BITS_FAST(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]); + + /* This sequence coaxes MSVC into using cmov's vs. jmp's. */ + s0 = s_tdefl_small_dist_sym[match_dist & 511]; + n0 = s_tdefl_small_dist_extra[match_dist & 511]; + s1 = s_tdefl_large_dist_sym[match_dist >> 8]; + n1 = s_tdefl_large_dist_extra[match_dist >> 8]; + sym = (match_dist < 512) ? s0 : s1; + num_extra_bits = (match_dist < 512) ? n0 : n1; + + MZ_ASSERT(d->m_huff_code_sizes[1][sym]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]); + TDEFL_PUT_BITS_FAST(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits); + } + else + { + mz_uint lit = *pLZ_codes++; + MZ_ASSERT(d->m_huff_code_sizes[0][lit]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); + + if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) + { + flags >>= 1; + lit = *pLZ_codes++; + MZ_ASSERT(d->m_huff_code_sizes[0][lit]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); + + if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) + { + flags >>= 1; + lit = *pLZ_codes++; + MZ_ASSERT(d->m_huff_code_sizes[0][lit]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); + } + } + } + + if (pOutput_buf >= d->m_pOutput_buf_end) + return MZ_FALSE; + + *(mz_uint64 *)pOutput_buf = bit_buffer; + pOutput_buf += (bits_in >> 3); + bit_buffer >>= (bits_in & ~7); + bits_in &= 7; + } + +#undef TDEFL_PUT_BITS_FAST + + d->m_pOutput_buf = pOutput_buf; + d->m_bits_in = 0; + d->m_bit_buffer = 0; + + while (bits_in) + { + mz_uint32 n = MZ_MIN(bits_in, 16); + TDEFL_PUT_BITS((mz_uint)bit_buffer & mz_bitmasks[n], n); + bit_buffer >>= n; + bits_in -= n; + } + + TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); + + return (d->m_pOutput_buf < d->m_pOutput_buf_end); +} +#else +static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) +{ + mz_uint flags; + mz_uint8 *pLZ_codes; + + flags = 1; + for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < d->m_pLZ_code_buf; flags >>= 1) + { + if (flags == 1) + flags = *pLZ_codes++ | 0x100; + if (flags & 1) + { + mz_uint sym, num_extra_bits; + mz_uint match_len = pLZ_codes[0], match_dist = (pLZ_codes[1] | (pLZ_codes[2] << 8)); + pLZ_codes += 3; + + MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); + TDEFL_PUT_BITS(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); + TDEFL_PUT_BITS(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]); + + if (match_dist < 512) + { + sym = s_tdefl_small_dist_sym[match_dist]; + num_extra_bits = s_tdefl_small_dist_extra[match_dist]; + } + else + { + sym = s_tdefl_large_dist_sym[match_dist >> 8]; + num_extra_bits = s_tdefl_large_dist_extra[match_dist >> 8]; + } + MZ_ASSERT(d->m_huff_code_sizes[1][sym]); + TDEFL_PUT_BITS(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]); + TDEFL_PUT_BITS(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits); + } + else + { + mz_uint lit = *pLZ_codes++; + MZ_ASSERT(d->m_huff_code_sizes[0][lit]); + TDEFL_PUT_BITS(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); + } + } + + TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); + + return (d->m_pOutput_buf < d->m_pOutput_buf_end); +} +#endif /* MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS */ + +static mz_bool tdefl_compress_block(tdefl_compressor *d, mz_bool static_block) +{ + if (static_block) + tdefl_start_static_block(d); + else + tdefl_start_dynamic_block(d); + return tdefl_compress_lz_codes(d); +} + +static int tdefl_flush_block(tdefl_compressor *d, int flush) +{ + mz_uint saved_bit_buf, saved_bits_in; + mz_uint8 *pSaved_output_buf; + mz_bool comp_block_succeeded = MZ_FALSE; + int n, use_raw_block = ((d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS) != 0) && (d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size; + mz_uint8 *pOutput_buf_start = ((d->m_pPut_buf_func == NULL) && ((*d->m_pOut_buf_size - d->m_out_buf_ofs) >= TDEFL_OUT_BUF_SIZE)) ? ((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs) : d->m_output_buf; + + d->m_pOutput_buf = pOutput_buf_start; + d->m_pOutput_buf_end = d->m_pOutput_buf + TDEFL_OUT_BUF_SIZE - 16; + + MZ_ASSERT(!d->m_output_flush_remaining); + d->m_output_flush_ofs = 0; + d->m_output_flush_remaining = 0; + + *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> d->m_num_flags_left); + d->m_pLZ_code_buf -= (d->m_num_flags_left == 8); + + if ((d->m_flags & TDEFL_WRITE_ZLIB_HEADER) && (!d->m_block_index)) + { + TDEFL_PUT_BITS(0x78, 8); + TDEFL_PUT_BITS(0x01, 8); + } + + TDEFL_PUT_BITS(flush == TDEFL_FINISH, 1); + + pSaved_output_buf = d->m_pOutput_buf; + saved_bit_buf = d->m_bit_buffer; + saved_bits_in = d->m_bits_in; + + if (!use_raw_block) + comp_block_succeeded = tdefl_compress_block(d, (d->m_flags & TDEFL_FORCE_ALL_STATIC_BLOCKS) || (d->m_total_lz_bytes < 48)); + + /* If the block gets expanded, forget the current contents of the output buffer and send a raw block instead. */ + if (((use_raw_block) || ((d->m_total_lz_bytes) && ((d->m_pOutput_buf - pSaved_output_buf + 1U) >= d->m_total_lz_bytes))) && + ((d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size)) + { + mz_uint i; + d->m_pOutput_buf = pSaved_output_buf; + d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; + TDEFL_PUT_BITS(0, 2); + if (d->m_bits_in) + { + TDEFL_PUT_BITS(0, 8 - d->m_bits_in); + } + for (i = 2; i; --i, d->m_total_lz_bytes ^= 0xFFFF) + { + TDEFL_PUT_BITS(d->m_total_lz_bytes & 0xFFFF, 16); + } + for (i = 0; i < d->m_total_lz_bytes; ++i) + { + TDEFL_PUT_BITS(d->m_dict[(d->m_lz_code_buf_dict_pos + i) & TDEFL_LZ_DICT_SIZE_MASK], 8); + } + } + /* Check for the extremely unlikely (if not impossible) case of the compressed block not fitting into the output buffer when using dynamic codes. */ + else if (!comp_block_succeeded) + { + d->m_pOutput_buf = pSaved_output_buf; + d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; + tdefl_compress_block(d, MZ_TRUE); + } + + if (flush) + { + if (flush == TDEFL_FINISH) + { + if (d->m_bits_in) + { + TDEFL_PUT_BITS(0, 8 - d->m_bits_in); + } + if (d->m_flags & TDEFL_WRITE_ZLIB_HEADER) + { + mz_uint i, a = d->m_adler32; + for (i = 0; i < 4; i++) + { + TDEFL_PUT_BITS((a >> 24) & 0xFF, 8); + a <<= 8; + } + } + } + else + { + mz_uint i, z = 0; + TDEFL_PUT_BITS(0, 3); + if (d->m_bits_in) + { + TDEFL_PUT_BITS(0, 8 - d->m_bits_in); + } + for (i = 2; i; --i, z ^= 0xFFFF) + { + TDEFL_PUT_BITS(z & 0xFFFF, 16); + } + } + } + + MZ_ASSERT(d->m_pOutput_buf < d->m_pOutput_buf_end); + + memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); + memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); + + d->m_pLZ_code_buf = d->m_lz_code_buf + 1; + d->m_pLZ_flags = d->m_lz_code_buf; + d->m_num_flags_left = 8; + d->m_lz_code_buf_dict_pos += d->m_total_lz_bytes; + d->m_total_lz_bytes = 0; + d->m_block_index++; + + if ((n = (int)(d->m_pOutput_buf - pOutput_buf_start)) != 0) + { + if (d->m_pPut_buf_func) + { + *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf; + if (!(*d->m_pPut_buf_func)(d->m_output_buf, n, d->m_pPut_buf_user)) + return (d->m_prev_return_status = TDEFL_STATUS_PUT_BUF_FAILED); + } + else if (pOutput_buf_start == d->m_output_buf) + { + int bytes_to_copy = (int)MZ_MIN((size_t)n, (size_t)(*d->m_pOut_buf_size - d->m_out_buf_ofs)); + memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf, bytes_to_copy); + d->m_out_buf_ofs += bytes_to_copy; + if ((n -= bytes_to_copy) != 0) + { + d->m_output_flush_ofs = bytes_to_copy; + d->m_output_flush_remaining = n; + } + } + else + { + d->m_out_buf_ofs += n; + } + } + + return d->m_output_flush_remaining; +} + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES +#ifdef MINIZ_UNALIGNED_USE_MEMCPY +static mz_uint16 TDEFL_READ_UNALIGNED_WORD(const mz_uint8* p) +{ + mz_uint16 ret; + memcpy(&ret, p, sizeof(mz_uint16)); + return ret; +} +static mz_uint16 TDEFL_READ_UNALIGNED_WORD2(const mz_uint16* p) +{ + mz_uint16 ret; + memcpy(&ret, p, sizeof(mz_uint16)); + return ret; +} +#else +#define TDEFL_READ_UNALIGNED_WORD(p) *(const mz_uint16 *)(p) +#define TDEFL_READ_UNALIGNED_WORD2(p) *(const mz_uint16 *)(p) +#endif +static MZ_FORCEINLINE void tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) +{ + mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; + mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; + const mz_uint16 *s = (const mz_uint16 *)(d->m_dict + pos), *p, *q; + mz_uint16 c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]), s01 = TDEFL_READ_UNALIGNED_WORD2(s); + MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); + if (max_match_len <= match_len) + return; + for (;;) + { + for (;;) + { + if (--num_probes_left == 0) + return; +#define TDEFL_PROBE \ + next_probe_pos = d->m_next[probe_pos]; \ + if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \ + return; \ + probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ + if (TDEFL_READ_UNALIGNED_WORD(&d->m_dict[probe_pos + match_len - 1]) == c01) \ + break; + TDEFL_PROBE; + TDEFL_PROBE; + TDEFL_PROBE; + } + if (!dist) + break; + q = (const mz_uint16 *)(d->m_dict + probe_pos); + if (TDEFL_READ_UNALIGNED_WORD2(q) != s01) + continue; + p = s; + probe_len = 32; + do + { + } while ((TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && + (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && (--probe_len > 0)); + if (!probe_len) + { + *pMatch_dist = dist; + *pMatch_len = MZ_MIN(max_match_len, (mz_uint)TDEFL_MAX_MATCH_LEN); + break; + } + else if ((probe_len = ((mz_uint)(p - s) * 2) + (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q)) > match_len) + { + *pMatch_dist = dist; + if ((*pMatch_len = match_len = MZ_MIN(max_match_len, probe_len)) == max_match_len) + break; + c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]); + } + } +} +#else +static MZ_FORCEINLINE void tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) +{ + mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; + mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; + const mz_uint8 *s = d->m_dict + pos, *p, *q; + mz_uint8 c0 = d->m_dict[pos + match_len], c1 = d->m_dict[pos + match_len - 1]; + MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); + if (max_match_len <= match_len) + return; + for (;;) + { + for (;;) + { + if (--num_probes_left == 0) + return; +#define TDEFL_PROBE \ + next_probe_pos = d->m_next[probe_pos]; \ + if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \ + return; \ + probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ + if ((d->m_dict[probe_pos + match_len] == c0) && (d->m_dict[probe_pos + match_len - 1] == c1)) \ + break; + TDEFL_PROBE; + TDEFL_PROBE; + TDEFL_PROBE; + } + if (!dist) + break; + p = s; + q = d->m_dict + probe_pos; + for (probe_len = 0; probe_len < max_match_len; probe_len++) + if (*p++ != *q++) + break; + if (probe_len > match_len) + { + *pMatch_dist = dist; + if ((*pMatch_len = match_len = probe_len) == max_match_len) + return; + c0 = d->m_dict[pos + match_len]; + c1 = d->m_dict[pos + match_len - 1]; + } + } +} +#endif /* #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES */ + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN +#ifdef MINIZ_UNALIGNED_USE_MEMCPY +static mz_uint32 TDEFL_READ_UNALIGNED_WORD32(const mz_uint8* p) +{ + mz_uint32 ret; + memcpy(&ret, p, sizeof(mz_uint32)); + return ret; +} +#else +#define TDEFL_READ_UNALIGNED_WORD32(p) *(const mz_uint32 *)(p) +#endif +static mz_bool tdefl_compress_fast(tdefl_compressor *d) +{ + /* Faster, minimally featured LZRW1-style match+parse loop with better register utilization. Intended for applications where raw throughput is valued more highly than ratio. */ + mz_uint lookahead_pos = d->m_lookahead_pos, lookahead_size = d->m_lookahead_size, dict_size = d->m_dict_size, total_lz_bytes = d->m_total_lz_bytes, num_flags_left = d->m_num_flags_left; + mz_uint8 *pLZ_code_buf = d->m_pLZ_code_buf, *pLZ_flags = d->m_pLZ_flags; + mz_uint cur_pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; + + while ((d->m_src_buf_left) || ((d->m_flush) && (lookahead_size))) + { + const mz_uint TDEFL_COMP_FAST_LOOKAHEAD_SIZE = 4096; + mz_uint dst_pos = (lookahead_pos + lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; + mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(d->m_src_buf_left, TDEFL_COMP_FAST_LOOKAHEAD_SIZE - lookahead_size); + d->m_src_buf_left -= num_bytes_to_process; + lookahead_size += num_bytes_to_process; + + while (num_bytes_to_process) + { + mz_uint32 n = MZ_MIN(TDEFL_LZ_DICT_SIZE - dst_pos, num_bytes_to_process); + memcpy(d->m_dict + dst_pos, d->m_pSrc, n); + if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) + memcpy(d->m_dict + TDEFL_LZ_DICT_SIZE + dst_pos, d->m_pSrc, MZ_MIN(n, (TDEFL_MAX_MATCH_LEN - 1) - dst_pos)); + d->m_pSrc += n; + dst_pos = (dst_pos + n) & TDEFL_LZ_DICT_SIZE_MASK; + num_bytes_to_process -= n; + } + + dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - lookahead_size, dict_size); + if ((!d->m_flush) && (lookahead_size < TDEFL_COMP_FAST_LOOKAHEAD_SIZE)) + break; + + while (lookahead_size >= 4) + { + mz_uint cur_match_dist, cur_match_len = 1; + mz_uint8 *pCur_dict = d->m_dict + cur_pos; + mz_uint first_trigram = TDEFL_READ_UNALIGNED_WORD32(pCur_dict) & 0xFFFFFF; + mz_uint hash = (first_trigram ^ (first_trigram >> (24 - (TDEFL_LZ_HASH_BITS - 8)))) & TDEFL_LEVEL1_HASH_SIZE_MASK; + mz_uint probe_pos = d->m_hash[hash]; + d->m_hash[hash] = (mz_uint16)lookahead_pos; + + if (((cur_match_dist = (mz_uint16)(lookahead_pos - probe_pos)) <= dict_size) && ((TDEFL_READ_UNALIGNED_WORD32(d->m_dict + (probe_pos &= TDEFL_LZ_DICT_SIZE_MASK)) & 0xFFFFFF) == first_trigram)) + { + const mz_uint16 *p = (const mz_uint16 *)pCur_dict; + const mz_uint16 *q = (const mz_uint16 *)(d->m_dict + probe_pos); + mz_uint32 probe_len = 32; + do + { + } while ((TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && + (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && (--probe_len > 0)); + cur_match_len = ((mz_uint)(p - (const mz_uint16 *)pCur_dict) * 2) + (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q); + if (!probe_len) + cur_match_len = cur_match_dist ? TDEFL_MAX_MATCH_LEN : 0; + + if ((cur_match_len < TDEFL_MIN_MATCH_LEN) || ((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U * 1024U))) + { + cur_match_len = 1; + *pLZ_code_buf++ = (mz_uint8)first_trigram; + *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); + d->m_huff_count[0][(mz_uint8)first_trigram]++; + } + else + { + mz_uint32 s0, s1; + cur_match_len = MZ_MIN(cur_match_len, lookahead_size); + + MZ_ASSERT((cur_match_len >= TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 1) && (cur_match_dist <= TDEFL_LZ_DICT_SIZE)); + + cur_match_dist--; + + pLZ_code_buf[0] = (mz_uint8)(cur_match_len - TDEFL_MIN_MATCH_LEN); +#ifdef MINIZ_UNALIGNED_USE_MEMCPY + memcpy(&pLZ_code_buf[1], &cur_match_dist, sizeof(cur_match_dist)); +#else + *(mz_uint16 *)(&pLZ_code_buf[1]) = (mz_uint16)cur_match_dist; +#endif + pLZ_code_buf += 3; + *pLZ_flags = (mz_uint8)((*pLZ_flags >> 1) | 0x80); + + s0 = s_tdefl_small_dist_sym[cur_match_dist & 511]; + s1 = s_tdefl_large_dist_sym[cur_match_dist >> 8]; + d->m_huff_count[1][(cur_match_dist < 512) ? s0 : s1]++; + + d->m_huff_count[0][s_tdefl_len_sym[cur_match_len - TDEFL_MIN_MATCH_LEN]]++; + } + } + else + { + *pLZ_code_buf++ = (mz_uint8)first_trigram; + *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); + d->m_huff_count[0][(mz_uint8)first_trigram]++; + } + + if (--num_flags_left == 0) + { + num_flags_left = 8; + pLZ_flags = pLZ_code_buf++; + } + + total_lz_bytes += cur_match_len; + lookahead_pos += cur_match_len; + dict_size = MZ_MIN(dict_size + cur_match_len, (mz_uint)TDEFL_LZ_DICT_SIZE); + cur_pos = (cur_pos + cur_match_len) & TDEFL_LZ_DICT_SIZE_MASK; + MZ_ASSERT(lookahead_size >= cur_match_len); + lookahead_size -= cur_match_len; + + if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) + { + int n; + d->m_lookahead_pos = lookahead_pos; + d->m_lookahead_size = lookahead_size; + d->m_dict_size = dict_size; + d->m_total_lz_bytes = total_lz_bytes; + d->m_pLZ_code_buf = pLZ_code_buf; + d->m_pLZ_flags = pLZ_flags; + d->m_num_flags_left = num_flags_left; + if ((n = tdefl_flush_block(d, 0)) != 0) + return (n < 0) ? MZ_FALSE : MZ_TRUE; + total_lz_bytes = d->m_total_lz_bytes; + pLZ_code_buf = d->m_pLZ_code_buf; + pLZ_flags = d->m_pLZ_flags; + num_flags_left = d->m_num_flags_left; + } + } + + while (lookahead_size) + { + mz_uint8 lit = d->m_dict[cur_pos]; + + total_lz_bytes++; + *pLZ_code_buf++ = lit; + *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); + if (--num_flags_left == 0) + { + num_flags_left = 8; + pLZ_flags = pLZ_code_buf++; + } + + d->m_huff_count[0][lit]++; + + lookahead_pos++; + dict_size = MZ_MIN(dict_size + 1, (mz_uint)TDEFL_LZ_DICT_SIZE); + cur_pos = (cur_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; + lookahead_size--; + + if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) + { + int n; + d->m_lookahead_pos = lookahead_pos; + d->m_lookahead_size = lookahead_size; + d->m_dict_size = dict_size; + d->m_total_lz_bytes = total_lz_bytes; + d->m_pLZ_code_buf = pLZ_code_buf; + d->m_pLZ_flags = pLZ_flags; + d->m_num_flags_left = num_flags_left; + if ((n = tdefl_flush_block(d, 0)) != 0) + return (n < 0) ? MZ_FALSE : MZ_TRUE; + total_lz_bytes = d->m_total_lz_bytes; + pLZ_code_buf = d->m_pLZ_code_buf; + pLZ_flags = d->m_pLZ_flags; + num_flags_left = d->m_num_flags_left; + } + } + } + + d->m_lookahead_pos = lookahead_pos; + d->m_lookahead_size = lookahead_size; + d->m_dict_size = dict_size; + d->m_total_lz_bytes = total_lz_bytes; + d->m_pLZ_code_buf = pLZ_code_buf; + d->m_pLZ_flags = pLZ_flags; + d->m_num_flags_left = num_flags_left; + return MZ_TRUE; +} +#endif /* MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN */ + +static MZ_FORCEINLINE void tdefl_record_literal(tdefl_compressor *d, mz_uint8 lit) +{ + d->m_total_lz_bytes++; + *d->m_pLZ_code_buf++ = lit; + *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> 1); + if (--d->m_num_flags_left == 0) + { + d->m_num_flags_left = 8; + d->m_pLZ_flags = d->m_pLZ_code_buf++; + } + d->m_huff_count[0][lit]++; +} + +static MZ_FORCEINLINE void tdefl_record_match(tdefl_compressor *d, mz_uint match_len, mz_uint match_dist) +{ + mz_uint32 s0, s1; + + MZ_ASSERT((match_len >= TDEFL_MIN_MATCH_LEN) && (match_dist >= 1) && (match_dist <= TDEFL_LZ_DICT_SIZE)); + + d->m_total_lz_bytes += match_len; + + d->m_pLZ_code_buf[0] = (mz_uint8)(match_len - TDEFL_MIN_MATCH_LEN); + + match_dist -= 1; + d->m_pLZ_code_buf[1] = (mz_uint8)(match_dist & 0xFF); + d->m_pLZ_code_buf[2] = (mz_uint8)(match_dist >> 8); + d->m_pLZ_code_buf += 3; + + *d->m_pLZ_flags = (mz_uint8)((*d->m_pLZ_flags >> 1) | 0x80); + if (--d->m_num_flags_left == 0) + { + d->m_num_flags_left = 8; + d->m_pLZ_flags = d->m_pLZ_code_buf++; + } + + s0 = s_tdefl_small_dist_sym[match_dist & 511]; + s1 = s_tdefl_large_dist_sym[(match_dist >> 8) & 127]; + d->m_huff_count[1][(match_dist < 512) ? s0 : s1]++; + + if (match_len >= TDEFL_MIN_MATCH_LEN) + d->m_huff_count[0][s_tdefl_len_sym[match_len - TDEFL_MIN_MATCH_LEN]]++; +} + +static mz_bool tdefl_compress_normal(tdefl_compressor *d) +{ + const mz_uint8 *pSrc = d->m_pSrc; + size_t src_buf_left = d->m_src_buf_left; + tdefl_flush flush = d->m_flush; + + while ((src_buf_left) || ((flush) && (d->m_lookahead_size))) + { + mz_uint len_to_move, cur_match_dist, cur_match_len, cur_pos; + /* Update dictionary and hash chains. Keeps the lookahead size equal to TDEFL_MAX_MATCH_LEN. */ + if ((d->m_lookahead_size + d->m_dict_size) >= (TDEFL_MIN_MATCH_LEN - 1)) + { + mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK, ins_pos = d->m_lookahead_pos + d->m_lookahead_size - 2; + mz_uint hash = (d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK]; + mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(src_buf_left, TDEFL_MAX_MATCH_LEN - d->m_lookahead_size); + const mz_uint8 *pSrc_end = pSrc + num_bytes_to_process; + src_buf_left -= num_bytes_to_process; + d->m_lookahead_size += num_bytes_to_process; + while (pSrc != pSrc_end) + { + mz_uint8 c = *pSrc++; + d->m_dict[dst_pos] = c; + if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) + d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; + hash = ((hash << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); + d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; + d->m_hash[hash] = (mz_uint16)(ins_pos); + dst_pos = (dst_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; + ins_pos++; + } + } + else + { + while ((src_buf_left) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) + { + mz_uint8 c = *pSrc++; + mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; + src_buf_left--; + d->m_dict[dst_pos] = c; + if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) + d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; + if ((++d->m_lookahead_size + d->m_dict_size) >= TDEFL_MIN_MATCH_LEN) + { + mz_uint ins_pos = d->m_lookahead_pos + (d->m_lookahead_size - 1) - 2; + mz_uint hash = ((d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << (TDEFL_LZ_HASH_SHIFT * 2)) ^ (d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); + d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; + d->m_hash[hash] = (mz_uint16)(ins_pos); + } + } + } + d->m_dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - d->m_lookahead_size, d->m_dict_size); + if ((!flush) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) + break; + + /* Simple lazy/greedy parsing state machine. */ + len_to_move = 1; + cur_match_dist = 0; + cur_match_len = d->m_saved_match_len ? d->m_saved_match_len : (TDEFL_MIN_MATCH_LEN - 1); + cur_pos = d->m_lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; + if (d->m_flags & (TDEFL_RLE_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS)) + { + if ((d->m_dict_size) && (!(d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) + { + mz_uint8 c = d->m_dict[(cur_pos - 1) & TDEFL_LZ_DICT_SIZE_MASK]; + cur_match_len = 0; + while (cur_match_len < d->m_lookahead_size) + { + if (d->m_dict[cur_pos + cur_match_len] != c) + break; + cur_match_len++; + } + if (cur_match_len < TDEFL_MIN_MATCH_LEN) + cur_match_len = 0; + else + cur_match_dist = 1; + } + } + else + { + tdefl_find_match(d, d->m_lookahead_pos, d->m_dict_size, d->m_lookahead_size, &cur_match_dist, &cur_match_len); + } + if (((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U * 1024U)) || (cur_pos == cur_match_dist) || ((d->m_flags & TDEFL_FILTER_MATCHES) && (cur_match_len <= 5))) + { + cur_match_dist = cur_match_len = 0; + } + if (d->m_saved_match_len) + { + if (cur_match_len > d->m_saved_match_len) + { + tdefl_record_literal(d, (mz_uint8)d->m_saved_lit); + if (cur_match_len >= 128) + { + tdefl_record_match(d, cur_match_len, cur_match_dist); + d->m_saved_match_len = 0; + len_to_move = cur_match_len; + } + else + { + d->m_saved_lit = d->m_dict[cur_pos]; + d->m_saved_match_dist = cur_match_dist; + d->m_saved_match_len = cur_match_len; + } + } + else + { + tdefl_record_match(d, d->m_saved_match_len, d->m_saved_match_dist); + len_to_move = d->m_saved_match_len - 1; + d->m_saved_match_len = 0; + } + } + else if (!cur_match_dist) + tdefl_record_literal(d, d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]); + else if ((d->m_greedy_parsing) || (d->m_flags & TDEFL_RLE_MATCHES) || (cur_match_len >= 128)) + { + tdefl_record_match(d, cur_match_len, cur_match_dist); + len_to_move = cur_match_len; + } + else + { + d->m_saved_lit = d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]; + d->m_saved_match_dist = cur_match_dist; + d->m_saved_match_len = cur_match_len; + } + /* Move the lookahead forward by len_to_move bytes. */ + d->m_lookahead_pos += len_to_move; + MZ_ASSERT(d->m_lookahead_size >= len_to_move); + d->m_lookahead_size -= len_to_move; + d->m_dict_size = MZ_MIN(d->m_dict_size + len_to_move, (mz_uint)TDEFL_LZ_DICT_SIZE); + /* Check if it's time to flush the current LZ codes to the internal output buffer. */ + if ((d->m_pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) || + ((d->m_total_lz_bytes > 31 * 1024) && (((((mz_uint)(d->m_pLZ_code_buf - d->m_lz_code_buf) * 115) >> 7) >= d->m_total_lz_bytes) || (d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS)))) + { + int n; + d->m_pSrc = pSrc; + d->m_src_buf_left = src_buf_left; + if ((n = tdefl_flush_block(d, 0)) != 0) + return (n < 0) ? MZ_FALSE : MZ_TRUE; + } + } + + d->m_pSrc = pSrc; + d->m_src_buf_left = src_buf_left; + return MZ_TRUE; +} + +static tdefl_status tdefl_flush_output_buffer(tdefl_compressor *d) +{ + if (d->m_pIn_buf_size) + { + *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf; + } + + if (d->m_pOut_buf_size) + { + size_t n = MZ_MIN(*d->m_pOut_buf_size - d->m_out_buf_ofs, d->m_output_flush_remaining); + memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf + d->m_output_flush_ofs, n); + d->m_output_flush_ofs += (mz_uint)n; + d->m_output_flush_remaining -= (mz_uint)n; + d->m_out_buf_ofs += n; + + *d->m_pOut_buf_size = d->m_out_buf_ofs; + } + + return (d->m_finished && !d->m_output_flush_remaining) ? TDEFL_STATUS_DONE : TDEFL_STATUS_OKAY; +} + +tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush) +{ + if (!d) + { + if (pIn_buf_size) + *pIn_buf_size = 0; + if (pOut_buf_size) + *pOut_buf_size = 0; + return TDEFL_STATUS_BAD_PARAM; + } + + d->m_pIn_buf = pIn_buf; + d->m_pIn_buf_size = pIn_buf_size; + d->m_pOut_buf = pOut_buf; + d->m_pOut_buf_size = pOut_buf_size; + d->m_pSrc = (const mz_uint8 *)(pIn_buf); + d->m_src_buf_left = pIn_buf_size ? *pIn_buf_size : 0; + d->m_out_buf_ofs = 0; + d->m_flush = flush; + + if (((d->m_pPut_buf_func != NULL) == ((pOut_buf != NULL) || (pOut_buf_size != NULL))) || (d->m_prev_return_status != TDEFL_STATUS_OKAY) || + (d->m_wants_to_finish && (flush != TDEFL_FINISH)) || (pIn_buf_size && *pIn_buf_size && !pIn_buf) || (pOut_buf_size && *pOut_buf_size && !pOut_buf)) + { + if (pIn_buf_size) + *pIn_buf_size = 0; + if (pOut_buf_size) + *pOut_buf_size = 0; + return (d->m_prev_return_status = TDEFL_STATUS_BAD_PARAM); + } + d->m_wants_to_finish |= (flush == TDEFL_FINISH); + + if ((d->m_output_flush_remaining) || (d->m_finished)) + return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN + if (((d->m_flags & TDEFL_MAX_PROBES_MASK) == 1) && + ((d->m_flags & TDEFL_GREEDY_PARSING_FLAG) != 0) && + ((d->m_flags & (TDEFL_FILTER_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS | TDEFL_RLE_MATCHES)) == 0)) + { + if (!tdefl_compress_fast(d)) + return d->m_prev_return_status; + } + else +#endif /* #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN */ + { + if (!tdefl_compress_normal(d)) + return d->m_prev_return_status; + } + + if ((d->m_flags & (TDEFL_WRITE_ZLIB_HEADER | TDEFL_COMPUTE_ADLER32)) && (pIn_buf)) + d->m_adler32 = (mz_uint32)mz_adler32(d->m_adler32, (const mz_uint8 *)pIn_buf, d->m_pSrc - (const mz_uint8 *)pIn_buf); + + if ((flush) && (!d->m_lookahead_size) && (!d->m_src_buf_left) && (!d->m_output_flush_remaining)) + { + if (tdefl_flush_block(d, flush) < 0) + return d->m_prev_return_status; + d->m_finished = (flush == TDEFL_FINISH); + if (flush == TDEFL_FULL_FLUSH) + { + MZ_CLEAR_OBJ(d->m_hash); + MZ_CLEAR_OBJ(d->m_next); + d->m_dict_size = 0; + } + } + + return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); +} + +tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush) +{ + MZ_ASSERT(d->m_pPut_buf_func); + return tdefl_compress(d, pIn_buf, &in_buf_size, NULL, NULL, flush); +} + +tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) +{ + d->m_pPut_buf_func = pPut_buf_func; + d->m_pPut_buf_user = pPut_buf_user; + d->m_flags = (mz_uint)(flags); + d->m_max_probes[0] = 1 + ((flags & 0xFFF) + 2) / 3; + d->m_greedy_parsing = (flags & TDEFL_GREEDY_PARSING_FLAG) != 0; + d->m_max_probes[1] = 1 + (((flags & 0xFFF) >> 2) + 2) / 3; + if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG)) + MZ_CLEAR_OBJ(d->m_hash); + d->m_lookahead_pos = d->m_lookahead_size = d->m_dict_size = d->m_total_lz_bytes = d->m_lz_code_buf_dict_pos = d->m_bits_in = 0; + d->m_output_flush_ofs = d->m_output_flush_remaining = d->m_finished = d->m_block_index = d->m_bit_buffer = d->m_wants_to_finish = 0; + d->m_pLZ_code_buf = d->m_lz_code_buf + 1; + d->m_pLZ_flags = d->m_lz_code_buf; + d->m_num_flags_left = 8; + d->m_pOutput_buf = d->m_output_buf; + d->m_pOutput_buf_end = d->m_output_buf; + d->m_prev_return_status = TDEFL_STATUS_OKAY; + d->m_saved_match_dist = d->m_saved_match_len = d->m_saved_lit = 0; + d->m_adler32 = 1; + d->m_pIn_buf = NULL; + d->m_pOut_buf = NULL; + d->m_pIn_buf_size = NULL; + d->m_pOut_buf_size = NULL; + d->m_flush = TDEFL_NO_FLUSH; + d->m_pSrc = NULL; + d->m_src_buf_left = 0; + d->m_out_buf_ofs = 0; + if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG)) + MZ_CLEAR_OBJ(d->m_dict); + memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); + memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); + return TDEFL_STATUS_OKAY; +} + +tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d) +{ + return d->m_prev_return_status; +} + +mz_uint32 tdefl_get_adler32(tdefl_compressor *d) +{ + return d->m_adler32; +} + +mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) +{ + tdefl_compressor *pComp; + mz_bool succeeded; + if (((buf_len) && (!pBuf)) || (!pPut_buf_func)) + return MZ_FALSE; + pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); + if (!pComp) + return MZ_FALSE; + succeeded = (tdefl_init(pComp, pPut_buf_func, pPut_buf_user, flags) == TDEFL_STATUS_OKAY); + succeeded = succeeded && (tdefl_compress_buffer(pComp, pBuf, buf_len, TDEFL_FINISH) == TDEFL_STATUS_DONE); + MZ_FREE(pComp); + return succeeded; +} + +typedef struct +{ + size_t m_size, m_capacity; + mz_uint8 *m_pBuf; + mz_bool m_expandable; +} tdefl_output_buffer; + +static mz_bool tdefl_output_buffer_putter(const void *pBuf, int len, void *pUser) +{ + tdefl_output_buffer *p = (tdefl_output_buffer *)pUser; + size_t new_size = p->m_size + len; + if (new_size > p->m_capacity) + { + size_t new_capacity = p->m_capacity; + mz_uint8 *pNew_buf; + if (!p->m_expandable) + return MZ_FALSE; + do + { + new_capacity = MZ_MAX(128U, new_capacity << 1U); + } while (new_size > new_capacity); + pNew_buf = (mz_uint8 *)MZ_REALLOC(p->m_pBuf, new_capacity); + if (!pNew_buf) + return MZ_FALSE; + p->m_pBuf = pNew_buf; + p->m_capacity = new_capacity; + } + memcpy((mz_uint8 *)p->m_pBuf + p->m_size, pBuf, len); + p->m_size = new_size; + return MZ_TRUE; +} + +void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) +{ + tdefl_output_buffer out_buf; + MZ_CLEAR_OBJ(out_buf); + if (!pOut_len) + return MZ_FALSE; + else + *pOut_len = 0; + out_buf.m_expandable = MZ_TRUE; + if (!tdefl_compress_mem_to_output(pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) + return NULL; + *pOut_len = out_buf.m_size; + return out_buf.m_pBuf; +} + +size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags) +{ + tdefl_output_buffer out_buf; + MZ_CLEAR_OBJ(out_buf); + if (!pOut_buf) + return 0; + out_buf.m_pBuf = (mz_uint8 *)pOut_buf; + out_buf.m_capacity = out_buf_len; + if (!tdefl_compress_mem_to_output(pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) + return 0; + return out_buf.m_size; +} + +static const mz_uint s_tdefl_num_probes[11] = { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500 }; + +/* level may actually range from [0,10] (10 is a "hidden" max level, where we want a bit more compression and it's fine if throughput to fall off a cliff on some files). */ +mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy) +{ + mz_uint comp_flags = s_tdefl_num_probes[(level >= 0) ? MZ_MIN(10, level) : MZ_DEFAULT_LEVEL] | ((level <= 3) ? TDEFL_GREEDY_PARSING_FLAG : 0); + if (window_bits > 0) + comp_flags |= TDEFL_WRITE_ZLIB_HEADER; + + if (!level) + comp_flags |= TDEFL_FORCE_ALL_RAW_BLOCKS; + else if (strategy == MZ_FILTERED) + comp_flags |= TDEFL_FILTER_MATCHES; + else if (strategy == MZ_HUFFMAN_ONLY) + comp_flags &= ~TDEFL_MAX_PROBES_MASK; + else if (strategy == MZ_FIXED) + comp_flags |= TDEFL_FORCE_ALL_STATIC_BLOCKS; + else if (strategy == MZ_RLE) + comp_flags |= TDEFL_RLE_MATCHES; + + return comp_flags; +} + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4204) /* nonstandard extension used : non-constant aggregate initializer (also supported by GNU C and C99, so no big deal) */ +#endif + +/* Simple PNG writer function by Alex Evans, 2011. Released into the public domain: https://gist.github.com/908299, more context at + http://altdevblogaday.org/2011/04/06/a-smaller-jpg-encoder/. + This is actually a modification of Alex's original code so PNG files generated by this function pass pngcheck. */ +void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip) +{ + /* Using a local copy of this array here in case MINIZ_NO_ZLIB_APIS was defined. */ + static const mz_uint s_tdefl_png_num_probes[11] = { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500 }; + tdefl_compressor *pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); + tdefl_output_buffer out_buf; + int i, bpl = w * num_chans, y, z; + mz_uint32 c; + *pLen_out = 0; + if (!pComp) + return NULL; + MZ_CLEAR_OBJ(out_buf); + out_buf.m_expandable = MZ_TRUE; + out_buf.m_capacity = 57 + MZ_MAX(64, (1 + bpl) * h); + if (NULL == (out_buf.m_pBuf = (mz_uint8 *)MZ_MALLOC(out_buf.m_capacity))) + { + MZ_FREE(pComp); + return NULL; + } + /* write dummy header */ + for (z = 41; z; --z) + tdefl_output_buffer_putter(&z, 1, &out_buf); + /* compress image data */ + tdefl_init(pComp, tdefl_output_buffer_putter, &out_buf, s_tdefl_png_num_probes[MZ_MIN(10, level)] | TDEFL_WRITE_ZLIB_HEADER); + for (y = 0; y < h; ++y) + { + tdefl_compress_buffer(pComp, &z, 1, TDEFL_NO_FLUSH); + tdefl_compress_buffer(pComp, (mz_uint8 *)pImage + (flip ? (h - 1 - y) : y) * bpl, bpl, TDEFL_NO_FLUSH); + } + if (tdefl_compress_buffer(pComp, NULL, 0, TDEFL_FINISH) != TDEFL_STATUS_DONE) + { + MZ_FREE(pComp); + MZ_FREE(out_buf.m_pBuf); + return NULL; + } + /* write real header */ + *pLen_out = out_buf.m_size - 41; + { + static const mz_uint8 chans[] = { 0x00, 0x00, 0x04, 0x02, 0x06 }; + mz_uint8 pnghdr[41] = { 0x89, 0x50, 0x4e, 0x47, 0x0d, + 0x0a, 0x1a, 0x0a, 0x00, 0x00, + 0x00, 0x0d, 0x49, 0x48, 0x44, + 0x52, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x08, + 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x49, 0x44, 0x41, + 0x54 }; + pnghdr[18] = (mz_uint8)(w >> 8); + pnghdr[19] = (mz_uint8)w; + pnghdr[22] = (mz_uint8)(h >> 8); + pnghdr[23] = (mz_uint8)h; + pnghdr[25] = chans[num_chans]; + pnghdr[33] = (mz_uint8)(*pLen_out >> 24); + pnghdr[34] = (mz_uint8)(*pLen_out >> 16); + pnghdr[35] = (mz_uint8)(*pLen_out >> 8); + pnghdr[36] = (mz_uint8)*pLen_out; + c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, pnghdr + 12, 17); + for (i = 0; i < 4; ++i, c <<= 8) + ((mz_uint8 *)(pnghdr + 29))[i] = (mz_uint8)(c >> 24); + memcpy(out_buf.m_pBuf, pnghdr, 41); + } + /* write footer (IDAT CRC-32, followed by IEND chunk) */ + if (!tdefl_output_buffer_putter("\0\0\0\0\0\0\0\0\x49\x45\x4e\x44\xae\x42\x60\x82", 16, &out_buf)) + { + *pLen_out = 0; + MZ_FREE(pComp); + MZ_FREE(out_buf.m_pBuf); + return NULL; + } + c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, out_buf.m_pBuf + 41 - 4, *pLen_out + 4); + for (i = 0; i < 4; ++i, c <<= 8) + (out_buf.m_pBuf + out_buf.m_size - 16)[i] = (mz_uint8)(c >> 24); + /* compute final size of file, grab compressed data buffer and return */ + *pLen_out += 57; + MZ_FREE(pComp); + return out_buf.m_pBuf; +} +void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out) +{ + /* Level 6 corresponds to TDEFL_DEFAULT_MAX_PROBES or MZ_DEFAULT_LEVEL (but we can't depend on MZ_DEFAULT_LEVEL being available in case the zlib API's where #defined out) */ + return tdefl_write_image_to_png_file_in_memory_ex(pImage, w, h, num_chans, pLen_out, 6, MZ_FALSE); +} + +#ifndef MINIZ_NO_MALLOC +/* Allocate the tdefl_compressor and tinfl_decompressor structures in C so that */ +/* non-C language bindings to tdefL_ and tinfl_ API don't need to worry about */ +/* structure size and allocation mechanism. */ +tdefl_compressor *tdefl_compressor_alloc() +{ + return (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); +} + +void tdefl_compressor_free(tdefl_compressor *pComp) +{ + MZ_FREE(pComp); +} +#endif + +#ifdef _MSC_VER +#pragma warning(pop) +#endif + +#ifdef __cplusplus +} +#endif +/************************************************************************** + * + * Copyright 2013-2014 RAD Game Tools and Valve Software + * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC + * All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + **************************************************************************/ + + + +#ifdef __cplusplus +extern "C" { +#endif + +/* ------------------- Low-level Decompression (completely independent from all compression API's) */ + +#define TINFL_MEMCPY(d, s, l) memcpy(d, s, l) +#define TINFL_MEMSET(p, c, l) memset(p, c, l) + +#define TINFL_CR_BEGIN \ + switch (r->m_state) \ + { \ + case 0: +#define TINFL_CR_RETURN(state_index, result) \ + do \ + { \ + status = result; \ + r->m_state = state_index; \ + goto common_exit; \ + case state_index:; \ + } \ + MZ_MACRO_END +#define TINFL_CR_RETURN_FOREVER(state_index, result) \ + do \ + { \ + for (;;) \ + { \ + TINFL_CR_RETURN(state_index, result); \ + } \ + } \ + MZ_MACRO_END +#define TINFL_CR_FINISH } + +#define TINFL_GET_BYTE(state_index, c) \ + do \ + { \ + while (pIn_buf_cur >= pIn_buf_end) \ + { \ + TINFL_CR_RETURN(state_index, (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) ? TINFL_STATUS_NEEDS_MORE_INPUT : TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS); \ + } \ + c = *pIn_buf_cur++; \ + } \ + MZ_MACRO_END + +#define TINFL_NEED_BITS(state_index, n) \ + do \ + { \ + mz_uint c; \ + TINFL_GET_BYTE(state_index, c); \ + bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \ + num_bits += 8; \ + } while (num_bits < (mz_uint)(n)) +#define TINFL_SKIP_BITS(state_index, n) \ + do \ + { \ + if (num_bits < (mz_uint)(n)) \ + { \ + TINFL_NEED_BITS(state_index, n); \ + } \ + bit_buf >>= (n); \ + num_bits -= (n); \ + } \ + MZ_MACRO_END +#define TINFL_GET_BITS(state_index, b, n) \ + do \ + { \ + if (num_bits < (mz_uint)(n)) \ + { \ + TINFL_NEED_BITS(state_index, n); \ + } \ + b = bit_buf & ((1 << (n)) - 1); \ + bit_buf >>= (n); \ + num_bits -= (n); \ + } \ + MZ_MACRO_END + +/* TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes remaining in the input buffer falls below 2. */ +/* It reads just enough bytes from the input stream that are needed to decode the next Huffman code (and absolutely no more). It works by trying to fully decode a */ +/* Huffman code by using whatever bits are currently present in the bit buffer. If this fails, it reads another byte, and tries again until it succeeds or until the */ +/* bit buffer contains >=15 bits (deflate's max. Huffman code size). */ +#define TINFL_HUFF_BITBUF_FILL(state_index, pHuff) \ + do \ + { \ + temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \ + if (temp >= 0) \ + { \ + code_len = temp >> 9; \ + if ((code_len) && (num_bits >= code_len)) \ + break; \ + } \ + else if (num_bits > TINFL_FAST_LOOKUP_BITS) \ + { \ + code_len = TINFL_FAST_LOOKUP_BITS; \ + do \ + { \ + temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \ + } while ((temp < 0) && (num_bits >= (code_len + 1))); \ + if (temp >= 0) \ + break; \ + } \ + TINFL_GET_BYTE(state_index, c); \ + bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \ + num_bits += 8; \ + } while (num_bits < 15); + +/* TINFL_HUFF_DECODE() decodes the next Huffman coded symbol. It's more complex than you would initially expect because the zlib API expects the decompressor to never read */ +/* beyond the final byte of the deflate stream. (In other words, when this macro wants to read another byte from the input, it REALLY needs another byte in order to fully */ +/* decode the next Huffman code.) Handling this properly is particularly important on raw deflate (non-zlib) streams, which aren't followed by a byte aligned adler-32. */ +/* The slow path is only executed at the very end of the input buffer. */ +/* v1.16: The original macro handled the case at the very end of the passed-in input buffer, but we also need to handle the case where the user passes in 1+zillion bytes */ +/* following the deflate data and our non-conservative read-ahead path won't kick in here on this code. This is much trickier. */ +#define TINFL_HUFF_DECODE(state_index, sym, pHuff) \ + do \ + { \ + int temp; \ + mz_uint code_len, c; \ + if (num_bits < 15) \ + { \ + if ((pIn_buf_end - pIn_buf_cur) < 2) \ + { \ + TINFL_HUFF_BITBUF_FILL(state_index, pHuff); \ + } \ + else \ + { \ + bit_buf |= (((tinfl_bit_buf_t)pIn_buf_cur[0]) << num_bits) | (((tinfl_bit_buf_t)pIn_buf_cur[1]) << (num_bits + 8)); \ + pIn_buf_cur += 2; \ + num_bits += 16; \ + } \ + } \ + if ((temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) \ + code_len = temp >> 9, temp &= 511; \ + else \ + { \ + code_len = TINFL_FAST_LOOKUP_BITS; \ + do \ + { \ + temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \ + } while (temp < 0); \ + } \ + sym = temp; \ + bit_buf >>= code_len; \ + num_bits -= code_len; \ + } \ + MZ_MACRO_END + +tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags) +{ + static const int s_length_base[31] = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 }; + static const int s_length_extra[31] = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 0, 0 }; + static const int s_dist_base[32] = { 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0 }; + static const int s_dist_extra[32] = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 }; + static const mz_uint8 s_length_dezigzag[19] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; + static const int s_min_table_sizes[3] = { 257, 1, 4 }; + + tinfl_status status = TINFL_STATUS_FAILED; + mz_uint32 num_bits, dist, counter, num_extra; + tinfl_bit_buf_t bit_buf; + const mz_uint8 *pIn_buf_cur = pIn_buf_next, *const pIn_buf_end = pIn_buf_next + *pIn_buf_size; + mz_uint8 *pOut_buf_cur = pOut_buf_next, *const pOut_buf_end = pOut_buf_next + *pOut_buf_size; + size_t out_buf_size_mask = (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF) ? (size_t)-1 : ((pOut_buf_next - pOut_buf_start) + *pOut_buf_size) - 1, dist_from_out_buf_start; + + /* Ensure the output buffer's size is a power of 2, unless the output buffer is large enough to hold the entire output file (in which case it doesn't matter). */ + if (((out_buf_size_mask + 1) & out_buf_size_mask) || (pOut_buf_next < pOut_buf_start)) + { + *pIn_buf_size = *pOut_buf_size = 0; + return TINFL_STATUS_BAD_PARAM; + } + + num_bits = r->m_num_bits; + bit_buf = r->m_bit_buf; + dist = r->m_dist; + counter = r->m_counter; + num_extra = r->m_num_extra; + dist_from_out_buf_start = r->m_dist_from_out_buf_start; + TINFL_CR_BEGIN + + bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0; + r->m_z_adler32 = r->m_check_adler32 = 1; + if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) + { + TINFL_GET_BYTE(1, r->m_zhdr0); + TINFL_GET_BYTE(2, r->m_zhdr1); + counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) || (r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8)); + if (!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) + counter |= (((1U << (8U + (r->m_zhdr0 >> 4))) > 32768U) || ((out_buf_size_mask + 1) < (size_t)(1U << (8U + (r->m_zhdr0 >> 4))))); + if (counter) + { + TINFL_CR_RETURN_FOREVER(36, TINFL_STATUS_FAILED); + } + } + + do + { + TINFL_GET_BITS(3, r->m_final, 3); + r->m_type = r->m_final >> 1; + if (r->m_type == 0) + { + TINFL_SKIP_BITS(5, num_bits & 7); + for (counter = 0; counter < 4; ++counter) + { + if (num_bits) + TINFL_GET_BITS(6, r->m_raw_header[counter], 8); + else + TINFL_GET_BYTE(7, r->m_raw_header[counter]); + } + if ((counter = (r->m_raw_header[0] | (r->m_raw_header[1] << 8))) != (mz_uint)(0xFFFF ^ (r->m_raw_header[2] | (r->m_raw_header[3] << 8)))) + { + TINFL_CR_RETURN_FOREVER(39, TINFL_STATUS_FAILED); + } + while ((counter) && (num_bits)) + { + TINFL_GET_BITS(51, dist, 8); + while (pOut_buf_cur >= pOut_buf_end) + { + TINFL_CR_RETURN(52, TINFL_STATUS_HAS_MORE_OUTPUT); + } + *pOut_buf_cur++ = (mz_uint8)dist; + counter--; + } + while (counter) + { + size_t n; + while (pOut_buf_cur >= pOut_buf_end) + { + TINFL_CR_RETURN(9, TINFL_STATUS_HAS_MORE_OUTPUT); + } + while (pIn_buf_cur >= pIn_buf_end) + { + TINFL_CR_RETURN(38, (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) ? TINFL_STATUS_NEEDS_MORE_INPUT : TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS); + } + n = MZ_MIN(MZ_MIN((size_t)(pOut_buf_end - pOut_buf_cur), (size_t)(pIn_buf_end - pIn_buf_cur)), counter); + TINFL_MEMCPY(pOut_buf_cur, pIn_buf_cur, n); + pIn_buf_cur += n; + pOut_buf_cur += n; + counter -= (mz_uint)n; + } + } + else if (r->m_type == 3) + { + TINFL_CR_RETURN_FOREVER(10, TINFL_STATUS_FAILED); + } + else + { + if (r->m_type == 1) + { + mz_uint8 *p = r->m_tables[0].m_code_size; + mz_uint i; + r->m_table_sizes[0] = 288; + r->m_table_sizes[1] = 32; + TINFL_MEMSET(r->m_tables[1].m_code_size, 5, 32); + for (i = 0; i <= 143; ++i) + *p++ = 8; + for (; i <= 255; ++i) + *p++ = 9; + for (; i <= 279; ++i) + *p++ = 7; + for (; i <= 287; ++i) + *p++ = 8; + } + else + { + for (counter = 0; counter < 3; counter++) + { + TINFL_GET_BITS(11, r->m_table_sizes[counter], "\05\05\04"[counter]); + r->m_table_sizes[counter] += s_min_table_sizes[counter]; + } + MZ_CLEAR_OBJ(r->m_tables[2].m_code_size); + for (counter = 0; counter < r->m_table_sizes[2]; counter++) + { + mz_uint s; + TINFL_GET_BITS(14, s, 3); + r->m_tables[2].m_code_size[s_length_dezigzag[counter]] = (mz_uint8)s; + } + r->m_table_sizes[2] = 19; + } + for (; (int)r->m_type >= 0; r->m_type--) + { + int tree_next, tree_cur; + tinfl_huff_table *pTable; + mz_uint i, j, used_syms, total, sym_index, next_code[17], total_syms[16]; + pTable = &r->m_tables[r->m_type]; + MZ_CLEAR_OBJ(total_syms); + MZ_CLEAR_OBJ(pTable->m_look_up); + MZ_CLEAR_OBJ(pTable->m_tree); + for (i = 0; i < r->m_table_sizes[r->m_type]; ++i) + total_syms[pTable->m_code_size[i]]++; + used_syms = 0, total = 0; + next_code[0] = next_code[1] = 0; + for (i = 1; i <= 15; ++i) + { + used_syms += total_syms[i]; + next_code[i + 1] = (total = ((total + total_syms[i]) << 1)); + } + if ((65536 != total) && (used_syms > 1)) + { + TINFL_CR_RETURN_FOREVER(35, TINFL_STATUS_FAILED); + } + for (tree_next = -1, sym_index = 0; sym_index < r->m_table_sizes[r->m_type]; ++sym_index) + { + mz_uint rev_code = 0, l, cur_code, code_size = pTable->m_code_size[sym_index]; + if (!code_size) + continue; + cur_code = next_code[code_size]++; + for (l = code_size; l > 0; l--, cur_code >>= 1) + rev_code = (rev_code << 1) | (cur_code & 1); + if (code_size <= TINFL_FAST_LOOKUP_BITS) + { + mz_int16 k = (mz_int16)((code_size << 9) | sym_index); + while (rev_code < TINFL_FAST_LOOKUP_SIZE) + { + pTable->m_look_up[rev_code] = k; + rev_code += (1 << code_size); + } + continue; + } + if (0 == (tree_cur = pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)])) + { + pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)] = (mz_int16)tree_next; + tree_cur = tree_next; + tree_next -= 2; + } + rev_code >>= (TINFL_FAST_LOOKUP_BITS - 1); + for (j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--) + { + tree_cur -= ((rev_code >>= 1) & 1); + if (!pTable->m_tree[-tree_cur - 1]) + { + pTable->m_tree[-tree_cur - 1] = (mz_int16)tree_next; + tree_cur = tree_next; + tree_next -= 2; + } + else + tree_cur = pTable->m_tree[-tree_cur - 1]; + } + tree_cur -= ((rev_code >>= 1) & 1); + pTable->m_tree[-tree_cur - 1] = (mz_int16)sym_index; + } + if (r->m_type == 2) + { + for (counter = 0; counter < (r->m_table_sizes[0] + r->m_table_sizes[1]);) + { + mz_uint s; + TINFL_HUFF_DECODE(16, dist, &r->m_tables[2]); + if (dist < 16) + { + r->m_len_codes[counter++] = (mz_uint8)dist; + continue; + } + if ((dist == 16) && (!counter)) + { + TINFL_CR_RETURN_FOREVER(17, TINFL_STATUS_FAILED); + } + num_extra = "\02\03\07"[dist - 16]; + TINFL_GET_BITS(18, s, num_extra); + s += "\03\03\013"[dist - 16]; + TINFL_MEMSET(r->m_len_codes + counter, (dist == 16) ? r->m_len_codes[counter - 1] : 0, s); + counter += s; + } + if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != counter) + { + TINFL_CR_RETURN_FOREVER(21, TINFL_STATUS_FAILED); + } + TINFL_MEMCPY(r->m_tables[0].m_code_size, r->m_len_codes, r->m_table_sizes[0]); + TINFL_MEMCPY(r->m_tables[1].m_code_size, r->m_len_codes + r->m_table_sizes[0], r->m_table_sizes[1]); + } + } + for (;;) + { + mz_uint8 *pSrc; + for (;;) + { + if (((pIn_buf_end - pIn_buf_cur) < 4) || ((pOut_buf_end - pOut_buf_cur) < 2)) + { + TINFL_HUFF_DECODE(23, counter, &r->m_tables[0]); + if (counter >= 256) + break; + while (pOut_buf_cur >= pOut_buf_end) + { + TINFL_CR_RETURN(24, TINFL_STATUS_HAS_MORE_OUTPUT); + } + *pOut_buf_cur++ = (mz_uint8)counter; + } + else + { + int sym2; + mz_uint code_len; +#if TINFL_USE_64BIT_BITBUF + if (num_bits < 30) + { + bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE32(pIn_buf_cur)) << num_bits); + pIn_buf_cur += 4; + num_bits += 32; + } +#else + if (num_bits < 15) + { + bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); + pIn_buf_cur += 2; + num_bits += 16; + } +#endif + if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) + code_len = sym2 >> 9; + else + { + code_len = TINFL_FAST_LOOKUP_BITS; + do + { + sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; + } while (sym2 < 0); + } + counter = sym2; + bit_buf >>= code_len; + num_bits -= code_len; + if (counter & 256) + break; + +#if !TINFL_USE_64BIT_BITBUF + if (num_bits < 15) + { + bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); + pIn_buf_cur += 2; + num_bits += 16; + } +#endif + if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) + code_len = sym2 >> 9; + else + { + code_len = TINFL_FAST_LOOKUP_BITS; + do + { + sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; + } while (sym2 < 0); + } + bit_buf >>= code_len; + num_bits -= code_len; + + pOut_buf_cur[0] = (mz_uint8)counter; + if (sym2 & 256) + { + pOut_buf_cur++; + counter = sym2; + break; + } + pOut_buf_cur[1] = (mz_uint8)sym2; + pOut_buf_cur += 2; + } + } + if ((counter &= 511) == 256) + break; + + num_extra = s_length_extra[counter - 257]; + counter = s_length_base[counter - 257]; + if (num_extra) + { + mz_uint extra_bits; + TINFL_GET_BITS(25, extra_bits, num_extra); + counter += extra_bits; + } + + TINFL_HUFF_DECODE(26, dist, &r->m_tables[1]); + num_extra = s_dist_extra[dist]; + dist = s_dist_base[dist]; + if (num_extra) + { + mz_uint extra_bits; + TINFL_GET_BITS(27, extra_bits, num_extra); + dist += extra_bits; + } + + dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start; + if ((dist > dist_from_out_buf_start) && (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) + { + TINFL_CR_RETURN_FOREVER(37, TINFL_STATUS_FAILED); + } + + pSrc = pOut_buf_start + ((dist_from_out_buf_start - dist) & out_buf_size_mask); + + if ((MZ_MAX(pOut_buf_cur, pSrc) + counter) > pOut_buf_end) + { + while (counter--) + { + while (pOut_buf_cur >= pOut_buf_end) + { + TINFL_CR_RETURN(53, TINFL_STATUS_HAS_MORE_OUTPUT); + } + *pOut_buf_cur++ = pOut_buf_start[(dist_from_out_buf_start++ - dist) & out_buf_size_mask]; + } + continue; + } +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES + else if ((counter >= 9) && (counter <= dist)) + { + const mz_uint8 *pSrc_end = pSrc + (counter & ~7); + do + { +#ifdef MINIZ_UNALIGNED_USE_MEMCPY + memcpy(pOut_buf_cur, pSrc, sizeof(mz_uint32)*2); +#else + ((mz_uint32 *)pOut_buf_cur)[0] = ((const mz_uint32 *)pSrc)[0]; + ((mz_uint32 *)pOut_buf_cur)[1] = ((const mz_uint32 *)pSrc)[1]; +#endif + pOut_buf_cur += 8; + } while ((pSrc += 8) < pSrc_end); + if ((counter &= 7) < 3) + { + if (counter) + { + pOut_buf_cur[0] = pSrc[0]; + if (counter > 1) + pOut_buf_cur[1] = pSrc[1]; + pOut_buf_cur += counter; + } + continue; + } + } +#endif + while(counter>2) + { + pOut_buf_cur[0] = pSrc[0]; + pOut_buf_cur[1] = pSrc[1]; + pOut_buf_cur[2] = pSrc[2]; + pOut_buf_cur += 3; + pSrc += 3; + counter -= 3; + } + if (counter > 0) + { + pOut_buf_cur[0] = pSrc[0]; + if (counter > 1) + pOut_buf_cur[1] = pSrc[1]; + pOut_buf_cur += counter; + } + } + } + } while (!(r->m_final & 1)); + + /* Ensure byte alignment and put back any bytes from the bitbuf if we've looked ahead too far on gzip, or other Deflate streams followed by arbitrary data. */ + /* I'm being super conservative here. A number of simplifications can be made to the byte alignment part, and the Adler32 check shouldn't ever need to worry about reading from the bitbuf now. */ + TINFL_SKIP_BITS(32, num_bits & 7); + while ((pIn_buf_cur > pIn_buf_next) && (num_bits >= 8)) + { + --pIn_buf_cur; + num_bits -= 8; + } + bit_buf &= (tinfl_bit_buf_t)((((mz_uint64)1) << num_bits) - (mz_uint64)1); + MZ_ASSERT(!num_bits); /* if this assert fires then we've read beyond the end of non-deflate/zlib streams with following data (such as gzip streams). */ + + if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) + { + for (counter = 0; counter < 4; ++counter) + { + mz_uint s; + if (num_bits) + TINFL_GET_BITS(41, s, 8); + else + TINFL_GET_BYTE(42, s); + r->m_z_adler32 = (r->m_z_adler32 << 8) | s; + } + } + TINFL_CR_RETURN_FOREVER(34, TINFL_STATUS_DONE); + + TINFL_CR_FINISH + +common_exit: + /* As long as we aren't telling the caller that we NEED more input to make forward progress: */ + /* Put back any bytes from the bitbuf in case we've looked ahead too far on gzip, or other Deflate streams followed by arbitrary data. */ + /* We need to be very careful here to NOT push back any bytes we definitely know we need to make forward progress, though, or we'll lock the caller up into an inf loop. */ + if ((status != TINFL_STATUS_NEEDS_MORE_INPUT) && (status != TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS)) + { + while ((pIn_buf_cur > pIn_buf_next) && (num_bits >= 8)) + { + --pIn_buf_cur; + num_bits -= 8; + } + } + r->m_num_bits = num_bits; + r->m_bit_buf = bit_buf & (tinfl_bit_buf_t)((((mz_uint64)1) << num_bits) - (mz_uint64)1); + r->m_dist = dist; + r->m_counter = counter; + r->m_num_extra = num_extra; + r->m_dist_from_out_buf_start = dist_from_out_buf_start; + *pIn_buf_size = pIn_buf_cur - pIn_buf_next; + *pOut_buf_size = pOut_buf_cur - pOut_buf_next; + if ((decomp_flags & (TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) && (status >= 0)) + { + const mz_uint8 *ptr = pOut_buf_next; + size_t buf_len = *pOut_buf_size; + mz_uint32 i, s1 = r->m_check_adler32 & 0xffff, s2 = r->m_check_adler32 >> 16; + size_t block_len = buf_len % 5552; + while (buf_len) + { + for (i = 0; i + 7 < block_len; i += 8, ptr += 8) + { + s1 += ptr[0], s2 += s1; + s1 += ptr[1], s2 += s1; + s1 += ptr[2], s2 += s1; + s1 += ptr[3], s2 += s1; + s1 += ptr[4], s2 += s1; + s1 += ptr[5], s2 += s1; + s1 += ptr[6], s2 += s1; + s1 += ptr[7], s2 += s1; + } + for (; i < block_len; ++i) + s1 += *ptr++, s2 += s1; + s1 %= 65521U, s2 %= 65521U; + buf_len -= block_len; + block_len = 5552; + } + r->m_check_adler32 = (s2 << 16) + s1; + if ((status == TINFL_STATUS_DONE) && (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) && (r->m_check_adler32 != r->m_z_adler32)) + status = TINFL_STATUS_ADLER32_MISMATCH; + } + return status; +} + +/* Higher level helper functions. */ +void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) +{ + tinfl_decompressor decomp; + void *pBuf = NULL, *pNew_buf; + size_t src_buf_ofs = 0, out_buf_capacity = 0; + *pOut_len = 0; + tinfl_init(&decomp); + for (;;) + { + size_t src_buf_size = src_buf_len - src_buf_ofs, dst_buf_size = out_buf_capacity - *pOut_len, new_out_buf_capacity; + tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8 *)pSrc_buf + src_buf_ofs, &src_buf_size, (mz_uint8 *)pBuf, pBuf ? (mz_uint8 *)pBuf + *pOut_len : NULL, &dst_buf_size, + (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); + if ((status < 0) || (status == TINFL_STATUS_NEEDS_MORE_INPUT)) + { + MZ_FREE(pBuf); + *pOut_len = 0; + return NULL; + } + src_buf_ofs += src_buf_size; + *pOut_len += dst_buf_size; + if (status == TINFL_STATUS_DONE) + break; + new_out_buf_capacity = out_buf_capacity * 2; + if (new_out_buf_capacity < 128) + new_out_buf_capacity = 128; + pNew_buf = MZ_REALLOC(pBuf, new_out_buf_capacity); + if (!pNew_buf) + { + MZ_FREE(pBuf); + *pOut_len = 0; + return NULL; + } + pBuf = pNew_buf; + out_buf_capacity = new_out_buf_capacity; + } + return pBuf; +} + +size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags) +{ + tinfl_decompressor decomp; + tinfl_status status; + tinfl_init(&decomp); + status = tinfl_decompress(&decomp, (const mz_uint8 *)pSrc_buf, &src_buf_len, (mz_uint8 *)pOut_buf, (mz_uint8 *)pOut_buf, &out_buf_len, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); + return (status != TINFL_STATUS_DONE) ? TINFL_DECOMPRESS_MEM_TO_MEM_FAILED : out_buf_len; +} + +int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) +{ + int result = 0; + tinfl_decompressor decomp; + mz_uint8 *pDict = (mz_uint8 *)MZ_MALLOC(TINFL_LZ_DICT_SIZE); + size_t in_buf_ofs = 0, dict_ofs = 0; + if (!pDict) + return TINFL_STATUS_FAILED; + tinfl_init(&decomp); + for (;;) + { + size_t in_buf_size = *pIn_buf_size - in_buf_ofs, dst_buf_size = TINFL_LZ_DICT_SIZE - dict_ofs; + tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8 *)pIn_buf + in_buf_ofs, &in_buf_size, pDict, pDict + dict_ofs, &dst_buf_size, + (flags & ~(TINFL_FLAG_HAS_MORE_INPUT | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))); + in_buf_ofs += in_buf_size; + if ((dst_buf_size) && (!(*pPut_buf_func)(pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user))) + break; + if (status != TINFL_STATUS_HAS_MORE_OUTPUT) + { + result = (status == TINFL_STATUS_DONE); + break; + } + dict_ofs = (dict_ofs + dst_buf_size) & (TINFL_LZ_DICT_SIZE - 1); + } + MZ_FREE(pDict); + *pIn_buf_size = in_buf_ofs; + return result; +} + +#ifndef MINIZ_NO_MALLOC +tinfl_decompressor *tinfl_decompressor_alloc() +{ + tinfl_decompressor *pDecomp = (tinfl_decompressor *)MZ_MALLOC(sizeof(tinfl_decompressor)); + if (pDecomp) + tinfl_init(pDecomp); + return pDecomp; +} + +void tinfl_decompressor_free(tinfl_decompressor *pDecomp) +{ + MZ_FREE(pDecomp); +} +#endif + +#ifdef __cplusplus +} +#endif +/************************************************************************** + * + * Copyright 2013-2014 RAD Game Tools and Valve Software + * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC + * Copyright 2016 Martin Raiber + * All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + **************************************************************************/ + + +#ifndef MINIZ_NO_ARCHIVE_APIS + +#ifdef __cplusplus +extern "C" { +#endif + +/* ------------------- .ZIP archive reading */ + +#ifdef MINIZ_NO_STDIO +#define MZ_FILE void * +#else +#include + +#if defined(_MSC_VER) || defined(__MINGW64__) +static FILE *mz_fopen(const char *pFilename, const char *pMode) +{ + FILE *pFile = NULL; + fopen_s(&pFile, pFilename, pMode); + return pFile; +} +static FILE *mz_freopen(const char *pPath, const char *pMode, FILE *pStream) +{ + FILE *pFile = NULL; + if (freopen_s(&pFile, pPath, pMode, pStream)) + return NULL; + return pFile; +} +#ifndef MINIZ_NO_TIME +#include +#endif +#define MZ_FOPEN mz_fopen +#define MZ_FCLOSE fclose +#define MZ_FREAD fread +#define MZ_FWRITE fwrite +#define MZ_FTELL64 _ftelli64 +#define MZ_FSEEK64 _fseeki64 +#define MZ_FILE_STAT_STRUCT _stat64 +#define MZ_FILE_STAT _stat64 +#define MZ_FFLUSH fflush +#define MZ_FREOPEN mz_freopen +#define MZ_DELETE_FILE remove +#elif defined(__MINGW32__) +#ifndef MINIZ_NO_TIME +#include +#endif +#define MZ_FOPEN(f, m) fopen(f, m) +#define MZ_FCLOSE fclose +#define MZ_FREAD fread +#define MZ_FWRITE fwrite +#define MZ_FTELL64 ftello64 +#define MZ_FSEEK64 fseeko64 +#define MZ_FILE_STAT_STRUCT _stat +#define MZ_FILE_STAT _stat +#define MZ_FFLUSH fflush +#define MZ_FREOPEN(f, m, s) freopen(f, m, s) +#define MZ_DELETE_FILE remove +#elif defined(__TINYC__) +#ifndef MINIZ_NO_TIME +#include +#endif +#define MZ_FOPEN(f, m) fopen(f, m) +#define MZ_FCLOSE fclose +#define MZ_FREAD fread +#define MZ_FWRITE fwrite +#define MZ_FTELL64 ftell +#define MZ_FSEEK64 fseek +#define MZ_FILE_STAT_STRUCT stat +#define MZ_FILE_STAT stat +#define MZ_FFLUSH fflush +#define MZ_FREOPEN(f, m, s) freopen(f, m, s) +#define MZ_DELETE_FILE remove +#elif defined(__GNUC__) && defined(_LARGEFILE64_SOURCE) +#ifndef MINIZ_NO_TIME +#include +#endif +#define MZ_FOPEN(f, m) fopen64(f, m) +#define MZ_FCLOSE fclose +#define MZ_FREAD fread +#define MZ_FWRITE fwrite +#define MZ_FTELL64 ftello64 +#define MZ_FSEEK64 fseeko64 +#define MZ_FILE_STAT_STRUCT stat64 +#define MZ_FILE_STAT stat64 +#define MZ_FFLUSH fflush +#define MZ_FREOPEN(p, m, s) freopen64(p, m, s) +#define MZ_DELETE_FILE remove +#elif defined(__APPLE__) +#ifndef MINIZ_NO_TIME +#include +#endif +#define MZ_FOPEN(f, m) fopen(f, m) +#define MZ_FCLOSE fclose +#define MZ_FREAD fread +#define MZ_FWRITE fwrite +#define MZ_FTELL64 ftello +#define MZ_FSEEK64 fseeko +#define MZ_FILE_STAT_STRUCT stat +#define MZ_FILE_STAT stat +#define MZ_FFLUSH fflush +#define MZ_FREOPEN(p, m, s) freopen(p, m, s) +#define MZ_DELETE_FILE remove + +#else +#pragma message("Using fopen, ftello, fseeko, stat() etc. path for file I/O - this path may not support large files.") +#ifndef MINIZ_NO_TIME +#include +#endif +#define MZ_FOPEN(f, m) fopen(f, m) +#define MZ_FCLOSE fclose +#define MZ_FREAD fread +#define MZ_FWRITE fwrite +#ifdef __STRICT_ANSI__ +#define MZ_FTELL64 ftell +#define MZ_FSEEK64 fseek +#else +#define MZ_FTELL64 ftello +#define MZ_FSEEK64 fseeko +#endif +#define MZ_FILE_STAT_STRUCT stat +#define MZ_FILE_STAT stat +#define MZ_FFLUSH fflush +#define MZ_FREOPEN(f, m, s) freopen(f, m, s) +#define MZ_DELETE_FILE remove +#endif /* #ifdef _MSC_VER */ +#endif /* #ifdef MINIZ_NO_STDIO */ + +#define MZ_TOLOWER(c) ((((c) >= 'A') && ((c) <= 'Z')) ? ((c) - 'A' + 'a') : (c)) + +/* Various ZIP archive enums. To completely avoid cross platform compiler alignment and platform endian issues, miniz.c doesn't use structs for any of this stuff. */ +enum +{ + /* ZIP archive identifiers and record sizes */ + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06054b50, + MZ_ZIP_CENTRAL_DIR_HEADER_SIG = 0x02014b50, + MZ_ZIP_LOCAL_DIR_HEADER_SIG = 0x04034b50, + MZ_ZIP_LOCAL_DIR_HEADER_SIZE = 30, + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE = 46, + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE = 22, + + /* ZIP64 archive identifier and record sizes */ + MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06064b50, + MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIG = 0x07064b50, + MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE = 56, + MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE = 20, + MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID = 0x0001, + MZ_ZIP_DATA_DESCRIPTOR_ID = 0x08074b50, + MZ_ZIP_DATA_DESCRIPTER_SIZE64 = 24, + MZ_ZIP_DATA_DESCRIPTER_SIZE32 = 16, + + /* Central directory header record offsets */ + MZ_ZIP_CDH_SIG_OFS = 0, + MZ_ZIP_CDH_VERSION_MADE_BY_OFS = 4, + MZ_ZIP_CDH_VERSION_NEEDED_OFS = 6, + MZ_ZIP_CDH_BIT_FLAG_OFS = 8, + MZ_ZIP_CDH_METHOD_OFS = 10, + MZ_ZIP_CDH_FILE_TIME_OFS = 12, + MZ_ZIP_CDH_FILE_DATE_OFS = 14, + MZ_ZIP_CDH_CRC32_OFS = 16, + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS = 20, + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS = 24, + MZ_ZIP_CDH_FILENAME_LEN_OFS = 28, + MZ_ZIP_CDH_EXTRA_LEN_OFS = 30, + MZ_ZIP_CDH_COMMENT_LEN_OFS = 32, + MZ_ZIP_CDH_DISK_START_OFS = 34, + MZ_ZIP_CDH_INTERNAL_ATTR_OFS = 36, + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS = 38, + MZ_ZIP_CDH_LOCAL_HEADER_OFS = 42, + + /* Local directory header offsets */ + MZ_ZIP_LDH_SIG_OFS = 0, + MZ_ZIP_LDH_VERSION_NEEDED_OFS = 4, + MZ_ZIP_LDH_BIT_FLAG_OFS = 6, + MZ_ZIP_LDH_METHOD_OFS = 8, + MZ_ZIP_LDH_FILE_TIME_OFS = 10, + MZ_ZIP_LDH_FILE_DATE_OFS = 12, + MZ_ZIP_LDH_CRC32_OFS = 14, + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS = 18, + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS = 22, + MZ_ZIP_LDH_FILENAME_LEN_OFS = 26, + MZ_ZIP_LDH_EXTRA_LEN_OFS = 28, + MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR = 1 << 3, + + /* End of central directory offsets */ + MZ_ZIP_ECDH_SIG_OFS = 0, + MZ_ZIP_ECDH_NUM_THIS_DISK_OFS = 4, + MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS = 6, + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 8, + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS = 10, + MZ_ZIP_ECDH_CDIR_SIZE_OFS = 12, + MZ_ZIP_ECDH_CDIR_OFS_OFS = 16, + MZ_ZIP_ECDH_COMMENT_SIZE_OFS = 20, + + /* ZIP64 End of central directory locator offsets */ + MZ_ZIP64_ECDL_SIG_OFS = 0, /* 4 bytes */ + MZ_ZIP64_ECDL_NUM_DISK_CDIR_OFS = 4, /* 4 bytes */ + MZ_ZIP64_ECDL_REL_OFS_TO_ZIP64_ECDR_OFS = 8, /* 8 bytes */ + MZ_ZIP64_ECDL_TOTAL_NUMBER_OF_DISKS_OFS = 16, /* 4 bytes */ + + /* ZIP64 End of central directory header offsets */ + MZ_ZIP64_ECDH_SIG_OFS = 0, /* 4 bytes */ + MZ_ZIP64_ECDH_SIZE_OF_RECORD_OFS = 4, /* 8 bytes */ + MZ_ZIP64_ECDH_VERSION_MADE_BY_OFS = 12, /* 2 bytes */ + MZ_ZIP64_ECDH_VERSION_NEEDED_OFS = 14, /* 2 bytes */ + MZ_ZIP64_ECDH_NUM_THIS_DISK_OFS = 16, /* 4 bytes */ + MZ_ZIP64_ECDH_NUM_DISK_CDIR_OFS = 20, /* 4 bytes */ + MZ_ZIP64_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 24, /* 8 bytes */ + MZ_ZIP64_ECDH_CDIR_TOTAL_ENTRIES_OFS = 32, /* 8 bytes */ + MZ_ZIP64_ECDH_CDIR_SIZE_OFS = 40, /* 8 bytes */ + MZ_ZIP64_ECDH_CDIR_OFS_OFS = 48, /* 8 bytes */ + MZ_ZIP_VERSION_MADE_BY_DOS_FILESYSTEM_ID = 0, + MZ_ZIP_DOS_DIR_ATTRIBUTE_BITFLAG = 0x10, + MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED = 1, + MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG = 32, + MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION = 64, + MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_LOCAL_DIR_IS_MASKED = 8192, + MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_UTF8 = 1 << 11 +}; + +typedef struct +{ + void *m_p; + size_t m_size, m_capacity; + mz_uint m_element_size; +} mz_zip_array; + +struct mz_zip_internal_state_tag +{ + mz_zip_array m_central_dir; + mz_zip_array m_central_dir_offsets; + mz_zip_array m_sorted_central_dir_offsets; + + /* The flags passed in when the archive is initially opened. */ + uint32_t m_init_flags; + + /* MZ_TRUE if the archive has a zip64 end of central directory headers, etc. */ + mz_bool m_zip64; + + /* MZ_TRUE if we found zip64 extended info in the central directory (m_zip64 will also be slammed to true too, even if we didn't find a zip64 end of central dir header, etc.) */ + mz_bool m_zip64_has_extended_info_fields; + + /* These fields are used by the file, FILE, memory, and memory/heap read/write helpers. */ + MZ_FILE *m_pFile; + mz_uint64 m_file_archive_start_ofs; + + void *m_pMem; + size_t m_mem_size; + size_t m_mem_capacity; +}; + +#define MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(array_ptr, element_size) (array_ptr)->m_element_size = element_size + +#if defined(DEBUG) || defined(_DEBUG) || defined(NDEBUG) +static MZ_FORCEINLINE mz_uint mz_zip_array_range_check(const mz_zip_array *pArray, mz_uint index) +{ + MZ_ASSERT(index < pArray->m_size); + return index; +} +#define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) ((element_type *)((array_ptr)->m_p))[mz_zip_array_range_check(array_ptr, index)] +#else +#define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) ((element_type *)((array_ptr)->m_p))[index] +#endif + +static MZ_FORCEINLINE void mz_zip_array_init(mz_zip_array *pArray, mz_uint32 element_size) +{ + memset(pArray, 0, sizeof(mz_zip_array)); + pArray->m_element_size = element_size; +} + +static MZ_FORCEINLINE void mz_zip_array_clear(mz_zip_archive *pZip, mz_zip_array *pArray) +{ + pZip->m_pFree(pZip->m_pAlloc_opaque, pArray->m_p); + memset(pArray, 0, sizeof(mz_zip_array)); +} + +static mz_bool mz_zip_array_ensure_capacity(mz_zip_archive *pZip, mz_zip_array *pArray, size_t min_new_capacity, mz_uint growing) +{ + void *pNew_p; + size_t new_capacity = min_new_capacity; + MZ_ASSERT(pArray->m_element_size); + if (pArray->m_capacity >= min_new_capacity) + return MZ_TRUE; + if (growing) + { + new_capacity = MZ_MAX(1, pArray->m_capacity); + while (new_capacity < min_new_capacity) + new_capacity *= 2; + } + if (NULL == (pNew_p = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pArray->m_p, pArray->m_element_size, new_capacity))) + return MZ_FALSE; + pArray->m_p = pNew_p; + pArray->m_capacity = new_capacity; + return MZ_TRUE; +} + +static MZ_FORCEINLINE mz_bool mz_zip_array_reserve(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_capacity, mz_uint growing) +{ + if (new_capacity > pArray->m_capacity) + { + if (!mz_zip_array_ensure_capacity(pZip, pArray, new_capacity, growing)) + return MZ_FALSE; + } + return MZ_TRUE; +} + +static MZ_FORCEINLINE mz_bool mz_zip_array_resize(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_size, mz_uint growing) +{ + if (new_size > pArray->m_capacity) + { + if (!mz_zip_array_ensure_capacity(pZip, pArray, new_size, growing)) + return MZ_FALSE; + } + pArray->m_size = new_size; + return MZ_TRUE; +} + +static MZ_FORCEINLINE mz_bool mz_zip_array_ensure_room(mz_zip_archive *pZip, mz_zip_array *pArray, size_t n) +{ + return mz_zip_array_reserve(pZip, pArray, pArray->m_size + n, MZ_TRUE); +} + +static MZ_FORCEINLINE mz_bool mz_zip_array_push_back(mz_zip_archive *pZip, mz_zip_array *pArray, const void *pElements, size_t n) +{ + size_t orig_size = pArray->m_size; + if (!mz_zip_array_resize(pZip, pArray, orig_size + n, MZ_TRUE)) + return MZ_FALSE; + if (n > 0) + memcpy((mz_uint8 *)pArray->m_p + orig_size * pArray->m_element_size, pElements, n * pArray->m_element_size); + return MZ_TRUE; +} + +#ifndef MINIZ_NO_TIME +static MZ_TIME_T mz_zip_dos_to_time_t(int dos_time, int dos_date) +{ + struct tm tm; + memset(&tm, 0, sizeof(tm)); + tm.tm_isdst = -1; + tm.tm_year = ((dos_date >> 9) & 127) + 1980 - 1900; + tm.tm_mon = ((dos_date >> 5) & 15) - 1; + tm.tm_mday = dos_date & 31; + tm.tm_hour = (dos_time >> 11) & 31; + tm.tm_min = (dos_time >> 5) & 63; + tm.tm_sec = (dos_time << 1) & 62; + return mktime(&tm); +} + +#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS +static void mz_zip_time_t_to_dos_time(MZ_TIME_T time, mz_uint16 *pDOS_time, mz_uint16 *pDOS_date) +{ +#ifdef _MSC_VER + struct tm tm_struct; + struct tm *tm = &tm_struct; + errno_t err = localtime_s(tm, &time); + if (err) + { + *pDOS_date = 0; + *pDOS_time = 0; + return; + } +#else + struct tm *tm = localtime(&time); +#endif /* #ifdef _MSC_VER */ + + *pDOS_time = (mz_uint16)(((tm->tm_hour) << 11) + ((tm->tm_min) << 5) + ((tm->tm_sec) >> 1)); + *pDOS_date = (mz_uint16)(((tm->tm_year + 1900 - 1980) << 9) + ((tm->tm_mon + 1) << 5) + tm->tm_mday); +} +#endif /* MINIZ_NO_ARCHIVE_WRITING_APIS */ + +#ifndef MINIZ_NO_STDIO +#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS +static mz_bool mz_zip_get_file_modified_time(const char *pFilename, MZ_TIME_T *pTime) +{ + struct MZ_FILE_STAT_STRUCT file_stat; + + /* On Linux with x86 glibc, this call will fail on large files (I think >= 0x80000000 bytes) unless you compiled with _LARGEFILE64_SOURCE. Argh. */ + if (MZ_FILE_STAT(pFilename, &file_stat) != 0) + return MZ_FALSE; + + *pTime = file_stat.st_mtime; + + return MZ_TRUE; +} +#endif /* #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS*/ + +static mz_bool mz_zip_set_file_times(const char *pFilename, MZ_TIME_T access_time, MZ_TIME_T modified_time) +{ + struct utimbuf t; + + memset(&t, 0, sizeof(t)); + t.actime = access_time; + t.modtime = modified_time; + + return !utime(pFilename, &t); +} +#endif /* #ifndef MINIZ_NO_STDIO */ +#endif /* #ifndef MINIZ_NO_TIME */ + +static MZ_FORCEINLINE mz_bool mz_zip_set_error(mz_zip_archive *pZip, mz_zip_error err_num) +{ + if (pZip) + pZip->m_last_error = err_num; + return MZ_FALSE; +} + +static mz_bool mz_zip_reader_init_internal(mz_zip_archive *pZip, mz_uint flags) +{ + (void)flags; + if ((!pZip) || (pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (!pZip->m_pAlloc) + pZip->m_pAlloc = miniz_def_alloc_func; + if (!pZip->m_pFree) + pZip->m_pFree = miniz_def_free_func; + if (!pZip->m_pRealloc) + pZip->m_pRealloc = miniz_def_realloc_func; + + pZip->m_archive_size = 0; + pZip->m_central_directory_file_ofs = 0; + pZip->m_total_files = 0; + pZip->m_last_error = MZ_ZIP_NO_ERROR; + + if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32)); + pZip->m_pState->m_init_flags = flags; + pZip->m_pState->m_zip64 = MZ_FALSE; + pZip->m_pState->m_zip64_has_extended_info_fields = MZ_FALSE; + + pZip->m_zip_mode = MZ_ZIP_MODE_READING; + + return MZ_TRUE; +} + +static MZ_FORCEINLINE mz_bool mz_zip_reader_filename_less(const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, mz_uint r_index) +{ + const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE; + const mz_uint8 *pR = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, r_index)); + mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS), r_len = MZ_READ_LE16(pR + MZ_ZIP_CDH_FILENAME_LEN_OFS); + mz_uint8 l = 0, r = 0; + pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; + pR += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; + pE = pL + MZ_MIN(l_len, r_len); + while (pL < pE) + { + if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) + break; + pL++; + pR++; + } + return (pL == pE) ? (l_len < r_len) : (l < r); +} + +#define MZ_SWAP_UINT32(a, b) \ + do \ + { \ + mz_uint32 t = a; \ + a = b; \ + b = t; \ + } \ + MZ_MACRO_END + +/* Heap sort of lowercased filenames, used to help accelerate plain central directory searches by mz_zip_reader_locate_file(). (Could also use qsort(), but it could allocate memory.) */ +static void mz_zip_reader_sort_central_dir_offsets_by_filename(mz_zip_archive *pZip) +{ + mz_zip_internal_state *pState = pZip->m_pState; + const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; + const mz_zip_array *pCentral_dir = &pState->m_central_dir; + mz_uint32 *pIndices; + mz_uint32 start, end; + const mz_uint32 size = pZip->m_total_files; + + if (size <= 1U) + return; + + pIndices = &MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, mz_uint32, 0); + + start = (size - 2U) >> 1U; + for (;;) + { + mz_uint64 child, root = start; + for (;;) + { + if ((child = (root << 1U) + 1U) >= size) + break; + child += (((child + 1U) < size) && (mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1U]))); + if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) + break; + MZ_SWAP_UINT32(pIndices[root], pIndices[child]); + root = child; + } + if (!start) + break; + start--; + } + + end = size - 1; + while (end > 0) + { + mz_uint64 child, root = 0; + MZ_SWAP_UINT32(pIndices[end], pIndices[0]); + for (;;) + { + if ((child = (root << 1U) + 1U) >= end) + break; + child += (((child + 1U) < end) && mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1U])); + if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) + break; + MZ_SWAP_UINT32(pIndices[root], pIndices[child]); + root = child; + } + end--; + } +} + +static mz_bool mz_zip_reader_locate_header_sig(mz_zip_archive *pZip, mz_uint32 record_sig, mz_uint32 record_size, mz_int64 *pOfs) +{ + mz_int64 cur_file_ofs; + mz_uint32 buf_u32[4096 / sizeof(mz_uint32)]; + mz_uint8 *pBuf = (mz_uint8 *)buf_u32; + + /* Basic sanity checks - reject files which are too small */ + if (pZip->m_archive_size < record_size) + return MZ_FALSE; + + /* Find the record by scanning the file from the end towards the beginning. */ + cur_file_ofs = MZ_MAX((mz_int64)pZip->m_archive_size - (mz_int64)sizeof(buf_u32), 0); + for (;;) + { + int i, n = (int)MZ_MIN(sizeof(buf_u32), pZip->m_archive_size - cur_file_ofs); + + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, n) != (mz_uint)n) + return MZ_FALSE; + + for (i = n - 4; i >= 0; --i) + { + mz_uint s = MZ_READ_LE32(pBuf + i); + if (s == record_sig) + { + if ((pZip->m_archive_size - (cur_file_ofs + i)) >= record_size) + break; + } + } + + if (i >= 0) + { + cur_file_ofs += i; + break; + } + + /* Give up if we've searched the entire file, or we've gone back "too far" (~64kb) */ + if ((!cur_file_ofs) || ((pZip->m_archive_size - cur_file_ofs) >= (MZ_UINT16_MAX + record_size))) + return MZ_FALSE; + + cur_file_ofs = MZ_MAX(cur_file_ofs - (sizeof(buf_u32) - 3), 0); + } + + *pOfs = cur_file_ofs; + return MZ_TRUE; +} + +static mz_bool mz_zip_reader_read_central_dir(mz_zip_archive *pZip, mz_uint flags) +{ + mz_uint cdir_size = 0, cdir_entries_on_this_disk = 0, num_this_disk = 0, cdir_disk_index = 0; + mz_uint64 cdir_ofs = 0; + mz_int64 cur_file_ofs = 0; + const mz_uint8 *p; + + mz_uint32 buf_u32[4096 / sizeof(mz_uint32)]; + mz_uint8 *pBuf = (mz_uint8 *)buf_u32; + mz_bool sort_central_dir = ((flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0); + mz_uint32 zip64_end_of_central_dir_locator_u32[(MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; + mz_uint8 *pZip64_locator = (mz_uint8 *)zip64_end_of_central_dir_locator_u32; + + mz_uint32 zip64_end_of_central_dir_header_u32[(MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; + mz_uint8 *pZip64_end_of_central_dir = (mz_uint8 *)zip64_end_of_central_dir_header_u32; + + mz_uint64 zip64_end_of_central_dir_ofs = 0; + + /* Basic sanity checks - reject files which are too small, and check the first 4 bytes of the file to make sure a local header is there. */ + if (pZip->m_archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); + + if (!mz_zip_reader_locate_header_sig(pZip, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE, &cur_file_ofs)) + return mz_zip_set_error(pZip, MZ_ZIP_FAILED_FINDING_CENTRAL_DIR); + + /* Read and verify the end of central directory record. */ + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + + if (MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_SIG_OFS) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) + return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); + + if (cur_file_ofs >= (MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE + MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE)) + { + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs - MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE, pZip64_locator, MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) == MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) + { + if (MZ_READ_LE32(pZip64_locator + MZ_ZIP64_ECDL_SIG_OFS) == MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIG) + { + zip64_end_of_central_dir_ofs = MZ_READ_LE64(pZip64_locator + MZ_ZIP64_ECDL_REL_OFS_TO_ZIP64_ECDR_OFS); + if (zip64_end_of_central_dir_ofs > (pZip->m_archive_size - MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE)) + return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); + + if (pZip->m_pRead(pZip->m_pIO_opaque, zip64_end_of_central_dir_ofs, pZip64_end_of_central_dir, MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) == MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) + { + if (MZ_READ_LE32(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_SIG_OFS) == MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIG) + { + pZip->m_pState->m_zip64 = MZ_TRUE; + } + } + } + } + } + + pZip->m_total_files = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS); + cdir_entries_on_this_disk = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS); + num_this_disk = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_THIS_DISK_OFS); + cdir_disk_index = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS); + cdir_size = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_SIZE_OFS); + cdir_ofs = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_OFS_OFS); + + if (pZip->m_pState->m_zip64) + { + mz_uint32 zip64_total_num_of_disks = MZ_READ_LE32(pZip64_locator + MZ_ZIP64_ECDL_TOTAL_NUMBER_OF_DISKS_OFS); + mz_uint64 zip64_cdir_total_entries = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_TOTAL_ENTRIES_OFS); + mz_uint64 zip64_cdir_total_entries_on_this_disk = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS); + mz_uint64 zip64_size_of_end_of_central_dir_record = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_SIZE_OF_RECORD_OFS); + mz_uint64 zip64_size_of_central_directory = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_SIZE_OFS); + + if (zip64_size_of_end_of_central_dir_record < (MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE - 12)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if (zip64_total_num_of_disks != 1U) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK); + + /* Check for miniz's practical limits */ + if (zip64_cdir_total_entries > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + + pZip->m_total_files = (mz_uint32)zip64_cdir_total_entries; + + if (zip64_cdir_total_entries_on_this_disk > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + + cdir_entries_on_this_disk = (mz_uint32)zip64_cdir_total_entries_on_this_disk; + + /* Check for miniz's current practical limits (sorry, this should be enough for millions of files) */ + if (zip64_size_of_central_directory > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); + + cdir_size = (mz_uint32)zip64_size_of_central_directory; + + num_this_disk = MZ_READ_LE32(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_NUM_THIS_DISK_OFS); + + cdir_disk_index = MZ_READ_LE32(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_NUM_DISK_CDIR_OFS); + + cdir_ofs = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_OFS_OFS); + } + + if (pZip->m_total_files != cdir_entries_on_this_disk) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK); + + if (((num_this_disk | cdir_disk_index) != 0) && ((num_this_disk != 1) || (cdir_disk_index != 1))) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK); + + if (cdir_size < pZip->m_total_files * MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if ((cdir_ofs + (mz_uint64)cdir_size) > pZip->m_archive_size) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + pZip->m_central_directory_file_ofs = cdir_ofs; + + if (pZip->m_total_files) + { + mz_uint i, n; + /* Read the entire central directory into a heap block, and allocate another heap block to hold the unsorted central dir file record offsets, and possibly another to hold the sorted indices. */ + if ((!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir, cdir_size, MZ_FALSE)) || + (!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir_offsets, pZip->m_total_files, MZ_FALSE))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + if (sort_central_dir) + { + if (!mz_zip_array_resize(pZip, &pZip->m_pState->m_sorted_central_dir_offsets, pZip->m_total_files, MZ_FALSE)) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if (pZip->m_pRead(pZip->m_pIO_opaque, cdir_ofs, pZip->m_pState->m_central_dir.m_p, cdir_size) != cdir_size) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + + /* Now create an index into the central directory file records, do some basic sanity checking on each record */ + p = (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p; + for (n = cdir_size, i = 0; i < pZip->m_total_files; ++i) + { + mz_uint total_header_size, disk_index, bit_flags, filename_size, ext_data_size; + mz_uint64 comp_size, decomp_size, local_header_ofs; + + if ((n < MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) || (MZ_READ_LE32(p) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, i) = (mz_uint32)(p - (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p); + + if (sort_central_dir) + MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_sorted_central_dir_offsets, mz_uint32, i) = i; + + comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); + decomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); + local_header_ofs = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS); + filename_size = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); + ext_data_size = MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS); + + if ((!pZip->m_pState->m_zip64_has_extended_info_fields) && + (ext_data_size) && + (MZ_MAX(MZ_MAX(comp_size, decomp_size), local_header_ofs) == MZ_UINT32_MAX)) + { + /* Attempt to find zip64 extended information field in the entry's extra data */ + mz_uint32 extra_size_remaining = ext_data_size; + + if (extra_size_remaining) + { + const mz_uint8 *pExtra_data; + void* buf = NULL; + + if (MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + ext_data_size > n) + { + buf = MZ_MALLOC(ext_data_size); + if(buf==NULL) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + if (pZip->m_pRead(pZip->m_pIO_opaque, cdir_ofs + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size, buf, ext_data_size) != ext_data_size) + { + MZ_FREE(buf); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + } + + pExtra_data = (mz_uint8*)buf; + } + else + { + pExtra_data = p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size; + } + + do + { + mz_uint32 field_id; + mz_uint32 field_data_size; + + if (extra_size_remaining < (sizeof(mz_uint16) * 2)) + { + MZ_FREE(buf); + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + } + + field_id = MZ_READ_LE16(pExtra_data); + field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); + + if ((field_data_size + sizeof(mz_uint16) * 2) > extra_size_remaining) + { + MZ_FREE(buf); + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + } + + if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) + { + /* Ok, the archive didn't have any zip64 headers but it uses a zip64 extended information field so mark it as zip64 anyway (this can occur with infozip's zip util when it reads compresses files from stdin). */ + pZip->m_pState->m_zip64 = MZ_TRUE; + pZip->m_pState->m_zip64_has_extended_info_fields = MZ_TRUE; + break; + } + + pExtra_data += sizeof(mz_uint16) * 2 + field_data_size; + extra_size_remaining = extra_size_remaining - sizeof(mz_uint16) * 2 - field_data_size; + } while (extra_size_remaining); + + MZ_FREE(buf); + } + } + + /* I've seen archives that aren't marked as zip64 that uses zip64 ext data, argh */ + if ((comp_size != MZ_UINT32_MAX) && (decomp_size != MZ_UINT32_MAX)) + { + if (((!MZ_READ_LE32(p + MZ_ZIP_CDH_METHOD_OFS)) && (decomp_size != comp_size)) || (decomp_size && !comp_size)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + } + + disk_index = MZ_READ_LE16(p + MZ_ZIP_CDH_DISK_START_OFS); + if ((disk_index == MZ_UINT16_MAX) || ((disk_index != num_this_disk) && (disk_index != 1))) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK); + + if (comp_size != MZ_UINT32_MAX) + { + if (((mz_uint64)MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS) + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + comp_size) > pZip->m_archive_size) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + } + + bit_flags = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); + if (bit_flags & MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_LOCAL_DIR_IS_MASKED) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); + + if ((total_header_size = MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS)) > n) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + n -= total_header_size; + p += total_header_size; + } + } + + if (sort_central_dir) + mz_zip_reader_sort_central_dir_offsets_by_filename(pZip); + + return MZ_TRUE; +} + +void mz_zip_zero_struct(mz_zip_archive *pZip) +{ + if (pZip) + MZ_CLEAR_OBJ(*pZip); +} + +static mz_bool mz_zip_reader_end_internal(mz_zip_archive *pZip, mz_bool set_last_error) +{ + mz_bool status = MZ_TRUE; + + if (!pZip) + return MZ_FALSE; + + if ((!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) + { + if (set_last_error) + pZip->m_last_error = MZ_ZIP_INVALID_PARAMETER; + + return MZ_FALSE; + } + + if (pZip->m_pState) + { + mz_zip_internal_state *pState = pZip->m_pState; + pZip->m_pState = NULL; + + mz_zip_array_clear(pZip, &pState->m_central_dir); + mz_zip_array_clear(pZip, &pState->m_central_dir_offsets); + mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); + +#ifndef MINIZ_NO_STDIO + if (pState->m_pFile) + { + if (pZip->m_zip_type == MZ_ZIP_TYPE_FILE) + { + if (MZ_FCLOSE(pState->m_pFile) == EOF) + { + if (set_last_error) + pZip->m_last_error = MZ_ZIP_FILE_CLOSE_FAILED; + status = MZ_FALSE; + } + } + pState->m_pFile = NULL; + } +#endif /* #ifndef MINIZ_NO_STDIO */ + + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + } + pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; + + return status; +} + +mz_bool mz_zip_reader_end(mz_zip_archive *pZip) +{ + return mz_zip_reader_end_internal(pZip, MZ_TRUE); +} +mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint flags) +{ + if ((!pZip) || (!pZip->m_pRead)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (!mz_zip_reader_init_internal(pZip, flags)) + return MZ_FALSE; + + pZip->m_zip_type = MZ_ZIP_TYPE_USER; + pZip->m_archive_size = size; + + if (!mz_zip_reader_read_central_dir(pZip, flags)) + { + mz_zip_reader_end_internal(pZip, MZ_FALSE); + return MZ_FALSE; + } + + return MZ_TRUE; +} + +static size_t mz_zip_mem_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) +{ + mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; + size_t s = (file_ofs >= pZip->m_archive_size) ? 0 : (size_t)MZ_MIN(pZip->m_archive_size - file_ofs, n); + memcpy(pBuf, (const mz_uint8 *)pZip->m_pState->m_pMem + file_ofs, s); + return s; +} + +mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint flags) +{ + if (!pMem) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); + + if (!mz_zip_reader_init_internal(pZip, flags)) + return MZ_FALSE; + + pZip->m_zip_type = MZ_ZIP_TYPE_MEMORY; + pZip->m_archive_size = size; + pZip->m_pRead = mz_zip_mem_read_func; + pZip->m_pIO_opaque = pZip; + pZip->m_pNeeds_keepalive = NULL; + +#ifdef __cplusplus + pZip->m_pState->m_pMem = const_cast(pMem); +#else + pZip->m_pState->m_pMem = (void *)pMem; +#endif + + pZip->m_pState->m_mem_size = size; + + if (!mz_zip_reader_read_central_dir(pZip, flags)) + { + mz_zip_reader_end_internal(pZip, MZ_FALSE); + return MZ_FALSE; + } + + return MZ_TRUE; +} + +#ifndef MINIZ_NO_STDIO +static size_t mz_zip_file_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) +{ + mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; + mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); + + file_ofs += pZip->m_pState->m_file_archive_start_ofs; + + if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) + return 0; + + return MZ_FREAD(pBuf, 1, n, pZip->m_pState->m_pFile); +} + +mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags) +{ + return mz_zip_reader_init_file_v2(pZip, pFilename, flags, 0, 0); +} + +mz_bool mz_zip_reader_init_file_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint flags, mz_uint64 file_start_ofs, mz_uint64 archive_size) +{ + mz_uint64 file_size; + MZ_FILE *pFile; + + if ((!pZip) || (!pFilename) || ((archive_size) && (archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE))) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pFile = MZ_FOPEN(pFilename, "rb"); + if (!pFile) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); + + file_size = archive_size; + if (!file_size) + { + if (MZ_FSEEK64(pFile, 0, SEEK_END)) + { + MZ_FCLOSE(pFile); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_SEEK_FAILED); + } + + file_size = MZ_FTELL64(pFile); + } + + /* TODO: Better sanity check archive_size and the # of actual remaining bytes */ + + if (file_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + { + MZ_FCLOSE(pFile); + return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); + } + + if (!mz_zip_reader_init_internal(pZip, flags)) + { + MZ_FCLOSE(pFile); + return MZ_FALSE; + } + + pZip->m_zip_type = MZ_ZIP_TYPE_FILE; + pZip->m_pRead = mz_zip_file_read_func; + pZip->m_pIO_opaque = pZip; + pZip->m_pState->m_pFile = pFile; + pZip->m_archive_size = file_size; + pZip->m_pState->m_file_archive_start_ofs = file_start_ofs; + + if (!mz_zip_reader_read_central_dir(pZip, flags)) + { + mz_zip_reader_end_internal(pZip, MZ_FALSE); + return MZ_FALSE; + } + + return MZ_TRUE; +} + +mz_bool mz_zip_reader_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile, mz_uint64 archive_size, mz_uint flags) +{ + mz_uint64 cur_file_ofs; + + if ((!pZip) || (!pFile)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); + + cur_file_ofs = MZ_FTELL64(pFile); + + if (!archive_size) + { + if (MZ_FSEEK64(pFile, 0, SEEK_END)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_SEEK_FAILED); + + archive_size = MZ_FTELL64(pFile) - cur_file_ofs; + + if (archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); + } + + if (!mz_zip_reader_init_internal(pZip, flags)) + return MZ_FALSE; + + pZip->m_zip_type = MZ_ZIP_TYPE_CFILE; + pZip->m_pRead = mz_zip_file_read_func; + + pZip->m_pIO_opaque = pZip; + pZip->m_pState->m_pFile = pFile; + pZip->m_archive_size = archive_size; + pZip->m_pState->m_file_archive_start_ofs = cur_file_ofs; + + if (!mz_zip_reader_read_central_dir(pZip, flags)) + { + mz_zip_reader_end_internal(pZip, MZ_FALSE); + return MZ_FALSE; + } + + return MZ_TRUE; +} + +#endif /* #ifndef MINIZ_NO_STDIO */ + +static MZ_FORCEINLINE const mz_uint8 *mz_zip_get_cdh(mz_zip_archive *pZip, mz_uint file_index) +{ + if ((!pZip) || (!pZip->m_pState) || (file_index >= pZip->m_total_files)) + return NULL; + return &MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index)); +} + +mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index) +{ + mz_uint m_bit_flag; + const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index); + if (!p) + { + mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + return MZ_FALSE; + } + + m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); + return (m_bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION)) != 0; +} + +mz_bool mz_zip_reader_is_file_supported(mz_zip_archive *pZip, mz_uint file_index) +{ + mz_uint bit_flag; + mz_uint method; + + const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index); + if (!p) + { + mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + return MZ_FALSE; + } + + method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS); + bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); + + if ((method != 0) && (method != MZ_DEFLATED)) + { + mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); + return MZ_FALSE; + } + + if (bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION)) + { + mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); + return MZ_FALSE; + } + + if (bit_flag & MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG) + { + mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_FEATURE); + return MZ_FALSE; + } + + return MZ_TRUE; +} + +mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index) +{ + mz_uint filename_len, attribute_mapping_id, external_attr; + const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index); + if (!p) + { + mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + return MZ_FALSE; + } + + filename_len = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); + if (filename_len) + { + if (*(p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_len - 1) == '/') + return MZ_TRUE; + } + + /* Bugfix: This code was also checking if the internal attribute was non-zero, which wasn't correct. */ + /* Most/all zip writers (hopefully) set DOS file/directory attributes in the low 16-bits, so check for the DOS directory flag and ignore the source OS ID in the created by field. */ + /* FIXME: Remove this check? Is it necessary - we already check the filename. */ + attribute_mapping_id = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS) >> 8; + (void)attribute_mapping_id; + + external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); + if ((external_attr & MZ_ZIP_DOS_DIR_ATTRIBUTE_BITFLAG) != 0) + { + return MZ_TRUE; + } + + return MZ_FALSE; +} + +static mz_bool mz_zip_file_stat_internal(mz_zip_archive *pZip, mz_uint file_index, const mz_uint8 *pCentral_dir_header, mz_zip_archive_file_stat *pStat, mz_bool *pFound_zip64_extra_data) +{ + mz_uint n; + const mz_uint8 *p = pCentral_dir_header; + + if (pFound_zip64_extra_data) + *pFound_zip64_extra_data = MZ_FALSE; + + if ((!p) || (!pStat)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + /* Extract fields from the central directory record. */ + pStat->m_file_index = file_index; + pStat->m_central_dir_ofs = MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index); + pStat->m_version_made_by = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS); + pStat->m_version_needed = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_NEEDED_OFS); + pStat->m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); + pStat->m_method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS); +#ifndef MINIZ_NO_TIME + pStat->m_time = mz_zip_dos_to_time_t(MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_TIME_OFS), MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_DATE_OFS)); +#endif + pStat->m_crc32 = MZ_READ_LE32(p + MZ_ZIP_CDH_CRC32_OFS); + pStat->m_comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); + pStat->m_uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); + pStat->m_internal_attr = MZ_READ_LE16(p + MZ_ZIP_CDH_INTERNAL_ATTR_OFS); + pStat->m_external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); + pStat->m_local_header_ofs = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS); + + /* Copy as much of the filename and comment as possible. */ + n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); + n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE - 1); + memcpy(pStat->m_filename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); + pStat->m_filename[n] = '\0'; + + n = MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS); + n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE - 1); + pStat->m_comment_size = n; + memcpy(pStat->m_comment, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS), n); + pStat->m_comment[n] = '\0'; + + /* Set some flags for convienance */ + pStat->m_is_directory = mz_zip_reader_is_file_a_directory(pZip, file_index); + pStat->m_is_encrypted = mz_zip_reader_is_file_encrypted(pZip, file_index); + pStat->m_is_supported = mz_zip_reader_is_file_supported(pZip, file_index); + + /* See if we need to read any zip64 extended information fields. */ + /* Confusingly, these zip64 fields can be present even on non-zip64 archives (Debian zip on a huge files from stdin piped to stdout creates them). */ + if (MZ_MAX(MZ_MAX(pStat->m_comp_size, pStat->m_uncomp_size), pStat->m_local_header_ofs) == MZ_UINT32_MAX) + { + /* Attempt to find zip64 extended information field in the entry's extra data */ + mz_uint32 extra_size_remaining = MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS); + + if (extra_size_remaining) + { + const mz_uint8 *pExtra_data = p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); + + do + { + mz_uint32 field_id; + mz_uint32 field_data_size; + + if (extra_size_remaining < (sizeof(mz_uint16) * 2)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + field_id = MZ_READ_LE16(pExtra_data); + field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); + + if ((field_data_size + sizeof(mz_uint16) * 2) > extra_size_remaining) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) + { + const mz_uint8 *pField_data = pExtra_data + sizeof(mz_uint16) * 2; + mz_uint32 field_data_remaining = field_data_size; + + if (pFound_zip64_extra_data) + *pFound_zip64_extra_data = MZ_TRUE; + + if (pStat->m_uncomp_size == MZ_UINT32_MAX) + { + if (field_data_remaining < sizeof(mz_uint64)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + pStat->m_uncomp_size = MZ_READ_LE64(pField_data); + pField_data += sizeof(mz_uint64); + field_data_remaining -= sizeof(mz_uint64); + } + + if (pStat->m_comp_size == MZ_UINT32_MAX) + { + if (field_data_remaining < sizeof(mz_uint64)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + pStat->m_comp_size = MZ_READ_LE64(pField_data); + pField_data += sizeof(mz_uint64); + field_data_remaining -= sizeof(mz_uint64); + } + + if (pStat->m_local_header_ofs == MZ_UINT32_MAX) + { + if (field_data_remaining < sizeof(mz_uint64)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + pStat->m_local_header_ofs = MZ_READ_LE64(pField_data); + pField_data += sizeof(mz_uint64); + field_data_remaining -= sizeof(mz_uint64); + } + + break; + } + + pExtra_data += sizeof(mz_uint16) * 2 + field_data_size; + extra_size_remaining = extra_size_remaining - sizeof(mz_uint16) * 2 - field_data_size; + } while (extra_size_remaining); + } + } + + return MZ_TRUE; +} + +static MZ_FORCEINLINE mz_bool mz_zip_string_equal(const char *pA, const char *pB, mz_uint len, mz_uint flags) +{ + mz_uint i; + if (flags & MZ_ZIP_FLAG_CASE_SENSITIVE) + return 0 == memcmp(pA, pB, len); + for (i = 0; i < len; ++i) + if (MZ_TOLOWER(pA[i]) != MZ_TOLOWER(pB[i])) + return MZ_FALSE; + return MZ_TRUE; +} + +static MZ_FORCEINLINE int mz_zip_filename_compare(const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, const char *pR, mz_uint r_len) +{ + const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE; + mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS); + mz_uint8 l = 0, r = 0; + pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; + pE = pL + MZ_MIN(l_len, r_len); + while (pL < pE) + { + if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) + break; + pL++; + pR++; + } + return (pL == pE) ? (int)(l_len - r_len) : (l - r); +} + +static mz_bool mz_zip_locate_file_binary_search(mz_zip_archive *pZip, const char *pFilename, mz_uint32 *pIndex) +{ + mz_zip_internal_state *pState = pZip->m_pState; + const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; + const mz_zip_array *pCentral_dir = &pState->m_central_dir; + mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, mz_uint32, 0); + const uint32_t size = pZip->m_total_files; + const mz_uint filename_len = (mz_uint)strlen(pFilename); + + if (pIndex) + *pIndex = 0; + + if (size) + { + /* yes I could use uint32_t's, but then we would have to add some special case checks in the loop, argh, and */ + /* honestly the major expense here on 32-bit CPU's will still be the filename compare */ + mz_int64 l = 0, h = (mz_int64)size - 1; + + while (l <= h) + { + mz_int64 m = l + ((h - l) >> 1); + uint32_t file_index = pIndices[(uint32_t)m]; + + int comp = mz_zip_filename_compare(pCentral_dir, pCentral_dir_offsets, file_index, pFilename, filename_len); + if (!comp) + { + if (pIndex) + *pIndex = file_index; + return MZ_TRUE; + } + else if (comp < 0) + l = m + 1; + else + h = m - 1; + } + } + + return mz_zip_set_error(pZip, MZ_ZIP_FILE_NOT_FOUND); +} + +int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags) +{ + mz_uint32 index; + if (!mz_zip_reader_locate_file_v2(pZip, pName, pComment, flags, &index)) + return -1; + else + return (int)index; +} + +mz_bool mz_zip_reader_locate_file_v2(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags, mz_uint32 *pIndex) +{ + mz_uint file_index; + size_t name_len, comment_len; + + if (pIndex) + *pIndex = 0; + + if ((!pZip) || (!pZip->m_pState) || (!pName)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + /* See if we can use a binary search */ + if (((pZip->m_pState->m_init_flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0) && + (pZip->m_zip_mode == MZ_ZIP_MODE_READING) && + ((flags & (MZ_ZIP_FLAG_IGNORE_PATH | MZ_ZIP_FLAG_CASE_SENSITIVE)) == 0) && (!pComment) && (pZip->m_pState->m_sorted_central_dir_offsets.m_size)) + { + return mz_zip_locate_file_binary_search(pZip, pName, pIndex); + } + + /* Locate the entry by scanning the entire central directory */ + name_len = strlen(pName); + if (name_len > MZ_UINT16_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + comment_len = pComment ? strlen(pComment) : 0; + if (comment_len > MZ_UINT16_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + for (file_index = 0; file_index < pZip->m_total_files; file_index++) + { + const mz_uint8 *pHeader = &MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index)); + mz_uint filename_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_FILENAME_LEN_OFS); + const char *pFilename = (const char *)pHeader + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; + if (filename_len < name_len) + continue; + if (comment_len) + { + mz_uint file_extra_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_EXTRA_LEN_OFS), file_comment_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_COMMENT_LEN_OFS); + const char *pFile_comment = pFilename + filename_len + file_extra_len; + if ((file_comment_len != comment_len) || (!mz_zip_string_equal(pComment, pFile_comment, file_comment_len, flags))) + continue; + } + if ((flags & MZ_ZIP_FLAG_IGNORE_PATH) && (filename_len)) + { + int ofs = filename_len - 1; + do + { + if ((pFilename[ofs] == '/') || (pFilename[ofs] == '\\') || (pFilename[ofs] == ':')) + break; + } while (--ofs >= 0); + ofs++; + pFilename += ofs; + filename_len -= ofs; + } + if ((filename_len == name_len) && (mz_zip_string_equal(pName, pFilename, filename_len, flags))) + { + if (pIndex) + *pIndex = file_index; + return MZ_TRUE; + } + } + + return mz_zip_set_error(pZip, MZ_ZIP_FILE_NOT_FOUND); +} + +mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) +{ + int status = TINFL_STATUS_DONE; + mz_uint64 needed_size, cur_file_ofs, comp_remaining, out_buf_ofs = 0, read_buf_size, read_buf_ofs = 0, read_buf_avail; + mz_zip_archive_file_stat file_stat; + void *pRead_buf; + mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; + mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; + tinfl_decompressor inflator; + + if ((!pZip) || (!pZip->m_pState) || ((buf_size) && (!pBuf)) || ((user_read_buf_size) && (!pUser_read_buf)) || (!pZip->m_pRead)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) + return MZ_FALSE; + + /* A directory or zero length file */ + if ((file_stat.m_is_directory) || (!file_stat.m_comp_size)) + return MZ_TRUE; + + /* Encryption and patch files are not supported. */ + if (file_stat.m_bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG)) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); + + /* This function only supports decompressing stored and deflate. */ + if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); + + /* Ensure supplied output buffer is large enough. */ + needed_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? file_stat.m_comp_size : file_stat.m_uncomp_size; + if (buf_size < needed_size) + return mz_zip_set_error(pZip, MZ_ZIP_BUF_TOO_SMALL); + + /* Read and parse the local directory entry. */ + cur_file_ofs = file_stat.m_local_header_ofs; + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + + if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); + if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) + { + /* The file is stored or the caller has requested the compressed data. */ + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, (size_t)needed_size) != needed_size) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) == 0) + { + if (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32) + return mz_zip_set_error(pZip, MZ_ZIP_CRC_CHECK_FAILED); + } +#endif + + return MZ_TRUE; + } + + /* Decompress the file either directly from memory or from a file input buffer. */ + tinfl_init(&inflator); + + if (pZip->m_pState->m_pMem) + { + /* Read directly from the archive in memory. */ + pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; + read_buf_size = read_buf_avail = file_stat.m_comp_size; + comp_remaining = 0; + } + else if (pUser_read_buf) + { + /* Use a user provided read buffer. */ + if (!user_read_buf_size) + return MZ_FALSE; + pRead_buf = (mz_uint8 *)pUser_read_buf; + read_buf_size = user_read_buf_size; + read_buf_avail = 0; + comp_remaining = file_stat.m_comp_size; + } + else + { + /* Temporarily allocate a read buffer. */ + read_buf_size = MZ_MIN(file_stat.m_comp_size, (mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE); + if (((sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF)) + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + + if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + read_buf_avail = 0; + comp_remaining = file_stat.m_comp_size; + } + + do + { + /* The size_t cast here should be OK because we've verified that the output buffer is >= file_stat.m_uncomp_size above */ + size_t in_buf_size, out_buf_size = (size_t)(file_stat.m_uncomp_size - out_buf_ofs); + if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) + { + read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) + { + status = TINFL_STATUS_FAILED; + mz_zip_set_error(pZip, MZ_ZIP_DECOMPRESSION_FAILED); + break; + } + cur_file_ofs += read_buf_avail; + comp_remaining -= read_buf_avail; + read_buf_ofs = 0; + } + in_buf_size = (size_t)read_buf_avail; + status = tinfl_decompress(&inflator, (mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pBuf, (mz_uint8 *)pBuf + out_buf_ofs, &out_buf_size, TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF | (comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0)); + read_buf_avail -= in_buf_size; + read_buf_ofs += in_buf_size; + out_buf_ofs += out_buf_size; + } while (status == TINFL_STATUS_NEEDS_MORE_INPUT); + + if (status == TINFL_STATUS_DONE) + { + /* Make sure the entire file was decompressed, and check its CRC. */ + if (out_buf_ofs != file_stat.m_uncomp_size) + { + mz_zip_set_error(pZip, MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE); + status = TINFL_STATUS_FAILED; + } +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + else if (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32) + { + mz_zip_set_error(pZip, MZ_ZIP_CRC_CHECK_FAILED); + status = TINFL_STATUS_FAILED; + } +#endif + } + + if ((!pZip->m_pState->m_pMem) && (!pUser_read_buf)) + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + + return status == TINFL_STATUS_DONE; +} + +mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) +{ + mz_uint32 file_index; + if (!mz_zip_reader_locate_file_v2(pZip, pFilename, NULL, flags, &file_index)) + return MZ_FALSE; + return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, pUser_read_buf, user_read_buf_size); +} + +mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags) +{ + return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, NULL, 0); +} + +mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags) +{ + return mz_zip_reader_extract_file_to_mem_no_alloc(pZip, pFilename, pBuf, buf_size, flags, NULL, 0); +} + +void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags) +{ + mz_uint64 comp_size, uncomp_size, alloc_size; + const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index); + void *pBuf; + + if (pSize) + *pSize = 0; + + if (!p) + { + mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + return NULL; + } + + comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); + uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); + + alloc_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? comp_size : uncomp_size; + if (((sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF)) + { + mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + return NULL; + } + + if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)alloc_size))) + { + mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + return NULL; + } + + if (!mz_zip_reader_extract_to_mem(pZip, file_index, pBuf, (size_t)alloc_size, flags)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return NULL; + } + + if (pSize) + *pSize = (size_t)alloc_size; + return pBuf; +} + +void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags) +{ + mz_uint32 file_index; + if (!mz_zip_reader_locate_file_v2(pZip, pFilename, NULL, flags, &file_index)) + { + if (pSize) + *pSize = 0; + return MZ_FALSE; + } + return mz_zip_reader_extract_to_heap(pZip, file_index, pSize, flags); +} + +mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags) +{ + int status = TINFL_STATUS_DONE; + mz_uint file_crc32 = MZ_CRC32_INIT; + mz_uint64 read_buf_size, read_buf_ofs = 0, read_buf_avail, comp_remaining, out_buf_ofs = 0, cur_file_ofs; + mz_zip_archive_file_stat file_stat; + void *pRead_buf = NULL; + void *pWrite_buf = NULL; + mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; + mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; + + if ((!pZip) || (!pZip->m_pState) || (!pCallback) || (!pZip->m_pRead)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) + return MZ_FALSE; + + /* A directory or zero length file */ + if ((file_stat.m_is_directory) || (!file_stat.m_comp_size)) + return MZ_TRUE; + + /* Encryption and patch files are not supported. */ + if (file_stat.m_bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG)) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); + + /* This function only supports decompressing stored and deflate. */ + if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); + + /* Read and do some minimal validation of the local directory entry (this doesn't crack the zip64 stuff, which we already have from the central dir) */ + cur_file_ofs = file_stat.m_local_header_ofs; + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + + if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); + if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + /* Decompress the file either directly from memory or from a file input buffer. */ + if (pZip->m_pState->m_pMem) + { + pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; + read_buf_size = read_buf_avail = file_stat.m_comp_size; + comp_remaining = 0; + } + else + { + read_buf_size = MZ_MIN(file_stat.m_comp_size, (mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE); + if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + read_buf_avail = 0; + comp_remaining = file_stat.m_comp_size; + } + + if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) + { + /* The file is stored or the caller has requested the compressed data. */ + if (pZip->m_pState->m_pMem) + { + if (((sizeof(size_t) == sizeof(mz_uint32))) && (file_stat.m_comp_size > MZ_UINT32_MAX)) + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + + if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)file_stat.m_comp_size) != file_stat.m_comp_size) + { + mz_zip_set_error(pZip, MZ_ZIP_WRITE_CALLBACK_FAILED); + status = TINFL_STATUS_FAILED; + } + else if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) + { +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)file_stat.m_comp_size); +#endif + } + + cur_file_ofs += file_stat.m_comp_size; + out_buf_ofs += file_stat.m_comp_size; + comp_remaining = 0; + } + else + { + while (comp_remaining) + { + read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) + { + mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + status = TINFL_STATUS_FAILED; + break; + } + +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) + { + file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)read_buf_avail); + } +#endif + + if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) + { + mz_zip_set_error(pZip, MZ_ZIP_WRITE_CALLBACK_FAILED); + status = TINFL_STATUS_FAILED; + break; + } + + cur_file_ofs += read_buf_avail; + out_buf_ofs += read_buf_avail; + comp_remaining -= read_buf_avail; + } + } + } + else + { + tinfl_decompressor inflator; + tinfl_init(&inflator); + + if (NULL == (pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, TINFL_LZ_DICT_SIZE))) + { + mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + status = TINFL_STATUS_FAILED; + } + else + { + do + { + mz_uint8 *pWrite_buf_cur = (mz_uint8 *)pWrite_buf + (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); + size_t in_buf_size, out_buf_size = TINFL_LZ_DICT_SIZE - (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); + if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) + { + read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) + { + mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + status = TINFL_STATUS_FAILED; + break; + } + cur_file_ofs += read_buf_avail; + comp_remaining -= read_buf_avail; + read_buf_ofs = 0; + } + + in_buf_size = (size_t)read_buf_avail; + status = tinfl_decompress(&inflator, (const mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pWrite_buf, pWrite_buf_cur, &out_buf_size, comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0); + read_buf_avail -= in_buf_size; + read_buf_ofs += in_buf_size; + + if (out_buf_size) + { + if (pCallback(pOpaque, out_buf_ofs, pWrite_buf_cur, out_buf_size) != out_buf_size) + { + mz_zip_set_error(pZip, MZ_ZIP_WRITE_CALLBACK_FAILED); + status = TINFL_STATUS_FAILED; + break; + } + +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + file_crc32 = (mz_uint32)mz_crc32(file_crc32, pWrite_buf_cur, out_buf_size); +#endif + if ((out_buf_ofs += out_buf_size) > file_stat.m_uncomp_size) + { + mz_zip_set_error(pZip, MZ_ZIP_DECOMPRESSION_FAILED); + status = TINFL_STATUS_FAILED; + break; + } + } + } while ((status == TINFL_STATUS_NEEDS_MORE_INPUT) || (status == TINFL_STATUS_HAS_MORE_OUTPUT)); + } + } + + if ((status == TINFL_STATUS_DONE) && (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) + { + /* Make sure the entire file was decompressed, and check its CRC. */ + if (out_buf_ofs != file_stat.m_uncomp_size) + { + mz_zip_set_error(pZip, MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE); + status = TINFL_STATUS_FAILED; + } +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + else if (file_crc32 != file_stat.m_crc32) + { + mz_zip_set_error(pZip, MZ_ZIP_DECOMPRESSION_FAILED); + status = TINFL_STATUS_FAILED; + } +#endif + } + + if (!pZip->m_pState->m_pMem) + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + + if (pWrite_buf) + pZip->m_pFree(pZip->m_pAlloc_opaque, pWrite_buf); + + return status == TINFL_STATUS_DONE; +} + +mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags) +{ + mz_uint32 file_index; + if (!mz_zip_reader_locate_file_v2(pZip, pFilename, NULL, flags, &file_index)) + return MZ_FALSE; + + return mz_zip_reader_extract_to_callback(pZip, file_index, pCallback, pOpaque, flags); +} + +mz_zip_reader_extract_iter_state* mz_zip_reader_extract_iter_new(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags) +{ + mz_zip_reader_extract_iter_state *pState; + mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; + mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; + + /* Argument sanity check */ + if ((!pZip) || (!pZip->m_pState)) + return NULL; + + /* Allocate an iterator status structure */ + pState = (mz_zip_reader_extract_iter_state*)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_reader_extract_iter_state)); + if (!pState) + { + mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + return NULL; + } + + /* Fetch file details */ + if (!mz_zip_reader_file_stat(pZip, file_index, &pState->file_stat)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + return NULL; + } + + /* Encryption and patch files are not supported. */ + if (pState->file_stat.m_bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG)) + { + mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + return NULL; + } + + /* This function only supports decompressing stored and deflate. */ + if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (pState->file_stat.m_method != 0) && (pState->file_stat.m_method != MZ_DEFLATED)) + { + mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + return NULL; + } + + /* Init state - save args */ + pState->pZip = pZip; + pState->flags = flags; + + /* Init state - reset variables to defaults */ + pState->status = TINFL_STATUS_DONE; +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + pState->file_crc32 = MZ_CRC32_INIT; +#endif + pState->read_buf_ofs = 0; + pState->out_buf_ofs = 0; + pState->pRead_buf = NULL; + pState->pWrite_buf = NULL; + pState->out_blk_remain = 0; + + /* Read and parse the local directory entry. */ + pState->cur_file_ofs = pState->file_stat.m_local_header_ofs; + if (pZip->m_pRead(pZip->m_pIO_opaque, pState->cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + { + mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + return NULL; + } + + if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) + { + mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + return NULL; + } + + pState->cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); + if ((pState->cur_file_ofs + pState->file_stat.m_comp_size) > pZip->m_archive_size) + { + mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + return NULL; + } + + /* Decompress the file either directly from memory or from a file input buffer. */ + if (pZip->m_pState->m_pMem) + { + pState->pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + pState->cur_file_ofs; + pState->read_buf_size = pState->read_buf_avail = pState->file_stat.m_comp_size; + pState->comp_remaining = pState->file_stat.m_comp_size; + } + else + { + if (!((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!pState->file_stat.m_method))) + { + /* Decompression required, therefore intermediate read buffer required */ + pState->read_buf_size = MZ_MIN(pState->file_stat.m_comp_size, MZ_ZIP_MAX_IO_BUF_SIZE); + if (NULL == (pState->pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)pState->read_buf_size))) + { + mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + return NULL; + } + } + else + { + /* Decompression not required - we will be reading directly into user buffer, no temp buf required */ + pState->read_buf_size = 0; + } + pState->read_buf_avail = 0; + pState->comp_remaining = pState->file_stat.m_comp_size; + } + + if (!((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!pState->file_stat.m_method))) + { + /* Decompression required, init decompressor */ + tinfl_init( &pState->inflator ); + + /* Allocate write buffer */ + if (NULL == (pState->pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, TINFL_LZ_DICT_SIZE))) + { + mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + if (pState->pRead_buf) + pZip->m_pFree(pZip->m_pAlloc_opaque, pState->pRead_buf); + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + return NULL; + } + } + + return pState; +} + +mz_zip_reader_extract_iter_state* mz_zip_reader_extract_file_iter_new(mz_zip_archive *pZip, const char *pFilename, mz_uint flags) +{ + mz_uint32 file_index; + + /* Locate file index by name */ + if (!mz_zip_reader_locate_file_v2(pZip, pFilename, NULL, flags, &file_index)) + return NULL; + + /* Construct iterator */ + return mz_zip_reader_extract_iter_new(pZip, file_index, flags); +} + +size_t mz_zip_reader_extract_iter_read(mz_zip_reader_extract_iter_state* pState, void* pvBuf, size_t buf_size) +{ + size_t copied_to_caller = 0; + + /* Argument sanity check */ + if ((!pState) || (!pState->pZip) || (!pState->pZip->m_pState) || (!pvBuf)) + return 0; + + if ((pState->flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!pState->file_stat.m_method)) + { + /* The file is stored or the caller has requested the compressed data, calc amount to return. */ + copied_to_caller = (size_t)MZ_MIN( buf_size, pState->comp_remaining ); + + /* Zip is in memory....or requires reading from a file? */ + if (pState->pZip->m_pState->m_pMem) + { + /* Copy data to caller's buffer */ + memcpy( pvBuf, pState->pRead_buf, copied_to_caller ); + pState->pRead_buf = ((mz_uint8*)pState->pRead_buf) + copied_to_caller; + } + else + { + /* Read directly into caller's buffer */ + if (pState->pZip->m_pRead(pState->pZip->m_pIO_opaque, pState->cur_file_ofs, pvBuf, copied_to_caller) != copied_to_caller) + { + /* Failed to read all that was asked for, flag failure and alert user */ + mz_zip_set_error(pState->pZip, MZ_ZIP_FILE_READ_FAILED); + pState->status = TINFL_STATUS_FAILED; + copied_to_caller = 0; + } + } + +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + /* Compute CRC if not returning compressed data only */ + if (!(pState->flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) + pState->file_crc32 = (mz_uint32)mz_crc32(pState->file_crc32, (const mz_uint8 *)pvBuf, copied_to_caller); +#endif + + /* Advance offsets, dec counters */ + pState->cur_file_ofs += copied_to_caller; + pState->out_buf_ofs += copied_to_caller; + pState->comp_remaining -= copied_to_caller; + } + else + { + do + { + /* Calc ptr to write buffer - given current output pos and block size */ + mz_uint8 *pWrite_buf_cur = (mz_uint8 *)pState->pWrite_buf + (pState->out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); + + /* Calc max output size - given current output pos and block size */ + size_t in_buf_size, out_buf_size = TINFL_LZ_DICT_SIZE - (pState->out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); + + if (!pState->out_blk_remain) + { + /* Read more data from file if none available (and reading from file) */ + if ((!pState->read_buf_avail) && (!pState->pZip->m_pState->m_pMem)) + { + /* Calc read size */ + pState->read_buf_avail = MZ_MIN(pState->read_buf_size, pState->comp_remaining); + if (pState->pZip->m_pRead(pState->pZip->m_pIO_opaque, pState->cur_file_ofs, pState->pRead_buf, (size_t)pState->read_buf_avail) != pState->read_buf_avail) + { + mz_zip_set_error(pState->pZip, MZ_ZIP_FILE_READ_FAILED); + pState->status = TINFL_STATUS_FAILED; + break; + } + + /* Advance offsets, dec counters */ + pState->cur_file_ofs += pState->read_buf_avail; + pState->comp_remaining -= pState->read_buf_avail; + pState->read_buf_ofs = 0; + } + + /* Perform decompression */ + in_buf_size = (size_t)pState->read_buf_avail; + pState->status = tinfl_decompress(&pState->inflator, (const mz_uint8 *)pState->pRead_buf + pState->read_buf_ofs, &in_buf_size, (mz_uint8 *)pState->pWrite_buf, pWrite_buf_cur, &out_buf_size, pState->comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0); + pState->read_buf_avail -= in_buf_size; + pState->read_buf_ofs += in_buf_size; + + /* Update current output block size remaining */ + pState->out_blk_remain = out_buf_size; + } + + if (pState->out_blk_remain) + { + /* Calc amount to return. */ + size_t to_copy = MZ_MIN( (buf_size - copied_to_caller), pState->out_blk_remain ); + + /* Copy data to caller's buffer */ + memcpy( (uint8_t*)pvBuf + copied_to_caller, pWrite_buf_cur, to_copy ); + +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + /* Perform CRC */ + pState->file_crc32 = (mz_uint32)mz_crc32(pState->file_crc32, pWrite_buf_cur, to_copy); +#endif + + /* Decrement data consumed from block */ + pState->out_blk_remain -= to_copy; + + /* Inc output offset, while performing sanity check */ + if ((pState->out_buf_ofs += to_copy) > pState->file_stat.m_uncomp_size) + { + mz_zip_set_error(pState->pZip, MZ_ZIP_DECOMPRESSION_FAILED); + pState->status = TINFL_STATUS_FAILED; + break; + } + + /* Increment counter of data copied to caller */ + copied_to_caller += to_copy; + } + } while ( (copied_to_caller < buf_size) && ((pState->status == TINFL_STATUS_NEEDS_MORE_INPUT) || (pState->status == TINFL_STATUS_HAS_MORE_OUTPUT)) ); + } + + /* Return how many bytes were copied into user buffer */ + return copied_to_caller; +} + +mz_bool mz_zip_reader_extract_iter_free(mz_zip_reader_extract_iter_state* pState) +{ + int status; + + /* Argument sanity check */ + if ((!pState) || (!pState->pZip) || (!pState->pZip->m_pState)) + return MZ_FALSE; + + /* Was decompression completed and requested? */ + if ((pState->status == TINFL_STATUS_DONE) && (!(pState->flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) + { + /* Make sure the entire file was decompressed, and check its CRC. */ + if (pState->out_buf_ofs != pState->file_stat.m_uncomp_size) + { + mz_zip_set_error(pState->pZip, MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE); + pState->status = TINFL_STATUS_FAILED; + } +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + else if (pState->file_crc32 != pState->file_stat.m_crc32) + { + mz_zip_set_error(pState->pZip, MZ_ZIP_DECOMPRESSION_FAILED); + pState->status = TINFL_STATUS_FAILED; + } +#endif + } + + /* Free buffers */ + if (!pState->pZip->m_pState->m_pMem) + pState->pZip->m_pFree(pState->pZip->m_pAlloc_opaque, pState->pRead_buf); + if (pState->pWrite_buf) + pState->pZip->m_pFree(pState->pZip->m_pAlloc_opaque, pState->pWrite_buf); + + /* Save status */ + status = pState->status; + + /* Free context */ + pState->pZip->m_pFree(pState->pZip->m_pAlloc_opaque, pState); + + return status == TINFL_STATUS_DONE; +} + +#ifndef MINIZ_NO_STDIO +static size_t mz_zip_file_write_callback(void *pOpaque, mz_uint64 ofs, const void *pBuf, size_t n) +{ + (void)ofs; + + return MZ_FWRITE(pBuf, 1, n, (MZ_FILE *)pOpaque); +} + +mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags) +{ + mz_bool status; + mz_zip_archive_file_stat file_stat; + MZ_FILE *pFile; + + if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) + return MZ_FALSE; + + if ((file_stat.m_is_directory) || (!file_stat.m_is_supported)) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_FEATURE); + + pFile = MZ_FOPEN(pDst_filename, "wb"); + if (!pFile) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); + + status = mz_zip_reader_extract_to_callback(pZip, file_index, mz_zip_file_write_callback, pFile, flags); + + if (MZ_FCLOSE(pFile) == EOF) + { + if (status) + mz_zip_set_error(pZip, MZ_ZIP_FILE_CLOSE_FAILED); + + status = MZ_FALSE; + } + +#if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_STDIO) + if (status) + mz_zip_set_file_times(pDst_filename, file_stat.m_time, file_stat.m_time); +#endif + + return status; +} + +mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags) +{ + mz_uint32 file_index; + if (!mz_zip_reader_locate_file_v2(pZip, pArchive_filename, NULL, flags, &file_index)) + return MZ_FALSE; + + return mz_zip_reader_extract_to_file(pZip, file_index, pDst_filename, flags); +} + +mz_bool mz_zip_reader_extract_to_cfile(mz_zip_archive *pZip, mz_uint file_index, MZ_FILE *pFile, mz_uint flags) +{ + mz_zip_archive_file_stat file_stat; + + if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) + return MZ_FALSE; + + if ((file_stat.m_is_directory) || (!file_stat.m_is_supported)) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_FEATURE); + + return mz_zip_reader_extract_to_callback(pZip, file_index, mz_zip_file_write_callback, pFile, flags); +} + +mz_bool mz_zip_reader_extract_file_to_cfile(mz_zip_archive *pZip, const char *pArchive_filename, MZ_FILE *pFile, mz_uint flags) +{ + mz_uint32 file_index; + if (!mz_zip_reader_locate_file_v2(pZip, pArchive_filename, NULL, flags, &file_index)) + return MZ_FALSE; + + return mz_zip_reader_extract_to_cfile(pZip, file_index, pFile, flags); +} +#endif /* #ifndef MINIZ_NO_STDIO */ + +static size_t mz_zip_compute_crc32_callback(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) +{ + mz_uint32 *p = (mz_uint32 *)pOpaque; + (void)file_ofs; + *p = (mz_uint32)mz_crc32(*p, (const mz_uint8 *)pBuf, n); + return n; +} + +mz_bool mz_zip_validate_file(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags) +{ + mz_zip_archive_file_stat file_stat; + mz_zip_internal_state *pState; + const mz_uint8 *pCentral_dir_header; + mz_bool found_zip64_ext_data_in_cdir = MZ_FALSE; + mz_bool found_zip64_ext_data_in_ldir = MZ_FALSE; + mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; + mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; + mz_uint64 local_header_ofs = 0; + mz_uint32 local_header_filename_len, local_header_extra_len, local_header_crc32; + mz_uint64 local_header_comp_size, local_header_uncomp_size; + mz_uint32 uncomp_crc32 = MZ_CRC32_INIT; + mz_bool has_data_descriptor; + mz_uint32 local_header_bit_flags; + + mz_zip_array file_data_array; + mz_zip_array_init(&file_data_array, 1); + + if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (!pZip->m_pRead)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (file_index > pZip->m_total_files) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pState = pZip->m_pState; + + pCentral_dir_header = mz_zip_get_cdh(pZip, file_index); + + if (!mz_zip_file_stat_internal(pZip, file_index, pCentral_dir_header, &file_stat, &found_zip64_ext_data_in_cdir)) + return MZ_FALSE; + + /* A directory or zero length file */ + if ((file_stat.m_is_directory) || (!file_stat.m_uncomp_size)) + return MZ_TRUE; + + /* Encryption and patch files are not supported. */ + if (file_stat.m_is_encrypted) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); + + /* This function only supports stored and deflate. */ + if ((file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); + + if (!file_stat.m_is_supported) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_FEATURE); + + /* Read and parse the local directory entry. */ + local_header_ofs = file_stat.m_local_header_ofs; + if (pZip->m_pRead(pZip->m_pIO_opaque, local_header_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + + if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + local_header_filename_len = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS); + local_header_extra_len = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); + local_header_comp_size = MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS); + local_header_uncomp_size = MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS); + local_header_crc32 = MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_CRC32_OFS); + local_header_bit_flags = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS); + has_data_descriptor = (local_header_bit_flags & 8) != 0; + + if (local_header_filename_len != strlen(file_stat.m_filename)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if ((local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + local_header_filename_len + local_header_extra_len + file_stat.m_comp_size) > pZip->m_archive_size) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if (!mz_zip_array_resize(pZip, &file_data_array, MZ_MAX(local_header_filename_len, local_header_extra_len), MZ_FALSE)) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + if (local_header_filename_len) + { + if (pZip->m_pRead(pZip->m_pIO_opaque, local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE, file_data_array.m_p, local_header_filename_len) != local_header_filename_len) + { + mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + goto handle_failure; + } + + /* I've seen 1 archive that had the same pathname, but used backslashes in the local dir and forward slashes in the central dir. Do we care about this? For now, this case will fail validation. */ + if (memcmp(file_stat.m_filename, file_data_array.m_p, local_header_filename_len) != 0) + { + mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); + goto handle_failure; + } + } + + if ((local_header_extra_len) && ((local_header_comp_size == MZ_UINT32_MAX) || (local_header_uncomp_size == MZ_UINT32_MAX))) + { + mz_uint32 extra_size_remaining = local_header_extra_len; + const mz_uint8 *pExtra_data = (const mz_uint8 *)file_data_array.m_p; + + if (pZip->m_pRead(pZip->m_pIO_opaque, local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + local_header_filename_len, file_data_array.m_p, local_header_extra_len) != local_header_extra_len) + { + mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + goto handle_failure; + } + + do + { + mz_uint32 field_id, field_data_size, field_total_size; + + if (extra_size_remaining < (sizeof(mz_uint16) * 2)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + field_id = MZ_READ_LE16(pExtra_data); + field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); + field_total_size = field_data_size + sizeof(mz_uint16) * 2; + + if (field_total_size > extra_size_remaining) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) + { + const mz_uint8 *pSrc_field_data = pExtra_data + sizeof(mz_uint32); + + if (field_data_size < sizeof(mz_uint64) * 2) + { + mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + goto handle_failure; + } + + local_header_uncomp_size = MZ_READ_LE64(pSrc_field_data); + local_header_comp_size = MZ_READ_LE64(pSrc_field_data + sizeof(mz_uint64)); + + found_zip64_ext_data_in_ldir = MZ_TRUE; + break; + } + + pExtra_data += field_total_size; + extra_size_remaining -= field_total_size; + } while (extra_size_remaining); + } + + /* TODO: parse local header extra data when local_header_comp_size is 0xFFFFFFFF! (big_descriptor.zip) */ + /* I've seen zips in the wild with the data descriptor bit set, but proper local header values and bogus data descriptors */ + if ((has_data_descriptor) && (!local_header_comp_size) && (!local_header_crc32)) + { + mz_uint8 descriptor_buf[32]; + mz_bool has_id; + const mz_uint8 *pSrc; + mz_uint32 file_crc32; + mz_uint64 comp_size = 0, uncomp_size = 0; + + mz_uint32 num_descriptor_uint32s = ((pState->m_zip64) || (found_zip64_ext_data_in_ldir)) ? 6 : 4; + + if (pZip->m_pRead(pZip->m_pIO_opaque, local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + local_header_filename_len + local_header_extra_len + file_stat.m_comp_size, descriptor_buf, sizeof(mz_uint32) * num_descriptor_uint32s) != (sizeof(mz_uint32) * num_descriptor_uint32s)) + { + mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + goto handle_failure; + } + + has_id = (MZ_READ_LE32(descriptor_buf) == MZ_ZIP_DATA_DESCRIPTOR_ID); + pSrc = has_id ? (descriptor_buf + sizeof(mz_uint32)) : descriptor_buf; + + file_crc32 = MZ_READ_LE32(pSrc); + + if ((pState->m_zip64) || (found_zip64_ext_data_in_ldir)) + { + comp_size = MZ_READ_LE64(pSrc + sizeof(mz_uint32)); + uncomp_size = MZ_READ_LE64(pSrc + sizeof(mz_uint32) + sizeof(mz_uint64)); + } + else + { + comp_size = MZ_READ_LE32(pSrc + sizeof(mz_uint32)); + uncomp_size = MZ_READ_LE32(pSrc + sizeof(mz_uint32) + sizeof(mz_uint32)); + } + + if ((file_crc32 != file_stat.m_crc32) || (comp_size != file_stat.m_comp_size) || (uncomp_size != file_stat.m_uncomp_size)) + { + mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); + goto handle_failure; + } + } + else + { + if ((local_header_crc32 != file_stat.m_crc32) || (local_header_comp_size != file_stat.m_comp_size) || (local_header_uncomp_size != file_stat.m_uncomp_size)) + { + mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); + goto handle_failure; + } + } + + mz_zip_array_clear(pZip, &file_data_array); + + if ((flags & MZ_ZIP_FLAG_VALIDATE_HEADERS_ONLY) == 0) + { + if (!mz_zip_reader_extract_to_callback(pZip, file_index, mz_zip_compute_crc32_callback, &uncomp_crc32, 0)) + return MZ_FALSE; + + /* 1 more check to be sure, although the extract checks too. */ + if (uncomp_crc32 != file_stat.m_crc32) + { + mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); + return MZ_FALSE; + } + } + + return MZ_TRUE; + +handle_failure: + mz_zip_array_clear(pZip, &file_data_array); + return MZ_FALSE; +} + +mz_bool mz_zip_validate_archive(mz_zip_archive *pZip, mz_uint flags) +{ + mz_zip_internal_state *pState; + uint32_t i; + + if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (!pZip->m_pRead)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pState = pZip->m_pState; + + /* Basic sanity checks */ + if (!pState->m_zip64) + { + if (pZip->m_total_files > MZ_UINT16_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + + if (pZip->m_archive_size > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + } + else + { + if (pZip->m_total_files >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + + if (pState->m_central_dir.m_size >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + } + + for (i = 0; i < pZip->m_total_files; i++) + { + if (MZ_ZIP_FLAG_VALIDATE_LOCATE_FILE_FLAG & flags) + { + mz_uint32 found_index; + mz_zip_archive_file_stat stat; + + if (!mz_zip_reader_file_stat(pZip, i, &stat)) + return MZ_FALSE; + + if (!mz_zip_reader_locate_file_v2(pZip, stat.m_filename, NULL, 0, &found_index)) + return MZ_FALSE; + + /* This check can fail if there are duplicate filenames in the archive (which we don't check for when writing - that's up to the user) */ + if (found_index != i) + return mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); + } + + if (!mz_zip_validate_file(pZip, i, flags)) + return MZ_FALSE; + } + + return MZ_TRUE; +} + +mz_bool mz_zip_validate_mem_archive(const void *pMem, size_t size, mz_uint flags, mz_zip_error *pErr) +{ + mz_bool success = MZ_TRUE; + mz_zip_archive zip; + mz_zip_error actual_err = MZ_ZIP_NO_ERROR; + + if ((!pMem) || (!size)) + { + if (pErr) + *pErr = MZ_ZIP_INVALID_PARAMETER; + return MZ_FALSE; + } + + mz_zip_zero_struct(&zip); + + if (!mz_zip_reader_init_mem(&zip, pMem, size, flags)) + { + if (pErr) + *pErr = zip.m_last_error; + return MZ_FALSE; + } + + if (!mz_zip_validate_archive(&zip, flags)) + { + actual_err = zip.m_last_error; + success = MZ_FALSE; + } + + if (!mz_zip_reader_end_internal(&zip, success)) + { + if (!actual_err) + actual_err = zip.m_last_error; + success = MZ_FALSE; + } + + if (pErr) + *pErr = actual_err; + + return success; +} + +#ifndef MINIZ_NO_STDIO +mz_bool mz_zip_validate_file_archive(const char *pFilename, mz_uint flags, mz_zip_error *pErr) +{ + mz_bool success = MZ_TRUE; + mz_zip_archive zip; + mz_zip_error actual_err = MZ_ZIP_NO_ERROR; + + if (!pFilename) + { + if (pErr) + *pErr = MZ_ZIP_INVALID_PARAMETER; + return MZ_FALSE; + } + + mz_zip_zero_struct(&zip); + + if (!mz_zip_reader_init_file_v2(&zip, pFilename, flags, 0, 0)) + { + if (pErr) + *pErr = zip.m_last_error; + return MZ_FALSE; + } + + if (!mz_zip_validate_archive(&zip, flags)) + { + actual_err = zip.m_last_error; + success = MZ_FALSE; + } + + if (!mz_zip_reader_end_internal(&zip, success)) + { + if (!actual_err) + actual_err = zip.m_last_error; + success = MZ_FALSE; + } + + if (pErr) + *pErr = actual_err; + + return success; +} +#endif /* #ifndef MINIZ_NO_STDIO */ + +/* ------------------- .ZIP archive writing */ + +#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS + +static MZ_FORCEINLINE void mz_write_le16(mz_uint8 *p, mz_uint16 v) +{ + p[0] = (mz_uint8)v; + p[1] = (mz_uint8)(v >> 8); +} +static MZ_FORCEINLINE void mz_write_le32(mz_uint8 *p, mz_uint32 v) +{ + p[0] = (mz_uint8)v; + p[1] = (mz_uint8)(v >> 8); + p[2] = (mz_uint8)(v >> 16); + p[3] = (mz_uint8)(v >> 24); +} +static MZ_FORCEINLINE void mz_write_le64(mz_uint8 *p, mz_uint64 v) +{ + mz_write_le32(p, (mz_uint32)v); + mz_write_le32(p + sizeof(mz_uint32), (mz_uint32)(v >> 32)); +} + +#define MZ_WRITE_LE16(p, v) mz_write_le16((mz_uint8 *)(p), (mz_uint16)(v)) +#define MZ_WRITE_LE32(p, v) mz_write_le32((mz_uint8 *)(p), (mz_uint32)(v)) +#define MZ_WRITE_LE64(p, v) mz_write_le64((mz_uint8 *)(p), (mz_uint64)(v)) + +static size_t mz_zip_heap_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) +{ + mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; + mz_zip_internal_state *pState = pZip->m_pState; + mz_uint64 new_size = MZ_MAX(file_ofs + n, pState->m_mem_size); + + if (!n) + return 0; + + /* An allocation this big is likely to just fail on 32-bit systems, so don't even go there. */ + if ((sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF)) + { + mz_zip_set_error(pZip, MZ_ZIP_FILE_TOO_LARGE); + return 0; + } + + if (new_size > pState->m_mem_capacity) + { + void *pNew_block; + size_t new_capacity = MZ_MAX(64, pState->m_mem_capacity); + + while (new_capacity < new_size) + new_capacity *= 2; + + if (NULL == (pNew_block = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pState->m_pMem, 1, new_capacity))) + { + mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + return 0; + } + + pState->m_pMem = pNew_block; + pState->m_mem_capacity = new_capacity; + } + memcpy((mz_uint8 *)pState->m_pMem + file_ofs, pBuf, n); + pState->m_mem_size = (size_t)new_size; + return n; +} + +static mz_bool mz_zip_writer_end_internal(mz_zip_archive *pZip, mz_bool set_last_error) +{ + mz_zip_internal_state *pState; + mz_bool status = MZ_TRUE; + + if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || ((pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) && (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED))) + { + if (set_last_error) + mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + return MZ_FALSE; + } + + pState = pZip->m_pState; + pZip->m_pState = NULL; + mz_zip_array_clear(pZip, &pState->m_central_dir); + mz_zip_array_clear(pZip, &pState->m_central_dir_offsets); + mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); + +#ifndef MINIZ_NO_STDIO + if (pState->m_pFile) + { + if (pZip->m_zip_type == MZ_ZIP_TYPE_FILE) + { + if (MZ_FCLOSE(pState->m_pFile) == EOF) + { + if (set_last_error) + mz_zip_set_error(pZip, MZ_ZIP_FILE_CLOSE_FAILED); + status = MZ_FALSE; + } + } + + pState->m_pFile = NULL; + } +#endif /* #ifndef MINIZ_NO_STDIO */ + + if ((pZip->m_pWrite == mz_zip_heap_write_func) && (pState->m_pMem)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pState->m_pMem); + pState->m_pMem = NULL; + } + + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; + return status; +} + +mz_bool mz_zip_writer_init_v2(mz_zip_archive *pZip, mz_uint64 existing_size, mz_uint flags) +{ + mz_bool zip64 = (flags & MZ_ZIP_FLAG_WRITE_ZIP64) != 0; + + if ((!pZip) || (pZip->m_pState) || (!pZip->m_pWrite) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) + { + if (!pZip->m_pRead) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + } + + if (pZip->m_file_offset_alignment) + { + /* Ensure user specified file offset alignment is a power of 2. */ + if (pZip->m_file_offset_alignment & (pZip->m_file_offset_alignment - 1)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + } + + if (!pZip->m_pAlloc) + pZip->m_pAlloc = miniz_def_alloc_func; + if (!pZip->m_pFree) + pZip->m_pFree = miniz_def_free_func; + if (!pZip->m_pRealloc) + pZip->m_pRealloc = miniz_def_realloc_func; + + pZip->m_archive_size = existing_size; + pZip->m_central_directory_file_ofs = 0; + pZip->m_total_files = 0; + + if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); + + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32)); + + pZip->m_pState->m_zip64 = zip64; + pZip->m_pState->m_zip64_has_extended_info_fields = zip64; + + pZip->m_zip_type = MZ_ZIP_TYPE_USER; + pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; + + return MZ_TRUE; +} + +mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size) +{ + return mz_zip_writer_init_v2(pZip, existing_size, 0); +} + +mz_bool mz_zip_writer_init_heap_v2(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size, mz_uint flags) +{ + pZip->m_pWrite = mz_zip_heap_write_func; + pZip->m_pNeeds_keepalive = NULL; + + if (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) + pZip->m_pRead = mz_zip_mem_read_func; + + pZip->m_pIO_opaque = pZip; + + if (!mz_zip_writer_init_v2(pZip, size_to_reserve_at_beginning, flags)) + return MZ_FALSE; + + pZip->m_zip_type = MZ_ZIP_TYPE_HEAP; + + if (0 != (initial_allocation_size = MZ_MAX(initial_allocation_size, size_to_reserve_at_beginning))) + { + if (NULL == (pZip->m_pState->m_pMem = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, initial_allocation_size))) + { + mz_zip_writer_end_internal(pZip, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + pZip->m_pState->m_mem_capacity = initial_allocation_size; + } + + return MZ_TRUE; +} + +mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size) +{ + return mz_zip_writer_init_heap_v2(pZip, size_to_reserve_at_beginning, initial_allocation_size, 0); +} + +#ifndef MINIZ_NO_STDIO +static size_t mz_zip_file_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) +{ + mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; + mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); + + file_ofs += pZip->m_pState->m_file_archive_start_ofs; + + if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) + { + mz_zip_set_error(pZip, MZ_ZIP_FILE_SEEK_FAILED); + return 0; + } + + return MZ_FWRITE(pBuf, 1, n, pZip->m_pState->m_pFile); +} + +mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning) +{ + return mz_zip_writer_init_file_v2(pZip, pFilename, size_to_reserve_at_beginning, 0); +} + +mz_bool mz_zip_writer_init_file_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning, mz_uint flags) +{ + MZ_FILE *pFile; + + pZip->m_pWrite = mz_zip_file_write_func; + pZip->m_pNeeds_keepalive = NULL; + + if (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) + pZip->m_pRead = mz_zip_file_read_func; + + pZip->m_pIO_opaque = pZip; + + if (!mz_zip_writer_init_v2(pZip, size_to_reserve_at_beginning, flags)) + return MZ_FALSE; + + if (NULL == (pFile = MZ_FOPEN(pFilename, (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) ? "w+b" : "wb"))) + { + mz_zip_writer_end(pZip); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); + } + + pZip->m_pState->m_pFile = pFile; + pZip->m_zip_type = MZ_ZIP_TYPE_FILE; + + if (size_to_reserve_at_beginning) + { + mz_uint64 cur_ofs = 0; + char buf[4096]; + + MZ_CLEAR_OBJ(buf); + + do + { + size_t n = (size_t)MZ_MIN(sizeof(buf), size_to_reserve_at_beginning); + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_ofs, buf, n) != n) + { + mz_zip_writer_end(pZip); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + cur_ofs += n; + size_to_reserve_at_beginning -= n; + } while (size_to_reserve_at_beginning); + } + + return MZ_TRUE; +} + +mz_bool mz_zip_writer_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile, mz_uint flags) +{ + pZip->m_pWrite = mz_zip_file_write_func; + pZip->m_pNeeds_keepalive = NULL; + + if (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) + pZip->m_pRead = mz_zip_file_read_func; + + pZip->m_pIO_opaque = pZip; + + if (!mz_zip_writer_init_v2(pZip, 0, flags)) + return MZ_FALSE; + + pZip->m_pState->m_pFile = pFile; + pZip->m_pState->m_file_archive_start_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); + pZip->m_zip_type = MZ_ZIP_TYPE_CFILE; + + return MZ_TRUE; +} +#endif /* #ifndef MINIZ_NO_STDIO */ + +mz_bool mz_zip_writer_init_from_reader_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint flags) +{ + mz_zip_internal_state *pState; + + if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (flags & MZ_ZIP_FLAG_WRITE_ZIP64) + { + /* We don't support converting a non-zip64 file to zip64 - this seems like more trouble than it's worth. (What about the existing 32-bit data descriptors that could follow the compressed data?) */ + if (!pZip->m_pState->m_zip64) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + } + + /* No sense in trying to write to an archive that's already at the support max size */ + if (pZip->m_pState->m_zip64) + { + if (pZip->m_total_files == MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + } + else + { + if (pZip->m_total_files == MZ_UINT16_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + + if ((pZip->m_archive_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_TOO_LARGE); + } + + pState = pZip->m_pState; + + if (pState->m_pFile) + { +#ifdef MINIZ_NO_STDIO + (void)pFilename; + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); +#else + if (pZip->m_pIO_opaque != pZip) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (pZip->m_zip_type == MZ_ZIP_TYPE_FILE) + { + if (!pFilename) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + /* Archive is being read from stdio and was originally opened only for reading. Try to reopen as writable. */ + if (NULL == (pState->m_pFile = MZ_FREOPEN(pFilename, "r+b", pState->m_pFile))) + { + /* The mz_zip_archive is now in a bogus state because pState->m_pFile is NULL, so just close it. */ + mz_zip_reader_end_internal(pZip, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); + } + } + + pZip->m_pWrite = mz_zip_file_write_func; + pZip->m_pNeeds_keepalive = NULL; +#endif /* #ifdef MINIZ_NO_STDIO */ + } + else if (pState->m_pMem) + { + /* Archive lives in a memory block. Assume it's from the heap that we can resize using the realloc callback. */ + if (pZip->m_pIO_opaque != pZip) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pState->m_mem_capacity = pState->m_mem_size; + pZip->m_pWrite = mz_zip_heap_write_func; + pZip->m_pNeeds_keepalive = NULL; + } + /* Archive is being read via a user provided read function - make sure the user has specified a write function too. */ + else if (!pZip->m_pWrite) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + /* Start writing new files at the archive's current central directory location. */ + /* TODO: We could add a flag that lets the user start writing immediately AFTER the existing central dir - this would be safer. */ + pZip->m_archive_size = pZip->m_central_directory_file_ofs; + pZip->m_central_directory_file_ofs = 0; + + /* Clear the sorted central dir offsets, they aren't useful or maintained now. */ + /* Even though we're now in write mode, files can still be extracted and verified, but file locates will be slow. */ + /* TODO: We could easily maintain the sorted central directory offsets. */ + mz_zip_array_clear(pZip, &pZip->m_pState->m_sorted_central_dir_offsets); + + pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; + + return MZ_TRUE; +} + +mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename) +{ + return mz_zip_writer_init_from_reader_v2(pZip, pFilename, 0); +} + +/* TODO: pArchive_name is a terrible name here! */ +mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags) +{ + return mz_zip_writer_add_mem_ex(pZip, pArchive_name, pBuf, buf_size, NULL, 0, level_and_flags, 0, 0); +} + +typedef struct +{ + mz_zip_archive *m_pZip; + mz_uint64 m_cur_archive_file_ofs; + mz_uint64 m_comp_size; +} mz_zip_writer_add_state; + +static mz_bool mz_zip_writer_add_put_buf_callback(const void *pBuf, int len, void *pUser) +{ + mz_zip_writer_add_state *pState = (mz_zip_writer_add_state *)pUser; + if ((int)pState->m_pZip->m_pWrite(pState->m_pZip->m_pIO_opaque, pState->m_cur_archive_file_ofs, pBuf, len) != len) + return MZ_FALSE; + + pState->m_cur_archive_file_ofs += len; + pState->m_comp_size += len; + return MZ_TRUE; +} + +#define MZ_ZIP64_MAX_LOCAL_EXTRA_FIELD_SIZE (sizeof(mz_uint16) * 2 + sizeof(mz_uint64) * 2) +#define MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE (sizeof(mz_uint16) * 2 + sizeof(mz_uint64) * 3) +static mz_uint32 mz_zip_writer_create_zip64_extra_data(mz_uint8 *pBuf, mz_uint64 *pUncomp_size, mz_uint64 *pComp_size, mz_uint64 *pLocal_header_ofs) +{ + mz_uint8 *pDst = pBuf; + mz_uint32 field_size = 0; + + MZ_WRITE_LE16(pDst + 0, MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID); + MZ_WRITE_LE16(pDst + 2, 0); + pDst += sizeof(mz_uint16) * 2; + + if (pUncomp_size) + { + MZ_WRITE_LE64(pDst, *pUncomp_size); + pDst += sizeof(mz_uint64); + field_size += sizeof(mz_uint64); + } + + if (pComp_size) + { + MZ_WRITE_LE64(pDst, *pComp_size); + pDst += sizeof(mz_uint64); + field_size += sizeof(mz_uint64); + } + + if (pLocal_header_ofs) + { + MZ_WRITE_LE64(pDst, *pLocal_header_ofs); + pDst += sizeof(mz_uint64); + field_size += sizeof(mz_uint64); + } + + MZ_WRITE_LE16(pBuf + 2, field_size); + + return (mz_uint32)(pDst - pBuf); +} + +static mz_bool mz_zip_writer_create_local_dir_header(mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, mz_uint16 extra_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date) +{ + (void)pZip; + memset(pDst, 0, MZ_ZIP_LOCAL_DIR_HEADER_SIZE); + MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_SIG_OFS, MZ_ZIP_LOCAL_DIR_HEADER_SIG); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_VERSION_NEEDED_OFS, method ? 20 : 0); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_BIT_FLAG_OFS, bit_flags); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_METHOD_OFS, method); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_TIME_OFS, dos_time); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_DATE_OFS, dos_date); + MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_CRC32_OFS, uncomp_crc32); + MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS, MZ_MIN(comp_size, MZ_UINT32_MAX)); + MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS, MZ_MIN(uncomp_size, MZ_UINT32_MAX)); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILENAME_LEN_OFS, filename_size); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_EXTRA_LEN_OFS, extra_size); + return MZ_TRUE; +} + +static mz_bool mz_zip_writer_create_central_dir_header(mz_zip_archive *pZip, mz_uint8 *pDst, + mz_uint16 filename_size, mz_uint16 extra_size, mz_uint16 comment_size, + mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, + mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, + mz_uint64 local_header_ofs, mz_uint32 ext_attributes) +{ + (void)pZip; + memset(pDst, 0, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_SIG_OFS, MZ_ZIP_CENTRAL_DIR_HEADER_SIG); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_VERSION_NEEDED_OFS, method ? 20 : 0); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_BIT_FLAG_OFS, bit_flags); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_METHOD_OFS, method); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_TIME_OFS, dos_time); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_DATE_OFS, dos_date); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_CRC32_OFS, uncomp_crc32); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS, MZ_MIN(comp_size, MZ_UINT32_MAX)); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS, MZ_MIN(uncomp_size, MZ_UINT32_MAX)); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILENAME_LEN_OFS, filename_size); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_EXTRA_LEN_OFS, extra_size); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_COMMENT_LEN_OFS, comment_size); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS, ext_attributes); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_LOCAL_HEADER_OFS, MZ_MIN(local_header_ofs, MZ_UINT32_MAX)); + return MZ_TRUE; +} + +static mz_bool mz_zip_writer_add_to_central_dir(mz_zip_archive *pZip, const char *pFilename, mz_uint16 filename_size, + const void *pExtra, mz_uint16 extra_size, const void *pComment, mz_uint16 comment_size, + mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, + mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, + mz_uint64 local_header_ofs, mz_uint32 ext_attributes, + const char *user_extra_data, mz_uint user_extra_data_len) +{ + mz_zip_internal_state *pState = pZip->m_pState; + mz_uint32 central_dir_ofs = (mz_uint32)pState->m_central_dir.m_size; + size_t orig_central_dir_size = pState->m_central_dir.m_size; + mz_uint8 central_dir_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; + + if (!pZip->m_pState->m_zip64) + { + if (local_header_ofs > 0xFFFFFFFF) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_TOO_LARGE); + } + + /* miniz doesn't support central dirs >= MZ_UINT32_MAX bytes yet */ + if (((mz_uint64)pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + extra_size + user_extra_data_len + comment_size) >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); + + if (!mz_zip_writer_create_central_dir_header(pZip, central_dir_header, filename_size, (mz_uint16)(extra_size + user_extra_data_len), comment_size, uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time, dos_date, local_header_ofs, ext_attributes)) + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + + if ((!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_dir_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pFilename, filename_size)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pExtra, extra_size)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir, user_extra_data, user_extra_data_len)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pComment, comment_size)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, ¢ral_dir_ofs, 1))) + { + /* Try to resize the central directory array back into its original state. */ + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + return MZ_TRUE; +} + +static mz_bool mz_zip_writer_validate_archive_name(const char *pArchive_name) +{ + /* Basic ZIP archive filename validity checks: Valid filenames cannot start with a forward slash, cannot contain a drive letter, and cannot use DOS-style backward slashes. */ + if (*pArchive_name == '/') + return MZ_FALSE; + + /* Making sure the name does not contain drive letters or DOS style backward slashes is the responsibility of the program using miniz*/ + + return MZ_TRUE; +} + +static mz_uint mz_zip_writer_compute_padding_needed_for_file_alignment(mz_zip_archive *pZip) +{ + mz_uint32 n; + if (!pZip->m_file_offset_alignment) + return 0; + n = (mz_uint32)(pZip->m_archive_size & (pZip->m_file_offset_alignment - 1)); + return (mz_uint)((pZip->m_file_offset_alignment - n) & (pZip->m_file_offset_alignment - 1)); +} + +static mz_bool mz_zip_writer_write_zeros(mz_zip_archive *pZip, mz_uint64 cur_file_ofs, mz_uint32 n) +{ + char buf[4096]; + memset(buf, 0, MZ_MIN(sizeof(buf), n)); + while (n) + { + mz_uint32 s = MZ_MIN(sizeof(buf), n); + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_file_ofs, buf, s) != s) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_file_ofs += s; + n -= s; + } + return MZ_TRUE; +} + +mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, + mz_uint64 uncomp_size, mz_uint32 uncomp_crc32) +{ + return mz_zip_writer_add_mem_ex_v2(pZip, pArchive_name, pBuf, buf_size, pComment, comment_size, level_and_flags, uncomp_size, uncomp_crc32, NULL, NULL, 0, NULL, 0); +} + +mz_bool mz_zip_writer_add_mem_ex_v2(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, + mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32, MZ_TIME_T *last_modified, + const char *user_extra_data, mz_uint user_extra_data_len, const char *user_extra_data_central, mz_uint user_extra_data_central_len) +{ + mz_uint16 method = 0, dos_time = 0, dos_date = 0; + mz_uint level, ext_attributes = 0, num_alignment_padding_bytes; + mz_uint64 local_dir_header_ofs = pZip->m_archive_size, cur_archive_file_ofs = pZip->m_archive_size, comp_size = 0; + size_t archive_name_size; + mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; + tdefl_compressor *pComp = NULL; + mz_bool store_data_uncompressed; + mz_zip_internal_state *pState; + mz_uint8 *pExtra_data = NULL; + mz_uint32 extra_size = 0; + mz_uint8 extra_data[MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE]; + mz_uint16 bit_flags = 0; + + if ((int)level_and_flags < 0) + level_and_flags = MZ_DEFAULT_LEVEL; + + if (uncomp_size || (buf_size && !(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) + bit_flags |= MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR; + + if (!(level_and_flags & MZ_ZIP_FLAG_ASCII_FILENAME)) + bit_flags |= MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_UTF8; + + level = level_and_flags & 0xF; + store_data_uncompressed = ((!level) || (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)); + + if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || ((buf_size) && (!pBuf)) || (!pArchive_name) || ((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pState = pZip->m_pState; + + if (pState->m_zip64) + { + if (pZip->m_total_files == MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + } + else + { + if (pZip->m_total_files == MZ_UINT16_MAX) + { + pState->m_zip64 = MZ_TRUE; + /*return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); */ + } + if ((buf_size > 0xFFFFFFFF) || (uncomp_size > 0xFFFFFFFF)) + { + pState->m_zip64 = MZ_TRUE; + /*return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); */ + } + } + + if ((!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (uncomp_size)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (!mz_zip_writer_validate_archive_name(pArchive_name)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_FILENAME); + +#ifndef MINIZ_NO_TIME + if (last_modified != NULL) + { + mz_zip_time_t_to_dos_time(*last_modified, &dos_time, &dos_date); + } + else + { + MZ_TIME_T cur_time; + time(&cur_time); + mz_zip_time_t_to_dos_time(cur_time, &dos_time, &dos_date); + } +#endif /* #ifndef MINIZ_NO_TIME */ + + if (!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) + { + uncomp_crc32 = (mz_uint32)mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, buf_size); + uncomp_size = buf_size; + if (uncomp_size <= 3) + { + level = 0; + store_data_uncompressed = MZ_TRUE; + } + } + + archive_name_size = strlen(pArchive_name); + if (archive_name_size > MZ_UINT16_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_FILENAME); + + num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); + + /* miniz doesn't support central dirs >= MZ_UINT32_MAX bytes yet */ + if (((mz_uint64)pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE + comment_size) >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); + + if (!pState->m_zip64) + { + /* Bail early if the archive would obviously become too large */ + if ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + archive_name_size + + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size + user_extra_data_len + + pState->m_central_dir.m_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE + user_extra_data_central_len + + MZ_ZIP_DATA_DESCRIPTER_SIZE32) > 0xFFFFFFFF) + { + pState->m_zip64 = MZ_TRUE; + /*return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); */ + } + } + + if ((archive_name_size) && (pArchive_name[archive_name_size - 1] == '/')) + { + /* Set DOS Subdirectory attribute bit. */ + ext_attributes |= MZ_ZIP_DOS_DIR_ATTRIBUTE_BITFLAG; + + /* Subdirectories cannot contain data. */ + if ((buf_size) || (uncomp_size)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + } + + /* Try to do any allocations before writing to the archive, so if an allocation fails the file remains unmodified. (A good idea if we're doing an in-place modification.) */ + if ((!mz_zip_array_ensure_room(pZip, &pState->m_central_dir, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size + (pState->m_zip64 ? MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE : 0))) || (!mz_zip_array_ensure_room(pZip, &pState->m_central_dir_offsets, 1))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + if ((!store_data_uncompressed) && (buf_size)) + { + if (NULL == (pComp = (tdefl_compressor *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, num_alignment_padding_bytes)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + return MZ_FALSE; + } + + local_dir_header_ofs += num_alignment_padding_bytes; + if (pZip->m_file_offset_alignment) + { + MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); + } + cur_archive_file_ofs += num_alignment_padding_bytes; + + MZ_CLEAR_OBJ(local_dir_header); + + if (!store_data_uncompressed || (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) + { + method = MZ_DEFLATED; + } + + if (pState->m_zip64) + { + if (uncomp_size >= MZ_UINT32_MAX || local_dir_header_ofs >= MZ_UINT32_MAX) + { + pExtra_data = extra_data; + extra_size = mz_zip_writer_create_zip64_extra_data(extra_data, (uncomp_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL, + (uncomp_size >= MZ_UINT32_MAX) ? &comp_size : NULL, (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL); + } + + if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, (mz_uint16)(extra_size + user_extra_data_len), 0, 0, 0, method, bit_flags, dos_time, dos_date)) + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += sizeof(local_dir_header); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + cur_archive_file_ofs += archive_name_size; + + if (pExtra_data != NULL) + { + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, extra_data, extra_size) != extra_size) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += extra_size; + } + } + else + { + if ((comp_size > MZ_UINT32_MAX) || (cur_archive_file_ofs > MZ_UINT32_MAX)) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, (mz_uint16)user_extra_data_len, 0, 0, 0, method, bit_flags, dos_time, dos_date)) + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += sizeof(local_dir_header); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + cur_archive_file_ofs += archive_name_size; + } + + if (user_extra_data_len > 0) + { + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, user_extra_data, user_extra_data_len) != user_extra_data_len) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += user_extra_data_len; + } + + if (store_data_uncompressed) + { + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pBuf, buf_size) != buf_size) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + + cur_archive_file_ofs += buf_size; + comp_size = buf_size; + } + else if (buf_size) + { + mz_zip_writer_add_state state; + + state.m_pZip = pZip; + state.m_cur_archive_file_ofs = cur_archive_file_ofs; + state.m_comp_size = 0; + + if ((tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params(level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) || + (tdefl_compress_buffer(pComp, pBuf, buf_size, TDEFL_FINISH) != TDEFL_STATUS_DONE)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + return mz_zip_set_error(pZip, MZ_ZIP_COMPRESSION_FAILED); + } + + comp_size = state.m_comp_size; + cur_archive_file_ofs = state.m_cur_archive_file_ofs; + } + + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + pComp = NULL; + + if (uncomp_size) + { + mz_uint8 local_dir_footer[MZ_ZIP_DATA_DESCRIPTER_SIZE64]; + mz_uint32 local_dir_footer_size = MZ_ZIP_DATA_DESCRIPTER_SIZE32; + + MZ_ASSERT(bit_flags & MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR); + + MZ_WRITE_LE32(local_dir_footer + 0, MZ_ZIP_DATA_DESCRIPTOR_ID); + MZ_WRITE_LE32(local_dir_footer + 4, uncomp_crc32); + if (pExtra_data == NULL) + { + if (comp_size > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + + MZ_WRITE_LE32(local_dir_footer + 8, comp_size); + MZ_WRITE_LE32(local_dir_footer + 12, uncomp_size); + } + else + { + MZ_WRITE_LE64(local_dir_footer + 8, comp_size); + MZ_WRITE_LE64(local_dir_footer + 16, uncomp_size); + local_dir_footer_size = MZ_ZIP_DATA_DESCRIPTER_SIZE64; + } + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, local_dir_footer, local_dir_footer_size) != local_dir_footer_size) + return MZ_FALSE; + + cur_archive_file_ofs += local_dir_footer_size; + } + + if (pExtra_data != NULL) + { + extra_size = mz_zip_writer_create_zip64_extra_data(extra_data, (uncomp_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL, + (uncomp_size >= MZ_UINT32_MAX) ? &comp_size : NULL, (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL); + } + + if (!mz_zip_writer_add_to_central_dir(pZip, pArchive_name, (mz_uint16)archive_name_size, pExtra_data, (mz_uint16)extra_size, pComment, + comment_size, uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time, dos_date, local_dir_header_ofs, ext_attributes, + user_extra_data_central, user_extra_data_central_len)) + return MZ_FALSE; + + pZip->m_total_files++; + pZip->m_archive_size = cur_archive_file_ofs; + + return MZ_TRUE; +} + +mz_bool mz_zip_writer_add_read_buf_callback(mz_zip_archive *pZip, const char *pArchive_name, mz_file_read_func read_callback, void* callback_opaque, mz_uint64 size_to_add, const MZ_TIME_T *pFile_time, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, + const char *user_extra_data, mz_uint user_extra_data_len, const char *user_extra_data_central, mz_uint user_extra_data_central_len) +{ + mz_uint16 gen_flags = MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR; + mz_uint uncomp_crc32 = MZ_CRC32_INIT, level, num_alignment_padding_bytes; + mz_uint16 method = 0, dos_time = 0, dos_date = 0, ext_attributes = 0; + mz_uint64 local_dir_header_ofs, cur_archive_file_ofs = pZip->m_archive_size, uncomp_size = size_to_add, comp_size = 0; + size_t archive_name_size; + mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; + mz_uint8 *pExtra_data = NULL; + mz_uint32 extra_size = 0; + mz_uint8 extra_data[MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE]; + mz_zip_internal_state *pState; + mz_uint64 file_ofs = 0; + + if (!(level_and_flags & MZ_ZIP_FLAG_ASCII_FILENAME)) + gen_flags |= MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_UTF8; + + if ((int)level_and_flags < 0) + level_and_flags = MZ_DEFAULT_LEVEL; + level = level_and_flags & 0xF; + + /* Sanity checks */ + if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pArchive_name) || ((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pState = pZip->m_pState; + + if ((!pState->m_zip64) && (uncomp_size > MZ_UINT32_MAX)) + { + /* Source file is too large for non-zip64 */ + /*return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); */ + pState->m_zip64 = MZ_TRUE; + } + + /* We could support this, but why? */ + if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (!mz_zip_writer_validate_archive_name(pArchive_name)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_FILENAME); + + if (pState->m_zip64) + { + if (pZip->m_total_files == MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + } + else + { + if (pZip->m_total_files == MZ_UINT16_MAX) + { + pState->m_zip64 = MZ_TRUE; + /*return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); */ + } + } + + archive_name_size = strlen(pArchive_name); + if (archive_name_size > MZ_UINT16_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_FILENAME); + + num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); + + /* miniz doesn't support central dirs >= MZ_UINT32_MAX bytes yet */ + if (((mz_uint64)pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE + comment_size) >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); + + if (!pState->m_zip64) + { + /* Bail early if the archive would obviously become too large */ + if ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + archive_name_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + + archive_name_size + comment_size + user_extra_data_len + pState->m_central_dir.m_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE + 1024 + + MZ_ZIP_DATA_DESCRIPTER_SIZE32 + user_extra_data_central_len) > 0xFFFFFFFF) + { + pState->m_zip64 = MZ_TRUE; + /*return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); */ + } + } + +#ifndef MINIZ_NO_TIME + if (pFile_time) + { + mz_zip_time_t_to_dos_time(*pFile_time, &dos_time, &dos_date); + } +#endif + + if (uncomp_size <= 3) + level = 0; + + if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, num_alignment_padding_bytes)) + { + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + + cur_archive_file_ofs += num_alignment_padding_bytes; + local_dir_header_ofs = cur_archive_file_ofs; + + if (pZip->m_file_offset_alignment) + { + MZ_ASSERT((cur_archive_file_ofs & (pZip->m_file_offset_alignment - 1)) == 0); + } + + if (uncomp_size && level) + { + method = MZ_DEFLATED; + } + + MZ_CLEAR_OBJ(local_dir_header); + if (pState->m_zip64) + { + if (uncomp_size >= MZ_UINT32_MAX || local_dir_header_ofs >= MZ_UINT32_MAX) + { + pExtra_data = extra_data; + extra_size = mz_zip_writer_create_zip64_extra_data(extra_data, (uncomp_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL, + (uncomp_size >= MZ_UINT32_MAX) ? &comp_size : NULL, (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL); + } + + if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, (mz_uint16)(extra_size + user_extra_data_len), 0, 0, 0, method, gen_flags, dos_time, dos_date)) + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += sizeof(local_dir_header); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) + { + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + + cur_archive_file_ofs += archive_name_size; + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, extra_data, extra_size) != extra_size) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += extra_size; + } + else + { + if ((comp_size > MZ_UINT32_MAX) || (cur_archive_file_ofs > MZ_UINT32_MAX)) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, (mz_uint16)user_extra_data_len, 0, 0, 0, method, gen_flags, dos_time, dos_date)) + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += sizeof(local_dir_header); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) + { + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + + cur_archive_file_ofs += archive_name_size; + } + + if (user_extra_data_len > 0) + { + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, user_extra_data, user_extra_data_len) != user_extra_data_len) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += user_extra_data_len; + } + + if (uncomp_size) + { + mz_uint64 uncomp_remaining = uncomp_size; + void *pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, MZ_ZIP_MAX_IO_BUF_SIZE); + if (!pRead_buf) + { + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if (!level) + { + while (uncomp_remaining) + { + mz_uint n = (mz_uint)MZ_MIN((mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE, uncomp_remaining); + if ((read_callback(callback_opaque, file_ofs, pRead_buf, n) != n) || (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pRead_buf, n) != n)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + } + file_ofs += n; + uncomp_crc32 = (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, n); + uncomp_remaining -= n; + cur_archive_file_ofs += n; + } + comp_size = uncomp_size; + } + else + { + mz_bool result = MZ_FALSE; + mz_zip_writer_add_state state; + tdefl_compressor *pComp = (tdefl_compressor *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)); + if (!pComp) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + state.m_pZip = pZip; + state.m_cur_archive_file_ofs = cur_archive_file_ofs; + state.m_comp_size = 0; + + if (tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params(level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + } + + for (;;) + { + size_t in_buf_size = (mz_uint32)MZ_MIN(uncomp_remaining, (mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE); + tdefl_status status; + tdefl_flush flush = TDEFL_NO_FLUSH; + + if (read_callback(callback_opaque, file_ofs, pRead_buf, in_buf_size)!= in_buf_size) + { + mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + break; + } + + file_ofs += in_buf_size; + uncomp_crc32 = (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, in_buf_size); + uncomp_remaining -= in_buf_size; + + if (pZip->m_pNeeds_keepalive != NULL && pZip->m_pNeeds_keepalive(pZip->m_pIO_opaque)) + flush = TDEFL_FULL_FLUSH; + + status = tdefl_compress_buffer(pComp, pRead_buf, in_buf_size, uncomp_remaining ? flush : TDEFL_FINISH); + if (status == TDEFL_STATUS_DONE) + { + result = MZ_TRUE; + break; + } + else if (status != TDEFL_STATUS_OKAY) + { + mz_zip_set_error(pZip, MZ_ZIP_COMPRESSION_FAILED); + break; + } + } + + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + + if (!result) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + return MZ_FALSE; + } + + comp_size = state.m_comp_size; + cur_archive_file_ofs = state.m_cur_archive_file_ofs; + } + + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + } + + { + mz_uint8 local_dir_footer[MZ_ZIP_DATA_DESCRIPTER_SIZE64]; + mz_uint32 local_dir_footer_size = MZ_ZIP_DATA_DESCRIPTER_SIZE32; + + MZ_WRITE_LE32(local_dir_footer + 0, MZ_ZIP_DATA_DESCRIPTOR_ID); + MZ_WRITE_LE32(local_dir_footer + 4, uncomp_crc32); + if (pExtra_data == NULL) + { + if (comp_size > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + + MZ_WRITE_LE32(local_dir_footer + 8, comp_size); + MZ_WRITE_LE32(local_dir_footer + 12, uncomp_size); + } + else + { + MZ_WRITE_LE64(local_dir_footer + 8, comp_size); + MZ_WRITE_LE64(local_dir_footer + 16, uncomp_size); + local_dir_footer_size = MZ_ZIP_DATA_DESCRIPTER_SIZE64; + } + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, local_dir_footer, local_dir_footer_size) != local_dir_footer_size) + return MZ_FALSE; + + cur_archive_file_ofs += local_dir_footer_size; + } + + if (pExtra_data != NULL) + { + extra_size = mz_zip_writer_create_zip64_extra_data(extra_data, (uncomp_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL, + (uncomp_size >= MZ_UINT32_MAX) ? &comp_size : NULL, (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL); + } + + if (!mz_zip_writer_add_to_central_dir(pZip, pArchive_name, (mz_uint16)archive_name_size, pExtra_data, (mz_uint16)extra_size, pComment, comment_size, + uncomp_size, comp_size, uncomp_crc32, method, gen_flags, dos_time, dos_date, local_dir_header_ofs, ext_attributes, + user_extra_data_central, user_extra_data_central_len)) + return MZ_FALSE; + + pZip->m_total_files++; + pZip->m_archive_size = cur_archive_file_ofs; + + return MZ_TRUE; +} + +#ifndef MINIZ_NO_STDIO + +static size_t mz_file_read_func_stdio(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) +{ + MZ_FILE *pSrc_file = (MZ_FILE *)pOpaque; + mz_int64 cur_ofs = MZ_FTELL64(pSrc_file); + + if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pSrc_file, (mz_int64)file_ofs, SEEK_SET)))) + return 0; + + return MZ_FREAD(pBuf, 1, n, pSrc_file); +} + +mz_bool mz_zip_writer_add_cfile(mz_zip_archive *pZip, const char *pArchive_name, MZ_FILE *pSrc_file, mz_uint64 size_to_add, const MZ_TIME_T *pFile_time, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, + const char *user_extra_data, mz_uint user_extra_data_len, const char *user_extra_data_central, mz_uint user_extra_data_central_len) +{ + return mz_zip_writer_add_read_buf_callback(pZip, pArchive_name, mz_file_read_func_stdio, pSrc_file, size_to_add, pFile_time, pComment, comment_size, level_and_flags, + user_extra_data, user_extra_data_len, user_extra_data_central, user_extra_data_central_len); +} + +mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags) +{ + MZ_FILE *pSrc_file = NULL; + mz_uint64 uncomp_size = 0; + MZ_TIME_T file_modified_time; + MZ_TIME_T *pFile_time = NULL; + mz_bool status; + + memset(&file_modified_time, 0, sizeof(file_modified_time)); + +#if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_STDIO) + pFile_time = &file_modified_time; + if (!mz_zip_get_file_modified_time(pSrc_filename, &file_modified_time)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_STAT_FAILED); +#endif + + pSrc_file = MZ_FOPEN(pSrc_filename, "rb"); + if (!pSrc_file) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); + + MZ_FSEEK64(pSrc_file, 0, SEEK_END); + uncomp_size = MZ_FTELL64(pSrc_file); + MZ_FSEEK64(pSrc_file, 0, SEEK_SET); + + status = mz_zip_writer_add_cfile(pZip, pArchive_name, pSrc_file, uncomp_size, pFile_time, pComment, comment_size, level_and_flags, NULL, 0, NULL, 0); + + MZ_FCLOSE(pSrc_file); + + return status; +} +#endif /* #ifndef MINIZ_NO_STDIO */ + +static mz_bool mz_zip_writer_update_zip64_extension_block(mz_zip_array *pNew_ext, mz_zip_archive *pZip, const mz_uint8 *pExt, uint32_t ext_len, mz_uint64 *pComp_size, mz_uint64 *pUncomp_size, mz_uint64 *pLocal_header_ofs, mz_uint32 *pDisk_start) +{ + /* + 64 should be enough for any new zip64 data */ + if (!mz_zip_array_reserve(pZip, pNew_ext, ext_len + 64, MZ_FALSE)) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + mz_zip_array_resize(pZip, pNew_ext, 0, MZ_FALSE); + + if ((pUncomp_size) || (pComp_size) || (pLocal_header_ofs) || (pDisk_start)) + { + mz_uint8 new_ext_block[64]; + mz_uint8 *pDst = new_ext_block; + mz_write_le16(pDst, MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID); + mz_write_le16(pDst + sizeof(mz_uint16), 0); + pDst += sizeof(mz_uint16) * 2; + + if (pUncomp_size) + { + mz_write_le64(pDst, *pUncomp_size); + pDst += sizeof(mz_uint64); + } + + if (pComp_size) + { + mz_write_le64(pDst, *pComp_size); + pDst += sizeof(mz_uint64); + } + + if (pLocal_header_ofs) + { + mz_write_le64(pDst, *pLocal_header_ofs); + pDst += sizeof(mz_uint64); + } + + if (pDisk_start) + { + mz_write_le32(pDst, *pDisk_start); + pDst += sizeof(mz_uint32); + } + + mz_write_le16(new_ext_block + sizeof(mz_uint16), (mz_uint16)((pDst - new_ext_block) - sizeof(mz_uint16) * 2)); + + if (!mz_zip_array_push_back(pZip, pNew_ext, new_ext_block, pDst - new_ext_block)) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if ((pExt) && (ext_len)) + { + mz_uint32 extra_size_remaining = ext_len; + const mz_uint8 *pExtra_data = pExt; + + do + { + mz_uint32 field_id, field_data_size, field_total_size; + + if (extra_size_remaining < (sizeof(mz_uint16) * 2)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + field_id = MZ_READ_LE16(pExtra_data); + field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); + field_total_size = field_data_size + sizeof(mz_uint16) * 2; + + if (field_total_size > extra_size_remaining) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if (field_id != MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) + { + if (!mz_zip_array_push_back(pZip, pNew_ext, pExtra_data, field_total_size)) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + pExtra_data += field_total_size; + extra_size_remaining -= field_total_size; + } while (extra_size_remaining); + } + + return MZ_TRUE; +} + +/* TODO: This func is now pretty freakin complex due to zip64, split it up? */ +mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint src_file_index) +{ + mz_uint n, bit_flags, num_alignment_padding_bytes, src_central_dir_following_data_size; + mz_uint64 src_archive_bytes_remaining, local_dir_header_ofs; + mz_uint64 cur_src_file_ofs, cur_dst_file_ofs; + mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; + mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; + mz_uint8 new_central_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; + size_t orig_central_dir_size; + mz_zip_internal_state *pState; + void *pBuf; + const mz_uint8 *pSrc_central_header; + mz_zip_archive_file_stat src_file_stat; + mz_uint32 src_filename_len, src_comment_len, src_ext_len; + mz_uint32 local_header_filename_size, local_header_extra_len; + mz_uint64 local_header_comp_size, local_header_uncomp_size; + mz_bool found_zip64_ext_data_in_ldir = MZ_FALSE; + + /* Sanity checks */ + if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pSource_zip->m_pRead)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pState = pZip->m_pState; + + /* Don't support copying files from zip64 archives to non-zip64, even though in some cases this is possible */ + if ((pSource_zip->m_pState->m_zip64) && (!pZip->m_pState->m_zip64)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + /* Get pointer to the source central dir header and crack it */ + if (NULL == (pSrc_central_header = mz_zip_get_cdh(pSource_zip, src_file_index))) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_SIG_OFS) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + src_filename_len = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_FILENAME_LEN_OFS); + src_comment_len = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_COMMENT_LEN_OFS); + src_ext_len = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS); + src_central_dir_following_data_size = src_filename_len + src_ext_len + src_comment_len; + + /* TODO: We don't support central dir's >= MZ_UINT32_MAX bytes right now (+32 fudge factor in case we need to add more extra data) */ + if ((pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + src_central_dir_following_data_size + 32) >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); + + num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); + + if (!pState->m_zip64) + { + if (pZip->m_total_files == MZ_UINT16_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + } + else + { + /* TODO: Our zip64 support still has some 32-bit limits that may not be worth fixing. */ + if (pZip->m_total_files == MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + } + + if (!mz_zip_file_stat_internal(pSource_zip, src_file_index, pSrc_central_header, &src_file_stat, NULL)) + return MZ_FALSE; + + cur_src_file_ofs = src_file_stat.m_local_header_ofs; + cur_dst_file_ofs = pZip->m_archive_size; + + /* Read the source archive's local dir header */ + if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + + if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + cur_src_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; + + /* Compute the total size we need to copy (filename+extra data+compressed data) */ + local_header_filename_size = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS); + local_header_extra_len = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); + local_header_comp_size = MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS); + local_header_uncomp_size = MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS); + src_archive_bytes_remaining = local_header_filename_size + local_header_extra_len + src_file_stat.m_comp_size; + + /* Try to find a zip64 extended information field */ + if ((local_header_extra_len) && ((local_header_comp_size == MZ_UINT32_MAX) || (local_header_uncomp_size == MZ_UINT32_MAX))) + { + mz_zip_array file_data_array; + const mz_uint8 *pExtra_data; + mz_uint32 extra_size_remaining = local_header_extra_len; + + mz_zip_array_init(&file_data_array, 1); + if (!mz_zip_array_resize(pZip, &file_data_array, local_header_extra_len, MZ_FALSE)) + { + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, src_file_stat.m_local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + local_header_filename_size, file_data_array.m_p, local_header_extra_len) != local_header_extra_len) + { + mz_zip_array_clear(pZip, &file_data_array); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + } + + pExtra_data = (const mz_uint8 *)file_data_array.m_p; + + do + { + mz_uint32 field_id, field_data_size, field_total_size; + + if (extra_size_remaining < (sizeof(mz_uint16) * 2)) + { + mz_zip_array_clear(pZip, &file_data_array); + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + } + + field_id = MZ_READ_LE16(pExtra_data); + field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); + field_total_size = field_data_size + sizeof(mz_uint16) * 2; + + if (field_total_size > extra_size_remaining) + { + mz_zip_array_clear(pZip, &file_data_array); + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + } + + if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) + { + const mz_uint8 *pSrc_field_data = pExtra_data + sizeof(mz_uint32); + + if (field_data_size < sizeof(mz_uint64) * 2) + { + mz_zip_array_clear(pZip, &file_data_array); + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + } + + local_header_uncomp_size = MZ_READ_LE64(pSrc_field_data); + local_header_comp_size = MZ_READ_LE64(pSrc_field_data + sizeof(mz_uint64)); /* may be 0 if there's a descriptor */ + + found_zip64_ext_data_in_ldir = MZ_TRUE; + break; + } + + pExtra_data += field_total_size; + extra_size_remaining -= field_total_size; + } while (extra_size_remaining); + + mz_zip_array_clear(pZip, &file_data_array); + } + + if (!pState->m_zip64) + { + /* Try to detect if the new archive will most likely wind up too big and bail early (+(sizeof(mz_uint32) * 4) is for the optional descriptor which could be present, +64 is a fudge factor). */ + /* We also check when the archive is finalized so this doesn't need to be perfect. */ + mz_uint64 approx_new_archive_size = cur_dst_file_ofs + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + src_archive_bytes_remaining + (sizeof(mz_uint32) * 4) + + pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + src_central_dir_following_data_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE + 64; + + if (approx_new_archive_size >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + } + + /* Write dest archive padding */ + if (!mz_zip_writer_write_zeros(pZip, cur_dst_file_ofs, num_alignment_padding_bytes)) + return MZ_FALSE; + + cur_dst_file_ofs += num_alignment_padding_bytes; + + local_dir_header_ofs = cur_dst_file_ofs; + if (pZip->m_file_offset_alignment) + { + MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); + } + + /* The original zip's local header+ext block doesn't change, even with zip64, so we can just copy it over to the dest zip */ + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_dst_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; + + /* Copy over the source archive bytes to the dest archive, also ensure we have enough buf space to handle optional data descriptor */ + if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)MZ_MAX(32U, MZ_MIN((mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE, src_archive_bytes_remaining))))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + while (src_archive_bytes_remaining) + { + n = (mz_uint)MZ_MIN((mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE, src_archive_bytes_remaining); + if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, n) != n) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + } + cur_src_file_ofs += n; + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + cur_dst_file_ofs += n; + + src_archive_bytes_remaining -= n; + } + + /* Now deal with the optional data descriptor */ + bit_flags = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS); + if (bit_flags & 8) + { + /* Copy data descriptor */ + if ((pSource_zip->m_pState->m_zip64) || (found_zip64_ext_data_in_ldir)) + { + /* src is zip64, dest must be zip64 */ + + /* name uint32_t's */ + /* id 1 (optional in zip64?) */ + /* crc 1 */ + /* comp_size 2 */ + /* uncomp_size 2 */ + if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, (sizeof(mz_uint32) * 6)) != (sizeof(mz_uint32) * 6)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + } + + n = sizeof(mz_uint32) * ((MZ_READ_LE32(pBuf) == MZ_ZIP_DATA_DESCRIPTOR_ID) ? 6 : 5); + } + else + { + /* src is NOT zip64 */ + mz_bool has_id; + + if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, sizeof(mz_uint32) * 4) != sizeof(mz_uint32) * 4) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + } + + has_id = (MZ_READ_LE32(pBuf) == MZ_ZIP_DATA_DESCRIPTOR_ID); + + if (pZip->m_pState->m_zip64) + { + /* dest is zip64, so upgrade the data descriptor */ + const mz_uint32 *pSrc_descriptor = (const mz_uint32 *)((const mz_uint8 *)pBuf + (has_id ? sizeof(mz_uint32) : 0)); + const mz_uint32 src_crc32 = pSrc_descriptor[0]; + const mz_uint64 src_comp_size = pSrc_descriptor[1]; + const mz_uint64 src_uncomp_size = pSrc_descriptor[2]; + + mz_write_le32((mz_uint8 *)pBuf, MZ_ZIP_DATA_DESCRIPTOR_ID); + mz_write_le32((mz_uint8 *)pBuf + sizeof(mz_uint32) * 1, src_crc32); + mz_write_le64((mz_uint8 *)pBuf + sizeof(mz_uint32) * 2, src_comp_size); + mz_write_le64((mz_uint8 *)pBuf + sizeof(mz_uint32) * 4, src_uncomp_size); + + n = sizeof(mz_uint32) * 6; + } + else + { + /* dest is NOT zip64, just copy it as-is */ + n = sizeof(mz_uint32) * (has_id ? 4 : 3); + } + } + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + + cur_src_file_ofs += n; + cur_dst_file_ofs += n; + } + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + + /* Finally, add the new central dir header */ + orig_central_dir_size = pState->m_central_dir.m_size; + + memcpy(new_central_header, pSrc_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); + + if (pState->m_zip64) + { + /* This is the painful part: We need to write a new central dir header + ext block with updated zip64 fields, and ensure the old fields (if any) are not included. */ + const mz_uint8 *pSrc_ext = pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + src_filename_len; + mz_zip_array new_ext_block; + + mz_zip_array_init(&new_ext_block, sizeof(mz_uint8)); + + MZ_WRITE_LE32(new_central_header + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS, MZ_UINT32_MAX); + MZ_WRITE_LE32(new_central_header + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS, MZ_UINT32_MAX); + MZ_WRITE_LE32(new_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS, MZ_UINT32_MAX); + + if (!mz_zip_writer_update_zip64_extension_block(&new_ext_block, pZip, pSrc_ext, src_ext_len, &src_file_stat.m_comp_size, &src_file_stat.m_uncomp_size, &local_dir_header_ofs, NULL)) + { + mz_zip_array_clear(pZip, &new_ext_block); + return MZ_FALSE; + } + + MZ_WRITE_LE16(new_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS, new_ext_block.m_size); + + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, new_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) + { + mz_zip_array_clear(pZip, &new_ext_block); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, src_filename_len)) + { + mz_zip_array_clear(pZip, &new_ext_block); + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, new_ext_block.m_p, new_ext_block.m_size)) + { + mz_zip_array_clear(pZip, &new_ext_block); + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + src_filename_len + src_ext_len, src_comment_len)) + { + mz_zip_array_clear(pZip, &new_ext_block); + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + mz_zip_array_clear(pZip, &new_ext_block); + } + else + { + /* sanity checks */ + if (cur_dst_file_ofs > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + + if (local_dir_header_ofs >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + + MZ_WRITE_LE32(new_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_dir_header_ofs); + + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, new_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, src_central_dir_following_data_size)) + { + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + } + + /* This shouldn't trigger unless we screwed up during the initial sanity checks */ + if (pState->m_central_dir.m_size >= MZ_UINT32_MAX) + { + /* TODO: Support central dirs >= 32-bits in size */ + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); + } + + n = (mz_uint32)orig_central_dir_size; + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &n, 1)) + { + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + pZip->m_total_files++; + pZip->m_archive_size = cur_dst_file_ofs; + + return MZ_TRUE; +} + +mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip) +{ + mz_zip_internal_state *pState; + mz_uint64 central_dir_ofs, central_dir_size; + mz_uint8 hdr[256]; + + if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pState = pZip->m_pState; + + if (pState->m_zip64) + { + if ((pZip->m_total_files > MZ_UINT32_MAX) || (pState->m_central_dir.m_size >= MZ_UINT32_MAX)) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + } + else + { + if ((pZip->m_total_files > MZ_UINT16_MAX) || ((pZip->m_archive_size + pState->m_central_dir.m_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) > MZ_UINT32_MAX)) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + } + + central_dir_ofs = 0; + central_dir_size = 0; + if (pZip->m_total_files) + { + /* Write central directory */ + central_dir_ofs = pZip->m_archive_size; + central_dir_size = pState->m_central_dir.m_size; + pZip->m_central_directory_file_ofs = central_dir_ofs; + if (pZip->m_pWrite(pZip->m_pIO_opaque, central_dir_ofs, pState->m_central_dir.m_p, (size_t)central_dir_size) != central_dir_size) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + pZip->m_archive_size += central_dir_size; + } + + if (pState->m_zip64) + { + /* Write zip64 end of central directory header */ + mz_uint64 rel_ofs_to_zip64_ecdr = pZip->m_archive_size; + + MZ_CLEAR_OBJ(hdr); + MZ_WRITE_LE32(hdr + MZ_ZIP64_ECDH_SIG_OFS, MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIG); + MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_SIZE_OF_RECORD_OFS, MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE - sizeof(mz_uint32) - sizeof(mz_uint64)); + MZ_WRITE_LE16(hdr + MZ_ZIP64_ECDH_VERSION_MADE_BY_OFS, 0x031E); /* TODO: always Unix */ + MZ_WRITE_LE16(hdr + MZ_ZIP64_ECDH_VERSION_NEEDED_OFS, 0x002D); + MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS, pZip->m_total_files); + MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_CDIR_TOTAL_ENTRIES_OFS, pZip->m_total_files); + MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_CDIR_SIZE_OFS, central_dir_size); + MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_CDIR_OFS_OFS, central_dir_ofs); + if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + pZip->m_archive_size += MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE; + + /* Write zip64 end of central directory locator */ + MZ_CLEAR_OBJ(hdr); + MZ_WRITE_LE32(hdr + MZ_ZIP64_ECDL_SIG_OFS, MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIG); + MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDL_REL_OFS_TO_ZIP64_ECDR_OFS, rel_ofs_to_zip64_ecdr); + MZ_WRITE_LE32(hdr + MZ_ZIP64_ECDL_TOTAL_NUMBER_OF_DISKS_OFS, 1); + if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) != MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + pZip->m_archive_size += MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE; + } + + /* Write end of central directory record */ + MZ_CLEAR_OBJ(hdr); + MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_SIG_OFS, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG); + MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS, MZ_MIN(MZ_UINT16_MAX, pZip->m_total_files)); + MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS, MZ_MIN(MZ_UINT16_MAX, pZip->m_total_files)); + MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_SIZE_OFS, MZ_MIN(MZ_UINT32_MAX, central_dir_size)); + MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_OFS_OFS, MZ_MIN(MZ_UINT32_MAX, central_dir_ofs)); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + +#ifndef MINIZ_NO_STDIO + if ((pState->m_pFile) && (MZ_FFLUSH(pState->m_pFile) == EOF)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_CLOSE_FAILED); +#endif /* #ifndef MINIZ_NO_STDIO */ + + pZip->m_archive_size += MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE; + + pZip->m_zip_mode = MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED; + return MZ_TRUE; +} + +mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **ppBuf, size_t *pSize) +{ + if ((!ppBuf) || (!pSize)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + *ppBuf = NULL; + *pSize = 0; + + if ((!pZip) || (!pZip->m_pState)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (pZip->m_pWrite != mz_zip_heap_write_func) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (!mz_zip_writer_finalize_archive(pZip)) + return MZ_FALSE; + + *ppBuf = pZip->m_pState->m_pMem; + *pSize = pZip->m_pState->m_mem_size; + pZip->m_pState->m_pMem = NULL; + pZip->m_pState->m_mem_size = pZip->m_pState->m_mem_capacity = 0; + + return MZ_TRUE; +} + +mz_bool mz_zip_writer_end(mz_zip_archive *pZip) +{ + return mz_zip_writer_end_internal(pZip, MZ_TRUE); +} + +#ifndef MINIZ_NO_STDIO +mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags) +{ + return mz_zip_add_mem_to_archive_file_in_place_v2(pZip_filename, pArchive_name, pBuf, buf_size, pComment, comment_size, level_and_flags, NULL); +} + +mz_bool mz_zip_add_mem_to_archive_file_in_place_v2(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_zip_error *pErr) +{ + mz_bool status, created_new_archive = MZ_FALSE; + mz_zip_archive zip_archive; + struct MZ_FILE_STAT_STRUCT file_stat; + mz_zip_error actual_err = MZ_ZIP_NO_ERROR; + + mz_zip_zero_struct(&zip_archive); + if ((int)level_and_flags < 0) + level_and_flags = MZ_DEFAULT_LEVEL; + + if ((!pZip_filename) || (!pArchive_name) || ((buf_size) && (!pBuf)) || ((comment_size) && (!pComment)) || ((level_and_flags & 0xF) > MZ_UBER_COMPRESSION)) + { + if (pErr) + *pErr = MZ_ZIP_INVALID_PARAMETER; + return MZ_FALSE; + } + + if (!mz_zip_writer_validate_archive_name(pArchive_name)) + { + if (pErr) + *pErr = MZ_ZIP_INVALID_FILENAME; + return MZ_FALSE; + } + + /* Important: The regular non-64 bit version of stat() can fail here if the file is very large, which could cause the archive to be overwritten. */ + /* So be sure to compile with _LARGEFILE64_SOURCE 1 */ + if (MZ_FILE_STAT(pZip_filename, &file_stat) != 0) + { + /* Create a new archive. */ + if (!mz_zip_writer_init_file_v2(&zip_archive, pZip_filename, 0, level_and_flags)) + { + if (pErr) + *pErr = zip_archive.m_last_error; + return MZ_FALSE; + } + + created_new_archive = MZ_TRUE; + } + else + { + /* Append to an existing archive. */ + if (!mz_zip_reader_init_file_v2(&zip_archive, pZip_filename, level_and_flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY, 0, 0)) + { + if (pErr) + *pErr = zip_archive.m_last_error; + return MZ_FALSE; + } + + if (!mz_zip_writer_init_from_reader_v2(&zip_archive, pZip_filename, level_and_flags)) + { + if (pErr) + *pErr = zip_archive.m_last_error; + + mz_zip_reader_end_internal(&zip_archive, MZ_FALSE); + + return MZ_FALSE; + } + } + + status = mz_zip_writer_add_mem_ex(&zip_archive, pArchive_name, pBuf, buf_size, pComment, comment_size, level_and_flags, 0, 0); + actual_err = zip_archive.m_last_error; + + /* Always finalize, even if adding failed for some reason, so we have a valid central directory. (This may not always succeed, but we can try.) */ + if (!mz_zip_writer_finalize_archive(&zip_archive)) + { + if (!actual_err) + actual_err = zip_archive.m_last_error; + + status = MZ_FALSE; + } + + if (!mz_zip_writer_end_internal(&zip_archive, status)) + { + if (!actual_err) + actual_err = zip_archive.m_last_error; + + status = MZ_FALSE; + } + + if ((!status) && (created_new_archive)) + { + /* It's a new archive and something went wrong, so just delete it. */ + int ignoredStatus = MZ_DELETE_FILE(pZip_filename); + (void)ignoredStatus; + } + + if (pErr) + *pErr = actual_err; + + return status; +} + +void *mz_zip_extract_archive_file_to_heap_v2(const char *pZip_filename, const char *pArchive_name, const char *pComment, size_t *pSize, mz_uint flags, mz_zip_error *pErr) +{ + mz_uint32 file_index; + mz_zip_archive zip_archive; + void *p = NULL; + + if (pSize) + *pSize = 0; + + if ((!pZip_filename) || (!pArchive_name)) + { + if (pErr) + *pErr = MZ_ZIP_INVALID_PARAMETER; + + return NULL; + } + + mz_zip_zero_struct(&zip_archive); + if (!mz_zip_reader_init_file_v2(&zip_archive, pZip_filename, flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY, 0, 0)) + { + if (pErr) + *pErr = zip_archive.m_last_error; + + return NULL; + } + + if (mz_zip_reader_locate_file_v2(&zip_archive, pArchive_name, pComment, flags, &file_index)) + { + p = mz_zip_reader_extract_to_heap(&zip_archive, file_index, pSize, flags); + } + + mz_zip_reader_end_internal(&zip_archive, p != NULL); + + if (pErr) + *pErr = zip_archive.m_last_error; + + return p; +} + +void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint flags) +{ + return mz_zip_extract_archive_file_to_heap_v2(pZip_filename, pArchive_name, NULL, pSize, flags, NULL); +} + +#endif /* #ifndef MINIZ_NO_STDIO */ + +#endif /* #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS */ + +/* ------------------- Misc utils */ + +mz_zip_mode mz_zip_get_mode(mz_zip_archive *pZip) +{ + return pZip ? pZip->m_zip_mode : MZ_ZIP_MODE_INVALID; +} + +mz_zip_type mz_zip_get_type(mz_zip_archive *pZip) +{ + return pZip ? pZip->m_zip_type : MZ_ZIP_TYPE_INVALID; +} + +mz_zip_error mz_zip_set_last_error(mz_zip_archive *pZip, mz_zip_error err_num) +{ + mz_zip_error prev_err; + + if (!pZip) + return MZ_ZIP_INVALID_PARAMETER; + + prev_err = pZip->m_last_error; + + pZip->m_last_error = err_num; + return prev_err; +} + +mz_zip_error mz_zip_peek_last_error(mz_zip_archive *pZip) +{ + if (!pZip) + return MZ_ZIP_INVALID_PARAMETER; + + return pZip->m_last_error; +} + +mz_zip_error mz_zip_clear_last_error(mz_zip_archive *pZip) +{ + return mz_zip_set_last_error(pZip, MZ_ZIP_NO_ERROR); +} + +mz_zip_error mz_zip_get_last_error(mz_zip_archive *pZip) +{ + mz_zip_error prev_err; + + if (!pZip) + return MZ_ZIP_INVALID_PARAMETER; + + prev_err = pZip->m_last_error; + + pZip->m_last_error = MZ_ZIP_NO_ERROR; + return prev_err; +} + +const char *mz_zip_get_error_string(mz_zip_error mz_err) +{ + switch (mz_err) + { + case MZ_ZIP_NO_ERROR: + return "no error"; + case MZ_ZIP_UNDEFINED_ERROR: + return "undefined error"; + case MZ_ZIP_TOO_MANY_FILES: + return "too many files"; + case MZ_ZIP_FILE_TOO_LARGE: + return "file too large"; + case MZ_ZIP_UNSUPPORTED_METHOD: + return "unsupported method"; + case MZ_ZIP_UNSUPPORTED_ENCRYPTION: + return "unsupported encryption"; + case MZ_ZIP_UNSUPPORTED_FEATURE: + return "unsupported feature"; + case MZ_ZIP_FAILED_FINDING_CENTRAL_DIR: + return "failed finding central directory"; + case MZ_ZIP_NOT_AN_ARCHIVE: + return "not a ZIP archive"; + case MZ_ZIP_INVALID_HEADER_OR_CORRUPTED: + return "invalid header or archive is corrupted"; + case MZ_ZIP_UNSUPPORTED_MULTIDISK: + return "unsupported multidisk archive"; + case MZ_ZIP_DECOMPRESSION_FAILED: + return "decompression failed or archive is corrupted"; + case MZ_ZIP_COMPRESSION_FAILED: + return "compression failed"; + case MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE: + return "unexpected decompressed size"; + case MZ_ZIP_CRC_CHECK_FAILED: + return "CRC-32 check failed"; + case MZ_ZIP_UNSUPPORTED_CDIR_SIZE: + return "unsupported central directory size"; + case MZ_ZIP_ALLOC_FAILED: + return "allocation failed"; + case MZ_ZIP_FILE_OPEN_FAILED: + return "file open failed"; + case MZ_ZIP_FILE_CREATE_FAILED: + return "file create failed"; + case MZ_ZIP_FILE_WRITE_FAILED: + return "file write failed"; + case MZ_ZIP_FILE_READ_FAILED: + return "file read failed"; + case MZ_ZIP_FILE_CLOSE_FAILED: + return "file close failed"; + case MZ_ZIP_FILE_SEEK_FAILED: + return "file seek failed"; + case MZ_ZIP_FILE_STAT_FAILED: + return "file stat failed"; + case MZ_ZIP_INVALID_PARAMETER: + return "invalid parameter"; + case MZ_ZIP_INVALID_FILENAME: + return "invalid filename"; + case MZ_ZIP_BUF_TOO_SMALL: + return "buffer too small"; + case MZ_ZIP_INTERNAL_ERROR: + return "internal error"; + case MZ_ZIP_FILE_NOT_FOUND: + return "file not found"; + case MZ_ZIP_ARCHIVE_TOO_LARGE: + return "archive is too large"; + case MZ_ZIP_VALIDATION_FAILED: + return "validation failed"; + case MZ_ZIP_WRITE_CALLBACK_FAILED: + return "write calledback failed"; + default: + break; + } + + return "unknown error"; +} + +/* Note: Just because the archive is not zip64 doesn't necessarily mean it doesn't have Zip64 extended information extra field, argh. */ +mz_bool mz_zip_is_zip64(mz_zip_archive *pZip) +{ + if ((!pZip) || (!pZip->m_pState)) + return MZ_FALSE; + + return pZip->m_pState->m_zip64; +} + +size_t mz_zip_get_central_dir_size(mz_zip_archive *pZip) +{ + if ((!pZip) || (!pZip->m_pState)) + return 0; + + return pZip->m_pState->m_central_dir.m_size; +} + +mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip) +{ + return pZip ? pZip->m_total_files : 0; +} + +mz_uint64 mz_zip_get_archive_size(mz_zip_archive *pZip) +{ + if (!pZip) + return 0; + return pZip->m_archive_size; +} + +mz_uint64 mz_zip_get_archive_file_start_offset(mz_zip_archive *pZip) +{ + if ((!pZip) || (!pZip->m_pState)) + return 0; + return pZip->m_pState->m_file_archive_start_ofs; +} + +MZ_FILE *mz_zip_get_cfile(mz_zip_archive *pZip) +{ + if ((!pZip) || (!pZip->m_pState)) + return 0; + return pZip->m_pState->m_pFile; +} + +size_t mz_zip_read_archive_data(mz_zip_archive *pZip, mz_uint64 file_ofs, void *pBuf, size_t n) +{ + if ((!pZip) || (!pZip->m_pState) || (!pBuf) || (!pZip->m_pRead)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + return pZip->m_pRead(pZip->m_pIO_opaque, file_ofs, pBuf, n); +} + +mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size) +{ + mz_uint n; + const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index); + if (!p) + { + if (filename_buf_size) + pFilename[0] = '\0'; + mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + return 0; + } + n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); + if (filename_buf_size) + { + n = MZ_MIN(n, filename_buf_size - 1); + memcpy(pFilename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); + pFilename[n] = '\0'; + } + return n + 1; +} + +mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat) +{ + return mz_zip_file_stat_internal(pZip, file_index, mz_zip_get_cdh(pZip, file_index), pStat, NULL); +} + +mz_bool mz_zip_end(mz_zip_archive *pZip) +{ + if (!pZip) + return MZ_FALSE; + + if (pZip->m_zip_mode == MZ_ZIP_MODE_READING) + return mz_zip_reader_end(pZip); +#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS + else if ((pZip->m_zip_mode == MZ_ZIP_MODE_WRITING) || (pZip->m_zip_mode == MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED)) + return mz_zip_writer_end(pZip); +#endif + + return MZ_FALSE; +} + +#ifdef __cplusplus +} +#endif + +#endif /*#ifndef MINIZ_NO_ARCHIVE_APIS*/ diff --git a/Frameworks/vgmstream/vgmstream/src/coding/circus_decoder_miniz.h b/Frameworks/vgmstream/vgmstream/src/coding/circus_decoder_miniz.h new file mode 100644 index 000000000..34a0f498f --- /dev/null +++ b/Frameworks/vgmstream/vgmstream/src/coding/circus_decoder_miniz.h @@ -0,0 +1,1346 @@ +// vgmstream config +/* force non-aligned reads to improve compiler warnings (slower tho) */ +#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 0 +/* .zip handling stuff */ +#define MINIZ_NO_TIME 1 +#define MINIZ_NO_ARCHIVE_APIS 1 +#define MINIZ_NO_ARCHIVE_WRITING_APIS 1 + +/* miniz.c 2.1.0 - public domain deflate/inflate, zlib-subset, ZIP reading/writing/appending, PNG writing + See "unlicense" statement at the end of this file. + Rich Geldreich , last updated Oct. 13, 2013 + Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951: http://www.ietf.org/rfc/rfc1951.txt + + Most API's defined in miniz.c are optional. For example, to disable the archive related functions just define + MINIZ_NO_ARCHIVE_APIS, or to get rid of all stdio usage define MINIZ_NO_STDIO (see the list below for more macros). + + * Low-level Deflate/Inflate implementation notes: + + Compression: Use the "tdefl" API's. The compressor supports raw, static, and dynamic blocks, lazy or + greedy parsing, match length filtering, RLE-only, and Huffman-only streams. It performs and compresses + approximately as well as zlib. + + Decompression: Use the "tinfl" API's. The entire decompressor is implemented as a single function + coroutine: see tinfl_decompress(). It supports decompression into a 32KB (or larger power of 2) wrapping buffer, or into a memory + block large enough to hold the entire file. + + The low-level tdefl/tinfl API's do not make any use of dynamic memory allocation. + + * zlib-style API notes: + + miniz.c implements a fairly large subset of zlib. There's enough functionality present for it to be a drop-in + zlib replacement in many apps: + The z_stream struct, optional memory allocation callbacks + deflateInit/deflateInit2/deflate/deflateReset/deflateEnd/deflateBound + inflateInit/inflateInit2/inflate/inflateReset/inflateEnd + compress, compress2, compressBound, uncompress + CRC-32, Adler-32 - Using modern, minimal code size, CPU cache friendly routines. + Supports raw deflate streams or standard zlib streams with adler-32 checking. + + Limitations: + The callback API's are not implemented yet. No support for gzip headers or zlib static dictionaries. + I've tried to closely emulate zlib's various flavors of stream flushing and return status codes, but + there are no guarantees that miniz.c pulls this off perfectly. + + * PNG writing: See the tdefl_write_image_to_png_file_in_memory() function, originally written by + Alex Evans. Supports 1-4 bytes/pixel images. + + * ZIP archive API notes: + + The ZIP archive API's where designed with simplicity and efficiency in mind, with just enough abstraction to + get the job done with minimal fuss. There are simple API's to retrieve file information, read files from + existing archives, create new archives, append new files to existing archives, or clone archive data from + one archive to another. It supports archives located in memory or the heap, on disk (using stdio.h), + or you can specify custom file read/write callbacks. + + - Archive reading: Just call this function to read a single file from a disk archive: + + void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, + size_t *pSize, mz_uint zip_flags); + + For more complex cases, use the "mz_zip_reader" functions. Upon opening an archive, the entire central + directory is located and read as-is into memory, and subsequent file access only occurs when reading individual files. + + - Archives file scanning: The simple way is to use this function to scan a loaded archive for a specific file: + + int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); + + The locate operation can optionally check file comments too, which (as one example) can be used to identify + multiple versions of the same file in an archive. This function uses a simple linear search through the central + directory, so it's not very fast. + + Alternately, you can iterate through all the files in an archive (using mz_zip_reader_get_num_files()) and + retrieve detailed info on each file by calling mz_zip_reader_file_stat(). + + - Archive creation: Use the "mz_zip_writer" functions. The ZIP writer immediately writes compressed file data + to disk and builds an exact image of the central directory in memory. The central directory image is written + all at once at the end of the archive file when the archive is finalized. + + The archive writer can optionally align each file's local header and file data to any power of 2 alignment, + which can be useful when the archive will be read from optical media. Also, the writer supports placing + arbitrary data blobs at the very beginning of ZIP archives. Archives written using either feature are still + readable by any ZIP tool. + + - Archive appending: The simple way to add a single file to an archive is to call this function: + + mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, + const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); + + The archive will be created if it doesn't already exist, otherwise it'll be appended to. + Note the appending is done in-place and is not an atomic operation, so if something goes wrong + during the operation it's possible the archive could be left without a central directory (although the local + file headers and file data will be fine, so the archive will be recoverable). + + For more complex archive modification scenarios: + 1. The safest way is to use a mz_zip_reader to read the existing archive, cloning only those bits you want to + preserve into a new archive using using the mz_zip_writer_add_from_zip_reader() function (which compiles the + compressed file data as-is). When you're done, delete the old archive and rename the newly written archive, and + you're done. This is safe but requires a bunch of temporary disk space or heap memory. + + 2. Or, you can convert an mz_zip_reader in-place to an mz_zip_writer using mz_zip_writer_init_from_reader(), + append new files as needed, then finalize the archive which will write an updated central directory to the + original archive. (This is basically what mz_zip_add_mem_to_archive_file_in_place() does.) There's a + possibility that the archive's central directory could be lost with this method if anything goes wrong, though. + + - ZIP archive support limitations: + No zip64 or spanning support. Extraction functions can only handle unencrypted, stored or deflated files. + Requires streams capable of seeking. + + * This is a header file library, like stb_image.c. To get only a header file, either cut and paste the + below header, or create miniz.h, #define MINIZ_HEADER_FILE_ONLY, and then include miniz.c from it. + + * Important: For best perf. be sure to customize the below macros for your target platform: + #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 + #define MINIZ_LITTLE_ENDIAN 1 + #define MINIZ_HAS_64BIT_REGISTERS 1 + + * On platforms using glibc, Be sure to "#define _LARGEFILE64_SOURCE 1" before including miniz.c to ensure miniz + uses the 64-bit variants: fopen64(), stat64(), etc. Otherwise you won't be able to process large files + (i.e. 32-bit stat() fails for me on files > 0x7FFFFFFF bytes). +*/ +#pragma once + + + + + +/* Defines to completely disable specific portions of miniz.c: + If all macros here are defined the only functionality remaining will be CRC-32, adler-32, tinfl, and tdefl. */ + +/* Define MINIZ_NO_STDIO to disable all usage and any functions which rely on stdio for file I/O. */ +/*#define MINIZ_NO_STDIO */ + +/* If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able to get the current time, or */ +/* get/set file times, and the C run-time funcs that get/set times won't be called. */ +/* The current downside is the times written to your archives will be from 1979. */ +/*#define MINIZ_NO_TIME */ + +/* Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's. */ +/*#define MINIZ_NO_ARCHIVE_APIS */ + +/* Define MINIZ_NO_ARCHIVE_WRITING_APIS to disable all writing related ZIP archive API's. */ +/*#define MINIZ_NO_ARCHIVE_WRITING_APIS */ + +/* Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression API's. */ +/*#define MINIZ_NO_ZLIB_APIS */ + +/* Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent conflicts against stock zlib. */ +/*#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES */ + +/* Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc. + Note if MINIZ_NO_MALLOC is defined then the user must always provide custom user alloc/free/realloc + callbacks to the zlib and archive API's, and a few stand-alone helper API's which don't provide custom user + functions (such as tdefl_compress_mem_to_heap() and tinfl_decompress_mem_to_heap()) won't work. */ +/*#define MINIZ_NO_MALLOC */ + +#if defined(__TINYC__) && (defined(__linux) || defined(__linux__)) +/* TODO: Work around "error: include file 'sys\utime.h' when compiling with tcc on Linux */ +#define MINIZ_NO_TIME +#endif + +#include + +#if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS) +#include +#endif + +#if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || defined(__i386) || defined(__i486__) || defined(__i486) || defined(i386) || defined(__ia64__) || defined(__x86_64__) +/* MINIZ_X86_OR_X64_CPU is only used to help set the below macros. */ +#define MINIZ_X86_OR_X64_CPU 1 +#else +#define MINIZ_X86_OR_X64_CPU 0 +#endif + +#if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU +/* Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian. */ +#define MINIZ_LITTLE_ENDIAN 1 +#else +#define MINIZ_LITTLE_ENDIAN 0 +#endif + +/* Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES only if not set */ +#if !defined(MINIZ_USE_UNALIGNED_LOADS_AND_STORES) +#if MINIZ_X86_OR_X64_CPU +/* Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient integer loads and stores from unaligned addresses. */ +#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 +#define MINIZ_UNALIGNED_USE_MEMCPY +#else +#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 0 +#endif +#endif + +#if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || defined(_LP64) || defined(__LP64__) || defined(__ia64__) || defined(__x86_64__) +/* Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are reasonably fast (and don't involve compiler generated calls to helper functions). */ +#define MINIZ_HAS_64BIT_REGISTERS 1 +#else +#define MINIZ_HAS_64BIT_REGISTERS 0 +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/* ------------------- zlib-style API Definitions. */ + +/* For more compatibility with zlib, miniz.c uses unsigned long for some parameters/struct members. Beware: mz_ulong can be either 32 or 64-bits! */ +typedef unsigned long mz_ulong; + +/* mz_free() internally uses the MZ_FREE() macro (which by default calls free() unless you've modified the MZ_MALLOC macro) to release a block allocated from the heap. */ +void mz_free(void *p); + +#define MZ_ADLER32_INIT (1) +/* mz_adler32() returns the initial adler-32 value to use when called with ptr==NULL. */ +mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len); + +#define MZ_CRC32_INIT (0) +/* mz_crc32() returns the initial CRC-32 value to use when called with ptr==NULL. */ +mz_ulong mz_crc32(mz_ulong crc, const unsigned char *ptr, size_t buf_len); + +/* Compression strategies. */ +enum +{ + MZ_DEFAULT_STRATEGY = 0, + MZ_FILTERED = 1, + MZ_HUFFMAN_ONLY = 2, + MZ_RLE = 3, + MZ_FIXED = 4 +}; + +/* Method */ +#define MZ_DEFLATED 8 + +/* Heap allocation callbacks. +Note that mz_alloc_func parameter types purpsosely differ from zlib's: items/size is size_t, not unsigned long. */ +typedef void *(*mz_alloc_func)(void *opaque, size_t items, size_t size); +typedef void (*mz_free_func)(void *opaque, void *address); +typedef void *(*mz_realloc_func)(void *opaque, void *address, size_t items, size_t size); + +/* Compression levels: 0-9 are the standard zlib-style levels, 10 is best possible compression (not zlib compatible, and may be very slow), MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL. */ +enum +{ + MZ_NO_COMPRESSION = 0, + MZ_BEST_SPEED = 1, + MZ_BEST_COMPRESSION = 9, + MZ_UBER_COMPRESSION = 10, + MZ_DEFAULT_LEVEL = 6, + MZ_DEFAULT_COMPRESSION = -1 +}; + +#define MZ_VERSION "10.1.0" +#define MZ_VERNUM 0xA100 +#define MZ_VER_MAJOR 10 +#define MZ_VER_MINOR 1 +#define MZ_VER_REVISION 0 +#define MZ_VER_SUBREVISION 0 + +#ifndef MINIZ_NO_ZLIB_APIS + +/* Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The other values are for advanced use (refer to the zlib docs). */ +enum +{ + MZ_NO_FLUSH = 0, + MZ_PARTIAL_FLUSH = 1, + MZ_SYNC_FLUSH = 2, + MZ_FULL_FLUSH = 3, + MZ_FINISH = 4, + MZ_BLOCK = 5 +}; + +/* Return status codes. MZ_PARAM_ERROR is non-standard. */ +enum +{ + MZ_OK = 0, + MZ_STREAM_END = 1, + MZ_NEED_DICT = 2, + MZ_ERRNO = -1, + MZ_STREAM_ERROR = -2, + MZ_DATA_ERROR = -3, + MZ_MEM_ERROR = -4, + MZ_BUF_ERROR = -5, + MZ_VERSION_ERROR = -6, + MZ_PARAM_ERROR = -10000 +}; + +/* Window bits */ +#define MZ_DEFAULT_WINDOW_BITS 15 + +struct mz_internal_state; + +/* Compression/decompression stream struct. */ +typedef struct mz_stream_s +{ + const unsigned char *next_in; /* pointer to next byte to read */ + unsigned int avail_in; /* number of bytes available at next_in */ + mz_ulong total_in; /* total number of bytes consumed so far */ + + unsigned char *next_out; /* pointer to next byte to write */ + unsigned int avail_out; /* number of bytes that can be written to next_out */ + mz_ulong total_out; /* total number of bytes produced so far */ + + char *msg; /* error msg (unused) */ + struct mz_internal_state *state; /* internal state, allocated by zalloc/zfree */ + + mz_alloc_func zalloc; /* optional heap allocation function (defaults to malloc) */ + mz_free_func zfree; /* optional heap free function (defaults to free) */ + void *opaque; /* heap alloc function user pointer */ + + int data_type; /* data_type (unused) */ + mz_ulong adler; /* adler32 of the source or uncompressed data */ + mz_ulong reserved; /* not used */ +} mz_stream; + +typedef mz_stream *mz_streamp; + +/* Returns the version string of miniz.c. */ +const char *mz_version(void); + +/* mz_deflateInit() initializes a compressor with default options: */ +/* Parameters: */ +/* pStream must point to an initialized mz_stream struct. */ +/* level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION]. */ +/* level 1 enables a specially optimized compression function that's been optimized purely for performance, not ratio. */ +/* (This special func. is currently only enabled when MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.) */ +/* Return values: */ +/* MZ_OK on success. */ +/* MZ_STREAM_ERROR if the stream is bogus. */ +/* MZ_PARAM_ERROR if the input parameters are bogus. */ +/* MZ_MEM_ERROR on out of memory. */ +int mz_deflateInit(mz_streamp pStream, int level); + +/* mz_deflateInit2() is like mz_deflate(), except with more control: */ +/* Additional parameters: */ +/* method must be MZ_DEFLATED */ +/* window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with zlib header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no header or footer) */ +/* mem_level must be between [1, 9] (it's checked but ignored by miniz.c) */ +int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy); + +/* Quickly resets a compressor without having to reallocate anything. Same as calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2(). */ +int mz_deflateReset(mz_streamp pStream); + +/* mz_deflate() compresses the input to output, consuming as much of the input and producing as much output as possible. */ +/* Parameters: */ +/* pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members. */ +/* flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or MZ_FINISH. */ +/* Return values: */ +/* MZ_OK on success (when flushing, or if more input is needed but not available, and/or there's more output to be written but the output buffer is full). */ +/* MZ_STREAM_END if all input has been consumed and all output bytes have been written. Don't call mz_deflate() on the stream anymore. */ +/* MZ_STREAM_ERROR if the stream is bogus. */ +/* MZ_PARAM_ERROR if one of the parameters is invalid. */ +/* MZ_BUF_ERROR if no forward progress is possible because the input and/or output buffers are empty. (Fill up the input buffer or free up some output space and try again.) */ +int mz_deflate(mz_streamp pStream, int flush); + +/* mz_deflateEnd() deinitializes a compressor: */ +/* Return values: */ +/* MZ_OK on success. */ +/* MZ_STREAM_ERROR if the stream is bogus. */ +int mz_deflateEnd(mz_streamp pStream); + +/* mz_deflateBound() returns a (very) conservative upper bound on the amount of data that could be generated by deflate(), assuming flush is set to only MZ_NO_FLUSH or MZ_FINISH. */ +mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len); + +/* Single-call compression functions mz_compress() and mz_compress2(): */ +/* Returns MZ_OK on success, or one of the error codes from mz_deflate() on failure. */ +int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); +int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level); + +/* mz_compressBound() returns a (very) conservative upper bound on the amount of data that could be generated by calling mz_compress(). */ +mz_ulong mz_compressBound(mz_ulong source_len); + +/* Initializes a decompressor. */ +int mz_inflateInit(mz_streamp pStream); + +/* mz_inflateInit2() is like mz_inflateInit() with an additional option that controls the window size and whether or not the stream has been wrapped with a zlib header/footer: */ +/* window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate). */ +int mz_inflateInit2(mz_streamp pStream, int window_bits); + +/* Quickly resets a compressor without having to reallocate anything. Same as calling mz_inflateEnd() followed by mz_inflateInit()/mz_inflateInit2(). */ +int mz_inflateReset(mz_streamp pStream); + +/* Decompresses the input stream to the output, consuming only as much of the input as needed, and writing as much to the output as possible. */ +/* Parameters: */ +/* pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members. */ +/* flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH. */ +/* On the first call, if flush is MZ_FINISH it's assumed the input and output buffers are both sized large enough to decompress the entire stream in a single call (this is slightly faster). */ +/* MZ_FINISH implies that there are no more source bytes available beside what's already in the input buffer, and that the output buffer is large enough to hold the rest of the decompressed data. */ +/* Return values: */ +/* MZ_OK on success. Either more input is needed but not available, and/or there's more output to be written but the output buffer is full. */ +/* MZ_STREAM_END if all needed input has been consumed and all output bytes have been written. For zlib streams, the adler-32 of the decompressed data has also been verified. */ +/* MZ_STREAM_ERROR if the stream is bogus. */ +/* MZ_DATA_ERROR if the deflate stream is invalid. */ +/* MZ_PARAM_ERROR if one of the parameters is invalid. */ +/* MZ_BUF_ERROR if no forward progress is possible because the input buffer is empty but the inflater needs more input to continue, or if the output buffer is not large enough. Call mz_inflate() again */ +/* with more input data, or with more room in the output buffer (except when using single call decompression, described above). */ +int mz_inflate(mz_streamp pStream, int flush); + +/* Deinitializes a decompressor. */ +int mz_inflateEnd(mz_streamp pStream); + +/* Single-call decompression. */ +/* Returns MZ_OK on success, or one of the error codes from mz_inflate() on failure. */ +int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); + +/* Returns a string description of the specified error code, or NULL if the error code is invalid. */ +const char *mz_error(int err); + +/* Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used as a drop-in replacement for the subset of zlib that miniz.c supports. */ +/* Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you use zlib in the same project. */ +#ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES +typedef unsigned char Byte; +typedef unsigned int uInt; +typedef mz_ulong uLong; +typedef Byte Bytef; +typedef uInt uIntf; +typedef char charf; +typedef int intf; +typedef void *voidpf; +typedef uLong uLongf; +typedef void *voidp; +typedef void *const voidpc; +#define Z_NULL 0 +#define Z_NO_FLUSH MZ_NO_FLUSH +#define Z_PARTIAL_FLUSH MZ_PARTIAL_FLUSH +#define Z_SYNC_FLUSH MZ_SYNC_FLUSH +#define Z_FULL_FLUSH MZ_FULL_FLUSH +#define Z_FINISH MZ_FINISH +#define Z_BLOCK MZ_BLOCK +#define Z_OK MZ_OK +#define Z_STREAM_END MZ_STREAM_END +#define Z_NEED_DICT MZ_NEED_DICT +#define Z_ERRNO MZ_ERRNO +#define Z_STREAM_ERROR MZ_STREAM_ERROR +#define Z_DATA_ERROR MZ_DATA_ERROR +#define Z_MEM_ERROR MZ_MEM_ERROR +#define Z_BUF_ERROR MZ_BUF_ERROR +#define Z_VERSION_ERROR MZ_VERSION_ERROR +#define Z_PARAM_ERROR MZ_PARAM_ERROR +#define Z_NO_COMPRESSION MZ_NO_COMPRESSION +#define Z_BEST_SPEED MZ_BEST_SPEED +#define Z_BEST_COMPRESSION MZ_BEST_COMPRESSION +#define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION +#define Z_DEFAULT_STRATEGY MZ_DEFAULT_STRATEGY +#define Z_FILTERED MZ_FILTERED +#define Z_HUFFMAN_ONLY MZ_HUFFMAN_ONLY +#define Z_RLE MZ_RLE +#define Z_FIXED MZ_FIXED +#define Z_DEFLATED MZ_DEFLATED +#define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS +#define alloc_func mz_alloc_func +#define free_func mz_free_func +#define internal_state mz_internal_state +#define z_stream mz_stream +#define deflateInit mz_deflateInit +#define deflateInit2 mz_deflateInit2 +#define deflateReset mz_deflateReset +#define deflate mz_deflate +#define deflateEnd mz_deflateEnd +#define deflateBound mz_deflateBound +#define compress mz_compress +#define compress2 mz_compress2 +#define compressBound mz_compressBound +#define inflateInit mz_inflateInit +#define inflateInit2 mz_inflateInit2 +#define inflateReset mz_inflateReset +#define inflate mz_inflate +#define inflateEnd mz_inflateEnd +#define uncompress mz_uncompress +#define crc32 mz_crc32 +#define adler32 mz_adler32 +#define MAX_WBITS 15 +#define MAX_MEM_LEVEL 9 +#define zError mz_error +#define ZLIB_VERSION MZ_VERSION +#define ZLIB_VERNUM MZ_VERNUM +#define ZLIB_VER_MAJOR MZ_VER_MAJOR +#define ZLIB_VER_MINOR MZ_VER_MINOR +#define ZLIB_VER_REVISION MZ_VER_REVISION +#define ZLIB_VER_SUBREVISION MZ_VER_SUBREVISION +#define zlibVersion mz_version +#define zlib_version mz_version() +#endif /* #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES */ + +#endif /* MINIZ_NO_ZLIB_APIS */ + +#ifdef __cplusplus +} +#endif +#pragma once +#include +#include +#include +#include + +/* ------------------- Types and macros */ +typedef unsigned char mz_uint8; +typedef signed short mz_int16; +typedef unsigned short mz_uint16; +typedef unsigned int mz_uint32; +typedef unsigned int mz_uint; +typedef int64_t mz_int64; +typedef uint64_t mz_uint64; +typedef int mz_bool; + +#define MZ_FALSE (0) +#define MZ_TRUE (1) + +/* Works around MSVC's spammy "warning C4127: conditional expression is constant" message. */ +#ifdef _MSC_VER +#define MZ_MACRO_END while (0, 0) +#else +#define MZ_MACRO_END while (0) +#endif + +#ifdef MINIZ_NO_STDIO +#define MZ_FILE void * +#else +#include +#define MZ_FILE FILE +#endif /* #ifdef MINIZ_NO_STDIO */ + +#ifdef MINIZ_NO_TIME +typedef struct mz_dummy_time_t_tag +{ + int m_dummy; +} mz_dummy_time_t; +#define MZ_TIME_T mz_dummy_time_t +#else +#define MZ_TIME_T time_t +#endif + +#define MZ_ASSERT(x) assert(x) + +#ifdef MINIZ_NO_MALLOC +#define MZ_MALLOC(x) NULL +#define MZ_FREE(x) (void)x, ((void)0) +#define MZ_REALLOC(p, x) NULL +#else +#define MZ_MALLOC(x) malloc(x) +#define MZ_FREE(x) free(x) +#define MZ_REALLOC(p, x) realloc(p, x) +#endif + +#define MZ_MAX(a, b) (((a) > (b)) ? (a) : (b)) +#define MZ_MIN(a, b) (((a) < (b)) ? (a) : (b)) +#define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj)) + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN +#define MZ_READ_LE16(p) *((const mz_uint16 *)(p)) +#define MZ_READ_LE32(p) *((const mz_uint32 *)(p)) +#else +#define MZ_READ_LE16(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U)) +#define MZ_READ_LE32(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | ((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | ((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U)) +#endif + +#define MZ_READ_LE64(p) (((mz_uint64)MZ_READ_LE32(p)) | (((mz_uint64)MZ_READ_LE32((const mz_uint8 *)(p) + sizeof(mz_uint32))) << 32U)) + +#ifdef _MSC_VER +#define MZ_FORCEINLINE __forceinline +#elif defined(__GNUC__) +#define MZ_FORCEINLINE __inline__ __attribute__((__always_inline__)) +#else +#define MZ_FORCEINLINE inline +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +extern void *miniz_def_alloc_func(void *opaque, size_t items, size_t size); +extern void miniz_def_free_func(void *opaque, void *address); +extern void *miniz_def_realloc_func(void *opaque, void *address, size_t items, size_t size); + +#define MZ_UINT16_MAX (0xFFFFU) +#define MZ_UINT32_MAX (0xFFFFFFFFU) + +#ifdef __cplusplus +} +#endif +#pragma once + + +#ifdef __cplusplus +extern "C" { +#endif +/* ------------------- Low-level Compression API Definitions */ + +/* Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly slower, and raw/dynamic blocks will be output more frequently). */ +#define TDEFL_LESS_MEMORY 0 + +/* tdefl_init() compression flags logically OR'd together (low 12 bits contain the max. number of probes per dictionary search): */ +/* TDEFL_DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes per dictionary search. 0=Huffman only, 1=Huffman+LZ (fastest/crap compression), 4095=Huffman+LZ (slowest/best compression). */ +enum +{ + TDEFL_HUFFMAN_ONLY = 0, + TDEFL_DEFAULT_MAX_PROBES = 128, + TDEFL_MAX_PROBES_MASK = 0xFFF +}; + +/* TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before the deflate data, and the Adler-32 of the source data at the end. Otherwise, you'll get raw deflate data. */ +/* TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even when not writing zlib headers). */ +/* TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more efficient lazy parsing. */ +/* TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's initialization time to the minimum, but the output may vary from run to run given the same input (depending on the contents of memory). */ +/* TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1) */ +/* TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled. */ +/* TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables. */ +/* TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks. */ +/* The low 12 bits are reserved to control the max # of hash probes per dictionary lookup (see TDEFL_MAX_PROBES_MASK). */ +enum +{ + TDEFL_WRITE_ZLIB_HEADER = 0x01000, + TDEFL_COMPUTE_ADLER32 = 0x02000, + TDEFL_GREEDY_PARSING_FLAG = 0x04000, + TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000, + TDEFL_RLE_MATCHES = 0x10000, + TDEFL_FILTER_MATCHES = 0x20000, + TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000, + TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000 +}; + +/* High level compression functions: */ +/* tdefl_compress_mem_to_heap() compresses a block in memory to a heap block allocated via malloc(). */ +/* On entry: */ +/* pSrc_buf, src_buf_len: Pointer and size of source block to compress. */ +/* flags: The max match finder probes (default is 128) logically OR'd against the above flags. Higher probes are slower but improve compression. */ +/* On return: */ +/* Function returns a pointer to the compressed data, or NULL on failure. */ +/* *pOut_len will be set to the compressed data's size, which could be larger than src_buf_len on uncompressible data. */ +/* The caller must free() the returned block when it's no longer needed. */ +void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); + +/* tdefl_compress_mem_to_mem() compresses a block in memory to another block in memory. */ +/* Returns 0 on failure. */ +size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); + +/* Compresses an image to a compressed PNG file in memory. */ +/* On entry: */ +/* pImage, w, h, and num_chans describe the image to compress. num_chans may be 1, 2, 3, or 4. */ +/* The image pitch in bytes per scanline will be w*num_chans. The leftmost pixel on the top scanline is stored first in memory. */ +/* level may range from [0,10], use MZ_NO_COMPRESSION, MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc. or a decent default is MZ_DEFAULT_LEVEL */ +/* If flip is true, the image will be flipped on the Y axis (useful for OpenGL apps). */ +/* On return: */ +/* Function returns a pointer to the compressed data, or NULL on failure. */ +/* *pLen_out will be set to the size of the PNG image file. */ +/* The caller must mz_free() the returned heap block (which will typically be larger than *pLen_out) when it's no longer needed. */ +void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip); +void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out); + +/* Output stream interface. The compressor uses this interface to write compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time. */ +typedef mz_bool (*tdefl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser); + +/* tdefl_compress_mem_to_output() compresses a block to an output stream. The above helpers use this function internally. */ +mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); + +enum +{ + TDEFL_MAX_HUFF_TABLES = 3, + TDEFL_MAX_HUFF_SYMBOLS_0 = 288, + TDEFL_MAX_HUFF_SYMBOLS_1 = 32, + TDEFL_MAX_HUFF_SYMBOLS_2 = 19, + TDEFL_LZ_DICT_SIZE = 32768, + TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1, + TDEFL_MIN_MATCH_LEN = 3, + TDEFL_MAX_MATCH_LEN = 258 +}; + +/* TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed output block (using static/fixed Huffman codes). */ +#if TDEFL_LESS_MEMORY +enum +{ + TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024, + TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10, + TDEFL_MAX_HUFF_SYMBOLS = 288, + TDEFL_LZ_HASH_BITS = 12, + TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, + TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, + TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS +}; +#else +enum +{ + TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024, + TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10, + TDEFL_MAX_HUFF_SYMBOLS = 288, + TDEFL_LZ_HASH_BITS = 15, + TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, + TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, + TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS +}; +#endif + +/* The low-level tdefl functions below may be used directly if the above helper functions aren't flexible enough. The low-level functions don't make any heap allocations, unlike the above helper functions. */ +typedef enum { + TDEFL_STATUS_BAD_PARAM = -2, + TDEFL_STATUS_PUT_BUF_FAILED = -1, + TDEFL_STATUS_OKAY = 0, + TDEFL_STATUS_DONE = 1 +} tdefl_status; + +/* Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums */ +typedef enum { + TDEFL_NO_FLUSH = 0, + TDEFL_SYNC_FLUSH = 2, + TDEFL_FULL_FLUSH = 3, + TDEFL_FINISH = 4 +} tdefl_flush; + +/* tdefl's compression state structure. */ +typedef struct +{ + tdefl_put_buf_func_ptr m_pPut_buf_func; + void *m_pPut_buf_user; + mz_uint m_flags, m_max_probes[2]; + int m_greedy_parsing; + mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size; + mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end; + mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in, m_bit_buffer; + mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit, m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index, m_wants_to_finish; + tdefl_status m_prev_return_status; + const void *m_pIn_buf; + void *m_pOut_buf; + size_t *m_pIn_buf_size, *m_pOut_buf_size; + tdefl_flush m_flush; + const mz_uint8 *m_pSrc; + size_t m_src_buf_left, m_out_buf_ofs; + mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1]; + mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; + mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; + mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; + mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE]; + mz_uint16 m_next[TDEFL_LZ_DICT_SIZE]; + mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE]; + mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE]; +} tdefl_compressor; + +/* Initializes the compressor. */ +/* There is no corresponding deinit() function because the tdefl API's do not dynamically allocate memory. */ +/* pBut_buf_func: If NULL, output data will be supplied to the specified callback. In this case, the user should call the tdefl_compress_buffer() API for compression. */ +/* If pBut_buf_func is NULL the user should always call the tdefl_compress() API. */ +/* flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER, etc.) */ +tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); + +/* Compresses a block of data, consuming as much of the specified input buffer as possible, and writing as much compressed data to the specified output buffer as possible. */ +tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush); + +/* tdefl_compress_buffer() is only usable when the tdefl_init() is called with a non-NULL tdefl_put_buf_func_ptr. */ +/* tdefl_compress_buffer() always consumes the entire input buffer. */ +tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush); + +tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d); +mz_uint32 tdefl_get_adler32(tdefl_compressor *d); + +/* Create tdefl_compress() flags given zlib-style compression parameters. */ +/* level may range from [0,10] (where 10 is absolute max compression, but may be much slower on some files) */ +/* window_bits may be -15 (raw deflate) or 15 (zlib) */ +/* strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY, MZ_RLE, or MZ_FIXED */ +mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy); + +#ifndef MINIZ_NO_MALLOC +/* Allocate the tdefl_compressor structure in C so that */ +/* non-C language bindings to tdefl_ API don't need to worry about */ +/* structure size and allocation mechanism. */ +tdefl_compressor *tdefl_compressor_alloc(void); +void tdefl_compressor_free(tdefl_compressor *pComp); +#endif + +#ifdef __cplusplus +} +#endif +#pragma once + +/* ------------------- Low-level Decompression API Definitions */ + +#ifdef __cplusplus +extern "C" { +#endif +/* Decompression flags used by tinfl_decompress(). */ +/* TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the input is a raw deflate stream. */ +/* TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available beyond the end of the supplied input buffer. If clear, the input buffer contains all remaining input. */ +/* TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large enough to hold the entire decompressed stream. If clear, the output buffer is at least the size of the dictionary (typically 32KB). */ +/* TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the decompressed bytes. */ +enum +{ + TINFL_FLAG_PARSE_ZLIB_HEADER = 1, + TINFL_FLAG_HAS_MORE_INPUT = 2, + TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4, + TINFL_FLAG_COMPUTE_ADLER32 = 8 +}; + +/* High level decompression functions: */ +/* tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block allocated via malloc(). */ +/* On entry: */ +/* pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data to decompress. */ +/* On return: */ +/* Function returns a pointer to the decompressed data, or NULL on failure. */ +/* *pOut_len will be set to the decompressed data's size, which could be larger than src_buf_len on uncompressible data. */ +/* The caller must call mz_free() on the returned block when it's no longer needed. */ +void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); + +/* tinfl_decompress_mem_to_mem() decompresses a block in memory to another block in memory. */ +/* Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes written on success. */ +#define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1)) +size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); + +/* tinfl_decompress_mem_to_callback() decompresses a block in memory to an internal 32KB buffer, and a user provided callback function will be called to flush the buffer. */ +/* Returns 1 on success or 0 on failure. */ +typedef int (*tinfl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser); +int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); + +struct tinfl_decompressor_tag; +typedef struct tinfl_decompressor_tag tinfl_decompressor; + +#ifndef MINIZ_NO_MALLOC +/* Allocate the tinfl_decompressor structure in C so that */ +/* non-C language bindings to tinfl_ API don't need to worry about */ +/* structure size and allocation mechanism. */ +tinfl_decompressor *tinfl_decompressor_alloc(void); +void tinfl_decompressor_free(tinfl_decompressor *pDecomp); +#endif + +/* Max size of LZ dictionary. */ +#define TINFL_LZ_DICT_SIZE 32768 + +/* Return status. */ +typedef enum { + /* This flags indicates the inflator needs 1 or more input bytes to make forward progress, but the caller is indicating that no more are available. The compressed data */ + /* is probably corrupted. If you call the inflator again with more bytes it'll try to continue processing the input but this is a BAD sign (either the data is corrupted or you called it incorrectly). */ + /* If you call it again with no input you'll just get TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS again. */ + TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS = -4, + + /* This flag indicates that one or more of the input parameters was obviously bogus. (You can try calling it again, but if you get this error the calling code is wrong.) */ + TINFL_STATUS_BAD_PARAM = -3, + + /* This flags indicate the inflator is finished but the adler32 check of the uncompressed data didn't match. If you call it again it'll return TINFL_STATUS_DONE. */ + TINFL_STATUS_ADLER32_MISMATCH = -2, + + /* This flags indicate the inflator has somehow failed (bad code, corrupted input, etc.). If you call it again without resetting via tinfl_init() it it'll just keep on returning the same status failure code. */ + TINFL_STATUS_FAILED = -1, + + /* Any status code less than TINFL_STATUS_DONE must indicate a failure. */ + + /* This flag indicates the inflator has returned every byte of uncompressed data that it can, has consumed every byte that it needed, has successfully reached the end of the deflate stream, and */ + /* if zlib headers and adler32 checking enabled that it has successfully checked the uncompressed data's adler32. If you call it again you'll just get TINFL_STATUS_DONE over and over again. */ + TINFL_STATUS_DONE = 0, + + /* This flag indicates the inflator MUST have more input data (even 1 byte) before it can make any more forward progress, or you need to clear the TINFL_FLAG_HAS_MORE_INPUT */ + /* flag on the next call if you don't have any more source data. If the source data was somehow corrupted it's also possible (but unlikely) for the inflator to keep on demanding input to */ + /* proceed, so be sure to properly set the TINFL_FLAG_HAS_MORE_INPUT flag. */ + TINFL_STATUS_NEEDS_MORE_INPUT = 1, + + /* This flag indicates the inflator definitely has 1 or more bytes of uncompressed data available, but it cannot write this data into the output buffer. */ + /* Note if the source compressed data was corrupted it's possible for the inflator to return a lot of uncompressed data to the caller. I've been assuming you know how much uncompressed data to expect */ + /* (either exact or worst case) and will stop calling the inflator and fail after receiving too much. In pure streaming scenarios where you have no idea how many bytes to expect this may not be possible */ + /* so I may need to add some code to address this. */ + TINFL_STATUS_HAS_MORE_OUTPUT = 2 +} tinfl_status; + +/* Initializes the decompressor to its initial state. */ +#define tinfl_init(r) \ + do \ + { \ + (r)->m_state = 0; \ + } \ + MZ_MACRO_END +#define tinfl_get_adler32(r) (r)->m_check_adler32 + +/* Main low-level decompressor coroutine function. This is the only function actually needed for decompression. All the other functions are just high-level helpers for improved usability. */ +/* This is a universal API, i.e. it can be used as a building block to build any desired higher level decompression API. In the limit case, it can be called once per every byte input or output. */ +tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags); + +/* Internal/private bits follow. */ +enum +{ + TINFL_MAX_HUFF_TABLES = 3, + TINFL_MAX_HUFF_SYMBOLS_0 = 288, + TINFL_MAX_HUFF_SYMBOLS_1 = 32, + TINFL_MAX_HUFF_SYMBOLS_2 = 19, + TINFL_FAST_LOOKUP_BITS = 10, + TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS +}; + +typedef struct +{ + mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0]; + mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE], m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2]; +} tinfl_huff_table; + +#if MINIZ_HAS_64BIT_REGISTERS +#define TINFL_USE_64BIT_BITBUF 1 +#else +#define TINFL_USE_64BIT_BITBUF 0 +#endif + +#if TINFL_USE_64BIT_BITBUF +typedef mz_uint64 tinfl_bit_buf_t; +#define TINFL_BITBUF_SIZE (64) +#else +typedef mz_uint32 tinfl_bit_buf_t; +#define TINFL_BITBUF_SIZE (32) +#endif + +struct tinfl_decompressor_tag +{ + mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type, m_check_adler32, m_dist, m_counter, m_num_extra, m_table_sizes[TINFL_MAX_HUFF_TABLES]; + tinfl_bit_buf_t m_bit_buf; + size_t m_dist_from_out_buf_start; + tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES]; + mz_uint8 m_raw_header[4], m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137]; +}; + +#ifdef __cplusplus +} +#endif + +#pragma once + + +/* ------------------- ZIP archive reading/writing */ + +#ifndef MINIZ_NO_ARCHIVE_APIS + +#ifdef __cplusplus +extern "C" { +#endif + +enum +{ + /* Note: These enums can be reduced as needed to save memory or stack space - they are pretty conservative. */ + MZ_ZIP_MAX_IO_BUF_SIZE = 64 * 1024, + MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 512, + MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 512 +}; + +typedef struct +{ + /* Central directory file index. */ + mz_uint32 m_file_index; + + /* Byte offset of this entry in the archive's central directory. Note we currently only support up to UINT_MAX or less bytes in the central dir. */ + mz_uint64 m_central_dir_ofs; + + /* These fields are copied directly from the zip's central dir. */ + mz_uint16 m_version_made_by; + mz_uint16 m_version_needed; + mz_uint16 m_bit_flag; + mz_uint16 m_method; + +#ifndef MINIZ_NO_TIME + MZ_TIME_T m_time; +#endif + + /* CRC-32 of uncompressed data. */ + mz_uint32 m_crc32; + + /* File's compressed size. */ + mz_uint64 m_comp_size; + + /* File's uncompressed size. Note, I've seen some old archives where directory entries had 512 bytes for their uncompressed sizes, but when you try to unpack them you actually get 0 bytes. */ + mz_uint64 m_uncomp_size; + + /* Zip internal and external file attributes. */ + mz_uint16 m_internal_attr; + mz_uint32 m_external_attr; + + /* Entry's local header file offset in bytes. */ + mz_uint64 m_local_header_ofs; + + /* Size of comment in bytes. */ + mz_uint32 m_comment_size; + + /* MZ_TRUE if the entry appears to be a directory. */ + mz_bool m_is_directory; + + /* MZ_TRUE if the entry uses encryption/strong encryption (which miniz_zip doesn't support) */ + mz_bool m_is_encrypted; + + /* MZ_TRUE if the file is not encrypted, a patch file, and if it uses a compression method we support. */ + mz_bool m_is_supported; + + /* Filename. If string ends in '/' it's a subdirectory entry. */ + /* Guaranteed to be zero terminated, may be truncated to fit. */ + char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE]; + + /* Comment field. */ + /* Guaranteed to be zero terminated, may be truncated to fit. */ + char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE]; + +} mz_zip_archive_file_stat; + +typedef size_t (*mz_file_read_func)(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n); +typedef size_t (*mz_file_write_func)(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n); +typedef mz_bool (*mz_file_needs_keepalive)(void *pOpaque); + +struct mz_zip_internal_state_tag; +typedef struct mz_zip_internal_state_tag mz_zip_internal_state; + +typedef enum { + MZ_ZIP_MODE_INVALID = 0, + MZ_ZIP_MODE_READING = 1, + MZ_ZIP_MODE_WRITING = 2, + MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3 +} mz_zip_mode; + +typedef enum { + MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100, + MZ_ZIP_FLAG_IGNORE_PATH = 0x0200, + MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400, + MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800, + MZ_ZIP_FLAG_VALIDATE_LOCATE_FILE_FLAG = 0x1000, /* if enabled, mz_zip_reader_locate_file() will be called on each file as its validated to ensure the func finds the file in the central dir (intended for testing) */ + MZ_ZIP_FLAG_VALIDATE_HEADERS_ONLY = 0x2000, /* validate the local headers, but don't decompress the entire file and check the crc32 */ + MZ_ZIP_FLAG_WRITE_ZIP64 = 0x4000, /* always use the zip64 file format, instead of the original zip file format with automatic switch to zip64. Use as flags parameter with mz_zip_writer_init*_v2 */ + MZ_ZIP_FLAG_WRITE_ALLOW_READING = 0x8000, + MZ_ZIP_FLAG_ASCII_FILENAME = 0x10000 +} mz_zip_flags; + +typedef enum { + MZ_ZIP_TYPE_INVALID = 0, + MZ_ZIP_TYPE_USER, + MZ_ZIP_TYPE_MEMORY, + MZ_ZIP_TYPE_HEAP, + MZ_ZIP_TYPE_FILE, + MZ_ZIP_TYPE_CFILE, + MZ_ZIP_TOTAL_TYPES +} mz_zip_type; + +/* miniz error codes. Be sure to update mz_zip_get_error_string() if you add or modify this enum. */ +typedef enum { + MZ_ZIP_NO_ERROR = 0, + MZ_ZIP_UNDEFINED_ERROR, + MZ_ZIP_TOO_MANY_FILES, + MZ_ZIP_FILE_TOO_LARGE, + MZ_ZIP_UNSUPPORTED_METHOD, + MZ_ZIP_UNSUPPORTED_ENCRYPTION, + MZ_ZIP_UNSUPPORTED_FEATURE, + MZ_ZIP_FAILED_FINDING_CENTRAL_DIR, + MZ_ZIP_NOT_AN_ARCHIVE, + MZ_ZIP_INVALID_HEADER_OR_CORRUPTED, + MZ_ZIP_UNSUPPORTED_MULTIDISK, + MZ_ZIP_DECOMPRESSION_FAILED, + MZ_ZIP_COMPRESSION_FAILED, + MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE, + MZ_ZIP_CRC_CHECK_FAILED, + MZ_ZIP_UNSUPPORTED_CDIR_SIZE, + MZ_ZIP_ALLOC_FAILED, + MZ_ZIP_FILE_OPEN_FAILED, + MZ_ZIP_FILE_CREATE_FAILED, + MZ_ZIP_FILE_WRITE_FAILED, + MZ_ZIP_FILE_READ_FAILED, + MZ_ZIP_FILE_CLOSE_FAILED, + MZ_ZIP_FILE_SEEK_FAILED, + MZ_ZIP_FILE_STAT_FAILED, + MZ_ZIP_INVALID_PARAMETER, + MZ_ZIP_INVALID_FILENAME, + MZ_ZIP_BUF_TOO_SMALL, + MZ_ZIP_INTERNAL_ERROR, + MZ_ZIP_FILE_NOT_FOUND, + MZ_ZIP_ARCHIVE_TOO_LARGE, + MZ_ZIP_VALIDATION_FAILED, + MZ_ZIP_WRITE_CALLBACK_FAILED, + MZ_ZIP_TOTAL_ERRORS +} mz_zip_error; + +typedef struct +{ + mz_uint64 m_archive_size; + mz_uint64 m_central_directory_file_ofs; + + /* We only support up to UINT32_MAX files in zip64 mode. */ + mz_uint32 m_total_files; + mz_zip_mode m_zip_mode; + mz_zip_type m_zip_type; + mz_zip_error m_last_error; + + mz_uint64 m_file_offset_alignment; + + mz_alloc_func m_pAlloc; + mz_free_func m_pFree; + mz_realloc_func m_pRealloc; + void *m_pAlloc_opaque; + + mz_file_read_func m_pRead; + mz_file_write_func m_pWrite; + mz_file_needs_keepalive m_pNeeds_keepalive; + void *m_pIO_opaque; + + mz_zip_internal_state *m_pState; + +} mz_zip_archive; + +typedef struct +{ + mz_zip_archive *pZip; + mz_uint flags; + + int status; +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + mz_uint file_crc32; +#endif + mz_uint64 read_buf_size, read_buf_ofs, read_buf_avail, comp_remaining, out_buf_ofs, cur_file_ofs; + mz_zip_archive_file_stat file_stat; + void *pRead_buf; + void *pWrite_buf; + + size_t out_blk_remain; + + tinfl_decompressor inflator; + +} mz_zip_reader_extract_iter_state; + +/* -------- ZIP reading */ + +/* Inits a ZIP archive reader. */ +/* These functions read and validate the archive's central directory. */ +mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint flags); + +mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint flags); + +#ifndef MINIZ_NO_STDIO +/* Read a archive from a disk file. */ +/* file_start_ofs is the file offset where the archive actually begins, or 0. */ +/* actual_archive_size is the true total size of the archive, which may be smaller than the file's actual size on disk. If zero the entire file is treated as the archive. */ +mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags); +mz_bool mz_zip_reader_init_file_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint flags, mz_uint64 file_start_ofs, mz_uint64 archive_size); + +/* Read an archive from an already opened FILE, beginning at the current file position. */ +/* The archive is assumed to be archive_size bytes long. If archive_size is < 0, then the entire rest of the file is assumed to contain the archive. */ +/* The FILE will NOT be closed when mz_zip_reader_end() is called. */ +mz_bool mz_zip_reader_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile, mz_uint64 archive_size, mz_uint flags); +#endif + +/* Ends archive reading, freeing all allocations, and closing the input archive file if mz_zip_reader_init_file() was used. */ +mz_bool mz_zip_reader_end(mz_zip_archive *pZip); + +/* -------- ZIP reading or writing */ + +/* Clears a mz_zip_archive struct to all zeros. */ +/* Important: This must be done before passing the struct to any mz_zip functions. */ +void mz_zip_zero_struct(mz_zip_archive *pZip); + +mz_zip_mode mz_zip_get_mode(mz_zip_archive *pZip); +mz_zip_type mz_zip_get_type(mz_zip_archive *pZip); + +/* Returns the total number of files in the archive. */ +mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip); + +mz_uint64 mz_zip_get_archive_size(mz_zip_archive *pZip); +mz_uint64 mz_zip_get_archive_file_start_offset(mz_zip_archive *pZip); +MZ_FILE *mz_zip_get_cfile(mz_zip_archive *pZip); + +/* Reads n bytes of raw archive data, starting at file offset file_ofs, to pBuf. */ +size_t mz_zip_read_archive_data(mz_zip_archive *pZip, mz_uint64 file_ofs, void *pBuf, size_t n); + +/* All mz_zip funcs set the m_last_error field in the mz_zip_archive struct. These functions retrieve/manipulate this field. */ +/* Note that the m_last_error functionality is not thread safe. */ +mz_zip_error mz_zip_set_last_error(mz_zip_archive *pZip, mz_zip_error err_num); +mz_zip_error mz_zip_peek_last_error(mz_zip_archive *pZip); +mz_zip_error mz_zip_clear_last_error(mz_zip_archive *pZip); +mz_zip_error mz_zip_get_last_error(mz_zip_archive *pZip); +const char *mz_zip_get_error_string(mz_zip_error mz_err); + +/* MZ_TRUE if the archive file entry is a directory entry. */ +mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index); + +/* MZ_TRUE if the file is encrypted/strong encrypted. */ +mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index); + +/* MZ_TRUE if the compression method is supported, and the file is not encrypted, and the file is not a compressed patch file. */ +mz_bool mz_zip_reader_is_file_supported(mz_zip_archive *pZip, mz_uint file_index); + +/* Retrieves the filename of an archive file entry. */ +/* Returns the number of bytes written to pFilename, or if filename_buf_size is 0 this function returns the number of bytes needed to fully store the filename. */ +mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size); + +/* Attempts to locates a file in the archive's central directory. */ +/* Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH */ +/* Returns -1 if the file cannot be found. */ +int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); +int mz_zip_reader_locate_file_v2(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags, mz_uint32 *file_index); + +/* Returns detailed information about an archive file entry. */ +mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat); + +/* MZ_TRUE if the file is in zip64 format. */ +/* A file is considered zip64 if it contained a zip64 end of central directory marker, or if it contained any zip64 extended file information fields in the central directory. */ +mz_bool mz_zip_is_zip64(mz_zip_archive *pZip); + +/* Returns the total central directory size in bytes. */ +/* The current max supported size is <= MZ_UINT32_MAX. */ +size_t mz_zip_get_central_dir_size(mz_zip_archive *pZip); + +/* Extracts a archive file to a memory buffer using no memory allocation. */ +/* There must be at least enough room on the stack to store the inflator's state (~34KB or so). */ +mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); +mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); + +/* Extracts a archive file to a memory buffer. */ +mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags); +mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags); + +/* Extracts a archive file to a dynamically allocated heap buffer. */ +/* The memory will be allocated via the mz_zip_archive's alloc/realloc functions. */ +/* Returns NULL and sets the last error on failure. */ +void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags); +void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags); + +/* Extracts a archive file using a callback function to output the file's data. */ +mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); +mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); + +/* Extract a file iteratively */ +mz_zip_reader_extract_iter_state* mz_zip_reader_extract_iter_new(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags); +mz_zip_reader_extract_iter_state* mz_zip_reader_extract_file_iter_new(mz_zip_archive *pZip, const char *pFilename, mz_uint flags); +size_t mz_zip_reader_extract_iter_read(mz_zip_reader_extract_iter_state* pState, void* pvBuf, size_t buf_size); +mz_bool mz_zip_reader_extract_iter_free(mz_zip_reader_extract_iter_state* pState); + +#ifndef MINIZ_NO_STDIO +/* Extracts a archive file to a disk file and sets its last accessed and modified times. */ +/* This function only extracts files, not archive directory records. */ +mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags); +mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags); + +/* Extracts a archive file starting at the current position in the destination FILE stream. */ +mz_bool mz_zip_reader_extract_to_cfile(mz_zip_archive *pZip, mz_uint file_index, MZ_FILE *File, mz_uint flags); +mz_bool mz_zip_reader_extract_file_to_cfile(mz_zip_archive *pZip, const char *pArchive_filename, MZ_FILE *pFile, mz_uint flags); +#endif + +#if 0 +/* TODO */ + typedef void *mz_zip_streaming_extract_state_ptr; + mz_zip_streaming_extract_state_ptr mz_zip_streaming_extract_begin(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags); + uint64_t mz_zip_streaming_extract_get_size(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState); + uint64_t mz_zip_streaming_extract_get_cur_ofs(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState); + mz_bool mz_zip_streaming_extract_seek(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState, uint64_t new_ofs); + size_t mz_zip_streaming_extract_read(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState, void *pBuf, size_t buf_size); + mz_bool mz_zip_streaming_extract_end(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState); +#endif + +/* This function compares the archive's local headers, the optional local zip64 extended information block, and the optional descriptor following the compressed data vs. the data in the central directory. */ +/* It also validates that each file can be successfully uncompressed unless the MZ_ZIP_FLAG_VALIDATE_HEADERS_ONLY is specified. */ +mz_bool mz_zip_validate_file(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags); + +/* Validates an entire archive by calling mz_zip_validate_file() on each file. */ +mz_bool mz_zip_validate_archive(mz_zip_archive *pZip, mz_uint flags); + +/* Misc utils/helpers, valid for ZIP reading or writing */ +mz_bool mz_zip_validate_mem_archive(const void *pMem, size_t size, mz_uint flags, mz_zip_error *pErr); +mz_bool mz_zip_validate_file_archive(const char *pFilename, mz_uint flags, mz_zip_error *pErr); + +/* Universal end function - calls either mz_zip_reader_end() or mz_zip_writer_end(). */ +mz_bool mz_zip_end(mz_zip_archive *pZip); + +/* -------- ZIP writing */ + +#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS + +/* Inits a ZIP archive writer. */ +/*Set pZip->m_pWrite (and pZip->m_pIO_opaque) before calling mz_zip_writer_init or mz_zip_writer_init_v2*/ +/*The output is streamable, i.e. file_ofs in mz_file_write_func always increases only by n*/ +mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size); +mz_bool mz_zip_writer_init_v2(mz_zip_archive *pZip, mz_uint64 existing_size, mz_uint flags); + +mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size); +mz_bool mz_zip_writer_init_heap_v2(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size, mz_uint flags); + +#ifndef MINIZ_NO_STDIO +mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning); +mz_bool mz_zip_writer_init_file_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning, mz_uint flags); +mz_bool mz_zip_writer_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile, mz_uint flags); +#endif + +/* Converts a ZIP archive reader object into a writer object, to allow efficient in-place file appends to occur on an existing archive. */ +/* For archives opened using mz_zip_reader_init_file, pFilename must be the archive's filename so it can be reopened for writing. If the file can't be reopened, mz_zip_reader_end() will be called. */ +/* For archives opened using mz_zip_reader_init_mem, the memory block must be growable using the realloc callback (which defaults to realloc unless you've overridden it). */ +/* Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's user provided m_pWrite function cannot be NULL. */ +/* Note: In-place archive modification is not recommended unless you know what you're doing, because if execution stops or something goes wrong before */ +/* the archive is finalized the file's central directory will be hosed. */ +mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename); +mz_bool mz_zip_writer_init_from_reader_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint flags); + +/* Adds the contents of a memory buffer to an archive. These functions record the current local time into the archive. */ +/* To add a directory entry, call this method with an archive name ending in a forwardslash with an empty buffer. */ +/* level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. */ +mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags); + +/* Like mz_zip_writer_add_mem(), except you can specify a file comment field, and optionally supply the function with already compressed data. */ +/* uncomp_size/uncomp_crc32 are only used if the MZ_ZIP_FLAG_COMPRESSED_DATA flag is specified. */ +mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, + mz_uint64 uncomp_size, mz_uint32 uncomp_crc32); + +mz_bool mz_zip_writer_add_mem_ex_v2(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, + mz_uint64 uncomp_size, mz_uint32 uncomp_crc32, MZ_TIME_T *last_modified, const char *user_extra_data_local, mz_uint user_extra_data_local_len, + const char *user_extra_data_central, mz_uint user_extra_data_central_len); + +/* Adds the contents of a file to an archive. This function also records the disk file's modified time into the archive. */ +/* File data is supplied via a read callback function. User mz_zip_writer_add_(c)file to add a file directly.*/ +mz_bool mz_zip_writer_add_read_buf_callback(mz_zip_archive *pZip, const char *pArchive_name, mz_file_read_func read_callback, void* callback_opaque, mz_uint64 size_to_add, + const MZ_TIME_T *pFile_time, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, const char *user_extra_data_local, mz_uint user_extra_data_local_len, + const char *user_extra_data_central, mz_uint user_extra_data_central_len); + +#ifndef MINIZ_NO_STDIO +/* Adds the contents of a disk file to an archive. This function also records the disk file's modified time into the archive. */ +/* level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. */ +mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); + +/* Like mz_zip_writer_add_file(), except the file data is read from the specified FILE stream. */ +mz_bool mz_zip_writer_add_cfile(mz_zip_archive *pZip, const char *pArchive_name, MZ_FILE *pSrc_file, mz_uint64 size_to_add, + const MZ_TIME_T *pFile_time, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, const char *user_extra_data_local, mz_uint user_extra_data_local_len, + const char *user_extra_data_central, mz_uint user_extra_data_central_len); +#endif + +/* Adds a file to an archive by fully cloning the data from another archive. */ +/* This function fully clones the source file's compressed data (no recompression), along with its full filename, extra data (it may add or modify the zip64 local header extra data field), and the optional descriptor following the compressed data. */ +mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint src_file_index); + +/* Finalizes the archive by writing the central directory records followed by the end of central directory record. */ +/* After an archive is finalized, the only valid call on the mz_zip_archive struct is mz_zip_writer_end(). */ +/* An archive must be manually finalized by calling this function for it to be valid. */ +mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip); + +/* Finalizes a heap archive, returning a poiner to the heap block and its size. */ +/* The heap block will be allocated using the mz_zip_archive's alloc/realloc callbacks. */ +mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **ppBuf, size_t *pSize); + +/* Ends archive writing, freeing all allocations, and closing the output file if mz_zip_writer_init_file() was used. */ +/* Note for the archive to be valid, it *must* have been finalized before ending (this function will not do it for you). */ +mz_bool mz_zip_writer_end(mz_zip_archive *pZip); + +/* -------- Misc. high-level helper functions: */ + +/* mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically) appends a memory blob to a ZIP archive. */ +/* Note this is NOT a fully safe operation. If it crashes or dies in some way your archive can be left in a screwed up state (without a central directory). */ +/* level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. */ +/* TODO: Perhaps add an option to leave the existing central dir in place in case the add dies? We could then truncate the file (so the old central dir would be at the end) if something goes wrong. */ +mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); +mz_bool mz_zip_add_mem_to_archive_file_in_place_v2(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_zip_error *pErr); + +/* Reads a single file from an archive into a heap block. */ +/* If pComment is not NULL, only the file with the specified comment will be extracted. */ +/* Returns NULL on failure. */ +void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint flags); +void *mz_zip_extract_archive_file_to_heap_v2(const char *pZip_filename, const char *pArchive_name, const char *pComment, size_t *pSize, mz_uint flags, mz_zip_error *pErr); + +#endif /* #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS */ + +#ifdef __cplusplus +} +#endif + +#endif /* MINIZ_NO_ARCHIVE_APIS */ diff --git a/Frameworks/vgmstream/vgmstream/src/coding/coding.h b/Frameworks/vgmstream/vgmstream/src/coding/coding.h index 5a4c00fc5..a2158fc74 100644 --- a/Frameworks/vgmstream/vgmstream/src/coding/coding.h +++ b/Frameworks/vgmstream/vgmstream/src/coding/coding.h @@ -35,7 +35,7 @@ void decode_apple_ima4(VGMSTREAMCHANNEL * stream, sample_t * outbuf, int channel void decode_fsb_ima(VGMSTREAM * vgmstream, VGMSTREAMCHANNEL * stream, sample_t * outbuf, int channelspacing, int32_t first_sample, int32_t samples_to_do, int channel); void decode_wwise_ima(VGMSTREAM * vgmstream, VGMSTREAMCHANNEL * stream, sample_t * outbuf, int channelspacing, int32_t first_sample, int32_t samples_to_do, int channel); void decode_awc_ima(VGMSTREAMCHANNEL * stream, sample_t * outbuf, int channelspacing, int32_t first_sample, int32_t samples_to_do); -void decode_ubi_ima(VGMSTREAMCHANNEL * stream, sample_t * outbuf, int channelspacing, int32_t first_sample, int32_t samples_to_do, int channel); +void decode_ubi_ima(VGMSTREAMCHANNEL * stream, sample_t * outbuf, int channelspacing, int32_t first_sample, int32_t samples_to_do, int channel, int codec_config); void decode_h4m_ima(VGMSTREAMCHANNEL * stream, sample_t * outbuf, int channelspacing, int32_t first_sample, int32_t samples_to_do, int channel, uint16_t frame_format); size_t ima_bytes_to_samples(size_t bytes, int channels); size_t ms_ima_bytes_to_samples(size_t bytes, int block_align, int channels); @@ -167,6 +167,7 @@ void decode_fadpcm(VGMSTREAMCHANNEL *stream, sample_t *outbuf, int channelspacin /* asf_decoder */ void decode_asf(VGMSTREAMCHANNEL *stream, sample_t *outbuf, int channelspacing, int32_t first_sample, int32_t samples_to_do); +int32_t asf_bytes_to_samples(size_t bytes, int channels); /* dsa_decoder */ void decode_dsa(VGMSTREAMCHANNEL *stream, sample_t *outbuf, int channelspacing, int32_t first_sample, int32_t samples_to_do); @@ -178,7 +179,13 @@ void decode_xmd(VGMSTREAMCHANNEL *stream, sample_t *outbuf, int channelspacing, void decode_derf(VGMSTREAMCHANNEL * stream, sample * outbuf, int channelspacing, int32_t first_sample, int32_t samples_to_do); /* circus_decoder */ -void decode_circus_adpcm(VGMSTREAMCHANNEL * stream, sample * outbuf, int channelspacing, int32_t first_sample, int32_t samples_to_do); +typedef struct circus_codec_data circus_codec_data; +circus_codec_data* init_circus_vq(STREAMFILE* sf, off_t start, uint8_t codec, uint8_t flags); +void decode_circus_vq(circus_codec_data* data, sample_t* outbuf, int32_t samples_to_do, int channels); +void reset_circus_vq(circus_codec_data* data); +void seek_circus_vq(circus_codec_data* data, int32_t num_sample); +void free_circus_vq(circus_codec_data* data); +void decode_circus_adpcm(VGMSTREAMCHANNEL* stream, sample_t* outbuf, int channelspacing, int32_t first_sample, int32_t samples_to_do); /* oki_decoder */ void decode_pcfx(VGMSTREAMCHANNEL * stream, sample_t * outbuf, int channelspacing, int32_t first_sample, int32_t samples_to_do, int mode); diff --git a/Frameworks/vgmstream/vgmstream/src/coding/ima_decoder.c b/Frameworks/vgmstream/vgmstream/src/coding/ima_decoder.c index ee8f4c509..7825db657 100644 --- a/Frameworks/vgmstream/vgmstream/src/coding/ima_decoder.c +++ b/Frameworks/vgmstream/vgmstream/src/coding/ima_decoder.c @@ -1009,8 +1009,9 @@ void decode_awc_ima(VGMSTREAMCHANNEL * stream, sample_t * outbuf, int channelspa /* DVI stereo/mono with some mini header and sample output */ -void decode_ubi_ima(VGMSTREAMCHANNEL * stream, sample_t * outbuf, int channelspacing, int32_t first_sample, int32_t samples_to_do, int channel) { +void decode_ubi_ima(VGMSTREAMCHANNEL * stream, sample_t * outbuf, int channelspacing, int32_t first_sample, int32_t samples_to_do, int channel, int codec_config) { int i, sample_count = 0; + int has_header = (codec_config & 0x80) == 0; int32_t hist1 = stream->adpcm_history1_32; int step_index = stream->adpcm_step_index; @@ -1018,7 +1019,7 @@ void decode_ubi_ima(VGMSTREAMCHANNEL * stream, sample_t * outbuf, int channelspa //internal interleave //header in the beginning of the stream - if (stream->channel_start_offset == stream->offset) { + if (has_header && stream->channel_start_offset == stream->offset) { int version, big_endian, header_samples, max_samples_to_do; int16_t (*read_16bit)(off_t,STREAMFILE*) = NULL; off_t offset = stream->offset; @@ -1051,8 +1052,12 @@ void decode_ubi_ima(VGMSTREAMCHANNEL * stream, sample_t * outbuf, int channelspa } } + if (has_header) { + first_sample -= 10; //todo fix hack (needed to adjust nibble offset below) + } - first_sample -= 10; //todo fix hack (needed to adjust nibble offset below) + if (step_index < 0) step_index=0; + if (step_index > 88) step_index=88; for (i = first_sample; i < first_sample + samples_to_do; i++, sample_count += channelspacing) { off_t byte_offset = channelspacing == 1 ? diff --git a/Frameworks/vgmstream/vgmstream/src/coding/psv_decoder.c b/Frameworks/vgmstream/vgmstream/src/coding/psv_decoder.c index 6daf057a6..bdb590ab9 100644 --- a/Frameworks/vgmstream/vgmstream/src/coding/psv_decoder.c +++ b/Frameworks/vgmstream/vgmstream/src/coding/psv_decoder.c @@ -173,25 +173,25 @@ void decode_hevag(VGMSTREAMCHANNEL * stream, sample_t * outbuf, int channelspaci if (shift_factor > 12) shift_factor = 9; /* ? */ + shift_factor = 20 - shift_factor; /* decode nibbles */ for (i = first_sample; i < first_sample + samples_to_do; i++) { - int32_t sample = 0, scale = 0; + int32_t sample = 0; if (flag < 0x07) { /* with flag 0x07 decoded sample must be 0 */ uint8_t nibbles = frame[0x02 + i/2]; - scale = i&1 ? /* low nibble first */ + sample = (i&1 ? /* low nibble first */ get_high_nibble_signed(nibbles): - get_low_nibble_signed(nibbles); - sample = (hist1 * hevag_coefs[coef_index][0] + - hist2 * hevag_coefs[coef_index][1] + - hist3 * hevag_coefs[coef_index][2] + - hist4 * hevag_coefs[coef_index][3] ) / 32; - sample = (sample + (scale << (20 - shift_factor)) + 128) >> 8; - sample = clamp16(sample); + get_low_nibble_signed(nibbles)) << shift_factor; /*scale*/ + sample = ((hist1 * hevag_coefs[coef_index][0] + + hist2 * hevag_coefs[coef_index][1] + + hist3 * hevag_coefs[coef_index][2] + + hist4 * hevag_coefs[coef_index][3]) >> 5) + sample; + sample >>= 8; } - outbuf[sample_count] = sample; + outbuf[sample_count] = clamp16(sample); /*clamping*/ sample_count += channelspacing; hist4 = hist3; diff --git a/Frameworks/vgmstream/vgmstream/src/coding/psx_decoder.c b/Frameworks/vgmstream/vgmstream/src/coding/psx_decoder.c index d70f06127..00bb28107 100644 --- a/Frameworks/vgmstream/vgmstream/src/coding/psx_decoder.c +++ b/Frameworks/vgmstream/vgmstream/src/coding/psx_decoder.c @@ -93,22 +93,22 @@ void decode_psx(VGMSTREAMCHANNEL* stream, sample_t* outbuf, int channelspacing, VGM_ASSERT_ONCE(flag > 7,"PS-ADPCM: unknown flag at %x\n", (uint32_t)frame_offset); /* meta should use PSX-badflags */ + shift_factor = 20 - shift_factor; /* decode nibbles */ for (i = first_sample; i < first_sample + samples_to_do; i++) { int32_t sample = 0; if (flag < 0x07) { /* with flag 0x07 decoded sample must be 0 */ uint8_t nibbles = frame[0x02 + i/2]; - - sample = i&1 ? /* low nibble first */ - (nibbles >> 4) & 0x0f : - (nibbles >> 0) & 0x0f; - sample = (int16_t)((sample << 12) & 0xf000) >> shift_factor; /* 16b sign extend + scale */ - sample = (int32_t)(sample + ps_adpcm_coefs_f[coef_index][0]*hist1 + ps_adpcm_coefs_f[coef_index][1]*hist2); - sample = clamp16(sample); + + sample = (i&1 ? /* low nibble first */ + get_high_nibble_signed(nibbles): + get_low_nibble_signed(nibbles)) << shift_factor; /*scale*/ + sample = sample + (int32_t)((ps_adpcm_coefs_f[coef_index][0]*hist1 + ps_adpcm_coefs_f[coef_index][1]*hist2) * 256.0f); + sample >>= 8; } - outbuf[sample_count] = sample; + outbuf[sample_count] = clamp16(sample); /*clamping*/ sample_count += channelspacing; hist2 = hist1; @@ -192,7 +192,6 @@ void decode_psx_pivotal(VGMSTREAMCHANNEL * stream, sample_t * outbuf, int channe uint8_t coef_index, shift_factor; int32_t hist1 = stream->adpcm_history1_32; int32_t hist2 = stream->adpcm_history2_32; - float scale; /* external interleave (variable size), mono */ @@ -213,21 +212,19 @@ void decode_psx_pivotal(VGMSTREAMCHANNEL * stream, sample_t * outbuf, int channe if (shift_factor > 12) /* same */ shift_factor = 12; - scale = (float)(1.0 / (double)(1 << shift_factor)); - - + shift_factor = 20 - shift_factor; /* decode nibbles */ for (i = first_sample; i < first_sample + samples_to_do; i++) { int32_t sample = 0; uint8_t nibbles = frame[0x01 + i/2]; - sample = !(i&1) ? /* low nibble first */ - (nibbles >> 0) & 0x0f : - (nibbles >> 4) & 0x0f; - sample = (int16_t)((sample << 12) & 0xf000); /* 16b sign extend + default scale */ - sample = sample*scale + ps_adpcm_coefs_f[coef_index][0]*hist1 + ps_adpcm_coefs_f[coef_index][1]*hist2; /* actually substracts negative coefs but whatevs */ + sample = (i&1 ? /* low nibble first */ + get_high_nibble_signed(nibbles): + get_low_nibble_signed(nibbles)) << shift_factor; /*scale*/ + sample = sample + (int32_t)((ps_adpcm_coefs_f[coef_index][0]*hist1 + ps_adpcm_coefs_f[coef_index][1]*hist2) * 256.0f); /* actually substracts negative coefs but whatevs */ + sample >>= 8; - outbuf[sample_count] = clamp16(sample); + outbuf[sample_count] = clamp16(sample); /*clamping*/ sample_count += channelspacing; hist2 = hist1; diff --git a/Frameworks/vgmstream/vgmstream/src/coding/vorbis_custom_utils_vid1.c b/Frameworks/vgmstream/vgmstream/src/coding/vorbis_custom_utils_vid1.c index 8dff6fdce..ec869db33 100644 --- a/Frameworks/vgmstream/vgmstream/src/coding/vorbis_custom_utils_vid1.c +++ b/Frameworks/vgmstream/vgmstream/src/coding/vorbis_custom_utils_vid1.c @@ -1,145 +1,152 @@ -#include "vorbis_custom_decoder.h" - -#ifdef VGM_USE_VORBIS -#include - - -/* **************************************************************************** */ -/* DEFS */ -/* **************************************************************************** */ - -static int get_packet_header(STREAMFILE *streamFile, off_t *offset, size_t *size); -static int build_header_comment(uint8_t * buf, size_t bufsize); - - -/* **************************************************************************** */ -/* EXTERNAL API */ -/* **************************************************************************** */ - -/** - * VID1 removes the Ogg layer and uses a block layout with custom packet headers. - * - * Info from hcs's vid1_2ogg: https://github.com/hcs64/vgm_ripping/tree/master/demux/vid1_2ogg - */ -int vorbis_custom_setup_init_vid1(STREAMFILE *streamFile, off_t start_offset, vorbis_custom_codec_data *data) { - off_t offset = start_offset; - size_t packet_size = 0; - - /* read header packets (id/setup), each with an VID1 header */ - - /* normal identificacion packet */ - get_packet_header(streamFile, &offset, &packet_size); - if (packet_size > data->buffer_size) goto fail; - data->op.bytes = read_streamfile(data->buffer,offset,packet_size, streamFile); - if (vorbis_synthesis_headerin(&data->vi, &data->vc, &data->op) != 0) goto fail; /* parse identification header */ - offset += packet_size; - - /* generate comment packet */ - data->op.bytes = build_header_comment(data->buffer, data->buffer_size); - if (!data->op.bytes) goto fail; - if (vorbis_synthesis_headerin(&data->vi, &data->vc, &data->op) !=0 ) goto fail; /* parse comment header */ - - /* normal setup packet */ - get_packet_header(streamFile, &offset, &packet_size); - if (packet_size > data->buffer_size) goto fail; - data->op.bytes = read_streamfile(data->buffer,offset,packet_size, streamFile); - if (vorbis_synthesis_headerin(&data->vi, &data->vc, &data->op) != 0) goto fail; /* parse setup header */ - offset += packet_size; - - return 1; - -fail: - return 0; -} - - -int vorbis_custom_parse_packet_vid1(VGMSTREAMCHANNEL *stream, vorbis_custom_codec_data *data) { - size_t bytes; - - - /* test block start */ - if (read_32bitBE(stream->offset + 0x00,stream->streamfile) == 0x4652414D && /* "FRAM" */ - read_32bitBE(stream->offset + 0x20,stream->streamfile) == 0x41554444) { /* "AUDD" */ - data->block_offset = stream->offset; - data->block_size = read_32bitBE(stream->offset + 0x2c,stream->streamfile); - stream->offset += 0x34; /* actual start, rest is chunk sizes and maybe granule info */ - } - - - /* get packet info the VID1 header */ - get_packet_header(stream->streamfile, &stream->offset, (uint32_t*)&data->op.bytes); - if (data->op.bytes == 0 || data->op.bytes > data->buffer_size) goto fail; /* EOF or end padding */ - - /* read raw block */ - bytes = read_streamfile(data->buffer,stream->offset, data->op.bytes,stream->streamfile); - stream->offset += data->op.bytes; - if (bytes != data->op.bytes) goto fail; /* wrong packet? */ - - //todo: sometimes there are short packets like 01be590000 and Vorbis complains and skips, no idea - - /* test block end (weird size calc but seems ok) */ - if ((stream->offset - (data->block_offset + 0x34)) >= (data->block_size - 0x06)) { - stream->offset = data->block_offset + read_32bitBE(data->block_offset + 0x04,stream->streamfile); - } - - return 1; - -fail: - return 0; -} - - -/* **************************************************************************** */ -/* INTERNAL HELPERS */ -/* **************************************************************************** */ - -static int build_header_comment(uint8_t * buf, size_t bufsize) { - int bytes = 0x19; - - if (bytes > bufsize) return 0; - - put_8bit (buf+0x00, 0x03); /* packet_type (comments) */ - memcpy (buf+0x01, "vorbis", 6); /* id */ - put_32bitLE(buf+0x07, 0x09); /* vendor_length */ - memcpy (buf+0x0b, "vgmstream", 9); /* vendor_string */ - put_32bitLE(buf+0x14, 0x00); /* user_comment_list_length */ - put_8bit (buf+0x18, 0x01); /* framing_flag (fixed) */ - - return bytes; -} - -/* read header in Vorbis bitpacking format */ -static int get_packet_header(STREAMFILE *streamFile, off_t *offset, size_t *size) { - uint8_t ibuf[0x04]; /* header buffer */ - size_t ibufsize = 0x04; /* header ~max */ - vgm_bitstream ib = {0}; - uint32_t size_bits; - - - if (read_streamfile(ibuf,(*offset),ibufsize, streamFile) != ibufsize) - goto fail; - ib.buf = ibuf; - ib.bufsize = ibufsize; - ib.b_off = 0; - ib.mode = BITSTREAM_VORBIS; - - /* read using Vorbis weird LSF */ - r_bits(&ib, 4,&size_bits); - r_bits(&ib, (size_bits+1),(uint32_t*)size); - - /* special meaning, seen in silent frames */ - if (size_bits == 0 && *size == 0 && (uint8_t)read_8bit(*offset, streamFile)==0x80) { - *size = 0x01; - } - - /* pad and convert to byte offset */ - if (ib.b_off % 8) - ib.b_off += 8 - (ib.b_off % 8); - *offset += (ib.b_off/8); - - return 1; -fail: - return 0; -} - -#endif +#include "vorbis_custom_decoder.h" + +#ifdef VGM_USE_VORBIS +#include + + +/* **************************************************************************** */ +/* DEFS */ +/* **************************************************************************** */ + +static int get_packet_header(STREAMFILE *streamFile, off_t *offset, size_t *size); +static int build_header_comment(uint8_t * buf, size_t bufsize); + + +/* **************************************************************************** */ +/* EXTERNAL API */ +/* **************************************************************************** */ + +/** + * VID1 removes the Ogg layer and uses a block layout with custom packet headers. + * + * Info from hcs's vid1_2ogg: https://github.com/hcs64/vgm_ripping/tree/master/demux/vid1_2ogg + */ +int vorbis_custom_setup_init_vid1(STREAMFILE *streamFile, off_t start_offset, vorbis_custom_codec_data *data) { + off_t offset = start_offset; + size_t packet_size = 0; + + /* read header packets (id/setup), each with an VID1 header */ + + /* normal identificacion packet */ + get_packet_header(streamFile, &offset, &packet_size); + if (packet_size > data->buffer_size) goto fail; + data->op.bytes = read_streamfile(data->buffer,offset,packet_size, streamFile); + if (vorbis_synthesis_headerin(&data->vi, &data->vc, &data->op) != 0) goto fail; /* parse identification header */ + offset += packet_size; + + /* generate comment packet */ + data->op.bytes = build_header_comment(data->buffer, data->buffer_size); + if (!data->op.bytes) goto fail; + if (vorbis_synthesis_headerin(&data->vi, &data->vc, &data->op) !=0 ) goto fail; /* parse comment header */ + + /* normal setup packet */ + get_packet_header(streamFile, &offset, &packet_size); + if (packet_size > data->buffer_size) goto fail; + data->op.bytes = read_streamfile(data->buffer,offset,packet_size, streamFile); + if (vorbis_synthesis_headerin(&data->vi, &data->vc, &data->op) != 0) goto fail; /* parse setup header */ + offset += packet_size; + + return 1; + +fail: + return 0; +} + + +int vorbis_custom_parse_packet_vid1(VGMSTREAMCHANNEL *stream, vorbis_custom_codec_data *data) { + size_t bytes; + + + /* test block start */ + if (read_32bitBE(stream->offset + 0x00,stream->streamfile) == 0x4652414D) { /* "FRAM" */ + stream->offset += 0x20; + + if (read_32bitBE(stream->offset + 0x00,stream->streamfile) == 0x56494444) { /* "VIDD"*/ + stream->offset += read_32bitBE(stream->offset + 0x04, stream->streamfile); + } + + if (read_32bitBE(stream->offset + 0x00,stream->streamfile) == 0x41554444) { /* "AUDD" */ + data->block_offset = stream->offset; + data->block_size = read_32bitBE(stream->offset + 0x0c,stream->streamfile); + stream->offset += 0x14; /* actual start, rest is chunk sizes and maybe granule info */ + } + } + + + /* get packet info the VID1 header */ + get_packet_header(stream->streamfile, &stream->offset, (uint32_t*)&data->op.bytes); + if (data->op.bytes == 0 || data->op.bytes > data->buffer_size) goto fail; /* EOF or end padding */ + + /* read raw block */ + bytes = read_streamfile(data->buffer,stream->offset, data->op.bytes,stream->streamfile); + stream->offset += data->op.bytes; + if (bytes != data->op.bytes) goto fail; /* wrong packet? */ + + //todo: sometimes there are short packets like 01be590000 and Vorbis complains and skips, no idea + + /* test block end (weird size calc but seems ok) */ + if ((stream->offset - (data->block_offset + 0x14)) >= (data->block_size - 0x06)) { + stream->offset = data->block_offset + read_32bitBE(data->block_offset + 0x04,stream->streamfile); + } + + return 1; + +fail: + return 0; +} + + +/* **************************************************************************** */ +/* INTERNAL HELPERS */ +/* **************************************************************************** */ + +static int build_header_comment(uint8_t * buf, size_t bufsize) { + int bytes = 0x19; + + if (bytes > bufsize) return 0; + + put_8bit (buf+0x00, 0x03); /* packet_type (comments) */ + memcpy (buf+0x01, "vorbis", 6); /* id */ + put_32bitLE(buf+0x07, 0x09); /* vendor_length */ + memcpy (buf+0x0b, "vgmstream", 9); /* vendor_string */ + put_32bitLE(buf+0x14, 0x00); /* user_comment_list_length */ + put_8bit (buf+0x18, 0x01); /* framing_flag (fixed) */ + + return bytes; +} + +/* read header in Vorbis bitpacking format */ +static int get_packet_header(STREAMFILE *streamFile, off_t *offset, size_t *size) { + uint8_t ibuf[0x04]; /* header buffer */ + size_t ibufsize = 0x04; /* header ~max */ + vgm_bitstream ib = {0}; + uint32_t size_bits; + + + if (read_streamfile(ibuf,(*offset),ibufsize, streamFile) != ibufsize) + goto fail; + ib.buf = ibuf; + ib.bufsize = ibufsize; + ib.b_off = 0; + ib.mode = BITSTREAM_VORBIS; + + /* read using Vorbis weird LSF */ + r_bits(&ib, 4,&size_bits); + r_bits(&ib, (size_bits+1),(uint32_t*)size); + + /* special meaning, seen in silent frames */ + if (size_bits == 0 && *size == 0 && (uint8_t)read_8bit(*offset, streamFile)==0x80) { + *size = 0x01; + } + + /* pad and convert to byte offset */ + if (ib.b_off % 8) + ib.b_off += 8 - (ib.b_off % 8); + *offset += (ib.b_off/8); + + return 1; +fail: + return 0; +} + +#endif diff --git a/Frameworks/vgmstream/vgmstream/src/formats.c b/Frameworks/vgmstream/vgmstream/src/formats.c index 0a2119113..32319cb51 100644 --- a/Frameworks/vgmstream/vgmstream/src/formats.c +++ b/Frameworks/vgmstream/vgmstream/src/formats.c @@ -64,6 +64,7 @@ static const char* extension_list[] = { "akb", "al", "al2", + "ams", //txth/reserved [Super Dragon Ball Z (PS2) ELF names] "amts", //fake extension/header id for .stm (renamed? to be removed?) "ao", "apc", @@ -297,6 +298,8 @@ static const char* extension_list[] = { "mihb", "mnstr", "mogg", + //"m4a", //common + //"m4v", //common //"mp+", //common [Moonshine Runners (PC)] //"mp2", //common //"mp3", //common @@ -450,6 +453,7 @@ static const char* extension_list[] = { "snr", "sns", "snu", + "snz", //txth/reserved [Killzone HD (PS3)] "sod", "son", "spd", @@ -458,6 +462,7 @@ static const char* extension_list[] = { "spsd", "spw", "ss2", + "ssd", //txth/reserved [Zack & Wiki (Wii)] "ssm", "sss", "ster", @@ -514,6 +519,7 @@ static const char* extension_list[] = { "vgm", //txth/reserved [Maximo (PS2)] "vgs", "vgv", + "vid", "vig", "vis", "vms", @@ -608,6 +614,8 @@ static const char* common_extension_list[] = { "aiff", //common "bin", //common "flac", //common + "m4a", //common + "m4v", //common "mp+", //common [Moonshine Runners (PC)] "mp2", //common "mp3", //common @@ -719,7 +727,6 @@ static const coding_info coding_info_list[] = { {coding_REF_IMA, "Reflections 4-bit IMA ADPCM"}, {coding_AWC_IMA, "Rockstar AWC 4-bit IMA ADPCM"}, {coding_UBI_IMA, "Ubisoft 4-bit IMA ADPCM"}, - {coding_H4M_IMA, "Hudson HVQM4 4-bit IMA ADPCM"}, {coding_MSADPCM, "Microsoft 4-bit ADPCM"}, @@ -758,7 +765,7 @@ static const coding_info coding_info_list[] = { {coding_UBI_ADPCM, "Ubisoft 4/6-bit ADPCM"}, {coding_EA_MT, "Electronic Arts MicroTalk"}, - + {coding_CIRCUS_VQ, "Circus VQ"}, {coding_RELIC, "Relic Codec"}, {coding_CRI_HCA, "CRI HCA"}, @@ -791,6 +798,9 @@ static const coding_info coding_info_list[] = { #ifdef VGM_USE_FFMPEG {coding_FFmpeg, "FFmpeg"}, #endif +#ifdef VGM_USE_FDKAAC + {coding_MP4_AAC, "MPEG-4 AAC"}, +#endif }; static const layout_info layout_info_list[] = { @@ -838,6 +848,8 @@ static const layout_info layout_info_list[] = { {layout_blocked_h4m, "blocked (H4M)"}, {layout_blocked_xa_aiff, "blocked (XA AIFF)"}, {layout_blocked_vs_square, "blocked (Square VS)"}, + {layout_blocked_vid1, "blocked (VID1)"}, + {layout_blocked_ubi_sce, "blocked (Ubi SCE)"}, }; static const meta_info meta_info_list[] = { @@ -1168,7 +1180,7 @@ static const meta_info meta_info_list[] = { {meta_VXN, "Gameloft VXN header"}, {meta_EA_SNR_SNS, "Electronic Arts SNR+SNS header"}, {meta_EA_SPS, "Electronic Arts SPS header"}, - {meta_NGC_VID1, "Neversoft VID1 header"}, + {meta_VID1, "Factor 5 VID1 header"}, {meta_PC_FLX, "Ultima IX .FLX header"}, {meta_MOGG, "Harmonix Music Systems MOGG Vorbis"}, {meta_OGG_VORBIS, "Ogg Vorbis header"}, @@ -1272,6 +1284,7 @@ static const meta_info meta_info_list[] = { {meta_TGC, "Tiger Game.com .4 header"}, {meta_KWB, "Koei Tecmo WaveBank header"}, {meta_LRMD, "Sony LRMD header"}, + {meta_WWISE_FX, "Audiokinetic Wwise FX header"}, }; diff --git a/Frameworks/vgmstream/vgmstream/src/layout/blocked.c b/Frameworks/vgmstream/vgmstream/src/layout/blocked.c index 4bfe92725..323353994 100644 --- a/Frameworks/vgmstream/vgmstream/src/layout/blocked.c +++ b/Frameworks/vgmstream/vgmstream/src/layout/blocked.c @@ -205,6 +205,12 @@ void block_update(off_t block_offset, VGMSTREAM * vgmstream) { case layout_blocked_vs_square: block_update_vs_square(block_offset,vgmstream); break; + case layout_blocked_vid1: + block_update_vid1(block_offset,vgmstream); + break; + case layout_blocked_ubi_sce: + block_update_ubi_sce(block_offset,vgmstream); + break; default: /* not a blocked layout */ break; } diff --git a/Frameworks/vgmstream/vgmstream/src/layout/blocked_ubi_sce.c b/Frameworks/vgmstream/vgmstream/src/layout/blocked_ubi_sce.c new file mode 100644 index 000000000..7c848fd9a --- /dev/null +++ b/Frameworks/vgmstream/vgmstream/src/layout/blocked_ubi_sce.c @@ -0,0 +1,57 @@ +#include "layout.h" +#include "../vgmstream.h" + +/* weird mix of Ubi ADPCM format with Ubi IMA, found in Splinter Cell Essentials (PSP) */ +void block_update_ubi_sce(off_t block_offset, VGMSTREAM* vgmstream) { + STREAMFILE* sf = vgmstream->ch[0].streamfile; + int i, channels; + size_t header_size, frame_size, subframe_size, padding_size; + + /* format mimics Ubi ADPCM's: + * - 0x34/38 header with frame size (ex. 0x600), pre-read in meta + * xN frames: + * - 0x34 channel header per channel, with ADPCM config + * - subframe (ex. 0x300) + padding byte + * - subframe (ex. 0x300) + padding byte + * + * to skip the padding byte we'll detect subframes using codec_config as a counter + * (higher bit has a special meaning) + */ + + vgmstream->codec_config |= 0x80; /* flag for decoder, ugly I know */ + + if ((vgmstream->codec_config & 1) == 0) { + header_size = 0x34; /* read header in first subframe */ + } + else { + header_size = 0x00; + } + vgmstream->codec_config ^= 1; /* swap counter bit */ + + channels = vgmstream->channels; + frame_size = vgmstream->full_block_size; + subframe_size = frame_size / 2; + padding_size = 0x01; + + vgmstream->current_block_offset = block_offset; + vgmstream->current_block_size = subframe_size; + vgmstream->next_block_offset = block_offset + header_size * vgmstream->channels + subframe_size + padding_size; + + for (i = 0; i < vgmstream->channels; i++) { + vgmstream->ch[i].offset = block_offset + header_size * channels; + + if (header_size > 0) { + vgmstream->ch[i].adpcm_step_index = read_32bitLE(block_offset + header_size * i + 0x04, sf); + vgmstream->ch[i].adpcm_history1_32 = read_32bitLE(block_offset + header_size * i + 0x08, sf); + + /* TODO figure out + * First step seems to always be a special value for the decoder, unsure of meaning. + * 0 = too quiet and max = 88 = waveform starts a bit off and clicky. First hist is usually +-1, + * other frames look, fine not sure what are they aiming for. + */ + if (vgmstream->ch[i].adpcm_step_index == 0x500) { + vgmstream->ch[i].adpcm_step_index = 88; + } + } + } +} diff --git a/Frameworks/vgmstream/vgmstream/src/layout/blocked_vid1.c b/Frameworks/vgmstream/vgmstream/src/layout/blocked_vid1.c new file mode 100644 index 000000000..12a6e09cc --- /dev/null +++ b/Frameworks/vgmstream/vgmstream/src/layout/blocked_vid1.c @@ -0,0 +1,61 @@ +#include "layout.h" +#include "../vgmstream.h" + +/* blocks with video and audio */ +void block_update_vid1(off_t block_offset, VGMSTREAM* vgmstream) { + STREAMFILE* sf = vgmstream->ch[0].streamfile; + int ch; + int channels = vgmstream->channels; + uint32_t (*read_u32)(off_t,STREAMFILE*) = vgmstream->codec_endian ? read_u32be : read_u32le; + size_t audd_size = 0, data_size = 0; + + + if (read_u32(block_offset + 0x00, sf) != 0x4652414D) { /* "FRAM" */ + /* signal EOF, as files ends with padding */ + vgmstream->current_block_offset = block_offset; + vgmstream->next_block_offset = block_offset; + vgmstream->current_block_size = 0; + vgmstream->current_block_samples = -1; + return; + } + + block_offset += 0x20; + if (read_u32(block_offset + 0x00, sf) == 0x56494444) { /* "VIDD"*/ + block_offset += read_u32(block_offset + 0x04, sf); + } + + if (read_u32(block_offset + 0x00, sf) == 0x41554444) { /* "AUDD" */ + audd_size = read_u32(block_offset + 0x04, sf); + data_size = read_u32(block_offset + 0x0c, sf); + } + + vgmstream->current_block_offset = block_offset; + vgmstream->next_block_offset = block_offset + audd_size; + vgmstream->current_block_size = (data_size / channels); + vgmstream->current_block_samples = 0; + + for (ch = 0; ch < vgmstream->channels; ch++) { + off_t interleave, head_size; + + switch(vgmstream->coding_type) { + case coding_PCM16_int: + interleave = 0x02 * ch; + head_size = 0x10; + break; + case coding_XBOX_IMA: + interleave = 0x00; + head_size = 0x10; + break; + case coding_NGC_DSP: + interleave = (data_size / channels) * ch; + head_size = 0x20; + break; + default: + interleave = 0; + head_size = 0x10; + break; + } + + vgmstream->ch[ch].offset = block_offset + head_size + interleave; + } +} diff --git a/Frameworks/vgmstream/vgmstream/src/layout/layout.h b/Frameworks/vgmstream/vgmstream/src/layout/layout.h index e9003c8f3..488f3b191 100644 --- a/Frameworks/vgmstream/vgmstream/src/layout/layout.h +++ b/Frameworks/vgmstream/vgmstream/src/layout/layout.h @@ -46,6 +46,8 @@ void block_update_sthd(off_t block_offset, VGMSTREAM * vgmstream); void block_update_h4m(off_t block_offset, VGMSTREAM * vgmstream); void block_update_xa_aiff(off_t block_offset, VGMSTREAM * vgmstream); void block_update_vs_square(off_t block_offset, VGMSTREAM * vgmstream); +void block_update_vid1(off_t block_offset, VGMSTREAM* vgmstream); +void block_update_ubi_sce(off_t block_offset, VGMSTREAM* vgmstream); /* other layouts */ void render_vgmstream_interleave(sample_t * buffer, int32_t sample_count, VGMSTREAM * vgmstream); diff --git a/Frameworks/vgmstream/vgmstream/src/meta/Cstr.c b/Frameworks/vgmstream/vgmstream/src/meta/Cstr.c index c625de84a..ecbd05c15 100644 --- a/Frameworks/vgmstream/vgmstream/src/meta/Cstr.c +++ b/Frameworks/vgmstream/vgmstream/src/meta/Cstr.c @@ -1,299 +1,109 @@ #include "meta.h" #include "../coding/coding.h" -#include "../util.h" -/* .dsp w/ Cstr header, seen in Star Fox Assault and Donkey Konga */ -VGMSTREAM * init_vgmstream_cstr(STREAMFILE *streamFile) { + +/* Cstr - from Namco NuSound v1 games [Mr. Driller (GC), Star Fox Assault (GC), Donkey Konga (GC)] */ +VGMSTREAM * init_vgmstream_cstr(STREAMFILE* sf) { VGMSTREAM * vgmstream = NULL; - char filename[PATH_LIMIT]; - - int loop_flag; off_t start_offset; - off_t first_data; - off_t loop_offset; - size_t interleave; - int loop_adjust; - int double_loop_end = 0; + size_t interleave, first_skip; + int loop_flag, channels, sample_rate; + int loop_start, loop_end, num_samples, num_nibbles; - /* check extension, case insensitive */ - streamFile->get_name(streamFile,filename,sizeof(filename)); - if (strcasecmp("dsp",filename_extension(filename))) goto fail; - /* check header */ - if ((uint32_t)read_32bitBE(0,streamFile)!=0x43737472) /* "Cstr" */ - goto fail; -#ifdef DEBUG - fprintf(stderr,"header ok\n"); -#endif - - if (read_8bit(0x1b,streamFile)==1) { - /* mono version, much simpler to handle */ - /* Only seen in R Racing Evolution radio sfx */ - - start_offset = 0x80; - loop_flag = read_16bitBE(0x2c,streamFile); - - /* check initial predictor/scale */ - if (read_16bitBE(0x5e,streamFile) != (uint8_t)read_8bit(start_offset,streamFile)) - goto fail; - - /* check type==0 and gain==0 */ - if (read_16bitBE(0x2e,streamFile) || read_16bitBE(0x5c,streamFile)) - goto fail; - - loop_offset = start_offset+read_32bitBE(0x10,streamFile); - if (loop_flag) { - if (read_16bitBE(0x64,streamFile) != (uint8_t)read_8bit(loop_offset,streamFile)) goto fail; - } - - /* build the VGMSTREAM */ - - vgmstream = allocate_vgmstream(1,loop_flag); - if (!vgmstream) goto fail; - - /* fill in the vital statistics */ - vgmstream->sample_rate = read_32bitBE(0x28,streamFile); - vgmstream->num_samples = read_32bitBE(0x20,streamFile); - - if (loop_flag) { - vgmstream->loop_start_sample = dsp_nibbles_to_samples( - read_32bitBE(0x30,streamFile)); - vgmstream->loop_end_sample = dsp_nibbles_to_samples( - read_32bitBE(0x34,streamFile))+1; - } - - vgmstream->coding_type = coding_NGC_DSP; - vgmstream->layout_type = layout_none; - vgmstream->meta_type = meta_DSP_CSTR; - - { - int i; - for (i=0;i<16;i++) - vgmstream->ch[0].adpcm_coef[i]=read_16bitBE(0x3c+i*2,streamFile); - } - - /* open the file for reading by each channel */ - vgmstream->ch[0].streamfile = streamFile->open(streamFile,filename,STREAMFILE_DEFAULT_BUFFER_SIZE); - - if (!vgmstream->ch[0].streamfile) goto fail; - - vgmstream->ch[0].channel_start_offset= - vgmstream->ch[0].offset= - start_offset; - - return vgmstream; - } /* end mono */ - - interleave = read_16bitBE(0x06,streamFile); - start_offset = 0xe0; - first_data = start_offset+read_32bitBE(0x0c,streamFile); - loop_flag = read_16bitBE(0x2c,streamFile); - - if (!loop_flag) { - /* Nonlooped tracks seem to follow no discernable pattern - * with where they actually start. - * But! with the magic of initial p/s redundancy, we can guess. - */ - while (first_data=-0x10;loop_adjust-=8) { -#ifdef DEBUG - fprintf(stderr,"looking for loop p/s at %#x,%#x\n",loop_offset-interleave+loop_adjust,loop_offset+loop_adjust); -#endif - if (read_16bitBE(0x64,streamFile) == (uint8_t)read_8bit(loop_offset-interleave+loop_adjust,streamFile) && - read_16bitBE(0xc4,streamFile) == (uint8_t)read_8bit(loop_offset+loop_adjust,streamFile)) { - loops_ok=1; + loop_flag = (loop_start >= 0); + start_offset = 0x20 + 0x60 * channels + first_skip; + +#if 1 + /* nonlooped tracks may not set first skip for no reason, but can be tested with initial p/s */ + if (!loop_flag && channels == 2 && first_skip == 0) { + while (first_skip < 0x800) { + if (read_u16be(0x20 + 0x3e, sf) == read_u8(start_offset + first_skip, sf) && + read_u16be(0x20 + 0x60 + 0x3e, sf) == read_u8(start_offset + first_skip + interleave, sf)) break; - } + first_skip += 0x08; } - if (!loops_ok) - for (loop_adjust=interleave;loop_adjust<=interleave+0x10;loop_adjust+=8) { -#ifdef DEBUG - fprintf(stderr,"looking for loop p/s at %#x,%#x\n",loop_offset-interleave+loop_adjust,loop_offset+loop_adjust); + /* not found */ + if (first_skip == 0x800) + first_skip = 0; + else + start_offset += first_skip; + } + if (first_skip > 0 && loop_start >= (interleave - first_skip)) + loop_start = loop_start - (interleave - first_skip); #endif - if (read_16bitBE(0x64,streamFile) == (uint8_t)read_8bit(loop_offset-interleave+loop_adjust,streamFile) && - read_16bitBE(0xc4,streamFile) == (uint8_t)read_8bit(loop_offset+loop_adjust,streamFile)) { - loops_ok=1; - break; - } - } + loop_start = loop_start * 2; - if (!loops_ok) goto fail; -#ifdef DEBUG - fprintf(stderr,"loop p/s ok (with %#4x adjust)\n",loop_adjust); -#endif - - /* check for agreement */ - /* loop end (channel 1 & 2 headers) */ - if (read_32bitBE(0x34,streamFile) != read_32bitBE(0x94,streamFile)) - goto fail; - - /* Mr. Driller oddity */ - if (dsp_nibbles_to_samples(read_32bitBE(0x34,streamFile)*2)+1 <= read_32bitBE(0x20,streamFile)) { -#ifdef DEBUG - fprintf(stderr,"loop end <= half total samples, should be doubled\n"); -#endif - double_loop_end = 1; - } - - /* loop start (Cstr header and channel 1 header) */ - if (read_32bitBE(0x30,streamFile) != read_32bitBE(0x10,streamFile) -#if 0 - /* this particular glitch only true for SFA, though it - * seems like something similar happens in Donkey Konga */ - /* loop start (Cstr, channel 1 & 2 headers) */ - || (read_32bitBE(0x0c,streamFile)+read_32bitLE(0x30,streamFile)) != - read_32bitBE(0x90,streamFile) -#endif - ) - /* alternatively (Donkey Konga) the header loop is 0x0c+0x10 */ - if ( - /* loop start (Cstr header and channel 1 header) */ - read_32bitBE(0x30,streamFile) != read_32bitBE(0x10,streamFile)+ - read_32bitBE(0x0c,streamFile)) - /* further alternatively (Donkey Konga), if we loop back to - * the very first frame 0x30 might be 0x00000002 (which - * is a *valid* std dsp loop start, imagine that) while 0x10 - * is 0x00000000 */ - if (!(read_32bitBE(0x30,streamFile) == 2 && - read_32bitBE(0x10,streamFile) == 0)) - /* lest there be too few alternatives, in Mr. Driller we - * find that [0x30] + [0x0c] + 8 = [0x10]*2 */ - if (!(double_loop_end && - read_32bitBE(0x30,streamFile) + - read_32bitBE(0x0c,streamFile) + 8 == - read_32bitBE(0x10,streamFile)*2)) { - /* for Mr.Driller Drill Land, no idea about the above but seems to play and loop ok */ - VGM_LOG("Cstr: bad loop check ignored\n"); - //goto fail; - } - -#ifdef DEBUG - fprintf(stderr,"loop points agree\n"); -#endif + /* Mr. Driller oddity, unreliable loop flag */ + if (loop_end == num_nibbles) { + loop_flag = 0; } - /* assure that sample counts, sample rates agree */ - if ( - /* sample count (channel 1 & 2 headers) */ - read_32bitBE(0x20,streamFile) != read_32bitBE(0x80,streamFile) || - /* sample rate (channel 1 & 2 headers) */ - read_32bitBE(0x28,streamFile) != read_32bitBE(0x88,streamFile) || - /* sample count (Cstr header and channel 1 header) */ - read_32bitLE(0x14,streamFile) != read_32bitBE(0x20,streamFile) || - /* sample rate (Cstr header and channel 1 header) */ - (uint16_t)read_16bitLE(0x18,streamFile) != read_32bitBE(0x28,streamFile)) - goto fail; + /* Mr. Driller oddity, half nibbles */ + if (loop_end * 2 + 1 <= num_nibbles) { + loop_end = loop_end * 2; + } + + + /* no loop_ps checks given how buggy the format is */ + /* build the VGMSTREAM */ - - vgmstream = allocate_vgmstream(2,loop_flag); + vgmstream = allocate_vgmstream(channels, loop_flag); if (!vgmstream) goto fail; - /* fill in the vital statistics */ - vgmstream->sample_rate = read_32bitBE(0x28,streamFile); - /* This is a slight hack to counteract their hack. - * All the data is ofset by first_data so that the loop - * point occurs at a block boundary. However, I always begin decoding - * right after the header, as that is the start of the first block and - * my interleave code relies on starting at the beginning of a block. - * So we decode a few silent samples at the beginning, and here we make up - * for it by lengthening the track by that much. - */ - vgmstream->num_samples = read_32bitBE(0x20,streamFile) + - (first_data-start_offset)/8*14; + vgmstream->sample_rate = sample_rate; + vgmstream->num_samples = num_samples; + vgmstream->loop_start_sample = dsp_bytes_to_samples(loop_start, channels); - if (loop_flag) { - off_t loop_start_bytes = loop_offset-start_offset-interleave; - vgmstream->loop_start_sample = dsp_nibbles_to_samples((loop_start_bytes/(2*interleave)*interleave+loop_start_bytes%(interleave*2))*2); - /*dsp_nibbles_to_samples(loop_start_bytes);*/ - /*dsp_nibbles_to_samples(read_32bitBE(0x30,streamFile)*2-inter);*/ - vgmstream->loop_end_sample = dsp_nibbles_to_samples( - read_32bitBE(0x34,streamFile))+1; - - if (double_loop_end) - vgmstream->loop_end_sample = - dsp_nibbles_to_samples(read_32bitBE(0x34,streamFile)*2)+1; - - if (vgmstream->loop_end_sample > vgmstream->num_samples) { -#ifdef DEBUG - fprintf(stderr,"loop_end_sample > num_samples, adjusting\n"); -#endif - vgmstream->loop_end_sample = vgmstream->num_samples; - } - } + vgmstream->loop_end_sample = dsp_nibbles_to_samples(loop_end) + 1; + /* Donkey Konga 3 oddity, loop/num nibbles not correct vs final samples */ + if (vgmstream->loop_end_sample > num_samples) + vgmstream->loop_end_sample = num_samples; vgmstream->coding_type = coding_NGC_DSP; vgmstream->layout_type = layout_interleave; vgmstream->interleave_block_size = interleave; + vgmstream->interleave_first_block_size = interleave - first_skip; + vgmstream->interleave_first_skip = first_skip; vgmstream->meta_type = meta_DSP_CSTR; +VGM_LOG("1=%x, =%x\n",vgmstream->interleave_first_block_size, vgmstream->interleave_first_skip); + dsp_read_coefs_be(vgmstream, sf, 0x3c, 0x60); - { - int i; - for (i=0;i<16;i++) - vgmstream->ch[0].adpcm_coef[i]=read_16bitBE(0x3c+i*2,streamFile); - for (i=0;i<16;i++) - vgmstream->ch[1].adpcm_coef[i]=read_16bitBE(0x9c+i*2,streamFile); - } - - /* open the file for reading by each channel */ - { - int i; - for (i=0;i<2;i++) { - vgmstream->ch[i].streamfile = streamFile->open(streamFile,filename,STREAMFILE_DEFAULT_BUFFER_SIZE); - - if (!vgmstream->ch[i].streamfile) goto fail; - - vgmstream->ch[i].channel_start_offset= - vgmstream->ch[i].offset= - start_offset+interleave*i; - } - } - + if (!vgmstream_open_stream(vgmstream, sf, start_offset)) + goto fail; return vgmstream; - - /* clean up anything we may have opened */ fail: - if (vgmstream) close_vgmstream(vgmstream); + close_vgmstream(vgmstream); return NULL; } diff --git a/Frameworks/vgmstream/vgmstream/src/meta/adx_keys.h b/Frameworks/vgmstream/vgmstream/src/meta/adx_keys.h index e691f0ba4..b0c21704d 100644 --- a/Frameworks/vgmstream/vgmstream/src/meta/adx_keys.h +++ b/Frameworks/vgmstream/vgmstream/src/meta/adx_keys.h @@ -232,7 +232,10 @@ static const adxkey_info adxkey9_list[] = { {0x2378,0x5511,0x0201, NULL,5613126134333697}, // 0013F11BC5510101 /* Detective Conan Runner / Case Closed Runner (Android) */ - {0x0613,0x0e3d,0x6dff, NULL,1175268187653273344}, // 104f643098e3f700 + {0x0613,0x0e3d,0x6dff, NULL,1175268187653273344}, // 104f643098e3f700 + + /* Persona 5 Royal (PS4)*/ + {0x0000,0x1c85,0x1043, NULL,29902882}, // guessed with VGAudio }; diff --git a/Frameworks/vgmstream/vgmstream/src/meta/awc.c b/Frameworks/vgmstream/vgmstream/src/meta/awc.c index 9aeb39621..583553521 100644 --- a/Frameworks/vgmstream/vgmstream/src/meta/awc.c +++ b/Frameworks/vgmstream/vgmstream/src/meta/awc.c @@ -25,16 +25,15 @@ typedef struct { static int parse_awc_header(STREAMFILE* streamFile, awc_header* awc); -/* AWC - from RAGE (Rockstar Advanced Game Engine) audio (Red Dead Redemption, Max Payne 3, GTA5) */ +/* AWC - from RAGE (Rockstar Advanced Game Engine) audio [Red Dead Redemption, Max Payne 3, GTA5 (multi)] */ VGMSTREAM * init_vgmstream_awc(STREAMFILE *streamFile) { VGMSTREAM * vgmstream = NULL; awc_header awc = {0}; - /* check extension */ + + /* checks */ if (!check_extensions(streamFile,"awc")) goto fail; - - /* check header */ if (!parse_awc_header(streamFile, &awc)) goto fail; @@ -51,7 +50,8 @@ VGMSTREAM * init_vgmstream_awc(STREAMFILE *streamFile) { switch(awc.codec) { - case 0x01: /* PCM (PC/PS3) [sfx, rarely] */ + case 0x00: /* PCM (PC) sfx, very rare, lower sample rates? [Max Payne 3 (PC)] */ + case 0x01: /* PCM (PC/PS3) sfx, rarely */ if (awc.is_music) goto fail; /* blocked_awc needs to be prepared */ vgmstream->coding_type = awc.big_endian ? coding_PCM16BE : coding_PCM16LE; vgmstream->layout_type = layout_interleave; @@ -294,17 +294,22 @@ static int parse_awc_header(STREAMFILE* streamFile, awc_header* awc) { sample_rate = (uint16_t)read_16bit(offset + 0x0c + 0x10*ch + 0x0a,streamFile); codec = read_8bit(offset + 0x0c + 0x10*ch + 0x0c, streamFile); - /* validate as all channels should repeat this (when channels is even and > 2 seems - * it's stereo pairs, and num_samples can vary slightly but no matter) */ + /* validate channels differences */ if ((awc->num_samples && !(awc->num_samples >= num_samples - 10 && awc->num_samples <= num_samples + 10)) || - (awc->sample_rate && awc->sample_rate != sample_rate) || - (awc->codec && awc->codec != codec)) { - VGM_LOG("AWC: found header diffs in channel %i, ns=%i vs %i, sr=%i vs %i, c=%i vs %i\n", - ch, awc->num_samples, num_samples, awc->sample_rate, sample_rate, awc->codec, codec); - //goto fail; //todo some Max Payne 3 cutscene channels have huge sample diffs + (awc->sample_rate && awc->sample_rate != sample_rate)) { + VGM_LOG("AWC: found header diffs in channel %i, ns=%i vs %i, sr=%i vs %i\n", + ch, awc->num_samples, num_samples, awc->sample_rate, sample_rate); + /* sometimes (often cutscenes in Max Payne 3 and RDR DLC) channels have bif sample diffs, + * probably one stream is simply silent after its samples end */ } - awc->num_samples = num_samples; + if ((awc->codec && awc->codec != codec)) { + VGM_LOG("AWC: found header diffs in channel %i, c=%i vs %i\n", ch, awc->codec, codec); + goto fail; + } + + if (awc->num_samples < num_samples) /* use biggest channel */ + awc->num_samples = num_samples; awc->sample_rate = sample_rate; awc->codec = codec; } diff --git a/Frameworks/vgmstream/vgmstream/src/meta/awc_xma_streamfile.h b/Frameworks/vgmstream/vgmstream/src/meta/awc_xma_streamfile.h index 541066247..17b9799c6 100644 --- a/Frameworks/vgmstream/vgmstream/src/meta/awc_xma_streamfile.h +++ b/Frameworks/vgmstream/vgmstream/src/meta/awc_xma_streamfile.h @@ -1,245 +1,114 @@ -#ifndef _AWC_XMA_STREAMFILE_H_ -#define _AWC_XMA_STREAMFILE_H_ -#include "../streamfile.h" - - -typedef struct { - /* config */ - int channel; - int channel_count; - size_t block_size; - off_t stream_offset; - size_t stream_size; - - /* state */ - off_t logical_offset; /* offset that corresponds to physical_offset */ - off_t physical_offset; /* actual file offset */ - - size_t skip_size; /* size to skip from a block start to reach data start */ - size_t data_size; /* logical size of the block */ - - size_t logical_size; -} awc_xma_io_data; - - -static size_t get_block_header_size(STREAMFILE *streamFile, off_t offset, awc_xma_io_data *data); -static size_t get_repeated_data_size(STREAMFILE *streamFile, off_t next_offset, size_t repeat_samples); -static size_t get_block_skip_count(STREAMFILE *streamFile, off_t offset, int channel); - -/* Reads plain XMA data of a single stream. Each block has a header and channels have different num_samples/frames. - * Channel data is separate within the block (first all frames of ch0, then ch1, etc), padded, and sometimes - * the last few frames of a channel are repeated in the new block (marked with the "discard samples" field). */ -static size_t awc_xma_io_read(STREAMFILE *streamfile, uint8_t *dest, off_t offset, size_t length, awc_xma_io_data* data) { - size_t total_read = 0; - size_t frame_size = 0x800; - - /* ignore bad reads */ - if (offset < 0 || offset > data->logical_size) { - return 0; - } - - /* previous offset: re-start as we can't map logical<>physical offsets - * (kinda slow as it trashes buffers, but shouldn't happen often) */ - if (offset < data->logical_offset) { - data->logical_offset = 0x00; - data->physical_offset = data->stream_offset; - data->data_size = 0; - } - - /* read blocks, one at a time */ - while (length > 0) { - - /* ignore EOF */ - if (data->logical_offset >= data->logical_size) { - break; - } - - /* process new block */ - if (data->data_size == 0) { - size_t header_size = get_block_header_size(streamfile, data->physical_offset, data); - /* header table entries = frames... I hope */ - size_t others_size = get_block_skip_count(streamfile, data->physical_offset, data->channel) * frame_size; - //size_t skip_size = read_32bitBE(data->physical_offset + 0x10*data->channel + 0x00, streamfile) * frame_size; - size_t data_size = read_32bitBE(data->physical_offset + 0x10*data->channel + 0x04, streamfile) * frame_size; - size_t repeat_samples = read_32bitBE(data->physical_offset + 0x10*data->channel + 0x08, streamfile); - size_t repeat_size = 0; - - - /* if there are repeat samples current block repeats some frames from last block, find out size */ - if (repeat_samples) { - off_t data_offset = data->physical_offset + header_size + others_size; - repeat_size = get_repeated_data_size(streamfile, data_offset, repeat_samples); - } - - data->skip_size = header_size + others_size + repeat_size; - data->data_size = data_size - repeat_size; - } - - /* move to next block */ - if (offset >= data->logical_offset + data->data_size) { - data->physical_offset += data->block_size; - data->logical_offset += data->data_size; - data->data_size = 0; - continue; - } - - /* read data */ - { - size_t bytes_consumed, bytes_done, to_read; - - bytes_consumed = offset - data->logical_offset; - - to_read = data->data_size - bytes_consumed; - if (to_read > length) - to_read = length; - bytes_done = read_streamfile(dest, data->physical_offset + data->skip_size + bytes_consumed, to_read, streamfile); - - offset += bytes_done; - total_read += bytes_done; - length -= bytes_done; - dest += bytes_done; - - if (bytes_done != to_read || bytes_done == 0) { - break; /* error/EOF */ - } - } - - } - - return total_read; -} - -static size_t awc_xma_io_size(STREAMFILE *streamfile, awc_xma_io_data* data) { - off_t physical_offset, max_physical_offset; - size_t frame_size = 0x800; - size_t logical_size = 0; - - if (data->logical_size) - return data->logical_size; - - physical_offset = data->stream_offset; - max_physical_offset = data->stream_offset + data->stream_size; - - /* get size of the logical stream */ - while (physical_offset < max_physical_offset) { - size_t header_size = get_block_header_size(streamfile, physical_offset, data); - /* header table entries = frames... I hope */ - size_t skip_size = get_block_skip_count(streamfile, physical_offset, data->channel) * frame_size; - //size_t skip_size = read_32bitBE(physical_offset + 0x10*data->channel + 0x00, streamfile) * frame_size; - size_t data_size = read_32bitBE(physical_offset + 0x10*data->channel + 0x04, streamfile) * frame_size; - size_t repeat_samples = read_32bitBE(physical_offset + 0x10*data->channel + 0x08, streamfile); - size_t repeat_size = 0; - - /* if there are repeat samples current block repeats some frames from last block, find out size */ - if (repeat_samples) { - off_t data_offset = physical_offset + header_size + skip_size; - repeat_size = get_repeated_data_size(streamfile, data_offset, repeat_samples); - } - - logical_size += data_size - repeat_size; - physical_offset += data->block_size; - } - - data->logical_size = logical_size; - return data->logical_size; -} - - -/* Prepares custom IO for AWC XMA, which is interleaved XMA in AWC blocks */ -static STREAMFILE* setup_awc_xma_streamfile(STREAMFILE *streamFile, off_t stream_offset, size_t stream_size, size_t block_size, int channel_count, int channel) { - STREAMFILE *temp_streamFile = NULL, *new_streamFile = NULL; - awc_xma_io_data io_data = {0}; - size_t io_data_size = sizeof(awc_xma_io_data); - - io_data.channel = channel; - io_data.channel_count = channel_count; - io_data.stream_offset = stream_offset; - io_data.stream_size = stream_size; - io_data.block_size = block_size; - io_data.physical_offset = stream_offset; - io_data.logical_size = awc_xma_io_size(streamFile, &io_data); /* force init */ - - if (io_data.logical_size > io_data.stream_size) { - VGM_LOG("AWC XMA: wrong logical size\n"); - goto fail; - } - - /* setup subfile */ - new_streamFile = open_wrap_streamfile(streamFile); - if (!new_streamFile) goto fail; - temp_streamFile = new_streamFile; - - new_streamFile = open_io_streamfile(temp_streamFile, &io_data,io_data_size, awc_xma_io_read,awc_xma_io_size); - if (!new_streamFile) goto fail; - temp_streamFile = new_streamFile; - - new_streamFile = open_buffer_streamfile(new_streamFile,0); - if (!new_streamFile) goto fail; - temp_streamFile = new_streamFile; - - return temp_streamFile; - -fail: - close_streamfile(temp_streamFile); - return NULL; -} - -/* block header size, aligned/padded to 0x800 */ -static size_t get_block_header_size(STREAMFILE *streamFile, off_t offset, awc_xma_io_data *data) { - size_t header_size = 0; - int i; - int entries = data->channel_count; - - for (i = 0; i < entries; i++) { - header_size += 0x10; - header_size += read_32bitBE(offset + 0x10*i + 0x04, streamFile) * 0x04; /* entries in the table */ - } - - if (header_size % 0x800) /* padded */ - header_size += 0x800 - (header_size % 0x800); - - return header_size; -} - - -/* find data that repeats in the beginning of a new block at the end of last block */ -static size_t get_repeated_data_size(STREAMFILE *streamFile, off_t next_offset, size_t repeat_samples) { - const size_t frame_size = 0x800; - const size_t samples_per_subframe = 512; - size_t samples_this_frame; - uint8_t subframes; - - //todo: fix this - /* Repeat samples are the number of decoded samples to discard, but in this streamfile we can't do that. - * Also XMA is VBR, and may encode silent frames with up to 63 subframes yet we may have few repeat samples. - * We could find out how many subframes of 512 samples to skip, then adjust the XMA frame header, though - * output will be slightly off since subframes are related. - * - * For now just skip a full frame depending on the number of subframes vs repeat samples. - * Most files work ok-ish but channels may desync slightly. */ - - subframes = ((uint8_t)read_8bit(next_offset,streamFile) >> 2) & 0x3F; /* peek into frame header */ - samples_this_frame = subframes*samples_per_subframe; - if (repeat_samples >= (int)(samples_this_frame*0.13)) { /* skip mosts */ - return frame_size; - } - else { - return 0; - } -} - -/* header has a skip value, but somehow it's sometimes bigger than expected (WHY!?!?) so just sum all */ -static size_t get_block_skip_count(STREAMFILE *streamFile, off_t offset, int channel) { - size_t skip_count = 0; - int i; - - //skip_size = read_32bitBE(offset + 0x10*channel + 0x00, streamFile); /* wrong! */ - for (i = 0; i < channel; i++) { - skip_count += read_32bitBE(offset + 0x10*i + 0x04, streamFile); /* number of frames of this channel */ - } - - return skip_count; -} - - -#endif /* _AWC_XMA_STREAMFILE_H_ */ +#ifndef _AWC_XMA_STREAMFILE_H_ +#define _AWC_XMA_STREAMFILE_H_ +#include "deblock_streamfile.h" + + +static size_t get_block_header_size(STREAMFILE* sf, off_t offset, int channels); +static size_t get_repeated_data_size(STREAMFILE* sf, off_t next_offset, size_t repeat_samples); +static size_t get_block_skip_count(STREAMFILE* sf, off_t offset, int channel); + +static void block_callback(STREAMFILE *sf, deblock_io_data* data) { + const size_t frame_size = 0x800; + int channel = data->cfg.track_number; + int channels = data->cfg.track_count; + + /* Blocks have a header then data per channel, each with a different num_samples/frames, + * separate (first all frames of ch0, then ch1, etc), padded, and sometimes the last few + * frames of a channel are repeated in the new block (marked with "repeat samples"). */ + size_t header_size = get_block_header_size(sf, data->physical_offset, channels); + /* header table entries = frames... I hope */ + size_t others_size = get_block_skip_count(sf, data->physical_offset, channel) * frame_size; + //size_t skip_size = read_u32be(data->physical_offset + 0x10*channel + 0x00, sf) * frame_size; + size_t data_size = read_u32be(data->physical_offset + 0x10*channel + 0x04, sf) * frame_size; + size_t repeat_samples = read_u32be(data->physical_offset + 0x10*channel + 0x08, sf); + size_t repeat_size = 0; + + data->block_size = data->cfg.chunk_size; + + /* if there are repeat samples current block repeats some frames from last block, find out size */ + if (repeat_samples) { + off_t data_offset = data->physical_offset + header_size + others_size; + repeat_size = get_repeated_data_size(sf, data_offset, repeat_samples); + } + + data->skip_size = header_size + others_size + repeat_size; + data->data_size = data_size - repeat_size; +} + +/* block header size, aligned/padded to 0x800 */ +static size_t get_block_header_size(STREAMFILE* sf, off_t offset, int channels) { + size_t header_size = 0; + int i; + + for (i = 0; i < channels; i++) { + header_size += 0x10; + header_size += read_u32be(offset + 0x10*i + 0x04, sf) * 0x04; /* entries in the table */ + } + + if (header_size % 0x800) /* padded */ + header_size += 0x800 - (header_size % 0x800); + + return header_size; +} + +/* find data that repeats in the beginning of a new block at the end of last block */ +static size_t get_repeated_data_size(STREAMFILE* sf, off_t next_offset, size_t repeat_samples) { + const size_t frame_size = 0x800; + const size_t samples_per_subframe = 512; + size_t samples_this_frame; + uint8_t subframes; + + //todo: fix this + /* Repeat samples are the number of decoded samples to discard, but in this streamfile we can't do that. + * Also XMA is VBR, and may encode silent frames with up to 63 subframes yet we may have few repeat samples. + * We could find out how many subframes of 512 samples to skip, then adjust the XMA frame header, though + * output will be slightly off since subframes are related. + * + * For now just skip a full frame depending on the number of subframes vs repeat samples. + * Most files work ok-ish but channels may desync slightly. */ + + subframes = ((uint8_t)read_8bit(next_offset,sf) >> 2) & 0x3F; /* peek into frame header */ + samples_this_frame = subframes*samples_per_subframe; + if (repeat_samples >= (int)(samples_this_frame*0.13)) { /* skip mosts */ + return frame_size; + } + else { + return 0; + } +} + +/* header has a skip value, but somehow it's sometimes bigger than expected (WHY!?!?) so just sum all */ +static size_t get_block_skip_count(STREAMFILE* sf, off_t offset, int channel) { + size_t skip_count = 0; + int i; + + //skip_size = read_u32be(offset + 0x10*channel + 0x00, sf); /* wrong! */ + for (i = 0; i < channel; i++) { + skip_count += read_u32be(offset + 0x10*i + 0x04, sf); /* number of frames of this channel */ + } + + return skip_count; +} + + +/* Deblocks interleaved XMA in AWC blocks */ +static STREAMFILE* setup_awc_xma_streamfile(STREAMFILE *sf, off_t stream_offset, size_t stream_size, size_t block_size, int channel_count, int channel) { + STREAMFILE *new_sf = NULL; + deblock_config_t cfg = {0}; + + cfg.track_number = channel; + cfg.track_count = channel_count; + cfg.stream_start = stream_offset; + cfg.stream_size = stream_size; + cfg.chunk_size = block_size; + //cfg.physical_offset = stream_offset; + //cfg.logical_size = awc_xma_io_size(sf, &cfg); /* force init */ + cfg.block_callback = block_callback; + + new_sf = open_wrap_streamfile(sf); + new_sf = open_io_deblock_streamfile_f(new_sf, &cfg); + //new_sf = open_buffer_streamfile_f(new_sf, 0); + return new_sf; +} + +#endif /* _AWC_XMA_STREAMFILE_H_ */ diff --git a/Frameworks/vgmstream/vgmstream/src/meta/bkhd.c b/Frameworks/vgmstream/vgmstream/src/meta/bkhd.c new file mode 100644 index 000000000..4788aad1f --- /dev/null +++ b/Frameworks/vgmstream/vgmstream/src/meta/bkhd.c @@ -0,0 +1,126 @@ +#include "meta.h" +#include "../coding/coding.h" + + +/* BKHD - Wwise soundbank container */ +VGMSTREAM* init_vgmstream_bkhd(STREAMFILE* sf) { + VGMSTREAM* vgmstream = NULL; + STREAMFILE* temp_sf = NULL; + off_t subfile_offset, didx_offset, data_offset, offset; + size_t subfile_size, didx_size; + uint32_t subfile_id; + int big_endian; + uint32_t (*read_u32)(off_t,STREAMFILE*); + int total_subsongs, target_subsong = sf->stream_index; + + + /* checks */ + if (!check_extensions(sf,"bnk")) + goto fail; + if (read_u32be(0x00, sf) != 0x424B4844) /* "BKHD" */ + goto fail; + big_endian = guess_endianness32bit(0x04, sf); + read_u32 = big_endian ? read_u32be : read_u32le; + + /* Wwise banks have event/track/sequence/etc info in the HIRC chunk, as well + * as other chunks, and may have a DIDX index to memory .wem in DATA. + * We support the internal .wem mainly for quick tests, as the HIRC is + * complex and better handled with TXTP (some info from Nicknine's script) */ + + /* unlike RIFF first chunk follows chunk rules */ + if (!find_chunk(sf, 0x44494458, 0x00,0, &didx_offset, &didx_size, big_endian, 0)) /* "DIDX" */ + goto fail; + if (!find_chunk(sf, 0x44415441, 0x00,0, &data_offset, NULL, big_endian, 0)) /* "DATA" */ + goto fail; + + total_subsongs = didx_size / 0x0c; + if (target_subsong == 0) target_subsong = 1; + if (target_subsong < 0 || target_subsong > total_subsongs || total_subsongs < 1) goto fail; + + offset = didx_offset + (target_subsong - 1) * 0x0c; + subfile_id = read_u32(offset + 0x00, sf); + subfile_offset = read_u32(offset + 0x04, sf) + data_offset; + subfile_size = read_u32(offset + 0x08, sf); + + //;VGM_LOG("BKHD: %lx, %x\n", subfile_offset, subfile_size); + temp_sf = setup_subfile_streamfile(sf, subfile_offset, subfile_size, "wem"); + if (!temp_sf) goto fail; + + subfile_id = read_u32(0x00, temp_sf); + if (subfile_id == 0x52494646 || subfile_id == 0x52494658) { /* "RIFF" / "RIFX" */ + vgmstream = init_vgmstream_wwise(temp_sf); + if (!vgmstream) goto fail; + } + else { + vgmstream = init_vgmstream_bkhd_fx(temp_sf); + if (!vgmstream) goto fail; + } + + vgmstream->num_streams = total_subsongs; + snprintf(vgmstream->stream_name, STREAM_NAME_SIZE, "%u", subfile_id); + + close_streamfile(temp_sf); + return vgmstream; + +fail: + close_streamfile(temp_sf); + close_vgmstream(vgmstream); + return NULL; +} + + +/* BKHD mini format, probably from a generator plugin [Borderlands 2 (X360)] */ +VGMSTREAM* init_vgmstream_bkhd_fx(STREAMFILE* sf) { + VGMSTREAM* vgmstream = NULL; + off_t start_offset, data_size; + int big_endian, loop_flag, channels, sample_rate, entries; + uint32_t (*read_u32)(off_t,STREAMFILE*); + + + /* checks */ + if (!check_extensions(sf,"wem,bnk")) /* assumed */ + goto fail; + big_endian = guess_endianness32bit(0x00, sf); + read_u32 = big_endian ? read_u32be : read_u32le; + + if (read_u32(0x00, sf) != 0x0400) /* codec? */ + goto fail; + if (read_u32(0x04, sf) != 0x0800) /* codec? */ + goto fail; + sample_rate = read_u32(0x08, sf); + channels = read_u32(0x0c, sf); + /* 0x10: some id or small size? */ + /* 0x14/18: some float? */ + entries = read_u32(0x1c, sf); + /* 0x20 data size / 0x10 */ + if (read_u8(0x24, sf) != 4) /* bps */ + goto fail; + /* 0x30: unknown table of 16b that goes up and down */ + + start_offset = 0x30 + align_size_to_block(entries * 0x02, 0x10); + data_size = get_streamfile_size(sf) - start_offset; + loop_flag = 0; + + /* output sounds a bit funny, maybe not an actual stream but parts using the table */ + + /* build the VGMSTREAM */ + vgmstream = allocate_vgmstream(channels, loop_flag); + if (!vgmstream) goto fail; + + vgmstream->meta_type = meta_WWISE_FX; + vgmstream->sample_rate = sample_rate; + + vgmstream->coding_type = coding_PCMFLOAT; + vgmstream->layout_type = layout_interleave; + vgmstream->codec_endian = big_endian; + vgmstream->interleave_block_size = 0x4; + + vgmstream->num_samples = pcm_bytes_to_samples(data_size, channels, 32); + + if (!vgmstream_open_stream(vgmstream,sf,start_offset)) + goto fail; + return vgmstream; +fail: + close_vgmstream(vgmstream); + return NULL; +} diff --git a/Frameworks/vgmstream/vgmstream/src/meta/bnk_sony.c b/Frameworks/vgmstream/vgmstream/src/meta/bnk_sony.c index 9fecfc0a8..db6aba443 100644 --- a/Frameworks/vgmstream/vgmstream/src/meta/bnk_sony.c +++ b/Frameworks/vgmstream/vgmstream/src/meta/bnk_sony.c @@ -4,8 +4,8 @@ typedef enum { PSX, PCM16, ATRAC9, HEVAG } bnk_codec; /* .BNK - Sony's Scream Tool bank format [Puyo Puyo Tetris (PS4), NekoBuro: Cats Block (Vita)] */ -VGMSTREAM * init_vgmstream_bnk_sony(STREAMFILE *streamFile) { - VGMSTREAM * vgmstream = NULL; +VGMSTREAM* init_vgmstream_bnk_sony(STREAMFILE* sf) { + VGMSTREAM* vgmstream = NULL; off_t start_offset, stream_offset, name_offset = 0; size_t stream_size, interleave = 0; off_t sblk_offset, data_offset; @@ -15,7 +15,7 @@ VGMSTREAM * init_vgmstream_bnk_sony(STREAMFILE *streamFile) { uint32_t pitch, flags; uint32_t atrac9_info = 0; - int total_subsongs, target_subsong = streamFile->stream_index; + int total_subsongs, target_subsong = sf->stream_index; int32_t (*read_32bit)(off_t,STREAMFILE*) = NULL; int16_t (*read_16bit)(off_t,STREAMFILE*) = NULL; float (*read_f32)(off_t,STREAMFILE*) = NULL; @@ -23,17 +23,17 @@ VGMSTREAM * init_vgmstream_bnk_sony(STREAMFILE *streamFile) { /* checks */ - if (!check_extensions(streamFile, "bnk")) + if (!check_extensions(sf, "bnk")) goto fail; /* bnk version */ - if (read_32bitBE(0x00,streamFile) == 0x00000003) { /* PS3 */ + if (read_32bitBE(0x00,sf) == 0x00000003) { /* PS3 */ read_32bit = read_32bitBE; read_16bit = read_16bitBE; read_f32 = read_f32be; big_endian = 1; } - else if (read_32bitBE(0x00,streamFile) == 0x03000000) { /* PS2/Vita/PS4 */ + else if (read_32bitBE(0x00,sf) == 0x03000000) { /* PS2/Vita/PS4 */ read_32bit = read_32bitLE; read_16bit = read_16bitLE; read_f32 = read_f32le; @@ -43,13 +43,13 @@ VGMSTREAM * init_vgmstream_bnk_sony(STREAMFILE *streamFile) { goto fail; } - parts = read_32bit(0x04,streamFile); + parts = read_32bit(0x04,sf); if (parts < 2 || parts > 3) goto fail; - sblk_offset = read_32bit(0x08,streamFile); + sblk_offset = read_32bit(0x08,sf); /* 0x0c: sklb size */ - data_offset = read_32bit(0x10,streamFile); - data_size = read_32bit(0x14,streamFile); + data_offset = read_32bit(0x10,sf); + data_size = read_32bit(0x14,sf); /* when sblk_offset >= 0x20: */ /* 0x18: ZLSD small footer, rare [Yakuza 6's Puyo Puyo (PS4)] */ /* 0x1c: ZLSD size */ @@ -60,9 +60,9 @@ VGMSTREAM * init_vgmstream_bnk_sony(STREAMFILE *streamFile) { /* SBlk part: parse header */ - if (read_32bit(sblk_offset+0x00,streamFile) != 0x6B6C4253) /* "klBS" (SBlk = sample block?) */ + if (read_32bit(sblk_offset+0x00,sf) != 0x6B6C4253) /* "klBS" (SBlk = sample block?) */ goto fail; - sblk_version = read_32bit(sblk_offset+0x04,streamFile); + sblk_version = read_32bit(sblk_offset+0x04,sf); /* 0x08: possibly when sblk_version=0x0d, 0x03=Vita, 0x06=PS4 */ //;VGM_LOG("BNK: sblk_offset=%lx, data_offset=%lx, sblk_version %x\n", sblk_offset, data_offset, sblk_version); @@ -79,11 +79,11 @@ VGMSTREAM * init_vgmstream_bnk_sony(STREAMFILE *streamFile) { switch(sblk_version) { case 0x01: /* Ratchet & Clank (PS2) */ - section_entries = (uint16_t)read_16bit(sblk_offset+0x16,streamFile); /* entry size: ~0x0c */ - material_entries = (uint16_t)read_16bit(sblk_offset+0x18,streamFile); /* entry size: ~0x28 */ - stream_entries = (uint16_t)read_16bit(sblk_offset+0x1a,streamFile); /* entry size: none (count) */ - table1_offset = sblk_offset + read_32bit(sblk_offset+0x1c,streamFile); - table2_offset = sblk_offset + read_32bit(sblk_offset+0x20,streamFile); + section_entries = (uint16_t)read_16bit(sblk_offset+0x16,sf); /* entry size: ~0x0c */ + material_entries = (uint16_t)read_16bit(sblk_offset+0x18,sf); /* entry size: ~0x28 */ + stream_entries = (uint16_t)read_16bit(sblk_offset+0x1a,sf); /* entry size: none (count) */ + table1_offset = sblk_offset + read_32bit(sblk_offset+0x1c,sf); + table2_offset = sblk_offset + read_32bit(sblk_offset+0x20,sf); table3_offset = table2_offset; /* mixed table in this version */ table4_offset = 0; /* not included */ @@ -92,16 +92,17 @@ VGMSTREAM * init_vgmstream_bnk_sony(STREAMFILE *streamFile) { table2_suboffset = 0; break; + case 0x03: /* Yu-Gi-Oh! GX - The Beginning of Destiny (PS2) */ case 0x04: /* Test banks */ case 0x05: /* Ratchet & Clank (PS3) */ case 0x09: /* Puyo Puyo Tetris (PS4) */ - section_entries = (uint16_t)read_16bit(sblk_offset+0x16,streamFile); /* entry size: ~0x0c */ - material_entries = (uint16_t)read_16bit(sblk_offset+0x18,streamFile); /* entry size: ~0x08 */ - stream_entries = (uint16_t)read_16bit(sblk_offset+0x1a,streamFile); /* entry size: ~0x18 + variable */ - table1_offset = sblk_offset + read_32bit(sblk_offset+0x1c,streamFile); - table2_offset = sblk_offset + read_32bit(sblk_offset+0x20,streamFile); - table3_offset = sblk_offset + read_32bit(sblk_offset+0x34,streamFile); - table4_offset = sblk_offset + read_32bit(sblk_offset+0x38,streamFile); + section_entries = (uint16_t)read_16bit(sblk_offset+0x16,sf); /* entry size: ~0x0c */ + material_entries = (uint16_t)read_16bit(sblk_offset+0x18,sf); /* entry size: ~0x08 */ + stream_entries = (uint16_t)read_16bit(sblk_offset+0x1a,sf); /* entry size: ~0x18 + variable */ + table1_offset = sblk_offset + read_32bit(sblk_offset+0x1c,sf); + table2_offset = sblk_offset + read_32bit(sblk_offset+0x20,sf); + table3_offset = sblk_offset + read_32bit(sblk_offset+0x34,sf); + table4_offset = sblk_offset + read_32bit(sblk_offset+0x38,sf); table1_entry_size = 0x0c; table1_suboffset = 0x08; @@ -110,13 +111,13 @@ VGMSTREAM * init_vgmstream_bnk_sony(STREAMFILE *streamFile) { case 0x0d: /* Polara (Vita), Crypt of the Necrodancer (Vita) */ case 0x0e: /* Yakuza 6's Puyo Puyo (PS4) */ - table1_offset = sblk_offset + read_32bit(sblk_offset+0x18,streamFile); - table2_offset = sblk_offset + read_32bit(sblk_offset+0x1c,streamFile); - table3_offset = sblk_offset + read_32bit(sblk_offset+0x2c,streamFile); - table4_offset = sblk_offset + read_32bit(sblk_offset+0x30,streamFile); - section_entries = (uint16_t)read_16bit(sblk_offset+0x38,streamFile); /* entry size: ~0x24 */ - material_entries = (uint16_t)read_16bit(sblk_offset+0x3a,streamFile); /* entry size: ~0x08 */ - stream_entries = (uint16_t)read_16bit(sblk_offset+0x3c,streamFile); /* entry size: ~0x5c + variable */ + table1_offset = sblk_offset + read_32bit(sblk_offset+0x18,sf); + table2_offset = sblk_offset + read_32bit(sblk_offset+0x1c,sf); + table3_offset = sblk_offset + read_32bit(sblk_offset+0x2c,sf); + table4_offset = sblk_offset + read_32bit(sblk_offset+0x30,sf); + section_entries = (uint16_t)read_16bit(sblk_offset+0x38,sf); /* entry size: ~0x24 */ + material_entries = (uint16_t)read_16bit(sblk_offset+0x3a,sf); /* entry size: ~0x08 */ + stream_entries = (uint16_t)read_16bit(sblk_offset+0x3c,sf); /* entry size: ~0x5c + variable */ table1_entry_size = 0x24; table1_suboffset = 0x0c; @@ -151,19 +152,34 @@ VGMSTREAM * init_vgmstream_bnk_sony(STREAMFILE *streamFile) { case 0x01: /* table2/3 has size 0x28 entries, seemingly: * 0x00: subtype(01=sound) - * 0x0A: pitch + * 0x08: same as other versions (pitch, flags, offset...) + * rest: padding * 0x18: stream offset - * there is no stream size so we'd need some sample counting - * many sounds repeat entries for no apparent reason + * there is no stream size like in v0x03 */ - goto fail; + for (i = 0; i < material_entries; i++) { + uint8_t table2_type = read_32bit(table2_offset + (i*0x28) + 0x00, sf); + + if (table2_type != 0x01) + continue; + + total_subsongs++; + if (total_subsongs == target_subsong) { + table2_entry_offset = 0; + table3_entry_offset = (i*0x28) + 0x08; + /* continue to count all subsongs*/ + } + + } + + break; default: for (i = 0; i < material_entries; i++) { uint32_t table2_value, table2_subinfo, table2_subtype; - table2_value = (uint32_t)read_32bit(table2_offset+(i*0x08)+table2_suboffset+0x00,streamFile); + table2_value = (uint32_t)read_32bit(table2_offset+(i*0x08)+table2_suboffset+0x00,sf); table2_subinfo = (table2_value >> 0) & 0xFFFF; table2_subtype = (table2_value >> 16) & 0xFFFF; if (table2_subtype != 0x100) @@ -194,14 +210,15 @@ VGMSTREAM * init_vgmstream_bnk_sony(STREAMFILE *streamFile) { /* parse sounds */ switch(sblk_version) { + case 0x01: case 0x03: case 0x04: case 0x05: case 0x09: - pitch = (uint8_t)read_8bit(table3_offset+table3_entry_offset+0x02,streamFile); - flags = (uint8_t)read_8bit(table3_offset+table3_entry_offset+0x0f,streamFile); - stream_offset = read_32bit(table3_offset+table3_entry_offset+0x10,streamFile); - stream_size = read_32bit(table3_offset+table3_entry_offset+0x14,streamFile); + pitch = (uint8_t)read_8bit(table3_offset+table3_entry_offset+0x02,sf); + flags = (uint8_t)read_8bit(table3_offset+table3_entry_offset+0x0f,sf); + stream_offset = read_32bit(table3_offset+table3_entry_offset+0x10,sf); + stream_size = read_32bit(table3_offset+table3_entry_offset+0x14,sf); /* must use some log/formula but whatevs */ switch(pitch) { @@ -218,6 +235,7 @@ VGMSTREAM * init_vgmstream_bnk_sony(STREAMFILE *streamFile) { case 0xAF: sample_rate = 14000; break; //? case 0xAE: sample_rate = 13000; break; //? case 0xAC: sample_rate = 12000; break; //? + case 0xAB: sample_rate = 11050; break; //? case 0xAA: sample_rate = 11025; break; case 0xA9: sample_rate = 10000; break; //? case 0xA4: sample_rate = 6000; break; //? @@ -230,10 +248,10 @@ VGMSTREAM * init_vgmstream_bnk_sony(STREAMFILE *streamFile) { case 0x0d: case 0x0e: - flags = (uint8_t)read_8bit(table3_offset+table3_entry_offset+0x12,streamFile); - stream_offset = read_32bit(table3_offset+table3_entry_offset+0x44,streamFile); - stream_size = read_32bit(table3_offset+table3_entry_offset+0x48,streamFile); - sample_rate = (int)read_f32(table3_offset+table3_entry_offset+0x4c,streamFile); + flags = (uint8_t)read_8bit(table3_offset+table3_entry_offset+0x12,sf); + stream_offset = read_32bit(table3_offset+table3_entry_offset+0x44,sf); + stream_size = read_32bit(table3_offset+table3_entry_offset+0x48,sf); + sample_rate = (int)read_f32(table3_offset+table3_entry_offset+0x4c,sf); break; default: @@ -251,7 +269,7 @@ VGMSTREAM * init_vgmstream_bnk_sony(STREAMFILE *streamFile) { case 0x0e: /* find if this sound has an assigned name in table1 */ for (i = 0; i < section_entries; i++) { - off_t entry_offset = (uint16_t)read_16bit(table1_offset+(i*table1_entry_size)+table1_suboffset+0x00,streamFile); + off_t entry_offset = (uint16_t)read_16bit(table1_offset+(i*table1_entry_size)+table1_suboffset+0x00,sf); /* rarely (ex. Polara sfx) one name applies to multiple materials, * from current entry_offset to next entry_offset (section offsets should be in order) */ @@ -267,15 +285,15 @@ VGMSTREAM * init_vgmstream_bnk_sony(STREAMFILE *streamFile) { /* 0x0c: table4 size */ /* variable: entries */ /* variable: names (null terminated) */ - table4_entries_offset = table4_offset + read_32bit(table4_offset+0x08, streamFile); + table4_entries_offset = table4_offset + read_32bit(table4_offset+0x08, sf); table4_names_offset = table4_entries_offset + (0x10*section_entries); //;VGM_LOG("BNK: t4_entries=%lx, t4_names=%lx\n", table4_entries_offset, table4_names_offset); /* get assigned name from table4 names */ for (i = 0; i < section_entries; i++) { - int entry_id = read_32bit(table4_entries_offset+(i*0x10)+0x0c, streamFile); + int entry_id = read_32bit(table4_entries_offset+(i*0x10)+0x0c, sf); if (entry_id == table4_entry_id) { - name_offset = table4_names_offset + read_32bit(table4_entries_offset+(i*0x10)+0x00, streamFile); + name_offset = table4_names_offset + read_32bit(table4_entries_offset+(i*0x10)+0x00, sf); break; } } @@ -302,6 +320,29 @@ VGMSTREAM * init_vgmstream_bnk_sony(STREAMFILE *streamFile) { case 0x05: channel_count = 1; + /* early versions don't have PS-ADPCM size, could check next offset but it's all kind of loopy */ + if (sblk_version <= 0x03 && stream_size == 0 && (flags & 0x80) == 0) { + off_t offset; + off_t max_offset = get_streamfile_size(sf); + + stream_size += 0x10; + for (offset = data_offset + stream_offset + 0x10; offset < max_offset; offset += 0x10) { + + /* beginning frame (if file loops won't have end frame) */ + if (read_32bitBE(offset + 0x00, sf) == 0x00000000 && read_32bitBE(offset + 0x04, sf) == 0x00000000) + break; + + stream_size += 0x10; + + /* end frame */ + if (read_32bitBE(offset + 0x00, sf) == 0x00077777 && read_32bitBE(offset + 0x04, sf) == 0x77777777) + break; + } + + //;VGM_LOG("BNK: stream offset=%lx + %lx, new size=%x\n", data_offset, stream_offset, stream_size); + } + + /* hack for PS3 files that use dual subsongs as stereo */ if (total_subsongs == 2 && stream_size * 2 == data_size) { channel_count = 2; @@ -314,7 +355,7 @@ VGMSTREAM * init_vgmstream_bnk_sony(STREAMFILE *streamFile) { codec = PCM16; /* rare [Wipeout HD (PS3)] */ } else { - loop_flag = ps_find_loop_offsets(streamFile, start_offset, stream_size, channel_count, interleave, &loop_start, &loop_end); + loop_flag = ps_find_loop_offsets(sf, start_offset, stream_size, channel_count, interleave, &loop_start, &loop_end); loop_flag = (flags & 0x40); /* no loops values in sight so may only apply to PS-ADPCM flags */ codec = PSX; @@ -324,20 +365,20 @@ VGMSTREAM * init_vgmstream_bnk_sony(STREAMFILE *streamFile) { break; case 0x09: - type = read_16bit(start_offset+0x00,streamFile); - extradata_size = 0x08 + read_32bit(start_offset+0x04,streamFile); /* 0x14 for AT9 */ + type = read_16bit(start_offset+0x00,sf); + extradata_size = 0x08 + read_32bit(start_offset+0x04,sf); /* 0x14 for AT9 */ switch(type) { case 0x02: /* ATRAC9 mono */ case 0x05: /* ATRAC9 stereo */ - if (read_32bit(start_offset+0x08,streamFile) + 0x08 != extradata_size) /* repeat? */ + if (read_32bit(start_offset+0x08,sf) + 0x08 != extradata_size) /* repeat? */ goto fail; channel_count = (type == 0x02) ? 1 : 2; - atrac9_info = (uint32_t)read_32bitBE(start_offset+0x0c,streamFile); + atrac9_info = (uint32_t)read_32bitBE(start_offset+0x0c,sf); /* 0x10: null? */ - loop_length = read_32bit(start_offset+0x14,streamFile); - loop_start = read_32bit(start_offset+0x18,streamFile); + loop_length = read_32bit(start_offset+0x14,sf); + loop_start = read_32bit(start_offset+0x18,sf); loop_end = loop_start + loop_length; /* loop_start is -1 if not set */ codec = ATRAC9; @@ -351,26 +392,26 @@ VGMSTREAM * init_vgmstream_bnk_sony(STREAMFILE *streamFile) { case 0x0d: case 0x0e: - type = read_16bit(start_offset+0x00,streamFile); - if (read_32bit(start_offset+0x04,streamFile) != 0x01) /* type? */ + type = read_16bit(start_offset+0x00,sf); + if (read_32bit(start_offset+0x04,sf) != 0x01) /* type? */ goto fail; - extradata_size = 0x10 + read_32bit(start_offset+0x08,streamFile); /* 0x80 for AT9, 0x10 for PCM/PS-ADPCM */ + extradata_size = 0x10 + read_32bit(start_offset+0x08,sf); /* 0x80 for AT9, 0x10 for PCM/PS-ADPCM */ /* 0x0c: null? */ switch(type) { case 0x02: /* ATRAC9 mono */ case 0x05: /* ATRAC9 stereo */ - if (read_32bit(start_offset+0x10,streamFile) + 0x10 != extradata_size) /* repeat? */ + if (read_32bit(start_offset+0x10,sf) + 0x10 != extradata_size) /* repeat? */ goto fail; channel_count = (type == 0x02) ? 1 : 2; - atrac9_info = (uint32_t)read_32bitBE(start_offset+0x14,streamFile); + atrac9_info = (uint32_t)read_32bitBE(start_offset+0x14,sf); /* 0x18: null? */ /* 0x1c: channels? */ /* 0x20: null? */ - loop_length = read_32bit(start_offset+0x24,streamFile); - loop_start = read_32bit(start_offset+0x28,streamFile); + loop_length = read_32bit(start_offset+0x24,sf); + loop_start = read_32bit(start_offset+0x28,sf); loop_end = loop_start + loop_length; /* loop_start is -1 if not set */ codec = ATRAC9; @@ -379,11 +420,11 @@ VGMSTREAM * init_vgmstream_bnk_sony(STREAMFILE *streamFile) { case 0x01: /* PCM16LE mono? (NekoBuro/Polara sfx) */ case 0x04: /* PCM16LE stereo? (NekoBuro/Polara sfx) */ /* 0x10: null? */ - channel_count = read_32bit(start_offset+0x14,streamFile); + channel_count = read_32bit(start_offset+0x14,sf); interleave = 0x02; - loop_start = read_32bit(start_offset+0x18,streamFile); - loop_length = read_32bit(start_offset+0x1c,streamFile); + loop_start = read_32bit(start_offset+0x18,sf); + loop_length = read_32bit(start_offset+0x1c,sf); loop_end = loop_start + loop_length; /* loop_start is -1 if not set */ codec = PCM16; @@ -391,11 +432,11 @@ VGMSTREAM * init_vgmstream_bnk_sony(STREAMFILE *streamFile) { case 0x00: /* PS-ADPCM (test banks) */ /* 0x10: null? */ - channel_count = read_32bit(start_offset+0x14,streamFile); + channel_count = read_32bit(start_offset+0x14,sf); interleave = 0x02; - loop_start = read_32bit(start_offset+0x18,streamFile); - loop_length = read_32bit(start_offset+0x1c,streamFile); + loop_start = read_32bit(start_offset+0x18,sf); + loop_length = read_32bit(start_offset+0x1c,sf); loop_end = loop_start + loop_length; /* loop_start is -1 if not set */ codec = HEVAG; @@ -486,10 +527,10 @@ VGMSTREAM * init_vgmstream_bnk_sony(STREAMFILE *streamFile) { } if (name_offset) - read_string(vgmstream->stream_name,STREAM_NAME_SIZE, name_offset,streamFile); + read_string(vgmstream->stream_name,STREAM_NAME_SIZE, name_offset,sf); - if (!vgmstream_open_stream(vgmstream,streamFile,start_offset)) + if (!vgmstream_open_stream(vgmstream, sf, start_offset)) goto fail; return vgmstream; fail: @@ -500,12 +541,16 @@ fail: #if 0 /* .BNK - Sony's bank, earlier version [Jak and Daxter (PS2), NCAA Gamebreaker 2001 (PS2)] */ -VGMSTREAM * init_vgmstream_bnk_sony_v2(STREAMFILE *streamFile) { +VGMSTREAM * init_vgmstream_bnk_sony_v2(STREAMFILE *sf) { /* 0x00: 0x00000001 * 0x04: sections (2 or 3) - * 0x08+ similar to v3 but "SBv2" - * table formats is a bit different - * header is like v3 but stream size is in other table? + * 0x08+: similar as above (start, size) but with "SBv2" + * + * 0x2C/2E=entries? + * 0x34: table offsets (from sbv2 start) + * - table1: 0x1c entries + * - table2: 0x08 entries, possibly point to table3 + * - table3: 0x18 entries, same format as early SBlk (pitch/flags/offset, no size) */ fail: diff --git a/Frameworks/vgmstream/vgmstream/src/meta/bnsf.c b/Frameworks/vgmstream/vgmstream/src/meta/bnsf.c index 3e0d1c0d6..1805d1065 100644 --- a/Frameworks/vgmstream/vgmstream/src/meta/bnsf.c +++ b/Frameworks/vgmstream/vgmstream/src/meta/bnsf.c @@ -4,12 +4,13 @@ #include "bnsf_keys.h" +#ifdef VGM_USE_G7221 //#define BNSF_BRUTEFORCE #ifdef BNSF_BRUTEFORCE static void bruteforce_bnsf_key(STREAMFILE* sf, off_t start, g7221_codec_data* data, uint8_t* best_key); #endif static void find_bnsf_key(STREAMFILE *sf, off_t start, g7221_codec_data *data, uint8_t *best_key); - +#endif /* BNSF - Bandai Namco Sound Format/File [Tales of Graces (Wii), Tales of Berseria (PS4)] */ VGMSTREAM * init_vgmstream_bnsf(STREAMFILE *streamFile) { @@ -126,6 +127,7 @@ fail: return NULL; } +#ifdef VGM_USE_G7221 static inline void test_key(STREAMFILE* sf, off_t start, g7221_codec_data* data, const char* key, int keylen, int* p_best_score, uint8_t* p_best_key) { uint8_t tmpkey[24]; int score; @@ -219,3 +221,5 @@ static void bruteforce_bnsf_key(STREAMFILE* sf, off_t start, g7221_codec_data* d close_streamfile(sf_keys); } #endif + +#endif diff --git a/Frameworks/vgmstream/vgmstream/src/meta/deblock_streamfile.c b/Frameworks/vgmstream/vgmstream/src/meta/deblock_streamfile.c index eda65a786..9ca3ce049 100644 --- a/Frameworks/vgmstream/vgmstream/src/meta/deblock_streamfile.c +++ b/Frameworks/vgmstream/vgmstream/src/meta/deblock_streamfile.c @@ -13,6 +13,7 @@ static void block_callback_default(STREAMFILE *sf, deblock_io_data *data) { static size_t deblock_io_read(STREAMFILE *sf, uint8_t *dest, off_t offset, size_t length, deblock_io_data* data) { size_t total_read = 0; + //;VGM_LOG("DEBLOCK: of=%lx, sz=%x, po=%lx\n", offset, length, data->physical_offset); /* re-start when previous offset (can't map logical<>physical offsets) */ if (data->logical_offset < 0 || offset < data->logical_offset) { @@ -81,11 +82,11 @@ static size_t deblock_io_read(STREAMFILE *sf, uint8_t *dest, off_t offset, size_ data->data_size = 0; data->step_count = data->cfg.step_count; - //VGM_LOG("ignore at %lx + %lx, skips=%i, reads=%i\n", data->physical_offset, data->block_size, data->step_count, data->read_count); + //VGM_LOG("ignore at %lx + %lx, skips=%i\n", data->physical_offset, data->block_size, data->step_count); continue; } - //VGM_LOG("accept at %lx + %lx, skips=%i, reads=%i\n", data->physical_offset, data->block_size, data->step_count, data->read_count); + //;VGM_LOG("accept at %lx + %lx, skips=%i\n", data->physical_offset, data->block_size, data->step_count); /* read block data */ { diff --git a/Frameworks/vgmstream/vgmstream/src/meta/ea_eaac.c b/Frameworks/vgmstream/vgmstream/src/meta/ea_eaac.c index 5db362cf6..2b551ccf1 100644 --- a/Frameworks/vgmstream/vgmstream/src/meta/ea_eaac.c +++ b/Frameworks/vgmstream/vgmstream/src/meta/ea_eaac.c @@ -1618,11 +1618,13 @@ static layered_layout_data* build_layered_eaaudiocore(STREAMFILE *sf_data, eaac_ if ( !vgmstream_open_stream(data->layers[i], temp_sf, 0x00) ) { goto fail; } + + close_streamfile(temp_sf); + temp_sf = NULL; } if (!setup_layout_layered(data)) goto fail; - close_streamfile(temp_sf); return data; fail: diff --git a/Frameworks/vgmstream/vgmstream/src/meta/encrypted.c b/Frameworks/vgmstream/vgmstream/src/meta/encrypted.c new file mode 100644 index 000000000..488823290 --- /dev/null +++ b/Frameworks/vgmstream/vgmstream/src/meta/encrypted.c @@ -0,0 +1,86 @@ +#include "meta.h" +#include "../coding/coding.h" +#include "ogg_vorbis_streamfile.h" + +//todo fuse ogg encryptions and use generic names + + +static const uint8_t tpf_key[] = { + 0x0a,0x2b,0x36,0x6f,0x0b,0x0a,0x2b,0x36,0x6f,0x0B +}; + +static void load_key(ogg_vorbis_io_config_data* cfg, const uint8_t* key, size_t size) { + cfg->is_encrypted = 1; + cfg->key_len = size; + memcpy(cfg->key, key, size); +} + +/* parser for various encrypted games */ +VGMSTREAM* init_vgmstream_encrypted(STREAMFILE* sf) { + VGMSTREAM* vgmstream = NULL; + STREAMFILE* temp_sf = NULL; + ogg_vorbis_io_config_data cfg = {0}; + uint32_t id; + + + /* checks */ + id = read_u32be(0x00, sf); + + if (check_extensions(sf,"ogg,logg")) { + /* The Pirate's Fate (PC) */ + if (id == 0x454C513C) { /* "OggS" xored */ + load_key(&cfg, tpf_key, sizeof(tpf_key)); + } + else { + goto fail; + } + + temp_sf = setup_ogg_vorbis_streamfile(sf, cfg); + if (!temp_sf) goto fail; +#ifdef VGM_USE_VORBIS + vgmstream = init_vgmstream_ogg_vorbis(temp_sf); +#endif + close_streamfile(temp_sf); + return vgmstream; + } + + if (check_extensions(sf,"mp3")) { + /* The Pirate's Fate (PC) */ + if ((id & 0xFFFFFF00) == 0x436F0500) { /* "ID3\0" xored */ + load_key(&cfg, tpf_key, sizeof(tpf_key)); + } + else { + goto fail; + } + + temp_sf = setup_ogg_vorbis_streamfile(sf, cfg); + if (!temp_sf) goto fail; + +#ifdef VGM_USE_FFMPEG //TODO: allow MP3 without FFmpeg + vgmstream = init_vgmstream_ffmpeg(temp_sf); +#endif + close_streamfile(temp_sf); + return vgmstream; + } + + if (check_extensions(sf,"wav,lwav")) { + /* The Pirate's Fate (PC) */ + if (id == 0x58627029) { /* "RIFF" xored */ + load_key(&cfg, tpf_key, sizeof(tpf_key)); + } + else { + goto fail; + } + + temp_sf = setup_ogg_vorbis_streamfile(sf, cfg); + if (!temp_sf) goto fail; + + vgmstream = init_vgmstream_riff(temp_sf); + close_streamfile(temp_sf); + return vgmstream; + } + + +fail: + return NULL; +} diff --git a/Frameworks/vgmstream/vgmstream/src/meta/fsb5.c b/Frameworks/vgmstream/vgmstream/src/meta/fsb5.c index 67f008500..58107cd40 100644 --- a/Frameworks/vgmstream/vgmstream/src/meta/fsb5.c +++ b/Frameworks/vgmstream/vgmstream/src/meta/fsb5.c @@ -1,629 +1,629 @@ -#include "meta.h" -#include "../coding/coding.h" -#include "../layout/layout.h" -#include "fsb5_interleave_streamfile.h" - - -typedef struct { - int total_subsongs; - int version; - int codec; - int flags; - - int channels; - int sample_rate; - int32_t num_samples; - int32_t loop_start; - int32_t loop_end; - int loop_flag; - - off_t sample_header_offset; - size_t sample_header_size; - size_t name_table_size; - size_t sample_data_size; - size_t base_header_size; - - off_t extradata_offset; - size_t extradata_size; - - off_t stream_offset; - size_t stream_size; - off_t name_offset; -} fsb5_header; - -/* ********************************************************************************** */ - -static layered_layout_data* build_layered_fsb5_celt(STREAMFILE *streamFile, fsb5_header* fsb5); -static layered_layout_data* build_layered_fsb5_atrac9(STREAMFILE *streamFile, fsb5_header* fsb5, off_t configs_offset, size_t configs_size); - -/* FSB5 - FMOD Studio multiplatform format */ -VGMSTREAM * init_vgmstream_fsb5(STREAMFILE *streamFile) { - VGMSTREAM * vgmstream = NULL; - fsb5_header fsb5 = {0}; - int target_subsong = streamFile->stream_index; - int i; - - - /* checks */ - /* .fsb: standard - * .snd: Alchemy engine (also Unity) */ - if (!check_extensions(streamFile,"fsb,snd")) - goto fail; - - if (read_32bitBE(0x00,streamFile) != 0x46534235) /* "FSB5" */ - goto fail; - - /* 0x00 is rare (seen in Tales from Space Vita) */ - fsb5.version = read_32bitLE(0x04,streamFile); - if (fsb5.version != 0x00 && fsb5.version != 0x01) goto fail; - - fsb5.total_subsongs = read_32bitLE(0x08,streamFile); - fsb5.sample_header_size = read_32bitLE(0x0C,streamFile); - fsb5.name_table_size = read_32bitLE(0x10,streamFile); - fsb5.sample_data_size = read_32bitLE(0x14,streamFile); - fsb5.codec = read_32bitLE(0x18,streamFile); - /* version 0x01 - 0x1c(4): zero, 0x24(16): hash, 0x34(8): unk - * version 0x00 has an extra field (always 0?) at 0x1c */ - if (fsb5.version == 0x01) { - /* found by tests and assumed to be flags, no games known */ - fsb5.flags = read_32bitLE(0x20,streamFile); - } - fsb5.base_header_size = (fsb5.version==0x00) ? 0x40 : 0x3C; - - if ((fsb5.sample_header_size + fsb5.name_table_size + fsb5.sample_data_size + fsb5.base_header_size) != get_streamfile_size(streamFile)) { - VGM_LOG("FSB5: bad size (%x + %x + %x + %x != %x)\n", fsb5.sample_header_size, fsb5.name_table_size, fsb5.sample_data_size, fsb5.base_header_size, get_streamfile_size(streamFile)); - goto fail; - } - - if (target_subsong == 0) target_subsong = 1; - if (target_subsong > fsb5.total_subsongs || fsb5.total_subsongs <= 0) goto fail; - - fsb5.sample_header_offset = fsb5.base_header_size; - - /* find target stream header and data offset, and read all needed values for later use - * (reads one by one as the size of a single stream header is variable) */ - for (i = 0; i < fsb5.total_subsongs; i++) { - size_t stream_header_size = 0; - off_t data_offset = 0; - uint32_t sample_mode1, sample_mode2; /* maybe one uint64? */ - - sample_mode1 = (uint32_t)read_32bitLE(fsb5.sample_header_offset+0x00,streamFile); - sample_mode2 = (uint32_t)read_32bitLE(fsb5.sample_header_offset+0x04,streamFile); - stream_header_size += 0x08; - - /* get samples */ - fsb5.num_samples = ((sample_mode2 >> 2) & 0x3FFFFFFF); /* bits2: 31..2 (30) */ - - /* get offset inside data section */ - /* up to 0x07FFFFFF * 0x20 = full 32b offset 0xFFFFFFE0 */ - data_offset = (((sample_mode2 & 0x03) << 25) | ((sample_mode1 >> 7) & 0x1FFFFFF)) << 5; /* bits2: 1..0 (2) | bits1: 31..8 (25) */ - - /* get channels */ - switch ((sample_mode1 >> 5) & 0x03) { /* bits1: 7..6 (2) */ - case 0: fsb5.channels = 1; break; - case 1: fsb5.channels = 2; break; - case 2: fsb5.channels = 6; break; /* some Dark Souls 2 MPEG; some IMA ADPCM */ - case 3: fsb5.channels = 8; break; /* some IMA ADPCM */ - /* other channels (ex. 4/10/12ch) use 0 here + set extra flags */ - default: /* not possible */ - goto fail; - } - - /* get sample rate */ - switch ((sample_mode1 >> 1) & 0x0f) { /* bits1: 5..1 (4) */ - case 0: fsb5.sample_rate = 4000; break; - case 1: fsb5.sample_rate = 8000; break; - case 2: fsb5.sample_rate = 11000; break; - case 3: fsb5.sample_rate = 11025; break; - case 4: fsb5.sample_rate = 16000; break; - case 5: fsb5.sample_rate = 22050; break; - case 6: fsb5.sample_rate = 24000; break; - case 7: fsb5.sample_rate = 32000; break; - case 8: fsb5.sample_rate = 44100; break; - case 9: fsb5.sample_rate = 48000; break; - case 10: fsb5.sample_rate = 96000; break; - /* other sample rates (ex. 3000/64000/192000) use 0 here + set extra flags */ - default: /* 11-15: rejected (FMOD error) */ - goto fail; - } - - /* get extra flags */ - if (sample_mode1 & 0x01) { /* bits1: 0 (1) */ - off_t extraflag_offset = fsb5.sample_header_offset+0x08; - uint32_t extraflag, extraflag_type, extraflag_size, extraflag_end; - - do { - extraflag = read_32bitLE(extraflag_offset,streamFile); - extraflag_type = (extraflag >> 25) & 0x7F; /* bits 32..26 (7) */ - extraflag_size = (extraflag >> 1) & 0xFFFFFF; /* bits 25..1 (24)*/ - extraflag_end = (extraflag & 0x01); /* bit 0 (1) */ - - /* parse target only, as flags change between subsongs */ - if (i + 1 == target_subsong) { - switch(extraflag_type) { - case 0x01: /* channels */ - fsb5.channels = read_8bit(extraflag_offset+0x04,streamFile); - break; - case 0x02: /* sample rate */ - fsb5.sample_rate = read_32bitLE(extraflag_offset+0x04,streamFile); - break; - case 0x03: /* loop info */ - fsb5.loop_start = read_32bitLE(extraflag_offset+0x04,streamFile); - if (extraflag_size > 0x04) { /* probably not needed */ - fsb5.loop_end = read_32bitLE(extraflag_offset+0x08,streamFile); - fsb5.loop_end += 1; /* correct compared to FMOD's tools */ - } - //;VGM_LOG("FSB5: stream %i loop start=%i, loop end=%i, samples=%i\n", i, fsb5.loop_start, fsb5.loop_end, fsb5.num_samples); - - /* autodetect unwanted loops */ - { - /* like FSB4 jingles/sfx/music do full loops for no reason, but happens a lot less. - * Most songs loop normally now with proper values [ex. Shantae, FFX] */ - int full_loop, ajurika_loops, is_small; - - /* disable some jingles, it's even possible one jingle (StingerA Var1) to not have loops - * and next one (StingerA Var2) do [Sonic Boom Fire & Ice (3DS)] */ - full_loop = fsb5.loop_start == 0 && fsb5.loop_end + 1152 >= fsb5.num_samples; /* around ~15 samples less, ~1000 for MPEG */ - /* a few longer Sonic songs shouldn't repeat */ - is_small = 1; //fsb5.num_samples < 20 * fsb5.sample_rate; - - /* wrong values in some files [Pac-Man CE2 Plus (Switch) pce2p_bgm_ajurika_*.fsb] */ - ajurika_loops = fsb5.loop_start == 0x3c && fsb5.loop_end == 0x007F007F && - fsb5.num_samples > fsb5.loop_end + 10000; /* arbitrary test in case some game does have those */ - - fsb5.loop_flag = 1; - if ((full_loop && is_small) || ajurika_loops) { - VGM_LOG("FSB5: stream %i disabled unwanted loop ls=%i, le=%i, ns=%i\n", i, fsb5.loop_start, fsb5.loop_end, fsb5.num_samples); - fsb5.loop_flag = 0; - } - } - break; - case 0x04: /* free comment, or maybe SFX info */ - break; - case 0x05: /* unknown 32b */ - /* rare, found in Tearaway (Vita) with value 0 in first stream and - * Shantae and the Seven Sirens (Mobile) with value 0x0003bd72 BE in #44 (Arena Town) */ - VGM_LOG("FSB5: stream %i flag %x with value %08x\n", i, extraflag_type, read_32bitLE(extraflag_offset+0x04,streamFile)); - break; - case 0x06: /* XMA seek table */ - /* no need for it */ - break; - case 0x07: /* DSP coefs */ - fsb5.extradata_offset = extraflag_offset + 0x04; - break; - case 0x09: /* ATRAC9 config */ - fsb5.extradata_offset = extraflag_offset + 0x04; - fsb5.extradata_size = extraflag_size; - break; - case 0x0a: /* XWMA config */ - fsb5.extradata_offset = extraflag_offset + 0x04; - break; - case 0x0b: /* Vorbis setup ID and seek table */ - fsb5.extradata_offset = extraflag_offset + 0x04; - /* seek table format: - * 0x08: table_size (total_entries = seek_table_size / (4+4)), not counting this value; can be 0 - * 0x0C: sample number (only some samples are saved in the table) - * 0x10: offset within data, pointing to a FSB vorbis block (with the 16b block size header) - * (xN entries) - */ - break; - case 0x0d: /* unknown 32b (config? usually 0x3fnnnn00 BE and sometimes 0x3dnnnn00 BE) */ - /* found in some XMA2/Vorbis/FADPCM */ - VGM_LOG("FSB5: stream %i flag %x with value %08x\n", i, extraflag_type, read_32bitLE(extraflag_offset+0x04,streamFile)); - break; - default: - VGM_LOG("FSB5: stream %i unknown flag 0x%x at %x + 0x04 (size 0x%x)\n", i, extraflag_type, (uint32_t)extraflag_offset, extraflag_size); - break; - } - } - - extraflag_offset += 0x04 + extraflag_size; - stream_header_size += 0x04 + extraflag_size; - } while (extraflag_end != 0x00); - } - - /* target found */ - if (i + 1 == target_subsong) { - fsb5.stream_offset = fsb5.base_header_size + fsb5.sample_header_size + fsb5.name_table_size + data_offset; - - /* get stream size from next stream offset or full size if there is only one */ - if (i + 1 == fsb5.total_subsongs) { - fsb5.stream_size = fsb5.sample_data_size - data_offset; - } - else { - off_t next_data_offset; - uint32_t next_sample_mode1, next_sample_mode2; - next_sample_mode1 = (uint32_t)read_32bitLE(fsb5.sample_header_offset+stream_header_size+0x00,streamFile); - next_sample_mode2 = (uint32_t)read_32bitLE(fsb5.sample_header_offset+stream_header_size+0x04,streamFile); - next_data_offset = (((next_sample_mode2 & 0x03) << 25) | ((next_sample_mode1 >> 7) & 0x1FFFFFF)) << 5; - - fsb5.stream_size = next_data_offset - data_offset; - } - - break; - } - - /* continue searching target */ - fsb5.sample_header_offset += stream_header_size; - } - /* target stream not found*/ - if (!fsb5.stream_offset || !fsb5.stream_size) goto fail; - - /* get stream name */ - if (fsb5.name_table_size) { - off_t name_suboffset = fsb5.base_header_size + fsb5.sample_header_size + 0x04*(target_subsong-1); - fsb5.name_offset = fsb5.base_header_size + fsb5.sample_header_size + read_32bitLE(name_suboffset,streamFile); - } - - - /* build the VGMSTREAM */ - vgmstream = allocate_vgmstream(fsb5.channels,fsb5.loop_flag); - if (!vgmstream) goto fail; - - vgmstream->sample_rate = fsb5.sample_rate; - vgmstream->num_samples = fsb5.num_samples; - if (fsb5.loop_flag) { - vgmstream->loop_start_sample = fsb5.loop_start; - vgmstream->loop_end_sample = fsb5.loop_end; - } - vgmstream->num_streams = fsb5.total_subsongs; - vgmstream->stream_size = fsb5.stream_size; - vgmstream->meta_type = meta_FSB5; - if (fsb5.name_offset) - read_string(vgmstream->stream_name,STREAM_NAME_SIZE, fsb5.name_offset,streamFile); - - switch (fsb5.codec) { - case 0x00: /* FMOD_SOUND_FORMAT_NONE */ - goto fail; - - case 0x01: /* FMOD_SOUND_FORMAT_PCM8 [Anima - Gate of Memories (PC)] */ - vgmstream->coding_type = coding_PCM8_U; - vgmstream->layout_type = fsb5.channels == 1 ? layout_none : layout_interleave; - vgmstream->interleave_block_size = 0x01; - break; - - case 0x02: /* FMOD_SOUND_FORMAT_PCM16 [Shantae Risky's Revenge (PC)] */ - vgmstream->coding_type = (fsb5.flags & 0x01) ? coding_PCM16BE : coding_PCM16LE; - vgmstream->layout_type = fsb5.channels == 1 ? layout_none : layout_interleave; - vgmstream->interleave_block_size = 0x02; - break; - - case 0x03: /* FMOD_SOUND_FORMAT_PCM24 */ - VGM_LOG("FSB5: FMOD_SOUND_FORMAT_PCM24 found\n"); - goto fail; - - case 0x04: /* FMOD_SOUND_FORMAT_PCM32 */ - VGM_LOG("FSB5: FMOD_SOUND_FORMAT_PCM32 found\n"); - goto fail; - - case 0x05: /* FMOD_SOUND_FORMAT_PCMFLOAT [Anima: Gate of Memories (PC)] */ - vgmstream->coding_type = coding_PCMFLOAT; - vgmstream->layout_type = (fsb5.channels == 1) ? layout_none : layout_interleave; - vgmstream->interleave_block_size = 0x04; - break; - - case 0x06: /* FMOD_SOUND_FORMAT_GCADPCM [Sonic Boom: Fire and Ice (3DS)] */ - if (fsb5.flags & 0x02) { /* non-interleaved mode */ - vgmstream->coding_type = coding_NGC_DSP; - vgmstream->layout_type = layout_interleave; - vgmstream->interleave_block_size = (fsb5.stream_size / fsb5.channels); - } - else { - vgmstream->coding_type = coding_NGC_DSP_subint; - vgmstream->layout_type = layout_none; - vgmstream->interleave_block_size = 0x02; - } - dsp_read_coefs_be(vgmstream,streamFile,fsb5.extradata_offset,0x2E); - break; - - case 0x07: /* FMOD_SOUND_FORMAT_IMAADPCM [Skylanders] */ - vgmstream->coding_type = (vgmstream->channels > 2) ? coding_FSB_IMA : coding_XBOX_IMA; - vgmstream->layout_type = layout_none; - break; - - case 0x08: /* FMOD_SOUND_FORMAT_VAG [from fsbankex tests, no known games] */ - vgmstream->coding_type = coding_PSX; - vgmstream->layout_type = layout_interleave; - if (fsb5.flags & 0x02) { /* non-interleaved mode */ - vgmstream->interleave_block_size = (fsb5.stream_size / fsb5.channels); - } - else { - vgmstream->interleave_block_size = 0x10; - } - break; - - case 0x09: /* FMOD_SOUND_FORMAT_HEVAG [Guacamelee (Vita)] */ - vgmstream->coding_type = coding_HEVAG; - vgmstream->layout_type = layout_interleave; - vgmstream->interleave_block_size = 0x10; - break; - -#ifdef VGM_USE_FFMPEG - case 0x0A: {/* FMOD_SOUND_FORMAT_XMA [Minecraft Story Mode (X360)] */ - uint8_t buf[0x100]; - int bytes, block_size, block_count; - - block_size = 0x8000; /* FSB default */ - block_count = fsb5.stream_size / block_size + (fsb5.stream_size % block_size ? 1 : 0); - - bytes = ffmpeg_make_riff_xma2(buf, 0x100, vgmstream->num_samples, fsb5.stream_size, vgmstream->channels, vgmstream->sample_rate, block_count, block_size); - vgmstream->codec_data = init_ffmpeg_header_offset(streamFile, buf,bytes, fsb5.stream_offset,fsb5.stream_size); - if (!vgmstream->codec_data) goto fail; - vgmstream->coding_type = coding_FFmpeg; - vgmstream->layout_type = layout_none; - - xma_fix_raw_samples(vgmstream, streamFile, fsb5.stream_offset,fsb5.stream_size, 0, 0,0); /* samples look ok */ - break; - } -#endif - -#ifdef VGM_USE_MPEG - case 0x0B: {/* FMOD_SOUND_FORMAT_MPEG [Final Fantasy X HD (PS3), Shantae Risky's Revenge (PC)] */ - mpeg_custom_config cfg = {0}; - - cfg.fsb_padding = (vgmstream->channels > 2 ? 16 : 4); /* observed default */ - - vgmstream->codec_data = init_mpeg_custom(streamFile, fsb5.stream_offset, &vgmstream->coding_type, vgmstream->channels, MPEG_FSB, &cfg); - if (!vgmstream->codec_data) goto fail; - vgmstream->layout_type = layout_none; - break; - } -#endif - -#ifdef VGM_USE_CELT - case 0x0C: { /* FMOD_SOUND_FORMAT_CELT [BIT.TRIP Presents Runner2 (PC), Full Bore (PC)] */ - int is_multistream = fsb5.channels > 2; - - if (is_multistream) { - vgmstream->layout_data = build_layered_fsb5_celt(streamFile, &fsb5); - if (!vgmstream->layout_data) goto fail; - vgmstream->coding_type = coding_CELT_FSB; - vgmstream->layout_type = layout_layered; - } - else { - vgmstream->codec_data = init_celt_fsb(vgmstream->channels, CELT_0_11_0); - if (!vgmstream->codec_data) goto fail; - vgmstream->coding_type = coding_CELT_FSB; - vgmstream->layout_type = layout_none; - } - break; - } -#endif - -#ifdef VGM_USE_ATRAC9 - case 0x0D: {/* FMOD_SOUND_FORMAT_AT9 */ - int is_multistream; - off_t configs_offset = fsb5.extradata_offset; - size_t configs_size = fsb5.extradata_size; - - - /* skip frame size in newer FSBs [Day of the Tentacle Remastered (Vita), Tearaway Unfolded (PS4)] */ - if (configs_size >= 0x08 && (uint8_t)read_8bit(configs_offset, streamFile) != 0xFE) { /* ATRAC9 sync */ - configs_offset += 0x04; - configs_size -= 0x04; - } - - is_multistream = (configs_size / 0x04) > 1; - - if (is_multistream) { - /* multichannel made of various streams [Little Big Planet (Vita)] */ - vgmstream->layout_data = build_layered_fsb5_atrac9(streamFile, &fsb5, configs_offset, configs_size); - if (!vgmstream->layout_data) goto fail; - vgmstream->coding_type = coding_ATRAC9; - vgmstream->layout_type = layout_layered; - } - else { - /* standard ATRAC9, can be multichannel [Tearaway Unfolded (PS4)] */ - atrac9_config cfg = {0}; - - cfg.channels = vgmstream->channels; - cfg.config_data = read_32bitBE(configs_offset,streamFile); - //cfg.encoder_delay = 0x100; //todo not used? num_samples seems to count all data - - vgmstream->codec_data = init_atrac9(&cfg); - if (!vgmstream->codec_data) goto fail; - vgmstream->coding_type = coding_ATRAC9; - vgmstream->layout_type = layout_none; - } - break; - } -#endif - -#ifdef VGM_USE_FFMPEG - case 0x0E: { /* FMOD_SOUND_FORMAT_XWMA [from fsbankex tests, no known games] */ - uint8_t buf[0x100]; - int bytes, format, average_bps, block_align; - - format = read_16bitBE(fsb5.extradata_offset+0x00,streamFile); - block_align = (uint16_t)read_16bitBE(fsb5.extradata_offset+0x02,streamFile); - average_bps = (uint32_t)read_32bitBE(fsb5.extradata_offset+0x04,streamFile); - /* rest: seek entries + mini seek table? */ - /* XWMA encoder only does up to 6ch (doesn't use FSB multistreams for more) */ - - bytes = ffmpeg_make_riff_xwma(buf,0x100, format, fsb5.stream_size, vgmstream->channels, vgmstream->sample_rate, average_bps, block_align); - vgmstream->codec_data = init_ffmpeg_header_offset(streamFile, buf,bytes, fsb5.stream_offset,fsb5.stream_size); - if ( !vgmstream->codec_data ) goto fail; - vgmstream->coding_type = coding_FFmpeg; - vgmstream->layout_type = layout_none; - break; - } -#endif - -#ifdef VGM_USE_VORBIS - case 0x0F: {/* FMOD_SOUND_FORMAT_VORBIS [Shantae Half Genie Hero (PC), Pokemon Go (iOS)] */ - vorbis_custom_config cfg = {0}; - - cfg.channels = vgmstream->channels; - cfg.sample_rate = vgmstream->sample_rate; - cfg.setup_id = read_32bitLE(fsb5.extradata_offset,streamFile); - - vgmstream->layout_type = layout_none; - vgmstream->coding_type = coding_VORBIS_custom; - vgmstream->codec_data = init_vorbis_custom(streamFile, fsb5.stream_offset, VORBIS_FSB, &cfg); - if (!vgmstream->codec_data) goto fail; - - break; - } -#endif - - case 0x10: /* FMOD_SOUND_FORMAT_FADPCM [Dead Rising 4 (PC), Sine Mora Ex (Switch)] */ - vgmstream->coding_type = coding_FADPCM; - vgmstream->layout_type = layout_interleave; - vgmstream->interleave_block_size = 0x8c; - break; - - default: - VGM_LOG("FSB5: unknown codec %x found\n", fsb5.codec); - goto fail; - } - - if (!vgmstream_open_stream(vgmstream,streamFile,fsb5.stream_offset)) - goto fail; - - return vgmstream; - -fail: - close_vgmstream(vgmstream); - return NULL; -} - - -static layered_layout_data* build_layered_fsb5_celt(STREAMFILE *streamFile, fsb5_header* fsb5) { - layered_layout_data* data = NULL; - STREAMFILE* temp_streamFile = NULL; - int i, layers = (fsb5->channels+1) / 2; - size_t interleave; - - if (read_32bitBE(fsb5->stream_offset+0x00,streamFile) != 0x17C30DF3) /* FSB CELT frame ID */ - goto fail; - interleave = 0x04+0x04+read_32bitLE(fsb5->stream_offset+0x04,streamFile); /* frame size */ - - //todo unknown interleave for max quality odd channel streams (found in test files) - /* FSB5 odd channels use 2ch+2ch...+1ch streams, and the last only goes up to 0x17a, and other - * streams only use that max (doesn't happen for smaller frames, even channels, or FSB4) - * however streams other than the last seem to be padded with 0s somehow and wont work */ - if (interleave > 0x17a && (fsb5->channels % 2 == 1)) - interleave = 0x17a; - - - /* init layout */ - data = init_layout_layered(layers); - if (!data) goto fail; - - /* open each layer subfile (1/2ch CELT streams: 2ch+2ch..+1ch or 2ch+2ch..+2ch) */ - for (i = 0; i < layers; i++) { - int layer_channels = (i+1 == layers && fsb5->channels % 2 == 1) - ? 1 : 2; /* last layer can be 1/2ch */ - - /* build the layer VGMSTREAM */ - data->layers[i] = allocate_vgmstream(layer_channels, fsb5->loop_flag); - if (!data->layers[i]) goto fail; - - data->layers[i]->sample_rate = fsb5->sample_rate; - data->layers[i]->num_samples = fsb5->num_samples; - data->layers[i]->loop_start_sample = fsb5->loop_start; - data->layers[i]->loop_end_sample = fsb5->loop_end; - -#ifdef VGM_USE_CELT - data->layers[i]->codec_data = init_celt_fsb(layer_channels, CELT_0_11_0); - if (!data->layers[i]->codec_data) goto fail; - data->layers[i]->coding_type = coding_CELT_FSB; - data->layers[i]->layout_type = layout_none; -#else - goto fail; -#endif - - temp_streamFile = setup_fsb5_interleave_streamfile(streamFile, fsb5->stream_offset, fsb5->stream_size, layers, i, FSB5_INT_CELT, interleave); - if (!temp_streamFile) goto fail; - - if (!vgmstream_open_stream(data->layers[i], temp_streamFile, 0x00)) - goto fail; - } - - /* setup layered VGMSTREAMs */ - if (!setup_layout_layered(data)) - goto fail; - close_streamfile(temp_streamFile); - return data; - -fail: - close_streamfile(temp_streamFile); - free_layout_layered(data); - return NULL; -} - - -static layered_layout_data* build_layered_fsb5_atrac9(STREAMFILE *streamFile, fsb5_header* fsb5, off_t configs_offset, size_t configs_size) { - layered_layout_data* data = NULL; - STREAMFILE* temp_streamFile = NULL; - int i, layers = (configs_size / 0x04); - size_t interleave = 0; - - - /* init layout */ - data = init_layout_layered(layers); - if (!data) goto fail; - - /* open each layer subfile (2ch+2ch..+1/2ch) */ - for (i = 0; i < layers; i++) { - uint32_t config = read_32bitBE(configs_offset + 0x04*i, streamFile); - int channel_index, layer_channels; - size_t frame_size; - - - /* parse ATRAC9 config (see VGAudio docs) */ - channel_index = ((config >> 17) & 0x7); - frame_size = (((config >> 5) & 0x7FF) + 1) * (1 << ((config >> 3) & 0x2)); /* frame size * superframe index */ - if (channel_index > 2) - goto fail; /* only 1/2ch expected */ - - layer_channels = (channel_index==0) ? 1 : 2; - if (interleave == 0) - interleave = frame_size; - //todo in test files with 2ch+..+1ch interleave is off (uses some strange padding) - - - /* build the layer VGMSTREAM */ - data->layers[i] = allocate_vgmstream(layer_channels, fsb5->loop_flag); - if (!data->layers[i]) goto fail; - - data->layers[i]->sample_rate = fsb5->sample_rate; - data->layers[i]->num_samples = fsb5->num_samples; - data->layers[i]->loop_start_sample = fsb5->loop_start; - data->layers[i]->loop_end_sample = fsb5->loop_end; - -#ifdef VGM_USE_ATRAC9 - { - atrac9_config cfg = {0}; - - cfg.channels = layer_channels; - cfg.config_data = config; - //cfg.encoder_delay = 0x100; //todo not used? num_samples seems to count all data - - data->layers[i]->codec_data = init_atrac9(&cfg); - if (!data->layers[i]->codec_data) goto fail; - data->layers[i]->coding_type = coding_ATRAC9; - data->layers[i]->layout_type = layout_none; - } -#else - goto fail; -#endif - - temp_streamFile = setup_fsb5_interleave_streamfile(streamFile, fsb5->stream_offset, fsb5->stream_size, layers, i, FSB5_INT_ATRAC9, interleave); - if (!temp_streamFile) goto fail; - - if (!vgmstream_open_stream(data->layers[i], temp_streamFile, 0x00)) - goto fail; - } - - /* setup layered VGMSTREAMs */ - if (!setup_layout_layered(data)) - goto fail; - close_streamfile(temp_streamFile); - return data; - -fail: - close_streamfile(temp_streamFile); - free_layout_layered(data); - return NULL; -} +#include "meta.h" +#include "../coding/coding.h" +#include "../layout/layout.h" +#include "fsb5_streamfile.h" + + +typedef struct { + int total_subsongs; + int version; + int codec; + int flags; + + int channels; + int sample_rate; + int32_t num_samples; + int32_t loop_start; + int32_t loop_end; + int loop_flag; + + off_t sample_header_offset; + size_t sample_header_size; + size_t name_table_size; + size_t sample_data_size; + size_t base_header_size; + + off_t extradata_offset; + size_t extradata_size; + + off_t stream_offset; + size_t stream_size; + off_t name_offset; +} fsb5_header; + +/* ********************************************************************************** */ + +static layered_layout_data* build_layered_fsb5_celt(STREAMFILE *streamFile, fsb5_header* fsb5); +static layered_layout_data* build_layered_fsb5_atrac9(STREAMFILE *streamFile, fsb5_header* fsb5, off_t configs_offset, size_t configs_size); + +/* FSB5 - FMOD Studio multiplatform format */ +VGMSTREAM * init_vgmstream_fsb5(STREAMFILE *streamFile) { + VGMSTREAM * vgmstream = NULL; + fsb5_header fsb5 = {0}; + int target_subsong = streamFile->stream_index; + int i; + + + /* checks */ + /* .fsb: standard + * .snd: Alchemy engine (also Unity) */ + if (!check_extensions(streamFile,"fsb,snd")) + goto fail; + + if (read_32bitBE(0x00,streamFile) != 0x46534235) /* "FSB5" */ + goto fail; + + /* 0x00 is rare (seen in Tales from Space Vita) */ + fsb5.version = read_32bitLE(0x04,streamFile); + if (fsb5.version != 0x00 && fsb5.version != 0x01) goto fail; + + fsb5.total_subsongs = read_32bitLE(0x08,streamFile); + fsb5.sample_header_size = read_32bitLE(0x0C,streamFile); + fsb5.name_table_size = read_32bitLE(0x10,streamFile); + fsb5.sample_data_size = read_32bitLE(0x14,streamFile); + fsb5.codec = read_32bitLE(0x18,streamFile); + /* version 0x01 - 0x1c(4): zero, 0x24(16): hash, 0x34(8): unk + * version 0x00 has an extra field (always 0?) at 0x1c */ + if (fsb5.version == 0x01) { + /* found by tests and assumed to be flags, no games known */ + fsb5.flags = read_32bitLE(0x20,streamFile); + } + fsb5.base_header_size = (fsb5.version==0x00) ? 0x40 : 0x3C; + + if ((fsb5.sample_header_size + fsb5.name_table_size + fsb5.sample_data_size + fsb5.base_header_size) != get_streamfile_size(streamFile)) { + VGM_LOG("FSB5: bad size (%x + %x + %x + %x != %x)\n", fsb5.sample_header_size, fsb5.name_table_size, fsb5.sample_data_size, fsb5.base_header_size, get_streamfile_size(streamFile)); + goto fail; + } + + if (target_subsong == 0) target_subsong = 1; + if (target_subsong > fsb5.total_subsongs || fsb5.total_subsongs <= 0) goto fail; + + fsb5.sample_header_offset = fsb5.base_header_size; + + /* find target stream header and data offset, and read all needed values for later use + * (reads one by one as the size of a single stream header is variable) */ + for (i = 0; i < fsb5.total_subsongs; i++) { + size_t stream_header_size = 0; + off_t data_offset = 0; + uint32_t sample_mode1, sample_mode2; /* maybe one uint64? */ + + sample_mode1 = (uint32_t)read_32bitLE(fsb5.sample_header_offset+0x00,streamFile); + sample_mode2 = (uint32_t)read_32bitLE(fsb5.sample_header_offset+0x04,streamFile); + stream_header_size += 0x08; + + /* get samples */ + fsb5.num_samples = ((sample_mode2 >> 2) & 0x3FFFFFFF); /* bits2: 31..2 (30) */ + + /* get offset inside data section */ + /* up to 0x07FFFFFF * 0x20 = full 32b offset 0xFFFFFFE0 */ + data_offset = (((sample_mode2 & 0x03) << 25) | ((sample_mode1 >> 7) & 0x1FFFFFF)) << 5; /* bits2: 1..0 (2) | bits1: 31..8 (25) */ + + /* get channels */ + switch ((sample_mode1 >> 5) & 0x03) { /* bits1: 7..6 (2) */ + case 0: fsb5.channels = 1; break; + case 1: fsb5.channels = 2; break; + case 2: fsb5.channels = 6; break; /* some Dark Souls 2 MPEG; some IMA ADPCM */ + case 3: fsb5.channels = 8; break; /* some IMA ADPCM */ + /* other channels (ex. 4/10/12ch) use 0 here + set extra flags */ + default: /* not possible */ + goto fail; + } + + /* get sample rate */ + switch ((sample_mode1 >> 1) & 0x0f) { /* bits1: 5..1 (4) */ + case 0: fsb5.sample_rate = 4000; break; + case 1: fsb5.sample_rate = 8000; break; + case 2: fsb5.sample_rate = 11000; break; + case 3: fsb5.sample_rate = 11025; break; + case 4: fsb5.sample_rate = 16000; break; + case 5: fsb5.sample_rate = 22050; break; + case 6: fsb5.sample_rate = 24000; break; + case 7: fsb5.sample_rate = 32000; break; + case 8: fsb5.sample_rate = 44100; break; + case 9: fsb5.sample_rate = 48000; break; + case 10: fsb5.sample_rate = 96000; break; + /* other sample rates (ex. 3000/64000/192000) use 0 here + set extra flags */ + default: /* 11-15: rejected (FMOD error) */ + goto fail; + } + + /* get extra flags */ + if (sample_mode1 & 0x01) { /* bits1: 0 (1) */ + off_t extraflag_offset = fsb5.sample_header_offset+0x08; + uint32_t extraflag, extraflag_type, extraflag_size, extraflag_end; + + do { + extraflag = read_32bitLE(extraflag_offset,streamFile); + extraflag_type = (extraflag >> 25) & 0x7F; /* bits 32..26 (7) */ + extraflag_size = (extraflag >> 1) & 0xFFFFFF; /* bits 25..1 (24)*/ + extraflag_end = (extraflag & 0x01); /* bit 0 (1) */ + + /* parse target only, as flags change between subsongs */ + if (i + 1 == target_subsong) { + switch(extraflag_type) { + case 0x01: /* channels */ + fsb5.channels = read_8bit(extraflag_offset+0x04,streamFile); + break; + case 0x02: /* sample rate */ + fsb5.sample_rate = read_32bitLE(extraflag_offset+0x04,streamFile); + break; + case 0x03: /* loop info */ + fsb5.loop_start = read_32bitLE(extraflag_offset+0x04,streamFile); + if (extraflag_size > 0x04) { /* probably not needed */ + fsb5.loop_end = read_32bitLE(extraflag_offset+0x08,streamFile); + fsb5.loop_end += 1; /* correct compared to FMOD's tools */ + } + //;VGM_LOG("FSB5: stream %i loop start=%i, loop end=%i, samples=%i\n", i, fsb5.loop_start, fsb5.loop_end, fsb5.num_samples); + + /* autodetect unwanted loops */ + { + /* like FSB4 jingles/sfx/music do full loops for no reason, but happens a lot less. + * Most songs loop normally now with proper values [ex. Shantae, FFX] */ + int full_loop, ajurika_loops, is_small; + + /* disable some jingles, it's even possible one jingle (StingerA Var1) to not have loops + * and next one (StingerA Var2) do [Sonic Boom Fire & Ice (3DS)] */ + full_loop = fsb5.loop_start == 0 && fsb5.loop_end + 1152 >= fsb5.num_samples; /* around ~15 samples less, ~1000 for MPEG */ + /* a few longer Sonic songs shouldn't repeat */ + is_small = 1; //fsb5.num_samples < 20 * fsb5.sample_rate; + + /* wrong values in some files [Pac-Man CE2 Plus (Switch) pce2p_bgm_ajurika_*.fsb] */ + ajurika_loops = fsb5.loop_start == 0x3c && fsb5.loop_end == 0x007F007F && + fsb5.num_samples > fsb5.loop_end + 10000; /* arbitrary test in case some game does have those */ + + fsb5.loop_flag = 1; + if ((full_loop && is_small) || ajurika_loops) { + VGM_LOG("FSB5: stream %i disabled unwanted loop ls=%i, le=%i, ns=%i\n", i, fsb5.loop_start, fsb5.loop_end, fsb5.num_samples); + fsb5.loop_flag = 0; + } + } + break; + case 0x04: /* free comment, or maybe SFX info */ + break; + case 0x05: /* unknown 32b */ + /* rare, found in Tearaway (Vita) with value 0 in first stream and + * Shantae and the Seven Sirens (Mobile) with value 0x0003bd72 BE in #44 (Arena Town) */ + VGM_LOG("FSB5: stream %i flag %x with value %08x\n", i, extraflag_type, read_32bitLE(extraflag_offset+0x04,streamFile)); + break; + case 0x06: /* XMA seek table */ + /* no need for it */ + break; + case 0x07: /* DSP coefs */ + fsb5.extradata_offset = extraflag_offset + 0x04; + break; + case 0x09: /* ATRAC9 config */ + fsb5.extradata_offset = extraflag_offset + 0x04; + fsb5.extradata_size = extraflag_size; + break; + case 0x0a: /* XWMA config */ + fsb5.extradata_offset = extraflag_offset + 0x04; + break; + case 0x0b: /* Vorbis setup ID and seek table */ + fsb5.extradata_offset = extraflag_offset + 0x04; + /* seek table format: + * 0x08: table_size (total_entries = seek_table_size / (4+4)), not counting this value; can be 0 + * 0x0C: sample number (only some samples are saved in the table) + * 0x10: offset within data, pointing to a FSB vorbis block (with the 16b block size header) + * (xN entries) + */ + break; + case 0x0d: /* unknown 32b (config? usually 0x3fnnnn00 BE and sometimes 0x3dnnnn00 BE) */ + /* found in some XMA2/Vorbis/FADPCM */ + VGM_LOG("FSB5: stream %i flag %x with value %08x\n", i, extraflag_type, read_32bitLE(extraflag_offset+0x04,streamFile)); + break; + default: + VGM_LOG("FSB5: stream %i unknown flag 0x%x at %x + 0x04 (size 0x%x)\n", i, extraflag_type, (uint32_t)extraflag_offset, extraflag_size); + break; + } + } + + extraflag_offset += 0x04 + extraflag_size; + stream_header_size += 0x04 + extraflag_size; + } while (extraflag_end != 0x00); + } + + /* target found */ + if (i + 1 == target_subsong) { + fsb5.stream_offset = fsb5.base_header_size + fsb5.sample_header_size + fsb5.name_table_size + data_offset; + + /* get stream size from next stream offset or full size if there is only one */ + if (i + 1 == fsb5.total_subsongs) { + fsb5.stream_size = fsb5.sample_data_size - data_offset; + } + else { + off_t next_data_offset; + uint32_t next_sample_mode1, next_sample_mode2; + next_sample_mode1 = (uint32_t)read_32bitLE(fsb5.sample_header_offset+stream_header_size+0x00,streamFile); + next_sample_mode2 = (uint32_t)read_32bitLE(fsb5.sample_header_offset+stream_header_size+0x04,streamFile); + next_data_offset = (((next_sample_mode2 & 0x03) << 25) | ((next_sample_mode1 >> 7) & 0x1FFFFFF)) << 5; + + fsb5.stream_size = next_data_offset - data_offset; + } + + break; + } + + /* continue searching target */ + fsb5.sample_header_offset += stream_header_size; + } + /* target stream not found*/ + if (!fsb5.stream_offset || !fsb5.stream_size) goto fail; + + /* get stream name */ + if (fsb5.name_table_size) { + off_t name_suboffset = fsb5.base_header_size + fsb5.sample_header_size + 0x04*(target_subsong-1); + fsb5.name_offset = fsb5.base_header_size + fsb5.sample_header_size + read_32bitLE(name_suboffset,streamFile); + } + + + /* build the VGMSTREAM */ + vgmstream = allocate_vgmstream(fsb5.channels,fsb5.loop_flag); + if (!vgmstream) goto fail; + + vgmstream->sample_rate = fsb5.sample_rate; + vgmstream->num_samples = fsb5.num_samples; + if (fsb5.loop_flag) { + vgmstream->loop_start_sample = fsb5.loop_start; + vgmstream->loop_end_sample = fsb5.loop_end; + } + vgmstream->num_streams = fsb5.total_subsongs; + vgmstream->stream_size = fsb5.stream_size; + vgmstream->meta_type = meta_FSB5; + if (fsb5.name_offset) + read_string(vgmstream->stream_name,STREAM_NAME_SIZE, fsb5.name_offset,streamFile); + + switch (fsb5.codec) { + case 0x00: /* FMOD_SOUND_FORMAT_NONE */ + goto fail; + + case 0x01: /* FMOD_SOUND_FORMAT_PCM8 [Anima - Gate of Memories (PC)] */ + vgmstream->coding_type = coding_PCM8_U; + vgmstream->layout_type = fsb5.channels == 1 ? layout_none : layout_interleave; + vgmstream->interleave_block_size = 0x01; + break; + + case 0x02: /* FMOD_SOUND_FORMAT_PCM16 [Shantae Risky's Revenge (PC)] */ + vgmstream->coding_type = (fsb5.flags & 0x01) ? coding_PCM16BE : coding_PCM16LE; + vgmstream->layout_type = fsb5.channels == 1 ? layout_none : layout_interleave; + vgmstream->interleave_block_size = 0x02; + break; + + case 0x03: /* FMOD_SOUND_FORMAT_PCM24 */ + VGM_LOG("FSB5: FMOD_SOUND_FORMAT_PCM24 found\n"); + goto fail; + + case 0x04: /* FMOD_SOUND_FORMAT_PCM32 */ + VGM_LOG("FSB5: FMOD_SOUND_FORMAT_PCM32 found\n"); + goto fail; + + case 0x05: /* FMOD_SOUND_FORMAT_PCMFLOAT [Anima: Gate of Memories (PC)] */ + vgmstream->coding_type = coding_PCMFLOAT; + vgmstream->layout_type = (fsb5.channels == 1) ? layout_none : layout_interleave; + vgmstream->interleave_block_size = 0x04; + break; + + case 0x06: /* FMOD_SOUND_FORMAT_GCADPCM [Sonic Boom: Fire and Ice (3DS)] */ + if (fsb5.flags & 0x02) { /* non-interleaved mode */ + vgmstream->coding_type = coding_NGC_DSP; + vgmstream->layout_type = layout_interleave; + vgmstream->interleave_block_size = (fsb5.stream_size / fsb5.channels); + } + else { + vgmstream->coding_type = coding_NGC_DSP_subint; + vgmstream->layout_type = layout_none; + vgmstream->interleave_block_size = 0x02; + } + dsp_read_coefs_be(vgmstream,streamFile,fsb5.extradata_offset,0x2E); + break; + + case 0x07: /* FMOD_SOUND_FORMAT_IMAADPCM [Skylanders] */ + vgmstream->coding_type = (vgmstream->channels > 2) ? coding_FSB_IMA : coding_XBOX_IMA; + vgmstream->layout_type = layout_none; + break; + + case 0x08: /* FMOD_SOUND_FORMAT_VAG [from fsbankex tests, no known games] */ + vgmstream->coding_type = coding_PSX; + vgmstream->layout_type = layout_interleave; + if (fsb5.flags & 0x02) { /* non-interleaved mode */ + vgmstream->interleave_block_size = (fsb5.stream_size / fsb5.channels); + } + else { + vgmstream->interleave_block_size = 0x10; + } + break; + + case 0x09: /* FMOD_SOUND_FORMAT_HEVAG [Guacamelee (Vita)] */ + vgmstream->coding_type = coding_HEVAG; + vgmstream->layout_type = layout_interleave; + vgmstream->interleave_block_size = 0x10; + break; + +#ifdef VGM_USE_FFMPEG + case 0x0A: {/* FMOD_SOUND_FORMAT_XMA [Minecraft Story Mode (X360)] */ + uint8_t buf[0x100]; + int bytes, block_size, block_count; + + block_size = 0x8000; /* FSB default */ + block_count = fsb5.stream_size / block_size + (fsb5.stream_size % block_size ? 1 : 0); + + bytes = ffmpeg_make_riff_xma2(buf, 0x100, vgmstream->num_samples, fsb5.stream_size, vgmstream->channels, vgmstream->sample_rate, block_count, block_size); + vgmstream->codec_data = init_ffmpeg_header_offset(streamFile, buf,bytes, fsb5.stream_offset,fsb5.stream_size); + if (!vgmstream->codec_data) goto fail; + vgmstream->coding_type = coding_FFmpeg; + vgmstream->layout_type = layout_none; + + xma_fix_raw_samples(vgmstream, streamFile, fsb5.stream_offset,fsb5.stream_size, 0, 0,0); /* samples look ok */ + break; + } +#endif + +#ifdef VGM_USE_MPEG + case 0x0B: {/* FMOD_SOUND_FORMAT_MPEG [Final Fantasy X HD (PS3), Shantae Risky's Revenge (PC)] */ + mpeg_custom_config cfg = {0}; + + cfg.fsb_padding = (vgmstream->channels > 2 ? 16 : 4); /* observed default */ + + vgmstream->codec_data = init_mpeg_custom(streamFile, fsb5.stream_offset, &vgmstream->coding_type, vgmstream->channels, MPEG_FSB, &cfg); + if (!vgmstream->codec_data) goto fail; + vgmstream->layout_type = layout_none; + break; + } +#endif + +#ifdef VGM_USE_CELT + case 0x0C: { /* FMOD_SOUND_FORMAT_CELT [BIT.TRIP Presents Runner2 (PC), Full Bore (PC)] */ + int is_multistream = fsb5.channels > 2; + + if (is_multistream) { + vgmstream->layout_data = build_layered_fsb5_celt(streamFile, &fsb5); + if (!vgmstream->layout_data) goto fail; + vgmstream->coding_type = coding_CELT_FSB; + vgmstream->layout_type = layout_layered; + } + else { + vgmstream->codec_data = init_celt_fsb(vgmstream->channels, CELT_0_11_0); + if (!vgmstream->codec_data) goto fail; + vgmstream->coding_type = coding_CELT_FSB; + vgmstream->layout_type = layout_none; + } + break; + } +#endif + +#ifdef VGM_USE_ATRAC9 + case 0x0D: {/* FMOD_SOUND_FORMAT_AT9 */ + int is_multistream; + off_t configs_offset = fsb5.extradata_offset; + size_t configs_size = fsb5.extradata_size; + + + /* skip frame size in newer FSBs [Day of the Tentacle Remastered (Vita), Tearaway Unfolded (PS4)] */ + if (configs_size >= 0x08 && (uint8_t)read_8bit(configs_offset, streamFile) != 0xFE) { /* ATRAC9 sync */ + configs_offset += 0x04; + configs_size -= 0x04; + } + + is_multistream = (configs_size / 0x04) > 1; + + if (is_multistream) { + /* multichannel made of various streams [Little Big Planet (Vita)] */ + vgmstream->layout_data = build_layered_fsb5_atrac9(streamFile, &fsb5, configs_offset, configs_size); + if (!vgmstream->layout_data) goto fail; + vgmstream->coding_type = coding_ATRAC9; + vgmstream->layout_type = layout_layered; + } + else { + /* standard ATRAC9, can be multichannel [Tearaway Unfolded (PS4)] */ + atrac9_config cfg = {0}; + + cfg.channels = vgmstream->channels; + cfg.config_data = read_32bitBE(configs_offset,streamFile); + //cfg.encoder_delay = 0x100; //todo not used? num_samples seems to count all data + + vgmstream->codec_data = init_atrac9(&cfg); + if (!vgmstream->codec_data) goto fail; + vgmstream->coding_type = coding_ATRAC9; + vgmstream->layout_type = layout_none; + } + break; + } +#endif + +#ifdef VGM_USE_FFMPEG + case 0x0E: { /* FMOD_SOUND_FORMAT_XWMA [from fsbankex tests, no known games] */ + uint8_t buf[0x100]; + int bytes, format, average_bps, block_align; + + format = read_16bitBE(fsb5.extradata_offset+0x00,streamFile); + block_align = (uint16_t)read_16bitBE(fsb5.extradata_offset+0x02,streamFile); + average_bps = (uint32_t)read_32bitBE(fsb5.extradata_offset+0x04,streamFile); + /* rest: seek entries + mini seek table? */ + /* XWMA encoder only does up to 6ch (doesn't use FSB multistreams for more) */ + + bytes = ffmpeg_make_riff_xwma(buf,0x100, format, fsb5.stream_size, vgmstream->channels, vgmstream->sample_rate, average_bps, block_align); + vgmstream->codec_data = init_ffmpeg_header_offset(streamFile, buf,bytes, fsb5.stream_offset,fsb5.stream_size); + if ( !vgmstream->codec_data ) goto fail; + vgmstream->coding_type = coding_FFmpeg; + vgmstream->layout_type = layout_none; + break; + } +#endif + +#ifdef VGM_USE_VORBIS + case 0x0F: {/* FMOD_SOUND_FORMAT_VORBIS [Shantae Half Genie Hero (PC), Pokemon Go (iOS)] */ + vorbis_custom_config cfg = {0}; + + cfg.channels = vgmstream->channels; + cfg.sample_rate = vgmstream->sample_rate; + cfg.setup_id = read_32bitLE(fsb5.extradata_offset,streamFile); + + vgmstream->layout_type = layout_none; + vgmstream->coding_type = coding_VORBIS_custom; + vgmstream->codec_data = init_vorbis_custom(streamFile, fsb5.stream_offset, VORBIS_FSB, &cfg); + if (!vgmstream->codec_data) goto fail; + + break; + } +#endif + + case 0x10: /* FMOD_SOUND_FORMAT_FADPCM [Dead Rising 4 (PC), Sine Mora Ex (Switch)] */ + vgmstream->coding_type = coding_FADPCM; + vgmstream->layout_type = layout_interleave; + vgmstream->interleave_block_size = 0x8c; + break; + + default: + VGM_LOG("FSB5: unknown codec %x found\n", fsb5.codec); + goto fail; + } + + if (!vgmstream_open_stream(vgmstream,streamFile,fsb5.stream_offset)) + goto fail; + + return vgmstream; + +fail: + close_vgmstream(vgmstream); + return NULL; +} + + +static layered_layout_data* build_layered_fsb5_celt(STREAMFILE *streamFile, fsb5_header* fsb5) { + layered_layout_data* data = NULL; + STREAMFILE* temp_streamFile = NULL; + int i, layers = (fsb5->channels+1) / 2; + size_t interleave; + + if (read_32bitBE(fsb5->stream_offset+0x00,streamFile) != 0x17C30DF3) /* FSB CELT frame ID */ + goto fail; + interleave = 0x04+0x04+read_32bitLE(fsb5->stream_offset+0x04,streamFile); /* frame size */ + + //todo unknown interleave for max quality odd channel streams (found in test files) + /* FSB5 odd channels use 2ch+2ch...+1ch streams, and the last only goes up to 0x17a, and other + * streams only use that max (doesn't happen for smaller frames, even channels, or FSB4) + * however streams other than the last seem to be padded with 0s somehow and wont work */ + if (interleave > 0x17a && (fsb5->channels % 2 == 1)) + interleave = 0x17a; + + + /* init layout */ + data = init_layout_layered(layers); + if (!data) goto fail; + + /* open each layer subfile (1/2ch CELT streams: 2ch+2ch..+1ch or 2ch+2ch..+2ch) */ + for (i = 0; i < layers; i++) { + int layer_channels = (i+1 == layers && fsb5->channels % 2 == 1) + ? 1 : 2; /* last layer can be 1/2ch */ + + /* build the layer VGMSTREAM */ + data->layers[i] = allocate_vgmstream(layer_channels, fsb5->loop_flag); + if (!data->layers[i]) goto fail; + + data->layers[i]->sample_rate = fsb5->sample_rate; + data->layers[i]->num_samples = fsb5->num_samples; + data->layers[i]->loop_start_sample = fsb5->loop_start; + data->layers[i]->loop_end_sample = fsb5->loop_end; + +#ifdef VGM_USE_CELT + data->layers[i]->codec_data = init_celt_fsb(layer_channels, CELT_0_11_0); + if (!data->layers[i]->codec_data) goto fail; + data->layers[i]->coding_type = coding_CELT_FSB; + data->layers[i]->layout_type = layout_none; +#else + goto fail; +#endif + + temp_streamFile = setup_fsb5_streamfile(streamFile, fsb5->stream_offset, fsb5->stream_size, layers, i, interleave); + if (!temp_streamFile) goto fail; + + if (!vgmstream_open_stream(data->layers[i], temp_streamFile, 0x00)) + goto fail; + } + + /* setup layered VGMSTREAMs */ + if (!setup_layout_layered(data)) + goto fail; + close_streamfile(temp_streamFile); + return data; + +fail: + close_streamfile(temp_streamFile); + free_layout_layered(data); + return NULL; +} + + +static layered_layout_data* build_layered_fsb5_atrac9(STREAMFILE *streamFile, fsb5_header* fsb5, off_t configs_offset, size_t configs_size) { + layered_layout_data* data = NULL; + STREAMFILE* temp_streamFile = NULL; + int i, layers = (configs_size / 0x04); + size_t interleave = 0; + + + /* init layout */ + data = init_layout_layered(layers); + if (!data) goto fail; + + /* open each layer subfile (2ch+2ch..+1/2ch) */ + for (i = 0; i < layers; i++) { + uint32_t config = read_32bitBE(configs_offset + 0x04*i, streamFile); + int channel_index, layer_channels; + size_t frame_size; + + + /* parse ATRAC9 config (see VGAudio docs) */ + channel_index = ((config >> 17) & 0x7); + frame_size = (((config >> 5) & 0x7FF) + 1) * (1 << ((config >> 3) & 0x2)); /* frame size * superframe index */ + if (channel_index > 2) + goto fail; /* only 1/2ch expected */ + + layer_channels = (channel_index==0) ? 1 : 2; + if (interleave == 0) + interleave = frame_size; + //todo in test files with 2ch+..+1ch interleave is off (uses some strange padding) + + + /* build the layer VGMSTREAM */ + data->layers[i] = allocate_vgmstream(layer_channels, fsb5->loop_flag); + if (!data->layers[i]) goto fail; + + data->layers[i]->sample_rate = fsb5->sample_rate; + data->layers[i]->num_samples = fsb5->num_samples; + data->layers[i]->loop_start_sample = fsb5->loop_start; + data->layers[i]->loop_end_sample = fsb5->loop_end; + +#ifdef VGM_USE_ATRAC9 + { + atrac9_config cfg = {0}; + + cfg.channels = layer_channels; + cfg.config_data = config; + //cfg.encoder_delay = 0x100; //todo not used? num_samples seems to count all data + + data->layers[i]->codec_data = init_atrac9(&cfg); + if (!data->layers[i]->codec_data) goto fail; + data->layers[i]->coding_type = coding_ATRAC9; + data->layers[i]->layout_type = layout_none; + } +#else + goto fail; +#endif + + temp_streamFile = setup_fsb5_streamfile(streamFile, fsb5->stream_offset, fsb5->stream_size, layers, i, interleave); + if (!temp_streamFile) goto fail; + + if (!vgmstream_open_stream(data->layers[i], temp_streamFile, 0x00)) + goto fail; + } + + /* setup layered VGMSTREAMs */ + if (!setup_layout_layered(data)) + goto fail; + close_streamfile(temp_streamFile); + return data; + +fail: + close_streamfile(temp_streamFile); + free_layout_layered(data); + return NULL; +} diff --git a/Frameworks/vgmstream/vgmstream/src/meta/fsb5_interleave_streamfile.h b/Frameworks/vgmstream/vgmstream/src/meta/fsb5_interleave_streamfile.h deleted file mode 100644 index d9cb14c2b..000000000 --- a/Frameworks/vgmstream/vgmstream/src/meta/fsb5_interleave_streamfile.h +++ /dev/null @@ -1,201 +0,0 @@ -#ifndef _FSB5_INTERLEAVE_STREAMFILE_H_ -#define _FSB5_INTERLEAVE_STREAMFILE_H_ -#include "../streamfile.h" - -typedef enum { FSB5_INT_CELT, FSB5_INT_ATRAC9 } fsb_interleave_codec_t; -typedef struct { - /* state */ - off_t logical_offset; /* offset that corresponds to physical_offset */ - off_t physical_offset; /* actual file offset */ - int skip_frames; /* frames to skip from other streams at points */ - - /* config */ - fsb_interleave_codec_t codec; - size_t interleave; - int stream_count; - int stream_number; - size_t stream_size; - off_t start_offset; /* pointing to the stream's beginning */ - size_t total_size; /* size of the resulting substream */ -} fsb_interleave_io_data; - - - -/* Reads skipping other streams */ -static size_t fsb_interleave_io_read(STREAMFILE *streamfile, uint8_t *dest, off_t offset, size_t length, fsb_interleave_io_data* data) { - size_t total_read = 0; - - /* ignore bad reads */ - if (offset < 0 || offset > data->total_size) { - return total_read; - } - - /* previous offset: re-start as we can't map logical<>physical offsets - * (kinda slow as it trashes buffers, but shouldn't happen often) */ - if (offset < data->logical_offset) { - data->physical_offset = data->start_offset; - data->logical_offset = 0x00; - data->skip_frames = data->stream_number; - } - - /* read doing one frame at a time */ - while (length > 0) { - size_t to_read, bytes_read; - off_t intrablock_offset, intradata_offset; - uint32_t data_size; - - if (offset >= data->total_size) - break; - - /* get current data */ - switch (data->codec) { - case FSB5_INT_CELT: - case FSB5_INT_ATRAC9: - data_size = data->interleave; - break; - - default: - return 0; - } - - /* skip frames from other streams */ - if (data->skip_frames) { - data->physical_offset += data_size; - data->skip_frames--; - continue; - } - - /* requested offset is outside current block, try next */ - if (offset >= data->logical_offset + data_size) { - data->physical_offset += data_size; - data->logical_offset += data_size; - data->skip_frames = data->stream_count - 1; - continue; - } - - /* reads could fall in the middle of the block */ - intradata_offset = offset - data->logical_offset; - intrablock_offset = intradata_offset; - - /* clamp reads up to this block's end */ - to_read = (data_size - intradata_offset); - if (to_read > length) - to_read = length; - if (to_read == 0) - break; /* should never happen... */ - - /* finally read and move buffer/offsets */ - bytes_read = read_streamfile(dest, data->physical_offset + intrablock_offset, to_read, streamfile); - total_read += bytes_read; - if (bytes_read != to_read) - break; /* couldn't read fully */ - - dest += bytes_read; - offset += bytes_read; - length -= bytes_read; - - /* block fully read, go next */ - if (intradata_offset + bytes_read == data_size) { - data->physical_offset += data_size; - data->logical_offset += data_size; - data->skip_frames = data->stream_count - 1; - } - } - - return total_read; -} - -static size_t fsb_interleave_io_size(STREAMFILE *streamfile, fsb_interleave_io_data* data) { - off_t physical_offset, max_physical_offset; - size_t total_size = 0; - int skip_frames = 0; - - if (data->total_size) - return data->total_size; - - physical_offset = data->start_offset; - max_physical_offset = physical_offset + data->stream_size; - skip_frames = data->stream_number; - - /* get size of the underlying stream, skipping other streams - * (all streams should have the same frame count) */ - while (physical_offset < max_physical_offset) { - size_t data_size; - - data_size = data->interleave; - switch(data->codec) { - case FSB5_INT_CELT: - case FSB5_INT_ATRAC9: - data_size = data->interleave; - break; - - default: - return 0; - } - - /* there may be padding at the end, so this doubles as EOF marker */ - if (data_size == 0) - break; - if (physical_offset+data_size > max_physical_offset) - break; - - /* skip frames from other streams */ - if (skip_frames) { - physical_offset += data_size; - skip_frames--; - continue; - } - - physical_offset += data_size; - total_size += data_size; - skip_frames = data->stream_count - 1; - } - - data->total_size = total_size; - return data->total_size; -} - - -/* Prepares custom IO for multistreams, interleaves 1 packet per stream */ -static STREAMFILE* setup_fsb5_interleave_streamfile(STREAMFILE *streamFile, off_t start_offset, size_t stream_size, int stream_count, int stream_number, fsb_interleave_codec_t codec, size_t interleave) { - STREAMFILE *temp_streamFile = NULL, *new_streamFile = NULL; - fsb_interleave_io_data io_data = {0}; - size_t io_data_size = sizeof(fsb_interleave_io_data); - - io_data.start_offset = start_offset; - io_data.physical_offset = start_offset; - io_data.skip_frames = stream_number; /* adjust since start_offset points to the first */ - io_data.codec = codec; - io_data.interleave = interleave; - io_data.stream_count = stream_count; - io_data.stream_number = stream_number; - io_data.stream_size = stream_size; /* full size for all streams */ - - io_data.total_size = fsb_interleave_io_size(streamFile, &io_data); /* force init, size of a single stream */ - - if (io_data.total_size == 0 || io_data.total_size > io_data.stream_size) { - VGM_LOG("FSB5 INTERLEAVE: wrong total_size %x vs %x\n", io_data.total_size,io_data.stream_size); - goto fail; - } - - /* setup subfile */ - new_streamFile = open_wrap_streamfile(streamFile); - if (!new_streamFile) goto fail; - temp_streamFile = new_streamFile; - - new_streamFile = open_io_streamfile(temp_streamFile, &io_data,io_data_size, fsb_interleave_io_read,fsb_interleave_io_size); - if (!new_streamFile) goto fail; - temp_streamFile = new_streamFile; - - new_streamFile = open_buffer_streamfile(new_streamFile,0); - if (!new_streamFile) goto fail; - temp_streamFile = new_streamFile; - - return temp_streamFile; - -fail: - close_streamfile(temp_streamFile); - return NULL; -} - -#endif /* _FSB_INTERLEAVE_STREAMFILE_H_ */ diff --git a/Frameworks/vgmstream/vgmstream/src/meta/fsb5_streamfile.h b/Frameworks/vgmstream/vgmstream/src/meta/fsb5_streamfile.h new file mode 100644 index 000000000..191751489 --- /dev/null +++ b/Frameworks/vgmstream/vgmstream/src/meta/fsb5_streamfile.h @@ -0,0 +1,21 @@ +#ifndef _FSB5_STREAMFILE_H_ +#define _FSB5_STREAMFILE_H_ +#include "deblock_streamfile.h" + +static STREAMFILE* setup_fsb5_streamfile(STREAMFILE* sf, off_t stream_start, size_t stream_size, int stream_count, int stream_number, size_t interleave) { + STREAMFILE* new_sf = NULL; + deblock_config_t cfg = {0}; + + cfg.stream_start = stream_start; + cfg.stream_size = stream_size; + cfg.chunk_size = interleave; + cfg.step_start = stream_number; + cfg.step_count = stream_count; + + /* setup sf */ + new_sf = open_wrap_streamfile(sf); + new_sf = open_io_deblock_streamfile_f(new_sf, &cfg); + return new_sf; +} + +#endif /* _FSB5_STREAMFILE_H_ */ diff --git a/Frameworks/vgmstream/vgmstream/src/meta/hca_keys.h b/Frameworks/vgmstream/vgmstream/src/meta/hca_keys.h index e77da08e2..2b294df79 100644 --- a/Frameworks/vgmstream/vgmstream/src/meta/hca_keys.h +++ b/Frameworks/vgmstream/vgmstream/src/meta/hca_keys.h @@ -229,6 +229,7 @@ static const hcakey_info hcakey_list[] = { {5047159794308}, // 00000497222AAA84 // Shin Tennis no Ouji-sama: Rising Beat (iOS/Android) voices? + // UNI'S ON AIR (iOS/Android) {4902201417679}, // 0000047561F95FCF // Kai-ri-Sei Million Arthur (Vita) diff --git a/Frameworks/vgmstream/vgmstream/src/meta/isb.c b/Frameworks/vgmstream/vgmstream/src/meta/isb.c index bef078c4e..de24493e2 100644 --- a/Frameworks/vgmstream/vgmstream/src/meta/isb.c +++ b/Frameworks/vgmstream/vgmstream/src/meta/isb.c @@ -2,32 +2,38 @@ #include "../coding/coding.h" -/* .ISB - Creative ISACT (Interactive Spatial Audio Composition Tools) middleware [Psychonauts (PC)] */ -VGMSTREAM * init_vgmstream_isb(STREAMFILE *streamFile) { +/* .ISB - Creative ISACT (Interactive Spatial Audio Composition Tools) middleware [Psychonauts (PC), Mass Effect (multi)] */ +VGMSTREAM * init_vgmstream_isb(STREAMFILE *sf) { VGMSTREAM * vgmstream = NULL; off_t start_offset = 0, name_offset = 0; size_t stream_size = 0, name_size = 0; int loop_flag = 0, channel_count = 0, sample_rate = 0, codec = 0, pcm_bytes = 0, bps = 0; - int total_subsongs, target_subsong = streamFile->stream_index; + int total_subsongs, target_subsong = sf->stream_index; + uint32_t (*read_u32me)(off_t,STREAMFILE*); + uint32_t (*read_u32ce)(off_t,STREAMFILE*); + int big_endian; /* checks */ - if (!check_extensions(streamFile, "isb")) + if (!check_extensions(sf, "isb")) goto fail; - if (read_32bitBE(0x00,streamFile) != 0x52494646) /* "RIFF" */ + big_endian = read_u32be(0x00,sf) == 0x46464952; /* "FFIR" */ + read_u32me = big_endian ? read_u32be : read_u32le; /* machine endianness... */ + read_u32ce = big_endian ? read_u32le : read_u32be; /* chunks change with endianness but this just reads as BE */ + + if (read_u32ce(0x00,sf) != 0x52494646) /* "RIFF" */ goto fail; - if (read_32bitLE(0x04,streamFile) + 0x08 != get_streamfile_size(streamFile)) + if (read_u32me(0x04,sf) + 0x08 != get_streamfile_size(sf)) goto fail; - if (read_32bitBE(0x08,streamFile) != 0x69736266) /* "isbf" */ + if (read_u32ce(0x08,sf) != 0x69736266) /* "isbf" */ goto fail; /* some files have a companion .icb, seems to be a cue file pointing here */ /* format is RIFF with many custom chunks, apparently for their DAW-like editor with * complex functions, but most seem always included by default and unused, and games - * Psychonauts seems to use the format as a simple audio bank. Mass Effect (X360) - * apparently uses ISACT, while Psychonauts Xbox/PS2 don't. */ + * seems to use the format as a simple audio bank. Psychonauts Xbox/PS2 doesn't use ISACT. */ { off_t offset, max_offset, header_offset = 0; @@ -38,15 +44,15 @@ VGMSTREAM * init_vgmstream_isb(STREAMFILE *streamFile) { /* parse base RIFF */ offset = 0x0c; - max_offset = get_streamfile_size(streamFile); + max_offset = get_streamfile_size(sf); while (offset < max_offset) { - uint32_t chunk_type = read_u32be(offset + 0x00,streamFile); - uint32_t chunk_size = read_s32le(offset + 0x04,streamFile); + uint32_t chunk_type = read_u32ce(offset + 0x00,sf); + uint32_t chunk_size = read_u32me(offset + 0x04,sf); offset += 0x08; switch(chunk_type) { case 0x4C495354: /* "LIST" */ - if (read_u32be(offset, streamFile) != 0x73616D70) /* "samp" */ + if (read_u32ce(offset, sf) != 0x73616D70) /* "samp" */ break; /* there are "bfob" LIST without data */ total_subsongs++; @@ -72,8 +78,8 @@ VGMSTREAM * init_vgmstream_isb(STREAMFILE *streamFile) { offset = header_offset + 0x04; max_offset = offset + header_size; while (offset < max_offset) { - uint32_t chunk_type = read_u32be(offset + 0x00,streamFile); - uint32_t chunk_size = read_s32le(offset + 0x04,streamFile); + uint32_t chunk_type = read_u32ce(offset + 0x00,sf); + uint32_t chunk_size = read_u32me(offset + 0x04,sf); offset += 0x08; switch(chunk_type) { @@ -83,21 +89,21 @@ VGMSTREAM * init_vgmstream_isb(STREAMFILE *streamFile) { break; case 0x63686E6B: /* "chnk" */ - channel_count = read_u32le(offset + 0x00, streamFile); + channel_count = read_u32me(offset + 0x00, sf); break; case 0x73696E66: /* "sinf" */ /* 0x00: null? */ /* 0x04: some value? */ - sample_rate = read_u32le(offset + 0x08, streamFile); - pcm_bytes = read_u32le(offset + 0x0c, streamFile); - bps = read_u16le(offset + 0x10, streamFile); + sample_rate = read_u32me(offset + 0x08, sf); + pcm_bytes = read_u32me(offset + 0x0c, sf); + bps = read_u16le(offset + 0x10, sf); /* 0x12: some value? */ break; case 0x636D7069: /* "cmpi" */ - codec = read_u32le(offset + 0x00, streamFile); - if (read_u32le(offset + 0x04, streamFile) != codec) { + codec = read_u32me(offset + 0x00, sf); + if (read_u32me(offset + 0x04, sf) != codec) { VGM_LOG("ISB: unknown compression repeat\n"); goto fail; } @@ -134,11 +140,17 @@ VGMSTREAM * init_vgmstream_isb(STREAMFILE *streamFile) { vgmstream = allocate_vgmstream(channel_count, loop_flag); if (!vgmstream) goto fail; - vgmstream->meta_type = meta_WAF; //todo + vgmstream->meta_type = meta_ISB; vgmstream->sample_rate = sample_rate; vgmstream->num_streams = total_subsongs; vgmstream->stream_size = stream_size; + if (name_offset) { /* UTF16 but only uses lower bytes */ + if (name_size > STREAM_NAME_SIZE) + name_size = STREAM_NAME_SIZE; + read_string_utf16(vgmstream->stream_name,name_size, name_offset, sf, big_endian); + } + switch(codec) { case 0x00: if (bps == 8) { @@ -162,7 +174,7 @@ VGMSTREAM * init_vgmstream_isb(STREAMFILE *streamFile) { #ifdef VGM_USE_VORBIS case 0x02: - vgmstream->codec_data = init_ogg_vorbis(streamFile, start_offset, stream_size, NULL); + vgmstream->codec_data = init_ogg_vorbis(sf, start_offset, stream_size, NULL); if (!vgmstream->codec_data) goto fail; vgmstream->coding_type = coding_OGG_VORBIS; vgmstream->layout_type = layout_none; @@ -170,18 +182,64 @@ VGMSTREAM * init_vgmstream_isb(STREAMFILE *streamFile) { break; #endif - default: /* according to press releases ISACT may support WMA and XMA */ +#ifdef VGM_USE_FFMPEG + case 0x04: { + uint8_t buf[0x100]; + size_t bytes; + off_t fmt_offset = start_offset; + size_t fmt_size = 0x20; + + start_offset += fmt_size; + stream_size -= fmt_size; + + /* XMA1 "fmt" chunk (BE, unlike the usual LE) */ + bytes = ffmpeg_make_riff_xma_from_fmt_chunk(buf,sizeof(buf), fmt_offset,fmt_size, stream_size, sf, 1); + vgmstream->codec_data = init_ffmpeg_header_offset(sf, buf,bytes, start_offset, stream_size); + if (!vgmstream->codec_data) goto fail; + vgmstream->coding_type = coding_FFmpeg; + vgmstream->layout_type = layout_none; + + vgmstream->num_samples = pcm_bytes / channel_count / (bps/8); + xma_fix_raw_samples(vgmstream, sf, start_offset, stream_size, fmt_offset, 1,1); + break; + } +#endif + + case 0x05: { + //TODO: improve + VGMSTREAM *temp_vgmstream = NULL; + STREAMFILE *temp_sf = NULL; + + temp_sf = setup_subfile_streamfile(sf, start_offset, stream_size, "msf"); + if (!temp_sf) goto fail; + + temp_vgmstream = init_vgmstream_msf(temp_sf); + if (temp_vgmstream) { + temp_vgmstream->num_streams = vgmstream->num_streams; + temp_vgmstream->stream_size = vgmstream->stream_size; + temp_vgmstream->meta_type = vgmstream->meta_type; + strcpy(temp_vgmstream->stream_name, vgmstream->stream_name); + + close_streamfile(temp_sf); + close_vgmstream(vgmstream); + return temp_vgmstream; + } + else { + close_streamfile(temp_sf); + goto fail; + } + + break; + + } + + default: /* according to press releases ISACT may support WMA */ VGM_LOG("ISB: unknown codec %i\n", codec); goto fail; } - if (name_offset) { /* UTF16 but only uses lower bytes */ - if (name_size > STREAM_NAME_SIZE) - name_size = STREAM_NAME_SIZE; - read_string_utf16le(vgmstream->stream_name,name_size, name_offset, streamFile); - } - if (!vgmstream_open_stream(vgmstream,streamFile,start_offset)) + if (!vgmstream_open_stream(vgmstream, sf, start_offset)) goto fail; return vgmstream; diff --git a/Frameworks/vgmstream/vgmstream/src/meta/meta.h b/Frameworks/vgmstream/vgmstream/src/meta/meta.h index bb619bc10..2a88778da 100644 --- a/Frameworks/vgmstream/vgmstream/src/meta/meta.h +++ b/Frameworks/vgmstream/vgmstream/src/meta/meta.h @@ -101,7 +101,7 @@ VGMSTREAM * init_vgmstream_ngc_str(STREAMFILE *streamFile); VGMSTREAM * init_vgmstream_caf(STREAMFILE *streamFile); -VGMSTREAM * init_vgmstream_ps2_vpk(STREAMFILE *streamFile); +VGMSTREAM * init_vgmstream_vpk(STREAMFILE *streamFile); VGMSTREAM * init_vgmstream_genh(STREAMFILE *streamFile); @@ -888,4 +888,9 @@ VGMSTREAM * init_vgmstream_kwb(STREAMFILE* sf); VGMSTREAM * init_vgmstream_lrmd(STREAMFILE* sf); +VGMSTREAM* init_vgmstream_bkhd(STREAMFILE* sf); +VGMSTREAM* init_vgmstream_bkhd_fx(STREAMFILE* sf); + +VGMSTREAM* init_vgmstream_encrypted(STREAMFILE* sf); + #endif /*_META_H*/ diff --git a/Frameworks/vgmstream/vgmstream/src/meta/mp4.c b/Frameworks/vgmstream/vgmstream/src/meta/mp4.c index 5471fe0df..c16ec2aaa 100644 --- a/Frameworks/vgmstream/vgmstream/src/meta/mp4.c +++ b/Frameworks/vgmstream/vgmstream/src/meta/mp4.c @@ -98,8 +98,6 @@ VGMSTREAM * init_vgmstream_mp4_aac_offset(STREAMFILE *streamFile, uint64_t start aac_file->h_aacdecoder = aacDecoder_Open( TT_MP4_RAW, 1 ); if ( !aac_file->h_aacdecoder ) goto fail; - aacDecoder_SetParam( aac_file->h_aacdecoder, AAC_PCM_OUTPUT_CHANNELS, 2 ); - MP4GetTrackESConfiguration( aac_file->h_mp4file, aac_file->track_id, (uint8_t**)(&buffer), (uint32_t*)(&buffer_size)); ubuffer_size = buffer_size; diff --git a/Frameworks/vgmstream/vgmstream/src/meta/mul.c b/Frameworks/vgmstream/vgmstream/src/meta/mul.c index cf262160a..7d2bf3e9f 100644 --- a/Frameworks/vgmstream/vgmstream/src/meta/mul.c +++ b/Frameworks/vgmstream/vgmstream/src/meta/mul.c @@ -1,164 +1,269 @@ -#include "meta.h" -#include "../layout/layout.h" -#include "../coding/coding.h" - -typedef enum { NONE, PSX, DSP, XBOX } mul_codec; - -/* .MUL - from Crystal Dynamics games [Legacy of Kain: Defiance (PS2), Tomb Raider Underworld (multi)] */ -VGMSTREAM * init_vgmstream_mul(STREAMFILE *streamFile) { - VGMSTREAM * vgmstream = NULL; - off_t start_offset, coefs_offset = 0; - int loop_flag, channel_count, sample_rate, num_samples, loop_start; - int big_endian; - mul_codec codec = NONE; - int32_t (*read_32bit)(off_t,STREAMFILE*) = NULL; - - - /* checks */ - /* .mul: found in the exe, used by the bigfile extractor (Gibbed.TombRaider) - * (some files have companion .mus/sam files but seem to be sequences/control stuff) - * .(extensionless): filenames as found in the bigfile - * .emff: fake extension ('Eidos Music File Format') */ - if (!check_extensions(streamFile, "mul,,emff")) - goto fail; - if (read_32bitBE(0x10,streamFile) != 0 || - read_32bitBE(0x14,streamFile) != 0 || - read_32bitBE(0x18,streamFile) != 0 || - read_32bitBE(0x1c,streamFile) != 0) - goto fail; - - big_endian = guess_endianness32bit(0x00, streamFile); - read_32bit = big_endian ? read_32bitBE : read_32bitLE; - - sample_rate = read_32bit(0x00,streamFile); - loop_start = read_32bit(0x04,streamFile); - num_samples = read_32bit(0x08,streamFile); - channel_count = read_32bit(0x0C,streamFile); - if (sample_rate < 8000 || sample_rate > 48000 || channel_count > 8) - goto fail; - /* 0x20: flag when file has non-audio blocks (ignored by the layout) */ - /* 0x24: same? */ - /* 0x28: loop offset within audio data (not file offset) */ - /* 0x2c: some value related to loop? */ - /* 0x34: id? */ - /* 0x38+: channel config until ~0x100? (multiple 0x3F800000 depending on the number of channels) */ - - /* test known versions (later versions start from 0x24 instead of 0x20) */ - if (!(read_32bit(0x38,streamFile) == 0x3F800000 || - read_32bit(0x3c,streamFile) == 0x3F800000)) /* Tomb Raider Underworld */ - goto fail; - - loop_flag = (loop_start >= 0); /* 0xFFFFFFFF when not looping */ - start_offset = 0x800; - - /* format is pretty limited so we need to guess codec */ - if (big_endian) { - /* test DSP (GC/Wii): check known coef locations */ - if (read_32bitBE(0xC8,streamFile) != 0) { /* Tomb Raider Legend (GC) */ - codec = DSP; - coefs_offset = 0xC8; - } - else if (read_32bitBE(0xCC,streamFile) != 0) { /* Tomb Raider Anniversary (Wii) */ - codec = DSP; - coefs_offset = 0xCC; - } - else if (read_32bitBE(0x2D0,streamFile) != 0) { /* Tomb Raider Underworld (Wii) */ - codec = DSP; - coefs_offset = 0x2D0; - } - - // todo test XMA1 (X360): mono streams, each block has 1 sub-blocks of 0x800 packet per channel - - // todo test ? (PS3) - } - else { - int i; - off_t offset = start_offset; - size_t file_size = get_streamfile_size(streamFile); - size_t frame_size; - - /* check first audio frame */ - while (offset < file_size) { - uint32_t block_type = read_32bit(offset+0x00, streamFile); - uint32_t block_size = read_32bit(offset+0x04, streamFile); - uint32_t data_size = read_32bit(offset+0x10, streamFile); - - if (block_type != 0x00) { - offset += 0x10 + block_size; - continue; /* not audio */ - } - - /* test PS-ADPCM (PS2/PSP): flag is always 2 in .mul */ - frame_size = 0x10; - for (i = 0; i < data_size / frame_size; i++) { - if (read_8bit(offset + 0x20 + frame_size*i + 0x01, streamFile) != 0x02) - break; - } - if (i == data_size / frame_size) { - codec = PSX; - break; - } - - /* test XBOX-IMA (PC/Xbox): reserved frame header value is always 0 */ - frame_size = 0x24; - for (i = 0; i < data_size / frame_size; i++) { - if (read_8bit(offset + 0x20 + frame_size*i + 0x03, streamFile) != 0x00) - break; - } - if (i == data_size / frame_size) { - codec = XBOX; - break; - } - - break; - } - } - - if (codec == NONE) { - VGM_LOG("MUL: unknown codec\n"); - goto fail; - } - - - /* build the VGMSTREAM */ - vgmstream = allocate_vgmstream(channel_count,loop_flag); - if (!vgmstream) goto fail; - - vgmstream->meta_type = meta_MUL; - vgmstream->sample_rate = sample_rate; - vgmstream->num_samples = num_samples; - vgmstream->loop_start_sample = loop_start; - vgmstream->loop_end_sample = num_samples; - vgmstream->codec_endian = big_endian; - - switch(codec) { - case PSX: - vgmstream->coding_type = coding_PSX; - vgmstream->layout_type = layout_blocked_mul; - break; - - case DSP: - vgmstream->coding_type = coding_NGC_DSP; - vgmstream->layout_type = layout_blocked_mul; - - dsp_read_coefs_be(vgmstream,streamFile,coefs_offset+0x00,0x2e); - dsp_read_hist_be (vgmstream,streamFile,coefs_offset+0x24,0x2e); - break; - - case XBOX: - vgmstream->coding_type = coding_XBOX_IMA_int; - vgmstream->layout_type = layout_blocked_mul; - break; - - default: - goto fail; - } - - if (!vgmstream_open_stream(vgmstream,streamFile,start_offset)) - goto fail; - return vgmstream; - -fail: - close_vgmstream(vgmstream); - return NULL; -} +#include "meta.h" +#include "../layout/layout.h" +#include "../coding/coding.h" +#include "mul_streamfile.h" + +typedef enum { PSX, DSP, XBOX, XMA1 } mul_codec; + +static int guess_codec(STREAMFILE* sf, int big_endian, int channels, mul_codec* p_codec, off_t* p_extra_offset); + +static layered_layout_data* build_layered_mul(STREAMFILE *sf_data, int big_endian, VGMSTREAM* vgmstream); + +/* .MUL - from Crystal Dynamics games [Legacy of Kain: Defiance (PS2), Tomb Raider Underworld (multi)] */ +VGMSTREAM * init_vgmstream_mul(STREAMFILE *sf) { + VGMSTREAM * vgmstream = NULL; + off_t start_offset, coefs_offset = 0; + int loop_flag, channel_count, sample_rate, num_samples, loop_start; + int big_endian; + mul_codec codec; + uint32_t (*read_u32)(off_t,STREAMFILE*) = NULL; + + + /* checks */ + /* .mul: found in the exe, used by the bigfile extractor (Gibbed.TombRaider) + * (some files have companion .mus/sam files but seem to be sequences/control stuff) + * .(extensionless): filenames as found in the bigfile + * .emff: fake extension ('Eidos Music File Format') */ + if (!check_extensions(sf, "mul,,emff")) + goto fail; + if (read_u32be(0x10,sf) != 0 || + read_u32be(0x14,sf) != 0 || + read_u32be(0x18,sf) != 0 || + read_u32be(0x1c,sf) != 0) + goto fail; + + big_endian = guess_endianness32bit(0x00, sf); + read_u32 = big_endian ? read_u32be : read_u32le; + + sample_rate = read_u32(0x00,sf); + loop_start = read_u32(0x04,sf); + num_samples = read_u32(0x08,sf); + channel_count = read_u32(0x0C,sf); + if (sample_rate < 8000 || sample_rate > 48000 || channel_count > 8) + goto fail; + /* 0x20: flag when file has non-audio blocks (ignored by the layout) */ + /* 0x24: same? */ + /* 0x28: loop offset within audio data (not file offset) */ + /* 0x2c: some value related to loop? */ + /* 0x34: id? */ + /* 0x38+: channel config until ~0x100? (multiple 0x3F800000 / 1.0f depending on the number of channels) */ + + /* test known versions (later versions start from 0x24 instead of 0x20) */ + if (!(read_u32(0x38,sf) == 0x3F800000 || + read_u32(0x3c,sf) == 0x3F800000)) /* Tomb Raider Underworld */ + goto fail; + + loop_flag = (loop_start >= 0); /* 0xFFFFFFFF when not looping */ + start_offset = 0x800; + + /* format is pretty limited so we need to guess codec */ + if (!guess_codec(sf, big_endian, channel_count, &codec, &coefs_offset)) + goto fail; + + + /* build the VGMSTREAM */ + vgmstream = allocate_vgmstream(channel_count,loop_flag); + if (!vgmstream) goto fail; + + vgmstream->meta_type = meta_MUL; + vgmstream->sample_rate = sample_rate; + vgmstream->num_samples = num_samples; + vgmstream->loop_start_sample = loop_start; + vgmstream->loop_end_sample = num_samples; + vgmstream->codec_endian = big_endian; + + switch(codec) { + case PSX: + vgmstream->coding_type = coding_PSX; + vgmstream->layout_type = layout_blocked_mul; + break; + + case DSP: + vgmstream->coding_type = coding_NGC_DSP; + vgmstream->layout_type = layout_blocked_mul; + + dsp_read_coefs_be(vgmstream,sf,coefs_offset+0x00,0x2e); + dsp_read_hist_be (vgmstream,sf,coefs_offset+0x24,0x2e); + break; + + case XBOX: + vgmstream->coding_type = coding_XBOX_IMA_int; + vgmstream->layout_type = layout_blocked_mul; + break; + +#ifdef VGM_USE_FFMPEG + case XMA1: { + + vgmstream->layout_data = build_layered_mul(sf, big_endian, vgmstream); + if (!vgmstream->layout_data) goto fail; + vgmstream->coding_type = coding_FFmpeg; + vgmstream->layout_type = layout_layered; + break; + } +#endif + + default: + goto fail; + } + + if (!vgmstream_open_stream(vgmstream, sf, start_offset)) + goto fail; + return vgmstream; + +fail: + close_vgmstream(vgmstream); + return NULL; +} + +static int guess_codec(STREAMFILE* sf, int big_endian, int channels, mul_codec* p_codec, off_t* p_extra_offset) { + uint32_t (*read_u32)(off_t,STREAMFILE*); + + read_u32 = big_endian ? read_u32be : read_u32le; + *p_extra_offset = 0; + + if (big_endian) { + /* test DSP (GC/Wii): check known coef locations */ + if (read_u32be(0xC8,sf) != 0) { /* Tomb Raider Legend (GC) */ + *p_codec = DSP; + *p_extra_offset = 0xC8; + return 1; + } + else if (read_u32be(0xCC,sf) != 0) { /* Tomb Raider Anniversary (Wii) */ + *p_codec = DSP; + *p_extra_offset = 0xCC; + return 1; + } + else if (read_u32be(0x2D0,sf) != 0) { /* Tomb Raider Underworld (Wii) */ + *p_codec = DSP; + *p_extra_offset = 0x2D0; + return 1; + } + else { //if (ps_check_format(sf, 0x820, 0x100)) { + /* may be PS3/X360, tested below [Tomb Raider 7 (PS3)] */ + } + + // todo test XMA1 (X360): N mono streams (layered), each block has 1 sub-blocks of 0x800 packet per channel + } + + + { + int i; + off_t offset = 0x800; + size_t file_size = get_streamfile_size(sf); + size_t frame_size; + + /* check first audio frame */ + while (offset < file_size) { + uint32_t block_type = read_u32(offset+0x00, sf); + uint32_t block_size = read_u32(offset+0x04, sf); + uint32_t data_size = read_u32(offset+0x10, sf); + + if (block_type != 0x00) { + offset += 0x10 + block_size; + continue; /* not audio */ + } + + /* test XMA1 (X360): has sub-blocks of 0x800 per channel */ + if (block_size == 0x810 * channels) { + for (i = 0; i < channels; i++) { + off_t test_offset = offset + 0x10 + 0x810*i; + if (read_u32(test_offset + 0x00, sf) != 0x800 || /* XMA packet size */ + read_u32(test_offset + 0x10, sf) != 0x08000000) /* XMA packet first header */ + break; + } + if (i == channels) { + *p_codec = XMA1; + return 1; + } + } + + /* test PS-ADPCM (PS2/PSP): flag is always 2 in .mul */ + frame_size = 0x10; + for (i = 0; i < data_size / frame_size; i++) { + if (read_8bit(offset + 0x20 + frame_size*i + 0x01, sf) != 0x02) + break; + } + if (i == data_size / frame_size) { + *p_codec = PSX; + return 1; + } + + /* test XBOX-IMA (PC/Xbox): reserved frame header value is always 0 */ + frame_size = 0x24; + for (i = 0; i < data_size / frame_size; i++) { + if (read_8bit(offset + 0x20 + frame_size*i + 0x03, sf) != 0x00) + break; + } + if (i == data_size / frame_size) { + *p_codec = XBOX; + return 1; + } + + break; + } + } + + return 0; +} + + +/* MUL contain one XMA1 streams per channel so we need the usual voodoo */ +static layered_layout_data* build_layered_mul(STREAMFILE *sf_data, int big_endian, VGMSTREAM* vgmstream) { + layered_layout_data* data = NULL; + STREAMFILE* temp_sf = NULL; + int i, layers = vgmstream->channels; + + + /* init layout */ + data = init_layout_layered(layers); + if (!data) goto fail; + + for (i = 0; i < layers; i++) { + int layer_channels = 1; + + + /* build the layer VGMSTREAM */ + data->layers[i] = allocate_vgmstream(layer_channels, 0); + if (!data->layers[i]) goto fail; + + data->layers[i]->sample_rate = vgmstream->sample_rate; + data->layers[i]->num_samples = vgmstream->num_samples; + +#ifdef VGM_USE_FFMPEG + { + uint8_t buf[0x100]; + int bytes; + size_t stream_size; + + temp_sf = setup_mul_streamfile(sf_data, big_endian, i, layers); + if (!temp_sf) goto fail; + + stream_size = get_streamfile_size(temp_sf); + + bytes = ffmpeg_make_riff_xma1(buf, 0x100, data->layers[i]->num_samples, stream_size, data->layers[i]->channels, data->layers[i]->sample_rate, 0); + data->layers[i]->codec_data = init_ffmpeg_header_offset(temp_sf, buf,bytes, 0x00, stream_size); + if (!data->layers[i]->codec_data) goto fail; + + data->layers[i]->coding_type = coding_FFmpeg; + data->layers[i]->layout_type = layout_none; + data->layers[i]->stream_size = stream_size; + + xma_fix_raw_samples(data->layers[i], temp_sf, 0x00,stream_size, 0, 0,0); /* ? */ + + close_streamfile(temp_sf); + temp_sf = NULL; + } +#else + goto fail; +#endif + } + + if (!setup_layout_layered(data)) + goto fail; + return data; + +fail: + close_streamfile(temp_sf); + free_layout_layered(data); + return NULL; +} diff --git a/Frameworks/vgmstream/vgmstream/src/meta/mul_streamfile.h b/Frameworks/vgmstream/vgmstream/src/meta/mul_streamfile.h new file mode 100644 index 000000000..842a86580 --- /dev/null +++ b/Frameworks/vgmstream/vgmstream/src/meta/mul_streamfile.h @@ -0,0 +1,65 @@ +#ifndef _MUL_STREAMFILE_H_ +#define _MUL_STREAMFILE_H_ +#include "deblock_streamfile.h" + +static void block_callback(STREAMFILE* sf, deblock_io_data* data) { + uint32_t block_type; + size_t block_size; + uint32_t (*read_u32)(off_t,STREAMFILE*) = data->cfg.big_endian ? read_u32be : read_u32le; + + + if (data->physical_offset == 0) { + data->block_size = 0x800; + data->data_size = 0; + data->skip_size = 0; + return; + } + + block_type = read_u32(data->physical_offset + 0x00, sf); + block_size = read_u32(data->physical_offset + 0x04, sf); /* not including main header */ + + /* some blocks only contain half of data (continues in next block) so use track numbers */ + + if (block_type == 0x00 && block_size != 0) { + /* header block */ + data->block_size = 0x10; + data->data_size = 0; + data->skip_size = 0; + } + else if (block_type == 0x00000800) { + data->block_size = 0x810; + + /* actually sub-block with size + number, kinda half-assed but meh... */ + if (block_size == data->cfg.track_number) { + data->data_size = 0x800; + data->skip_size = 0x10; + } + else{ + data->data_size = 0; + data->skip_size = 0; + } + } + else { + /* non-audio block */ + data->block_size = block_size + 0x10; + data->data_size = 0; + data->skip_size = 0; + } +} + +/* Deinterleaves MUL streams */ +static STREAMFILE* setup_mul_streamfile(STREAMFILE* sf, int big_endian, int track_number, int track_count) { + STREAMFILE *new_sf = NULL; + deblock_config_t cfg = {0}; + + cfg.big_endian = big_endian; + cfg.track_number = track_number; + cfg.track_count = track_count; + cfg.block_callback = block_callback; + + new_sf = open_wrap_streamfile(sf); + new_sf = open_io_deblock_streamfile_f(new_sf, &cfg); + return new_sf; +} + +#endif /* _MUL_STREAMFILE_H_ */ diff --git a/Frameworks/vgmstream/vgmstream/src/meta/ngc_vid1.c b/Frameworks/vgmstream/vgmstream/src/meta/ngc_vid1.c deleted file mode 100644 index 6e4120eb5..000000000 --- a/Frameworks/vgmstream/vgmstream/src/meta/ngc_vid1.c +++ /dev/null @@ -1,75 +0,0 @@ -#include "meta.h" -#include "../util.h" -#include "../coding/coding.h" - - -/* VID1 - from Neversoft games (Gun, Tony Hawk's American Wasteland GC) */ -VGMSTREAM * init_vgmstream_ngc_vid1(STREAMFILE *streamFile) { - VGMSTREAM * vgmstream = NULL; - off_t start_offset, header_offset, header_size; - int loop_flag = 0, channel_count; - - - /* check extension */ - if (!check_extensions(streamFile,"ogg,logg")) - goto fail; - - /* chunked/blocked format containing video or audio frames */ - if (read_32bitBE(0x00,streamFile) != 0x56494431) /* "VID1" */ - goto fail; - - /* find actual header start/size in the chunks */ - { - header_offset = read_32bitBE(0x04, streamFile); - if (read_32bitBE(header_offset,streamFile) != 0x48454144) /* "HEAD" */ - goto fail; - start_offset = header_offset + read_32bitBE(header_offset + 0x04, streamFile); - header_offset += 0x0c; - - /* videos have VIDH before AUDH, and VIDD in blocks, but aren't parsed ATM */ - - if (read_32bitBE(header_offset,streamFile) != 0x41554448) /* "AUDH" */ - goto fail; - header_size = read_32bitBE(header_offset + 0x04, streamFile); - header_offset += 0x0c; - - if (read_32bitBE(header_offset,streamFile) != 0x56415544) /* "VAUD" (Vorbis audio?) */ - goto fail; - header_offset += 0x04; - header_size -= 0x10; - - } - channel_count = read_8bit(header_offset + 0x04,streamFile); - /* other values unknown, maybe related to vorbis (ex. bitrate/encoding modes) */ - - - /* build the VGMSTREAM */ - vgmstream = allocate_vgmstream(channel_count,loop_flag); - if (!vgmstream) goto fail; - - vgmstream->sample_rate = read_32bitBE(header_offset + 0x00, streamFile); - vgmstream->num_samples = read_32bitBE(header_offset + 0x1c, streamFile); - vgmstream->meta_type = meta_NGC_VID1; - -#ifdef VGM_USE_VORBIS - { - vorbis_custom_config cfg = {0}; - - vgmstream->layout_type = layout_none; - vgmstream->coding_type = coding_VORBIS_custom; - vgmstream->codec_data = init_vorbis_custom(streamFile, header_offset + 0x20, VORBIS_VID1, &cfg); - if (!vgmstream->codec_data) goto fail; - } -#else - goto fail; -#endif - - /* open the file for reading */ - if ( !vgmstream_open_stream(vgmstream, streamFile, start_offset) ) - goto fail; - return vgmstream; - -fail: - close_vgmstream(vgmstream); - return NULL; -} diff --git a/Frameworks/vgmstream/vgmstream/src/meta/nps.c b/Frameworks/vgmstream/vgmstream/src/meta/nps.c index bc89cd818..7f2a1ef5b 100644 --- a/Frameworks/vgmstream/vgmstream/src/meta/nps.c +++ b/Frameworks/vgmstream/vgmstream/src/meta/nps.c @@ -1,44 +1,56 @@ #include "meta.h" #include "../coding/coding.h" -/* NPFS - found in Namco PS2/PSP games [Tekken 5 (PS2), Venus & Braves (PS2), Ridge Racer (PSP)] */ -VGMSTREAM * init_vgmstream_nps(STREAMFILE *streamFile) { +/* NPFS - found in Namco NuSound v1 games [Tekken 5 (PS2), Venus & Braves (PS2), Ridge Racer (PSP)] */ +VGMSTREAM* init_vgmstream_nps(STREAMFILE* sf) { VGMSTREAM * vgmstream = NULL; off_t start_offset; - int loop_flag, channel_count; + uint32_t channel_size; + int loop_flag, channel_count, loop_start, sample_rate; + /* checks */ - /* .nps: referenced extension (ex. Venus & Braves data files) + /* .nps: referenced extension (ex. Venus & Braves, Ridge Racer data files) * .npsf: header id (Namco Production Sound File?) */ - if ( !check_extensions(streamFile,"nps,npsf")) + if ( !check_extensions(sf,"nps,npsf")) goto fail; - if (read_32bitBE(0x00,streamFile) != 0x4E505346) /* "NPSF" */ + if (read_u32be(0x00, sf) != 0x4E505346) /* "NPSF" */ goto fail; - loop_flag = (read_32bitLE(0x14,streamFile) != 0xFFFFFFFF); - channel_count = read_32bitLE(0x0C,streamFile); - start_offset = (off_t)read_32bitLE(0x10,streamFile); + /* 0x04: version? (0x00001000 = 1.00?) */ + channel_size = read_s32le(0x08, sf); + channel_count = read_s32le(0x0C, sf); + start_offset = read_s32le(0x10, sf); /* interleave? */ + loop_start = read_s32le(0x14, sf); + sample_rate = read_s32le(0x18, sf); + /* 0x1c: volume? (0x3e8 = 1000 = max) */ + /* 0x20: flags? (varies between sound types in a game, but no clear pattern vs other games) */ + /* 0x24: flag? (0/1) */ + /* 0x28: null */ + /* 0x2c: null */ + /* 0x30: always 0x40 */ + /* 0x34: name (usually null terminated but may contain garbage) */ + /* rest: null or 0xFF until start */ + loop_flag = loop_start != -1; + /* build the VGMSTREAM */ - vgmstream = allocate_vgmstream(channel_count,loop_flag); + vgmstream = allocate_vgmstream(channel_count, loop_flag); if (!vgmstream) goto fail; - vgmstream->channels = read_32bitLE(0x0C,streamFile); - vgmstream->sample_rate = read_32bitLE(0x18,streamFile); - vgmstream->num_samples = ps_bytes_to_samples(read_32bitLE(0x08,streamFile), 1); /* single channel data */ - if(vgmstream->loop_flag) { - vgmstream->loop_start_sample = read_32bitLE(0x14,streamFile); - vgmstream->loop_end_sample = ps_bytes_to_samples(read_32bitLE(0x08,streamFile), 1); - } + vgmstream->sample_rate = sample_rate; + vgmstream->num_samples = ps_bytes_to_samples(channel_size, 1); + vgmstream->loop_start_sample = loop_start; + vgmstream->loop_end_sample = vgmstream->num_samples; vgmstream->coding_type = coding_PSX; vgmstream->layout_type = layout_interleave; - vgmstream->interleave_block_size = read_32bitLE(0x04,streamFile) / 2; + vgmstream->interleave_block_size = 0x800; vgmstream->meta_type = meta_NPS; - read_string(vgmstream->stream_name,STREAM_NAME_SIZE, 0x34,streamFile); + read_string(vgmstream->stream_name, STREAM_NAME_SIZE, 0x34, sf); - if ( !vgmstream_open_stream(vgmstream, streamFile, start_offset) ) + if (!vgmstream_open_stream(vgmstream, sf, start_offset)) goto fail; return vgmstream; diff --git a/Frameworks/vgmstream/vgmstream/src/meta/ogg_opus.c b/Frameworks/vgmstream/vgmstream/src/meta/ogg_opus.c index 521b8acc5..e3c5fb681 100644 --- a/Frameworks/vgmstream/vgmstream/src/meta/ogg_opus.c +++ b/Frameworks/vgmstream/vgmstream/src/meta/ogg_opus.c @@ -86,7 +86,10 @@ VGMSTREAM * init_vgmstream_ogg_opus(STREAMFILE *streamFile) { else if (strstr(user_comment,"LoopEnd=")==user_comment) { /* LoopStart pair */ loop_end = atol(strrchr(user_comment,'=')+1); } - + else if (strstr(user_comment, "loops=") == user_comment) { /* The Legend of Heroes: Trails of Cold Steel III (Switch) */ + sscanf(strrchr(user_comment, '=') + 1, "%d-%d", &loop_start, &loop_end); + loop_flag = 1; + } //;VGM_LOG("OggOpus: user_comment=%s\n", user_comment); offset += 0x04 + user_comment_size; diff --git a/Frameworks/vgmstream/vgmstream/src/meta/opus.c b/Frameworks/vgmstream/vgmstream/src/meta/opus.c index 5213a0655..932ecef2e 100644 --- a/Frameworks/vgmstream/vgmstream/src/meta/opus.c +++ b/Frameworks/vgmstream/vgmstream/src/meta/opus.c @@ -172,7 +172,7 @@ VGMSTREAM * init_vgmstream_opus_capcom(STREAMFILE *streamFile) { /* 0x30+: extra chunks (0x00: 0x7f, 0x04: num_sample), alt loop starts/regions? */ if (channel_count == 6) { - /* 2ch multistream hacky-hacks, don't try this at home. We'll end up with: + /* 2ch multistream hacky-hacks in RE:RE, don't try this at home. We'll end up with: * main vgmstream > N vgmstream layers > substream IO deinterleaver > opus meta > Opus IO transmogrifier (phew) */ layered_layout_data* data = NULL; int layers = channel_count / 2; @@ -193,11 +193,11 @@ VGMSTREAM * init_vgmstream_opus_capcom(STREAMFILE *streamFile) { /* open each layer subfile */ for (i = 0; i < layers; i++) { - STREAMFILE* temp_streamFile = setup_opus_interleave_streamfile(streamFile, offset+0x28*i, layers); - if (!temp_streamFile) goto fail; + STREAMFILE* temp_sf = setup_opus_interleave_streamfile(streamFile, offset, i, layers); + if (!temp_sf) goto fail; - data->layers[i] = init_vgmstream_opus(temp_streamFile, meta_OPUS, 0x00, num_samples,loop_start,loop_end); - close_streamfile(temp_streamFile); + data->layers[i] = init_vgmstream_opus(temp_sf, meta_OPUS, 0x00, num_samples,loop_start,loop_end); + close_streamfile(temp_sf); if (!data->layers[i]) goto fail; } diff --git a/Frameworks/vgmstream/vgmstream/src/meta/opus_interleave_streamfile.h b/Frameworks/vgmstream/vgmstream/src/meta/opus_interleave_streamfile.h index 503e83410..4985e4037 100644 --- a/Frameworks/vgmstream/vgmstream/src/meta/opus_interleave_streamfile.h +++ b/Frameworks/vgmstream/vgmstream/src/meta/opus_interleave_streamfile.h @@ -1,136 +1,47 @@ -#ifndef _OPUS_INTERLEAVE_STREAMFILE_H_ -#define _OPUS_INTERLEAVE_STREAMFILE_H_ -#include "../streamfile.h" - - -typedef struct { - /* config */ - int streams; - off_t stream_offset; - - /* state */ - off_t logical_offset; /* offset that corresponds to physical_offset */ - off_t physical_offset; /* actual file offset */ - int skip_frames; /* frames to skip from other streams at points */ - - size_t logical_size; -} opus_interleave_io_data; - - -/* Reads skipping other streams */ -static size_t opus_interleave_io_read(STREAMFILE *streamfile, uint8_t *dest, off_t offset, size_t length, opus_interleave_io_data* data) { - size_t total_read = 0; - - /* ignore bad reads */ - if (offset < 0 || offset > data->logical_size) { - return total_read; - } - - /* previous offset: re-start as we can't map logical<>physical offsets (may be VBR) */ - if (offset < data->logical_offset) { - data->physical_offset = data->stream_offset; - data->logical_offset = 0x00; - data->skip_frames = 0; - } - - /* read doing one frame at a time */ - while (length > 0) { - size_t data_size; - - /* ignore EOF */ - if (data->logical_offset >= data->logical_size) { - break; - } - - /* process block (must be read every time since skip frame sizes may vary) */ - { - data_size = read_32bitBE(data->physical_offset,streamfile); - if ((uint32_t)data_size == 0x01000080) //todo not ok if offset between 0 and header_size - data_size = read_32bitLE(data->physical_offset+0x10,streamfile) + 0x08; - else - data_size += 0x08; - } - - /* skip frames from other streams */ - if (data->skip_frames) { - data->physical_offset += data_size; - data->skip_frames--; - continue; - } - - /* move to next block */ - if (offset >= data->logical_offset + data_size) { - data->physical_offset += data_size; - data->logical_offset += data_size; - data->skip_frames = data->streams - 1; - continue; - } - - /* read data */ - { - size_t bytes_consumed, bytes_done, to_read; - - bytes_consumed = offset - data->logical_offset; - to_read = data_size - bytes_consumed; - if (to_read > length) - to_read = length; - bytes_done = read_streamfile(dest, data->physical_offset + bytes_consumed, to_read, streamfile); - - offset += bytes_done; - total_read += bytes_done; - length -= bytes_done; - dest += bytes_done; - - if (bytes_done != to_read || bytes_done == 0) { - break; /* error/EOF */ - } - } - } - - return total_read; -} - -static size_t opus_interleave_io_size(STREAMFILE *streamfile, opus_interleave_io_data* data) { - off_t info_offset; - - if (data->logical_size) - return data->logical_size; - - info_offset = read_32bitLE(data->stream_offset+0x10,streamfile); - data->logical_size = (0x08+info_offset) + read_32bitLE(data->stream_offset+info_offset+0x04,streamfile); - return data->logical_size; -} - - -/* Prepares custom IO for multistream, interleaves 1 packet per stream */ -static STREAMFILE* setup_opus_interleave_streamfile(STREAMFILE *streamFile, off_t start_offset, int streams) { - STREAMFILE *temp_streamFile = NULL, *new_streamFile = NULL; - opus_interleave_io_data io_data = {0}; - size_t io_data_size = sizeof(opus_interleave_io_data); - - io_data.stream_offset = start_offset; - io_data.streams = streams; - io_data.physical_offset = start_offset; - io_data.logical_size = opus_interleave_io_size(streamFile, &io_data); /* force init */ - - /* setup subfile */ - new_streamFile = open_wrap_streamfile(streamFile); - if (!new_streamFile) goto fail; - temp_streamFile = new_streamFile; - - new_streamFile = open_io_streamfile(temp_streamFile, &io_data,io_data_size, opus_interleave_io_read,opus_interleave_io_size); - if (!new_streamFile) goto fail; - temp_streamFile = new_streamFile; - - new_streamFile = open_buffer_streamfile(new_streamFile,0); - if (!new_streamFile) goto fail; - temp_streamFile = new_streamFile; - - return temp_streamFile; - -fail: - close_streamfile(temp_streamFile); - return NULL; -} - -#endif /* _OPUS_INTERLEAVE_STREAMFILE_H_ */ +#ifndef _OPUS_INTERLEAVE_STREAMFILE_H_ +#define _OPUS_INTERLEAVE_STREAMFILE_H_ +#include "deblock_streamfile.h" + + +static void block_callback(STREAMFILE* sf, deblock_io_data* data) { + uint32_t chunk_size = read_u32be(data->physical_offset, sf); + + //todo not ok if offset between 0 and header_size + if (chunk_size == 0x01000080) /* header */ + chunk_size = read_u32le(data->physical_offset + 0x10, sf) + 0x08; + else + chunk_size += 0x08; + data->block_size = chunk_size; + data->data_size = data->block_size; +} + +/* Deblocks NXOPUS streams that interleave 1 packet per stream */ +static STREAMFILE* setup_opus_interleave_streamfile(STREAMFILE* sf, off_t start_offset, int stream_number, int stream_count) { + STREAMFILE* new_sf = NULL; + deblock_config_t cfg = {0}; + + cfg.stream_start = start_offset; + cfg.step_start = stream_number; + cfg.step_count = stream_count; + { + int i; + off_t offset = start_offset; + /* read full size from NXOPUS header N */ + for (i = 0; i < stream_number + 1; i++) { + off_t start = read_s32le(offset + 0x10, sf); + off_t size = read_s32le(offset + start + 0x04, sf); + + if (i == stream_number) + cfg.logical_size = 0x08 + start + size; + offset += 0x08 + start; + } + } + cfg.block_callback = block_callback; + + new_sf = open_wrap_streamfile(sf); + new_sf = open_io_deblock_streamfile_f(new_sf, &cfg); + //new_sf = open_buffer_streamfile_f(new_sf, 0); + return new_sf; +} + +#endif /* _OPUS_INTERLEAVE_STREAMFILE_H_ */ diff --git a/Frameworks/vgmstream/vgmstream/src/meta/riff.c b/Frameworks/vgmstream/vgmstream/src/meta/riff.c index efd6e9d86..e96939a5d 100644 --- a/Frameworks/vgmstream/vgmstream/src/meta/riff.c +++ b/Frameworks/vgmstream/vgmstream/src/meta/riff.c @@ -509,20 +509,21 @@ VGMSTREAM * init_vgmstream_riff(STREAMFILE *streamFile) { } break; - case 0x4E584246: /* "NXBF" (Namco NUS v1) [R:Racing Evolution (Xbox)] */ - /* 0x00: "NXBF" again */ - /* 0x04: always 0x1000? */ + case 0x4E584246: /* "NXBF" (Namco NuSound v1) [R:Racing Evolution (Xbox)] */ + /* very similar to NUS's NPSF, but not quite like Cstr */ + /* 0x00: "NXBF" id */ + /* 0x04: version? (0x00001000 = 1.00?) */ /* 0x08: data size */ /* 0x0c: channels */ /* 0x10: null */ loop_start_nxbf = read_32bitLE(current_chunk + 0x08 + 0x14, streamFile); /* 0x18: sample rate */ - /* 0x1c: volume? */ + /* 0x1c: volume? (0x3e8 = 1000 = max) */ /* 0x20: type/flags? */ - /* 0x24: codec? */ + /* 0x24: flag? */ /* 0x28: null */ /* 0x2c: null */ - /* 0x30: type/flags? */ + /* 0x30: always 0x40 */ loop_flag = (loop_start_nxbf >= 0); break; diff --git a/Frameworks/vgmstream/vgmstream/src/meta/sqex_sead.c b/Frameworks/vgmstream/vgmstream/src/meta/sqex_sead.c index f48efcd70..09b32b9ae 100644 --- a/Frameworks/vgmstream/vgmstream/src/meta/sqex_sead.c +++ b/Frameworks/vgmstream/vgmstream/src/meta/sqex_sead.c @@ -6,45 +6,46 @@ typedef struct { int big_endian; - int version; int is_sab; int is_mab; int total_subsongs; int target_subsong; - uint16_t wave_id; + uint16_t mtrl_index; + uint16_t mtrl_number; int loop_flag; - int channel_count; + int channels; int codec; int sample_rate; int loop_start; int loop_end; - off_t meta_offset; + off_t mtrl_offset; off_t extradata_offset; size_t extradata_size; size_t stream_size; - size_t special_size; + uint16_t extradata_id; - off_t descriptor_offset; - size_t descriptor_size; - off_t filename_offset; + off_t filename_offset; size_t filename_size; - off_t cuename_offset; - size_t cuename_size; - off_t modename_offset; + off_t muscname_offset; + size_t muscname_size; + off_t sectname_offset; + size_t sectname_size; + off_t modename_offset; size_t modename_size; - off_t instname_offset; + off_t instname_offset; size_t instname_size; - off_t sndname_offset; + off_t sndname_offset; size_t sndname_size; off_t sections_offset; - off_t snd_offset; - off_t trk_offset; - off_t musc_offset; - off_t inst_offset; - off_t mtrl_offset; + off_t snd_section_offset; + off_t seq_section_offset; + off_t trk_section_offset; + off_t musc_section_offset; + off_t inst_section_offset; + off_t mtrl_section_offset; char readable_name[STREAM_NAME_SIZE]; @@ -54,48 +55,52 @@ static int parse_sead(sead_header *sead, STREAMFILE *sf); /* SABF/MABF - Square Enix's "sead" audio games [Dragon Quest Builders (PS3), Dissidia Opera Omnia (mobile), FF XV (PS4)] */ -VGMSTREAM * init_vgmstream_sqex_sead(STREAMFILE * streamFile) { - VGMSTREAM * vgmstream = NULL; +VGMSTREAM* init_vgmstream_sqex_sead(STREAMFILE* sf) { + VGMSTREAM* vgmstream = NULL; sead_header sead = {0}; off_t start_offset; - int target_subsong = streamFile->stream_index; - int32_t (*read_32bit)(off_t,STREAMFILE*) = NULL; - int16_t (*read_16bit)(off_t,STREAMFILE*) = NULL; + int target_subsong = sf->stream_index; + uint32_t (*read_u32)(off_t,STREAMFILE*) = NULL; + uint16_t (*read_u16)(off_t,STREAMFILE*) = NULL; /* checks */ /* .sab: sound/bgm * .mab: music * .sbin: Dissidia Opera Omnia .sab */ - if (!check_extensions(streamFile,"sab,mab,sbin")) + if (!check_extensions(sf,"sab,mab,sbin")) goto fail; - if (read_32bitBE(0x00,streamFile) == 0x73616266) { /* "sabf" */ + if (read_u32be(0x00, sf) == 0x73616266) { /* "sabf" */ sead.is_sab = 1; - } else if (read_32bitBE(0x00,streamFile) == 0x6D616266) { /* "mabf" */ + } else if (read_u32be(0x00, sf) == 0x6D616266) { /* "mabf" */ sead.is_mab = 1; } else { - /* there are other SEAD files with other chunks but similar formats too */ goto fail; } - sead.big_endian = guess_endianness16bit(0x06,streamFile); /* use some value as no apparent flag */ + /* SEAD handles both sab/mab in the same lib, and other similar files (config, engine, etc). + * Has some chunks pointing to sections, and each section entry (usually starting with section + * version/reserved/size) is always padded to 0x10. Most values are unsigned. */ + + + sead.big_endian = guess_endianness16bit(0x06, sf); /* no flag, use size */ if (sead.big_endian) { - read_32bit = read_32bitBE; - read_16bit = read_16bitBE; + read_u32 = read_u32be; + read_u16 = read_u16be; } else { - read_32bit = read_32bitLE; - read_16bit = read_16bitLE; + read_u32 = read_u32le; + read_u16 = read_u16le; } sead.target_subsong = target_subsong; - if (!parse_sead(&sead, streamFile)) + if (!parse_sead(&sead, sf)) goto fail; /* build the VGMSTREAM */ - vgmstream = allocate_vgmstream(sead.channel_count, sead.loop_flag); + vgmstream = allocate_vgmstream(sead.channels, sead.loop_flag); if (!vgmstream) goto fail; vgmstream->meta_type = sead.is_sab ? meta_SQEX_SAB : meta_SQEX_MAB; @@ -106,13 +111,15 @@ VGMSTREAM * init_vgmstream_sqex_sead(STREAMFILE * streamFile) { switch(sead.codec) { - case 0x01: { /* PCM [Chrono Trigger sfx (PC)] */ + case 0x01: { /* PCM [Chrono Trigger (PC) sfx] */ start_offset = sead.extradata_offset + sead.extradata_size; vgmstream->coding_type = coding_PCM16LE; vgmstream->layout_type = layout_interleave; vgmstream->interleave_block_size = 0x02; + /* no known extradata */ + vgmstream->num_samples = pcm_bytes_to_samples(sead.stream_size, vgmstream->channels, 16); vgmstream->loop_start_sample = sead.loop_start; vgmstream->loop_end_sample = sead.loop_end; @@ -122,21 +129,29 @@ VGMSTREAM * init_vgmstream_sqex_sead(STREAMFILE * streamFile) { case 0x02: { /* MSADPCM [Dragon Quest Builders (Vita) sfx] */ start_offset = sead.extradata_offset + sead.extradata_size; - /* 0x00 (2): null?, 0x02(2): entry size? */ vgmstream->coding_type = coding_MSADPCM; vgmstream->layout_type = layout_none; - vgmstream->frame_size = read_16bit(sead.extradata_offset+0x04,streamFile); + vgmstream->frame_size = read_u16(sead.extradata_offset+0x04, sf); - /* much like AKBs, there are slightly different loop values here, probably more accurate + /* extradata: */ + /* 0x00: version */ + /* 0x01: reserved */ + /* 0x02: size */ + /* 0x02: frame size */ + /* 0x06: reserved */ + /* 0x08: loop start offset */ + /* 0x0c: loop end offset */ + + /* much like AKBs, loop values are slightly different, probably more accurate * (if no loop, loop_end doubles as num_samples) */ vgmstream->num_samples = msadpcm_bytes_to_samples(sead.stream_size, vgmstream->frame_size, vgmstream->channels); - vgmstream->loop_start_sample = read_32bit(sead.extradata_offset+0x08, streamFile); //loop_start - vgmstream->loop_end_sample = read_32bit(sead.extradata_offset+0x0c, streamFile); //loop_end + vgmstream->loop_start_sample = read_u32(sead.extradata_offset+0x08, sf); + vgmstream->loop_end_sample = read_u32(sead.extradata_offset+0x0c, sf); break; } #ifdef VGM_USE_VORBIS - case 0x03: { /* OGG [Final Fantasy XV Benchmark sfx (PC)] */ + case 0x03: { /* VORBIS (Ogg subfile) [Final Fantasy XV Benchmark sfx (PC)] */ VGMSTREAM *ogg_vgmstream = NULL; ogg_vorbis_meta_info_t ovmi = {0}; off_t subfile_offset = sead.extradata_offset + sead.extradata_size; @@ -144,9 +159,20 @@ VGMSTREAM * init_vgmstream_sqex_sead(STREAMFILE * streamFile) { ovmi.meta_type = vgmstream->meta_type; ovmi.total_subsongs = sead.total_subsongs; ovmi.stream_size = sead.stream_size; - /* post header has some kind of repeated values, config/table? */ - ogg_vgmstream = init_vgmstream_ogg_vorbis_callbacks(streamFile, NULL, subfile_offset, &ovmi); + /* extradata: */ + /* 0x00: version */ + /* 0x01: reserved */ + /* 0x02: size */ + /* 0x04: loop start offset */ + /* 0x08: loop end offset */ + /* 0x0c: num samples */ + /* 0x10: header size */ + /* 0x14: seek table size */ + /* 0x18: reserved x2 */ + /* 0x20: seek table */ + + ogg_vgmstream = init_vgmstream_ogg_vorbis_callbacks(sf, NULL, subfile_offset, &ovmi); if (ogg_vgmstream) { ogg_vgmstream->num_streams = vgmstream->num_streams; ogg_vgmstream->stream_size = vgmstream->stream_size; @@ -168,33 +194,51 @@ VGMSTREAM * init_vgmstream_sqex_sead(STREAMFILE * streamFile) { atrac9_config cfg = {0}; start_offset = sead.extradata_offset + sead.extradata_size; - /* post header has various typical ATRAC9 values */ + cfg.channels = vgmstream->channels; - cfg.config_data = read_32bit(sead.extradata_offset+0x0c,streamFile); - cfg.encoder_delay = read_32bit(sead.extradata_offset+0x18,streamFile); + cfg.config_data = read_u32(sead.extradata_offset+0x0c, sf); + cfg.encoder_delay = read_u32(sead.extradata_offset+0x18, sf); + + /* extradata: */ + /* 0x00: version */ + /* 0x01: reserved */ + /* 0x02: size */ + /* 0x04: block align */ + /* 0x06: block samples */ + /* 0x08: channel mask */ + /* 0x1c: config */ + /* 0x10: samples */ + /* 0x14: "overlap delay" */ + /* 0x18: "encoder delay" */ + /* 0x1c: sample rate */ + /* 0x24: loop start */ + /* 0x28: loop end */ vgmstream->codec_data = init_atrac9(&cfg); if (!vgmstream->codec_data) goto fail; vgmstream->coding_type = coding_ATRAC9; vgmstream->layout_type = layout_none; - vgmstream->sample_rate = read_32bit(sead.extradata_offset+0x1c,streamFile); /* SAB's sample rate can be different but it's ignored */ - vgmstream->num_samples = read_32bit(sead.extradata_offset+0x10,streamFile); /* loop values above are also weird and ignored */ - vgmstream->loop_start_sample = read_32bit(sead.extradata_offset+0x20, streamFile) - (sead.loop_flag ? cfg.encoder_delay : 0); //loop_start - vgmstream->loop_end_sample = read_32bit(sead.extradata_offset+0x24, streamFile) - (sead.loop_flag ? cfg.encoder_delay : 0); //loop_end + vgmstream->channel_layout = read_u32(sead.extradata_offset+0x08,sf); + vgmstream->sample_rate = read_u32(sead.extradata_offset+0x1c,sf); /* SAB's sample rate can be different/wrong */ + vgmstream->num_samples = read_u32(sead.extradata_offset+0x10,sf); /* loop values above are also weird and ignored */ + vgmstream->loop_start_sample = read_u32(sead.extradata_offset+0x20, sf) - (sead.loop_flag ? cfg.encoder_delay : 0); //loop_start + vgmstream->loop_end_sample = read_u32(sead.extradata_offset+0x24, sf) - (sead.loop_flag ? cfg.encoder_delay : 0); //loop_end break; } #endif #ifdef VGM_USE_MPEG - case 0x06: { /* MSF subfile (MPEG mode) [Dragon Quest Builders (PS3)] */ + case 0x06: { /* MSMP3 (MSF subfile) [Dragon Quest Builders (PS3)] */ mpeg_codec_data *mpeg_data = NULL; mpeg_custom_config cfg = {0}; start_offset = sead.extradata_offset + sead.extradata_size; - /* post header is a proper MSF, but sample rate/loops are ignored in favor of SAB's */ - mpeg_data = init_mpeg_custom(streamFile, start_offset, &vgmstream->coding_type, vgmstream->channels, MPEG_STANDARD, &cfg); + /* extradata: */ + /* proper MSF header, but sample rate/loops are ignored in favor of SAB's */ + + mpeg_data = init_mpeg_custom(sf, start_offset, &vgmstream->coding_type, vgmstream->channels, MPEG_STANDARD, &cfg); if (!mpeg_data) goto fail; vgmstream->codec_data = mpeg_data; vgmstream->layout_type = layout_none; @@ -206,23 +250,35 @@ VGMSTREAM * init_vgmstream_sqex_sead(STREAMFILE * streamFile) { } #endif - case 0x07: { /* HCA subfile [Dissidia Opera Omnia (Mobile), Final Fantaxy XV (PS4)] */ - //todo there is no easy way to use the HCA decoder; try subfile hack for now + case 0x07: { /* HCA (subfile) [Dissidia Opera Omnia (Mobile), Final Fantaxy XV (PS4)] */ VGMSTREAM *temp_vgmstream = NULL; - STREAMFILE *temp_streamFile = NULL; + STREAMFILE *temp_sf = NULL; off_t subfile_offset = sead.extradata_offset + 0x10; size_t subfile_size = sead.stream_size + sead.extradata_size - 0x10; - /* post header: values from the HCA header, in file endianness + HCA header */ - size_t key_start = sead.special_size & 0xff; - size_t header_size = read_16bit(sead.extradata_offset+0x02, streamFile); - int encryption = read_16bit(sead.extradata_offset+0x0c, streamFile); //maybe 8bit? - /* encryption type 0x01 found in Final Fantasy XII TZA (PS4/PC) */ + size_t key_start = sead.extradata_id & 0xff; + size_t header_size = read_u16(sead.extradata_offset+0x02, sf); + int encryption = read_u8(sead.extradata_offset+0x0d, sf); + /* encryption type 0x01 found in Final Fantasy XII TZA (PS4/PC) + * (XOR subtable is fed to HCA's engine instead of generating from a key) */ - temp_streamFile = setup_sqex_sead_streamfile(streamFile, subfile_offset, subfile_size, encryption, header_size, key_start); - if (!temp_streamFile) goto fail; + /* extradata (mostly same as HCA's): */ + /* 0x00: version */ + /* 0x01: size */ + /* 0x02: header size */ + /* 0x04: frame size */ + /* 0x06: loop start frame */ + /* 0x08: loop end frame */ + /* 0x0a: inserted samples (encoder delay) */ + /* 0x0c: "use mixer" flag */ + /* 0x0d: encryption flag */ + /* 0x0e: reserved x2 */ + /* 0x10+ HCA header */ - temp_vgmstream = init_vgmstream_hca(temp_streamFile); + temp_sf = setup_sqex_sead_streamfile(sf, subfile_offset, subfile_size, encryption, header_size, key_start); + if (!temp_sf) goto fail; + + temp_vgmstream = init_vgmstream_hca(temp_sf); if (temp_vgmstream) { /* loops can be slightly different (~1000 samples) but probably HCA's are more accurate */ temp_vgmstream->num_streams = vgmstream->num_streams; @@ -230,17 +286,19 @@ VGMSTREAM * init_vgmstream_sqex_sead(STREAMFILE * streamFile) { temp_vgmstream->meta_type = vgmstream->meta_type; strcpy(temp_vgmstream->stream_name, vgmstream->stream_name); - close_streamfile(temp_streamFile); + close_streamfile(temp_sf); close_vgmstream(vgmstream); return temp_vgmstream; } else { - close_streamfile(temp_streamFile); + close_streamfile(temp_sf); goto fail; } } - case 0x00: /* dummy entry */ + case 0x00: /* NONE / dummy entry */ + case 0x05: /* XMA2 (extradata may be a XMA2 fmt extra chunk) */ + case 0x08: /* SWITCHOPUS (no extradata?) */ default: VGM_LOG("SQEX SEAD: unknown codec %x\n", sead.codec); goto fail; @@ -249,7 +307,7 @@ VGMSTREAM * init_vgmstream_sqex_sead(STREAMFILE * streamFile) { strcpy(vgmstream->stream_name, sead.readable_name); /* open the file for reading */ - if ( !vgmstream_open_stream(vgmstream, streamFile, start_offset) ) + if ( !vgmstream_open_stream(vgmstream, sf, start_offset) ) goto fail; return vgmstream; @@ -264,9 +322,9 @@ static void build_readable_name(char * buf, size_t buf_size, sead_header *sead, if (sead->is_sab) { char descriptor[255], name[255]; - if (sead->descriptor_size > 255 || sead->sndname_size > 255) goto fail; + if (sead->filename_size > 255 || sead->sndname_size > 255) goto fail; - read_string(descriptor,sead->descriptor_size+1,sead->descriptor_offset, sf); + read_string(descriptor,sead->filename_size+1,sead->filename_offset, sf); read_string(name,sead->sndname_size+1,sead->sndname_offset, sf); snprintf(buf,buf_size, "%s/%s", descriptor, name); @@ -274,20 +332,21 @@ static void build_readable_name(char * buf, size_t buf_size, sead_header *sead, else { char descriptor[255], name[255], mode[255]; - if (sead->descriptor_size > 255 || sead->filename_size > 255 || sead->cuename_size > 255 || sead->modename_size > 255) goto fail; + if (sead->filename_size > 255 || sead->muscname_size > 255 || sead->sectname_size > 255 || sead->modename_size > 255) goto fail; - read_string(descriptor,sead->descriptor_size+1,sead->descriptor_offset, sf); - //read_string(filename,sead->filename_size+1,sead->filename_offset, sf); /* same as filename, not too interesting */ - if (sead->cuename_offset) - read_string(name,sead->cuename_size+1,sead->cuename_offset, sf); + read_string(descriptor,sead->filename_size+1,sead->filename_offset, sf); + //read_string(filename,sead->muscname_size+1,sead->muscname_offset, sf); /* same as filename, not too interesting */ + if (sead->sectname_offset) + read_string(name,sead->sectname_size+1,sead->sectname_offset, sf); else if (sead->instname_offset) read_string(name,sead->instname_size+1,sead->instname_offset, sf); else strcpy(name, "?"); - read_string(mode,sead->modename_size+1,sead->modename_offset, sf); + if (sead->modename_offset > 0) + read_string(mode,sead->modename_size+1,sead->modename_offset, sf); - /* default mode in most files, not very interesting */ - if (strcmp(mode, "Mode") == 0 || strcmp(mode, "Mode0") == 0) + /* default mode in most files */ + if (sead->modename_offset == 0 || strcmp(mode, "Mode") == 0 || strcmp(mode, "Mode0") == 0) snprintf(buf,buf_size, "%s/%s", descriptor, name); else snprintf(buf,buf_size, "%s/%s/%s", descriptor, name, mode); @@ -299,357 +358,528 @@ fail: } static void parse_sead_mab_name(sead_header *sead, STREAMFILE *sf) { - int32_t (*read_32bit)(off_t,STREAMFILE*) = sead->big_endian ? read_32bitBE : read_32bitLE; - int16_t (*read_16bit)(off_t,STREAMFILE*) = sead->big_endian ? read_16bitBE : read_16bitLE; - int i, entries, cue, mode, cue_count, mode_count; - off_t entry_offset, cue_offset, mode_offset, name_offset, table_offset; - size_t name_size; - //int wave, wave_count; off_t wave_offset, subtable_offset; uint16_t wave_id; - int name = 0; + uint32_t (*read_u32)(off_t,STREAMFILE*) = sead->big_endian ? read_u32be : read_u32le; + uint16_t (*read_u16)(off_t,STREAMFILE*) = sead->big_endian ? read_u16be : read_u16le; + int i, j, k, entries; + off_t target_muscname_offset = 0, target_sectname_offset = 0; + size_t target_muscname_size = 0, target_sectname_size = 0; - /* find which name corresponds to our song (mabf can have N subsongs - * and X cues + Y modes and also Z instruments, one of which should reference it) */ - //todo exact name matching unknown, assumes subsong N = name N + /* find names referencing to our material stream, usually: + * - music > sections > layers (<> meters) > material index + * - instruments > instrument materials > material index */ - /* parse "musc" (music cue?) */ - entries = read_16bit(sead->musc_offset + 0x04, sf); + + /* parse musics */ + entries = read_u16(sead->musc_section_offset + 0x04, sf); for (i = 0; i < entries; i++) { - entry_offset = sead->musc_offset + read_32bit(sead->musc_offset + 0x10 + i*0x04, sf); + off_t musc_offset = sead->musc_section_offset + read_u32(sead->musc_section_offset + 0x10 + i*0x04, sf); + off_t muscname_offset, table_offset; + size_t musc_size, muscname_size; + int musc_version, sect_count, mode_count; - /* 0x00: config? */ - sead->filename_offset = entry_offset + read_16bit(entry_offset + 0x02, sf); - cue_count = read_8bit(entry_offset + 0x04, sf); - mode_count = read_8bit(entry_offset + 0x05, sf); - /* 0x06: some low number? */ - /* 0x07: always 0x80? (apparently not an offset/size) */ - /* 0x08: id? */ - /* 0x0a: 0? */ + musc_version = read_u8 (musc_offset + 0x00, sf); + /* 0x01: "output"? */ + musc_size = read_u16(musc_offset + 0x02, sf); + sect_count = read_u8 (musc_offset + 0x04, sf); + mode_count = read_u8 (musc_offset + 0x05, sf); + /* 0x06: category? */ + /* 0x07: priority (default 0x80) */ + /* 0x08: number */ + /* 0x0a: flags */ + /* 0x0b: distance attenuation curve? */ + /* 0x0c: interior factor (f32) */ + /* 0x10: name in <=v8 */ + /* 0x20: audible range? (f32) */ + /* 0x24: inner range? (f32) */ + /* 0x28: volume (f32) */ + /* 0x2c: send busses x4 / send volumes (f32) x4 */ + /* 0x40: counts: aux sends/end methods/start methods/zero-ones */ /* 0x44: sample rate */ - /* others: unknown/null */ - sead->filename_size = read_8bit(entry_offset + 0x48, sf); + muscname_size = read_u8(musc_offset + 0x48, sf); + /* 0x49: port? */ + /* 0x4a: reserved */ + /* 0x4c: audio length (float) */ + /* 0x50+: extra data in later versions */ - /* table points to all cue offsets first then all modes offsets */ - table_offset = align_size_to_block(sead->filename_offset + sead->filename_size + 0x01, 0x10); + if (musc_version <= 8) { + muscname_offset = musc_offset + 0x10; + muscname_size = 0x0f; + } + else { + muscname_offset = musc_offset + musc_size; + } - /* cue name (ex. "bgm_007_take2" / "bgm_007s" / etc subsongs) */ - for (cue = 0; cue < cue_count; cue++) { - cue_offset = sead->musc_offset + 0x20 + read_32bit(table_offset + cue*0x04, sf); + table_offset = align_size_to_block(muscname_offset + muscname_size + 0x01, 0x10); - /* 0x00: id? */ - name_offset = cue_offset + read_16bit(cue_offset + 0x02, sf); - name_size = read_8bit(cue_offset + 0x04, sf); - //wave_count = read_8bit(cue_offset + 0x05, sf); - /* 0x06: ? */ - /* 0x0c: num samples */ - /* 0x10: loop start */ - /* 0x14: loop end */ - /* 0x18: flag? */ - /* others: ? */ + /* parse sections (layered parts that possibly transition into others using "meter" info) */ + for (j = 0; j < sect_count; j++) { + off_t sect_offset = musc_offset + read_u32(table_offset + j*0x04, sf); + off_t sectname_offset, subtable_offset; + size_t sect_size, sectname_size; + int sect_version, layr_count; - name++; - if (name == sead->target_subsong || cue_count == 1) { - sead->cuename_offset = name_offset; - sead->cuename_size = name_size; - break; + sect_version = read_u8 (sect_offset + 0x00, sf); + /* 0x01: number */ + sect_size = read_u16(sect_offset + 0x02, sf); + + if (sect_version <= 7) { + /* 0x04: meter count */ + layr_count = read_u8(sect_offset + 0x05, sf); + /* 0x06: custom points count */ + /* 0x08: entry points (sample) */ + /* 0x0c: exit points (sample) */ + /* 0x10: loop start */ + /* 0x14: loop end */ + /* 0x18+: meter transition timing info (offsets, points, curves, etc) */ + sectname_offset = 0x30; + sectname_size = 0x0f; + + subtable_offset = sect_offset + sect_size; + } + else { + sectname_size = read_u8(sect_offset + 0x04, sf); + layr_count = read_u8(sect_offset + 0x05, sf); + /* 0x06: custom points count */ + /* 0x08: entry point (sample) */ + /* 0x0c: exit point (sample) */ + /* 0x10: loop start */ + /* 0x14: loop end */ + /* 0x18: meter count */ + /* 0x1c+: meter transition timing info (offsets, points, curves, etc) */ + sectname_offset = sect_offset + sect_size; + + subtable_offset = align_size_to_block(sectname_offset + sectname_size + 0x01, 0x10); } -#if 0 //this works for some games like KH3 but not others like FFXII - /* subtable: first N wave refs + ? unk refs (rarely more than 1 each) */ - subtable_offset = align_size_to_block(name_offset + name_size + 1, 0x10); - for (wave = 0; wave < wave_count; wave++) { - wave_offset = cue_offset + read_32bit(subtable_offset + wave*0x04, sf); + if (j + 1== sead->target_subsong) { + target_muscname_offset = muscname_offset; + target_muscname_size = muscname_size; + target_sectname_offset = sectname_offset; + target_sectname_size = sectname_size; + } - /* 0x00: config? */ - /* 0x02: entry size */ - wave_id = read_16bit(wave_offset + 0x04, sf); - /* 0x06: null? */ - /* 0x08: null? */ - /* 0x0c: some id/config? */ + /* parse layers */ + for (k = 0; k < layr_count; k++) { + off_t layr_offset = sect_offset + read_u32(subtable_offset + k*0x04, sf); + int mtrl_index; - if (wave_id == sead->wave_id) { - sead->cuename_offset = name_offset; - sead->cuename_size = name_size; - break; + /* 0x00: version */ + /* 0x01: flags */ + /* 0x02: size */ + mtrl_index = read_u16(layr_offset + 0x04, sf); + /* 0x06: loop count */ + /* 0x08: offset */ + /* 0x0c: end point (sample) */ + + if (mtrl_index == sead->mtrl_index) { + sead->muscname_offset = muscname_offset; + sead->muscname_size = muscname_size; + sead->sectname_offset = sectname_offset; + sead->sectname_size = sectname_size; + //break; } } - if (sead->cuename_offset) - break; -#endif + /* use last name for cloned materials (see below) */ + //if (sead->sectname_offset > 0) + // break; + + /* meters offset go after layer offsets, not useful */ } - /* mode name (ex. almost always "Mode" and only 1 entry, rarely "Water" / "Restaurant" / etc) - * no idea how modes are referenced (perhaps manually with in-game events) - * so just a quick hack, only found multiple in FFXV's bgm_gardina */ + /* in some files (ex. FF12 TZA) materials are cloned, but sections only point to one of the + * clones, so one material has multiple section names while others have none. For those cases + * we can try to match names by subsong number */ + if (sead->sectname_offset == 0) { + sead->muscname_offset = target_muscname_offset; + sead->muscname_size = target_muscname_size; + sead->sectname_offset = target_sectname_offset; + sead->sectname_size = target_sectname_size; + VGM_LOG("MAB: voodoo name matching\n"); + } + + + /* modes have names (almost always "Mode" and only 1 entry, rarely "Water" / "Restaurant" / etc) + * and seem referenced manually (in-game events) and alter sound parameters instead of being + * an actual playable thing (only found multiple in FFXV's bgm_gardina) */ + + /* hack to use mode as subsong name, which for the only known file looks correct */ if (mode_count == sead->total_subsongs) - mode = sead->target_subsong - 1; + i = sead->target_subsong - 1; else - mode = 0; + i = 0; - { //for (mode = 0; mode < mode_count; mode++) { - mode_offset = sead->musc_offset + 0x20 + read_32bit(table_offset + cue_count*0x04 + mode*0x04, sf); + { //for (i = 0; i < mode_count; i++) { + off_t mode_offset = musc_offset + read_u32(table_offset + sect_count*0x04 + i*0x04, sf); + off_t modename_offset; + size_t mode_size, modename_size; + int mode_version; - /* 0x00: id? */ - name_offset = mode_offset + read_16bit(mode_offset + 0x02, sf); - /* 0x04: mode id */ - name_size = read_8bit(mode_offset + 0x06, sf); - /* 0x08: offset? */ - /* others: floats and stuff */ + mode_version = read_u8 (mode_offset + 0x00, sf); + /* 0x01: flags */ + mode_size = read_u16(mode_offset + 0x02, sf); + /* 0x04: number */ + modename_size = read_u8 (mode_offset + 0x06, sf); + /* 0x07: reserved */ + /* 0x08: transition param offset */ + /* 0x0c: reserved */ + /* 0x10: volume */ + /* 0x14: pitch */ + /* 0x18: lowpass */ + /* 0x1c: speed */ + /* 0x20: name <=v2 (otherwise null) */ - sead->modename_offset = name_offset; - sead->modename_size = name_size; + if (mode_version <= 2) { + modename_offset = mode_offset + 0x20; + modename_size = 0x0f; + } + else { + modename_offset = mode_offset + mode_size; + } + + sead->modename_offset = modename_offset; + sead->modename_size = modename_size; } } - /* parse "inst" (instruments) */ - entries = read_16bit(sead->inst_offset + 0x04, sf); + /* parse instruments (very rare, ex. KH3 tut) */ + entries = read_u16(sead->inst_section_offset + 0x04, sf); for (i = 0; i < entries; i++) { - entry_offset = sead->inst_offset + read_32bit(sead->inst_offset + 0x10 + i*0x04, sf); + off_t inst_offset = sead->inst_section_offset + read_u32(sead->inst_section_offset + 0x10 + i*0x04, sf); + off_t instname_offset, mtrl_offset; + size_t instname_size; + int mtrl_count; - /* 0x00: id? */ - /* 0x02: base size? */ - /* 0x05: count? */ - //wave_count = read_8bit(entry_offset + 0x06, sf); - /* 0x0c: num samples */ - /* 0x10: loop start */ - /* 0x14: loop end */ - /* 0x18: flag? */ - /* others: ? */ + /* 0x00: version */ + /* 0x01: "output"? */ + /* 0x02: size */ + /* 0x04: type (normal, random, switch, etc) */ + mtrl_count = read_u8(inst_offset + 0x05, sf); + /* 0x06: category */ + /* 0x07: priority */ + /* 0x08: number */ + /* 0x0a: flags */ + /* 0x0b: distance attenuation curve */ + /* 0x0c: interior factor (f32) */ + /* 0x10: audible range (f32) */ + /* 0x14: inner range (f32) */ + /* 0x18: play length (f32) */ + /* 0x1c: reserved */ + /* 0x20: ? (f32) */ + /* 0x30: name */ - /* no apparent fields and inst is very rare (ex. KH3 tut) */ - name_offset = entry_offset + 0x30; - name_size = 0x0F; + instname_offset = inst_offset + 0x30; + instname_size = 0x0F; - name++; - if (name == sead->target_subsong) { - sead->instname_offset = name_offset; - sead->instname_size = name_size; - break; - } + mtrl_offset = instname_offset + instname_size + 0x01; + /* parse instrument materials */ + for (j = 0; j < mtrl_count; j++) { + size_t mtrl_size; + int mtrl_index; -#if 0 //not actually tested - if (wave_count != 1) break; /* ? */ - - /* subtable: N wave refs? */ - subtable_offset = align_size_to_block(name_offset + name_size + 1, 0x10); - - for (wave = 0; wave < wave_count; wave++) { - wave_offset = subtable_offset + read_32bit(subtable_offset + wave*0x04, sf); - - /* 0x00: config? */ - /* 0x02: entry size? */ - wave_id = read_16bit(wave_offset + 0x04, sf); - /* 0x06: ? */ - /* 0x08: id/crc? */ - /* 0x0c: ? */ + /* 0x00: version */ + /* 0x01: value (meaning depends on type) */ + mtrl_size = read_u16(mtrl_offset + 0x02, sf); + mtrl_index = read_u16(mtrl_offset + 0x04, sf); + /* 0x06: number */ + /* 0x08: volume */ + /* 0x0c: sync point */ /* 0x10: sample rate */ - /* others: null? */ + /* 0x14-20: reserved */ - if (wave_id == sead->wave_id) { - sead->instname_offset = name_offset; - sead->instname_size = name_size; + if (mtrl_index == sead->mtrl_index) { + sead->instname_offset = instname_offset; + sead->instname_size = instname_size; break; } + + mtrl_offset += mtrl_size; } - if (sead->instname_offset) + if (sead->instname_offset > 0) break; -#endif } } static void parse_sead_sab_name(sead_header *sead, STREAMFILE *sf) { - int32_t (*read_32bit)(off_t,STREAMFILE*) = sead->big_endian ? read_32bitBE : read_32bitLE; - int16_t (*read_16bit)(off_t,STREAMFILE*) = sead->big_endian ? read_16bitBE : read_16bitLE; - int i, snd_entries, trk_entries, snd_id, wave_id, snd_found = 0; - size_t size; - off_t entry_offset; + uint32_t (*read_u32)(off_t,STREAMFILE*) = sead->big_endian ? read_u32be : read_u32le; + uint16_t (*read_u16)(off_t,STREAMFILE*) = sead->big_endian ? read_u16be : read_u16le; + int i, j, entries; + /* find names referencing to our material stream, usually: + * - sound > sequence index + * - sequence > command > track index + * - track > material index + * + * most of the time sounds<>materials go 1:1 but there are exceptions + * (ex. DQB se_break_soil, FFXV aircraftzeroone, FFXV 03bt100031pc00) + * + * some configs (mainly zero-ones, that seem to be a kind of random sound) have a name too, + * but it's usually "Default" "(name)ZeroOne" and other uninteresting stuff */ - //todo looks mostly correct for many subsongs but in rare cases wave_ids aren't referenced - // or maybe id needs another jump (seq?) (ex. DQB se_break_soil, FFXV aircraftzeroone, FFXV 03bt100031pc00) + /* parse sounds */ + entries = read_u16(sead->snd_section_offset + 0x04, sf); + for (i = 0; i < entries; i++) { + off_t snd_offset = sead->snd_section_offset + read_u32(sead->snd_section_offset + 0x10 + i*0x04, sf); + size_t snd_size, sndname_size; + off_t seqi_start, seqi_offset, sndname_offset; + int snd_version, seqi_count; - snd_entries = read_16bit(sead->snd_offset + 0x04, sf); - trk_entries = read_16bit(sead->trk_offset + 0x04, sf); - - /* parse "trk" (track info) */ - for (i = 0; i < trk_entries; i++) { - entry_offset = sead->trk_offset + read_32bit(sead->trk_offset + 0x10 + i*0x04, sf); - - /* 0x00: type? */ - /* 0x01: subtype? */ - size = read_16bit(entry_offset + 0x02, sf); /* bigger if 'type=03' */ - /* 0x04: trk id? */ - /* 0x04: some id? */ - - if (size > 0x10) { - snd_id = read_8bit(entry_offset + 0x10, sf); - wave_id = read_16bit(entry_offset + 0x11, sf); - } - else { - snd_id = read_16bit(entry_offset + 0x08, sf); - wave_id = read_16bit(entry_offset + 0x0a, sf); - } - - - if (wave_id == sead->wave_id) { - snd_found = 1; - break; - } - } - - if (snd_found && snd_id >= snd_entries) { - VGM_LOG("SEAD: bad snd_id found\n"); - snd_found = 0; - } - - if (!snd_found) { - if (sead->total_subsongs == 1 || snd_entries == 1) { - snd_id = 0; /* meh */ - VGM_LOG("SEAD: snd_id not found, using first\n"); - } else { - VGM_LOG("SEAD: snd_id not found, subsongs=%i, snd=%i, trk=%i\n", sead->total_subsongs, snd_entries, trk_entries); - return; - } - } - - /* parse "snd " (sound info) */ - { - off_t entry_offset = sead->snd_offset + read_32bit(sead->snd_offset + 0x10 + snd_id*0x04, sf); - - /* 0x00: config? */ - sead->sndname_offset = entry_offset + read_16bit(entry_offset + 0x02, sf); - /* 0x04: count of ? */ - /* 0x05: count of ? (0 if no sound exist in file) */ - /* 0x06: some low number? */ - /* 0x07: always 0x80? (apparently not an offset/size) */ - /* 0x08: snd id */ - /* 0x0a: 0? */ - /* 0x0c: 1.0? */ + snd_version = read_u8(snd_offset + 0x00, sf); + /* 0x01: work? */ + snd_size = read_u16(snd_offset + 0x02, sf); + /* 0x04: type */ + seqi_count = read_u8(snd_offset + 0x05, sf); /* may be 0 */ + /* 0x06: category */ + /* 0x07: priority (default 0x80) */ + /* 0x08: number */ + /* 0x0a: start+end macro */ + /* 0x0c: volume */ + /* 0x10: cycle config */ /* 0x1a: header size? */ - /* 0x1c: 30.0? * */ - /* 0x24: crc/id? */ - /* 0x46: header size? */ - /* 0x4c: header size? */ + seqi_start = read_u16(snd_offset + 0x1a, sf); + /* 0x1c: audible range */ + /* 0x20: output/curve/port */ + /* 0x23: reserved/name size */ + /* 0x24: play length */ + /* 0x28+: more config params */ - if (sead->version == 1) { - sead->sndname_offset -= 0x10; - sead->sndname_size = read_8bit(entry_offset + 0x08, sf); + if (snd_version <= 8) { + sndname_size = 0x0F; + sndname_offset = snd_offset + 0x50; } else { - sead->sndname_size = read_8bit(entry_offset + 0x23, sf); + sndname_size = read_u8(snd_offset + 0x23, sf); + sndname_offset = snd_offset + snd_size; } - /* 0x24: unique id? (referenced in "seq" section?) */ - /* others: probably sound config like pan/volume (has floats and stuff) */ + /* parse sequence info */ + seqi_offset = snd_offset + seqi_start; + for (j = 0; j < seqi_count; j++) { + size_t seqi_size; + int seq_index; + + /* 0x00: version */ + /* 0x01: reserved */ + seqi_size = read_u16(seqi_offset + 0x02, sf); + seq_index = read_u16(seqi_offset + 0x04, sf); + /* 0x06: sequence ID */ + /* 0x08: reserved x2 */ + + seqi_offset += seqi_size; + + /* parse sequence */ + { + off_t seq_offset = sead->seq_section_offset + read_u32(sead->seq_section_offset + 0x10 + seq_index*0x04, sf); + off_t cmnd_start, cmnd_offset; + int seq_version; + + seq_version = read_u8(seq_offset + 0x00, sf); + /* 0x01: reserved */ + /* 0x02: size */ + + if (seq_version <= 2) { + /* 0x04: config depending on type */ + /* 0x10: number */ + /* 0x12: volume zero-one offsets */ + /* 0x12: pitch zero-one offsets */ + cmnd_start = read_u16(seq_offset + 0x16, sf); + /* 0x18: reserved x2 */ + } + else { + /* 0x04: id */ + cmnd_start = read_u16(seq_offset + 0x06, sf); + /* 0x08: zero-ones count */ + /* 0x09: reserved */ + /* 0x10: config depending on type */ + } + + + /* parse sequence commands (breaks once an end command is found) */ + cmnd_offset = seq_offset + cmnd_start; + while (cmnd_offset < sead->trk_section_offset) { + uint8_t cmnd_size, cmnd_type, cmnd_body; + + /* 0x00: version (each command may have a different version) */ + cmnd_size = read_u8(cmnd_offset + 0x01, sf); /* doesn't include body */ + cmnd_type = read_u8(cmnd_offset + 0x02, sf); + cmnd_body = read_u8(cmnd_offset + 0x03, sf); + + /* 0=none, 1=end, 2=key on, 3=interval, 4=keyoff, 5=wat, 6=loop start, 7=loop end, 8=trigger */ + if (cmnd_type == 0x02) { + uint32_t trk_index; + + trk_index = read_u32(cmnd_offset + cmnd_size + 0x00, sf); + /* 0x04: is loop */ + /* 0x05: reserved */ + /* 0x06: track id */ + /* 0x08: play length (f32) */ + + /* parse track */ + { + off_t trk_offset = sead->trk_section_offset + read_u32(sead->trk_section_offset + 0x10 + trk_index*0x04, sf); + uint8_t trk_type; + uint16_t mtrl_index; + + /* 0x00: version */ + trk_type = read_u8(trk_offset + 0x01, sf); + /* 0x02: size */ + /* 0x04: config depending on type */ + /* 0x08: id */ + /* 0x0a: child id */ + /* 0x0c: reserved */ + + /* 0=none, 1=material, 2=sound */ + if (trk_type == 0x01) { + mtrl_index = read_u16(trk_offset + 0x04, sf); + /* 0x02: bank */ + + /* assumes same bank, not sure if bank info is even inside .sab */ + if (mtrl_index == sead->mtrl_index) { + sead->sndname_offset = sndname_offset; + sead->sndname_size = sndname_size; + } + } + else if (trk_type == 0x02) { + /* 0x00: index */ + /* 0x02: reserved */ + /* parse sound again? */ + } + } + } + + cmnd_offset += cmnd_size + cmnd_body; + + /* commands normally end when a type 0=none is found */ + if (cmnd_type <= 0x00 || cmnd_type > 0x08) + break; + if (sead->sndname_offset > 0) + break; + } + } + + } } } + static int parse_sead(sead_header *sead, STREAMFILE *sf) { - int32_t (*read_32bit)(off_t,STREAMFILE*) = sead->big_endian ? read_32bitBE : read_32bitLE; - int16_t (*read_16bit)(off_t,STREAMFILE*) = sead->big_endian ? read_16bitBE : read_16bitLE; + uint32_t (*read_u32)(off_t,STREAMFILE*) = sead->big_endian ? read_u32be : read_u32le; + uint16_t (*read_u16)(off_t,STREAMFILE*) = sead->big_endian ? read_u16be : read_u16le; /** base header **/ - sead->version = read_8bit(0x04, sf); /* usually 0x02, rarely 0x01 (ex FF XV early songs) */ - /* 0x05(1): 0/1? */ - /* 0x06(2): ? (usually 0x10, rarely 0x20) */ - /* 0x08(1): 3/4? */ - sead->descriptor_size = read_8bit(0x09, sf); - /* 0x0a(2): ? */ - if (read_32bit(0x0c, sf) != get_streamfile_size(sf)) + /* 0x00: id */ + /* 0x04: version (usually 0x02, rarely 0x01 ex FF XV early songs) */ + /* 0x05: flags */ + /* 0x06: size */ + /* 0x08: chunk count (in practice mab=3, sab=4) */ + sead->filename_size = read_u8(0x09, sf); + /* 0x0a: number (shared between multiple sab/mab though) */ + if (read_u32(0x0c, sf) != get_streamfile_size(sf)) goto fail; - if (sead->descriptor_size == 0) /* not set when version == 1 */ - sead->descriptor_size = 0x0f; - sead->descriptor_offset = 0x10; /* file descriptor ("BGM", "Music2", "SE", etc, long names are ok) */ - sead->sections_offset = sead->descriptor_offset + (sead->descriptor_size + 0x01); /* string null matters for padding */ + /* not set/reserved when version == 1 (name is part of size) */ + if (sead->filename_size == 0) + sead->filename_size = 0x0f; + sead->filename_offset = 0x10; /* file description ("BGM", "Music2", "SE", etc, long names are ok) */ + sead->sections_offset = sead->filename_offset + (sead->filename_size + 0x01); /* string null matters for padding */ sead->sections_offset = align_size_to_block(sead->sections_offset, 0x10); + /* roughly, mab play audio by calling musics/instruments, and sab with sounds/sequences/track. Both + * point to a "material" or stream wave that may be reused. We only want material streams as subsongs, + * but also try to find names from musics/sounds/etc. */ - /** offsets to sections **/ + /** chunk table elements (offsets to sections) **/ + /* 0x00: id */ + /* 0x04: version */ + /* 0x05: reserved */ + /* 0x06: size */ + /* 0x08: offset */ + /* 0x0c: reserved */ if (sead->is_sab) { - if (read_32bitBE(sead->sections_offset + 0x00, sf) != 0x736E6420) goto fail; /* "snd " (sonds) */ - if (read_32bitBE(sead->sections_offset + 0x10, sf) != 0x73657120) goto fail; /* "seq " (unknown) */ - if (read_32bitBE(sead->sections_offset + 0x20, sf) != 0x74726B20) goto fail; /* "trk " (unknown) */ - if (read_32bitBE(sead->sections_offset + 0x30, sf) != 0x6D74726C) goto fail; /* "mtrl" (headers/streams) */ - sead->snd_offset = read_32bit(sead->sections_offset + 0x08, sf); - //sead->seq_offset = read_32bit(sead->sections_offset + 0x18, sf); - sead->trk_offset = read_32bit(sead->sections_offset + 0x28, sf); - sead->mtrl_offset = read_32bit(sead->sections_offset + 0x38, sf); + if (read_u32be(sead->sections_offset + 0x00, sf) != 0x736E6420) goto fail; /* "snd " (sounds) */ + if (read_u32be(sead->sections_offset + 0x10, sf) != 0x73657120) goto fail; /* "seq " (sequences) */ + if (read_u32be(sead->sections_offset + 0x20, sf) != 0x74726B20) goto fail; /* "trk " (tracks) */ + if (read_u32be(sead->sections_offset + 0x30, sf) != 0x6D74726C) goto fail; /* "mtrl" (material headers/streams) */ + sead->snd_section_offset = read_u32(sead->sections_offset + 0x08, sf); + sead->seq_section_offset = read_u32(sead->sections_offset + 0x18, sf); + sead->trk_section_offset = read_u32(sead->sections_offset + 0x28, sf); + sead->mtrl_section_offset = read_u32(sead->sections_offset + 0x38, sf); } else if (sead->is_mab) { - if (read_32bitBE(sead->sections_offset + 0x00, sf) != 0x6D757363) goto fail; /* "musc" (cues) */ - if (read_32bitBE(sead->sections_offset + 0x10, sf) != 0x696E7374) goto fail; /* "inst" (instruments) */ - if (read_32bitBE(sead->sections_offset + 0x20, sf) != 0x6D74726C) goto fail; /* "mtrl" (headers/streams) */ - sead->musc_offset = read_32bit(sead->sections_offset + 0x08, sf); - sead->inst_offset = read_32bit(sead->sections_offset + 0x18, sf); - sead->mtrl_offset = read_32bit(sead->sections_offset + 0x28, sf); + if (read_u32be(sead->sections_offset + 0x00, sf) != 0x6D757363) goto fail; /* "musc" (musics) */ + if (read_u32be(sead->sections_offset + 0x10, sf) != 0x696E7374) goto fail; /* "inst" (instruments) */ + if (read_u32be(sead->sections_offset + 0x20, sf) != 0x6D74726C) goto fail; /* "mtrl" (material headers/streams) */ + sead->musc_section_offset = read_u32(sead->sections_offset + 0x08, sf); + sead->inst_section_offset = read_u32(sead->sections_offset + 0x18, sf); + sead->mtrl_section_offset = read_u32(sead->sections_offset + 0x28, sf); } else { goto fail; } - /* section format at offset: - * 0x00(2): 0/1? - * 0x02(2): header size? (always 0x10) - * 0x04(2): entries - * 0x06(+): padded to 0x10 - * 0x10 + 0x04*entry: offset to entry from table start (also padded to 0x10 at the end) */ + /* section "chunk" format at offset: */ + /* 0x00: version */ + /* 0x01: reserved */ + /* 0x02: size */ + /* 0x04: entries */ + /* 0x06: reserved */ + /* 0x10+ 0x04*entry: offset to entry from table start */ - /* find meta_offset in "mtrl" and total subsongs */ + /* find target material offset */ { int i, entries; - entries = read_16bit(sead->mtrl_offset+0x04, sf); + entries = read_u16(sead->mtrl_section_offset + 0x04, sf); if (sead->target_subsong == 0) sead->target_subsong = 1; sead->total_subsongs = 0; - sead->meta_offset = 0; + sead->mtrl_offset = 0; /* manually find subsongs as entries can be dummy (ex. sfx banks in Dissidia Opera Omnia) */ for (i = 0; i < entries; i++) { - off_t entry_offset = sead->mtrl_offset + read_32bit(sead->mtrl_offset + 0x10 + i*0x04, sf); + off_t entry_offset = sead->mtrl_section_offset + read_u32(sead->mtrl_section_offset + 0x10 + i*0x04, sf); - if (read_8bit(entry_offset + 0x05, sf) == 0) { + if (read_u8(entry_offset + 0x05, sf) == 0) { continue; /* codec 0 when dummy (see stream header) */ } - sead->total_subsongs++; - if (!sead->meta_offset && sead->total_subsongs == sead->target_subsong) { - sead->meta_offset = entry_offset; + if (!sead->mtrl_offset && sead->total_subsongs == sead->target_subsong) { + sead->mtrl_offset = entry_offset; + sead->mtrl_index = i; } } - if (sead->meta_offset == 0) goto fail; + /* SAB can contain 0 entries too */ + if (sead->mtrl_offset == 0) + goto fail; } - /** stream header **/ - /* 0x00(2): 0x00/01? */ - /* 0x02(2): base entry size? (0x20) */ - sead->channel_count = read_8bit(sead->meta_offset + 0x04, sf); - sead->codec = read_8bit(sead->meta_offset + 0x05, sf); - sead->wave_id = read_16bit(sead->meta_offset + 0x06, sf); /* 0..N */ - sead->sample_rate = read_32bit(sead->meta_offset + 0x08, sf); - sead->loop_start = read_32bit(sead->meta_offset + 0x0c, sf); /* in samples but usually ignored */ - - sead->loop_end = read_32bit(sead->meta_offset + 0x10, sf); - sead->extradata_size = read_32bit(sead->meta_offset + 0x14, sf); /* including subfile header, can be 0 */ - sead->stream_size = read_32bit(sead->meta_offset + 0x18, sf); /* not including subfile header */ - sead->special_size = read_32bit(sead->meta_offset + 0x1c, sf); + /* 0x00: version */ + /* 0x01: reserved */ + /* 0x02: size */ + sead->channels = read_u8 (sead->mtrl_offset + 0x04, sf); + sead->codec = read_u8 (sead->mtrl_offset + 0x05, sf); /* format */ + sead->mtrl_number = read_u16(sead->mtrl_offset + 0x06, sf); /* 0..N */ + sead->sample_rate = read_u32(sead->mtrl_offset + 0x08, sf); + sead->loop_start = read_u32(sead->mtrl_offset + 0x0c, sf); /* in samples but usually ignored */ + sead->loop_end = read_u32(sead->mtrl_offset + 0x10, sf); + sead->extradata_size= read_u32(sead->mtrl_offset + 0x14, sf); /* including subfile header, can be 0 */ + sead->stream_size = read_u32(sead->mtrl_offset + 0x18, sf); /* not including subfile header */ + sead->extradata_id = read_u16(sead->mtrl_offset + 0x1c, sf); + /* 0x1e: reserved */ sead->loop_flag = (sead->loop_end > 0); - sead->extradata_offset = sead->meta_offset + 0x20; + sead->extradata_offset = sead->mtrl_offset + 0x20; - - /** info section (get stream name) **/ if (sead->is_sab) { parse_sead_sab_name(sead, sf); } diff --git a/Frameworks/vgmstream/vgmstream/src/meta/sqex_sead_streamfile.h b/Frameworks/vgmstream/vgmstream/src/meta/sqex_sead_streamfile.h index 98cad9284..25f567c81 100644 --- a/Frameworks/vgmstream/vgmstream/src/meta/sqex_sead_streamfile.h +++ b/Frameworks/vgmstream/vgmstream/src/meta/sqex_sead_streamfile.h @@ -1,86 +1,67 @@ -#ifndef _SQEX_SEAD_STREAMFILE_H_ -#define _SQEX_SEAD_STREAMFILE_H_ -#include "../streamfile.h" - -static STREAMFILE* setup_sqex_sead_streamfile(STREAMFILE *streamFile, off_t subfile_offset, size_t subfile_size, int encryption, size_t header_size, size_t key_start); - - -typedef struct { - size_t header_size; - size_t key_start; -} sqex_sead_decryption_data; - - -static size_t sqex_sead_decryption_read(STREAMFILE *streamfile, uint8_t *dest, off_t offset, size_t length, sqex_sead_decryption_data* data) { - /* Found in FFXII_TZA.exe (same key in SCD Ogg V3) */ - static const uint8_t encryption_key[0x100] = { - 0x3A,0x32,0x32,0x32,0x03,0x7E,0x12,0xF7,0xB2,0xE2,0xA2,0x67,0x32,0x32,0x22,0x32, // 00-0F - 0x32,0x52,0x16,0x1B,0x3C,0xA1,0x54,0x7B,0x1B,0x97,0xA6,0x93,0x1A,0x4B,0xAA,0xA6, // 10-1F - 0x7A,0x7B,0x1B,0x97,0xA6,0xF7,0x02,0xBB,0xAA,0xA6,0xBB,0xF7,0x2A,0x51,0xBE,0x03, // 20-2F - 0xF4,0x2A,0x51,0xBE,0x03,0xF4,0x2A,0x51,0xBE,0x12,0x06,0x56,0x27,0x32,0x32,0x36, // 30-3F - 0x32,0xB2,0x1A,0x3B,0xBC,0x91,0xD4,0x7B,0x58,0xFC,0x0B,0x55,0x2A,0x15,0xBC,0x40, // 40-4F - 0x92,0x0B,0x5B,0x7C,0x0A,0x95,0x12,0x35,0xB8,0x63,0xD2,0x0B,0x3B,0xF0,0xC7,0x14, // 50-5F - 0x51,0x5C,0x94,0x86,0x94,0x59,0x5C,0xFC,0x1B,0x17,0x3A,0x3F,0x6B,0x37,0x32,0x32, // 60-6F - 0x30,0x32,0x72,0x7A,0x13,0xB7,0x26,0x60,0x7A,0x13,0xB7,0x26,0x50,0xBA,0x13,0xB4, // 70-7F - 0x2A,0x50,0xBA,0x13,0xB5,0x2E,0x40,0xFA,0x13,0x95,0xAE,0x40,0x38,0x18,0x9A,0x92, // 80-8F - 0xB0,0x38,0x00,0xFA,0x12,0xB1,0x7E,0x00,0xDB,0x96,0xA1,0x7C,0x08,0xDB,0x9A,0x91, // 90-9F - 0xBC,0x08,0xD8,0x1A,0x86,0xE2,0x70,0x39,0x1F,0x86,0xE0,0x78,0x7E,0x03,0xE7,0x64, // A0-AF - 0x51,0x9C,0x8F,0x34,0x6F,0x4E,0x41,0xFC,0x0B,0xD5,0xAE,0x41,0xFC,0x0B,0xD5,0xAE, // B0-BF - 0x41,0xFC,0x3B,0x70,0x71,0x64,0x33,0x32,0x12,0x32,0x32,0x36,0x70,0x34,0x2B,0x56, // C0-CF - 0x22,0x70,0x3A,0x13,0xB7,0x26,0x60,0xBA,0x1B,0x94,0xAA,0x40,0x38,0x00,0xFA,0xB2, // D0-DF - 0xE2,0xA2,0x67,0x32,0x32,0x12,0x32,0xB2,0x32,0x32,0x32,0x32,0x75,0xA3,0x26,0x7B, // E0-EF - 0x83,0x26,0xF9,0x83,0x2E,0xFF,0xE3,0x16,0x7D,0xC0,0x1E,0x63,0x21,0x07,0xE3,0x01, // F0-FF - }; - size_t bytes_read; - off_t encrypted_offset = data->header_size; - int i; - - bytes_read = streamfile->read(streamfile, dest, offset, length); - - /* decrypt data (xor) */ - if (offset >= encrypted_offset) { - for (i = 0; i < bytes_read; i++) { - dest[i] ^= encryption_key[(data->key_start + (offset - encrypted_offset) + i) % 0x100]; - } - } - - return bytes_read; -} - -/* decrypts subfile if neccessary */ -static STREAMFILE* setup_sqex_sead_streamfile(STREAMFILE *streamFile, off_t subfile_offset, size_t subfile_size, int encryption, size_t header_size, size_t key_start) { - STREAMFILE *temp_streamFile = NULL, *new_streamFile = NULL; - - /* setup subfile */ - new_streamFile = open_wrap_streamfile(streamFile); - if (!new_streamFile) goto fail; - temp_streamFile = new_streamFile; - - new_streamFile = open_clamp_streamfile(temp_streamFile, subfile_offset,subfile_size); - if (!new_streamFile) goto fail; - temp_streamFile = new_streamFile; - - if (encryption) { - sqex_sead_decryption_data io_data = {0}; - size_t io_data_size = sizeof(sqex_sead_decryption_data); - - io_data.header_size = header_size; - io_data.key_start = key_start; - - new_streamFile = open_io_streamfile(temp_streamFile, &io_data,io_data_size, sqex_sead_decryption_read,NULL); - if (!new_streamFile) goto fail; - temp_streamFile = new_streamFile; - } - - new_streamFile = open_fakename_streamfile(temp_streamFile, NULL,"hca"); - if (!new_streamFile) goto fail; - temp_streamFile = new_streamFile; - - return temp_streamFile; - -fail: - close_streamfile(temp_streamFile); - return NULL; -} - -#endif /* _SQEX_SEAD_STREAMFILE_H_ */ +#ifndef _SQEX_SEAD_STREAMFILE_H_ +#define _SQEX_SEAD_STREAMFILE_H_ +#include "../streamfile.h" + + +typedef struct { + size_t start; + size_t key_start; +} sqex_sead_io_data; + + +static size_t sqex_sead_io_read(STREAMFILE *sf, uint8_t *dest, off_t offset, size_t length, sqex_sead_io_data* data) { + /* Found in FFXII_TZA.exe (same key in SCD Ogg V3) */ + static const uint8_t key[0x100] = { + 0x3A,0x32,0x32,0x32,0x03,0x7E,0x12,0xF7,0xB2,0xE2,0xA2,0x67,0x32,0x32,0x22,0x32, // 00-0F + 0x32,0x52,0x16,0x1B,0x3C,0xA1,0x54,0x7B,0x1B,0x97,0xA6,0x93,0x1A,0x4B,0xAA,0xA6, // 10-1F + 0x7A,0x7B,0x1B,0x97,0xA6,0xF7,0x02,0xBB,0xAA,0xA6,0xBB,0xF7,0x2A,0x51,0xBE,0x03, // 20-2F + 0xF4,0x2A,0x51,0xBE,0x03,0xF4,0x2A,0x51,0xBE,0x12,0x06,0x56,0x27,0x32,0x32,0x36, // 30-3F + 0x32,0xB2,0x1A,0x3B,0xBC,0x91,0xD4,0x7B,0x58,0xFC,0x0B,0x55,0x2A,0x15,0xBC,0x40, // 40-4F + 0x92,0x0B,0x5B,0x7C,0x0A,0x95,0x12,0x35,0xB8,0x63,0xD2,0x0B,0x3B,0xF0,0xC7,0x14, // 50-5F + 0x51,0x5C,0x94,0x86,0x94,0x59,0x5C,0xFC,0x1B,0x17,0x3A,0x3F,0x6B,0x37,0x32,0x32, // 60-6F + 0x30,0x32,0x72,0x7A,0x13,0xB7,0x26,0x60,0x7A,0x13,0xB7,0x26,0x50,0xBA,0x13,0xB4, // 70-7F + 0x2A,0x50,0xBA,0x13,0xB5,0x2E,0x40,0xFA,0x13,0x95,0xAE,0x40,0x38,0x18,0x9A,0x92, // 80-8F + 0xB0,0x38,0x00,0xFA,0x12,0xB1,0x7E,0x00,0xDB,0x96,0xA1,0x7C,0x08,0xDB,0x9A,0x91, // 90-9F + 0xBC,0x08,0xD8,0x1A,0x86,0xE2,0x70,0x39,0x1F,0x86,0xE0,0x78,0x7E,0x03,0xE7,0x64, // A0-AF + 0x51,0x9C,0x8F,0x34,0x6F,0x4E,0x41,0xFC,0x0B,0xD5,0xAE,0x41,0xFC,0x0B,0xD5,0xAE, // B0-BF + 0x41,0xFC,0x3B,0x70,0x71,0x64,0x33,0x32,0x12,0x32,0x32,0x36,0x70,0x34,0x2B,0x56, // C0-CF + 0x22,0x70,0x3A,0x13,0xB7,0x26,0x60,0xBA,0x1B,0x94,0xAA,0x40,0x38,0x00,0xFA,0xB2, // D0-DF + 0xE2,0xA2,0x67,0x32,0x32,0x12,0x32,0xB2,0x32,0x32,0x32,0x32,0x75,0xA3,0x26,0x7B, // E0-EF + 0x83,0x26,0xF9,0x83,0x2E,0xFF,0xE3,0x16,0x7D,0xC0,0x1E,0x63,0x21,0x07,0xE3,0x01, // F0-FF + }; + int i; + size_t bytes = read_streamfile(dest, offset, length, sf); + + /* decrypt data (xor) */ + //if (offset >= data->start) { + for (i = 0; i < bytes; i++) { + if (offset + i >= data->start) { //todo recheck + dest[i] ^= key[(data->key_start + (offset - data->start) + i) % sizeof(key)]; + } + } + //} + + return bytes; +} + +/* decrypts subfile if needed */ +static STREAMFILE* setup_sqex_sead_streamfile(STREAMFILE* sf, off_t subfile_offset, size_t subfile_size, int encryption, size_t header_size, size_t key_start) { + STREAMFILE* new_sf = NULL; + + /* setup sf */ + new_sf = open_wrap_streamfile(sf); + new_sf = open_clamp_streamfile_f(new_sf, subfile_offset, subfile_size); + if (encryption) { + sqex_sead_io_data io_data = {0}; + + io_data.start = header_size; + io_data.key_start = key_start; + + new_sf = open_io_streamfile_f(new_sf, &io_data, sizeof(sqex_sead_io_data), sqex_sead_io_read, NULL); + } + + new_sf = open_fakename_streamfile_f(new_sf, NULL, "hca"); + return new_sf; +} + +#endif /* _SQEX_SEAD_STREAMFILE_H_ */ diff --git a/Frameworks/vgmstream/vgmstream/src/meta/txth.c b/Frameworks/vgmstream/vgmstream/src/meta/txth.c index 2d763728b..f98e6296f 100644 --- a/Frameworks/vgmstream/vgmstream/src/meta/txth.c +++ b/Frameworks/vgmstream/vgmstream/src/meta/txth.c @@ -36,7 +36,8 @@ typedef enum { PCM4_U = 26, /* 4-bit unsigned PCM (3rd and 4th gen games) */ OKI16 = 27, /* OKI ADPCM with 16-bit output (unlike OKI/VOX/Dialogic ADPCM's 12-bit) */ AAC = 28, /* Advanced Audio Coding (raw without .mp4) */ - TGC = 29 /* Tiger Game.com 4-bit ADPCM */ + TGC = 29, /* Tiger Game.com 4-bit ADPCM */ + ASF = 30, /* Argonaut ASF 4-bit ADPCM */ } txth_type; typedef struct { @@ -223,6 +224,7 @@ VGMSTREAM * init_vgmstream_txth(STREAMFILE *streamFile) { case PCM4_U: coding = coding_PCM4_U; break; case OKI16: coding = coding_OKI16; break; case TGC: coding = coding_TGC; break; + case ASF: coding = coding_ASF; break; default: goto fail; } @@ -334,6 +336,11 @@ VGMSTREAM * init_vgmstream_txth(STREAMFILE *streamFile) { vgmstream->layout_type = layout_none; break; + case coding_ASF: + vgmstream->layout_type = layout_interleave; + vgmstream->interleave_block_size = 0x11; + break; + case coding_MS_IMA: if (!txth.interleave) goto fail; /* creates garbage */ @@ -450,7 +457,7 @@ VGMSTREAM * init_vgmstream_txth(STREAMFILE *streamFile) { } else { /* fake header FFmpeg */ - uint8_t buf[200]; + uint8_t buf[0x100]; int32_t bytes; if (txth.codec == ATRAC3) { @@ -465,14 +472,14 @@ VGMSTREAM * init_vgmstream_txth(STREAMFILE *streamFile) { else if (txth.codec == ATRAC3PLUS) { int block_size = txth.interleave; - bytes = ffmpeg_make_riff_atrac3plus(buf, 200, vgmstream->num_samples, txth.data_size, vgmstream->channels, vgmstream->sample_rate, block_size, txth.skip_samples); + bytes = ffmpeg_make_riff_atrac3plus(buf, sizeof(buf), vgmstream->num_samples, txth.data_size, vgmstream->channels, vgmstream->sample_rate, block_size, txth.skip_samples); ffmpeg_data = init_ffmpeg_header_offset(txth.streamBody, buf,bytes, txth.start_offset,txth.data_size); if ( !ffmpeg_data ) goto fail; } else if (txth.codec == XMA1) { int xma_stream_mode = txth.codec_mode == 1 ? 1 : 0; - bytes = ffmpeg_make_riff_xma1(buf, 100, vgmstream->num_samples, txth.data_size, vgmstream->channels, vgmstream->sample_rate, xma_stream_mode); + bytes = ffmpeg_make_riff_xma1(buf, sizeof(buf), vgmstream->num_samples, txth.data_size, vgmstream->channels, vgmstream->sample_rate, xma_stream_mode); ffmpeg_data = init_ffmpeg_header_offset(txth.streamBody, buf,bytes, txth.start_offset,txth.data_size); if ( !ffmpeg_data ) goto fail; } @@ -482,7 +489,7 @@ VGMSTREAM * init_vgmstream_txth(STREAMFILE *streamFile) { block_size = txth.interleave ? txth.interleave : 2048; block_count = txth.data_size / block_size; - bytes = ffmpeg_make_riff_xma2(buf, 200, vgmstream->num_samples, txth.data_size, vgmstream->channels, vgmstream->sample_rate, block_count, block_size); + bytes = ffmpeg_make_riff_xma2(buf, sizeof(buf), vgmstream->num_samples, txth.data_size, vgmstream->channels, vgmstream->sample_rate, block_count, block_size); ffmpeg_data = init_ffmpeg_header_offset(txth.streamBody, buf,bytes, txth.start_offset,txth.data_size); if ( !ffmpeg_data ) goto fail; } @@ -848,6 +855,7 @@ static int parse_keyval(STREAMFILE * streamFile_, txth_header * txth, const char else if (is_string(val,"AAC")) txth->codec = AAC; else if (is_string(val,"TGC")) txth->codec = TGC; else if (is_string(val,"GCOM_ADPCM")) txth->codec = TGC; + else if (is_string(val,"ASF")) txth->codec = ASF; else goto fail; /* set common interleaves to simplify usage @@ -1063,9 +1071,10 @@ static int parse_keyval(STREAMFILE * streamFile_, txth_header * txth, const char /* COEFS */ else if (is_string(key,"coef_offset")) { if (!parse_num(txth->streamHead,txth,val, &txth->coef_offset)) goto fail; - /* special adjustment */ + /* special adjustments */ + txth->coef_offset += txth->base_offset; if (txth->subsong_offset) - txth->coef_offset = txth->base_offset + txth->coef_offset + txth->subsong_offset * (txth->target_subsong - 1); + txth->coef_offset += txth->subsong_offset * (txth->target_subsong - 1); } else if (is_string(key,"coef_spacing")) { if (!parse_num(txth->streamHead,txth,val, &txth->coef_spacing)) goto fail; @@ -1090,8 +1099,9 @@ static int parse_keyval(STREAMFILE * streamFile_, txth_header * txth, const char if (!parse_num(txth->streamHead,txth,val, &txth->hist_offset)) goto fail; txth->hist_set = 1; /* special adjustment */ + txth->hist_offset += txth->hist_offset; if (txth->subsong_offset) - txth->hist_offset = txth->base_offset + txth->hist_offset + txth->subsong_offset * (txth->target_subsong - 1); + txth->hist_offset += txth->subsong_offset * (txth->target_subsong - 1); } else if (is_string(key,"hist_spacing")) { if (!parse_num(txth->streamHead,txth,val, &txth->hist_spacing)) goto fail; @@ -1115,8 +1125,9 @@ static int parse_keyval(STREAMFILE * streamFile_, txth_header * txth, const char if (!parse_num(txth->streamHead,txth,val, &txth->name_offset)) goto fail; txth->name_offset_set = 1; /* special adjustment */ + txth->name_offset += txth->base_offset; if (txth->subsong_offset) - txth->name_offset = txth->base_offset + txth->name_offset + txth->subsong_offset * (txth->target_subsong - 1); + txth->name_offset += txth->subsong_offset * (txth->target_subsong - 1); } else if (is_string(key,"name_size")) { if (!parse_num(txth->streamHead,txth,val, &txth->name_size)) goto fail; @@ -1314,6 +1325,8 @@ static uint16_t get_string_wchar(const char * val, int pos, int *csize) { if (wchar >= 0x41 && wchar <= 0x5a) wchar += 0x20; + if (wchar == '\\') + wchar = '/'; /* normalize paths */ } return wchar; @@ -1408,11 +1421,12 @@ fail: static int parse_name_table(txth_header * txth, char * name_list) { STREAMFILE *nameFile = NULL; off_t txt_offset, file_size; + char fullname[PATH_LIMIT]; char filename[PATH_LIMIT]; char basename[PATH_LIMIT]; /* just in case */ - if (txth->streamfile_is_txth || !txth->streamText || !txth->streamFile) + if (!txth->streamText || !txth->streamBody) goto fail; /* trim name_list just in case */ @@ -1426,15 +1440,16 @@ static int parse_name_table(txth_header * txth, char * name_list) { } } - //;VGM_LOG("TXTH: name_list2='%s'\n", name_list); + //;VGM_LOG("TXTH: name_list='%s'\n", name_list); /* open companion file near .txth */ nameFile = open_streamfile_by_filename(txth->streamText, name_list); if (!nameFile) goto fail; - get_streamfile_filename(txth->streamFile, filename, sizeof(filename)); - get_streamfile_basename(txth->streamFile, basename, sizeof(basename)); - //;VGM_LOG("TXTH: filename=%s, basename=%s\n", filename, basename); + get_streamfile_name(txth->streamBody, fullname, sizeof(filename)); + get_streamfile_filename(txth->streamBody, filename, sizeof(filename)); + get_streamfile_basename(txth->streamBody, basename, sizeof(basename)); + //;VGM_LOG("TXTH: names full=%s, file=%s, base=%s\n", fullname, filename, basename); txt_offset = 0x00; file_size = get_streamfile_size(nameFile); @@ -1477,7 +1492,10 @@ static int parse_name_table(txth_header * txth, char * name_list) { //;VGM_LOG("TXTH: compare name '%s'\n", key); /* parse values if key (name) matches default ("") or filename with/without extension */ - if (key[0]=='\0' || is_string_match(filename, key) || is_string_match(basename, key)) { + if (key[0]=='\0' + || is_string_match(filename, key) + || is_string_match(basename, key) + || is_string_match(fullname, key)) { int n; char subval[TXT_LINE_MAX]; const char *current = val; @@ -1615,7 +1633,8 @@ static int parse_num(STREAMFILE * streamFile, txth_header * txth, const char * v else if ((n = is_string_field(val,"subsong_count"))) value = txth->subsong_count; else if ((n = is_string_field(val,"subsong_offset"))) value = txth->subsong_offset; else if ((n = is_string_field(val,"subfile_offset"))) value = txth->subfile_offset; - else if ((n = is_string_field(val,"subfile_size"))) value = txth->subfile_size; + else if ((n = is_string_field(val,"subfile_size"))) value = txth->subfile_size; + else if ((n = is_string_field(val,"base_offset"))) value = txth->base_offset; //todo whatever, improve else if ((n = is_string_field(val,"name_value"))) value = txth->name_values[0]; else if ((n = is_string_field(val,"name_value1"))) value = txth->name_values[0]; @@ -1719,6 +1738,8 @@ static int get_bytes_to_samples(txth_header * txth, uint32_t bytes) { #endif case AC3: return ac3_bytes_to_samples(bytes, txth->interleave, txth->channels); + case ASF: + return asf_bytes_to_samples(bytes, txth->channels); /* XMA bytes-to-samples is done at the end as the value meanings are a bit different */ case XMA1: diff --git a/Frameworks/vgmstream/vgmstream/src/meta/ubi_ckd.c b/Frameworks/vgmstream/vgmstream/src/meta/ubi_ckd.c index b876e2087..17776a564 100644 --- a/Frameworks/vgmstream/vgmstream/src/meta/ubi_ckd.c +++ b/Frameworks/vgmstream/vgmstream/src/meta/ubi_ckd.c @@ -2,39 +2,107 @@ #include "../coding/coding.h" -/* CKD RIFF - Ubisoft audio [Rayman Origins (Wii)] */ -VGMSTREAM * init_vgmstream_ubi_ckd(STREAMFILE *streamFile) { - VGMSTREAM * vgmstream = NULL; - off_t start_offset, first_offset = 0xc, chunk_offset; +typedef enum { MSADPCM, DSP, MP3, XMA2 } ckd_codec; + +/* CKD RIFF - UbiArt Framework (v1) audio [Rayman Origins (Wii/X360/PS3/PC)] */ +VGMSTREAM* init_vgmstream_ubi_ckd(STREAMFILE* sf) { + VGMSTREAM* vgmstream = NULL; + off_t start_offset, first_offset = 0x0c, chunk_offset; size_t chunk_size, data_size; - int loop_flag, channel_count, interleave; + int loop_flag, channel_count, interleave = 0, format; + ckd_codec codec; + int big_endian; + uint32_t (*read_u32)(off_t,STREAMFILE*); + uint16_t (*read_u16)(off_t,STREAMFILE*); - - /* check extension, case insensitive */ - if (!check_extensions(streamFile,"ckd")) goto fail; - - /* check header */ - if (read_32bitBE(0x0,streamFile) != 0x52494646) /* RIFF */ - goto fail; - if (read_32bitBE(0x26,streamFile) != 0x6473704C) /* dspL */ + /* checks */ + /* .wav.ckd: main (other files are called .xxx.ckd too) */ + if (!check_extensions(sf,"ckd")) goto fail; + /* another slighly funny RIFF */ + if (read_u32be(0x00,sf) != 0x52494646) /* "RIFF" */ + goto fail; + if (read_u32be(0x08,sf) != 0x57415645) /* "WAVE" */ + goto fail; + /* RIFF size is normal */ + + big_endian = guess_endianness32bit(0x04, sf); + read_u32 = big_endian ? read_u32be : read_u32le; + read_u16 = big_endian ? read_u16be : read_u16le; + loop_flag = 0; - channel_count = read_16bitBE(0x16,streamFile); - - /* find data chunk, in 3 variants */ - if (find_chunk_be(streamFile, 0x64617453,first_offset,0, &chunk_offset,&chunk_size)) { /*"datS"*/ - /* normal interleave */ - start_offset = chunk_offset; - data_size = chunk_size; - interleave = 8; - } else if (find_chunk_be(streamFile, 0x6461744C,first_offset,0, &chunk_offset,&chunk_size)) { /*"datL"*/ - /* mono or full interleave (with a "datR" after the "datL", no check as we can just pretend it exists) */ - start_offset = chunk_offset; - data_size = chunk_size * channel_count; - interleave = (4+4) + chunk_size; /* don't forget to skip the "datR"+size chunk */ - } else { - goto fail; + format = read_u16(0x14,sf); + channel_count = read_u16(0x16,sf); + + switch(format) { + case 0x0002: + if (big_endian) { + if (read_u32(0x26,sf) != 0x6473704C) /* "dspL" */ + goto fail; + + /* find data chunk, in 2 variants */ + if (find_chunk_be(sf, 0x64617453,first_offset,0, &chunk_offset,&chunk_size)) { /* "datS" */ + /* normal interleave */ + start_offset = chunk_offset; + data_size = chunk_size; + interleave = 0x08; + } else if (find_chunk_be(sf, 0x6461744C,first_offset,0, &chunk_offset,&chunk_size)) { /* "datL" */ + /* mono "datL" or full interleave with a "datR" after the "datL" (no check, pretend it exists) */ + start_offset = chunk_offset; + data_size = chunk_size * channel_count; + interleave = (0x4+0x4) + chunk_size; /* don't forget to skip the "datR"+size chunk */ + } else { + goto fail; + } + + codec = DSP; + } + else { + /* PC has MS-ADPCM, same as wav's except without "fact" (recommended by MS), kinda useless + * but might as well have it here */ + if (find_chunk_le(sf, 0x64617461,first_offset,0, &chunk_offset,&chunk_size)) { /* "data" */ + start_offset = chunk_offset; + data_size = chunk_size; + } else { + goto fail; + } + + interleave = read_u16(0x20, sf); + if (!msadpcm_check_coefs(sf, 0x28)) + goto fail; + + /* there is also a "smpl" chunk with full loops too, but other codecs don't have it for the same tracks... */ + + codec = MSADPCM; + } + break; + + case 0x0055: + if (read_u32(0x26,sf) != 0x6D736620) /* "msf " */ + goto fail; + start_offset = 0x26; + data_size = read_u32(0x2A,sf); + codec = MP3; + break; + + case 0x0166: + if (read_u32(0x48,sf) != 0x7365656B && /* "seek */ + read_u32(0x48,sf) != 0x7365656B) /* "data" */ + goto fail; + + if (find_chunk_be(sf, 0x64617461,first_offset,0, &chunk_offset,&chunk_size)) { /* "data" */ + start_offset = chunk_offset; + data_size = chunk_size; + } else { + goto fail; + } + + codec = XMA2; + break; + + default: + goto fail; } @@ -42,18 +110,59 @@ VGMSTREAM * init_vgmstream_ubi_ckd(STREAMFILE *streamFile) { vgmstream = allocate_vgmstream(channel_count,loop_flag); if (!vgmstream) goto fail; - vgmstream->sample_rate = read_32bitBE(0x18,streamFile); + vgmstream->sample_rate = read_u32(0x18,sf); vgmstream->num_samples = dsp_bytes_to_samples(data_size, channel_count); vgmstream->coding_type = coding_NGC_DSP; - vgmstream->layout_type = channel_count==1 ? layout_none : layout_interleave; - vgmstream->interleave_block_size = interleave; vgmstream->meta_type = meta_UBI_CKD; - dsp_read_coefs_be(vgmstream,streamFile, 0x4A, (4+4)+0x60); + switch(codec) { + case MSADPCM: + vgmstream->coding_type = coding_MSADPCM; + vgmstream->layout_type = layout_none; + vgmstream->frame_size = interleave; + break; + case DSP: + vgmstream->layout_type = layout_interleave; + vgmstream->interleave_block_size = interleave; + dsp_read_coefs_be(vgmstream,sf, 0x4A, (4+4)+0x60); + break; - if (!vgmstream_open_stream(vgmstream,streamFile,start_offset)) +#ifdef VGM_USE_MPEG + case MP3: { + vgmstream->codec_data = init_mpeg(sf, start_offset, &vgmstream->coding_type, vgmstream->channels); + if (!vgmstream->codec_data) goto fail; + vgmstream->layout_type = layout_none; + + vgmstream->num_samples = mpeg_bytes_to_samples(data_size, vgmstream->codec_data); + break; + } +#endif + +#ifdef VGM_USE_FFMPEG + case XMA2: { + uint8_t buf[0x100]; + int bytes; + + bytes = ffmpeg_make_riff_xma_from_fmt_chunk(buf, sizeof(buf), 0x14, 0x34, data_size, sf, 1); + vgmstream->codec_data = init_ffmpeg_header_offset(sf, buf,bytes, start_offset,data_size); + if (!vgmstream->codec_data) goto fail; + vgmstream->coding_type = coding_FFmpeg; + vgmstream->layout_type = layout_none; + + vgmstream->num_samples = read_u32(0x14+0x18,sf); + + xma_fix_raw_samples(vgmstream, sf, start_offset,data_size, 0, 0,0); /* should apply to num_samples? */ + break; + } +#endif + + default: + goto fail; + } + + if (!vgmstream_open_stream(vgmstream,sf,start_offset)) goto fail; return vgmstream; diff --git a/Frameworks/vgmstream/vgmstream/src/meta/ubi_lyn.c b/Frameworks/vgmstream/vgmstream/src/meta/ubi_lyn.c index f63116ad6..4e8200b84 100644 --- a/Frameworks/vgmstream/vgmstream/src/meta/ubi_lyn.c +++ b/Frameworks/vgmstream/vgmstream/src/meta/ubi_lyn.c @@ -1,9 +1,8 @@ #include "meta.h" #include "../layout/layout.h" #include "../coding/coding.h" -#include "ubi_lyn_ogg_streamfile.h" +#include "ubi_lyn_streamfile.h" -static STREAMFILE* setup_lyn_streamfile(STREAMFILE *streamFile, off_t subfile_offset, size_t subfile_size); /* LyN RIFF - from Ubisoft LyN engine games [Red Steel 2 (Wii), Adventures of Tintin (Multi), From Dust (Multi), Just Dance 3/4 (multi)] */ VGMSTREAM * init_vgmstream_ubi_lyn(STREAMFILE *streamFile) { @@ -111,7 +110,7 @@ VGMSTREAM * init_vgmstream_ubi_lyn(STREAMFILE *streamFile) { #ifdef VGM_USE_VORBIS case 0x3157: { /* Ogg (PC), interleaved 1ch */ - size_t interleave_size, stride_size; + size_t interleave_size; layered_layout_data* data = NULL; int i; @@ -119,7 +118,6 @@ VGMSTREAM * init_vgmstream_ubi_lyn(STREAMFILE *streamFile) { goto fail; interleave_size = read_32bitLE(start_offset+0x04,streamFile); - stride_size = interleave_size * channel_count; /* interleave is adjusted so there is no smaller last block, it seems */ vgmstream->coding_type = coding_OGG_VORBIS; @@ -132,15 +130,15 @@ VGMSTREAM * init_vgmstream_ubi_lyn(STREAMFILE *streamFile) { /* open each layer subfile */ for (i = 0; i < channel_count; i++) { - STREAMFILE* temp_streamFile = NULL; - size_t total_size = read_32bitLE(start_offset+0x08 + 0x04*i,streamFile); - off_t layer_offset = start_offset+0x08 + 0x04*channel_count + interleave_size*i; + STREAMFILE* temp_sf = NULL; + size_t logical_size = read_32bitLE(start_offset+0x08 + 0x04*i,streamFile); + off_t layer_offset = start_offset + 0x08 + 0x04*channel_count; //+ interleave_size*i; - temp_streamFile = setup_lyn_ogg_streamfile(streamFile, layer_offset, interleave_size, stride_size, total_size); - if (!temp_streamFile) goto fail; + temp_sf = setup_ubi_lyn_streamfile(streamFile, layer_offset, interleave_size, i, channel_count, logical_size); + if (!temp_sf) goto fail; - data->layers[i] = init_vgmstream_ogg_vorbis(temp_streamFile); - close_streamfile(temp_streamFile); + data->layers[i] = init_vgmstream_ogg_vorbis(temp_sf); + close_streamfile(temp_sf); if (!data->layers[i]) goto fail; /* could validate between layers, meh */ @@ -193,10 +191,8 @@ VGMSTREAM * init_vgmstream_ubi_lyn(STREAMFILE *streamFile) { off_t chunk_offset; size_t chunk_size, seek_size; - if (read_32bitLE(start_offset+0x00,streamFile) != 3) /* id? */ - goto fail; - /* skip standard XMA header + seek table */ + /* 0x00: version? no apparent differences (0x1=Just Dance 4, 0x3=others) */ chunk_offset = start_offset + 0x04 + 0x04; chunk_size = read_32bitLE(start_offset + 0x04, streamFile); seek_size = read_32bitLE(chunk_offset+chunk_size, streamFile); @@ -231,7 +227,7 @@ fail: /* LyN RIFF in containers */ VGMSTREAM * init_vgmstream_ubi_lyn_container(STREAMFILE *streamFile) { VGMSTREAM *vgmstream = NULL; - STREAMFILE *temp_streamFile = NULL; + STREAMFILE *temp_sf = NULL; off_t subfile_offset; size_t subfile_size; @@ -261,35 +257,16 @@ VGMSTREAM * init_vgmstream_ubi_lyn_container(STREAMFILE *streamFile) { subfile_size = read_32bitLE(subfile_offset+0x04,streamFile) + 0x04+0x04; - temp_streamFile = setup_lyn_streamfile(streamFile, subfile_offset,subfile_size); - if (!temp_streamFile) goto fail; + temp_sf = setup_subfile_streamfile(streamFile, subfile_offset, subfile_size, NULL); + if (!temp_sf) goto fail; - vgmstream = init_vgmstream_ubi_lyn(temp_streamFile); + vgmstream = init_vgmstream_ubi_lyn(temp_sf); - close_streamfile(temp_streamFile); + close_streamfile(temp_sf); return vgmstream; fail: - close_streamfile(temp_streamFile); + close_streamfile(temp_sf); close_vgmstream(vgmstream); return NULL; } - -static STREAMFILE* setup_lyn_streamfile(STREAMFILE *streamFile, off_t subfile_offset, size_t subfile_size) { - STREAMFILE *temp_streamFile = NULL, *new_streamFile = NULL; - - /* setup subfile */ - new_streamFile = open_wrap_streamfile(streamFile); - if (!new_streamFile) goto fail; - temp_streamFile = new_streamFile; - - new_streamFile = open_clamp_streamfile(temp_streamFile, subfile_offset,subfile_size); - if (!new_streamFile) goto fail; - temp_streamFile = new_streamFile; - - return temp_streamFile; - -fail: - close_streamfile(temp_streamFile); - return NULL; -} diff --git a/Frameworks/vgmstream/vgmstream/src/meta/ubi_lyn_ogg_streamfile.h b/Frameworks/vgmstream/vgmstream/src/meta/ubi_lyn_ogg_streamfile.h deleted file mode 100644 index 364718d34..000000000 --- a/Frameworks/vgmstream/vgmstream/src/meta/ubi_lyn_ogg_streamfile.h +++ /dev/null @@ -1,92 +0,0 @@ -#ifndef _LYN_OGG_STREAMFILE_H_ -#define _LYN_OGG_STREAMFILE_H_ -#include "../streamfile.h" - - -typedef struct { - off_t start_physical_offset; /* interleaved data start, for this substream */ - size_t interleave_block_size; /* max size that can be read before encountering other substreams */ - size_t stride_size; /* step size between interleave blocks (interleave*channels) */ - size_t total_size; /* final size of the deinterleaved substream */ -} lyn_ogg_io_data; - - -/* Handles deinterleaving of complete files, skipping portions or other substreams. */ -static size_t lyn_ogg_io_read(STREAMFILE *streamfile, uint8_t *dest, off_t offset, size_t length, lyn_ogg_io_data* data) { - size_t total_read = 0; - - while (length > 0) { - size_t to_read; - size_t length_available; - off_t block_num; - off_t intrablock_offset; - off_t physical_offset; - - block_num = offset / data->interleave_block_size; - intrablock_offset = offset % data->interleave_block_size; - physical_offset = data->start_physical_offset + block_num*data->stride_size + intrablock_offset; - length_available = data->interleave_block_size - intrablock_offset; - - if (length < length_available) { - to_read = length; - } - else { - to_read = length_available; - } - - if (to_read > 0) { - size_t bytes_read; - - bytes_read = read_streamfile(dest, physical_offset, to_read, streamfile); - total_read += bytes_read; - - if (bytes_read != to_read) { - return total_read; - } - - dest += bytes_read; - offset += bytes_read; - length -= bytes_read; - } - } - - return total_read; -} - -static size_t lyn_ogg_io_size(STREAMFILE *streamfile, lyn_ogg_io_data* data) { - return data->total_size; -} - - -static STREAMFILE* setup_lyn_ogg_streamfile(STREAMFILE *streamFile, off_t start_offset, size_t interleave_block_size, size_t stride_size, size_t total_size) { - STREAMFILE *temp_streamFile = NULL, *new_streamFile = NULL; - lyn_ogg_io_data io_data = {0}; - size_t io_data_size = sizeof(lyn_ogg_io_data); - - io_data.start_physical_offset = start_offset; - io_data.interleave_block_size = interleave_block_size; - io_data.stride_size = stride_size; - io_data.total_size = total_size; - - - /* setup subfile */ - new_streamFile = open_wrap_streamfile(streamFile); - if (!new_streamFile) goto fail; - temp_streamFile = new_streamFile; - - new_streamFile = open_io_streamfile(temp_streamFile, &io_data,io_data_size, lyn_ogg_io_read,lyn_ogg_io_size); - if (!new_streamFile) goto fail; - temp_streamFile = new_streamFile; - - new_streamFile = open_fakename_streamfile(temp_streamFile, NULL,"ogg"); - if (!new_streamFile) goto fail; - temp_streamFile = new_streamFile; - - return temp_streamFile; - -fail: - close_streamfile(temp_streamFile); - return NULL; -} - -#endif /* _LYN_OGG_STREAMFILE_H_ */ diff --git a/Frameworks/vgmstream/vgmstream/src/meta/ubi_lyn_streamfile.h b/Frameworks/vgmstream/vgmstream/src/meta/ubi_lyn_streamfile.h new file mode 100644 index 000000000..ecef0f6d9 --- /dev/null +++ b/Frameworks/vgmstream/vgmstream/src/meta/ubi_lyn_streamfile.h @@ -0,0 +1,23 @@ +#ifndef _UBI_LYN_STREAMFILE_H_ +#define _UBI_LYN_STREAMFILE_H_ +#include "deblock_streamfile.h" + +/* Deinterleaves LYN streams */ +static STREAMFILE* setup_ubi_lyn_streamfile(STREAMFILE* sf, off_t stream_offset, size_t interleave_size, int stream_number, int stream_count, size_t logical_size) { + STREAMFILE *new_sf = NULL; + deblock_config_t cfg = {0}; +VGM_LOG("so=%lx, chu=%x, n=%i, c=%i, lo=%x\n", stream_offset, interleave_size, stream_number, stream_count, logical_size); + cfg.stream_start = stream_offset; + cfg.chunk_size = interleave_size; + cfg.step_start = stream_number; + cfg.step_count = stream_count; + cfg.logical_size = logical_size; + + new_sf = open_wrap_streamfile(sf); + new_sf = open_io_deblock_streamfile_f(new_sf, &cfg); + //new_sf = open_buffer_streamfile_f(new_sf, 0); + new_sf = open_fakename_streamfile_f(new_sf, NULL, "ogg"); + return new_sf; +} + +#endif /* _UBI_LYN_STREAMFILE_H_ */ diff --git a/Frameworks/vgmstream/vgmstream/src/meta/ubi_sb.c b/Frameworks/vgmstream/vgmstream/src/meta/ubi_sb.c index 5b3b66b0d..396dc3827 100644 --- a/Frameworks/vgmstream/vgmstream/src/meta/ubi_sb.c +++ b/Frameworks/vgmstream/vgmstream/src/meta/ubi_sb.c @@ -7,7 +7,7 @@ #define SB_MAX_LAYER_COUNT 16 /* arbitrary max */ #define SB_MAX_CHAIN_COUNT 256 /* +150 exist in Tonic Trouble */ -typedef enum { UBI_IMA, UBI_ADPCM, RAW_PCM, RAW_PSX, RAW_DSP, RAW_XBOX, FMT_VAG, FMT_AT3, RAW_AT3, FMT_XMA1, RAW_XMA1, FMT_OGG, FMT_CWAV, FMT_APM, FMT_MPDX } ubi_sb_codec; +typedef enum { UBI_IMA, UBI_ADPCM, RAW_PCM, RAW_PSX, RAW_DSP, RAW_XBOX, FMT_VAG, FMT_AT3, RAW_AT3, FMT_XMA1, RAW_XMA1, FMT_OGG, FMT_CWAV, FMT_APM, FMT_MPDX, UBI_IMA_SCE } ubi_sb_codec; typedef enum { UBI_PC, UBI_PS2, UBI_XBOX, UBI_GC, UBI_X360, UBI_PSP, UBI_PS3, UBI_WII, UBI_3DS } ubi_sb_platform; typedef enum { UBI_NONE = 0, UBI_AUDIO, UBI_LAYER, UBI_SEQUENCE, UBI_SILENCE } ubi_sb_type; @@ -496,6 +496,16 @@ static VGMSTREAM * init_vgmstream_ubi_sb_base(ubi_sb_header *sb, STREAMFILE *str vgmstream->layout_type = layout_none; break; + case UBI_IMA_SCE: + vgmstream->coding_type = coding_UBI_IMA; + vgmstream->layout_type = layout_blocked_ubi_sce; + vgmstream->full_block_size = read_32bitLE(0x18, streamData); + + /* this "codec" is an ugly hack of IMA w/ Ubi ADPCM's frame format, surely to + * shoehorn a simpler codec into the existing code when porting the game */ + start_offset += 0x08 + 0x30; /* skip Ubi ADPCM header */ + break; + case UBI_ADPCM: /* custom Ubi 4/6-bit ADPCM used in early games: * - Splinter Cell (PC): 4-bit w/ 2ch (music), 6-bit w/ 1ch (sfx) @@ -1553,10 +1563,9 @@ static int parse_stream_codec(ubi_sb_header * sb) { case UBI_PS3: sb->codec = RAW_PSX; /* PS3 */ break; - case UBI_PSP: - /* TODO: IMA using Ubisoft ADPCM frame layout [Splinter Cell: Essentials (PSP)] */ - VGM_LOG("UBI SB: Unimplemented custom IMA codec.\n"); - goto fail; + case UBI_PSP: /* Splinter Cell: Essentials (PSP) */ + sb->codec = UBI_IMA_SCE; + break; default: sb->codec = UBI_ADPCM; break; @@ -2704,6 +2713,19 @@ static int config_sb_version(ubi_sb_header * sb, STREAMFILE *streamFile) { return 1; } + /* Tom Clancy's Ghost Recon Advanced Warfighter (2006)(Xbox)-bank */ + if (sb->version == 0x00130004 && sb->platform == UBI_XBOX) { + config_sb_entry(sb, 0x48, 0x50); + + config_sb_audio_fb(sb, 0x1c, (1 << 3), (1 << 4), (1 << 10)); + config_sb_audio_he(sb, 0x3c, 0x34, 0x20, 0x28, 0x44, 0x40); + + /* what */ + sb->cfg.audio_extra_offset = 0x10; + sb->cfg.audio_stream_offset = 0x14; + return 1; + } + /* Prince of Persia: The Two Thrones (2005)(PC)-bank */ if (sb->version == 0x00150000 && sb->platform == UBI_PC) { config_sb_entry(sb, 0x68, 0x78); @@ -2903,8 +2925,12 @@ static int config_sb_version(ubi_sb_header * sb, STREAMFILE *streamFile) { return 1; } - /* Red Steel (2006)(Wii)-bank */ - if (sb->version == 0x00180006 && sb->platform == UBI_WII) { + /* Red Steel (2006)(Wii)-bank 0x00180006 */ + /* Splinter Cell: Double Agent (2006)(Wii)-map 0x00180007 */ + /* Open Season (2006)(Wii)-map 0x00180008 */ + if ((sb->version == 0x00180006 && sb->platform == UBI_WII) || + (sb->version == 0x00180007 && sb->platform == UBI_WII) || + (sb->version == 0x00180008 && sb->platform == UBI_WII)) { config_sb_entry(sb, 0x68, 0x6c); config_sb_audio_fs(sb, 0x28, 0x2c, 0x30); @@ -2969,12 +2995,14 @@ static int config_sb_version(ubi_sb_header * sb, STREAMFILE *streamFile) { /* My Word Coach (2007)(Wii)-bank 0x00190002 */ /* Prince of Persia: Rival Swords (2007)(Wii)-bank 0x00190003 */ /* Rainbow Six Vegas (2007)(PS3)-bank 0x00190005 */ + /* Surf's Up (2007)(Wii)-bank 0x00190005 */ /* Surf's Up (2007)(PS3)-bank 0x00190005 */ /* Surf's Up (2007)(X360)-bank 0x00190005 */ /* Splinter Cell: Double Agent (2007)(PS3)-map 0x00190005 */ if ((sb->version == 0x00190002 && sb->platform == UBI_X360) || (sb->version == 0x00190002 && sb->platform == UBI_WII) || (sb->version == 0x00190003 && sb->platform == UBI_WII) || + (sb->version == 0x00190005 && sb->platform == UBI_WII) || (sb->version == 0x00190005 && sb->platform == UBI_PS3) || (sb->version == 0x00190005 && sb->platform == UBI_X360)) { config_sb_entry(sb, 0x68, 0x70); diff --git a/Frameworks/vgmstream/vgmstream/src/meta/vid1.c b/Frameworks/vgmstream/vgmstream/src/meta/vid1.c new file mode 100644 index 000000000..fedeb81a0 --- /dev/null +++ b/Frameworks/vgmstream/vgmstream/src/meta/vid1.c @@ -0,0 +1,135 @@ +#include "meta.h" +#include "../coding/coding.h" +#include "../layout/layout.h" + + +/* VID1 - Factor 5/DivX format GC/Xbox games [Gun (GC), Tony Hawk's American Wasteland (GC), Enter The Matrix (Xbox)]*/ +VGMSTREAM * init_vgmstream_ngc_vid1(STREAMFILE* sf) { + VGMSTREAM * vgmstream = NULL; + off_t start_offset, header_offset; + int loop_flag = 0, channels, sample_rate; + uint32_t codec; + int big_endian; + uint32_t (*read_u32)(off_t,STREAMFILE*); + + + /* checks */ + /* .vid: video + (often) audio + * .ogg: audio only [Gun (GC)], .logg: for plugins */ + if (!check_extensions(sf,"vid,ogg,logg")) + goto fail; + + /* chunked/blocked format containing video or audio frames */ + if (read_u32be(0x00, sf) == 0x56494431) { /* "VID1" BE (GC) */ + big_endian = 1; + } + else if (read_u32le(0x00,sf) == 0x56494431) { /* "VID1" LE (Xbox) */ + big_endian = 0; + } + else { + goto fail; + } + read_u32 = big_endian ? read_u32be : read_u32le; + + + /* find actual header start/size in the chunks (id + size + null) */ + { + off_t offset = read_u32(0x04, sf); + + if (read_u32(offset + 0x00, sf) != 0x48454144) /* "HEAD" */ + goto fail; + start_offset = offset + read_u32(offset + 0x04, sf); + offset += 0x0c; + + /* videos have VIDH before AUDH */ + if (read_u32(offset + 0x00, sf) == 0x56494448) { /* "VIDH" */ + offset += read_u32(offset + 0x04, sf); + } + + if (read_u32(offset, sf) != 0x41554448) /* "AUDH" */ + goto fail; + offset += 0x0c; + + header_offset = offset; + codec = read_u32(offset + 0x00, sf); + sample_rate = read_u32(offset + 0x04, sf); + channels = read_u8 (offset + 0x08, sf); + /* 0x09: flag? 0/1 */ + /* 0x0a+: varies per codec (PCM/X-IMA: nothing, DSP: coefs, Vorbis: bitrate/frame info?) + padding */ + } + + + /* build the VGMSTREAM */ + vgmstream = allocate_vgmstream(channels, loop_flag); + if (!vgmstream) goto fail; + + vgmstream->meta_type = meta_VID1; + vgmstream->sample_rate = sample_rate; + vgmstream->codec_endian = big_endian; + + switch(codec) { + case 0x50433136: /* "PC16" [Enter the Matrix (Xbox)] */ + vgmstream->coding_type = coding_PCM16_int; + vgmstream->layout_type = layout_blocked_vid1; + break; + + case 0x5841504D: /* "XAPM" [Enter the Matrix (Xbox)] */ + vgmstream->coding_type = coding_XBOX_IMA; + vgmstream->layout_type = layout_blocked_vid1; + break; + + case 0x4150434D: /* "APCM" [Enter the Matrix (GC)] */ + vgmstream->coding_type = coding_NGC_DSP; + vgmstream->layout_type = layout_blocked_vid1; + + dsp_read_coefs_be(vgmstream, sf, header_offset + 0x0a, 0x20); + break; + +#ifdef VGM_USE_VORBIS + case 0x56415544: { /* "VAUD" [Gun (GC)] */ + vorbis_custom_config cfg = {0}; + + vgmstream->num_samples = read_u32(header_offset + 0x20, sf); + + vgmstream->codec_data = init_vorbis_custom(sf, header_offset + 0x24, VORBIS_VID1, &cfg); + if (!vgmstream->codec_data) goto fail; + vgmstream->coding_type = coding_VORBIS_custom; + vgmstream->layout_type = layout_none; + break; + } +#endif + + default: + goto fail; + } + + if (!vgmstream_open_stream(vgmstream, sf, start_offset)) + goto fail; + + /* calc num_samples as playable data size varies between files/blocks */ + if (vgmstream->layout_type == layout_blocked_vid1) { + int block_samples; + + vgmstream->next_block_offset = start_offset; + do { + block_update(vgmstream->next_block_offset, vgmstream); + if (vgmstream->current_block_samples < 0) + break; + + switch(vgmstream->coding_type) { + case coding_PCM16_int: block_samples = pcm_bytes_to_samples(vgmstream->current_block_size, 1, 16); break; + case coding_XBOX_IMA: block_samples = xbox_ima_bytes_to_samples(vgmstream->current_block_size, 1); break; + case coding_NGC_DSP: block_samples = dsp_bytes_to_samples(vgmstream->current_block_size, 1); break; + default: goto fail; + } + vgmstream->num_samples += block_samples; + } + while (vgmstream->next_block_offset < get_streamfile_size(sf)); + block_update(start_offset, vgmstream); + } + + return vgmstream; +fail: + close_vgmstream(vgmstream); + return NULL; +} diff --git a/Frameworks/vgmstream/vgmstream/src/meta/vpk.c b/Frameworks/vgmstream/vgmstream/src/meta/vpk.c index 7718b0b06..ddedd1cf9 100644 --- a/Frameworks/vgmstream/vgmstream/src/meta/vpk.c +++ b/Frameworks/vgmstream/vgmstream/src/meta/vpk.c @@ -2,7 +2,7 @@ #include "../coding/coding.h" /* VPK - from SCE America second party devs [God of War (PS2), NBA 08 (PS3)] */ -VGMSTREAM * init_vgmstream_ps2_vpk(STREAMFILE *streamFile) { +VGMSTREAM * init_vgmstream_vpk(STREAMFILE *streamFile) { VGMSTREAM * vgmstream = NULL; int loop_flag, channel_count; off_t start_offset, loop_channel_offset; @@ -16,12 +16,14 @@ VGMSTREAM * init_vgmstream_ps2_vpk(STREAMFILE *streamFile) { if (read_32bitBE(0x00,streamFile) != 0x204B5056) /* " KPV" */ goto fail; - /* seems this consistently has 0x10-0x20 extra bytes, landing in garbage 0xC00000..00 frames at the end */ - channel_size = read_32bitLE(0x04,streamFile) - 0x20; /* remove for cleaner ends */ + /* files are padded with garbage/silent 0xC00000..00 frames, and channel_size sometimes + * has extra size into the padding: +0x10 (NBA08), +0x20 (GoW), or none (Sly 2, loops ok). + * Could detect and remove to slightly improve full loops, but maybe this is just how the game works */ + channel_size = read_32bitLE(0x04,streamFile); start_offset = read_32bitLE(0x08,streamFile); channel_count = read_32bitLE(0x14,streamFile); - /* 0x18+(per channel): channel config(?) */ + /* 0x18+: channel config(?), 0x04 per channel */ loop_channel_offset = read_32bitLE(0x7FC,streamFile); loop_flag = (loop_channel_offset != 0); /* found in Sly 2/3 */ diff --git a/Frameworks/vgmstream/vgmstream/src/meta/wwise.c b/Frameworks/vgmstream/vgmstream/src/meta/wwise.c index 687066105..ba55da073 100644 --- a/Frameworks/vgmstream/vgmstream/src/meta/wwise.c +++ b/Frameworks/vgmstream/vgmstream/src/meta/wwise.c @@ -213,10 +213,12 @@ VGMSTREAM * init_vgmstream_wwise(STREAMFILE *streamFile) { goto fail; } - if (ww.codec == PCM || ww.codec == IMA || ww.codec == VORBIS || ww.codec == XMA2 || ww.codec == OPUSNX) + if (ww.codec == PCM || ww.codec == IMA || ww.codec == VORBIS || ww.codec == XMA2 || ww.codec == OPUSNX || ww.codec == OPUS) { ww.truncated = 1; /* only seen those, probably all exist */ - else + } else { + VGM_LOG("WWISE: wrong size, maybe truncated\n"); goto fail; + } } @@ -605,6 +607,13 @@ VGMSTREAM * init_vgmstream_wwise(STREAMFILE *streamFile) { /* 0x1c: stream size without OggS? */ /* 0x20: full samples (without encoder delay) */ + /* OPUS is VBR so this is very approximate percent, meh */ + if (ww.truncated) { + vgmstream->num_samples = (int32_t)(vgmstream->num_samples * + (double)(ww.file_size - start_offset) / (double)ww.data_size); + ww.data_size = ww.file_size - start_offset; + } + vgmstream->codec_data = init_ffmpeg_offset(streamFile, ww.data_offset,ww.data_size); if (!vgmstream->codec_data) goto fail; vgmstream->coding_type = coding_FFmpeg; diff --git a/Frameworks/vgmstream/vgmstream/src/meta/xnb.c b/Frameworks/vgmstream/vgmstream/src/meta/xnb.c index 930cc6cf7..0b824739b 100644 --- a/Frameworks/vgmstream/vgmstream/src/meta/xnb.c +++ b/Frameworks/vgmstream/vgmstream/src/meta/xnb.c @@ -1,187 +1,246 @@ -#include "meta.h" -#include "../coding/coding.h" - -/* XNB - Microsoft XNA Game Studio 4.0 format */ -VGMSTREAM * init_vgmstream_xnb(STREAMFILE *streamFile) { - VGMSTREAM * vgmstream = NULL; - off_t start_offset, xma_chunk_offset = 0; - int loop_flag = 0, channel_count, num_samples = 0, loop_start = 0, loop_end = 0; - int big_endian, flags, codec, sample_rate, block_align, bps; - size_t data_size; - char platform; - - - /* checks */ - if (!check_extensions(streamFile,"xnb")) - goto fail; - if ((read_32bitBE(0,streamFile) & 0xFFFFFF00) != 0x584E4200) /* "XNB" */ - goto fail; - - /* XNA Studio platforms: 'w' = Windows, 'm' = Windows Phone 7, 'x' = X360 - * MonoGame extensions: 'i' = iOS, 'a' = Android, 'X' = MacOSX, 'P' = PS4, 'S' = Switch, etc */ - platform = read_8bit(0x03,streamFile); - big_endian = (platform == 'x'); - - if (read_8bit(0x04,streamFile) != 0x04 && /* XNA 3.0? found on Scare Me (XBLIG), no notable diffs */ - read_8bit(0x04,streamFile) != 0x05) /* XNA 4.0 version */ - goto fail; - - flags = read_8bit(0x05,streamFile); - //if (flags & 0x01) goto fail; /* "HiDef profile" content (no actual difference) */ - if (flags & 0x80) goto fail; /* compressed with LZX/XMemCompress (at 0x0a is decompressed size) */ - if (flags & 0x40) goto fail; /* compressed with LZ4, MonoGame extension [ex. Square Heroes (PS4)] */ - - /* full size */ - if (read_32bitLE(0x06,streamFile) != get_streamfile_size(streamFile)) - goto fail; - - - /* XNB contains "type reader" class references to parse "shared resource" data (can be any implemented filetype) */ - { - char reader_name[255+1]; - off_t current_offset = 0x0a; - size_t reader_string_len; - uint32_t fmt_chunk_size; - const char * type_sound = "Microsoft.Xna.Framework.Content.SoundEffectReader"; /* partial "fmt" chunk or XMA */ - //const char * type_song = "Microsoft.Xna.Framework.Content.SongReader"; /* just references a companion .wma */ - - /* type reader count, accept only one for now */ - if (read_8bit(current_offset++, streamFile) != 1) - goto fail; - - reader_string_len = read_8bit(current_offset++, streamFile); /* doesn't count null */ - if (reader_string_len > 255) goto fail; - - /* check SoundEffect type string */ - if (read_string(reader_name,reader_string_len+1,current_offset,streamFile) != reader_string_len) - goto fail; - if ( strcmp(reader_name, type_sound) != 0 ) - goto fail; - current_offset += reader_string_len + 1; - current_offset += 0x04; /* reader version */ - - /* shared resource count */ - if (read_8bit(current_offset++, streamFile) != 1) - goto fail; - - /* shared resource: partial "fmt" chunk */ - fmt_chunk_size = read_32bitLE(current_offset, streamFile); - current_offset += 0x04; - - { - int32_t (*read_32bit)(off_t,STREAMFILE*) = big_endian ? read_32bitBE : read_32bitLE; - int16_t (*read_16bit)(off_t,STREAMFILE*) = big_endian ? read_16bitBE : read_16bitLE; - - codec = (uint16_t)read_16bit(current_offset+0x00, streamFile); - channel_count = read_16bit(current_offset+0x02, streamFile); - sample_rate = read_32bit(current_offset+0x04, streamFile); - /* 0x08: byte rate */ - block_align = read_16bit(current_offset+0x0c, streamFile); - bps = read_16bit(current_offset+0x0e, streamFile); - - if (codec == 0x0002) { - if (!msadpcm_check_coefs(streamFile, current_offset + 0x14)) - goto fail; - } - - if (codec == 0x0166) { - xma2_parse_fmt_chunk_extra(streamFile, current_offset, &loop_flag, &num_samples, &loop_start, &loop_end, big_endian); - xma_chunk_offset = current_offset; - } - - if (codec == 0xFFFF) { - if (platform != 'S') goto fail; - sample_rate = read_32bit(current_offset+fmt_chunk_size+0x04+0x08, streamFile); - } - } - - current_offset += fmt_chunk_size; - - data_size = read_32bitLE(current_offset, streamFile); - current_offset += 0x04; - - start_offset = current_offset; - } - - - /* build the VGMSTREAM */ - vgmstream = allocate_vgmstream(channel_count,loop_flag); - if (!vgmstream) goto fail; - - vgmstream->sample_rate = sample_rate; - vgmstream->meta_type = meta_XNB; - - switch (codec) { - case 0x01: /* Dragon's Blade (Android) */ - /* null in Metagalactic Blitz (PC) */ - if (!block_align) - block_align = (bps == 8 ? 0x01 : 0x02) * channel_count; - - vgmstream->coding_type = bps == 8 ? coding_PCM8_U : coding_PCM16LE; - vgmstream->layout_type = layout_interleave; - vgmstream->interleave_block_size = block_align / channel_count; - vgmstream->num_samples = pcm_bytes_to_samples(data_size, channel_count, bps); - break; - - case 0x02: /* White Noise Online (PC) */ - if (!block_align) goto fail; - vgmstream->coding_type = coding_MSADPCM; - vgmstream->layout_type = layout_none; - vgmstream->frame_size = block_align; - vgmstream->num_samples = msadpcm_bytes_to_samples(data_size, block_align, channel_count); - break; - - case 0x11: - if (!block_align) goto fail; - vgmstream->coding_type = coding_MS_IMA; - vgmstream->layout_type = layout_none; - vgmstream->interleave_block_size = block_align; - vgmstream->num_samples = ms_ima_bytes_to_samples(data_size, block_align, channel_count); - break; - -#ifdef VGM_USE_FFMPEG - case 0x166: { /* Terraria (X360) */ - uint8_t buf[0x100]; - int32_t bytes, block_size, block_count; - - block_size = 0x10000; /* guessed */ - block_count = data_size / block_size + (data_size % block_size ? 1 : 0); - - bytes = ffmpeg_make_riff_xma2(buf,0x100, num_samples, data_size, vgmstream->channels, vgmstream->sample_rate, block_count, block_size); - vgmstream->codec_data = init_ffmpeg_header_offset(streamFile, buf,bytes, start_offset,data_size); - if (!vgmstream->codec_data) goto fail; - vgmstream->coding_type = coding_FFmpeg; - vgmstream->layout_type = layout_none; - - vgmstream->num_samples = num_samples; - vgmstream->loop_start_sample = loop_start; - vgmstream->loop_end_sample = loop_end; - - xma_fix_raw_samples(vgmstream, streamFile, start_offset,data_size, xma_chunk_offset, 1,1); - break; - } -#endif - case 0xFFFF: /* Eagle Island (Switch) */ - vgmstream->coding_type = coding_NGC_DSP; - vgmstream->layout_type = layout_interleave; - vgmstream->interleave_block_size = data_size / channel_count; - vgmstream->num_samples = read_32bitLE(start_offset + 0x00, streamFile); - //vgmstream->num_samples = dsp_bytes_to_samples(data_size - 0x60*channel_count, channel_count); - - dsp_read_coefs(vgmstream,streamFile,start_offset + 0x1c,vgmstream->interleave_block_size,big_endian); - dsp_read_hist (vgmstream,streamFile,start_offset + 0x3c,vgmstream->interleave_block_size,big_endian); - break; - - default: - VGM_LOG("XNB: unknown codec 0x%x\n", codec); - goto fail; - } - - if ( !vgmstream_open_stream(vgmstream,streamFile,start_offset) ) - goto fail; - return vgmstream; - -fail: - close_vgmstream(vgmstream); - return NULL; -} +#include "meta.h" +#include "../coding/coding.h" +#include "xnb_streamfile.h" + + +/* XNB - Microsoft XNA Game Studio 4.0 format */ +VGMSTREAM* init_vgmstream_xnb(STREAMFILE* sf) { + VGMSTREAM* vgmstream = NULL; + STREAMFILE* sf_h = NULL; + off_t start_offset, offset, xma_chunk_offset = 0; + int loop_flag = 0, channel_count, num_samples = 0, loop_start = 0, loop_end = 0; + int big_endian, flags, codec, sample_rate, block_align, bps; + size_t data_size; + char platform; + int is_ogg = 0, is_at9 = 0; + + + /* checks */ + if (!check_extensions(sf,"xnb")) + goto fail; + if ((read_32bitBE(0x00, sf) & 0xFFFFFF00) != 0x584E4200) /* "XNB" */ + goto fail; + + /* XNA Studio platforms: 'w' = Windows, 'm' = Windows Phone 7, 'x' = X360 + * MonoGame extensions: 'i' = iOS, 'a' = Android, 'X' = MacOSX, 'P' = PS4, 'S' = Switch, etc */ + platform = read_u8(0x03, sf); + big_endian = (platform == 'x'); + + if (read_u8(0x04,sf) != 0x04 && /* XNA 3.0? found on Scare Me (XBLIG), no notable diffs */ + read_u8(0x04,sf) != 0x05) /* XNA 4.0 version */ + goto fail; + + flags = read_u8(0x05, sf); + //if (flags & 0x01) goto fail; /* "HiDef profile" content (no actual difference) */ + + /* full size */ + if (read_32bitLE(0x06, sf) != get_streamfile_size(sf)) { + goto fail; + } + + /* handle XNB compression as a normal non-compressed stream, normally for graphics + * and other formats, but confused devs use it with already-compressed audio like Ogg/ATRAC9 */ + if ((flags & 0x80) || /* LZX/XMemCompress (not used with audio?) */ + (flags & 0x40)) { /* LZ4 (MonoGame extension) [Square Heroes (PS4), Little Savior (PC)] */ + size_t compression_start = 0x0e; + size_t compression_size = read_u32le(0x0a, sf); + sf_h = setup_xnb_streamfile(sf, flags, compression_start, compression_size); + if (!sf_h) goto fail; + + //dump_streamfile(sf_h, 0); + offset = 0x0e; /* refers to decompressed stream */ + } + else { + sf_h = sf; + offset = 0x0a; + } + + + /* XNB contains "type reader" class references to parse "shared resource" data (can be any implemented filetype) */ + { + char reader_name[255+1]; + size_t reader_string_len; + uint32_t fmt_chunk_size; + const char* type_sound = "Microsoft.Xna.Framework.Content.SoundEffectReader"; /* partial "fmt" chunk or XMA */ + const char* type_ogg = "SoundEffectFromOggReader"; /* has extra text info after base part */ + //const char* type_song = "Microsoft.Xna.Framework.Content.SongReader"; /* references a companion .wma */ + + /* type reader count, accept only one for now */ + if (read_u8(offset++, sf_h) != 1) + goto fail; + + reader_string_len = read_u8(offset++, sf_h); /* doesn't count null */ + if (reader_string_len > 255) goto fail; + + /* check SoundEffect type string */ + if (read_string(reader_name, reader_string_len+1, offset, sf_h) != reader_string_len) + goto fail; + if (strcmp(reader_name, type_sound) != 0) { + is_ogg = strncmp(reader_name, type_ogg, strlen(type_ogg)) == 0; + if (!is_ogg) + goto fail; + } + + offset += reader_string_len + 1; + offset += 0x04; /* reader version, 0 */ + + /* shared resource count */ + if (read_u8(offset++, sf_h) != 1) + goto fail; + + /* shared resource: partial "fmt" chunk */ + fmt_chunk_size = read_32bitLE(offset, sf_h); + offset += 0x04; + + { + int32_t (*read_32bit)(off_t,STREAMFILE*) = big_endian ? read_32bitBE : read_32bitLE; + int16_t (*read_16bit)(off_t,STREAMFILE*) = big_endian ? read_16bitBE : read_16bitLE; + + codec = (uint16_t)read_16bit(offset+0x00, sf_h); + channel_count = read_16bit(offset+0x02, sf_h); + sample_rate = read_32bit(offset+0x04, sf_h); + /* 0x08: byte rate */ + block_align = read_16bit(offset+0x0c, sf_h); + bps = read_16bit(offset+0x0e, sf_h); + + if (codec == 0x0002) { + if (!msadpcm_check_coefs(sf_h, offset + 0x14)) + goto fail; + } + + if (codec == 0x0166) { + xma2_parse_fmt_chunk_extra(sf_h, offset, &loop_flag, &num_samples, &loop_start, &loop_end, big_endian); + xma_chunk_offset = offset; + } + + if (codec == 0xFFFF) { + if (platform != 'S') goto fail; + sample_rate = read_32bit(offset+fmt_chunk_size+0x04+0x08, sf_h); + } + + /* mini-fmt has AT9 stuff then a regular RIFF [Square Heroes (PS4)] */ + if (codec == 0xFFFE) { + is_at9 = 1; + } + + /* regular (with loop tags) Ogg poses as PCM [Little Savior (PC)] */ + } + + offset += fmt_chunk_size; + + data_size = read_32bitLE(offset, sf_h); + offset += 0x04; + + start_offset = offset; + } + + /* container handling */ + if (is_ogg || is_at9) { + STREAMFILE* temp_sf = NULL; + const char* fake_ext = is_ogg ? "ogg" : "at9"; + + /* after data_size is loop start + loop length and offset? (same as loop tags), 0 if not enabled */ + + temp_sf = setup_subfile_streamfile(sf_h, start_offset, data_size, fake_ext); + if (!temp_sf) goto fail; + + if (is_ogg) { +#ifdef VGM_USE_VORBIS + vgmstream = init_vgmstream_ogg_vorbis(temp_sf); +#endif + } else { + vgmstream = init_vgmstream_riff(temp_sf); + } + close_streamfile(temp_sf); + if (!vgmstream) goto fail; + + vgmstream->meta_type = meta_XNB; + if (sf_h != sf) close_streamfile(sf_h); + return vgmstream; + } + + + /* build the VGMSTREAM */ + vgmstream = allocate_vgmstream(channel_count,loop_flag); + if (!vgmstream) goto fail; + + vgmstream->sample_rate = sample_rate; + vgmstream->meta_type = meta_XNB; + + switch (codec) { + case 0x01: /* Dragon's Blade (Android) */ + if (!block_align) /* null in Metagalactic Blitz (PC) */ + block_align = (bps == 8 ? 0x01 : 0x02) * channel_count; + + vgmstream->coding_type = bps == 8 ? coding_PCM8_U : coding_PCM16LE; + vgmstream->layout_type = layout_interleave; + vgmstream->interleave_block_size = block_align / channel_count; + vgmstream->num_samples = pcm_bytes_to_samples(data_size, channel_count, bps); + break; + + case 0x02: /* White Noise Online (PC) */ + if (!block_align) goto fail; + vgmstream->coding_type = coding_MSADPCM; + vgmstream->layout_type = layout_none; + vgmstream->frame_size = block_align; + vgmstream->num_samples = msadpcm_bytes_to_samples(data_size, block_align, channel_count); + break; + + case 0x11: + if (!block_align) goto fail; + vgmstream->coding_type = coding_MS_IMA; + vgmstream->layout_type = layout_none; + vgmstream->interleave_block_size = block_align; + vgmstream->num_samples = ms_ima_bytes_to_samples(data_size, block_align, channel_count); + break; + +#ifdef VGM_USE_FFMPEG + case 0x166: { /* Terraria (X360) */ + uint8_t buf[0x100]; + int32_t bytes, block_size, block_count; + + block_size = 0x10000; /* guessed */ + block_count = data_size / block_size + (data_size % block_size ? 1 : 0); + + bytes = ffmpeg_make_riff_xma2(buf,0x100, num_samples, data_size, vgmstream->channels, vgmstream->sample_rate, block_count, block_size); + vgmstream->codec_data = init_ffmpeg_header_offset(sf_h, buf,bytes, start_offset,data_size); + if (!vgmstream->codec_data) goto fail; + vgmstream->coding_type = coding_FFmpeg; + vgmstream->layout_type = layout_none; + + vgmstream->num_samples = num_samples; + vgmstream->loop_start_sample = loop_start; + vgmstream->loop_end_sample = loop_end; + + xma_fix_raw_samples(vgmstream, sf_h, start_offset,data_size, xma_chunk_offset, 1,1); + break; + } +#endif + + case 0xFFFF: /* Eagle Island (Switch) */ + vgmstream->coding_type = coding_NGC_DSP; + vgmstream->layout_type = layout_interleave; + vgmstream->interleave_block_size = data_size / channel_count; + vgmstream->num_samples = read_32bitLE(start_offset + 0x00, sf_h); + //vgmstream->num_samples = dsp_bytes_to_samples(data_size - 0x60*channel_count, channel_count); + + dsp_read_coefs(vgmstream, sf_h, start_offset + 0x1c, vgmstream->interleave_block_size, big_endian); + dsp_read_hist (vgmstream, sf_h, start_offset + 0x3c, vgmstream->interleave_block_size, big_endian); + break; + + default: + VGM_LOG("XNB: unknown codec 0x%x\n", codec); + goto fail; + } + + if (!vgmstream_open_stream(vgmstream, sf_h, start_offset)) + goto fail; + + if (sf_h != sf) close_streamfile(sf_h); + return vgmstream; + +fail: + if (sf_h != sf) close_streamfile(sf_h); + close_vgmstream(vgmstream); + return NULL; +} diff --git a/Frameworks/vgmstream/vgmstream/src/meta/xnb_lz4mg.h b/Frameworks/vgmstream/vgmstream/src/meta/xnb_lz4mg.h new file mode 100644 index 000000000..f783fa593 --- /dev/null +++ b/Frameworks/vgmstream/vgmstream/src/meta/xnb_lz4mg.h @@ -0,0 +1,266 @@ +#ifndef _XNB_LZ4MG_H_ +#define _XNB_LZ4MG_H_ + +#include +#include +#include +#include + +/* Decompresses LZ4 from MonoGame. The original C lib has a lot of modes and configs, but + * MonoGame only uses the core 'block' part, which is a fairly simple LZ77 (has one command + * to copy literal and window values, with variable copy lengths). + * + * This is a basic re-implementation (not tuned for performance) for practice/test purposes, + * that handles streaming decompression as a state machine since we can run out of src or dst + * bytes anytime and LZ4 allows any copy length, with copy window as a circular buffer. Not + * sure what's the best/standard way to do it though. Info: + * - https://github.com/lz4/lz4 + * - https://github.com/MonoGame/MonoGame/blob/develop/MonoGame.Framework/Utilities/Lz4Stream/Lz4DecoderStream.cs + */ + +#define LZ4MG_OK 0 +#define LZ4MG_ERROR -1 +#define LZ4MG_WINDOW_SIZE (1 << 16) +#define LZ4MG_WINDOW_BYTES 2 +#define LZ4MG_MIN_MATCH_LEN 4 +#define LZ4MG_VARLEN_MARK 15 +#define LZ4MG_VARLEN_CONTINUE 255 + + +typedef enum { + READ_TOKEN, + READ_LITERAL, + COPY_LITERAL, + READ_OFFSET, + READ_MATCH, + SET_MATCH, + COPY_MATCH +} lz4mg_state_t; + +typedef struct { + lz4mg_state_t state; + + uint8_t token; + int literal_len; + int offset_cur; + int offset_pos; + int match_len; + int match_pos; + + int window_pos; + uint8_t window[LZ4MG_WINDOW_SIZE]; +} lz4mg_context_t; + +typedef struct { + lz4mg_context_t ctx; + + uint8_t *next_out; /* next bytes to write (reassign when avail is 0) */ + int avail_out; /* bytes available at next_out */ + int total_out; /* written bytes, for reference (set to 0 per call if needed) */ + + const uint8_t *next_in; /* next bytes to read (reassign when avail is 0) */ + int avail_in; /* bytes available at next_in */ + int total_in; /* read bytes, for reference (set to 0 per call if needed) */ +} lz4mg_stream_t; + +static void lz4mg_reset(lz4mg_stream_t* strm) { + memset(strm, 0, sizeof(lz4mg_stream_t)); +} + +/* Decompress src into dst, returning a code and number of bytes used. Caller must handle + * stop (when no more input data or all data has been decompressed) as LZ4 has no end markers. */ +static int lz4mg_decompress(lz4mg_stream_t* strm) { + lz4mg_context_t* ctx = &strm->ctx; + uint8_t* dst = strm->next_out; + const uint8_t* src = strm->next_in; + int dst_size = strm->avail_out; + int src_size = strm->avail_in; + int dst_pos = 0; + int src_pos = 0; + uint8_t next_len, next_val; + + + while (1) { + /* mostly linear state machine, but it may break anytime when reaching dst or src + * end, and resume from same state in next call */ + switch(ctx->state) { + + case READ_TOKEN: + if (src_pos >= src_size) + goto buffer_end; + ctx->token = src[src_pos++]; + + ctx->literal_len = (ctx->token >> 4) & 0xF; + if (ctx->literal_len == LZ4MG_VARLEN_MARK) + ctx->state = READ_LITERAL; + else + ctx->state = COPY_LITERAL; + break; + + case READ_LITERAL: + do { + if (src_pos >= src_size) + goto buffer_end; + next_len = src[src_pos++]; + ctx->literal_len += next_len; + } while (next_len == LZ4MG_VARLEN_CONTINUE); + + ctx->state = COPY_LITERAL; + break; + + case COPY_LITERAL: + while (ctx->literal_len > 0) { /* may be 0 */ + if (src_pos >= src_size || dst_pos >= dst_size) + goto buffer_end; + next_val = src[src_pos++]; + + dst[dst_pos++] = next_val; + + ctx->window[ctx->window_pos++] = next_val; + if (ctx->window_pos == LZ4MG_WINDOW_SIZE) + ctx->window_pos = 0; + + ctx->literal_len--; + }; + + /* LZ4 is designed to reach EOF with a literal in this state with some empty values */ + + ctx->offset_cur = 0; + ctx->offset_pos = 0; + ctx->state = READ_OFFSET; + break; + + case READ_OFFSET: + do { + if (src_pos >= src_size) + goto buffer_end; + ctx->offset_pos |= (src[src_pos++] << ctx->offset_cur*8); + ctx->offset_cur++; + } while (ctx->offset_cur < LZ4MG_WINDOW_BYTES); + + ctx->match_len = (ctx->token & 0xF); + if (ctx->match_len == LZ4MG_VARLEN_MARK) + ctx->state = READ_MATCH; + else + ctx->state = SET_MATCH; + break; + + case READ_MATCH: + do { + if (src_pos >= src_size) + goto buffer_end; + next_len = src[src_pos++]; + ctx->match_len += next_len; + } while (next_len == LZ4MG_VARLEN_CONTINUE); + + ctx->state = SET_MATCH; + break; + + case SET_MATCH: + ctx->match_len += LZ4MG_MIN_MATCH_LEN; + + ctx->match_pos = ctx->window_pos - ctx->offset_pos; + if (ctx->match_pos < 0) /* circular buffer so negative is from window end */ + ctx->match_pos = LZ4MG_WINDOW_SIZE + ctx->match_pos; + + ctx->state = COPY_MATCH; + break; + + case COPY_MATCH: + while (ctx->match_len > 0) { + if (dst_pos >= dst_size) + goto buffer_end; + + next_val = ctx->window[ctx->match_pos++]; + if (ctx->match_pos == LZ4MG_WINDOW_SIZE) + ctx->match_pos = 0; + + dst[dst_pos++] = next_val; + + ctx->window[ctx->window_pos++] = next_val; + if (ctx->window_pos == LZ4MG_WINDOW_SIZE) + ctx->window_pos = 0; + + ctx->match_len--; + }; + + ctx->state = READ_TOKEN; + break; + + default: + goto fail; + } + } + +buffer_end: + strm->next_out += dst_pos; + strm->next_in += src_pos; + strm->avail_out -= dst_pos; + strm->avail_in -= src_pos; + strm->total_out += dst_pos; + strm->total_in += src_pos; + + return LZ4MG_OK; +fail: + return LZ4MG_ERROR; +} + +#if 0 +/* non-streamed form for reference, assumes buffers are big enough */ +static void decompress_lz4mg(uint8_t* dst, size_t dst_size, const uint8_t* src, size_t src_size) { + size_t src_pos = 0; + size_t dst_pos = 0; + uint8_t token; + int literal_len, match_len, next_len; + int match_pos, match_offset; + int i; + + while (src_pos < src_size && dst_pos < dst_size) { + + token = src[src_pos++]; + if (src_pos > src_size) + break; + + /* handle literals */ + literal_len = token >> 4; + if (literal_len == 15) { + do { + next_len = src[src_pos++]; + literal_len += next_len; + if (src_pos > src_size) + break; + } while (next_len == 255); + } + + for (i = 0; i < literal_len; i++) { + dst[dst_pos++] = src[src_pos++]; + } + + /* can happen at EOF */ + if (dst_pos >= dst_size) + break; + + /* handle window matches */ + match_offset = src[src_pos++]; + match_offset |= (src[src_pos++] << 8); + + match_len = (token & 0xF); + if (match_len == 15) { + do { + next_len = src[src_pos++]; + match_len += next_len; + if (src_pos > src_size) + break; + } while (next_len == 255); + } + match_len += 4; /* min len */ + + match_pos = dst_pos - match_offset; + for(i = 0; i < match_len; i++) { + dst[dst_pos++] = dst[match_pos++]; /* note RLE with short offsets */ + } + } +} +#endif + +#endif /* _XNB_LZ4MG_H_ */ diff --git a/Frameworks/vgmstream/vgmstream/src/meta/xnb_streamfile.h b/Frameworks/vgmstream/vgmstream/src/meta/xnb_streamfile.h new file mode 100644 index 000000000..949f2716c --- /dev/null +++ b/Frameworks/vgmstream/vgmstream/src/meta/xnb_streamfile.h @@ -0,0 +1,300 @@ +#ifndef _XNB_STREAMFILE_H_ +#define _XNB_STREAMFILE_H_ + +//#define XNB_ENABLE_LZX 1 + +#ifdef XNB_ENABLE_LZX +/* lib from https://github.com/sumatrapdfreader/chmlib + * which is a cleaned-up version of https://github.com/jedwing/CHMLib */ +#include "lzx.h" + +#define LZX_XNB_WINDOW_BITS 16 +#endif + +#include "xnb_lz4mg.h" + + +#define XNB_TYPE_LZX 1 +#define XNB_TYPE_LZ4 2 + +typedef struct { + /* config */ + int type; + off_t compression_start; + size_t compression_size; + + /* state */ + off_t logical_offset; /* offset that corresponds to physical_offset */ + off_t physical_offset; /* actual file offset */ + + size_t block_size; /* current block size */ + size_t skip_size; /* size to skip from a block start to reach data start */ + size_t data_size; /* logical size of the block */ + + size_t logical_size; + + /* decompression state (dst size min for LZX) */ + uint8_t dst[0x10000]; + uint8_t src[0x10000]; + + lz4mg_stream_t lz4s; +#ifdef XNB_ENABLE_LZX + struct lzx_state* lzxs; +#endif +} xnb_io_data; + +static int xnb_io_init(STREAMFILE* sf, xnb_io_data* data) { + /* When a new IO SF is opened, the data struct is malloc'd and cloned. This works + * well enough in other cases, but b/c the decompression context works with buf ptrs + * the clone will point to the original struct bufs, so we need to force + * reset on new open so that new bufs of the clone are used. */ + data->logical_offset = -1; + +#ifdef XNB_ENABLE_LZX + if (data->type == XNB_TYPE_LZX) { + data->lzxs = lzx_init(LZX_XNB_WINDOW_BITS); + if (!data->lzxs) + return -1; + } +#endif + + return 0; +} + +static void xnb_io_close(STREAMFILE* sf, xnb_io_data* data) { +#ifdef XNB_ENABLE_LZX + if (data->type == XNB_TYPE_LZX) { + lzx_teardown(data->lzxs); + } +#endif +} + +#ifdef XNB_ENABLE_LZX +/* Decompresses LZX used in XNB. Has 16b window and headered blocks (with input size and + * optionally output size) and standard LZX inside, probably what's known as XMemCompress. + * Info: https://github.com/MonoGame/MonoGame/blob/develop/MonoGame.Framework/Utilities/LzxStream/LzxDecoderStream.cs */ +static int decompress_lzx_block(STREAMFILE* sf, xnb_io_data* data) { + int src_size, dst_size, ret; + uint8_t hi, lo; + off_t head_size; + off_t offset = data->physical_offset; + + + hi = read_u8(offset + 0x00, sf); + if (hi == 0xFF) { + hi = read_u8(offset + 0x01, sf); + lo = read_u8(offset + 0x02, sf); + dst_size = (hi << 8) | lo; + + hi = read_u8(offset + 0x03, sf); + lo = read_u8(offset + 0x04, sf); + src_size = (hi << 8) | lo; + + head_size = 0x05; + } + else { + dst_size = 0x8000; /* default */ + + lo = read_u8(offset + 0x01, sf); + src_size = (hi << 8) | lo; + + head_size = 0x02; + } + + if (src_size == 0 || dst_size == 0) { + VGM_LOG("LZX: EOF\n"); + return 1; + } + + read_streamfile(data->src, offset + head_size, src_size, sf); + + ret = lzx_decompress(data->lzxs, data->src, data->dst, src_size, dst_size); + if (ret != DECR_OK) { + VGM_LOG("LZX: decompression error %i\n", ret); + goto fail; + } + + data->data_size = dst_size; + data->block_size = head_size + src_size; + + return 1; +fail: + return 0; +} +#endif + +static int decompress_lz4_block(STREAMFILE* sf, xnb_io_data* data) { + int ret; + + if (data->lz4s.avail_in == 0) { + data->lz4s.next_in = data->src; + data->lz4s.avail_in = read_streamfile(data->src, data->physical_offset, sizeof(data->src), sf); + + /* shouldn't happen since we have decomp size */ + if (data->lz4s.avail_in <= 0) { + VGM_LOG("XNB: EOF reached\n"); + goto fail; + } + + data->block_size = data->lz4s.avail_in; /* physical data (smaller) */ + } + else { + data->block_size = 0; /* physical data doesn't move until new read */ + } + + data->lz4s.total_out = 0; + data->lz4s.avail_out = sizeof(data->dst); + data->lz4s.next_out = data->dst; + + ret = lz4mg_decompress(&data->lz4s); + + data->data_size = data->lz4s.total_out; /* logical data (bigger) */ + + if (ret != LZ4MG_OK) { + VGM_LOG("XNB: LZ4 error %i\n", ret); + goto fail; + } + + return 1; +fail: + return 0; +} + +static size_t xnb_io_read(STREAMFILE* sf, uint8_t *dest, off_t offset, size_t length, xnb_io_data* data) { + size_t total_read = 0; + + /* reset */ + if (data->logical_offset < 0 || offset < data->logical_offset) { + data->physical_offset = 0x00; + data->logical_offset = 0x00; + data->block_size = 0; + data->data_size = 0; + data->skip_size = 0; + + switch(data->type) { +#ifdef XNB_ENABLE_LZX + case XNB_TYPE_LZX: lzx_reset(data->lzxs); break; +#endif + case XNB_TYPE_LZ4: lz4mg_reset(&data->lz4s); break; + default: break; + } + } + + /* read blocks, one at a time */ + while (length > 0) { + + /* ignore EOF */ + if (offset < 0 || data->logical_offset >= data->logical_size) { + break; + } + + /* process new block */ + if (data->data_size <= 0) { + + if (data->physical_offset < data->compression_start) { + /* copy data */ + int to_read = data->compression_start - data->physical_offset; + + data->data_size = read_streamfile(data->dst, data->physical_offset, to_read, sf); + data->block_size = data->data_size; + } + else { + /* decompress data */ + int ok = 0; + + switch(data->type) { +#ifdef XNB_ENABLE_LZX + case XNB_TYPE_LZX: ok = decompress_lzx_block(sf, data); break; +#endif + case XNB_TYPE_LZ4: ok = decompress_lz4_block(sf, data); break; + default: break; + } + if (!ok) { + VGM_LOG("XNB: decompression error\n"); + break; + } + } + } + + /* move to next block */ + if (data->data_size == 0 || offset >= data->logical_offset + data->data_size) { + data->physical_offset += data->block_size; + data->logical_offset += data->data_size; + data->data_size = 0; + continue; + } + + /* read/copy block data */ + { + size_t bytes_consumed, bytes_done, to_read; + + bytes_consumed = offset - data->logical_offset; + to_read = data->data_size - bytes_consumed; + if (to_read > length) + to_read = length; + memcpy(dest, data->dst + data->skip_size + bytes_consumed, to_read); + bytes_done = to_read; + + total_read += bytes_done; + dest += bytes_done; + offset += bytes_done; + length -= bytes_done; + + if (bytes_done != to_read || bytes_done == 0) { + break; /* error/EOF */ + } + } + + } + + return total_read; +} + + +static size_t xnb_io_size(STREAMFILE *streamfile, xnb_io_data* data) { + uint8_t buf[1]; + + if (data->logical_size) + return data->logical_size; + + /* force a fake read at max offset, to get max logical_offset (will be reset next read) */ + xnb_io_read(streamfile, buf, 0x7FFFFFFF, 1, data); + data->logical_size = data->logical_offset; + + return data->logical_size; +} + + +/* Decompresses XNB streams */ +static STREAMFILE* setup_xnb_streamfile(STREAMFILE* sf, int flags, off_t compression_start, size_t compression_size) { + STREAMFILE *new_sf = NULL; + xnb_io_data io_data = {0}; + + if (flags & 0x80) + io_data.type = XNB_TYPE_LZX; + else if (flags & 0x40) + io_data.type = XNB_TYPE_LZ4; + else + goto fail; + io_data.compression_start = compression_start; + io_data.compression_size = compression_size; + io_data.physical_offset = 0x00; + io_data.logical_size = compression_start + compression_size; + io_data.logical_offset = -1; /* force reset */ + +#ifndef XNB_ENABLE_LZX + /* no known audio use it (otherwise works if enabled and included lzx.c/lzx.h) */ + if (io_data.type == XNB_TYPE_LZX) + goto fail; +#endif + + /* setup subfile */ + new_sf = open_wrap_streamfile(sf); + new_sf = open_io_streamfile_ex_f(new_sf, &io_data, sizeof(xnb_io_data), xnb_io_read, xnb_io_size, xnb_io_init, xnb_io_close); + //new_sf = open_buffer_streamfile_f(new_sf, 0); /* useful? we already have a decompression buffer */ + return new_sf; +fail: + return NULL; +} + +#endif /* _XNB_STREAMFILE_H_ */ diff --git a/Frameworks/vgmstream/vgmstream/src/meta/xpcm.c b/Frameworks/vgmstream/vgmstream/src/meta/xpcm.c index 9635bdd22..74a551c72 100644 --- a/Frameworks/vgmstream/vgmstream/src/meta/xpcm.c +++ b/Frameworks/vgmstream/vgmstream/src/meta/xpcm.c @@ -1,69 +1,82 @@ -#include "meta.h" -#include "../coding/coding.h" - -/* XPCM - from Circus games [Eternal Fantasy (PC), D.C. White Season (PC)] */ -VGMSTREAM * init_vgmstream_xpcm(STREAMFILE *streamFile) { - VGMSTREAM * vgmstream = NULL; - off_t start_offset; - size_t decompressed_size; - int loop_flag, channel_count, codec, subcodec, sample_rate; - - - /* checks */ - if (!check_extensions(streamFile, "pcm")) - goto fail; - - if (read_32bitBE(0x00,streamFile) != 0x5850434D) /* "XPCM" "*/ - goto fail; - - decompressed_size = read_32bitLE(0x04,streamFile); /* (data_size for PCM) */ - codec = read_8bit(0x08, streamFile); - subcodec = read_8bit(0x09, streamFile); - /* 0x0a: always null */ - /* 0x0c: always 0x01 (PCM codec) */ - channel_count = read_16bitLE(0x0e,streamFile); - sample_rate = read_32bitLE(0x10,streamFile); - /* 0x14: average bitrate */ - /* 0x18: block size */ - /* 0x1a: output bits (16) */ - start_offset = 0x1c; /* compressed size in codec 0x01/03 */ - - loop_flag = 0; - - - /* build the VGMSTREAM */ - vgmstream = allocate_vgmstream(channel_count, loop_flag); - if (!vgmstream) goto fail; - - vgmstream->meta_type = meta_XPCM; - vgmstream->sample_rate = sample_rate; - vgmstream->num_samples = decompressed_size / sizeof(int16_t) / channel_count; - - switch(codec) { - case 0x00: - if (subcodec != 0) goto fail; - vgmstream->coding_type = coding_PCM16LE; - vgmstream->layout_type = layout_interleave; - vgmstream->interleave_block_size = 0x02; - break; - case 0x02: - if (subcodec != 0) goto fail; - vgmstream->coding_type = coding_CIRCUS_ADPCM; - vgmstream->layout_type = layout_interleave; - vgmstream->interleave_block_size = 0x01; - break; - - case 0x01: /* LZSS + VQ */ - case 0x03: /* unknown */ - default: - goto fail; - } - - if (!vgmstream_open_stream(vgmstream,streamFile,start_offset)) - goto fail; - return vgmstream; - -fail: - close_vgmstream(vgmstream); - return NULL; -} +#include "meta.h" +#include "../coding/coding.h" + +/* XPCM - from Circus games [Eternal Fantasy (PC), D.C. White Season (PC)] */ +VGMSTREAM * init_vgmstream_xpcm(STREAMFILE *streamFile) { + VGMSTREAM * vgmstream = NULL; + off_t start_offset; + size_t decompressed_size; + int loop_flag, channel_count, codec, flags, sample_rate; + + + /* checks */ + if (!check_extensions(streamFile, "pcm")) + goto fail; + + if (read_32bitBE(0x00,streamFile) != 0x5850434D) /* "XPCM" "*/ + goto fail; + + decompressed_size = read_32bitLE(0x04,streamFile); /* (data_size for PCM) */ + codec = read_8bit(0x08, streamFile); + flags = read_8bit(0x09, streamFile); + /* 0x0a: always null */ + /* 0x0c: always 0x01 (PCM codec) */ + channel_count = read_16bitLE(0x0e,streamFile); + sample_rate = read_32bitLE(0x10,streamFile); + /* 0x14: average bitrate */ + /* 0x18: block size */ + /* 0x1a: output bits (16) */ + start_offset = 0x1c; /* compressed size in codec 0x01/03 */ + + loop_flag = 0; + + + /* build the VGMSTREAM */ + vgmstream = allocate_vgmstream(channel_count, loop_flag); + if (!vgmstream) goto fail; + + vgmstream->meta_type = meta_XPCM; + vgmstream->sample_rate = sample_rate; + vgmstream->num_samples = decompressed_size / sizeof(int16_t) / channel_count; + + switch(codec) { + case 0x00: + if (flags != 0) goto fail; + vgmstream->coding_type = coding_PCM16LE; + vgmstream->layout_type = layout_interleave; + vgmstream->interleave_block_size = 0x02; + break; + + case 0x02: + if (flags != 0) goto fail; + vgmstream->coding_type = coding_CIRCUS_ADPCM; + vgmstream->layout_type = layout_interleave; + vgmstream->interleave_block_size = 0x01; + break; + + case 0x01: /* VQ + LZ (usually music) */ + case 0x03: /* VQ + deflate (usually sfx/voices) */ + vgmstream->codec_data = init_circus_vq(streamFile, 0x20, codec, flags); + if (!vgmstream->codec_data) goto fail; + vgmstream->coding_type = coding_CIRCUS_VQ; + vgmstream->layout_type = layout_none; + + /* not too sure about samples, since decompressed size isn't exact sometimes vs + * total decompression, though it's what the code uses to alloc bufs (plus + 0x2000 leeway) */ + //vgmstream->num_samples = decompressed_size / 0x2000 * 4064 / channel_count; + //if (decompressed_size % 0x2000 != 0) + // vgmstream->num_samples += (decompressed_size % 0x2000) / channel_count; + break; + + default: + goto fail; + } + + if (!vgmstream_open_stream(vgmstream,streamFile,start_offset)) + goto fail; + return vgmstream; + +fail: + close_vgmstream(vgmstream); + return NULL; +} diff --git a/Frameworks/vgmstream/vgmstream/src/meta/xwma_konami_streamfile.h b/Frameworks/vgmstream/vgmstream/src/meta/xwma_konami_streamfile.h index d95df4594..2332695cb 100644 --- a/Frameworks/vgmstream/vgmstream/src/meta/xwma_konami_streamfile.h +++ b/Frameworks/vgmstream/vgmstream/src/meta/xwma_konami_streamfile.h @@ -1,125 +1,26 @@ -#ifndef _XWMA_KONAMI_STREAMFILE_H_ -#define _XWMA_KONAMI_STREAMFILE_H_ -#include "../streamfile.h" - - -typedef struct { - /* config */ - off_t stream_offset; - size_t stream_size; - size_t block_align; - - /* state */ - off_t logical_offset; /* fake offset */ - off_t physical_offset; /* actual offset */ - size_t block_size; /* current size */ - size_t skip_size; /* size from block start to reach data */ - size_t data_size; /* usable size in a block */ - - size_t logical_size; -} xwma_konami_io_data; - - -static size_t xwma_konami_io_read(STREAMFILE *streamfile, uint8_t *dest, off_t offset, size_t length, xwma_konami_io_data* data) { - size_t total_read = 0; - - - /* re-start when previous offset (can't map logical<>physical offsets) */ - if (data->logical_offset < 0 || offset < data->logical_offset) { - data->physical_offset = data->stream_offset; - data->logical_offset = 0x00; - data->data_size = 0; - } - - /* read blocks */ - while (length > 0) { - - /* ignore EOF */ - if (offset < 0 || data->physical_offset >= data->stream_offset + data->stream_size) { - break; - } - - /* process new block */ - if (data->data_size == 0) { - data->block_size = align_size_to_block(data->block_align, 0x10); - data->data_size = data->block_align; - data->skip_size = 0x00; - } - - /* move to next block */ - if (data->data_size == 0 || offset >= data->logical_offset + data->data_size) { - data->physical_offset += data->block_size; - data->logical_offset += data->data_size; - data->data_size = 0; - continue; - } - - /* read data */ - { - size_t bytes_consumed, bytes_done, to_read; - - bytes_consumed = offset - data->logical_offset; - to_read = data->data_size - bytes_consumed; - if (to_read > length) - to_read = length; - bytes_done = read_streamfile(dest, data->physical_offset + data->skip_size + bytes_consumed, to_read, streamfile); - - total_read += bytes_done; - dest += bytes_done; - offset += bytes_done; - length -= bytes_done; - - if (bytes_done != to_read || bytes_done == 0) { - break; /* error/EOF */ - } - } - } - - return total_read; -} - -static size_t xwma_konami_io_size(STREAMFILE *streamfile, xwma_konami_io_data* data) { - uint8_t buf[1]; - - if (data->logical_size) - return data->logical_size; - - /* force a fake read at max offset, to get max logical_offset (will be reset next read) */ - xwma_konami_io_read(streamfile, buf, 0x7FFFFFFF, 1, data); - data->logical_size = data->logical_offset; - - return data->logical_size; -} - -/* Handles de-padding Konami XWMA blocked streams */ -static STREAMFILE* setup_xwma_konami_streamfile(STREAMFILE *streamFile, off_t stream_offset, size_t block_align) { - STREAMFILE *temp_streamFile = NULL, *new_streamFile = NULL; - xwma_konami_io_data io_data = {0}; - size_t io_data_size = sizeof(xwma_konami_io_data); - - io_data.stream_offset = stream_offset; - io_data.stream_size = get_streamfile_size(streamFile) - stream_offset; - io_data.block_align = block_align; - io_data.logical_offset = -1; /* force phys offset reset */ - - /* setup subfile */ - new_streamFile = open_wrap_streamfile(streamFile); - if (!new_streamFile) goto fail; - temp_streamFile = new_streamFile; - - new_streamFile = open_io_streamfile(new_streamFile, &io_data,io_data_size, xwma_konami_io_read,xwma_konami_io_size); - if (!new_streamFile) goto fail; - temp_streamFile = new_streamFile; - - new_streamFile = open_buffer_streamfile(new_streamFile,0); - if (!new_streamFile) goto fail; - temp_streamFile = new_streamFile; - - return temp_streamFile; - -fail: - close_streamfile(temp_streamFile); - return NULL; -} - -#endif /* _XWMA_KONAMI_STREAMFILE_H_ */ +#ifndef _XWMA_KONAMI_STREAMFILE_H_ +#define _XWMA_KONAMI_STREAMFILE_H_ +#include "deblock_streamfile.h" + +static void block_callback(STREAMFILE* sf, deblock_io_data* data) { + data->block_size = align_size_to_block(data->cfg.chunk_size, 0x10); + data->data_size = data->cfg.chunk_size; + data->skip_size = 0x00; +} + +/* De-pads Konami XWMA streams */ +static STREAMFILE* setup_xwma_konami_streamfile(STREAMFILE* sf, off_t stream_offset, size_t block_align) { + STREAMFILE* new_sf = NULL; + deblock_config_t cfg = {0}; + + cfg.stream_start = stream_offset; + cfg.chunk_size = block_align; + cfg.block_callback = block_callback; + + new_sf = open_wrap_streamfile(sf); + new_sf = open_io_deblock_streamfile_f(new_sf, &cfg); + //new_sf = open_buffer_streamfile_f(new_sf, 0); + return new_sf; +} + +#endif /* _XWMA_KONAMI_STREAMFILE_H_ */ diff --git a/Frameworks/vgmstream/vgmstream/src/streamfile.c b/Frameworks/vgmstream/vgmstream/src/streamfile.c index b9b90d50d..3be097199 100644 --- a/Frameworks/vgmstream/vgmstream/src/streamfile.c +++ b/Frameworks/vgmstream/vgmstream/src/streamfile.c @@ -518,8 +518,8 @@ typedef struct { size_t data_size; size_t (*read_callback)(STREAMFILE *, uint8_t *, off_t, size_t, void*); /* custom read to modify data before copying into buffer */ size_t (*size_callback)(STREAMFILE *, void*); /* size when custom reads make data smaller/bigger than underlying streamfile */ - //todo would need to make sure re-opened streamfiles work with this, maybe should use init_data_callback per call - //size_t (*close_data_callback)(STREAMFILE *, void*); /* called during close, allows to free stuff in data */ + int (*init_callback)(STREAMFILE*, void*); /* init the data struct members somehow, return >= 0 if ok */ + void (*close_callback)(STREAMFILE*, void*); /* close the data struct members somehow */ } IO_STREAMFILE; static size_t io_read(IO_STREAMFILE *streamfile, uint8_t *dst, off_t offset, size_t length) { @@ -538,24 +538,25 @@ static void io_get_name(IO_STREAMFILE *streamfile, char *buffer, size_t length) streamfile->inner_sf->get_name(streamfile->inner_sf, buffer, length); /* default */ } static STREAMFILE* io_open(IO_STREAMFILE *streamfile, const char * const filename, size_t buffersize) { - //todo should have some flag to decide if opening other files with IO STREAMFILE *new_inner_sf = streamfile->inner_sf->open(streamfile->inner_sf,filename,buffersize); - return open_io_streamfile(new_inner_sf, streamfile->data, streamfile->data_size, streamfile->read_callback, streamfile->size_callback); + return open_io_streamfile_ex(new_inner_sf, streamfile->data, streamfile->data_size, streamfile->read_callback, streamfile->size_callback, streamfile->init_callback, streamfile->close_callback); } static void io_close(IO_STREAMFILE *streamfile) { + if (streamfile->close_callback) + streamfile->close_callback(streamfile->inner_sf, streamfile->data); streamfile->inner_sf->close(streamfile->inner_sf); free(streamfile->data); free(streamfile); } -STREAMFILE* open_io_streamfile(STREAMFILE *streamfile, void *data, size_t data_size, void *read_callback, void *size_callback) { +STREAMFILE* open_io_streamfile_ex(STREAMFILE *streamfile, void *data, size_t data_size, void *read_callback, void *size_callback, void* init_callback, void* close_callback) { IO_STREAMFILE *this_sf = NULL; - if (!streamfile) return NULL; - if ((data && !data_size) || (!data && data_size)) return NULL; + if (!streamfile) goto fail; + if ((data && !data_size) || (!data && data_size)) goto fail; this_sf = calloc(1,sizeof(IO_STREAMFILE)); - if (!this_sf) return NULL; + if (!this_sf) goto fail; /* set callbacks and internals */ this_sf->sf.read = (void*)io_read; @@ -569,25 +570,42 @@ STREAMFILE* open_io_streamfile(STREAMFILE *streamfile, void *data, size_t data_s this_sf->inner_sf = streamfile; if (data) { this_sf->data = malloc(data_size); - if (!this_sf->data) { - free(this_sf); - return NULL; - } + if (!this_sf->data) goto fail; memcpy(this_sf->data, data, data_size); } this_sf->data_size = data_size; this_sf->read_callback = read_callback; this_sf->size_callback = size_callback; + this_sf->init_callback = init_callback; + this_sf->close_callback = close_callback; + + if (this_sf->init_callback) { + int ok = this_sf->init_callback(this_sf->inner_sf, this_sf->data); + if (ok < 0) goto fail; + } return &this_sf->sf; + +fail: + if (this_sf) free(this_sf->data); + free(this_sf); + return NULL; } -STREAMFILE* open_io_streamfile_f(STREAMFILE *streamfile, void *data, size_t data_size, void *read_callback, void *size_callback) { - STREAMFILE *new_sf = open_io_streamfile(streamfile, data, data_size, read_callback, size_callback); + +STREAMFILE* open_io_streamfile_ex_f(STREAMFILE *streamfile, void *data, size_t data_size, void *read_callback, void *size_callback, void* init_callback, void* close_callback) { + STREAMFILE *new_sf = open_io_streamfile_ex(streamfile, data, data_size, read_callback, size_callback, init_callback, close_callback); if (!new_sf) close_streamfile(streamfile); return new_sf; } +STREAMFILE* open_io_streamfile(STREAMFILE *streamfile, void *data, size_t data_size, void *read_callback, void *size_callback) { + return open_io_streamfile_ex(streamfile, data, data_size, read_callback, size_callback, NULL, NULL); +} +STREAMFILE* open_io_streamfile_f(STREAMFILE *streamfile, void *data, size_t data_size, void *read_callback, void *size_callback) { + return open_io_streamfile_ex_f(streamfile, data, data_size, read_callback, size_callback, NULL, NULL); +} + /* **************************************************** */ typedef struct { @@ -989,11 +1007,14 @@ fail: if (buf) buf[0] = '\0'; return 0; } -size_t read_string_utf16le(char *buf, size_t buf_size, off_t offset, STREAMFILE *sf) { + +size_t read_string_utf16(char *buf, size_t buf_size, off_t offset, STREAMFILE *sf, int big_endian) { size_t pos, offpos; + uint16_t (*read_u16)(off_t,STREAMFILE*) = big_endian ? read_u16be : read_u16le; + for (pos = 0, offpos = 0; pos < buf_size; pos++, offpos += 2) { - char c = read_u16le(offset + offpos, sf) & 0xFF; /* lower byte for now */ + char c = read_u16(offset + offpos, sf) & 0xFF; /* lower byte for now */ if (buf) buf[pos] = c; if (c == '\0') return pos; @@ -1010,6 +1031,13 @@ fail: return 0; } +size_t read_string_utf16le(char* buf, size_t buf_size, off_t offset, STREAMFILE* sf) { + return read_string_utf16(buf, buf_size, offset, sf, 0); +} +size_t read_string_utf16be(char* buf, size_t buf_size, off_t offset, STREAMFILE* sf) { + return read_string_utf16(buf, buf_size, offset, sf, 1); +} + size_t read_key_file(uint8_t *buf, size_t buf_size, STREAMFILE *sf) { diff --git a/Frameworks/vgmstream/vgmstream/src/streamfile.h b/Frameworks/vgmstream/vgmstream/src/streamfile.h index 0e184fec2..4d32231c1 100644 --- a/Frameworks/vgmstream/vgmstream/src/streamfile.h +++ b/Frameworks/vgmstream/vgmstream/src/streamfile.h @@ -109,9 +109,14 @@ STREAMFILE* open_clamp_streamfile(STREAMFILE *streamfile, off_t start, size_t si STREAMFILE* open_clamp_streamfile_f(STREAMFILE *streamfile, off_t start, size_t size); /* Opens a STREAMFILE that uses custom IO for streamfile reads. - * Can be used to modify data on the fly (ex. decryption), or even transform it from a format to another. */ + * Can be used to modify data on the fly (ex. decryption), or even transform it from a format to another. + * Data is an optional state struct of some size what will be malloc+copied on open. */ STREAMFILE* open_io_streamfile(STREAMFILE *streamfile, void *data, size_t data_size, void *read_callback, void *size_callback); STREAMFILE* open_io_streamfile_f(STREAMFILE *streamfile, void *data, size_t data_size, void *read_callback, void *size_callback); +/* Same, but calls init on SF open and close on close, when malloc/free is needed. + * Data struct may be used to hold malloc'd pointers and stuff. */ +STREAMFILE* open_io_streamfile_ex(STREAMFILE *streamfile, void *data, size_t data_size, void *read_callback, void *size_callback, void* init_callback, void* close_callback); +STREAMFILE* open_io_streamfile_ex_f(STREAMFILE *streamfile, void *data, size_t data_size, void *read_callback, void *size_callback, void* init_callback, void* close_callback); /* Opens a STREAMFILE that reports a fake name, but still re-opens itself properly. * Can be used to trick a meta's extension check (to call from another, with a modified SF). @@ -331,7 +336,9 @@ size_t read_line(char *buf, int buf_size, off_t offset, STREAMFILE *sf, int *p_l /* reads a c-string (ANSI only), up to bufsize or NULL, returning size. buf is optional (works as get_string_size). */ size_t read_string(char *buf, size_t buf_size, off_t offset, STREAMFILE *sf); /* reads a UTF16 string... but actually only as ANSI (discards the upper byte) */ -size_t read_string_utf16le(char *buf, size_t buf_size, off_t offset, STREAMFILE *sf); +size_t read_string_utf16(char* buf, size_t buf_size, off_t offset, STREAMFILE* sf, int big_endian); +size_t read_string_utf16le(char* buf, size_t buf_size, off_t offset, STREAMFILE* sf); +size_t read_string_utf16be(char* buf, size_t buf_size, off_t offset, STREAMFILE* sf); /* Opens a file containing decryption keys and copies to buffer. * Tries "(name.ext)key" (per song), "(.ext)key" (per folder) keynames. diff --git a/Frameworks/vgmstream/vgmstream/src/vgmstream.c b/Frameworks/vgmstream/vgmstream/src/vgmstream.c index 62ad41da5..455ea3478 100644 --- a/Frameworks/vgmstream/vgmstream/src/vgmstream.c +++ b/Frameworks/vgmstream/vgmstream/src/vgmstream.c @@ -58,7 +58,7 @@ VGMSTREAM * (*init_vgmstream_functions[])(STREAMFILE *streamFile) = { init_vgmstream_ngc_str, init_vgmstream_ea_schl, init_vgmstream_caf, - init_vgmstream_ps2_vpk, + init_vgmstream_vpk, init_vgmstream_genh, #ifdef VGM_USE_VORBIS init_vgmstream_ogg_vorbis, @@ -490,9 +490,12 @@ VGMSTREAM * (*init_vgmstream_functions[])(STREAMFILE *streamFile) = { init_vgmstream_tgc, init_vgmstream_kwb, init_vgmstream_lrmd, + init_vgmstream_bkhd, + init_vgmstream_bkhd_fx, /* lowest priority metas (should go after all metas, and TXTH should go before raw formats) */ init_vgmstream_txth, /* proper parsers should supersede TXTH, once added */ + init_vgmstream_encrypted, /* encrypted stuff */ init_vgmstream_raw_int, /* .int raw PCM */ init_vgmstream_ps_headerless, /* tries to detect a bunch of PS-ADPCM formats */ init_vgmstream_raw_snds, /* .snds raw SNDS IMA (*after* ps_headerless) */ @@ -661,6 +664,10 @@ void reset_vgmstream(VGMSTREAM * vgmstream) { } #endif + if (vgmstream->coding_type == coding_CIRCUS_VQ) { + reset_circus_vq(vgmstream->codec_data); + } + if (vgmstream->coding_type == coding_RELIC) { reset_relic(vgmstream->codec_data); } @@ -832,6 +839,11 @@ void close_vgmstream(VGMSTREAM * vgmstream) { } #endif + if (vgmstream->coding_type == coding_CIRCUS_VQ) { + free_circus_vq(vgmstream->codec_data); + vgmstream->codec_data = NULL; + } + if (vgmstream->coding_type == coding_RELIC) { free_relic(vgmstream->codec_data); vgmstream->codec_data = NULL; @@ -1097,6 +1109,8 @@ void render_vgmstream(sample_t * buffer, int32_t sample_count, VGMSTREAM * vgmst case layout_blocked_h4m: case layout_blocked_xa_aiff: case layout_blocked_vs_square: + case layout_blocked_vid1: + case layout_blocked_ubi_sce: render_vgmstream_blocked(buffer,sample_count,vgmstream); break; case layout_segmented: @@ -1288,6 +1302,8 @@ int get_vgmstream_samples_per_frame(VGMSTREAM * vgmstream) { return 0; /* varies per mode */ case coding_EA_MT: return 0; /* 432, but variable in looped files */ + case coding_CIRCUS_VQ: + return 0; case coding_RELIC: return 0; /* 512 */ case coding_CRI_HCA: @@ -1775,6 +1791,9 @@ void decode_vgmstream(VGMSTREAM * vgmstream, int samples_written, int samples_to samples_to_do,vgmstream->channels); break; #endif + case coding_CIRCUS_VQ: + decode_circus_vq(vgmstream->codec_data, buffer+samples_written*vgmstream->channels, samples_to_do, vgmstream->channels); + break; case coding_RELIC: decode_relic(&vgmstream->ch[0], vgmstream->codec_data, buffer+samples_written*vgmstream->channels, samples_to_do); @@ -1930,7 +1949,7 @@ void decode_vgmstream(VGMSTREAM * vgmstream, int samples_written, int samples_to case coding_UBI_IMA: for (ch = 0; ch < vgmstream->channels; ch++) { decode_ubi_ima(&vgmstream->ch[ch],buffer+samples_written*vgmstream->channels+ch, - vgmstream->channels,vgmstream->samples_into_block,samples_to_do, ch); + vgmstream->channels,vgmstream->samples_into_block,samples_to_do, ch, vgmstream->codec_config); } break; case coding_H4M_IMA: @@ -2227,6 +2246,10 @@ int vgmstream_do_loop(VGMSTREAM * vgmstream) { /* prepare certain codecs' internal state for looping */ + if (vgmstream->coding_type == coding_CIRCUS_VQ) { + seek_circus_vq(vgmstream->codec_data, vgmstream->loop_sample); + } + if (vgmstream->coding_type == coding_RELIC) { seek_relic(vgmstream->codec_data, vgmstream->loop_sample); } @@ -2426,12 +2449,12 @@ void describe_vgmstream(VGMSTREAM * vgmstream, char * desc, int length) { snprintf(temp,TEMPSIZE, "interleave: %#x bytes\n", (int32_t)vgmstream->interleave_block_size); concatn(length,desc,temp); - if (vgmstream->interleave_first_block_size) { + if (vgmstream->interleave_first_block_size && vgmstream->interleave_first_block_size != vgmstream->interleave_block_size) { snprintf(temp,TEMPSIZE, "interleave first block: %#x bytes\n", (int32_t)vgmstream->interleave_first_block_size); concatn(length,desc,temp); } - if (vgmstream->interleave_last_block_size) { + if (vgmstream->interleave_last_block_size && vgmstream->interleave_last_block_size != vgmstream->interleave_block_size) { snprintf(temp,TEMPSIZE, "interleave last block: %#x bytes\n", (int32_t)vgmstream->interleave_last_block_size); concatn(length,desc,temp); } diff --git a/Frameworks/vgmstream/vgmstream/src/vgmstream.h b/Frameworks/vgmstream/vgmstream/src/vgmstream.h index 2a24b25b7..f4dcc5039 100644 --- a/Frameworks/vgmstream/vgmstream/src/vgmstream.h +++ b/Frameworks/vgmstream/vgmstream/src/vgmstream.h @@ -190,7 +190,7 @@ typedef enum { coding_UBI_ADPCM, /* Ubisoft 4/6-bit ADPCM */ coding_EA_MT, /* Electronic Arts MicroTalk (linear-predictive speech codec) */ - + coding_CIRCUS_VQ, /* Circus VQ */ coding_RELIC, /* Relic Codec (DCT-based) */ coding_CRI_HCA, /* CRI High Compression Audio (MDCT-based) */ @@ -283,6 +283,8 @@ typedef enum { layout_blocked_h4m, /* H4M video */ layout_blocked_xa_aiff, /* XA in AIFF files [Crusader: No Remorse (SAT), Road Rash (3DO)] */ layout_blocked_vs_square, + layout_blocked_vid1, + layout_blocked_ubi_sce, /* otherwise odd */ layout_segmented, /* song divided in segments (song sections) */ @@ -629,7 +631,7 @@ typedef enum { meta_VXN, /* Gameloft mobile games */ meta_EA_SNR_SNS, /* Electronic Arts SNR+SNS (Burnout Paradise) */ meta_EA_SPS, /* Electronic Arts SPS (Burnout Crash) */ - meta_NGC_VID1, /* Neversoft .ogg (Gun GC) */ + meta_VID1, meta_PC_FLX, /* Ultima IX PC */ meta_MOGG, /* Harmonix Music Systems MOGG Vorbis */ meta_OGG_VORBIS, /* Ogg Vorbis */ @@ -732,6 +734,7 @@ typedef enum { meta_TGC, meta_KWB, meta_LRMD, + meta_WWISE_FX, } meta_t; /* standard WAVEFORMATEXTENSIBLE speaker positions */