diff --git a/desmume/src/addons/compactFlash.cpp b/desmume/src/addons/compactFlash.cpp index 46223bf0c..362ad0daa 100644 --- a/desmume/src/addons/compactFlash.cpp +++ b/desmume/src/addons/compactFlash.cpp @@ -1,7 +1,4 @@ /* Copyright (C) 2006 yopyop - yopyop156@ifrance.com - yopyop156.ifrance.com - Copyright (C) 2006 Mic Copyright (C) 2009 CrazyMax Copyright (C) 2009 DeSmuME team diff --git a/desmume/src/addons/expMemory.cpp b/desmume/src/addons/expMemory.cpp index 9b5ee670d..5826d18aa 100644 --- a/desmume/src/addons/expMemory.cpp +++ b/desmume/src/addons/expMemory.cpp @@ -1,8 +1,4 @@ -/* Copyright (C) 2006 yopyop - yopyop156@ifrance.com - yopyop156.ifrance.com - - Copyright (C) 2009 CrazyMax +/* Copyright (C) 2009 CrazyMax Copyright (C) 2009 DeSmuME team This file is part of DeSmuME diff --git a/desmume/src/addons/gbagame.cpp b/desmume/src/addons/gbagame.cpp index 8d3b4d21a..457e1d566 100644 --- a/desmume/src/addons/gbagame.cpp +++ b/desmume/src/addons/gbagame.cpp @@ -1,8 +1,4 @@ -/* Copyright (C) 2006 yopyop - yopyop156@ifrance.com - yopyop156.ifrance.com - - Copyright (C) 2009 CrazyMax +/* Copyright (C) 2009 CrazyMax Copyright (C) 2009 DeSmuME team This file is part of DeSmuME diff --git a/desmume/src/addons/guitarGrip.cpp b/desmume/src/addons/guitarGrip.cpp index be629e46d..9000ef8c0 100644 --- a/desmume/src/addons/guitarGrip.cpp +++ b/desmume/src/addons/guitarGrip.cpp @@ -1,8 +1,4 @@ -/* Copyright (C) 2006 yopyop - yopyop156@ifrance.com - yopyop156.ifrance.com - - Copyright (C) 2009 CrazyMax +/* Copyright (C) 2009 CrazyMax Copyright (C) 2009 DeSmuME team This file is part of DeSmuME diff --git a/desmume/src/addons/none.cpp b/desmume/src/addons/none.cpp index 1393fbe7e..66015e1cd 100644 --- a/desmume/src/addons/none.cpp +++ b/desmume/src/addons/none.cpp @@ -1,8 +1,4 @@ -/* Copyright (C) 2006 yopyop - yopyop156@ifrance.com - yopyop156.ifrance.com - - Copyright (C) 2009 CrazyMax +/* Copyright (C) 2009 CrazyMax Copyright (C) 2009 DeSmuME team This file is part of DeSmuME diff --git a/desmume/src/addons/rumblepak.cpp b/desmume/src/addons/rumblepak.cpp index 6c31fb19c..f8291111c 100644 --- a/desmume/src/addons/rumblepak.cpp +++ b/desmume/src/addons/rumblepak.cpp @@ -1,8 +1,4 @@ -/* Copyright (C) 2006 yopyop - yopyop156@ifrance.com - yopyop156.ifrance.com - - Copyright (C) 2009 CrazyMax +/* Copyright (C) 2009 CrazyMax Copyright (C) 2009 DeSmuME team This file is part of DeSmuME diff --git a/desmume/src/utils/decrypt/crc.cpp b/desmume/src/utils/decrypt/crc.cpp index 30f62cf9e..52f3fd37b 100644 --- a/desmume/src/utils/decrypt/crc.cpp +++ b/desmume/src/utils/decrypt/crc.cpp @@ -1,5 +1,5 @@ //taken from ndstool -//http://devkitpro.cvs.sourceforge.net/viewvc/devkitpro/tools/nds/ndstool/source/crc.cpp?revision=1.2 +//http://devkitpro.svn.sourceforge.net/viewvc/devkitpro/trunk/tools/nds/ndstool/source/crc.cpp?revision=1587 /* crc.cpp - this file is part of DeSmuME * diff --git a/desmume/src/utils/decrypt/crc.h b/desmume/src/utils/decrypt/crc.h index 38da26d76..e7ca5779e 100644 --- a/desmume/src/utils/decrypt/crc.h +++ b/desmume/src/utils/decrypt/crc.h @@ -1,5 +1,5 @@ //taken from ndstool -//http://devkitpro.cvs.sourceforge.net/viewvc/devkitpro/tools/nds/ndstool/include/crc.h?revision=1.3 +//http://devkitpro.svn.sourceforge.net/viewvc/devkitpro/trunk/tools/nds/ndstool/include/crc.h?revision=2447 /* crc.h - this file is part of DeSmuME * diff --git a/desmume/src/utils/decrypt/decrypt.cpp b/desmume/src/utils/decrypt/decrypt.cpp index 9a0de58e1..00c83f035 100644 --- a/desmume/src/utils/decrypt/decrypt.cpp +++ b/desmume/src/utils/decrypt/decrypt.cpp @@ -1,5 +1,5 @@ //taken from ndstool -//http://devkitpro.cvs.sourceforge.net/viewvc/devkitpro/tools/nds/ndstool/source/encryption.cpp?revision=1.2 +//http://devkitpro.svn.sourceforge.net/viewvc/devkitpro/trunk/tools/nds/ndstool/source/encryption.cpp?revision=1565 /* decrypt.cpp - this file is part of DeSmuME * diff --git a/desmume/src/utils/decrypt/header.cpp b/desmume/src/utils/decrypt/header.cpp index 484e7e0e8..c64dd7730 100644 --- a/desmume/src/utils/decrypt/header.cpp +++ b/desmume/src/utils/decrypt/header.cpp @@ -1,5 +1,5 @@ //taken from ndstool -//http://devkitpro.cvs.sourceforge.net/viewvc/devkitpro/tools/nds/ndstool/source/header.cpp?revision=1.23 +//http://devkitpro.svn.sourceforge.net/viewvc/devkitpro/trunk/tools/nds/ndstool/source/header.cpp?revision=3063 /* header.cpp - this file is part of DeSmuME * diff --git a/desmume/src/utils/decrypt/header.h b/desmume/src/utils/decrypt/header.h index a8eb9c380..bca8ee524 100644 --- a/desmume/src/utils/decrypt/header.h +++ b/desmume/src/utils/decrypt/header.h @@ -1,5 +1,5 @@ //taken from ndstool -//http://devkitpro.cvs.sourceforge.net/viewvc/devkitpro/tools/nds/ndstool/include/header.h?revision=1.14 +//http://devkitpro.svn.sourceforge.net/viewvc/devkitpro/trunk/tools/nds/ndstool/include/header.h?revision=2447 /* header.h - this file is part of DeSmuME * diff --git a/desmume/src/windows/7z/7z-4.64_from_tastools b/desmume/src/windows/7z/7z-4.64_from_tastools new file mode 100644 index 000000000..e69de29bb diff --git a/desmume/src/windows/7z/7zip.lib b/desmume/src/windows/7z/7z-vc8-Win32.lib similarity index 74% rename from desmume/src/windows/7z/7zip.lib rename to desmume/src/windows/7z/7z-vc8-Win32.lib index abcc91a6d..ec3d32ee9 100644 Binary files a/desmume/src/windows/7z/7zip.lib and b/desmume/src/windows/7z/7z-vc8-Win32.lib differ diff --git a/desmume/src/windows/7z/7zip-x64.lib b/desmume/src/windows/7z/7z-vc8-x64.lib similarity index 82% rename from desmume/src/windows/7z/7zip-x64.lib rename to desmume/src/windows/7z/7z-vc8-x64.lib index f971840f9..fc6bd7696 100644 Binary files a/desmume/src/windows/7z/7zip-x64.lib and b/desmume/src/windows/7z/7z-vc8-x64.lib differ diff --git a/desmume/src/windows/7z/7zip.sln b/desmume/src/windows/7z/7zip.sln deleted file mode 100644 index 510da469c..000000000 --- a/desmume/src/windows/7z/7zip.sln +++ /dev/null @@ -1,26 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 9.00 -# Visual Studio 2005 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "lib7zip", "7zip.vcproj", "{5646C572-A578-49F8-9DA9-3E00A8CBFE3F}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Win32 = Debug|Win32 - Debug|x64 = Debug|x64 - Release|Win32 = Release|Win32 - Release|x64 = Release|x64 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {5646C572-A578-49F8-9DA9-3E00A8CBFE3F}.Debug|Win32.ActiveCfg = Debug|Win32 - {5646C572-A578-49F8-9DA9-3E00A8CBFE3F}.Debug|Win32.Build.0 = Debug|Win32 - {5646C572-A578-49F8-9DA9-3E00A8CBFE3F}.Debug|x64.ActiveCfg = Debug|x64 - {5646C572-A578-49F8-9DA9-3E00A8CBFE3F}.Debug|x64.Build.0 = Debug|x64 - {5646C572-A578-49F8-9DA9-3E00A8CBFE3F}.Release|Win32.ActiveCfg = Release|Win32 - {5646C572-A578-49F8-9DA9-3E00A8CBFE3F}.Release|Win32.Build.0 = Release|Win32 - {5646C572-A578-49F8-9DA9-3E00A8CBFE3F}.Release|x64.ActiveCfg = Release|x64 - {5646C572-A578-49F8-9DA9-3E00A8CBFE3F}.Release|x64.Build.0 = Release|x64 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/desmume/src/windows/7z/7zip.vcproj b/desmume/src/windows/7z/7zip.vcproj deleted file mode 100644 index c83181604..000000000 --- a/desmume/src/windows/7z/7zip.vcproj +++ /dev/null @@ -1,6611 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/desmume/src/windows/7z/C/7zCrc.c b/desmume/src/windows/7z/C/7zCrc.c deleted file mode 100644 index 92c47de0d..000000000 --- a/desmume/src/windows/7z/C/7zCrc.c +++ /dev/null @@ -1,35 +0,0 @@ -/* 7zCrc.c -- CRC32 calculation -2008-08-05 -Igor Pavlov -Public domain */ - -#include "7zCrc.h" - -#define kCrcPoly 0xEDB88320 -UInt32 g_CrcTable[256]; - -void MY_FAST_CALL CrcGenerateTable(void) -{ - UInt32 i; - for (i = 0; i < 256; i++) - { - UInt32 r = i; - int j; - for (j = 0; j < 8; j++) - r = (r >> 1) ^ (kCrcPoly & ~((r & 1) - 1)); - g_CrcTable[i] = r; - } -} - -UInt32 MY_FAST_CALL CrcUpdate(UInt32 v, const void *data, size_t size) -{ - const Byte *p = (const Byte *)data; - for (; size > 0 ; size--, p++) - v = CRC_UPDATE_BYTE(v, *p); - return v; -} - -UInt32 MY_FAST_CALL CrcCalc(const void *data, size_t size) -{ - return CrcUpdate(CRC_INIT_VAL, data, size) ^ 0xFFFFFFFF; -} diff --git a/desmume/src/windows/7z/C/7zCrc.h b/desmume/src/windows/7z/C/7zCrc.h deleted file mode 100644 index ae230991e..000000000 --- a/desmume/src/windows/7z/C/7zCrc.h +++ /dev/null @@ -1,24 +0,0 @@ -/* 7zCrc.h -- CRC32 calculation -2008-03-13 -Igor Pavlov -Public domain */ - -#ifndef __7Z_CRC_H -#define __7Z_CRC_H - -#include - -#include "Types.h" - -extern UInt32 g_CrcTable[]; - -void MY_FAST_CALL CrcGenerateTable(void); - -#define CRC_INIT_VAL 0xFFFFFFFF -#define CRC_GET_DIGEST(crc) ((crc) ^ 0xFFFFFFFF) -#define CRC_UPDATE_BYTE(crc, b) (g_CrcTable[((crc) ^ (b)) & 0xFF] ^ ((crc) >> 8)) - -UInt32 MY_FAST_CALL CrcUpdate(UInt32 crc, const void *data, size_t size); -UInt32 MY_FAST_CALL CrcCalc(const void *data, size_t size); - -#endif diff --git a/desmume/src/windows/7z/C/Aes.c b/desmume/src/windows/7z/C/Aes.c deleted file mode 100644 index 8c185f20b..000000000 --- a/desmume/src/windows/7z/C/Aes.c +++ /dev/null @@ -1,262 +0,0 @@ -/* Aes.c -- AES encryption / decryption -2008-08-05 -Igor Pavlov -Public domain */ - -#include "Aes.h" -#include "CpuArch.h" - -static UInt32 T[256 * 4]; -static Byte Sbox[256] = { - 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, - 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, - 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, - 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, - 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, - 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, - 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, - 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, - 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, - 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, - 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, - 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, - 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, - 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, - 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, - 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16}; - -static UInt32 D[256 * 4]; -static Byte InvS[256]; - -static Byte Rcon[11] = { 0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36 }; - -#define xtime(x) ((((x) << 1) ^ (((x) & 0x80) != 0 ? 0x1B : 0)) & 0xFF) - -#define Ui32(a0, a1, a2, a3) ((UInt32)(a0) | ((UInt32)(a1) << 8) | ((UInt32)(a2) << 16) | ((UInt32)(a3) << 24)) - -#define gb0(x) ( (x) & 0xFF) -#define gb1(x) (((x) >> ( 8)) & 0xFF) -#define gb2(x) (((x) >> (16)) & 0xFF) -#define gb3(x) (((x) >> (24)) & 0xFF) - -void AesGenTables(void) -{ - unsigned i; - for (i = 0; i < 256; i++) - InvS[Sbox[i]] = (Byte)i; - for (i = 0; i < 256; i++) - { - { - UInt32 a1 = Sbox[i]; - UInt32 a2 = xtime(a1); - UInt32 a3 = xtime(a1) ^ a1; - T[ i] = Ui32(a2, a1, a1, a3); - T[0x100 + i] = Ui32(a3, a2, a1, a1); - T[0x200 + i] = Ui32(a1, a3, a2, a1); - T[0x300 + i] = Ui32(a1, a1, a3, a2); - } - { - UInt32 a1 = InvS[i]; - UInt32 a2 = xtime(a1); - UInt32 a4 = xtime(a2); - UInt32 a8 = xtime(a4); - UInt32 a9 = a8 ^ a1; - UInt32 aB = a8 ^ a2 ^ a1; - UInt32 aD = a8 ^ a4 ^ a1; - UInt32 aE = a8 ^ a4 ^ a2; - D[ i] = Ui32(aE, a9, aD, aB); - D[0x100 + i] = Ui32(aB, aE, a9, aD); - D[0x200 + i] = Ui32(aD, aB, aE, a9); - D[0x300 + i] = Ui32(a9, aD, aB, aE); - } - } -} - -#define HT(i, x, s) (T + (x << 8))[gb ## x(s[(i + x) & 3])] -#define HT4(m, i, s, p) m[i] = \ - HT(i, 0, s) ^ \ - HT(i, 1, s) ^ \ - HT(i, 2, s) ^ \ - HT(i, 3, s) ^ w[p + i] -/* such order (2031) in HT16 is for VC6/K8 speed optimization) */ -#define HT16(m, s, p) \ - HT4(m, 2, s, p); \ - HT4(m, 0, s, p); \ - HT4(m, 3, s, p); \ - HT4(m, 1, s, p); \ - -#define FT(i, x) Sbox[gb ## x(m[(i + x) & 3])] -#define FT4(i) dest[i] = Ui32(FT(i, 0), FT(i, 1), FT(i, 2), FT(i, 3)) ^ w[i]; - -#define HD(i, x, s) (D + (x << 8))[gb ## x(s[(i - x) & 3])] -#define HD4(m, i, s, p) m[i] = \ - HD(i, 0, s) ^ \ - HD(i, 1, s) ^ \ - HD(i, 2, s) ^ \ - HD(i, 3, s) ^ w[p + i]; -/* such order (0231) in HD16 is for VC6/K8 speed optimization) */ -#define HD16(m, s, p) \ - HD4(m, 0, s, p); \ - HD4(m, 2, s, p); \ - HD4(m, 3, s, p); \ - HD4(m, 1, s, p); \ - -#define FD(i, x) InvS[gb ## x(m[(i - x) & 3])] -#define FD4(i) dest[i] = Ui32(FD(i, 0), FD(i, 1), FD(i, 2), FD(i, 3)) ^ w[i]; - -void Aes_SetKeyEncode(CAes *p, const Byte *key, unsigned keySize) -{ - unsigned i, wSize; - UInt32 *w; - keySize /= 4; - p->numRounds2 = keySize / 2 + 3; - - wSize = (p->numRounds2 * 2 + 1) * 4; - w = p->rkey; - - for (i = 0; i < keySize; i++, key += 4) - w[i] = Ui32(key[0], key[1], key[2], key[3]); - - for (; i < wSize; i++) - { - UInt32 t = w[i - 1]; - unsigned rem = i % keySize; - if (rem == 0) - t = Ui32(Sbox[gb1(t)] ^ Rcon[i / keySize], Sbox[gb2(t)], Sbox[gb3(t)], Sbox[gb0(t)]); - else if (keySize > 6 && rem == 4) - t = Ui32(Sbox[gb0(t)], Sbox[gb1(t)], Sbox[gb2(t)], Sbox[gb3(t)]); - w[i] = w[i - keySize] ^ t; - } -} - -void Aes_SetKeyDecode(CAes *p, const Byte *key, unsigned keySize) -{ - unsigned i, num; - UInt32 *w; - Aes_SetKeyEncode(p, key, keySize); - num = p->numRounds2 * 8 - 4; - w = p->rkey + 4; - for (i = 0; i < num; i++) - { - UInt32 r = w[i]; - w[i] = - D[ Sbox[gb0(r)]] ^ - D[0x100 + Sbox[gb1(r)]] ^ - D[0x200 + Sbox[gb2(r)]] ^ - D[0x300 + Sbox[gb3(r)]]; - } -} - -static void AesEncode32(UInt32 *dest, const UInt32 *src, const UInt32 *w, unsigned numRounds2) -{ - UInt32 s[4]; - UInt32 m[4]; - s[0] = src[0] ^ w[0]; - s[1] = src[1] ^ w[1]; - s[2] = src[2] ^ w[2]; - s[3] = src[3] ^ w[3]; - w += 4; - for (;;) - { - HT16(m, s, 0); - if (--numRounds2 == 0) - break; - HT16(s, m, 4); - w += 8; - } - w += 4; - FT4(0); FT4(1); FT4(2); FT4(3); -} - -static void AesDecode32(UInt32 *dest, const UInt32 *src, const UInt32 *w, unsigned numRounds2) -{ - UInt32 s[4]; - UInt32 m[4]; - w += numRounds2 * 8; - s[0] = src[0] ^ w[0]; - s[1] = src[1] ^ w[1]; - s[2] = src[2] ^ w[2]; - s[3] = src[3] ^ w[3]; - for (;;) - { - w -= 8; - HD16(m, s, 4); - if (--numRounds2 == 0) - break; - HD16(s, m, 0); - } - FD4(0); FD4(1); FD4(2); FD4(3); -} - -void Aes_Encode32(const CAes *p, UInt32 *dest, const UInt32 *src) -{ - AesEncode32(dest, src, p->rkey, p->numRounds2); -} - -void Aes_Decode32(const CAes *p, UInt32 *dest, const UInt32 *src) -{ - AesDecode32(dest, src, p->rkey, p->numRounds2); -} - -void AesCbc_Init(CAesCbc *p, const Byte *iv) -{ - unsigned i; - for (i = 0; i < 4; i++) - p->prev[i] = GetUi32(iv + i * 4); -} - -SizeT AesCbc_Encode(CAesCbc *p, Byte *data, SizeT size) -{ - SizeT i; - if (size == 0) - return 0; - if (size < AES_BLOCK_SIZE) - return AES_BLOCK_SIZE; - size -= AES_BLOCK_SIZE; - for (i = 0; i <= size; i += AES_BLOCK_SIZE, data += AES_BLOCK_SIZE) - { - p->prev[0] ^= GetUi32(data); - p->prev[1] ^= GetUi32(data + 4); - p->prev[2] ^= GetUi32(data + 8); - p->prev[3] ^= GetUi32(data + 12); - - AesEncode32(p->prev, p->prev, p->aes.rkey, p->aes.numRounds2); - - SetUi32(data, p->prev[0]); - SetUi32(data + 4, p->prev[1]); - SetUi32(data + 8, p->prev[2]); - SetUi32(data + 12, p->prev[3]); - } - return i; -} - -SizeT AesCbc_Decode(CAesCbc *p, Byte *data, SizeT size) -{ - SizeT i; - UInt32 in[4], out[4]; - if (size == 0) - return 0; - if (size < AES_BLOCK_SIZE) - return AES_BLOCK_SIZE; - size -= AES_BLOCK_SIZE; - for (i = 0; i <= size; i += AES_BLOCK_SIZE, data += AES_BLOCK_SIZE) - { - in[0] = GetUi32(data); - in[1] = GetUi32(data + 4); - in[2] = GetUi32(data + 8); - in[3] = GetUi32(data + 12); - - AesDecode32(out, in, p->aes.rkey, p->aes.numRounds2); - - SetUi32(data, p->prev[0] ^ out[0]); - SetUi32(data + 4, p->prev[1] ^ out[1]); - SetUi32(data + 8, p->prev[2] ^ out[2]); - SetUi32(data + 12, p->prev[3] ^ out[3]); - - p->prev[0] = in[0]; - p->prev[1] = in[1]; - p->prev[2] = in[2]; - p->prev[3] = in[3]; - } - return i; -} diff --git a/desmume/src/windows/7z/C/Aes.h b/desmume/src/windows/7z/C/Aes.h deleted file mode 100644 index 98ef0c6ea..000000000 --- a/desmume/src/windows/7z/C/Aes.h +++ /dev/null @@ -1,48 +0,0 @@ -/* Aes.h -- AES encryption / decryption -2008-08-05 -Igor Pavlov -Public domain */ - -#ifndef __AES_H -#define __AES_H - -#include "Types.h" - -#define AES_BLOCK_SIZE 16 - -typedef struct -{ - unsigned numRounds2; /* = numRounds / 2 */ - UInt32 rkey[(14 + 1) * 4]; -} CAes; - -/* Call AesGenTables one time before other AES functions */ -void AesGenTables(void); - -/* keySize = 16 or 24 or 32 (bytes) */ -void Aes_SetKeyEncode(CAes *p, const Byte *key, unsigned keySize); -void Aes_SetKeyDecode(CAes *p, const Byte *key, unsigned keySize); - -/* Aes_Encode32 and Aes_Decode32 functions work with little-endian words. - src and dest are pointers to 4 UInt32 words. - arc and dest can point to same block */ -void Aes_Encode32(const CAes *p, UInt32 *dest, const UInt32 *src); -void Aes_Decode32(const CAes *p, UInt32 *dest, const UInt32 *src); - -typedef struct -{ - UInt32 prev[4]; - CAes aes; -} CAesCbc; - -void AesCbc_Init(CAesCbc *p, const Byte *iv); /* iv size is AES_BLOCK_SIZE */ - -/* AesCbc_Encode and AesCbc_Decode: - if (res <= size): Filter have converted res bytes - if (res > size): Filter have not converted anything. And it needs at - least res = AES_BLOCK_SIZE bytes to convert one block */ - -SizeT AesCbc_Encode(CAesCbc *p, Byte *data, SizeT size); -SizeT AesCbc_Decode(CAesCbc *p, Byte *data, SizeT size); - -#endif diff --git a/desmume/src/windows/7z/C/Alloc.c b/desmume/src/windows/7z/C/Alloc.c deleted file mode 100644 index bb24a772b..000000000 --- a/desmume/src/windows/7z/C/Alloc.c +++ /dev/null @@ -1,127 +0,0 @@ -/* Alloc.c -- Memory allocation functions -2008-09-24 -Igor Pavlov -Public domain */ - -#ifdef _WIN32 -#include -#endif -#include - -#include "Alloc.h" - -/* #define _SZ_ALLOC_DEBUG */ - -/* use _SZ_ALLOC_DEBUG to debug alloc/free operations */ -#ifdef _SZ_ALLOC_DEBUG -#include -int g_allocCount = 0; -int g_allocCountMid = 0; -int g_allocCountBig = 0; -#endif - -void *MyAlloc(size_t size) -{ - if (size == 0) - return 0; - #ifdef _SZ_ALLOC_DEBUG - { - void *p = malloc(size); - fprintf(stderr, "\nAlloc %10d bytes, count = %10d, addr = %8X", size, g_allocCount++, (unsigned)p); - return p; - } - #else - return malloc(size); - #endif -} - -void MyFree(void *address) -{ - #ifdef _SZ_ALLOC_DEBUG - if (address != 0) - fprintf(stderr, "\nFree; count = %10d, addr = %8X", --g_allocCount, (unsigned)address); - #endif - free(address); -} - -#ifdef _WIN32 - -void *MidAlloc(size_t size) -{ - if (size == 0) - return 0; - #ifdef _SZ_ALLOC_DEBUG - fprintf(stderr, "\nAlloc_Mid %10d bytes; count = %10d", size, g_allocCountMid++); - #endif - return VirtualAlloc(0, size, MEM_COMMIT, PAGE_READWRITE); -} - -void MidFree(void *address) -{ - #ifdef _SZ_ALLOC_DEBUG - if (address != 0) - fprintf(stderr, "\nFree_Mid; count = %10d", --g_allocCountMid); - #endif - if (address == 0) - return; - VirtualFree(address, 0, MEM_RELEASE); -} - -#ifndef MEM_LARGE_PAGES -#undef _7ZIP_LARGE_PAGES -#endif - -#ifdef _7ZIP_LARGE_PAGES -SIZE_T g_LargePageSize = 0; -typedef SIZE_T (WINAPI *GetLargePageMinimumP)(); -#endif - -void SetLargePageSize() -{ - #ifdef _7ZIP_LARGE_PAGES - SIZE_T size = 0; - GetLargePageMinimumP largePageMinimum = (GetLargePageMinimumP) - GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "GetLargePageMinimum"); - if (largePageMinimum == 0) - return; - size = largePageMinimum(); - if (size == 0 || (size & (size - 1)) != 0) - return; - g_LargePageSize = size; - #endif -} - - -void *BigAlloc(size_t size) -{ - if (size == 0) - return 0; - #ifdef _SZ_ALLOC_DEBUG - fprintf(stderr, "\nAlloc_Big %10d bytes; count = %10d", size, g_allocCountBig++); - #endif - - #ifdef _7ZIP_LARGE_PAGES - if (g_LargePageSize != 0 && g_LargePageSize <= (1 << 30) && size >= (1 << 18)) - { - void *res = VirtualAlloc(0, (size + g_LargePageSize - 1) & (~(g_LargePageSize - 1)), - MEM_COMMIT | MEM_LARGE_PAGES, PAGE_READWRITE); - if (res != 0) - return res; - } - #endif - return VirtualAlloc(0, size, MEM_COMMIT, PAGE_READWRITE); -} - -void BigFree(void *address) -{ - #ifdef _SZ_ALLOC_DEBUG - if (address != 0) - fprintf(stderr, "\nFree_Big; count = %10d", --g_allocCountBig); - #endif - - if (address == 0) - return; - VirtualFree(address, 0, MEM_RELEASE); -} - -#endif diff --git a/desmume/src/windows/7z/C/Alloc.h b/desmume/src/windows/7z/C/Alloc.h deleted file mode 100644 index a396c6b9e..000000000 --- a/desmume/src/windows/7z/C/Alloc.h +++ /dev/null @@ -1,32 +0,0 @@ -/* Alloc.h -- Memory allocation functions -2008-03-13 -Igor Pavlov -Public domain */ - -#ifndef __COMMON_ALLOC_H -#define __COMMON_ALLOC_H - -#include - -void *MyAlloc(size_t size); -void MyFree(void *address); - -#ifdef _WIN32 - -void SetLargePageSize(); - -void *MidAlloc(size_t size); -void MidFree(void *address); -void *BigAlloc(size_t size); -void BigFree(void *address); - -#else - -#define MidAlloc(size) MyAlloc(size) -#define MidFree(address) MyFree(address) -#define BigAlloc(size) MyAlloc(size) -#define BigFree(address) MyFree(address) - -#endif - -#endif diff --git a/desmume/src/windows/7z/C/Bra.c b/desmume/src/windows/7z/C/Bra.c deleted file mode 100644 index 3b75f0ccb..000000000 --- a/desmume/src/windows/7z/C/Bra.c +++ /dev/null @@ -1,133 +0,0 @@ -/* Bra.c -- Converters for RISC code -2008-10-04 : Igor Pavlov : Public domain */ - -#include "Bra.h" - -SizeT ARM_Convert(Byte *data, SizeT size, UInt32 ip, int encoding) -{ - SizeT i; - if (size < 4) - return 0; - size -= 4; - ip += 8; - for (i = 0; i <= size; i += 4) - { - if (data[i + 3] == 0xEB) - { - UInt32 dest; - UInt32 src = ((UInt32)data[i + 2] << 16) | ((UInt32)data[i + 1] << 8) | (data[i + 0]); - src <<= 2; - if (encoding) - dest = ip + (UInt32)i + src; - else - dest = src - (ip + (UInt32)i); - dest >>= 2; - data[i + 2] = (Byte)(dest >> 16); - data[i + 1] = (Byte)(dest >> 8); - data[i + 0] = (Byte)dest; - } - } - return i; -} - -SizeT ARMT_Convert(Byte *data, SizeT size, UInt32 ip, int encoding) -{ - SizeT i; - if (size < 4) - return 0; - size -= 4; - ip += 4; - for (i = 0; i <= size; i += 2) - { - if ((data[i + 1] & 0xF8) == 0xF0 && - (data[i + 3] & 0xF8) == 0xF8) - { - UInt32 dest; - UInt32 src = - (((UInt32)data[i + 1] & 0x7) << 19) | - ((UInt32)data[i + 0] << 11) | - (((UInt32)data[i + 3] & 0x7) << 8) | - (data[i + 2]); - - src <<= 1; - if (encoding) - dest = ip + (UInt32)i + src; - else - dest = src - (ip + (UInt32)i); - dest >>= 1; - - data[i + 1] = (Byte)(0xF0 | ((dest >> 19) & 0x7)); - data[i + 0] = (Byte)(dest >> 11); - data[i + 3] = (Byte)(0xF8 | ((dest >> 8) & 0x7)); - data[i + 2] = (Byte)dest; - i += 2; - } - } - return i; -} - -SizeT PPC_Convert(Byte *data, SizeT size, UInt32 ip, int encoding) -{ - SizeT i; - if (size < 4) - return 0; - size -= 4; - for (i = 0; i <= size; i += 4) - { - if ((data[i] >> 2) == 0x12 && (data[i + 3] & 3) == 1) - { - UInt32 src = ((UInt32)(data[i + 0] & 3) << 24) | - ((UInt32)data[i + 1] << 16) | - ((UInt32)data[i + 2] << 8) | - ((UInt32)data[i + 3] & (~3)); - - UInt32 dest; - if (encoding) - dest = ip + (UInt32)i + src; - else - dest = src - (ip + (UInt32)i); - data[i + 0] = (Byte)(0x48 | ((dest >> 24) & 0x3)); - data[i + 1] = (Byte)(dest >> 16); - data[i + 2] = (Byte)(dest >> 8); - data[i + 3] &= 0x3; - data[i + 3] |= dest; - } - } - return i; -} - -SizeT SPARC_Convert(Byte *data, SizeT size, UInt32 ip, int encoding) -{ - UInt32 i; - if (size < 4) - return 0; - size -= 4; - for (i = 0; i <= size; i += 4) - { - if (data[i] == 0x40 && (data[i + 1] & 0xC0) == 0x00 || - data[i] == 0x7F && (data[i + 1] & 0xC0) == 0xC0) - { - UInt32 src = - ((UInt32)data[i + 0] << 24) | - ((UInt32)data[i + 1] << 16) | - ((UInt32)data[i + 2] << 8) | - ((UInt32)data[i + 3]); - UInt32 dest; - - src <<= 2; - if (encoding) - dest = ip + i + src; - else - dest = src - (ip + i); - dest >>= 2; - - dest = (((0 - ((dest >> 22) & 1)) << 22) & 0x3FFFFFFF) | (dest & 0x3FFFFF) | 0x40000000; - - data[i + 0] = (Byte)(dest >> 24); - data[i + 1] = (Byte)(dest >> 16); - data[i + 2] = (Byte)(dest >> 8); - data[i + 3] = (Byte)dest; - } - } - return i; -} diff --git a/desmume/src/windows/7z/C/Bra.h b/desmume/src/windows/7z/C/Bra.h deleted file mode 100644 index b9018eb99..000000000 --- a/desmume/src/windows/7z/C/Bra.h +++ /dev/null @@ -1,60 +0,0 @@ -/* Bra.h -- Branch converters for executables -2008-10-04 : Igor Pavlov : Public domain */ - -#ifndef __BRA_H -#define __BRA_H - -#include "Types.h" - -/* -These functions convert relative addresses to absolute addresses -in CALL instructions to increase the compression ratio. - - In: - data - data buffer - size - size of data - ip - current virtual Instruction Pinter (IP) value - state - state variable for x86 converter - encoding - 0 (for decoding), 1 (for encoding) - - Out: - state - state variable for x86 converter - - Returns: - The number of processed bytes. If you call these functions with multiple calls, - you must start next call with first byte after block of processed bytes. - - Type Endian Alignment LookAhead - - x86 little 1 4 - ARMT little 2 2 - ARM little 4 0 - PPC big 4 0 - SPARC big 4 0 - IA64 little 16 0 - - size must be >= Alignment + LookAhead, if it's not last block. - If (size < Alignment + LookAhead), converter returns 0. - - Example: - - UInt32 ip = 0; - for () - { - ; size must be >= Alignment + LookAhead, if it's not last block - SizeT processed = Convert(data, size, ip, 1); - data += processed; - size -= processed; - ip += processed; - } -*/ - -#define x86_Convert_Init(state) { state = 0; } -SizeT x86_Convert(Byte *data, SizeT size, UInt32 ip, UInt32 *state, int encoding); -SizeT ARM_Convert(Byte *data, SizeT size, UInt32 ip, int encoding); -SizeT ARMT_Convert(Byte *data, SizeT size, UInt32 ip, int encoding); -SizeT PPC_Convert(Byte *data, SizeT size, UInt32 ip, int encoding); -SizeT SPARC_Convert(Byte *data, SizeT size, UInt32 ip, int encoding); -SizeT IA64_Convert(Byte *data, SizeT size, UInt32 ip, int encoding); - -#endif diff --git a/desmume/src/windows/7z/C/Bra86.c b/desmume/src/windows/7z/C/Bra86.c deleted file mode 100644 index c3eda016e..000000000 --- a/desmume/src/windows/7z/C/Bra86.c +++ /dev/null @@ -1,85 +0,0 @@ -/* Bra86.c -- Converter for x86 code (BCJ) -2008-10-04 : Igor Pavlov : Public domain */ - -#include "Bra.h" - -#define Test86MSByte(b) ((b) == 0 || (b) == 0xFF) - -const Byte kMaskToAllowedStatus[8] = {1, 1, 1, 0, 1, 0, 0, 0}; -const Byte kMaskToBitNumber[8] = {0, 1, 2, 2, 3, 3, 3, 3}; - -SizeT x86_Convert(Byte *data, SizeT size, UInt32 ip, UInt32 *state, int encoding) -{ - SizeT bufferPos = 0, prevPosT; - UInt32 prevMask = *state & 0x7; - if (size < 5) - return 0; - ip += 5; - prevPosT = (SizeT)0 - 1; - - for (;;) - { - Byte *p = data + bufferPos; - Byte *limit = data + size - 4; - for (; p < limit; p++) - if ((*p & 0xFE) == 0xE8) - break; - bufferPos = (SizeT)(p - data); - if (p >= limit) - break; - prevPosT = bufferPos - prevPosT; - if (prevPosT > 3) - prevMask = 0; - else - { - prevMask = (prevMask << ((int)prevPosT - 1)) & 0x7; - if (prevMask != 0) - { - Byte b = p[4 - kMaskToBitNumber[prevMask]]; - if (!kMaskToAllowedStatus[prevMask] || Test86MSByte(b)) - { - prevPosT = bufferPos; - prevMask = ((prevMask << 1) & 0x7) | 1; - bufferPos++; - continue; - } - } - } - prevPosT = bufferPos; - - if (Test86MSByte(p[4])) - { - UInt32 src = ((UInt32)p[4] << 24) | ((UInt32)p[3] << 16) | ((UInt32)p[2] << 8) | ((UInt32)p[1]); - UInt32 dest; - for (;;) - { - Byte b; - int index; - if (encoding) - dest = (ip + (UInt32)bufferPos) + src; - else - dest = src - (ip + (UInt32)bufferPos); - if (prevMask == 0) - break; - index = kMaskToBitNumber[prevMask] * 8; - b = (Byte)((dest >> (24 - index)) & 0xFF); - if (!Test86MSByte(b)) - break; - src = dest ^ ((1 << (32 - index)) - 1); - } - p[4] = (Byte)((~(((dest >> 24) & 1) - 1)) & 0xFF); - p[3] = (Byte)((dest >> 16) & 0xFF); - p[2] = (Byte)((dest >> 8) & 0xFF); - p[1] = (Byte)(dest & 0xFF); - bufferPos += 5; - } - else - { - prevMask = ((prevMask << 1) & 0x7) | 1; - bufferPos++; - } - } - prevPosT = bufferPos - prevPosT; - *state = ((prevPosT > 3) ? 0 : ((prevMask << ((int)prevPosT - 1)) & 0x7)); - return bufferPos; -} diff --git a/desmume/src/windows/7z/C/BraIA64.c b/desmume/src/windows/7z/C/BraIA64.c deleted file mode 100644 index f359f16a3..000000000 --- a/desmume/src/windows/7z/C/BraIA64.c +++ /dev/null @@ -1,67 +0,0 @@ -/* BraIA64.c -- Converter for IA-64 code -2008-10-04 : Igor Pavlov : Public domain */ - -#include "Bra.h" - -static const Byte kBranchTable[32] = -{ - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 4, 4, 6, 6, 0, 0, 7, 7, - 4, 4, 0, 0, 4, 4, 0, 0 -}; - -SizeT IA64_Convert(Byte *data, SizeT size, UInt32 ip, int encoding) -{ - SizeT i; - if (size < 16) - return 0; - size -= 16; - for (i = 0; i <= size; i += 16) - { - UInt32 instrTemplate = data[i] & 0x1F; - UInt32 mask = kBranchTable[instrTemplate]; - UInt32 bitPos = 5; - int slot; - for (slot = 0; slot < 3; slot++, bitPos += 41) - { - UInt32 bytePos, bitRes; - UInt64 instruction, instNorm; - int j; - if (((mask >> slot) & 1) == 0) - continue; - bytePos = (bitPos >> 3); - bitRes = bitPos & 0x7; - instruction = 0; - for (j = 0; j < 6; j++) - instruction += (UInt64)data[i + j + bytePos] << (8 * j); - - instNorm = instruction >> bitRes; - if (((instNorm >> 37) & 0xF) == 0x5 && ((instNorm >> 9) & 0x7) == 0) - { - UInt32 src = (UInt32)((instNorm >> 13) & 0xFFFFF); - UInt32 dest; - src |= ((UInt32)(instNorm >> 36) & 1) << 20; - - src <<= 4; - - if (encoding) - dest = ip + (UInt32)i + src; - else - dest = src - (ip + (UInt32)i); - - dest >>= 4; - - instNorm &= ~((UInt64)(0x8FFFFF) << 13); - instNorm |= ((UInt64)(dest & 0xFFFFF) << 13); - instNorm |= ((UInt64)(dest & 0x100000) << (36 - 20)); - - instruction &= (1 << bitRes) - 1; - instruction |= (instNorm << bitRes); - for (j = 0; j < 6; j++) - data[i + j + bytePos] = (Byte)(instruction >> (8 * j)); - } - } - } - return i; -} diff --git a/desmume/src/windows/7z/C/BwtSort.c b/desmume/src/windows/7z/C/BwtSort.c deleted file mode 100644 index d6b545e83..000000000 --- a/desmume/src/windows/7z/C/BwtSort.c +++ /dev/null @@ -1,516 +0,0 @@ -/* BwtSort.c -- BWT block sorting -2008-08-17 -Igor Pavlov -Public domain */ - -#include "BwtSort.h" -#include "Sort.h" - -/* #define BLOCK_SORT_USE_HEAP_SORT */ - -#define NO_INLINE MY_FAST_CALL - -/* Don't change it !!! */ -#define kNumHashBytes 2 -#define kNumHashValues (1 << (kNumHashBytes * 8)) - -/* kNumRefBitsMax must be < (kNumHashBytes * 8) = 16 */ -#define kNumRefBitsMax 12 - -#define BS_TEMP_SIZE kNumHashValues - -#ifdef BLOCK_SORT_EXTERNAL_FLAGS - -/* 32 Flags in UInt32 word */ -#define kNumFlagsBits 5 -#define kNumFlagsInWord (1 << kNumFlagsBits) -#define kFlagsMask (kNumFlagsInWord - 1) -#define kAllFlags 0xFFFFFFFF - -#else - -#define kNumBitsMax 20 -#define kIndexMask ((1 << kNumBitsMax) - 1) -#define kNumExtraBits (32 - kNumBitsMax) -#define kNumExtra0Bits (kNumExtraBits - 2) -#define kNumExtra0Mask ((1 << kNumExtra0Bits) - 1) - -#define SetFinishedGroupSize(p, size) \ - { *(p) |= ((((size) - 1) & kNumExtra0Mask) << kNumBitsMax); \ - if ((size) > (1 << kNumExtra0Bits)) { \ - *(p) |= 0x40000000; *((p) + 1) |= ((((size) - 1)>> kNumExtra0Bits) << kNumBitsMax); } } \ - -static void SetGroupSize(UInt32 *p, UInt32 size) -{ - if (--size == 0) - return; - *p |= 0x80000000 | ((size & kNumExtra0Mask) << kNumBitsMax); - if (size >= (1 << kNumExtra0Bits)) - { - *p |= 0x40000000; - p[1] |= ((size >> kNumExtra0Bits) << kNumBitsMax); - } -} - -#endif - -/* -SortGroup - is recursive Range-Sort function with HeapSort optimization for small blocks - "range" is not real range. It's only for optimization. -returns: 1 - if there are groups, 0 - no more groups -*/ - -UInt32 NO_INLINE SortGroup(UInt32 BlockSize, UInt32 NumSortedBytes, UInt32 groupOffset, UInt32 groupSize, int NumRefBits, UInt32 *Indices - #ifndef BLOCK_SORT_USE_HEAP_SORT - , UInt32 left, UInt32 range - #endif - ) -{ - UInt32 *ind2 = Indices + groupOffset; - UInt32 *Groups; - if (groupSize <= 1) - { - /* - #ifndef BLOCK_SORT_EXTERNAL_FLAGS - SetFinishedGroupSize(ind2, 1); - #endif - */ - return 0; - } - Groups = Indices + BlockSize + BS_TEMP_SIZE; - if (groupSize <= ((UInt32)1 << NumRefBits) - #ifndef BLOCK_SORT_USE_HEAP_SORT - && groupSize <= range - #endif - ) - { - UInt32 *temp = Indices + BlockSize; - UInt32 j; - UInt32 mask, thereAreGroups, group, cg; - { - UInt32 gPrev; - UInt32 gRes = 0; - { - UInt32 sp = ind2[0] + NumSortedBytes; - if (sp >= BlockSize) sp -= BlockSize; - gPrev = Groups[sp]; - temp[0] = (gPrev << NumRefBits); - } - - for (j = 1; j < groupSize; j++) - { - UInt32 sp = ind2[j] + NumSortedBytes; - UInt32 g; - if (sp >= BlockSize) sp -= BlockSize; - g = Groups[sp]; - temp[j] = (g << NumRefBits) | j; - gRes |= (gPrev ^ g); - } - if (gRes == 0) - { - #ifndef BLOCK_SORT_EXTERNAL_FLAGS - SetGroupSize(ind2, groupSize); - #endif - return 1; - } - } - - HeapSort(temp, groupSize); - mask = ((1 << NumRefBits) - 1); - thereAreGroups = 0; - - group = groupOffset; - cg = (temp[0] >> NumRefBits); - temp[0] = ind2[temp[0] & mask]; - - { - #ifdef BLOCK_SORT_EXTERNAL_FLAGS - UInt32 *Flags = Groups + BlockSize; - #else - UInt32 prevGroupStart = 0; - #endif - - for (j = 1; j < groupSize; j++) - { - UInt32 val = temp[j]; - UInt32 cgCur = (val >> NumRefBits); - - if (cgCur != cg) - { - cg = cgCur; - group = groupOffset + j; - - #ifdef BLOCK_SORT_EXTERNAL_FLAGS - { - UInt32 t = group - 1; - Flags[t >> kNumFlagsBits] &= ~(1 << (t & kFlagsMask)); - } - #else - SetGroupSize(temp + prevGroupStart, j - prevGroupStart); - prevGroupStart = j; - #endif - } - else - thereAreGroups = 1; - { - UInt32 ind = ind2[val & mask]; - temp[j] = ind; - Groups[ind] = group; - } - } - - #ifndef BLOCK_SORT_EXTERNAL_FLAGS - SetGroupSize(temp + prevGroupStart, j - prevGroupStart); - #endif - } - - for (j = 0; j < groupSize; j++) - ind2[j] = temp[j]; - return thereAreGroups; - } - - /* Check that all strings are in one group (cannot sort) */ - { - UInt32 group, j; - UInt32 sp = ind2[0] + NumSortedBytes; if (sp >= BlockSize) sp -= BlockSize; - group = Groups[sp]; - for (j = 1; j < groupSize; j++) - { - sp = ind2[j] + NumSortedBytes; if (sp >= BlockSize) sp -= BlockSize; - if (Groups[sp] != group) - break; - } - if (j == groupSize) - { - #ifndef BLOCK_SORT_EXTERNAL_FLAGS - SetGroupSize(ind2, groupSize); - #endif - return 1; - } - } - - #ifndef BLOCK_SORT_USE_HEAP_SORT - { - /* ---------- Range Sort ---------- */ - UInt32 i; - UInt32 mid; - for (;;) - { - UInt32 j; - if (range <= 1) - { - #ifndef BLOCK_SORT_EXTERNAL_FLAGS - SetGroupSize(ind2, groupSize); - #endif - return 1; - } - mid = left + ((range + 1) >> 1); - j = groupSize; - i = 0; - do - { - UInt32 sp = ind2[i] + NumSortedBytes; if (sp >= BlockSize) sp -= BlockSize; - if (Groups[sp] >= mid) - { - for (j--; j > i; j--) - { - sp = ind2[j] + NumSortedBytes; if (sp >= BlockSize) sp -= BlockSize; - if (Groups[sp] < mid) - { - UInt32 temp = ind2[i]; ind2[i] = ind2[j]; ind2[j] = temp; - break; - } - } - if (i >= j) - break; - } - } - while (++i < j); - if (i == 0) - { - range = range - (mid - left); - left = mid; - } - else if (i == groupSize) - range = (mid - left); - else - break; - } - - #ifdef BLOCK_SORT_EXTERNAL_FLAGS - { - UInt32 t = (groupOffset + i - 1); - UInt32 *Flags = Groups + BlockSize; - Flags[t >> kNumFlagsBits] &= ~(1 << (t & kFlagsMask)); - } - #endif - - { - UInt32 j; - for (j = i; j < groupSize; j++) - Groups[ind2[j]] = groupOffset + i; - } - - { - UInt32 res = SortGroup(BlockSize, NumSortedBytes, groupOffset, i, NumRefBits, Indices, left, mid - left); - return res | SortGroup(BlockSize, NumSortedBytes, groupOffset + i, groupSize - i, NumRefBits, Indices, mid, range - (mid - left)); - } - - } - - #else - - /* ---------- Heap Sort ---------- */ - - { - UInt32 j; - for (j = 0; j < groupSize; j++) - { - UInt32 sp = ind2[j] + NumSortedBytes; if (sp >= BlockSize) sp -= BlockSize; - ind2[j] = sp; - } - - HeapSortRef(ind2, Groups, groupSize); - - /* Write Flags */ - { - UInt32 sp = ind2[0]; - UInt32 group = Groups[sp]; - - #ifdef BLOCK_SORT_EXTERNAL_FLAGS - UInt32 *Flags = Groups + BlockSize; - #else - UInt32 prevGroupStart = 0; - #endif - - for (j = 1; j < groupSize; j++) - { - sp = ind2[j]; - if (Groups[sp] != group) - { - group = Groups[sp]; - #ifdef BLOCK_SORT_EXTERNAL_FLAGS - { - UInt32 t = groupOffset + j - 1; - Flags[t >> kNumFlagsBits] &= ~(1 << (t & kFlagsMask)); - } - #else - SetGroupSize(ind2 + prevGroupStart, j - prevGroupStart); - prevGroupStart = j; - #endif - } - } - - #ifndef BLOCK_SORT_EXTERNAL_FLAGS - SetGroupSize(ind2 + prevGroupStart, j - prevGroupStart); - #endif - } - { - /* Write new Groups values and Check that there are groups */ - UInt32 thereAreGroups = 0; - for (j = 0; j < groupSize; j++) - { - UInt32 group = groupOffset + j; - #ifndef BLOCK_SORT_EXTERNAL_FLAGS - UInt32 subGroupSize = ((ind2[j] & ~0xC0000000) >> kNumBitsMax); - if ((ind2[j] & 0x40000000) != 0) - subGroupSize += ((ind2[j + 1] >> kNumBitsMax) << kNumExtra0Bits); - subGroupSize++; - for (;;) - { - UInt32 original = ind2[j]; - UInt32 sp = original & kIndexMask; - if (sp < NumSortedBytes) sp += BlockSize; sp -= NumSortedBytes; - ind2[j] = sp | (original & ~kIndexMask); - Groups[sp] = group; - if (--subGroupSize == 0) - break; - j++; - thereAreGroups = 1; - } - #else - UInt32 *Flags = Groups + BlockSize; - for (;;) - { - UInt32 sp = ind2[j]; if (sp < NumSortedBytes) sp += BlockSize; sp -= NumSortedBytes; - ind2[j] = sp; - Groups[sp] = group; - if ((Flags[(groupOffset + j) >> kNumFlagsBits] & (1 << ((groupOffset + j) & kFlagsMask))) == 0) - break; - j++; - thereAreGroups = 1; - } - #endif - } - return thereAreGroups; - } - } - #endif -} - -/* conditions: blockSize > 0 */ -UInt32 BlockSort(UInt32 *Indices, const Byte *data, UInt32 blockSize) -{ - UInt32 *counters = Indices + blockSize; - UInt32 i; - UInt32 *Groups; - #ifdef BLOCK_SORT_EXTERNAL_FLAGS - UInt32 *Flags; - #endif - - /* Radix-Sort for 2 bytes */ - for (i = 0; i < kNumHashValues; i++) - counters[i] = 0; - for (i = 0; i < blockSize - 1; i++) - counters[((UInt32)data[i] << 8) | data[i + 1]]++; - counters[((UInt32)data[i] << 8) | data[0]]++; - - Groups = counters + BS_TEMP_SIZE; - #ifdef BLOCK_SORT_EXTERNAL_FLAGS - Flags = Groups + blockSize; - { - UInt32 numWords = (blockSize + kFlagsMask) >> kNumFlagsBits; - for (i = 0; i < numWords; i++) - Flags[i] = kAllFlags; - } - #endif - - { - UInt32 sum = 0; - for (i = 0; i < kNumHashValues; i++) - { - UInt32 groupSize = counters[i]; - if (groupSize > 0) - { - #ifdef BLOCK_SORT_EXTERNAL_FLAGS - UInt32 t = sum + groupSize - 1; - Flags[t >> kNumFlagsBits] &= ~(1 << (t & kFlagsMask)); - #endif - sum += groupSize; - } - counters[i] = sum - groupSize; - } - - for (i = 0; i < blockSize - 1; i++) - Groups[i] = counters[((UInt32)data[i] << 8) | data[i + 1]]; - Groups[i] = counters[((UInt32)data[i] << 8) | data[0]]; - - for (i = 0; i < blockSize - 1; i++) - Indices[counters[((UInt32)data[i] << 8) | data[i + 1]]++] = i; - Indices[counters[((UInt32)data[i] << 8) | data[0]]++] = i; - - #ifndef BLOCK_SORT_EXTERNAL_FLAGS - { - UInt32 prev = 0; - for (i = 0; i < kNumHashValues; i++) - { - UInt32 prevGroupSize = counters[i] - prev; - if (prevGroupSize == 0) - continue; - SetGroupSize(Indices + prev, prevGroupSize); - prev = counters[i]; - } - } - #endif - } - - { - int NumRefBits; - UInt32 NumSortedBytes; - for (NumRefBits = 0; ((blockSize - 1) >> NumRefBits) != 0; NumRefBits++); - NumRefBits = 32 - NumRefBits; - if (NumRefBits > kNumRefBitsMax) - NumRefBits = kNumRefBitsMax; - - for (NumSortedBytes = kNumHashBytes; ; NumSortedBytes <<= 1) - { - #ifndef BLOCK_SORT_EXTERNAL_FLAGS - UInt32 finishedGroupSize = 0; - #endif - UInt32 newLimit = 0; - for (i = 0; i < blockSize;) - { - UInt32 groupSize; - #ifdef BLOCK_SORT_EXTERNAL_FLAGS - - if ((Flags[i >> kNumFlagsBits] & (1 << (i & kFlagsMask))) == 0) - { - i++; - continue; - } - for (groupSize = 1; - (Flags[(i + groupSize) >> kNumFlagsBits] & (1 << ((i + groupSize) & kFlagsMask))) != 0; - groupSize++); - - groupSize++; - - #else - - groupSize = ((Indices[i] & ~0xC0000000) >> kNumBitsMax); - { - Bool finishedGroup = ((Indices[i] & 0x80000000) == 0); - if ((Indices[i] & 0x40000000) != 0) - { - groupSize += ((Indices[i + 1] >> kNumBitsMax) << kNumExtra0Bits); - Indices[i + 1] &= kIndexMask; - } - Indices[i] &= kIndexMask; - groupSize++; - if (finishedGroup || groupSize == 1) - { - Indices[i - finishedGroupSize] &= kIndexMask; - if (finishedGroupSize > 1) - Indices[i - finishedGroupSize + 1] &= kIndexMask; - { - UInt32 newGroupSize = groupSize + finishedGroupSize; - SetFinishedGroupSize(Indices + i - finishedGroupSize, newGroupSize); - finishedGroupSize = newGroupSize; - } - i += groupSize; - continue; - } - finishedGroupSize = 0; - } - - #endif - - if (NumSortedBytes >= blockSize) - { - UInt32 j; - for (j = 0; j < groupSize; j++) - { - UInt32 t = (i + j); - /* Flags[t >> kNumFlagsBits] &= ~(1 << (t & kFlagsMask)); */ - Groups[Indices[t]] = t; - } - } - else - if (SortGroup(blockSize, NumSortedBytes, i, groupSize, NumRefBits, Indices - #ifndef BLOCK_SORT_USE_HEAP_SORT - , 0, blockSize - #endif - ) != 0) - newLimit = i + groupSize; - i += groupSize; - } - if (newLimit == 0) - break; - } - } - #ifndef BLOCK_SORT_EXTERNAL_FLAGS - for (i = 0; i < blockSize;) - { - UInt32 groupSize = ((Indices[i] & ~0xC0000000) >> kNumBitsMax); - if ((Indices[i] & 0x40000000) != 0) - { - groupSize += ((Indices[i + 1] >> kNumBitsMax) << kNumExtra0Bits); - Indices[i + 1] &= kIndexMask; - } - Indices[i] &= kIndexMask; - groupSize++; - i += groupSize; - } - #endif - return Groups[0]; -} - diff --git a/desmume/src/windows/7z/C/BwtSort.h b/desmume/src/windows/7z/C/BwtSort.h deleted file mode 100644 index 84c50339c..000000000 --- a/desmume/src/windows/7z/C/BwtSort.h +++ /dev/null @@ -1,24 +0,0 @@ -/* BwtSort.h -- BWT block sorting -2008-03-26 -Igor Pavlov -Public domain */ - -#ifndef __BWTSORT_H -#define __BWTSORT_H - -#include "Types.h" - -/* use BLOCK_SORT_EXTERNAL_FLAGS if blockSize can be > 1M */ -/* #define BLOCK_SORT_EXTERNAL_FLAGS */ - -#ifdef BLOCK_SORT_EXTERNAL_FLAGS -#define BLOCK_SORT_EXTERNAL_SIZE(blockSize) ((((blockSize) + 31) >> 5)) -#else -#define BLOCK_SORT_EXTERNAL_SIZE(blockSize) 0 -#endif - -#define BLOCK_SORT_BUF_SIZE(blockSize) ((blockSize) * 2 + BLOCK_SORT_EXTERNAL_SIZE(blockSize) + (1 << 16)) - -UInt32 BlockSort(UInt32 *indices, const Byte *data, UInt32 blockSize); - -#endif diff --git a/desmume/src/windows/7z/C/CpuArch.h b/desmume/src/windows/7z/C/CpuArch.h deleted file mode 100644 index 006361f2f..000000000 --- a/desmume/src/windows/7z/C/CpuArch.h +++ /dev/null @@ -1,69 +0,0 @@ -/* CpuArch.h -2008-08-05 -Igor Pavlov -Public domain */ - -#ifndef __CPUARCH_H -#define __CPUARCH_H - -/* -LITTLE_ENDIAN_UNALIGN means: - 1) CPU is LITTLE_ENDIAN - 2) it's allowed to make unaligned memory accesses -if LITTLE_ENDIAN_UNALIGN is not defined, it means that we don't know -about these properties of platform. -*/ - -#if defined(_M_IX86) || defined(_M_X64) || defined(_M_AMD64) || defined(__i386__) || defined(__x86_64__) -#define LITTLE_ENDIAN_UNALIGN -#endif - -#ifdef LITTLE_ENDIAN_UNALIGN - -#define GetUi16(p) (*(const UInt16 *)(p)) -#define GetUi32(p) (*(const UInt32 *)(p)) -#define GetUi64(p) (*(const UInt64 *)(p)) -#define SetUi32(p, d) *(UInt32 *)(p) = (d); - -#else - -#define GetUi16(p) (((const Byte *)(p))[0] | ((UInt16)((const Byte *)(p))[1] << 8)) - -#define GetUi32(p) ( \ - ((const Byte *)(p))[0] | \ - ((UInt32)((const Byte *)(p))[1] << 8) | \ - ((UInt32)((const Byte *)(p))[2] << 16) | \ - ((UInt32)((const Byte *)(p))[3] << 24)) - -#define GetUi64(p) (GetUi32(p) | ((UInt64)GetUi32(((const Byte *)(p)) + 4) << 32)) - -#define SetUi32(p, d) { UInt32 _x_ = (d); \ - ((Byte *)(p))[0] = (Byte)_x_; \ - ((Byte *)(p))[1] = (Byte)(_x_ >> 8); \ - ((Byte *)(p))[2] = (Byte)(_x_ >> 16); \ - ((Byte *)(p))[3] = (Byte)(_x_ >> 24); } - -#endif - -#if defined(LITTLE_ENDIAN_UNALIGN) && defined(_WIN64) && (_MSC_VER >= 1300) - -#pragma intrinsic(_byteswap_ulong) -#pragma intrinsic(_byteswap_uint64) -#define GetBe32(p) _byteswap_ulong(*(const UInt32 *)(const Byte *)(p)) -#define GetBe64(p) _byteswap_uint64(*(const UInt64 *)(const Byte *)(p)) - -#else - -#define GetBe32(p) ( \ - ((UInt32)((const Byte *)(p))[0] << 24) | \ - ((UInt32)((const Byte *)(p))[1] << 16) | \ - ((UInt32)((const Byte *)(p))[2] << 8) | \ - ((const Byte *)(p))[3] ) - -#define GetBe64(p) (((UInt64)GetBe32(p) << 32) | GetBe32(((const Byte *)(p)) + 4)) - -#endif - -#define GetBe16(p) (((UInt16)((const Byte *)(p))[0] << 8) | ((const Byte *)(p))[1]) - -#endif diff --git a/desmume/src/windows/7z/C/HuffEnc.c b/desmume/src/windows/7z/C/HuffEnc.c deleted file mode 100644 index 2d31ad596..000000000 --- a/desmume/src/windows/7z/C/HuffEnc.c +++ /dev/null @@ -1,148 +0,0 @@ -/* HuffEnc.c -- functions for Huffman encoding -2008-08-05 -Igor Pavlov -Public domain */ - -#include "HuffEnc.h" -#include "Sort.h" - -#define kMaxLen 16 -#define NUM_BITS 10 -#define MASK ((1 << NUM_BITS) - 1) - -#define NUM_COUNTERS 64 - -#define HUFFMAN_SPEED_OPT - -void Huffman_Generate(const UInt32 *freqs, UInt32 *p, Byte *lens, UInt32 numSymbols, UInt32 maxLen) -{ - UInt32 num = 0; - /* if (maxLen > 10) maxLen = 10; */ - { - UInt32 i; - - #ifdef HUFFMAN_SPEED_OPT - - UInt32 counters[NUM_COUNTERS]; - for (i = 0; i < NUM_COUNTERS; i++) - counters[i] = 0; - for (i = 0; i < numSymbols; i++) - { - UInt32 freq = freqs[i]; - counters[(freq < NUM_COUNTERS - 1) ? freq : NUM_COUNTERS - 1]++; - } - - for (i = 1; i < NUM_COUNTERS; i++) - { - UInt32 temp = counters[i]; - counters[i] = num; - num += temp; - } - - for (i = 0; i < numSymbols; i++) - { - UInt32 freq = freqs[i]; - if (freq == 0) - lens[i] = 0; - else - p[counters[((freq < NUM_COUNTERS - 1) ? freq : NUM_COUNTERS - 1)]++] = i | (freq << NUM_BITS); - } - counters[0] = 0; - HeapSort(p + counters[NUM_COUNTERS - 2], counters[NUM_COUNTERS - 1] - counters[NUM_COUNTERS - 2]); - - #else - - for (i = 0; i < numSymbols; i++) - { - UInt32 freq = freqs[i]; - if (freq == 0) - lens[i] = 0; - else - p[num++] = i | (freq << NUM_BITS); - } - HeapSort(p, num); - - #endif - } - - if (num < 2) - { - int minCode = 0; - int maxCode = 1; - if (num == 1) - { - maxCode = (int)(p[0] & MASK); - if (maxCode == 0) - maxCode++; - } - p[minCode] = 0; - p[maxCode] = 1; - lens[minCode] = lens[maxCode] = 1; - return; - } - - { - UInt32 b, e, i; - - i = b = e = 0; - do - { - UInt32 n, m, freq; - n = (i != num && (b == e || (p[i] >> NUM_BITS) <= (p[b] >> NUM_BITS))) ? i++ : b++; - freq = (p[n] & ~MASK); - p[n] = (p[n] & MASK) | (e << NUM_BITS); - m = (i != num && (b == e || (p[i] >> NUM_BITS) <= (p[b] >> NUM_BITS))) ? i++ : b++; - freq += (p[m] & ~MASK); - p[m] = (p[m] & MASK) | (e << NUM_BITS); - p[e] = (p[e] & MASK) | freq; - e++; - } - while (num - e > 1); - - { - UInt32 lenCounters[kMaxLen + 1]; - for (i = 0; i <= kMaxLen; i++) - lenCounters[i] = 0; - - p[--e] &= MASK; - lenCounters[1] = 2; - while (e > 0) - { - UInt32 len = (p[p[--e] >> NUM_BITS] >> NUM_BITS) + 1; - p[e] = (p[e] & MASK) | (len << NUM_BITS); - if (len >= maxLen) - for (len = maxLen - 1; lenCounters[len] == 0; len--); - lenCounters[len]--; - lenCounters[len + 1] += 2; - } - - { - UInt32 len; - i = 0; - for (len = maxLen; len != 0; len--) - { - UInt32 num; - for (num = lenCounters[len]; num != 0; num--) - lens[p[i++] & MASK] = (Byte)len; - } - } - - { - UInt32 nextCodes[kMaxLen + 1]; - { - UInt32 code = 0; - UInt32 len; - for (len = 1; len <= kMaxLen; len++) - nextCodes[len] = code = (code + lenCounters[len - 1]) << 1; - } - /* if (code + lenCounters[kMaxLen] - 1 != (1 << kMaxLen) - 1) throw 1; */ - - { - UInt32 i; - for (i = 0; i < numSymbols; i++) - p[i] = nextCodes[lens[i]]++; - } - } - } - } -} diff --git a/desmume/src/windows/7z/C/HuffEnc.h b/desmume/src/windows/7z/C/HuffEnc.h deleted file mode 100644 index c0617b33e..000000000 --- a/desmume/src/windows/7z/C/HuffEnc.h +++ /dev/null @@ -1,21 +0,0 @@ -/* HuffEnc.h -- functions for Huffman encoding -2008-03-26 -Igor Pavlov -Public domain */ - -#ifndef __HUFFENC_H -#define __HUFFENC_H - -#include "Types.h" - -/* -Conditions: - num <= 1024 = 2 ^ NUM_BITS - Sum(freqs) < 4M = 2 ^ (32 - NUM_BITS) - maxLen <= 16 = kMaxLen - Num_Items(p) >= HUFFMAN_TEMP_SIZE(num) -*/ - -void Huffman_Generate(const UInt32 *freqs, UInt32 *p, Byte *lens, UInt32 num, UInt32 maxLen); - -#endif diff --git a/desmume/src/windows/7z/C/LzFind.c b/desmume/src/windows/7z/C/LzFind.c deleted file mode 100644 index e0ebe6235..000000000 --- a/desmume/src/windows/7z/C/LzFind.c +++ /dev/null @@ -1,751 +0,0 @@ -/* LzFind.c -- Match finder for LZ algorithms -2008-10-04 : Igor Pavlov : Public domain */ - -#include - -#include "LzFind.h" -#include "LzHash.h" - -#define kEmptyHashValue 0 -#define kMaxValForNormalize ((UInt32)0xFFFFFFFF) -#define kNormalizeStepMin (1 << 10) /* it must be power of 2 */ -#define kNormalizeMask (~(kNormalizeStepMin - 1)) -#define kMaxHistorySize ((UInt32)3 << 30) - -#define kStartMaxLen 3 - -static void LzInWindow_Free(CMatchFinder *p, ISzAlloc *alloc) -{ - if (!p->directInput) - { - alloc->Free(alloc, p->bufferBase); - p->bufferBase = 0; - } -} - -/* keepSizeBefore + keepSizeAfter + keepSizeReserv must be < 4G) */ - -static int LzInWindow_Create(CMatchFinder *p, UInt32 keepSizeReserv, ISzAlloc *alloc) -{ - UInt32 blockSize = p->keepSizeBefore + p->keepSizeAfter + keepSizeReserv; - if (p->directInput) - { - p->blockSize = blockSize; - return 1; - } - if (p->bufferBase == 0 || p->blockSize != blockSize) - { - LzInWindow_Free(p, alloc); - p->blockSize = blockSize; - p->bufferBase = (Byte *)alloc->Alloc(alloc, (size_t)blockSize); - } - return (p->bufferBase != 0); -} - -Byte *MatchFinder_GetPointerToCurrentPos(CMatchFinder *p) { return p->buffer; } -Byte MatchFinder_GetIndexByte(CMatchFinder *p, Int32 index) { return p->buffer[index]; } - -UInt32 MatchFinder_GetNumAvailableBytes(CMatchFinder *p) { return p->streamPos - p->pos; } - -void MatchFinder_ReduceOffsets(CMatchFinder *p, UInt32 subValue) -{ - p->posLimit -= subValue; - p->pos -= subValue; - p->streamPos -= subValue; -} - -static void MatchFinder_ReadBlock(CMatchFinder *p) -{ - if (p->streamEndWasReached || p->result != SZ_OK) - return; - for (;;) - { - Byte *dest = p->buffer + (p->streamPos - p->pos); - size_t size = (p->bufferBase + p->blockSize - dest); - if (size == 0) - return; - p->result = p->stream->Read(p->stream, dest, &size); - if (p->result != SZ_OK) - return; - if (size == 0) - { - p->streamEndWasReached = 1; - return; - } - p->streamPos += (UInt32)size; - if (p->streamPos - p->pos > p->keepSizeAfter) - return; - } -} - -void MatchFinder_MoveBlock(CMatchFinder *p) -{ - memmove(p->bufferBase, - p->buffer - p->keepSizeBefore, - (size_t)(p->streamPos - p->pos + p->keepSizeBefore)); - p->buffer = p->bufferBase + p->keepSizeBefore; -} - -int MatchFinder_NeedMove(CMatchFinder *p) -{ - /* if (p->streamEndWasReached) return 0; */ - return ((size_t)(p->bufferBase + p->blockSize - p->buffer) <= p->keepSizeAfter); -} - -void MatchFinder_ReadIfRequired(CMatchFinder *p) -{ - if (p->streamEndWasReached) - return; - if (p->keepSizeAfter >= p->streamPos - p->pos) - MatchFinder_ReadBlock(p); -} - -static void MatchFinder_CheckAndMoveAndRead(CMatchFinder *p) -{ - if (MatchFinder_NeedMove(p)) - MatchFinder_MoveBlock(p); - MatchFinder_ReadBlock(p); -} - -static void MatchFinder_SetDefaultSettings(CMatchFinder *p) -{ - p->cutValue = 32; - p->btMode = 1; - p->numHashBytes = 4; - /* p->skipModeBits = 0; */ - p->directInput = 0; - p->bigHash = 0; -} - -#define kCrcPoly 0xEDB88320 - -void MatchFinder_Construct(CMatchFinder *p) -{ - UInt32 i; - p->bufferBase = 0; - p->directInput = 0; - p->hash = 0; - MatchFinder_SetDefaultSettings(p); - - for (i = 0; i < 256; i++) - { - UInt32 r = i; - int j; - for (j = 0; j < 8; j++) - r = (r >> 1) ^ (kCrcPoly & ~((r & 1) - 1)); - p->crc[i] = r; - } -} - -static void MatchFinder_FreeThisClassMemory(CMatchFinder *p, ISzAlloc *alloc) -{ - alloc->Free(alloc, p->hash); - p->hash = 0; -} - -void MatchFinder_Free(CMatchFinder *p, ISzAlloc *alloc) -{ - MatchFinder_FreeThisClassMemory(p, alloc); - LzInWindow_Free(p, alloc); -} - -static CLzRef* AllocRefs(UInt32 num, ISzAlloc *alloc) -{ - size_t sizeInBytes = (size_t)num * sizeof(CLzRef); - if (sizeInBytes / sizeof(CLzRef) != num) - return 0; - return (CLzRef *)alloc->Alloc(alloc, sizeInBytes); -} - -int MatchFinder_Create(CMatchFinder *p, UInt32 historySize, - UInt32 keepAddBufferBefore, UInt32 matchMaxLen, UInt32 keepAddBufferAfter, - ISzAlloc *alloc) -{ - UInt32 sizeReserv; - if (historySize > kMaxHistorySize) - { - MatchFinder_Free(p, alloc); - return 0; - } - sizeReserv = historySize >> 1; - if (historySize > ((UInt32)2 << 30)) - sizeReserv = historySize >> 2; - sizeReserv += (keepAddBufferBefore + matchMaxLen + keepAddBufferAfter) / 2 + (1 << 19); - - p->keepSizeBefore = historySize + keepAddBufferBefore + 1; - p->keepSizeAfter = matchMaxLen + keepAddBufferAfter; - /* we need one additional byte, since we use MoveBlock after pos++ and before dictionary using */ - if (LzInWindow_Create(p, sizeReserv, alloc)) - { - UInt32 newCyclicBufferSize = (historySize /* >> p->skipModeBits */) + 1; - UInt32 hs; - p->matchMaxLen = matchMaxLen; - { - p->fixedHashSize = 0; - if (p->numHashBytes == 2) - hs = (1 << 16) - 1; - else - { - hs = historySize - 1; - hs |= (hs >> 1); - hs |= (hs >> 2); - hs |= (hs >> 4); - hs |= (hs >> 8); - hs >>= 1; - /* hs >>= p->skipModeBits; */ - hs |= 0xFFFF; /* don't change it! It's required for Deflate */ - if (hs > (1 << 24)) - { - if (p->numHashBytes == 3) - hs = (1 << 24) - 1; - else - hs >>= 1; - } - } - p->hashMask = hs; - hs++; - if (p->numHashBytes > 2) p->fixedHashSize += kHash2Size; - if (p->numHashBytes > 3) p->fixedHashSize += kHash3Size; - if (p->numHashBytes > 4) p->fixedHashSize += kHash4Size; - hs += p->fixedHashSize; - } - - { - UInt32 prevSize = p->hashSizeSum + p->numSons; - UInt32 newSize; - p->historySize = historySize; - p->hashSizeSum = hs; - p->cyclicBufferSize = newCyclicBufferSize; - p->numSons = (p->btMode ? newCyclicBufferSize * 2 : newCyclicBufferSize); - newSize = p->hashSizeSum + p->numSons; - if (p->hash != 0 && prevSize == newSize) - return 1; - MatchFinder_FreeThisClassMemory(p, alloc); - p->hash = AllocRefs(newSize, alloc); - if (p->hash != 0) - { - p->son = p->hash + p->hashSizeSum; - return 1; - } - } - } - MatchFinder_Free(p, alloc); - return 0; -} - -static void MatchFinder_SetLimits(CMatchFinder *p) -{ - UInt32 limit = kMaxValForNormalize - p->pos; - UInt32 limit2 = p->cyclicBufferSize - p->cyclicBufferPos; - if (limit2 < limit) - limit = limit2; - limit2 = p->streamPos - p->pos; - if (limit2 <= p->keepSizeAfter) - { - if (limit2 > 0) - limit2 = 1; - } - else - limit2 -= p->keepSizeAfter; - if (limit2 < limit) - limit = limit2; - { - UInt32 lenLimit = p->streamPos - p->pos; - if (lenLimit > p->matchMaxLen) - lenLimit = p->matchMaxLen; - p->lenLimit = lenLimit; - } - p->posLimit = p->pos + limit; -} - -void MatchFinder_Init(CMatchFinder *p) -{ - UInt32 i; - for (i = 0; i < p->hashSizeSum; i++) - p->hash[i] = kEmptyHashValue; - p->cyclicBufferPos = 0; - p->buffer = p->bufferBase; - p->pos = p->streamPos = p->cyclicBufferSize; - p->result = SZ_OK; - p->streamEndWasReached = 0; - MatchFinder_ReadBlock(p); - MatchFinder_SetLimits(p); -} - -static UInt32 MatchFinder_GetSubValue(CMatchFinder *p) -{ - return (p->pos - p->historySize - 1) & kNormalizeMask; -} - -void MatchFinder_Normalize3(UInt32 subValue, CLzRef *items, UInt32 numItems) -{ - UInt32 i; - for (i = 0; i < numItems; i++) - { - UInt32 value = items[i]; - if (value <= subValue) - value = kEmptyHashValue; - else - value -= subValue; - items[i] = value; - } -} - -static void MatchFinder_Normalize(CMatchFinder *p) -{ - UInt32 subValue = MatchFinder_GetSubValue(p); - MatchFinder_Normalize3(subValue, p->hash, p->hashSizeSum + p->numSons); - MatchFinder_ReduceOffsets(p, subValue); -} - -static void MatchFinder_CheckLimits(CMatchFinder *p) -{ - if (p->pos == kMaxValForNormalize) - MatchFinder_Normalize(p); - if (!p->streamEndWasReached && p->keepSizeAfter == p->streamPos - p->pos) - MatchFinder_CheckAndMoveAndRead(p); - if (p->cyclicBufferPos == p->cyclicBufferSize) - p->cyclicBufferPos = 0; - MatchFinder_SetLimits(p); -} - -static UInt32 * Hc_GetMatchesSpec(UInt32 lenLimit, UInt32 curMatch, UInt32 pos, const Byte *cur, CLzRef *son, - UInt32 _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 cutValue, - UInt32 *distances, UInt32 maxLen) -{ - son[_cyclicBufferPos] = curMatch; - for (;;) - { - UInt32 delta = pos - curMatch; - if (cutValue-- == 0 || delta >= _cyclicBufferSize) - return distances; - { - const Byte *pb = cur - delta; - curMatch = son[_cyclicBufferPos - delta + ((delta > _cyclicBufferPos) ? _cyclicBufferSize : 0)]; - if (pb[maxLen] == cur[maxLen] && *pb == *cur) - { - UInt32 len = 0; - while (++len != lenLimit) - if (pb[len] != cur[len]) - break; - if (maxLen < len) - { - *distances++ = maxLen = len; - *distances++ = delta - 1; - if (len == lenLimit) - return distances; - } - } - } - } -} - -UInt32 * GetMatchesSpec1(UInt32 lenLimit, UInt32 curMatch, UInt32 pos, const Byte *cur, CLzRef *son, - UInt32 _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 cutValue, - UInt32 *distances, UInt32 maxLen) -{ - CLzRef *ptr0 = son + (_cyclicBufferPos << 1) + 1; - CLzRef *ptr1 = son + (_cyclicBufferPos << 1); - UInt32 len0 = 0, len1 = 0; - for (;;) - { - UInt32 delta = pos - curMatch; - if (cutValue-- == 0 || delta >= _cyclicBufferSize) - { - *ptr0 = *ptr1 = kEmptyHashValue; - return distances; - } - { - CLzRef *pair = son + ((_cyclicBufferPos - delta + ((delta > _cyclicBufferPos) ? _cyclicBufferSize : 0)) << 1); - const Byte *pb = cur - delta; - UInt32 len = (len0 < len1 ? len0 : len1); - if (pb[len] == cur[len]) - { - if (++len != lenLimit && pb[len] == cur[len]) - while (++len != lenLimit) - if (pb[len] != cur[len]) - break; - if (maxLen < len) - { - *distances++ = maxLen = len; - *distances++ = delta - 1; - if (len == lenLimit) - { - *ptr1 = pair[0]; - *ptr0 = pair[1]; - return distances; - } - } - } - if (pb[len] < cur[len]) - { - *ptr1 = curMatch; - ptr1 = pair + 1; - curMatch = *ptr1; - len1 = len; - } - else - { - *ptr0 = curMatch; - ptr0 = pair; - curMatch = *ptr0; - len0 = len; - } - } - } -} - -static void SkipMatchesSpec(UInt32 lenLimit, UInt32 curMatch, UInt32 pos, const Byte *cur, CLzRef *son, - UInt32 _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 cutValue) -{ - CLzRef *ptr0 = son + (_cyclicBufferPos << 1) + 1; - CLzRef *ptr1 = son + (_cyclicBufferPos << 1); - UInt32 len0 = 0, len1 = 0; - for (;;) - { - UInt32 delta = pos - curMatch; - if (cutValue-- == 0 || delta >= _cyclicBufferSize) - { - *ptr0 = *ptr1 = kEmptyHashValue; - return; - } - { - CLzRef *pair = son + ((_cyclicBufferPos - delta + ((delta > _cyclicBufferPos) ? _cyclicBufferSize : 0)) << 1); - const Byte *pb = cur - delta; - UInt32 len = (len0 < len1 ? len0 : len1); - if (pb[len] == cur[len]) - { - while (++len != lenLimit) - if (pb[len] != cur[len]) - break; - { - if (len == lenLimit) - { - *ptr1 = pair[0]; - *ptr0 = pair[1]; - return; - } - } - } - if (pb[len] < cur[len]) - { - *ptr1 = curMatch; - ptr1 = pair + 1; - curMatch = *ptr1; - len1 = len; - } - else - { - *ptr0 = curMatch; - ptr0 = pair; - curMatch = *ptr0; - len0 = len; - } - } - } -} - -#define MOVE_POS \ - ++p->cyclicBufferPos; \ - p->buffer++; \ - if (++p->pos == p->posLimit) MatchFinder_CheckLimits(p); - -#define MOVE_POS_RET MOVE_POS return offset; - -static void MatchFinder_MovePos(CMatchFinder *p) { MOVE_POS; } - -#define GET_MATCHES_HEADER2(minLen, ret_op) \ - UInt32 lenLimit; UInt32 hashValue; const Byte *cur; UInt32 curMatch; \ - lenLimit = p->lenLimit; { if (lenLimit < minLen) { MatchFinder_MovePos(p); ret_op; }} \ - cur = p->buffer; - -#define GET_MATCHES_HEADER(minLen) GET_MATCHES_HEADER2(minLen, return 0) -#define SKIP_HEADER(minLen) GET_MATCHES_HEADER2(minLen, continue) - -#define MF_PARAMS(p) p->pos, p->buffer, p->son, p->cyclicBufferPos, p->cyclicBufferSize, p->cutValue - -#define GET_MATCHES_FOOTER(offset, maxLen) \ - offset = (UInt32)(GetMatchesSpec1(lenLimit, curMatch, MF_PARAMS(p), \ - distances + offset, maxLen) - distances); MOVE_POS_RET; - -#define SKIP_FOOTER \ - SkipMatchesSpec(lenLimit, curMatch, MF_PARAMS(p)); MOVE_POS; - -static UInt32 Bt2_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) -{ - UInt32 offset; - GET_MATCHES_HEADER(2) - HASH2_CALC; - curMatch = p->hash[hashValue]; - p->hash[hashValue] = p->pos; - offset = 0; - GET_MATCHES_FOOTER(offset, 1) -} - -UInt32 Bt3Zip_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) -{ - UInt32 offset; - GET_MATCHES_HEADER(3) - HASH_ZIP_CALC; - curMatch = p->hash[hashValue]; - p->hash[hashValue] = p->pos; - offset = 0; - GET_MATCHES_FOOTER(offset, 2) -} - -static UInt32 Bt3_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) -{ - UInt32 hash2Value, delta2, maxLen, offset; - GET_MATCHES_HEADER(3) - - HASH3_CALC; - - delta2 = p->pos - p->hash[hash2Value]; - curMatch = p->hash[kFix3HashSize + hashValue]; - - p->hash[hash2Value] = - p->hash[kFix3HashSize + hashValue] = p->pos; - - - maxLen = 2; - offset = 0; - if (delta2 < p->cyclicBufferSize && *(cur - delta2) == *cur) - { - for (; maxLen != lenLimit; maxLen++) - if (cur[(ptrdiff_t)maxLen - delta2] != cur[maxLen]) - break; - distances[0] = maxLen; - distances[1] = delta2 - 1; - offset = 2; - if (maxLen == lenLimit) - { - SkipMatchesSpec(lenLimit, curMatch, MF_PARAMS(p)); - MOVE_POS_RET; - } - } - GET_MATCHES_FOOTER(offset, maxLen) -} - -static UInt32 Bt4_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) -{ - UInt32 hash2Value, hash3Value, delta2, delta3, maxLen, offset; - GET_MATCHES_HEADER(4) - - HASH4_CALC; - - delta2 = p->pos - p->hash[ hash2Value]; - delta3 = p->pos - p->hash[kFix3HashSize + hash3Value]; - curMatch = p->hash[kFix4HashSize + hashValue]; - - p->hash[ hash2Value] = - p->hash[kFix3HashSize + hash3Value] = - p->hash[kFix4HashSize + hashValue] = p->pos; - - maxLen = 1; - offset = 0; - if (delta2 < p->cyclicBufferSize && *(cur - delta2) == *cur) - { - distances[0] = maxLen = 2; - distances[1] = delta2 - 1; - offset = 2; - } - if (delta2 != delta3 && delta3 < p->cyclicBufferSize && *(cur - delta3) == *cur) - { - maxLen = 3; - distances[offset + 1] = delta3 - 1; - offset += 2; - delta2 = delta3; - } - if (offset != 0) - { - for (; maxLen != lenLimit; maxLen++) - if (cur[(ptrdiff_t)maxLen - delta2] != cur[maxLen]) - break; - distances[offset - 2] = maxLen; - if (maxLen == lenLimit) - { - SkipMatchesSpec(lenLimit, curMatch, MF_PARAMS(p)); - MOVE_POS_RET; - } - } - if (maxLen < 3) - maxLen = 3; - GET_MATCHES_FOOTER(offset, maxLen) -} - -static UInt32 Hc4_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) -{ - UInt32 hash2Value, hash3Value, delta2, delta3, maxLen, offset; - GET_MATCHES_HEADER(4) - - HASH4_CALC; - - delta2 = p->pos - p->hash[ hash2Value]; - delta3 = p->pos - p->hash[kFix3HashSize + hash3Value]; - curMatch = p->hash[kFix4HashSize + hashValue]; - - p->hash[ hash2Value] = - p->hash[kFix3HashSize + hash3Value] = - p->hash[kFix4HashSize + hashValue] = p->pos; - - maxLen = 1; - offset = 0; - if (delta2 < p->cyclicBufferSize && *(cur - delta2) == *cur) - { - distances[0] = maxLen = 2; - distances[1] = delta2 - 1; - offset = 2; - } - if (delta2 != delta3 && delta3 < p->cyclicBufferSize && *(cur - delta3) == *cur) - { - maxLen = 3; - distances[offset + 1] = delta3 - 1; - offset += 2; - delta2 = delta3; - } - if (offset != 0) - { - for (; maxLen != lenLimit; maxLen++) - if (cur[(ptrdiff_t)maxLen - delta2] != cur[maxLen]) - break; - distances[offset - 2] = maxLen; - if (maxLen == lenLimit) - { - p->son[p->cyclicBufferPos] = curMatch; - MOVE_POS_RET; - } - } - if (maxLen < 3) - maxLen = 3; - offset = (UInt32)(Hc_GetMatchesSpec(lenLimit, curMatch, MF_PARAMS(p), - distances + offset, maxLen) - (distances)); - MOVE_POS_RET -} - -UInt32 Hc3Zip_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) -{ - UInt32 offset; - GET_MATCHES_HEADER(3) - HASH_ZIP_CALC; - curMatch = p->hash[hashValue]; - p->hash[hashValue] = p->pos; - offset = (UInt32)(Hc_GetMatchesSpec(lenLimit, curMatch, MF_PARAMS(p), - distances, 2) - (distances)); - MOVE_POS_RET -} - -static void Bt2_MatchFinder_Skip(CMatchFinder *p, UInt32 num) -{ - do - { - SKIP_HEADER(2) - HASH2_CALC; - curMatch = p->hash[hashValue]; - p->hash[hashValue] = p->pos; - SKIP_FOOTER - } - while (--num != 0); -} - -void Bt3Zip_MatchFinder_Skip(CMatchFinder *p, UInt32 num) -{ - do - { - SKIP_HEADER(3) - HASH_ZIP_CALC; - curMatch = p->hash[hashValue]; - p->hash[hashValue] = p->pos; - SKIP_FOOTER - } - while (--num != 0); -} - -static void Bt3_MatchFinder_Skip(CMatchFinder *p, UInt32 num) -{ - do - { - UInt32 hash2Value; - SKIP_HEADER(3) - HASH3_CALC; - curMatch = p->hash[kFix3HashSize + hashValue]; - p->hash[hash2Value] = - p->hash[kFix3HashSize + hashValue] = p->pos; - SKIP_FOOTER - } - while (--num != 0); -} - -static void Bt4_MatchFinder_Skip(CMatchFinder *p, UInt32 num) -{ - do - { - UInt32 hash2Value, hash3Value; - SKIP_HEADER(4) - HASH4_CALC; - curMatch = p->hash[kFix4HashSize + hashValue]; - p->hash[ hash2Value] = - p->hash[kFix3HashSize + hash3Value] = p->pos; - p->hash[kFix4HashSize + hashValue] = p->pos; - SKIP_FOOTER - } - while (--num != 0); -} - -static void Hc4_MatchFinder_Skip(CMatchFinder *p, UInt32 num) -{ - do - { - UInt32 hash2Value, hash3Value; - SKIP_HEADER(4) - HASH4_CALC; - curMatch = p->hash[kFix4HashSize + hashValue]; - p->hash[ hash2Value] = - p->hash[kFix3HashSize + hash3Value] = - p->hash[kFix4HashSize + hashValue] = p->pos; - p->son[p->cyclicBufferPos] = curMatch; - MOVE_POS - } - while (--num != 0); -} - -void Hc3Zip_MatchFinder_Skip(CMatchFinder *p, UInt32 num) -{ - do - { - SKIP_HEADER(3) - HASH_ZIP_CALC; - curMatch = p->hash[hashValue]; - p->hash[hashValue] = p->pos; - p->son[p->cyclicBufferPos] = curMatch; - MOVE_POS - } - while (--num != 0); -} - -void MatchFinder_CreateVTable(CMatchFinder *p, IMatchFinder *vTable) -{ - vTable->Init = (Mf_Init_Func)MatchFinder_Init; - vTable->GetIndexByte = (Mf_GetIndexByte_Func)MatchFinder_GetIndexByte; - vTable->GetNumAvailableBytes = (Mf_GetNumAvailableBytes_Func)MatchFinder_GetNumAvailableBytes; - vTable->GetPointerToCurrentPos = (Mf_GetPointerToCurrentPos_Func)MatchFinder_GetPointerToCurrentPos; - if (!p->btMode) - { - vTable->GetMatches = (Mf_GetMatches_Func)Hc4_MatchFinder_GetMatches; - vTable->Skip = (Mf_Skip_Func)Hc4_MatchFinder_Skip; - } - else if (p->numHashBytes == 2) - { - vTable->GetMatches = (Mf_GetMatches_Func)Bt2_MatchFinder_GetMatches; - vTable->Skip = (Mf_Skip_Func)Bt2_MatchFinder_Skip; - } - else if (p->numHashBytes == 3) - { - vTable->GetMatches = (Mf_GetMatches_Func)Bt3_MatchFinder_GetMatches; - vTable->Skip = (Mf_Skip_Func)Bt3_MatchFinder_Skip; - } - else - { - vTable->GetMatches = (Mf_GetMatches_Func)Bt4_MatchFinder_GetMatches; - vTable->Skip = (Mf_Skip_Func)Bt4_MatchFinder_Skip; - } -} diff --git a/desmume/src/windows/7z/C/LzFind.h b/desmume/src/windows/7z/C/LzFind.h deleted file mode 100644 index 423d67e0c..000000000 --- a/desmume/src/windows/7z/C/LzFind.h +++ /dev/null @@ -1,107 +0,0 @@ -/* LzFind.h -- Match finder for LZ algorithms -2008-10-04 : Igor Pavlov : Public domain */ - -#ifndef __LZFIND_H -#define __LZFIND_H - -#include "Types.h" - -typedef UInt32 CLzRef; - -typedef struct _CMatchFinder -{ - Byte *buffer; - UInt32 pos; - UInt32 posLimit; - UInt32 streamPos; - UInt32 lenLimit; - - UInt32 cyclicBufferPos; - UInt32 cyclicBufferSize; /* it must be = (historySize + 1) */ - - UInt32 matchMaxLen; - CLzRef *hash; - CLzRef *son; - UInt32 hashMask; - UInt32 cutValue; - - Byte *bufferBase; - ISeqInStream *stream; - int streamEndWasReached; - - UInt32 blockSize; - UInt32 keepSizeBefore; - UInt32 keepSizeAfter; - - UInt32 numHashBytes; - int directInput; - int btMode; - /* int skipModeBits; */ - int bigHash; - UInt32 historySize; - UInt32 fixedHashSize; - UInt32 hashSizeSum; - UInt32 numSons; - SRes result; - UInt32 crc[256]; -} CMatchFinder; - -#define Inline_MatchFinder_GetPointerToCurrentPos(p) ((p)->buffer) -#define Inline_MatchFinder_GetIndexByte(p, index) ((p)->buffer[(Int32)(index)]) - -#define Inline_MatchFinder_GetNumAvailableBytes(p) ((p)->streamPos - (p)->pos) - -int MatchFinder_NeedMove(CMatchFinder *p); -Byte *MatchFinder_GetPointerToCurrentPos(CMatchFinder *p); -void MatchFinder_MoveBlock(CMatchFinder *p); -void MatchFinder_ReadIfRequired(CMatchFinder *p); - -void MatchFinder_Construct(CMatchFinder *p); - -/* Conditions: - historySize <= 3 GB - keepAddBufferBefore + matchMaxLen + keepAddBufferAfter < 511MB -*/ -int MatchFinder_Create(CMatchFinder *p, UInt32 historySize, - UInt32 keepAddBufferBefore, UInt32 matchMaxLen, UInt32 keepAddBufferAfter, - ISzAlloc *alloc); -void MatchFinder_Free(CMatchFinder *p, ISzAlloc *alloc); -void MatchFinder_Normalize3(UInt32 subValue, CLzRef *items, UInt32 numItems); -void MatchFinder_ReduceOffsets(CMatchFinder *p, UInt32 subValue); - -UInt32 * GetMatchesSpec1(UInt32 lenLimit, UInt32 curMatch, UInt32 pos, const Byte *buffer, CLzRef *son, - UInt32 _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 _cutValue, - UInt32 *distances, UInt32 maxLen); - -/* -Conditions: - Mf_GetNumAvailableBytes_Func must be called before each Mf_GetMatchLen_Func. - Mf_GetPointerToCurrentPos_Func's result must be used only before any other function -*/ - -typedef void (*Mf_Init_Func)(void *object); -typedef Byte (*Mf_GetIndexByte_Func)(void *object, Int32 index); -typedef UInt32 (*Mf_GetNumAvailableBytes_Func)(void *object); -typedef const Byte * (*Mf_GetPointerToCurrentPos_Func)(void *object); -typedef UInt32 (*Mf_GetMatches_Func)(void *object, UInt32 *distances); -typedef void (*Mf_Skip_Func)(void *object, UInt32); - -typedef struct _IMatchFinder -{ - Mf_Init_Func Init; - Mf_GetIndexByte_Func GetIndexByte; - Mf_GetNumAvailableBytes_Func GetNumAvailableBytes; - Mf_GetPointerToCurrentPos_Func GetPointerToCurrentPos; - Mf_GetMatches_Func GetMatches; - Mf_Skip_Func Skip; -} IMatchFinder; - -void MatchFinder_CreateVTable(CMatchFinder *p, IMatchFinder *vTable); - -void MatchFinder_Init(CMatchFinder *p); -UInt32 Bt3Zip_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances); -UInt32 Hc3Zip_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances); -void Bt3Zip_MatchFinder_Skip(CMatchFinder *p, UInt32 num); -void Hc3Zip_MatchFinder_Skip(CMatchFinder *p, UInt32 num); - -#endif diff --git a/desmume/src/windows/7z/C/LzFindMt.c b/desmume/src/windows/7z/C/LzFindMt.c deleted file mode 100644 index 0ef134735..000000000 --- a/desmume/src/windows/7z/C/LzFindMt.c +++ /dev/null @@ -1,793 +0,0 @@ -/* LzFindMt.c -- multithreaded Match finder for LZ algorithms -2008-10-04 : Igor Pavlov : Public domain */ - -#include "LzHash.h" - -#include "LzFindMt.h" - -void MtSync_Construct(CMtSync *p) -{ - p->wasCreated = False; - p->csWasInitialized = False; - p->csWasEntered = False; - Thread_Construct(&p->thread); - Event_Construct(&p->canStart); - Event_Construct(&p->wasStarted); - Event_Construct(&p->wasStopped); - Semaphore_Construct(&p->freeSemaphore); - Semaphore_Construct(&p->filledSemaphore); -} - -void MtSync_GetNextBlock(CMtSync *p) -{ - if (p->needStart) - { - p->numProcessedBlocks = 1; - p->needStart = False; - p->stopWriting = False; - p->exit = False; - Event_Reset(&p->wasStarted); - Event_Reset(&p->wasStopped); - - Event_Set(&p->canStart); - Event_Wait(&p->wasStarted); - } - else - { - CriticalSection_Leave(&p->cs); - p->csWasEntered = False; - p->numProcessedBlocks++; - Semaphore_Release1(&p->freeSemaphore); - } - Semaphore_Wait(&p->filledSemaphore); - CriticalSection_Enter(&p->cs); - p->csWasEntered = True; -} - -/* MtSync_StopWriting must be called if Writing was started */ - -void MtSync_StopWriting(CMtSync *p) -{ - UInt32 myNumBlocks = p->numProcessedBlocks; - if (!Thread_WasCreated(&p->thread) || p->needStart) - return; - p->stopWriting = True; - if (p->csWasEntered) - { - CriticalSection_Leave(&p->cs); - p->csWasEntered = False; - } - Semaphore_Release1(&p->freeSemaphore); - - Event_Wait(&p->wasStopped); - - while (myNumBlocks++ != p->numProcessedBlocks) - { - Semaphore_Wait(&p->filledSemaphore); - Semaphore_Release1(&p->freeSemaphore); - } - p->needStart = True; -} - -void MtSync_Destruct(CMtSync *p) -{ - if (Thread_WasCreated(&p->thread)) - { - MtSync_StopWriting(p); - p->exit = True; - if (p->needStart) - Event_Set(&p->canStart); - Thread_Wait(&p->thread); - Thread_Close(&p->thread); - } - if (p->csWasInitialized) - { - CriticalSection_Delete(&p->cs); - p->csWasInitialized = False; - } - - Event_Close(&p->canStart); - Event_Close(&p->wasStarted); - Event_Close(&p->wasStopped); - Semaphore_Close(&p->freeSemaphore); - Semaphore_Close(&p->filledSemaphore); - - p->wasCreated = False; -} - -#define RINOK_THREAD(x) { if ((x) != 0) return SZ_ERROR_THREAD; } - -static SRes MtSync_Create2(CMtSync *p, unsigned (MY_STD_CALL *startAddress)(void *), void *obj, UInt32 numBlocks) -{ - if (p->wasCreated) - return SZ_OK; - - RINOK_THREAD(CriticalSection_Init(&p->cs)); - p->csWasInitialized = True; - - RINOK_THREAD(AutoResetEvent_CreateNotSignaled(&p->canStart)); - RINOK_THREAD(AutoResetEvent_CreateNotSignaled(&p->wasStarted)); - RINOK_THREAD(AutoResetEvent_CreateNotSignaled(&p->wasStopped)); - - RINOK_THREAD(Semaphore_Create(&p->freeSemaphore, numBlocks, numBlocks)); - RINOK_THREAD(Semaphore_Create(&p->filledSemaphore, 0, numBlocks)); - - p->needStart = True; - - RINOK_THREAD(Thread_Create(&p->thread, startAddress, obj)); - p->wasCreated = True; - return SZ_OK; -} - -static SRes MtSync_Create(CMtSync *p, unsigned (MY_STD_CALL *startAddress)(void *), void *obj, UInt32 numBlocks) -{ - SRes res = MtSync_Create2(p, startAddress, obj, numBlocks); - if (res != SZ_OK) - MtSync_Destruct(p); - return res; -} - -void MtSync_Init(CMtSync *p) { p->needStart = True; } - -#define kMtMaxValForNormalize 0xFFFFFFFF - -#define DEF_GetHeads2(name, v, action) \ -static void GetHeads ## name(const Byte *p, UInt32 pos, \ -UInt32 *hash, UInt32 hashMask, UInt32 *heads, UInt32 numHeads, const UInt32 *crc) \ -{ action; for (; numHeads != 0; numHeads--) { \ -const UInt32 value = (v); p++; *heads++ = pos - hash[value]; hash[value] = pos++; } } - -#define DEF_GetHeads(name, v) DEF_GetHeads2(name, v, ;) - -DEF_GetHeads2(2, (p[0] | ((UInt32)p[1] << 8)), hashMask = hashMask; crc = crc; ) -DEF_GetHeads(3, (crc[p[0]] ^ p[1] ^ ((UInt32)p[2] << 8)) & hashMask) -DEF_GetHeads(4, (crc[p[0]] ^ p[1] ^ ((UInt32)p[2] << 8) ^ (crc[p[3]] << 5)) & hashMask) -DEF_GetHeads(4b, (crc[p[0]] ^ p[1] ^ ((UInt32)p[2] << 8) ^ ((UInt32)p[3] << 16)) & hashMask) -DEF_GetHeads(5, (crc[p[0]] ^ p[1] ^ ((UInt32)p[2] << 8) ^ (crc[p[3]] << 5) ^ (crc[p[4]] << 3)) & hashMask) - -void HashThreadFunc(CMatchFinderMt *mt) -{ - CMtSync *p = &mt->hashSync; - for (;;) - { - UInt32 numProcessedBlocks = 0; - Event_Wait(&p->canStart); - Event_Set(&p->wasStarted); - for (;;) - { - if (p->exit) - return; - if (p->stopWriting) - { - p->numProcessedBlocks = numProcessedBlocks; - Event_Set(&p->wasStopped); - break; - } - - { - CMatchFinder *mf = mt->MatchFinder; - if (MatchFinder_NeedMove(mf)) - { - CriticalSection_Enter(&mt->btSync.cs); - CriticalSection_Enter(&mt->hashSync.cs); - { - const Byte *beforePtr = MatchFinder_GetPointerToCurrentPos(mf); - const Byte *afterPtr; - MatchFinder_MoveBlock(mf); - afterPtr = MatchFinder_GetPointerToCurrentPos(mf); - mt->pointerToCurPos -= beforePtr - afterPtr; - mt->buffer -= beforePtr - afterPtr; - } - CriticalSection_Leave(&mt->btSync.cs); - CriticalSection_Leave(&mt->hashSync.cs); - continue; - } - - Semaphore_Wait(&p->freeSemaphore); - - MatchFinder_ReadIfRequired(mf); - if (mf->pos > (kMtMaxValForNormalize - kMtHashBlockSize)) - { - UInt32 subValue = (mf->pos - mf->historySize - 1); - MatchFinder_ReduceOffsets(mf, subValue); - MatchFinder_Normalize3(subValue, mf->hash + mf->fixedHashSize, mf->hashMask + 1); - } - { - UInt32 *heads = mt->hashBuf + ((numProcessedBlocks++) & kMtHashNumBlocksMask) * kMtHashBlockSize; - UInt32 num = mf->streamPos - mf->pos; - heads[0] = 2; - heads[1] = num; - if (num >= mf->numHashBytes) - { - num = num - mf->numHashBytes + 1; - if (num > kMtHashBlockSize - 2) - num = kMtHashBlockSize - 2; - mt->GetHeadsFunc(mf->buffer, mf->pos, mf->hash + mf->fixedHashSize, mf->hashMask, heads + 2, num, mf->crc); - heads[0] += num; - } - mf->pos += num; - mf->buffer += num; - } - } - - Semaphore_Release1(&p->filledSemaphore); - } - } -} - -void MatchFinderMt_GetNextBlock_Hash(CMatchFinderMt *p) -{ - MtSync_GetNextBlock(&p->hashSync); - p->hashBufPosLimit = p->hashBufPos = ((p->hashSync.numProcessedBlocks - 1) & kMtHashNumBlocksMask) * kMtHashBlockSize; - p->hashBufPosLimit += p->hashBuf[p->hashBufPos++]; - p->hashNumAvail = p->hashBuf[p->hashBufPos++]; -} - -#define kEmptyHashValue 0 - -/* #define MFMT_GM_INLINE */ - -#ifdef MFMT_GM_INLINE - -#define NO_INLINE MY_FAST_CALL - -Int32 NO_INLINE GetMatchesSpecN(UInt32 lenLimit, UInt32 pos, const Byte *cur, CLzRef *son, - UInt32 _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 _cutValue, - UInt32 *_distances, UInt32 _maxLen, const UInt32 *hash, Int32 limit, UInt32 size, UInt32 *posRes) -{ - do - { - UInt32 *distances = _distances + 1; - UInt32 curMatch = pos - *hash++; - - CLzRef *ptr0 = son + (_cyclicBufferPos << 1) + 1; - CLzRef *ptr1 = son + (_cyclicBufferPos << 1); - UInt32 len0 = 0, len1 = 0; - UInt32 cutValue = _cutValue; - UInt32 maxLen = _maxLen; - for (;;) - { - UInt32 delta = pos - curMatch; - if (cutValue-- == 0 || delta >= _cyclicBufferSize) - { - *ptr0 = *ptr1 = kEmptyHashValue; - break; - } - { - CLzRef *pair = son + ((_cyclicBufferPos - delta + ((delta > _cyclicBufferPos) ? _cyclicBufferSize : 0)) << 1); - const Byte *pb = cur - delta; - UInt32 len = (len0 < len1 ? len0 : len1); - if (pb[len] == cur[len]) - { - if (++len != lenLimit && pb[len] == cur[len]) - while (++len != lenLimit) - if (pb[len] != cur[len]) - break; - if (maxLen < len) - { - *distances++ = maxLen = len; - *distances++ = delta - 1; - if (len == lenLimit) - { - *ptr1 = pair[0]; - *ptr0 = pair[1]; - break; - } - } - } - if (pb[len] < cur[len]) - { - *ptr1 = curMatch; - ptr1 = pair + 1; - curMatch = *ptr1; - len1 = len; - } - else - { - *ptr0 = curMatch; - ptr0 = pair; - curMatch = *ptr0; - len0 = len; - } - } - } - pos++; - _cyclicBufferPos++; - cur++; - { - UInt32 num = (UInt32)(distances - _distances); - *_distances = num - 1; - _distances += num; - limit -= num; - } - } - while (limit > 0 && --size != 0); - *posRes = pos; - return limit; -} - -#endif - -void BtGetMatches(CMatchFinderMt *p, UInt32 *distances) -{ - UInt32 numProcessed = 0; - UInt32 curPos = 2; - UInt32 limit = kMtBtBlockSize - (p->matchMaxLen * 2); - distances[1] = p->hashNumAvail; - while (curPos < limit) - { - if (p->hashBufPos == p->hashBufPosLimit) - { - MatchFinderMt_GetNextBlock_Hash(p); - distances[1] = numProcessed + p->hashNumAvail; - if (p->hashNumAvail >= p->numHashBytes) - continue; - for (; p->hashNumAvail != 0; p->hashNumAvail--) - distances[curPos++] = 0; - break; - } - { - UInt32 size = p->hashBufPosLimit - p->hashBufPos; - UInt32 lenLimit = p->matchMaxLen; - UInt32 pos = p->pos; - UInt32 cyclicBufferPos = p->cyclicBufferPos; - if (lenLimit >= p->hashNumAvail) - lenLimit = p->hashNumAvail; - { - UInt32 size2 = p->hashNumAvail - lenLimit + 1; - if (size2 < size) - size = size2; - size2 = p->cyclicBufferSize - cyclicBufferPos; - if (size2 < size) - size = size2; - } - #ifndef MFMT_GM_INLINE - while (curPos < limit && size-- != 0) - { - UInt32 *startDistances = distances + curPos; - UInt32 num = (UInt32)(GetMatchesSpec1(lenLimit, pos - p->hashBuf[p->hashBufPos++], - pos, p->buffer, p->son, cyclicBufferPos, p->cyclicBufferSize, p->cutValue, - startDistances + 1, p->numHashBytes - 1) - startDistances); - *startDistances = num - 1; - curPos += num; - cyclicBufferPos++; - pos++; - p->buffer++; - } - #else - { - UInt32 posRes; - curPos = limit - GetMatchesSpecN(lenLimit, pos, p->buffer, p->son, cyclicBufferPos, p->cyclicBufferSize, p->cutValue, - distances + curPos, p->numHashBytes - 1, p->hashBuf + p->hashBufPos, (Int32)(limit - curPos) , size, &posRes); - p->hashBufPos += posRes - pos; - cyclicBufferPos += posRes - pos; - p->buffer += posRes - pos; - pos = posRes; - } - #endif - - numProcessed += pos - p->pos; - p->hashNumAvail -= pos - p->pos; - p->pos = pos; - if (cyclicBufferPos == p->cyclicBufferSize) - cyclicBufferPos = 0; - p->cyclicBufferPos = cyclicBufferPos; - } - } - distances[0] = curPos; -} - -void BtFillBlock(CMatchFinderMt *p, UInt32 globalBlockIndex) -{ - CMtSync *sync = &p->hashSync; - if (!sync->needStart) - { - CriticalSection_Enter(&sync->cs); - sync->csWasEntered = True; - } - - BtGetMatches(p, p->btBuf + (globalBlockIndex & kMtBtNumBlocksMask) * kMtBtBlockSize); - - if (p->pos > kMtMaxValForNormalize - kMtBtBlockSize) - { - UInt32 subValue = p->pos - p->cyclicBufferSize; - MatchFinder_Normalize3(subValue, p->son, p->cyclicBufferSize * 2); - p->pos -= subValue; - } - - if (!sync->needStart) - { - CriticalSection_Leave(&sync->cs); - sync->csWasEntered = False; - } -} - -void BtThreadFunc(CMatchFinderMt *mt) -{ - CMtSync *p = &mt->btSync; - for (;;) - { - UInt32 blockIndex = 0; - Event_Wait(&p->canStart); - Event_Set(&p->wasStarted); - for (;;) - { - if (p->exit) - return; - if (p->stopWriting) - { - p->numProcessedBlocks = blockIndex; - MtSync_StopWriting(&mt->hashSync); - Event_Set(&p->wasStopped); - break; - } - Semaphore_Wait(&p->freeSemaphore); - BtFillBlock(mt, blockIndex++); - Semaphore_Release1(&p->filledSemaphore); - } - } -} - -void MatchFinderMt_Construct(CMatchFinderMt *p) -{ - p->hashBuf = 0; - MtSync_Construct(&p->hashSync); - MtSync_Construct(&p->btSync); -} - -void MatchFinderMt_FreeMem(CMatchFinderMt *p, ISzAlloc *alloc) -{ - alloc->Free(alloc, p->hashBuf); - p->hashBuf = 0; -} - -void MatchFinderMt_Destruct(CMatchFinderMt *p, ISzAlloc *alloc) -{ - MtSync_Destruct(&p->hashSync); - MtSync_Destruct(&p->btSync); - MatchFinderMt_FreeMem(p, alloc); -} - -#define kHashBufferSize (kMtHashBlockSize * kMtHashNumBlocks) -#define kBtBufferSize (kMtBtBlockSize * kMtBtNumBlocks) - -static unsigned MY_STD_CALL HashThreadFunc2(void *p) { HashThreadFunc((CMatchFinderMt *)p); return 0; } -static unsigned MY_STD_CALL BtThreadFunc2(void *p) -{ - Byte allocaDummy[0x180]; - int i = 0; - for (i = 0; i < 16; i++) - allocaDummy[i] = (Byte)i; - BtThreadFunc((CMatchFinderMt *)p); - return 0; -} - -SRes MatchFinderMt_Create(CMatchFinderMt *p, UInt32 historySize, UInt32 keepAddBufferBefore, - UInt32 matchMaxLen, UInt32 keepAddBufferAfter, ISzAlloc *alloc) -{ - CMatchFinder *mf = p->MatchFinder; - p->historySize = historySize; - if (kMtBtBlockSize <= matchMaxLen * 4) - return SZ_ERROR_PARAM; - if (p->hashBuf == 0) - { - p->hashBuf = (UInt32 *)alloc->Alloc(alloc, (kHashBufferSize + kBtBufferSize) * sizeof(UInt32)); - if (p->hashBuf == 0) - return SZ_ERROR_MEM; - p->btBuf = p->hashBuf + kHashBufferSize; - } - keepAddBufferBefore += (kHashBufferSize + kBtBufferSize); - keepAddBufferAfter += kMtHashBlockSize; - if (!MatchFinder_Create(mf, historySize, keepAddBufferBefore, matchMaxLen, keepAddBufferAfter, alloc)) - return SZ_ERROR_MEM; - - RINOK(MtSync_Create(&p->hashSync, HashThreadFunc2, p, kMtHashNumBlocks)); - RINOK(MtSync_Create(&p->btSync, BtThreadFunc2, p, kMtBtNumBlocks)); - return SZ_OK; -} - -/* Call it after ReleaseStream / SetStream */ -void MatchFinderMt_Init(CMatchFinderMt *p) -{ - CMatchFinder *mf = p->MatchFinder; - p->btBufPos = p->btBufPosLimit = 0; - p->hashBufPos = p->hashBufPosLimit = 0; - MatchFinder_Init(mf); - p->pointerToCurPos = MatchFinder_GetPointerToCurrentPos(mf); - p->btNumAvailBytes = 0; - p->lzPos = p->historySize + 1; - - p->hash = mf->hash; - p->fixedHashSize = mf->fixedHashSize; - p->crc = mf->crc; - - p->son = mf->son; - p->matchMaxLen = mf->matchMaxLen; - p->numHashBytes = mf->numHashBytes; - p->pos = mf->pos; - p->buffer = mf->buffer; - p->cyclicBufferPos = mf->cyclicBufferPos; - p->cyclicBufferSize = mf->cyclicBufferSize; - p->cutValue = mf->cutValue; -} - -/* ReleaseStream is required to finish multithreading */ -void MatchFinderMt_ReleaseStream(CMatchFinderMt *p) -{ - MtSync_StopWriting(&p->btSync); - /* p->MatchFinder->ReleaseStream(); */ -} - -void MatchFinderMt_Normalize(CMatchFinderMt *p) -{ - MatchFinder_Normalize3(p->lzPos - p->historySize - 1, p->hash, p->fixedHashSize); - p->lzPos = p->historySize + 1; -} - -void MatchFinderMt_GetNextBlock_Bt(CMatchFinderMt *p) -{ - UInt32 blockIndex; - MtSync_GetNextBlock(&p->btSync); - blockIndex = ((p->btSync.numProcessedBlocks - 1) & kMtBtNumBlocksMask); - p->btBufPosLimit = p->btBufPos = blockIndex * kMtBtBlockSize; - p->btBufPosLimit += p->btBuf[p->btBufPos++]; - p->btNumAvailBytes = p->btBuf[p->btBufPos++]; - if (p->lzPos >= kMtMaxValForNormalize - kMtBtBlockSize) - MatchFinderMt_Normalize(p); -} - -const Byte * MatchFinderMt_GetPointerToCurrentPos(CMatchFinderMt *p) -{ - return p->pointerToCurPos; -} - -#define GET_NEXT_BLOCK_IF_REQUIRED if (p->btBufPos == p->btBufPosLimit) MatchFinderMt_GetNextBlock_Bt(p); - -UInt32 MatchFinderMt_GetNumAvailableBytes(CMatchFinderMt *p) -{ - GET_NEXT_BLOCK_IF_REQUIRED; - return p->btNumAvailBytes; -} - -Byte MatchFinderMt_GetIndexByte(CMatchFinderMt *p, Int32 index) -{ - return p->pointerToCurPos[index]; -} - -UInt32 * MixMatches2(CMatchFinderMt *p, UInt32 matchMinPos, UInt32 *distances) -{ - UInt32 hash2Value, curMatch2; - UInt32 *hash = p->hash; - const Byte *cur = p->pointerToCurPos; - UInt32 lzPos = p->lzPos; - MT_HASH2_CALC - - curMatch2 = hash[hash2Value]; - hash[hash2Value] = lzPos; - - if (curMatch2 >= matchMinPos) - if (cur[(ptrdiff_t)curMatch2 - lzPos] == cur[0]) - { - *distances++ = 2; - *distances++ = lzPos - curMatch2 - 1; - } - return distances; -} - -UInt32 * MixMatches3(CMatchFinderMt *p, UInt32 matchMinPos, UInt32 *distances) -{ - UInt32 hash2Value, hash3Value, curMatch2, curMatch3; - UInt32 *hash = p->hash; - const Byte *cur = p->pointerToCurPos; - UInt32 lzPos = p->lzPos; - MT_HASH3_CALC - - curMatch2 = hash[ hash2Value]; - curMatch3 = hash[kFix3HashSize + hash3Value]; - - hash[ hash2Value] = - hash[kFix3HashSize + hash3Value] = - lzPos; - - if (curMatch2 >= matchMinPos && cur[(ptrdiff_t)curMatch2 - lzPos] == cur[0]) - { - distances[1] = lzPos - curMatch2 - 1; - if (cur[(ptrdiff_t)curMatch2 - lzPos + 2] == cur[2]) - { - distances[0] = 3; - return distances + 2; - } - distances[0] = 2; - distances += 2; - } - if (curMatch3 >= matchMinPos && cur[(ptrdiff_t)curMatch3 - lzPos] == cur[0]) - { - *distances++ = 3; - *distances++ = lzPos - curMatch3 - 1; - } - return distances; -} - -/* -UInt32 *MixMatches4(CMatchFinderMt *p, UInt32 matchMinPos, UInt32 *distances) -{ - UInt32 hash2Value, hash3Value, hash4Value, curMatch2, curMatch3, curMatch4; - UInt32 *hash = p->hash; - const Byte *cur = p->pointerToCurPos; - UInt32 lzPos = p->lzPos; - MT_HASH4_CALC - - curMatch2 = hash[ hash2Value]; - curMatch3 = hash[kFix3HashSize + hash3Value]; - curMatch4 = hash[kFix4HashSize + hash4Value]; - - hash[ hash2Value] = - hash[kFix3HashSize + hash3Value] = - hash[kFix4HashSize + hash4Value] = - lzPos; - - if (curMatch2 >= matchMinPos && cur[(ptrdiff_t)curMatch2 - lzPos] == cur[0]) - { - distances[1] = lzPos - curMatch2 - 1; - if (cur[(ptrdiff_t)curMatch2 - lzPos + 2] == cur[2]) - { - distances[0] = (cur[(ptrdiff_t)curMatch2 - lzPos + 3] == cur[3]) ? 4 : 3; - return distances + 2; - } - distances[0] = 2; - distances += 2; - } - if (curMatch3 >= matchMinPos && cur[(ptrdiff_t)curMatch3 - lzPos] == cur[0]) - { - distances[1] = lzPos - curMatch3 - 1; - if (cur[(ptrdiff_t)curMatch3 - lzPos + 3] == cur[3]) - { - distances[0] = 4; - return distances + 2; - } - distances[0] = 3; - distances += 2; - } - - if (curMatch4 >= matchMinPos) - if ( - cur[(ptrdiff_t)curMatch4 - lzPos] == cur[0] && - cur[(ptrdiff_t)curMatch4 - lzPos + 3] == cur[3] - ) - { - *distances++ = 4; - *distances++ = lzPos - curMatch4 - 1; - } - return distances; -} -*/ - -#define INCREASE_LZ_POS p->lzPos++; p->pointerToCurPos++; - -UInt32 MatchFinderMt2_GetMatches(CMatchFinderMt *p, UInt32 *distances) -{ - const UInt32 *btBuf = p->btBuf + p->btBufPos; - UInt32 len = *btBuf++; - p->btBufPos += 1 + len; - p->btNumAvailBytes--; - { - UInt32 i; - for (i = 0; i < len; i += 2) - { - *distances++ = *btBuf++; - *distances++ = *btBuf++; - } - } - INCREASE_LZ_POS - return len; -} - -UInt32 MatchFinderMt_GetMatches(CMatchFinderMt *p, UInt32 *distances) -{ - const UInt32 *btBuf = p->btBuf + p->btBufPos; - UInt32 len = *btBuf++; - p->btBufPos += 1 + len; - - if (len == 0) - { - if (p->btNumAvailBytes-- >= 4) - len = (UInt32)(p->MixMatchesFunc(p, p->lzPos - p->historySize, distances) - (distances)); - } - else - { - /* Condition: there are matches in btBuf with length < p->numHashBytes */ - UInt32 *distances2; - p->btNumAvailBytes--; - distances2 = p->MixMatchesFunc(p, p->lzPos - btBuf[1], distances); - do - { - *distances2++ = *btBuf++; - *distances2++ = *btBuf++; - } - while ((len -= 2) != 0); - len = (UInt32)(distances2 - (distances)); - } - INCREASE_LZ_POS - return len; -} - -#define SKIP_HEADER2 do { GET_NEXT_BLOCK_IF_REQUIRED -#define SKIP_HEADER(n) SKIP_HEADER2 if (p->btNumAvailBytes-- >= (n)) { const Byte *cur = p->pointerToCurPos; UInt32 *hash = p->hash; -#define SKIP_FOOTER } INCREASE_LZ_POS p->btBufPos += p->btBuf[p->btBufPos] + 1; } while (--num != 0); - -void MatchFinderMt0_Skip(CMatchFinderMt *p, UInt32 num) -{ - SKIP_HEADER2 { p->btNumAvailBytes--; - SKIP_FOOTER -} - -void MatchFinderMt2_Skip(CMatchFinderMt *p, UInt32 num) -{ - SKIP_HEADER(2) - UInt32 hash2Value; - MT_HASH2_CALC - hash[hash2Value] = p->lzPos; - SKIP_FOOTER -} - -void MatchFinderMt3_Skip(CMatchFinderMt *p, UInt32 num) -{ - SKIP_HEADER(3) - UInt32 hash2Value, hash3Value; - MT_HASH3_CALC - hash[kFix3HashSize + hash3Value] = - hash[ hash2Value] = - p->lzPos; - SKIP_FOOTER -} - -/* -void MatchFinderMt4_Skip(CMatchFinderMt *p, UInt32 num) -{ - SKIP_HEADER(4) - UInt32 hash2Value, hash3Value, hash4Value; - MT_HASH4_CALC - hash[kFix4HashSize + hash4Value] = - hash[kFix3HashSize + hash3Value] = - hash[ hash2Value] = - p->lzPos; - SKIP_FOOTER -} -*/ - -void MatchFinderMt_CreateVTable(CMatchFinderMt *p, IMatchFinder *vTable) -{ - vTable->Init = (Mf_Init_Func)MatchFinderMt_Init; - vTable->GetIndexByte = (Mf_GetIndexByte_Func)MatchFinderMt_GetIndexByte; - vTable->GetNumAvailableBytes = (Mf_GetNumAvailableBytes_Func)MatchFinderMt_GetNumAvailableBytes; - vTable->GetPointerToCurrentPos = (Mf_GetPointerToCurrentPos_Func)MatchFinderMt_GetPointerToCurrentPos; - vTable->GetMatches = (Mf_GetMatches_Func)MatchFinderMt_GetMatches; - switch(p->MatchFinder->numHashBytes) - { - case 2: - p->GetHeadsFunc = GetHeads2; - p->MixMatchesFunc = (Mf_Mix_Matches)0; - vTable->Skip = (Mf_Skip_Func)MatchFinderMt0_Skip; - vTable->GetMatches = (Mf_GetMatches_Func)MatchFinderMt2_GetMatches; - break; - case 3: - p->GetHeadsFunc = GetHeads3; - p->MixMatchesFunc = (Mf_Mix_Matches)MixMatches2; - vTable->Skip = (Mf_Skip_Func)MatchFinderMt2_Skip; - break; - default: - /* case 4: */ - p->GetHeadsFunc = p->MatchFinder->bigHash ? GetHeads4b : GetHeads4; - /* p->GetHeadsFunc = GetHeads4; */ - p->MixMatchesFunc = (Mf_Mix_Matches)MixMatches3; - vTable->Skip = (Mf_Skip_Func)MatchFinderMt3_Skip; - break; - /* - default: - p->GetHeadsFunc = GetHeads5; - p->MixMatchesFunc = (Mf_Mix_Matches)MixMatches4; - vTable->Skip = (Mf_Skip_Func)MatchFinderMt4_Skip; - break; - */ - } -} diff --git a/desmume/src/windows/7z/C/LzFindMt.h b/desmume/src/windows/7z/C/LzFindMt.h deleted file mode 100644 index b7ead2d47..000000000 --- a/desmume/src/windows/7z/C/LzFindMt.h +++ /dev/null @@ -1,97 +0,0 @@ -/* LzFindMt.h -- multithreaded Match finder for LZ algorithms -2008-10-04 : Igor Pavlov : Public domain */ - -#ifndef __LZFINDMT_H -#define __LZFINDMT_H - -#include "Threads.h" -#include "LzFind.h" - -#define kMtHashBlockSize (1 << 13) -#define kMtHashNumBlocks (1 << 3) -#define kMtHashNumBlocksMask (kMtHashNumBlocks - 1) - -#define kMtBtBlockSize (1 << 14) -#define kMtBtNumBlocks (1 << 6) -#define kMtBtNumBlocksMask (kMtBtNumBlocks - 1) - -typedef struct _CMtSync -{ - Bool wasCreated; - Bool needStart; - Bool exit; - Bool stopWriting; - - CThread thread; - CAutoResetEvent canStart; - CAutoResetEvent wasStarted; - CAutoResetEvent wasStopped; - CSemaphore freeSemaphore; - CSemaphore filledSemaphore; - Bool csWasInitialized; - Bool csWasEntered; - CCriticalSection cs; - UInt32 numProcessedBlocks; -} CMtSync; - -typedef UInt32 * (*Mf_Mix_Matches)(void *p, UInt32 matchMinPos, UInt32 *distances); - -/* kMtCacheLineDummy must be >= size_of_CPU_cache_line */ -#define kMtCacheLineDummy 128 - -typedef void (*Mf_GetHeads)(const Byte *buffer, UInt32 pos, - UInt32 *hash, UInt32 hashMask, UInt32 *heads, UInt32 numHeads, const UInt32 *crc); - -typedef struct _CMatchFinderMt -{ - /* LZ */ - const Byte *pointerToCurPos; - UInt32 *btBuf; - UInt32 btBufPos; - UInt32 btBufPosLimit; - UInt32 lzPos; - UInt32 btNumAvailBytes; - - UInt32 *hash; - UInt32 fixedHashSize; - UInt32 historySize; - const UInt32 *crc; - - Mf_Mix_Matches MixMatchesFunc; - - /* LZ + BT */ - CMtSync btSync; - Byte btDummy[kMtCacheLineDummy]; - - /* BT */ - UInt32 *hashBuf; - UInt32 hashBufPos; - UInt32 hashBufPosLimit; - UInt32 hashNumAvail; - - CLzRef *son; - UInt32 matchMaxLen; - UInt32 numHashBytes; - UInt32 pos; - Byte *buffer; - UInt32 cyclicBufferPos; - UInt32 cyclicBufferSize; /* it must be historySize + 1 */ - UInt32 cutValue; - - /* BT + Hash */ - CMtSync hashSync; - /* Byte hashDummy[kMtCacheLineDummy]; */ - - /* Hash */ - Mf_GetHeads GetHeadsFunc; - CMatchFinder *MatchFinder; -} CMatchFinderMt; - -void MatchFinderMt_Construct(CMatchFinderMt *p); -void MatchFinderMt_Destruct(CMatchFinderMt *p, ISzAlloc *alloc); -SRes MatchFinderMt_Create(CMatchFinderMt *p, UInt32 historySize, UInt32 keepAddBufferBefore, - UInt32 matchMaxLen, UInt32 keepAddBufferAfter, ISzAlloc *alloc); -void MatchFinderMt_CreateVTable(CMatchFinderMt *p, IMatchFinder *vTable); -void MatchFinderMt_ReleaseStream(CMatchFinderMt *p); - -#endif diff --git a/desmume/src/windows/7z/C/LzHash.h b/desmume/src/windows/7z/C/LzHash.h deleted file mode 100644 index c92341750..000000000 --- a/desmume/src/windows/7z/C/LzHash.h +++ /dev/null @@ -1,54 +0,0 @@ -/* LzHash.h -- HASH functions for LZ algorithms -2008-10-04 : Igor Pavlov : Public domain */ - -#ifndef __LZHASH_H -#define __LZHASH_H - -#define kHash2Size (1 << 10) -#define kHash3Size (1 << 16) -#define kHash4Size (1 << 20) - -#define kFix3HashSize (kHash2Size) -#define kFix4HashSize (kHash2Size + kHash3Size) -#define kFix5HashSize (kHash2Size + kHash3Size + kHash4Size) - -#define HASH2_CALC hashValue = cur[0] | ((UInt32)cur[1] << 8); - -#define HASH3_CALC { \ - UInt32 temp = p->crc[cur[0]] ^ cur[1]; \ - hash2Value = temp & (kHash2Size - 1); \ - hashValue = (temp ^ ((UInt32)cur[2] << 8)) & p->hashMask; } - -#define HASH4_CALC { \ - UInt32 temp = p->crc[cur[0]] ^ cur[1]; \ - hash2Value = temp & (kHash2Size - 1); \ - hash3Value = (temp ^ ((UInt32)cur[2] << 8)) & (kHash3Size - 1); \ - hashValue = (temp ^ ((UInt32)cur[2] << 8) ^ (p->crc[cur[3]] << 5)) & p->hashMask; } - -#define HASH5_CALC { \ - UInt32 temp = p->crc[cur[0]] ^ cur[1]; \ - hash2Value = temp & (kHash2Size - 1); \ - hash3Value = (temp ^ ((UInt32)cur[2] << 8)) & (kHash3Size - 1); \ - hash4Value = (temp ^ ((UInt32)cur[2] << 8) ^ (p->crc[cur[3]] << 5)); \ - hashValue = (hash4Value ^ (p->crc[cur[4]] << 3)) & p->hashMask; \ - hash4Value &= (kHash4Size - 1); } - -/* #define HASH_ZIP_CALC hashValue = ((cur[0] | ((UInt32)cur[1] << 8)) ^ p->crc[cur[2]]) & 0xFFFF; */ -#define HASH_ZIP_CALC hashValue = ((cur[2] | ((UInt32)cur[0] << 8)) ^ p->crc[cur[1]]) & 0xFFFF; - - -#define MT_HASH2_CALC \ - hash2Value = (p->crc[cur[0]] ^ cur[1]) & (kHash2Size - 1); - -#define MT_HASH3_CALC { \ - UInt32 temp = p->crc[cur[0]] ^ cur[1]; \ - hash2Value = temp & (kHash2Size - 1); \ - hash3Value = (temp ^ ((UInt32)cur[2] << 8)) & (kHash3Size - 1); } - -#define MT_HASH4_CALC { \ - UInt32 temp = p->crc[cur[0]] ^ cur[1]; \ - hash2Value = temp & (kHash2Size - 1); \ - hash3Value = (temp ^ ((UInt32)cur[2] << 8)) & (kHash3Size - 1); \ - hash4Value = (temp ^ ((UInt32)cur[2] << 8) ^ (p->crc[cur[3]] << 5)) & (kHash4Size - 1); } - -#endif diff --git a/desmume/src/windows/7z/C/LzmaDec.c b/desmume/src/windows/7z/C/LzmaDec.c deleted file mode 100644 index e40e4286e..000000000 --- a/desmume/src/windows/7z/C/LzmaDec.c +++ /dev/null @@ -1,1007 +0,0 @@ -/* LzmaDec.c -- LZMA Decoder -2008-11-06 : Igor Pavlov : Public domain */ - -#include "LzmaDec.h" - -#include - -#define kNumTopBits 24 -#define kTopValue ((UInt32)1 << kNumTopBits) - -#define kNumBitModelTotalBits 11 -#define kBitModelTotal (1 << kNumBitModelTotalBits) -#define kNumMoveBits 5 - -#define RC_INIT_SIZE 5 - -#define NORMALIZE if (range < kTopValue) { range <<= 8; code = (code << 8) | (*buf++); } - -#define IF_BIT_0(p) ttt = *(p); NORMALIZE; bound = (range >> kNumBitModelTotalBits) * ttt; if (code < bound) -#define UPDATE_0(p) range = bound; *(p) = (CLzmaProb)(ttt + ((kBitModelTotal - ttt) >> kNumMoveBits)); -#define UPDATE_1(p) range -= bound; code -= bound; *(p) = (CLzmaProb)(ttt - (ttt >> kNumMoveBits)); -#define GET_BIT2(p, i, A0, A1) IF_BIT_0(p) \ - { UPDATE_0(p); i = (i + i); A0; } else \ - { UPDATE_1(p); i = (i + i) + 1; A1; } -#define GET_BIT(p, i) GET_BIT2(p, i, ; , ;) - -#define TREE_GET_BIT(probs, i) { GET_BIT((probs + i), i); } -#define TREE_DECODE(probs, limit, i) \ - { i = 1; do { TREE_GET_BIT(probs, i); } while (i < limit); i -= limit; } - -/* #define _LZMA_SIZE_OPT */ - -#ifdef _LZMA_SIZE_OPT -#define TREE_6_DECODE(probs, i) TREE_DECODE(probs, (1 << 6), i) -#else -#define TREE_6_DECODE(probs, i) \ - { i = 1; \ - TREE_GET_BIT(probs, i); \ - TREE_GET_BIT(probs, i); \ - TREE_GET_BIT(probs, i); \ - TREE_GET_BIT(probs, i); \ - TREE_GET_BIT(probs, i); \ - TREE_GET_BIT(probs, i); \ - i -= 0x40; } -#endif - -#define NORMALIZE_CHECK if (range < kTopValue) { if (buf >= bufLimit) return DUMMY_ERROR; range <<= 8; code = (code << 8) | (*buf++); } - -#define IF_BIT_0_CHECK(p) ttt = *(p); NORMALIZE_CHECK; bound = (range >> kNumBitModelTotalBits) * ttt; if (code < bound) -#define UPDATE_0_CHECK range = bound; -#define UPDATE_1_CHECK range -= bound; code -= bound; -#define GET_BIT2_CHECK(p, i, A0, A1) IF_BIT_0_CHECK(p) \ - { UPDATE_0_CHECK; i = (i + i); A0; } else \ - { UPDATE_1_CHECK; i = (i + i) + 1; A1; } -#define GET_BIT_CHECK(p, i) GET_BIT2_CHECK(p, i, ; , ;) -#define TREE_DECODE_CHECK(probs, limit, i) \ - { i = 1; do { GET_BIT_CHECK(probs + i, i) } while (i < limit); i -= limit; } - - -#define kNumPosBitsMax 4 -#define kNumPosStatesMax (1 << kNumPosBitsMax) - -#define kLenNumLowBits 3 -#define kLenNumLowSymbols (1 << kLenNumLowBits) -#define kLenNumMidBits 3 -#define kLenNumMidSymbols (1 << kLenNumMidBits) -#define kLenNumHighBits 8 -#define kLenNumHighSymbols (1 << kLenNumHighBits) - -#define LenChoice 0 -#define LenChoice2 (LenChoice + 1) -#define LenLow (LenChoice2 + 1) -#define LenMid (LenLow + (kNumPosStatesMax << kLenNumLowBits)) -#define LenHigh (LenMid + (kNumPosStatesMax << kLenNumMidBits)) -#define kNumLenProbs (LenHigh + kLenNumHighSymbols) - - -#define kNumStates 12 -#define kNumLitStates 7 - -#define kStartPosModelIndex 4 -#define kEndPosModelIndex 14 -#define kNumFullDistances (1 << (kEndPosModelIndex >> 1)) - -#define kNumPosSlotBits 6 -#define kNumLenToPosStates 4 - -#define kNumAlignBits 4 -#define kAlignTableSize (1 << kNumAlignBits) - -#define kMatchMinLen 2 -#define kMatchSpecLenStart (kMatchMinLen + kLenNumLowSymbols + kLenNumMidSymbols + kLenNumHighSymbols) - -#define IsMatch 0 -#define IsRep (IsMatch + (kNumStates << kNumPosBitsMax)) -#define IsRepG0 (IsRep + kNumStates) -#define IsRepG1 (IsRepG0 + kNumStates) -#define IsRepG2 (IsRepG1 + kNumStates) -#define IsRep0Long (IsRepG2 + kNumStates) -#define PosSlot (IsRep0Long + (kNumStates << kNumPosBitsMax)) -#define SpecPos (PosSlot + (kNumLenToPosStates << kNumPosSlotBits)) -#define Align (SpecPos + kNumFullDistances - kEndPosModelIndex) -#define LenCoder (Align + kAlignTableSize) -#define RepLenCoder (LenCoder + kNumLenProbs) -#define Literal (RepLenCoder + kNumLenProbs) - -#define LZMA_BASE_SIZE 1846 -#define LZMA_LIT_SIZE 768 - -#define LzmaProps_GetNumProbs(p) ((UInt32)LZMA_BASE_SIZE + (LZMA_LIT_SIZE << ((p)->lc + (p)->lp))) - -#if Literal != LZMA_BASE_SIZE -StopCompilingDueBUG -#endif - -static const Byte kLiteralNextStates[kNumStates * 2] = -{ - 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 4, 5, - 7, 7, 7, 7, 7, 7, 7, 10, 10, 10, 10, 10 -}; - -#define LZMA_DIC_MIN (1 << 12) - -/* First LZMA-symbol is always decoded. -And it decodes new LZMA-symbols while (buf < bufLimit), but "buf" is without last normalization -Out: - Result: - SZ_OK - OK - SZ_ERROR_DATA - Error - p->remainLen: - < kMatchSpecLenStart : normal remain - = kMatchSpecLenStart : finished - = kMatchSpecLenStart + 1 : Flush marker - = kMatchSpecLenStart + 2 : State Init Marker -*/ - -static int MY_FAST_CALL LzmaDec_DecodeReal(CLzmaDec *p, SizeT limit, const Byte *bufLimit) -{ - CLzmaProb *probs = p->probs; - - unsigned state = p->state; - UInt32 rep0 = p->reps[0], rep1 = p->reps[1], rep2 = p->reps[2], rep3 = p->reps[3]; - unsigned pbMask = ((unsigned)1 << (p->prop.pb)) - 1; - unsigned lpMask = ((unsigned)1 << (p->prop.lp)) - 1; - unsigned lc = p->prop.lc; - - Byte *dic = p->dic; - SizeT dicBufSize = p->dicBufSize; - SizeT dicPos = p->dicPos; - - UInt32 processedPos = p->processedPos; - UInt32 checkDicSize = p->checkDicSize; - unsigned len = 0; - - const Byte *buf = p->buf; - UInt32 range = p->range; - UInt32 code = p->code; - - do - { - CLzmaProb *prob; - UInt32 bound; - unsigned ttt; - unsigned posState = processedPos & pbMask; - - prob = probs + IsMatch + (state << kNumPosBitsMax) + posState; - IF_BIT_0(prob) - { - unsigned symbol; - UPDATE_0(prob); - prob = probs + Literal; - if (checkDicSize != 0 || processedPos != 0) - prob += (LZMA_LIT_SIZE * (((processedPos & lpMask) << lc) + - (dic[(dicPos == 0 ? dicBufSize : dicPos) - 1] >> (8 - lc)))); - - if (state < kNumLitStates) - { - symbol = 1; - do { GET_BIT(prob + symbol, symbol) } while (symbol < 0x100); - } - else - { - unsigned matchByte = p->dic[(dicPos - rep0) + ((dicPos < rep0) ? dicBufSize : 0)]; - unsigned offs = 0x100; - symbol = 1; - do - { - unsigned bit; - CLzmaProb *probLit; - matchByte <<= 1; - bit = (matchByte & offs); - probLit = prob + offs + bit + symbol; - GET_BIT2(probLit, symbol, offs &= ~bit, offs &= bit) - } - while (symbol < 0x100); - } - dic[dicPos++] = (Byte)(symbol & 0xFF); - processedPos++; - - state = kLiteralNextStates[state]; - /* if (state < 4) state = 0; else if (state < 10) state -= 3; else state -= 6; */ - continue; - } - else - { - UPDATE_1(prob); - prob = probs + IsRep + state; - IF_BIT_0(prob) - { - UPDATE_0(prob); - state += kNumStates; - prob = probs + LenCoder; - } - else - { - UPDATE_1(prob); - if (checkDicSize == 0 && processedPos == 0) - return SZ_ERROR_DATA; - prob = probs + IsRepG0 + state; - IF_BIT_0(prob) - { - UPDATE_0(prob); - prob = probs + IsRep0Long + (state << kNumPosBitsMax) + posState; - IF_BIT_0(prob) - { - UPDATE_0(prob); - dic[dicPos] = dic[(dicPos - rep0) + ((dicPos < rep0) ? dicBufSize : 0)]; - dicPos++; - processedPos++; - state = state < kNumLitStates ? 9 : 11; - continue; - } - UPDATE_1(prob); - } - else - { - UInt32 distance; - UPDATE_1(prob); - prob = probs + IsRepG1 + state; - IF_BIT_0(prob) - { - UPDATE_0(prob); - distance = rep1; - } - else - { - UPDATE_1(prob); - prob = probs + IsRepG2 + state; - IF_BIT_0(prob) - { - UPDATE_0(prob); - distance = rep2; - } - else - { - UPDATE_1(prob); - distance = rep3; - rep3 = rep2; - } - rep2 = rep1; - } - rep1 = rep0; - rep0 = distance; - } - state = state < kNumLitStates ? 8 : 11; - prob = probs + RepLenCoder; - } - { - unsigned limit, offset; - CLzmaProb *probLen = prob + LenChoice; - IF_BIT_0(probLen) - { - UPDATE_0(probLen); - probLen = prob + LenLow + (posState << kLenNumLowBits); - offset = 0; - limit = (1 << kLenNumLowBits); - } - else - { - UPDATE_1(probLen); - probLen = prob + LenChoice2; - IF_BIT_0(probLen) - { - UPDATE_0(probLen); - probLen = prob + LenMid + (posState << kLenNumMidBits); - offset = kLenNumLowSymbols; - limit = (1 << kLenNumMidBits); - } - else - { - UPDATE_1(probLen); - probLen = prob + LenHigh; - offset = kLenNumLowSymbols + kLenNumMidSymbols; - limit = (1 << kLenNumHighBits); - } - } - TREE_DECODE(probLen, limit, len); - len += offset; - } - - if (state >= kNumStates) - { - UInt32 distance; - prob = probs + PosSlot + - ((len < kNumLenToPosStates ? len : kNumLenToPosStates - 1) << kNumPosSlotBits); - TREE_6_DECODE(prob, distance); - if (distance >= kStartPosModelIndex) - { - unsigned posSlot = (unsigned)distance; - int numDirectBits = (int)(((distance >> 1) - 1)); - distance = (2 | (distance & 1)); - if (posSlot < kEndPosModelIndex) - { - distance <<= numDirectBits; - prob = probs + SpecPos + distance - posSlot - 1; - { - UInt32 mask = 1; - unsigned i = 1; - do - { - GET_BIT2(prob + i, i, ; , distance |= mask); - mask <<= 1; - } - while (--numDirectBits != 0); - } - } - else - { - numDirectBits -= kNumAlignBits; - do - { - NORMALIZE - range >>= 1; - - { - UInt32 t; - code -= range; - t = (0 - ((UInt32)code >> 31)); /* (UInt32)((Int32)code >> 31) */ - distance = (distance << 1) + (t + 1); - code += range & t; - } - /* - distance <<= 1; - if (code >= range) - { - code -= range; - distance |= 1; - } - */ - } - while (--numDirectBits != 0); - prob = probs + Align; - distance <<= kNumAlignBits; - { - unsigned i = 1; - GET_BIT2(prob + i, i, ; , distance |= 1); - GET_BIT2(prob + i, i, ; , distance |= 2); - GET_BIT2(prob + i, i, ; , distance |= 4); - GET_BIT2(prob + i, i, ; , distance |= 8); - } - if (distance == (UInt32)0xFFFFFFFF) - { - len += kMatchSpecLenStart; - state -= kNumStates; - break; - } - } - } - rep3 = rep2; - rep2 = rep1; - rep1 = rep0; - rep0 = distance + 1; - if (checkDicSize == 0) - { - if (distance >= processedPos) - return SZ_ERROR_DATA; - } - else if (distance >= checkDicSize) - return SZ_ERROR_DATA; - state = (state < kNumStates + kNumLitStates) ? kNumLitStates : kNumLitStates + 3; - /* state = kLiteralNextStates[state]; */ - } - - len += kMatchMinLen; - - if (limit == dicPos) - return SZ_ERROR_DATA; - { - SizeT rem = limit - dicPos; - unsigned curLen = ((rem < len) ? (unsigned)rem : len); - SizeT pos = (dicPos - rep0) + ((dicPos < rep0) ? dicBufSize : 0); - - processedPos += curLen; - - len -= curLen; - if (pos + curLen <= dicBufSize) - { - Byte *dest = dic + dicPos; - ptrdiff_t src = (ptrdiff_t)pos - (ptrdiff_t)dicPos; - const Byte *lim = dest + curLen; - dicPos += curLen; - do - *(dest) = (Byte)*(dest + src); - while (++dest != lim); - } - else - { - do - { - dic[dicPos++] = dic[pos]; - if (++pos == dicBufSize) - pos = 0; - } - while (--curLen != 0); - } - } - } - } - while (dicPos < limit && buf < bufLimit); - NORMALIZE; - p->buf = buf; - p->range = range; - p->code = code; - p->remainLen = len; - p->dicPos = dicPos; - p->processedPos = processedPos; - p->reps[0] = rep0; - p->reps[1] = rep1; - p->reps[2] = rep2; - p->reps[3] = rep3; - p->state = state; - - return SZ_OK; -} - -static void MY_FAST_CALL LzmaDec_WriteRem(CLzmaDec *p, SizeT limit) -{ - if (p->remainLen != 0 && p->remainLen < kMatchSpecLenStart) - { - Byte *dic = p->dic; - SizeT dicPos = p->dicPos; - SizeT dicBufSize = p->dicBufSize; - unsigned len = p->remainLen; - UInt32 rep0 = p->reps[0]; - if (limit - dicPos < len) - len = (unsigned)(limit - dicPos); - - if (p->checkDicSize == 0 && p->prop.dicSize - p->processedPos <= len) - p->checkDicSize = p->prop.dicSize; - - p->processedPos += len; - p->remainLen -= len; - while (len-- != 0) - { - dic[dicPos] = dic[(dicPos - rep0) + ((dicPos < rep0) ? dicBufSize : 0)]; - dicPos++; - } - p->dicPos = dicPos; - } -} - -static int MY_FAST_CALL LzmaDec_DecodeReal2(CLzmaDec *p, SizeT limit, const Byte *bufLimit) -{ - do - { - SizeT limit2 = limit; - if (p->checkDicSize == 0) - { - UInt32 rem = p->prop.dicSize - p->processedPos; - if (limit - p->dicPos > rem) - limit2 = p->dicPos + rem; - } - RINOK(LzmaDec_DecodeReal(p, limit2, bufLimit)); - if (p->processedPos >= p->prop.dicSize) - p->checkDicSize = p->prop.dicSize; - LzmaDec_WriteRem(p, limit); - } - while (p->dicPos < limit && p->buf < bufLimit && p->remainLen < kMatchSpecLenStart); - - if (p->remainLen > kMatchSpecLenStart) - { - p->remainLen = kMatchSpecLenStart; - } - return 0; -} - -typedef enum -{ - DUMMY_ERROR, /* unexpected end of input stream */ - DUMMY_LIT, - DUMMY_MATCH, - DUMMY_REP -} ELzmaDummy; - -static ELzmaDummy LzmaDec_TryDummy(const CLzmaDec *p, const Byte *buf, SizeT inSize) -{ - UInt32 range = p->range; - UInt32 code = p->code; - const Byte *bufLimit = buf + inSize; - CLzmaProb *probs = p->probs; - unsigned state = p->state; - ELzmaDummy res; - - { - CLzmaProb *prob; - UInt32 bound; - unsigned ttt; - unsigned posState = (p->processedPos) & ((1 << p->prop.pb) - 1); - - prob = probs + IsMatch + (state << kNumPosBitsMax) + posState; - IF_BIT_0_CHECK(prob) - { - UPDATE_0_CHECK - - /* if (bufLimit - buf >= 7) return DUMMY_LIT; */ - - prob = probs + Literal; - if (p->checkDicSize != 0 || p->processedPos != 0) - prob += (LZMA_LIT_SIZE * - ((((p->processedPos) & ((1 << (p->prop.lp)) - 1)) << p->prop.lc) + - (p->dic[(p->dicPos == 0 ? p->dicBufSize : p->dicPos) - 1] >> (8 - p->prop.lc)))); - - if (state < kNumLitStates) - { - unsigned symbol = 1; - do { GET_BIT_CHECK(prob + symbol, symbol) } while (symbol < 0x100); - } - else - { - unsigned matchByte = p->dic[p->dicPos - p->reps[0] + - ((p->dicPos < p->reps[0]) ? p->dicBufSize : 0)]; - unsigned offs = 0x100; - unsigned symbol = 1; - do - { - unsigned bit; - CLzmaProb *probLit; - matchByte <<= 1; - bit = (matchByte & offs); - probLit = prob + offs + bit + symbol; - GET_BIT2_CHECK(probLit, symbol, offs &= ~bit, offs &= bit) - } - while (symbol < 0x100); - } - res = DUMMY_LIT; - } - else - { - unsigned len; - UPDATE_1_CHECK; - - prob = probs + IsRep + state; - IF_BIT_0_CHECK(prob) - { - UPDATE_0_CHECK; - state = 0; - prob = probs + LenCoder; - res = DUMMY_MATCH; - } - else - { - UPDATE_1_CHECK; - res = DUMMY_REP; - prob = probs + IsRepG0 + state; - IF_BIT_0_CHECK(prob) - { - UPDATE_0_CHECK; - prob = probs + IsRep0Long + (state << kNumPosBitsMax) + posState; - IF_BIT_0_CHECK(prob) - { - UPDATE_0_CHECK; - NORMALIZE_CHECK; - return DUMMY_REP; - } - else - { - UPDATE_1_CHECK; - } - } - else - { - UPDATE_1_CHECK; - prob = probs + IsRepG1 + state; - IF_BIT_0_CHECK(prob) - { - UPDATE_0_CHECK; - } - else - { - UPDATE_1_CHECK; - prob = probs + IsRepG2 + state; - IF_BIT_0_CHECK(prob) - { - UPDATE_0_CHECK; - } - else - { - UPDATE_1_CHECK; - } - } - } - state = kNumStates; - prob = probs + RepLenCoder; - } - { - unsigned limit, offset; - CLzmaProb *probLen = prob + LenChoice; - IF_BIT_0_CHECK(probLen) - { - UPDATE_0_CHECK; - probLen = prob + LenLow + (posState << kLenNumLowBits); - offset = 0; - limit = 1 << kLenNumLowBits; - } - else - { - UPDATE_1_CHECK; - probLen = prob + LenChoice2; - IF_BIT_0_CHECK(probLen) - { - UPDATE_0_CHECK; - probLen = prob + LenMid + (posState << kLenNumMidBits); - offset = kLenNumLowSymbols; - limit = 1 << kLenNumMidBits; - } - else - { - UPDATE_1_CHECK; - probLen = prob + LenHigh; - offset = kLenNumLowSymbols + kLenNumMidSymbols; - limit = 1 << kLenNumHighBits; - } - } - TREE_DECODE_CHECK(probLen, limit, len); - len += offset; - } - - if (state < 4) - { - unsigned posSlot; - prob = probs + PosSlot + - ((len < kNumLenToPosStates ? len : kNumLenToPosStates - 1) << - kNumPosSlotBits); - TREE_DECODE_CHECK(prob, 1 << kNumPosSlotBits, posSlot); - if (posSlot >= kStartPosModelIndex) - { - int numDirectBits = ((posSlot >> 1) - 1); - - /* if (bufLimit - buf >= 8) return DUMMY_MATCH; */ - - if (posSlot < kEndPosModelIndex) - { - prob = probs + SpecPos + ((2 | (posSlot & 1)) << numDirectBits) - posSlot - 1; - } - else - { - numDirectBits -= kNumAlignBits; - do - { - NORMALIZE_CHECK - range >>= 1; - code -= range & (((code - range) >> 31) - 1); - /* if (code >= range) code -= range; */ - } - while (--numDirectBits != 0); - prob = probs + Align; - numDirectBits = kNumAlignBits; - } - { - unsigned i = 1; - do - { - GET_BIT_CHECK(prob + i, i); - } - while (--numDirectBits != 0); - } - } - } - } - } - NORMALIZE_CHECK; - return res; -} - - -static void LzmaDec_InitRc(CLzmaDec *p, const Byte *data) -{ - p->code = ((UInt32)data[1] << 24) | ((UInt32)data[2] << 16) | ((UInt32)data[3] << 8) | ((UInt32)data[4]); - p->range = 0xFFFFFFFF; - p->needFlush = 0; -} - -void LzmaDec_InitDicAndState(CLzmaDec *p, Bool initDic, Bool initState) -{ - p->needFlush = 1; - p->remainLen = 0; - p->tempBufSize = 0; - - if (initDic) - { - p->processedPos = 0; - p->checkDicSize = 0; - p->needInitState = 1; - } - if (initState) - p->needInitState = 1; -} - -void LzmaDec_Init(CLzmaDec *p) -{ - p->dicPos = 0; - LzmaDec_InitDicAndState(p, True, True); -} - -static void LzmaDec_InitStateReal(CLzmaDec *p) -{ - UInt32 numProbs = Literal + ((UInt32)LZMA_LIT_SIZE << (p->prop.lc + p->prop.lp)); - UInt32 i; - CLzmaProb *probs = p->probs; - for (i = 0; i < numProbs; i++) - probs[i] = kBitModelTotal >> 1; - p->reps[0] = p->reps[1] = p->reps[2] = p->reps[3] = 1; - p->state = 0; - p->needInitState = 0; -} - -SRes LzmaDec_DecodeToDic(CLzmaDec *p, SizeT dicLimit, const Byte *src, SizeT *srcLen, - ELzmaFinishMode finishMode, ELzmaStatus *status) -{ - SizeT inSize = *srcLen; - (*srcLen) = 0; - LzmaDec_WriteRem(p, dicLimit); - - *status = LZMA_STATUS_NOT_SPECIFIED; - - while (p->remainLen != kMatchSpecLenStart) - { - int checkEndMarkNow; - - if (p->needFlush != 0) - { - for (; inSize > 0 && p->tempBufSize < RC_INIT_SIZE; (*srcLen)++, inSize--) - p->tempBuf[p->tempBufSize++] = *src++; - if (p->tempBufSize < RC_INIT_SIZE) - { - *status = LZMA_STATUS_NEEDS_MORE_INPUT; - return SZ_OK; - } - if (p->tempBuf[0] != 0) - return SZ_ERROR_DATA; - - LzmaDec_InitRc(p, p->tempBuf); - p->tempBufSize = 0; - } - - checkEndMarkNow = 0; - if (p->dicPos >= dicLimit) - { - if (p->remainLen == 0 && p->code == 0) - { - *status = LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK; - return SZ_OK; - } - if (finishMode == LZMA_FINISH_ANY) - { - *status = LZMA_STATUS_NOT_FINISHED; - return SZ_OK; - } - if (p->remainLen != 0) - { - *status = LZMA_STATUS_NOT_FINISHED; - return SZ_ERROR_DATA; - } - checkEndMarkNow = 1; - } - - if (p->needInitState) - LzmaDec_InitStateReal(p); - - if (p->tempBufSize == 0) - { - SizeT processed; - const Byte *bufLimit; - if (inSize < LZMA_REQUIRED_INPUT_MAX || checkEndMarkNow) - { - int dummyRes = LzmaDec_TryDummy(p, src, inSize); - if (dummyRes == DUMMY_ERROR) - { - memcpy(p->tempBuf, src, inSize); - p->tempBufSize = (unsigned)inSize; - (*srcLen) += inSize; - *status = LZMA_STATUS_NEEDS_MORE_INPUT; - return SZ_OK; - } - if (checkEndMarkNow && dummyRes != DUMMY_MATCH) - { - *status = LZMA_STATUS_NOT_FINISHED; - return SZ_ERROR_DATA; - } - bufLimit = src; - } - else - bufLimit = src + inSize - LZMA_REQUIRED_INPUT_MAX; - p->buf = src; - if (LzmaDec_DecodeReal2(p, dicLimit, bufLimit) != 0) - return SZ_ERROR_DATA; - processed = (SizeT)(p->buf - src); - (*srcLen) += processed; - src += processed; - inSize -= processed; - } - else - { - unsigned rem = p->tempBufSize, lookAhead = 0; - while (rem < LZMA_REQUIRED_INPUT_MAX && lookAhead < inSize) - p->tempBuf[rem++] = src[lookAhead++]; - p->tempBufSize = rem; - if (rem < LZMA_REQUIRED_INPUT_MAX || checkEndMarkNow) - { - int dummyRes = LzmaDec_TryDummy(p, p->tempBuf, rem); - if (dummyRes == DUMMY_ERROR) - { - (*srcLen) += lookAhead; - *status = LZMA_STATUS_NEEDS_MORE_INPUT; - return SZ_OK; - } - if (checkEndMarkNow && dummyRes != DUMMY_MATCH) - { - *status = LZMA_STATUS_NOT_FINISHED; - return SZ_ERROR_DATA; - } - } - p->buf = p->tempBuf; - if (LzmaDec_DecodeReal2(p, dicLimit, p->buf) != 0) - return SZ_ERROR_DATA; - lookAhead -= (rem - (unsigned)(p->buf - p->tempBuf)); - (*srcLen) += lookAhead; - src += lookAhead; - inSize -= lookAhead; - p->tempBufSize = 0; - } - } - if (p->code == 0) - *status = LZMA_STATUS_FINISHED_WITH_MARK; - return (p->code == 0) ? SZ_OK : SZ_ERROR_DATA; -} - -SRes LzmaDec_DecodeToBuf(CLzmaDec *p, Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen, ELzmaFinishMode finishMode, ELzmaStatus *status) -{ - SizeT outSize = *destLen; - SizeT inSize = *srcLen; - *srcLen = *destLen = 0; - for (;;) - { - SizeT inSizeCur = inSize, outSizeCur, dicPos; - ELzmaFinishMode curFinishMode; - SRes res; - if (p->dicPos == p->dicBufSize) - p->dicPos = 0; - dicPos = p->dicPos; - if (outSize > p->dicBufSize - dicPos) - { - outSizeCur = p->dicBufSize; - curFinishMode = LZMA_FINISH_ANY; - } - else - { - outSizeCur = dicPos + outSize; - curFinishMode = finishMode; - } - - res = LzmaDec_DecodeToDic(p, outSizeCur, src, &inSizeCur, curFinishMode, status); - src += inSizeCur; - inSize -= inSizeCur; - *srcLen += inSizeCur; - outSizeCur = p->dicPos - dicPos; - memcpy(dest, p->dic + dicPos, outSizeCur); - dest += outSizeCur; - outSize -= outSizeCur; - *destLen += outSizeCur; - if (res != 0) - return res; - if (outSizeCur == 0 || outSize == 0) - return SZ_OK; - } -} - -void LzmaDec_FreeProbs(CLzmaDec *p, ISzAlloc *alloc) -{ - alloc->Free(alloc, p->probs); - p->probs = 0; -} - -static void LzmaDec_FreeDict(CLzmaDec *p, ISzAlloc *alloc) -{ - alloc->Free(alloc, p->dic); - p->dic = 0; -} - -void LzmaDec_Free(CLzmaDec *p, ISzAlloc *alloc) -{ - LzmaDec_FreeProbs(p, alloc); - LzmaDec_FreeDict(p, alloc); -} - -SRes LzmaProps_Decode(CLzmaProps *p, const Byte *data, unsigned size) -{ - UInt32 dicSize; - Byte d; - - if (size < LZMA_PROPS_SIZE) - return SZ_ERROR_UNSUPPORTED; - else - dicSize = data[1] | ((UInt32)data[2] << 8) | ((UInt32)data[3] << 16) | ((UInt32)data[4] << 24); - - if (dicSize < LZMA_DIC_MIN) - dicSize = LZMA_DIC_MIN; - p->dicSize = dicSize; - - d = data[0]; - if (d >= (9 * 5 * 5)) - return SZ_ERROR_UNSUPPORTED; - - p->lc = d % 9; - d /= 9; - p->pb = d / 5; - p->lp = d % 5; - - return SZ_OK; -} - -static SRes LzmaDec_AllocateProbs2(CLzmaDec *p, const CLzmaProps *propNew, ISzAlloc *alloc) -{ - UInt32 numProbs = LzmaProps_GetNumProbs(propNew); - if (p->probs == 0 || numProbs != p->numProbs) - { - LzmaDec_FreeProbs(p, alloc); - p->probs = (CLzmaProb *)alloc->Alloc(alloc, numProbs * sizeof(CLzmaProb)); - p->numProbs = numProbs; - if (p->probs == 0) - return SZ_ERROR_MEM; - } - return SZ_OK; -} - -SRes LzmaDec_AllocateProbs(CLzmaDec *p, const Byte *props, unsigned propsSize, ISzAlloc *alloc) -{ - CLzmaProps propNew; - RINOK(LzmaProps_Decode(&propNew, props, propsSize)); - RINOK(LzmaDec_AllocateProbs2(p, &propNew, alloc)); - p->prop = propNew; - return SZ_OK; -} - -SRes LzmaDec_Allocate(CLzmaDec *p, const Byte *props, unsigned propsSize, ISzAlloc *alloc) -{ - CLzmaProps propNew; - SizeT dicBufSize; - RINOK(LzmaProps_Decode(&propNew, props, propsSize)); - RINOK(LzmaDec_AllocateProbs2(p, &propNew, alloc)); - dicBufSize = propNew.dicSize; - if (p->dic == 0 || dicBufSize != p->dicBufSize) - { - LzmaDec_FreeDict(p, alloc); - p->dic = (Byte *)alloc->Alloc(alloc, dicBufSize); - if (p->dic == 0) - { - LzmaDec_FreeProbs(p, alloc); - return SZ_ERROR_MEM; - } - } - p->dicBufSize = dicBufSize; - p->prop = propNew; - return SZ_OK; -} - -SRes LzmaDecode(Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen, - const Byte *propData, unsigned propSize, ELzmaFinishMode finishMode, - ELzmaStatus *status, ISzAlloc *alloc) -{ - CLzmaDec p; - SRes res; - SizeT inSize = *srcLen; - SizeT outSize = *destLen; - *srcLen = *destLen = 0; - if (inSize < RC_INIT_SIZE) - return SZ_ERROR_INPUT_EOF; - - LzmaDec_Construct(&p); - res = LzmaDec_AllocateProbs(&p, propData, propSize, alloc); - if (res != 0) - return res; - p.dic = dest; - p.dicBufSize = outSize; - - LzmaDec_Init(&p); - - *srcLen = inSize; - res = LzmaDec_DecodeToDic(&p, outSize, src, srcLen, finishMode, status); - - if (res == SZ_OK && *status == LZMA_STATUS_NEEDS_MORE_INPUT) - res = SZ_ERROR_INPUT_EOF; - - (*destLen) = p.dicPos; - LzmaDec_FreeProbs(&p, alloc); - return res; -} diff --git a/desmume/src/windows/7z/C/LzmaDec.h b/desmume/src/windows/7z/C/LzmaDec.h deleted file mode 100644 index ad7d7057a..000000000 --- a/desmume/src/windows/7z/C/LzmaDec.h +++ /dev/null @@ -1,223 +0,0 @@ -/* LzmaDec.h -- LZMA Decoder -2008-10-04 : Igor Pavlov : Public domain */ - -#ifndef __LZMADEC_H -#define __LZMADEC_H - -#include "Types.h" - -/* #define _LZMA_PROB32 */ -/* _LZMA_PROB32 can increase the speed on some CPUs, - but memory usage for CLzmaDec::probs will be doubled in that case */ - -#ifdef _LZMA_PROB32 -#define CLzmaProb UInt32 -#else -#define CLzmaProb UInt16 -#endif - - -/* ---------- LZMA Properties ---------- */ - -#define LZMA_PROPS_SIZE 5 - -typedef struct _CLzmaProps -{ - unsigned lc, lp, pb; - UInt32 dicSize; -} CLzmaProps; - -/* LzmaProps_Decode - decodes properties -Returns: - SZ_OK - SZ_ERROR_UNSUPPORTED - Unsupported properties -*/ - -SRes LzmaProps_Decode(CLzmaProps *p, const Byte *data, unsigned size); - - -/* ---------- LZMA Decoder state ---------- */ - -/* LZMA_REQUIRED_INPUT_MAX = number of required input bytes for worst case. - Num bits = log2((2^11 / 31) ^ 22) + 26 < 134 + 26 = 160; */ - -#define LZMA_REQUIRED_INPUT_MAX 20 - -typedef struct -{ - CLzmaProps prop; - CLzmaProb *probs; - Byte *dic; - const Byte *buf; - UInt32 range, code; - SizeT dicPos; - SizeT dicBufSize; - UInt32 processedPos; - UInt32 checkDicSize; - unsigned state; - UInt32 reps[4]; - unsigned remainLen; - int needFlush; - int needInitState; - UInt32 numProbs; - unsigned tempBufSize; - Byte tempBuf[LZMA_REQUIRED_INPUT_MAX]; -} CLzmaDec; - -#define LzmaDec_Construct(p) { (p)->dic = 0; (p)->probs = 0; } - -void LzmaDec_Init(CLzmaDec *p); - -/* There are two types of LZMA streams: - 0) Stream with end mark. That end mark adds about 6 bytes to compressed size. - 1) Stream without end mark. You must know exact uncompressed size to decompress such stream. */ - -typedef enum -{ - LZMA_FINISH_ANY, /* finish at any point */ - LZMA_FINISH_END /* block must be finished at the end */ -} ELzmaFinishMode; - -/* ELzmaFinishMode has meaning only if the decoding reaches output limit !!! - - You must use LZMA_FINISH_END, when you know that current output buffer - covers last bytes of block. In other cases you must use LZMA_FINISH_ANY. - - If LZMA decoder sees end marker before reaching output limit, it returns SZ_OK, - and output value of destLen will be less than output buffer size limit. - You can check status result also. - - You can use multiple checks to test data integrity after full decompression: - 1) Check Result and "status" variable. - 2) Check that output(destLen) = uncompressedSize, if you know real uncompressedSize. - 3) Check that output(srcLen) = compressedSize, if you know real compressedSize. - You must use correct finish mode in that case. */ - -typedef enum -{ - LZMA_STATUS_NOT_SPECIFIED, /* use main error code instead */ - LZMA_STATUS_FINISHED_WITH_MARK, /* stream was finished with end mark. */ - LZMA_STATUS_NOT_FINISHED, /* stream was not finished */ - LZMA_STATUS_NEEDS_MORE_INPUT, /* you must provide more input bytes */ - LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK /* there is probability that stream was finished without end mark */ -} ELzmaStatus; - -/* ELzmaStatus is used only as output value for function call */ - - -/* ---------- Interfaces ---------- */ - -/* There are 3 levels of interfaces: - 1) Dictionary Interface - 2) Buffer Interface - 3) One Call Interface - You can select any of these interfaces, but don't mix functions from different - groups for same object. */ - - -/* There are two variants to allocate state for Dictionary Interface: - 1) LzmaDec_Allocate / LzmaDec_Free - 2) LzmaDec_AllocateProbs / LzmaDec_FreeProbs - You can use variant 2, if you set dictionary buffer manually. - For Buffer Interface you must always use variant 1. - -LzmaDec_Allocate* can return: - SZ_OK - SZ_ERROR_MEM - Memory allocation error - SZ_ERROR_UNSUPPORTED - Unsupported properties -*/ - -SRes LzmaDec_AllocateProbs(CLzmaDec *p, const Byte *props, unsigned propsSize, ISzAlloc *alloc); -void LzmaDec_FreeProbs(CLzmaDec *p, ISzAlloc *alloc); - -SRes LzmaDec_Allocate(CLzmaDec *state, const Byte *prop, unsigned propsSize, ISzAlloc *alloc); -void LzmaDec_Free(CLzmaDec *state, ISzAlloc *alloc); - -/* ---------- Dictionary Interface ---------- */ - -/* You can use it, if you want to eliminate the overhead for data copying from - dictionary to some other external buffer. - You must work with CLzmaDec variables directly in this interface. - - STEPS: - LzmaDec_Constr() - LzmaDec_Allocate() - for (each new stream) - { - LzmaDec_Init() - while (it needs more decompression) - { - LzmaDec_DecodeToDic() - use data from CLzmaDec::dic and update CLzmaDec::dicPos - } - } - LzmaDec_Free() -*/ - -/* LzmaDec_DecodeToDic - - The decoding to internal dictionary buffer (CLzmaDec::dic). - You must manually update CLzmaDec::dicPos, if it reaches CLzmaDec::dicBufSize !!! - -finishMode: - It has meaning only if the decoding reaches output limit (dicLimit). - LZMA_FINISH_ANY - Decode just dicLimit bytes. - LZMA_FINISH_END - Stream must be finished after dicLimit. - -Returns: - SZ_OK - status: - LZMA_STATUS_FINISHED_WITH_MARK - LZMA_STATUS_NOT_FINISHED - LZMA_STATUS_NEEDS_MORE_INPUT - LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK - SZ_ERROR_DATA - Data error -*/ - -SRes LzmaDec_DecodeToDic(CLzmaDec *p, SizeT dicLimit, - const Byte *src, SizeT *srcLen, ELzmaFinishMode finishMode, ELzmaStatus *status); - - -/* ---------- Buffer Interface ---------- */ - -/* It's zlib-like interface. - See LzmaDec_DecodeToDic description for information about STEPS and return results, - but you must use LzmaDec_DecodeToBuf instead of LzmaDec_DecodeToDic and you don't need - to work with CLzmaDec variables manually. - -finishMode: - It has meaning only if the decoding reaches output limit (*destLen). - LZMA_FINISH_ANY - Decode just destLen bytes. - LZMA_FINISH_END - Stream must be finished after (*destLen). -*/ - -SRes LzmaDec_DecodeToBuf(CLzmaDec *p, Byte *dest, SizeT *destLen, - const Byte *src, SizeT *srcLen, ELzmaFinishMode finishMode, ELzmaStatus *status); - - -/* ---------- One Call Interface ---------- */ - -/* LzmaDecode - -finishMode: - It has meaning only if the decoding reaches output limit (*destLen). - LZMA_FINISH_ANY - Decode just destLen bytes. - LZMA_FINISH_END - Stream must be finished after (*destLen). - -Returns: - SZ_OK - status: - LZMA_STATUS_FINISHED_WITH_MARK - LZMA_STATUS_NOT_FINISHED - LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK - SZ_ERROR_DATA - Data error - SZ_ERROR_MEM - Memory allocation error - SZ_ERROR_UNSUPPORTED - Unsupported properties - SZ_ERROR_INPUT_EOF - It needs more bytes in input buffer (src). -*/ - -SRes LzmaDecode(Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen, - const Byte *propData, unsigned propSize, ELzmaFinishMode finishMode, - ELzmaStatus *status, ISzAlloc *alloc); - -#endif diff --git a/desmume/src/windows/7z/C/LzmaEnc.c b/desmume/src/windows/7z/C/LzmaEnc.c deleted file mode 100644 index a5a82da91..000000000 --- a/desmume/src/windows/7z/C/LzmaEnc.c +++ /dev/null @@ -1,2275 +0,0 @@ -/* LzmaEnc.c -- LZMA Encoder -2008-10-04 : Igor Pavlov : Public domain */ - -#include - -/* #define SHOW_STAT */ -/* #define SHOW_STAT2 */ - -#if defined(SHOW_STAT) || defined(SHOW_STAT2) -#include -#endif - -#include "LzmaEnc.h" - -#include "LzFind.h" -#ifdef COMPRESS_MF_MT -#include "LzFindMt.h" -#endif - -#ifdef SHOW_STAT -static int ttt = 0; -#endif - -#define kBlockSizeMax ((1 << LZMA_NUM_BLOCK_SIZE_BITS) - 1) - -#define kBlockSize (9 << 10) -#define kUnpackBlockSize (1 << 18) -#define kMatchArraySize (1 << 21) -#define kMatchRecordMaxSize ((LZMA_MATCH_LEN_MAX * 2 + 3) * LZMA_MATCH_LEN_MAX) - -#define kNumMaxDirectBits (31) - -#define kNumTopBits 24 -#define kTopValue ((UInt32)1 << kNumTopBits) - -#define kNumBitModelTotalBits 11 -#define kBitModelTotal (1 << kNumBitModelTotalBits) -#define kNumMoveBits 5 -#define kProbInitValue (kBitModelTotal >> 1) - -#define kNumMoveReducingBits 4 -#define kNumBitPriceShiftBits 4 -#define kBitPrice (1 << kNumBitPriceShiftBits) - -void LzmaEncProps_Init(CLzmaEncProps *p) -{ - p->level = 5; - p->dictSize = p->mc = 0; - p->lc = p->lp = p->pb = p->algo = p->fb = p->btMode = p->numHashBytes = p->numThreads = -1; - p->writeEndMark = 0; -} - -void LzmaEncProps_Normalize(CLzmaEncProps *p) -{ - int level = p->level; - if (level < 0) level = 5; - p->level = level; - if (p->dictSize == 0) p->dictSize = (level <= 5 ? (1 << (level * 2 + 14)) : (level == 6 ? (1 << 25) : (1 << 26))); - if (p->lc < 0) p->lc = 3; - if (p->lp < 0) p->lp = 0; - if (p->pb < 0) p->pb = 2; - if (p->algo < 0) p->algo = (level < 5 ? 0 : 1); - if (p->fb < 0) p->fb = (level < 7 ? 32 : 64); - if (p->btMode < 0) p->btMode = (p->algo == 0 ? 0 : 1); - if (p->numHashBytes < 0) p->numHashBytes = 4; - if (p->mc == 0) p->mc = (16 + (p->fb >> 1)) >> (p->btMode ? 0 : 1); - if (p->numThreads < 0) p->numThreads = ((p->btMode && p->algo) ? 2 : 1); -} - -UInt32 LzmaEncProps_GetDictSize(const CLzmaEncProps *props2) -{ - CLzmaEncProps props = *props2; - LzmaEncProps_Normalize(&props); - return props.dictSize; -} - -/* #define LZMA_LOG_BSR */ -/* Define it for Intel's CPU */ - - -#ifdef LZMA_LOG_BSR - -#define kDicLogSizeMaxCompress 30 - -#define BSR2_RET(pos, res) { unsigned long i; _BitScanReverse(&i, (pos)); res = (i + i) + ((pos >> (i - 1)) & 1); } - -UInt32 GetPosSlot1(UInt32 pos) -{ - UInt32 res; - BSR2_RET(pos, res); - return res; -} -#define GetPosSlot2(pos, res) { BSR2_RET(pos, res); } -#define GetPosSlot(pos, res) { if (pos < 2) res = pos; else BSR2_RET(pos, res); } - -#else - -#define kNumLogBits (9 + (int)sizeof(size_t) / 2) -#define kDicLogSizeMaxCompress ((kNumLogBits - 1) * 2 + 7) - -void LzmaEnc_FastPosInit(Byte *g_FastPos) -{ - int c = 2, slotFast; - g_FastPos[0] = 0; - g_FastPos[1] = 1; - - for (slotFast = 2; slotFast < kNumLogBits * 2; slotFast++) - { - UInt32 k = (1 << ((slotFast >> 1) - 1)); - UInt32 j; - for (j = 0; j < k; j++, c++) - g_FastPos[c] = (Byte)slotFast; - } -} - -#define BSR2_RET(pos, res) { UInt32 i = 6 + ((kNumLogBits - 1) & \ - (0 - (((((UInt32)1 << (kNumLogBits + 6)) - 1) - pos) >> 31))); \ - res = p->g_FastPos[pos >> i] + (i * 2); } -/* -#define BSR2_RET(pos, res) { res = (pos < (1 << (kNumLogBits + 6))) ? \ - p->g_FastPos[pos >> 6] + 12 : \ - p->g_FastPos[pos >> (6 + kNumLogBits - 1)] + (6 + (kNumLogBits - 1)) * 2; } -*/ - -#define GetPosSlot1(pos) p->g_FastPos[pos] -#define GetPosSlot2(pos, res) { BSR2_RET(pos, res); } -#define GetPosSlot(pos, res) { if (pos < kNumFullDistances) res = p->g_FastPos[pos]; else BSR2_RET(pos, res); } - -#endif - - -#define LZMA_NUM_REPS 4 - -typedef unsigned CState; - -typedef struct _COptimal -{ - UInt32 price; - - CState state; - int prev1IsChar; - int prev2; - - UInt32 posPrev2; - UInt32 backPrev2; - - UInt32 posPrev; - UInt32 backPrev; - UInt32 backs[LZMA_NUM_REPS]; -} COptimal; - -#define kNumOpts (1 << 12) - -#define kNumLenToPosStates 4 -#define kNumPosSlotBits 6 -#define kDicLogSizeMin 0 -#define kDicLogSizeMax 32 -#define kDistTableSizeMax (kDicLogSizeMax * 2) - - -#define kNumAlignBits 4 -#define kAlignTableSize (1 << kNumAlignBits) -#define kAlignMask (kAlignTableSize - 1) - -#define kStartPosModelIndex 4 -#define kEndPosModelIndex 14 -#define kNumPosModels (kEndPosModelIndex - kStartPosModelIndex) - -#define kNumFullDistances (1 << (kEndPosModelIndex / 2)) - -#ifdef _LZMA_PROB32 -#define CLzmaProb UInt32 -#else -#define CLzmaProb UInt16 -#endif - -#define LZMA_PB_MAX 4 -#define LZMA_LC_MAX 8 -#define LZMA_LP_MAX 4 - -#define LZMA_NUM_PB_STATES_MAX (1 << LZMA_PB_MAX) - - -#define kLenNumLowBits 3 -#define kLenNumLowSymbols (1 << kLenNumLowBits) -#define kLenNumMidBits 3 -#define kLenNumMidSymbols (1 << kLenNumMidBits) -#define kLenNumHighBits 8 -#define kLenNumHighSymbols (1 << kLenNumHighBits) - -#define kLenNumSymbolsTotal (kLenNumLowSymbols + kLenNumMidSymbols + kLenNumHighSymbols) - -#define LZMA_MATCH_LEN_MIN 2 -#define LZMA_MATCH_LEN_MAX (LZMA_MATCH_LEN_MIN + kLenNumSymbolsTotal - 1) - -#define kNumStates 12 - -typedef struct -{ - CLzmaProb choice; - CLzmaProb choice2; - CLzmaProb low[LZMA_NUM_PB_STATES_MAX << kLenNumLowBits]; - CLzmaProb mid[LZMA_NUM_PB_STATES_MAX << kLenNumMidBits]; - CLzmaProb high[kLenNumHighSymbols]; -} CLenEnc; - -typedef struct -{ - CLenEnc p; - UInt32 prices[LZMA_NUM_PB_STATES_MAX][kLenNumSymbolsTotal]; - UInt32 tableSize; - UInt32 counters[LZMA_NUM_PB_STATES_MAX]; -} CLenPriceEnc; - -typedef struct _CRangeEnc -{ - UInt32 range; - Byte cache; - UInt64 low; - UInt64 cacheSize; - Byte *buf; - Byte *bufLim; - Byte *bufBase; - ISeqOutStream *outStream; - UInt64 processed; - SRes res; -} CRangeEnc; - -typedef struct _CSeqInStreamBuf -{ - ISeqInStream funcTable; - const Byte *data; - SizeT rem; -} CSeqInStreamBuf; - -static SRes MyRead(void *pp, void *data, size_t *size) -{ - size_t curSize = *size; - CSeqInStreamBuf *p = (CSeqInStreamBuf *)pp; - if (p->rem < curSize) - curSize = p->rem; - memcpy(data, p->data, curSize); - p->rem -= curSize; - p->data += curSize; - *size = curSize; - return SZ_OK; -} - -typedef struct -{ - CLzmaProb *litProbs; - - CLzmaProb isMatch[kNumStates][LZMA_NUM_PB_STATES_MAX]; - CLzmaProb isRep[kNumStates]; - CLzmaProb isRepG0[kNumStates]; - CLzmaProb isRepG1[kNumStates]; - CLzmaProb isRepG2[kNumStates]; - CLzmaProb isRep0Long[kNumStates][LZMA_NUM_PB_STATES_MAX]; - - CLzmaProb posSlotEncoder[kNumLenToPosStates][1 << kNumPosSlotBits]; - CLzmaProb posEncoders[kNumFullDistances - kEndPosModelIndex]; - CLzmaProb posAlignEncoder[1 << kNumAlignBits]; - - CLenPriceEnc lenEnc; - CLenPriceEnc repLenEnc; - - UInt32 reps[LZMA_NUM_REPS]; - UInt32 state; -} CSaveState; - -typedef struct _CLzmaEnc -{ - IMatchFinder matchFinder; - void *matchFinderObj; - - #ifdef COMPRESS_MF_MT - Bool mtMode; - CMatchFinderMt matchFinderMt; - #endif - - CMatchFinder matchFinderBase; - - #ifdef COMPRESS_MF_MT - Byte pad[128]; - #endif - - UInt32 optimumEndIndex; - UInt32 optimumCurrentIndex; - - UInt32 longestMatchLength; - UInt32 numPairs; - UInt32 numAvail; - COptimal opt[kNumOpts]; - - #ifndef LZMA_LOG_BSR - Byte g_FastPos[1 << kNumLogBits]; - #endif - - UInt32 ProbPrices[kBitModelTotal >> kNumMoveReducingBits]; - UInt32 matches[LZMA_MATCH_LEN_MAX * 2 + 2 + 1]; - UInt32 numFastBytes; - UInt32 additionalOffset; - UInt32 reps[LZMA_NUM_REPS]; - UInt32 state; - - UInt32 posSlotPrices[kNumLenToPosStates][kDistTableSizeMax]; - UInt32 distancesPrices[kNumLenToPosStates][kNumFullDistances]; - UInt32 alignPrices[kAlignTableSize]; - UInt32 alignPriceCount; - - UInt32 distTableSize; - - unsigned lc, lp, pb; - unsigned lpMask, pbMask; - - CLzmaProb *litProbs; - - CLzmaProb isMatch[kNumStates][LZMA_NUM_PB_STATES_MAX]; - CLzmaProb isRep[kNumStates]; - CLzmaProb isRepG0[kNumStates]; - CLzmaProb isRepG1[kNumStates]; - CLzmaProb isRepG2[kNumStates]; - CLzmaProb isRep0Long[kNumStates][LZMA_NUM_PB_STATES_MAX]; - - CLzmaProb posSlotEncoder[kNumLenToPosStates][1 << kNumPosSlotBits]; - CLzmaProb posEncoders[kNumFullDistances - kEndPosModelIndex]; - CLzmaProb posAlignEncoder[1 << kNumAlignBits]; - - CLenPriceEnc lenEnc; - CLenPriceEnc repLenEnc; - - unsigned lclp; - - Bool fastMode; - - CRangeEnc rc; - - Bool writeEndMark; - UInt64 nowPos64; - UInt32 matchPriceCount; - Bool finished; - Bool multiThread; - - SRes result; - UInt32 dictSize; - UInt32 matchFinderCycles; - - ISeqInStream *inStream; - CSeqInStreamBuf seqBufInStream; - - CSaveState saveState; -} CLzmaEnc; - -void LzmaEnc_SaveState(CLzmaEncHandle pp) -{ - CLzmaEnc *p = (CLzmaEnc *)pp; - CSaveState *dest = &p->saveState; - int i; - dest->lenEnc = p->lenEnc; - dest->repLenEnc = p->repLenEnc; - dest->state = p->state; - - for (i = 0; i < kNumStates; i++) - { - memcpy(dest->isMatch[i], p->isMatch[i], sizeof(p->isMatch[i])); - memcpy(dest->isRep0Long[i], p->isRep0Long[i], sizeof(p->isRep0Long[i])); - } - for (i = 0; i < kNumLenToPosStates; i++) - memcpy(dest->posSlotEncoder[i], p->posSlotEncoder[i], sizeof(p->posSlotEncoder[i])); - memcpy(dest->isRep, p->isRep, sizeof(p->isRep)); - memcpy(dest->isRepG0, p->isRepG0, sizeof(p->isRepG0)); - memcpy(dest->isRepG1, p->isRepG1, sizeof(p->isRepG1)); - memcpy(dest->isRepG2, p->isRepG2, sizeof(p->isRepG2)); - memcpy(dest->posEncoders, p->posEncoders, sizeof(p->posEncoders)); - memcpy(dest->posAlignEncoder, p->posAlignEncoder, sizeof(p->posAlignEncoder)); - memcpy(dest->reps, p->reps, sizeof(p->reps)); - memcpy(dest->litProbs, p->litProbs, (0x300 << p->lclp) * sizeof(CLzmaProb)); -} - -void LzmaEnc_RestoreState(CLzmaEncHandle pp) -{ - CLzmaEnc *dest = (CLzmaEnc *)pp; - const CSaveState *p = &dest->saveState; - int i; - dest->lenEnc = p->lenEnc; - dest->repLenEnc = p->repLenEnc; - dest->state = p->state; - - for (i = 0; i < kNumStates; i++) - { - memcpy(dest->isMatch[i], p->isMatch[i], sizeof(p->isMatch[i])); - memcpy(dest->isRep0Long[i], p->isRep0Long[i], sizeof(p->isRep0Long[i])); - } - for (i = 0; i < kNumLenToPosStates; i++) - memcpy(dest->posSlotEncoder[i], p->posSlotEncoder[i], sizeof(p->posSlotEncoder[i])); - memcpy(dest->isRep, p->isRep, sizeof(p->isRep)); - memcpy(dest->isRepG0, p->isRepG0, sizeof(p->isRepG0)); - memcpy(dest->isRepG1, p->isRepG1, sizeof(p->isRepG1)); - memcpy(dest->isRepG2, p->isRepG2, sizeof(p->isRepG2)); - memcpy(dest->posEncoders, p->posEncoders, sizeof(p->posEncoders)); - memcpy(dest->posAlignEncoder, p->posAlignEncoder, sizeof(p->posAlignEncoder)); - memcpy(dest->reps, p->reps, sizeof(p->reps)); - memcpy(dest->litProbs, p->litProbs, (0x300 << dest->lclp) * sizeof(CLzmaProb)); -} - -SRes LzmaEnc_SetProps(CLzmaEncHandle pp, const CLzmaEncProps *props2) -{ - CLzmaEnc *p = (CLzmaEnc *)pp; - CLzmaEncProps props = *props2; - LzmaEncProps_Normalize(&props); - - if (props.lc > LZMA_LC_MAX || props.lp > LZMA_LP_MAX || props.pb > LZMA_PB_MAX || - props.dictSize > (1 << kDicLogSizeMaxCompress) || props.dictSize > (1 << 30)) - return SZ_ERROR_PARAM; - p->dictSize = props.dictSize; - p->matchFinderCycles = props.mc; - { - unsigned fb = props.fb; - if (fb < 5) - fb = 5; - if (fb > LZMA_MATCH_LEN_MAX) - fb = LZMA_MATCH_LEN_MAX; - p->numFastBytes = fb; - } - p->lc = props.lc; - p->lp = props.lp; - p->pb = props.pb; - p->fastMode = (props.algo == 0); - p->matchFinderBase.btMode = props.btMode; - { - UInt32 numHashBytes = 4; - if (props.btMode) - { - if (props.numHashBytes < 2) - numHashBytes = 2; - else if (props.numHashBytes < 4) - numHashBytes = props.numHashBytes; - } - p->matchFinderBase.numHashBytes = numHashBytes; - } - - p->matchFinderBase.cutValue = props.mc; - - p->writeEndMark = props.writeEndMark; - - #ifdef COMPRESS_MF_MT - /* - if (newMultiThread != _multiThread) - { - ReleaseMatchFinder(); - _multiThread = newMultiThread; - } - */ - p->multiThread = (props.numThreads > 1); - #endif - - return SZ_OK; -} - -static const int kLiteralNextStates[kNumStates] = {0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 4, 5}; -static const int kMatchNextStates[kNumStates] = {7, 7, 7, 7, 7, 7, 7, 10, 10, 10, 10, 10}; -static const int kRepNextStates[kNumStates] = {8, 8, 8, 8, 8, 8, 8, 11, 11, 11, 11, 11}; -static const int kShortRepNextStates[kNumStates]= {9, 9, 9, 9, 9, 9, 9, 11, 11, 11, 11, 11}; - -#define IsCharState(s) ((s) < 7) - -#define GetLenToPosState(len) (((len) < kNumLenToPosStates + 1) ? (len) - 2 : kNumLenToPosStates - 1) - -#define kInfinityPrice (1 << 30) - -static void RangeEnc_Construct(CRangeEnc *p) -{ - p->outStream = 0; - p->bufBase = 0; -} - -#define RangeEnc_GetProcessed(p) ((p)->processed + ((p)->buf - (p)->bufBase) + (p)->cacheSize) - -#define RC_BUF_SIZE (1 << 16) -static int RangeEnc_Alloc(CRangeEnc *p, ISzAlloc *alloc) -{ - if (p->bufBase == 0) - { - p->bufBase = (Byte *)alloc->Alloc(alloc, RC_BUF_SIZE); - if (p->bufBase == 0) - return 0; - p->bufLim = p->bufBase + RC_BUF_SIZE; - } - return 1; -} - -static void RangeEnc_Free(CRangeEnc *p, ISzAlloc *alloc) -{ - alloc->Free(alloc, p->bufBase); - p->bufBase = 0; -} - -static void RangeEnc_Init(CRangeEnc *p) -{ - /* Stream.Init(); */ - p->low = 0; - p->range = 0xFFFFFFFF; - p->cacheSize = 1; - p->cache = 0; - - p->buf = p->bufBase; - - p->processed = 0; - p->res = SZ_OK; -} - -static void RangeEnc_FlushStream(CRangeEnc *p) -{ - size_t num; - if (p->res != SZ_OK) - return; - num = p->buf - p->bufBase; - if (num != p->outStream->Write(p->outStream, p->bufBase, num)) - p->res = SZ_ERROR_WRITE; - p->processed += num; - p->buf = p->bufBase; -} - -static void MY_FAST_CALL RangeEnc_ShiftLow(CRangeEnc *p) -{ - if ((UInt32)p->low < (UInt32)0xFF000000 || (int)(p->low >> 32) != 0) - { - Byte temp = p->cache; - do - { - Byte *buf = p->buf; - *buf++ = (Byte)(temp + (Byte)(p->low >> 32)); - p->buf = buf; - if (buf == p->bufLim) - RangeEnc_FlushStream(p); - temp = 0xFF; - } - while (--p->cacheSize != 0); - p->cache = (Byte)((UInt32)p->low >> 24); - } - p->cacheSize++; - p->low = (UInt32)p->low << 8; -} - -static void RangeEnc_FlushData(CRangeEnc *p) -{ - int i; - for (i = 0; i < 5; i++) - RangeEnc_ShiftLow(p); -} - -static void RangeEnc_EncodeDirectBits(CRangeEnc *p, UInt32 value, int numBits) -{ - do - { - p->range >>= 1; - p->low += p->range & (0 - ((value >> --numBits) & 1)); - if (p->range < kTopValue) - { - p->range <<= 8; - RangeEnc_ShiftLow(p); - } - } - while (numBits != 0); -} - -static void RangeEnc_EncodeBit(CRangeEnc *p, CLzmaProb *prob, UInt32 symbol) -{ - UInt32 ttt = *prob; - UInt32 newBound = (p->range >> kNumBitModelTotalBits) * ttt; - if (symbol == 0) - { - p->range = newBound; - ttt += (kBitModelTotal - ttt) >> kNumMoveBits; - } - else - { - p->low += newBound; - p->range -= newBound; - ttt -= ttt >> kNumMoveBits; - } - *prob = (CLzmaProb)ttt; - if (p->range < kTopValue) - { - p->range <<= 8; - RangeEnc_ShiftLow(p); - } -} - -static void LitEnc_Encode(CRangeEnc *p, CLzmaProb *probs, UInt32 symbol) -{ - symbol |= 0x100; - do - { - RangeEnc_EncodeBit(p, probs + (symbol >> 8), (symbol >> 7) & 1); - symbol <<= 1; - } - while (symbol < 0x10000); -} - -static void LitEnc_EncodeMatched(CRangeEnc *p, CLzmaProb *probs, UInt32 symbol, UInt32 matchByte) -{ - UInt32 offs = 0x100; - symbol |= 0x100; - do - { - matchByte <<= 1; - RangeEnc_EncodeBit(p, probs + (offs + (matchByte & offs) + (symbol >> 8)), (symbol >> 7) & 1); - symbol <<= 1; - offs &= ~(matchByte ^ symbol); - } - while (symbol < 0x10000); -} - -void LzmaEnc_InitPriceTables(UInt32 *ProbPrices) -{ - UInt32 i; - for (i = (1 << kNumMoveReducingBits) / 2; i < kBitModelTotal; i += (1 << kNumMoveReducingBits)) - { - const int kCyclesBits = kNumBitPriceShiftBits; - UInt32 w = i; - UInt32 bitCount = 0; - int j; - for (j = 0; j < kCyclesBits; j++) - { - w = w * w; - bitCount <<= 1; - while (w >= ((UInt32)1 << 16)) - { - w >>= 1; - bitCount++; - } - } - ProbPrices[i >> kNumMoveReducingBits] = ((kNumBitModelTotalBits << kCyclesBits) - 15 - bitCount); - } -} - - -#define GET_PRICE(prob, symbol) \ - p->ProbPrices[((prob) ^ (((-(int)(symbol))) & (kBitModelTotal - 1))) >> kNumMoveReducingBits]; - -#define GET_PRICEa(prob, symbol) \ - ProbPrices[((prob) ^ ((-((int)(symbol))) & (kBitModelTotal - 1))) >> kNumMoveReducingBits]; - -#define GET_PRICE_0(prob) p->ProbPrices[(prob) >> kNumMoveReducingBits] -#define GET_PRICE_1(prob) p->ProbPrices[((prob) ^ (kBitModelTotal - 1)) >> kNumMoveReducingBits] - -#define GET_PRICE_0a(prob) ProbPrices[(prob) >> kNumMoveReducingBits] -#define GET_PRICE_1a(prob) ProbPrices[((prob) ^ (kBitModelTotal - 1)) >> kNumMoveReducingBits] - -static UInt32 LitEnc_GetPrice(const CLzmaProb *probs, UInt32 symbol, UInt32 *ProbPrices) -{ - UInt32 price = 0; - symbol |= 0x100; - do - { - price += GET_PRICEa(probs[symbol >> 8], (symbol >> 7) & 1); - symbol <<= 1; - } - while (symbol < 0x10000); - return price; -} - -static UInt32 LitEnc_GetPriceMatched(const CLzmaProb *probs, UInt32 symbol, UInt32 matchByte, UInt32 *ProbPrices) -{ - UInt32 price = 0; - UInt32 offs = 0x100; - symbol |= 0x100; - do - { - matchByte <<= 1; - price += GET_PRICEa(probs[offs + (matchByte & offs) + (symbol >> 8)], (symbol >> 7) & 1); - symbol <<= 1; - offs &= ~(matchByte ^ symbol); - } - while (symbol < 0x10000); - return price; -} - - -static void RcTree_Encode(CRangeEnc *rc, CLzmaProb *probs, int numBitLevels, UInt32 symbol) -{ - UInt32 m = 1; - int i; - for (i = numBitLevels; i != 0;) - { - UInt32 bit; - i--; - bit = (symbol >> i) & 1; - RangeEnc_EncodeBit(rc, probs + m, bit); - m = (m << 1) | bit; - } -} - -static void RcTree_ReverseEncode(CRangeEnc *rc, CLzmaProb *probs, int numBitLevels, UInt32 symbol) -{ - UInt32 m = 1; - int i; - for (i = 0; i < numBitLevels; i++) - { - UInt32 bit = symbol & 1; - RangeEnc_EncodeBit(rc, probs + m, bit); - m = (m << 1) | bit; - symbol >>= 1; - } -} - -static UInt32 RcTree_GetPrice(const CLzmaProb *probs, int numBitLevels, UInt32 symbol, UInt32 *ProbPrices) -{ - UInt32 price = 0; - symbol |= (1 << numBitLevels); - while (symbol != 1) - { - price += GET_PRICEa(probs[symbol >> 1], symbol & 1); - symbol >>= 1; - } - return price; -} - -static UInt32 RcTree_ReverseGetPrice(const CLzmaProb *probs, int numBitLevels, UInt32 symbol, UInt32 *ProbPrices) -{ - UInt32 price = 0; - UInt32 m = 1; - int i; - for (i = numBitLevels; i != 0; i--) - { - UInt32 bit = symbol & 1; - symbol >>= 1; - price += GET_PRICEa(probs[m], bit); - m = (m << 1) | bit; - } - return price; -} - - -static void LenEnc_Init(CLenEnc *p) -{ - unsigned i; - p->choice = p->choice2 = kProbInitValue; - for (i = 0; i < (LZMA_NUM_PB_STATES_MAX << kLenNumLowBits); i++) - p->low[i] = kProbInitValue; - for (i = 0; i < (LZMA_NUM_PB_STATES_MAX << kLenNumMidBits); i++) - p->mid[i] = kProbInitValue; - for (i = 0; i < kLenNumHighSymbols; i++) - p->high[i] = kProbInitValue; -} - -static void LenEnc_Encode(CLenEnc *p, CRangeEnc *rc, UInt32 symbol, UInt32 posState) -{ - if (symbol < kLenNumLowSymbols) - { - RangeEnc_EncodeBit(rc, &p->choice, 0); - RcTree_Encode(rc, p->low + (posState << kLenNumLowBits), kLenNumLowBits, symbol); - } - else - { - RangeEnc_EncodeBit(rc, &p->choice, 1); - if (symbol < kLenNumLowSymbols + kLenNumMidSymbols) - { - RangeEnc_EncodeBit(rc, &p->choice2, 0); - RcTree_Encode(rc, p->mid + (posState << kLenNumMidBits), kLenNumMidBits, symbol - kLenNumLowSymbols); - } - else - { - RangeEnc_EncodeBit(rc, &p->choice2, 1); - RcTree_Encode(rc, p->high, kLenNumHighBits, symbol - kLenNumLowSymbols - kLenNumMidSymbols); - } - } -} - -static void LenEnc_SetPrices(CLenEnc *p, UInt32 posState, UInt32 numSymbols, UInt32 *prices, UInt32 *ProbPrices) -{ - UInt32 a0 = GET_PRICE_0a(p->choice); - UInt32 a1 = GET_PRICE_1a(p->choice); - UInt32 b0 = a1 + GET_PRICE_0a(p->choice2); - UInt32 b1 = a1 + GET_PRICE_1a(p->choice2); - UInt32 i = 0; - for (i = 0; i < kLenNumLowSymbols; i++) - { - if (i >= numSymbols) - return; - prices[i] = a0 + RcTree_GetPrice(p->low + (posState << kLenNumLowBits), kLenNumLowBits, i, ProbPrices); - } - for (; i < kLenNumLowSymbols + kLenNumMidSymbols; i++) - { - if (i >= numSymbols) - return; - prices[i] = b0 + RcTree_GetPrice(p->mid + (posState << kLenNumMidBits), kLenNumMidBits, i - kLenNumLowSymbols, ProbPrices); - } - for (; i < numSymbols; i++) - prices[i] = b1 + RcTree_GetPrice(p->high, kLenNumHighBits, i - kLenNumLowSymbols - kLenNumMidSymbols, ProbPrices); -} - -static void MY_FAST_CALL LenPriceEnc_UpdateTable(CLenPriceEnc *p, UInt32 posState, UInt32 *ProbPrices) -{ - LenEnc_SetPrices(&p->p, posState, p->tableSize, p->prices[posState], ProbPrices); - p->counters[posState] = p->tableSize; -} - -static void LenPriceEnc_UpdateTables(CLenPriceEnc *p, UInt32 numPosStates, UInt32 *ProbPrices) -{ - UInt32 posState; - for (posState = 0; posState < numPosStates; posState++) - LenPriceEnc_UpdateTable(p, posState, ProbPrices); -} - -static void LenEnc_Encode2(CLenPriceEnc *p, CRangeEnc *rc, UInt32 symbol, UInt32 posState, Bool updatePrice, UInt32 *ProbPrices) -{ - LenEnc_Encode(&p->p, rc, symbol, posState); - if (updatePrice) - if (--p->counters[posState] == 0) - LenPriceEnc_UpdateTable(p, posState, ProbPrices); -} - - - - -static void MovePos(CLzmaEnc *p, UInt32 num) -{ - #ifdef SHOW_STAT - ttt += num; - printf("\n MovePos %d", num); - #endif - if (num != 0) - { - p->additionalOffset += num; - p->matchFinder.Skip(p->matchFinderObj, num); - } -} - -static UInt32 ReadMatchDistances(CLzmaEnc *p, UInt32 *numDistancePairsRes) -{ - UInt32 lenRes = 0, numPairs; - p->numAvail = p->matchFinder.GetNumAvailableBytes(p->matchFinderObj); - numPairs = p->matchFinder.GetMatches(p->matchFinderObj, p->matches); - #ifdef SHOW_STAT - printf("\n i = %d numPairs = %d ", ttt, numPairs / 2); - ttt++; - { - UInt32 i; - for (i = 0; i < numPairs; i += 2) - printf("%2d %6d | ", p->matches[i], p->matches[i + 1]); - } - #endif - if (numPairs > 0) - { - lenRes = p->matches[numPairs - 2]; - if (lenRes == p->numFastBytes) - { - const Byte *pby = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1; - UInt32 distance = p->matches[numPairs - 1] + 1; - UInt32 numAvail = p->numAvail; - if (numAvail > LZMA_MATCH_LEN_MAX) - numAvail = LZMA_MATCH_LEN_MAX; - { - const Byte *pby2 = pby - distance; - for (; lenRes < numAvail && pby[lenRes] == pby2[lenRes]; lenRes++); - } - } - } - p->additionalOffset++; - *numDistancePairsRes = numPairs; - return lenRes; -} - - -#define MakeAsChar(p) (p)->backPrev = (UInt32)(-1); (p)->prev1IsChar = False; -#define MakeAsShortRep(p) (p)->backPrev = 0; (p)->prev1IsChar = False; -#define IsShortRep(p) ((p)->backPrev == 0) - -static UInt32 GetRepLen1Price(CLzmaEnc *p, UInt32 state, UInt32 posState) -{ - return - GET_PRICE_0(p->isRepG0[state]) + - GET_PRICE_0(p->isRep0Long[state][posState]); -} - -static UInt32 GetPureRepPrice(CLzmaEnc *p, UInt32 repIndex, UInt32 state, UInt32 posState) -{ - UInt32 price; - if (repIndex == 0) - { - price = GET_PRICE_0(p->isRepG0[state]); - price += GET_PRICE_1(p->isRep0Long[state][posState]); - } - else - { - price = GET_PRICE_1(p->isRepG0[state]); - if (repIndex == 1) - price += GET_PRICE_0(p->isRepG1[state]); - else - { - price += GET_PRICE_1(p->isRepG1[state]); - price += GET_PRICE(p->isRepG2[state], repIndex - 2); - } - } - return price; -} - -static UInt32 GetRepPrice(CLzmaEnc *p, UInt32 repIndex, UInt32 len, UInt32 state, UInt32 posState) -{ - return p->repLenEnc.prices[posState][len - LZMA_MATCH_LEN_MIN] + - GetPureRepPrice(p, repIndex, state, posState); -} - -static UInt32 Backward(CLzmaEnc *p, UInt32 *backRes, UInt32 cur) -{ - UInt32 posMem = p->opt[cur].posPrev; - UInt32 backMem = p->opt[cur].backPrev; - p->optimumEndIndex = cur; - do - { - if (p->opt[cur].prev1IsChar) - { - MakeAsChar(&p->opt[posMem]) - p->opt[posMem].posPrev = posMem - 1; - if (p->opt[cur].prev2) - { - p->opt[posMem - 1].prev1IsChar = False; - p->opt[posMem - 1].posPrev = p->opt[cur].posPrev2; - p->opt[posMem - 1].backPrev = p->opt[cur].backPrev2; - } - } - { - UInt32 posPrev = posMem; - UInt32 backCur = backMem; - - backMem = p->opt[posPrev].backPrev; - posMem = p->opt[posPrev].posPrev; - - p->opt[posPrev].backPrev = backCur; - p->opt[posPrev].posPrev = cur; - cur = posPrev; - } - } - while (cur != 0); - *backRes = p->opt[0].backPrev; - p->optimumCurrentIndex = p->opt[0].posPrev; - return p->optimumCurrentIndex; -} - -#define LIT_PROBS(pos, prevByte) (p->litProbs + ((((pos) & p->lpMask) << p->lc) + ((prevByte) >> (8 - p->lc))) * 0x300) - -static UInt32 GetOptimum(CLzmaEnc *p, UInt32 position, UInt32 *backRes) -{ - UInt32 numAvail, mainLen, numPairs, repMaxIndex, i, posState, lenEnd, len, cur; - UInt32 matchPrice, repMatchPrice, normalMatchPrice; - UInt32 reps[LZMA_NUM_REPS], repLens[LZMA_NUM_REPS]; - UInt32 *matches; - const Byte *data; - Byte curByte, matchByte; - if (p->optimumEndIndex != p->optimumCurrentIndex) - { - const COptimal *opt = &p->opt[p->optimumCurrentIndex]; - UInt32 lenRes = opt->posPrev - p->optimumCurrentIndex; - *backRes = opt->backPrev; - p->optimumCurrentIndex = opt->posPrev; - return lenRes; - } - p->optimumCurrentIndex = p->optimumEndIndex = 0; - - if (p->additionalOffset == 0) - mainLen = ReadMatchDistances(p, &numPairs); - else - { - mainLen = p->longestMatchLength; - numPairs = p->numPairs; - } - - numAvail = p->numAvail; - if (numAvail < 2) - { - *backRes = (UInt32)(-1); - return 1; - } - if (numAvail > LZMA_MATCH_LEN_MAX) - numAvail = LZMA_MATCH_LEN_MAX; - - data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1; - repMaxIndex = 0; - for (i = 0; i < LZMA_NUM_REPS; i++) - { - UInt32 lenTest; - const Byte *data2; - reps[i] = p->reps[i]; - data2 = data - (reps[i] + 1); - if (data[0] != data2[0] || data[1] != data2[1]) - { - repLens[i] = 0; - continue; - } - for (lenTest = 2; lenTest < numAvail && data[lenTest] == data2[lenTest]; lenTest++); - repLens[i] = lenTest; - if (lenTest > repLens[repMaxIndex]) - repMaxIndex = i; - } - if (repLens[repMaxIndex] >= p->numFastBytes) - { - UInt32 lenRes; - *backRes = repMaxIndex; - lenRes = repLens[repMaxIndex]; - MovePos(p, lenRes - 1); - return lenRes; - } - - matches = p->matches; - if (mainLen >= p->numFastBytes) - { - *backRes = matches[numPairs - 1] + LZMA_NUM_REPS; - MovePos(p, mainLen - 1); - return mainLen; - } - curByte = *data; - matchByte = *(data - (reps[0] + 1)); - - if (mainLen < 2 && curByte != matchByte && repLens[repMaxIndex] < 2) - { - *backRes = (UInt32)-1; - return 1; - } - - p->opt[0].state = (CState)p->state; - - posState = (position & p->pbMask); - - { - const CLzmaProb *probs = LIT_PROBS(position, *(data - 1)); - p->opt[1].price = GET_PRICE_0(p->isMatch[p->state][posState]) + - (!IsCharState(p->state) ? - LitEnc_GetPriceMatched(probs, curByte, matchByte, p->ProbPrices) : - LitEnc_GetPrice(probs, curByte, p->ProbPrices)); - } - - MakeAsChar(&p->opt[1]); - - matchPrice = GET_PRICE_1(p->isMatch[p->state][posState]); - repMatchPrice = matchPrice + GET_PRICE_1(p->isRep[p->state]); - - if (matchByte == curByte) - { - UInt32 shortRepPrice = repMatchPrice + GetRepLen1Price(p, p->state, posState); - if (shortRepPrice < p->opt[1].price) - { - p->opt[1].price = shortRepPrice; - MakeAsShortRep(&p->opt[1]); - } - } - lenEnd = ((mainLen >= repLens[repMaxIndex]) ? mainLen : repLens[repMaxIndex]); - - if (lenEnd < 2) - { - *backRes = p->opt[1].backPrev; - return 1; - } - - p->opt[1].posPrev = 0; - for (i = 0; i < LZMA_NUM_REPS; i++) - p->opt[0].backs[i] = reps[i]; - - len = lenEnd; - do - p->opt[len--].price = kInfinityPrice; - while (len >= 2); - - for (i = 0; i < LZMA_NUM_REPS; i++) - { - UInt32 repLen = repLens[i]; - UInt32 price; - if (repLen < 2) - continue; - price = repMatchPrice + GetPureRepPrice(p, i, p->state, posState); - do - { - UInt32 curAndLenPrice = price + p->repLenEnc.prices[posState][repLen - 2]; - COptimal *opt = &p->opt[repLen]; - if (curAndLenPrice < opt->price) - { - opt->price = curAndLenPrice; - opt->posPrev = 0; - opt->backPrev = i; - opt->prev1IsChar = False; - } - } - while (--repLen >= 2); - } - - normalMatchPrice = matchPrice + GET_PRICE_0(p->isRep[p->state]); - - len = ((repLens[0] >= 2) ? repLens[0] + 1 : 2); - if (len <= mainLen) - { - UInt32 offs = 0; - while (len > matches[offs]) - offs += 2; - for (; ; len++) - { - COptimal *opt; - UInt32 distance = matches[offs + 1]; - - UInt32 curAndLenPrice = normalMatchPrice + p->lenEnc.prices[posState][len - LZMA_MATCH_LEN_MIN]; - UInt32 lenToPosState = GetLenToPosState(len); - if (distance < kNumFullDistances) - curAndLenPrice += p->distancesPrices[lenToPosState][distance]; - else - { - UInt32 slot; - GetPosSlot2(distance, slot); - curAndLenPrice += p->alignPrices[distance & kAlignMask] + p->posSlotPrices[lenToPosState][slot]; - } - opt = &p->opt[len]; - if (curAndLenPrice < opt->price) - { - opt->price = curAndLenPrice; - opt->posPrev = 0; - opt->backPrev = distance + LZMA_NUM_REPS; - opt->prev1IsChar = False; - } - if (len == matches[offs]) - { - offs += 2; - if (offs == numPairs) - break; - } - } - } - - cur = 0; - - #ifdef SHOW_STAT2 - if (position >= 0) - { - unsigned i; - printf("\n pos = %4X", position); - for (i = cur; i <= lenEnd; i++) - printf("\nprice[%4X] = %d", position - cur + i, p->opt[i].price); - } - #endif - - for (;;) - { - UInt32 numAvailFull, newLen, numPairs, posPrev, state, posState, startLen; - UInt32 curPrice, curAnd1Price, matchPrice, repMatchPrice; - Bool nextIsChar; - Byte curByte, matchByte; - const Byte *data; - COptimal *curOpt; - COptimal *nextOpt; - - cur++; - if (cur == lenEnd) - return Backward(p, backRes, cur); - - newLen = ReadMatchDistances(p, &numPairs); - if (newLen >= p->numFastBytes) - { - p->numPairs = numPairs; - p->longestMatchLength = newLen; - return Backward(p, backRes, cur); - } - position++; - curOpt = &p->opt[cur]; - posPrev = curOpt->posPrev; - if (curOpt->prev1IsChar) - { - posPrev--; - if (curOpt->prev2) - { - state = p->opt[curOpt->posPrev2].state; - if (curOpt->backPrev2 < LZMA_NUM_REPS) - state = kRepNextStates[state]; - else - state = kMatchNextStates[state]; - } - else - state = p->opt[posPrev].state; - state = kLiteralNextStates[state]; - } - else - state = p->opt[posPrev].state; - if (posPrev == cur - 1) - { - if (IsShortRep(curOpt)) - state = kShortRepNextStates[state]; - else - state = kLiteralNextStates[state]; - } - else - { - UInt32 pos; - const COptimal *prevOpt; - if (curOpt->prev1IsChar && curOpt->prev2) - { - posPrev = curOpt->posPrev2; - pos = curOpt->backPrev2; - state = kRepNextStates[state]; - } - else - { - pos = curOpt->backPrev; - if (pos < LZMA_NUM_REPS) - state = kRepNextStates[state]; - else - state = kMatchNextStates[state]; - } - prevOpt = &p->opt[posPrev]; - if (pos < LZMA_NUM_REPS) - { - UInt32 i; - reps[0] = prevOpt->backs[pos]; - for (i = 1; i <= pos; i++) - reps[i] = prevOpt->backs[i - 1]; - for (; i < LZMA_NUM_REPS; i++) - reps[i] = prevOpt->backs[i]; - } - else - { - UInt32 i; - reps[0] = (pos - LZMA_NUM_REPS); - for (i = 1; i < LZMA_NUM_REPS; i++) - reps[i] = prevOpt->backs[i - 1]; - } - } - curOpt->state = (CState)state; - - curOpt->backs[0] = reps[0]; - curOpt->backs[1] = reps[1]; - curOpt->backs[2] = reps[2]; - curOpt->backs[3] = reps[3]; - - curPrice = curOpt->price; - nextIsChar = False; - data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1; - curByte = *data; - matchByte = *(data - (reps[0] + 1)); - - posState = (position & p->pbMask); - - curAnd1Price = curPrice + GET_PRICE_0(p->isMatch[state][posState]); - { - const CLzmaProb *probs = LIT_PROBS(position, *(data - 1)); - curAnd1Price += - (!IsCharState(state) ? - LitEnc_GetPriceMatched(probs, curByte, matchByte, p->ProbPrices) : - LitEnc_GetPrice(probs, curByte, p->ProbPrices)); - } - - nextOpt = &p->opt[cur + 1]; - - if (curAnd1Price < nextOpt->price) - { - nextOpt->price = curAnd1Price; - nextOpt->posPrev = cur; - MakeAsChar(nextOpt); - nextIsChar = True; - } - - matchPrice = curPrice + GET_PRICE_1(p->isMatch[state][posState]); - repMatchPrice = matchPrice + GET_PRICE_1(p->isRep[state]); - - if (matchByte == curByte && !(nextOpt->posPrev < cur && nextOpt->backPrev == 0)) - { - UInt32 shortRepPrice = repMatchPrice + GetRepLen1Price(p, state, posState); - if (shortRepPrice <= nextOpt->price) - { - nextOpt->price = shortRepPrice; - nextOpt->posPrev = cur; - MakeAsShortRep(nextOpt); - nextIsChar = True; - } - } - numAvailFull = p->numAvail; - { - UInt32 temp = kNumOpts - 1 - cur; - if (temp < numAvailFull) - numAvailFull = temp; - } - - if (numAvailFull < 2) - continue; - numAvail = (numAvailFull <= p->numFastBytes ? numAvailFull : p->numFastBytes); - - if (!nextIsChar && matchByte != curByte) /* speed optimization */ - { - /* try Literal + rep0 */ - UInt32 temp; - UInt32 lenTest2; - const Byte *data2 = data - (reps[0] + 1); - UInt32 limit = p->numFastBytes + 1; - if (limit > numAvailFull) - limit = numAvailFull; - - for (temp = 1; temp < limit && data[temp] == data2[temp]; temp++); - lenTest2 = temp - 1; - if (lenTest2 >= 2) - { - UInt32 state2 = kLiteralNextStates[state]; - UInt32 posStateNext = (position + 1) & p->pbMask; - UInt32 nextRepMatchPrice = curAnd1Price + - GET_PRICE_1(p->isMatch[state2][posStateNext]) + - GET_PRICE_1(p->isRep[state2]); - /* for (; lenTest2 >= 2; lenTest2--) */ - { - UInt32 curAndLenPrice; - COptimal *opt; - UInt32 offset = cur + 1 + lenTest2; - while (lenEnd < offset) - p->opt[++lenEnd].price = kInfinityPrice; - curAndLenPrice = nextRepMatchPrice + GetRepPrice(p, 0, lenTest2, state2, posStateNext); - opt = &p->opt[offset]; - if (curAndLenPrice < opt->price) - { - opt->price = curAndLenPrice; - opt->posPrev = cur + 1; - opt->backPrev = 0; - opt->prev1IsChar = True; - opt->prev2 = False; - } - } - } - } - - startLen = 2; /* speed optimization */ - { - UInt32 repIndex; - for (repIndex = 0; repIndex < LZMA_NUM_REPS; repIndex++) - { - UInt32 lenTest; - UInt32 lenTestTemp; - UInt32 price; - const Byte *data2 = data - (reps[repIndex] + 1); - if (data[0] != data2[0] || data[1] != data2[1]) - continue; - for (lenTest = 2; lenTest < numAvail && data[lenTest] == data2[lenTest]; lenTest++); - while (lenEnd < cur + lenTest) - p->opt[++lenEnd].price = kInfinityPrice; - lenTestTemp = lenTest; - price = repMatchPrice + GetPureRepPrice(p, repIndex, state, posState); - do - { - UInt32 curAndLenPrice = price + p->repLenEnc.prices[posState][lenTest - 2]; - COptimal *opt = &p->opt[cur + lenTest]; - if (curAndLenPrice < opt->price) - { - opt->price = curAndLenPrice; - opt->posPrev = cur; - opt->backPrev = repIndex; - opt->prev1IsChar = False; - } - } - while (--lenTest >= 2); - lenTest = lenTestTemp; - - if (repIndex == 0) - startLen = lenTest + 1; - - /* if (_maxMode) */ - { - UInt32 lenTest2 = lenTest + 1; - UInt32 limit = lenTest2 + p->numFastBytes; - UInt32 nextRepMatchPrice; - if (limit > numAvailFull) - limit = numAvailFull; - for (; lenTest2 < limit && data[lenTest2] == data2[lenTest2]; lenTest2++); - lenTest2 -= lenTest + 1; - if (lenTest2 >= 2) - { - UInt32 state2 = kRepNextStates[state]; - UInt32 posStateNext = (position + lenTest) & p->pbMask; - UInt32 curAndLenCharPrice = - price + p->repLenEnc.prices[posState][lenTest - 2] + - GET_PRICE_0(p->isMatch[state2][posStateNext]) + - LitEnc_GetPriceMatched(LIT_PROBS(position + lenTest, data[lenTest - 1]), - data[lenTest], data2[lenTest], p->ProbPrices); - state2 = kLiteralNextStates[state2]; - posStateNext = (position + lenTest + 1) & p->pbMask; - nextRepMatchPrice = curAndLenCharPrice + - GET_PRICE_1(p->isMatch[state2][posStateNext]) + - GET_PRICE_1(p->isRep[state2]); - - /* for (; lenTest2 >= 2; lenTest2--) */ - { - UInt32 curAndLenPrice; - COptimal *opt; - UInt32 offset = cur + lenTest + 1 + lenTest2; - while (lenEnd < offset) - p->opt[++lenEnd].price = kInfinityPrice; - curAndLenPrice = nextRepMatchPrice + GetRepPrice(p, 0, lenTest2, state2, posStateNext); - opt = &p->opt[offset]; - if (curAndLenPrice < opt->price) - { - opt->price = curAndLenPrice; - opt->posPrev = cur + lenTest + 1; - opt->backPrev = 0; - opt->prev1IsChar = True; - opt->prev2 = True; - opt->posPrev2 = cur; - opt->backPrev2 = repIndex; - } - } - } - } - } - } - /* for (UInt32 lenTest = 2; lenTest <= newLen; lenTest++) */ - if (newLen > numAvail) - { - newLen = numAvail; - for (numPairs = 0; newLen > matches[numPairs]; numPairs += 2); - matches[numPairs] = newLen; - numPairs += 2; - } - if (newLen >= startLen) - { - UInt32 normalMatchPrice = matchPrice + GET_PRICE_0(p->isRep[state]); - UInt32 offs, curBack, posSlot; - UInt32 lenTest; - while (lenEnd < cur + newLen) - p->opt[++lenEnd].price = kInfinityPrice; - - offs = 0; - while (startLen > matches[offs]) - offs += 2; - curBack = matches[offs + 1]; - GetPosSlot2(curBack, posSlot); - for (lenTest = /*2*/ startLen; ; lenTest++) - { - UInt32 curAndLenPrice = normalMatchPrice + p->lenEnc.prices[posState][lenTest - LZMA_MATCH_LEN_MIN]; - UInt32 lenToPosState = GetLenToPosState(lenTest); - COptimal *opt; - if (curBack < kNumFullDistances) - curAndLenPrice += p->distancesPrices[lenToPosState][curBack]; - else - curAndLenPrice += p->posSlotPrices[lenToPosState][posSlot] + p->alignPrices[curBack & kAlignMask]; - - opt = &p->opt[cur + lenTest]; - if (curAndLenPrice < opt->price) - { - opt->price = curAndLenPrice; - opt->posPrev = cur; - opt->backPrev = curBack + LZMA_NUM_REPS; - opt->prev1IsChar = False; - } - - if (/*_maxMode && */lenTest == matches[offs]) - { - /* Try Match + Literal + Rep0 */ - const Byte *data2 = data - (curBack + 1); - UInt32 lenTest2 = lenTest + 1; - UInt32 limit = lenTest2 + p->numFastBytes; - UInt32 nextRepMatchPrice; - if (limit > numAvailFull) - limit = numAvailFull; - for (; lenTest2 < limit && data[lenTest2] == data2[lenTest2]; lenTest2++); - lenTest2 -= lenTest + 1; - if (lenTest2 >= 2) - { - UInt32 state2 = kMatchNextStates[state]; - UInt32 posStateNext = (position + lenTest) & p->pbMask; - UInt32 curAndLenCharPrice = curAndLenPrice + - GET_PRICE_0(p->isMatch[state2][posStateNext]) + - LitEnc_GetPriceMatched(LIT_PROBS(position + lenTest, data[lenTest - 1]), - data[lenTest], data2[lenTest], p->ProbPrices); - state2 = kLiteralNextStates[state2]; - posStateNext = (posStateNext + 1) & p->pbMask; - nextRepMatchPrice = curAndLenCharPrice + - GET_PRICE_1(p->isMatch[state2][posStateNext]) + - GET_PRICE_1(p->isRep[state2]); - - /* for (; lenTest2 >= 2; lenTest2--) */ - { - UInt32 offset = cur + lenTest + 1 + lenTest2; - UInt32 curAndLenPrice; - COptimal *opt; - while (lenEnd < offset) - p->opt[++lenEnd].price = kInfinityPrice; - curAndLenPrice = nextRepMatchPrice + GetRepPrice(p, 0, lenTest2, state2, posStateNext); - opt = &p->opt[offset]; - if (curAndLenPrice < opt->price) - { - opt->price = curAndLenPrice; - opt->posPrev = cur + lenTest + 1; - opt->backPrev = 0; - opt->prev1IsChar = True; - opt->prev2 = True; - opt->posPrev2 = cur; - opt->backPrev2 = curBack + LZMA_NUM_REPS; - } - } - } - offs += 2; - if (offs == numPairs) - break; - curBack = matches[offs + 1]; - if (curBack >= kNumFullDistances) - GetPosSlot2(curBack, posSlot); - } - } - } - } -} - -#define ChangePair(smallDist, bigDist) (((bigDist) >> 7) > (smallDist)) - -static UInt32 GetOptimumFast(CLzmaEnc *p, UInt32 *backRes) -{ - UInt32 numAvail, mainLen, mainDist, numPairs, repIndex, repLen, i; - const Byte *data; - const UInt32 *matches; - - if (p->additionalOffset == 0) - mainLen = ReadMatchDistances(p, &numPairs); - else - { - mainLen = p->longestMatchLength; - numPairs = p->numPairs; - } - - numAvail = p->numAvail; - *backRes = (UInt32)-1; - if (numAvail < 2) - return 1; - if (numAvail > LZMA_MATCH_LEN_MAX) - numAvail = LZMA_MATCH_LEN_MAX; - data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1; - - repLen = repIndex = 0; - for (i = 0; i < LZMA_NUM_REPS; i++) - { - UInt32 len; - const Byte *data2 = data - (p->reps[i] + 1); - if (data[0] != data2[0] || data[1] != data2[1]) - continue; - for (len = 2; len < numAvail && data[len] == data2[len]; len++); - if (len >= p->numFastBytes) - { - *backRes = i; - MovePos(p, len - 1); - return len; - } - if (len > repLen) - { - repIndex = i; - repLen = len; - } - } - - matches = p->matches; - if (mainLen >= p->numFastBytes) - { - *backRes = matches[numPairs - 1] + LZMA_NUM_REPS; - MovePos(p, mainLen - 1); - return mainLen; - } - - mainDist = 0; /* for GCC */ - if (mainLen >= 2) - { - mainDist = matches[numPairs - 1]; - while (numPairs > 2 && mainLen == matches[numPairs - 4] + 1) - { - if (!ChangePair(matches[numPairs - 3], mainDist)) - break; - numPairs -= 2; - mainLen = matches[numPairs - 2]; - mainDist = matches[numPairs - 1]; - } - if (mainLen == 2 && mainDist >= 0x80) - mainLen = 1; - } - - if (repLen >= 2 && ( - (repLen + 1 >= mainLen) || - (repLen + 2 >= mainLen && mainDist >= (1 << 9)) || - (repLen + 3 >= mainLen && mainDist >= (1 << 15)))) - { - *backRes = repIndex; - MovePos(p, repLen - 1); - return repLen; - } - - if (mainLen < 2 || numAvail <= 2) - return 1; - - p->longestMatchLength = ReadMatchDistances(p, &p->numPairs); - if (p->longestMatchLength >= 2) - { - UInt32 newDistance = matches[p->numPairs - 1]; - if ((p->longestMatchLength >= mainLen && newDistance < mainDist) || - (p->longestMatchLength == mainLen + 1 && !ChangePair(mainDist, newDistance)) || - (p->longestMatchLength > mainLen + 1) || - (p->longestMatchLength + 1 >= mainLen && mainLen >= 3 && ChangePair(newDistance, mainDist))) - return 1; - } - - data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1; - for (i = 0; i < LZMA_NUM_REPS; i++) - { - UInt32 len, limit; - const Byte *data2 = data - (p->reps[i] + 1); - if (data[0] != data2[0] || data[1] != data2[1]) - continue; - limit = mainLen - 1; - for (len = 2; len < limit && data[len] == data2[len]; len++); - if (len >= limit) - return 1; - } - *backRes = mainDist + LZMA_NUM_REPS; - MovePos(p, mainLen - 2); - return mainLen; -} - -static void WriteEndMarker(CLzmaEnc *p, UInt32 posState) -{ - UInt32 len; - RangeEnc_EncodeBit(&p->rc, &p->isMatch[p->state][posState], 1); - RangeEnc_EncodeBit(&p->rc, &p->isRep[p->state], 0); - p->state = kMatchNextStates[p->state]; - len = LZMA_MATCH_LEN_MIN; - LenEnc_Encode2(&p->lenEnc, &p->rc, len - LZMA_MATCH_LEN_MIN, posState, !p->fastMode, p->ProbPrices); - RcTree_Encode(&p->rc, p->posSlotEncoder[GetLenToPosState(len)], kNumPosSlotBits, (1 << kNumPosSlotBits) - 1); - RangeEnc_EncodeDirectBits(&p->rc, (((UInt32)1 << 30) - 1) >> kNumAlignBits, 30 - kNumAlignBits); - RcTree_ReverseEncode(&p->rc, p->posAlignEncoder, kNumAlignBits, kAlignMask); -} - -static SRes CheckErrors(CLzmaEnc *p) -{ - if (p->result != SZ_OK) - return p->result; - if (p->rc.res != SZ_OK) - p->result = SZ_ERROR_WRITE; - if (p->matchFinderBase.result != SZ_OK) - p->result = SZ_ERROR_READ; - if (p->result != SZ_OK) - p->finished = True; - return p->result; -} - -static SRes Flush(CLzmaEnc *p, UInt32 nowPos) -{ - /* ReleaseMFStream(); */ - p->finished = True; - if (p->writeEndMark) - WriteEndMarker(p, nowPos & p->pbMask); - RangeEnc_FlushData(&p->rc); - RangeEnc_FlushStream(&p->rc); - return CheckErrors(p); -} - -static void FillAlignPrices(CLzmaEnc *p) -{ - UInt32 i; - for (i = 0; i < kAlignTableSize; i++) - p->alignPrices[i] = RcTree_ReverseGetPrice(p->posAlignEncoder, kNumAlignBits, i, p->ProbPrices); - p->alignPriceCount = 0; -} - -static void FillDistancesPrices(CLzmaEnc *p) -{ - UInt32 tempPrices[kNumFullDistances]; - UInt32 i, lenToPosState; - for (i = kStartPosModelIndex; i < kNumFullDistances; i++) - { - UInt32 posSlot = GetPosSlot1(i); - UInt32 footerBits = ((posSlot >> 1) - 1); - UInt32 base = ((2 | (posSlot & 1)) << footerBits); - tempPrices[i] = RcTree_ReverseGetPrice(p->posEncoders + base - posSlot - 1, footerBits, i - base, p->ProbPrices); - } - - for (lenToPosState = 0; lenToPosState < kNumLenToPosStates; lenToPosState++) - { - UInt32 posSlot; - const CLzmaProb *encoder = p->posSlotEncoder[lenToPosState]; - UInt32 *posSlotPrices = p->posSlotPrices[lenToPosState]; - for (posSlot = 0; posSlot < p->distTableSize; posSlot++) - posSlotPrices[posSlot] = RcTree_GetPrice(encoder, kNumPosSlotBits, posSlot, p->ProbPrices); - for (posSlot = kEndPosModelIndex; posSlot < p->distTableSize; posSlot++) - posSlotPrices[posSlot] += ((((posSlot >> 1) - 1) - kNumAlignBits) << kNumBitPriceShiftBits); - - { - UInt32 *distancesPrices = p->distancesPrices[lenToPosState]; - UInt32 i; - for (i = 0; i < kStartPosModelIndex; i++) - distancesPrices[i] = posSlotPrices[i]; - for (; i < kNumFullDistances; i++) - distancesPrices[i] = posSlotPrices[GetPosSlot1(i)] + tempPrices[i]; - } - } - p->matchPriceCount = 0; -} - -void LzmaEnc_Construct(CLzmaEnc *p) -{ - RangeEnc_Construct(&p->rc); - MatchFinder_Construct(&p->matchFinderBase); - #ifdef COMPRESS_MF_MT - MatchFinderMt_Construct(&p->matchFinderMt); - p->matchFinderMt.MatchFinder = &p->matchFinderBase; - #endif - - { - CLzmaEncProps props; - LzmaEncProps_Init(&props); - LzmaEnc_SetProps(p, &props); - } - - #ifndef LZMA_LOG_BSR - LzmaEnc_FastPosInit(p->g_FastPos); - #endif - - LzmaEnc_InitPriceTables(p->ProbPrices); - p->litProbs = 0; - p->saveState.litProbs = 0; -} - -CLzmaEncHandle LzmaEnc_Create(ISzAlloc *alloc) -{ - void *p; - p = alloc->Alloc(alloc, sizeof(CLzmaEnc)); - if (p != 0) - LzmaEnc_Construct((CLzmaEnc *)p); - return p; -} - -void LzmaEnc_FreeLits(CLzmaEnc *p, ISzAlloc *alloc) -{ - alloc->Free(alloc, p->litProbs); - alloc->Free(alloc, p->saveState.litProbs); - p->litProbs = 0; - p->saveState.litProbs = 0; -} - -void LzmaEnc_Destruct(CLzmaEnc *p, ISzAlloc *alloc, ISzAlloc *allocBig) -{ - #ifdef COMPRESS_MF_MT - MatchFinderMt_Destruct(&p->matchFinderMt, allocBig); - #endif - MatchFinder_Free(&p->matchFinderBase, allocBig); - LzmaEnc_FreeLits(p, alloc); - RangeEnc_Free(&p->rc, alloc); -} - -void LzmaEnc_Destroy(CLzmaEncHandle p, ISzAlloc *alloc, ISzAlloc *allocBig) -{ - LzmaEnc_Destruct((CLzmaEnc *)p, alloc, allocBig); - alloc->Free(alloc, p); -} - -static SRes LzmaEnc_CodeOneBlock(CLzmaEnc *p, Bool useLimits, UInt32 maxPackSize, UInt32 maxUnpackSize) -{ - UInt32 nowPos32, startPos32; - if (p->inStream != 0) - { - p->matchFinderBase.stream = p->inStream; - p->matchFinder.Init(p->matchFinderObj); - p->inStream = 0; - } - - if (p->finished) - return p->result; - RINOK(CheckErrors(p)); - - nowPos32 = (UInt32)p->nowPos64; - startPos32 = nowPos32; - - if (p->nowPos64 == 0) - { - UInt32 numPairs; - Byte curByte; - if (p->matchFinder.GetNumAvailableBytes(p->matchFinderObj) == 0) - return Flush(p, nowPos32); - ReadMatchDistances(p, &numPairs); - RangeEnc_EncodeBit(&p->rc, &p->isMatch[p->state][0], 0); - p->state = kLiteralNextStates[p->state]; - curByte = p->matchFinder.GetIndexByte(p->matchFinderObj, 0 - p->additionalOffset); - LitEnc_Encode(&p->rc, p->litProbs, curByte); - p->additionalOffset--; - nowPos32++; - } - - if (p->matchFinder.GetNumAvailableBytes(p->matchFinderObj) != 0) - for (;;) - { - UInt32 pos, len, posState; - - if (p->fastMode) - len = GetOptimumFast(p, &pos); - else - len = GetOptimum(p, nowPos32, &pos); - - #ifdef SHOW_STAT2 - printf("\n pos = %4X, len = %d pos = %d", nowPos32, len, pos); - #endif - - posState = nowPos32 & p->pbMask; - if (len == 1 && pos == (UInt32)-1) - { - Byte curByte; - CLzmaProb *probs; - const Byte *data; - - RangeEnc_EncodeBit(&p->rc, &p->isMatch[p->state][posState], 0); - data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - p->additionalOffset; - curByte = *data; - probs = LIT_PROBS(nowPos32, *(data - 1)); - if (IsCharState(p->state)) - LitEnc_Encode(&p->rc, probs, curByte); - else - LitEnc_EncodeMatched(&p->rc, probs, curByte, *(data - p->reps[0] - 1)); - p->state = kLiteralNextStates[p->state]; - } - else - { - RangeEnc_EncodeBit(&p->rc, &p->isMatch[p->state][posState], 1); - if (pos < LZMA_NUM_REPS) - { - RangeEnc_EncodeBit(&p->rc, &p->isRep[p->state], 1); - if (pos == 0) - { - RangeEnc_EncodeBit(&p->rc, &p->isRepG0[p->state], 0); - RangeEnc_EncodeBit(&p->rc, &p->isRep0Long[p->state][posState], ((len == 1) ? 0 : 1)); - } - else - { - UInt32 distance = p->reps[pos]; - RangeEnc_EncodeBit(&p->rc, &p->isRepG0[p->state], 1); - if (pos == 1) - RangeEnc_EncodeBit(&p->rc, &p->isRepG1[p->state], 0); - else - { - RangeEnc_EncodeBit(&p->rc, &p->isRepG1[p->state], 1); - RangeEnc_EncodeBit(&p->rc, &p->isRepG2[p->state], pos - 2); - if (pos == 3) - p->reps[3] = p->reps[2]; - p->reps[2] = p->reps[1]; - } - p->reps[1] = p->reps[0]; - p->reps[0] = distance; - } - if (len == 1) - p->state = kShortRepNextStates[p->state]; - else - { - LenEnc_Encode2(&p->repLenEnc, &p->rc, len - LZMA_MATCH_LEN_MIN, posState, !p->fastMode, p->ProbPrices); - p->state = kRepNextStates[p->state]; - } - } - else - { - UInt32 posSlot; - RangeEnc_EncodeBit(&p->rc, &p->isRep[p->state], 0); - p->state = kMatchNextStates[p->state]; - LenEnc_Encode2(&p->lenEnc, &p->rc, len - LZMA_MATCH_LEN_MIN, posState, !p->fastMode, p->ProbPrices); - pos -= LZMA_NUM_REPS; - GetPosSlot(pos, posSlot); - RcTree_Encode(&p->rc, p->posSlotEncoder[GetLenToPosState(len)], kNumPosSlotBits, posSlot); - - if (posSlot >= kStartPosModelIndex) - { - UInt32 footerBits = ((posSlot >> 1) - 1); - UInt32 base = ((2 | (posSlot & 1)) << footerBits); - UInt32 posReduced = pos - base; - - if (posSlot < kEndPosModelIndex) - RcTree_ReverseEncode(&p->rc, p->posEncoders + base - posSlot - 1, footerBits, posReduced); - else - { - RangeEnc_EncodeDirectBits(&p->rc, posReduced >> kNumAlignBits, footerBits - kNumAlignBits); - RcTree_ReverseEncode(&p->rc, p->posAlignEncoder, kNumAlignBits, posReduced & kAlignMask); - p->alignPriceCount++; - } - } - p->reps[3] = p->reps[2]; - p->reps[2] = p->reps[1]; - p->reps[1] = p->reps[0]; - p->reps[0] = pos; - p->matchPriceCount++; - } - } - p->additionalOffset -= len; - nowPos32 += len; - if (p->additionalOffset == 0) - { - UInt32 processed; - if (!p->fastMode) - { - if (p->matchPriceCount >= (1 << 7)) - FillDistancesPrices(p); - if (p->alignPriceCount >= kAlignTableSize) - FillAlignPrices(p); - } - if (p->matchFinder.GetNumAvailableBytes(p->matchFinderObj) == 0) - break; - processed = nowPos32 - startPos32; - if (useLimits) - { - if (processed + kNumOpts + 300 >= maxUnpackSize || - RangeEnc_GetProcessed(&p->rc) + kNumOpts * 2 >= maxPackSize) - break; - } - else if (processed >= (1 << 15)) - { - p->nowPos64 += nowPos32 - startPos32; - return CheckErrors(p); - } - } - } - p->nowPos64 += nowPos32 - startPos32; - return Flush(p, nowPos32); -} - -#define kBigHashDicLimit ((UInt32)1 << 24) - -static SRes LzmaEnc_Alloc(CLzmaEnc *p, UInt32 keepWindowSize, ISzAlloc *alloc, ISzAlloc *allocBig) -{ - UInt32 beforeSize = kNumOpts; - Bool btMode; - if (!RangeEnc_Alloc(&p->rc, alloc)) - return SZ_ERROR_MEM; - btMode = (p->matchFinderBase.btMode != 0); - #ifdef COMPRESS_MF_MT - p->mtMode = (p->multiThread && !p->fastMode && btMode); - #endif - - { - unsigned lclp = p->lc + p->lp; - if (p->litProbs == 0 || p->saveState.litProbs == 0 || p->lclp != lclp) - { - LzmaEnc_FreeLits(p, alloc); - p->litProbs = (CLzmaProb *)alloc->Alloc(alloc, (0x300 << lclp) * sizeof(CLzmaProb)); - p->saveState.litProbs = (CLzmaProb *)alloc->Alloc(alloc, (0x300 << lclp) * sizeof(CLzmaProb)); - if (p->litProbs == 0 || p->saveState.litProbs == 0) - { - LzmaEnc_FreeLits(p, alloc); - return SZ_ERROR_MEM; - } - p->lclp = lclp; - } - } - - p->matchFinderBase.bigHash = (p->dictSize > kBigHashDicLimit); - - if (beforeSize + p->dictSize < keepWindowSize) - beforeSize = keepWindowSize - p->dictSize; - - #ifdef COMPRESS_MF_MT - if (p->mtMode) - { - RINOK(MatchFinderMt_Create(&p->matchFinderMt, p->dictSize, beforeSize, p->numFastBytes, LZMA_MATCH_LEN_MAX, allocBig)); - p->matchFinderObj = &p->matchFinderMt; - MatchFinderMt_CreateVTable(&p->matchFinderMt, &p->matchFinder); - } - else - #endif - { - if (!MatchFinder_Create(&p->matchFinderBase, p->dictSize, beforeSize, p->numFastBytes, LZMA_MATCH_LEN_MAX, allocBig)) - return SZ_ERROR_MEM; - p->matchFinderObj = &p->matchFinderBase; - MatchFinder_CreateVTable(&p->matchFinderBase, &p->matchFinder); - } - return SZ_OK; -} - -void LzmaEnc_Init(CLzmaEnc *p) -{ - UInt32 i; - p->state = 0; - for (i = 0 ; i < LZMA_NUM_REPS; i++) - p->reps[i] = 0; - - RangeEnc_Init(&p->rc); - - - for (i = 0; i < kNumStates; i++) - { - UInt32 j; - for (j = 0; j < LZMA_NUM_PB_STATES_MAX; j++) - { - p->isMatch[i][j] = kProbInitValue; - p->isRep0Long[i][j] = kProbInitValue; - } - p->isRep[i] = kProbInitValue; - p->isRepG0[i] = kProbInitValue; - p->isRepG1[i] = kProbInitValue; - p->isRepG2[i] = kProbInitValue; - } - - { - UInt32 num = 0x300 << (p->lp + p->lc); - for (i = 0; i < num; i++) - p->litProbs[i] = kProbInitValue; - } - - { - for (i = 0; i < kNumLenToPosStates; i++) - { - CLzmaProb *probs = p->posSlotEncoder[i]; - UInt32 j; - for (j = 0; j < (1 << kNumPosSlotBits); j++) - probs[j] = kProbInitValue; - } - } - { - for (i = 0; i < kNumFullDistances - kEndPosModelIndex; i++) - p->posEncoders[i] = kProbInitValue; - } - - LenEnc_Init(&p->lenEnc.p); - LenEnc_Init(&p->repLenEnc.p); - - for (i = 0; i < (1 << kNumAlignBits); i++) - p->posAlignEncoder[i] = kProbInitValue; - - p->optimumEndIndex = 0; - p->optimumCurrentIndex = 0; - p->additionalOffset = 0; - - p->pbMask = (1 << p->pb) - 1; - p->lpMask = (1 << p->lp) - 1; -} - -void LzmaEnc_InitPrices(CLzmaEnc *p) -{ - if (!p->fastMode) - { - FillDistancesPrices(p); - FillAlignPrices(p); - } - - p->lenEnc.tableSize = - p->repLenEnc.tableSize = - p->numFastBytes + 1 - LZMA_MATCH_LEN_MIN; - LenPriceEnc_UpdateTables(&p->lenEnc, 1 << p->pb, p->ProbPrices); - LenPriceEnc_UpdateTables(&p->repLenEnc, 1 << p->pb, p->ProbPrices); -} - -static SRes LzmaEnc_AllocAndInit(CLzmaEnc *p, UInt32 keepWindowSize, ISzAlloc *alloc, ISzAlloc *allocBig) -{ - UInt32 i; - for (i = 0; i < (UInt32)kDicLogSizeMaxCompress; i++) - if (p->dictSize <= ((UInt32)1 << i)) - break; - p->distTableSize = i * 2; - - p->finished = False; - p->result = SZ_OK; - RINOK(LzmaEnc_Alloc(p, keepWindowSize, alloc, allocBig)); - LzmaEnc_Init(p); - LzmaEnc_InitPrices(p); - p->nowPos64 = 0; - return SZ_OK; -} - -static SRes LzmaEnc_Prepare(CLzmaEncHandle pp, ISeqInStream *inStream, ISeqOutStream *outStream, - ISzAlloc *alloc, ISzAlloc *allocBig) -{ - CLzmaEnc *p = (CLzmaEnc *)pp; - p->inStream = inStream; - p->rc.outStream = outStream; - return LzmaEnc_AllocAndInit(p, 0, alloc, allocBig); -} - -SRes LzmaEnc_PrepareForLzma2(CLzmaEncHandle pp, - ISeqInStream *inStream, UInt32 keepWindowSize, - ISzAlloc *alloc, ISzAlloc *allocBig) -{ - CLzmaEnc *p = (CLzmaEnc *)pp; - p->inStream = inStream; - return LzmaEnc_AllocAndInit(p, keepWindowSize, alloc, allocBig); -} - -static void LzmaEnc_SetInputBuf(CLzmaEnc *p, const Byte *src, SizeT srcLen) -{ - p->seqBufInStream.funcTable.Read = MyRead; - p->seqBufInStream.data = src; - p->seqBufInStream.rem = srcLen; -} - -SRes LzmaEnc_MemPrepare(CLzmaEncHandle pp, const Byte *src, SizeT srcLen, - UInt32 keepWindowSize, ISzAlloc *alloc, ISzAlloc *allocBig) -{ - CLzmaEnc *p = (CLzmaEnc *)pp; - LzmaEnc_SetInputBuf(p, src, srcLen); - p->inStream = &p->seqBufInStream.funcTable; - return LzmaEnc_AllocAndInit(p, keepWindowSize, alloc, allocBig); -} - -void LzmaEnc_Finish(CLzmaEncHandle pp) -{ - #ifdef COMPRESS_MF_MT - CLzmaEnc *p = (CLzmaEnc *)pp; - if (p->mtMode) - MatchFinderMt_ReleaseStream(&p->matchFinderMt); - #else - pp = pp; - #endif -} - -typedef struct _CSeqOutStreamBuf -{ - ISeqOutStream funcTable; - Byte *data; - SizeT rem; - Bool overflow; -} CSeqOutStreamBuf; - -static size_t MyWrite(void *pp, const void *data, size_t size) -{ - CSeqOutStreamBuf *p = (CSeqOutStreamBuf *)pp; - if (p->rem < size) - { - size = p->rem; - p->overflow = True; - } - memcpy(p->data, data, size); - p->rem -= size; - p->data += size; - return size; -} - - -UInt32 LzmaEnc_GetNumAvailableBytes(CLzmaEncHandle pp) -{ - const CLzmaEnc *p = (CLzmaEnc *)pp; - return p->matchFinder.GetNumAvailableBytes(p->matchFinderObj); -} - -const Byte *LzmaEnc_GetCurBuf(CLzmaEncHandle pp) -{ - const CLzmaEnc *p = (CLzmaEnc *)pp; - return p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - p->additionalOffset; -} - -SRes LzmaEnc_CodeOneMemBlock(CLzmaEncHandle pp, Bool reInit, - Byte *dest, size_t *destLen, UInt32 desiredPackSize, UInt32 *unpackSize) -{ - CLzmaEnc *p = (CLzmaEnc *)pp; - UInt64 nowPos64; - SRes res; - CSeqOutStreamBuf outStream; - - outStream.funcTable.Write = MyWrite; - outStream.data = dest; - outStream.rem = *destLen; - outStream.overflow = False; - - p->writeEndMark = False; - p->finished = False; - p->result = SZ_OK; - - if (reInit) - LzmaEnc_Init(p); - LzmaEnc_InitPrices(p); - nowPos64 = p->nowPos64; - RangeEnc_Init(&p->rc); - p->rc.outStream = &outStream.funcTable; - - res = LzmaEnc_CodeOneBlock(p, True, desiredPackSize, *unpackSize); - - *unpackSize = (UInt32)(p->nowPos64 - nowPos64); - *destLen -= outStream.rem; - if (outStream.overflow) - return SZ_ERROR_OUTPUT_EOF; - - return res; -} - -SRes LzmaEnc_Encode(CLzmaEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStream, ICompressProgress *progress, - ISzAlloc *alloc, ISzAlloc *allocBig) -{ - CLzmaEnc *p = (CLzmaEnc *)pp; - SRes res = SZ_OK; - - #ifdef COMPRESS_MF_MT - Byte allocaDummy[0x300]; - int i = 0; - for (i = 0; i < 16; i++) - allocaDummy[i] = (Byte)i; - #endif - - RINOK(LzmaEnc_Prepare(pp, inStream, outStream, alloc, allocBig)); - - for (;;) - { - res = LzmaEnc_CodeOneBlock(p, False, 0, 0); - if (res != SZ_OK || p->finished != 0) - break; - if (progress != 0) - { - res = progress->Progress(progress, p->nowPos64, RangeEnc_GetProcessed(&p->rc)); - if (res != SZ_OK) - { - res = SZ_ERROR_PROGRESS; - break; - } - } - } - LzmaEnc_Finish(pp); - return res; -} - -SRes LzmaEnc_WriteProperties(CLzmaEncHandle pp, Byte *props, SizeT *size) -{ - CLzmaEnc *p = (CLzmaEnc *)pp; - int i; - UInt32 dictSize = p->dictSize; - if (*size < LZMA_PROPS_SIZE) - return SZ_ERROR_PARAM; - *size = LZMA_PROPS_SIZE; - props[0] = (Byte)((p->pb * 5 + p->lp) * 9 + p->lc); - - for (i = 11; i <= 30; i++) - { - if (dictSize <= ((UInt32)2 << i)) - { - dictSize = (2 << i); - break; - } - if (dictSize <= ((UInt32)3 << i)) - { - dictSize = (3 << i); - break; - } - } - - for (i = 0; i < 4; i++) - props[1 + i] = (Byte)(dictSize >> (8 * i)); - return SZ_OK; -} - -SRes LzmaEnc_MemEncode(CLzmaEncHandle pp, Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen, - int writeEndMark, ICompressProgress *progress, ISzAlloc *alloc, ISzAlloc *allocBig) -{ - SRes res; - CLzmaEnc *p = (CLzmaEnc *)pp; - - CSeqOutStreamBuf outStream; - - LzmaEnc_SetInputBuf(p, src, srcLen); - - outStream.funcTable.Write = MyWrite; - outStream.data = dest; - outStream.rem = *destLen; - outStream.overflow = False; - - p->writeEndMark = writeEndMark; - res = LzmaEnc_Encode(pp, &outStream.funcTable, &p->seqBufInStream.funcTable, - progress, alloc, allocBig); - - *destLen -= outStream.rem; - if (outStream.overflow) - return SZ_ERROR_OUTPUT_EOF; - return res; -} - -SRes LzmaEncode(Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen, - const CLzmaEncProps *props, Byte *propsEncoded, SizeT *propsSize, int writeEndMark, - ICompressProgress *progress, ISzAlloc *alloc, ISzAlloc *allocBig) -{ - CLzmaEnc *p = (CLzmaEnc *)LzmaEnc_Create(alloc); - SRes res; - if (p == 0) - return SZ_ERROR_MEM; - - res = LzmaEnc_SetProps(p, props); - if (res == SZ_OK) - { - res = LzmaEnc_WriteProperties(p, propsEncoded, propsSize); - if (res == SZ_OK) - res = LzmaEnc_MemEncode(p, dest, destLen, src, srcLen, - writeEndMark, progress, alloc, allocBig); - } - - LzmaEnc_Destroy(p, alloc, allocBig); - return res; -} diff --git a/desmume/src/windows/7z/C/LzmaEnc.h b/desmume/src/windows/7z/C/LzmaEnc.h deleted file mode 100644 index e3d84fa35..000000000 --- a/desmume/src/windows/7z/C/LzmaEnc.h +++ /dev/null @@ -1,72 +0,0 @@ -/* LzmaEnc.h -- LZMA Encoder -2008-10-04 : Igor Pavlov : Public domain */ - -#ifndef __LZMAENC_H -#define __LZMAENC_H - -#include "Types.h" - -#define LZMA_PROPS_SIZE 5 - -typedef struct _CLzmaEncProps -{ - int level; /* 0 <= level <= 9 */ - UInt32 dictSize; /* (1 << 12) <= dictSize <= (1 << 27) for 32-bit version - (1 << 12) <= dictSize <= (1 << 30) for 64-bit version - default = (1 << 24) */ - int lc; /* 0 <= lc <= 8, default = 3 */ - int lp; /* 0 <= lp <= 4, default = 0 */ - int pb; /* 0 <= pb <= 4, default = 2 */ - int algo; /* 0 - fast, 1 - normal, default = 1 */ - int fb; /* 5 <= fb <= 273, default = 32 */ - int btMode; /* 0 - hashChain Mode, 1 - binTree mode - normal, default = 1 */ - int numHashBytes; /* 2, 3 or 4, default = 4 */ - UInt32 mc; /* 1 <= mc <= (1 << 30), default = 32 */ - unsigned writeEndMark; /* 0 - do not write EOPM, 1 - write EOPM, default = 0 */ - int numThreads; /* 1 or 2, default = 2 */ -} CLzmaEncProps; - -void LzmaEncProps_Init(CLzmaEncProps *p); -void LzmaEncProps_Normalize(CLzmaEncProps *p); -UInt32 LzmaEncProps_GetDictSize(const CLzmaEncProps *props2); - - -/* ---------- CLzmaEncHandle Interface ---------- */ - -/* LzmaEnc_* functions can return the following exit codes: -Returns: - SZ_OK - OK - SZ_ERROR_MEM - Memory allocation error - SZ_ERROR_PARAM - Incorrect paramater in props - SZ_ERROR_WRITE - Write callback error. - SZ_ERROR_PROGRESS - some break from progress callback - SZ_ERROR_THREAD - errors in multithreading functions (only for Mt version) -*/ - -typedef void * CLzmaEncHandle; - -CLzmaEncHandle LzmaEnc_Create(ISzAlloc *alloc); -void LzmaEnc_Destroy(CLzmaEncHandle p, ISzAlloc *alloc, ISzAlloc *allocBig); -SRes LzmaEnc_SetProps(CLzmaEncHandle p, const CLzmaEncProps *props); -SRes LzmaEnc_WriteProperties(CLzmaEncHandle p, Byte *properties, SizeT *size); -SRes LzmaEnc_Encode(CLzmaEncHandle p, ISeqOutStream *outStream, ISeqInStream *inStream, - ICompressProgress *progress, ISzAlloc *alloc, ISzAlloc *allocBig); -SRes LzmaEnc_MemEncode(CLzmaEncHandle p, Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen, - int writeEndMark, ICompressProgress *progress, ISzAlloc *alloc, ISzAlloc *allocBig); - -/* ---------- One Call Interface ---------- */ - -/* LzmaEncode -Return code: - SZ_OK - OK - SZ_ERROR_MEM - Memory allocation error - SZ_ERROR_PARAM - Incorrect paramater - SZ_ERROR_OUTPUT_EOF - output buffer overflow - SZ_ERROR_THREAD - errors in multithreading functions (only for Mt version) -*/ - -SRes LzmaEncode(Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen, - const CLzmaEncProps *props, Byte *propsEncoded, SizeT *propsSize, int writeEndMark, - ICompressProgress *progress, ISzAlloc *alloc, ISzAlloc *allocBig); - -#endif diff --git a/desmume/src/windows/7z/C/RotateDefs.h b/desmume/src/windows/7z/C/RotateDefs.h deleted file mode 100644 index 189350d7b..000000000 --- a/desmume/src/windows/7z/C/RotateDefs.h +++ /dev/null @@ -1,22 +0,0 @@ -/* RotateDefs.h -- Rotate functions -2008-08-05 -Igor Pavlov -Public domain */ - -#ifndef __ROTATEDEFS_H -#define __ROTATEDEFS_H - -#ifdef _MSC_VER - -#include -#define rotlFixed(x, n) _rotl((x), (n)) -#define rotrFixed(x, n) _rotr((x), (n)) - -#else - -#define rotlFixed(x, n) (((x) << (n)) | ((x) >> (32 - (n)))) -#define rotrFixed(x, n) (((x) >> (n)) | ((x) << (32 - (n)))) - -#endif - -#endif diff --git a/desmume/src/windows/7z/C/Sha256.c b/desmume/src/windows/7z/C/Sha256.c deleted file mode 100644 index 657c2ab92..000000000 --- a/desmume/src/windows/7z/C/Sha256.c +++ /dev/null @@ -1,204 +0,0 @@ -/* Crypto/Sha256.c -- SHA-256 Hash function -2008-11-06 : Igor Pavlov : Public domain -This code is based on public domain code from Wei Dai's Crypto++ library. */ - -#include "Sha256.h" -#include "RotateDefs.h" - -/* define it for speed optimization */ -/* #define _SHA256_UNROLL */ -/* #define _SHA256_UNROLL2 */ - -void Sha256_Init(CSha256 *p) -{ - p->state[0] = 0x6a09e667; - p->state[1] = 0xbb67ae85; - p->state[2] = 0x3c6ef372; - p->state[3] = 0xa54ff53a; - p->state[4] = 0x510e527f; - p->state[5] = 0x9b05688c; - p->state[6] = 0x1f83d9ab; - p->state[7] = 0x5be0cd19; - p->count = 0; -} - -#define S0(x) (rotrFixed(x, 2) ^ rotrFixed(x,13) ^ rotrFixed(x, 22)) -#define S1(x) (rotrFixed(x, 6) ^ rotrFixed(x,11) ^ rotrFixed(x, 25)) -#define s0(x) (rotrFixed(x, 7) ^ rotrFixed(x,18) ^ (x >> 3)) -#define s1(x) (rotrFixed(x,17) ^ rotrFixed(x,19) ^ (x >> 10)) - -#define blk0(i) (W[i] = data[i]) -#define blk2(i) (W[i&15] += s1(W[(i-2)&15]) + W[(i-7)&15] + s0(W[(i-15)&15])) - -#define Ch(x,y,z) (z^(x&(y^z))) -#define Maj(x,y,z) ((x&y)|(z&(x|y))) - -#define a(i) T[(0-(i))&7] -#define b(i) T[(1-(i))&7] -#define c(i) T[(2-(i))&7] -#define d(i) T[(3-(i))&7] -#define e(i) T[(4-(i))&7] -#define f(i) T[(5-(i))&7] -#define g(i) T[(6-(i))&7] -#define h(i) T[(7-(i))&7] - - -#ifdef _SHA256_UNROLL2 - -#define R(a,b,c,d,e,f,g,h, i) h += S1(e) + Ch(e,f,g) + K[i+j] + (j?blk2(i):blk0(i));\ - d += h; h += S0(a) + Maj(a, b, c) - -#define RX_8(i) \ - R(a,b,c,d,e,f,g,h, i); \ - R(h,a,b,c,d,e,f,g, i+1); \ - R(g,h,a,b,c,d,e,f, i+2); \ - R(f,g,h,a,b,c,d,e, i+3); \ - R(e,f,g,h,a,b,c,d, i+4); \ - R(d,e,f,g,h,a,b,c, i+5); \ - R(c,d,e,f,g,h,a,b, i+6); \ - R(b,c,d,e,f,g,h,a, i+7) - -#else - -#define R(i) h(i) += S1(e(i)) + Ch(e(i),f(i),g(i)) + K[i+j] + (j?blk2(i):blk0(i));\ - d(i) += h(i); h(i) += S0(a(i)) + Maj(a(i), b(i), c(i)) - -#ifdef _SHA256_UNROLL - -#define RX_8(i) R(i+0); R(i+1); R(i+2); R(i+3); R(i+4); R(i+5); R(i+6); R(i+7); - -#endif - -#endif - -const UInt32 K[64] = { - 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, - 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, - 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, - 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, - 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, - 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, - 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, - 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, - 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, - 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, - 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, - 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, - 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, - 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, - 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, - 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 -}; - -static void Sha256_Transform(UInt32 *state, const UInt32 *data) -{ - UInt32 W[16]; - unsigned j; - #ifdef _SHA256_UNROLL2 - UInt32 a,b,c,d,e,f,g,h; - a = state[0]; - b = state[1]; - c = state[2]; - d = state[3]; - e = state[4]; - f = state[5]; - g = state[6]; - h = state[7]; - #else - UInt32 T[8]; - for (j = 0; j < 8; j++) - T[j] = state[j]; - #endif - - for (j = 0; j < 64; j += 16) - { - #if defined(_SHA256_UNROLL) || defined(_SHA256_UNROLL2) - RX_8(0); RX_8(8); - #else - unsigned i; - for (i = 0; i < 16; i++) { R(i); } - #endif - } - - #ifdef _SHA256_UNROLL2 - state[0] += a; - state[1] += b; - state[2] += c; - state[3] += d; - state[4] += e; - state[5] += f; - state[6] += g; - state[7] += h; - #else - for (j = 0; j < 8; j++) - state[j] += T[j]; - #endif - - /* Wipe variables */ - /* memset(W, 0, sizeof(W)); */ - /* memset(T, 0, sizeof(T)); */ -} - -#undef S0 -#undef S1 -#undef s0 -#undef s1 - -static void Sha256_WriteByteBlock(CSha256 *p) -{ - UInt32 data32[16]; - unsigned i; - for (i = 0; i < 16; i++) - data32[i] = - ((UInt32)(p->buffer[i * 4 ]) << 24) + - ((UInt32)(p->buffer[i * 4 + 1]) << 16) + - ((UInt32)(p->buffer[i * 4 + 2]) << 8) + - ((UInt32)(p->buffer[i * 4 + 3])); - Sha256_Transform(p->state, data32); -} - -void Sha256_Update(CSha256 *p, const Byte *data, size_t size) -{ - UInt32 curBufferPos = (UInt32)p->count & 0x3F; - while (size > 0) - { - p->buffer[curBufferPos++] = *data++; - p->count++; - size--; - if (curBufferPos == 64) - { - curBufferPos = 0; - Sha256_WriteByteBlock(p); - } - } -} - -void Sha256_Final(CSha256 *p, Byte *digest) -{ - UInt64 lenInBits = (p->count << 3); - UInt32 curBufferPos = (UInt32)p->count & 0x3F; - unsigned i; - p->buffer[curBufferPos++] = 0x80; - while (curBufferPos != (64 - 8)) - { - curBufferPos &= 0x3F; - if (curBufferPos == 0) - Sha256_WriteByteBlock(p); - p->buffer[curBufferPos++] = 0; - } - for (i = 0; i < 8; i++) - { - p->buffer[curBufferPos++] = (Byte)(lenInBits >> 56); - lenInBits <<= 8; - } - Sha256_WriteByteBlock(p); - - for (i = 0; i < 8; i++) - { - *digest++ = (Byte)((p->state[i] >> 24) & 0xFF); - *digest++ = (Byte)((p->state[i] >> 16) & 0xFF); - *digest++ = (Byte)((p->state[i] >> 8) & 0xFF); - *digest++ = (Byte)((p->state[i]) & 0xFF); - } - Sha256_Init(p); -} diff --git a/desmume/src/windows/7z/C/Sha256.h b/desmume/src/windows/7z/C/Sha256.h deleted file mode 100644 index 8703b4a63..000000000 --- a/desmume/src/windows/7z/C/Sha256.h +++ /dev/null @@ -1,22 +0,0 @@ -/* Crypto/Sha256.h -- SHA-256 Hash function -2008-10-04 : Igor Pavlov : Public domain */ - -#ifndef __CRYPTO_SHA256_H -#define __CRYPTO_SHA256_H - -#include "Types.h" - -#define SHA256_DIGEST_SIZE 32 - -typedef struct -{ - UInt32 state[8]; - UInt64 count; - Byte buffer[64]; -} CSha256; - -void Sha256_Init(CSha256 *p); -void Sha256_Update(CSha256 *p, const Byte *data, size_t size); -void Sha256_Final(CSha256 *p, Byte *digest); - -#endif diff --git a/desmume/src/windows/7z/C/Sort.c b/desmume/src/windows/7z/C/Sort.c deleted file mode 100644 index bb20dc348..000000000 --- a/desmume/src/windows/7z/C/Sort.c +++ /dev/null @@ -1,95 +0,0 @@ -/* Sort.c -- Sort functions -2008-08-17 -Igor Pavlov -Public domain */ - -#include "Sort.h" - -#define HeapSortDown(p, k, size, temp) \ - { for (;;) { \ - UInt32 s = (k << 1); \ - if (s > size) break; \ - if (s < size && p[s + 1] > p[s]) s++; \ - if (temp >= p[s]) break; \ - p[k] = p[s]; k = s; \ - } p[k] = temp; } - -void HeapSort(UInt32 *p, UInt32 size) -{ - if (size <= 1) - return; - p--; - { - UInt32 i = size / 2; - do - { - UInt32 temp = p[i]; - UInt32 k = i; - HeapSortDown(p, k, size, temp) - } - while (--i != 0); - } - /* - do - { - UInt32 k = 1; - UInt32 temp = p[size]; - p[size--] = p[1]; - HeapSortDown(p, k, size, temp) - } - while (size > 1); - */ - while (size > 3) - { - UInt32 temp = p[size]; - UInt32 k = (p[3] > p[2]) ? 3 : 2; - p[size--] = p[1]; - p[1] = p[k]; - HeapSortDown(p, k, size, temp) - } - { - UInt32 temp = p[size]; - p[size] = p[1]; - if (size > 2 && p[2] < temp) - { - p[1] = p[2]; - p[2] = temp; - } - else - p[1] = temp; - } -} - -/* -#define HeapSortRefDown(p, vals, n, size, temp) \ - { UInt32 k = n; UInt32 val = vals[temp]; for (;;) { \ - UInt32 s = (k << 1); \ - if (s > size) break; \ - if (s < size && vals[p[s + 1]] > vals[p[s]]) s++; \ - if (val >= vals[p[s]]) break; \ - p[k] = p[s]; k = s; \ - } p[k] = temp; } - -void HeapSortRef(UInt32 *p, UInt32 *vals, UInt32 size) -{ - if (size <= 1) - return; - p--; - { - UInt32 i = size / 2; - do - { - UInt32 temp = p[i]; - HeapSortRefDown(p, vals, i, size, temp); - } - while (--i != 0); - } - do - { - UInt32 temp = p[size]; - p[size--] = p[1]; - HeapSortRefDown(p, vals, 1, size, temp); - } - while (size > 1); -} -*/ \ No newline at end of file diff --git a/desmume/src/windows/7z/C/Sort.h b/desmume/src/windows/7z/C/Sort.h deleted file mode 100644 index cff6c4c32..000000000 --- a/desmume/src/windows/7z/C/Sort.h +++ /dev/null @@ -1,14 +0,0 @@ -/* Sort.h -- Sort functions -2008-03-19 -Igor Pavlov -Public domain */ - -#ifndef __7Z_SORT_H -#define __7Z_SORT_H - -#include "Types.h" - -void HeapSort(UInt32 *p, UInt32 size); -/* void HeapSortRef(UInt32 *p, UInt32 *vals, UInt32 size); */ - -#endif diff --git a/desmume/src/windows/7z/C/Threads.c b/desmume/src/windows/7z/C/Threads.c deleted file mode 100644 index c7d8b0a8a..000000000 --- a/desmume/src/windows/7z/C/Threads.c +++ /dev/null @@ -1,109 +0,0 @@ -/* Threads.c -- multithreading library -2008-08-05 -Igor Pavlov -Public domain */ - -#include "Threads.h" -#include - -static WRes GetError() -{ - DWORD res = GetLastError(); - return (res) ? (WRes)(res) : 1; -} - -WRes HandleToWRes(HANDLE h) { return (h != 0) ? 0 : GetError(); } -WRes BOOLToWRes(BOOL v) { return v ? 0 : GetError(); } - -static WRes MyCloseHandle(HANDLE *h) -{ - if (*h != NULL) - if (!CloseHandle(*h)) - return GetError(); - *h = NULL; - return 0; -} - -WRes Thread_Create(CThread *thread, THREAD_FUNC_RET_TYPE (THREAD_FUNC_CALL_TYPE *startAddress)(void *), LPVOID parameter) -{ - unsigned threadId; /* Windows Me/98/95: threadId parameter may not be NULL in _beginthreadex/CreateThread functions */ - thread->handle = - /* CreateThread(0, 0, startAddress, parameter, 0, &threadId); */ - (HANDLE)_beginthreadex(NULL, 0, startAddress, parameter, 0, &threadId); - /* maybe we must use errno here, but probably GetLastError() is also OK. */ - return HandleToWRes(thread->handle); -} - -WRes WaitObject(HANDLE h) -{ - return (WRes)WaitForSingleObject(h, INFINITE); -} - -WRes Thread_Wait(CThread *thread) -{ - if (thread->handle == NULL) - return 1; - return WaitObject(thread->handle); -} - -WRes Thread_Close(CThread *thread) -{ - return MyCloseHandle(&thread->handle); -} - -WRes Event_Create(CEvent *p, BOOL manualReset, int initialSignaled) -{ - p->handle = CreateEvent(NULL, manualReset, (initialSignaled ? TRUE : FALSE), NULL); - return HandleToWRes(p->handle); -} - -WRes ManualResetEvent_Create(CManualResetEvent *p, int initialSignaled) - { return Event_Create(p, TRUE, initialSignaled); } -WRes ManualResetEvent_CreateNotSignaled(CManualResetEvent *p) - { return ManualResetEvent_Create(p, 0); } - -WRes AutoResetEvent_Create(CAutoResetEvent *p, int initialSignaled) - { return Event_Create(p, FALSE, initialSignaled); } -WRes AutoResetEvent_CreateNotSignaled(CAutoResetEvent *p) - { return AutoResetEvent_Create(p, 0); } - -WRes Event_Set(CEvent *p) { return BOOLToWRes(SetEvent(p->handle)); } -WRes Event_Reset(CEvent *p) { return BOOLToWRes(ResetEvent(p->handle)); } -WRes Event_Wait(CEvent *p) { return WaitObject(p->handle); } -WRes Event_Close(CEvent *p) { return MyCloseHandle(&p->handle); } - - -WRes Semaphore_Create(CSemaphore *p, UInt32 initiallyCount, UInt32 maxCount) -{ - p->handle = CreateSemaphore(NULL, (LONG)initiallyCount, (LONG)maxCount, NULL); - return HandleToWRes(p->handle); -} - -WRes Semaphore_Release(CSemaphore *p, LONG releaseCount, LONG *previousCount) -{ - return BOOLToWRes(ReleaseSemaphore(p->handle, releaseCount, previousCount)); -} -WRes Semaphore_ReleaseN(CSemaphore *p, UInt32 releaseCount) -{ - return Semaphore_Release(p, (LONG)releaseCount, NULL); -} -WRes Semaphore_Release1(CSemaphore *p) -{ - return Semaphore_ReleaseN(p, 1); -} - -WRes Semaphore_Wait(CSemaphore *p) { return WaitObject(p->handle); } -WRes Semaphore_Close(CSemaphore *p) { return MyCloseHandle(&p->handle); } - -WRes CriticalSection_Init(CCriticalSection *p) -{ - /* InitializeCriticalSection can raise only STATUS_NO_MEMORY exception */ - __try - { - InitializeCriticalSection(p); - /* InitializeCriticalSectionAndSpinCount(p, 0); */ - } - __except (EXCEPTION_EXECUTE_HANDLER) { return 1; } - return 0; -} - diff --git a/desmume/src/windows/7z/C/Threads.h b/desmume/src/windows/7z/C/Threads.h deleted file mode 100644 index 3d9072946..000000000 --- a/desmume/src/windows/7z/C/Threads.h +++ /dev/null @@ -1,68 +0,0 @@ -/* Threads.h -- multithreading library -2008-11-22 : Igor Pavlov : Public domain */ - -#ifndef __7Z_THRESDS_H -#define __7Z_THRESDS_H - -#include "Types.h" - -typedef struct _CThread -{ - HANDLE handle; -} CThread; - -#define Thread_Construct(thread) (thread)->handle = NULL -#define Thread_WasCreated(thread) ((thread)->handle != NULL) - -typedef unsigned THREAD_FUNC_RET_TYPE; -#define THREAD_FUNC_CALL_TYPE MY_STD_CALL -#define THREAD_FUNC_DECL THREAD_FUNC_RET_TYPE THREAD_FUNC_CALL_TYPE - -WRes Thread_Create(CThread *thread, THREAD_FUNC_RET_TYPE (THREAD_FUNC_CALL_TYPE *startAddress)(void *), LPVOID parameter); -WRes Thread_Wait(CThread *thread); -WRes Thread_Close(CThread *thread); - -typedef struct _CEvent -{ - HANDLE handle; -} CEvent; - -typedef CEvent CAutoResetEvent; -typedef CEvent CManualResetEvent; - -#define Event_Construct(event) (event)->handle = NULL -#define Event_IsCreated(event) ((event)->handle != NULL) - -WRes ManualResetEvent_Create(CManualResetEvent *event, int initialSignaled); -WRes ManualResetEvent_CreateNotSignaled(CManualResetEvent *event); -WRes AutoResetEvent_Create(CAutoResetEvent *event, int initialSignaled); -WRes AutoResetEvent_CreateNotSignaled(CAutoResetEvent *event); -WRes Event_Set(CEvent *event); -WRes Event_Reset(CEvent *event); -WRes Event_Wait(CEvent *event); -WRes Event_Close(CEvent *event); - - -typedef struct _CSemaphore -{ - HANDLE handle; -} CSemaphore; - -#define Semaphore_Construct(p) (p)->handle = NULL - -WRes Semaphore_Create(CSemaphore *p, UInt32 initiallyCount, UInt32 maxCount); -WRes Semaphore_ReleaseN(CSemaphore *p, UInt32 num); -WRes Semaphore_Release1(CSemaphore *p); -WRes Semaphore_Wait(CSemaphore *p); -WRes Semaphore_Close(CSemaphore *p); - - -typedef CRITICAL_SECTION CCriticalSection; - -WRes CriticalSection_Init(CCriticalSection *p); -#define CriticalSection_Delete(p) DeleteCriticalSection(p) -#define CriticalSection_Enter(p) EnterCriticalSection(p) -#define CriticalSection_Leave(p) LeaveCriticalSection(p) - -#endif - diff --git a/desmume/src/windows/7z/C/Types.h b/desmume/src/windows/7z/C/Types.h deleted file mode 100644 index 2638196aa..000000000 --- a/desmume/src/windows/7z/C/Types.h +++ /dev/null @@ -1,208 +0,0 @@ -/* Types.h -- Basic types -2008-11-23 : Igor Pavlov : Public domain */ - -#ifndef __7Z_TYPES_H -#define __7Z_TYPES_H - -#include - -#ifdef _WIN32 -#include -#endif - -#define SZ_OK 0 - -#define SZ_ERROR_DATA 1 -#define SZ_ERROR_MEM 2 -#define SZ_ERROR_CRC 3 -#define SZ_ERROR_UNSUPPORTED 4 -#define SZ_ERROR_PARAM 5 -#define SZ_ERROR_INPUT_EOF 6 -#define SZ_ERROR_OUTPUT_EOF 7 -#define SZ_ERROR_READ 8 -#define SZ_ERROR_WRITE 9 -#define SZ_ERROR_PROGRESS 10 -#define SZ_ERROR_FAIL 11 -#define SZ_ERROR_THREAD 12 - -#define SZ_ERROR_ARCHIVE 16 -#define SZ_ERROR_NO_ARCHIVE 17 - -typedef int SRes; - -#ifdef _WIN32 -typedef DWORD WRes; -#else -typedef int WRes; -#endif - -#ifndef RINOK -#define RINOK(x) { int __result__ = (x); if (__result__ != 0) return __result__; } -#endif - -typedef unsigned char Byte; -typedef short Int16; -typedef unsigned short UInt16; - -#ifdef _LZMA_UINT32_IS_ULONG -typedef long Int32; -typedef unsigned long UInt32; -#else -typedef int Int32; -typedef unsigned int UInt32; -#endif - -#ifdef _SZ_NO_INT_64 - -/* define _SZ_NO_INT_64, if your compiler doesn't support 64-bit integers. - NOTES: Some code will work incorrectly in that case! */ - -typedef long Int64; -typedef unsigned long UInt64; - -#else - -#if defined(_MSC_VER) || defined(__BORLANDC__) -typedef __int64 Int64; -typedef unsigned __int64 UInt64; -#else -typedef long long int Int64; -typedef unsigned long long int UInt64; -#endif - -#endif - -#ifdef _LZMA_NO_SYSTEM_SIZE_T -typedef UInt32 SizeT; -#else -typedef size_t SizeT; -#endif - -typedef int Bool; -#define True 1 -#define False 0 - - -#ifdef _MSC_VER - -#if _MSC_VER >= 1300 -#define MY_NO_INLINE __declspec(noinline) -#else -#define MY_NO_INLINE -#endif - -#define MY_CDECL __cdecl -#define MY_STD_CALL __stdcall -#define MY_FAST_CALL MY_NO_INLINE __fastcall - -#else - -#define MY_CDECL -#define MY_STD_CALL -#define MY_FAST_CALL - -#endif - - -/* The following interfaces use first parameter as pointer to structure */ - -typedef struct -{ - SRes (*Read)(void *p, void *buf, size_t *size); - /* if (input(*size) != 0 && output(*size) == 0) means end_of_stream. - (output(*size) < input(*size)) is allowed */ -} ISeqInStream; - -/* it can return SZ_ERROR_INPUT_EOF */ -SRes SeqInStream_Read(ISeqInStream *stream, void *buf, size_t size); -SRes SeqInStream_Read2(ISeqInStream *stream, void *buf, size_t size, SRes errorType); -SRes SeqInStream_ReadByte(ISeqInStream *stream, Byte *buf); - -typedef struct -{ - size_t (*Write)(void *p, const void *buf, size_t size); - /* Returns: result - the number of actually written bytes. - (result < size) means error */ -} ISeqOutStream; - -typedef enum -{ - SZ_SEEK_SET = 0, - SZ_SEEK_CUR = 1, - SZ_SEEK_END = 2 -} ESzSeek; - -typedef struct -{ - SRes (*Read)(void *p, void *buf, size_t *size); /* same as ISeqInStream::Read */ - SRes (*Seek)(void *p, Int64 *pos, ESzSeek origin); -} ISeekInStream; - -typedef struct -{ - SRes (*Look)(void *p, void **buf, size_t *size); - /* if (input(*size) != 0 && output(*size) == 0) means end_of_stream. - (output(*size) > input(*size)) is not allowed - (output(*size) < input(*size)) is allowed */ - SRes (*Skip)(void *p, size_t offset); - /* offset must be <= output(*size) of Look */ - - SRes (*Read)(void *p, void *buf, size_t *size); - /* reads directly (without buffer). It's same as ISeqInStream::Read */ - SRes (*Seek)(void *p, Int64 *pos, ESzSeek origin); -} ILookInStream; - -SRes LookInStream_LookRead(ILookInStream *stream, void *buf, size_t *size); -SRes LookInStream_SeekTo(ILookInStream *stream, UInt64 offset); - -/* reads via ILookInStream::Read */ -SRes LookInStream_Read2(ILookInStream *stream, void *buf, size_t size, SRes errorType); -SRes LookInStream_Read(ILookInStream *stream, void *buf, size_t size); - -#define LookToRead_BUF_SIZE (1 << 14) - -typedef struct -{ - ILookInStream s; - ISeekInStream *realStream; - size_t pos; - size_t size; - Byte buf[LookToRead_BUF_SIZE]; -} CLookToRead; - -void LookToRead_CreateVTable(CLookToRead *p, int lookahead); -void LookToRead_Init(CLookToRead *p); - -typedef struct -{ - ISeqInStream s; - ILookInStream *realStream; -} CSecToLook; - -void SecToLook_CreateVTable(CSecToLook *p); - -typedef struct -{ - ISeqInStream s; - ILookInStream *realStream; -} CSecToRead; - -void SecToRead_CreateVTable(CSecToRead *p); - -typedef struct -{ - SRes (*Progress)(void *p, UInt64 inSize, UInt64 outSize); - /* Returns: result. (result != SZ_OK) means break. - Value (UInt64)(Int64)-1 for size means unknown value. */ -} ICompressProgress; - -typedef struct -{ - void *(*Alloc)(void *p, size_t size); - void (*Free)(void *p, void *address); /* address can be 0 */ -} ISzAlloc; - -#define IAlloc_Alloc(p, size) (p)->Alloc((p), size) -#define IAlloc_Free(p, a) (p)->Free((p), a) - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zCompressionMode.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zCompressionMode.cpp deleted file mode 100644 index 232c63820..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zCompressionMode.cpp +++ /dev/null @@ -1,3 +0,0 @@ -// CompressionMethod.cpp - -#include "StdAfx.h" diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zCompressionMode.h b/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zCompressionMode.h deleted file mode 100644 index 5e986355b..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zCompressionMode.h +++ /dev/null @@ -1,50 +0,0 @@ -// 7zCompressionMode.h - -#ifndef __7Z_COMPRESSION_MODE_H -#define __7Z_COMPRESSION_MODE_H - -#include "../../../Common/MyString.h" - -#include "../../../Windows/PropVariant.h" - -#include "../../Common/MethodProps.h" - -namespace NArchive { -namespace N7z { - -struct CMethodFull: public CMethod -{ - UInt32 NumInStreams; - UInt32 NumOutStreams; - bool IsSimpleCoder() const { return (NumInStreams == 1) && (NumOutStreams == 1); } -}; - -struct CBind -{ - UInt32 InCoder; - UInt32 InStream; - UInt32 OutCoder; - UInt32 OutStream; -}; - -struct CCompressionMethodMode -{ - CObjectVector Methods; - CRecordVector Binds; - #ifdef COMPRESS_MT - UInt32 NumThreads; - #endif - bool PasswordIsDefined; - UString Password; - - bool IsEmpty() const { return (Methods.IsEmpty() && !PasswordIsDefined); } - CCompressionMethodMode(): PasswordIsDefined(false) - #ifdef COMPRESS_MT - , NumThreads(1) - #endif - {} -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zDecode.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zDecode.cpp deleted file mode 100644 index 02744c96a..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zDecode.cpp +++ /dev/null @@ -1,332 +0,0 @@ -// 7zDecode.cpp - -#include "StdAfx.h" - -#include "../../Common/LimitedStreams.h" -#include "../../Common/LockedStream.h" -#include "../../Common/ProgressUtils.h" -#include "../../Common/StreamObjects.h" - -#include "7zDecode.h" - -namespace NArchive { -namespace N7z { - -static void ConvertFolderItemInfoToBindInfo(const CFolder &folder, - CBindInfoEx &bindInfo) -{ - bindInfo.Clear(); - int i; - for (i = 0; i < folder.BindPairs.Size(); i++) - { - NCoderMixer::CBindPair bindPair; - bindPair.InIndex = (UInt32)folder.BindPairs[i].InIndex; - bindPair.OutIndex = (UInt32)folder.BindPairs[i].OutIndex; - bindInfo.BindPairs.Add(bindPair); - } - UInt32 outStreamIndex = 0; - for (i = 0; i < folder.Coders.Size(); i++) - { - NCoderMixer::CCoderStreamsInfo coderStreamsInfo; - const CCoderInfo &coderInfo = folder.Coders[i]; - coderStreamsInfo.NumInStreams = (UInt32)coderInfo.NumInStreams; - coderStreamsInfo.NumOutStreams = (UInt32)coderInfo.NumOutStreams; - bindInfo.Coders.Add(coderStreamsInfo); - bindInfo.CoderMethodIDs.Add(coderInfo.MethodID); - for (UInt32 j = 0; j < coderStreamsInfo.NumOutStreams; j++, outStreamIndex++) - if (folder.FindBindPairForOutStream(outStreamIndex) < 0) - bindInfo.OutStreams.Add(outStreamIndex); - } - for (i = 0; i < folder.PackStreams.Size(); i++) - bindInfo.InStreams.Add((UInt32)folder.PackStreams[i]); -} - -static bool AreCodersEqual(const NCoderMixer::CCoderStreamsInfo &a1, - const NCoderMixer::CCoderStreamsInfo &a2) -{ - return (a1.NumInStreams == a2.NumInStreams) && - (a1.NumOutStreams == a2.NumOutStreams); -} - -static bool AreBindPairsEqual(const NCoderMixer::CBindPair &a1, const NCoderMixer::CBindPair &a2) -{ - return (a1.InIndex == a2.InIndex) && - (a1.OutIndex == a2.OutIndex); -} - -static bool AreBindInfoExEqual(const CBindInfoEx &a1, const CBindInfoEx &a2) -{ - if (a1.Coders.Size() != a2.Coders.Size()) - return false; - int i; - for (i = 0; i < a1.Coders.Size(); i++) - if (!AreCodersEqual(a1.Coders[i], a2.Coders[i])) - return false; - if (a1.BindPairs.Size() != a2.BindPairs.Size()) - return false; - for (i = 0; i < a1.BindPairs.Size(); i++) - if (!AreBindPairsEqual(a1.BindPairs[i], a2.BindPairs[i])) - return false; - for (i = 0; i < a1.CoderMethodIDs.Size(); i++) - if (a1.CoderMethodIDs[i] != a2.CoderMethodIDs[i]) - return false; - if (a1.InStreams.Size() != a2.InStreams.Size()) - return false; - if (a1.OutStreams.Size() != a2.OutStreams.Size()) - return false; - return true; -} - -CDecoder::CDecoder(bool multiThread) -{ - #ifndef _ST_MODE - multiThread = true; - #endif - _multiThread = multiThread; - _bindInfoExPrevIsDefined = false; -} - -HRESULT CDecoder::Decode( - DECL_EXTERNAL_CODECS_LOC_VARS - IInStream *inStream, - UInt64 startPos, - const UInt64 *packSizes, - const CFolder &folderInfo, - ISequentialOutStream *outStream, - ICompressProgressInfo *compressProgress - #ifndef _NO_CRYPTO - , ICryptoGetTextPassword *getTextPassword, bool &passwordIsDefined - #endif - #ifdef COMPRESS_MT - , bool mtMode, UInt32 numThreads - #endif - ) -{ - if (!folderInfo.CheckStructure()) - return E_NOTIMPL; - #ifndef _NO_CRYPTO - passwordIsDefined = false; - #endif - CObjectVector< CMyComPtr > inStreams; - - CLockedInStream lockedInStream; - lockedInStream.Init(inStream); - - for (int j = 0; j < folderInfo.PackStreams.Size(); j++) - { - CLockedSequentialInStreamImp *lockedStreamImpSpec = new - CLockedSequentialInStreamImp; - CMyComPtr lockedStreamImp = lockedStreamImpSpec; - lockedStreamImpSpec->Init(&lockedInStream, startPos); - startPos += packSizes[j]; - - CLimitedSequentialInStream *streamSpec = new - CLimitedSequentialInStream; - CMyComPtr inStream = streamSpec; - streamSpec->SetStream(lockedStreamImp); - streamSpec->Init(packSizes[j]); - inStreams.Add(inStream); - } - - int numCoders = folderInfo.Coders.Size(); - - CBindInfoEx bindInfo; - ConvertFolderItemInfoToBindInfo(folderInfo, bindInfo); - bool createNewCoders; - if (!_bindInfoExPrevIsDefined) - createNewCoders = true; - else - createNewCoders = !AreBindInfoExEqual(bindInfo, _bindInfoExPrev); - if (createNewCoders) - { - int i; - _decoders.Clear(); - // _decoders2.Clear(); - - _mixerCoder.Release(); - - if (_multiThread) - { - _mixerCoderMTSpec = new NCoderMixer::CCoderMixer2MT; - _mixerCoder = _mixerCoderMTSpec; - _mixerCoderCommon = _mixerCoderMTSpec; - } - else - { - #ifdef _ST_MODE - _mixerCoderSTSpec = new NCoderMixer::CCoderMixer2ST; - _mixerCoder = _mixerCoderSTSpec; - _mixerCoderCommon = _mixerCoderSTSpec; - #endif - } - RINOK(_mixerCoderCommon->SetBindInfo(bindInfo)); - - for (i = 0; i < numCoders; i++) - { - const CCoderInfo &coderInfo = folderInfo.Coders[i]; - - - CMyComPtr decoder; - CMyComPtr decoder2; - RINOK(CreateCoder( - EXTERNAL_CODECS_LOC_VARS - coderInfo.MethodID, decoder, decoder2, false)); - CMyComPtr decoderUnknown; - if (coderInfo.IsSimpleCoder()) - { - if (decoder == 0) - return E_NOTIMPL; - - decoderUnknown = (IUnknown *)decoder; - - if (_multiThread) - _mixerCoderMTSpec->AddCoder(decoder); - #ifdef _ST_MODE - else - _mixerCoderSTSpec->AddCoder(decoder, false); - #endif - } - else - { - if (decoder2 == 0) - return E_NOTIMPL; - decoderUnknown = (IUnknown *)decoder2; - if (_multiThread) - _mixerCoderMTSpec->AddCoder2(decoder2); - #ifdef _ST_MODE - else - _mixerCoderSTSpec->AddCoder2(decoder2, false); - #endif - } - _decoders.Add(decoderUnknown); - #ifdef EXTERNAL_CODECS - CMyComPtr setCompressCodecsInfo; - decoderUnknown.QueryInterface(IID_ISetCompressCodecsInfo, (void **)&setCompressCodecsInfo); - if (setCompressCodecsInfo) - { - RINOK(setCompressCodecsInfo->SetCompressCodecsInfo(codecsInfo)); - } - #endif - } - _bindInfoExPrev = bindInfo; - _bindInfoExPrevIsDefined = true; - } - int i; - _mixerCoderCommon->ReInit(); - - UInt32 packStreamIndex = 0, unpackStreamIndex = 0; - UInt32 coderIndex = 0; - // UInt32 coder2Index = 0; - - for (i = 0; i < numCoders; i++) - { - const CCoderInfo &coderInfo = folderInfo.Coders[i]; - CMyComPtr &decoder = _decoders[coderIndex]; - - { - CMyComPtr setDecoderProperties; - decoder.QueryInterface(IID_ICompressSetDecoderProperties2, &setDecoderProperties); - if (setDecoderProperties) - { - const CByteBuffer &props = coderInfo.Props; - size_t size = props.GetCapacity(); - if (size > 0xFFFFFFFF) - return E_NOTIMPL; - if (size > 0) - { - RINOK(setDecoderProperties->SetDecoderProperties2((const Byte *)props, (UInt32)size)); - } - } - } - - #ifdef COMPRESS_MT - if (mtMode) - { - CMyComPtr setCoderMt; - decoder.QueryInterface(IID_ICompressSetCoderMt, &setCoderMt); - if (setCoderMt) - { - RINOK(setCoderMt->SetNumberOfThreads(numThreads)); - } - } - #endif - - #ifndef _NO_CRYPTO - { - CMyComPtr cryptoSetPassword; - decoder.QueryInterface(IID_ICryptoSetPassword, &cryptoSetPassword); - if (cryptoSetPassword) - { - if (getTextPassword == 0) - return E_FAIL; - CMyComBSTR passwordBSTR; - RINOK(getTextPassword->CryptoGetTextPassword(&passwordBSTR)); - CByteBuffer buffer; - passwordIsDefined = true; - const UString password(passwordBSTR); - const UInt32 sizeInBytes = password.Length() * 2; - buffer.SetCapacity(sizeInBytes); - for (int i = 0; i < password.Length(); i++) - { - wchar_t c = password[i]; - ((Byte *)buffer)[i * 2] = (Byte)c; - ((Byte *)buffer)[i * 2 + 1] = (Byte)(c >> 8); - } - RINOK(cryptoSetPassword->CryptoSetPassword((const Byte *)buffer, sizeInBytes)); - } - } - #endif - - coderIndex++; - - UInt32 numInStreams = (UInt32)coderInfo.NumInStreams; - UInt32 numOutStreams = (UInt32)coderInfo.NumOutStreams; - CRecordVector packSizesPointers; - CRecordVector unpackSizesPointers; - packSizesPointers.Reserve(numInStreams); - unpackSizesPointers.Reserve(numOutStreams); - UInt32 j; - for (j = 0; j < numOutStreams; j++, unpackStreamIndex++) - unpackSizesPointers.Add(&folderInfo.UnpackSizes[unpackStreamIndex]); - - for (j = 0; j < numInStreams; j++, packStreamIndex++) - { - int bindPairIndex = folderInfo.FindBindPairForInStream(packStreamIndex); - if (bindPairIndex >= 0) - packSizesPointers.Add( - &folderInfo.UnpackSizes[(UInt32)folderInfo.BindPairs[bindPairIndex].OutIndex]); - else - { - int index = folderInfo.FindPackStreamArrayIndex(packStreamIndex); - if (index < 0) - return E_FAIL; - packSizesPointers.Add(&packSizes[index]); - } - } - - _mixerCoderCommon->SetCoderInfo(i, - &packSizesPointers.Front(), - &unpackSizesPointers.Front()); - } - UInt32 mainCoder, temp; - bindInfo.FindOutStream(bindInfo.OutStreams[0], mainCoder, temp); - - if (_multiThread) - _mixerCoderMTSpec->SetProgressCoderIndex(mainCoder); - /* - else - _mixerCoderSTSpec->SetProgressCoderIndex(mainCoder);; - */ - - if (numCoders == 0) - return 0; - CRecordVector inStreamPointers; - inStreamPointers.Reserve(inStreams.Size()); - for (i = 0; i < inStreams.Size(); i++) - inStreamPointers.Add(inStreams[i]); - ISequentialOutStream *outStreamPointer = outStream; - return _mixerCoder->Code(&inStreamPointers.Front(), NULL, - inStreams.Size(), &outStreamPointer, NULL, 1, compressProgress); -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zDecode.h b/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zDecode.h deleted file mode 100644 index aa3904a7c..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zDecode.h +++ /dev/null @@ -1,68 +0,0 @@ -// 7zDecode.h - -#ifndef __7Z_DECODE_H -#define __7Z_DECODE_H - -#include "../../IStream.h" -#include "../../IPassword.h" - -#include "../Common/CoderMixer2.h" -#include "../Common/CoderMixer2MT.h" -#ifdef _ST_MODE -#include "../Common/CoderMixer2ST.h" -#endif - -#include "../../Common/CreateCoder.h" - -#include "7zItem.h" - -namespace NArchive { -namespace N7z { - -struct CBindInfoEx: public NCoderMixer::CBindInfo -{ - CRecordVector CoderMethodIDs; - void Clear() - { - CBindInfo::Clear(); - CoderMethodIDs.Clear(); - } -}; - -class CDecoder -{ - bool _bindInfoExPrevIsDefined; - CBindInfoEx _bindInfoExPrev; - - bool _multiThread; - #ifdef _ST_MODE - NCoderMixer::CCoderMixer2ST *_mixerCoderSTSpec; - #endif - NCoderMixer::CCoderMixer2MT *_mixerCoderMTSpec; - NCoderMixer::CCoderMixer2 *_mixerCoderCommon; - - CMyComPtr _mixerCoder; - CObjectVector > _decoders; - // CObjectVector > _decoders2; -public: - CDecoder(bool multiThread); - HRESULT Decode( - DECL_EXTERNAL_CODECS_LOC_VARS - IInStream *inStream, - UInt64 startPos, - const UInt64 *packSizes, - const CFolder &folder, - ISequentialOutStream *outStream, - ICompressProgressInfo *compressProgress - #ifndef _NO_CRYPTO - , ICryptoGetTextPassword *getTextPasswordSpec, bool &passwordIsDefined - #endif - #ifdef COMPRESS_MT - , bool mtMode, UInt32 numThreads - #endif - ); -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zExtract.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zExtract.cpp deleted file mode 100644 index dbc1aa522..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zExtract.cpp +++ /dev/null @@ -1,273 +0,0 @@ -// 7zExtract.cpp - -#include "StdAfx.h" - -#include "7zHandler.h" -#include "7zFolderOutStream.h" -#include "7zDecode.h" -// #include "7z1Decode.h" - -#include "../../../Common/ComTry.h" -#include "../../Common/StreamObjects.h" -#include "../../Common/ProgressUtils.h" -#include "../../Common/LimitedStreams.h" - -namespace NArchive { -namespace N7z { - -struct CExtractFolderInfo -{ - #ifdef _7Z_VOL - int VolumeIndex; - #endif - CNum FileIndex; - CNum FolderIndex; - CBoolVector ExtractStatuses; - UInt64 UnpackSize; - CExtractFolderInfo( - #ifdef _7Z_VOL - int volumeIndex, - #endif - CNum fileIndex, CNum folderIndex): - #ifdef _7Z_VOL - VolumeIndex(volumeIndex), - #endif - FileIndex(fileIndex), - FolderIndex(folderIndex), - UnpackSize(0) - { - if (fileIndex != kNumNoIndex) - { - ExtractStatuses.Reserve(1); - ExtractStatuses.Add(true); - } - }; -}; - -STDMETHODIMP CHandler::Extract(const UInt32* indices, UInt32 numItems, - Int32 testModeSpec, IArchiveExtractCallback *extractCallbackSpec) -{ - COM_TRY_BEGIN - bool testMode = (testModeSpec != 0); - CMyComPtr extractCallback = extractCallbackSpec; - UInt64 importantTotalUnpacked = 0; - - bool allFilesMode = (numItems == UInt32(-1)); - if (allFilesMode) - numItems = - #ifdef _7Z_VOL - _refs.Size(); - #else - _db.Files.Size(); - #endif - - if(numItems == 0) - return S_OK; - - /* - if(_volumes.Size() != 1) - return E_FAIL; - const CVolume &volume = _volumes.Front(); - const CArchiveDatabaseEx &_db = volume.Database; - IInStream *_inStream = volume.Stream; - */ - - CObjectVector extractFolderInfoVector; - for(UInt32 ii = 0; ii < numItems; ii++) - { - // UInt32 fileIndex = allFilesMode ? indexIndex : indices[indexIndex]; - UInt32 ref2Index = allFilesMode ? ii : indices[ii]; - // const CRef2 &ref2 = _refs[ref2Index]; - - // for(UInt32 ri = 0; ri < ref2.Refs.Size(); ri++) - { - #ifdef _7Z_VOL - // const CRef &ref = ref2.Refs[ri]; - const CRef &ref = _refs[ref2Index]; - - int volumeIndex = ref.VolumeIndex; - const CVolume &volume = _volumes[volumeIndex]; - const CArchiveDatabaseEx &db = volume.Database; - UInt32 fileIndex = ref.ItemIndex; - #else - const CArchiveDatabaseEx &db = _db; - UInt32 fileIndex = ref2Index; - #endif - - CNum folderIndex = db.FileIndexToFolderIndexMap[fileIndex]; - if (folderIndex == kNumNoIndex) - { - extractFolderInfoVector.Add(CExtractFolderInfo( - #ifdef _7Z_VOL - volumeIndex, - #endif - fileIndex, kNumNoIndex)); - continue; - } - if (extractFolderInfoVector.IsEmpty() || - folderIndex != extractFolderInfoVector.Back().FolderIndex - #ifdef _7Z_VOL - || volumeIndex != extractFolderInfoVector.Back().VolumeIndex - #endif - ) - { - extractFolderInfoVector.Add(CExtractFolderInfo( - #ifdef _7Z_VOL - volumeIndex, - #endif - kNumNoIndex, folderIndex)); - const CFolder &folderInfo = db.Folders[folderIndex]; - UInt64 unpackSize = folderInfo.GetUnpackSize(); - importantTotalUnpacked += unpackSize; - extractFolderInfoVector.Back().UnpackSize = unpackSize; - } - - CExtractFolderInfo &efi = extractFolderInfoVector.Back(); - - // const CFolderInfo &folderInfo = m_dam_Folders[folderIndex]; - CNum startIndex = db.FolderStartFileIndex[folderIndex]; - for (CNum index = efi.ExtractStatuses.Size(); - index <= fileIndex - startIndex; index++) - { - // UInt64 unpackSize = _db.Files[startIndex + index].UnpackSize; - // Count partial_folder_size - // efi.UnpackSize += unpackSize; - // importantTotalUnpacked += unpackSize; - efi.ExtractStatuses.Add(index == fileIndex - startIndex); - } - } - } - - extractCallback->SetTotal(importantTotalUnpacked); - - CDecoder decoder( - #ifdef _ST_MODE - false - #else - true - #endif - ); - // CDecoder1 decoder; - - UInt64 currentTotalPacked = 0; - UInt64 currentTotalUnpacked = 0; - UInt64 totalFolderUnpacked; - UInt64 totalFolderPacked; - - CLocalProgress *lps = new CLocalProgress; - CMyComPtr progress = lps; - lps->Init(extractCallback, false); - - for(int i = 0; i < extractFolderInfoVector.Size(); i++, - currentTotalUnpacked += totalFolderUnpacked, - currentTotalPacked += totalFolderPacked) - { - lps->OutSize = currentTotalUnpacked; - lps->InSize = currentTotalPacked; - RINOK(lps->SetCur()); - - const CExtractFolderInfo &efi = extractFolderInfoVector[i]; - totalFolderUnpacked = efi.UnpackSize; - - totalFolderPacked = 0; - - CFolderOutStream *folderOutStream = new CFolderOutStream; - CMyComPtr outStream(folderOutStream); - - #ifdef _7Z_VOL - const CVolume &volume = _volumes[efi.VolumeIndex]; - const CArchiveDatabaseEx &db = volume.Database; - #else - const CArchiveDatabaseEx &db = _db; - #endif - - CNum startIndex; - if (efi.FileIndex != kNumNoIndex) - startIndex = efi.FileIndex; - else - startIndex = db.FolderStartFileIndex[efi.FolderIndex]; - - - HRESULT result = folderOutStream->Init(&db, - #ifdef _7Z_VOL - volume.StartRef2Index, - #else - 0, - #endif - startIndex, - &efi.ExtractStatuses, extractCallback, testMode, _crcSize != 0); - - RINOK(result); - - if (efi.FileIndex != kNumNoIndex) - continue; - - CNum folderIndex = efi.FolderIndex; - const CFolder &folderInfo = db.Folders[folderIndex]; - - totalFolderPacked = _db.GetFolderFullPackSize(folderIndex); - - CNum packStreamIndex = db.FolderStartPackStreamIndex[folderIndex]; - UInt64 folderStartPackPos = db.GetFolderStreamPos(folderIndex, 0); - - #ifndef _NO_CRYPTO - CMyComPtr getTextPassword; - if (extractCallback) - extractCallback.QueryInterface(IID_ICryptoGetTextPassword, &getTextPassword); - #endif - - try - { - #ifndef _NO_CRYPTO - bool passwordIsDefined; - #endif - - HRESULT result = decoder.Decode( - EXTERNAL_CODECS_VARS - #ifdef _7Z_VOL - volume.Stream, - #else - _inStream, - #endif - folderStartPackPos, - &db.PackSizes[packStreamIndex], - folderInfo, - outStream, - progress - #ifndef _NO_CRYPTO - , getTextPassword, passwordIsDefined - #endif - #ifdef COMPRESS_MT - , true, _numThreads - #endif - ); - - if (result == S_FALSE) - { - RINOK(folderOutStream->FlushCorrupted(NArchive::NExtract::NOperationResult::kDataError)); - continue; - } - if (result == E_NOTIMPL) - { - RINOK(folderOutStream->FlushCorrupted(NArchive::NExtract::NOperationResult::kUnSupportedMethod)); - continue; - } - if (result != S_OK) - return result; - if (folderOutStream->WasWritingFinished() != S_OK) - { - RINOK(folderOutStream->FlushCorrupted(NArchive::NExtract::NOperationResult::kDataError)); - continue; - } - } - catch(...) - { - RINOK(folderOutStream->FlushCorrupted(NArchive::NExtract::NOperationResult::kDataError)); - continue; - } - } - return S_OK; - COM_TRY_END -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zFolderInStream.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zFolderInStream.cpp deleted file mode 100644 index 3b11f1686..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zFolderInStream.cpp +++ /dev/null @@ -1,130 +0,0 @@ -// 7zFolderInStream.cpp - -#include "StdAfx.h" - -#include "7zFolderInStream.h" - -namespace NArchive { -namespace N7z { - -CFolderInStream::CFolderInStream() -{ - _inStreamWithHashSpec = new CSequentialInStreamWithCRC; - _inStreamWithHash = _inStreamWithHashSpec; -} - -void CFolderInStream::Init(IArchiveUpdateCallback *updateCallback, - const UInt32 *fileIndices, UInt32 numFiles) -{ - _updateCallback = updateCallback; - _numFiles = numFiles; - _fileIndex = 0; - _fileIndices = fileIndices; - Processed.Clear(); - CRCs.Clear(); - Sizes.Clear(); - _fileIsOpen = false; - _currentSizeIsDefined = false; -} - -HRESULT CFolderInStream::OpenStream() -{ - _filePos = 0; - while (_fileIndex < _numFiles) - { - _currentSizeIsDefined = false; - CMyComPtr stream; - HRESULT result = _updateCallback->GetStream(_fileIndices[_fileIndex], &stream); - if (result != S_OK && result != S_FALSE) - return result; - _fileIndex++; - _inStreamWithHashSpec->SetStream(stream); - _inStreamWithHashSpec->Init(); - if (!stream) - { - RINOK(_updateCallback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK)); - Sizes.Add(0); - Processed.Add(result == S_OK); - AddDigest(); - continue; - } - CMyComPtr streamGetSize; - if (stream.QueryInterface(IID_IStreamGetSize, &streamGetSize) == S_OK) - { - if(streamGetSize) - { - _currentSizeIsDefined = true; - RINOK(streamGetSize->GetSize(&_currentSize)); - } - } - - _fileIsOpen = true; - return S_OK; - } - return S_OK; -} - -void CFolderInStream::AddDigest() -{ - CRCs.Add(_inStreamWithHashSpec->GetCRC()); -} - -HRESULT CFolderInStream::CloseStream() -{ - RINOK(_updateCallback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK)); - _inStreamWithHashSpec->ReleaseStream(); - _fileIsOpen = false; - Processed.Add(true); - Sizes.Add(_filePos); - AddDigest(); - return S_OK; -} - -STDMETHODIMP CFolderInStream::Read(void *data, UInt32 size, UInt32 *processedSize) -{ - UInt32 realProcessedSize = 0; - while ((_fileIndex < _numFiles || _fileIsOpen) && size > 0) - { - if (_fileIsOpen) - { - UInt32 localProcessedSize; - RINOK(_inStreamWithHash->Read( - ((Byte *)data) + realProcessedSize, size, &localProcessedSize)); - if (localProcessedSize == 0) - { - RINOK(CloseStream()); - continue; - } - realProcessedSize += localProcessedSize; - _filePos += localProcessedSize; - size -= localProcessedSize; - break; - } - else - { - RINOK(OpenStream()); - } - } - if (processedSize != 0) - *processedSize = realProcessedSize; - return S_OK; -} - -STDMETHODIMP CFolderInStream::GetSubStreamSize(UInt64 subStream, UInt64 *value) -{ - *value = 0; - int subStreamIndex = (int)subStream; - if (subStreamIndex < 0 || subStream > Sizes.Size()) - return E_FAIL; - if (subStreamIndex < Sizes.Size()) - { - *value= Sizes[subStreamIndex]; - return S_OK; - } - if (!_currentSizeIsDefined) - return S_FALSE; - *value = _currentSize; - return S_OK; -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zFolderInStream.h b/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zFolderInStream.h deleted file mode 100644 index b4df6d62a..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zFolderInStream.h +++ /dev/null @@ -1,66 +0,0 @@ -// 7z/FolderInStream.h - -#ifndef __7Z_FOLDERINSTREAM_H -#define __7Z_FOLDERINSTREAM_H - -#include "7zItem.h" -#include "7zHeader.h" - -#include "../IArchive.h" -#include "../Common/InStreamWithCRC.h" -#include "../../IStream.h" -#include "../../ICoder.h" - -namespace NArchive { -namespace N7z { - -class CFolderInStream: - public ISequentialInStream, - public ICompressGetSubStreamSize, - public CMyUnknownImp -{ -public: - - MY_UNKNOWN_IMP1(ICompressGetSubStreamSize) - - CFolderInStream(); - - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); - - STDMETHOD(GetSubStreamSize)(UInt64 subStream, UInt64 *value); -private: - CSequentialInStreamWithCRC *_inStreamWithHashSpec; - CMyComPtr _inStreamWithHash; - CMyComPtr _updateCallback; - - bool _currentSizeIsDefined; - UInt64 _currentSize; - - bool _fileIsOpen; - UInt64 _filePos; - - const UInt32 *_fileIndices; - UInt32 _numFiles; - UInt32 _fileIndex; - - HRESULT OpenStream(); - HRESULT CloseStream(); - void AddDigest(); -public: - void Init(IArchiveUpdateCallback *updateCallback, - const UInt32 *fileIndices, UInt32 numFiles); - CRecordVector Processed; - CRecordVector CRCs; - CRecordVector Sizes; - UInt64 GetFullSize() const - { - UInt64 size = 0; - for (int i = 0; i < Sizes.Size(); i++) - size += Sizes[i]; - return size; - } -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zFolderOutStream.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zFolderOutStream.cpp deleted file mode 100644 index d3a79ee13..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zFolderOutStream.cpp +++ /dev/null @@ -1,164 +0,0 @@ -// 7zFolderOutStream.cpp - -#include "StdAfx.h" - -#include "7zFolderOutStream.h" - -namespace NArchive { -namespace N7z { - -CFolderOutStream::CFolderOutStream() -{ - _outStreamWithHashSpec = new COutStreamWithCRC; - _outStreamWithHash = _outStreamWithHashSpec; -} - -HRESULT CFolderOutStream::Init( - const CArchiveDatabaseEx *archiveDatabase, - UInt32 ref2Offset, - UInt32 startIndex, - const CBoolVector *extractStatuses, - IArchiveExtractCallback *extractCallback, - bool testMode, - bool checkCrc) -{ - _archiveDatabase = archiveDatabase; - _ref2Offset = ref2Offset; - _startIndex = startIndex; - - _extractStatuses = extractStatuses; - _extractCallback = extractCallback; - _testMode = testMode; - - _checkCrc = checkCrc; - - _currentIndex = 0; - _fileIsOpen = false; - return WriteEmptyFiles(); -} - -HRESULT CFolderOutStream::OpenFile() -{ - Int32 askMode; - if((*_extractStatuses)[_currentIndex]) - askMode = _testMode ? - NArchive::NExtract::NAskMode::kTest : - NArchive::NExtract::NAskMode::kExtract; - else - askMode = NArchive::NExtract::NAskMode::kSkip; - CMyComPtr realOutStream; - - UInt32 index = _startIndex + _currentIndex; - RINOK(_extractCallback->GetStream(_ref2Offset + index, &realOutStream, askMode)); - - _outStreamWithHashSpec->SetStream(realOutStream); - _outStreamWithHashSpec->Init(_checkCrc); - if (askMode == NArchive::NExtract::NAskMode::kExtract && - (!realOutStream)) - { - const CFileItem &fi = _archiveDatabase->Files[index]; - if (!_archiveDatabase->IsItemAnti(index) && !fi.IsDir) - askMode = NArchive::NExtract::NAskMode::kSkip; - } - return _extractCallback->PrepareOperation(askMode); -} - -HRESULT CFolderOutStream::WriteEmptyFiles() -{ - for(;_currentIndex < _extractStatuses->Size(); _currentIndex++) - { - UInt32 index = _startIndex + _currentIndex; - const CFileItem &fi = _archiveDatabase->Files[index]; - if (!_archiveDatabase->IsItemAnti(index) && !fi.IsDir && fi.Size != 0) - return S_OK; - RINOK(OpenFile()); - RINOK(_extractCallback->SetOperationResult(NArchive::NExtract::NOperationResult::kOK)); - _outStreamWithHashSpec->ReleaseStream(); - } - return S_OK; -} - -STDMETHODIMP CFolderOutStream::Write(const void *data, - UInt32 size, UInt32 *processedSize) -{ - UInt32 realProcessedSize = 0; - while(_currentIndex < _extractStatuses->Size()) - { - if (_fileIsOpen) - { - UInt32 index = _startIndex + _currentIndex; - const CFileItem &fi = _archiveDatabase->Files[index]; - UInt64 fileSize = fi.Size; - - UInt32 numBytesToWrite = (UInt32)MyMin(fileSize - _filePos, - UInt64(size - realProcessedSize)); - - UInt32 processedSizeLocal; - RINOK(_outStreamWithHash->Write((const Byte *)data + realProcessedSize, - numBytesToWrite, &processedSizeLocal)); - - _filePos += processedSizeLocal; - realProcessedSize += processedSizeLocal; - if (_filePos == fileSize) - { - bool digestsAreEqual; - if (fi.CrcDefined && _checkCrc) - digestsAreEqual = fi.Crc == _outStreamWithHashSpec->GetCRC(); - else - digestsAreEqual = true; - - RINOK(_extractCallback->SetOperationResult( - digestsAreEqual ? - NArchive::NExtract::NOperationResult::kOK : - NArchive::NExtract::NOperationResult::kCRCError)); - _outStreamWithHashSpec->ReleaseStream(); - _fileIsOpen = false; - _currentIndex++; - } - if (realProcessedSize == size) - { - if (processedSize != NULL) - *processedSize = realProcessedSize; - return WriteEmptyFiles(); - } - } - else - { - RINOK(OpenFile()); - _fileIsOpen = true; - _filePos = 0; - } - } - if (processedSize != NULL) - *processedSize = size; - return S_OK; -} - -HRESULT CFolderOutStream::FlushCorrupted(Int32 resultEOperationResult) -{ - while(_currentIndex < _extractStatuses->Size()) - { - if (_fileIsOpen) - { - RINOK(_extractCallback->SetOperationResult(resultEOperationResult)); - _outStreamWithHashSpec->ReleaseStream(); - _fileIsOpen = false; - _currentIndex++; - } - else - { - RINOK(OpenFile()); - _fileIsOpen = true; - } - } - return S_OK; -} - -HRESULT CFolderOutStream::WasWritingFinished() -{ - if (_currentIndex == _extractStatuses->Size()) - return S_OK; - return E_FAIL; -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zFolderOutStream.h b/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zFolderOutStream.h deleted file mode 100644 index d88cde985..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zFolderOutStream.h +++ /dev/null @@ -1,60 +0,0 @@ -// 7zFolderOutStream.h - -#ifndef __7Z_FOLDEROUTSTREAM_H -#define __7Z_FOLDEROUTSTREAM_H - -#include "7zIn.h" - -#include "../../IStream.h" -#include "../IArchive.h" -#include "../Common/OutStreamWithCRC.h" - -namespace NArchive { -namespace N7z { - -class CFolderOutStream: - public ISequentialOutStream, - public CMyUnknownImp -{ -public: - MY_UNKNOWN_IMP - - CFolderOutStream(); - - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); -private: - - COutStreamWithCRC *_outStreamWithHashSpec; - CMyComPtr _outStreamWithHash; - const CArchiveDatabaseEx *_archiveDatabase; - const CBoolVector *_extractStatuses; - UInt32 _startIndex; - UInt32 _ref2Offset; - int _currentIndex; - // UInt64 _currentDataPos; - CMyComPtr _extractCallback; - bool _testMode; - - bool _fileIsOpen; - - bool _checkCrc; - UInt64 _filePos; - - HRESULT OpenFile(); - HRESULT WriteEmptyFiles(); -public: - HRESULT Init( - const CArchiveDatabaseEx *archiveDatabase, - UInt32 ref2Offset, - UInt32 startIndex, - const CBoolVector *extractStatuses, - IArchiveExtractCallback *extractCallback, - bool testMode, - bool checkCrc); - HRESULT FlushCorrupted(Int32 resultEOperationResult); - HRESULT WasWritingFinished(); -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zHandler.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zHandler.cpp deleted file mode 100644 index c76a106f8..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zHandler.cpp +++ /dev/null @@ -1,503 +0,0 @@ -// 7zHandler.cpp - -#include "StdAfx.h" - -extern "C" -{ - #include "../../../../C/CpuArch.h" -} - -#include "../../../Common/ComTry.h" -#include "../../../Common/IntToString.h" - -#ifdef COMPRESS_MT -#include "../../../Windows/System.h" -#endif - -#include "../Common/ItemNameUtils.h" - -#include "7zHandler.h" -#include "7zProperties.h" - -#ifdef __7Z_SET_PROPERTIES -#ifdef EXTRACT_ONLY -#include "../Common/ParseProperties.h" -#endif -#endif - -using namespace NWindows; - -extern UString ConvertMethodIdToString(UInt64 id); - -namespace NArchive { -namespace N7z { - -CHandler::CHandler() -{ - _crcSize = 4; - - #ifndef _NO_CRYPTO - _passwordIsDefined = false; - #endif - - #ifdef EXTRACT_ONLY - #ifdef COMPRESS_MT - _numThreads = NSystem::GetNumberOfProcessors(); - #endif - #else - Init(); - #endif -} - -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) -{ - *numItems = _db.Files.Size(); - return S_OK; -} - -#ifdef _SFX - -IMP_IInArchive_ArcProps_NO - -STDMETHODIMP CHandler::GetNumberOfProperties(UInt32 * /* numProperties */) -{ - return E_NOTIMPL; -} - -STDMETHODIMP CHandler::GetPropertyInfo(UInt32 /* index */, - BSTR * /* name */, PROPID * /* propID */, VARTYPE * /* varType */) -{ - return E_NOTIMPL; -} - - -#else - -STATPROPSTG kArcProps[] = -{ - { NULL, kpidMethod, VT_BSTR}, - { NULL, kpidSolid, VT_BOOL}, - { NULL, kpidNumBlocks, VT_UI4}, - { NULL, kpidPhySize, VT_UI8}, - { NULL, kpidHeadersSize, VT_UI8}, - { NULL, kpidOffset, VT_UI8} -}; - -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) -{ - COM_TRY_BEGIN - NCOM::CPropVariant prop; - switch(propID) - { - case kpidMethod: - { - UString resString; - CRecordVector ids; - int i; - for (i = 0; i < _db.Folders.Size(); i++) - { - const CFolder &f = _db.Folders[i]; - for (int j = f.Coders.Size() - 1; j >= 0; j--) - ids.AddToUniqueSorted(f.Coders[j].MethodID); - } - - for (i = 0; i < ids.Size(); i++) - { - UInt64 id = ids[i]; - UString methodName; - /* bool methodIsKnown = */ FindMethod(EXTERNAL_CODECS_VARS id, methodName); - if (methodName.IsEmpty()) - methodName = ConvertMethodIdToString(id); - if (!resString.IsEmpty()) - resString += L' '; - resString += methodName; - } - prop = resString; - break; - } - case kpidSolid: prop = _db.IsSolid(); break; - case kpidNumBlocks: prop = (UInt32)_db.Folders.Size(); break; - case kpidHeadersSize: prop = _db.HeadersSize; break; - case kpidPhySize: prop = _db.PhySize; break; - case kpidOffset: if (_db.ArchiveInfo.StartPosition != 0) prop = _db.ArchiveInfo.StartPosition; break; - } - prop.Detach(value); - return S_OK; - COM_TRY_END -} - -IMP_IInArchive_ArcProps - -#endif - -static void SetPropFromUInt64Def(CUInt64DefVector &v, int index, NCOM::CPropVariant &prop) -{ - UInt64 value; - if (v.GetItem(index, value)) - { - FILETIME ft; - ft.dwLowDateTime = (DWORD)value; - ft.dwHighDateTime = (DWORD)(value >> 32); - prop = ft; - } -} - -#ifndef _SFX - -static UString ConvertUInt32ToString(UInt32 value) -{ - wchar_t buffer[32]; - ConvertUInt64ToString(value, buffer); - return buffer; -} - -static UString GetStringForSizeValue(UInt32 value) -{ - for (int i = 31; i >= 0; i--) - if ((UInt32(1) << i) == value) - return ConvertUInt32ToString(i); - UString result; - if (value % (1 << 20) == 0) - { - result += ConvertUInt32ToString(value >> 20); - result += L"m"; - } - else if (value % (1 << 10) == 0) - { - result += ConvertUInt32ToString(value >> 10); - result += L"k"; - } - else - { - result += ConvertUInt32ToString(value); - result += L"b"; - } - return result; -} - -static const UInt64 k_Copy = 0x0; -static const UInt64 k_LZMA = 0x030101; -static const UInt64 k_PPMD = 0x030401; - -static wchar_t GetHex(Byte value) -{ - return (wchar_t)((value < 10) ? (L'0' + value) : (L'A' + (value - 10))); -} -static inline UString GetHex2(Byte value) -{ - UString result; - result += GetHex((Byte)(value >> 4)); - result += GetHex((Byte)(value & 0xF)); - return result; -} - -#endif - -static const UInt64 k_AES = 0x06F10701; - -bool CHandler::IsEncrypted(UInt32 index2) const -{ - CNum folderIndex = _db.FileIndexToFolderIndexMap[index2]; - if (folderIndex != kNumNoIndex) - { - const CFolder &folderInfo = _db.Folders[folderIndex]; - for (int i = folderInfo.Coders.Size() - 1; i >= 0; i--) - if (folderInfo.Coders[i].MethodID == k_AES) - return true; - } - return false; -} - -STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) -{ - COM_TRY_BEGIN - NCOM::CPropVariant prop; - - /* - const CRef2 &ref2 = _refs[index]; - if (ref2.Refs.IsEmpty()) - return E_FAIL; - const CRef &ref = ref2.Refs.Front(); - */ - - const CFileItem &item = _db.Files[index]; - UInt32 index2 = index; - - switch(propID) - { - case kpidPath: - if (!item.Name.IsEmpty()) - prop = NItemName::GetOSName(item.Name); - break; - case kpidIsDir: prop = item.IsDir; break; - case kpidSize: - { - prop = item.Size; - // prop = ref2.Size; - break; - } - case kpidPackSize: - { - // prop = ref2.PackSize; - { - CNum folderIndex = _db.FileIndexToFolderIndexMap[index2]; - if (folderIndex != kNumNoIndex) - { - if (_db.FolderStartFileIndex[folderIndex] == (CNum)index2) - prop = _db.GetFolderFullPackSize(folderIndex); - /* - else - prop = (UInt64)0; - */ - } - else - prop = (UInt64)0; - } - break; - } - case kpidPosition: { UInt64 v; if (_db.StartPos.GetItem(index2, v)) prop = v; break; } - case kpidCTime: SetPropFromUInt64Def(_db.CTime, index2, prop); break; - case kpidATime: SetPropFromUInt64Def(_db.ATime, index2, prop); break; - case kpidMTime: SetPropFromUInt64Def(_db.MTime, index2, prop); break; - case kpidAttrib: if (item.AttribDefined) prop = item.Attrib; break; - case kpidCRC: if (item.CrcDefined) prop = item.Crc; break; - case kpidEncrypted: prop = IsEncrypted(index2); break; - case kpidIsAnti: prop = _db.IsItemAnti(index2); break; - #ifndef _SFX - case kpidMethod: - { - CNum folderIndex = _db.FileIndexToFolderIndexMap[index2]; - if (folderIndex != kNumNoIndex) - { - const CFolder &folderInfo = _db.Folders[folderIndex]; - UString methodsString; - for (int i = folderInfo.Coders.Size() - 1; i >= 0; i--) - { - const CCoderInfo &coderInfo = folderInfo.Coders[i]; - if (!methodsString.IsEmpty()) - methodsString += L' '; - - { - UString methodName; - bool methodIsKnown = FindMethod( - EXTERNAL_CODECS_VARS - coderInfo.MethodID, methodName); - - if (methodIsKnown) - { - methodsString += methodName; - if (coderInfo.MethodID == k_LZMA) - { - if (coderInfo.Props.GetCapacity() >= 5) - { - methodsString += L":"; - UInt32 dicSize = GetUi32((const Byte *)coderInfo.Props + 1); - methodsString += GetStringForSizeValue(dicSize); - } - } - else if (coderInfo.MethodID == k_PPMD) - { - if (coderInfo.Props.GetCapacity() >= 5) - { - Byte order = *(const Byte *)coderInfo.Props; - methodsString += L":o"; - methodsString += ConvertUInt32ToString(order); - methodsString += L":mem"; - UInt32 dicSize = GetUi32((const Byte *)coderInfo.Props + 1); - methodsString += GetStringForSizeValue(dicSize); - } - } - else if (coderInfo.MethodID == k_AES) - { - if (coderInfo.Props.GetCapacity() >= 1) - { - methodsString += L":"; - const Byte *data = (const Byte *)coderInfo.Props; - Byte firstByte = *data++; - UInt32 numCyclesPower = firstByte & 0x3F; - methodsString += ConvertUInt32ToString(numCyclesPower); - /* - if ((firstByte & 0xC0) != 0) - { - methodsString += L":"; - return S_OK; - UInt32 saltSize = (firstByte >> 7) & 1; - UInt32 ivSize = (firstByte >> 6) & 1; - if (coderInfo.Props.GetCapacity() >= 2) - { - Byte secondByte = *data++; - saltSize += (secondByte >> 4); - ivSize += (secondByte & 0x0F); - } - } - */ - } - } - else - { - if (coderInfo.Props.GetCapacity() > 0) - { - methodsString += L":["; - for (size_t bi = 0; bi < coderInfo.Props.GetCapacity(); bi++) - { - if (bi > 5 && bi + 1 < coderInfo.Props.GetCapacity()) - { - methodsString += L".."; - break; - } - else - methodsString += GetHex2(coderInfo.Props[bi]); - } - methodsString += L"]"; - } - } - } - else - { - methodsString += ConvertMethodIdToString(coderInfo.MethodID); - } - } - } - prop = methodsString; - } - } - break; - case kpidBlock: - { - CNum folderIndex = _db.FileIndexToFolderIndexMap[index2]; - if (folderIndex != kNumNoIndex) - prop = (UInt32)folderIndex; - } - break; - case kpidPackedSize0: - case kpidPackedSize1: - case kpidPackedSize2: - case kpidPackedSize3: - case kpidPackedSize4: - { - CNum folderIndex = _db.FileIndexToFolderIndexMap[index2]; - if (folderIndex != kNumNoIndex) - { - const CFolder &folderInfo = _db.Folders[folderIndex]; - if (_db.FolderStartFileIndex[folderIndex] == (CNum)index2 && - folderInfo.PackStreams.Size() > (int)(propID - kpidPackedSize0)) - { - prop = _db.GetFolderPackStreamSize(folderIndex, propID - kpidPackedSize0); - } - else - prop = (UInt64)0; - } - else - prop = (UInt64)0; - } - break; - #endif - } - prop.Detach(value); - return S_OK; - COM_TRY_END -} - -STDMETHODIMP CHandler::Open(IInStream *stream, - const UInt64 *maxCheckStartPosition, - IArchiveOpenCallback *openArchiveCallback) -{ - COM_TRY_BEGIN - Close(); - #ifndef _SFX - _fileInfoPopIDs.Clear(); - #endif - try - { - CMyComPtr openArchiveCallbackTemp = openArchiveCallback; - - #ifndef _NO_CRYPTO - CMyComPtr getTextPassword; - if (openArchiveCallback) - { - openArchiveCallbackTemp.QueryInterface( - IID_ICryptoGetTextPassword, &getTextPassword); - } - #endif - CInArchive archive; - RINOK(archive.Open(stream, maxCheckStartPosition)); - #ifndef _NO_CRYPTO - _passwordIsDefined = false; - UString password; - #endif - HRESULT result = archive.ReadDatabase( - EXTERNAL_CODECS_VARS - _db - #ifndef _NO_CRYPTO - , getTextPassword, _passwordIsDefined - #endif - ); - RINOK(result); - _db.Fill(); - _inStream = stream; - } - catch(...) - { - Close(); - return S_FALSE; - } - // _inStream = stream; - #ifndef _SFX - FillPopIDs(); - #endif - return S_OK; - COM_TRY_END -} - -STDMETHODIMP CHandler::Close() -{ - COM_TRY_BEGIN - _inStream.Release(); - _db.Clear(); - return S_OK; - COM_TRY_END -} - -#ifdef __7Z_SET_PROPERTIES -#ifdef EXTRACT_ONLY - -STDMETHODIMP CHandler::SetProperties(const wchar_t **names, const PROPVARIANT *values, Int32 numProperties) -{ - COM_TRY_BEGIN - #ifdef COMPRESS_MT - const UInt32 numProcessors = NSystem::GetNumberOfProcessors(); - _numThreads = numProcessors; - #endif - - for (int i = 0; i < numProperties; i++) - { - UString name = names[i]; - name.MakeUpper(); - if (name.IsEmpty()) - return E_INVALIDARG; - const PROPVARIANT &value = values[i]; - UInt32 number; - int index = ParseStringToUInt32(name, number); - if (index == 0) - { - if(name.Left(2).CompareNoCase(L"MT") == 0) - { - #ifdef COMPRESS_MT - RINOK(ParseMtProp(name.Mid(2), value, numProcessors, _numThreads)); - #endif - continue; - } - else - return E_INVALIDARG; - } - } - return S_OK; - COM_TRY_END -} - -#endif -#endif - -IMPL_ISetCompressCodecsInfo - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zHandler.h b/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zHandler.h deleted file mode 100644 index c04a0f931..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zHandler.h +++ /dev/null @@ -1,121 +0,0 @@ -// 7z/Handler.h - -#ifndef __7Z_HANDLER_H -#define __7Z_HANDLER_H - -#include "../../ICoder.h" -#include "../IArchive.h" -#include "7zIn.h" - -#include "7zCompressionMode.h" - -#include "../../Common/CreateCoder.h" - -#ifndef EXTRACT_ONLY -#include "../Common/HandlerOut.h" -#endif - -namespace NArchive { -namespace N7z { - -#ifndef __7Z_SET_PROPERTIES - -#ifdef EXTRACT_ONLY -#ifdef COMPRESS_MT -#define __7Z_SET_PROPERTIES -#endif -#else -#define __7Z_SET_PROPERTIES -#endif - -#endif - - -class CHandler: - #ifndef EXTRACT_ONLY - public NArchive::COutHandler, - #endif - public IInArchive, - #ifdef __7Z_SET_PROPERTIES - public ISetProperties, - #endif - #ifndef EXTRACT_ONLY - public IOutArchive, - #endif - PUBLIC_ISetCompressCodecsInfo - public CMyUnknownImp -{ -public: - MY_QUERYINTERFACE_BEGIN2(IInArchive) - #ifdef __7Z_SET_PROPERTIES - MY_QUERYINTERFACE_ENTRY(ISetProperties) - #endif - #ifndef EXTRACT_ONLY - MY_QUERYINTERFACE_ENTRY(IOutArchive) - #endif - QUERY_ENTRY_ISetCompressCodecsInfo - MY_QUERYINTERFACE_END - MY_ADDREF_RELEASE - - INTERFACE_IInArchive(;) - - #ifdef __7Z_SET_PROPERTIES - STDMETHOD(SetProperties)(const wchar_t **names, const PROPVARIANT *values, Int32 numProperties); - #endif - - #ifndef EXTRACT_ONLY - INTERFACE_IOutArchive(;) - #endif - - DECL_ISetCompressCodecsInfo - - CHandler(); - -private: - CMyComPtr _inStream; - NArchive::N7z::CArchiveDatabaseEx _db; - #ifndef _NO_CRYPTO - bool _passwordIsDefined; - #endif - - #ifdef EXTRACT_ONLY - - #ifdef COMPRESS_MT - UInt32 _numThreads; - #endif - - UInt32 _crcSize; - - #else - - CRecordVector _binds; - - HRESULT SetPassword(CCompressionMethodMode &methodMode, IArchiveUpdateCallback *updateCallback); - - HRESULT SetCompressionMethod(CCompressionMethodMode &method, - CObjectVector &methodsInfo - #ifdef COMPRESS_MT - , UInt32 numThreads - #endif - ); - - HRESULT SetCompressionMethod( - CCompressionMethodMode &method, - CCompressionMethodMode &headerMethod); - - #endif - - bool IsEncrypted(UInt32 index2) const; - #ifndef _SFX - - CRecordVector _fileInfoPopIDs; - void FillPopIDs(); - - #endif - - DECL_EXTERNAL_CODECS_VARS -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zHeader.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zHeader.cpp deleted file mode 100644 index c010f3671..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zHeader.cpp +++ /dev/null @@ -1,27 +0,0 @@ -// 7z/Header.cpp - -#include "StdAfx.h" -#include "7zHeader.h" - -namespace NArchive { -namespace N7z { - -Byte kSignature[kSignatureSize] = {'7' + 1, 'z', 0xBC, 0xAF, 0x27, 0x1C}; -#ifdef _7Z_VOL -Byte kFinishSignature[kSignatureSize] = {'7' + 1, 'z', 0xBC, 0xAF, 0x27, 0x1C + 1}; -#endif - -class SignatureInitializer -{ -public: - SignatureInitializer() - { - kSignature[0]--; - #ifdef _7Z_VOL - kFinishSignature[0]--; - #endif - }; -} g_SignatureInitializer; - -}} - diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zHeader.h b/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zHeader.h deleted file mode 100644 index 57f455b81..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zHeader.h +++ /dev/null @@ -1,97 +0,0 @@ -// 7z/7zHeader.h - -#ifndef __7Z_HEADER_H -#define __7Z_HEADER_H - -#include "../../../Common/Types.h" - -namespace NArchive { -namespace N7z { - -const int kSignatureSize = 6; -extern Byte kSignature[kSignatureSize]; - -// #define _7Z_VOL -// 7z-MultiVolume is not finished yet. -// It can work already, but I still do not like some -// things of that new multivolume format. -// So please keep it commented. - -#ifdef _7Z_VOL -extern Byte kFinishSignature[kSignatureSize]; -#endif - -struct CArchiveVersion -{ - Byte Major; - Byte Minor; -}; - -const Byte kMajorVersion = 0; - -struct CStartHeader -{ - UInt64 NextHeaderOffset; - UInt64 NextHeaderSize; - UInt32 NextHeaderCRC; -}; - -const UInt32 kStartHeaderSize = 20; - -#ifdef _7Z_VOL -struct CFinishHeader: public CStartHeader -{ - UInt64 ArchiveStartOffset; // data offset from end if that struct - UInt64 AdditionalStartBlockSize; // start signature & start header size -}; - -const UInt32 kFinishHeaderSize = kStartHeaderSize + 16; -#endif - -namespace NID -{ - enum EEnum - { - kEnd, - - kHeader, - - kArchiveProperties, - - kAdditionalStreamsInfo, - kMainStreamsInfo, - kFilesInfo, - - kPackInfo, - kUnpackInfo, - kSubStreamsInfo, - - kSize, - kCRC, - - kFolder, - - kCodersUnpackSize, - kNumUnpackStream, - - kEmptyStream, - kEmptyFile, - kAnti, - - kName, - kCTime, - kATime, - kMTime, - kWinAttributes, - kComment, - - kEncodedHeader, - - kStartPos, - kDummy - }; -} - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zIn.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zIn.cpp deleted file mode 100644 index a9fecf8e1..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zIn.cpp +++ /dev/null @@ -1,1260 +0,0 @@ -// 7zIn.cpp - -#include "StdAfx.h" - -extern "C" -{ - #include "../../../../C/7zCrc.h" - #include "../../../../C/CpuArch.h" -} - -#include "../../Common/StreamObjects.h" -#include "../../Common/StreamUtils.h" - -#include "7zDecode.h" -#include "7zIn.h" - -#define Get16(p) GetUi16(p) -#define Get32(p) GetUi32(p) -#define Get64(p) GetUi64(p) - -// define FORMAT_7Z_RECOVERY if you want to recover multivolume archives with empty StartHeader -#ifndef _SFX -#define FORMAT_7Z_RECOVERY -#endif - -namespace NArchive { -namespace N7z { - -static void BoolVector_Fill_False(CBoolVector &v, int size) -{ - v.Clear(); - v.Reserve(size); - for (int i = 0; i < size; i++) - v.Add(false); -} - -static bool BoolVector_GetAndSet(CBoolVector &v, UInt32 index) -{ - if (index >= (UInt32)v.Size()) - return true; - bool res = v[index]; - v[index] = true; - return res; -} - -bool CFolder::CheckStructure() const -{ - const int kNumCodersMax = sizeof(UInt32) * 8; // don't change it - const int kMaskSize = sizeof(UInt32) * 8; // it must be >= kNumCodersMax - const int kNumBindsMax = 32; - - if (Coders.Size() > kNumCodersMax || BindPairs.Size() > kNumBindsMax) - return false; - - { - CBoolVector v; - BoolVector_Fill_False(v, BindPairs.Size() + PackStreams.Size()); - - int i; - for (i = 0; i < BindPairs.Size(); i++) - if (BoolVector_GetAndSet(v, BindPairs[i].InIndex)) - return false; - for (i = 0; i < PackStreams.Size(); i++) - if (BoolVector_GetAndSet(v, PackStreams[i])) - return false; - - BoolVector_Fill_False(v, UnpackSizes.Size()); - for (i = 0; i < BindPairs.Size(); i++) - if (BoolVector_GetAndSet(v, BindPairs[i].OutIndex)) - return false; - } - - UInt32 mask[kMaskSize]; - int i; - for (i = 0; i < kMaskSize; i++) - mask[i] = 0; - - { - CIntVector inStreamToCoder, outStreamToCoder; - for (i = 0; i < Coders.Size(); i++) - { - CNum j; - const CCoderInfo &coder = Coders[i]; - for (j = 0; j < coder.NumInStreams; j++) - inStreamToCoder.Add(i); - for (j = 0; j < coder.NumOutStreams; j++) - outStreamToCoder.Add(i); - } - - for (i = 0; i < BindPairs.Size(); i++) - { - const CBindPair &bp = BindPairs[i]; - mask[inStreamToCoder[bp.InIndex]] |= (1 << outStreamToCoder[bp.OutIndex]); - } - } - - for (i = 0; i < kMaskSize; i++) - for (int j = 0; j < kMaskSize; j++) - if (((1 << j) & mask[i]) != 0) - mask[i] |= mask[j]; - - for (i = 0; i < kMaskSize; i++) - if (((1 << i) & mask[i]) != 0) - return false; - - return true; -} - -class CInArchiveException {}; - -static void ThrowException() { throw CInArchiveException(); } -static inline void ThrowEndOfData() { ThrowException(); } -static inline void ThrowUnsupported() { ThrowException(); } -static inline void ThrowIncorrect() { ThrowException(); } -static inline void ThrowUnsupportedVersion() { ThrowException(); } - -/* -class CInArchiveException -{ -public: - enum CCauseType - { - kUnsupportedVersion = 0, - kUnsupported, - kIncorrect, - kEndOfData, - } Cause; - CInArchiveException(CCauseType cause): Cause(cause) {}; -}; - -static void ThrowException(CInArchiveException::CCauseType c) { throw CInArchiveException(c); } -static void ThrowEndOfData() { ThrowException(CInArchiveException::kEndOfData); } -static void ThrowUnsupported() { ThrowException(CInArchiveException::kUnsupported); } -static void ThrowIncorrect() { ThrowException(CInArchiveException::kIncorrect); } -static void ThrowUnsupportedVersion() { ThrowException(CInArchiveException::kUnsupportedVersion); } -*/ - -class CStreamSwitch -{ - CInArchive *_archive; - bool _needRemove; -public: - CStreamSwitch(): _needRemove(false) {} - ~CStreamSwitch() { Remove(); } - void Remove(); - void Set(CInArchive *archive, const Byte *data, size_t size); - void Set(CInArchive *archive, const CByteBuffer &byteBuffer); - void Set(CInArchive *archive, const CObjectVector *dataVector); -}; - -void CStreamSwitch::Remove() -{ - if (_needRemove) - { - _archive->DeleteByteStream(); - _needRemove = false; - } -} - -void CStreamSwitch::Set(CInArchive *archive, const Byte *data, size_t size) -{ - Remove(); - _archive = archive; - _archive->AddByteStream(data, size); - _needRemove = true; -} - -void CStreamSwitch::Set(CInArchive *archive, const CByteBuffer &byteBuffer) -{ - Set(archive, byteBuffer, byteBuffer.GetCapacity()); -} - -void CStreamSwitch::Set(CInArchive *archive, const CObjectVector *dataVector) -{ - Remove(); - Byte external = archive->ReadByte(); - if (external != 0) - { - int dataIndex = (int)archive->ReadNum(); - if (dataIndex < 0 || dataIndex >= dataVector->Size()) - ThrowIncorrect(); - Set(archive, (*dataVector)[dataIndex]); - } -} - -Byte CInByte2::ReadByte() -{ - if (_pos >= _size) - ThrowEndOfData(); - return _buffer[_pos++]; -} - -void CInByte2::ReadBytes(Byte *data, size_t size) -{ - if (size > _size - _pos) - ThrowEndOfData(); - for (size_t i = 0; i < size; i++) - data[i] = _buffer[_pos++]; -} - -void CInByte2::SkeepData(UInt64 size) -{ - if (size > _size - _pos) - ThrowEndOfData(); - _pos += (size_t)size; -} - -void CInByte2::SkeepData() -{ - SkeepData(ReadNumber()); -} - -UInt64 CInByte2::ReadNumber() -{ - if (_pos >= _size) - ThrowEndOfData(); - Byte firstByte = _buffer[_pos++]; - Byte mask = 0x80; - UInt64 value = 0; - for (int i = 0; i < 8; i++) - { - if ((firstByte & mask) == 0) - { - UInt64 highPart = firstByte & (mask - 1); - value += (highPart << (i * 8)); - return value; - } - if (_pos >= _size) - ThrowEndOfData(); - value |= ((UInt64)_buffer[_pos++] << (8 * i)); - mask >>= 1; - } - return value; -} - -CNum CInByte2::ReadNum() -{ - UInt64 value = ReadNumber(); - if (value > kNumMax) - ThrowUnsupported(); - return (CNum)value; -} - -UInt32 CInByte2::ReadUInt32() -{ - if (_pos + 4 > _size) - ThrowEndOfData(); - UInt32 res = Get32(_buffer + _pos); - _pos += 4; - return res; -} - -UInt64 CInByte2::ReadUInt64() -{ - if (_pos + 8 > _size) - ThrowEndOfData(); - UInt64 res = Get64(_buffer + _pos); - _pos += 8; - return res; -} - -void CInByte2::ReadString(UString &s) -{ - const Byte *buf = _buffer + _pos; - size_t rem = (_size - _pos) / 2 * 2; - { - size_t i; - for (i = 0; i < rem; i += 2) - if (buf[i] == 0 && buf[i + 1] == 0) - break; - if (i == rem) - ThrowEndOfData(); - rem = i; - } - int len = (int)(rem / 2); - if (len < 0 || (size_t)len * 2 != rem) - ThrowUnsupported(); - wchar_t *p = s.GetBuffer(len); - int i; - for (i = 0; i < len; i++, buf += 2) - p[i] = (wchar_t)Get16(buf); - s.ReleaseBuffer(len); - _pos += rem + 2; -} - -static inline bool TestSignatureCandidate(const Byte *p) -{ - for (int i = 0; i < kSignatureSize; i++) - if (p[i] != kSignature[i]) - return false; - return (p[0x1A] == 0 && p[0x1B] == 0); -} - -HRESULT CInArchive::FindAndReadSignature(IInStream *stream, const UInt64 *searchHeaderSizeLimit) -{ - RINOK(ReadStream_FALSE(stream, _header, kHeaderSize)); - - if (TestSignatureCandidate(_header)) - return S_OK; - - CByteBuffer byteBuffer; - const UInt32 kBufferSize = (1 << 16); - byteBuffer.SetCapacity(kBufferSize); - Byte *buffer = byteBuffer; - UInt32 numPrevBytes = kHeaderSize - 1; - memcpy(buffer, _header + 1, numPrevBytes); - UInt64 curTestPos = _arhiveBeginStreamPosition + 1; - for (;;) - { - if (searchHeaderSizeLimit != NULL) - if (curTestPos - _arhiveBeginStreamPosition > *searchHeaderSizeLimit) - break; - do - { - UInt32 numReadBytes = kBufferSize - numPrevBytes; - UInt32 processedSize; - RINOK(stream->Read(buffer + numPrevBytes, numReadBytes, &processedSize)); - numPrevBytes += processedSize; - if (processedSize == 0) - return S_FALSE; - } - while (numPrevBytes < kHeaderSize); - UInt32 numTests = numPrevBytes - kHeaderSize + 1; - for (UInt32 pos = 0; pos < numTests; pos++) - { - for (; buffer[pos] != '7' && pos < numTests; pos++); - if (pos == numTests) - break; - if (TestSignatureCandidate(buffer + pos)) - { - memcpy(_header, buffer + pos, kHeaderSize); - curTestPos += pos; - _arhiveBeginStreamPosition = curTestPos; - return stream->Seek(curTestPos + kHeaderSize, STREAM_SEEK_SET, NULL); - } - } - curTestPos += numTests; - numPrevBytes -= numTests; - memmove(buffer, buffer + numTests, numPrevBytes); - } - return S_FALSE; -} - -// S_FALSE means that file is not archive -HRESULT CInArchive::Open(IInStream *stream, const UInt64 *searchHeaderSizeLimit) -{ - HeadersSize = 0; - Close(); - RINOK(stream->Seek(0, STREAM_SEEK_CUR, &_arhiveBeginStreamPosition)) - RINOK(FindAndReadSignature(stream, searchHeaderSizeLimit)); - _stream = stream; - return S_OK; -} - -void CInArchive::Close() -{ - _stream.Release(); -} - -void CInArchive::ReadArchiveProperties(CInArchiveInfo & /* archiveInfo */) -{ - for (;;) - { - if (ReadID() == NID::kEnd) - break; - SkeepData(); - } -} - -void CInArchive::GetNextFolderItem(CFolder &folder) -{ - CNum numCoders = ReadNum(); - - folder.Coders.Clear(); - folder.Coders.Reserve((int)numCoders); - CNum numInStreams = 0; - CNum numOutStreams = 0; - CNum i; - for (i = 0; i < numCoders; i++) - { - folder.Coders.Add(CCoderInfo()); - CCoderInfo &coder = folder.Coders.Back(); - - { - Byte mainByte = ReadByte(); - int idSize = (mainByte & 0xF); - Byte longID[15]; - ReadBytes(longID, idSize); - if (idSize > 8) - ThrowUnsupported(); - UInt64 id = 0; - for (int j = 0; j < idSize; j++) - id |= (UInt64)longID[idSize - 1 - j] << (8 * j); - coder.MethodID = id; - - if ((mainByte & 0x10) != 0) - { - coder.NumInStreams = ReadNum(); - coder.NumOutStreams = ReadNum(); - } - else - { - coder.NumInStreams = 1; - coder.NumOutStreams = 1; - } - if ((mainByte & 0x20) != 0) - { - CNum propsSize = ReadNum(); - coder.Props.SetCapacity((size_t)propsSize); - ReadBytes((Byte *)coder.Props, (size_t)propsSize); - } - if ((mainByte & 0x80) != 0) - ThrowUnsupported(); - } - numInStreams += coder.NumInStreams; - numOutStreams += coder.NumOutStreams; - } - - CNum numBindPairs = numOutStreams - 1; - folder.BindPairs.Clear(); - folder.BindPairs.Reserve(numBindPairs); - for (i = 0; i < numBindPairs; i++) - { - CBindPair bp; - bp.InIndex = ReadNum(); - bp.OutIndex = ReadNum(); - folder.BindPairs.Add(bp); - } - - if (numInStreams < numBindPairs) - ThrowUnsupported(); - CNum numPackStreams = numInStreams - numBindPairs; - folder.PackStreams.Reserve(numPackStreams); - if (numPackStreams == 1) - { - for (i = 0; i < numInStreams; i++) - if (folder.FindBindPairForInStream(i) < 0) - { - folder.PackStreams.Add(i); - break; - } - if (folder.PackStreams.Size() != 1) - ThrowUnsupported(); - } - else - for (i = 0; i < numPackStreams; i++) - folder.PackStreams.Add(ReadNum()); -} - -void CInArchive::WaitAttribute(UInt64 attribute) -{ - for (;;) - { - UInt64 type = ReadID(); - if (type == attribute) - return; - if (type == NID::kEnd) - ThrowIncorrect(); - SkeepData(); - } -} - -void CInArchive::ReadHashDigests(int numItems, - CBoolVector &digestsDefined, - CRecordVector &digests) -{ - ReadBoolVector2(numItems, digestsDefined); - digests.Clear(); - digests.Reserve(numItems); - for (int i = 0; i < numItems; i++) - { - UInt32 crc = 0; - if (digestsDefined[i]) - crc = ReadUInt32(); - digests.Add(crc); - } -} - -void CInArchive::ReadPackInfo( - UInt64 &dataOffset, - CRecordVector &packSizes, - CBoolVector &packCRCsDefined, - CRecordVector &packCRCs) -{ - dataOffset = ReadNumber(); - CNum numPackStreams = ReadNum(); - - WaitAttribute(NID::kSize); - packSizes.Clear(); - packSizes.Reserve(numPackStreams); - for (CNum i = 0; i < numPackStreams; i++) - packSizes.Add(ReadNumber()); - - UInt64 type; - for (;;) - { - type = ReadID(); - if (type == NID::kEnd) - break; - if (type == NID::kCRC) - { - ReadHashDigests(numPackStreams, packCRCsDefined, packCRCs); - continue; - } - SkeepData(); - } - if (packCRCsDefined.IsEmpty()) - { - BoolVector_Fill_False(packCRCsDefined, numPackStreams); - packCRCs.Reserve(numPackStreams); - packCRCs.Clear(); - for (CNum i = 0; i < numPackStreams; i++) - packCRCs.Add(0); - } -} - -void CInArchive::ReadUnpackInfo( - const CObjectVector *dataVector, - CObjectVector &folders) -{ - WaitAttribute(NID::kFolder); - CNum numFolders = ReadNum(); - - { - CStreamSwitch streamSwitch; - streamSwitch.Set(this, dataVector); - folders.Clear(); - folders.Reserve(numFolders); - for (CNum i = 0; i < numFolders; i++) - { - folders.Add(CFolder()); - GetNextFolderItem(folders.Back()); - } - } - - WaitAttribute(NID::kCodersUnpackSize); - - CNum i; - for (i = 0; i < numFolders; i++) - { - CFolder &folder = folders[i]; - CNum numOutStreams = folder.GetNumOutStreams(); - folder.UnpackSizes.Reserve(numOutStreams); - for (CNum j = 0; j < numOutStreams; j++) - folder.UnpackSizes.Add(ReadNumber()); - } - - for (;;) - { - UInt64 type = ReadID(); - if (type == NID::kEnd) - return; - if (type == NID::kCRC) - { - CBoolVector crcsDefined; - CRecordVector crcs; - ReadHashDigests(numFolders, crcsDefined, crcs); - for (i = 0; i < numFolders; i++) - { - CFolder &folder = folders[i]; - folder.UnpackCRCDefined = crcsDefined[i]; - folder.UnpackCRC = crcs[i]; - } - continue; - } - SkeepData(); - } -} - -void CInArchive::ReadSubStreamsInfo( - const CObjectVector &folders, - CRecordVector &numUnpackStreamsInFolders, - CRecordVector &unpackSizes, - CBoolVector &digestsDefined, - CRecordVector &digests) -{ - numUnpackStreamsInFolders.Clear(); - numUnpackStreamsInFolders.Reserve(folders.Size()); - UInt64 type; - for (;;) - { - type = ReadID(); - if (type == NID::kNumUnpackStream) - { - for (int i = 0; i < folders.Size(); i++) - numUnpackStreamsInFolders.Add(ReadNum()); - continue; - } - if (type == NID::kCRC || type == NID::kSize) - break; - if (type == NID::kEnd) - break; - SkeepData(); - } - - if (numUnpackStreamsInFolders.IsEmpty()) - for (int i = 0; i < folders.Size(); i++) - numUnpackStreamsInFolders.Add(1); - - int i; - for (i = 0; i < numUnpackStreamsInFolders.Size(); i++) - { - // v3.13 incorrectly worked with empty folders - // v4.07: we check that folder is empty - CNum numSubstreams = numUnpackStreamsInFolders[i]; - if (numSubstreams == 0) - continue; - UInt64 sum = 0; - for (CNum j = 1; j < numSubstreams; j++) - if (type == NID::kSize) - { - UInt64 size = ReadNumber(); - unpackSizes.Add(size); - sum += size; - } - unpackSizes.Add(folders[i].GetUnpackSize() - sum); - } - if (type == NID::kSize) - type = ReadID(); - - int numDigests = 0; - int numDigestsTotal = 0; - for (i = 0; i < folders.Size(); i++) - { - CNum numSubstreams = numUnpackStreamsInFolders[i]; - if (numSubstreams != 1 || !folders[i].UnpackCRCDefined) - numDigests += numSubstreams; - numDigestsTotal += numSubstreams; - } - - for (;;) - { - if (type == NID::kCRC) - { - CBoolVector digestsDefined2; - CRecordVector digests2; - ReadHashDigests(numDigests, digestsDefined2, digests2); - int digestIndex = 0; - for (i = 0; i < folders.Size(); i++) - { - CNum numSubstreams = numUnpackStreamsInFolders[i]; - const CFolder &folder = folders[i]; - if (numSubstreams == 1 && folder.UnpackCRCDefined) - { - digestsDefined.Add(true); - digests.Add(folder.UnpackCRC); - } - else - for (CNum j = 0; j < numSubstreams; j++, digestIndex++) - { - digestsDefined.Add(digestsDefined2[digestIndex]); - digests.Add(digests2[digestIndex]); - } - } - } - else if (type == NID::kEnd) - { - if (digestsDefined.IsEmpty()) - { - BoolVector_Fill_False(digestsDefined, numDigestsTotal); - digests.Clear(); - for (int i = 0; i < numDigestsTotal; i++) - digests.Add(0); - } - return; - } - else - SkeepData(); - type = ReadID(); - } -} - -void CInArchive::ReadStreamsInfo( - const CObjectVector *dataVector, - UInt64 &dataOffset, - CRecordVector &packSizes, - CBoolVector &packCRCsDefined, - CRecordVector &packCRCs, - CObjectVector &folders, - CRecordVector &numUnpackStreamsInFolders, - CRecordVector &unpackSizes, - CBoolVector &digestsDefined, - CRecordVector &digests) -{ - for (;;) - { - UInt64 type = ReadID(); - if (type > ((UInt32)1 << 30)) - ThrowIncorrect(); - switch((UInt32)type) - { - case NID::kEnd: - return; - case NID::kPackInfo: - { - ReadPackInfo(dataOffset, packSizes, packCRCsDefined, packCRCs); - break; - } - case NID::kUnpackInfo: - { - ReadUnpackInfo(dataVector, folders); - break; - } - case NID::kSubStreamsInfo: - { - ReadSubStreamsInfo(folders, numUnpackStreamsInFolders, - unpackSizes, digestsDefined, digests); - break; - } - default: - ThrowIncorrect(); - } - } -} - -void CInArchive::ReadBoolVector(int numItems, CBoolVector &v) -{ - v.Clear(); - v.Reserve(numItems); - Byte b = 0; - Byte mask = 0; - for (int i = 0; i < numItems; i++) - { - if (mask == 0) - { - b = ReadByte(); - mask = 0x80; - } - v.Add((b & mask) != 0); - mask >>= 1; - } -} - -void CInArchive::ReadBoolVector2(int numItems, CBoolVector &v) -{ - Byte allAreDefined = ReadByte(); - if (allAreDefined == 0) - { - ReadBoolVector(numItems, v); - return; - } - v.Clear(); - v.Reserve(numItems); - for (int i = 0; i < numItems; i++) - v.Add(true); -} - -void CInArchive::ReadUInt64DefVector(const CObjectVector &dataVector, - CUInt64DefVector &v, int numFiles) -{ - ReadBoolVector2(numFiles, v.Defined); - - CStreamSwitch streamSwitch; - streamSwitch.Set(this, &dataVector); - v.Values.Reserve(numFiles); - - for (int i = 0; i < numFiles; i++) - { - UInt64 t = 0; - if (v.Defined[i]) - t = ReadUInt64(); - v.Values.Add(t); - } -} - -HRESULT CInArchive::ReadAndDecodePackedStreams( - DECL_EXTERNAL_CODECS_LOC_VARS - UInt64 baseOffset, - UInt64 &dataOffset, CObjectVector &dataVector - #ifndef _NO_CRYPTO - , ICryptoGetTextPassword *getTextPassword, bool &passwordIsDefined - #endif - ) -{ - CRecordVector packSizes; - CBoolVector packCRCsDefined; - CRecordVector packCRCs; - CObjectVector folders; - - CRecordVector numUnpackStreamsInFolders; - CRecordVector unpackSizes; - CBoolVector digestsDefined; - CRecordVector digests; - - ReadStreamsInfo(NULL, - dataOffset, - packSizes, - packCRCsDefined, - packCRCs, - folders, - numUnpackStreamsInFolders, - unpackSizes, - digestsDefined, - digests); - - // db.ArchiveInfo.DataStartPosition2 += db.ArchiveInfo.StartPositionAfterHeader; - - CNum packIndex = 0; - CDecoder decoder( - #ifdef _ST_MODE - false - #else - true - #endif - ); - UInt64 dataStartPos = baseOffset + dataOffset; - for (int i = 0; i < folders.Size(); i++) - { - const CFolder &folder = folders[i]; - dataVector.Add(CByteBuffer()); - CByteBuffer &data = dataVector.Back(); - UInt64 unpackSize64 = folder.GetUnpackSize(); - size_t unpackSize = (size_t)unpackSize64; - if (unpackSize != unpackSize64) - ThrowUnsupported(); - data.SetCapacity(unpackSize); - - CSequentialOutStreamImp2 *outStreamSpec = new CSequentialOutStreamImp2; - CMyComPtr outStream = outStreamSpec; - outStreamSpec->Init(data, unpackSize); - - HRESULT result = decoder.Decode( - EXTERNAL_CODECS_LOC_VARS - _stream, dataStartPos, - &packSizes[packIndex], folder, outStream, NULL - #ifndef _NO_CRYPTO - , getTextPassword, passwordIsDefined - #endif - #ifdef COMPRESS_MT - , false, 1 - #endif - ); - RINOK(result); - - if (folder.UnpackCRCDefined) - if (CrcCalc(data, unpackSize) != folder.UnpackCRC) - ThrowIncorrect(); - for (int j = 0; j < folder.PackStreams.Size(); j++) - { - UInt64 packSize = packSizes[packIndex++]; - dataStartPos += packSize; - HeadersSize += packSize; - } - } - return S_OK; -} - -HRESULT CInArchive::ReadHeader( - DECL_EXTERNAL_CODECS_LOC_VARS - CArchiveDatabaseEx &db - #ifndef _NO_CRYPTO - , ICryptoGetTextPassword *getTextPassword, bool &passwordIsDefined - #endif - ) -{ - UInt64 type = ReadID(); - - if (type == NID::kArchiveProperties) - { - ReadArchiveProperties(db.ArchiveInfo); - type = ReadID(); - } - - CObjectVector dataVector; - - if (type == NID::kAdditionalStreamsInfo) - { - HRESULT result = ReadAndDecodePackedStreams( - EXTERNAL_CODECS_LOC_VARS - db.ArchiveInfo.StartPositionAfterHeader, - db.ArchiveInfo.DataStartPosition2, - dataVector - #ifndef _NO_CRYPTO - , getTextPassword, passwordIsDefined - #endif - ); - RINOK(result); - db.ArchiveInfo.DataStartPosition2 += db.ArchiveInfo.StartPositionAfterHeader; - type = ReadID(); - } - - CRecordVector unpackSizes; - CBoolVector digestsDefined; - CRecordVector digests; - - if (type == NID::kMainStreamsInfo) - { - ReadStreamsInfo(&dataVector, - db.ArchiveInfo.DataStartPosition, - db.PackSizes, - db.PackCRCsDefined, - db.PackCRCs, - db.Folders, - db.NumUnpackStreamsVector, - unpackSizes, - digestsDefined, - digests); - db.ArchiveInfo.DataStartPosition += db.ArchiveInfo.StartPositionAfterHeader; - type = ReadID(); - } - else - { - for (int i = 0; i < db.Folders.Size(); i++) - { - db.NumUnpackStreamsVector.Add(1); - CFolder &folder = db.Folders[i]; - unpackSizes.Add(folder.GetUnpackSize()); - digestsDefined.Add(folder.UnpackCRCDefined); - digests.Add(folder.UnpackCRC); - } - } - - db.Files.Clear(); - - if (type == NID::kEnd) - return S_OK; - if (type != NID::kFilesInfo) - ThrowIncorrect(); - - CNum numFiles = ReadNum(); - db.Files.Reserve(numFiles); - CNum i; - for (i = 0; i < numFiles; i++) - db.Files.Add(CFileItem()); - - db.ArchiveInfo.FileInfoPopIDs.Add(NID::kSize); - if (!db.PackSizes.IsEmpty()) - db.ArchiveInfo.FileInfoPopIDs.Add(NID::kPackInfo); - if (numFiles > 0 && !digests.IsEmpty()) - db.ArchiveInfo.FileInfoPopIDs.Add(NID::kCRC); - - CBoolVector emptyStreamVector; - BoolVector_Fill_False(emptyStreamVector, (int)numFiles); - CBoolVector emptyFileVector; - CBoolVector antiFileVector; - CNum numEmptyStreams = 0; - - for (;;) - { - UInt64 type = ReadID(); - if (type == NID::kEnd) - break; - UInt64 size = ReadNumber(); - size_t ppp = _inByteBack->_pos; - bool addPropIdToList = true; - bool isKnownType = true; - if (type > ((UInt32)1 << 30)) - isKnownType = false; - else switch((UInt32)type) - { - case NID::kName: - { - CStreamSwitch streamSwitch; - streamSwitch.Set(this, &dataVector); - for (int i = 0; i < db.Files.Size(); i++) - _inByteBack->ReadString(db.Files[i].Name); - break; - } - case NID::kWinAttributes: - { - CBoolVector boolVector; - ReadBoolVector2(db.Files.Size(), boolVector); - CStreamSwitch streamSwitch; - streamSwitch.Set(this, &dataVector); - for (i = 0; i < numFiles; i++) - { - CFileItem &file = db.Files[i]; - file.AttribDefined = boolVector[i]; - if (file.AttribDefined) - file.Attrib = ReadUInt32(); - } - break; - } - case NID::kEmptyStream: - { - ReadBoolVector(numFiles, emptyStreamVector); - for (i = 0; i < (CNum)emptyStreamVector.Size(); i++) - if (emptyStreamVector[i]) - numEmptyStreams++; - - BoolVector_Fill_False(emptyFileVector, numEmptyStreams); - BoolVector_Fill_False(antiFileVector, numEmptyStreams); - - break; - } - case NID::kEmptyFile: ReadBoolVector(numEmptyStreams, emptyFileVector); break; - case NID::kAnti: ReadBoolVector(numEmptyStreams, antiFileVector); break; - case NID::kStartPos: ReadUInt64DefVector(dataVector, db.StartPos, (int)numFiles); break; - case NID::kCTime: ReadUInt64DefVector(dataVector, db.CTime, (int)numFiles); break; - case NID::kATime: ReadUInt64DefVector(dataVector, db.ATime, (int)numFiles); break; - case NID::kMTime: ReadUInt64DefVector(dataVector, db.MTime, (int)numFiles); break; - case NID::kDummy: - { - for (UInt64 j = 0; j < size; j++) - if (ReadByte() != 0) - ThrowIncorrect(); - addPropIdToList = false; - break; - } - default: - addPropIdToList = isKnownType = false; - } - if (isKnownType) - { - if(addPropIdToList) - db.ArchiveInfo.FileInfoPopIDs.Add(type); - } - else - SkeepData(size); - bool checkRecordsSize = (db.ArchiveInfo.Version.Major > 0 || - db.ArchiveInfo.Version.Minor > 2); - if (checkRecordsSize && _inByteBack->_pos - ppp != size) - ThrowIncorrect(); - } - - CNum emptyFileIndex = 0; - CNum sizeIndex = 0; - - CNum numAntiItems = 0; - for (i = 0; i < numEmptyStreams; i++) - if (antiFileVector[i]) - numAntiItems++; - - for (i = 0; i < numFiles; i++) - { - CFileItem &file = db.Files[i]; - bool isAnti; - file.HasStream = !emptyStreamVector[i]; - if (file.HasStream) - { - file.IsDir = false; - isAnti = false; - file.Size = unpackSizes[sizeIndex]; - file.Crc = digests[sizeIndex]; - file.CrcDefined = digestsDefined[sizeIndex]; - sizeIndex++; - } - else - { - file.IsDir = !emptyFileVector[emptyFileIndex]; - isAnti = antiFileVector[emptyFileIndex]; - emptyFileIndex++; - file.Size = 0; - file.CrcDefined = false; - } - if (numAntiItems != 0) - db.IsAnti.Add(isAnti); - } - return S_OK; -} - - -void CArchiveDatabaseEx::FillFolderStartPackStream() -{ - FolderStartPackStreamIndex.Clear(); - FolderStartPackStreamIndex.Reserve(Folders.Size()); - CNum startPos = 0; - for (int i = 0; i < Folders.Size(); i++) - { - FolderStartPackStreamIndex.Add(startPos); - startPos += (CNum)Folders[i].PackStreams.Size(); - } -} - -void CArchiveDatabaseEx::FillStartPos() -{ - PackStreamStartPositions.Clear(); - PackStreamStartPositions.Reserve(PackSizes.Size()); - UInt64 startPos = 0; - for (int i = 0; i < PackSizes.Size(); i++) - { - PackStreamStartPositions.Add(startPos); - startPos += PackSizes[i]; - } -} - -void CArchiveDatabaseEx::FillFolderStartFileIndex() -{ - FolderStartFileIndex.Clear(); - FolderStartFileIndex.Reserve(Folders.Size()); - FileIndexToFolderIndexMap.Clear(); - FileIndexToFolderIndexMap.Reserve(Files.Size()); - - int folderIndex = 0; - CNum indexInFolder = 0; - for (int i = 0; i < Files.Size(); i++) - { - const CFileItem &file = Files[i]; - bool emptyStream = !file.HasStream; - if (emptyStream && indexInFolder == 0) - { - FileIndexToFolderIndexMap.Add(kNumNoIndex); - continue; - } - if (indexInFolder == 0) - { - // v3.13 incorrectly worked with empty folders - // v4.07: Loop for skipping empty folders - for (;;) - { - if (folderIndex >= Folders.Size()) - ThrowIncorrect(); - FolderStartFileIndex.Add(i); // check it - if (NumUnpackStreamsVector[folderIndex] != 0) - break; - folderIndex++; - } - } - FileIndexToFolderIndexMap.Add(folderIndex); - if (emptyStream) - continue; - indexInFolder++; - if (indexInFolder >= NumUnpackStreamsVector[folderIndex]) - { - folderIndex++; - indexInFolder = 0; - } - } -} - -HRESULT CInArchive::ReadDatabase2( - DECL_EXTERNAL_CODECS_LOC_VARS - CArchiveDatabaseEx &db - #ifndef _NO_CRYPTO - , ICryptoGetTextPassword *getTextPassword, bool &passwordIsDefined - #endif - ) -{ - db.Clear(); - db.ArchiveInfo.StartPosition = _arhiveBeginStreamPosition; - - db.ArchiveInfo.Version.Major = _header[6]; - db.ArchiveInfo.Version.Minor = _header[7]; - - if (db.ArchiveInfo.Version.Major != kMajorVersion) - ThrowUnsupportedVersion(); - - UInt32 crcFromArchive = Get32(_header + 8); - UInt64 nextHeaderOffset = Get64(_header + 0xC); - UInt64 nextHeaderSize = Get64(_header + 0x14); - UInt32 nextHeaderCRC = Get32(_header + 0x1C); - UInt32 crc = CrcCalc(_header + 0xC, 20); - - #ifdef FORMAT_7Z_RECOVERY - if (crcFromArchive == 0 && nextHeaderOffset == 0 && nextHeaderSize == 0 && nextHeaderCRC == 0) - { - UInt64 cur, cur2; - RINOK(_stream->Seek(0, STREAM_SEEK_CUR, &cur)); - const int kCheckSize = 500; - Byte buf[kCheckSize]; - RINOK(_stream->Seek(0, STREAM_SEEK_END, &cur2)); - int checkSize = kCheckSize; - if (cur2 - cur < kCheckSize) - checkSize = (int)(cur2 - cur); - RINOK(_stream->Seek(-checkSize, STREAM_SEEK_END, &cur2)); - - RINOK(ReadStream_FALSE(_stream, buf, (size_t)checkSize)); - - int i; - for (i = (int)checkSize - 2; i >= 0; i--) - if (buf[i] == 0x17 && buf[i + 1] == 0x6 || buf[i] == 0x01 && buf[i + 1] == 0x04) - break; - if (i < 0) - return S_FALSE; - nextHeaderSize = checkSize - i; - nextHeaderOffset = cur2 - cur + i; - nextHeaderCRC = CrcCalc(buf + i, (size_t)nextHeaderSize); - RINOK(_stream->Seek(cur, STREAM_SEEK_SET, NULL)); - } - #endif - - #ifdef FORMAT_7Z_RECOVERY - crcFromArchive = crc; - #endif - - db.ArchiveInfo.StartPositionAfterHeader = _arhiveBeginStreamPosition + kHeaderSize; - - if (crc != crcFromArchive) - ThrowIncorrect(); - - if (nextHeaderSize == 0) - return S_OK; - - if (nextHeaderSize > (UInt64)0xFFFFFFFF) - return S_FALSE; - - RINOK(_stream->Seek(nextHeaderOffset, STREAM_SEEK_CUR, NULL)); - - CByteBuffer buffer2; - buffer2.SetCapacity((size_t)nextHeaderSize); - - RINOK(ReadStream_FALSE(_stream, buffer2, (size_t)nextHeaderSize)); - HeadersSize += kHeaderSize + nextHeaderSize; - db.PhySize = kHeaderSize + nextHeaderOffset + nextHeaderSize; - - if (CrcCalc(buffer2, (UInt32)nextHeaderSize) != nextHeaderCRC) - ThrowIncorrect(); - - CStreamSwitch streamSwitch; - streamSwitch.Set(this, buffer2); - - CObjectVector dataVector; - - UInt64 type = ReadID(); - if (type != NID::kHeader) - { - if (type != NID::kEncodedHeader) - ThrowIncorrect(); - HRESULT result = ReadAndDecodePackedStreams( - EXTERNAL_CODECS_LOC_VARS - db.ArchiveInfo.StartPositionAfterHeader, - db.ArchiveInfo.DataStartPosition2, - dataVector - #ifndef _NO_CRYPTO - , getTextPassword, passwordIsDefined - #endif - ); - RINOK(result); - if (dataVector.Size() == 0) - return S_OK; - if (dataVector.Size() > 1) - ThrowIncorrect(); - streamSwitch.Remove(); - streamSwitch.Set(this, dataVector.Front()); - if (ReadID() != NID::kHeader) - ThrowIncorrect(); - } - - db.HeadersSize = HeadersSize; - - return ReadHeader( - EXTERNAL_CODECS_LOC_VARS - db - #ifndef _NO_CRYPTO - , getTextPassword, passwordIsDefined - #endif - ); -} - -HRESULT CInArchive::ReadDatabase( - DECL_EXTERNAL_CODECS_LOC_VARS - CArchiveDatabaseEx &db - #ifndef _NO_CRYPTO - , ICryptoGetTextPassword *getTextPassword, bool &passwordIsDefined - #endif - ) -{ - try - { - return ReadDatabase2( - EXTERNAL_CODECS_LOC_VARS db - #ifndef _NO_CRYPTO - , getTextPassword, passwordIsDefined - #endif - ); - } - catch(CInArchiveException &) { return S_FALSE; } -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zIn.h b/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zIn.h deleted file mode 100644 index bfec78564..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zIn.h +++ /dev/null @@ -1,245 +0,0 @@ -// 7zIn.h - -#ifndef __7Z_IN_H -#define __7Z_IN_H - -#include "../../../Common/MyCom.h" - -#include "../../IPassword.h" -#include "../../IStream.h" - -#include "../../Common/CreateCoder.h" -#include "../../Common/InBuffer.h" - -#include "7zItem.h" - -namespace NArchive { -namespace N7z { - -struct CInArchiveInfo -{ - CArchiveVersion Version; - UInt64 StartPosition; - UInt64 StartPositionAfterHeader; - UInt64 DataStartPosition; - UInt64 DataStartPosition2; - CRecordVector FileInfoPopIDs; - void Clear() - { - FileInfoPopIDs.Clear(); - } -}; - -struct CArchiveDatabaseEx: public CArchiveDatabase -{ - CInArchiveInfo ArchiveInfo; - CRecordVector PackStreamStartPositions; - CRecordVector FolderStartPackStreamIndex; - CRecordVector FolderStartFileIndex; - CRecordVector FileIndexToFolderIndexMap; - - UInt64 HeadersSize; - UInt64 PhySize; - - void Clear() - { - CArchiveDatabase::Clear(); - ArchiveInfo.Clear(); - PackStreamStartPositions.Clear(); - FolderStartPackStreamIndex.Clear(); - FolderStartFileIndex.Clear(); - FileIndexToFolderIndexMap.Clear(); - - HeadersSize = 0; - PhySize = 0; - } - - void FillFolderStartPackStream(); - void FillStartPos(); - void FillFolderStartFileIndex(); - - void Fill() - { - FillFolderStartPackStream(); - FillStartPos(); - FillFolderStartFileIndex(); - } - - UInt64 GetFolderStreamPos(int folderIndex, int indexInFolder) const - { - return ArchiveInfo.DataStartPosition + - PackStreamStartPositions[FolderStartPackStreamIndex[folderIndex] + indexInFolder]; - } - - UInt64 GetFolderFullPackSize(int folderIndex) const - { - CNum packStreamIndex = FolderStartPackStreamIndex[folderIndex]; - const CFolder &folder = Folders[folderIndex]; - UInt64 size = 0; - for (int i = 0; i < folder.PackStreams.Size(); i++) - size += PackSizes[packStreamIndex + i]; - return size; - } - - UInt64 GetFolderPackStreamSize(int folderIndex, int streamIndex) const - { - return PackSizes[FolderStartPackStreamIndex[folderIndex] + streamIndex]; - } - - UInt64 GetFilePackSize(CNum fileIndex) const - { - CNum folderIndex = FileIndexToFolderIndexMap[fileIndex]; - if (folderIndex != kNumNoIndex) - if (FolderStartFileIndex[folderIndex] == fileIndex) - return GetFolderFullPackSize(folderIndex); - return 0; - } -}; - -class CInByte2 -{ - const Byte *_buffer; - size_t _size; -public: - size_t _pos; - void Init(const Byte *buffer, size_t size) - { - _buffer = buffer; - _size = size; - _pos = 0; - } - Byte ReadByte(); - void ReadBytes(Byte *data, size_t size); - void SkeepData(UInt64 size); - void SkeepData(); - UInt64 ReadNumber(); - CNum ReadNum(); - UInt32 ReadUInt32(); - UInt64 ReadUInt64(); - void ReadString(UString &s); -}; - -class CStreamSwitch; - -const UInt32 kHeaderSize = 32; - -class CInArchive -{ - friend class CStreamSwitch; - - CMyComPtr _stream; - - CObjectVector _inByteVector; - CInByte2 *_inByteBack; - - UInt64 _arhiveBeginStreamPosition; - - Byte _header[kHeaderSize]; - - UInt64 HeadersSize; - - void AddByteStream(const Byte *buffer, size_t size) - { - _inByteVector.Add(CInByte2()); - _inByteBack = &_inByteVector.Back(); - _inByteBack->Init(buffer, size); - } - - void DeleteByteStream() - { - _inByteVector.DeleteBack(); - if (!_inByteVector.IsEmpty()) - _inByteBack = &_inByteVector.Back(); - } - -private: - HRESULT FindAndReadSignature(IInStream *stream, const UInt64 *searchHeaderSizeLimit); - - void ReadBytes(Byte *data, size_t size) { _inByteBack->ReadBytes(data, size); } - Byte ReadByte() { return _inByteBack->ReadByte(); } - UInt64 ReadNumber() { return _inByteBack->ReadNumber(); } - CNum ReadNum() { return _inByteBack->ReadNum(); } - UInt64 ReadID() { return _inByteBack->ReadNumber(); } - UInt32 ReadUInt32() { return _inByteBack->ReadUInt32(); } - UInt64 ReadUInt64() { return _inByteBack->ReadUInt64(); } - void SkeepData(UInt64 size) { _inByteBack->SkeepData(size); } - void SkeepData() { _inByteBack->SkeepData(); } - void WaitAttribute(UInt64 attribute); - - void ReadArchiveProperties(CInArchiveInfo &archiveInfo); - void GetNextFolderItem(CFolder &itemInfo); - void ReadHashDigests(int numItems, - CBoolVector &digestsDefined, CRecordVector &digests); - - void ReadPackInfo( - UInt64 &dataOffset, - CRecordVector &packSizes, - CBoolVector &packCRCsDefined, - CRecordVector &packCRCs); - - void ReadUnpackInfo( - const CObjectVector *dataVector, - CObjectVector &folders); - - void ReadSubStreamsInfo( - const CObjectVector &folders, - CRecordVector &numUnpackStreamsInFolders, - CRecordVector &unpackSizes, - CBoolVector &digestsDefined, - CRecordVector &digests); - - void ReadStreamsInfo( - const CObjectVector *dataVector, - UInt64 &dataOffset, - CRecordVector &packSizes, - CBoolVector &packCRCsDefined, - CRecordVector &packCRCs, - CObjectVector &folders, - CRecordVector &numUnpackStreamsInFolders, - CRecordVector &unpackSizes, - CBoolVector &digestsDefined, - CRecordVector &digests); - - - void ReadBoolVector(int numItems, CBoolVector &v); - void ReadBoolVector2(int numItems, CBoolVector &v); - void ReadUInt64DefVector(const CObjectVector &dataVector, - CUInt64DefVector &v, int numFiles); - HRESULT ReadAndDecodePackedStreams( - DECL_EXTERNAL_CODECS_LOC_VARS - UInt64 baseOffset, UInt64 &dataOffset, - CObjectVector &dataVector - #ifndef _NO_CRYPTO - , ICryptoGetTextPassword *getTextPassword, bool &passwordIsDefined - #endif - ); - HRESULT ReadHeader( - DECL_EXTERNAL_CODECS_LOC_VARS - CArchiveDatabaseEx &db - #ifndef _NO_CRYPTO - ,ICryptoGetTextPassword *getTextPassword, bool &passwordIsDefined - #endif - ); - HRESULT ReadDatabase2( - DECL_EXTERNAL_CODECS_LOC_VARS - CArchiveDatabaseEx &db - #ifndef _NO_CRYPTO - ,ICryptoGetTextPassword *getTextPassword, bool &passwordIsDefined - #endif - ); -public: - HRESULT Open(IInStream *stream, const UInt64 *searchHeaderSizeLimit); // S_FALSE means is not archive - void Close(); - - HRESULT ReadDatabase( - DECL_EXTERNAL_CODECS_LOC_VARS - CArchiveDatabaseEx &db - #ifndef _NO_CRYPTO - ,ICryptoGetTextPassword *getTextPassword, bool &passwordIsDefined - #endif - ); -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zItem.h b/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zItem.h deleted file mode 100644 index 6cc9ccc55..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zItem.h +++ /dev/null @@ -1,258 +0,0 @@ -// 7zItem.h - -#ifndef __7Z_ITEM_H -#define __7Z_ITEM_H - -#include "../../../Common/Buffer.h" -#include "../../../Common/MyString.h" - -#include "../../Common/MethodId.h" - -#include "7zHeader.h" - -namespace NArchive { -namespace N7z { - -typedef UInt32 CNum; -const CNum kNumMax = 0x7FFFFFFF; -const CNum kNumNoIndex = 0xFFFFFFFF; - -struct CCoderInfo -{ - CMethodId MethodID; - CByteBuffer Props; - CNum NumInStreams; - CNum NumOutStreams; - bool IsSimpleCoder() const { return (NumInStreams == 1) && (NumOutStreams == 1); } -}; - -struct CBindPair -{ - CNum InIndex; - CNum OutIndex; -}; - -struct CFolder -{ - CObjectVector Coders; - CRecordVector BindPairs; - CRecordVector PackStreams; - CRecordVector UnpackSizes; - UInt32 UnpackCRC; - bool UnpackCRCDefined; - - CFolder(): UnpackCRCDefined(false) {} - - UInt64 GetUnpackSize() const // test it - { - if (UnpackSizes.IsEmpty()) - return 0; - for (int i = UnpackSizes.Size() - 1; i >= 0; i--) - if (FindBindPairForOutStream(i) < 0) - return UnpackSizes[i]; - throw 1; - } - - CNum GetNumOutStreams() const - { - CNum result = 0; - for (int i = 0; i < Coders.Size(); i++) - result += Coders[i].NumOutStreams; - return result; - } - - int FindBindPairForInStream(CNum inStreamIndex) const - { - for(int i = 0; i < BindPairs.Size(); i++) - if (BindPairs[i].InIndex == inStreamIndex) - return i; - return -1; - } - int FindBindPairForOutStream(CNum outStreamIndex) const - { - for(int i = 0; i < BindPairs.Size(); i++) - if (BindPairs[i].OutIndex == outStreamIndex) - return i; - return -1; - } - int FindPackStreamArrayIndex(CNum inStreamIndex) const - { - for(int i = 0; i < PackStreams.Size(); i++) - if (PackStreams[i] == inStreamIndex) - return i; - return -1; - } - - bool CheckStructure() const; -}; - -struct CUInt64DefVector -{ - CRecordVector Values; - CRecordVector Defined; - - void Clear() - { - Values.Clear(); - Defined.Clear(); - } - - void ReserveDown() - { - Values.ReserveDown(); - Values.ReserveDown(); - } - - bool GetItem(int index, UInt64 &value) const - { - if (index < Defined.Size() && Defined[index]) - { - value = Values[index]; - return true; - } - value = 0; - return false; - } - - void SetItem(int index, bool defined, UInt64 value) - { - while (index >= Defined.Size()) - Defined.Add(false); - Defined[index] = defined; - if (!defined) - return; - while (index >= Values.Size()) - Values.Add(0); - Values[index] = value; - } - - bool CheckSize(int size) const { return Defined.Size() == size || Defined.Size() == 0; } -}; - -struct CFileItem -{ - UInt64 Size; - UInt32 Attrib; - UInt32 Crc; - UString Name; - - bool HasStream; // Test it !!! it means that there is - // stream in some folder. It can be empty stream - bool IsDir; - bool CrcDefined; - bool AttribDefined; - - CFileItem(): - HasStream(true), - IsDir(false), - CrcDefined(false), - AttribDefined(false) - {} - void SetAttrib(UInt32 attrib) - { - AttribDefined = true; - Attrib = attrib; - } -}; - -struct CFileItem2 -{ - UInt64 CTime; - UInt64 ATime; - UInt64 MTime; - UInt64 StartPos; - bool CTimeDefined; - bool ATimeDefined; - bool MTimeDefined; - bool StartPosDefined; - bool IsAnti; -}; - -struct CArchiveDatabase -{ - CRecordVector PackSizes; - CRecordVector PackCRCsDefined; - CRecordVector PackCRCs; - CObjectVector Folders; - CRecordVector NumUnpackStreamsVector; - CObjectVector Files; - - CUInt64DefVector CTime; - CUInt64DefVector ATime; - CUInt64DefVector MTime; - CUInt64DefVector StartPos; - CRecordVector IsAnti; - - void Clear() - { - PackSizes.Clear(); - PackCRCsDefined.Clear(); - PackCRCs.Clear(); - Folders.Clear(); - NumUnpackStreamsVector.Clear(); - Files.Clear(); - CTime.Clear(); - ATime.Clear(); - MTime.Clear(); - StartPos.Clear(); - IsAnti.Clear(); - } - - void ReserveDown() - { - PackSizes.ReserveDown(); - PackCRCsDefined.ReserveDown(); - PackCRCs.ReserveDown(); - Folders.ReserveDown(); - NumUnpackStreamsVector.ReserveDown(); - Files.ReserveDown(); - CTime.ReserveDown(); - ATime.ReserveDown(); - MTime.ReserveDown(); - StartPos.ReserveDown(); - IsAnti.ReserveDown(); - } - - bool IsEmpty() const - { - return (PackSizes.IsEmpty() && - PackCRCsDefined.IsEmpty() && - PackCRCs.IsEmpty() && - Folders.IsEmpty() && - NumUnpackStreamsVector.IsEmpty() && - Files.IsEmpty()); - } - - bool CheckNumFiles() const - { - int size = Files.Size(); - return ( - CTime.CheckSize(size) && - ATime.CheckSize(size) && - MTime.CheckSize(size) && - StartPos.CheckSize(size) && - (size == IsAnti.Size() || IsAnti.Size() == 0)); - } - - bool IsSolid() const - { - for (int i = 0; i < NumUnpackStreamsVector.Size(); i++) - if (NumUnpackStreamsVector[i] > 1) - return true; - return false; - } - bool IsItemAnti(int index) const { return (index < IsAnti.Size() && IsAnti[index]); } - void SetItemAnti(int index, bool isAnti) - { - while (index >= IsAnti.Size()) - IsAnti.Add(false); - IsAnti[index] = isAnti; - } - - void GetFile(int index, CFileItem &file, CFileItem2 &file2) const; - void AddFile(const CFileItem &file, const CFileItem2 &file2); -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zProperties.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zProperties.cpp deleted file mode 100644 index f5ac3b9bf..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zProperties.cpp +++ /dev/null @@ -1,163 +0,0 @@ -// 7zProperties.cpp - -#include "StdAfx.h" - -#include "7zProperties.h" -#include "7zHeader.h" -#include "7zHandler.h" - -// #define _MULTI_PACK - -namespace NArchive { -namespace N7z { - -struct CPropMap -{ - UInt64 FilePropID; - STATPROPSTG StatPROPSTG; -}; - -CPropMap kPropMap[] = -{ - { NID::kName, NULL, kpidPath, VT_BSTR}, - { NID::kSize, NULL, kpidSize, VT_UI8}, - { NID::kPackInfo, NULL, kpidPackSize, VT_UI8}, - - #ifdef _MULTI_PACK - { 100, L"Pack0", kpidPackedSize0, VT_UI8}, - { 101, L"Pack1", kpidPackedSize1, VT_UI8}, - { 102, L"Pack2", kpidPackedSize2, VT_UI8}, - { 103, L"Pack3", kpidPackedSize3, VT_UI8}, - { 104, L"Pack4", kpidPackedSize4, VT_UI8}, - #endif - - { NID::kCTime, NULL, kpidCTime, VT_FILETIME}, - { NID::kMTime, NULL, kpidMTime, VT_FILETIME}, - { NID::kATime, NULL, kpidATime, VT_FILETIME}, - { NID::kWinAttributes, NULL, kpidAttrib, VT_UI4}, - { NID::kStartPos, NULL, kpidPosition, VT_UI4}, - - { NID::kCRC, NULL, kpidCRC, VT_UI4}, - - { NID::kAnti, NULL, kpidIsAnti, VT_BOOL}, - - #ifndef _SFX - { 97, NULL, kpidEncrypted, VT_BOOL}, - { 98, NULL, kpidMethod, VT_BSTR}, - { 99, NULL, kpidBlock, VT_UI4} - #endif -}; - -static const int kPropMapSize = sizeof(kPropMap) / sizeof(kPropMap[0]); - -static int FindPropInMap(UInt64 filePropID) -{ - for (int i = 0; i < kPropMapSize; i++) - if (kPropMap[i].FilePropID == filePropID) - return i; - return -1; -} - -static void CopyOneItem(CRecordVector &src, - CRecordVector &dest, UInt32 item) -{ - for (int i = 0; i < src.Size(); i++) - if (src[i] == item) - { - dest.Add(item); - src.Delete(i); - return; - } -} - -static void RemoveOneItem(CRecordVector &src, UInt32 item) -{ - for (int i = 0; i < src.Size(); i++) - if (src[i] == item) - { - src.Delete(i); - return; - } -} - -static void InsertToHead(CRecordVector &dest, UInt32 item) -{ - for (int i = 0; i < dest.Size(); i++) - if (dest[i] == item) - { - dest.Delete(i); - break; - } - dest.Insert(0, item); -} - -void CHandler::FillPopIDs() -{ - _fileInfoPopIDs.Clear(); - - #ifdef _7Z_VOL - if(_volumes.Size() < 1) - return; - const CVolume &volume = _volumes.Front(); - const CArchiveDatabaseEx &_db = volume.Database; - #endif - - CRecordVector fileInfoPopIDs = _db.ArchiveInfo.FileInfoPopIDs; - - RemoveOneItem(fileInfoPopIDs, NID::kEmptyStream); - RemoveOneItem(fileInfoPopIDs, NID::kEmptyFile); - - CopyOneItem(fileInfoPopIDs, _fileInfoPopIDs, NID::kName); - CopyOneItem(fileInfoPopIDs, _fileInfoPopIDs, NID::kAnti); - CopyOneItem(fileInfoPopIDs, _fileInfoPopIDs, NID::kSize); - CopyOneItem(fileInfoPopIDs, _fileInfoPopIDs, NID::kPackInfo); - CopyOneItem(fileInfoPopIDs, _fileInfoPopIDs, NID::kCTime); - CopyOneItem(fileInfoPopIDs, _fileInfoPopIDs, NID::kMTime); - CopyOneItem(fileInfoPopIDs, _fileInfoPopIDs, NID::kATime); - CopyOneItem(fileInfoPopIDs, _fileInfoPopIDs, NID::kWinAttributes); - CopyOneItem(fileInfoPopIDs, _fileInfoPopIDs, NID::kCRC); - CopyOneItem(fileInfoPopIDs, _fileInfoPopIDs, NID::kComment); - _fileInfoPopIDs += fileInfoPopIDs; - - #ifndef _SFX - _fileInfoPopIDs.Add(97); - _fileInfoPopIDs.Add(98); - _fileInfoPopIDs.Add(99); - #endif - #ifdef _MULTI_PACK - _fileInfoPopIDs.Add(100); - _fileInfoPopIDs.Add(101); - _fileInfoPopIDs.Add(102); - _fileInfoPopIDs.Add(103); - _fileInfoPopIDs.Add(104); - #endif - - #ifndef _SFX - InsertToHead(_fileInfoPopIDs, NID::kMTime); - InsertToHead(_fileInfoPopIDs, NID::kPackInfo); - InsertToHead(_fileInfoPopIDs, NID::kSize); - InsertToHead(_fileInfoPopIDs, NID::kName); - #endif -} - -STDMETHODIMP CHandler::GetNumberOfProperties(UInt32 *numProperties) -{ - *numProperties = _fileInfoPopIDs.Size(); - return S_OK; -} - -STDMETHODIMP CHandler::GetPropertyInfo(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType) -{ - if ((int)index >= _fileInfoPopIDs.Size()) - return E_INVALIDARG; - int indexInMap = FindPropInMap(_fileInfoPopIDs[index]); - if (indexInMap == -1) - return E_INVALIDARG; - const STATPROPSTG &srcItem = kPropMap[indexInMap].StatPROPSTG; - *propID = srcItem.propid; - *varType = srcItem.vt; - *name = 0; - return S_OK; -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zProperties.h b/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zProperties.h deleted file mode 100644 index 7b78130ef..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zProperties.h +++ /dev/null @@ -1,22 +0,0 @@ -// 7zProperties.h - -#ifndef __7Z_PROPERTIES_H -#define __7Z_PROPERTIES_H - -#include "../../PropID.h" - -namespace NArchive { -namespace N7z { - -enum -{ - kpidPackedSize0 = kpidUserDefined, - kpidPackedSize1, - kpidPackedSize2, - kpidPackedSize3, - kpidPackedSize4 -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zRegister.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zRegister.cpp deleted file mode 100644 index 4450498f0..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zRegister.cpp +++ /dev/null @@ -1,18 +0,0 @@ -// 7zRegister.cpp - -#include "StdAfx.h" - -#include "../../Common/RegisterArc.h" - -#include "7zHandler.h" -static IInArchive *CreateArc() { return new NArchive::N7z::CHandler; } -#ifndef EXTRACT_ONLY -static IOutArchive *CreateArcOut() { return new NArchive::N7z::CHandler; } -#else -#define CreateArcOut 0 -#endif - -static CArcInfo g_ArcInfo = - { L"7z", L"7z", 0, 7, {'7', 'z', 0xBC, 0xAF, 0x27, 0x1C}, 6, false, CreateArc, CreateArcOut }; - -REGISTER_ARC(7z) diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zSpecStream.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zSpecStream.cpp deleted file mode 100644 index 58f2ec459..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zSpecStream.cpp +++ /dev/null @@ -1,24 +0,0 @@ -// 7zSpecStream.cpp - -#include "StdAfx.h" - -#include "7zSpecStream.h" - -STDMETHODIMP CSequentialInStreamSizeCount2::Read(void *data, UInt32 size, UInt32 *processedSize) -{ - UInt32 realProcessedSize; - HRESULT result = _stream->Read(data, size, &realProcessedSize); - _size += realProcessedSize; - if (processedSize != 0) - *processedSize = realProcessedSize; - return result; -} - -STDMETHODIMP CSequentialInStreamSizeCount2::GetSubStreamSize( - UInt64 subStream, UInt64 *value) -{ - if (_getSubStreamSize == NULL) - return E_NOTIMPL; - return _getSubStreamSize->GetSubStreamSize(subStream, value); -} - diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zSpecStream.h b/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zSpecStream.h deleted file mode 100644 index 0058ac27c..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zSpecStream.h +++ /dev/null @@ -1,35 +0,0 @@ -// 7zSpecStream.h - -#ifndef __7Z_SPEC_STREAM_H -#define __7Z_SPEC_STREAM_H - -#include "../../IStream.h" -#include "../../ICoder.h" -#include "../../../Common/MyCom.h" - -class CSequentialInStreamSizeCount2: - public ISequentialInStream, - public ICompressGetSubStreamSize, - public CMyUnknownImp -{ - CMyComPtr _stream; - CMyComPtr _getSubStreamSize; - UInt64 _size; -public: - void Init(ISequentialInStream *stream) - { - _stream = stream; - _getSubStreamSize = 0; - _stream.QueryInterface(IID_ICompressGetSubStreamSize, &_getSubStreamSize); - _size = 0; - } - UInt64 GetSize() const { return _size; } - - MY_UNKNOWN_IMP1(ICompressGetSubStreamSize) - - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); - - STDMETHOD(GetSubStreamSize)(UInt64 subStream, UInt64 *value); -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/7z/StdAfx.h b/desmume/src/windows/7z/CPP/7zip/Archive/7z/StdAfx.h deleted file mode 100644 index a4e617312..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/7z/StdAfx.h +++ /dev/null @@ -1,9 +0,0 @@ -// StdAfx.h - -#ifndef __STDAFX_H -#define __STDAFX_H - -#include "../../../Common/MyWindows.h" -#include "../../../Common/NewHandler.h" - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/ArchiveExports.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/ArchiveExports.cpp deleted file mode 100644 index 054f1b081..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/ArchiveExports.cpp +++ /dev/null @@ -1,130 +0,0 @@ -// ArchiveExports.cpp - -#include "StdAfx.h" - -#include "../../Common/ComTry.h" -#include "../../Common/Types.h" -#include "../../Windows/PropVariant.h" -#include "../Common/RegisterArc.h" - -#include "IArchive.h" -#include "../ICoder.h" -#include "../IPassword.h" - -static const unsigned int kNumArcsMax = 32; -static unsigned int g_NumArcs = 0; -static const CArcInfo *g_Arcs[kNumArcsMax]; -void RegisterArc(const CArcInfo *arcInfo) -{ - if (g_NumArcs < kNumArcsMax) - g_Arcs[g_NumArcs++] = arcInfo; -} - -DEFINE_GUID(CLSID_CArchiveHandler, -0x23170F69, 0x40C1, 0x278A, 0x10, 0x00, 0x00, 0x01, 0x10, 0x00, 0x00, 0x00); - -#define CLS_ARC_ID_ITEM(cls) ((cls).Data4[5]) - -static inline HRESULT SetPropString(const char *s, unsigned int size, PROPVARIANT *value) -{ - if ((value->bstrVal = ::SysAllocStringByteLen(s, size)) != 0) - value->vt = VT_BSTR; - return S_OK; -} - -static inline HRESULT SetPropGUID(const GUID &guid, PROPVARIANT *value) -{ - return SetPropString((const char *)&guid, sizeof(GUID), value); -} - -int FindFormatCalssId(const GUID *clsID) -{ - GUID cls = *clsID; - CLS_ARC_ID_ITEM(cls) = 0; - if (cls != CLSID_CArchiveHandler) - return -1; - Byte id = CLS_ARC_ID_ITEM(*clsID); - for (unsigned i = 0; i < g_NumArcs; i++) - if (g_Arcs[i]->ClassId == id) - return (int)i; - return -1; -} - -STDAPI CreateArchiver(const GUID *clsid, const GUID *iid, void **outObject) -{ - COM_TRY_BEGIN - { - int needIn = (*iid == IID_IInArchive); - int needOut = (*iid == IID_IOutArchive); - if (!needIn && !needOut) - return E_NOINTERFACE; - int formatIndex = FindFormatCalssId(clsid); - if (formatIndex < 0) - return CLASS_E_CLASSNOTAVAILABLE; - - const CArcInfo &arc = *g_Arcs[formatIndex]; - if (needIn) - { - *outObject = arc.CreateInArchive(); - ((IInArchive *)*outObject)->AddRef(); - } - else - { - if (!arc.CreateOutArchive) - return CLASS_E_CLASSNOTAVAILABLE; - *outObject = arc.CreateOutArchive(); - ((IOutArchive *)*outObject)->AddRef(); - } - } - COM_TRY_END - return S_OK; -} - -STDAPI GetHandlerProperty2(UInt32 formatIndex, PROPID propID, PROPVARIANT *value) -{ - if (formatIndex >= g_NumArcs) - return E_INVALIDARG; - const CArcInfo &arc = *g_Arcs[formatIndex]; - NWindows::NCOM::CPropVariant prop; - switch(propID) - { - case NArchive::kName: - prop = arc.Name; - break; - case NArchive::kClassID: - { - GUID clsId = CLSID_CArchiveHandler; - CLS_ARC_ID_ITEM(clsId) = arc.ClassId; - return SetPropGUID(clsId, value); - } - case NArchive::kExtension: - if (arc.Ext != 0) - prop = arc.Ext; - break; - case NArchive::kAddExtension: - if (arc.AddExt != 0) - prop = arc.AddExt; - break; - case NArchive::kUpdate: - prop = (bool)(arc.CreateOutArchive != 0); - break; - case NArchive::kKeepName: - prop = arc.KeepName; - break; - case NArchive::kStartSignature: - return SetPropString((const char *)arc.Signature, arc.SignatureSize, value); - } - prop.Detach(value); - return S_OK; -} - -STDAPI GetHandlerProperty(PROPID propID, PROPVARIANT *value) -{ - return GetHandlerProperty2(0, propID, value); -} - -STDAPI GetNumberOfFormats(UINT32 *numFormats) -{ - *numFormats = g_NumArcs; - return S_OK; -} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/BZip2/BZip2Handler.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/BZip2/BZip2Handler.cpp deleted file mode 100644 index a797b6ddd..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/BZip2/BZip2Handler.cpp +++ /dev/null @@ -1,216 +0,0 @@ -// BZip2Handler.cpp - -#include "StdAfx.h" - -#include "Common/ComTry.h" - -#include "Windows/PropVariant.h" - -#include "../../Common/CreateCoder.h" -#include "../../Common/ProgressUtils.h" -#include "../../Common/StreamUtils.h" - -#include "../Common/DummyOutStream.h" - -#include "BZip2Handler.h" - -using namespace NWindows; - -namespace NArchive { -namespace NBZip2 { - -static const CMethodId kMethodId_BZip2 = 0x040202; - -STATPROPSTG kProps[] = -{ - { NULL, kpidPackSize, VT_UI8} -}; - -IMP_IInArchive_Props -IMP_IInArchive_ArcProps_NO - -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) -{ - *numItems = 1; - return S_OK; -} - -STDMETHODIMP CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value) -{ - NWindows::NCOM::CPropVariant prop; - switch(propID) - { - case kpidPackSize: prop = _item.PackSize; break; - } - prop.Detach(value); - return S_OK; -} - -STDMETHODIMP CHandler::Open(IInStream *stream, - const UInt64 * /* maxCheckStartPosition */, - IArchiveOpenCallback * /* openArchiveCallback */) -{ - COM_TRY_BEGIN - try - { - RINOK(stream->Seek(0, STREAM_SEEK_CUR, &_streamStartPosition)); - const int kSignatureSize = 3; - Byte buffer[kSignatureSize]; - RINOK(ReadStream_FALSE(stream, buffer, kSignatureSize)); - if (buffer[0] != 'B' || buffer[1] != 'Z' || buffer[2] != 'h') - return S_FALSE; - - UInt64 endPosition; - RINOK(stream->Seek(0, STREAM_SEEK_END, &endPosition)); - _item.PackSize = endPosition - _streamStartPosition; - - _stream = stream; - } - catch(...) - { - return S_FALSE; - } - return S_OK; - COM_TRY_END -} - -STDMETHODIMP CHandler::Close() -{ - _stream.Release(); - return S_OK; -} - - -STDMETHODIMP CHandler::Extract(const UInt32* indices, UInt32 numItems, - Int32 testModeSpec, IArchiveExtractCallback *extractCallback) -{ - COM_TRY_BEGIN - bool allFilesMode = (numItems == UInt32(-1)); - if (!allFilesMode) - { - if (numItems == 0) - return S_OK; - if (numItems != 1) - return E_INVALIDARG; - if (indices[0] != 0) - return E_INVALIDARG; - } - - bool testMode = (testModeSpec != 0); - - extractCallback->SetTotal(_item.PackSize); - - UInt64 currentTotalPacked = 0; - - RINOK(extractCallback->SetCompleted(¤tTotalPacked)); - - CMyComPtr realOutStream; - Int32 askMode; - askMode = testMode ? NExtract::NAskMode::kTest : - NExtract::NAskMode::kExtract; - - RINOK(extractCallback->GetStream(0, &realOutStream, askMode)); - - if(!testMode && !realOutStream) - return S_OK; - - - extractCallback->PrepareOperation(askMode); - - CMyComPtr decoder; - HRESULT loadResult = CreateCoder( - EXTERNAL_CODECS_VARS - kMethodId_BZip2, decoder, false); - if (loadResult != S_OK || !decoder) - { - RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kUnSupportedMethod)); - return S_OK; - } - - #ifdef COMPRESS_MT - { - CMyComPtr setCoderMt; - decoder.QueryInterface(IID_ICompressSetCoderMt, &setCoderMt); - if (setCoderMt) - { - RINOK(setCoderMt->SetNumberOfThreads(_numThreads)); - } - } - #endif - - CDummyOutStream *outStreamSpec = new CDummyOutStream; - CMyComPtr outStream(outStreamSpec); - outStreamSpec->SetStream(realOutStream); - outStreamSpec->Init(); - - realOutStream.Release(); - - CLocalProgress *lps = new CLocalProgress; - CMyComPtr progress = lps; - lps->Init(extractCallback, true); - - RINOK(_stream->Seek(_streamStartPosition, STREAM_SEEK_SET, NULL)); - - HRESULT result = S_OK; - - bool firstItem = true; - for (;;) - { - lps->InSize = currentTotalPacked; - lps->OutSize = outStreamSpec->GetSize(); - - RINOK(lps->SetCur()); - - const int kSignatureSize = 3; - Byte buffer[kSignatureSize]; - size_t processedSize = kSignatureSize; - RINOK(ReadStream(_stream, buffer, &processedSize)); - if (processedSize != kSignatureSize) - { - if (firstItem) - return E_FAIL; - break; - } - if (buffer[0] != 'B' || buffer[1] != 'Z' || buffer[2] != 'h') - { - if (firstItem) - return E_FAIL; - break; - } - firstItem = false; - - UInt64 dataStartPos; - RINOK(_stream->Seek((UInt64)(Int64)(-3), STREAM_SEEK_CUR, &dataStartPos)); - - result = decoder->Code(_stream, outStream, NULL, NULL, progress); - - if (result != S_OK) - break; - - CMyComPtr getInStreamProcessedSize; - decoder.QueryInterface(IID_ICompressGetInStreamProcessedSize, &getInStreamProcessedSize); - if (!getInStreamProcessedSize) - break; - UInt64 packSize; - RINOK(getInStreamProcessedSize->GetInStreamProcessedSize(&packSize)); - UInt64 pos; - RINOK(_stream->Seek(dataStartPos + packSize, STREAM_SEEK_SET, &pos)); - currentTotalPacked = pos - _streamStartPosition; - } - outStream.Release(); - - Int32 retResult; - if (result == S_OK) - retResult = NExtract::NOperationResult::kOK; - else if (result == S_FALSE) - retResult = NExtract::NOperationResult::kDataError; - else - return result; - return extractCallback->SetOperationResult(retResult); - - COM_TRY_END -} - -IMPL_ISetCompressCodecsInfo - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/BZip2/BZip2Handler.h b/desmume/src/windows/7z/CPP/7zip/Archive/BZip2/BZip2Handler.h deleted file mode 100644 index 5d9fb1430..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/BZip2/BZip2Handler.h +++ /dev/null @@ -1,70 +0,0 @@ -// BZip2/Handler.h - -#ifndef __BZIP2_HANDLER_H -#define __BZIP2_HANDLER_H - -#include "Common/MyCom.h" -#include "../IArchive.h" -#include "../../Common/CreateCoder.h" -#include "BZip2Item.h" - -#ifdef COMPRESS_MT -#include "../../../Windows/System.h" -#endif - -namespace NArchive { -namespace NBZip2 { - -class CHandler: - public IInArchive, - public IOutArchive, - public ISetProperties, - PUBLIC_ISetCompressCodecsInfo - public CMyUnknownImp -{ - CMyComPtr _stream; - NArchive::NBZip2::CItem _item; - UInt64 _streamStartPosition; - - UInt32 _level; - UInt32 _dicSize; - UInt32 _numPasses; - #ifdef COMPRESS_MT - UInt32 _numThreads; - #endif - - DECL_EXTERNAL_CODECS_VARS - - void InitMethodProperties() - { - _level = 5; - _dicSize = - _numPasses = 0xFFFFFFFF; - #ifdef COMPRESS_MT - _numThreads = NWindows::NSystem::GetNumberOfProcessors();; - #endif - } - -public: - MY_QUERYINTERFACE_BEGIN2(IInArchive) - MY_QUERYINTERFACE_ENTRY(IOutArchive) - MY_QUERYINTERFACE_ENTRY(ISetProperties) - QUERY_ENTRY_ISetCompressCodecsInfo - MY_QUERYINTERFACE_END - MY_ADDREF_RELEASE - - INTERFACE_IInArchive(;) -#ifndef EXTRACT_ONLY - INTERFACE_IOutArchive(;) - - STDMETHOD(SetProperties)(const wchar_t **names, const PROPVARIANT *values, Int32 numProperties); -#endif - - DECL_ISetCompressCodecsInfo - - CHandler() { InitMethodProperties(); } -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/BZip2/BZip2Item.h b/desmume/src/windows/7z/CPP/7zip/Archive/BZip2/BZip2Item.h deleted file mode 100644 index f3fce499a..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/BZip2/BZip2Item.h +++ /dev/null @@ -1,20 +0,0 @@ -// Archive/BZip2Item.h - -#ifndef __ARCHIVE_BZIP2_ITEM_H -#define __ARCHIVE_BZIP2_ITEM_H - -namespace NArchive { -namespace NBZip2 { - -struct CItem -{ - UInt64 PackSize; - UInt64 UnPackSize; -}; - -}} - -#endif - - - diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/BZip2/StdAfx.h b/desmume/src/windows/7z/CPP/7zip/Archive/BZip2/StdAfx.h deleted file mode 100644 index 83fdd22d5..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/BZip2/StdAfx.h +++ /dev/null @@ -1,8 +0,0 @@ -// StdAfx.h - -#ifndef __STDAFX_H -#define __STDAFX_H - -#include "../../../Common/MyWindows.h" - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/BZip2/bz2Register.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/BZip2/bz2Register.cpp deleted file mode 100644 index f4a706ed1..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/BZip2/bz2Register.cpp +++ /dev/null @@ -1,18 +0,0 @@ -// BZip2Register.cpp - -#include "StdAfx.h" - -#include "../../Common/RegisterArc.h" - -#include "BZip2Handler.h" -static IInArchive *CreateArc() { return new NArchive::NBZip2::CHandler; } -#ifndef EXTRACT_ONLY -static IOutArchive *CreateArcOut() { return new NArchive::NBZip2::CHandler; } -#else -#define CreateArcOut 0 -#endif - -static CArcInfo g_ArcInfo = - { L"BZip2", L"bz2 bzip2 tbz2 tbz", L"* * .tar .tar", 2, { 'B', 'Z', 'h' }, 3, true, CreateArc, CreateArcOut }; - -REGISTER_ARC(BZip2) diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Common/CoderMixer2.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Common/CoderMixer2.cpp deleted file mode 100644 index c4333f234..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Common/CoderMixer2.cpp +++ /dev/null @@ -1,121 +0,0 @@ -// CoderMixer2.cpp - -#include "StdAfx.h" - -#include "CoderMixer2.h" - -namespace NCoderMixer { - -CBindReverseConverter::CBindReverseConverter(const CBindInfo &srcBindInfo): - _srcBindInfo(srcBindInfo) -{ - srcBindInfo.GetNumStreams(NumSrcInStreams, _numSrcOutStreams); - - UInt32 j; - for (j = 0; j < NumSrcInStreams; j++) - { - _srcInToDestOutMap.Add(0); - DestOutToSrcInMap.Add(0); - } - for (j = 0; j < _numSrcOutStreams; j++) - { - _srcOutToDestInMap.Add(0); - _destInToSrcOutMap.Add(0); - } - - UInt32 destInOffset = 0; - UInt32 destOutOffset = 0; - UInt32 srcInOffset = NumSrcInStreams; - UInt32 srcOutOffset = _numSrcOutStreams; - - for (int i = srcBindInfo.Coders.Size() - 1; i >= 0; i--) - { - const CCoderStreamsInfo &srcCoderInfo = srcBindInfo.Coders[i]; - - srcInOffset -= srcCoderInfo.NumInStreams; - srcOutOffset -= srcCoderInfo.NumOutStreams; - - UInt32 j; - for (j = 0; j < srcCoderInfo.NumInStreams; j++, destOutOffset++) - { - UInt32 index = srcInOffset + j; - _srcInToDestOutMap[index] = destOutOffset; - DestOutToSrcInMap[destOutOffset] = index; - } - for (j = 0; j < srcCoderInfo.NumOutStreams; j++, destInOffset++) - { - UInt32 index = srcOutOffset + j; - _srcOutToDestInMap[index] = destInOffset; - _destInToSrcOutMap[destInOffset] = index; - } - } -} - -void CBindReverseConverter::CreateReverseBindInfo(CBindInfo &destBindInfo) -{ - destBindInfo.Coders.Clear(); - destBindInfo.BindPairs.Clear(); - destBindInfo.InStreams.Clear(); - destBindInfo.OutStreams.Clear(); - - int i; - for (i = _srcBindInfo.Coders.Size() - 1; i >= 0; i--) - { - const CCoderStreamsInfo &srcCoderInfo = _srcBindInfo.Coders[i]; - CCoderStreamsInfo destCoderInfo; - destCoderInfo.NumInStreams = srcCoderInfo.NumOutStreams; - destCoderInfo.NumOutStreams = srcCoderInfo.NumInStreams; - destBindInfo.Coders.Add(destCoderInfo); - } - for (i = _srcBindInfo.BindPairs.Size() - 1; i >= 0; i--) - { - const CBindPair &srcBindPair = _srcBindInfo.BindPairs[i]; - CBindPair destBindPair; - destBindPair.InIndex = _srcOutToDestInMap[srcBindPair.OutIndex]; - destBindPair.OutIndex = _srcInToDestOutMap[srcBindPair.InIndex]; - destBindInfo.BindPairs.Add(destBindPair); - } - for (i = 0; i < _srcBindInfo.InStreams.Size(); i++) - destBindInfo.OutStreams.Add(_srcInToDestOutMap[_srcBindInfo.InStreams[i]]); - for (i = 0; i < _srcBindInfo.OutStreams.Size(); i++) - destBindInfo.InStreams.Add(_srcOutToDestInMap[_srcBindInfo.OutStreams[i]]); -} - -CCoderInfo2::CCoderInfo2(UInt32 numInStreams, UInt32 numOutStreams): - NumInStreams(numInStreams), - NumOutStreams(numOutStreams) -{ - InSizes.Reserve(NumInStreams); - InSizePointers.Reserve(NumInStreams); - OutSizePointers.Reserve(NumOutStreams); - OutSizePointers.Reserve(NumOutStreams); -} - -static void SetSizes(const UInt64 **srcSizes, CRecordVector &sizes, - CRecordVector &sizePointers, UInt32 numItems) -{ - sizes.Clear(); - sizePointers.Clear(); - for(UInt32 i = 0; i < numItems; i++) - { - if (srcSizes == 0 || srcSizes[i] == NULL) - { - sizes.Add(0); - sizePointers.Add(NULL); - } - else - { - sizes.Add(*srcSizes[i]); - sizePointers.Add(&sizes.Back()); - } - } -} - -void CCoderInfo2::SetCoderInfo(const UInt64 **inSizes, - const UInt64 **outSizes) -{ - SetSizes(inSizes, InSizes, InSizePointers, NumInStreams); - SetSizes(outSizes, OutSizes, OutSizePointers, NumOutStreams); -} - -} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Common/CoderMixer2.h b/desmume/src/windows/7z/CPP/7zip/Archive/Common/CoderMixer2.h deleted file mode 100644 index b1893b217..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Common/CoderMixer2.h +++ /dev/null @@ -1,174 +0,0 @@ -// CoderMixer2.h - -#ifndef __CODER_MIXER2_H -#define __CODER_MIXER2_H - -#include "../../../Common/MyVector.h" -#include "../../../Common/Types.h" -#include "../../../Common/MyCom.h" -#include "../../ICoder.h" - -namespace NCoderMixer { - -struct CBindPair -{ - UInt32 InIndex; - UInt32 OutIndex; -}; - -struct CCoderStreamsInfo -{ - UInt32 NumInStreams; - UInt32 NumOutStreams; -}; - -struct CBindInfo -{ - CRecordVector Coders; - CRecordVector BindPairs; - CRecordVector InStreams; - CRecordVector OutStreams; - - void Clear() - { - Coders.Clear(); - BindPairs.Clear(); - InStreams.Clear(); - OutStreams.Clear(); - } - - /* - UInt32 GetCoderStartOutStream(UInt32 coderIndex) const - { - UInt32 numOutStreams = 0; - for (UInt32 i = 0; i < coderIndex; i++) - numOutStreams += Coders[i].NumOutStreams; - return numOutStreams; - } - */ - - - void GetNumStreams(UInt32 &numInStreams, UInt32 &numOutStreams) const - { - numInStreams = 0; - numOutStreams = 0; - for (int i = 0; i < Coders.Size(); i++) - { - const CCoderStreamsInfo &coderStreamsInfo = Coders[i]; - numInStreams += coderStreamsInfo.NumInStreams; - numOutStreams += coderStreamsInfo.NumOutStreams; - } - } - - int FindBinderForInStream(UInt32 inStream) const - { - for (int i = 0; i < BindPairs.Size(); i++) - if (BindPairs[i].InIndex == inStream) - return i; - return -1; - } - int FindBinderForOutStream(UInt32 outStream) const - { - for (int i = 0; i < BindPairs.Size(); i++) - if (BindPairs[i].OutIndex == outStream) - return i; - return -1; - } - - UInt32 GetCoderInStreamIndex(UInt32 coderIndex) const - { - UInt32 streamIndex = 0; - for (UInt32 i = 0; i < coderIndex; i++) - streamIndex += Coders[i].NumInStreams; - return streamIndex; - } - - UInt32 GetCoderOutStreamIndex(UInt32 coderIndex) const - { - UInt32 streamIndex = 0; - for (UInt32 i = 0; i < coderIndex; i++) - streamIndex += Coders[i].NumOutStreams; - return streamIndex; - } - - - void FindInStream(UInt32 streamIndex, UInt32 &coderIndex, - UInt32 &coderStreamIndex) const - { - for (coderIndex = 0; coderIndex < (UInt32)Coders.Size(); coderIndex++) - { - UInt32 curSize = Coders[coderIndex].NumInStreams; - if (streamIndex < curSize) - { - coderStreamIndex = streamIndex; - return; - } - streamIndex -= curSize; - } - throw 1; - } - void FindOutStream(UInt32 streamIndex, UInt32 &coderIndex, - UInt32 &coderStreamIndex) const - { - for (coderIndex = 0; coderIndex < (UInt32)Coders.Size(); coderIndex++) - { - UInt32 curSize = Coders[coderIndex].NumOutStreams; - if (streamIndex < curSize) - { - coderStreamIndex = streamIndex; - return; - } - streamIndex -= curSize; - } - throw 1; - } -}; - -class CBindReverseConverter -{ - UInt32 _numSrcOutStreams; - NCoderMixer::CBindInfo _srcBindInfo; - CRecordVector _srcInToDestOutMap; - CRecordVector _srcOutToDestInMap; - CRecordVector _destInToSrcOutMap; -public: - UInt32 NumSrcInStreams; - CRecordVector DestOutToSrcInMap; - - CBindReverseConverter(const NCoderMixer::CBindInfo &srcBindInfo); - void CreateReverseBindInfo(NCoderMixer::CBindInfo &destBindInfo); -}; - -struct CCoderInfo2 -{ - CMyComPtr Coder; - CMyComPtr Coder2; - UInt32 NumInStreams; - UInt32 NumOutStreams; - - CRecordVector InSizes; - CRecordVector OutSizes; - CRecordVector InSizePointers; - CRecordVector OutSizePointers; - - CCoderInfo2(UInt32 numInStreams, UInt32 numOutStreams); - void SetCoderInfo(const UInt64 **inSizes, const UInt64 **outSizes); - - HRESULT QueryInterface(REFGUID iid, void** pp) const - { - IUnknown *p = Coder ? (IUnknown *)Coder : (IUnknown *)Coder2; - return p->QueryInterface(iid, pp); - } -}; - -class CCoderMixer2 -{ -public: - virtual HRESULT SetBindInfo(const CBindInfo &bindInfo) = 0; - virtual void ReInit() = 0; - virtual void SetCoderInfo(UInt32 coderIndex, const UInt64 **inSizes, const UInt64 **outSizes) = 0; -}; - -} -#endif - diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Common/CoderMixer2MT.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Common/CoderMixer2MT.cpp deleted file mode 100644 index f3bea728d..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Common/CoderMixer2MT.cpp +++ /dev/null @@ -1,230 +0,0 @@ -// CoderMixer2MT.cpp - -#include "StdAfx.h" - -#include "CoderMixer2MT.h" - -namespace NCoderMixer { - -CCoder2::CCoder2(UInt32 numInStreams, UInt32 numOutStreams): - CCoderInfo2(numInStreams, numOutStreams) -{ - InStreams.Reserve(NumInStreams); - InStreamPointers.Reserve(NumInStreams); - OutStreams.Reserve(NumOutStreams); - OutStreamPointers.Reserve(NumOutStreams); -} - -void CCoder2::Execute() { Code(NULL); } - -void CCoder2::Code(ICompressProgressInfo *progress) -{ - InStreamPointers.Clear(); - OutStreamPointers.Clear(); - UInt32 i; - for (i = 0; i < NumInStreams; i++) - { - if (InSizePointers[i] != NULL) - InSizePointers[i] = &InSizes[i]; - InStreamPointers.Add((ISequentialInStream *)InStreams[i]); - } - for (i = 0; i < NumOutStreams; i++) - { - if (OutSizePointers[i] != NULL) - OutSizePointers[i] = &OutSizes[i]; - OutStreamPointers.Add((ISequentialOutStream *)OutStreams[i]); - } - if (Coder) - Result = Coder->Code(InStreamPointers[0], OutStreamPointers[0], - InSizePointers[0], OutSizePointers[0], progress); - else - Result = Coder2->Code(&InStreamPointers.Front(), &InSizePointers.Front(), NumInStreams, - &OutStreamPointers.Front(), &OutSizePointers.Front(), NumOutStreams, progress); - { - int i; - for (i = 0; i < InStreams.Size(); i++) - InStreams[i].Release(); - for (i = 0; i < OutStreams.Size(); i++) - OutStreams[i].Release(); - } -} - -static void SetSizes(const UInt64 **srcSizes, CRecordVector &sizes, - CRecordVector &sizePointers, UInt32 numItems) -{ - sizes.Clear(); - sizePointers.Clear(); - for(UInt32 i = 0; i < numItems; i++) - { - if (srcSizes == 0 || srcSizes[i] == NULL) - { - sizes.Add(0); - sizePointers.Add(NULL); - } - else - { - sizes.Add(*srcSizes[i]); - sizePointers.Add(&sizes.Back()); - } - } -} - - -void CCoder2::SetCoderInfo(const UInt64 **inSizes, const UInt64 **outSizes) -{ - SetSizes(inSizes, InSizes, InSizePointers, NumInStreams); - SetSizes(outSizes, OutSizes, OutSizePointers, NumOutStreams); -} - -////////////////////////////////////// -// CCoderMixer2MT - -HRESULT CCoderMixer2MT::SetBindInfo(const CBindInfo &bindInfo) -{ - _bindInfo = bindInfo; - _streamBinders.Clear(); - for(int i = 0; i < _bindInfo.BindPairs.Size(); i++) - { - _streamBinders.Add(CStreamBinder()); - RINOK(_streamBinders.Back().CreateEvents()); - } - return S_OK; -} - -void CCoderMixer2MT::AddCoderCommon() -{ - const CCoderStreamsInfo &c = _bindInfo.Coders[_coders.Size()]; - CCoder2 threadCoderInfo(c.NumInStreams, c.NumOutStreams); - _coders.Add(threadCoderInfo); -} - -void CCoderMixer2MT::AddCoder(ICompressCoder *coder) -{ - AddCoderCommon(); - _coders.Back().Coder = coder; -} - -void CCoderMixer2MT::AddCoder2(ICompressCoder2 *coder) -{ - AddCoderCommon(); - _coders.Back().Coder2 = coder; -} - - -void CCoderMixer2MT::ReInit() -{ - for(int i = 0; i < _streamBinders.Size(); i++) - _streamBinders[i].ReInit(); -} - - -HRESULT CCoderMixer2MT::Init(ISequentialInStream **inStreams, ISequentialOutStream **outStreams) -{ - /* - if (_coders.Size() != _bindInfo.Coders.Size()) - throw 0; - */ - int i; - for(i = 0; i < _coders.Size(); i++) - { - CCoder2 &coderInfo = _coders[i]; - const CCoderStreamsInfo &coderStreamsInfo = _bindInfo.Coders[i]; - coderInfo.InStreams.Clear(); - UInt32 j; - for(j = 0; j < coderStreamsInfo.NumInStreams; j++) - coderInfo.InStreams.Add(NULL); - coderInfo.OutStreams.Clear(); - for(j = 0; j < coderStreamsInfo.NumOutStreams; j++) - coderInfo.OutStreams.Add(NULL); - } - - for(i = 0; i < _bindInfo.BindPairs.Size(); i++) - { - const CBindPair &bindPair = _bindInfo.BindPairs[i]; - UInt32 inCoderIndex, inCoderStreamIndex; - UInt32 outCoderIndex, outCoderStreamIndex; - _bindInfo.FindInStream(bindPair.InIndex, inCoderIndex, inCoderStreamIndex); - _bindInfo.FindOutStream(bindPair.OutIndex, outCoderIndex, outCoderStreamIndex); - - _streamBinders[i].CreateStreams( - &_coders[inCoderIndex].InStreams[inCoderStreamIndex], - &_coders[outCoderIndex].OutStreams[outCoderStreamIndex]); - } - - for(i = 0; i < _bindInfo.InStreams.Size(); i++) - { - UInt32 inCoderIndex, inCoderStreamIndex; - _bindInfo.FindInStream(_bindInfo.InStreams[i], inCoderIndex, inCoderStreamIndex); - _coders[inCoderIndex].InStreams[inCoderStreamIndex] = inStreams[i]; - } - - for(i = 0; i < _bindInfo.OutStreams.Size(); i++) - { - UInt32 outCoderIndex, outCoderStreamIndex; - _bindInfo.FindOutStream(_bindInfo.OutStreams[i], outCoderIndex, outCoderStreamIndex); - _coders[outCoderIndex].OutStreams[outCoderStreamIndex] = outStreams[i]; - } - return S_OK; -} - -HRESULT CCoderMixer2MT::ReturnIfError(HRESULT code) -{ - for (int i = 0; i < _coders.Size(); i++) - if (_coders[i].Result == code) - return code; - return S_OK; -} - -STDMETHODIMP CCoderMixer2MT::Code(ISequentialInStream **inStreams, - const UInt64 ** /* inSizes */, - UInt32 numInStreams, - ISequentialOutStream **outStreams, - const UInt64 ** /* outSizes */, - UInt32 numOutStreams, - ICompressProgressInfo *progress) -{ - if (numInStreams != (UInt32)_bindInfo.InStreams.Size() || - numOutStreams != (UInt32)_bindInfo.OutStreams.Size()) - return E_INVALIDARG; - - Init(inStreams, outStreams); - - int i; - for (i = 0; i < _coders.Size(); i++) - if (i != _progressCoderIndex) - { - RINOK(_coders[i].Create()); - } - - for (i = 0; i < _coders.Size(); i++) - if (i != _progressCoderIndex) - _coders[i].Start(); - - _coders[_progressCoderIndex].Code(progress); - - for (i = 0; i < _coders.Size(); i++) - if (i != _progressCoderIndex) - _coders[i].WaitFinish(); - - RINOK(ReturnIfError(E_ABORT)); - RINOK(ReturnIfError(E_OUTOFMEMORY)); - - for (i = 0; i < _coders.Size(); i++) - { - HRESULT result = _coders[i].Result; - if (result != S_OK && result != E_FAIL && result != S_FALSE) - return result; - } - - RINOK(ReturnIfError(S_FALSE)); - - for (i = 0; i < _coders.Size(); i++) - { - HRESULT result = _coders[i].Result; - if (result != S_OK) - return result; - } - return S_OK; -} - -} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Common/CoderMixer2MT.h b/desmume/src/windows/7z/CPP/7zip/Archive/Common/CoderMixer2MT.h deleted file mode 100644 index acecc390f..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Common/CoderMixer2MT.h +++ /dev/null @@ -1,80 +0,0 @@ -// CoderMixer2MT.h - -#ifndef __CODER_MIXER2_MT_H -#define __CODER_MIXER2_MT_H - -#include "CoderMixer2.h" -#include "../../../Common/MyCom.h" -#include "../../Common/StreamBinder.h" -#include "../../Common/VirtThread.h" - -namespace NCoderMixer { - -struct CCoder2: public CCoderInfo2, public CVirtThread -{ - HRESULT Result; - CObjectVector< CMyComPtr > InStreams; - CObjectVector< CMyComPtr > OutStreams; - CRecordVector InStreamPointers; - CRecordVector OutStreamPointers; - - CCoder2(UInt32 numInStreams, UInt32 numOutStreams); - void SetCoderInfo(const UInt64 **inSizes, const UInt64 **outSizes); - virtual void Execute(); - void Code(ICompressProgressInfo *progress); -}; - - -/* - SetBindInfo() - for each coder - AddCoder[2]() - SetProgressIndex(UInt32 coderIndex); - - for each file - { - ReInit() - for each coder - SetCoderInfo - Code - } -*/ - -class CCoderMixer2MT: - public ICompressCoder2, - public CCoderMixer2, - public CMyUnknownImp -{ - CBindInfo _bindInfo; - CObjectVector _streamBinders; - int _progressCoderIndex; - - void AddCoderCommon(); - HRESULT Init(ISequentialInStream **inStreams, ISequentialOutStream **outStreams); - HRESULT ReturnIfError(HRESULT code); -public: - CObjectVector _coders; - MY_UNKNOWN_IMP - - STDMETHOD(Code)(ISequentialInStream **inStreams, - const UInt64 **inSizes, - UInt32 numInStreams, - ISequentialOutStream **outStreams, - const UInt64 **outSizes, - UInt32 numOutStreams, - ICompressProgressInfo *progress); - - HRESULT SetBindInfo(const CBindInfo &bindInfo); - void AddCoder(ICompressCoder *coder); - void AddCoder2(ICompressCoder2 *coder); - void SetProgressCoderIndex(int coderIndex) { _progressCoderIndex = coderIndex; } - - void ReInit(); - void SetCoderInfo(UInt32 coderIndex, const UInt64 **inSizes, const UInt64 **outSizes) - { _coders[coderIndex].SetCoderInfo(inSizes, outSizes); } - UInt64 GetWriteProcessedSize(UInt32 binderIndex) const - { return _streamBinders[binderIndex].ProcessedSize; } -}; - -} -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Common/DummyOutStream.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Common/DummyOutStream.cpp deleted file mode 100644 index 237e01e59..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Common/DummyOutStream.cpp +++ /dev/null @@ -1,22 +0,0 @@ -// DummyOutStream.cpp - -#include "StdAfx.h" - -#include "DummyOutStream.h" - -STDMETHODIMP CDummyOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize) -{ - UInt32 realProcessedSize; - HRESULT result; - if(!_stream) - { - realProcessedSize = size; - result = S_OK; - } - else - result = _stream->Write(data, size, &realProcessedSize); - _size += realProcessedSize; - if(processedSize != NULL) - *processedSize = realProcessedSize; - return result; -} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Common/DummyOutStream.h b/desmume/src/windows/7z/CPP/7zip/Archive/Common/DummyOutStream.h deleted file mode 100644 index c993bb3dd..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Common/DummyOutStream.h +++ /dev/null @@ -1,24 +0,0 @@ -// DummyOutStream.h - -#ifndef __DUMMYOUTSTREAM_H -#define __DUMMYOUTSTREAM_H - -#include "../../IStream.h" -#include "Common/MyCom.h" - -class CDummyOutStream: - public ISequentialOutStream, - public CMyUnknownImp -{ - CMyComPtr _stream; - UInt64 _size; -public: - void SetStream(ISequentialOutStream *outStream) { _stream = outStream; } - void ReleaseStream() { _stream.Release(); } - void Init() { _size = 0; } - MY_UNKNOWN_IMP - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); - UInt64 GetSize() const { return _size; } -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Common/FindSignature.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Common/FindSignature.cpp deleted file mode 100644 index ad04bfcb7..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Common/FindSignature.cpp +++ /dev/null @@ -1,62 +0,0 @@ -// FindSignature.cpp - -#include "StdAfx.h" - -#include "Common/Buffer.h" - -#include "FindSignature.h" - -#include "../../Common/StreamUtils.h" - -HRESULT FindSignatureInStream(ISequentialInStream *stream, - const Byte *signature, unsigned signatureSize, - const UInt64 *limit, UInt64 &resPos) -{ - resPos = 0; - CByteBuffer byteBuffer2; - byteBuffer2.SetCapacity(signatureSize); - RINOK(ReadStream_FALSE(stream, byteBuffer2, signatureSize)); - - if (memcmp(byteBuffer2, signature, signatureSize) == 0) - return S_OK; - - const UInt32 kBufferSize = (1 << 16); - CByteBuffer byteBuffer; - byteBuffer.SetCapacity(kBufferSize); - Byte *buffer = byteBuffer; - UInt32 numPrevBytes = signatureSize - 1; - memcpy(buffer, (const Byte *)byteBuffer2 + 1, numPrevBytes); - resPos = 1; - for (;;) - { - if (limit != NULL) - if (resPos > *limit) - return S_FALSE; - do - { - UInt32 numReadBytes = kBufferSize - numPrevBytes; - UInt32 processedSize; - RINOK(stream->Read(buffer + numPrevBytes, numReadBytes, &processedSize)); - numPrevBytes += processedSize; - if (processedSize == 0) - return S_FALSE; - } - while (numPrevBytes < signatureSize); - UInt32 numTests = numPrevBytes - signatureSize + 1; - for (UInt32 pos = 0; pos < numTests; pos++) - { - Byte b = signature[0]; - for (; buffer[pos] != b && pos < numTests; pos++); - if (pos == numTests) - break; - if (memcmp(buffer + pos, signature, signatureSize) == 0) - { - resPos += pos; - return S_OK; - } - } - resPos += numTests; - numPrevBytes -= numTests; - memmove(buffer, buffer + numTests, numPrevBytes); - } -} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Common/FindSignature.h b/desmume/src/windows/7z/CPP/7zip/Archive/Common/FindSignature.h deleted file mode 100644 index f801d9860..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Common/FindSignature.h +++ /dev/null @@ -1,12 +0,0 @@ -// FindSignature.h - -#ifndef __FINDSIGNATURE_H -#define __FINDSIGNATURE_H - -#include "../../IStream.h" - -HRESULT FindSignatureInStream(ISequentialInStream *stream, - const Byte *signature, unsigned signatureSize, - const UInt64 *limit, UInt64 &resPos); - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Common/InStreamWithCRC.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Common/InStreamWithCRC.cpp deleted file mode 100644 index 4b87a43c0..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Common/InStreamWithCRC.cpp +++ /dev/null @@ -1,40 +0,0 @@ -// InStreamWithCRC.cpp - -#include "StdAfx.h" - -#include "InStreamWithCRC.h" - -STDMETHODIMP CSequentialInStreamWithCRC::Read(void *data, UInt32 size, UInt32 *processedSize) -{ - UInt32 realProcessedSize; - HRESULT result = _stream->Read(data, size, &realProcessedSize); - _size += realProcessedSize; - if (size > 0 && realProcessedSize == 0) - _wasFinished = true; - _crc = CrcUpdate(_crc, data, realProcessedSize); - if(processedSize != NULL) - *processedSize = realProcessedSize; - return result; -} - -STDMETHODIMP CInStreamWithCRC::Read(void *data, UInt32 size, UInt32 *processedSize) -{ - UInt32 realProcessedSize; - HRESULT result = _stream->Read(data, size, &realProcessedSize); - if (size > 0 && realProcessedSize == 0) - _wasFinished = true; - _size += realProcessedSize; - _crc = CrcUpdate(_crc, data, realProcessedSize); - if(processedSize != NULL) - *processedSize = realProcessedSize; - return result; -} - -STDMETHODIMP CInStreamWithCRC::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) -{ - if (seekOrigin != STREAM_SEEK_SET || offset != 0) - return E_FAIL; - _size = 0; - _crc = CRC_INIT_VAL; - return _stream->Seek(offset, seekOrigin, newPosition); -} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Common/InStreamWithCRC.h b/desmume/src/windows/7z/CPP/7zip/Archive/Common/InStreamWithCRC.h deleted file mode 100644 index d73f658e3..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Common/InStreamWithCRC.h +++ /dev/null @@ -1,69 +0,0 @@ -// InStreamWithCRC.h - -#ifndef __INSTREAMWITHCRC_H -#define __INSTREAMWITHCRC_H - -#include "../../../Common/MyCom.h" -#include "../../IStream.h" - -extern "C" -{ -#include "../../../../C/7zCrc.h" -} - -class CSequentialInStreamWithCRC: - public ISequentialInStream, - public CMyUnknownImp -{ -public: - MY_UNKNOWN_IMP - - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); -private: - CMyComPtr _stream; - UInt64 _size; - UInt32 _crc; - bool _wasFinished; -public: - void SetStream(ISequentialInStream *stream) { _stream = stream; } - void Init() - { - _size = 0; - _wasFinished = false; - _crc = CRC_INIT_VAL; - } - void ReleaseStream() { _stream.Release(); } - UInt32 GetCRC() const { return CRC_GET_DIGEST(_crc); } - UInt64 GetSize() const { return _size; } - bool WasFinished() const { return _wasFinished; } -}; - -class CInStreamWithCRC: - public IInStream, - public CMyUnknownImp -{ -public: - MY_UNKNOWN_IMP1(IInStream) - - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); - STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition); -private: - CMyComPtr _stream; - UInt64 _size; - UInt32 _crc; - bool _wasFinished; -public: - void SetStream(IInStream *stream) { _stream = stream; } - void Init() - { - _size = 0; - _wasFinished = false; - _crc = CRC_INIT_VAL; - } - void ReleaseStream() { _stream.Release(); } - UInt32 GetCRC() const { return CRC_GET_DIGEST(_crc); } - UInt64 GetSize() const { return _size; } - bool WasFinished() const { return _wasFinished; } -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Common/ItemNameUtils.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Common/ItemNameUtils.cpp deleted file mode 100644 index b4fee7c06..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Common/ItemNameUtils.cpp +++ /dev/null @@ -1,59 +0,0 @@ -// Archive/Common/ItemNameUtils.cpp - -#include "StdAfx.h" - -#include "ItemNameUtils.h" - -namespace NArchive { -namespace NItemName { - -static const wchar_t kOSDirDelimiter = WCHAR_PATH_SEPARATOR; -static const wchar_t kDirDelimiter = L'/'; - -UString MakeLegalName(const UString &name) -{ - UString zipName = name; - zipName.Replace(kOSDirDelimiter, kDirDelimiter); - return zipName; -} - -UString GetOSName(const UString &name) -{ - UString newName = name; - newName.Replace(kDirDelimiter, kOSDirDelimiter); - return newName; -} - -UString GetOSName2(const UString &name) -{ - if (name.IsEmpty()) - return UString(); - UString newName = GetOSName(name); - if (newName[newName.Length() - 1] == kOSDirDelimiter) - newName.Delete(newName.Length() - 1); - return newName; -} - -bool HasTailSlash(const AString &name, UINT codePage) -{ - if (name.IsEmpty()) - return false; - LPCSTR prev = - #ifdef _WIN32 - CharPrevExA((WORD)codePage, name, &name[name.Length()], 0); - #else - (LPCSTR)(name) + (name.Length() - 1); - #endif - return (*prev == '/'); -} - -#ifndef _WIN32 -UString WinNameToOSName(const UString &name) -{ - UString newName = name; - newName.Replace(L'\\', kOSDirDelimiter); - return newName; -} -#endif - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Common/ItemNameUtils.h b/desmume/src/windows/7z/CPP/7zip/Archive/Common/ItemNameUtils.h deleted file mode 100644 index 8b91d1c68..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Common/ItemNameUtils.h +++ /dev/null @@ -1,24 +0,0 @@ -// Archive/Common/ItemNameUtils.h - -#ifndef __ARCHIVE_ITEMNAMEUTILS_H -#define __ARCHIVE_ITEMNAMEUTILS_H - -#include "../../../Common/MyString.h" - -namespace NArchive { -namespace NItemName { - - UString MakeLegalName(const UString &name); - UString GetOSName(const UString &name); - UString GetOSName2(const UString &name); - bool HasTailSlash(const AString &name, UINT codePage); - - #ifdef _WIN32 - inline UString WinNameToOSName(const UString &name) { return name; } - #else - UString WinNameToOSName(const UString &name); - #endif - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Common/MultiStream.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Common/MultiStream.cpp deleted file mode 100644 index 33bb91ed8..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Common/MultiStream.cpp +++ /dev/null @@ -1,201 +0,0 @@ -// MultiStream.cpp - -#include "StdAfx.h" - -#include "MultiStream.h" - -STDMETHODIMP CMultiStream::Read(void *data, UInt32 size, UInt32 *processedSize) -{ - if(processedSize != NULL) - *processedSize = 0; - while(_streamIndex < Streams.Size() && size > 0) - { - CSubStreamInfo &s = Streams[_streamIndex]; - if (_pos == s.Size) - { - _streamIndex++; - _pos = 0; - continue; - } - RINOK(s.Stream->Seek(s.Pos + _pos, STREAM_SEEK_SET, 0)); - UInt32 sizeToRead = UInt32(MyMin((UInt64)size, s.Size - _pos)); - UInt32 realProcessed; - HRESULT result = s.Stream->Read(data, sizeToRead, &realProcessed); - data = (void *)((Byte *)data + realProcessed); - size -= realProcessed; - if(processedSize != NULL) - *processedSize += realProcessed; - _pos += realProcessed; - _seekPos += realProcessed; - RINOK(result); - break; - } - return S_OK; -} - -STDMETHODIMP CMultiStream::Seek(Int64 offset, UInt32 seekOrigin, - UInt64 *newPosition) -{ - UInt64 newPos; - switch(seekOrigin) - { - case STREAM_SEEK_SET: - newPos = offset; - break; - case STREAM_SEEK_CUR: - newPos = _seekPos + offset; - break; - case STREAM_SEEK_END: - newPos = _totalLength + offset; - break; - default: - return STG_E_INVALIDFUNCTION; - } - _seekPos = 0; - for (_streamIndex = 0; _streamIndex < Streams.Size(); _streamIndex++) - { - UInt64 size = Streams[_streamIndex].Size; - if (newPos < _seekPos + size) - { - _pos = newPos - _seekPos; - _seekPos += _pos; - if (newPosition != 0) - *newPosition = newPos; - return S_OK; - } - _seekPos += size; - } - if (newPos == _seekPos) - { - if (newPosition != 0) - *newPosition = newPos; - return S_OK; - } - return E_FAIL; -} - - -/* -class COutVolumeStream: - public ISequentialOutStream, - public CMyUnknownImp -{ - int _volIndex; - UInt64 _volSize; - UInt64 _curPos; - CMyComPtr _volumeStream; - COutArchive _archive; - CCRC _crc; - -public: - MY_UNKNOWN_IMP - - CFileItem _file; - CUpdateOptions _options; - CMyComPtr VolumeCallback; - void Init(IArchiveUpdateCallback2 *volumeCallback, - const UString &name) - { - _file.Name = name; - _file.IsStartPosDefined = true; - _file.StartPos = 0; - - VolumeCallback = volumeCallback; - _volIndex = 0; - _volSize = 0; - } - - HRESULT Flush(); - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); -}; - -HRESULT COutVolumeStream::Flush() -{ - if (_volumeStream) - { - _file.UnPackSize = _curPos; - _file.FileCRC = _crc.GetDigest(); - RINOK(WriteVolumeHeader(_archive, _file, _options)); - _archive.Close(); - _volumeStream.Release(); - _file.StartPos += _file.UnPackSize; - } - return S_OK; -} -*/ - -/* -STDMETHODIMP COutMultiStream::Write(const void *data, UInt32 size, UInt32 *processedSize) -{ - if(processedSize != NULL) - *processedSize = 0; - while(size > 0) - { - if (_streamIndex >= Streams.Size()) - { - CSubStreamInfo subStream; - RINOK(VolumeCallback->GetVolumeSize(Streams.Size(), &subStream.Size)); - RINOK(VolumeCallback->GetVolumeStream(Streams.Size(), &subStream.Stream)); - subStream.Pos = 0; - Streams.Add(subStream); - continue; - } - CSubStreamInfo &subStream = Streams[_streamIndex]; - if (_offsetPos >= subStream.Size) - { - _offsetPos -= subStream.Size; - _streamIndex++; - continue; - } - if (_offsetPos != subStream.Pos) - { - CMyComPtr outStream; - RINOK(subStream.Stream.QueryInterface(IID_IOutStream, &outStream)); - RINOK(outStream->Seek(_offsetPos, STREAM_SEEK_SET, NULL)); - subStream.Pos = _offsetPos; - } - - UInt32 curSize = (UInt32)MyMin((UInt64)size, subStream.Size - subStream.Pos); - UInt32 realProcessed; - RINOK(subStream.Stream->Write(data, curSize, &realProcessed)); - data = (void *)((Byte *)data + realProcessed); - size -= realProcessed; - subStream.Pos += realProcessed; - _offsetPos += realProcessed; - _absPos += realProcessed; - if (_absPos > _length) - _length = _absPos; - if(processedSize != NULL) - *processedSize += realProcessed; - if (subStream.Pos == subStream.Size) - { - _streamIndex++; - _offsetPos = 0; - } - if (realProcessed != curSize && realProcessed == 0) - return E_FAIL; - } - return S_OK; -} - -STDMETHODIMP COutMultiStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) -{ - if(seekOrigin >= 3) - return STG_E_INVALIDFUNCTION; - switch(seekOrigin) - { - case STREAM_SEEK_SET: - _absPos = offset; - break; - case STREAM_SEEK_CUR: - _absPos += offset; - break; - case STREAM_SEEK_END: - _absPos = _length + offset; - break; - } - _offsetPos = _absPos; - _streamIndex = 0; - return S_OK; -} -*/ diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Common/MultiStream.h b/desmume/src/windows/7z/CPP/7zip/Archive/Common/MultiStream.h deleted file mode 100644 index 133a06f9f..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Common/MultiStream.h +++ /dev/null @@ -1,76 +0,0 @@ -// MultiStream.h - -#ifndef __MULTISTREAM_H -#define __MULTISTREAM_H - -#include "../../../Common/MyCom.h" -#include "../../../Common/MyVector.h" -#include "../../Archive/IArchive.h" - -class CMultiStream: - public IInStream, - public CMyUnknownImp -{ - int _streamIndex; - UInt64 _pos; - UInt64 _seekPos; - UInt64 _totalLength; -public: - struct CSubStreamInfo - { - CMyComPtr Stream; - UInt64 Pos; - UInt64 Size; - }; - CObjectVector Streams; - void Init() - { - _streamIndex = 0; - _pos = 0; - _seekPos = 0; - _totalLength = 0; - for (int i = 0; i < Streams.Size(); i++) - _totalLength += Streams[i].Size; - } - - MY_UNKNOWN_IMP1(IInStream) - - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); - STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition); -}; - -/* -class COutMultiStream: - public IOutStream, - public CMyUnknownImp -{ - int _streamIndex; // required stream - UInt64 _offsetPos; // offset from start of _streamIndex index - UInt64 _absPos; - UInt64 _length; - - struct CSubStreamInfo - { - CMyComPtr Stream; - UInt64 Size; - UInt64 Pos; - }; - CObjectVector Streams; -public: - CMyComPtr VolumeCallback; - void Init() - { - _streamIndex = 0; - _offsetPos = 0; - _absPos = 0; - _length = 0; - } - - MY_UNKNOWN_IMP1(IOutStream) - - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); - STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition); -}; -*/ - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Common/OutStreamWithCRC.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Common/OutStreamWithCRC.cpp deleted file mode 100644 index 37b157d1e..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Common/OutStreamWithCRC.cpp +++ /dev/null @@ -1,24 +0,0 @@ -// OutStreamWithCRC.cpp - -#include "StdAfx.h" - -#include "OutStreamWithCRC.h" - -STDMETHODIMP COutStreamWithCRC::Write(const void *data, UInt32 size, UInt32 *processedSize) -{ - UInt32 realProcessedSize; - HRESULT result; - if(!_stream) - { - realProcessedSize = size; - result = S_OK; - } - else - result = _stream->Write(data, size, &realProcessedSize); - if (_calculate) - _crc = CrcUpdate(_crc, data, realProcessedSize); - _size += realProcessedSize; - if(processedSize != NULL) - *processedSize = realProcessedSize; - return result; -} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Common/OutStreamWithCRC.h b/desmume/src/windows/7z/CPP/7zip/Archive/Common/OutStreamWithCRC.h deleted file mode 100644 index 44e5eb24b..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Common/OutStreamWithCRC.h +++ /dev/null @@ -1,38 +0,0 @@ -// OutStreamWithCRC.h - -#ifndef __OUT_STREAM_WITH_CRC_H -#define __OUT_STREAM_WITH_CRC_H - -#include "../../../Common/MyCom.h" -#include "../../IStream.h" - -extern "C" -{ -#include "../../../../C/7zCrc.h" -} - -class COutStreamWithCRC: - public ISequentialOutStream, - public CMyUnknownImp -{ - CMyComPtr _stream; - UInt64 _size; - UInt32 _crc; - bool _calculate; -public: - MY_UNKNOWN_IMP - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); - void SetStream(ISequentialOutStream *stream) { _stream = stream; } - void ReleaseStream() { _stream.Release(); } - void Init(bool calculate = true) - { - _size = 0; - _calculate = calculate; - _crc = CRC_INIT_VAL; - } - void InitCRC() { _crc = CRC_INIT_VAL; } - UInt64 GetSize() const { return _size; } - UInt32 GetCRC() const { return CRC_GET_DIGEST(_crc); } -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Common/ParseProperties.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Common/ParseProperties.cpp deleted file mode 100644 index 5550a23bc..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Common/ParseProperties.cpp +++ /dev/null @@ -1,177 +0,0 @@ -// ParseProperties.cpp - -#include "StdAfx.h" - -#include "ParseProperties.h" - -#include "Common/StringToInt.h" -#include "Common/MyCom.h" - -HRESULT ParsePropValue(const UString &name, const PROPVARIANT &prop, UInt32 &resValue) -{ - if (prop.vt == VT_UI4) - { - if (!name.IsEmpty()) - return E_INVALIDARG; - resValue = prop.ulVal; - } - else if (prop.vt == VT_EMPTY) - { - if(!name.IsEmpty()) - { - const wchar_t *start = name; - const wchar_t *end; - UInt64 v = ConvertStringToUInt64(start, &end); - if (end - start != name.Length()) - return E_INVALIDARG; - resValue = (UInt32)v; - } - } - else - return E_INVALIDARG; - return S_OK; -} - -static const int kLogarithmicSizeLimit = 32; -static const wchar_t kByteSymbol = L'B'; -static const wchar_t kKiloByteSymbol = L'K'; -static const wchar_t kMegaByteSymbol = L'M'; - -HRESULT ParsePropDictionaryValue(const UString &srcStringSpec, UInt32 &dicSize) -{ - UString srcString = srcStringSpec; - srcString.MakeUpper(); - - const wchar_t *start = srcString; - const wchar_t *end; - UInt64 number = ConvertStringToUInt64(start, &end); - int numDigits = (int)(end - start); - if (numDigits == 0 || srcString.Length() > numDigits + 1) - return E_INVALIDARG; - if (srcString.Length() == numDigits) - { - if (number >= kLogarithmicSizeLimit) - return E_INVALIDARG; - dicSize = (UInt32)1 << (int)number; - return S_OK; - } - switch (srcString[numDigits]) - { - case kByteSymbol: - if (number >= ((UInt64)1 << kLogarithmicSizeLimit)) - return E_INVALIDARG; - dicSize = (UInt32)number; - break; - case kKiloByteSymbol: - if (number >= ((UInt64)1 << (kLogarithmicSizeLimit - 10))) - return E_INVALIDARG; - dicSize = (UInt32)(number << 10); - break; - case kMegaByteSymbol: - if (number >= ((UInt64)1 << (kLogarithmicSizeLimit - 20))) - return E_INVALIDARG; - dicSize = (UInt32)(number << 20); - break; - default: - return E_INVALIDARG; - } - return S_OK; -} - -HRESULT ParsePropDictionaryValue(const UString &name, const PROPVARIANT &prop, UInt32 &resValue) -{ - if (name.IsEmpty()) - { - if (prop.vt == VT_UI4) - { - UInt32 logDicSize = prop.ulVal; - if (logDicSize >= 32) - return E_INVALIDARG; - resValue = (UInt32)1 << logDicSize; - return S_OK; - } - if (prop.vt == VT_BSTR) - return ParsePropDictionaryValue(prop.bstrVal, resValue); - return E_INVALIDARG; - } - return ParsePropDictionaryValue(name, resValue); -} - -bool StringToBool(const UString &s, bool &res) -{ - if (s.IsEmpty() || s.CompareNoCase(L"ON") == 0 || s.Compare(L"+") == 0) - { - res = true; - return true; - } - if (s.CompareNoCase(L"OFF") == 0 || s.Compare(L"-") == 0) - { - res = false; - return true; - } - return false; -} - -HRESULT SetBoolProperty(bool &dest, const PROPVARIANT &value) -{ - switch(value.vt) - { - case VT_EMPTY: - dest = true; - return S_OK; - case VT_BOOL: - dest = (value.boolVal != VARIANT_FALSE); - return S_OK; - /* - case VT_UI4: - dest = (value.ulVal != 0); - break; - */ - case VT_BSTR: - return StringToBool(value.bstrVal, dest) ? S_OK : E_INVALIDARG; - } - return E_INVALIDARG; -} - -int ParseStringToUInt32(const UString &srcString, UInt32 &number) -{ - const wchar_t *start = srcString; - const wchar_t *end; - UInt64 number64 = ConvertStringToUInt64(start, &end); - if (number64 > 0xFFFFFFFF) - { - number = 0; - return 0; - } - number = (UInt32)number64; - return (int)(end - start); -} - -HRESULT ParseMtProp(const UString &name, const PROPVARIANT &prop, UInt32 defaultNumThreads, UInt32 &numThreads) -{ - if (name.IsEmpty()) - { - switch(prop.vt) - { - case VT_UI4: - numThreads = prop.ulVal; - break; - default: - { - bool val; - RINOK(SetBoolProperty(val, prop)); - numThreads = (val ? defaultNumThreads : 1); - break; - } - } - } - else - { - UInt32 number; - int index = ParseStringToUInt32(name, number); - if (index != name.Length()) - return E_INVALIDARG; - numThreads = number; - } - return S_OK; -} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Common/ParseProperties.h b/desmume/src/windows/7z/CPP/7zip/Archive/Common/ParseProperties.h deleted file mode 100644 index c64fc1ea1..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Common/ParseProperties.h +++ /dev/null @@ -1,18 +0,0 @@ -// ParseProperties.h - -#ifndef __PARSEPROPERTIES_H -#define __PARSEPROPERTIES_H - -#include "Common/MyString.h" -#include "Common/Types.h" - -HRESULT ParsePropValue(const UString &name, const PROPVARIANT &prop, UInt32 &resValue); -HRESULT ParsePropDictionaryValue(const UString &srcStringSpec, UInt32 &dicSize); -HRESULT ParsePropDictionaryValue(const UString &name, const PROPVARIANT &prop, UInt32 &resValue); - -bool StringToBool(const UString &s, bool &res); -HRESULT SetBoolProperty(bool &dest, const PROPVARIANT &value); -int ParseStringToUInt32(const UString &srcString, UInt32 &number); -HRESULT ParseMtProp(const UString &name, const PROPVARIANT &prop, UInt32 defaultNumThreads, UInt32 &numThreads); - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Common/StdAfx.h b/desmume/src/windows/7z/CPP/7zip/Archive/Common/StdAfx.h deleted file mode 100644 index a4e617312..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Common/StdAfx.h +++ /dev/null @@ -1,9 +0,0 @@ -// StdAfx.h - -#ifndef __STDAFX_H -#define __STDAFX_H - -#include "../../../Common/MyWindows.h" -#include "../../../Common/NewHandler.h" - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/DllExports2.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/DllExports2.cpp deleted file mode 100644 index 7f4764654..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/DllExports2.cpp +++ /dev/null @@ -1,83 +0,0 @@ -// DLLExports.cpp - -#include "StdAfx.h" - -#include "../../Common/MyInitGuid.h" -#include "../../Common/ComTry.h" -#include "../../Common/Types.h" -#include "../../Windows/PropVariant.h" -#if defined(_WIN32) && defined(_7ZIP_LARGE_PAGES) -extern "C" -{ -#include "../../../C/Alloc.h" -} -#endif - -#include "IArchive.h" -#include "../ICoder.h" -#include "../IPassword.h" - -HINSTANCE g_hInstance; -#ifndef _UNICODE -#ifdef _WIN32 -bool g_IsNT = false; -static bool IsItWindowsNT() -{ - OSVERSIONINFO versionInfo; - versionInfo.dwOSVersionInfoSize = sizeof(versionInfo); - if (!::GetVersionEx(&versionInfo)) - return false; - return (versionInfo.dwPlatformId == VER_PLATFORM_WIN32_NT); -} -#endif -#endif - -//desmume 27-jun-09 - dont want this in a static library -//extern "C" -//BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID /*lpReserved*/) -//{ -// if (dwReason == DLL_PROCESS_ATTACH) -// { -// g_hInstance = hInstance; -// #ifndef _UNICODE -// #ifdef _WIN32 -// g_IsNT = IsItWindowsNT(); -// #endif -// #endif -// } -// return TRUE; -//} - -DEFINE_GUID(CLSID_CArchiveHandler, -0x23170F69, 0x40C1, 0x278A, 0x10, 0x00, 0x00, 0x01, 0x10, 0x00, 0x00, 0x00); - -static const UInt16 kDecodeId = 0x2790; - -DEFINE_GUID(CLSID_CCodec, -0x23170F69, 0x40C1, kDecodeId, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00); - -STDAPI CreateCoder(const GUID *clsid, const GUID *iid, void **outObject); -STDAPI CreateArchiver(const GUID *classID, const GUID *iid, void **outObject); - -STDAPI CreateObject(const GUID *clsid, const GUID *iid, void **outObject) -{ - // COM_TRY_BEGIN - *outObject = 0; - if (*iid == IID_ICompressCoder || *iid == IID_ICompressCoder2 || *iid == IID_ICompressFilter) - { - return CreateCoder(clsid, iid, outObject); - } - else - { - return CreateArchiver(clsid, iid, outObject); - } - // COM_TRY_END -} - -STDAPI SetLargePageMode() -{ - #if defined(_WIN32) && defined(_7ZIP_LARGE_PAGES) - SetLargePageSize(); - #endif - return S_OK; -} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipHandler.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipHandler.cpp deleted file mode 100644 index 01a5c9f99..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipHandler.cpp +++ /dev/null @@ -1,284 +0,0 @@ -// GZipHandler.cpp - -#include "StdAfx.h" - -#include "GZipHandler.h" - -#include "Common/Defs.h" -#include "Common/StringConvert.h" -#include "Common/ComTry.h" -#include "Windows/PropVariant.h" -#include "Windows/Time.h" - -#include "../../ICoder.h" -#include "../../Common/ProgressUtils.h" -#include "../../Common/CreateCoder.h" -#include "../Common/OutStreamWithCRC.h" - -using namespace NWindows; - -namespace NArchive { -namespace NGZip { - -static const CMethodId kMethodId_Deflate = 0x040108; - -const wchar_t *kHostOS[] = -{ - L"FAT", - L"AMIGA", - L"VMS", - L"Unix", - L"VM_CMS", - L"Atari", // what if it's a minix filesystem? [cjh] - L"HPFS", // filesystem used by OS/2 (and NT 3.x) - L"Mac", - L"Z_System", - L"CPM", - L"TOPS20", // pkzip 2.50 NTFS - L"NTFS", // filesystem used by Windows NT - L"QDOS ", // SMS/QDOS - L"Acorn", // Archimedes Acorn RISC OS - L"VFAT", // filesystem used by Windows 95, NT - L"MVS", - L"BeOS", // hybrid POSIX/database filesystem - // BeBOX or PowerMac - L"Tandem", - L"THEOS" -}; - -static const int kNumHostOSes = sizeof(kHostOS) / sizeof(kHostOS[0]); - -static const wchar_t *kUnknownOS = L"Unknown"; - -/* -enum // PropID -{ - kpidExtraIsPresent = kpidUserDefined, - kpidExtraFlags, - kpidIsText -}; -*/ - -STATPROPSTG kProps[] = -{ - { NULL, kpidPath, VT_BSTR}, - { NULL, kpidSize, VT_UI8}, - { NULL, kpidPackSize, VT_UI8}, - { NULL, kpidMTime, VT_FILETIME}, - // { NULL, kpidMethod, VT_UI1}, - { NULL, kpidHostOS, VT_BSTR}, - { NULL, kpidCRC, VT_UI4} - // { L"Extra", kpidExtraIsPresent, VT_BOOL} - // { L"Extra flags", kpidExtraFlags, VT_UI1}, - // { L"Is Text", kpidIsText, VT_BOOL}, -}; - -IMP_IInArchive_Props -IMP_IInArchive_ArcProps_NO - -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) -{ - *numItems = 1; - return S_OK; -} - -STDMETHODIMP CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value) -{ - COM_TRY_BEGIN - NWindows::NCOM::CPropVariant prop; - switch(propID) - { - case kpidPath: - if (m_Item.NameIsPresent()) - prop = MultiByteToUnicodeString(m_Item.Name, CP_ACP); - break; - case kpidMTime: - { - FILETIME utcTime; - if (m_Item.Time != 0) - { - NTime::UnixTimeToFileTime((UInt32)m_Item.Time, utcTime); - prop = utcTime; - } - else - { - // utcTime.dwLowDateTime = utcTime.dwHighDateTime = 0; - // prop = utcTime; - } - break; - } - case kpidSize: prop = UInt64(m_Item.UnPackSize32); break; - case kpidPackSize: prop = m_PackSize; break; - case kpidCommented: prop = m_Item.CommentIsPresent(); break; - case kpidHostOS: - prop = (m_Item.HostOS < kNumHostOSes) ? - kHostOS[m_Item.HostOS] : kUnknownOS; - break; - case kpidMethod: prop = m_Item.CompressionMethod; break; - case kpidCRC: prop = m_Item.FileCRC; break; - /* - case kpidExtraFlags: prop = m_Item.ExtraFlags; break; - case kpidIsText: prop = m_Item.IsText(); break; - case kpidExtraIsPresent: prop = m_Item.ExtraFieldIsPresent(); break; - */ - } - prop.Detach(value); - return S_OK; - COM_TRY_END -} - -STDMETHODIMP CHandler::Open(IInStream *inStream, - const UInt64 * /* maxCheckStartPosition */, - IArchiveOpenCallback * /* openArchiveCallback */) -{ - COM_TRY_BEGIN - try - { - CInArchive archive; - RINOK(inStream->Seek(0, STREAM_SEEK_CUR, &m_StreamStartPosition)); - RINOK(archive.ReadHeader(inStream, m_Item)); - m_DataOffset = archive.GetOffset(); - UInt64 newPosition; - RINOK(inStream->Seek(-8, STREAM_SEEK_END, &newPosition)); - m_PackSize = newPosition - (m_StreamStartPosition + m_DataOffset); - if (archive.ReadPostHeader(inStream, m_Item) != S_OK) - return S_FALSE; - m_Stream = inStream; - } - catch(...) - { - return S_FALSE; - } - return S_OK; - COM_TRY_END -} - -STDMETHODIMP CHandler::Close() -{ - m_Stream.Release(); - return S_OK; -} - -STDMETHODIMP CHandler::Extract(const UInt32* indices, UInt32 numItems, - Int32 _aTestMode, IArchiveExtractCallback *extractCallback) -{ - COM_TRY_BEGIN - bool allFilesMode = (numItems == UInt32(-1)); - if (!allFilesMode) - { - if (numItems == 0) - return S_OK; - if (numItems != 1) - return E_INVALIDARG; - if (indices[0] != 0) - return E_INVALIDARG; - } - - bool testMode = (_aTestMode != 0); - - extractCallback->SetTotal(m_PackSize); - - UInt64 currentTotalPacked = 0; - - RINOK(extractCallback->SetCompleted(¤tTotalPacked)); - CMyComPtr realOutStream; - Int32 askMode; - askMode = testMode ? NArchive::NExtract::NAskMode::kTest : - NArchive::NExtract::NAskMode::kExtract; - - RINOK(extractCallback->GetStream(0, &realOutStream, askMode)); - - if(!testMode && !realOutStream) - return S_OK; - - extractCallback->PrepareOperation(askMode); - - COutStreamWithCRC *outStreamSpec = new COutStreamWithCRC; - CMyComPtr outStream(outStreamSpec); - outStreamSpec->SetStream(realOutStream); - outStreamSpec->Init(); - realOutStream.Release(); - - CLocalProgress *lps = new CLocalProgress; - CMyComPtr progress = lps; - lps->Init(extractCallback, true); - - CMyComPtr deflateDecoder; - bool firstItem = true; - RINOK(m_Stream->Seek(m_StreamStartPosition, STREAM_SEEK_SET, NULL)); - Int32 opRes; - for (;;) - { - lps->InSize = currentTotalPacked; - lps->OutSize = outStreamSpec->GetSize(); - - CInArchive archive; - CItem item; - HRESULT result = archive.ReadHeader(m_Stream, item); - if (result != S_OK) - { - if (firstItem) - return E_FAIL; - opRes = NArchive::NExtract::NOperationResult::kOK; - break; - } - firstItem = false; - - UInt64 dataStartPos; - RINOK(m_Stream->Seek(0, STREAM_SEEK_CUR, &dataStartPos)); - - outStreamSpec->InitCRC(); - - if (item.CompressionMethod != NFileHeader::NCompressionMethod::kDeflate) - { - opRes = NArchive::NExtract::NOperationResult::kUnSupportedMethod; - break; - } - - if (!deflateDecoder) - { - RINOK(CreateCoder( - EXTERNAL_CODECS_VARS - kMethodId_Deflate, deflateDecoder, false)); - if (!deflateDecoder) - { - opRes = NArchive::NExtract::NOperationResult::kUnSupportedMethod; - break; - } - } - result = deflateDecoder->Code(m_Stream, outStream, NULL, NULL, progress); - if (result != S_OK) - { - if (result != S_FALSE) - return result; - opRes = NArchive::NExtract::NOperationResult::kDataError; - break; - } - - CMyComPtr getInStreamProcessedSize; - RINOK(deflateDecoder.QueryInterface(IID_ICompressGetInStreamProcessedSize, - &getInStreamProcessedSize)); - UInt64 packSize; - RINOK(getInStreamProcessedSize->GetInStreamProcessedSize(&packSize)); - UInt64 pos; - RINOK(m_Stream->Seek(dataStartPos + packSize, STREAM_SEEK_SET, &pos)); - - currentTotalPacked = pos - m_StreamStartPosition; - - CItem postItem; - if (archive.ReadPostHeader(m_Stream, postItem) != S_OK) - return E_FAIL; - if((outStreamSpec->GetCRC() != postItem.FileCRC)) - { - opRes = NArchive::NExtract::NOperationResult::kCRCError; - break; - } - } - outStream.Release(); - return extractCallback->SetOperationResult(opRes); - COM_TRY_END -} - -IMPL_ISetCompressCodecsInfo - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipHandler.h b/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipHandler.h deleted file mode 100644 index 31f5a430f..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipHandler.h +++ /dev/null @@ -1,65 +0,0 @@ -// GZip/Handler.h - -#ifndef __GZIP_HANDLER_H -#define __GZIP_HANDLER_H - -#include "Common/MyCom.h" - -#include "../IArchive.h" - -#include "../../Common/CreateCoder.h" - -#include "GZipIn.h" -#include "GZipUpdate.h" - -namespace NArchive { -namespace NGZip { - -class CHandler: - public IInArchive, - public IOutArchive, - public ISetProperties, - PUBLIC_ISetCompressCodecsInfo - public CMyUnknownImp -{ -public: - MY_QUERYINTERFACE_BEGIN2(IInArchive) - MY_QUERYINTERFACE_ENTRY(IOutArchive) - MY_QUERYINTERFACE_ENTRY(ISetProperties) - QUERY_ENTRY_ISetCompressCodecsInfo - MY_QUERYINTERFACE_END - MY_ADDREF_RELEASE - - INTERFACE_IInArchive(;) -#ifndef EXTRACT_ONLY - INTERFACE_IOutArchive(;) - - STDMETHOD(SetProperties)(const wchar_t **names, const PROPVARIANT *values, Int32 numProperties); -#endif - - DECL_ISetCompressCodecsInfo - - CHandler() { InitMethodProperties(); } - -private: - NArchive::NGZip::CItem m_Item; - UInt64 m_StreamStartPosition; - UInt64 m_DataOffset; - UInt64 m_PackSize; - CMyComPtr m_Stream; - CCompressionMethodMode m_Method; - UInt32 m_Level; - - DECL_EXTERNAL_CODECS_VARS - - void InitMethodProperties() - { - m_Method.NumMatchFinderCyclesDefined = false; - m_Level = m_Method.NumPasses = m_Method.NumFastBytes = - m_Method.NumMatchFinderCycles = m_Method.Algo = 0xFFFFFFFF; - } -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipHeader.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipHeader.cpp deleted file mode 100644 index 508d6bd5b..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipHeader.cpp +++ /dev/null @@ -1,20 +0,0 @@ -// Archive/GZip/Header.h - -#include "StdAfx.h" - -#include "GZipHeader.h" - -namespace NArchive { -namespace NGZip { - -extern UInt16 kSignature = 0x8B1F + 1; - -class CMarkersInitializer -{ -public: - CMarkersInitializer() - { kSignature--; } -} g_MarkerInitializer; - -}} - diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipHeader.h b/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipHeader.h deleted file mode 100644 index 3e76ad6d2..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipHeader.h +++ /dev/null @@ -1,85 +0,0 @@ -// Archive/GZip/Header.h - -#ifndef __ARCHIVE_GZIP_HEADER_H -#define __ARCHIVE_GZIP_HEADER_H - -#include "Common/Types.h" - -namespace NArchive { -namespace NGZip { - -extern UInt16 kSignature; -static const UInt32 kSignatureSize = 2; - -namespace NFileHeader -{ - /* - struct CBlock - { - UInt16 Id; - Byte CompressionMethod; - Byte Flags; - UInt32 Time; - Byte ExtraFlags; - Byte HostOS; - }; - */ - - namespace NFlags - { - const int kDataIsText = 1 << 0; - const int kHeaderCRCIsPresent = 1 << 1; - const int kExtraIsPresent = 1 << 2; - const int kNameIsPresent = 1 << 3; - const int kComentIsPresent = 1 << 4; - } - - namespace NExtraFlags - { - enum EEnum - { - kMaximum = 2, - kFastest = 4 - }; - } - - namespace NCompressionMethod - { - const Byte kDeflate = 8; - } - - namespace NHostOS - { - enum EEnum - { - kFAT = 0, // filesystem used by MS-DOS, OS/2, Win32 - // pkzip 2.50 (FAT / VFAT / FAT32 file systems) - kAMIGA = 1, - kVMS = 2, // VAX/VMS - kUnix = 3, - kVM_CMS = 4, - kAtari = 5, // what if it's a minix filesystem? [cjh] - kHPFS = 6, // filesystem used by OS/2 (and NT 3.x) - kMac = 7, - kZ_System = 8, - kCPM = 9, - kTOPS20 = 10, // pkzip 2.50 NTFS - kNTFS = 11, // filesystem used by Windows NT - kQDOS = 12, // SMS/QDOS - kAcorn = 13, // Archimedes Acorn RISC OS - kVFAT = 14, // filesystem used by Windows 95, NT - kMVS = 15, - kBeOS = 16, // hybrid POSIX/database filesystem - // BeBOX or PowerMac - kTandem = 17, - kTHEOS = 18, - - kUnknown = 255 - }; - const int kNumHostSystems = 19; - } -} - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipIn.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipIn.cpp deleted file mode 100644 index b29f10e08..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipIn.cpp +++ /dev/null @@ -1,119 +0,0 @@ -// Archive/GZipIn.cpp - -#include "StdAfx.h" - -#include "GZipIn.h" - -#include "Common/Defs.h" -#include "Common/MyCom.h" -#include "Windows/Defs.h" - -#include "../../Common/StreamUtils.h" - -extern "C" -{ - #include "../../../../C/7zCrc.h" -} - -namespace NArchive { -namespace NGZip { - -HRESULT CInArchive::ReadBytes(ISequentialInStream *inStream, void *data, UInt32 size) -{ - RINOK(ReadStream_FALSE(inStream, data, size)); - m_Position += size; - return S_OK; -} - -HRESULT CInArchive::ReadByte(ISequentialInStream *inStream, Byte &value, UInt32 &crc) -{ - RINOK(ReadBytes(inStream, &value, 1)); - crc = CRC_UPDATE_BYTE(crc, value); - return S_OK; -} - -HRESULT CInArchive::ReadUInt16(ISequentialInStream *inStream, UInt16 &value, UInt32 &crc) -{ - value = 0; - for (int i = 0; i < 2; i++) - { - Byte b; - RINOK(ReadByte(inStream, b, crc)); - value |= (UInt16(b) << (8 * i)); - } - return S_OK; -} - -HRESULT CInArchive::ReadUInt32(ISequentialInStream *inStream, UInt32 &value, UInt32 &crc) -{ - value = 0; - for (int i = 0; i < 4; i++) - { - Byte b; - RINOK(ReadByte(inStream, b, crc)); - value |= (UInt32(b) << (8 * i)); - } - return S_OK; -} - -HRESULT CInArchive::ReadZeroTerminatedString(ISequentialInStream *inStream, AString &resString, UInt32 &crc) -{ - resString.Empty(); - for (;;) - { - Byte c; - RINOK(ReadByte(inStream, c, crc)); - if (c == 0) - return S_OK; - resString += char(c); - } -} - -HRESULT CInArchive::ReadHeader(ISequentialInStream *inStream, CItem &item) -{ - item.Clear(); - m_Position = 0; - - UInt16 signature; - UInt32 crc = CRC_INIT_VAL;; - RINOK(ReadUInt16(inStream, signature, crc)); - if (signature != kSignature) - return S_FALSE; - - RINOK(ReadByte(inStream, item.CompressionMethod, crc)); - RINOK(ReadByte(inStream, item.Flags, crc)); - RINOK(ReadUInt32(inStream, item.Time, crc)); - RINOK(ReadByte(inStream, item.ExtraFlags, crc)); - RINOK(ReadByte(inStream, item.HostOS, crc)); - - if (item.ExtraFieldIsPresent()) - { - UInt16 extraSize; - RINOK(ReadUInt16(inStream, extraSize, crc)); - item.Extra.SetCapacity(extraSize); - RINOK(ReadBytes(inStream, item.Extra, extraSize)); - crc = CrcUpdate(crc, item.Extra, extraSize); - } - if (item.NameIsPresent()) - RINOK(ReadZeroTerminatedString(inStream, item.Name, crc)); - if (item.CommentIsPresent()) - RINOK(ReadZeroTerminatedString(inStream, item.Comment, crc)); - if (item.HeaderCRCIsPresent()) - { - UInt16 headerCRC; - UInt32 dummy = 0; - RINOK(ReadUInt16(inStream, headerCRC, dummy)); - if ((UInt16)CRC_GET_DIGEST(crc) != headerCRC) - return S_FALSE; - } - return S_OK; -} - -HRESULT CInArchive::ReadPostHeader(ISequentialInStream *inStream, CItem &item) -{ - UInt32 dummy = 0; - RINOK(ReadUInt32(inStream, item.FileCRC, dummy)); - return ReadUInt32(inStream, item.UnPackSize32, dummy); -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipIn.h b/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipIn.h deleted file mode 100644 index 1204d667c..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipIn.h +++ /dev/null @@ -1,30 +0,0 @@ -// Archive/GZipIn.h - -#ifndef __ARCHIVE_GZIP_IN_H -#define __ARCHIVE_GZIP_IN_H - -#include "GZipHeader.h" -#include "GZipItem.h" -#include "../../IStream.h" - -namespace NArchive { -namespace NGZip { - -class CInArchive -{ - UInt64 m_Position; - - HRESULT ReadBytes(ISequentialInStream *inStream, void *data, UInt32 size); - HRESULT ReadZeroTerminatedString(ISequentialInStream *inStream, AString &resString, UInt32 &crc); - HRESULT ReadByte(ISequentialInStream *inStream, Byte &value, UInt32 &crc); - HRESULT ReadUInt16(ISequentialInStream *inStream, UInt16 &value, UInt32 &crc); - HRESULT ReadUInt32(ISequentialInStream *inStream, UInt32 &value, UInt32 &crc); -public: - HRESULT ReadHeader(ISequentialInStream *inStream, CItem &item); - HRESULT ReadPostHeader(ISequentialInStream *inStream, CItem &item); - UInt64 GetOffset() const { return m_Position; } -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipItem.h b/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipItem.h deleted file mode 100644 index 50eaef8a8..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipItem.h +++ /dev/null @@ -1,59 +0,0 @@ -// Archive/GZipItem.h - -#ifndef __ARCHIVE_GZIP_ITEM_H -#define __ARCHIVE_GZIP_ITEM_H - -#include "Common/Types.h" -#include "Common/MyString.h" -#include "Common/Buffer.h" - -namespace NArchive { -namespace NGZip { - -class CItem -{ -private: - bool TestFlag(Byte flag) const { return ((Flags & flag) != 0); } -public: - Byte CompressionMethod; - Byte Flags; - UInt32 Time; - Byte ExtraFlags; - Byte HostOS; - UInt32 FileCRC; - UInt32 UnPackSize32; - - AString Name; - AString Comment; - CByteBuffer Extra; - - bool IsText() const - { return TestFlag(NFileHeader::NFlags::kDataIsText); } - bool HeaderCRCIsPresent() const - { return TestFlag(NFileHeader::NFlags::kHeaderCRCIsPresent); } - bool ExtraFieldIsPresent() const - { return TestFlag(NFileHeader::NFlags::kExtraIsPresent); } - bool NameIsPresent() const - { return TestFlag(NFileHeader::NFlags::kNameIsPresent); } - bool CommentIsPresent() const - { return TestFlag(NFileHeader::NFlags::kComentIsPresent); } - - void SetNameIsPresentFlag(bool nameIsPresent) - { - if (nameIsPresent) - Flags |= NFileHeader::NFlags::kNameIsPresent; - else - Flags &= (~NFileHeader::NFlags::kNameIsPresent); - } - - void Clear() - { - Name.Empty(); - Comment.Empty();; - Extra.SetCapacity(0); - } -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipRegister.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipRegister.cpp deleted file mode 100644 index 0c1065088..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipRegister.cpp +++ /dev/null @@ -1,18 +0,0 @@ -// GZipRegister.cpp - -#include "StdAfx.h" - -#include "../../Common/RegisterArc.h" - -#include "GZipHandler.h" -static IInArchive *CreateArc() { return new NArchive::NGZip::CHandler; } -#ifndef EXTRACT_ONLY -static IOutArchive *CreateArcOut() { return new NArchive::NGZip::CHandler; } -#else -#define CreateArcOut 0 -#endif - -static CArcInfo g_ArcInfo = - { L"GZip", L"gz gzip tgz tpz", L"* * .tar .tar", 0xEF, { 0x1F, 0x8B, 8 }, 3, true, CreateArc, CreateArcOut }; - -REGISTER_ARC(GZip) diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipUpdate.h b/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipUpdate.h deleted file mode 100644 index 59115ba2d..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipUpdate.h +++ /dev/null @@ -1,39 +0,0 @@ -// GZip/Update.h - -#ifndef __GZIP_UPDATE_H -#define __GZIP_UPDATE_H - -#include "../IArchive.h" - -#include "../../Common/CreateCoder.h" - -#ifndef EXTRACT_ONLY -#include "GZipOut.h" -#endif -#include "GZipItem.h" - -namespace NArchive { -namespace NGZip { - -struct CCompressionMethodMode -{ - UInt32 NumPasses; - UInt32 NumFastBytes; - UInt32 Algo; - bool NumMatchFinderCyclesDefined; - UInt32 NumMatchFinderCycles; -}; - -HRESULT UpdateArchive( - DECL_EXTERNAL_CODECS_LOC_VARS - IInStream *inStream, - UInt64 unpackSize, - ISequentialOutStream *outStream, - const CItem &newItem, - const CCompressionMethodMode &compressionMethod, - int indexInClient, - IArchiveUpdateCallback *updateCallback); - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/GZip/StdAfx.h b/desmume/src/windows/7z/CPP/7zip/Archive/GZip/StdAfx.h deleted file mode 100644 index 83fdd22d5..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/GZip/StdAfx.h +++ /dev/null @@ -1,8 +0,0 @@ -// StdAfx.h - -#ifndef __STDAFX_H -#define __STDAFX_H - -#include "../../../Common/MyWindows.h" - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/IArchive.h b/desmume/src/windows/7z/CPP/7zip/Archive/IArchive.h deleted file mode 100644 index 2ab476324..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/IArchive.h +++ /dev/null @@ -1,237 +0,0 @@ -// IArchive.h - -#ifndef __IARCHIVE_H -#define __IARCHIVE_H - -#include "../IStream.h" -#include "../IProgress.h" -#include "../PropID.h" - -#define ARCHIVE_INTERFACE_SUB(i, base, x) DECL_INTERFACE_SUB(i, base, 6, x) -#define ARCHIVE_INTERFACE(i, x) ARCHIVE_INTERFACE_SUB(i, IUnknown, x) - -namespace NFileTimeType -{ - enum EEnum - { - kWindows, - kUnix, - kDOS - }; -} - -namespace NArchive -{ - enum - { - kName = 0, - kClassID, - kExtension, - kAddExtension, - kUpdate, - kKeepName, - kStartSignature, - kFinishSignature, - kAssociate - }; - - namespace NExtract - { - namespace NAskMode - { - enum - { - kExtract = 0, - kTest, - kSkip - }; - } - namespace NOperationResult - { - enum - { - kOK = 0, - kUnSupportedMethod, - kDataError, - kCRCError - }; - } - } - namespace NUpdate - { - namespace NOperationResult - { - enum - { - kOK = 0, - kError - }; - } - } -} - -#define INTERFACE_IArchiveOpenCallback(x) \ - STDMETHOD(SetTotal)(const UInt64 *files, const UInt64 *bytes) x; \ - STDMETHOD(SetCompleted)(const UInt64 *files, const UInt64 *bytes) x; \ - -ARCHIVE_INTERFACE(IArchiveOpenCallback, 0x10) -{ - INTERFACE_IArchiveOpenCallback(PURE); -}; - - -#define INTERFACE_IArchiveExtractCallback(x) \ - INTERFACE_IProgress(x) \ - /* GetStream OUT: S_OK - OK, S_FALSE - skeep this file */ \ - STDMETHOD(GetStream)(UInt32 index, ISequentialOutStream **outStream, Int32 askExtractMode) x; \ - STDMETHOD(PrepareOperation)(Int32 askExtractMode) x; \ - STDMETHOD(SetOperationResult)(Int32 resultEOperationResult) x; \ - -ARCHIVE_INTERFACE_SUB(IArchiveExtractCallback, IProgress, 0x20) -{ - INTERFACE_IArchiveExtractCallback(PURE) -}; - - -#define INTERFACE_IArchiveOpenVolumeCallback(x) \ - STDMETHOD(GetProperty)(PROPID propID, PROPVARIANT *value) x; \ - STDMETHOD(GetStream)(const wchar_t *name, IInStream **inStream) x; \ - -ARCHIVE_INTERFACE(IArchiveOpenVolumeCallback, 0x30) -{ - INTERFACE_IArchiveOpenVolumeCallback(PURE); -}; - - -ARCHIVE_INTERFACE(IInArchiveGetStream, 0x40) -{ - STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream) PURE; -}; - - -ARCHIVE_INTERFACE(IArchiveOpenSetSubArchiveName, 0x50) -{ - STDMETHOD(SetSubArchiveName)(const wchar_t *name) PURE; -}; - - -/* -IInArchive::Extract: - indices must be sorted - numItems = 0xFFFFFFFF means "all files" - testMode != 0 means "test files without writing to outStream" -*/ - -#define INTERFACE_IInArchive(x) \ - STDMETHOD(Open)(IInStream *stream, const UInt64 *maxCheckStartPosition, IArchiveOpenCallback *openArchiveCallback) x; \ - STDMETHOD(Close)() x; \ - STDMETHOD(GetNumberOfItems)(UInt32 *numItems) x; \ - STDMETHOD(GetProperty)(UInt32 index, PROPID propID, PROPVARIANT *value) x; \ - STDMETHOD(Extract)(const UInt32* indices, UInt32 numItems, Int32 testMode, IArchiveExtractCallback *extractCallback) x; \ - STDMETHOD(GetArchiveProperty)(PROPID propID, PROPVARIANT *value) x; \ - STDMETHOD(GetNumberOfProperties)(UInt32 *numProperties) x; \ - STDMETHOD(GetPropertyInfo)(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType) x; \ - STDMETHOD(GetNumberOfArchiveProperties)(UInt32 *numProperties) x; \ - STDMETHOD(GetArchivePropertyInfo)(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType) x; - -ARCHIVE_INTERFACE(IInArchive, 0x60) -{ - INTERFACE_IInArchive(PURE) - virtual ~IInArchive() {} -}; - - -#define INTERFACE_IArchiveUpdateCallback(x) \ - INTERFACE_IProgress(x); \ - STDMETHOD(GetUpdateItemInfo)(UInt32 index, \ - Int32 *newData, /*1 - new data, 0 - old data */ \ - Int32 *newProperties, /* 1 - new properties, 0 - old properties */ \ - UInt32 *indexInArchive /* -1 if there is no in archive, or if doesn't matter */ \ - ) x; \ - STDMETHOD(GetProperty)(UInt32 index, PROPID propID, PROPVARIANT *value) x; \ - STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **inStream) x; \ - STDMETHOD(SetOperationResult)(Int32 operationResult) x; \ - -ARCHIVE_INTERFACE_SUB(IArchiveUpdateCallback, IProgress, 0x80) -{ - INTERFACE_IArchiveUpdateCallback(PURE); -}; - -#define INTERFACE_IArchiveUpdateCallback2(x) \ - INTERFACE_IArchiveUpdateCallback(x) \ - STDMETHOD(GetVolumeSize)(UInt32 index, UInt64 *size) x; \ - STDMETHOD(GetVolumeStream)(UInt32 index, ISequentialOutStream **volumeStream) x; \ - -ARCHIVE_INTERFACE_SUB(IArchiveUpdateCallback2, IArchiveUpdateCallback, 0x82) -{ - INTERFACE_IArchiveUpdateCallback2(PURE); -}; - - -#ifndef EXTRACT_ONLY -#define INTERFACE_IOutArchive(x) \ - STDMETHOD(UpdateItems)(ISequentialOutStream *outStream, UInt32 numItems, IArchiveUpdateCallback *updateCallback) x; \ - STDMETHOD(GetFileTimeType)(UInt32 *type) x; -#else -#define INTERFACE_IOutArchive(x) -#endif - -ARCHIVE_INTERFACE(IOutArchive, 0xA0) -{ -#ifndef EXTRACT_ONLY - INTERFACE_IOutArchive(PURE) -#endif -}; - - -ARCHIVE_INTERFACE(ISetProperties, 0x03) -{ -#ifndef EXTRACT_ONLY - STDMETHOD(SetProperties)(const wchar_t **names, const PROPVARIANT *values, Int32 numProperties) PURE; -#endif -}; - - -#define IMP_IInArchive_GetProp(k) \ - (UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType) \ - { if(index >= sizeof(k) / sizeof(k[0])) return E_INVALIDARG; \ - const STATPROPSTG &srcItem = k[index]; \ - *propID = srcItem.propid; *varType = srcItem.vt; *name = 0; return S_OK; } \ - -#define IMP_IInArchive_GetProp_WITH_NAME(k) \ - (UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType) \ - { if(index >= sizeof(k) / sizeof(k[0])) return E_INVALIDARG; \ - const STATPROPSTG &srcItem = k[index]; \ - *propID = srcItem.propid; *varType = srcItem.vt; \ - if (srcItem.lpwstrName == 0) *name = 0; else *name = ::SysAllocString(srcItem.lpwstrName); return S_OK; } \ - -#define IMP_IInArchive_Props \ - STDMETHODIMP CHandler::GetNumberOfProperties(UInt32 *numProperties) \ - { *numProperties = sizeof(kProps) / sizeof(kProps[0]); return S_OK; } \ - STDMETHODIMP CHandler::GetPropertyInfo IMP_IInArchive_GetProp(kProps) - -#define IMP_IInArchive_Props_WITH_NAME \ - STDMETHODIMP CHandler::GetNumberOfProperties(UInt32 *numProperties) \ - { *numProperties = sizeof(kProps) / sizeof(kProps[0]); return S_OK; } \ - STDMETHODIMP CHandler::GetPropertyInfo IMP_IInArchive_GetProp_WITH_NAME(kProps) - - -#define IMP_IInArchive_ArcProps \ - STDMETHODIMP CHandler::GetNumberOfArchiveProperties(UInt32 *numProperties) \ - { *numProperties = sizeof(kArcProps) / sizeof(kArcProps[0]); return S_OK; } \ - STDMETHODIMP CHandler::GetArchivePropertyInfo IMP_IInArchive_GetProp(kArcProps) - -#define IMP_IInArchive_ArcProps_WITH_NAME \ - STDMETHODIMP CHandler::GetNumberOfArchiveProperties(UInt32 *numProperties) \ - { *numProperties = sizeof(kArcProps) / sizeof(kArcProps[0]); return S_OK; } \ - STDMETHODIMP CHandler::GetArchivePropertyInfo IMP_IInArchive_GetProp_WITH_NAME(kArcProps) - -#define IMP_IInArchive_ArcProps_NO \ - STDMETHODIMP CHandler::GetNumberOfArchiveProperties(UInt32 *numProperties) \ - { *numProperties = 0; return S_OK; } \ - STDMETHODIMP CHandler::GetArchivePropertyInfo(UInt32, BSTR *, PROPID *, VARTYPE *) \ - { return E_NOTIMPL; } \ - STDMETHODIMP CHandler::GetArchiveProperty(PROPID, PROPVARIANT *value) \ - { value->vt = VT_EMPTY; return S_OK; } - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhCRC.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhCRC.cpp deleted file mode 100644 index 0afeb7102..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhCRC.cpp +++ /dev/null @@ -1,43 +0,0 @@ -// LzhCRC.cpp - -#include "StdAfx.h" - -#include "LzhCRC.h" - -namespace NArchive { -namespace NLzh { - -static const UInt16 kCRCPoly = 0xA001; - -UInt16 CCRC::Table[256]; - -void CCRC::InitTable() -{ - for (UInt32 i = 0; i < 256; i++) - { - UInt32 r = i; - for (int j = 0; j < 8; j++) - if (r & 1) - r = (r >> 1) ^ kCRCPoly; - else - r >>= 1; - CCRC::Table[i] = (UInt16)r; - } -} - -class CCRCTableInit -{ -public: - CCRCTableInit() { CCRC::InitTable(); } -} g_CRCTableInit; - -void CCRC::Update(const void *data, size_t size) -{ - UInt16 v = _value; - const Byte *p = (const Byte *)data; - for (; size > 0; size--, p++) - v = (UInt16)(Table[((Byte)(v)) ^ *p] ^ (v >> 8)); - _value = v; -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhCRC.h b/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhCRC.h deleted file mode 100644 index aaa647baf..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhCRC.h +++ /dev/null @@ -1,27 +0,0 @@ -// LzhCRC.h - -#ifndef __LZH_CRC_H -#define __LZH_CRC_H - -#include -#include "Common/Types.h" - -namespace NArchive { -namespace NLzh { - -class CCRC -{ - UInt16 _value; -public: - static UInt16 Table[256]; - static void InitTable(); - - CCRC(): _value(0){}; - void Init() { _value = 0; } - void Update(const void *data, size_t size); - UInt16 GetDigest() const { return _value; } -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhHandler.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhHandler.cpp deleted file mode 100644 index b15ffd1bc..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhHandler.cpp +++ /dev/null @@ -1,387 +0,0 @@ -// LzhHandler.cpp - -#include "StdAfx.h" - -#include "Common/ComTry.h" -#include "Common/Defs.h" -#include "Common/StringConvert.h" - -#include "Windows/PropVariant.h" -#include "Windows/Time.h" - -#include "LzhHandler.h" -#include "LzhOutStreamWithCRC.h" - -#include "../../ICoder.h" - -#include "../../Common/LimitedStreams.h" -#include "../../Common/ProgressUtils.h" - -#include "../../Compress/CopyCoder.h" -#include "../../Compress/LzhDecoder.h" - -#include "../Common/ItemNameUtils.h" - -using namespace NWindows; -using namespace NTime; - -namespace NArchive { -namespace NLzh{ - -struct COsPair -{ - Byte Id; - const wchar_t *Name; -}; - -COsPair g_OsPairs[] = -{ - { 'M', L"MS-DOS" }, - { '2', L"OS/2" }, - { '9', L"OS9" }, - { 'K', L"OS/68K" }, - { '3', L"OS/386" }, - { 'H', L"HUMAN" }, - { 'U', L"UNIX" }, - { 'C', L"CP/M" }, - { 'F', L"FLEX" }, - { 'm', L"Mac" }, - { 'R', L"Runser" }, - { 'T', L"TownsOS" }, - { 'X', L"XOSK" }, - { 'w', L"Windows95" }, - { 'W', L"WindowsNT" }, - { 0, L"MS-DOS" }, - { 'J', L"Java VM" } -}; - -const wchar_t *kUnknownOS = L"Unknown"; - -const int kNumHostOSes = sizeof(g_OsPairs) / sizeof(g_OsPairs[0]); - -static const wchar_t *GetOS(Byte osId) -{ - for (int i = 0; i < kNumHostOSes; i++) - if (g_OsPairs[i].Id == osId) - return g_OsPairs[i].Name; - return kUnknownOS; -}; - -STATPROPSTG kProps[] = -{ - { NULL, kpidPath, VT_BSTR}, - { NULL, kpidIsDir, VT_BOOL}, - { NULL, kpidSize, VT_UI8}, - { NULL, kpidPackSize, VT_UI8}, - { NULL, kpidMTime, VT_FILETIME}, - { NULL, kpidAttrib, VT_UI4}, - - // { NULL, kpidCommented, VT_BOOL}, - - { NULL, kpidCRC, VT_UI4}, - - { NULL, kpidMethod, VT_UI1}, - { NULL, kpidHostOS, VT_BSTR} - -}; - -IMP_IInArchive_Props -IMP_IInArchive_ArcProps_NO - -CHandler::CHandler() {} - -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) -{ - *numItems = _items.Size(); - return S_OK; -} - -STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) -{ - COM_TRY_BEGIN - NWindows::NCOM::CPropVariant prop; - const CItemEx &item = _items[index]; - switch(propID) - { - case kpidPath: - { - UString s = NItemName::WinNameToOSName(MultiByteToUnicodeString(item.GetName(), CP_OEMCP)); - if (!s.IsEmpty()) - { - if (s[s.Length() - 1] == WCHAR_PATH_SEPARATOR) - s.Delete(s.Length() - 1); - prop = s; - } - break; - } - case kpidIsDir: prop = item.IsDir(); break; - case kpidSize: prop = item.Size; break; - case kpidPackSize: prop = item.PackSize; break; - case kpidCRC: prop = (UInt32)item.CRC; break; - case kpidHostOS: prop = GetOS(item.OsId); break; - case kpidMTime: - { - FILETIME utcFileTime; - UInt32 unixTime; - if (item.GetUnixTime(unixTime)) - NTime::UnixTimeToFileTime(unixTime, utcFileTime); - else - { - FILETIME localFileTime; - if (DosTimeToFileTime(item.ModifiedTime, localFileTime)) - { - if (!LocalFileTimeToFileTime(&localFileTime, &utcFileTime)) - utcFileTime.dwHighDateTime = utcFileTime.dwLowDateTime = 0; - } - else - utcFileTime.dwHighDateTime = utcFileTime.dwLowDateTime = 0; - } - prop = utcFileTime; - break; - } - /* - case kpidAttrib: prop = (UInt32)item.Attributes; break; - case kpidCommented: prop = item.IsCommented(); break; - */ - case kpidMethod: - { - wchar_t method2[kMethodIdSize + 1]; - method2[kMethodIdSize] = 0; - for (int i = 0; i < kMethodIdSize; i++) - method2[i] = item.Method[i]; - prop = method2; - break; - } - } - prop.Detach(value); - return S_OK; - COM_TRY_END -} - -/* -class CProgressImp: public CProgressVirt -{ -public: - CMyComPtr Callback; - STDMETHOD(SetCompleted)(const UInt64 *numFiles); -}; - -STDMETHODIMP CProgressImp::SetCompleted(const UInt64 *numFiles) -{ - if (Callback) - return Callback->SetCompleted(numFiles, NULL); - return S_OK; -} -*/ - -STDMETHODIMP CHandler::Open(IInStream *stream, - const UInt64 * /* maxCheckStartPosition */, IArchiveOpenCallback *callback) -{ - COM_TRY_BEGIN - try - { - _items.Clear(); - CInArchive archive; - - UInt64 endPos = 0; - bool needSetTotal = true; - - if (callback != NULL) - { - RINOK(stream->Seek(0, STREAM_SEEK_END, &endPos)); - RINOK(stream->Seek(0, STREAM_SEEK_SET, NULL)); - } - - RINOK(archive.Open(stream)); - for (;;) - { - CItemEx item; - bool filled; - HRESULT result = archive.GetNextItem(filled, item); - if (result == S_FALSE) - return S_FALSE; - if (result != S_OK) - return S_FALSE; - if (!filled) - break; - _items.Add(item); - archive.Skeep(item.PackSize); - if (callback != NULL) - { - if (needSetTotal) - { - RINOK(callback->SetTotal(NULL, &endPos)); - needSetTotal = false; - } - if (_items.Size() % 100 == 0) - { - UInt64 numFiles = _items.Size(); - UInt64 numBytes = item.DataPosition; - RINOK(callback->SetCompleted(&numFiles, &numBytes)); - } - } - } - if (_items.IsEmpty()) - return S_FALSE; - - _stream = stream; - } - catch(...) - { - return S_FALSE; - } - COM_TRY_END - return S_OK; -} - -STDMETHODIMP CHandler::Close() -{ - _items.Clear(); - _stream.Release(); - return S_OK; -} - - - -////////////////////////////////////// -// CHandler::DecompressItems - -STDMETHODIMP CHandler::Extract(const UInt32* indices, UInt32 numItems, - Int32 testModeSpec, IArchiveExtractCallback *extractCallback) -{ - COM_TRY_BEGIN - bool testMode = (testModeSpec != 0); - UInt64 totalUnPacked = 0, totalPacked = 0; - bool allFilesMode = (numItems == UInt32(-1)); - if (allFilesMode) - numItems = _items.Size(); - if(numItems == 0) - return S_OK; - UInt32 i; - for(i = 0; i < numItems; i++) - { - const CItemEx &item = _items[allFilesMode ? i : indices[i]]; - totalUnPacked += item.Size; - totalPacked += item.PackSize; - } - extractCallback->SetTotal(totalUnPacked); - - UInt64 currentTotalUnPacked = 0, currentTotalPacked = 0; - UInt64 currentItemUnPacked, currentItemPacked; - - NCompress::NLzh::NDecoder::CCoder *lzhDecoderSpec = 0; - CMyComPtr lzhDecoder; - CMyComPtr lzh1Decoder; - CMyComPtr arj2Decoder; - - NCompress::CCopyCoder *copyCoderSpec = new NCompress::CCopyCoder(); - CMyComPtr copyCoder = copyCoderSpec; - - CLocalProgress *lps = new CLocalProgress; - CMyComPtr progress = lps; - lps->Init(extractCallback, false); - - CLimitedSequentialInStream *streamSpec = new CLimitedSequentialInStream; - CMyComPtr inStream(streamSpec); - streamSpec->SetStream(_stream); - - for(i = 0; i < numItems; i++, currentTotalUnPacked += currentItemUnPacked, - currentTotalPacked += currentItemPacked) - { - currentItemUnPacked = 0; - currentItemPacked = 0; - - lps->InSize = currentTotalPacked; - lps->OutSize = currentTotalUnPacked; - RINOK(lps->SetCur()); - - CMyComPtr realOutStream; - Int32 askMode; - askMode = testMode ? NExtract::NAskMode::kTest : - NExtract::NAskMode::kExtract; - Int32 index = allFilesMode ? i : indices[i]; - const CItemEx &item = _items[index]; - RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); - - if (item.IsDir()) - { - // if (!testMode) - { - RINOK(extractCallback->PrepareOperation(askMode)); - RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); - } - continue; - } - - if (!testMode && (!realOutStream)) - continue; - - RINOK(extractCallback->PrepareOperation(askMode)); - currentItemUnPacked = item.Size; - currentItemPacked = item.PackSize; - - { - COutStreamWithCRC *outStreamSpec = new COutStreamWithCRC; - CMyComPtr outStream(outStreamSpec); - outStreamSpec->Init(realOutStream); - realOutStream.Release(); - - UInt64 pos; - _stream->Seek(item.DataPosition, STREAM_SEEK_SET, &pos); - - streamSpec->Init(item.PackSize); - - HRESULT result = S_OK; - Int32 opRes = NExtract::NOperationResult::kOK; - - if (item.IsCopyMethod()) - { - result = copyCoder->Code(inStream, outStream, NULL, NULL, progress); - if (result == S_OK && copyCoderSpec->TotalSize != item.PackSize) - result = S_FALSE; - } - else if (item.IsLh4GroupMethod()) - { - if (!lzhDecoder) - { - lzhDecoderSpec = new NCompress::NLzh::NDecoder::CCoder; - lzhDecoder = lzhDecoderSpec; - } - lzhDecoderSpec->SetDictionary(item.GetNumDictBits()); - result = lzhDecoder->Code(inStream, outStream, NULL, ¤tItemUnPacked, progress); - } - /* - else if (item.IsLh1GroupMethod()) - { - if (!lzh1Decoder) - { - lzh1DecoderSpec = new NCompress::NLzh1::NDecoder::CCoder; - lzh1Decoder = lzh1DecoderSpec; - } - lzh1DecoderSpec->SetDictionary(item.GetNumDictBits()); - result = lzh1Decoder->Code(inStream, outStream, NULL, ¤tItemUnPacked, progress); - } - */ - else - opRes = NExtract::NOperationResult::kUnSupportedMethod; - - if (opRes == NExtract::NOperationResult::kOK) - { - if (result == S_FALSE) - opRes = NExtract::NOperationResult::kDataError; - else - { - RINOK(result); - if (outStreamSpec->GetCRC() != item.CRC) - opRes = NExtract::NOperationResult::kCRCError; - } - } - outStream.Release(); - RINOK(extractCallback->SetOperationResult(opRes)); - } - } - return S_OK; - COM_TRY_END -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhHandler.h b/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhHandler.h deleted file mode 100644 index 6d31df534..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhHandler.h +++ /dev/null @@ -1,30 +0,0 @@ -// LzhHandler.h - -#ifndef __LZH_HANDLER_H -#define __LZH_HANDLER_H - -#include "Common/MyCom.h" -#include "../IArchive.h" -#include "LzhIn.h" - -namespace NArchive { -namespace NLzh { - -class CHandler: - public IInArchive, - public CMyUnknownImp -{ -public: - MY_UNKNOWN_IMP1(IInArchive) - - INTERFACE_IInArchive(;) - - CHandler(); -private: - CObjectVector _items; - CMyComPtr _stream; -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhHeader.h b/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhHeader.h deleted file mode 100644 index 1c758a14b..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhHeader.h +++ /dev/null @@ -1,19 +0,0 @@ -// Archive/Lzh/Header.h - -#ifndef __ARCHIVE_LZH_HEADER_H -#define __ARCHIVE_LZH_HEADER_H - -#include "Common/Types.h" - -namespace NArchive { -namespace NLzh { - -const int kMethodIdSize = 5; - -const Byte kExtIdFileName = 0x01; -const Byte kExtIdDirName = 0x02; -const Byte kExtIdUnixTime = 0x54; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhIn.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhIn.cpp deleted file mode 100644 index 56b62a943..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhIn.cpp +++ /dev/null @@ -1,172 +0,0 @@ -// Archive/LzhIn.cpp - -#include "StdAfx.h" - -#include "Common/StringConvert.h" -#include "Common/Buffer.h" - -#include "../../Common/StreamUtils.h" - -#include "LzhIn.h" - -namespace NArchive { -namespace NLzh { - -HRESULT CInArchive::ReadBytes(void *data, UInt32 size, UInt32 &processedSize) -{ - size_t realProcessedSize = size; - RINOK(ReadStream(m_Stream, data, &realProcessedSize)); - processedSize = (UInt32)realProcessedSize; - m_Position += processedSize; - return S_OK; -} - -HRESULT CInArchive::CheckReadBytes(void *data, UInt32 size) -{ - UInt32 processedSize; - RINOK(ReadBytes(data, size, processedSize)); - return (processedSize == size) ? S_OK: S_FALSE; -} - -HRESULT CInArchive::Open(IInStream *inStream) -{ - RINOK(inStream->Seek(0, STREAM_SEEK_CUR, &m_Position)); - m_Stream = inStream; - return S_OK; -} - -static const Byte *ReadUInt32(const Byte *p, UInt32 &v) -{ - v = 0; - for (int i = 0; i < 4; i++) - v |= ((UInt32)(*p++) << (i * 8)); - return p; -} - -static const Byte *ReadUInt16(const Byte *p, UInt16 &v) -{ - v = 0; - for (int i = 0; i < 2; i++) - v |= ((UInt16)(*p++) << (i * 8)); - return p; -} - -static const Byte *ReadString(const Byte *p, size_t size, AString &s) -{ - s.Empty(); - for (size_t i = 0; i < size; i++) - { - char c = p[i]; - if (c == 0) - break; - s += c; - } - return p + size; -} - -static Byte CalcSum(const Byte *data, size_t size) -{ - Byte sum = 0; - for (size_t i = 0; i < size; i++) - sum = (Byte)(sum + data[i]); - return sum; -} - -HRESULT CInArchive::GetNextItem(bool &filled, CItemEx &item) -{ - filled = false; - - UInt32 processedSize; - Byte startHeader[2]; - RINOK(ReadBytes(startHeader, 2, processedSize)) - if (processedSize == 0) - return S_OK; - if (processedSize == 1) - return (startHeader[0] == 0) ? S_OK: S_FALSE; - if (startHeader[0] == 0 && startHeader[1] == 0) - return S_OK; - - Byte header[256]; - const UInt32 kBasicPartSize = 22; - RINOK(ReadBytes(header, kBasicPartSize, processedSize)); - if (processedSize != kBasicPartSize) - return (startHeader[0] == 0) ? S_OK: S_FALSE; - - const Byte *p = header; - memmove(item.Method, p, kMethodIdSize); - if (!item.IsValidMethod()) - return S_OK; - p += kMethodIdSize; - p = ReadUInt32(p, item.PackSize); - p = ReadUInt32(p, item.Size); - p = ReadUInt32(p, item.ModifiedTime); - item.Attributes = *p++; - item.Level = *p++; - if (item.Level > 2) - return S_FALSE; - UInt32 headerSize; - if (item.Level < 2) - { - headerSize = startHeader[0]; - if (headerSize < kBasicPartSize) - return S_FALSE; - UInt32 remain = headerSize - kBasicPartSize; - RINOK(CheckReadBytes(header + kBasicPartSize, remain)); - if (startHeader[1] != CalcSum(header, headerSize)) - return S_FALSE; - size_t nameLength = *p++; - if ((p - header) + nameLength + 2 > headerSize) - return S_FALSE; - p = ReadString(p, nameLength, item.Name); - } - else - headerSize = startHeader[0] | ((UInt32)startHeader[1] << 8); - p = ReadUInt16(p, item.CRC); - if (item.Level != 0) - { - if (item.Level == 2) - { - RINOK(CheckReadBytes(header + kBasicPartSize, 2)); - } - if ((size_t)(p - header) + 3 > headerSize) - return S_FALSE; - item.OsId = *p++; - UInt16 nextSize; - p = ReadUInt16(p, nextSize); - while (nextSize != 0) - { - if (nextSize < 3) - return S_FALSE; - if (item.Level == 1) - { - if (item.PackSize < nextSize) - return S_FALSE; - item.PackSize -= nextSize; - } - CExtension ext; - RINOK(CheckReadBytes(&ext.Type, 1)) - nextSize -= 3; - ext.Data.SetCapacity(nextSize); - RINOK(CheckReadBytes((Byte *)ext.Data, nextSize)) - item.Extensions.Add(ext); - Byte hdr2[2]; - RINOK(CheckReadBytes(hdr2, 2)); - ReadUInt16(hdr2, nextSize); - } - } - item.DataPosition = m_Position; - filled = true; - return S_OK; -} - -HRESULT CInArchive::Skeep(UInt64 numBytes) -{ - UInt64 newPostion; - RINOK(m_Stream->Seek(numBytes, STREAM_SEEK_CUR, &newPostion)); - m_Position += numBytes; - if (m_Position != newPostion) - return E_FAIL; - return S_OK; -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhIn.h b/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhIn.h deleted file mode 100644 index a8c639801..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhIn.h +++ /dev/null @@ -1,29 +0,0 @@ -// Archive/LzhIn.h - -#ifndef __ARCHIVE_LZHIN_H -#define __ARCHIVE_LZHIN_H - -#include "Common/MyCom.h" -#include "../../IStream.h" - -#include "LzhItem.h" - -namespace NArchive { -namespace NLzh { - -class CInArchive -{ - CMyComPtr m_Stream; - UInt64 m_Position; - - HRESULT ReadBytes(void *data, UInt32 size, UInt32 &processedSize); - HRESULT CheckReadBytes(void *data, UInt32 size); -public: - HRESULT Open(IInStream *inStream); - HRESULT GetNextItem(bool &filled, CItemEx &itemInfo); - HRESULT Skeep(UInt64 numBytes); -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhItem.h b/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhItem.h deleted file mode 100644 index ca85a5153..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhItem.h +++ /dev/null @@ -1,172 +0,0 @@ -// Archive/LzhItem.h - -#ifndef __ARCHIVE_LZH_ITEM_H -#define __ARCHIVE_LZH_ITEM_H - -#include "Common/Types.h" -#include "Common/MyString.h" -#include "Common/Buffer.h" -#include "LzhHeader.h" - -namespace NArchive { -namespace NLzh { - -struct CExtension -{ - Byte Type; - CByteBuffer Data; - AString GetString() const - { - AString s; - for (size_t i = 0; i < Data.GetCapacity(); i++) - { - char c = (char)Data[i]; - if (c == 0) - break; - s += c; - } - return s; - } -}; - -struct CItem -{ -public: - AString Name; - Byte Method[kMethodIdSize]; - UInt32 PackSize; - UInt32 Size; - UInt32 ModifiedTime; - Byte Attributes; - Byte Level; - UInt16 CRC; - Byte OsId; - CObjectVector Extensions; - - bool IsValidMethod() const { return (Method[0] == '-' && Method[1] == 'l' && Method[4] == '-'); } - bool IsLhMethod() const {return (IsValidMethod() && Method[2] == 'h'); } - bool IsDir() const {return (IsLhMethod() && Method[3] == 'd'); } - - bool IsCopyMethod() const - { - return (IsLhMethod() && Method[3] == '0') || - (IsValidMethod() && Method[2] == 'z' && Method[3] == '4'); - } - - bool IsLh1GroupMethod() const - { - if (!IsLhMethod()) - return false; - switch(Method[3]) - { - case '1': - return true; - } - return false; - } - - bool IsLh4GroupMethod() const - { - if (!IsLhMethod()) - return false; - switch(Method[3]) - { - case '4': - case '5': - case '6': - case '7': - return true; - } - return false; - } - - int GetNumDictBits() const - { - if (!IsLhMethod()) - return 0; - switch(Method[3]) - { - case '1': - return 12; - case '2': - return 13; - case '3': - return 13; - case '4': - return 12; - case '5': - return 13; - case '6': - return 15; - case '7': - return 16; - } - return 0; - } - - int FindExt(Byte type) const - { - for (int i = 0; i < Extensions.Size(); i++) - if (Extensions[i].Type == type) - return i; - return -1; - } - bool GetUnixTime(UInt32 &value) const - { - int index = FindExt(kExtIdUnixTime); - if (index < 0) - { - if (Level == 2) - { - value = ModifiedTime; - return true; - } - return false; - } - const Byte *data = (const Byte *)(Extensions[index].Data); - value = data[0] | - ((UInt32)data[1] << 8) | - ((UInt32)data[2] << 16) | - ((UInt32)data[3] << 24); - return true; - } - - AString GetDirName() const - { - int index = FindExt(kExtIdDirName); - if (index < 0) - return AString(); - return Extensions[index].GetString(); - } - - AString GetFileName() const - { - int index = FindExt(kExtIdFileName); - if (index < 0) - return Name; - return Extensions[index].GetString(); - } - - AString GetName() const - { - AString dirName = GetDirName(); - dirName.Replace((char)(unsigned char)0xFF, '\\'); - if (!dirName.IsEmpty()) - { - char c = dirName[dirName.Length() - 1]; - if (c != '\\') - dirName += '\\'; - } - return dirName + GetFileName(); - } -}; - -class CItemEx: public CItem -{ -public: - UInt64 DataPosition; -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhOutStreamWithCRC.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhOutStreamWithCRC.cpp deleted file mode 100644 index 3cd632aa7..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhOutStreamWithCRC.cpp +++ /dev/null @@ -1,27 +0,0 @@ -// LzhOutStreamWithCRC.cpp - -#include "StdAfx.h" - -#include "LzhOutStreamWithCRC.h" - -namespace NArchive { -namespace NLzh { - -STDMETHODIMP COutStreamWithCRC::Write(const void *data, UInt32 size, UInt32 *processedSize) -{ - UInt32 realProcessedSize; - HRESULT result; - if(!_stream) - { - realProcessedSize = size; - result = S_OK; - } - else - result = _stream->Write(data, size, &realProcessedSize); - _crc.Update(data, realProcessedSize); - if(processedSize != NULL) - *processedSize = realProcessedSize; - return result; -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhOutStreamWithCRC.h b/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhOutStreamWithCRC.h deleted file mode 100644 index eee15d0e2..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhOutStreamWithCRC.h +++ /dev/null @@ -1,38 +0,0 @@ -// LzhOutStreamWithCRC.h - -#ifndef __LZHOUTSTREAMWITHCRC_H -#define __LZHOUTSTREAMWITHCRC_H - -#include "LzhCRC.h" -#include "../../../Common/MyCom.h" -#include "../../IStream.h" - -namespace NArchive { -namespace NLzh { - -class COutStreamWithCRC: - public ISequentialOutStream, - public CMyUnknownImp -{ -public: - MY_UNKNOWN_IMP - - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); -private: - CCRC _crc; - CMyComPtr _stream; -public: - void Init(ISequentialOutStream *stream) - { - _stream = stream; - _crc.Init(); - } - void ReleaseStream() { _stream.Release(); } - UInt32 GetCRC() const { return _crc.GetDigest(); } - void InitCRC() { _crc.Init(); } - -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhRegister.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhRegister.cpp deleted file mode 100644 index b83d2ee6c..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhRegister.cpp +++ /dev/null @@ -1,13 +0,0 @@ -// LzhRegister.cpp - -#include "StdAfx.h" - -#include "../../Common/RegisterArc.h" - -#include "LzhHandler.h" -static IInArchive *CreateArc() { return new NArchive::NLzh::CHandler; } - -static CArcInfo g_ArcInfo = - { L"Lzh", L"lzh lha", 0, 6, { '-', 'l' }, 2, false, CreateArc, 0 }; - -REGISTER_ARC(Lzh) diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/StdAfx.h b/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/StdAfx.h deleted file mode 100644 index 83fdd22d5..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/StdAfx.h +++ /dev/null @@ -1,8 +0,0 @@ -// StdAfx.h - -#ifndef __STDAFX_H -#define __STDAFX_H - -#include "../../../Common/MyWindows.h" - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/LzmaArcRegister.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/LzmaArcRegister.cpp deleted file mode 100644 index 867bc78ff..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/LzmaArcRegister.cpp +++ /dev/null @@ -1,14 +0,0 @@ -// LzmaArcRegister.cpp - -#include "StdAfx.h" - -#include "../../Common/RegisterArc.h" - -#include "LzmaHandler.h" - -static IInArchive *CreateArc() { return new NArchive::NLzma::CHandler; } - -static CArcInfo g_ArcInfo = - { L"Lzma", L"lzma lzma86", 0, 0xA, {0 }, 0, true, CreateArc, NULL }; - -REGISTER_ARC(Lzma) diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/LzmaFiltersDecode.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/LzmaFiltersDecode.cpp deleted file mode 100644 index 2ab3dbf4b..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/LzmaFiltersDecode.cpp +++ /dev/null @@ -1,86 +0,0 @@ -// LzmaFiltersDecode.cpp - -#include "StdAfx.h" - -#include "LzmaFiltersDecode.h" - -namespace NArchive { -namespace NLzma { - -static const UInt64 k_LZMA = 0x030101; -static const UInt64 k_BCJ = 0x03030103; - -HRESULT CDecoder::Code( - DECL_EXTERNAL_CODECS_LOC_VARS - const CHeader &block, - ISequentialInStream *inStream, ISequentialOutStream *outStream, - UInt64 *inProcessedSize, ICompressProgressInfo *progress) -{ - *inProcessedSize = (UInt64)(Int64)-1; - - if (block.FilterMethod > 1) - return E_NOTIMPL; - - if (!_lzmaDecoder) - { - RINOK(CreateCoder(EXTERNAL_CODECS_LOC_VARS k_LZMA, _lzmaDecoder, false)); - if (_lzmaDecoder == 0) - return E_NOTIMPL; - } - - { - CMyComPtr setDecoderProperties; - _lzmaDecoder.QueryInterface(IID_ICompressSetDecoderProperties2, &setDecoderProperties); - if (!setDecoderProperties) - return E_NOTIMPL; - RINOK(setDecoderProperties->SetDecoderProperties2(block.LzmaProps, 5)); - } - - bool filteredMode = (block.FilterMethod == 1); - - CMyComPtr setOutStream; - - if (filteredMode) - { - if (!_bcjStream) - { - CMyComPtr coder; - RINOK(CreateCoder(EXTERNAL_CODECS_LOC_VARS k_BCJ, coder, false)); - if (!coder) - return E_NOTIMPL; - coder.QueryInterface(IID_ISequentialOutStream, &_bcjStream); - if (!_bcjStream) - return E_NOTIMPL; - } - - _bcjStream.QueryInterface(IID_ICompressSetOutStream, &setOutStream); - if (!setOutStream) - return E_NOTIMPL; - RINOK(setOutStream->SetOutStream(outStream)); - outStream = _bcjStream; - } - - const UInt64 *unpackSize = block.HasUnpackSize() ? &block.UnpackSize : NULL; - RINOK(_lzmaDecoder->Code(inStream, outStream, NULL, unpackSize, progress)); - - if (filteredMode) - { - CMyComPtr flush; - _bcjStream.QueryInterface(IID_IOutStreamFlush, &flush); - if (flush) - { - RINOK(flush->Flush()); - } - RINOK(setOutStream->ReleaseOutStream()); - } - - CMyComPtr getInStreamProcessedSize; - _lzmaDecoder.QueryInterface(IID_ICompressGetInStreamProcessedSize, &getInStreamProcessedSize); - if (getInStreamProcessedSize) - { - RINOK(getInStreamProcessedSize->GetInStreamProcessedSize(inProcessedSize)); - } - return S_OK; -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/LzmaFiltersDecode.h b/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/LzmaFiltersDecode.h deleted file mode 100644 index b966b422a..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/LzmaFiltersDecode.h +++ /dev/null @@ -1,26 +0,0 @@ -// LzmaFiltersDecode.h - -#ifndef __LZMA_FILTERS_DECODE_H -#define __LZMA_FILTERS_DECODE_H - -#include "../../Common/CreateCoder.h" - -#include "LzmaItem.h" - -namespace NArchive { -namespace NLzma { - -class CDecoder -{ - CMyComPtr _lzmaDecoder; - CMyComPtr _bcjStream; -public: - HRESULT Code(DECL_EXTERNAL_CODECS_LOC_VARS - const CHeader &block, - ISequentialInStream *inStream, ISequentialOutStream *outStream, - UInt64 *inProcessedSize, ICompressProgressInfo *progress); -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/LzmaHandler.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/LzmaHandler.cpp deleted file mode 100644 index 249fd90fa..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/LzmaHandler.cpp +++ /dev/null @@ -1,243 +0,0 @@ -// LzmaHandler.cpp - -#include "StdAfx.h" - -#include "LzmaHandler.h" - -#include "Common/Defs.h" -#include "Common/StringConvert.h" -#include "Common/ComTry.h" -#include "Common/IntToString.h" - -#include "Windows/PropVariant.h" - -#include "../../Common/ProgressUtils.h" -#include "../../Common/StreamUtils.h" -#include "../Common/DummyOutStream.h" - -#include "LzmaFiltersDecode.h" - -namespace NArchive { -namespace NLzma { - -STATPROPSTG kProps[] = -{ - { NULL, kpidSize, VT_UI8}, - { NULL, kpidPackSize, VT_UI8}, - { NULL, kpidMethod, VT_UI1} -}; - -IMP_IInArchive_Props -IMP_IInArchive_ArcProps_NO - -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) -{ - *numItems = 1; - return S_OK; -} - -static void ConvertUInt32ToString(UInt32 value, wchar_t *s) -{ - ConvertUInt64ToString(value, s + MyStringLen(s)); -} - -static void DictSizeToString(UInt32 value, wchar_t *s) -{ - for (int i = 0; i <= 31; i++) - if ((UInt32(1) << i) == value) - { - ConvertUInt32ToString(i, s); - return; - } - wchar_t c = L'b'; - if ((value & ((1 << 20) - 1)) == 0) - { - value >>= 20; - c = L'm'; - } - else if ((value & ((1 << 10) - 1)) == 0) - { - value >>= 10; - c = L'k'; - } - ConvertUInt32ToString(value, s); - int p = MyStringLen(s); - s[p++] = c; - s[p++] = L'\0'; -} - -static void MyStrCat(wchar_t *d, const wchar_t *s) -{ - MyStringCopy(d + MyStringLen(d), s); -} - -STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) -{ - if (index != 0) - return E_INVALIDARG; - NWindows::NCOM::CPropVariant propVariant; - switch(propID) - { - case kpidSize: - if (m_StreamInfo.HasUnpackSize()) - propVariant = (UInt64)m_StreamInfo.UnpackSize; - break; - case kpidPackSize: - propVariant = (UInt64)m_PackSize; - break; - case kpidMethod: - { - wchar_t s[64]; - s[0] = '\0'; - if (m_StreamInfo.IsThereFilter) - { - const wchar_t *f; - if (m_StreamInfo.FilterMethod == 0) - f = L"Copy"; - else if (m_StreamInfo.FilterMethod == 1) - f = L"BCJ"; - else - f = L"Unknown"; - MyStrCat(s, f); - MyStrCat(s, L" "); - } - MyStrCat(s, L"LZMA:"); - DictSizeToString(m_StreamInfo.GetDicSize(), s); - propVariant = s; - break; - } - } - propVariant.Detach(value); - return S_OK; -} - -STDMETHODIMP CHandler::Open(IInStream *inStream, - const UInt64 * /* maxCheckStartPosition */, - IArchiveOpenCallback * /* openArchiveCallback */) -{ - { - RINOK(inStream->Seek(0, STREAM_SEEK_CUR, &m_StreamStartPosition)); - - HRESULT res = ReadStreamHeader(inStream, m_StreamInfo); - if (res != S_OK) - return S_FALSE; - - Byte b; - RINOK(ReadStream_FALSE(inStream, &b, 1)); - if (b != 0) - return S_FALSE; - - UInt64 endPos; - RINOK(inStream->Seek(0, STREAM_SEEK_END, &endPos)); - m_PackSize = endPos - m_StreamStartPosition - m_StreamInfo.GetHeaderSize(); - - m_Stream = inStream; - } - return S_OK; -} - -STDMETHODIMP CHandler::Close() -{ - m_Stream.Release(); - return S_OK; -} - - -STDMETHODIMP CHandler::Extract(const UInt32* indices, UInt32 numItems, - Int32 _aTestMode, IArchiveExtractCallback *extractCallback) -{ - COM_TRY_BEGIN - bool allFilesMode = (numItems == UInt32(-1)); - if (!allFilesMode) - { - if (numItems == 0) - return S_OK; - if (numItems != 1) - return E_INVALIDARG; - if (indices[0] != 0) - return E_INVALIDARG; - } - - bool testMode = (_aTestMode != 0); - - RINOK(extractCallback->SetTotal(m_PackSize)); - - UInt64 currentTotalPacked = 0; - - CDummyOutStream *outStreamSpec = new CDummyOutStream; - CMyComPtr outStream(outStreamSpec); - - { - CMyComPtr realOutStream; - Int32 askMode = testMode ? - NArchive::NExtract::NAskMode::kTest : - NArchive::NExtract::NAskMode::kExtract; - - RINOK(extractCallback->GetStream(0, &realOutStream, askMode)); - - outStreamSpec->SetStream(realOutStream); - outStreamSpec->Init(); - if(!testMode && !realOutStream) - return S_OK; - extractCallback->PrepareOperation(askMode); - } - - CLocalProgress *lps = new CLocalProgress; - CMyComPtr progress = lps; - lps->Init(extractCallback, true); - - CDecoder decoder; - RINOK(m_Stream->Seek(m_StreamStartPosition, STREAM_SEEK_SET, NULL)); - UInt64 streamPos = m_StreamStartPosition; - Int32 opRes = NArchive::NExtract::NOperationResult::kOK; - bool firstItem = true; - for (;;) - { - CHeader st; - HRESULT result = ReadStreamHeader(m_Stream, st); - if (result != S_OK) - { - if (firstItem) - return E_FAIL; - break; - } - firstItem = false; - - lps->OutSize = outStreamSpec->GetSize(); - lps->InSize = currentTotalPacked; - RINOK(lps->SetCur()); - - streamPos += st.GetHeaderSize(); - UInt64 packProcessed; - - { - result = decoder.Code( - EXTERNAL_CODECS_VARS - st, m_Stream, outStream, &packProcessed, progress); - if (result == E_NOTIMPL) - { - opRes = NArchive::NExtract::NOperationResult::kUnSupportedMethod; - break; - } - if (result == S_FALSE) - { - opRes = NArchive::NExtract::NOperationResult::kDataError; - break; - } - RINOK(result); - } - - if (packProcessed == (UInt64)(Int64)-1) - break; - RINOK(m_Stream->Seek(streamPos + packProcessed, STREAM_SEEK_SET, NULL)); - currentTotalPacked += packProcessed; - streamPos += packProcessed; - } - outStream.Release(); - return extractCallback->SetOperationResult(opRes); - COM_TRY_END -} - -IMPL_ISetCompressCodecsInfo - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/LzmaHandler.h b/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/LzmaHandler.h deleted file mode 100644 index bbf11a46b..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/LzmaHandler.h +++ /dev/null @@ -1,69 +0,0 @@ -// Lzma/Handler.h - -#ifndef __GZIP_HANDLER_H -#define __GZIP_HANDLER_H - -#include "Common/MyCom.h" - -#include "../IArchive.h" -#include "../../Common/CreateCoder.h" - -#include "LzmaIn.h" - -namespace NArchive { -namespace NLzma { - -// const UInt64 k_LZMA = 0x030101; - -class CHandler: - public IInArchive, - PUBLIC_ISetCompressCodecsInfo - public CMyUnknownImp -{ -public: - MY_QUERYINTERFACE_BEGIN - MY_QUERYINTERFACE_ENTRY(IInArchive) - QUERY_ENTRY_ISetCompressCodecsInfo - MY_QUERYINTERFACE_END - MY_ADDREF_RELEASE - - STDMETHOD(Open)(IInStream *inStream, - const UInt64 *maxCheckStartPosition, - IArchiveOpenCallback *openArchiveCallback); - STDMETHOD(Close)(); - - STDMETHOD(GetNumberOfItems)(UInt32 *numItems); - STDMETHOD(GetProperty)(UInt32 index, PROPID propID, PROPVARIANT *value); - STDMETHOD(Extract)(const UInt32* indices, UInt32 numItems, - Int32 testMode, IArchiveExtractCallback *extractCallback); - - STDMETHOD(GetArchiveProperty)(PROPID propID, PROPVARIANT *value); - - STDMETHOD(GetNumberOfProperties)(UInt32 *numProperties); - STDMETHOD(GetPropertyInfo)(UInt32 index, - BSTR *name, PROPID *propID, VARTYPE *varType); - - STDMETHOD(GetNumberOfArchiveProperties)(UInt32 *numProperties); - STDMETHOD(GetArchivePropertyInfo)(UInt32 index, - BSTR *name, PROPID *propID, VARTYPE *varType); - - UString GetMethodString(); -public: - CHandler() { } - -private: - CHeader m_StreamInfo; - UInt64 m_StreamStartPosition; - UInt64 m_PackSize; - - CMyComPtr m_Stream; - - DECL_EXTERNAL_CODECS_VARS - - DECL_ISetCompressCodecsInfo - -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/LzmaIn.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/LzmaIn.cpp deleted file mode 100644 index 7d2475c75..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/LzmaIn.cpp +++ /dev/null @@ -1,56 +0,0 @@ -// Archive/LzmaIn.cpp - -#include "StdAfx.h" - -#include "LzmaIn.h" - -#include "../../Common/StreamUtils.h" - -namespace NArchive { -namespace NLzma { - -static bool CheckDictSize(const Byte *p) -{ - UInt32 dicSize = GetUi32(p); - int i; - for (i = 1; i <= 30; i++) - if (dicSize == ((UInt32)2 << i) || dicSize == ((UInt32)3 << i)) - return true; - return false; -} - -HRESULT ReadStreamHeader(ISequentialInStream *inStream, CHeader &block) -{ - Byte sig[5 + 9]; - RINOK(ReadStream_FALSE(inStream, sig, 5 + 8)); - - const Byte kMaxProp0Val = 5 * 5 * 9 - 1; - if (sig[0] > kMaxProp0Val) - return S_FALSE; - - for (int i = 0; i < 5; i++) - block.LzmaProps[i] = sig[i]; - - block.IsThereFilter = false; - block.FilterMethod = 0; - - if (!CheckDictSize(sig + 1)) - { - if (sig[0] > 1 || sig[1] > kMaxProp0Val) - return S_FALSE; - block.IsThereFilter = true; - block.FilterMethod = sig[0]; - for (int i = 0; i < 5; i++) - block.LzmaProps[i] = sig[i + 1]; - if (!CheckDictSize(block.LzmaProps + 1)) - return S_FALSE; - RINOK(ReadStream_FALSE(inStream, sig + 5 + 8, 1)); - } - UInt32 unpOffset = 5 + (block.IsThereFilter ? 1 : 0); - block.UnpackSize = GetUi64(sig + unpOffset); - if (block.HasUnpackSize() && block.UnpackSize >= ((UInt64)1 << 56)) - return S_FALSE; - return S_OK; -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/LzmaIn.h b/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/LzmaIn.h deleted file mode 100644 index 6f5c24c0e..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/LzmaIn.h +++ /dev/null @@ -1,16 +0,0 @@ -// Archive/LzmaIn.h - -#ifndef __ARCHIVE_LZMA_IN_H -#define __ARCHIVE_LZMA_IN_H - -#include "LzmaItem.h" -#include "../../IStream.h" - -namespace NArchive { -namespace NLzma { - -HRESULT ReadStreamHeader(ISequentialInStream *inStream, CHeader &st); - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/LzmaItem.h b/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/LzmaItem.h deleted file mode 100644 index 1bfadf727..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/LzmaItem.h +++ /dev/null @@ -1,27 +0,0 @@ -// Archive/LzmaItem.h - -#ifndef __ARCHIVE_LZMA_ITEM_H -#define __ARCHIVE_LZMA_ITEM_H - -#include "Common/Types.h" - -#include "../../../../C/CpuArch.h" - -namespace NArchive { -namespace NLzma { - -struct CHeader -{ - UInt64 UnpackSize; - bool IsThereFilter; - Byte FilterMethod; - Byte LzmaProps[5]; - - UInt32 GetDicSize() const { return GetUi32(LzmaProps + 1); } - bool HasUnpackSize() const { return (UnpackSize != (UInt64)(Int64)-1); } - unsigned GetHeaderSize() const { return 5 + 8 + (IsThereFilter ? 1 : 0); } -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/StdAfx.h b/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/StdAfx.h deleted file mode 100644 index 83fdd22d5..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/StdAfx.h +++ /dev/null @@ -1,8 +0,0 @@ -// StdAfx.h - -#ifndef __STDAFX_H -#define __STDAFX_H - -#include "../../../Common/MyWindows.h" - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarHandler.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarHandler.cpp deleted file mode 100644 index 3bd17b6db..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarHandler.cpp +++ /dev/null @@ -1,835 +0,0 @@ -// RarHandler.cpp - -#include "StdAfx.h" - -#include "Common/ComTry.h" -#include "Common/IntToString.h" -#include "Common/StringConvert.h" - -#include "Windows/PropVariant.h" -#include "Windows/Time.h" - -#include "../../IPassword.h" - -#include "../../Common/CreateCoder.h" -#include "../../Common/FilterCoder.h" -#include "../../Common/MethodId.h" -#include "../../Common/ProgressUtils.h" - -#include "../../Compress/CopyCoder.h" - -#include "../../Crypto/Rar20Crypto.h" -#include "../../Crypto/RarAes.h" - -#include "../Common/ItemNameUtils.h" -#include "../Common/OutStreamWithCRC.h" - -#include "RarHandler.h" - -using namespace NWindows; -using namespace NTime; - -namespace NArchive { -namespace NRar { - -static const wchar_t *kHostOS[] = -{ - L"MS DOS", - L"OS/2", - L"Win32", - L"Unix", - L"Mac OS", - L"BeOS" -}; - -static const int kNumHostOSes = sizeof(kHostOS) / sizeof(kHostOS[0]); - -static const wchar_t *kUnknownOS = L"Unknown"; - -STATPROPSTG kProps[] = -{ - { NULL, kpidPath, VT_BSTR}, - { NULL, kpidIsDir, VT_BOOL}, - { NULL, kpidSize, VT_UI8}, - { NULL, kpidPackSize, VT_UI8}, - { NULL, kpidMTime, VT_FILETIME}, - { NULL, kpidCTime, VT_FILETIME}, - { NULL, kpidATime, VT_FILETIME}, - { NULL, kpidAttrib, VT_UI4}, - - { NULL, kpidEncrypted, VT_BOOL}, - { NULL, kpidSolid, VT_BOOL}, - { NULL, kpidCommented, VT_BOOL}, - { NULL, kpidSplitBefore, VT_BOOL}, - { NULL, kpidSplitAfter, VT_BOOL}, - { NULL, kpidCRC, VT_UI4}, - { NULL, kpidHostOS, VT_BSTR}, - { NULL, kpidMethod, VT_BSTR}, - { NULL, kpidUnpackVer, VT_UI1} -}; - -STATPROPSTG kArcProps[] = -{ - { NULL, kpidSolid, VT_BOOL}, - { NULL, kpidNumBlocks, VT_UI4}, - // { NULL, kpidEncrypted, VT_BOOL}, - { NULL, kpidIsVolume, VT_BOOL}, - { NULL, kpidNumVolumes, VT_UI4}, - { NULL, kpidPhySize, VT_UI8} - // { NULL, kpidCommented, VT_BOOL} -}; - -IMP_IInArchive_Props -IMP_IInArchive_ArcProps - -UInt64 CHandler::GetPackSize(int refIndex) const -{ - const CRefItem &refItem = _refItems[refIndex]; - UInt64 totalPackSize = 0; - for (int i = 0; i < refItem.NumItems; i++) - totalPackSize += _items[refItem.ItemIndex + i].PackSize; - return totalPackSize; -} - -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) -{ - // COM_TRY_BEGIN - NWindows::NCOM::CPropVariant prop; - switch(propID) - { - case kpidSolid: prop = _archiveInfo.IsSolid(); break; - // case kpidEncrypted: prop = _archiveInfo.IsEncrypted(); break; // it's for encrypted names. - case kpidIsVolume: prop = _archiveInfo.IsVolume(); break; - case kpidNumVolumes: prop = (UInt32)_archives.Size(); break; - case kpidOffset: if (_archiveInfo.StartPosition != 0) prop = _archiveInfo.StartPosition; break; - // case kpidCommented: prop = _archiveInfo.IsCommented(); break; - case kpidNumBlocks: - { - UInt32 numBlocks = 0; - for (int i = 0; i < _refItems.Size(); i++) - if (!IsSolid(i)) - numBlocks++; - prop = (UInt32)numBlocks; - break; - } - } - prop.Detach(value); - return S_OK; - // COM_TRY_END -} - -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) -{ - *numItems = _refItems.Size(); - return S_OK; -} - -static bool RarTimeToFileTime(const CRarTime &rarTime, FILETIME &result) -{ - if (!DosTimeToFileTime(rarTime.DosTime, result)) - return false; - UInt64 value = (((UInt64)result.dwHighDateTime) << 32) + result.dwLowDateTime; - value += (UInt64)rarTime.LowSecond * 10000000; - value += ((UInt64)rarTime.SubTime[2] << 16) + - ((UInt64)rarTime.SubTime[1] << 8) + - ((UInt64)rarTime.SubTime[0]); - result.dwLowDateTime = (DWORD)value; - result.dwHighDateTime = DWORD(value >> 32); - return true; -} - -static void RarTimeToProp(const CRarTime &rarTime, NWindows::NCOM::CPropVariant &prop) -{ - FILETIME localFileTime, utcFileTime; - if (RarTimeToFileTime(rarTime, localFileTime)) - { - if (!LocalFileTimeToFileTime(&localFileTime, &utcFileTime)) - utcFileTime.dwHighDateTime = utcFileTime.dwLowDateTime = 0; - } - else - utcFileTime.dwHighDateTime = utcFileTime.dwLowDateTime = 0; - prop = utcFileTime; -} - -STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) -{ - COM_TRY_BEGIN - NWindows::NCOM::CPropVariant prop; - const CRefItem &refItem = _refItems[index]; - const CItemEx &item = _items[refItem.ItemIndex]; - switch(propID) - { - case kpidPath: - { - UString u; - if (item.HasUnicodeName() && !item.UnicodeName.IsEmpty()) - u = item.UnicodeName; - else - u = MultiByteToUnicodeString(item.Name, CP_OEMCP); - prop = (const wchar_t *)NItemName::WinNameToOSName(u); - break; - } - case kpidIsDir: prop = item.IsDir(); break; - case kpidSize: prop = item.Size; break; - case kpidPackSize: prop = GetPackSize(index); break; - case kpidMTime: RarTimeToProp(item.MTime, prop); break; - case kpidCTime: if (item.CTimeDefined) RarTimeToProp(item.CTime, prop); break; - case kpidATime: if (item.ATimeDefined) RarTimeToProp(item.ATime, prop); break; - case kpidAttrib: prop = item.GetWinAttributes(); break; - case kpidEncrypted: prop = item.IsEncrypted(); break; - case kpidSolid: prop = IsSolid(index); break; - case kpidCommented: prop = item.IsCommented(); break; - case kpidSplitBefore: prop = item.IsSplitBefore(); break; - case kpidSplitAfter: prop = _items[refItem.ItemIndex + refItem.NumItems - 1].IsSplitAfter(); break; - case kpidCRC: - { - const CItemEx &lastItem = _items[refItem.ItemIndex + refItem.NumItems - 1]; - prop = ((lastItem.IsSplitAfter()) ? item.FileCRC : lastItem.FileCRC); - break; - } - case kpidUnpackVer: prop = item.UnPackVersion; break; - case kpidMethod: - { - UString method; - if (item.Method >= Byte('0') && item.Method <= Byte('5')) - { - method = L"m"; - wchar_t temp[32]; - ConvertUInt64ToString(item.Method - Byte('0'), temp); - method += temp; - if (!item.IsDir()) - { - method += L":"; - ConvertUInt64ToString(16 + item.GetDictSize(), temp); - method += temp; - } - } - else - { - wchar_t temp[32]; - ConvertUInt64ToString(item.Method, temp); - method += temp; - } - prop = method; - break; - } - case kpidHostOS: prop = (item.HostOS < kNumHostOSes) ? (kHostOS[item.HostOS]) : kUnknownOS; break; - } - prop.Detach(value); - return S_OK; - COM_TRY_END -} - -class CVolumeName -{ - bool _first; - bool _newStyle; - UString _unchangedPart; - UString _changedPart; - UString _afterPart; -public: - CVolumeName(): _newStyle(true) {}; - - bool InitName(const UString &name, bool newStyle) - { - _first = true; - _newStyle = newStyle; - int dotPos = name.ReverseFind('.'); - UString basePart = name; - if (dotPos >= 0) - { - UString ext = name.Mid(dotPos + 1); - if (ext.CompareNoCase(L"rar") == 0) - { - _afterPart = name.Mid(dotPos); - basePart = name.Left(dotPos); - } - else if (ext.CompareNoCase(L"exe") == 0) - { - _afterPart = L".rar"; - basePart = name.Left(dotPos); - } - else if (!_newStyle) - { - if (ext.CompareNoCase(L"000") == 0 || ext.CompareNoCase(L"001") == 0) - { - _afterPart.Empty(); - _first = false; - _changedPart = ext; - _unchangedPart = name.Left(dotPos + 1); - return true; - } - } - } - - if (!_newStyle) - { - _afterPart.Empty(); - _unchangedPart = basePart + UString(L"."); - _changedPart = L"r00"; - return true; - } - - int numLetters = 1; - if (basePart.Right(numLetters) == L"1" || basePart.Right(numLetters) == L"0") - { - while (numLetters < basePart.Length()) - { - if (basePart[basePart.Length() - numLetters - 1] != '0') - break; - numLetters++; - } - } - else - return false; - _unchangedPart = basePart.Left(basePart.Length() - numLetters); - _changedPart = basePart.Right(numLetters); - return true; - } - - UString GetNextName() - { - UString newName; - if (_newStyle || !_first) - { - int i; - int numLetters = _changedPart.Length(); - for (i = numLetters - 1; i >= 0; i--) - { - wchar_t c = _changedPart[i]; - if (c == L'9') - { - c = L'0'; - newName = c + newName; - if (i == 0) - newName = UString(L'1') + newName; - continue; - } - c++; - newName = UString(c) + newName; - i--; - for (; i >= 0; i--) - newName = _changedPart[i] + newName; - break; - } - _changedPart = newName; - } - _first = false; - return _unchangedPart + _changedPart + _afterPart; - } -}; - -HRESULT CHandler::Open2(IInStream *stream, - const UInt64 *maxCheckStartPosition, - IArchiveOpenCallback *openArchiveCallback) -{ - { - CMyComPtr openVolumeCallback; - CMyComPtr getTextPassword; - CMyComPtr openArchiveCallbackWrap = openArchiveCallback; - - CVolumeName seqName; - - UInt64 totalBytes = 0; - UInt64 curBytes = 0; - - if (openArchiveCallback != NULL) - { - openArchiveCallbackWrap.QueryInterface(IID_IArchiveOpenVolumeCallback, &openVolumeCallback); - openArchiveCallbackWrap.QueryInterface(IID_ICryptoGetTextPassword, &getTextPassword); - } - - for (;;) - { - CMyComPtr inStream; - if (!_archives.IsEmpty()) - { - if (!openVolumeCallback) - break; - - if(_archives.Size() == 1) - { - if (!_archiveInfo.IsVolume()) - break; - UString baseName; - { - NCOM::CPropVariant prop; - RINOK(openVolumeCallback->GetProperty(kpidName, &prop)); - if (prop.vt != VT_BSTR) - break; - baseName = prop.bstrVal; - } - seqName.InitName(baseName, _archiveInfo.HaveNewVolumeName()); - } - - UString fullName = seqName.GetNextName(); - HRESULT result = openVolumeCallback->GetStream(fullName, &inStream); - if (result == S_FALSE) - break; - if (result != S_OK) - return result; - if (!stream) - break; - } - else - inStream = stream; - - UInt64 endPos = 0; - if (openArchiveCallback != NULL) - { - RINOK(stream->Seek(0, STREAM_SEEK_END, &endPos)); - RINOK(stream->Seek(0, STREAM_SEEK_SET, NULL)); - totalBytes += endPos; - RINOK(openArchiveCallback->SetTotal(NULL, &totalBytes)); - } - - NArchive::NRar::CInArchive archive; - RINOK(archive.Open(inStream, maxCheckStartPosition)); - - if (_archives.IsEmpty()) - archive.GetArchiveInfo(_archiveInfo); - - CItemEx item; - for (;;) - { - HRESULT result = archive.GetNextItem(item, getTextPassword); - if (result == S_FALSE) - break; - RINOK(result); - if (item.IgnoreItem()) - continue; - - bool needAdd = true; - if (item.IsSplitBefore()) - { - if (!_refItems.IsEmpty()) - { - CRefItem &refItem = _refItems.Back(); - refItem.NumItems++; - needAdd = false; - } - } - if (needAdd) - { - CRefItem refItem; - refItem.ItemIndex = _items.Size(); - refItem.NumItems = 1; - refItem.VolumeIndex = _archives.Size(); - _refItems.Add(refItem); - } - _items.Add(item); - if (openArchiveCallback != NULL && _items.Size() % 100 == 0) - { - UInt64 numFiles = _items.Size(); - UInt64 numBytes = curBytes + item.Position; - RINOK(openArchiveCallback->SetCompleted(&numFiles, &numBytes)); - } - } - curBytes += endPos; - _archives.Add(archive); - } - } - return S_OK; -} - -STDMETHODIMP CHandler::Open(IInStream *stream, - const UInt64 *maxCheckStartPosition, - IArchiveOpenCallback *openArchiveCallback) -{ - COM_TRY_BEGIN - Close(); - try - { - HRESULT res = Open2(stream, maxCheckStartPosition, openArchiveCallback); - if (res != S_OK) - Close(); - return res; - } - catch(const CInArchiveException &) { Close(); return S_FALSE; } - catch(...) { Close(); throw; } - COM_TRY_END -} - -STDMETHODIMP CHandler::Close() -{ - COM_TRY_BEGIN - _refItems.Clear(); - _items.Clear(); - _archives.Clear(); - return S_OK; - COM_TRY_END -} - -struct CMethodItem -{ - Byte RarUnPackVersion; - CMyComPtr Coder; -}; - - -STDMETHODIMP CHandler::Extract(const UInt32* indices, UInt32 numItems, - Int32 _aTestMode, IArchiveExtractCallback *_anExtractCallback) -{ - COM_TRY_BEGIN - CMyComPtr getTextPassword; - bool testMode = (_aTestMode != 0); - CMyComPtr extractCallback = _anExtractCallback; - UInt64 censoredTotalUnPacked = 0, - // censoredTotalPacked = 0, - importantTotalUnPacked = 0; - // importantTotalPacked = 0; - bool allFilesMode = (numItems == UInt32(-1)); - if (allFilesMode) - numItems = _refItems.Size(); - if(numItems == 0) - return S_OK; - int lastIndex = 0; - CRecordVector importantIndexes; - CRecordVector extractStatuses; - - for(UInt32 t = 0; t < numItems; t++) - { - int index = allFilesMode ? t : indices[t]; - const CRefItem &refItem = _refItems[index]; - const CItemEx &item = _items[refItem.ItemIndex]; - censoredTotalUnPacked += item.Size; - // censoredTotalPacked += item.PackSize; - int j; - for(j = lastIndex; j <= index; j++) - // if(!_items[_refItems[j].ItemIndex].IsSolid()) - if(!IsSolid(j)) - lastIndex = j; - for(j = lastIndex; j <= index; j++) - { - const CRefItem &refItem = _refItems[j]; - const CItemEx &item = _items[refItem.ItemIndex]; - - // const CItemEx &item = _items[j]; - - importantTotalUnPacked += item.Size; - // importantTotalPacked += item.PackSize; - importantIndexes.Add(j); - extractStatuses.Add(j == index); - } - lastIndex = index + 1; - } - - extractCallback->SetTotal(importantTotalUnPacked); - UInt64 currentImportantTotalUnPacked = 0; - UInt64 currentImportantTotalPacked = 0; - UInt64 currentUnPackSize, currentPackSize; - - CObjectVector methodItems; - - NCompress::CCopyCoder *copyCoderSpec = new NCompress::CCopyCoder; - CMyComPtr copyCoder = copyCoderSpec; - - CFilterCoder *filterStreamSpec = new CFilterCoder; - CMyComPtr filterStream = filterStreamSpec; - - NCrypto::NRar20::CDecoder *rar20CryptoDecoderSpec = NULL; - CMyComPtr rar20CryptoDecoder; - NCrypto::NRar29::CDecoder *rar29CryptoDecoderSpec = NULL; - CMyComPtr rar29CryptoDecoder; - - CFolderInStream *folderInStreamSpec = NULL; - CMyComPtr folderInStream; - - CLocalProgress *lps = new CLocalProgress; - CMyComPtr progress = lps; - lps->Init(extractCallback, false); - - bool solidStart = true; - for(int i = 0; i < importantIndexes.Size(); i++, - currentImportantTotalUnPacked += currentUnPackSize, - currentImportantTotalPacked += currentPackSize) - { - lps->InSize = currentImportantTotalPacked; - lps->OutSize = currentImportantTotalUnPacked; - RINOK(lps->SetCur()); - CMyComPtr realOutStream; - - Int32 askMode; - if(extractStatuses[i]) - askMode = testMode ? - NArchive::NExtract::NAskMode::kTest : - NArchive::NExtract::NAskMode::kExtract; - else - askMode = NArchive::NExtract::NAskMode::kSkip; - - UInt32 index = importantIndexes[i]; - - const CRefItem &refItem = _refItems[index]; - const CItemEx &item = _items[refItem.ItemIndex]; - - currentUnPackSize = item.Size; - - currentPackSize = GetPackSize(index); - - if(item.IgnoreItem()) - continue; - - RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); - - if (!IsSolid(index)) - solidStart = true; - if(item.IsDir()) - { - RINOK(extractCallback->PrepareOperation(askMode)); - RINOK(extractCallback->SetOperationResult(NArchive::NExtract::NOperationResult::kOK)); - continue; - } - - bool mustBeProcessedAnywhere = false; - if(i < importantIndexes.Size() - 1) - { - // const CRefItem &nextRefItem = _refItems[importantIndexes[i + 1]]; - // const CItemEx &nextItemInfo = _items[nextRefItem.ItemIndex]; - // mustBeProcessedAnywhere = nextItemInfo.IsSolid(); - mustBeProcessedAnywhere = IsSolid(importantIndexes[i + 1]); - } - - if (!mustBeProcessedAnywhere && !testMode && !realOutStream) - continue; - - if (!realOutStream && !testMode) - askMode = NArchive::NExtract::NAskMode::kSkip; - - RINOK(extractCallback->PrepareOperation(askMode)); - - COutStreamWithCRC *outStreamSpec = new COutStreamWithCRC; - CMyComPtr outStream(outStreamSpec); - outStreamSpec->SetStream(realOutStream); - outStreamSpec->Init(); - realOutStream.Release(); - - /* - for (int partIndex = 0; partIndex < 1; partIndex++) - { - CMyComPtr inStream; - - // item redefinition - const CItemEx &item = _items[refItem.ItemIndex + partIndex]; - - NArchive::NRar::CInArchive &archive = _archives[refItem.VolumeIndex + partIndex]; - - inStream.Attach(archive.CreateLimitedStream(item.GetDataPosition(), - item.PackSize)); - */ - if (!folderInStream) - { - folderInStreamSpec = new CFolderInStream; - folderInStream = folderInStreamSpec; - } - - folderInStreamSpec->Init(&_archives, &_items, refItem); - - UInt64 packSize = currentPackSize; - - // packedPos += item.PackSize; - // unpackedPos += 0; - - CMyComPtr inStream; - if (item.IsEncrypted()) - { - CMyComPtr cryptoSetPassword; - if (item.UnPackVersion >= 29) - { - if (!rar29CryptoDecoder) - { - rar29CryptoDecoderSpec = new NCrypto::NRar29::CDecoder; - rar29CryptoDecoder = rar29CryptoDecoderSpec; - // RINOK(rar29CryptoDecoder.CoCreateInstance(CLSID_CCryptoRar29Decoder)); - } - rar29CryptoDecoderSpec->SetRar350Mode(item.UnPackVersion < 36); - CMyComPtr cryptoProperties; - RINOK(rar29CryptoDecoder.QueryInterface(IID_ICompressSetDecoderProperties2, - &cryptoProperties)); - RINOK(cryptoProperties->SetDecoderProperties2(item.Salt, item.HasSalt() ? sizeof(item.Salt) : 0)); - filterStreamSpec->Filter = rar29CryptoDecoder; - } - else if (item.UnPackVersion >= 20) - { - if (!rar20CryptoDecoder) - { - rar20CryptoDecoderSpec = new NCrypto::NRar20::CDecoder; - rar20CryptoDecoder = rar20CryptoDecoderSpec; - // RINOK(rar20CryptoDecoder.CoCreateInstance(CLSID_CCryptoRar20Decoder)); - } - filterStreamSpec->Filter = rar20CryptoDecoder; - } - else - { - outStream.Release(); - RINOK(extractCallback->SetOperationResult(NArchive::NExtract::NOperationResult::kUnSupportedMethod)); - continue; - } - RINOK(filterStreamSpec->Filter.QueryInterface(IID_ICryptoSetPassword, - &cryptoSetPassword)); - - if (!getTextPassword) - extractCallback.QueryInterface(IID_ICryptoGetTextPassword, - &getTextPassword); - if (getTextPassword) - { - CMyComBSTR password; - RINOK(getTextPassword->CryptoGetTextPassword(&password)); - if (item.UnPackVersion >= 29) - { - CByteBuffer buffer; - UString unicodePassword(password); - const UInt32 sizeInBytes = unicodePassword.Length() * 2; - buffer.SetCapacity(sizeInBytes); - for (int i = 0; i < unicodePassword.Length(); i++) - { - wchar_t c = unicodePassword[i]; - ((Byte *)buffer)[i * 2] = (Byte)c; - ((Byte *)buffer)[i * 2 + 1] = (Byte)(c >> 8); - } - RINOK(cryptoSetPassword->CryptoSetPassword( - (const Byte *)buffer, sizeInBytes)); - } - else - { - AString oemPassword = UnicodeStringToMultiByte( - (const wchar_t *)password, CP_OEMCP); - RINOK(cryptoSetPassword->CryptoSetPassword( - (const Byte *)(const char *)oemPassword, oemPassword.Length())); - } - } - else - { - RINOK(cryptoSetPassword->CryptoSetPassword(0, 0)); - } - filterStreamSpec->SetInStream(folderInStream); - inStream = filterStream; - } - else - { - inStream = folderInStream; - } - CMyComPtr commonCoder; - switch(item.Method) - { - case '0': - { - commonCoder = copyCoder; - break; - } - case '1': - case '2': - case '3': - case '4': - case '5': - { - /* - if (item.UnPackVersion >= 29) - { - outStream.Release(); - RINOK(extractCallback->SetOperationResult(NArchive::NExtract::NOperationResult::kUnSupportedMethod)); - continue; - } - */ - int m; - for (m = 0; m < methodItems.Size(); m++) - if (methodItems[m].RarUnPackVersion == item.UnPackVersion) - break; - if (m == methodItems.Size()) - { - CMethodItem mi; - mi.RarUnPackVersion = item.UnPackVersion; - - mi.Coder.Release(); - if (item.UnPackVersion <= 30) - { - UInt32 methodID = 0x040300; - if (item.UnPackVersion < 20) - methodID += 1; - else if (item.UnPackVersion < 29) - methodID += 2; - else - methodID += 3; - RINOK(CreateCoder(EXTERNAL_CODECS_VARS methodID, mi.Coder, false)); - } - - if (mi.Coder == 0) - { - outStream.Release(); - RINOK(extractCallback->SetOperationResult(NArchive::NExtract::NOperationResult::kUnSupportedMethod)); - continue; - } - - m = methodItems.Add(mi); - } - CMyComPtr decoder = methodItems[m].Coder; - - CMyComPtr compressSetDecoderProperties; - RINOK(decoder.QueryInterface(IID_ICompressSetDecoderProperties2, - &compressSetDecoderProperties)); - - Byte isSolid = (Byte)((IsSolid(index) || item.IsSplitBefore()) ? 1: 0); - if (solidStart) - { - isSolid = false; - solidStart = false; - } - - - RINOK(compressSetDecoderProperties->SetDecoderProperties2(&isSolid, 1)); - - commonCoder = decoder; - break; - } - default: - outStream.Release(); - RINOK(extractCallback->SetOperationResult(NArchive::NExtract::NOperationResult::kUnSupportedMethod)); - continue; - } - HRESULT result = commonCoder->Code(inStream, outStream, &packSize, &item.Size, progress); - if (item.IsEncrypted()) - filterStreamSpec->ReleaseInStream(); - if (result == S_FALSE) - { - outStream.Release(); - RINOK(extractCallback->SetOperationResult(NArchive::NExtract::NOperationResult::kDataError)); - continue; - } - if (result != S_OK) - return result; - - /* - if (refItem.NumItems == 1 && - !item.IsSplitBefore() && !item.IsSplitAfter()) - */ - { - const CItemEx &lastItem = _items[refItem.ItemIndex + refItem.NumItems - 1]; - bool crcOK = outStreamSpec->GetCRC() == lastItem.FileCRC; - outStream.Release(); - RINOK(extractCallback->SetOperationResult(crcOK ? NArchive::NExtract::NOperationResult::kOK: - NArchive::NExtract::NOperationResult::kCRCError)); - } - /* - else - { - bool crcOK = true; - for (int partIndex = 0; partIndex < refItem.NumItems; partIndex++) - { - const CItemEx &item = _items[refItem.ItemIndex + partIndex]; - if (item.FileCRC != folderInStreamSpec->CRCs[partIndex]) - { - crcOK = false; - break; - } - } - RINOK(extractCallback->SetOperationResult(crcOK ? NArchive::NExtract::NOperationResult::kOK: - NArchive::NExtract::NOperationResult::kCRCError)); - } - */ - } - return S_OK; - COM_TRY_END -} - -IMPL_ISetCompressCodecsInfo - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarHandler.h b/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarHandler.h deleted file mode 100644 index dff8ed322..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarHandler.h +++ /dev/null @@ -1,60 +0,0 @@ -// Rar/Handler.h - -#ifndef __RAR_HANDLER_H -#define __RAR_HANDLER_H - -#include "../IArchive.h" -#include "RarIn.h" -#include "RarVolumeInStream.h" - -#include "../../Common/CreateCoder.h" - -namespace NArchive { -namespace NRar { - -class CHandler: - public IInArchive, - PUBLIC_ISetCompressCodecsInfo - public CMyUnknownImp -{ -public: - MY_QUERYINTERFACE_BEGIN2(IInArchive) - QUERY_ENTRY_ISetCompressCodecsInfo - MY_QUERYINTERFACE_END - MY_ADDREF_RELEASE - - INTERFACE_IInArchive(;) - - DECL_ISetCompressCodecsInfo - -private: - CRecordVector _refItems; - CObjectVector _items; - CObjectVector _archives; - NArchive::NRar::CInArchiveInfo _archiveInfo; - - DECL_EXTERNAL_CODECS_VARS - - UInt64 GetPackSize(int refIndex) const; - // NArchive::NRar::CInArchive _archive; - - bool IsSolid(int refIndex) - { - const CItemEx &item = _items[_refItems[refIndex].ItemIndex]; - if (item.UnPackVersion < 20) - { - if (_archiveInfo.IsSolid()) - return (refIndex > 0); - return false; - } - return item.IsSolid(); - } - - HRESULT Open2(IInStream *stream, - const UInt64 *maxCheckStartPosition, - IArchiveOpenCallback *openArchiveCallback); -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarHeader.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarHeader.cpp deleted file mode 100644 index 90dc8366f..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarHeader.cpp +++ /dev/null @@ -1,19 +0,0 @@ -// Archive/Rar/Headers.cpp - -#include "StdAfx.h" - -#include "RarHeader.h" - -namespace NArchive{ -namespace NRar{ -namespace NHeader{ - -Byte kMarker[kMarkerSize] = {0x52 + 1, 0x61, 0x72, 0x21, 0x1a, 0x07, 0x00}; - -class CMarkerInitializer -{ -public: - CMarkerInitializer() { kMarker[0]--; }; -} g_MarkerInitializer; - -}}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarHeader.h b/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarHeader.h deleted file mode 100644 index e5a3e1deb..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarHeader.h +++ /dev/null @@ -1,224 +0,0 @@ -// Archive/RarHeader.h - -#ifndef __ARCHIVE_RAR_HEADER_H -#define __ARCHIVE_RAR_HEADER_H - -#include "Common/Types.h" - -namespace NArchive{ -namespace NRar{ -namespace NHeader{ - -const int kMarkerSize = 7; -extern Byte kMarker[kMarkerSize]; - -const int kArchiveSolid = 0x1; - -namespace NBlockType -{ - enum EBlockType - { - kMarker = 0x72, - kArchiveHeader = 0x73, - kFileHeader = 0x74, - kCommentHeader = 0x75, - kOldAuthenticity = 0x76, - kSubBlock = 0x77, - kRecoveryRecord = 0x78, - kAuthenticity = 0x79, - - kEndOfArchive = 0x7B // Is not safe - }; -} - -namespace NArchive -{ - const UInt16 kVolume = 1; - const UInt16 kComment = 2; - const UInt16 kLock = 4; - const UInt16 kSolid = 8; - const UInt16 kNewVolName = 0x10; // ('volname.partN.rar') - const UInt16 kAuthenticity = 0x20; - const UInt16 kRecovery = 0x40; - const UInt16 kBlockEncryption = 0x80; - const UInt16 kFirstVolume = 0x100; // (set only by RAR 3.0 and later) - const UInt16 kEncryptVer = 0x200; // RAR 3.6 there is EncryptVer Byte in End of MainHeader - - const int kHeaderSizeMin = 7; - - struct CBlock - { - UInt16 CRC; - Byte Type; - UInt16 Flags; - UInt16 Size; - UInt16 Reserved1; - UInt32 Reserved2; - // UInt16 GetRealCRC() const; - }; - - const int kArchiveHeaderSize = 13; - - const int kBlockHeadersAreEncrypted = 0x80; - - struct CHeader360: public CBlock - { - Byte EncryptVersion; - bool IsEncrypted() const { return (Flags & NHeader::NArchive::kBlockEncryption) != 0; } - bool IsThereEncryptVer() const { return (Flags & NHeader::NArchive::kEncryptVer) != 0; } - bool IsEncryptOld() const { return (!IsThereEncryptVer() || EncryptVersion < 36); } - UInt32 GetBaseSize() const { return kArchiveHeaderSize + (IsEncryptOld() ? 0 : 1); } - }; -} - -namespace NFile -{ - const int kSplitBefore = 1 << 0; - const int kSplitAfter = 1 << 1; - const int kEncrypted = 1 << 2; - const int kComment = 1 << 3; - const int kSolid = 1 << 4; - - const int kDictBitStart = 5; - const int kNumDictBits = 3; - const int kDictMask = (1 << kNumDictBits) - 1; - const int kDictDirectoryValue = 0x7; - - const int kSize64Bits = 1 << 8; - const int kUnicodeName = 1 << 9; - const int kSalt = 1 << 10; - const int kOldVersion = 1 << 11; - const int kExtTime = 1 << 12; - // const int kExtFlags = 1 << 13; - // const int kSkipIfUnknown = 1 << 14; - - const int kLongBlock = 1 << 15; - - /* - struct CBlock - { - // UInt16 HeadCRC; - // Byte Type; - // UInt16 Flags; - // UInt16 HeadSize; - UInt32 PackSize; - UInt32 UnPackSize; - Byte HostOS; - UInt32 FileCRC; - UInt32 Time; - Byte UnPackVersion; - Byte Method; - UInt16 NameSize; - UInt32 Attributes; - }; - */ - - /* - struct CBlock32 - { - UInt16 HeadCRC; - Byte Type; - UInt16 Flags; - UInt16 HeadSize; - UInt32 PackSize; - UInt32 UnPackSize; - Byte HostOS; - UInt32 FileCRC; - UInt32 Time; - Byte UnPackVersion; - Byte Method; - UInt16 NameSize; - UInt32 Attributes; - UInt16 GetRealCRC(const void *aName, UInt32 aNameSize, - bool anExtraDataDefined = false, Byte *anExtraData = 0) const; - }; - struct CBlock64 - { - UInt16 HeadCRC; - Byte Type; - UInt16 Flags; - UInt16 HeadSize; - UInt32 PackSizeLow; - UInt32 UnPackSizeLow; - Byte HostOS; - UInt32 FileCRC; - UInt32 Time; - Byte UnPackVersion; - Byte Method; - UInt16 NameSize; - UInt32 Attributes; - UInt32 PackSizeHigh; - UInt32 UnPackSizeHigh; - UInt16 GetRealCRC(const void *aName, UInt32 aNameSize) const; - }; - */ - - const int kLabelFileAttribute = 0x08; - const int kWinFileDirectoryAttributeMask = 0x10; - - enum CHostOS - { - kHostMSDOS = 0, - kHostOS2 = 1, - kHostWin32 = 2, - kHostUnix = 3, - kHostMacOS = 4, - kHostBeOS = 5 - }; -} - -namespace NBlock -{ - const UInt16 kLongBlock = 1 << 15; - struct CBlock - { - UInt16 CRC; - Byte Type; - UInt16 Flags; - UInt16 HeadSize; - // UInt32 DataSize; - }; -} - -/* -struct CSubBlock -{ - UInt16 HeadCRC; - Byte HeadType; - UInt16 Flags; - UInt16 HeadSize; - UInt32 DataSize; - UInt16 SubType; - Byte Level; // Reserved : Must be 0 -}; - -struct CCommentBlock -{ - UInt16 HeadCRC; - Byte HeadType; - UInt16 Flags; - UInt16 HeadSize; - UInt16 UnpSize; - Byte UnpVer; - Byte Method; - UInt16 CommCRC; -}; - - -struct CProtectHeader -{ - UInt16 HeadCRC; - Byte HeadType; - UInt16 Flags; - UInt16 HeadSize; - UInt32 DataSize; - Byte Version; - UInt16 RecSectors; - UInt32 TotalBlocks; - Byte Mark[8]; -}; -*/ - -}}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarIn.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarIn.cpp deleted file mode 100644 index f434bce63..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarIn.cpp +++ /dev/null @@ -1,513 +0,0 @@ -// Archive/RarIn.cpp - -#include "StdAfx.h" - -#include "Common/StringConvert.h" -#include "Common/UTFConvert.h" - -#include "RarIn.h" -#include "../../Common/LimitedStreams.h" -#include "../../Common/StreamUtils.h" - -#include "../Common/FindSignature.h" - -extern "C" -{ - #include "../../../../C/7zCrc.h" -} - -namespace NArchive { -namespace NRar { - -void CInArchive::ThrowExceptionWithCode( - CInArchiveException::CCauseType cause) -{ - throw CInArchiveException(cause); -} - -HRESULT CInArchive::Open(IInStream *inStream, const UInt64 *searchHeaderSizeLimit) -{ - try - { - Close(); - HRESULT res = Open2(inStream, searchHeaderSizeLimit); - if (res == S_OK) - return res; - Close(); - return res; - } - catch(...) { Close(); throw; } -} - -void CInArchive::Close() -{ - m_Stream.Release(); -} - - -static inline bool TestMarkerCandidate(const void *aTestBytes) -{ - for (UInt32 i = 0; i < NHeader::kMarkerSize; i++) - if (((const Byte *)aTestBytes)[i] != NHeader::kMarker[i]) - return false; - return true; -} - -HRESULT CInArchive::FindAndReadMarker(IInStream *stream, const UInt64 *searchHeaderSizeLimit) -{ - RINOK(FindSignatureInStream(stream, - NHeader::kMarker, NHeader::kMarkerSize, - searchHeaderSizeLimit, m_ArchiveStartPosition)); - m_Stream = stream; - m_Position = m_ArchiveStartPosition + NHeader::kMarkerSize; - return m_Stream->Seek(m_Position, STREAM_SEEK_SET, NULL); -} - -void CInArchive::ThrowUnexpectedEndOfArchiveException() -{ - ThrowExceptionWithCode(CInArchiveException::kUnexpectedEndOfArchive); -} - -bool CInArchive::ReadBytesAndTestSize(void *data, UInt32 size) -{ - if (m_CryptoMode) - { - const Byte *bufData = (const Byte *)m_DecryptedData; - UInt32 bufSize = m_DecryptedDataSize; - UInt32 i; - for (i = 0; i < size && m_CryptoPos < bufSize; i++) - ((Byte *)data)[i] = bufData[m_CryptoPos++]; - return (i == size); - } - return (ReadStream_FALSE(m_Stream, data, size) == S_OK); -} - -void CInArchive::ReadBytesAndTestResult(void *data, UInt32 size) -{ - if(!ReadBytesAndTestSize(data,size)) - ThrowUnexpectedEndOfArchiveException(); -} - -HRESULT CInArchive::ReadBytes(void *data, UInt32 size, UInt32 *processedSize) -{ - size_t realProcessedSize = size; - HRESULT result = ReadStream(m_Stream, data, &realProcessedSize); - if (processedSize != NULL) - *processedSize = (UInt32)realProcessedSize; - AddToSeekValue(realProcessedSize); - return result; -} - -static UInt32 CrcUpdateUInt16(UInt32 crc, UInt16 v) -{ - crc = CRC_UPDATE_BYTE(crc, (Byte)(v & 0xFF)); - crc = CRC_UPDATE_BYTE(crc, (Byte)((v >> 8) & 0xFF)); - return crc; -} - -static UInt32 CrcUpdateUInt32(UInt32 crc, UInt32 v) -{ - crc = CRC_UPDATE_BYTE(crc, (Byte)(v & 0xFF)); - crc = CRC_UPDATE_BYTE(crc, (Byte)((v >> 8) & 0xFF)); - crc = CRC_UPDATE_BYTE(crc, (Byte)((v >> 16) & 0xFF)); - crc = CRC_UPDATE_BYTE(crc, (Byte)((v >> 24) & 0xFF)); - return crc; -} - - -HRESULT CInArchive::Open2(IInStream *stream, const UInt64 *searchHeaderSizeLimit) -{ - m_CryptoMode = false; - RINOK(stream->Seek(0, STREAM_SEEK_SET, &m_StreamStartPosition)); - m_Position = m_StreamStartPosition; - - RINOK(FindAndReadMarker(stream, searchHeaderSizeLimit)); - - Byte buf[NHeader::NArchive::kArchiveHeaderSize]; - UInt32 processedSize; - ReadBytes(buf, sizeof(buf), &processedSize); - if (processedSize != sizeof(buf)) - return S_FALSE; - m_CurData = buf; - m_CurPos = 0; - m_PosLimit = sizeof(buf); - - m_ArchiveHeader.CRC = ReadUInt16(); - m_ArchiveHeader.Type = ReadByte(); - m_ArchiveHeader.Flags = ReadUInt16(); - m_ArchiveHeader.Size = ReadUInt16(); - m_ArchiveHeader.Reserved1 = ReadUInt16(); - m_ArchiveHeader.Reserved2 = ReadUInt32(); - m_ArchiveHeader.EncryptVersion = 0; - - UInt32 crc = CRC_INIT_VAL; - crc = CRC_UPDATE_BYTE(crc, m_ArchiveHeader.Type); - crc = CrcUpdateUInt16(crc, m_ArchiveHeader.Flags); - crc = CrcUpdateUInt16(crc, m_ArchiveHeader.Size); - crc = CrcUpdateUInt16(crc, m_ArchiveHeader.Reserved1); - crc = CrcUpdateUInt32(crc, m_ArchiveHeader.Reserved2); - - if (m_ArchiveHeader.IsThereEncryptVer() && m_ArchiveHeader.Size > NHeader::NArchive::kArchiveHeaderSize) - { - ReadBytes(&m_ArchiveHeader.EncryptVersion, 1, &processedSize); - if (processedSize != 1) - return S_FALSE; - crc = CRC_UPDATE_BYTE(crc, m_ArchiveHeader.EncryptVersion); - } - - if(m_ArchiveHeader.CRC != (CRC_GET_DIGEST(crc) & 0xFFFF)) - ThrowExceptionWithCode(CInArchiveException::kArchiveHeaderCRCError); - if (m_ArchiveHeader.Type != NHeader::NBlockType::kArchiveHeader) - return S_FALSE; - m_ArchiveCommentPosition = m_Position; - m_SeekOnArchiveComment = true; - return S_OK; -} - -void CInArchive::SkipArchiveComment() -{ - if (!m_SeekOnArchiveComment) - return; - AddToSeekValue(m_ArchiveHeader.Size - m_ArchiveHeader.GetBaseSize()); - m_SeekOnArchiveComment = false; -} - -void CInArchive::GetArchiveInfo(CInArchiveInfo &archiveInfo) const -{ - archiveInfo.StartPosition = m_ArchiveStartPosition; - archiveInfo.Flags = m_ArchiveHeader.Flags; - archiveInfo.CommentPosition = m_ArchiveCommentPosition; - archiveInfo.CommentSize = (UInt16)(m_ArchiveHeader.Size - NHeader::NArchive::kArchiveHeaderSize); -} - -static void DecodeUnicodeFileName(const char *name, const Byte *encName, - int encSize, wchar_t *unicodeName, int maxDecSize) -{ - int encPos = 0; - int decPos = 0; - int flagBits = 0; - Byte flags = 0; - Byte highByte = encName[encPos++]; - while (encPos < encSize && decPos < maxDecSize) - { - if (flagBits == 0) - { - flags = encName[encPos++]; - flagBits = 8; - } - switch(flags >> 6) - { - case 0: - unicodeName[decPos++] = encName[encPos++]; - break; - case 1: - unicodeName[decPos++] = (wchar_t)(encName[encPos++] + (highByte << 8)); - break; - case 2: - unicodeName[decPos++] = (wchar_t)(encName[encPos] + (encName[encPos + 1] << 8)); - encPos += 2; - break; - case 3: - { - int length = encName[encPos++]; - if (length & 0x80) - { - Byte correction = encName[encPos++]; - for (length = (length & 0x7f) + 2; - length > 0 && decPos < maxDecSize; length--, decPos++) - unicodeName[decPos] = (wchar_t)(((name[decPos] + correction) & 0xff) + (highByte << 8)); - } - else - for (length += 2; length > 0 && decPos < maxDecSize; length--, decPos++) - unicodeName[decPos] = name[decPos]; - } - break; - } - flags <<= 2; - flagBits -= 2; - } - unicodeName[decPos < maxDecSize ? decPos : maxDecSize - 1] = 0; -} - -void CInArchive::ReadName(CItemEx &item, int nameSize) -{ - item.UnicodeName.Empty(); - if (nameSize > 0) - { - m_NameBuffer.EnsureCapacity(nameSize + 1); - char *buffer = (char *)m_NameBuffer; - - for (int i = 0; i < nameSize; i++) - buffer[i] = ReadByte(); - - int mainLen; - for (mainLen = 0; mainLen < nameSize; mainLen++) - if (buffer[mainLen] == '\0') - break; - buffer[mainLen] = '\0'; - item.Name = buffer; - - if(item.HasUnicodeName()) - { - if(mainLen < nameSize) - { - int unicodeNameSizeMax = MyMin(nameSize, (0x400)); - _unicodeNameBuffer.EnsureCapacity(unicodeNameSizeMax + 1); - DecodeUnicodeFileName(buffer, (const Byte *)buffer + mainLen + 1, - nameSize - (mainLen + 1), _unicodeNameBuffer, unicodeNameSizeMax); - item.UnicodeName = _unicodeNameBuffer; - } - else if (!ConvertUTF8ToUnicode(item.Name, item.UnicodeName)) - item.UnicodeName.Empty(); - } - } - else - item.Name.Empty(); -} - -Byte CInArchive::ReadByte() -{ - if (m_CurPos >= m_PosLimit) - throw CInArchiveException(CInArchiveException::kIncorrectArchive); - return m_CurData[m_CurPos++]; -} - -UInt16 CInArchive::ReadUInt16() -{ - UInt16 value = 0; - for (int i = 0; i < 2; i++) - { - Byte b = ReadByte(); - value |= (UInt16(b) << (8 * i)); - } - return value; -} - -UInt32 CInArchive::ReadUInt32() -{ - UInt32 value = 0; - for (int i = 0; i < 4; i++) - { - Byte b = ReadByte(); - value |= (UInt32(b) << (8 * i)); - } - return value; -} - -void CInArchive::ReadTime(Byte mask, CRarTime &rarTime) -{ - rarTime.LowSecond = (Byte)(((mask & 4) != 0) ? 1 : 0); - int numDigits = (mask & 3); - rarTime.SubTime[0] = rarTime.SubTime[1] = rarTime.SubTime[2] = 0; - for (int i = 0; i < numDigits; i++) - rarTime.SubTime[3 - numDigits + i] = ReadByte(); -} - -void CInArchive::ReadHeaderReal(CItemEx &item) -{ - item.Flags = m_BlockHeader.Flags; - item.PackSize = ReadUInt32(); - item.Size = ReadUInt32(); - item.HostOS = ReadByte(); - item.FileCRC = ReadUInt32(); - item.MTime.DosTime = ReadUInt32(); - item.UnPackVersion = ReadByte(); - item.Method = ReadByte(); - int nameSize = ReadUInt16(); - item.Attrib = ReadUInt32(); - - item.MTime.LowSecond = 0; - item.MTime.SubTime[0] = - item.MTime.SubTime[1] = - item.MTime.SubTime[2] = 0; - - if((item.Flags & NHeader::NFile::kSize64Bits) != 0) - { - item.PackSize |= ((UInt64)ReadUInt32() << 32); - item.Size |= ((UInt64)ReadUInt32() << 32); - } - - ReadName(item, nameSize); - - if (item.HasSalt()) - for (int i = 0; i < sizeof(item.Salt); i++) - item.Salt[i] = ReadByte(); - - // some rar archives have HasExtTime flag without field. - if (m_CurPos < m_PosLimit && item.HasExtTime()) - { - Byte accessMask = (Byte)(ReadByte() >> 4); - Byte b = ReadByte(); - Byte modifMask = (Byte)(b >> 4); - Byte createMask = (Byte)(b & 0xF); - if ((modifMask & 8) != 0) - ReadTime(modifMask, item.MTime); - item.CTimeDefined = ((createMask & 8) != 0); - if (item.CTimeDefined) - { - item.CTime.DosTime = ReadUInt32(); - ReadTime(createMask, item.CTime); - } - item.ATimeDefined = ((accessMask & 8) != 0); - if (item.ATimeDefined) - { - item.ATime.DosTime = ReadUInt32(); - ReadTime(accessMask, item.ATime); - } - } - - UInt16 fileHeaderWithNameSize = (UInt16)m_CurPos; - - item.Position = m_Position; - item.MainPartSize = fileHeaderWithNameSize; - item.CommentSize = (UInt16)(m_BlockHeader.HeadSize - fileHeaderWithNameSize); - - if (m_CryptoMode) - item.AlignSize = (UInt16)((16 - ((m_BlockHeader.HeadSize) & 0xF)) & 0xF); - else - item.AlignSize = 0; - AddToSeekValue(m_BlockHeader.HeadSize); -} - -void CInArchive::AddToSeekValue(UInt64 addValue) -{ - m_Position += addValue; -} - -HRESULT CInArchive::GetNextItem(CItemEx &item, ICryptoGetTextPassword *getTextPassword) -{ - if (m_SeekOnArchiveComment) - SkipArchiveComment(); - for (;;) - { - if(!SeekInArchive(m_Position)) - return S_FALSE; - if (!m_CryptoMode && (m_ArchiveHeader.Flags & - NHeader::NArchive::kBlockHeadersAreEncrypted) != 0) - { - m_CryptoMode = false; - if (getTextPassword == 0) - return S_FALSE; - if(!SeekInArchive(m_Position)) - return S_FALSE; - if (!m_RarAES) - { - m_RarAESSpec = new NCrypto::NRar29::CDecoder; - m_RarAES = m_RarAESSpec; - } - m_RarAESSpec->SetRar350Mode(m_ArchiveHeader.IsEncryptOld()); - - // Salt - const UInt32 kSaltSize = 8; - Byte salt[kSaltSize]; - if(!ReadBytesAndTestSize(salt, kSaltSize)) - return S_FALSE; - m_Position += kSaltSize; - RINOK(m_RarAESSpec->SetDecoderProperties2(salt, kSaltSize)) - // Password - CMyComBSTR password; - RINOK(getTextPassword->CryptoGetTextPassword(&password)) - UString unicodePassword(password); - - CByteBuffer buffer; - const UInt32 sizeInBytes = unicodePassword.Length() * 2; - buffer.SetCapacity(sizeInBytes); - for (int i = 0; i < unicodePassword.Length(); i++) - { - wchar_t c = unicodePassword[i]; - ((Byte *)buffer)[i * 2] = (Byte)c; - ((Byte *)buffer)[i * 2 + 1] = (Byte)(c >> 8); - } - - RINOK(m_RarAESSpec->CryptoSetPassword((const Byte *)buffer, sizeInBytes)); - - const UInt32 kDecryptedBufferSize = (1 << 12); - if (m_DecryptedData.GetCapacity() == 0) - { - m_DecryptedData.SetCapacity(kDecryptedBufferSize); - } - RINOK(m_RarAES->Init()); - size_t decryptedDataSizeT = kDecryptedBufferSize; - RINOK(ReadStream(m_Stream, (Byte *)m_DecryptedData, &decryptedDataSizeT)); - m_DecryptedDataSize = (UInt32)decryptedDataSizeT; - m_DecryptedDataSize = m_RarAES->Filter((Byte *)m_DecryptedData, m_DecryptedDataSize); - - m_CryptoMode = true; - m_CryptoPos = 0; - } - - m_FileHeaderData.EnsureCapacity(7); - if(!ReadBytesAndTestSize((Byte *)m_FileHeaderData, 7)) - return S_FALSE; - - m_CurData = (Byte *)m_FileHeaderData; - m_CurPos = 0; - m_PosLimit = 7; - m_BlockHeader.CRC = ReadUInt16(); - m_BlockHeader.Type = ReadByte(); - m_BlockHeader.Flags = ReadUInt16(); - m_BlockHeader.HeadSize = ReadUInt16(); - - if (m_BlockHeader.HeadSize < 7) - ThrowExceptionWithCode(CInArchiveException::kIncorrectArchive); - - if (m_BlockHeader.Type == NHeader::NBlockType::kEndOfArchive) - return S_FALSE; - - if (m_BlockHeader.Type == NHeader::NBlockType::kFileHeader) - { - m_FileHeaderData.EnsureCapacity(m_BlockHeader.HeadSize); - m_CurData = (Byte *)m_FileHeaderData; - m_PosLimit = m_BlockHeader.HeadSize; - ReadBytesAndTestResult(m_CurData + m_CurPos, m_BlockHeader.HeadSize - 7); - ReadHeaderReal(item); - if ((CrcCalc(m_CurData + 2, - m_BlockHeader.HeadSize - item.CommentSize - 2) & 0xFFFF) != m_BlockHeader.CRC) - ThrowExceptionWithCode(CInArchiveException::kFileHeaderCRCError); - - FinishCryptoBlock(); - m_CryptoMode = false; - SeekInArchive(m_Position); // Move Position to compressed Data; - AddToSeekValue(item.PackSize); // m_Position points to next header; - return S_OK; - } - if (m_CryptoMode && m_BlockHeader.HeadSize > (1 << 12)) - return E_FAIL; // it's for bad passwords - if ((m_BlockHeader.Flags & NHeader::NBlock::kLongBlock) != 0) - { - m_FileHeaderData.EnsureCapacity(7 + 4); - m_CurData = (Byte *)m_FileHeaderData; - ReadBytesAndTestResult(m_CurData + m_CurPos, 4); // test it - m_PosLimit = 7 + 4; - UInt32 dataSize = ReadUInt32(); - AddToSeekValue(dataSize); - if (m_CryptoMode && dataSize > (1 << 27)) - return E_FAIL; // it's for bad passwords - m_CryptoPos = m_BlockHeader.HeadSize; - } - else - m_CryptoPos = 0; - AddToSeekValue(m_BlockHeader.HeadSize); - FinishCryptoBlock(); - m_CryptoMode = false; - } -} - -bool CInArchive::SeekInArchive(UInt64 position) -{ - UInt64 newPosition; - m_Stream->Seek(position, STREAM_SEEK_SET, &newPosition); - return newPosition == position; -} - -ISequentialInStream* CInArchive::CreateLimitedStream(UInt64 position, UInt64 size) -{ - CLimitedSequentialInStream *streamSpec = new CLimitedSequentialInStream; - CMyComPtr inStream(streamSpec); - SeekInArchive(position); - streamSpec->SetStream(m_Stream); - streamSpec->Init(size); - return inStream.Detach(); -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarIn.h b/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarIn.h deleted file mode 100644 index 500f1134e..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarIn.h +++ /dev/null @@ -1,126 +0,0 @@ -// RarIn.h - -#ifndef __ARCHIVE_RAR_IN_H -#define __ARCHIVE_RAR_IN_H - -#include "Common/DynamicBuffer.h" -#include "Common/MyCom.h" - -#include "../../ICoder.h" -#include "../../IStream.h" - -#include "../../Common/StreamObjects.h" - -#include "../../Crypto/RarAes.h" - -#include "RarHeader.h" -#include "RarItem.h" - -namespace NArchive { -namespace NRar { - -class CInArchiveException -{ -public: - enum CCauseType - { - kUnexpectedEndOfArchive = 0, - kArchiveHeaderCRCError, - kFileHeaderCRCError, - kIncorrectArchive - } - Cause; - CInArchiveException(CCauseType cause) : Cause(cause) {} -}; - -class CInArchiveInfo -{ -public: - UInt64 StartPosition; - UInt16 Flags; - UInt64 CommentPosition; - UInt16 CommentSize; - bool IsSolid() const { return (Flags & NHeader::NArchive::kSolid) != 0; } - bool IsCommented() const { return (Flags & NHeader::NArchive::kComment) != 0; } - bool IsVolume() const { return (Flags & NHeader::NArchive::kVolume) != 0; } - bool HaveNewVolumeName() const { return (Flags & NHeader::NArchive::kNewVolName) != 0; } - bool IsEncrypted() const { return (Flags & NHeader::NArchive::kBlockEncryption) != 0; } -}; - -class CInArchive -{ - CMyComPtr m_Stream; - - UInt64 m_StreamStartPosition; - UInt64 m_Position; - UInt64 m_ArchiveStartPosition; - - NHeader::NArchive::CHeader360 m_ArchiveHeader; - CDynamicBuffer m_NameBuffer; - CDynamicBuffer _unicodeNameBuffer; - bool m_SeekOnArchiveComment; - UInt64 m_ArchiveCommentPosition; - - void ReadName(CItemEx &item, int nameSize); - void ReadHeaderReal(CItemEx &item); - - HRESULT ReadBytes(void *data, UInt32 size, UInt32 *aProcessedSize); - bool ReadBytesAndTestSize(void *data, UInt32 size); - void ReadBytesAndTestResult(void *data, UInt32 size); - - HRESULT FindAndReadMarker(IInStream *stream, const UInt64 *searchHeaderSizeLimit); - HRESULT Open2(IInStream *stream, const UInt64 *searchHeaderSizeLimit); - - void ThrowExceptionWithCode(CInArchiveException::CCauseType cause); - void ThrowUnexpectedEndOfArchiveException(); - - void AddToSeekValue(UInt64 addValue); - -protected: - - CDynamicBuffer m_FileHeaderData; - - NHeader::NBlock::CBlock m_BlockHeader; - - NCrypto::NRar29::CDecoder *m_RarAESSpec; - CMyComPtr m_RarAES; - - Byte *m_CurData; // it must point to start of Rar::Block - UInt32 m_CurPos; - UInt32 m_PosLimit; - Byte ReadByte(); - UInt16 ReadUInt16(); - UInt32 ReadUInt32(); - void ReadTime(Byte mask, CRarTime &rarTime); - - CBuffer m_DecryptedData; - UInt32 m_DecryptedDataSize; - - bool m_CryptoMode; - UInt32 m_CryptoPos; - void FinishCryptoBlock() - { - if (m_CryptoMode) - while ((m_CryptoPos & 0xF) != 0) - { - m_CryptoPos++; - m_Position++; - } - } - -public: - HRESULT Open(IInStream *inStream, const UInt64 *searchHeaderSizeLimit); - void Close(); - HRESULT GetNextItem(CItemEx &item, ICryptoGetTextPassword *getTextPassword); - - void SkipArchiveComment(); - - void GetArchiveInfo(CInArchiveInfo &archiveInfo) const; - - bool SeekInArchive(UInt64 position); - ISequentialInStream *CreateLimitedStream(UInt64 position, UInt64 size); -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarItem.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarItem.cpp deleted file mode 100644 index b0963778b..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarItem.cpp +++ /dev/null @@ -1,55 +0,0 @@ -// RarItem.cpp - -#include "StdAfx.h" - -#include "RarItem.h" - -namespace NArchive{ -namespace NRar{ - -bool CItem::IgnoreItem() const -{ - switch(HostOS) - { - case NHeader::NFile::kHostMSDOS: - case NHeader::NFile::kHostOS2: - case NHeader::NFile::kHostWin32: - return ((Attrib & NHeader::NFile::kLabelFileAttribute) != 0); - } - return false; -} - -bool CItem::IsDir() const -{ - if (GetDictSize() == NHeader::NFile::kDictDirectoryValue) - return true; - switch(HostOS) - { - case NHeader::NFile::kHostMSDOS: - case NHeader::NFile::kHostOS2: - case NHeader::NFile::kHostWin32: - if ((Attrib & FILE_ATTRIBUTE_DIRECTORY) != 0) - return true; - } - return false; -} - -UInt32 CItem::GetWinAttributes() const -{ - UInt32 winAttributes; - switch(HostOS) - { - case NHeader::NFile::kHostMSDOS: - case NHeader::NFile::kHostOS2: - case NHeader::NFile::kHostWin32: - winAttributes = Attrib; - break; - default: - winAttributes = 0; // must be converted from unix value; - } - if (IsDir()) - winAttributes |= NHeader::NFile::kWinFileDirectoryAttributeMask; - return winAttributes; -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarItem.h b/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarItem.h deleted file mode 100644 index 515ecd4be..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarItem.h +++ /dev/null @@ -1,79 +0,0 @@ -// RarItem.h - -#ifndef __ARCHIVE_RAR_ITEM_H -#define __ARCHIVE_RAR_ITEM_H - -#include "Common/Types.h" -#include "Common/MyString.h" - -#include "RarHeader.h" - -namespace NArchive{ -namespace NRar{ - -struct CRarTime -{ - UInt32 DosTime; - Byte LowSecond; - Byte SubTime[3]; -}; - -struct CItem -{ - UInt64 Size; - UInt64 PackSize; - - CRarTime CTime; - CRarTime ATime; - CRarTime MTime; - - UInt32 FileCRC; - UInt32 Attrib; - - UInt16 Flags; - Byte HostOS; - Byte UnPackVersion; - Byte Method; - - bool CTimeDefined; - bool ATimeDefined; - - AString Name; - UString UnicodeName; - - Byte Salt[8]; - - bool IsEncrypted() const { return (Flags & NHeader::NFile::kEncrypted) != 0; } - bool IsSolid() const { return (Flags & NHeader::NFile::kSolid) != 0; } - bool IsCommented() const { return (Flags & NHeader::NFile::kComment) != 0; } - bool IsSplitBefore() const { return (Flags & NHeader::NFile::kSplitBefore) != 0; } - bool IsSplitAfter() const { return (Flags & NHeader::NFile::kSplitAfter) != 0; } - bool HasSalt() const { return (Flags & NHeader::NFile::kSalt) != 0; } - bool HasExtTime() const { return (Flags & NHeader::NFile::kExtTime) != 0; } - bool HasUnicodeName()const { return (Flags & NHeader::NFile::kUnicodeName) != 0; } - bool IsOldVersion() const { return (Flags & NHeader::NFile::kOldVersion) != 0; } - - UInt32 GetDictSize() const { return (Flags >> NHeader::NFile::kDictBitStart) & NHeader::NFile::kDictMask; } - bool IsDir() const; - bool IgnoreItem() const; - UInt32 GetWinAttributes() const; - - CItem(): CTimeDefined(false), ATimeDefined(false) {} -}; - -class CItemEx: public CItem -{ -public: - UInt64 Position; - UInt16 MainPartSize; - UInt16 CommentSize; - UInt16 AlignSize; - UInt64 GetFullSize() const { return MainPartSize + CommentSize + AlignSize + PackSize; }; - // DWORD GetHeaderWithCommentSize() const { return MainPartSize + CommentSize; }; - UInt64 GetCommentPosition() const { return Position + MainPartSize; }; - UInt64 GetDataPosition() const { return GetCommentPosition() + CommentSize + AlignSize; }; -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarRegister.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarRegister.cpp deleted file mode 100644 index f7897a607..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarRegister.cpp +++ /dev/null @@ -1,13 +0,0 @@ -// RarRegister.cpp - -#include "StdAfx.h" - -#include "../../Common/RegisterArc.h" - -#include "RarHandler.h" -static IInArchive *CreateArc() { return new NArchive::NRar::CHandler; } - -static CArcInfo g_ArcInfo = - { L"Rar", L"rar r00", 0, 3, {0x52 , 0x61, 0x72, 0x21, 0x1a, 0x07, 0x00}, 7, false, CreateArc, 0, }; - -REGISTER_ARC(Rar) diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarVolumeInStream.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarVolumeInStream.cpp deleted file mode 100644 index 8b62d9fd9..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarVolumeInStream.cpp +++ /dev/null @@ -1,84 +0,0 @@ -// RarVolumeInStream.cpp - -#include "StdAfx.h" - -#include "RarVolumeInStream.h" - -#include "Windows/Defs.h" -#include "Common/Defs.h" - -extern "C" -{ - #include "../../../../C/7zCrc.h" -} - -namespace NArchive { -namespace NRar { - -void CFolderInStream::Init( - CObjectVector *archives, - const CObjectVector *items, - const CRefItem &refItem) -{ - _archives = archives; - _items = items; - _refItem = refItem; - _curIndex = 0; - CRCs.Clear(); - _fileIsOpen = false; -} - -HRESULT CFolderInStream::OpenStream() -{ - while (_curIndex < _refItem.NumItems) - { - const CItemEx &item = (*_items)[_refItem.ItemIndex + _curIndex]; - _stream.Attach((*_archives)[_refItem.VolumeIndex + _curIndex]. - CreateLimitedStream(item.GetDataPosition(), item.PackSize)); - _curIndex++; - _fileIsOpen = true; - _crc = CRC_INIT_VAL; - return S_OK; - } - return S_OK; -} - -HRESULT CFolderInStream::CloseStream() -{ - CRCs.Add(CRC_GET_DIGEST(_crc)); - _stream.Release(); - _fileIsOpen = false; - return S_OK; -} - -STDMETHODIMP CFolderInStream::Read(void *data, UInt32 size, UInt32 *processedSize) -{ - UInt32 realProcessedSize = 0; - while ((_curIndex < _refItem.NumItems || _fileIsOpen) && size > 0) - { - if (_fileIsOpen) - { - UInt32 localProcessedSize; - RINOK(_stream->Read( - ((Byte *)data) + realProcessedSize, size, &localProcessedSize)); - _crc = CrcUpdate(_crc, ((Byte *)data) + realProcessedSize, localProcessedSize); - if (localProcessedSize == 0) - { - RINOK(CloseStream()); - continue; - } - realProcessedSize += localProcessedSize; - size -= localProcessedSize; - break; - } - else - { - RINOK(OpenStream()); - } - } - if (processedSize != 0) - *processedSize = realProcessedSize; - return S_OK; -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarVolumeInStream.h b/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarVolumeInStream.h deleted file mode 100644 index d175a2c0c..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarVolumeInStream.h +++ /dev/null @@ -1,49 +0,0 @@ -// RarVolumeInStream.h - -#ifndef __RAR_VOLUME_IN_STREAM_H -#define __RAR_VOLUME_IN_STREAM_H - -#include "../../IStream.h" -#include "RarIn.h" - -namespace NArchive { -namespace NRar { - -struct CRefItem -{ - int VolumeIndex; - int ItemIndex; - int NumItems; -}; - -class CFolderInStream: - public ISequentialInStream, - public CMyUnknownImp -{ -public: - MY_UNKNOWN_IMP - - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); - -private: - CObjectVector *_archives; - const CObjectVector *_items; - CRefItem _refItem; - int _curIndex; - UInt32 _crc; - bool _fileIsOpen; - CMyComPtr _stream; - - HRESULT OpenStream(); - HRESULT CloseStream(); -public: - void Init(CObjectVector *archives, - const CObjectVector *items, - const CRefItem &refItem); - - CRecordVector CRCs; -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Rar/StdAfx.h b/desmume/src/windows/7z/CPP/7zip/Archive/Rar/StdAfx.h deleted file mode 100644 index 83fdd22d5..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Rar/StdAfx.h +++ /dev/null @@ -1,8 +0,0 @@ -// StdAfx.h - -#ifndef __STDAFX_H -#define __STDAFX_H - -#include "../../../Common/MyWindows.h" - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Split/SplitHandler.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Split/SplitHandler.cpp deleted file mode 100644 index 36be6cc3b..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Split/SplitHandler.cpp +++ /dev/null @@ -1,357 +0,0 @@ -// SplitHandler.cpp - -#include "StdAfx.h" - -#include "Common/ComTry.h" -#include "Common/Defs.h" -#include "Common/NewHandler.h" -#include "Common/StringConvert.h" - -#include "Windows/PropVariant.h" -#include "Windows/Time.h" - -#include "../../Common/ProgressUtils.h" - -#include "../../Compress/CopyCoder.h" - -#include "../Common/ItemNameUtils.h" -#include "../Common/MultiStream.h" - -#include "SplitHandler.h" - -using namespace NWindows; -using namespace NTime; - -namespace NArchive { -namespace NSplit { - -STATPROPSTG kProps[] = -{ - { NULL, kpidPath, VT_BSTR}, - { NULL, kpidSize, VT_UI8}, - { NULL, kpidPackSize, VT_UI8}, -}; - -IMP_IInArchive_Props -IMP_IInArchive_ArcProps_NO - -class CSeqName -{ -public: - UString _unchangedPart; - UString _changedPart; - bool _splitStyle; - UString GetNextName() - { - UString newName; - if (_splitStyle) - { - int i; - int numLetters = _changedPart.Length(); - for (i = numLetters - 1; i >= 0; i--) - { - wchar_t c = _changedPart[i]; - if (c == 'z') - { - c = 'a'; - newName = c + newName; - continue; - } - else if (c == 'Z') - { - c = 'A'; - newName = c + newName; - continue; - } - c++; - if ((c == 'z' || c == 'Z') && i == 0) - { - _unchangedPart += c; - wchar_t newChar = (c == 'z') ? L'a' : L'A'; - newName.Empty(); - numLetters++; - for (int k = 0; k < numLetters; k++) - newName += newChar; - break; - } - newName = c + newName; - i--; - for (; i >= 0; i--) - newName = _changedPart[i] + newName; - break; - } - } - else - { - int i; - int numLetters = _changedPart.Length(); - for (i = numLetters - 1; i >= 0; i--) - { - wchar_t c = _changedPart[i]; - if (c == L'9') - { - c = L'0'; - newName = c + newName; - if (i == 0) - newName = UString(L'1') + newName; - continue; - } - c++; - newName = c + newName; - i--; - for (; i >= 0; i--) - newName = _changedPart[i] + newName; - break; - } - } - _changedPart = newName; - return _unchangedPart + _changedPart; - } -}; - -STDMETHODIMP CHandler::Open(IInStream *stream, - const UInt64 * /* maxCheckStartPosition */, - IArchiveOpenCallback *openArchiveCallback) -{ - COM_TRY_BEGIN - Close(); - if (openArchiveCallback == 0) - return S_FALSE; - // try - { - CMyComPtr openVolumeCallback; - CMyComPtr openArchiveCallbackWrap = openArchiveCallback; - if (openArchiveCallbackWrap.QueryInterface(IID_IArchiveOpenVolumeCallback, - &openVolumeCallback) != S_OK) - return S_FALSE; - - { - NCOM::CPropVariant prop; - RINOK(openVolumeCallback->GetProperty(kpidName, &prop)); - if (prop.vt != VT_BSTR) - return S_FALSE; - _name = prop.bstrVal; - } - - int dotPos = _name.ReverseFind('.'); - UString prefix, ext; - if (dotPos >= 0) - { - prefix = _name.Left(dotPos + 1); - ext = _name.Mid(dotPos + 1); - } - else - ext = _name; - UString extBig = ext; - extBig.MakeUpper(); - - CSeqName seqName; - - int numLetters = 2; - bool splitStyle = false; - if (extBig.Right(2) == L"AA") - { - splitStyle = true; - while (numLetters < extBig.Length()) - { - if (extBig[extBig.Length() - numLetters - 1] != 'A') - break; - numLetters++; - } - } - else if (ext.Right(2) == L"01") - { - while (numLetters < extBig.Length()) - { - if (extBig[extBig.Length() - numLetters - 1] != '0') - break; - numLetters++; - } - if (numLetters != ext.Length()) - return S_FALSE; - } - else - return S_FALSE; - - _streams.Add(stream); - - seqName._unchangedPart = prefix + ext.Left(extBig.Length() - numLetters); - seqName._changedPart = ext.Right(numLetters); - seqName._splitStyle = splitStyle; - - if (prefix.Length() < 1) - _subName = L"file"; - else - _subName = prefix.Left(prefix.Length() - 1); - - _totalSize = 0; - UInt64 size; - { - NCOM::CPropVariant prop; - RINOK(openVolumeCallback->GetProperty(kpidSize, &prop)); - if (prop.vt != VT_UI8) - return E_INVALIDARG; - size = prop.uhVal.QuadPart; - } - _totalSize += size; - _sizes.Add(size); - - if (openArchiveCallback != NULL) - { - UInt64 numFiles = _streams.Size(); - RINOK(openArchiveCallback->SetCompleted(&numFiles, NULL)); - } - - for (;;) - { - UString fullName = seqName.GetNextName(); - CMyComPtr nextStream; - HRESULT result = openVolumeCallback->GetStream(fullName, &nextStream); - if (result == S_FALSE) - break; - if (result != S_OK) - return result; - if (!stream) - break; - { - NCOM::CPropVariant prop; - RINOK(openVolumeCallback->GetProperty(kpidSize, &prop)); - if (prop.vt != VT_UI8) - return E_INVALIDARG; - size = prop.uhVal.QuadPart; - } - _totalSize += size; - _sizes.Add(size); - _streams.Add(nextStream); - if (openArchiveCallback != NULL) - { - UInt64 numFiles = _streams.Size(); - RINOK(openArchiveCallback->SetCompleted(&numFiles, NULL)); - } - } - } - /* - catch(...) - { - return S_FALSE; - } - */ - return S_OK; - COM_TRY_END -} - -STDMETHODIMP CHandler::Close() -{ - _sizes.Clear(); - _streams.Clear(); - return S_OK; -} - -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) -{ - *numItems = _streams.IsEmpty() ? 0 : 1; - return S_OK; -} - -STDMETHODIMP CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value) -{ - NWindows::NCOM::CPropVariant prop; - switch(propID) - { - case kpidPath: - prop = _subName; - break; - case kpidSize: - case kpidPackSize: - prop = _totalSize; - break; - } - prop.Detach(value); - return S_OK; -} - -STDMETHODIMP CHandler::Extract(const UInt32* indices, UInt32 numItems, - Int32 _aTestMode, IArchiveExtractCallback *_anExtractCallback) -{ - COM_TRY_BEGIN - - if (numItems != UInt32(-1)) - { - if (numItems != 1) - return E_INVALIDARG; - if (indices[0] != 0) - return E_INVALIDARG; - } - bool testMode = (_aTestMode != 0); - CMyComPtr extractCallback = _anExtractCallback; - extractCallback->SetTotal(_totalSize); - - /* - CMyComPtr volumeExtractCallback; - if (extractCallback.QueryInterface(&volumeExtractCallback) != S_OK) - return E_FAIL; - */ - - UInt64 currentTotalSize = 0; - UInt64 currentItemSize; - - RINOK(extractCallback->SetCompleted(¤tTotalSize)); - CMyComPtr realOutStream; - Int32 askMode; - askMode = testMode ? NArchive::NExtract::NAskMode::kTest : - NArchive::NExtract::NAskMode::kExtract; - Int32 index = 0; - RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); - - RINOK(extractCallback->PrepareOperation(askMode)); - if (testMode) - { - RINOK(extractCallback->SetOperationResult(NArchive::NExtract::NOperationResult::kOK)); - return S_OK; - } - - if (!testMode && (!realOutStream)) - return S_OK; - - NCompress::CCopyCoder *copyCoderSpec = new NCompress::CCopyCoder; - CMyComPtr copyCoder = copyCoderSpec; - - CLocalProgress *lps = new CLocalProgress; - CMyComPtr progress = lps; - lps->Init(extractCallback, false); - - for (int i = 0; i < _streams.Size(); i++, currentTotalSize += currentItemSize) - { - lps->InSize = lps->OutSize = currentTotalSize; - RINOK(lps->SetCur()); - IInStream *inStream = _streams[i]; - RINOK(inStream->Seek(0, STREAM_SEEK_SET, NULL)); - RINOK(copyCoder->Code(inStream, realOutStream, NULL, NULL, progress)); - currentItemSize = copyCoderSpec->TotalSize; - } - realOutStream.Release(); - return extractCallback->SetOperationResult(NArchive::NExtract::NOperationResult::kOK); - COM_TRY_END -} - -STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) -{ - if (index != 0) - return E_INVALIDARG; - *stream = 0; - CMultiStream *streamSpec = new CMultiStream; - CMyComPtr streamTemp = streamSpec; - for (int i = 0; i < _streams.Size(); i++) - { - CMultiStream::CSubStreamInfo subStreamInfo; - subStreamInfo.Stream = _streams[i]; - subStreamInfo.Pos = 0; - subStreamInfo.Size = _sizes[i]; - streamSpec->Streams.Add(subStreamInfo); - } - streamSpec->Init(); - *stream = streamTemp.Detach(); - return S_OK; -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Split/SplitHandler.h b/desmume/src/windows/7z/CPP/7zip/Archive/Split/SplitHandler.h deleted file mode 100644 index c323490ae..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Split/SplitHandler.h +++ /dev/null @@ -1,37 +0,0 @@ -// Split/Handler.h - -#ifndef __SPLIT_HANDLER_H -#define __SPLIT_HANDLER_H - -#include "Common/MyCom.h" -#include "Common/MyString.h" -#include "../IArchive.h" - -namespace NArchive { -namespace NSplit { - -class CHandler: - public IInArchive, - public IInArchiveGetStream, - // public IOutArchive, - public CMyUnknownImp -{ -public: - MY_UNKNOWN_IMP2(IInArchive, IInArchiveGetStream) - - INTERFACE_IInArchive(;) - - STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream); - -private: - UString _subName; - UString _name; - CObjectVector > _streams; - CRecordVector _sizes; - - UInt64 _totalSize; -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Split/SplitRegister.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Split/SplitRegister.cpp deleted file mode 100644 index 691a3829c..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Split/SplitRegister.cpp +++ /dev/null @@ -1,20 +0,0 @@ -// SplitRegister.cpp - -#include "StdAfx.h" - -#include "../../Common/RegisterArc.h" - -#include "SplitHandler.h" -static IInArchive *CreateArc() { return new NArchive::NSplit::CHandler; } -/* -#ifndef EXTRACT_ONLY -static IOutArchive *CreateArcOut() { return new NArchive::NSplit::CHandler; } -#else -#define CreateArcOut 0 -#endif -*/ - -static CArcInfo g_ArcInfo = -{ L"Split", L"001", 0, 0xEA, { 0 }, 0, false, CreateArc, 0 }; - -REGISTER_ARC(Split) diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Split/StdAfx.h b/desmume/src/windows/7z/CPP/7zip/Archive/Split/StdAfx.h deleted file mode 100644 index 83fdd22d5..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Split/StdAfx.h +++ /dev/null @@ -1,8 +0,0 @@ -// StdAfx.h - -#ifndef __STDAFX_H -#define __STDAFX_H - -#include "../../../Common/MyWindows.h" - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/StdAfx.h b/desmume/src/windows/7z/CPP/7zip/Archive/StdAfx.h deleted file mode 100644 index f56e92fd8..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/StdAfx.h +++ /dev/null @@ -1,9 +0,0 @@ -// StdAfx.h - -#ifndef __STDAFX_H -#define __STDAFX_H - -#include "../../Common/MyWindows.h" -#include "../../Common/NewHandler.h" - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Tar/StdAfx.h b/desmume/src/windows/7z/CPP/7zip/Archive/Tar/StdAfx.h deleted file mode 100644 index a4e617312..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Tar/StdAfx.h +++ /dev/null @@ -1,9 +0,0 @@ -// StdAfx.h - -#ifndef __STDAFX_H -#define __STDAFX_H - -#include "../../../Common/MyWindows.h" -#include "../../../Common/NewHandler.h" - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Tar/TarHandler.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Tar/TarHandler.cpp deleted file mode 100644 index b1e34fff7..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Tar/TarHandler.cpp +++ /dev/null @@ -1,229 +0,0 @@ -// TarHandler.cpp - -#include "StdAfx.h" - -#include "Common/ComTry.h" -#include "Common/Defs.h" -#include "Common/NewHandler.h" -#include "Common/StringConvert.h" - -#include "Windows/PropVariant.h" -#include "Windows/Time.h" - -#include "../../Common/LimitedStreams.h" -#include "../../Common/ProgressUtils.h" - -#include "../../Compress/CopyCoder.h" - -#include "../Common/DummyOutStream.h" -#include "../Common/ItemNameUtils.h" - -#include "TarHandler.h" -#include "TarIn.h" - -using namespace NWindows; - -namespace NArchive { -namespace NTar { - -STATPROPSTG kProps[] = -{ - { NULL, kpidPath, VT_BSTR}, - { NULL, kpidIsDir, VT_BOOL}, - { NULL, kpidSize, VT_UI8}, - { NULL, kpidPackSize, VT_UI8}, - { NULL, kpidMTime, VT_FILETIME}, - { NULL, kpidUser, VT_BSTR}, - { NULL, kpidGroup, VT_BSTR} -}; - -IMP_IInArchive_Props -IMP_IInArchive_ArcProps_NO - -HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback) -{ - UInt64 endPos = 0; - if (callback != NULL) - { - RINOK(stream->Seek(0, STREAM_SEEK_END, &endPos)); - RINOK(stream->Seek(0, STREAM_SEEK_SET, NULL)); - } - - UInt64 pos = 0; - for (;;) - { - CItemEx item; - bool filled; - item.HeaderPosition = pos; - RINOK(ReadItem(stream, filled, item)); - if (!filled) - break; - _items.Add(item); - - RINOK(stream->Seek(item.GetPackSize(), STREAM_SEEK_CUR, &pos)); - if (pos >= endPos) - return S_FALSE; - if (callback != NULL) - { - if (_items.Size() == 1) - { - RINOK(callback->SetTotal(NULL, &endPos)); - } - if (_items.Size() % 100 == 0) - { - UInt64 numFiles = _items.Size(); - RINOK(callback->SetCompleted(&numFiles, &pos)); - } - } - } - - if (_items.Size() == 0) - { - CMyComPtr openVolumeCallback; - if (!callback) - return S_FALSE; - callback->QueryInterface(IID_IArchiveOpenVolumeCallback, (void **)&openVolumeCallback); - if (!openVolumeCallback) - return S_FALSE; - NCOM::CPropVariant prop; - if (openVolumeCallback->GetProperty(kpidName, &prop) != S_OK) - return S_FALSE; - if (prop.vt != VT_BSTR) - return S_FALSE; - UString baseName = prop.bstrVal; - baseName = baseName.Right(4); - if (baseName.CompareNoCase(L".tar") != 0) - return S_FALSE; - } - return S_OK; -} - -STDMETHODIMP CHandler::Open(IInStream *stream, - const UInt64 * /* maxCheckStartPosition */, - IArchiveOpenCallback *openArchiveCallback) -{ - COM_TRY_BEGIN - { - Close(); - RINOK(Open2(stream, openArchiveCallback)); - _inStream = stream; - } - return S_OK; - COM_TRY_END -} - -STDMETHODIMP CHandler::Close() -{ - _items.Clear(); - _inStream.Release(); - return S_OK; -} - -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) -{ - *numItems = _items.Size(); - return S_OK; -} - -STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) -{ - COM_TRY_BEGIN - NWindows::NCOM::CPropVariant prop; - const CItemEx &item = _items[index]; - - switch(propID) - { - case kpidPath: prop = NItemName::GetOSName2(MultiByteToUnicodeString(item.Name, CP_OEMCP)); break; - case kpidIsDir: prop = item.IsDir(); break; - case kpidSize: prop = item.Size; break; - case kpidPackSize: prop = item.GetPackSize(); break; - case kpidMTime: - if (item.MTime != 0) - { - FILETIME ft; - NTime::UnixTimeToFileTime(item.MTime, ft); - prop = ft; - } - break; - case kpidUser: prop = MultiByteToUnicodeString(item.UserName, CP_OEMCP); break; - case kpidGroup: prop = MultiByteToUnicodeString(item.GroupName, CP_OEMCP); break; - } - prop.Detach(value); - return S_OK; - COM_TRY_END -} - -STDMETHODIMP CHandler::Extract(const UInt32* indices, UInt32 numItems, - Int32 _aTestMode, IArchiveExtractCallback *extractCallback) -{ - COM_TRY_BEGIN - bool testMode = (_aTestMode != 0); - bool allFilesMode = (numItems == UInt32(-1)); - if (allFilesMode) - numItems = _items.Size(); - if (numItems == 0) - return S_OK; - UInt64 totalSize = 0; - UInt32 i; - for (i = 0; i < numItems; i++) - totalSize += _items[allFilesMode ? i : indices[i]].Size; - extractCallback->SetTotal(totalSize); - - UInt64 totalPackSize, curPackSize, curSize; - totalSize = totalPackSize = 0; - - NCompress::CCopyCoder *copyCoderSpec = new NCompress::CCopyCoder(); - CMyComPtr copyCoder = copyCoderSpec; - - CLocalProgress *lps = new CLocalProgress; - CMyComPtr progress = lps; - lps->Init(extractCallback, false); - - CLimitedSequentialInStream *streamSpec = new CLimitedSequentialInStream; - CMyComPtr inStream(streamSpec); - streamSpec->SetStream(_inStream); - - CDummyOutStream *outStreamSpec = new CDummyOutStream; - CMyComPtr outStream(outStreamSpec); - - for (i = 0; i < numItems; i++, totalSize += curSize, totalPackSize += curPackSize) - { - lps->InSize = totalPackSize; - lps->OutSize = totalSize; - RINOK(lps->SetCur()); - CMyComPtr realOutStream; - Int32 askMode = testMode ? - NArchive::NExtract::NAskMode::kTest : - NArchive::NExtract::NAskMode::kExtract; - Int32 index = allFilesMode ? i : indices[i]; - const CItemEx &item = _items[index]; - RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); - curSize = item.Size; - curPackSize = item.GetPackSize(); - if (item.IsDir()) - { - RINOK(extractCallback->PrepareOperation(askMode)); - RINOK(extractCallback->SetOperationResult(NArchive::NExtract::NOperationResult::kOK)); - continue; - } - if (!testMode && (!realOutStream)) - continue; - RINOK(extractCallback->PrepareOperation(askMode)); - - outStreamSpec->SetStream(realOutStream); - realOutStream.Release(); - outStreamSpec->Init(); - - RINOK(_inStream->Seek(item.GetDataPosition(), STREAM_SEEK_SET, NULL)); - streamSpec->Init(item.Size); - RINOK(copyCoder->Code(inStream, outStream, NULL, NULL, progress)); - outStreamSpec->ReleaseStream(); - RINOK(extractCallback->SetOperationResult(copyCoderSpec->TotalSize == item.Size ? - NArchive::NExtract::NOperationResult::kOK: - NArchive::NExtract::NOperationResult::kDataError)); - } - return S_OK; - COM_TRY_END -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Tar/TarHandler.h b/desmume/src/windows/7z/CPP/7zip/Archive/Tar/TarHandler.h deleted file mode 100644 index 38792b25a..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Tar/TarHandler.h +++ /dev/null @@ -1,37 +0,0 @@ -// Tar/Handler.h - -#ifndef __TAR_HANDLER_H -#define __TAR_HANDLER_H - -#include "Common/MyCom.h" -#include "../IArchive.h" - -#include "TarItem.h" - -namespace NArchive { -namespace NTar { - -class CHandler: - public IInArchive, - public IOutArchive, - public CMyUnknownImp -{ -public: - MY_UNKNOWN_IMP2( - IInArchive, - IOutArchive - ) - - INTERFACE_IInArchive(;) - INTERFACE_IOutArchive(;) - - HRESULT Open2(IInStream *stream, IArchiveOpenCallback *callback); - -private: - CObjectVector _items; - CMyComPtr _inStream; -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Tar/TarHeader.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Tar/TarHeader.cpp deleted file mode 100644 index 9304388bc..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Tar/TarHeader.cpp +++ /dev/null @@ -1,25 +0,0 @@ -// Archive/Tar/Header.h - -#include "StdAfx.h" - -#include "TarHeader.h" - -namespace NArchive { -namespace NTar { -namespace NFileHeader { - - // The checksum field is filled with this while the checksum is computed. - const char *kCheckSumBlanks = " "; // 8 blanks, no null - - const char *kLongLink = "././@LongLink"; - const char *kLongLink2 = "@LongLink"; - - // The magic field is filled with this if uname and gname are valid. - namespace NMagic - { - const char *kUsTar = "ustar"; // 5 chars - const char *kGNUTar = "GNUtar "; // 7 chars and a null - const char *kEmpty = "\0\0\0\0\0\0\0\0"; // 7 chars and a null - } - -}}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Tar/TarHeader.h b/desmume/src/windows/7z/CPP/7zip/Archive/Tar/TarHeader.h deleted file mode 100644 index dece1f7f4..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Tar/TarHeader.h +++ /dev/null @@ -1,108 +0,0 @@ -// Archive/Tar/Header.h - -#ifndef __ARCHIVE_TAR_HEADER_H -#define __ARCHIVE_TAR_HEADER_H - -#include "Common/Types.h" - -namespace NArchive { -namespace NTar { - -namespace NFileHeader -{ - const int kRecordSize = 512; - const int kNameSize = 100; - const int kUserNameSize = 32; - const int kGroupNameSize = 32; - const int kPrefixSize = 155; - - /* - struct CHeader - { - char Name[kNameSize]; - char Mode[8]; - char UID[8]; - char GID[8]; - char Size[12]; - char ModificationTime[12]; - char CheckSum[8]; - char LinkFlag; - char LinkName[kNameSize]; - char Magic[8]; - char UserName[kUserNameSize]; - char GroupName[kGroupNameSize]; - char DeviceMajor[8]; - char DeviceMinor[8]; - char Prefix[155]; - }; - union CRecord - { - CHeader Header; - Byte Padding[kRecordSize]; - }; - */ - - namespace NMode - { - const int kSetUID = 04000; // Set UID on execution - const int kSetGID = 02000; // Set GID on execution - const int kSaveText = 01000; // Save text (sticky bit) - } - - namespace NFilePermissions - { - const int kUserRead = 00400; // read by owner - const int kUserWrite = 00200; // write by owner - const int kUserExecute = 00100; // execute/search by owner - const int kGroupRead = 00040; // read by group - const int kGroupWrite = 00020; // write by group - const int kGroupExecute = 00010; // execute/search by group - const int kOtherRead = 00004; // read by other - const int kOtherWrite = 00002; // write by other - const int kOtherExecute = 00001; // execute/search by other - } - - - // The linkflag defines the type of file - namespace NLinkFlag - { - const char kOldNormal = '\0'; // Normal disk file, Unix compatible - const char kNormal = '0'; // Normal disk file - const char kLink = '1'; // Link to previously dumped file - const char kSymbolicLink = '2'; // Symbolic link - const char kCharacter = '3'; // Character special file - const char kBlock = '4'; // Block special file - const char kDirectory = '5'; // Directory - const char kFIFO = '6'; // FIFO special file - const char kContiguous = '7'; // Contiguous file - - const char kDumpDir = 'D'; /* GNUTYPE_DUMPDIR. - data: list of files created by the --incremental (-G) option - Each file name is preceded by either - - 'Y' (file should be in this archive) - - 'N' (file is a directory, or is not stored in the archive.) - Each file name is terminated by a null + an additional null after - the last file name. */ - - } - // Further link types may be defined later. - - // The checksum field is filled with this while the checksum is computed. - extern const char *kCheckSumBlanks;// = " "; // 8 blanks, no null - - extern const char *kLongLink; // = "././@LongLink"; - extern const char *kLongLink2; // = "@LongLink"; - - // The magic field is filled with this if uname and gname are valid. - namespace NMagic - { - extern const char *kUsTar; // = "ustar"; // 5 chars - extern const char *kGNUTar; // = "GNUtar "; // 7 chars and a null - extern const char *kEmpty; // = "GNUtar "; // 7 chars and a null - } - -} - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Tar/TarIn.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Tar/TarIn.cpp deleted file mode 100644 index 85702eb2b..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Tar/TarIn.cpp +++ /dev/null @@ -1,176 +0,0 @@ -// Archive/TarIn.cpp - -#include "StdAfx.h" - -#include "TarIn.h" -#include "TarHeader.h" - -#include "Common/StringToInt.h" -#include "Windows/Defs.h" - -#include "../../Common/StreamUtils.h" - -namespace NArchive { -namespace NTar { - -static void MyStrNCpy(char *dest, const char *src, int size) -{ - for (int i = 0; i < size; i++) - { - char c = src[i]; - dest[i] = c; - if (c == 0) - break; - } -} - -static bool OctalToNumber(const char *srcString, int size, UInt64 &res) -{ - char sz[32]; - MyStrNCpy(sz, srcString, size); - sz[size] = 0; - const char *end; - int i; - for (i = 0; sz[i] == ' '; i++); - res = ConvertOctStringToUInt64(sz + i, &end); - return (*end == ' ' || *end == 0); -} - -static bool OctalToNumber32(const char *srcString, int size, UInt32 &res) -{ - UInt64 res64; - if (!OctalToNumber(srcString, size, res64)) - return false; - res = (UInt32)res64; - return (res64 <= 0xFFFFFFFF); -} - -#define RIF(x) { if (!(x)) return S_FALSE; } - -static bool IsRecordLast(const char *buf) -{ - for (int i = 0; i < NFileHeader::kRecordSize; i++) - if (buf[i] != 0) - return false; - return true; -} - -static void ReadString(const char *s, int size, AString &result) -{ - char temp[NFileHeader::kRecordSize + 1]; - MyStrNCpy(temp, s, size); - temp[size] = '\0'; - result = temp; -} - -static HRESULT GetNextItemReal(ISequentialInStream *stream, bool &filled, CItemEx &item, size_t &processedSize) -{ - item.LongLinkSize = 0; - char buf[NFileHeader::kRecordSize]; - char *p = buf; - - filled = false; - - processedSize = NFileHeader::kRecordSize; - RINOK(ReadStream(stream, buf, &processedSize)); - if (processedSize == 0 || (processedSize == NFileHeader::kRecordSize && IsRecordLast(buf))) - return S_OK; - if (processedSize < NFileHeader::kRecordSize) - return S_FALSE; - - ReadString(p, NFileHeader::kNameSize, item.Name); p += NFileHeader::kNameSize; - - RIF(OctalToNumber32(p, 8, item.Mode)); p += 8; - - if (!OctalToNumber32(p, 8, item.UID)) item.UID = 0; p += 8; - if (!OctalToNumber32(p, 8, item.GID)) item.GID = 0; p += 8; - - RIF(OctalToNumber(p, 12, item.Size)); p += 12; - RIF(OctalToNumber32(p, 12, item.MTime)); p += 12; - - UInt32 checkSum; - RIF(OctalToNumber32(p, 8, checkSum)); - memcpy(p, NFileHeader::kCheckSumBlanks, 8); p += 8; - - item.LinkFlag = *p++; - - ReadString(p, NFileHeader::kNameSize, item.LinkName); p += NFileHeader::kNameSize; - - memcpy(item.Magic, p, 8); p += 8; - - ReadString(p, NFileHeader::kUserNameSize, item.UserName); p += NFileHeader::kUserNameSize; - ReadString(p, NFileHeader::kUserNameSize, item.GroupName); p += NFileHeader::kUserNameSize; - - item.DeviceMajorDefined = (p[0] != 0); RIF(OctalToNumber32(p, 8, item.DeviceMajor)); p += 8; - item.DeviceMinorDefined = (p[0] != 0); RIF(OctalToNumber32(p, 8, item.DeviceMinor)); p += 8; - - AString prefix; - ReadString(p, NFileHeader::kPrefixSize, prefix); - p += NFileHeader::kPrefixSize; - if (!prefix.IsEmpty() && item.IsMagic() && - (item.LinkFlag != 'L' /* || prefix != "00000000000" */ )) - item.Name = prefix + AString('/') + item.Name; - - if (item.LinkFlag == NFileHeader::NLinkFlag::kLink) - item.Size = 0; - - UInt32 checkSumReal = 0; - for (int i = 0; i < NFileHeader::kRecordSize; i++) - checkSumReal += (Byte)buf[i]; - - if (checkSumReal != checkSum) - return S_FALSE; - - filled = true; - return S_OK; -} - -HRESULT ReadItem(ISequentialInStream *stream, bool &filled, CItemEx &item) -{ - size_t processedSize; - RINOK(GetNextItemReal(stream, filled, item, processedSize)); - if (!filled) - return S_OK; - // GNUtar extension - if (item.LinkFlag == 'L') - { - if (item.Name.Compare(NFileHeader::kLongLink) != 0) - if (item.Name.Compare(NFileHeader::kLongLink2) != 0) - return S_FALSE; - - AString fullName; - if (item.Size > (1 << 15)) - return S_FALSE; - int packSize = (int)item.GetPackSize(); - char *buffer = fullName.GetBuffer(packSize + 1); - - RINOK(ReadStream_FALSE(stream, buffer, packSize)); - processedSize += packSize; - buffer[item.Size] = '\0'; - fullName.ReleaseBuffer(); - - UInt64 headerPosition = item.HeaderPosition; - { - size_t processedSize2; - RINOK(GetNextItemReal(stream, filled, item, processedSize2)); - } - item.LongLinkSize = (unsigned)processedSize; - item.Name = fullName; - item.HeaderPosition = headerPosition; - } - else if (item.LinkFlag == 'g' || item.LinkFlag == 'x' || item.LinkFlag == 'X') - { - // pax Extended Header - return S_OK; - } - else if (item.LinkFlag == NFileHeader::NLinkFlag::kDumpDir) - { - // GNU Extensions to the Archive Format - return S_OK; - } - else if (item.LinkFlag > '7' || (item.LinkFlag < '0' && item.LinkFlag != 0)) - return S_FALSE; - return S_OK; -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Tar/TarIn.h b/desmume/src/windows/7z/CPP/7zip/Archive/Tar/TarIn.h deleted file mode 100644 index 546ad1966..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Tar/TarIn.h +++ /dev/null @@ -1,18 +0,0 @@ -// Archive/TarIn.h - -#ifndef __ARCHIVE_TAR_IN_H -#define __ARCHIVE_TAR_IN_H - -#include "Common/MyCom.h" -#include "../../IStream.h" - -#include "TarItem.h" - -namespace NArchive { -namespace NTar { - -HRESULT ReadItem(ISequentialInStream *stream, bool &filled, CItemEx &itemInfo); - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Tar/TarItem.h b/desmume/src/windows/7z/CPP/7zip/Archive/Tar/TarItem.h deleted file mode 100644 index 54beefcc4..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Tar/TarItem.h +++ /dev/null @@ -1,71 +0,0 @@ -// Archive/Tar/Item.h - -#ifndef __ARCHIVE_TAR_ITEM_H -#define __ARCHIVE_TAR_ITEM_H - -#include "Common/Types.h" -#include "Common/MyString.h" - -#include "../Common/ItemNameUtils.h" -#include "TarHeader.h" - -namespace NArchive { -namespace NTar { - -struct CItem -{ - AString Name; - UInt64 Size; - - UInt32 Mode; - UInt32 UID; - UInt32 GID; - UInt32 MTime; - UInt32 DeviceMajor; - UInt32 DeviceMinor; - - AString LinkName; - AString UserName; - AString GroupName; - - char Magic[8]; - char LinkFlag; - bool DeviceMajorDefined; - bool DeviceMinorDefined; - - bool IsDir() const - { - switch(LinkFlag) - { - case NFileHeader::NLinkFlag::kDirectory: - case NFileHeader::NLinkFlag::kDumpDir: - return true; - case NFileHeader::NLinkFlag::kOldNormal: - case NFileHeader::NLinkFlag::kNormal: - return NItemName::HasTailSlash(Name, CP_OEMCP); - } - return false; - } - - bool IsMagic() const - { - for (int i = 0; i < 5; i++) - if (Magic[i] != NFileHeader::NMagic::kUsTar[i]) - return false; - return true; - } - - UInt64 GetPackSize() const { return (Size + 0x1FF) & (~((UInt64)0x1FF)); } -}; - -struct CItemEx: public CItem -{ - UInt64 HeaderPosition; - unsigned LongLinkSize; - UInt64 GetDataPosition() const { return HeaderPosition + LongLinkSize + NFileHeader::kRecordSize; } - UInt64 GetFullSize() const { return LongLinkSize + NFileHeader::kRecordSize + Size; } -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Tar/TarRegister.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Tar/TarRegister.cpp deleted file mode 100644 index 17eccb7b3..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Tar/TarRegister.cpp +++ /dev/null @@ -1,18 +0,0 @@ -// TarRegister.cpp - -#include "StdAfx.h" - -#include "../../Common/RegisterArc.h" - -#include "TarHandler.h" -static IInArchive *CreateArc() { return new NArchive::NTar::CHandler; } -#ifndef EXTRACT_ONLY -static IOutArchive *CreateArcOut() { return new NArchive::NTar::CHandler; } -#else -#define CreateArcOut 0 -#endif - -static CArcInfo g_ArcInfo = -{ L"Tar", L"tar", 0, 0xEE, { 'u', 's', 't', 'a', 'r' }, 5, false, CreateArc, CreateArcOut }; - -REGISTER_ARC(Tar) diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Zip/StdAfx.h b/desmume/src/windows/7z/CPP/7zip/Archive/Zip/StdAfx.h deleted file mode 100644 index 83fdd22d5..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Zip/StdAfx.h +++ /dev/null @@ -1,8 +0,0 @@ -// StdAfx.h - -#ifndef __STDAFX_H -#define __STDAFX_H - -#include "../../../Common/MyWindows.h" - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipCompressionMode.h b/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipCompressionMode.h deleted file mode 100644 index f3c105e81..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipCompressionMode.h +++ /dev/null @@ -1,39 +0,0 @@ -// CompressionMode.h - -#ifndef __ZIP_COMPRESSIONMETHOD_H -#define __ZIP_COMPRESSIONMETHOD_H - -#include "../../../Common/MyString.h" - -namespace NArchive { -namespace NZip { - -struct CCompressionMethodMode -{ - CRecordVector MethodSequence; - UString MatchFinder; - UInt32 Algo; - UInt32 NumPasses; - UInt32 NumFastBytes; - bool NumMatchFinderCyclesDefined; - UInt32 NumMatchFinderCycles; - UInt32 DicSize; - #ifdef COMPRESS_MT - UInt32 NumThreads; - #endif - bool PasswordIsDefined; - AString Password; - bool IsAesMode; - Byte AesKeyMode; - - CCompressionMethodMode(): - NumMatchFinderCyclesDefined(false), - PasswordIsDefined(false), - IsAesMode(false), - AesKeyMode(3) - {} -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipHandler.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipHandler.cpp deleted file mode 100644 index 43f1cf996..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipHandler.cpp +++ /dev/null @@ -1,831 +0,0 @@ -// ZipHandler.cpp - -#include "StdAfx.h" - -#include "Common/ComTry.h" -#include "Common/Defs.h" -#include "Common/IntToString.h" -#include "Common/StringConvert.h" - -#include "Windows/PropVariant.h" -#include "Windows/Time.h" - -#include "../../IPassword.h" - -#include "../../Common/CreateCoder.h" -#include "../../Common/FilterCoder.h" -#include "../../Common/ProgressUtils.h" -#include "../../Common/StreamObjects.h" -#include "../../Common/StreamUtils.h" - -#include "../../Compress/CopyCoder.h" -#include "../../Compress/LzmaDecoder.h" -#include "../../Compress/ImplodeDecoder.h" -#include "../../Compress/ShrinkDecoder.h" - -#include "../../Crypto/WzAes.h" -#include "../../Crypto/ZipCrypto.h" -#include "../../Crypto/ZipStrong.h" - -#include "../Common/ItemNameUtils.h" -#include "../Common/OutStreamWithCRC.h" - -#include "ZipHandler.h" - -using namespace NWindows; - -namespace NArchive { -namespace NZip { - -// static const CMethodId kMethodId_Store = 0; -static const CMethodId kMethodId_ZipBase = 0x040100; -static const CMethodId kMethodId_BZip2 = 0x040202; - -const wchar_t *kHostOS[] = -{ - L"FAT", - L"AMIGA", - L"VMS", - L"Unix", - L"VM/CMS", - L"Atari", - L"HPFS", - L"Macintosh", - L"Z-System", - L"CP/M", - L"TOPS-20", - L"NTFS", - L"SMS/QDOS", - L"Acorn", - L"VFAT", - L"MVS", - L"BeOS", - L"Tandem", - L"OS/400", - L"OS/X" -}; - - -static const int kNumHostOSes = sizeof(kHostOS) / sizeof(kHostOS[0]); - -static const wchar_t *kUnknownOS = L"Unknown"; - -STATPROPSTG kProps[] = -{ - { NULL, kpidPath, VT_BSTR}, - { NULL, kpidIsDir, VT_BOOL}, - { NULL, kpidSize, VT_UI8}, - { NULL, kpidPackSize, VT_UI8}, - { NULL, kpidMTime, VT_FILETIME}, - { NULL, kpidCTime, VT_FILETIME}, - { NULL, kpidATime, VT_FILETIME}, - - { NULL, kpidAttrib, VT_UI4}, - - { NULL, kpidEncrypted, VT_BOOL}, - { NULL, kpidComment, VT_BSTR}, - - { NULL, kpidCRC, VT_UI4}, - - { NULL, kpidMethod, VT_BSTR}, - { NULL, kpidHostOS, VT_BSTR} - - // { NULL, kpidUnpackVer, VT_UI1}, -}; - -const wchar_t *kMethods[] = -{ - L"Store", - L"Shrink", - L"Reduced1", - L"Reduced2", - L"Reduced2", - L"Reduced3", - L"Implode", - L"Tokenizing", - L"Deflate", - L"Deflate64", - L"PKImploding" -}; - -const int kNumMethods = sizeof(kMethods) / sizeof(kMethods[0]); -const wchar_t *kBZip2Method = L"BZip2"; -const wchar_t *kLZMAMethod = L"LZMA"; -const wchar_t *kJpegMethod = L"Jpeg"; -const wchar_t *kWavPackMethod = L"WavPack"; -const wchar_t *kPPMdMethod = L"PPMd"; -const wchar_t *kAESMethod = L"AES"; -const wchar_t *kZipCryptoMethod = L"ZipCrypto"; -const wchar_t *kStrongCryptoMethod = L"StrongCrypto"; - -struct CStrongCryptoPair -{ - UInt16 Id; - const wchar_t *Name; -}; - -CStrongCryptoPair g_StrongCryptoPairs[] = -{ - { NStrongCryptoFlags::kDES, L"DES" }, - { NStrongCryptoFlags::kRC2old, L"RC2a" }, - { NStrongCryptoFlags::k3DES168, L"3DES-168" }, - { NStrongCryptoFlags::k3DES112, L"3DES-112" }, - { NStrongCryptoFlags::kAES128, L"pkAES-128" }, - { NStrongCryptoFlags::kAES192, L"pkAES-192" }, - { NStrongCryptoFlags::kAES256, L"pkAES-256" }, - { NStrongCryptoFlags::kRC2, L"RC2" }, - { NStrongCryptoFlags::kBlowfish, L"Blowfish" }, - { NStrongCryptoFlags::kTwofish, L"Twofish" }, - { NStrongCryptoFlags::kRC4, L"RC4" } -}; - -STATPROPSTG kArcProps[] = -{ - { NULL, kpidBit64, VT_BOOL}, - { NULL, kpidComment, VT_BSTR} -}; - -CHandler::CHandler() -{ - InitMethodProperties(); -} - -static AString BytesToString(const CByteBuffer &data) -{ - AString s; - int size = (int)data.GetCapacity(); - if (size > 0) - { - char *p = s.GetBuffer(size + 1); - memcpy(p, (const Byte *)data, size); - p[size] = '\0'; - s.ReleaseBuffer(); - } - return s; -} - -IMP_IInArchive_Props -IMP_IInArchive_ArcProps - -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) -{ - COM_TRY_BEGIN - NWindows::NCOM::CPropVariant prop; - switch(propID) - { - case kpidBit64: if (m_Archive.IsZip64) prop = m_Archive.IsZip64; break; - case kpidComment: - prop = MultiByteToUnicodeString(BytesToString(m_Archive.m_ArchiveInfo.Comment), CP_ACP); - break; - } - prop.Detach(value); - COM_TRY_END - return S_OK; -} - -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) -{ - *numItems = m_Items.Size(); - return S_OK; -} - -STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) -{ - COM_TRY_BEGIN - NWindows::NCOM::CPropVariant prop; - const CItemEx &item = m_Items[index]; - switch(propID) - { - case kpidPath: prop = NItemName::GetOSName2(item.GetUnicodeString(item.Name)); break; - case kpidIsDir: prop = item.IsDir(); break; - case kpidSize: prop = item.UnPackSize; break; - case kpidPackSize: prop = item.PackSize; break; - case kpidTimeType: - { - FILETIME utcFileTime; - if (item.CentralExtra.GetNtfsTime(NFileHeader::NNtfsExtra::kTagTime, utcFileTime)) - prop = (UInt32)NFileTimeType::kWindows; - break; - } - case kpidCTime: - { - FILETIME ft; - if (item.CentralExtra.GetNtfsTime(NFileHeader::NNtfsExtra::kCTime, ft)) - prop = ft; - break; - } - case kpidATime: - { - FILETIME ft; - if (item.CentralExtra.GetNtfsTime(NFileHeader::NNtfsExtra::kATime, ft)) - prop = ft; - break; - } - case kpidMTime: - { - FILETIME utcFileTime; - if (!item.CentralExtra.GetNtfsTime(NFileHeader::NNtfsExtra::kMTime, utcFileTime)) - { - FILETIME localFileTime; - if (NTime::DosTimeToFileTime(item.Time, localFileTime)) - { - if (!LocalFileTimeToFileTime(&localFileTime, &utcFileTime)) - utcFileTime.dwHighDateTime = utcFileTime.dwLowDateTime = 0; - } - else - utcFileTime.dwHighDateTime = utcFileTime.dwLowDateTime = 0; - } - prop = utcFileTime; - break; - } - case kpidAttrib: prop = item.GetWinAttributes(); break; - case kpidEncrypted: prop = item.IsEncrypted(); break; - case kpidComment: prop = item.GetUnicodeString(BytesToString(item.Comment)); break; - case kpidCRC: if (item.IsThereCrc()) prop = item.FileCRC; break; - case kpidMethod: - { - UInt16 methodId = item.CompressionMethod; - UString method; - if (item.IsEncrypted()) - { - if (methodId == NFileHeader::NCompressionMethod::kWzAES) - { - method = kAESMethod; - CWzAesExtraField aesField; - if (item.CentralExtra.GetWzAesField(aesField)) - { - method += L"-"; - wchar_t s[32]; - ConvertUInt64ToString((aesField.Strength + 1) * 64 , s); - method += s; - method += L" "; - methodId = aesField.Method; - } - } - else - { - if (item.IsStrongEncrypted()) - { - CStrongCryptoField f; - bool finded = false; - if (item.CentralExtra.GetStrongCryptoField(f)) - { - for (int i = 0; i < sizeof(g_StrongCryptoPairs) / sizeof(g_StrongCryptoPairs[0]); i++) - { - const CStrongCryptoPair &pair = g_StrongCryptoPairs[i]; - if (f.AlgId == pair.Id) - { - method += pair.Name; - finded = true; - break; - } - } - } - if (!finded) - method += kStrongCryptoMethod; - } - else - method += kZipCryptoMethod; - method += L" "; - } - } - if (methodId < kNumMethods) - method += kMethods[methodId]; - else switch (methodId) - { - case NFileHeader::NCompressionMethod::kLZMA: - method += kLZMAMethod; - if (item.IsLzmaEOS()) - method += L":EOS"; - break; - case NFileHeader::NCompressionMethod::kBZip2: method += kBZip2Method; break; - case NFileHeader::NCompressionMethod::kJpeg: method += kJpegMethod; break; - case NFileHeader::NCompressionMethod::kWavPack: method += kWavPackMethod; break; - case NFileHeader::NCompressionMethod::kPPMd: method += kPPMdMethod; break; - default: - { - wchar_t s[32]; - ConvertUInt64ToString(methodId, s); - method += s; - } - } - prop = method; - break; - } - case kpidHostOS: - prop = (item.MadeByVersion.HostOS < kNumHostOSes) ? - (kHostOS[item.MadeByVersion.HostOS]) : kUnknownOS; - break; - } - prop.Detach(value); - return S_OK; - COM_TRY_END -} - -class CProgressImp: public CProgressVirt -{ - CMyComPtr _callback; -public: - STDMETHOD(SetTotal)(UInt64 numFiles); - STDMETHOD(SetCompleted)(UInt64 numFiles); - CProgressImp(IArchiveOpenCallback *callback): _callback(callback) {} -}; - -STDMETHODIMP CProgressImp::SetTotal(UInt64 numFiles) -{ - if (_callback) - return _callback->SetTotal(&numFiles, NULL); - return S_OK; -} - -STDMETHODIMP CProgressImp::SetCompleted(UInt64 numFiles) -{ - if (_callback) - return _callback->SetCompleted(&numFiles, NULL); - return S_OK; -} - -STDMETHODIMP CHandler::Open(IInStream *inStream, - const UInt64 *maxCheckStartPosition, IArchiveOpenCallback *callback) -{ - COM_TRY_BEGIN - try - { - Close(); - RINOK(inStream->Seek(0, STREAM_SEEK_SET, NULL)); - RINOK(m_Archive.Open(inStream, maxCheckStartPosition)); - CProgressImp progressImp(callback); - return m_Archive.ReadHeaders(m_Items, &progressImp); - } - catch(const CInArchiveException &) { Close(); return S_FALSE; } - catch(...) { Close(); throw; } - COM_TRY_END -} - -STDMETHODIMP CHandler::Close() -{ - m_Items.Clear(); - m_Archive.Close(); - return S_OK; -} - -////////////////////////////////////// -// CHandler::DecompressItems - -class CLzmaDecoder: - public ICompressCoder, - public CMyUnknownImp -{ - NCompress::NLzma::CDecoder *DecoderSpec; - CMyComPtr Decoder; -public: - CLzmaDecoder(); - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - - MY_UNKNOWN_IMP -}; - -CLzmaDecoder::CLzmaDecoder() -{ - DecoderSpec = new NCompress::NLzma::CDecoder; - Decoder = DecoderSpec; -} - -HRESULT CLzmaDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 * /* inSize */, const UInt64 *outSize, ICompressProgressInfo *progress) -{ - Byte buf[9]; - RINOK(ReadStream_FALSE(inStream, buf, 9)); - if (buf[2] != 5 || buf[3] != 0) - return E_NOTIMPL; - RINOK(DecoderSpec->SetDecoderProperties2(buf + 4, 5)); - return Decoder->Code(inStream, outStream, NULL, outSize, progress); -} - -struct CMethodItem -{ - UInt16 ZipMethod; - CMyComPtr Coder; -}; - -class CZipDecoder -{ - NCrypto::NZip::CDecoder *_zipCryptoDecoderSpec; - NCrypto::NZipStrong::CDecoder *_pkAesDecoderSpec; - NCrypto::NWzAes::CDecoder *_wzAesDecoderSpec; - - CMyComPtr _zipCryptoDecoder; - CMyComPtr _pkAesDecoder; - CMyComPtr _wzAesDecoder; - - CFilterCoder *filterStreamSpec; - CMyComPtr filterStream; - CMyComPtr getTextPassword; - CObjectVector methodItems; - -public: - CZipDecoder(): - _zipCryptoDecoderSpec(0), - _pkAesDecoderSpec(0), - _wzAesDecoderSpec(0), - filterStreamSpec(0) {} - - HRESULT Decode( - DECL_EXTERNAL_CODECS_LOC_VARS - CInArchive &archive, const CItemEx &item, - ISequentialOutStream *realOutStream, - IArchiveExtractCallback *extractCallback, - ICompressProgressInfo *compressProgress, - UInt32 numThreads, Int32 &res); -}; - -HRESULT CZipDecoder::Decode( - DECL_EXTERNAL_CODECS_LOC_VARS - CInArchive &archive, const CItemEx &item, - ISequentialOutStream *realOutStream, - IArchiveExtractCallback *extractCallback, - ICompressProgressInfo *compressProgress, - UInt32 numThreads, Int32 &res) -{ - res = NArchive::NExtract::NOperationResult::kDataError; - CInStreamReleaser inStreamReleaser; - - bool needCRC = true; - bool wzAesMode = false; - bool pkAesMode = false; - UInt16 methodId = item.CompressionMethod; - if (item.IsEncrypted()) - { - if (item.IsStrongEncrypted()) - { - CStrongCryptoField f; - if (item.CentralExtra.GetStrongCryptoField(f)) - { - pkAesMode = true; - } - if (!pkAesMode) - { - res = NArchive::NExtract::NOperationResult::kUnSupportedMethod; - return S_OK; - } - } - if (methodId == NFileHeader::NCompressionMethod::kWzAES) - { - CWzAesExtraField aesField; - if (item.CentralExtra.GetWzAesField(aesField)) - { - wzAesMode = true; - needCRC = aesField.NeedCrc(); - } - } - } - - COutStreamWithCRC *outStreamSpec = new COutStreamWithCRC; - CMyComPtr outStream = outStreamSpec; - outStreamSpec->SetStream(realOutStream); - outStreamSpec->Init(needCRC); - - UInt64 authenticationPos; - - CMyComPtr inStream; - { - UInt64 packSize = item.PackSize; - if (wzAesMode) - { - if (packSize < NCrypto::NWzAes::kMacSize) - return S_OK; - packSize -= NCrypto::NWzAes::kMacSize; - } - UInt64 dataPos = item.GetDataPosition(); - inStream.Attach(archive.CreateLimitedStream(dataPos, packSize)); - authenticationPos = dataPos + packSize; - } - - CMyComPtr cryptoFilter; - if (item.IsEncrypted()) - { - if (wzAesMode) - { - CWzAesExtraField aesField; - if (!item.CentralExtra.GetWzAesField(aesField)) - return S_OK; - methodId = aesField.Method; - if (!_wzAesDecoder) - { - _wzAesDecoderSpec = new NCrypto::NWzAes::CDecoder; - _wzAesDecoder = _wzAesDecoderSpec; - } - cryptoFilter = _wzAesDecoder; - Byte properties = aesField.Strength; - RINOK(_wzAesDecoderSpec->SetDecoderProperties2(&properties, 1)); - } - else if (pkAesMode) - { - if (!_pkAesDecoder) - { - _pkAesDecoderSpec = new NCrypto::NZipStrong::CDecoder; - _pkAesDecoder = _pkAesDecoderSpec; - } - cryptoFilter = _pkAesDecoder; - } - else - { - if (!_zipCryptoDecoder) - { - _zipCryptoDecoderSpec = new NCrypto::NZip::CDecoder; - _zipCryptoDecoder = _zipCryptoDecoderSpec; - } - cryptoFilter = _zipCryptoDecoder; - } - CMyComPtr cryptoSetPassword; - RINOK(cryptoFilter.QueryInterface(IID_ICryptoSetPassword, &cryptoSetPassword)); - - if (!getTextPassword) - extractCallback->QueryInterface(IID_ICryptoGetTextPassword, (void **)&getTextPassword); - - if (getTextPassword) - { - CMyComBSTR password; - RINOK(getTextPassword->CryptoGetTextPassword(&password)); - AString charPassword; - if (wzAesMode || pkAesMode) - { - charPassword = UnicodeStringToMultiByte((const wchar_t *)password, CP_ACP); - /* - for (int i = 0;; i++) - { - wchar_t c = password[i]; - if (c == 0) - break; - if (c >= 0x80) - { - res = NArchive::NExtract::NOperationResult::kDataError; - return S_OK; - } - charPassword += (char)c; - } - */ - } - else - { - // we use OEM. WinZip/Windows probably use ANSI for some files - charPassword = UnicodeStringToMultiByte((const wchar_t *)password, CP_OEMCP); - } - HRESULT result = cryptoSetPassword->CryptoSetPassword( - (const Byte *)(const char *)charPassword, charPassword.Length()); - if (result != S_OK) - return S_OK; - } - else - { - RINOK(cryptoSetPassword->CryptoSetPassword(0, 0)); - } - } - - int m; - for (m = 0; m < methodItems.Size(); m++) - if (methodItems[m].ZipMethod == methodId) - break; - - if (m == methodItems.Size()) - { - CMethodItem mi; - mi.ZipMethod = methodId; - if (methodId == NFileHeader::NCompressionMethod::kStored) - mi.Coder = new NCompress::CCopyCoder; - else if (methodId == NFileHeader::NCompressionMethod::kShrunk) - mi.Coder = new NCompress::NShrink::CDecoder; - else if (methodId == NFileHeader::NCompressionMethod::kImploded) - mi.Coder = new NCompress::NImplode::NDecoder::CCoder; - else if (methodId == NFileHeader::NCompressionMethod::kLZMA) - mi.Coder = new CLzmaDecoder; - else - { - CMethodId szMethodID; - if (methodId == NFileHeader::NCompressionMethod::kBZip2) - szMethodID = kMethodId_BZip2; - else - { - if (methodId > 0xFF) - { - res = NArchive::NExtract::NOperationResult::kUnSupportedMethod; - return S_OK; - } - szMethodID = kMethodId_ZipBase + (Byte)methodId; - } - - RINOK(CreateCoder(EXTERNAL_CODECS_LOC_VARS szMethodID, mi.Coder, false)); - - if (mi.Coder == 0) - { - res = NArchive::NExtract::NOperationResult::kUnSupportedMethod; - return S_OK; - } - } - m = methodItems.Add(mi); - } - ICompressCoder *coder = methodItems[m].Coder; - - { - CMyComPtr setDecoderProperties; - coder->QueryInterface(IID_ICompressSetDecoderProperties2, (void **)&setDecoderProperties); - if (setDecoderProperties) - { - Byte properties = (Byte)item.Flags; - RINOK(setDecoderProperties->SetDecoderProperties2(&properties, 1)); - } - } - - #ifdef COMPRESS_MT - { - CMyComPtr setCoderMt; - coder->QueryInterface(IID_ICompressSetCoderMt, (void **)&setCoderMt); - if (setCoderMt) - { - RINOK(setCoderMt->SetNumberOfThreads(numThreads)); - } - } - #endif - - { - HRESULT result = S_OK; - CMyComPtr inStreamNew; - if (item.IsEncrypted()) - { - if (!filterStream) - { - filterStreamSpec = new CFilterCoder; - filterStream = filterStreamSpec; - } - filterStreamSpec->Filter = cryptoFilter; - if (wzAesMode) - { - result = _wzAesDecoderSpec->ReadHeader(inStream); - } - else if (pkAesMode) - { - result =_pkAesDecoderSpec->ReadHeader(inStream, item.FileCRC, item.UnPackSize); - if (result == S_OK) - { - bool passwOK; - result = _pkAesDecoderSpec->CheckPassword(passwOK); - if (result == S_OK && !passwOK) - result = S_FALSE; - } - } - else - { - result = _zipCryptoDecoderSpec->ReadHeader(inStream); - } - - if (result == S_OK) - { - RINOK(filterStreamSpec->SetInStream(inStream)); - inStreamReleaser.FilterCoder = filterStreamSpec; - inStreamNew = filterStream; - if (wzAesMode) - { - if (!_wzAesDecoderSpec->CheckPasswordVerifyCode()) - result = S_FALSE; - } - } - } - else - inStreamNew = inStream; - if (result == S_OK) - result = coder->Code(inStreamNew, outStream, NULL, &item.UnPackSize, compressProgress); - if (result == S_FALSE) - return S_OK; - if (result == E_NOTIMPL) - { - res = NArchive::NExtract::NOperationResult::kUnSupportedMethod; - return S_OK; - } - - RINOK(result); - } - bool crcOK = true; - bool authOk = true; - if (needCRC) - crcOK = (outStreamSpec->GetCRC() == item.FileCRC); - if (wzAesMode) - { - inStream.Attach(archive.CreateLimitedStream(authenticationPos, NCrypto::NWzAes::kMacSize)); - if (_wzAesDecoderSpec->CheckMac(inStream, authOk) != S_OK) - authOk = false; - } - - res = ((crcOK && authOk) ? - NArchive::NExtract::NOperationResult::kOK : - NArchive::NExtract::NOperationResult::kCRCError); - return S_OK; -} - - -STDMETHODIMP CHandler::Extract(const UInt32* indices, UInt32 numItems, - Int32 _aTestMode, IArchiveExtractCallback *extractCallback) -{ - COM_TRY_BEGIN - CZipDecoder myDecoder; - bool testMode = (_aTestMode != 0); - UInt64 totalUnPacked = 0, totalPacked = 0; - bool allFilesMode = (numItems == UInt32(-1)); - if (allFilesMode) - numItems = m_Items.Size(); - if(numItems == 0) - return S_OK; - UInt32 i; - for(i = 0; i < numItems; i++) - { - const CItemEx &item = m_Items[allFilesMode ? i : indices[i]]; - totalUnPacked += item.UnPackSize; - totalPacked += item.PackSize; - } - RINOK(extractCallback->SetTotal(totalUnPacked)); - - UInt64 currentTotalUnPacked = 0, currentTotalPacked = 0; - UInt64 currentItemUnPacked, currentItemPacked; - - CLocalProgress *lps = new CLocalProgress; - CMyComPtr progress = lps; - lps->Init(extractCallback, false); - - for (i = 0; i < numItems; i++, currentTotalUnPacked += currentItemUnPacked, - currentTotalPacked += currentItemPacked) - { - currentItemUnPacked = 0; - currentItemPacked = 0; - - lps->InSize = currentTotalPacked; - lps->OutSize = currentTotalUnPacked; - RINOK(lps->SetCur()); - - CMyComPtr realOutStream; - Int32 askMode = testMode ? - NArchive::NExtract::NAskMode::kTest : - NArchive::NExtract::NAskMode::kExtract; - Int32 index = allFilesMode ? i : indices[i]; - - RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); - - CItemEx item = m_Items[index]; - if (!item.FromLocal) - { - HRESULT res = m_Archive.ReadLocalItemAfterCdItem(item); - if (res == S_FALSE) - { - if (item.IsDir() || realOutStream || testMode) - { - RINOK(extractCallback->PrepareOperation(askMode)); - realOutStream.Release(); - RINOK(extractCallback->SetOperationResult(NArchive::NExtract::NOperationResult::kUnSupportedMethod)); - } - continue; - } - RINOK(res); - } - - if (item.IsDir() || item.IgnoreItem()) - { - // if (!testMode) - { - RINOK(extractCallback->PrepareOperation(askMode)); - realOutStream.Release(); - RINOK(extractCallback->SetOperationResult(NArchive::NExtract::NOperationResult::kOK)); - } - continue; - } - - currentItemUnPacked = item.UnPackSize; - currentItemPacked = item.PackSize; - - if (!testMode && (!realOutStream)) - continue; - - RINOK(extractCallback->PrepareOperation(askMode)); - -#ifndef COMPRESS_MT -#define _numThreads 1 -#endif - - Int32 res; - RINOK(myDecoder.Decode( - EXTERNAL_CODECS_VARS - m_Archive, item, realOutStream, extractCallback, - progress, - _numThreads, - res)); - realOutStream.Release(); - - RINOK(extractCallback->SetOperationResult(res)) - } - return S_OK; - COM_TRY_END -} - -#ifndef EXTRACT_ONLY -IMPL_ISetCompressCodecsInfo -#endif - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipHandler.h b/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipHandler.h deleted file mode 100644 index fc0cfa250..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipHandler.h +++ /dev/null @@ -1,100 +0,0 @@ -// Zip/Handler.h - -#ifndef __ZIP_HANDLER_H -#define __ZIP_HANDLER_H - -#include "../../../Common/DynamicBuffer.h" -#include "../../ICoder.h" -#include "../IArchive.h" - -#include "../../Common/CreateCoder.h" - -#include "ZipIn.h" -#include "ZipCompressionMode.h" - -#ifdef COMPRESS_MT -#include "../../../Windows/System.h" -#endif - -namespace NArchive { -namespace NZip { - -class CHandler: - public IInArchive, -#ifndef EXTRACT_ONLY - public IOutArchive, - public ISetProperties, - PUBLIC_ISetCompressCodecsInfo -#endif - public CMyUnknownImp -{ -public: - MY_QUERYINTERFACE_BEGIN2(IInArchive) -#ifndef EXTRACT_ONLY - MY_QUERYINTERFACE_ENTRY(IOutArchive) - MY_QUERYINTERFACE_ENTRY(ISetProperties) - QUERY_ENTRY_ISetCompressCodecsInfo -#endif - MY_QUERYINTERFACE_END - MY_ADDREF_RELEASE - - INTERFACE_IInArchive(;) -#ifndef EXTRACT_ONLY - INTERFACE_IOutArchive(;) - - STDMETHOD(SetProperties)(const wchar_t **names, const PROPVARIANT *values, Int32 numProperties); - - DECL_ISetCompressCodecsInfo -#endif - - CHandler(); -private: - CObjectVector m_Items; - CInArchive m_Archive; - - int m_Level; - int m_MainMethod; - UInt32 m_DicSize; - UInt32 m_Algo; - UInt32 m_NumPasses; - UInt32 m_NumFastBytes; - UInt32 m_NumMatchFinderCycles; - bool m_NumMatchFinderCyclesDefined; - - bool m_IsAesMode; - Byte m_AesKeyMode; - - bool m_WriteNtfsTimeExtra; - bool m_ForseLocal; - bool m_ForseUtf8; - - #ifdef COMPRESS_MT - UInt32 _numThreads; - #endif - - DECL_EXTERNAL_CODECS_VARS - - void InitMethodProperties() - { - m_Level = -1; - m_MainMethod = -1; - m_Algo = - m_DicSize = - m_NumPasses = - m_NumFastBytes = - m_NumMatchFinderCycles = 0xFFFFFFFF; - m_NumMatchFinderCyclesDefined = false; - m_IsAesMode = false; - m_AesKeyMode = 3; // aes-256 - m_WriteNtfsTimeExtra = false; - m_ForseLocal = false; - m_ForseUtf8 = false; - #ifdef COMPRESS_MT - _numThreads = NWindows::NSystem::GetNumberOfProcessors();; - #endif - } -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipHeader.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipHeader.cpp deleted file mode 100644 index 331aed2be..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipHeader.cpp +++ /dev/null @@ -1,35 +0,0 @@ -// Archive/Zip/Header.h - -#include "StdAfx.h" - -#include "ZipHeader.h" - -namespace NArchive { -namespace NZip { - -namespace NSignature -{ - UInt32 kLocalFileHeader = 0x04034B50 + 1; - UInt32 kDataDescriptor = 0x08074B50 + 1; - UInt32 kCentralFileHeader = 0x02014B50 + 1; - UInt32 kEndOfCentralDir = 0x06054B50 + 1; - UInt32 kZip64EndOfCentralDir = 0x06064B50 + 1; - UInt32 kZip64EndOfCentralDirLocator = 0x07064B50 + 1; - - class CMarkersInitializer - { - public: - CMarkersInitializer() - { - kLocalFileHeader--; - kDataDescriptor--; - kCentralFileHeader--; - kEndOfCentralDir--; - kZip64EndOfCentralDir--; - kZip64EndOfCentralDirLocator--; - } - } g_MarkerInitializer; -} - -}} - diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipHeader.h b/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipHeader.h deleted file mode 100644 index b595e65e8..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipHeader.h +++ /dev/null @@ -1,265 +0,0 @@ -// Archive/Zip/Header.h - -#ifndef __ARCHIVE_ZIP_HEADER_H -#define __ARCHIVE_ZIP_HEADER_H - -#include "../../../Common/Types.h" - -namespace NArchive { -namespace NZip { - -namespace NSignature -{ - extern UInt32 kLocalFileHeader; - extern UInt32 kDataDescriptor; - extern UInt32 kCentralFileHeader; - extern UInt32 kEndOfCentralDir; - extern UInt32 kZip64EndOfCentralDir; - extern UInt32 kZip64EndOfCentralDirLocator; - - static const UInt32 kMarkerSize = 4; -} - -const UInt32 kEcdSize = 22; -const UInt32 kZip64EcdSize = 44; -const UInt32 kZip64EcdLocatorSize = 20; -/* -struct CEndOfCentralDirectoryRecord -{ - UInt16 ThisDiskNumber; - UInt16 StartCentralDirectoryDiskNumber; - UInt16 NumEntriesInCentaralDirectoryOnThisDisk; - UInt16 NumEntriesInCentaralDirectory; - UInt32 CentralDirectorySize; - UInt32 CentralDirectoryStartOffset; - UInt16 CommentSize; -}; - -struct CEndOfCentralDirectoryRecordFull -{ - UInt32 Signature; - CEndOfCentralDirectoryRecord Header; -}; -*/ - -namespace NFileHeader -{ - /* - struct CVersion - { - Byte Version; - Byte HostOS; - }; - */ - - namespace NCompressionMethod - { - enum EType - { - kStored = 0, - kShrunk = 1, - kReduced1 = 2, - kReduced2 = 3, - kReduced3 = 4, - kReduced4 = 5, - kImploded = 6, - kReservedTokenizing = 7, // reserved for tokenizing - kDeflated = 8, - kDeflated64 = 9, - kPKImploding = 10, - - kBZip2 = 12, - kLZMA = 14, - kTerse = 18, - kLz77 = 19, - kJpeg = 0x60, - kWavPack = 0x61, - kPPMd = 0x62, - kWzAES = 0x63 - }; - const int kNumCompressionMethods = 11; - const Byte kMadeByProgramVersion = 20; - - const Byte kDeflateExtractVersion = 20; - const Byte kStoreExtractVersion = 10; - - const Byte kSupportedVersion = 20; - } - - namespace NExtraID - { - enum - { - kZip64 = 0x01, - kNTFS = 0x0A, - kStrongEncrypt = 0x17, - kWzAES = 0x9901 - }; - } - - namespace NNtfsExtra - { - const UInt16 kTagTime = 1; - enum - { - kMTime = 0, - kATime = 1, - kCTime = 2 - }; - } - - const UInt32 kLocalBlockSize = 26; - /* - struct CLocalBlock - { - CVersion ExtractVersion; - - UInt16 Flags; - UInt16 CompressionMethod; - UInt32 Time; - UInt32 FileCRC; - UInt32 PackSize; - UInt32 UnPackSize; - UInt16 NameSize; - UInt16 ExtraSize; - }; - */ - - const UInt32 kDataDescriptorSize = 16; - // const UInt32 kDataDescriptor64Size = 16 + 8; - /* - struct CDataDescriptor - { - UInt32 Signature; - UInt32 FileCRC; - UInt32 PackSize; - UInt32 UnPackSize; - }; - - struct CLocalBlockFull - { - UInt32 Signature; - CLocalBlock Header; - }; - */ - - const UInt32 kCentralBlockSize = 42; - /* - struct CBlock - { - CVersion MadeByVersion; - CVersion ExtractVersion; - UInt16 Flags; - UInt16 CompressionMethod; - UInt32 Time; - UInt32 FileCRC; - UInt32 PackSize; - UInt32 UnPackSize; - UInt16 NameSize; - UInt16 ExtraSize; - UInt16 CommentSize; - UInt16 DiskNumberStart; - UInt16 InternalAttributes; - UInt32 ExternalAttributes; - UInt32 LocalHeaderOffset; - }; - - struct CBlockFull - { - UInt32 Signature; - CBlock Header; - }; - */ - - namespace NFlags - { - const int kEncrypted = 1 << 0; - const int kLzmaEOS = 1 << 1; - const int kDescriptorUsedMask = 1 << 3; - const int kStrongEncrypted = 1 << 6; - const int kUtf8 = 1 << 11; - - const int kImplodeDictionarySizeMask = 1 << 1; - const int kImplodeLiteralsOnMask = 1 << 2; - - const int kDeflateTypeBitStart = 1; - const int kNumDeflateTypeBits = 2; - const int kNumDeflateTypes = (1 << kNumDeflateTypeBits); - const int kDeflateTypeMask = (1 << kNumDeflateTypeBits) - 1; - } - - namespace NHostOS - { - enum EEnum - { - kFAT = 0, - kAMIGA = 1, - kVMS = 2, // VAX/VMS - kUnix = 3, - kVM_CMS = 4, - kAtari = 5, // what if it's a minix filesystem? [cjh] - kHPFS = 6, // filesystem used by OS/2 (and NT 3.x) - kMac = 7, - kZ_System = 8, - kCPM = 9, - kTOPS20 = 10, // pkzip 2.50 NTFS - kNTFS = 11, // filesystem used by Windows NT - kQDOS = 12, // SMS/QDOS - kAcorn = 13, // Archimedes Acorn RISC OS - kVFAT = 14, // filesystem used by Windows 95, NT - kMVS = 15, - kBeOS = 16, // hybrid POSIX/database filesystem - kTandem = 17, - kOS400 = 18, - kOSX = 19 - }; - } - namespace NUnixAttribute - { - const UInt32 kIFMT = 0170000; /* Unix file type mask */ - - const UInt32 kIFDIR = 0040000; /* Unix directory */ - const UInt32 kIFREG = 0100000; /* Unix regular file */ - const UInt32 kIFSOCK = 0140000; /* Unix socket (BSD, not SysV or Amiga) */ - const UInt32 kIFLNK = 0120000; /* Unix symbolic link (not SysV, Amiga) */ - const UInt32 kIFBLK = 0060000; /* Unix block special (not Amiga) */ - const UInt32 kIFCHR = 0020000; /* Unix character special (not Amiga) */ - const UInt32 kIFIFO = 0010000; /* Unix fifo (BCC, not MSC or Amiga) */ - - const UInt32 kISUID = 04000; /* Unix set user id on execution */ - const UInt32 kISGID = 02000; /* Unix set group id on execution */ - const UInt32 kISVTX = 01000; /* Unix directory permissions control */ - const UInt32 kENFMT = kISGID; /* Unix record locking enforcement flag */ - const UInt32 kIRWXU = 00700; /* Unix read, write, execute: owner */ - const UInt32 kIRUSR = 00400; /* Unix read permission: owner */ - const UInt32 kIWUSR = 00200; /* Unix write permission: owner */ - const UInt32 kIXUSR = 00100; /* Unix execute permission: owner */ - const UInt32 kIRWXG = 00070; /* Unix read, write, execute: group */ - const UInt32 kIRGRP = 00040; /* Unix read permission: group */ - const UInt32 kIWGRP = 00020; /* Unix write permission: group */ - const UInt32 kIXGRP = 00010; /* Unix execute permission: group */ - const UInt32 kIRWXO = 00007; /* Unix read, write, execute: other */ - const UInt32 kIROTH = 00004; /* Unix read permission: other */ - const UInt32 kIWOTH = 00002; /* Unix write permission: other */ - const UInt32 kIXOTH = 00001; /* Unix execute permission: other */ - } - - namespace NAmigaAttribute - { - const UInt32 kIFMT = 06000; /* Amiga file type mask */ - const UInt32 kIFDIR = 04000; /* Amiga directory */ - const UInt32 kIFREG = 02000; /* Amiga regular file */ - const UInt32 kIHIDDEN = 00200; /* to be supported in AmigaDOS 3.x */ - const UInt32 kISCRIPT = 00100; /* executable script (text command file) */ - const UInt32 kIPURE = 00040; /* allow loading into resident memory */ - const UInt32 kIARCHIVE = 00020; /* not modified since bit was last set */ - const UInt32 kIREAD = 00010; /* can be opened for reading */ - const UInt32 kIWRITE = 00004; /* can be opened for writing */ - const UInt32 kIEXECUTE = 00002; /* executable image, a loadable runfile */ - const UInt32 kIDELETE = 00001; /* can be deleted */ - } -} - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipIn.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipIn.cpp deleted file mode 100644 index 7c43bd911..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipIn.cpp +++ /dev/null @@ -1,868 +0,0 @@ -// Archive/ZipIn.cpp - -#include "StdAfx.h" - -#include "ZipIn.h" -#include "Windows/Defs.h" -#include "Common/StringConvert.h" -#include "Common/DynamicBuffer.h" -#include "../../Common/LimitedStreams.h" -#include "../../Common/StreamUtils.h" - -extern "C" -{ - #include "../../../../C/CpuArch.h" -} - -#define Get16(p) GetUi16(p) -#define Get32(p) GetUi32(p) -#define Get64(p) GetUi64(p) - -namespace NArchive { -namespace NZip { - -// static const char kEndOfString = '\0'; - -HRESULT CInArchive::Open(IInStream *stream, const UInt64 *searchHeaderSizeLimit) -{ - Close(); - RINOK(stream->Seek(0, STREAM_SEEK_CUR, &m_StreamStartPosition)); - m_Position = m_StreamStartPosition; - RINOK(FindAndReadMarker(stream, searchHeaderSizeLimit)); - RINOK(stream->Seek(m_Position, STREAM_SEEK_SET, NULL)); - m_Stream = stream; - return S_OK; -} - -void CInArchive::Close() -{ - m_Stream.Release(); -} - -HRESULT CInArchive::Seek(UInt64 offset) -{ - return m_Stream->Seek(offset, STREAM_SEEK_SET, NULL); -} - -////////////////////////////////////// -// Markers - -static inline bool TestMarkerCandidate(const Byte *p, UInt32 &value) -{ - value = Get32(p); - return - (value == NSignature::kLocalFileHeader) || - (value == NSignature::kEndOfCentralDir); -} - -static const UInt32 kNumMarkerAddtionalBytes = 2; -static inline bool TestMarkerCandidate2(const Byte *p, UInt32 &value) -{ - value = Get32(p); - if (value == NSignature::kEndOfCentralDir) - return (Get16(p + 4) == 0); - return (value == NSignature::kLocalFileHeader && p[4] < 128); -} - -HRESULT CInArchive::FindAndReadMarker(IInStream *stream, const UInt64 *searchHeaderSizeLimit) -{ - m_ArchiveInfo.Clear(); - m_Position = m_StreamStartPosition; - - Byte marker[NSignature::kMarkerSize]; - RINOK(ReadStream_FALSE(stream, marker, NSignature::kMarkerSize)); - m_Position += NSignature::kMarkerSize; - if (TestMarkerCandidate(marker, m_Signature)) - return S_OK; - - CByteDynamicBuffer dynamicBuffer; - const UInt32 kSearchMarkerBufferSize = 0x10000; - dynamicBuffer.EnsureCapacity(kSearchMarkerBufferSize); - Byte *buffer = dynamicBuffer; - UInt32 numBytesPrev = NSignature::kMarkerSize - 1; - memcpy(buffer, marker + 1, numBytesPrev); - UInt64 curTestPos = m_StreamStartPosition + 1; - for (;;) - { - if (searchHeaderSizeLimit != NULL) - if (curTestPos - m_StreamStartPosition > *searchHeaderSizeLimit) - break; - size_t numReadBytes = kSearchMarkerBufferSize - numBytesPrev; - RINOK(ReadStream(stream, buffer + numBytesPrev, &numReadBytes)); - m_Position += numReadBytes; - UInt32 numBytesInBuffer = numBytesPrev + (UInt32)numReadBytes; - const UInt32 kMarker2Size = NSignature::kMarkerSize + kNumMarkerAddtionalBytes; - if (numBytesInBuffer < kMarker2Size) - break; - UInt32 numTests = numBytesInBuffer - kMarker2Size + 1; - for (UInt32 pos = 0; pos < numTests; pos++) - { - if (buffer[pos] != 0x50) - continue; - if (TestMarkerCandidate2(buffer + pos, m_Signature)) - { - curTestPos += pos; - m_ArchiveInfo.StartPosition = curTestPos; - m_Position = curTestPos + NSignature::kMarkerSize; - return S_OK; - } - } - curTestPos += numTests; - numBytesPrev = numBytesInBuffer - numTests; - memmove(buffer, buffer + numTests, numBytesPrev); - } - return S_FALSE; -} - -HRESULT CInArchive::ReadBytes(void *data, UInt32 size, UInt32 *processedSize) -{ - size_t realProcessedSize = size; - HRESULT result = ReadStream(m_Stream, data, &realProcessedSize); - if (processedSize != NULL) - *processedSize = (UInt32)realProcessedSize; - m_Position += realProcessedSize; - return result; -} - -void CInArchive::IncreaseRealPosition(UInt64 addValue) -{ - if (m_Stream->Seek(addValue, STREAM_SEEK_CUR, &m_Position) != S_OK) - throw CInArchiveException(CInArchiveException::kSeekStreamError); -} - -bool CInArchive::ReadBytesAndTestSize(void *data, UInt32 size) -{ - UInt32 realProcessedSize; - if (ReadBytes(data, size, &realProcessedSize) != S_OK) - throw CInArchiveException(CInArchiveException::kReadStreamError); - return (realProcessedSize == size); -} - -void CInArchive::SafeReadBytes(void *data, UInt32 size) -{ - if (!ReadBytesAndTestSize(data, size)) - throw CInArchiveException(CInArchiveException::kUnexpectedEndOfArchive); -} - -void CInArchive::ReadBuffer(CByteBuffer &buffer, UInt32 size) -{ - buffer.SetCapacity(size); - if (size > 0) - SafeReadBytes(buffer, size); -} - -Byte CInArchive::ReadByte() -{ - Byte b; - SafeReadBytes(&b, 1); - return b; -} - -UInt16 CInArchive::ReadUInt16() -{ - UInt16 value = 0; - for (int i = 0; i < 2; i++) - value |= (((UInt16)ReadByte()) << (8 * i)); - return value; -} - -UInt32 CInArchive::ReadUInt32() -{ - UInt32 value = 0; - for (int i = 0; i < 4; i++) - value |= (((UInt32)ReadByte()) << (8 * i)); - return value; -} - -UInt64 CInArchive::ReadUInt64() -{ - UInt64 value = 0; - for (int i = 0; i < 8; i++) - value |= (((UInt64)ReadByte()) << (8 * i)); - return value; -} - -bool CInArchive::ReadUInt32(UInt32 &value) -{ - value = 0; - for (int i = 0; i < 4; i++) - { - Byte b; - if (!ReadBytesAndTestSize(&b, 1)) - return false; - value |= (UInt32(b) << (8 * i)); - } - return true; -} - - -AString CInArchive::ReadFileName(UInt32 nameSize) -{ - if (nameSize == 0) - return AString(); - char *p = m_NameBuffer.GetBuffer(nameSize); - SafeReadBytes(p, nameSize); - p[nameSize] = 0; - m_NameBuffer.ReleaseBuffer(); - return m_NameBuffer; -} - -void CInArchive::GetArchiveInfo(CInArchiveInfo &archiveInfo) const -{ - archiveInfo = m_ArchiveInfo; -} - -/* -void CInArchive::ThrowIncorrectArchiveException() -{ - throw CInArchiveException(CInArchiveException::kIncorrectArchive); -} -*/ - -static UInt32 GetUInt32(const Byte *data) -{ - return - ((UInt32)(Byte)data[0]) | - (((UInt32)(Byte)data[1]) << 8) | - (((UInt32)(Byte)data[2]) << 16) | - (((UInt32)(Byte)data[3]) << 24); -} - -/* -static UInt16 GetUInt16(const Byte *data) -{ - return - ((UInt16)(Byte)data[0]) | - (((UInt16)(Byte)data[1]) << 8); -} -*/ - -static UInt64 GetUInt64(const Byte *data) -{ - return GetUInt32(data) | ((UInt64)GetUInt32(data + 4) << 32); -} - - - -void CInArchive::ReadExtra(UInt32 extraSize, CExtraBlock &extraBlock, - UInt64 &unpackSize, UInt64 &packSize, UInt64 &localHeaderOffset, UInt32 &diskStartNumber) -{ - extraBlock.Clear(); - UInt32 remain = extraSize; - while(remain >= 4) - { - CExtraSubBlock subBlock; - subBlock.ID = ReadUInt16(); - UInt32 dataSize = ReadUInt16(); - remain -= 4; - if (dataSize > remain) // it's bug - dataSize = remain; - if (subBlock.ID == NFileHeader::NExtraID::kZip64) - { - if (unpackSize == 0xFFFFFFFF) - { - if (dataSize < 8) - break; - unpackSize = ReadUInt64(); - remain -= 8; - dataSize -= 8; - } - if (packSize == 0xFFFFFFFF) - { - if (dataSize < 8) - break; - packSize = ReadUInt64(); - remain -= 8; - dataSize -= 8; - } - if (localHeaderOffset == 0xFFFFFFFF) - { - if (dataSize < 8) - break; - localHeaderOffset = ReadUInt64(); - remain -= 8; - dataSize -= 8; - } - if (diskStartNumber == 0xFFFF) - { - if (dataSize < 4) - break; - diskStartNumber = ReadUInt32(); - remain -= 4; - dataSize -= 4; - } - for (UInt32 i = 0; i < dataSize; i++) - ReadByte(); - } - else - { - ReadBuffer(subBlock.Data, dataSize); - extraBlock.SubBlocks.Add(subBlock); - } - remain -= dataSize; - } - IncreaseRealPosition(remain); -} - -HRESULT CInArchive::ReadLocalItem(CItemEx &item) -{ - item.ExtractVersion.Version = ReadByte(); - item.ExtractVersion.HostOS = ReadByte(); - item.Flags = ReadUInt16(); - item.CompressionMethod = ReadUInt16(); - item.Time = ReadUInt32(); - item.FileCRC = ReadUInt32(); - item.PackSize = ReadUInt32(); - item.UnPackSize = ReadUInt32(); - UInt32 fileNameSize = ReadUInt16(); - item.LocalExtraSize = ReadUInt16(); - item.Name = ReadFileName(fileNameSize); - item.FileHeaderWithNameSize = 4 + NFileHeader::kLocalBlockSize + fileNameSize; - if (item.LocalExtraSize > 0) - { - UInt64 localHeaderOffset = 0; - UInt32 diskStartNumber = 0; - ReadExtra(item.LocalExtraSize, item.LocalExtra, item.UnPackSize, item.PackSize, - localHeaderOffset, diskStartNumber); - } - /* - if (item.IsDir()) - item.UnPackSize = 0; // check It - */ - return S_OK; -} - -HRESULT CInArchive::ReadLocalItemAfterCdItem(CItemEx &item) -{ - if (item.FromLocal) - return S_OK; - try - { - RINOK(Seek(m_ArchiveInfo.Base + item.LocalHeaderPosition)); - CItemEx localItem; - if (ReadUInt32() != NSignature::kLocalFileHeader) - return S_FALSE; - RINOK(ReadLocalItem(localItem)); - if (item.Flags != localItem.Flags) - { - if ( - (item.CompressionMethod != NFileHeader::NCompressionMethod::kDeflated || - (item.Flags & 0x7FF9) != (localItem.Flags & 0x7FF9)) && - (item.CompressionMethod != NFileHeader::NCompressionMethod::kStored || - (item.Flags & 0x7FFF) != (localItem.Flags & 0x7FFF)) && - (item.CompressionMethod != NFileHeader::NCompressionMethod::kImploded || - (item.Flags & 0x7FFF) != (localItem.Flags & 0x7FFF)) - ) - return S_FALSE; - } - - if (item.CompressionMethod != localItem.CompressionMethod || - // item.Time != localItem.Time || - (!localItem.HasDescriptor() && - ( - item.FileCRC != localItem.FileCRC || - item.PackSize != localItem.PackSize || - item.UnPackSize != localItem.UnPackSize - ) - ) || - item.Name.Length() != localItem.Name.Length() - ) - return S_FALSE; - item.FileHeaderWithNameSize = localItem.FileHeaderWithNameSize; - item.LocalExtraSize = localItem.LocalExtraSize; - item.LocalExtra = localItem.LocalExtra; - item.FromLocal = true; - } - catch(...) { return S_FALSE; } - return S_OK; -} - -HRESULT CInArchive::ReadLocalItemDescriptor(CItemEx &item) -{ - if (item.HasDescriptor()) - { - const int kBufferSize = (1 << 12); - Byte buffer[kBufferSize]; - - UInt32 numBytesInBuffer = 0; - UInt32 packedSize = 0; - - bool descriptorWasFound = false; - for (;;) - { - UInt32 processedSize; - RINOK(ReadBytes(buffer + numBytesInBuffer, kBufferSize - numBytesInBuffer, &processedSize)); - numBytesInBuffer += processedSize; - if (numBytesInBuffer < NFileHeader::kDataDescriptorSize) - return S_FALSE; - UInt32 i; - for (i = 0; i <= numBytesInBuffer - NFileHeader::kDataDescriptorSize; i++) - { - // descriptorSignature field is Info-ZIP's extension - // to Zip specification. - UInt32 descriptorSignature = GetUInt32(buffer + i); - - // !!!! It must be fixed for Zip64 archives - UInt32 descriptorPackSize = GetUInt32(buffer + i + 8); - if (descriptorSignature== NSignature::kDataDescriptor && descriptorPackSize == packedSize + i) - { - descriptorWasFound = true; - item.FileCRC = GetUInt32(buffer + i + 4); - item.PackSize = descriptorPackSize; - item.UnPackSize = GetUInt32(buffer + i + 12); - IncreaseRealPosition(Int64(Int32(0 - (numBytesInBuffer - i - NFileHeader::kDataDescriptorSize)))); - break; - } - } - if (descriptorWasFound) - break; - packedSize += i; - int j; - for (j = 0; i < numBytesInBuffer; i++, j++) - buffer[j] = buffer[i]; - numBytesInBuffer = j; - } - } - else - IncreaseRealPosition(item.PackSize); - return S_OK; -} - -HRESULT CInArchive::ReadLocalItemAfterCdItemFull(CItemEx &item) -{ - if (item.FromLocal) - return S_OK; - try - { - RINOK(ReadLocalItemAfterCdItem(item)); - if (item.HasDescriptor()) - { - RINOK(Seek(m_ArchiveInfo.Base + item.GetDataPosition() + item.PackSize)); - if (ReadUInt32() != NSignature::kDataDescriptor) - return S_FALSE; - UInt32 crc = ReadUInt32(); - UInt64 packSize, unpackSize; - - /* - if (IsZip64) - { - packSize = ReadUInt64(); - unpackSize = ReadUInt64(); - } - else - */ - { - packSize = ReadUInt32(); - unpackSize = ReadUInt32(); - } - - if (crc != item.FileCRC || item.PackSize != packSize || item.UnPackSize != unpackSize) - return S_FALSE; - } - } - catch(...) { return S_FALSE; } - return S_OK; -} - -HRESULT CInArchive::ReadCdItem(CItemEx &item) -{ - item.FromCentral = true; - const int kBufSize = 42; - Byte p[kBufSize]; - SafeReadBytes(p, kBufSize); - item.MadeByVersion.Version = p[0]; - item.MadeByVersion.HostOS = p[1]; - item.ExtractVersion.Version = p[2]; - item.ExtractVersion.HostOS = p[3]; - item.Flags = Get16(p + 4); - item.CompressionMethod = Get16(p + 6); - item.Time = Get32(p + 8); - item.FileCRC = Get32(p + 12); - item.PackSize = Get32(p + 16); - item.UnPackSize = Get32(p + 20); - UInt16 headerNameSize = Get16(p + 24); - UInt16 headerExtraSize = Get16(p + 26); - UInt16 headerCommentSize = Get16(p + 28); - UInt32 headerDiskNumberStart = Get16(p + 30); - item.InternalAttributes = Get16(p + 32); - item.ExternalAttributes = Get32(p + 34); - item.LocalHeaderPosition = Get32(p + 38); - item.Name = ReadFileName(headerNameSize); - - if (headerExtraSize > 0) - { - ReadExtra(headerExtraSize, item.CentralExtra, item.UnPackSize, item.PackSize, - item.LocalHeaderPosition, headerDiskNumberStart); - } - - if (headerDiskNumberStart != 0) - throw CInArchiveException(CInArchiveException::kMultiVolumeArchiveAreNotSupported); - - // May be these strings must be deleted - /* - if (item.IsDir()) - item.UnPackSize = 0; - */ - - ReadBuffer(item.Comment, headerCommentSize); - return S_OK; -} - -HRESULT CInArchive::TryEcd64(UInt64 offset, CCdInfo &cdInfo) -{ - RINOK(Seek(offset)); - const UInt32 kEcd64Size = 56; - Byte buf[kEcd64Size]; - if (!ReadBytesAndTestSize(buf, kEcd64Size)) - return S_FALSE; - if (GetUInt32(buf) != NSignature::kZip64EndOfCentralDir) - return S_FALSE; - // cdInfo.NumEntries = GetUInt64(buf + 24); - cdInfo.Size = GetUInt64(buf + 40); - cdInfo.Offset = GetUInt64(buf + 48); - return S_OK; -} - -HRESULT CInArchive::FindCd(CCdInfo &cdInfo) -{ - UInt64 endPosition; - RINOK(m_Stream->Seek(0, STREAM_SEEK_END, &endPosition)); - const UInt32 kBufSizeMax = (1 << 16) + kEcdSize + kZip64EcdLocatorSize; - Byte buf[kBufSizeMax]; - UInt32 bufSize = (endPosition < kBufSizeMax) ? (UInt32)endPosition : kBufSizeMax; - if (bufSize < kEcdSize) - return S_FALSE; - UInt64 startPosition = endPosition - bufSize; - RINOK(m_Stream->Seek(startPosition, STREAM_SEEK_SET, &m_Position)); - if (m_Position != startPosition) - return S_FALSE; - if (!ReadBytesAndTestSize(buf, bufSize)) - return S_FALSE; - for (int i = (int)(bufSize - kEcdSize); i >= 0; i--) - { - if (GetUInt32(buf + i) == NSignature::kEndOfCentralDir) - { - if (i >= kZip64EcdLocatorSize) - { - const Byte *locator = buf + i - kZip64EcdLocatorSize; - if (GetUInt32(locator) == NSignature::kZip64EndOfCentralDirLocator) - { - UInt64 ecd64Offset = GetUInt64(locator + 8); - if (TryEcd64(ecd64Offset, cdInfo) == S_OK) - return S_OK; - if (TryEcd64(m_ArchiveInfo.StartPosition + ecd64Offset, cdInfo) == S_OK) - { - m_ArchiveInfo.Base = m_ArchiveInfo.StartPosition; - return S_OK; - } - } - } - if (GetUInt32(buf + i + 4) == 0) - { - // cdInfo.NumEntries = GetUInt16(buf + i + 10); - cdInfo.Size = GetUInt32(buf + i + 12); - cdInfo.Offset = GetUInt32(buf + i + 16); - UInt64 curPos = endPosition - bufSize + i; - UInt64 cdEnd = cdInfo.Size + cdInfo.Offset; - if (curPos > cdEnd) - m_ArchiveInfo.Base = curPos - cdEnd; - return S_OK; - } - } - } - return S_FALSE; -} - -HRESULT CInArchive::TryReadCd(CObjectVector &items, UInt64 cdOffset, UInt64 cdSize, CProgressVirt *progress) -{ - items.Clear(); - RINOK(m_Stream->Seek(cdOffset, STREAM_SEEK_SET, &m_Position)); - if (m_Position != cdOffset) - return S_FALSE; - while(m_Position - cdOffset < cdSize) - { - if (ReadUInt32() != NSignature::kCentralFileHeader) - return S_FALSE; - CItemEx cdItem; - RINOK(ReadCdItem(cdItem)); - items.Add(cdItem); - if (progress && items.Size() % 1000 == 0) - RINOK(progress->SetCompleted(items.Size())); - } - return (m_Position - cdOffset == cdSize) ? S_OK : S_FALSE; -} - -HRESULT CInArchive::ReadCd(CObjectVector &items, UInt64 &cdOffset, UInt64 &cdSize, CProgressVirt *progress) -{ - m_ArchiveInfo.Base = 0; - CCdInfo cdInfo; - RINOK(FindCd(cdInfo)); - HRESULT res = S_FALSE; - cdSize = cdInfo.Size; - cdOffset = cdInfo.Offset; - res = TryReadCd(items, m_ArchiveInfo.Base + cdOffset, cdSize, progress); - if (res == S_FALSE && m_ArchiveInfo.Base == 0) - { - res = TryReadCd(items, cdInfo.Offset + m_ArchiveInfo.StartPosition, cdSize, progress); - if (res == S_OK) - m_ArchiveInfo.Base = m_ArchiveInfo.StartPosition; - } - if (!ReadUInt32(m_Signature)) - return S_FALSE; - return res; -} - -HRESULT CInArchive::ReadLocalsAndCd(CObjectVector &items, CProgressVirt *progress, UInt64 &cdOffset) -{ - items.Clear(); - while (m_Signature == NSignature::kLocalFileHeader) - { - // FSeek points to next byte after signature - // NFileHeader::CLocalBlock localHeader; - CItemEx item; - item.LocalHeaderPosition = m_Position - m_StreamStartPosition - 4; // points to signature; - RINOK(ReadLocalItem(item)); - item.FromLocal = true; - ReadLocalItemDescriptor(item); - items.Add(item); - if (progress && items.Size() % 100 == 0) - RINOK(progress->SetCompleted(items.Size())); - if (!ReadUInt32(m_Signature)) - break; - } - cdOffset = m_Position - 4; - for (int i = 0; i < items.Size(); i++) - { - if (progress && i % 1000 == 0) - RINOK(progress->SetCompleted(items.Size())); - if (m_Signature != NSignature::kCentralFileHeader) - return S_FALSE; - - CItemEx cdItem; - RINOK(ReadCdItem(cdItem)); - - if (i == 0) - { - if (cdItem.LocalHeaderPosition == 0) - m_ArchiveInfo.Base = m_ArchiveInfo.StartPosition; - } - - int index; - int left = 0, right = items.Size(); - for (;;) - { - if (left >= right) - return S_FALSE; - index = (left + right) / 2; - UInt64 position = items[index].LocalHeaderPosition - m_ArchiveInfo.Base; - if (cdItem.LocalHeaderPosition == position) - break; - if (cdItem.LocalHeaderPosition < position) - right = index; - else - left = index + 1; - } - CItemEx &item = items[index]; - item.LocalHeaderPosition = cdItem.LocalHeaderPosition; - item.MadeByVersion = cdItem.MadeByVersion; - item.CentralExtra = cdItem.CentralExtra; - - if ( - // item.ExtractVersion != cdItem.ExtractVersion || - item.Flags != cdItem.Flags || - item.CompressionMethod != cdItem.CompressionMethod || - // item.Time != cdItem.Time || - item.FileCRC != cdItem.FileCRC) - return S_FALSE; - - if (item.Name.Length() != cdItem.Name.Length() || - item.PackSize != cdItem.PackSize || - item.UnPackSize != cdItem.UnPackSize - ) - return S_FALSE; - item.Name = cdItem.Name; - item.InternalAttributes = cdItem.InternalAttributes; - item.ExternalAttributes = cdItem.ExternalAttributes; - item.Comment = cdItem.Comment; - item.FromCentral = cdItem.FromCentral; - if (!ReadUInt32(m_Signature)) - return S_FALSE; - } - return S_OK; -} - -struct CEcd -{ - UInt16 thisDiskNumber; - UInt16 startCDDiskNumber; - UInt16 numEntriesInCDOnThisDisk; - UInt16 numEntriesInCD; - UInt32 cdSize; - UInt32 cdStartOffset; - UInt16 commentSize; - void Parse(const Byte *p); -}; - -void CEcd::Parse(const Byte *p) -{ - thisDiskNumber = Get16(p); - startCDDiskNumber = Get16(p + 2); - numEntriesInCDOnThisDisk = Get16(p + 4); - numEntriesInCD = Get16(p + 6); - cdSize = Get32(p + 8); - cdStartOffset = Get32(p + 12); - commentSize = Get16(p + 16); -} - -struct CEcd64 -{ - UInt16 versionMade; - UInt16 versionNeedExtract; - UInt32 thisDiskNumber; - UInt32 startCDDiskNumber; - UInt64 numEntriesInCDOnThisDisk; - UInt64 numEntriesInCD; - UInt64 cdSize; - UInt64 cdStartOffset; - void Parse(const Byte *p); - CEcd64() { memset(this, 0, sizeof(*this)); } -}; - -void CEcd64::Parse(const Byte *p) -{ - versionMade = Get16(p); - versionNeedExtract = Get16(p + 2); - thisDiskNumber = Get32(p + 4); - startCDDiskNumber = Get32(p + 8); - numEntriesInCDOnThisDisk = Get64(p + 12); - numEntriesInCD = Get64(p + 20); - cdSize = Get64(p + 28); - cdStartOffset = Get64(p + 36); -} - -#define COPY_ECD_ITEM_16(n) if (!isZip64 || ecd. n != 0xFFFF) ecd64. n = ecd. n; -#define COPY_ECD_ITEM_32(n) if (!isZip64 || ecd. n != 0xFFFFFFFF) ecd64. n = ecd. n; - -HRESULT CInArchive::ReadHeaders(CObjectVector &items, CProgressVirt *progress) -{ - // m_Signature must be kLocalFileHeaderSignature or - // kEndOfCentralDirSignature - // m_Position points to next byte after signature - - IsZip64 = false; - items.Clear(); - - UInt64 cdSize, cdStartOffset; - HRESULT res = ReadCd(items, cdStartOffset, cdSize, progress); - if (res != S_FALSE && res != S_OK) - return res; - - /* - if (res != S_OK) - return res; - res = S_FALSE; - */ - - if (res == S_FALSE) - { - m_ArchiveInfo.Base = 0; - RINOK(m_Stream->Seek(m_ArchiveInfo.StartPosition, STREAM_SEEK_SET, &m_Position)); - if (m_Position != m_ArchiveInfo.StartPosition) - return S_FALSE; - if (!ReadUInt32(m_Signature)) - return S_FALSE; - RINOK(ReadLocalsAndCd(items, progress, cdStartOffset)); - cdSize = (m_Position - 4) - cdStartOffset; - cdStartOffset -= m_ArchiveInfo.Base; - } - - CEcd64 ecd64; - bool isZip64 = false; - UInt64 zip64EcdStartOffset = m_Position - 4 - m_ArchiveInfo.Base; - if (m_Signature == NSignature::kZip64EndOfCentralDir) - { - IsZip64 = isZip64 = true; - UInt64 recordSize = ReadUInt64(); - - const int kBufSize = kZip64EcdSize; - Byte buf[kBufSize]; - SafeReadBytes(buf, kBufSize); - ecd64.Parse(buf); - - IncreaseRealPosition(recordSize - kZip64EcdSize); - if (!ReadUInt32(m_Signature)) - return S_FALSE; - if (ecd64.thisDiskNumber != 0 || ecd64.startCDDiskNumber != 0) - throw CInArchiveException(CInArchiveException::kMultiVolumeArchiveAreNotSupported); - if (ecd64.numEntriesInCDOnThisDisk != items.Size() || - ecd64.numEntriesInCD != items.Size() || - ecd64.cdSize != cdSize || - (ecd64.cdStartOffset != cdStartOffset && - (!items.IsEmpty()))) - return S_FALSE; - } - if (m_Signature == NSignature::kZip64EndOfCentralDirLocator) - { - /* UInt32 startEndCDDiskNumber = */ ReadUInt32(); - UInt64 endCDStartOffset = ReadUInt64(); - /* UInt32 numberOfDisks = */ ReadUInt32(); - if (zip64EcdStartOffset != endCDStartOffset) - return S_FALSE; - if (!ReadUInt32(m_Signature)) - return S_FALSE; - } - if (m_Signature != NSignature::kEndOfCentralDir) - return S_FALSE; - - const int kBufSize = kEcdSize - 4; - Byte buf[kBufSize]; - SafeReadBytes(buf, kBufSize); - CEcd ecd; - ecd.Parse(buf); - - COPY_ECD_ITEM_16(thisDiskNumber); - COPY_ECD_ITEM_16(startCDDiskNumber); - COPY_ECD_ITEM_16(numEntriesInCDOnThisDisk); - COPY_ECD_ITEM_16(numEntriesInCD); - COPY_ECD_ITEM_32(cdSize); - COPY_ECD_ITEM_32(cdStartOffset); - - ReadBuffer(m_ArchiveInfo.Comment, ecd.commentSize); - - if (ecd64.thisDiskNumber != 0 || ecd64.startCDDiskNumber != 0) - throw CInArchiveException(CInArchiveException::kMultiVolumeArchiveAreNotSupported); - if ((UInt16)ecd64.numEntriesInCDOnThisDisk != ((UInt16)items.Size()) || - (UInt16)ecd64.numEntriesInCD != ((UInt16)items.Size()) || - (UInt32)ecd64.cdSize != (UInt32)cdSize || - ((UInt32)(ecd64.cdStartOffset) != (UInt32)cdStartOffset && - (!items.IsEmpty()))) - return S_FALSE; - - return S_OK; -} - -ISequentialInStream* CInArchive::CreateLimitedStream(UInt64 position, UInt64 size) -{ - CLimitedSequentialInStream *streamSpec = new CLimitedSequentialInStream; - CMyComPtr stream(streamSpec); - SeekInArchive(m_ArchiveInfo.Base + position); - streamSpec->SetStream(m_Stream); - streamSpec->Init(size); - return stream.Detach(); -} - -IInStream* CInArchive::CreateStream() -{ - CMyComPtr stream = m_Stream; - return stream.Detach(); -} - -bool CInArchive::SeekInArchive(UInt64 position) -{ - UInt64 newPosition; - if (m_Stream->Seek(position, STREAM_SEEK_SET, &newPosition) != S_OK) - return false; - return (newPosition == position); -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipIn.h b/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipIn.h deleted file mode 100644 index dd8114c3d..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipIn.h +++ /dev/null @@ -1,116 +0,0 @@ -// Archive/ZipIn.h - -#ifndef __ZIP_IN_H -#define __ZIP_IN_H - -#include "../../../Common/MyCom.h" -#include "../../IStream.h" - -#include "ZipHeader.h" -#include "ZipItemEx.h" - -namespace NArchive { -namespace NZip { - -class CInArchiveException -{ -public: - enum ECauseType - { - kUnexpectedEndOfArchive = 0, - kArchiceHeaderCRCError, - kFileHeaderCRCError, - kIncorrectArchive, - kDataDescroptorsAreNotSupported, - kMultiVolumeArchiveAreNotSupported, - kReadStreamError, - kSeekStreamError - } - Cause; - CInArchiveException(ECauseType cause): Cause(cause) {} -}; - -class CInArchiveInfo -{ -public: - UInt64 Base; - UInt64 StartPosition; - CByteBuffer Comment; - CInArchiveInfo(): Base(0), StartPosition(0) {} - void Clear() - { - Base = 0; - StartPosition = 0; - Comment.SetCapacity(0); - } -}; - -class CProgressVirt -{ -public: - STDMETHOD(SetTotal)(UInt64 numFiles) PURE; - STDMETHOD(SetCompleted)(UInt64 numFiles) PURE; -}; - -struct CCdInfo -{ - // UInt64 NumEntries; - UInt64 Size; - UInt64 Offset; -}; - -class CInArchive -{ - CMyComPtr m_Stream; - UInt32 m_Signature; - UInt64 m_StreamStartPosition; - UInt64 m_Position; - AString m_NameBuffer; - - HRESULT Seek(UInt64 offset); - - HRESULT FindAndReadMarker(IInStream *stream, const UInt64 *searchHeaderSizeLimit); - bool ReadUInt32(UInt32 &signature); - AString ReadFileName(UInt32 nameSize); - - HRESULT ReadBytes(void *data, UInt32 size, UInt32 *processedSize); - bool ReadBytesAndTestSize(void *data, UInt32 size); - void SafeReadBytes(void *data, UInt32 size); - void ReadBuffer(CByteBuffer &buffer, UInt32 size); - Byte ReadByte(); - UInt16 ReadUInt16(); - UInt32 ReadUInt32(); - UInt64 ReadUInt64(); - - void IncreaseRealPosition(UInt64 addValue); - - void ReadExtra(UInt32 extraSize, CExtraBlock &extraBlock, - UInt64 &unpackSize, UInt64 &packSize, UInt64 &localHeaderOffset, UInt32 &diskStartNumber); - HRESULT ReadLocalItem(CItemEx &item); - HRESULT ReadLocalItemDescriptor(CItemEx &item); - HRESULT ReadCdItem(CItemEx &item); - HRESULT TryEcd64(UInt64 offset, CCdInfo &cdInfo); - HRESULT FindCd(CCdInfo &cdInfo); - HRESULT TryReadCd(CObjectVector &items, UInt64 cdOffset, UInt64 cdSize, CProgressVirt *progress); - HRESULT ReadCd(CObjectVector &items, UInt64 &cdOffset, UInt64 &cdSize, CProgressVirt *progress); - HRESULT ReadLocalsAndCd(CObjectVector &items, CProgressVirt *progress, UInt64 &cdOffset); -public: - CInArchiveInfo m_ArchiveInfo; - bool IsZip64; - - HRESULT ReadHeaders(CObjectVector &items, CProgressVirt *progress); - HRESULT ReadLocalItemAfterCdItem(CItemEx &item); - HRESULT ReadLocalItemAfterCdItemFull(CItemEx &item); - HRESULT Open(IInStream *stream, const UInt64 *searchHeaderSizeLimit); - void Close(); - void GetArchiveInfo(CInArchiveInfo &archiveInfo) const; - bool SeekInArchive(UInt64 position); - ISequentialInStream *CreateLimitedStream(UInt64 position, UInt64 size); - IInStream* CreateStream(); - - bool IsOpen() const { return m_Stream != NULL; } -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipItem.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipItem.cpp deleted file mode 100644 index 6756e4b44..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipItem.cpp +++ /dev/null @@ -1,147 +0,0 @@ -// Archive/ZipItem.cpp - -#include "StdAfx.h" - -#include "ZipHeader.h" -#include "ZipItem.h" -#include "../Common/ItemNameUtils.h" -#include "../../../../C/CpuArch.h" - -namespace NArchive { -namespace NZip { - -bool operator==(const CVersion &v1, const CVersion &v2) -{ - return (v1.Version == v2.Version) && (v1.HostOS == v2.HostOS); -} - -bool operator!=(const CVersion &v1, const CVersion &v2) -{ - return !(v1 == v2); -} - -bool CExtraSubBlock::ExtractNtfsTime(int index, FILETIME &ft) const -{ - ft.dwHighDateTime = ft.dwLowDateTime = 0; - UInt32 size = (UInt32)Data.GetCapacity(); - if (ID != NFileHeader::NExtraID::kNTFS || size < 32) - return false; - const Byte *p = (const Byte *)Data; - p += 4; // for reserved - size -= 4; - while (size > 4) - { - UInt16 tag = GetUi16(p); - UInt32 attrSize = GetUi16(p + 2); - p += 4; - size -= 4; - if (attrSize > size) - attrSize = size; - - if (tag == NFileHeader::NNtfsExtra::kTagTime && attrSize >= 24) - { - p += 8 * index; - ft.dwLowDateTime = GetUi32(p); - ft.dwHighDateTime = GetUi32(p + 4); - return true; - } - p += attrSize; - size -= attrSize; - } - return false; -} - -bool CLocalItem::IsDir() const -{ - return NItemName::HasTailSlash(Name, GetCodePage()); -} - -bool CItem::IsDir() const -{ - if (NItemName::HasTailSlash(Name, GetCodePage())) - return true; - if (!FromCentral) - return false; - WORD highAttributes = WORD((ExternalAttributes >> 16 ) & 0xFFFF); - switch(MadeByVersion.HostOS) - { - case NFileHeader::NHostOS::kAMIGA: - switch (highAttributes & NFileHeader::NAmigaAttribute::kIFMT) - { - case NFileHeader::NAmigaAttribute::kIFDIR: return true; - case NFileHeader::NAmigaAttribute::kIFREG: return false; - default: return false; // change it throw kUnknownAttributes; - } - case NFileHeader::NHostOS::kFAT: - case NFileHeader::NHostOS::kNTFS: - case NFileHeader::NHostOS::kHPFS: - case NFileHeader::NHostOS::kVFAT: - return ((ExternalAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0); - case NFileHeader::NHostOS::kAtari: - case NFileHeader::NHostOS::kMac: - case NFileHeader::NHostOS::kVMS: - case NFileHeader::NHostOS::kVM_CMS: - case NFileHeader::NHostOS::kAcorn: - case NFileHeader::NHostOS::kMVS: - return false; // change it throw kUnknownAttributes; - default: - /* - switch (highAttributes & NFileHeader::NUnixAttribute::kIFMT) - { - case NFileHeader::NUnixAttribute::kIFDIR: - return true; - default: - return false; - } - */ - return false; - } -} - -UInt32 CLocalItem::GetWinAttributes() const -{ - DWORD winAttributes = 0; - if (IsDir()) - winAttributes |= FILE_ATTRIBUTE_DIRECTORY; - return winAttributes; -} - -UInt32 CItem::GetWinAttributes() const -{ - DWORD winAttributes = 0; - switch(MadeByVersion.HostOS) - { - case NFileHeader::NHostOS::kFAT: - case NFileHeader::NHostOS::kNTFS: - if (FromCentral) - winAttributes = ExternalAttributes; - break; - default: - winAttributes = 0; // must be converted from unix value; - } - if (IsDir()) // test it; - winAttributes |= FILE_ATTRIBUTE_DIRECTORY; - return winAttributes; -} - -void CLocalItem::SetFlagBits(int startBitNumber, int numBits, int value) -{ - UInt16 mask = (UInt16)(((1 << numBits) - 1) << startBitNumber); - Flags &= ~mask; - Flags |= value << startBitNumber; -} - -void CLocalItem::SetBitMask(int bitMask, bool enable) -{ - if(enable) - Flags |= bitMask; - else - Flags &= ~bitMask; -} - -void CLocalItem::SetEncrypted(bool encrypted) - { SetBitMask(NFileHeader::NFlags::kEncrypted, encrypted); } -void CLocalItem::SetUtf8(bool isUtf8) - { SetBitMask(NFileHeader::NFlags::kUtf8, isUtf8); } - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipItem.h b/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipItem.h deleted file mode 100644 index e7e0c47bf..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipItem.h +++ /dev/null @@ -1,268 +0,0 @@ -// Archive/ZipItem.h - -#ifndef __ARCHIVE_ZIP_ITEM_H -#define __ARCHIVE_ZIP_ITEM_H - -#include "../../../Common/Types.h" -#include "../../../Common/MyString.h" -#include "../../../Common/Buffer.h" -#include "../../../Common/UTFConvert.h" -#include "../../../Common/StringConvert.h" - -#include "ZipHeader.h" - -namespace NArchive { -namespace NZip { - -struct CVersion -{ - Byte Version; - Byte HostOS; -}; - -bool operator==(const CVersion &v1, const CVersion &v2); -bool operator!=(const CVersion &v1, const CVersion &v2); - -struct CExtraSubBlock -{ - UInt16 ID; - CByteBuffer Data; - bool ExtractNtfsTime(int index, FILETIME &ft) const; -}; - -struct CWzAesExtraField -{ - UInt16 VendorVersion; // 0x0001 - AE-1, 0x0002 - AE-2, - // UInt16 VendorId; // "AE" - Byte Strength; // 1 - 128-bit , 2 - 192-bit , 3 - 256-bit - UInt16 Method; - - CWzAesExtraField(): VendorVersion(2), Strength(3), Method(0) {} - - bool NeedCrc() const { return (VendorVersion == 1); } - - bool ParseFromSubBlock(const CExtraSubBlock &sb) - { - if (sb.ID != NFileHeader::NExtraID::kWzAES) - return false; - if (sb.Data.GetCapacity() < 7) - return false; - const Byte *p = (const Byte *)sb.Data; - VendorVersion = (((UInt16)p[1]) << 8) | p[0]; - if (p[2] != 'A' || p[3] != 'E') - return false; - Strength = p[4]; - Method = (((UInt16)p[6]) << 16) | p[5]; - return true; - } - void SetSubBlock(CExtraSubBlock &sb) const - { - sb.Data.SetCapacity(7); - sb.ID = NFileHeader::NExtraID::kWzAES; - Byte *p = (Byte *)sb.Data; - p[0] = (Byte)VendorVersion; - p[1] = (Byte)(VendorVersion >> 8); - p[2] = 'A'; - p[3] = 'E'; - p[4] = Strength; - p[5] = (Byte)Method; - p[6] = (Byte)(Method >> 8); - } -}; - -namespace NStrongCryptoFlags -{ - const UInt16 kDES = 0x6601; - const UInt16 kRC2old = 0x6602; - const UInt16 k3DES168 = 0x6603; - const UInt16 k3DES112 = 0x6609; - const UInt16 kAES128 = 0x660E; - const UInt16 kAES192 = 0x660F; - const UInt16 kAES256 = 0x6610; - const UInt16 kRC2 = 0x6702; - const UInt16 kBlowfish = 0x6720; - const UInt16 kTwofish = 0x6721; - const UInt16 kRC4 = 0x6801; -} - -struct CStrongCryptoField -{ - UInt16 Format; - UInt16 AlgId; - UInt16 BitLen; - UInt16 Flags; - - bool ParseFromSubBlock(const CExtraSubBlock &sb) - { - if (sb.ID != NFileHeader::NExtraID::kStrongEncrypt) - return false; - const Byte *p = (const Byte *)sb.Data; - if (sb.Data.GetCapacity() < 8) - return false; - Format = (((UInt16)p[1]) << 8) | p[0]; - AlgId = (((UInt16)p[3]) << 8) | p[2]; - BitLen = (((UInt16)p[5]) << 8) | p[4]; - Flags = (((UInt16)p[7]) << 8) | p[6]; - return (Format == 2); - } -}; - -struct CExtraBlock -{ - CObjectVector SubBlocks; - void Clear() { SubBlocks.Clear(); } - size_t GetSize() const - { - size_t res = 0; - for (int i = 0; i < SubBlocks.Size(); i++) - res += SubBlocks[i].Data.GetCapacity() + 2 + 2; - return res; - } - bool GetWzAesField(CWzAesExtraField &aesField) const - { - for (int i = 0; i < SubBlocks.Size(); i++) - if (aesField.ParseFromSubBlock(SubBlocks[i])) - return true; - return false; - } - - bool GetStrongCryptoField(CStrongCryptoField &f) const - { - for (int i = 0; i < SubBlocks.Size(); i++) - if (f.ParseFromSubBlock(SubBlocks[i])) - return true; - return false; - } - - bool HasWzAesField() const - { - CWzAesExtraField aesField; - return GetWzAesField(aesField); - } - - bool GetNtfsTime(int index, FILETIME &ft) const - { - for (int i = 0; i < SubBlocks.Size(); i++) - { - const CExtraSubBlock &sb = SubBlocks[i]; - if (sb.ID == NFileHeader::NExtraID::kNTFS) - return sb.ExtractNtfsTime(index, ft); - } - return false; - } - - /* - bool HasStrongCryptoField() const - { - CStrongCryptoField f; - return GetStrongCryptoField(f); - } - */ - - void RemoveUnknownSubBlocks() - { - for (int i = SubBlocks.Size() - 1; i >= 0; i--) - if (SubBlocks[i].ID != NFileHeader::NExtraID::kWzAES) - SubBlocks.Delete(i); - } -}; - - -class CLocalItem -{ -public: - CVersion ExtractVersion; - UInt16 Flags; - UInt16 CompressionMethod; - UInt32 Time; - UInt32 FileCRC; - UInt64 PackSize; - UInt64 UnPackSize; - - AString Name; - - CExtraBlock LocalExtra; - - bool IsUtf8() const { return (Flags & NFileHeader::NFlags::kUtf8) != 0; } - - bool IsEncrypted() const { return (Flags & NFileHeader::NFlags::kEncrypted) != 0; } - bool IsStrongEncrypted() const { return IsEncrypted() && (Flags & NFileHeader::NFlags::kStrongEncrypted) != 0; }; - - bool IsLzmaEOS() const { return (Flags & NFileHeader::NFlags::kLzmaEOS) != 0; } - - bool IsDir() const; - bool IgnoreItem() const { return false; } - UInt32 GetWinAttributes() const; - - bool HasDescriptor() const { return (Flags & NFileHeader::NFlags::kDescriptorUsedMask) != 0; } - - UString GetUnicodeString(const AString &s) const - { - UString res; - if (IsUtf8()) - if (!ConvertUTF8ToUnicode(s, res)) - res.Empty(); - if (res.IsEmpty()) - res = MultiByteToUnicodeString(s, GetCodePage()); - return res; - } - -private: - void SetFlagBits(int startBitNumber, int numBits, int value); - void SetBitMask(int bitMask, bool enable); -public: - void ClearFlags() { Flags = 0; } - void SetEncrypted(bool encrypted); - void SetUtf8(bool isUtf8); - - WORD GetCodePage() const { return CP_OEMCP; } -}; - -class CItem: public CLocalItem -{ -public: - CVersion MadeByVersion; - UInt16 InternalAttributes; - UInt32 ExternalAttributes; - - UInt64 LocalHeaderPosition; - - FILETIME NtfsMTime; - FILETIME NtfsATime; - FILETIME NtfsCTime; - - CExtraBlock CentralExtra; - CByteBuffer Comment; - - bool FromLocal; - bool FromCentral; - bool NtfsTimeIsDefined; - - bool IsDir() const; - UInt32 GetWinAttributes() const; - - bool IsThereCrc() const - { - if (CompressionMethod == NFileHeader::NCompressionMethod::kWzAES) - { - CWzAesExtraField aesField; - if (CentralExtra.GetWzAesField(aesField)) - return aesField.NeedCrc(); - } - return (FileCRC != 0 || !IsDir()); - } - - WORD GetCodePage() const - { - return (WORD)((MadeByVersion.HostOS == NFileHeader::NHostOS::kFAT - || MadeByVersion.HostOS == NFileHeader::NHostOS::kNTFS - ) ? CP_OEMCP : CP_ACP); - } - CItem() : FromLocal(false), FromCentral(false), NtfsTimeIsDefined(false) {} -}; - -}} - -#endif - - diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipItemEx.h b/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipItemEx.h deleted file mode 100644 index 0d74edd80..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipItemEx.h +++ /dev/null @@ -1,34 +0,0 @@ -// Archive/ZipItemEx.h - -#ifndef __ARCHIVE_ZIP_ITEMEX_H -#define __ARCHIVE_ZIP_ITEMEX_H - -#include "ZipHeader.h" -#include "ZipItem.h" - -namespace NArchive { -namespace NZip { - -class CItemEx: public CItem -{ -public: - UInt32 FileHeaderWithNameSize; - UInt16 LocalExtraSize; - - UInt64 GetLocalFullSize() const - { return FileHeaderWithNameSize + LocalExtraSize + PackSize + - (HasDescriptor() ? NFileHeader::kDataDescriptorSize : 0); }; - /* - UInt64 GetLocalFullSize(bool isZip64) const - { return FileHeaderWithNameSize + LocalExtraSize + PackSize + - (HasDescriptor() ? (isZip64 ? NFileHeader::kDataDescriptor64Size : NFileHeader::kDataDescriptorSize) : 0); }; - */ - UInt64 GetLocalExtraPosition() const - { return LocalHeaderPosition + FileHeaderWithNameSize; }; - UInt64 GetDataPosition() const - { return GetLocalExtraPosition() + LocalExtraSize; }; -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipRegister.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipRegister.cpp deleted file mode 100644 index 0e90e4ec3..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipRegister.cpp +++ /dev/null @@ -1,21 +0,0 @@ -// ZipRegister.cpp - -#include "StdAfx.h" - -#include "../../Common/RegisterArc.h" - -#include "ZipHandler.h" -static IInArchive *CreateArc() { return new NArchive::NZip::CHandler; } -#ifndef EXTRACT_ONLY -static IOutArchive *CreateArcOut() { return new NArchive::NZip::CHandler; } -#else -#define CreateArcOut 0 -#endif - -static CArcInfo g_ArcInfo = { L"Zip", L"zip jar xpi zsg", 0, 1, { 0x50, 0x4B, 0x03, 0x04 }, 4, false, CreateArc, CreateArcOut }; -static CArcInfo g_ArcInfo2 = { L"Zip", L"zip jar xpi zsg", 0, 1, { 0x50, 0x4B, 0x01, 0x02 }, 4, false, CreateArc, CreateArcOut }; -static CArcInfo g_ArcInfo3 = { L"Zip", L"zip jar xpi zsg", 0, 1, { 0x50, 0x4B, 0x05, 0x06 }, 4, false, CreateArc, CreateArcOut }; - -REGISTER_ARC(Zip) -REGISTER_ARCN(Zip,2) -REGISTER_ARCN(Zip,3) diff --git a/desmume/src/windows/7z/CPP/7zip/Common/CreateCoder.cpp b/desmume/src/windows/7z/CPP/7zip/Common/CreateCoder.cpp deleted file mode 100644 index 10c9f9600..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/CreateCoder.cpp +++ /dev/null @@ -1,292 +0,0 @@ -// CreateCoder.cpp - -#include "StdAfx.h" - -#include "CreateCoder.h" - -#include "../../Windows/PropVariant.h" -#include "../../Windows/Defs.h" -#include "FilterCoder.h" -#include "RegisterCodec.h" - -static const unsigned int kNumCodecsMax = 64; -unsigned int g_NumCodecs = 0; -const CCodecInfo *g_Codecs[kNumCodecsMax]; -void RegisterCodec(const CCodecInfo *codecInfo) -{ - if (g_NumCodecs < kNumCodecsMax) - g_Codecs[g_NumCodecs++] = codecInfo; -} - -#ifdef EXTERNAL_CODECS -static HRESULT ReadNumberOfStreams(ICompressCodecsInfo *codecsInfo, UInt32 index, PROPID propID, UInt32 &res) -{ - NWindows::NCOM::CPropVariant prop; - RINOK(codecsInfo->GetProperty(index, propID, &prop)); - if (prop.vt == VT_EMPTY) - res = 1; - else if (prop.vt == VT_UI4) - res = prop.ulVal; - else - return E_INVALIDARG; - return S_OK; -} - -static HRESULT ReadIsAssignedProp(ICompressCodecsInfo *codecsInfo, UInt32 index, PROPID propID, bool &res) -{ - NWindows::NCOM::CPropVariant prop; - RINOK(codecsInfo->GetProperty(index, propID, &prop)); - if (prop.vt == VT_EMPTY) - res = true; - else if (prop.vt == VT_BOOL) - res = VARIANT_BOOLToBool(prop.boolVal); - else - return E_INVALIDARG; - return S_OK; -} - -HRESULT LoadExternalCodecs(ICompressCodecsInfo *codecsInfo, CObjectVector &externalCodecs) -{ - UInt32 num; - RINOK(codecsInfo->GetNumberOfMethods(&num)); - for (UInt32 i = 0; i < num; i++) - { - CCodecInfoEx info; - NWindows::NCOM::CPropVariant prop; - RINOK(codecsInfo->GetProperty(i, NMethodPropID::kID, &prop)); - // if (prop.vt != VT_BSTR) - // info.Id.IDSize = (Byte)SysStringByteLen(prop.bstrVal); - // memmove(info.Id.ID, prop.bstrVal, info.Id.IDSize); - if (prop.vt != VT_UI8) - { - continue; // old Interface - // return E_INVALIDARG; - } - info.Id = prop.uhVal.QuadPart; - prop.Clear(); - - RINOK(codecsInfo->GetProperty(i, NMethodPropID::kName, &prop)); - if (prop.vt == VT_BSTR) - info.Name = prop.bstrVal; - else if (prop.vt != VT_EMPTY) - return E_INVALIDARG;; - - RINOK(ReadNumberOfStreams(codecsInfo, i, NMethodPropID::kInStreams, info.NumInStreams)); - RINOK(ReadNumberOfStreams(codecsInfo, i, NMethodPropID::kOutStreams, info.NumOutStreams)); - RINOK(ReadIsAssignedProp(codecsInfo, i, NMethodPropID::kEncoderIsAssigned, info.EncoderIsAssigned)); - RINOK(ReadIsAssignedProp(codecsInfo, i, NMethodPropID::kDecoderIsAssigned, info.DecoderIsAssigned)); - - externalCodecs.Add(info); - } - return S_OK; -} - -#endif - -bool FindMethod( - #ifdef EXTERNAL_CODECS - ICompressCodecsInfo * /* codecsInfo */, const CObjectVector *externalCodecs, - #endif - const UString &name, - CMethodId &methodId, UInt32 &numInStreams, UInt32 &numOutStreams) -{ - UInt32 i; - for (i = 0; i < g_NumCodecs; i++) - { - const CCodecInfo &codec = *g_Codecs[i]; - if (name.CompareNoCase(codec.Name) == 0) - { - methodId = codec.Id; - numInStreams = codec.NumInStreams; - numOutStreams = 1; - return true; - } - } - #ifdef EXTERNAL_CODECS - if (externalCodecs) - for (i = 0; i < (UInt32)externalCodecs->Size(); i++) - { - const CCodecInfoEx &codec = (*externalCodecs)[i]; - if (codec.Name.CompareNoCase(name) == 0) - { - methodId = codec.Id; - numInStreams = codec.NumInStreams; - numOutStreams = codec.NumOutStreams; - return true; - } - } - #endif - return false; -} - -bool FindMethod( - #ifdef EXTERNAL_CODECS - ICompressCodecsInfo * /* codecsInfo */, const CObjectVector *externalCodecs, - #endif - CMethodId methodId, UString &name) -{ - UInt32 i; - for (i = 0; i < g_NumCodecs; i++) - { - const CCodecInfo &codec = *g_Codecs[i]; - if (methodId == codec.Id) - { - name = codec.Name; - return true; - } - } - #ifdef EXTERNAL_CODECS - if (externalCodecs) - for (i = 0; i < (UInt32)externalCodecs->Size(); i++) - { - const CCodecInfoEx &codec = (*externalCodecs)[i]; - if (methodId == codec.Id) - { - name = codec.Name; - return true; - } - } - #endif - return false; -} - -HRESULT CreateCoder( - DECL_EXTERNAL_CODECS_LOC_VARS - CMethodId methodId, - CMyComPtr &filter, - CMyComPtr &coder, - CMyComPtr &coder2, - bool encode, bool onlyCoder) -{ - bool created = false; - UInt32 i; - for (i = 0; i < g_NumCodecs; i++) - { - const CCodecInfo &codec = *g_Codecs[i]; - if (codec.Id == methodId) - { - if (encode) - { - if (codec.CreateEncoder) - { - void *p = codec.CreateEncoder(); - if (codec.IsFilter) filter = (ICompressFilter *)p; - else if (codec.NumInStreams == 1) coder = (ICompressCoder *)p; - else coder2 = (ICompressCoder2 *)p; - created = (p != 0); - break; - } - } - else - if (codec.CreateDecoder) - { - void *p = codec.CreateDecoder(); - if (codec.IsFilter) filter = (ICompressFilter *)p; - else if (codec.NumInStreams == 1) coder = (ICompressCoder *)p; - else coder2 = (ICompressCoder2 *)p; - created = (p != 0); - break; - } - } - } - - #ifdef EXTERNAL_CODECS - if (!created && externalCodecs) - for (i = 0; i < (UInt32)externalCodecs->Size(); i++) - { - const CCodecInfoEx &codec = (*externalCodecs)[i]; - if (codec.Id == methodId) - { - if (encode) - { - if (codec.EncoderIsAssigned) - { - if (codec.IsSimpleCodec()) - { - HRESULT result = codecsInfo->CreateEncoder(i, &IID_ICompressCoder, (void **)&coder); - if (result != S_OK && result != E_NOINTERFACE && result != CLASS_E_CLASSNOTAVAILABLE) - return result; - if (!coder) - { - RINOK(codecsInfo->CreateEncoder(i, &IID_ICompressFilter, (void **)&filter)); - } - } - else - { - RINOK(codecsInfo->CreateEncoder(i, &IID_ICompressCoder2, (void **)&coder2)); - } - break; - } - } - else - if (codec.DecoderIsAssigned) - { - if (codec.IsSimpleCodec()) - { - HRESULT result = codecsInfo->CreateDecoder(i, &IID_ICompressCoder, (void **)&coder); - if (result != S_OK && result != E_NOINTERFACE && result != CLASS_E_CLASSNOTAVAILABLE) - return result; - if (!coder) - { - RINOK(codecsInfo->CreateDecoder(i, &IID_ICompressFilter, (void **)&filter)); - } - } - else - { - RINOK(codecsInfo->CreateDecoder(i, &IID_ICompressCoder2, (void **)&coder2)); - } - break; - } - } - } - #endif - - if (onlyCoder && filter) - { - CFilterCoder *coderSpec = new CFilterCoder; - coder = coderSpec; - coderSpec->Filter = filter; - } - return S_OK; -} - -HRESULT CreateCoder( - DECL_EXTERNAL_CODECS_LOC_VARS - CMethodId methodId, - CMyComPtr &coder, - CMyComPtr &coder2, - bool encode) -{ - CMyComPtr filter; - return CreateCoder( - EXTERNAL_CODECS_LOC_VARS - methodId, - filter, coder, coder2, encode, true); -} - -HRESULT CreateCoder( - DECL_EXTERNAL_CODECS_LOC_VARS - CMethodId methodId, - CMyComPtr &coder, bool encode) -{ - CMyComPtr filter; - CMyComPtr coder2; - return CreateCoder( - EXTERNAL_CODECS_LOC_VARS - methodId, - coder, coder2, encode); -} - -HRESULT CreateFilter( - DECL_EXTERNAL_CODECS_LOC_VARS - CMethodId methodId, - CMyComPtr &filter, - bool encode) -{ - CMyComPtr coder; - CMyComPtr coder2; - return CreateCoder( - EXTERNAL_CODECS_LOC_VARS - methodId, - filter, coder, coder2, encode, false); -} diff --git a/desmume/src/windows/7z/CPP/7zip/Common/CreateCoder.h b/desmume/src/windows/7z/CPP/7zip/Common/CreateCoder.h deleted file mode 100644 index 2f83f5ec5..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/CreateCoder.h +++ /dev/null @@ -1,98 +0,0 @@ -// CreateCoder.h - -#ifndef __CREATECODER_H -#define __CREATECODER_H - -#include "../../Common/MyCom.h" -#include "../../Common/MyString.h" -#include "../ICoder.h" - -#include "MethodId.h" - -#ifdef EXTERNAL_CODECS - -struct CCodecInfoEx -{ - UString Name; - CMethodId Id; - UInt32 NumInStreams; - UInt32 NumOutStreams; - bool EncoderIsAssigned; - bool DecoderIsAssigned; - bool IsSimpleCodec() const { return NumOutStreams == 1 && NumInStreams == 1; } - CCodecInfoEx(): EncoderIsAssigned(false), DecoderIsAssigned(false) {} -}; - -HRESULT LoadExternalCodecs(ICompressCodecsInfo *codecsInfo, CObjectVector &externalCodecs); - -#define PUBLIC_ISetCompressCodecsInfo public ISetCompressCodecsInfo, -#define QUERY_ENTRY_ISetCompressCodecsInfo MY_QUERYINTERFACE_ENTRY(ISetCompressCodecsInfo) -#define DECL_ISetCompressCodecsInfo STDMETHOD(SetCompressCodecsInfo)(ICompressCodecsInfo *compressCodecsInfo); -#define IMPL_ISetCompressCodecsInfo2(x) \ -STDMETHODIMP x::SetCompressCodecsInfo(ICompressCodecsInfo *compressCodecsInfo) { \ - COM_TRY_BEGIN _codecsInfo = compressCodecsInfo; return LoadExternalCodecs(_codecsInfo, _externalCodecs); COM_TRY_END } -#define IMPL_ISetCompressCodecsInfo IMPL_ISetCompressCodecsInfo2(CHandler) - -#define EXTERNAL_CODECS_VARS2 _codecsInfo, &_externalCodecs - -#define DECL_EXTERNAL_CODECS_VARS CMyComPtr _codecsInfo; CObjectVector _externalCodecs; -#define EXTERNAL_CODECS_VARS EXTERNAL_CODECS_VARS2, - -#define DECL_EXTERNAL_CODECS_LOC_VARS2 ICompressCodecsInfo *codecsInfo, const CObjectVector *externalCodecs -#define EXTERNAL_CODECS_LOC_VARS2 codecsInfo, externalCodecs - -#define DECL_EXTERNAL_CODECS_LOC_VARS DECL_EXTERNAL_CODECS_LOC_VARS2, -#define EXTERNAL_CODECS_LOC_VARS EXTERNAL_CODECS_LOC_VARS2, - -#else - -#define PUBLIC_ISetCompressCodecsInfo -#define QUERY_ENTRY_ISetCompressCodecsInfo -#define DECL_ISetCompressCodecsInfo -#define IMPL_ISetCompressCodecsInfo -#define EXTERNAL_CODECS_VARS2 -#define DECL_EXTERNAL_CODECS_VARS -#define EXTERNAL_CODECS_VARS EXTERNAL_CODECS_VARS2 -#define DECL_EXTERNAL_CODECS_LOC_VARS2 -#define EXTERNAL_CODECS_LOC_VARS2 -#define DECL_EXTERNAL_CODECS_LOC_VARS -#define EXTERNAL_CODECS_LOC_VARS - -#endif - -bool FindMethod( - DECL_EXTERNAL_CODECS_LOC_VARS - const UString &name, CMethodId &methodId, UInt32 &numInStreams, UInt32 &numOutStreams); - -bool FindMethod( - DECL_EXTERNAL_CODECS_LOC_VARS - CMethodId methodId, UString &name); - - -HRESULT CreateCoder( - DECL_EXTERNAL_CODECS_LOC_VARS - CMethodId methodId, - CMyComPtr &filter, - CMyComPtr &coder, - CMyComPtr &coder2, - bool encode, bool onlyCoder); - -HRESULT CreateCoder( - DECL_EXTERNAL_CODECS_LOC_VARS - CMethodId methodId, - CMyComPtr &coder, - CMyComPtr &coder2, - bool encode); - -HRESULT CreateCoder( - DECL_EXTERNAL_CODECS_LOC_VARS - CMethodId methodId, - CMyComPtr &coder, bool encode); - -HRESULT CreateFilter( - DECL_EXTERNAL_CODECS_LOC_VARS - CMethodId methodId, - CMyComPtr &filter, - bool encode); - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Common/DeclareArcs.h b/desmume/src/windows/7z/CPP/7zip/Common/DeclareArcs.h deleted file mode 100644 index 22443a779..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/DeclareArcs.h +++ /dev/null @@ -1,28 +0,0 @@ -// DeclareArcs.h - -#ifndef __DECLAREARCS_H -#define __DECLAREARCS_H - -#define DECLARE_ARC(x) struct CRegister##x { CRegister##x(); }; \ - FORCE_REF(CRegister##x, g_RegisterArc##x) - -#define DECLARE_ARCN(x,n) struct CRegister##x##n { CRegister##x##n(); }; \ - FORCE_REF(CRegister##x##n, g_RegisterArc##n##x) - -#ifndef FORCE_REF - #define FORCE_REF(...) -#endif - -DECLARE_ARC(7z) -DECLARE_ARC(BZip2) -DECLARE_ARC(GZip) -DECLARE_ARC(Lzh) -DECLARE_ARC(Lzma) -DECLARE_ARC(Rar) -DECLARE_ARC(Split) -DECLARE_ARC(Tar) -DECLARE_ARC(Zip) -DECLARE_ARCN(Zip,2) -DECLARE_ARCN(Zip,3) - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Common/DeclareCodecs.h b/desmume/src/windows/7z/CPP/7zip/Common/DeclareCodecs.h deleted file mode 100644 index 6b933cac6..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/DeclareCodecs.h +++ /dev/null @@ -1,31 +0,0 @@ -// DeclareCodecs.h - -#ifndef __DECLARECODECS_H -#define __DECLARECODECS_H - -#define DECLARE_CODEC(x) struct CRegisterCodec##x { CRegisterCodec##x(); }; \ - FORCE_REF(CRegisterCodec##x, g_RegisterCodec##x) - -#define DECLARE_CODECS(x) struct CRegisterCodecs##x { CRegisterCodecs##x(); }; \ - FORCE_REF(CRegisterCodecs##x, g_RegisterCodecs##x) - -#ifndef FORCE_REF - #define FORCE_REF(...) -#endif - -DECLARE_CODEC(7zAES) -DECLARE_CODEC(BCJ2) -DECLARE_CODEC(BCJ) -DECLARE_CODEC(BZip2) -DECLARE_CODEC(Copy) -DECLARE_CODEC(Deflate64) -DECLARE_CODEC(DeflateNsis) -DECLARE_CODEC(Deflate) -DECLARE_CODEC(LZMA) -DECLARE_CODEC(PPMD) - -DECLARE_CODECS(Branch) -DECLARE_CODECS(ByteSwap) -DECLARE_CODECS(Rar) - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Common/FilterCoder.cpp b/desmume/src/windows/7z/CPP/7zip/Common/FilterCoder.cpp deleted file mode 100644 index 1985d383a..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/FilterCoder.cpp +++ /dev/null @@ -1,262 +0,0 @@ -// FilterCoder.cpp - -#include "StdAfx.h" - -#include "FilterCoder.h" -extern "C" -{ -#include "../../../C/Alloc.h" -} -#include "../../Common/Defs.h" -#include "StreamUtils.h" - -static const UInt32 kBufferSize = 1 << 17; - -CFilterCoder::CFilterCoder() -{ - _buffer = (Byte *)::MidAlloc(kBufferSize); -} - -CFilterCoder::~CFilterCoder() -{ - ::MidFree(_buffer); -} - -HRESULT CFilterCoder::WriteWithLimit(ISequentialOutStream *outStream, UInt32 size) -{ - if (_outSizeIsDefined) - { - UInt64 remSize = _outSize - _nowPos64; - if (size > remSize) - size = (UInt32)remSize; - } - RINOK(WriteStream(outStream, _buffer, size)); - _nowPos64 += size; - return S_OK; -} - - -STDMETHODIMP CFilterCoder::Code(ISequentialInStream *inStream, - ISequentialOutStream *outStream, const UInt64 * /* inSize */, const UInt64 *outSize, - ICompressProgressInfo *progress) -{ - RINOK(Init()); - UInt32 bufferPos = 0; - _outSizeIsDefined = (outSize != 0); - if (_outSizeIsDefined) - _outSize = *outSize; - - while(NeedMore()) - { - size_t processedSize = kBufferSize - bufferPos; - - // Change it: It can be optimized using ReadPart - RINOK(ReadStream(inStream, _buffer + bufferPos, &processedSize)); - - UInt32 endPos = bufferPos + (UInt32)processedSize; - - bufferPos = Filter->Filter(_buffer, endPos); - if (bufferPos > endPos) - { - for (; endPos< bufferPos; endPos++) - _buffer[endPos] = 0; - bufferPos = Filter->Filter(_buffer, endPos); - } - - if (bufferPos == 0) - { - if (endPos > 0) - return WriteWithLimit(outStream, endPos); - return S_OK; - } - RINOK(WriteWithLimit(outStream, bufferPos)); - if (progress != NULL) - { - RINOK(progress->SetRatioInfo(&_nowPos64, &_nowPos64)); - } - UInt32 i = 0; - while(bufferPos < endPos) - _buffer[i++] = _buffer[bufferPos++]; - bufferPos = i; - } - return S_OK; -} - -// #ifdef _ST_MODE -STDMETHODIMP CFilterCoder::SetOutStream(ISequentialOutStream *outStream) -{ - _bufferPos = 0; - _outStream = outStream; - return Init(); -} - -STDMETHODIMP CFilterCoder::ReleaseOutStream() -{ - _outStream.Release(); - return S_OK; -}; - - -STDMETHODIMP CFilterCoder::Write(const void *data, UInt32 size, UInt32 *processedSize) -{ - UInt32 processedSizeTotal = 0; - while(size > 0) - { - UInt32 sizeMax = kBufferSize - _bufferPos; - UInt32 sizeTemp = size; - if (sizeTemp > sizeMax) - sizeTemp = sizeMax; - memmove(_buffer + _bufferPos, data, sizeTemp); - size -= sizeTemp; - processedSizeTotal += sizeTemp; - data = (const Byte *)data + sizeTemp; - UInt32 endPos = _bufferPos + sizeTemp; - _bufferPos = Filter->Filter(_buffer, endPos); - if (_bufferPos == 0) - { - _bufferPos = endPos; - break; - } - if (_bufferPos > endPos) - { - if (size != 0) - return E_FAIL; - break; - } - RINOK(WriteWithLimit(_outStream, _bufferPos)); - UInt32 i = 0; - while(_bufferPos < endPos) - _buffer[i++] = _buffer[_bufferPos++]; - _bufferPos = i; - } - if (processedSize != NULL) - *processedSize = processedSizeTotal; - return S_OK; -} - -STDMETHODIMP CFilterCoder::Flush() -{ - if (_bufferPos != 0) - { - UInt32 endPos = Filter->Filter(_buffer, _bufferPos); - if (endPos > _bufferPos) - { - for (; _bufferPos < endPos; _bufferPos++) - _buffer[_bufferPos] = 0; - if (Filter->Filter(_buffer, endPos) != endPos) - return E_FAIL; - } - RINOK(WriteStream(_outStream, _buffer, _bufferPos)); - _bufferPos = 0; - } - CMyComPtr flush; - _outStream.QueryInterface(IID_IOutStreamFlush, &flush); - if (flush) - return flush->Flush(); - return S_OK; -} - - -STDMETHODIMP CFilterCoder::SetInStream(ISequentialInStream *inStream) -{ - _convertedPosBegin = _convertedPosEnd = _bufferPos = 0; - _inStream = inStream; - return Init(); -} - -STDMETHODIMP CFilterCoder::ReleaseInStream() -{ - _inStream.Release(); - return S_OK; -}; - -STDMETHODIMP CFilterCoder::Read(void *data, UInt32 size, UInt32 *processedSize) -{ - UInt32 processedSizeTotal = 0; - while(size > 0) - { - if (_convertedPosBegin != _convertedPosEnd) - { - UInt32 sizeTemp = MyMin(size, _convertedPosEnd - _convertedPosBegin); - memmove(data, _buffer + _convertedPosBegin, sizeTemp); - _convertedPosBegin += sizeTemp; - data = (void *)((Byte *)data + sizeTemp); - size -= sizeTemp; - processedSizeTotal += sizeTemp; - break; - } - int i; - for (i = 0; _convertedPosEnd + i < _bufferPos; i++) - _buffer[i] = _buffer[i + _convertedPosEnd]; - _bufferPos = i; - _convertedPosBegin = _convertedPosEnd = 0; - size_t processedSizeTemp = kBufferSize - _bufferPos; - RINOK(ReadStream(_inStream, _buffer + _bufferPos, &processedSizeTemp)); - _bufferPos = _bufferPos + (UInt32)processedSizeTemp; - _convertedPosEnd = Filter->Filter(_buffer, _bufferPos); - if (_convertedPosEnd == 0) - { - if (_bufferPos == 0) - break; - else - { - _convertedPosEnd = _bufferPos; // check it - continue; - } - } - if (_convertedPosEnd > _bufferPos) - { - for (; _bufferPos < _convertedPosEnd; _bufferPos++) - _buffer[_bufferPos] = 0; - _convertedPosEnd = Filter->Filter(_buffer, _bufferPos); - } - } - if (processedSize != NULL) - *processedSize = processedSizeTotal; - return S_OK; -} - -// #endif // _ST_MODE - -#ifndef _NO_CRYPTO -STDMETHODIMP CFilterCoder::CryptoSetPassword(const Byte *data, UInt32 size) -{ - return _setPassword->CryptoSetPassword(data, size); -} -#endif - -#ifndef EXTRACT_ONLY -STDMETHODIMP CFilterCoder::SetCoderProperties(const PROPID *propIDs, - const PROPVARIANT *properties, UInt32 numProperties) -{ - return _SetCoderProperties->SetCoderProperties(propIDs, properties, numProperties); -} - -STDMETHODIMP CFilterCoder::WriteCoderProperties(ISequentialOutStream *outStream) -{ - return _writeCoderProperties->WriteCoderProperties(outStream); -} - -/* -STDMETHODIMP CFilterCoder::ResetSalt() -{ - return _CryptoResetSalt->ResetSalt(); -} -*/ - -STDMETHODIMP CFilterCoder::ResetInitVector() -{ - return _CryptoResetInitVector->ResetInitVector(); -} -#endif - -STDMETHODIMP CFilterCoder::SetDecoderProperties2(const Byte *data, UInt32 size) -{ - return _setDecoderProperties->SetDecoderProperties2(data, size); -} - - - -void foo() -{ -} diff --git a/desmume/src/windows/7z/CPP/7zip/Common/FilterCoder.h b/desmume/src/windows/7z/CPP/7zip/Common/FilterCoder.h deleted file mode 100644 index 496eb5e04..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/FilterCoder.h +++ /dev/null @@ -1,143 +0,0 @@ -// FilterCoder.h - -#ifndef __FILTERCODER_H -#define __FILTERCODER_H - -#include "../../Common/MyCom.h" -#include "../ICoder.h" -#include "../IPassword.h" - -#define MY_QUERYINTERFACE_ENTRY_AG(i, sub0, sub) if (iid == IID_ ## i) \ -{ if (!sub) RINOK(sub0->QueryInterface(IID_ ## i, (void **)&sub)) \ -*outObject = (void *)(i *)this; AddRef(); return S_OK; } - -class CFilterCoder: - public ICompressCoder, - // #ifdef _ST_MODE - public ICompressSetInStream, - public ISequentialInStream, - public ICompressSetOutStream, - public ISequentialOutStream, - public IOutStreamFlush, - // #endif - - #ifndef _NO_CRYPTO - public ICryptoSetPassword, - #endif - #ifndef EXTRACT_ONLY - public ICompressSetCoderProperties, - public ICompressWriteCoderProperties, - // public ICryptoResetSalt, - public ICryptoResetInitVector, - #endif - public ICompressSetDecoderProperties2, - public CMyUnknownImp -{ -protected: - Byte *_buffer; - // #ifdef _ST_MODE - CMyComPtr _inStream; - CMyComPtr _outStream; - UInt32 _bufferPos; - UInt32 _convertedPosBegin; - UInt32 _convertedPosEnd; - // #endif - bool _outSizeIsDefined; - UInt64 _outSize; - UInt64 _nowPos64; - - HRESULT Init() - { - _nowPos64 = 0; - _outSizeIsDefined = false; - return Filter->Init(); - } - - CMyComPtr _setPassword; - #ifndef EXTRACT_ONLY - CMyComPtr _SetCoderProperties; - CMyComPtr _writeCoderProperties; - // CMyComPtr _CryptoResetSalt; - CMyComPtr _CryptoResetInitVector; - #endif - CMyComPtr _setDecoderProperties; -public: - CMyComPtr Filter; - - CFilterCoder(); - ~CFilterCoder(); - HRESULT WriteWithLimit(ISequentialOutStream *outStream, UInt32 size); - bool NeedMore() const - { return (!_outSizeIsDefined || (_nowPos64 < _outSize)); } - -public: - MY_QUERYINTERFACE_BEGIN - MY_QUERYINTERFACE_ENTRY(ICompressCoder) - // #ifdef _ST_MODE - MY_QUERYINTERFACE_ENTRY(ICompressSetInStream) - MY_QUERYINTERFACE_ENTRY(ISequentialInStream) - - MY_QUERYINTERFACE_ENTRY(ICompressSetOutStream) - MY_QUERYINTERFACE_ENTRY(ISequentialOutStream) - MY_QUERYINTERFACE_ENTRY(IOutStreamFlush) - // #endif - - #ifndef _NO_CRYPTO - MY_QUERYINTERFACE_ENTRY_AG(ICryptoSetPassword, Filter, _setPassword) - #endif - - #ifndef EXTRACT_ONLY - MY_QUERYINTERFACE_ENTRY_AG(ICompressSetCoderProperties, Filter, _SetCoderProperties) - MY_QUERYINTERFACE_ENTRY_AG(ICompressWriteCoderProperties, Filter, _writeCoderProperties) - // MY_QUERYINTERFACE_ENTRY_AG(ICryptoResetSalt, Filter, _CryptoResetSalt) - MY_QUERYINTERFACE_ENTRY_AG(ICryptoResetInitVector, Filter, _CryptoResetInitVector) - #endif - - MY_QUERYINTERFACE_ENTRY_AG(ICompressSetDecoderProperties2, Filter, _setDecoderProperties) - MY_QUERYINTERFACE_END - MY_ADDREF_RELEASE - STDMETHOD(Code)(ISequentialInStream *inStream, - ISequentialOutStream *outStream, const UInt64 *inSize, const UInt64 *outSize, - ICompressProgressInfo *progress); - // #ifdef _ST_MODE - STDMETHOD(ReleaseInStream)(); - STDMETHOD(SetInStream)(ISequentialInStream *inStream); - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); \ - STDMETHOD(SetOutStream)(ISequentialOutStream *outStream); - STDMETHOD(ReleaseOutStream)(); - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); - STDMETHOD(Flush)(); - // #endif - - #ifndef _NO_CRYPTO - STDMETHOD(CryptoSetPassword)(const Byte *data, UInt32 size); - #endif - #ifndef EXTRACT_ONLY - STDMETHOD(SetCoderProperties)(const PROPID *propIDs, - const PROPVARIANT *properties, UInt32 numProperties); - STDMETHOD(WriteCoderProperties)(ISequentialOutStream *outStream); - // STDMETHOD(ResetSalt)(); - STDMETHOD(ResetInitVector)(); - #endif - STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size); -}; - -// #ifdef _ST_MODE -class CInStreamReleaser -{ -public: - CFilterCoder *FilterCoder; - CInStreamReleaser(): FilterCoder(0) {} - ~CInStreamReleaser() { if (FilterCoder) FilterCoder->ReleaseInStream(); } -}; - -class COutStreamReleaser -{ -public: - CFilterCoder *FilterCoder; - COutStreamReleaser(): FilterCoder(0) {} - ~COutStreamReleaser() { if (FilterCoder) FilterCoder->ReleaseOutStream(); } -}; -// #endif - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Common/InBuffer.cpp b/desmume/src/windows/7z/CPP/7zip/Common/InBuffer.cpp deleted file mode 100644 index 7e061156a..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/InBuffer.cpp +++ /dev/null @@ -1,83 +0,0 @@ -// InBuffer.cpp - -#include "StdAfx.h" - -#include "InBuffer.h" - -extern "C" -{ - #include "../../../C/Alloc.h" -} - -CInBuffer::CInBuffer(): - _buffer(0), - _bufferLimit(0), - _bufferBase(0), - _stream(0), - _bufferSize(0) -{} - -bool CInBuffer::Create(UInt32 bufferSize) -{ - const UInt32 kMinBlockSize = 1; - if (bufferSize < kMinBlockSize) - bufferSize = kMinBlockSize; - if (_bufferBase != 0 && _bufferSize == bufferSize) - return true; - Free(); - _bufferSize = bufferSize; - _bufferBase = (Byte *)::MidAlloc(bufferSize); - return (_bufferBase != 0); -} - -void CInBuffer::Free() -{ - ::MidFree(_bufferBase); - _bufferBase = 0; -} - -void CInBuffer::SetStream(ISequentialInStream *stream) -{ - _stream = stream; -} - -void CInBuffer::Init() -{ - _processedSize = 0; - _buffer = _bufferBase; - _bufferLimit = _buffer; - _wasFinished = false; - #ifdef _NO_EXCEPTIONS - ErrorCode = S_OK; - #endif -} - -bool CInBuffer::ReadBlock() -{ - #ifdef _NO_EXCEPTIONS - if (ErrorCode != S_OK) - return false; - #endif - if (_wasFinished) - return false; - _processedSize += (_buffer - _bufferBase); - UInt32 numProcessedBytes; - HRESULT result = _stream->Read(_bufferBase, _bufferSize, &numProcessedBytes); - #ifdef _NO_EXCEPTIONS - ErrorCode = result; - #else - if (result != S_OK) - throw CInBufferException(result); - #endif - _buffer = _bufferBase; - _bufferLimit = _buffer + numProcessedBytes; - _wasFinished = (numProcessedBytes == 0); - return (!_wasFinished); -} - -Byte CInBuffer::ReadBlock2() -{ - if(!ReadBlock()) - return 0xFF; - return *_buffer++; -} diff --git a/desmume/src/windows/7z/CPP/7zip/Common/InBuffer.h b/desmume/src/windows/7z/CPP/7zip/Common/InBuffer.h deleted file mode 100644 index cdd50f1b2..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/InBuffer.h +++ /dev/null @@ -1,81 +0,0 @@ -// InBuffer.h - -#ifndef __INBUFFER_H -#define __INBUFFER_H - -#include "../IStream.h" -#include "../../Common/MyCom.h" -#include "../../Common/MyException.h" - -#ifndef _NO_EXCEPTIONS -struct CInBufferException: public CSystemException -{ - CInBufferException(HRESULT errorCode): CSystemException(errorCode) {} -}; -#endif - -class CInBuffer -{ - Byte *_buffer; - Byte *_bufferLimit; - Byte *_bufferBase; - CMyComPtr _stream; - UInt64 _processedSize; - UInt32 _bufferSize; - bool _wasFinished; - - bool ReadBlock(); - Byte ReadBlock2(); - -public: - #ifdef _NO_EXCEPTIONS - HRESULT ErrorCode; - #endif - - CInBuffer(); - ~CInBuffer() { Free(); } - - bool Create(UInt32 bufferSize); - void Free(); - - void SetStream(ISequentialInStream *stream); - void Init(); - void ReleaseStream() { _stream.Release(); } - - bool ReadByte(Byte &b) - { - if (_buffer >= _bufferLimit) - if (!ReadBlock()) - return false; - b = *_buffer++; - return true; - } - Byte ReadByte() - { - if (_buffer >= _bufferLimit) - return ReadBlock2(); - return *_buffer++; - } - UInt32 ReadBytes(Byte *buf, UInt32 size) - { - if ((UInt32)(_bufferLimit - _buffer) >= size) - { - for (UInt32 i = 0; i < size; i++) - buf[i] = _buffer[i]; - _buffer += size; - return size; - } - for (UInt32 i = 0; i < size; i++) - { - if (_buffer >= _bufferLimit) - if (!ReadBlock()) - return i; - buf[i] = *_buffer++; - } - return size; - } - UInt64 GetProcessedSize() const { return _processedSize + (_buffer - _bufferBase); } - bool WasFinished() const { return _wasFinished; } -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Common/InOutTempBuffer.cpp b/desmume/src/windows/7z/CPP/7zip/Common/InOutTempBuffer.cpp deleted file mode 100644 index 79c04c109..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/InOutTempBuffer.cpp +++ /dev/null @@ -1,122 +0,0 @@ -// InOutTempBuffer.cpp - -#include "StdAfx.h" - -#include "InOutTempBuffer.h" -#include "../../Common/Defs.h" -// #include "Windows/Defs.h" - -#include "StreamUtils.h" - -using namespace NWindows; -using namespace NFile; -using namespace NDirectory; - -static UInt32 kTmpBufferMemorySize = (1 << 20); - -static LPCTSTR kTempFilePrefixString = TEXT("iot"); - -CInOutTempBuffer::CInOutTempBuffer(): - _buffer(NULL) -{ -} - -void CInOutTempBuffer::Create() -{ - _buffer = new Byte[kTmpBufferMemorySize]; -} - -CInOutTempBuffer::~CInOutTempBuffer() -{ - delete []_buffer; -} -void CInOutTempBuffer::InitWriting() -{ - _bufferPosition = 0; - _tmpFileCreated = false; - _fileSize = 0; -} - -bool CInOutTempBuffer::WriteToFile(const void *data, UInt32 size) -{ - if (size == 0) - return true; - if(!_tmpFileCreated) - { - CSysString tempDirPath; - if(!MyGetTempPath(tempDirPath)) - return false; - if (_tempFile.Create(tempDirPath, kTempFilePrefixString, _tmpFileName) == 0) - return false; - // _outFile.SetOpenCreationDispositionCreateAlways(); - if(!_outFile.Create(_tmpFileName, true)) - return false; - _tmpFileCreated = true; - } - UInt32 processedSize; - if(!_outFile.Write(data, size, processedSize)) - return false; - _fileSize += processedSize; - return (processedSize == size); -} - -bool CInOutTempBuffer::FlushWrite() -{ - return _outFile.Close(); -} - -bool CInOutTempBuffer::Write(const void *data, UInt32 size) -{ - if(_bufferPosition < kTmpBufferMemorySize) - { - UInt32 curSize = MyMin(kTmpBufferMemorySize - _bufferPosition, size); - memmove(_buffer + _bufferPosition, (const Byte *)data, curSize); - _bufferPosition += curSize; - size -= curSize; - data = ((const Byte *)data) + curSize; - _fileSize += curSize; - } - return WriteToFile(data, size); -} - -bool CInOutTempBuffer::InitReading() -{ - _currentPositionInBuffer = 0; - if(_tmpFileCreated) - return _inFile.Open(_tmpFileName); - return true; -} - -HRESULT CInOutTempBuffer::WriteToStream(ISequentialOutStream *stream) -{ - if (_currentPositionInBuffer < _bufferPosition) - { - UInt32 sizeToWrite = _bufferPosition - _currentPositionInBuffer; - RINOK(WriteStream(stream, _buffer + _currentPositionInBuffer, sizeToWrite)); - _currentPositionInBuffer += sizeToWrite; - } - if (!_tmpFileCreated) - return true; - for (;;) - { - UInt32 localProcessedSize; - if (!_inFile.ReadPart(_buffer, kTmpBufferMemorySize, localProcessedSize)) - return E_FAIL; - if (localProcessedSize == 0) - return S_OK; - RINOK(WriteStream(stream, _buffer, localProcessedSize)); - } -} - -STDMETHODIMP CSequentialOutTempBufferImp::Write(const void *data, UInt32 size, UInt32 *processedSize) -{ - if (!_buffer->Write(data, size)) - { - if (processedSize != NULL) - *processedSize = 0; - return E_FAIL; - } - if (processedSize != NULL) - *processedSize = size; - return S_OK; -} diff --git a/desmume/src/windows/7z/CPP/7zip/Common/InOutTempBuffer.h b/desmume/src/windows/7z/CPP/7zip/Common/InOutTempBuffer.h deleted file mode 100644 index 1ccf1153f..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/InOutTempBuffer.h +++ /dev/null @@ -1,55 +0,0 @@ -// Util/InOutTempBuffer.h - -#ifndef __IN_OUT_TEMP_BUFFER_H -#define __IN_OUT_TEMP_BUFFER_H - -#include "../../Windows/FileIO.h" -#include "../../Windows/FileDir.h" -#include "../../Common/MyCom.h" - -#include "../IStream.h" - -class CInOutTempBuffer -{ - NWindows::NFile::NDirectory::CTempFile _tempFile; - NWindows::NFile::NIO::COutFile _outFile; - NWindows::NFile::NIO::CInFile _inFile; - Byte *_buffer; - UInt32 _bufferPosition; - UInt32 _currentPositionInBuffer; - CSysString _tmpFileName; - bool _tmpFileCreated; - - UInt64 _fileSize; - - bool WriteToFile(const void *data, UInt32 size); -public: - CInOutTempBuffer(); - ~CInOutTempBuffer(); - void Create(); - - void InitWriting(); - bool Write(const void *data, UInt32 size); - UInt64 GetDataSize() const { return _fileSize; } - bool FlushWrite(); - bool InitReading(); - HRESULT WriteToStream(ISequentialOutStream *stream); -}; - -class CSequentialOutTempBufferImp: - public ISequentialOutStream, - public CMyUnknownImp -{ - CInOutTempBuffer *_buffer; -public: - // CSequentialOutStreamImp(): _size(0) {} - // UInt32 _size; - void Init(CInOutTempBuffer *buffer) { _buffer = buffer; } - // UInt32 GetSize() const { return _size; } - - MY_UNKNOWN_IMP - - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Common/LimitedStreams.cpp b/desmume/src/windows/7z/CPP/7zip/Common/LimitedStreams.cpp deleted file mode 100644 index 0a1bfa38e..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/LimitedStreams.cpp +++ /dev/null @@ -1,45 +0,0 @@ -// LimitedStreams.cpp - -#include "StdAfx.h" - -#include "LimitedStreams.h" -#include "../../Common/Defs.h" - -STDMETHODIMP CLimitedSequentialInStream::Read(void *data, UInt32 size, UInt32 *processedSize) -{ - UInt32 realProcessedSize = 0; - UInt32 sizeToRead = (UInt32)MyMin((_size - _pos), (UInt64)size); - HRESULT result = S_OK; - if (sizeToRead > 0) - { - result = _stream->Read(data, sizeToRead, &realProcessedSize); - _pos += realProcessedSize; - if (realProcessedSize == 0) - _wasFinished = true; - } - if(processedSize != NULL) - *processedSize = realProcessedSize; - return result; -} - -STDMETHODIMP CLimitedSequentialOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize) -{ - HRESULT result = S_OK; - if (processedSize != NULL) - *processedSize = 0; - if (size > _size) - { - size = (UInt32)_size; - if (size == 0) - { - _overflow = true; - return E_FAIL; - } - } - if (_stream) - result = _stream->Write(data, size, &size); - _size -= size; - if (processedSize != NULL) - *processedSize = size; - return result; -} diff --git a/desmume/src/windows/7z/CPP/7zip/Common/LimitedStreams.h b/desmume/src/windows/7z/CPP/7zip/Common/LimitedStreams.h deleted file mode 100644 index 7e0e1c126..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/LimitedStreams.h +++ /dev/null @@ -1,54 +0,0 @@ -// LimitedStreams.h - -#ifndef __LIMITEDSTREAMS_H -#define __LIMITEDSTREAMS_H - -#include "../../Common/MyCom.h" -#include "../IStream.h" - -class CLimitedSequentialInStream: - public ISequentialInStream, - public CMyUnknownImp -{ - CMyComPtr _stream; - UInt64 _size; - UInt64 _pos; - bool _wasFinished; -public: - void SetStream(ISequentialInStream *stream) { _stream = stream; } - void Init(UInt64 streamSize) - { - _size = streamSize; - _pos = 0; - _wasFinished = false; - } - - MY_UNKNOWN_IMP - - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); - UInt64 GetSize() const { return _pos; } - bool WasFinished() const { return _wasFinished; } -}; - -class CLimitedSequentialOutStream: - public ISequentialOutStream, - public CMyUnknownImp -{ - CMyComPtr _stream; - UInt64 _size; - bool _overflow; -public: - MY_UNKNOWN_IMP - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); - void SetStream(ISequentialOutStream *stream) { _stream = stream; } - void ReleaseStream() { _stream.Release(); } - void Init(UInt64 size) - { - _size = size; - _overflow = false; - } - bool IsFinishedOK() const { return (_size == 0 && !_overflow); } - UInt64 GetRem() const { return _size; } -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Common/LockedStream.cpp b/desmume/src/windows/7z/CPP/7zip/Common/LockedStream.cpp deleted file mode 100644 index d1bbf6dba..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/LockedStream.cpp +++ /dev/null @@ -1,23 +0,0 @@ -// LockedStream.cpp - -#include "StdAfx.h" - -#include "LockedStream.h" - -HRESULT CLockedInStream::Read(UInt64 startPos, void *data, UInt32 size, - UInt32 *processedSize) -{ - NWindows::NSynchronization::CCriticalSectionLock lock(_criticalSection); - RINOK(_stream->Seek(startPos, STREAM_SEEK_SET, NULL)); - return _stream->Read(data, size, processedSize); -} - -STDMETHODIMP CLockedSequentialInStreamImp::Read(void *data, UInt32 size, UInt32 *processedSize) -{ - UInt32 realProcessedSize = 0; - HRESULT result = _lockedInStream->Read(_pos, data, size, &realProcessedSize); - _pos += realProcessedSize; - if (processedSize != NULL) - *processedSize = realProcessedSize; - return result; -} diff --git a/desmume/src/windows/7z/CPP/7zip/Common/LockedStream.h b/desmume/src/windows/7z/CPP/7zip/Common/LockedStream.h deleted file mode 100644 index e12e22a4a..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/LockedStream.h +++ /dev/null @@ -1,38 +0,0 @@ -// LockedStream.h - -#ifndef __LOCKEDSTREAM_H -#define __LOCKEDSTREAM_H - -#include "../../Windows/Synchronization.h" -#include "../../Common/MyCom.h" -#include "../IStream.h" - -class CLockedInStream -{ - CMyComPtr _stream; - NWindows::NSynchronization::CCriticalSection _criticalSection; -public: - void Init(IInStream *stream) - { _stream = stream; } - HRESULT Read(UInt64 startPos, void *data, UInt32 size, UInt32 *processedSize); -}; - -class CLockedSequentialInStreamImp: - public ISequentialInStream, - public CMyUnknownImp -{ - CLockedInStream *_lockedInStream; - UInt64 _pos; -public: - void Init(CLockedInStream *lockedInStream, UInt64 startPos) - { - _lockedInStream = lockedInStream; - _pos = startPos; - } - - MY_UNKNOWN_IMP - - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Common/MemBlocks.cpp b/desmume/src/windows/7z/CPP/7zip/Common/MemBlocks.cpp deleted file mode 100644 index 923c2e775..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/MemBlocks.cpp +++ /dev/null @@ -1,183 +0,0 @@ -// MemBlocks.cpp - -#include "StdAfx.h" - -#include "Common/MyCom.h" - -#include "StreamUtils.h" -#include "MemBlocks.h" - -bool CMemBlockManager::AllocateSpace(size_t numBlocks) -{ - FreeSpace(); - if (_blockSize < sizeof(void *) || numBlocks < 1) - return false; - size_t totalSize = numBlocks * _blockSize; - if (totalSize / _blockSize != numBlocks) - return false; - _data = ::MidAlloc(totalSize); - if (_data == 0) - return false; - Byte *p = (Byte *)_data; - for (size_t i = 0; i + 1 < numBlocks; i++, p += _blockSize) - *(Byte **)p = (p + _blockSize); - *(Byte **)p = 0; - _headFree = _data; - return true; -} - -void CMemBlockManager::FreeSpace() -{ - ::MidFree(_data); - _data = 0; - _headFree= 0; -} - -void *CMemBlockManager::AllocateBlock() -{ - if (_headFree == 0) - return 0; - void *p = _headFree; - _headFree = *(void **)_headFree; - return p; -} - -void CMemBlockManager::FreeBlock(void *p) -{ - if (p == 0) - return; - *(void **)p = _headFree; - _headFree = p; -} - - -HRes CMemBlockManagerMt::AllocateSpace(size_t numBlocks, size_t numNoLockBlocks) -{ - if (numNoLockBlocks > numBlocks) - return E_INVALIDARG; - if (!CMemBlockManager::AllocateSpace(numBlocks)) - return E_OUTOFMEMORY; - size_t numLockBlocks = numBlocks - numNoLockBlocks; - Semaphore.Close(); - return Semaphore.Create((LONG)numLockBlocks, (LONG)numLockBlocks); -} - -HRes CMemBlockManagerMt::AllocateSpaceAlways(size_t desiredNumberOfBlocks, size_t numNoLockBlocks) -{ - if (numNoLockBlocks > desiredNumberOfBlocks) - return E_INVALIDARG; - for (;;) - { - if (AllocateSpace(desiredNumberOfBlocks, numNoLockBlocks) == 0) - return 0; - if (desiredNumberOfBlocks == numNoLockBlocks) - return E_OUTOFMEMORY; - desiredNumberOfBlocks = numNoLockBlocks + ((desiredNumberOfBlocks - numNoLockBlocks) >> 1); - } -} - -void CMemBlockManagerMt::FreeSpace() -{ - Semaphore.Close(); - CMemBlockManager::FreeSpace(); -} - -void *CMemBlockManagerMt::AllocateBlock() -{ - // Semaphore.Lock(); - NWindows::NSynchronization::CCriticalSectionLock lock(_criticalSection); - return CMemBlockManager::AllocateBlock(); -} - -void CMemBlockManagerMt::FreeBlock(void *p, bool lockMode) -{ - if (p == 0) - return; - { - NWindows::NSynchronization::CCriticalSectionLock lock(_criticalSection); - CMemBlockManager::FreeBlock(p); - } - if (lockMode) - Semaphore.Release(); -} - -void CMemBlocks::Free(CMemBlockManagerMt *manager) -{ - while(Blocks.Size() > 0) - { - manager->FreeBlock(Blocks.Back()); - Blocks.DeleteBack(); - } - TotalSize = 0; -} - -void CMemBlocks::FreeOpt(CMemBlockManagerMt *manager) -{ - Free(manager); - Blocks.ClearAndFree(); -} - -HRESULT CMemBlocks::WriteToStream(size_t blockSize, ISequentialOutStream *outStream) const -{ - UInt64 totalSize = TotalSize; - for (int blockIndex = 0; totalSize > 0; blockIndex++) - { - UInt32 curSize = (UInt32)blockSize; - if (totalSize < curSize) - curSize = (UInt32)totalSize; - if (blockIndex >= Blocks.Size()) - return E_FAIL; - RINOK(WriteStream(outStream, Blocks[blockIndex], curSize)); - totalSize -= curSize; - } - return S_OK; -} - - -void CMemLockBlocks::FreeBlock(int index, CMemBlockManagerMt *memManager) -{ - memManager->FreeBlock(Blocks[index], LockMode); - Blocks[index] = 0; -} - -void CMemLockBlocks::Free(CMemBlockManagerMt *memManager) -{ - while (Blocks.Size() > 0) - { - FreeBlock(Blocks.Size() - 1, memManager); - Blocks.DeleteBack(); - } - TotalSize = 0; -} - -HRes CMemLockBlocks::SwitchToNoLockMode(CMemBlockManagerMt *memManager) -{ - if (LockMode) - { - if (Blocks.Size() > 0) - { - RINOK(memManager->ReleaseLockedBlocks(Blocks.Size())); - } - LockMode = false; - } - return 0; -} - -void CMemLockBlocks::Detach(CMemLockBlocks &blocks, CMemBlockManagerMt *memManager) -{ - blocks.Free(memManager); - blocks.LockMode = LockMode; - UInt64 totalSize = 0; - size_t blockSize = memManager->GetBlockSize(); - for (int i = 0; i < Blocks.Size(); i++) - { - if (totalSize < TotalSize) - blocks.Blocks.Add(Blocks[i]); - else - FreeBlock(i, memManager); - Blocks[i] = 0; - totalSize += blockSize; - } - blocks.TotalSize = TotalSize; - Free(memManager); -} diff --git a/desmume/src/windows/7z/CPP/7zip/Common/MemBlocks.h b/desmume/src/windows/7z/CPP/7zip/Common/MemBlocks.h deleted file mode 100644 index 4b20a1c4a..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/MemBlocks.h +++ /dev/null @@ -1,77 +0,0 @@ -// MemBlocks.h - -#ifndef __MEMBLOCKS_H -#define __MEMBLOCKS_H - -extern "C" -{ -#include "../../../C/Alloc.h" -} - -#include "Common/Types.h" -#include "Common/MyVector.h" - -#include "Windows/Synchronization.h" - -#include "../IStream.h" - -class CMemBlockManager -{ - void *_data; - size_t _blockSize; - void *_headFree; -public: - CMemBlockManager(size_t blockSize = (1 << 20)): _data(0), _blockSize(blockSize), _headFree(0) {} - ~CMemBlockManager() { FreeSpace(); } - - bool AllocateSpace(size_t numBlocks); - void FreeSpace(); - size_t GetBlockSize() const { return _blockSize; } - void *AllocateBlock(); - void FreeBlock(void *p); -}; - - -class CMemBlockManagerMt: public CMemBlockManager -{ - NWindows::NSynchronization::CCriticalSection _criticalSection; -public: - NWindows::NSynchronization::CSemaphore Semaphore; - - CMemBlockManagerMt(size_t blockSize = (1 << 20)): CMemBlockManager(blockSize) {} - ~CMemBlockManagerMt() { FreeSpace(); } - - HRes AllocateSpace(size_t numBlocks, size_t numNoLockBlocks = 0); - HRes AllocateSpaceAlways(size_t desiredNumberOfBlocks, size_t numNoLockBlocks = 0); - void FreeSpace(); - void *AllocateBlock(); - void FreeBlock(void *p, bool lockMode = true); - HRes ReleaseLockedBlocks(int number) { return Semaphore.Release(number); } -}; - - -class CMemBlocks -{ - void Free(CMemBlockManagerMt *manager); -public: - CRecordVector Blocks; - UInt64 TotalSize; - - CMemBlocks(): TotalSize(0) {} - - void FreeOpt(CMemBlockManagerMt *manager); - HRESULT WriteToStream(size_t blockSize, ISequentialOutStream *outStream) const; -}; - -struct CMemLockBlocks: public CMemBlocks -{ - bool LockMode; - - CMemLockBlocks(): LockMode(true) {}; - void Free(CMemBlockManagerMt *memManager); - void FreeBlock(int index, CMemBlockManagerMt *memManager); - HRes SwitchToNoLockMode(CMemBlockManagerMt *memManager); - void Detach(CMemLockBlocks &blocks, CMemBlockManagerMt *memManager); -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Common/MethodId.cpp b/desmume/src/windows/7z/CPP/7zip/Common/MethodId.cpp deleted file mode 100644 index 705cc4d9b..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/MethodId.cpp +++ /dev/null @@ -1,27 +0,0 @@ -// MethodId.cpp - -#include "StdAfx.h" - -#include "MethodId.h" -#include "../../Common/MyString.h" - -static inline wchar_t GetHex(Byte value) -{ - return (wchar_t)((value < 10) ? ('0' + value) : ('A' + (value - 10))); -} - -UString ConvertMethodIdToString(UInt64 id) -{ - wchar_t s[32]; - int len = 32; - s[--len] = 0; - do - { - s[--len] = GetHex((Byte)id & 0xF); - id >>= 4; - s[--len] = GetHex((Byte)id & 0xF); - id >>= 4; - } - while (id != 0); - return s + len; -} diff --git a/desmume/src/windows/7z/CPP/7zip/Common/MethodId.h b/desmume/src/windows/7z/CPP/7zip/Common/MethodId.h deleted file mode 100644 index 955172354..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/MethodId.h +++ /dev/null @@ -1,10 +0,0 @@ -// MethodId.h - -#ifndef __7Z_METHOD_ID_H -#define __7Z_METHOD_ID_H - -#include "../../Common/Types.h" - -typedef UInt64 CMethodId; - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Common/MethodProps.cpp b/desmume/src/windows/7z/CPP/7zip/Common/MethodProps.cpp deleted file mode 100644 index d917a2c23..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/MethodProps.cpp +++ /dev/null @@ -1,99 +0,0 @@ -// MethodProps.cpp - -#include "StdAfx.h" - -#include "../../Common/MyCom.h" - -#include "../ICoder.h" - -#include "MethodProps.h" - -static UInt64 k_LZMA = 0x030101; -// static UInt64 k_LZMA2 = 0x030102; - -HRESULT SetMethodProperties(const CMethod &method, const UInt64 *inSizeForReduce, IUnknown *coder) -{ - bool tryReduce = false; - UInt32 reducedDictionarySize = 1 << 10; - if (inSizeForReduce != 0 && (method.Id == k_LZMA /* || methodFull.MethodID == k_LZMA2 */)) - { - for (;;) - { - const UInt32 step = (reducedDictionarySize >> 1); - if (reducedDictionarySize >= *inSizeForReduce) - { - tryReduce = true; - break; - } - reducedDictionarySize += step; - if (reducedDictionarySize >= *inSizeForReduce) - { - tryReduce = true; - break; - } - if (reducedDictionarySize >= ((UInt32)3 << 30)) - break; - reducedDictionarySize += step; - } - } - - { - int numProps = method.Props.Size(); - CMyComPtr setCoderProperties; - coder->QueryInterface(IID_ICompressSetCoderProperties, (void **)&setCoderProperties); - if (setCoderProperties == NULL) - { - if (numProps != 0) - return E_INVALIDARG; - } - else - { - CRecordVector propIDs; - NWindows::NCOM::CPropVariant *values = new NWindows::NCOM::CPropVariant[numProps]; - HRESULT res = S_OK; - try - { - for (int i = 0; i < numProps; i++) - { - const CProp &prop = method.Props[i]; - propIDs.Add(prop.Id); - NWindows::NCOM::CPropVariant &value = values[i]; - value = prop.Value; - // if (tryReduce && prop.Id == NCoderPropID::kDictionarySize && value.vt == VT_UI4 && reducedDictionarySize < value.ulVal) - if (tryReduce) - if (prop.Id == NCoderPropID::kDictionarySize) - if (value.vt == VT_UI4) - if (reducedDictionarySize < value.ulVal) - value.ulVal = reducedDictionarySize; - } - CMyComPtr setCoderProperties; - coder->QueryInterface(IID_ICompressSetCoderProperties, (void **)&setCoderProperties); - res = setCoderProperties->SetCoderProperties(&propIDs.Front(), values, numProps); - } - catch(...) - { - delete []values; - throw; - } - delete []values; - RINOK(res); - } - } - - /* - CMyComPtr writeCoderProperties; - coder->QueryInterface(IID_ICompressWriteCoderProperties, (void **)&writeCoderProperties); - if (writeCoderProperties != NULL) - { - CSequentialOutStreamImp *outStreamSpec = new CSequentialOutStreamImp; - CMyComPtr outStream(outStreamSpec); - outStreamSpec->Init(); - RINOK(writeCoderProperties->WriteCoderProperties(outStream)); - size_t size = outStreamSpec->GetSize(); - filterProps.SetCapacity(size); - memmove(filterProps, outStreamSpec->GetBuffer(), size); - } - */ - return S_OK; -} - diff --git a/desmume/src/windows/7z/CPP/7zip/Common/MethodProps.h b/desmume/src/windows/7z/CPP/7zip/Common/MethodProps.h deleted file mode 100644 index e27f09574..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/MethodProps.h +++ /dev/null @@ -1,41 +0,0 @@ -// MethodProps.h - -#ifndef __7Z_METHOD_PROPS_H -#define __7Z_METHOD_PROPS_H - -#include "../../Common/MyVector.h" - -#include "../../Windows/PropVariant.h" - -#include "MethodId.h" - -struct CProp -{ - PROPID Id; - NWindows::NCOM::CPropVariant Value; -}; - -struct CMethod -{ - CMethodId Id; - CObjectVector Props; -}; - -struct CMethodsMode -{ - CObjectVector Methods; - #ifdef COMPRESS_MT - UInt32 NumThreads; - #endif - - CMethodsMode() - #ifdef COMPRESS_MT - : NumThreads(1) - #endif - {} - bool IsEmpty() const { return Methods.IsEmpty() ; } -}; - -HRESULT SetMethodProperties(const CMethod &method, const UInt64 *inSizeForReduce, IUnknown *coder); - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Common/OffsetStream.cpp b/desmume/src/windows/7z/CPP/7zip/Common/OffsetStream.cpp deleted file mode 100644 index d37657949..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/OffsetStream.cpp +++ /dev/null @@ -1,35 +0,0 @@ -// OffsetStream.cpp - -#include "StdAfx.h" - -#include "Common/Defs.h" -#include "OffsetStream.h" - -HRESULT COffsetOutStream::Init(IOutStream *stream, UInt64 offset) -{ - _offset = offset; - _stream = stream; - return _stream->Seek(offset, STREAM_SEEK_SET, NULL); -} - -STDMETHODIMP COffsetOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize) -{ - return _stream->Write(data, size, processedSize); -} - -STDMETHODIMP COffsetOutStream::Seek(Int64 offset, UInt32 seekOrigin, - UInt64 *newPosition) -{ - UInt64 absoluteNewPosition; - if (seekOrigin == STREAM_SEEK_SET) - offset += _offset; - HRESULT result = _stream->Seek(offset, seekOrigin, &absoluteNewPosition); - if (newPosition != NULL) - *newPosition = absoluteNewPosition - _offset; - return result; -} - -STDMETHODIMP COffsetOutStream::SetSize(Int64 newSize) -{ - return _stream->SetSize(_offset + newSize); -} diff --git a/desmume/src/windows/7z/CPP/7zip/Common/OffsetStream.h b/desmume/src/windows/7z/CPP/7zip/Common/OffsetStream.h deleted file mode 100644 index 15846b24a..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/OffsetStream.h +++ /dev/null @@ -1,25 +0,0 @@ -// OffsetStream.h - -#ifndef __OFFSETSTREAM_H -#define __OFFSETSTREAM_H - -#include "Common/MyCom.h" -#include "../IStream.h" - -class COffsetOutStream: - public IOutStream, - public CMyUnknownImp -{ - UInt64 _offset; - CMyComPtr _stream; -public: - HRESULT Init(IOutStream *stream, UInt64 offset); - - MY_UNKNOWN_IMP - - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); - STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition); - STDMETHOD(SetSize)(Int64 newSize); -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Common/OutBuffer.cpp b/desmume/src/windows/7z/CPP/7zip/Common/OutBuffer.cpp deleted file mode 100644 index 238320fe4..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/OutBuffer.cpp +++ /dev/null @@ -1,119 +0,0 @@ -// OutByte.cpp - -#include "StdAfx.h" - -#include "OutBuffer.h" - -extern "C" -{ - #include "../../../C/Alloc.h" -} - -bool COutBuffer::Create(UInt32 bufferSize) -{ - const UInt32 kMinBlockSize = 1; - if (bufferSize < kMinBlockSize) - bufferSize = kMinBlockSize; - if (_buffer != 0 && _bufferSize == bufferSize) - return true; - Free(); - _bufferSize = bufferSize; - _buffer = (Byte *)::MidAlloc(bufferSize); - return (_buffer != 0); -} - -void COutBuffer::Free() -{ - ::MidFree(_buffer); - _buffer = 0; -} - -void COutBuffer::SetStream(ISequentialOutStream *stream) -{ - _stream = stream; -} - -void COutBuffer::Init() -{ - _streamPos = 0; - _limitPos = _bufferSize; - _pos = 0; - _processedSize = 0; - _overDict = false; - #ifdef _NO_EXCEPTIONS - ErrorCode = S_OK; - #endif -} - -UInt64 COutBuffer::GetProcessedSize() const -{ - UInt64 res = _processedSize + _pos - _streamPos; - if (_streamPos > _pos) - res += _bufferSize; - return res; -} - - -HRESULT COutBuffer::FlushPart() -{ - // _streamPos < _bufferSize - UInt32 size = (_streamPos >= _pos) ? (_bufferSize - _streamPos) : (_pos - _streamPos); - HRESULT result = S_OK; - #ifdef _NO_EXCEPTIONS - result = ErrorCode; - #endif - if (_buffer2 != 0) - { - memmove(_buffer2, _buffer + _streamPos, size); - _buffer2 += size; - } - - if (_stream != 0 - #ifdef _NO_EXCEPTIONS - && (ErrorCode == S_OK) - #endif - ) - { - UInt32 processedSize = 0; - result = _stream->Write(_buffer + _streamPos, size, &processedSize); - size = processedSize; - } - _streamPos += size; - if (_streamPos == _bufferSize) - _streamPos = 0; - if (_pos == _bufferSize) - { - _overDict = true; - _pos = 0; - } - _limitPos = (_streamPos > _pos) ? _streamPos : _bufferSize; - _processedSize += size; - return result; -} - -HRESULT COutBuffer::Flush() -{ - #ifdef _NO_EXCEPTIONS - if (ErrorCode != S_OK) - return ErrorCode; - #endif - - while(_streamPos != _pos) - { - HRESULT result = FlushPart(); - if (result != S_OK) - return result; - } - return S_OK; -} - -void COutBuffer::FlushWithCheck() -{ - HRESULT result = Flush(); - #ifdef _NO_EXCEPTIONS - ErrorCode = result; - #else - if (result != S_OK) - throw COutBufferException(result); - #endif -} diff --git a/desmume/src/windows/7z/CPP/7zip/Common/OutBuffer.h b/desmume/src/windows/7z/CPP/7zip/Common/OutBuffer.h deleted file mode 100644 index e2e76ad58..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/OutBuffer.h +++ /dev/null @@ -1,64 +0,0 @@ -// OutBuffer.h - -#ifndef __OUTBUFFER_H -#define __OUTBUFFER_H - -#include "../IStream.h" -#include "../../Common/MyCom.h" -#include "../../Common/MyException.h" - -#ifndef _NO_EXCEPTIONS -struct COutBufferException: public CSystemException -{ - COutBufferException(HRESULT errorCode): CSystemException(errorCode) {} -}; -#endif - -class COutBuffer -{ -protected: - Byte *_buffer; - UInt32 _pos; - UInt32 _limitPos; - UInt32 _streamPos; - UInt32 _bufferSize; - CMyComPtr _stream; - UInt64 _processedSize; - Byte *_buffer2; - bool _overDict; - - HRESULT FlushPart(); -public: - #ifdef _NO_EXCEPTIONS - HRESULT ErrorCode; - #endif - - COutBuffer(): _buffer(0), _pos(0), _stream(0), _buffer2(0) {} - ~COutBuffer() { Free(); } - - bool Create(UInt32 bufferSize); - void Free(); - - void SetMemStream(Byte *buffer) { _buffer2 = buffer; } - void SetStream(ISequentialOutStream *stream); - void Init(); - HRESULT Flush(); - void FlushWithCheck(); - void ReleaseStream() { _stream.Release(); } - - void WriteByte(Byte b) - { - _buffer[_pos++] = b; - if(_pos == _limitPos) - FlushWithCheck(); - } - void WriteBytes(const void *data, size_t size) - { - for (size_t i = 0; i < size; i++) - WriteByte(((const Byte *)data)[i]); - } - - UInt64 GetProcessedSize() const; -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Common/OutMemStream.cpp b/desmume/src/windows/7z/CPP/7zip/Common/OutMemStream.cpp deleted file mode 100644 index f0208eaaf..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/OutMemStream.cpp +++ /dev/null @@ -1,142 +0,0 @@ -// OutMemStream.cpp - -#include "StdAfx.h" - -#include "OutMemStream.h" - -void COutMemStream::Free() -{ - Blocks.Free(_memManager); - Blocks.LockMode = true; -} - -void COutMemStream::Init() -{ - WriteToRealStreamEvent.Reset(); - _unlockEventWasSent = false; - _realStreamMode = false; - Free(); - _curBlockPos = 0; - _curBlockIndex = 0; -} - -void COutMemStream::DetachData(CMemLockBlocks &blocks) -{ - Blocks.Detach(blocks, _memManager); - Free(); -} - - -HRESULT COutMemStream::WriteToRealStream() -{ - RINOK(Blocks.WriteToStream(_memManager->GetBlockSize(), OutSeqStream)); - Blocks.Free(_memManager); - return S_OK; -} - -STDMETHODIMP COutMemStream::Write(const void *data, UInt32 size, UInt32 *processedSize) -{ - if (_realStreamMode) - return OutSeqStream->Write(data, size, processedSize); - if (processedSize != 0) - *processedSize = 0; - while(size != 0) - { - if ((int)_curBlockIndex < Blocks.Blocks.Size()) - { - Byte *p = (Byte *)Blocks.Blocks[(int)_curBlockIndex] + _curBlockPos; - size_t curSize = _memManager->GetBlockSize() - _curBlockPos; - if (size < curSize) - curSize = size; - memmove(p, data, curSize); - if (processedSize != 0) - *processedSize += (UInt32)curSize; - data = (const void *)((const Byte *)data + curSize); - size -= (UInt32)curSize; - _curBlockPos += curSize; - - UInt64 pos64 = GetPos(); - if (pos64 > Blocks.TotalSize) - Blocks.TotalSize = pos64; - if (_curBlockPos == _memManager->GetBlockSize()) - { - _curBlockIndex++; - _curBlockPos = 0; - } - continue; - } - HANDLE events[3] = { StopWritingEvent, WriteToRealStreamEvent, /* NoLockEvent, */ _memManager->Semaphore }; - DWORD waitResult = ::WaitForMultipleObjects((Blocks.LockMode ? 3 : 2), events, FALSE, INFINITE); - switch (waitResult) - { - case (WAIT_OBJECT_0 + 0): - return StopWriteResult; - case (WAIT_OBJECT_0 + 1): - { - _realStreamMode = true; - RINOK(WriteToRealStream()); - UInt32 processedSize2; - HRESULT res = OutSeqStream->Write(data, size, &processedSize2); - if (processedSize != 0) - *processedSize += processedSize2; - return res; - } - /* - case (WAIT_OBJECT_0 + 2): - { - // it has bug: no write. - if (!Blocks.SwitchToNoLockMode(_memManager)) - return E_FAIL; - break; - } - */ - case (WAIT_OBJECT_0 + 2): - break; - default: - return E_FAIL; - } - Blocks.Blocks.Add(_memManager->AllocateBlock()); - if (Blocks.Blocks.Back() == 0) - return E_FAIL; - } - return S_OK; -} - -STDMETHODIMP COutMemStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) -{ - if (_realStreamMode) - { - if (!OutStream) - return E_FAIL; - return OutStream->Seek(offset, seekOrigin, newPosition); - } - if (seekOrigin == STREAM_SEEK_CUR) - { - if (offset != 0) - return E_NOTIMPL; - } - else if (seekOrigin == STREAM_SEEK_SET) - { - if (offset != 0) - return E_NOTIMPL; - _curBlockIndex = 0; - _curBlockPos = 0; - } - else - return E_NOTIMPL; - if (newPosition != 0) - *newPosition = GetPos(); - return S_OK; -} - -STDMETHODIMP COutMemStream::SetSize(Int64 newSize) -{ - if (_realStreamMode) - { - if (!OutStream) - return E_FAIL; - return OutStream->SetSize(newSize); - } - Blocks.TotalSize = newSize; - return S_OK; -} diff --git a/desmume/src/windows/7z/CPP/7zip/Common/OutMemStream.h b/desmume/src/windows/7z/CPP/7zip/Common/OutMemStream.h deleted file mode 100644 index 9a8cac431..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/OutMemStream.h +++ /dev/null @@ -1,96 +0,0 @@ -// OutMemStream.h - -#ifndef __OUTMEMSTREAM_H -#define __OUTMEMSTREAM_H - -#include "Common/MyCom.h" -#include "MemBlocks.h" - -class COutMemStream: - public IOutStream, - public CMyUnknownImp -{ - CMemBlockManagerMt *_memManager; - size_t _curBlockIndex; - size_t _curBlockPos; - bool _realStreamMode; - - bool _unlockEventWasSent; - NWindows::NSynchronization::CAutoResetEvent StopWritingEvent; - NWindows::NSynchronization::CAutoResetEvent WriteToRealStreamEvent; - // NWindows::NSynchronization::CAutoResetEvent NoLockEvent; - - HRESULT StopWriteResult; - CMemLockBlocks Blocks; - - UInt64 GetPos() const { return (UInt64)_curBlockIndex * _memManager->GetBlockSize() + _curBlockPos; } - - CMyComPtr OutSeqStream; - CMyComPtr OutStream; - -public: - - HRes CreateEvents() - { - RINOK(StopWritingEvent.CreateIfNotCreated()); - return WriteToRealStreamEvent.CreateIfNotCreated(); - } - - void SetOutStream(IOutStream *outStream) - { - OutStream = outStream; - OutSeqStream = outStream; - } - - void SetSeqOutStream(ISequentialOutStream *outStream) - { - OutStream = NULL; - OutSeqStream = outStream; - } - - void ReleaseOutStream() - { - OutStream.Release(); - OutSeqStream.Release(); - } - - COutMemStream(CMemBlockManagerMt *memManager): _memManager(memManager) { } - - ~COutMemStream() { Free(); } - void Free(); - - void Init(); - HRESULT WriteToRealStream(); - - void DetachData(CMemLockBlocks &blocks); - - bool WasUnlockEventSent() const { return _unlockEventWasSent; } - - void SetRealStreamMode() - { - _unlockEventWasSent = true; - WriteToRealStreamEvent.Set(); - } - - /* - void SetNoLockMode() - { - _unlockEventWasSent = true; - NoLockEvent.Set(); - } - */ - - void StopWriting(HRESULT res) - { - StopWriteResult = res; - StopWritingEvent.Set(); - } - - MY_UNKNOWN_IMP - - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); - STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition); - STDMETHOD(SetSize)(Int64 newSize); -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Common/ProgressMt.cpp b/desmume/src/windows/7z/CPP/7zip/Common/ProgressMt.cpp deleted file mode 100644 index e1e7f38e0..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/ProgressMt.cpp +++ /dev/null @@ -1,53 +0,0 @@ -// ProgressMt.h - -#include "StdAfx.h" - -#include "ProgressMt.h" - -void CMtCompressProgressMixer::Init(int numItems, ICompressProgressInfo *progress) -{ - NWindows::NSynchronization::CCriticalSectionLock lock(CriticalSection); - InSizes.Clear(); - OutSizes.Clear(); - for (int i = 0; i < numItems; i++) - { - InSizes.Add(0); - OutSizes.Add(0); - } - TotalInSize = 0; - TotalOutSize = 0; - _progress = progress; -} - -void CMtCompressProgressMixer::Reinit(int index) -{ - NWindows::NSynchronization::CCriticalSectionLock lock(CriticalSection); - InSizes[index] = 0; - OutSizes[index] = 0; -} - -HRESULT CMtCompressProgressMixer::SetRatioInfo(int index, const UInt64 *inSize, const UInt64 *outSize) -{ - NWindows::NSynchronization::CCriticalSectionLock lock(CriticalSection); - if (inSize != 0) - { - UInt64 diff = *inSize - InSizes[index]; - InSizes[index] = *inSize; - TotalInSize += diff; - } - if (outSize != 0) - { - UInt64 diff = *outSize - OutSizes[index]; - OutSizes[index] = *outSize; - TotalOutSize += diff; - } - if (_progress) - return _progress->SetRatioInfo(&TotalInSize, &TotalOutSize); - return S_OK; -} - - -STDMETHODIMP CMtCompressProgress::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize) -{ - return _progress->SetRatioInfo(_index, inSize, outSize); -} diff --git a/desmume/src/windows/7z/CPP/7zip/Common/ProgressMt.h b/desmume/src/windows/7z/CPP/7zip/Common/ProgressMt.h deleted file mode 100644 index 4eeb02aa0..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/ProgressMt.h +++ /dev/null @@ -1,46 +0,0 @@ -// ProgressMt.h - -#ifndef __PROGRESSMT_H -#define __PROGRESSMT_H - -#include "../../Common/MyCom.h" -#include "../../Common/MyVector.h" -#include "../../Windows/Synchronization.h" - -#include "../ICoder.h" -#include "../IProgress.h" - -class CMtCompressProgressMixer -{ - CMyComPtr _progress; - CRecordVector InSizes; - CRecordVector OutSizes; - UInt64 TotalInSize; - UInt64 TotalOutSize; -public: - NWindows::NSynchronization::CCriticalSection CriticalSection; - void Init(int numItems, ICompressProgressInfo *progress); - void Reinit(int index); - HRESULT SetRatioInfo(int index, const UInt64 *inSize, const UInt64 *outSize); -}; - -class CMtCompressProgress: - public ICompressProgressInfo, - public CMyUnknownImp -{ - CMtCompressProgressMixer *_progress; - int _index; -public: - void Init(CMtCompressProgressMixer *progress, int index) - { - _progress = progress; - _index = index; - } - void Reinit() { _progress->Reinit(_index); } - - MY_UNKNOWN_IMP - - STDMETHOD(SetRatioInfo)(const UInt64 *inSize, const UInt64 *outSize); -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Common/ProgressUtils.cpp b/desmume/src/windows/7z/CPP/7zip/Common/ProgressUtils.cpp deleted file mode 100644 index 84a3eaf65..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/ProgressUtils.cpp +++ /dev/null @@ -1,42 +0,0 @@ -// ProgressUtils.h - -#include "StdAfx.h" - -#include "ProgressUtils.h" - -CLocalProgress::CLocalProgress() -{ - ProgressOffset = InSize = OutSize = 0; - SendRatio = SendProgress = true; -} - -void CLocalProgress::Init(IProgress *progress, bool inSizeIsMain) -{ - _ratioProgress.Release(); - _progress = progress; - _progress.QueryInterface(IID_ICompressProgressInfo, &_ratioProgress); - _inSizeIsMain = inSizeIsMain; -} - -STDMETHODIMP CLocalProgress::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize) -{ - UInt64 inSizeNew = InSize, outSizeNew = OutSize; - if (inSize) - inSizeNew += (*inSize); - if (outSize) - outSizeNew += (*outSize); - if (SendRatio && _ratioProgress) - { - RINOK(_ratioProgress->SetRatioInfo(&inSizeNew, &outSizeNew)); - } - inSizeNew += ProgressOffset; - outSizeNew += ProgressOffset; - if (SendProgress) - return _progress->SetCompleted(_inSizeIsMain ? &inSizeNew : &outSizeNew); - return S_OK; -} - -HRESULT CLocalProgress::SetCur() -{ - return SetRatioInfo(NULL, NULL); -} diff --git a/desmume/src/windows/7z/CPP/7zip/Common/ProgressUtils.h b/desmume/src/windows/7z/CPP/7zip/Common/ProgressUtils.h deleted file mode 100644 index c6204844a..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/ProgressUtils.h +++ /dev/null @@ -1,34 +0,0 @@ -// ProgressUtils.h - -#ifndef __PROGRESSUTILS_H -#define __PROGRESSUTILS_H - -#include "../../Common/MyCom.h" - -#include "../ICoder.h" -#include "../IProgress.h" - -class CLocalProgress: - public ICompressProgressInfo, - public CMyUnknownImp -{ - CMyComPtr _progress; - CMyComPtr _ratioProgress; - bool _inSizeIsMain; -public: - UInt64 ProgressOffset; - UInt64 InSize; - UInt64 OutSize; - bool SendRatio; - bool SendProgress; - - CLocalProgress(); - void Init(IProgress *progress, bool inSizeIsMain); - HRESULT SetCur(); - - MY_UNKNOWN_IMP - - STDMETHOD(SetRatioInfo)(const UInt64 *inSize, const UInt64 *outSize); -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Common/RegisterArc.h b/desmume/src/windows/7z/CPP/7zip/Common/RegisterArc.h deleted file mode 100644 index e377c4095..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/RegisterArc.h +++ /dev/null @@ -1,33 +0,0 @@ -// RegisterArc.h - -#ifndef __REGISTERARC_H -#define __REGISTERARC_H - -#include "../Archive/IArchive.h" -#include "DeclareArcs.h" - -typedef IInArchive * (*CreateInArchiveP)(); -typedef IOutArchive * (*CreateOutArchiveP)(); - -struct CArcInfo -{ - const wchar_t *Name; - const wchar_t *Ext; - const wchar_t *AddExt; - Byte ClassId; - Byte Signature[16]; - int SignatureSize; - bool KeepName; - CreateInArchiveP CreateInArchive; - CreateOutArchiveP CreateOutArchive; -}; - -void RegisterArc(const CArcInfo *arcInfo); - -#define REGISTER_ARC(x) CRegister##x::CRegister##x() { RegisterArc(&g_ArcInfo); } \ - CRegister##x g_RegisterArc##x; - -#define REGISTER_ARCN(x,n) CRegister##x##n::CRegister##x##n() { RegisterArc(&g_ArcInfo##n); } \ - CRegister##x##n g_RegisterArc##n##x; - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Common/RegisterCodec.h b/desmume/src/windows/7z/CPP/7zip/Common/RegisterCodec.h deleted file mode 100644 index f51e6317e..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/RegisterCodec.h +++ /dev/null @@ -1,30 +0,0 @@ -// RegisterCodec.h - -#ifndef __REGISTERCODEC_H -#define __REGISTERCODEC_H - -#include "../Common/MethodId.h" -#include "DeclareCodecs.h" - -typedef void * (*CreateCodecP)(); -struct CCodecInfo -{ - CreateCodecP CreateDecoder; - CreateCodecP CreateEncoder; - CMethodId Id; - const wchar_t *Name; - UInt32 NumInStreams; - bool IsFilter; -}; - -void RegisterCodec(const CCodecInfo *codecInfo); - -#define REGISTER_CODEC(x) CRegisterCodec##x::CRegisterCodec##x() { RegisterCodec(&g_CodecInfo); } \ - CRegisterCodec##x g_RegisterCodec##x; - -#define REGISTER_CODECS(x) CRegisterCodecs##x::CRegisterCodecs##x() { \ - for(int i=0;iCloseRead(); } - void SetBinder(CStreamBinder *streamBinder) { m_StreamBinder = streamBinder; } -}; - -STDMETHODIMP CSequentialInStreamForBinder::Read(void *data, UInt32 size, UInt32 *processedSize) - { return m_StreamBinder->Read(data, size, processedSize); } - -class CSequentialOutStreamForBinder: - public ISequentialOutStream, - public CMyUnknownImp -{ -public: - MY_UNKNOWN_IMP - - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); - -private: - CStreamBinder *m_StreamBinder; -public: - ~CSequentialOutStreamForBinder() { m_StreamBinder->CloseWrite(); } - void SetBinder(CStreamBinder *streamBinder) { m_StreamBinder = streamBinder; } -}; - -STDMETHODIMP CSequentialOutStreamForBinder::Write(const void *data, UInt32 size, UInt32 *processedSize) - { return m_StreamBinder->Write(data, size, processedSize); } - - -////////////////////////// -// CStreamBinder -// (_thereAreBytesToReadEvent && _bufferSize == 0) means that stream is finished. - -HRes CStreamBinder::CreateEvents() -{ - RINOK(_allBytesAreWritenEvent.Create(true)); - RINOK(_thereAreBytesToReadEvent.Create()); - return _readStreamIsClosedEvent.Create(); -} - -void CStreamBinder::ReInit() -{ - _thereAreBytesToReadEvent.Reset(); - _readStreamIsClosedEvent.Reset(); - ProcessedSize = 0; -} - - - -void CStreamBinder::CreateStreams(ISequentialInStream **inStream, - ISequentialOutStream **outStream) -{ - CSequentialInStreamForBinder *inStreamSpec = new - CSequentialInStreamForBinder; - CMyComPtr inStreamLoc(inStreamSpec); - inStreamSpec->SetBinder(this); - *inStream = inStreamLoc.Detach(); - - CSequentialOutStreamForBinder *outStreamSpec = new - CSequentialOutStreamForBinder; - CMyComPtr outStreamLoc(outStreamSpec); - outStreamSpec->SetBinder(this); - *outStream = outStreamLoc.Detach(); - - _buffer = NULL; - _bufferSize= 0; - ProcessedSize = 0; -} - -HRESULT CStreamBinder::Read(void *data, UInt32 size, UInt32 *processedSize) -{ - UInt32 sizeToRead = size; - if (size > 0) - { - RINOK(_thereAreBytesToReadEvent.Lock()); - sizeToRead = MyMin(_bufferSize, size); - if (_bufferSize > 0) - { - memcpy(data, _buffer, sizeToRead); - _buffer = ((const Byte *)_buffer) + sizeToRead; - _bufferSize -= sizeToRead; - if (_bufferSize == 0) - { - _thereAreBytesToReadEvent.Reset(); - _allBytesAreWritenEvent.Set(); - } - } - } - if (processedSize != NULL) - *processedSize = sizeToRead; - ProcessedSize += sizeToRead; - return S_OK; -} - -void CStreamBinder::CloseRead() -{ - _readStreamIsClosedEvent.Set(); -} - -HRESULT CStreamBinder::Write(const void *data, UInt32 size, UInt32 *processedSize) -{ - if (size > 0) - { - _buffer = data; - _bufferSize = size; - _allBytesAreWritenEvent.Reset(); - _thereAreBytesToReadEvent.Set(); - - HANDLE events[2]; - events[0] = _allBytesAreWritenEvent; - events[1] = _readStreamIsClosedEvent; - DWORD waitResult = ::WaitForMultipleObjects(2, events, FALSE, INFINITE); - if (waitResult != WAIT_OBJECT_0 + 0) - { - // ReadingWasClosed = true; - return S_FALSE; - } - // if(!_allBytesAreWritenEvent.Lock()) - // return E_FAIL; - } - if (processedSize != NULL) - *processedSize = size; - return S_OK; -} - -void CStreamBinder::CloseWrite() -{ - // _bufferSize must be = 0 - _thereAreBytesToReadEvent.Set(); -} diff --git a/desmume/src/windows/7z/CPP/7zip/Common/StreamBinder.h b/desmume/src/windows/7z/CPP/7zip/Common/StreamBinder.h deleted file mode 100644 index b5d6c0d1c..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/StreamBinder.h +++ /dev/null @@ -1,32 +0,0 @@ -// StreamBinder.h - -#ifndef __STREAMBINDER_H -#define __STREAMBINDER_H - -#include "../IStream.h" -#include "../../Windows/Synchronization.h" - -class CStreamBinder -{ - NWindows::NSynchronization::CManualResetEvent _allBytesAreWritenEvent; - NWindows::NSynchronization::CManualResetEvent _thereAreBytesToReadEvent; - NWindows::NSynchronization::CManualResetEvent _readStreamIsClosedEvent; - UInt32 _bufferSize; - const void *_buffer; -public: - // bool ReadingWasClosed; - UInt64 ProcessedSize; - CStreamBinder() {} - HRes CreateEvents(); - - void CreateStreams(ISequentialInStream **inStream, - ISequentialOutStream **outStream); - HRESULT Read(void *data, UInt32 size, UInt32 *processedSize); - void CloseRead(); - - HRESULT Write(const void *data, UInt32 size, UInt32 *processedSize); - void CloseWrite(); - void ReInit(); -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Common/StreamObjects.cpp b/desmume/src/windows/7z/CPP/7zip/Common/StreamObjects.cpp deleted file mode 100644 index f42b56bfa..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/StreamObjects.cpp +++ /dev/null @@ -1,68 +0,0 @@ -// StreamObjects.cpp - -#include "StdAfx.h" - -#include "StreamObjects.h" -#include "../../Common/Defs.h" - - -STDMETHODIMP CSequentialInStreamImp::Read(void *data, UInt32 size, UInt32 *processedSize) -{ - size_t rem = _size - _pos; - if (size < rem) - rem = (size_t)size; - memcpy(data, _dataPointer + _pos, rem); - _pos += rem; - if (processedSize != NULL) - *processedSize = (UInt32)rem; - return S_OK; -} - - -void CWriteBuffer::Write(const void *data, size_t size) -{ - size_t newCapacity = _size + size; - _buffer.EnsureCapacity(newCapacity); - memcpy(_buffer + _size, data, size); - _size += size; -} - -STDMETHODIMP CSequentialOutStreamImp::Write(const void *data, UInt32 size, UInt32 *processedSize) -{ - _writeBuffer.Write(data, (size_t)size); - if(processedSize != NULL) - *processedSize = size; - return S_OK; -} - -STDMETHODIMP CSequentialOutStreamImp2::Write(const void *data, UInt32 size, UInt32 *processedSize) -{ - size_t rem = _size - _pos; - if (size < rem) - rem = (size_t)size; - memcpy(_buffer + _pos, data, rem); - _pos += rem; - if (processedSize != NULL) - *processedSize = (UInt32)rem; - return (rem == size ? S_OK : E_FAIL); -} - -STDMETHODIMP CSequentialInStreamSizeCount::Read(void *data, UInt32 size, UInt32 *processedSize) -{ - UInt32 realProcessedSize; - HRESULT result = _stream->Read(data, size, &realProcessedSize); - _size += realProcessedSize; - if (processedSize != 0) - *processedSize = realProcessedSize; - return result; -} - -STDMETHODIMP CSequentialOutStreamSizeCount::Write(const void *data, UInt32 size, UInt32 *processedSize) -{ - UInt32 realProcessedSize; - HRESULT result = _stream->Write(data, size, &realProcessedSize); - _size += realProcessedSize; - if (processedSize != 0) - *processedSize = realProcessedSize; - return result; -} diff --git a/desmume/src/windows/7z/CPP/7zip/Common/StreamObjects.h b/desmume/src/windows/7z/CPP/7zip/Common/StreamObjects.h deleted file mode 100644 index 7f19fd479..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/StreamObjects.h +++ /dev/null @@ -1,117 +0,0 @@ -// StreamObjects.h - -#ifndef __STREAMOBJECTS_H -#define __STREAMOBJECTS_H - -#include "../../Common/DynamicBuffer.h" -#include "../../Common/MyCom.h" -#include "../IStream.h" - -class CSequentialInStreamImp: - public ISequentialInStream, - public CMyUnknownImp -{ - const Byte *_dataPointer; - size_t _size; - size_t _pos; - -public: - void Init(const Byte *dataPointer, size_t size) - { - _dataPointer = dataPointer; - _size = size; - _pos = 0; - } - - MY_UNKNOWN_IMP - - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); -}; - - -class CWriteBuffer -{ - CByteDynamicBuffer _buffer; - size_t _size; -public: - CWriteBuffer(): _size(0) {} - void Init() { _size = 0; } - void Write(const void *data, size_t size); - size_t GetSize() const { return _size; } - const CByteDynamicBuffer& GetBuffer() const { return _buffer; } -}; - -class CSequentialOutStreamImp: - public ISequentialOutStream, - public CMyUnknownImp -{ - CWriteBuffer _writeBuffer; -public: - void Init() { _writeBuffer.Init(); } - size_t GetSize() const { return _writeBuffer.GetSize(); } - const CByteDynamicBuffer& GetBuffer() const { return _writeBuffer.GetBuffer(); } - - MY_UNKNOWN_IMP - - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); -}; - -class CSequentialOutStreamImp2: - public ISequentialOutStream, - public CMyUnknownImp -{ - Byte *_buffer; - size_t _size; - size_t _pos; -public: - - void Init(Byte *buffer, size_t size) - { - _buffer = buffer; - _pos = 0; - _size = size; - } - - size_t GetPos() const { return _pos; } - - MY_UNKNOWN_IMP - - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); -}; - -class CSequentialInStreamSizeCount: - public ISequentialInStream, - public CMyUnknownImp -{ - CMyComPtr _stream; - UInt64 _size; -public: - void Init(ISequentialInStream *stream) - { - _stream = stream; - _size = 0; - } - UInt64 GetSize() const { return _size; } - - MY_UNKNOWN_IMP - - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); -}; - -class CSequentialOutStreamSizeCount: - public ISequentialOutStream, - public CMyUnknownImp -{ - CMyComPtr _stream; - UInt64 _size; -public: - void SetStream(ISequentialOutStream *stream) { _stream = stream; } - void Init() { _size = 0; } - UInt64 GetSize() const { return _size; } - - MY_UNKNOWN_IMP - - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Common/StreamUtils.cpp b/desmume/src/windows/7z/CPP/7zip/Common/StreamUtils.cpp deleted file mode 100644 index 57ff4ee38..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/StreamUtils.cpp +++ /dev/null @@ -1,56 +0,0 @@ -// StreamUtils.cpp - -#include "StdAfx.h" - -#include "StreamUtils.h" - -static const UInt32 kBlockSize = ((UInt32)1 << 31); - -HRESULT ReadStream(ISequentialInStream *stream, void *data, size_t *processedSize) -{ - size_t size = *processedSize; - *processedSize = 0; - while (size != 0) - { - UInt32 curSize = (size < kBlockSize) ? (UInt32)size : kBlockSize; - UInt32 processedSizeLoc; - HRESULT res = stream->Read(data, curSize, &processedSizeLoc); - *processedSize += processedSizeLoc; - data = (void *)((Byte *)data + processedSizeLoc); - size -= processedSizeLoc; - RINOK(res); - if (processedSizeLoc == 0) - return S_OK; - } - return S_OK; -} - -HRESULT ReadStream_FALSE(ISequentialInStream *stream, void *data, size_t size) -{ - size_t processedSize = size; - RINOK(ReadStream(stream, data, &processedSize)); - return (size == processedSize) ? S_OK : S_FALSE; -} - -HRESULT ReadStream_FAIL(ISequentialInStream *stream, void *data, size_t size) -{ - size_t processedSize = size; - RINOK(ReadStream(stream, data, &processedSize)); - return (size == processedSize) ? S_OK : E_FAIL; -} - -HRESULT WriteStream(ISequentialOutStream *stream, const void *data, size_t size) -{ - while (size != 0) - { - UInt32 curSize = (size < kBlockSize) ? (UInt32)size : kBlockSize; - UInt32 processedSizeLoc; - HRESULT res = stream->Write(data, curSize, &processedSizeLoc); - data = (const void *)((const Byte *)data + processedSizeLoc); - size -= processedSizeLoc; - RINOK(res); - if (processedSizeLoc == 0) - return E_FAIL; - } - return S_OK; -} diff --git a/desmume/src/windows/7z/CPP/7zip/Common/StreamUtils.h b/desmume/src/windows/7z/CPP/7zip/Common/StreamUtils.h deleted file mode 100644 index 30535ab1b..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/StreamUtils.h +++ /dev/null @@ -1,13 +0,0 @@ -// StreamUtils.h - -#ifndef __STREAMUTILS_H -#define __STREAMUTILS_H - -#include "../IStream.h" - -HRESULT ReadStream(ISequentialInStream *stream, void *data, size_t *size); -HRESULT ReadStream_FALSE(ISequentialInStream *stream, void *data, size_t size); -HRESULT ReadStream_FAIL(ISequentialInStream *stream, void *data, size_t size); -HRESULT WriteStream(ISequentialOutStream *stream, const void *data, size_t size); - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Common/VirtThread.cpp b/desmume/src/windows/7z/CPP/7zip/Common/VirtThread.cpp deleted file mode 100644 index 75dc24c35..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/VirtThread.cpp +++ /dev/null @@ -1,45 +0,0 @@ -// VirtThread.cpp - -#include "StdAfx.h" - -#include "VirtThread.h" - -static THREAD_FUNC_DECL CoderThread(void *p) -{ - for (;;) - { - CVirtThread *t = (CVirtThread *)p; - t->StartEvent.Lock(); - if (t->ExitEvent) - return 0; - t->Execute(); - t->FinishedEvent.Set(); - } -} - -WRes CVirtThread::Create() -{ - RINOK(StartEvent.CreateIfNotCreated()); - RINOK(FinishedEvent.CreateIfNotCreated()); - StartEvent.Reset(); - FinishedEvent.Reset(); - ExitEvent = false; - if (Thread.IsCreated()) - return S_OK; - return Thread.Create(CoderThread, this); -} - -void CVirtThread::Start() -{ - ExitEvent = false; - StartEvent.Set(); -} - -CVirtThread::~CVirtThread() -{ - ExitEvent = true; - if (StartEvent.IsCreated()) - StartEvent.Set(); - Thread.Wait(); -} - diff --git a/desmume/src/windows/7z/CPP/7zip/Common/VirtThread.h b/desmume/src/windows/7z/CPP/7zip/Common/VirtThread.h deleted file mode 100644 index bfc10dc4a..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/VirtThread.h +++ /dev/null @@ -1,23 +0,0 @@ -// VirtThread.h - -#ifndef __VIRTTHREAD_H -#define __VIRTTHREAD_H - -#include "../../Windows/Synchronization.h" -#include "../../Windows/Thread.h" - -struct CVirtThread -{ - NWindows::NSynchronization::CAutoResetEvent StartEvent; - NWindows::NSynchronization::CAutoResetEvent FinishedEvent; - NWindows::CThread Thread; - bool ExitEvent; - - ~CVirtThread(); - WRes Create(); - void Start(); - void WaitFinish() { FinishedEvent.Lock(); } - virtual void Execute() = 0; -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/BZip2Const.h b/desmume/src/windows/7z/CPP/7zip/Compress/BZip2Const.h deleted file mode 100644 index fe0c53ff2..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/BZip2Const.h +++ /dev/null @@ -1,54 +0,0 @@ -// Compress/BZip2Const.h - -#ifndef __COMPRESS_BZIP2_CONST_H -#define __COMPRESS_BZIP2_CONST_H - -namespace NCompress { -namespace NBZip2 { - -const Byte kArSig0 = 'B'; -const Byte kArSig1 = 'Z'; -const Byte kArSig2 = 'h'; -const Byte kArSig3 = '0'; - -const Byte kFinSig0 = 0x17; -const Byte kFinSig1 = 0x72; -const Byte kFinSig2 = 0x45; -const Byte kFinSig3 = 0x38; -const Byte kFinSig4 = 0x50; -const Byte kFinSig5 = 0x90; - -const Byte kBlockSig0 = 0x31; -const Byte kBlockSig1 = 0x41; -const Byte kBlockSig2 = 0x59; -const Byte kBlockSig3 = 0x26; -const Byte kBlockSig4 = 0x53; -const Byte kBlockSig5 = 0x59; - -const int kNumOrigBits = 24; - -const int kNumTablesBits = 3; -const int kNumTablesMin = 2; -const int kNumTablesMax = 6; - -const int kNumLevelsBits = 5; - -const int kMaxHuffmanLen = 20; // Check it - -const int kMaxAlphaSize = 258; - -const int kGroupSize = 50; - -const int kBlockSizeMultMin = 1; -const int kBlockSizeMultMax = 9; -const UInt32 kBlockSizeStep = 100000; -const UInt32 kBlockSizeMax = kBlockSizeMultMax * kBlockSizeStep; - -const int kNumSelectorsBits = 15; -const UInt32 kNumSelectorsMax = (2 + (kBlockSizeMax / kGroupSize)); - -const int kRleModeRepSize = 4; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/BZip2Crc.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/BZip2Crc.cpp deleted file mode 100644 index 2a8277ca4..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/BZip2Crc.cpp +++ /dev/null @@ -1,26 +0,0 @@ -// BZip2Crc.cpp - -#include "StdAfx.h" - -#include "BZip2Crc.h" - -UInt32 CBZip2Crc::Table[256]; - -static const UInt32 kBZip2CrcPoly = 0x04c11db7; /* AUTODIN II, Ethernet, & FDDI */ - -void CBZip2Crc::InitTable() -{ - for (UInt32 i = 0; i < 256; i++) - { - UInt32 r = (i << 24); - for (int j = 8; j > 0; j--) - r = (r & 0x80000000) ? ((r << 1) ^ kBZip2CrcPoly) : (r << 1); - Table[i] = r; - } -} - -class CBZip2CrcTableInit -{ -public: - CBZip2CrcTableInit() { CBZip2Crc::InitTable(); } -} g_BZip2CrcTableInit; diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/BZip2Crc.h b/desmume/src/windows/7z/CPP/7zip/Compress/BZip2Crc.h deleted file mode 100644 index ad1322fdd..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/BZip2Crc.h +++ /dev/null @@ -1,31 +0,0 @@ -// BZip2Crc.h - -#ifndef __BZIP2_CRC_H -#define __BZIP2_CRC_H - -#include "Common/Types.h" - -class CBZip2Crc -{ - UInt32 _value; - static UInt32 Table[256]; -public: - static void InitTable(); - CBZip2Crc(): _value(0xFFFFFFFF) {}; - void Init() { _value = 0xFFFFFFFF; } - void UpdateByte(Byte b) { _value = Table[(_value >> 24) ^ b] ^ (_value << 8); } - void UpdateByte(unsigned int b) { _value = Table[(_value >> 24) ^ b] ^ (_value << 8); } - UInt32 GetDigest() const { return _value ^ 0xFFFFFFFF; } -}; - -class CBZip2CombinedCrc -{ - UInt32 _value; -public: - CBZip2CombinedCrc(): _value(0){}; - void Init() { _value = 0; } - void Update(UInt32 v) { _value = ((_value << 1) | (_value >> 31)) ^ v; } - UInt32 GetDigest() const { return _value ; } -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/BZip2Decoder.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/BZip2Decoder.cpp deleted file mode 100644 index b291be6f1..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/BZip2Decoder.cpp +++ /dev/null @@ -1,791 +0,0 @@ -// BZip2Decoder.cpp - -#include "StdAfx.h" - -extern "C" -{ -#include "../../../C/Alloc.h" -} - -#include "../../Common/Defs.h" - -#include "BZip2Crc.h" -#include "BZip2Decoder.h" -#include "Mtf8.h" - -namespace NCompress { -namespace NBZip2 { - -#define NO_INLINE MY_FAST_CALL - -const UInt32 kNumThreadsMax = 4; - -static const UInt32 kBufferSize = (1 << 17); - -static Int16 kRandNums[512] = { - 619, 720, 127, 481, 931, 816, 813, 233, 566, 247, - 985, 724, 205, 454, 863, 491, 741, 242, 949, 214, - 733, 859, 335, 708, 621, 574, 73, 654, 730, 472, - 419, 436, 278, 496, 867, 210, 399, 680, 480, 51, - 878, 465, 811, 169, 869, 675, 611, 697, 867, 561, - 862, 687, 507, 283, 482, 129, 807, 591, 733, 623, - 150, 238, 59, 379, 684, 877, 625, 169, 643, 105, - 170, 607, 520, 932, 727, 476, 693, 425, 174, 647, - 73, 122, 335, 530, 442, 853, 695, 249, 445, 515, - 909, 545, 703, 919, 874, 474, 882, 500, 594, 612, - 641, 801, 220, 162, 819, 984, 589, 513, 495, 799, - 161, 604, 958, 533, 221, 400, 386, 867, 600, 782, - 382, 596, 414, 171, 516, 375, 682, 485, 911, 276, - 98, 553, 163, 354, 666, 933, 424, 341, 533, 870, - 227, 730, 475, 186, 263, 647, 537, 686, 600, 224, - 469, 68, 770, 919, 190, 373, 294, 822, 808, 206, - 184, 943, 795, 384, 383, 461, 404, 758, 839, 887, - 715, 67, 618, 276, 204, 918, 873, 777, 604, 560, - 951, 160, 578, 722, 79, 804, 96, 409, 713, 940, - 652, 934, 970, 447, 318, 353, 859, 672, 112, 785, - 645, 863, 803, 350, 139, 93, 354, 99, 820, 908, - 609, 772, 154, 274, 580, 184, 79, 626, 630, 742, - 653, 282, 762, 623, 680, 81, 927, 626, 789, 125, - 411, 521, 938, 300, 821, 78, 343, 175, 128, 250, - 170, 774, 972, 275, 999, 639, 495, 78, 352, 126, - 857, 956, 358, 619, 580, 124, 737, 594, 701, 612, - 669, 112, 134, 694, 363, 992, 809, 743, 168, 974, - 944, 375, 748, 52, 600, 747, 642, 182, 862, 81, - 344, 805, 988, 739, 511, 655, 814, 334, 249, 515, - 897, 955, 664, 981, 649, 113, 974, 459, 893, 228, - 433, 837, 553, 268, 926, 240, 102, 654, 459, 51, - 686, 754, 806, 760, 493, 403, 415, 394, 687, 700, - 946, 670, 656, 610, 738, 392, 760, 799, 887, 653, - 978, 321, 576, 617, 626, 502, 894, 679, 243, 440, - 680, 879, 194, 572, 640, 724, 926, 56, 204, 700, - 707, 151, 457, 449, 797, 195, 791, 558, 945, 679, - 297, 59, 87, 824, 713, 663, 412, 693, 342, 606, - 134, 108, 571, 364, 631, 212, 174, 643, 304, 329, - 343, 97, 430, 751, 497, 314, 983, 374, 822, 928, - 140, 206, 73, 263, 980, 736, 876, 478, 430, 305, - 170, 514, 364, 692, 829, 82, 855, 953, 676, 246, - 369, 970, 294, 750, 807, 827, 150, 790, 288, 923, - 804, 378, 215, 828, 592, 281, 565, 555, 710, 82, - 896, 831, 547, 261, 524, 462, 293, 465, 502, 56, - 661, 821, 976, 991, 658, 869, 905, 758, 745, 193, - 768, 550, 608, 933, 378, 286, 215, 979, 792, 961, - 61, 688, 793, 644, 986, 403, 106, 366, 905, 644, - 372, 567, 466, 434, 645, 210, 389, 550, 919, 135, - 780, 773, 635, 389, 707, 100, 626, 958, 165, 504, - 920, 176, 193, 713, 857, 265, 203, 50, 668, 108, - 645, 990, 626, 197, 510, 357, 358, 850, 858, 364, - 936, 638 -}; - -bool CState::Alloc() -{ - if (Counters == 0) - Counters = (UInt32 *)BigAlloc((256 + kBlockSizeMax) * sizeof(UInt32)); - return (Counters != 0); -} - -void CState::Free() -{ - ::BigFree(Counters); - Counters = 0; -} - -UInt32 CDecoder::ReadBits(int numBits) { return m_InStream.ReadBits(numBits); } -Byte CDecoder::ReadByte() {return (Byte)ReadBits(8); } -bool CDecoder::ReadBit() { return ReadBits(1) != 0; } - -UInt32 CDecoder::ReadCrc() -{ - UInt32 crc = 0; - for (int i = 0; i < 4; i++) - { - crc <<= 8; - crc |= ReadByte(); - } - return crc; -} - -UInt32 NO_INLINE ReadBits(NBitm::CDecoder *m_InStream, int num) -{ - return m_InStream->ReadBits(num); -} - -UInt32 NO_INLINE ReadBit(NBitm::CDecoder *m_InStream) -{ - return m_InStream->ReadBits(1); -} - -static HRESULT NO_INLINE ReadBlock(NBitm::CDecoder *m_InStream, - UInt32 *CharCounters, UInt32 blockSizeMax, Byte *m_Selectors, CHuffmanDecoder *m_HuffmanDecoders, - UInt32 *blockSizeRes, UInt32 *origPtrRes, bool *randRes) -{ - *randRes = ReadBit(m_InStream) ? true : false; - *origPtrRes = ReadBits(m_InStream, kNumOrigBits); - - // in original code it compares OrigPtr to (UInt32)(10 + blockSizeMax)) : why ? - if (*origPtrRes >= blockSizeMax) - return S_FALSE; - - CMtf8Decoder mtf; - mtf.StartInit(); - - int numInUse = 0; - { - Byte inUse16[16]; - int i; - for (i = 0; i < 16; i++) - inUse16[i] = (Byte)ReadBit(m_InStream); - for (i = 0; i < 256; i++) - if (inUse16[i >> 4]) - { - if (ReadBit(m_InStream)) - mtf.Add(numInUse++, (Byte)i); - } - if (numInUse == 0) - return S_FALSE; - // mtf.Init(numInUse); - } - int alphaSize = numInUse + 2; - - int numTables = ReadBits(m_InStream, kNumTablesBits); - if (numTables < kNumTablesMin || numTables > kNumTablesMax) - return S_FALSE; - - UInt32 numSelectors = ReadBits(m_InStream, kNumSelectorsBits); - if (numSelectors < 1 || numSelectors > kNumSelectorsMax) - return S_FALSE; - - { - Byte mtfPos[kNumTablesMax]; - int t = 0; - do - mtfPos[t] = (Byte)t; - while(++t < numTables); - UInt32 i = 0; - do - { - int j = 0; - while (ReadBit(m_InStream)) - if (++j >= numTables) - return S_FALSE; - Byte tmp = mtfPos[j]; - for (;j > 0; j--) - mtfPos[j] = mtfPos[j - 1]; - m_Selectors[i] = mtfPos[0] = tmp; - } - while(++i < numSelectors); - } - - int t = 0; - do - { - Byte lens[kMaxAlphaSize]; - int len = (int)ReadBits(m_InStream, kNumLevelsBits); - int i; - for (i = 0; i < alphaSize; i++) - { - for (;;) - { - if (len < 1 || len > kMaxHuffmanLen) - return S_FALSE; - if (!ReadBit(m_InStream)) - break; - len += 1 - (int)(ReadBit(m_InStream) << 1); - } - lens[i] = (Byte)len; - } - for (; i < kMaxAlphaSize; i++) - lens[i] = 0; - if(!m_HuffmanDecoders[t].SetCodeLengths(lens)) - return S_FALSE; - } - while(++t < numTables); - - { - for (int i = 0; i < 256; i++) - CharCounters[i] = 0; - } - - UInt32 blockSize = 0; - { - UInt32 groupIndex = 0; - UInt32 groupSize = 0; - CHuffmanDecoder *huffmanDecoder = 0; - int runPower = 0; - UInt32 runCounter = 0; - - for (;;) - { - if (groupSize == 0) - { - if (groupIndex >= numSelectors) - return S_FALSE; - groupSize = kGroupSize; - huffmanDecoder = &m_HuffmanDecoders[m_Selectors[groupIndex++]]; - } - groupSize--; - - UInt32 nextSym = huffmanDecoder->DecodeSymbol(m_InStream); - - if (nextSym < 2) - { - runCounter += ((UInt32)(nextSym + 1) << runPower++); - if (blockSizeMax - blockSize < runCounter) - return S_FALSE; - continue; - } - if (runCounter != 0) - { - UInt32 b = (UInt32)mtf.GetHead(); - CharCounters[b] += runCounter; - do - CharCounters[256 + blockSize++] = b; - while(--runCounter != 0); - runPower = 0; - } - if (nextSym <= (UInt32)numInUse) - { - UInt32 b = (UInt32)mtf.GetAndMove((int)nextSym - 1); - if (blockSize >= blockSizeMax) - return S_FALSE; - CharCounters[b]++; - CharCounters[256 + blockSize++] = b; - } - else if (nextSym == (UInt32)numInUse + 1) - break; - else - return S_FALSE; - } - } - *blockSizeRes = blockSize; - return (*origPtrRes < blockSize) ? S_OK : S_FALSE; -} - -void NO_INLINE DecodeBlock1(UInt32 *charCounters, UInt32 blockSize) -{ - { - UInt32 sum = 0; - for (UInt32 i = 0; i < 256; i++) - { - sum += charCounters[i]; - charCounters[i] = sum - charCounters[i]; - } - } - - UInt32 *tt = charCounters + 256; - // Compute the T^(-1) vector - UInt32 i = 0; - do - tt[charCounters[tt[i] & 0xFF]++] |= (i << 8); - while(++i < blockSize); -} - -static UInt32 NO_INLINE DecodeBlock2(const UInt32 *tt, UInt32 blockSize, UInt32 OrigPtr, COutBuffer &m_OutStream) -{ - CBZip2Crc crc; - - // it's for speed optimization: prefetch & prevByte_init; - UInt32 tPos = tt[tt[OrigPtr] >> 8]; - unsigned int prevByte = (unsigned int)(tPos & 0xFF); - - int numReps = 0; - - do - { - unsigned int b = (unsigned int)(tPos & 0xFF); - tPos = tt[tPos >> 8]; - - if (numReps == kRleModeRepSize) - { - for (; b > 0; b--) - { - crc.UpdateByte(prevByte); - m_OutStream.WriteByte((Byte)prevByte); - } - numReps = 0; - continue; - } - if (b != prevByte) - numReps = 0; - numReps++; - prevByte = b; - crc.UpdateByte(b); - m_OutStream.WriteByte((Byte)b); - - /* - prevByte = b; - crc.UpdateByte(b); - m_OutStream.WriteByte((Byte)b); - for (; --blockSize != 0;) - { - b = (unsigned int)(tPos & 0xFF); - tPos = tt[tPos >> 8]; - crc.UpdateByte(b); - m_OutStream.WriteByte((Byte)b); - if (b != prevByte) - { - prevByte = b; - continue; - } - if (--blockSize == 0) - break; - - b = (unsigned int)(tPos & 0xFF); - tPos = tt[tPos >> 8]; - crc.UpdateByte(b); - m_OutStream.WriteByte((Byte)b); - if (b != prevByte) - { - prevByte = b; - continue; - } - if (--blockSize == 0) - break; - - b = (unsigned int)(tPos & 0xFF); - tPos = tt[tPos >> 8]; - crc.UpdateByte(b); - m_OutStream.WriteByte((Byte)b); - if (b != prevByte) - { - prevByte = b; - continue; - } - --blockSize; - break; - } - if (blockSize == 0) - break; - - b = (unsigned int)(tPos & 0xFF); - tPos = tt[tPos >> 8]; - - for (; b > 0; b--) - { - crc.UpdateByte(prevByte); - m_OutStream.WriteByte((Byte)prevByte); - } - */ - } - while(--blockSize != 0); - return crc.GetDigest(); -} - -static UInt32 NO_INLINE DecodeBlock2Rand(const UInt32 *tt, UInt32 blockSize, UInt32 OrigPtr, COutBuffer &m_OutStream) -{ - CBZip2Crc crc; - - UInt32 randIndex = 1; - UInt32 randToGo = kRandNums[0] - 2; - - int numReps = 0; - - // it's for speed optimization: prefetch & prevByte_init; - UInt32 tPos = tt[tt[OrigPtr] >> 8]; - unsigned int prevByte = (unsigned int)(tPos & 0xFF); - - do - { - unsigned int b = (unsigned int)(tPos & 0xFF); - tPos = tt[tPos >> 8]; - - { - if (randToGo == 0) - { - b ^= 1; - randToGo = kRandNums[randIndex++]; - randIndex &= 0x1FF; - } - randToGo--; - } - - if (numReps == kRleModeRepSize) - { - for (; b > 0; b--) - { - crc.UpdateByte(prevByte); - m_OutStream.WriteByte((Byte)prevByte); - } - numReps = 0; - continue; - } - if (b != prevByte) - numReps = 0; - numReps++; - prevByte = b; - crc.UpdateByte(b); - m_OutStream.WriteByte((Byte)b); - } - while(--blockSize != 0); - return crc.GetDigest(); -} - -#ifdef COMPRESS_BZIP2_MT - -CDecoder::CDecoder(): - m_States(0) -{ - m_NumThreadsPrev = 0; - NumThreads = 1; -} - -CDecoder::~CDecoder() -{ - Free(); -} - -#define RINOK_THREAD(x) { WRes __result_ = (x); if(__result_ != 0) return __result_; } - -HRESULT CDecoder::Create() -{ - RINOK_THREAD(CanProcessEvent.CreateIfNotCreated()); - RINOK_THREAD(CanStartWaitingEvent.CreateIfNotCreated()); - if (m_States != 0 && m_NumThreadsPrev == NumThreads) - return S_OK; - Free(); - MtMode = (NumThreads > 1); - m_NumThreadsPrev = NumThreads; - try - { - m_States = new CState[NumThreads]; - if (m_States == 0) - return E_OUTOFMEMORY; - } - catch(...) { return E_OUTOFMEMORY; } - for (UInt32 t = 0; t < NumThreads; t++) - { - CState &ti = m_States[t]; - ti.Decoder = this; - if (MtMode) - { - HRESULT res = ti.Create(); - if (res != S_OK) - { - NumThreads = t; - Free(); - return res; - } - } - } - return S_OK; -} - -void CDecoder::Free() -{ - if (!m_States) - return; - CloseThreads = true; - CanProcessEvent.Set(); - for (UInt32 t = 0; t < NumThreads; t++) - { - CState &s = m_States[t]; - if (MtMode) - s.Thread.Wait(); - s.Free(); - } - delete []m_States; - m_States = 0; -} -#endif - -HRESULT CDecoder::ReadSignatures(bool &wasFinished, UInt32 &crc) -{ - wasFinished = false; - Byte s[6]; - for (int i = 0; i < 6; i++) - s[i] = ReadByte(); - crc = ReadCrc(); - if (s[0] == kFinSig0) - { - if (s[1] != kFinSig1 || - s[2] != kFinSig2 || - s[3] != kFinSig3 || - s[4] != kFinSig4 || - s[5] != kFinSig5) - return S_FALSE; - - wasFinished = true; - return (crc == CombinedCrc.GetDigest()) ? S_OK : S_FALSE; - } - if (s[0] != kBlockSig0 || - s[1] != kBlockSig1 || - s[2] != kBlockSig2 || - s[3] != kBlockSig3 || - s[4] != kBlockSig4 || - s[5] != kBlockSig5) - return S_FALSE; - CombinedCrc.Update(crc); - return S_OK; -} - -HRESULT CDecoder::DecodeFile(bool &isBZ, ICompressProgressInfo *progress) -{ - #ifdef COMPRESS_BZIP2_MT - Progress = progress; - RINOK(Create()); - for (UInt32 t = 0; t < NumThreads; t++) - { - CState &s = m_States[t]; - if (!s.Alloc()) - return E_OUTOFMEMORY; - if (MtMode) - { - RINOK(s.StreamWasFinishedEvent.Reset()); - RINOK(s.WaitingWasStartedEvent.Reset()); - RINOK(s.CanWriteEvent.Reset()); - } - } - #else - if (!m_States[0].Alloc()) - return E_OUTOFMEMORY; - #endif - - isBZ = false; - Byte s[6]; - int i; - for (i = 0; i < 4; i++) - s[i] = ReadByte(); - if (s[0] != kArSig0 || - s[1] != kArSig1 || - s[2] != kArSig2 || - s[3] <= kArSig3 || - s[3] > kArSig3 + kBlockSizeMultMax) - return S_OK; - isBZ = true; - UInt32 dicSize = (UInt32)(s[3] - kArSig3) * kBlockSizeStep; - - CombinedCrc.Init(); - #ifdef COMPRESS_BZIP2_MT - if (MtMode) - { - NextBlockIndex = 0; - StreamWasFinished1 = StreamWasFinished2 = false; - CloseThreads = false; - CanStartWaitingEvent.Reset(); - m_States[0].CanWriteEvent.Set(); - BlockSizeMax = dicSize; - Result1 = Result2 = S_OK; - CanProcessEvent.Set(); - UInt32 t; - for (t = 0; t < NumThreads; t++) - m_States[t].StreamWasFinishedEvent.Lock(); - CanProcessEvent.Reset(); - CanStartWaitingEvent.Set(); - for (t = 0; t < NumThreads; t++) - m_States[t].WaitingWasStartedEvent.Lock(); - CanStartWaitingEvent.Reset(); - RINOK(Result2); - RINOK(Result1); - } - else - #endif - { - CState &state = m_States[0]; - for (;;) - { - if (progress) - { - UInt64 packSize = m_InStream.GetProcessedSize(); - UInt64 unpackSize = m_OutStream.GetProcessedSize(); - RINOK(progress->SetRatioInfo(&packSize, &unpackSize)); - } - bool wasFinished; - UInt32 crc; - RINOK(ReadSignatures(wasFinished, crc)); - if (wasFinished) - return S_OK; - - UInt32 blockSize, origPtr; - bool randMode; - RINOK(ReadBlock(&m_InStream, state.Counters, dicSize, - m_Selectors, m_HuffmanDecoders, - &blockSize, &origPtr, &randMode)); - DecodeBlock1(state.Counters, blockSize); - if ((randMode ? - DecodeBlock2Rand(state.Counters + 256, blockSize, origPtr, m_OutStream) : - DecodeBlock2(state.Counters + 256, blockSize, origPtr, m_OutStream)) != crc) - return S_FALSE; - } - } - return S_OK; -} - -HRESULT CDecoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 * /* inSize */, const UInt64 * /* outSize */, ICompressProgressInfo *progress) -{ - if (!m_InStream.Create(kBufferSize)) - return E_OUTOFMEMORY; - if (!m_OutStream.Create(kBufferSize)) - return E_OUTOFMEMORY; - - m_InStream.SetStream(inStream); - m_InStream.Init(); - - m_OutStream.SetStream(outStream); - m_OutStream.Init(); - - CDecoderFlusher flusher(this); - - bool isBZ; - RINOK(DecodeFile(isBZ, progress)); - return isBZ ? S_OK: S_FALSE; -} - -STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) -{ - try { return CodeReal(inStream, outStream, inSize, outSize, progress); } - catch(const CInBufferException &e) { return e.ErrorCode; } - catch(const COutBufferException &e) { return e.ErrorCode; } - catch(...) { return E_FAIL; } -} - -STDMETHODIMP CDecoder::GetInStreamProcessedSize(UInt64 *value) -{ - if (value == NULL) - return E_INVALIDARG; - *value = m_InStream.GetProcessedSize(); - return S_OK; -} - -#ifdef COMPRESS_BZIP2_MT - -static THREAD_FUNC_DECL MFThread(void *p) { ((CState *)p)->ThreadFunc(); return 0; } - -HRESULT CState::Create() -{ - RINOK_THREAD(StreamWasFinishedEvent.CreateIfNotCreated()); - RINOK_THREAD(WaitingWasStartedEvent.CreateIfNotCreated()); - RINOK_THREAD(CanWriteEvent.CreateIfNotCreated()); - RINOK_THREAD(Thread.Create(MFThread, this)); - return S_OK; -} - -void CState::FinishStream() -{ - Decoder->StreamWasFinished1 = true; - StreamWasFinishedEvent.Set(); - Decoder->CS.Leave(); - Decoder->CanStartWaitingEvent.Lock(); - WaitingWasStartedEvent.Set(); -} - -void CState::ThreadFunc() -{ - for (;;) - { - Decoder->CanProcessEvent.Lock(); - Decoder->CS.Enter(); - if (Decoder->CloseThreads) - { - Decoder->CS.Leave(); - return; - } - if (Decoder->StreamWasFinished1) - { - FinishStream(); - continue; - } - HRESULT res = S_OK; - - UInt32 blockIndex = Decoder->NextBlockIndex; - UInt32 nextBlockIndex = blockIndex + 1; - if (nextBlockIndex == Decoder->NumThreads) - nextBlockIndex = 0; - Decoder->NextBlockIndex = nextBlockIndex; - UInt32 crc; - UInt64 packSize; - UInt32 blockSize = 0, origPtr = 0; - bool randMode = false; - - try - { - bool wasFinished; - res = Decoder->ReadSignatures(wasFinished, crc); - if (res != S_OK) - { - Decoder->Result1 = res; - FinishStream(); - continue; - } - if (wasFinished) - { - Decoder->Result1 = res; - FinishStream(); - continue; - } - - res = ReadBlock(&Decoder->m_InStream, Counters, Decoder->BlockSizeMax, - Decoder->m_Selectors, Decoder->m_HuffmanDecoders, - &blockSize, &origPtr, &randMode); - if (res != S_OK) - { - Decoder->Result1 = res; - FinishStream(); - continue; - } - packSize = Decoder->m_InStream.GetProcessedSize(); - } - catch(const CInBufferException &e) { res = e.ErrorCode; if (res != S_OK) res = E_FAIL; } - catch(...) { res = E_FAIL; } - if (res != S_OK) - { - Decoder->Result1 = res; - FinishStream(); - continue; - } - - Decoder->CS.Leave(); - - DecodeBlock1(Counters, blockSize); - - bool needFinish = true; - try - { - Decoder->m_States[blockIndex].CanWriteEvent.Lock(); - needFinish = Decoder->StreamWasFinished2; - if (!needFinish) - { - if ((randMode ? - DecodeBlock2Rand(Counters + 256, blockSize, origPtr, Decoder->m_OutStream) : - DecodeBlock2(Counters + 256, blockSize, origPtr, Decoder->m_OutStream)) == crc) - { - if (Decoder->Progress) - { - UInt64 unpackSize = Decoder->m_OutStream.GetProcessedSize(); - res = Decoder->Progress->SetRatioInfo(&packSize, &unpackSize); - } - } - else - res = S_FALSE; - } - } - catch(const COutBufferException &e) { res = e.ErrorCode; if (res != S_OK) res = E_FAIL; } - catch(...) { res = E_FAIL; } - if (res != S_OK) - { - Decoder->Result2 = res; - Decoder->StreamWasFinished2 = true; - } - Decoder->m_States[nextBlockIndex].CanWriteEvent.Set(); - if (res != S_OK || needFinish) - { - StreamWasFinishedEvent.Set(); - Decoder->CanStartWaitingEvent.Lock(); - WaitingWasStartedEvent.Set(); - } - } -} - -STDMETHODIMP CDecoder::SetNumberOfThreads(UInt32 numThreads) -{ - NumThreads = numThreads; - if (NumThreads < 1) - NumThreads = 1; - if (NumThreads > kNumThreadsMax) - NumThreads = kNumThreadsMax; - return S_OK; -} -#endif - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/BZip2Decoder.h b/desmume/src/windows/7z/CPP/7zip/Compress/BZip2Decoder.h deleted file mode 100644 index 394860071..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/BZip2Decoder.h +++ /dev/null @@ -1,159 +0,0 @@ -// Compress/BZip2Decoder.h - -#ifndef __COMPRESS_BZIP2_DECODER_H -#define __COMPRESS_BZIP2_DECODER_H - -#include "../../Common/MyCom.h" - -#ifdef COMPRESS_BZIP2_MT -#include "../../Windows/Synchronization.h" -#include "../../Windows/Thread.h" -#endif - -#include "../ICoder.h" - -#include "../Common/InBuffer.h" -#include "../Common/OutBuffer.h" - -#include "BitmDecoder.h" -#include "BZip2Const.h" -#include "BZip2Crc.h" -#include "HuffmanDecoder.h" - -namespace NCompress { -namespace NBZip2 { - -typedef NCompress::NHuffman::CDecoder CHuffmanDecoder; - -class CDecoder; - -struct CState -{ - UInt32 *Counters; - - #ifdef COMPRESS_BZIP2_MT - - CDecoder *Decoder; - NWindows::CThread Thread; - bool m_OptimizeNumTables; - - NWindows::NSynchronization::CAutoResetEvent StreamWasFinishedEvent; - NWindows::NSynchronization::CAutoResetEvent WaitingWasStartedEvent; - - // it's not member of this thread. We just need one event per thread - NWindows::NSynchronization::CAutoResetEvent CanWriteEvent; - - Byte MtPad[1 << 8]; // It's pad for Multi-Threading. Must be >= Cache_Line_Size. - - HRESULT Create(); - void FinishStream(); - void ThreadFunc(); - - #endif - - CState(): Counters(0) {} - ~CState() { Free(); } - bool Alloc(); - void Free(); -}; - -class CDecoder : - public ICompressCoder, - #ifdef COMPRESS_BZIP2_MT - public ICompressSetCoderMt, - #endif - public ICompressGetInStreamProcessedSize, - public CMyUnknownImp -{ -public: - COutBuffer m_OutStream; - Byte MtPad[1 << 8]; // It's pad for Multi-Threading. Must be >= Cache_Line_Size. - NBitm::CDecoder m_InStream; - Byte m_Selectors[kNumSelectorsMax]; - CHuffmanDecoder m_HuffmanDecoders[kNumTablesMax]; -private: - - UInt32 m_NumThreadsPrev; - - UInt32 ReadBits(int numBits); - Byte ReadByte(); - bool ReadBit(); - UInt32 ReadCrc(); - HRESULT PrepareBlock(CState &state); - HRESULT DecodeFile(bool &isBZ, ICompressProgressInfo *progress); - HRESULT CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - class CDecoderFlusher - { - CDecoder *_decoder; - public: - bool NeedFlush; - CDecoderFlusher(CDecoder *decoder): _decoder(decoder), NeedFlush(true) {} - ~CDecoderFlusher() - { - if (NeedFlush) - _decoder->Flush(); - _decoder->ReleaseStreams(); - } - }; - -public: - CBZip2CombinedCrc CombinedCrc; - - #ifdef COMPRESS_BZIP2_MT - ICompressProgressInfo *Progress; - CState *m_States; - - NWindows::NSynchronization::CManualResetEvent CanProcessEvent; - NWindows::NSynchronization::CCriticalSection CS; - UInt32 NumThreads; - bool MtMode; - UInt32 NextBlockIndex; - bool CloseThreads; - bool StreamWasFinished1; - bool StreamWasFinished2; - NWindows::NSynchronization::CManualResetEvent CanStartWaitingEvent; - - HRESULT Result1; - HRESULT Result2; - - UInt32 BlockSizeMax; - CDecoder(); - ~CDecoder(); - HRESULT Create(); - void Free(); - - #else - CState m_States[1]; - #endif - - HRESULT ReadSignatures(bool &wasFinished, UInt32 &crc); - - - HRESULT Flush() { return m_OutStream.Flush(); } - void ReleaseStreams() - { - m_InStream.ReleaseStream(); - m_OutStream.ReleaseStream(); - } - - #ifdef COMPRESS_BZIP2_MT - MY_UNKNOWN_IMP2(ICompressSetCoderMt, ICompressGetInStreamProcessedSize) - #else - MY_UNKNOWN_IMP1(ICompressGetInStreamProcessedSize) - #endif - - - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - - STDMETHOD(GetInStreamProcessedSize)(UInt64 *value); - - #ifdef COMPRESS_BZIP2_MT - STDMETHOD(SetNumberOfThreads)(UInt32 numThreads); - #endif -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/BZip2Register.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/BZip2Register.cpp deleted file mode 100644 index f10e594c6..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/BZip2Register.cpp +++ /dev/null @@ -1,20 +0,0 @@ -// BZip2Register.cpp - -#include "StdAfx.h" - -#include "../Common/RegisterCodec.h" - -#include "BZip2Decoder.h" - -static void *CreateCodec() { return (void *)(ICompressCoder *)(new NCompress::NBZip2::CDecoder); } -#if !defined(EXTRACT_ONLY) && !defined(BZIP2_EXTRACT_ONLY) -#include "BZip2Encoder.h" -static void *CreateCodecOut() { return (void *)(ICompressCoder *)(new NCompress::NBZip2::CEncoder); } -#else -#define CreateCodecOut 0 -#endif - -static CCodecInfo g_CodecInfo = - { CreateCodec, CreateCodecOut, 0x040202, L"BZip2", 1, false }; - -REGISTER_CODEC(BZip2) diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/Bcj2Coder.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/Bcj2Coder.cpp deleted file mode 100644 index e52095a77..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/Bcj2Coder.cpp +++ /dev/null @@ -1,393 +0,0 @@ -// Bcj2Coder.cpp - -#include "StdAfx.h" - -extern "C" -{ -#include "../../../C/Alloc.h" -} - -#include "Bcj2Coder.h" - -namespace NCompress { -namespace NBcj2 { - -inline bool IsJcc(Byte b0, Byte b1) { return (b0 == 0x0F && (b1 & 0xF0) == 0x80); } -inline bool IsJ(Byte b0, Byte b1) { return ((b1 & 0xFE) == 0xE8 || IsJcc(b0, b1)); } -inline unsigned GetIndex(Byte b0, Byte b1) { return ((b1 == 0xE8) ? b0 : ((b1 == 0xE9) ? 256 : 257)); } - -#ifndef EXTRACT_ONLY - -static const int kBufferSize = 1 << 17; - -static bool inline Test86MSByte(Byte b) -{ - return (b == 0 || b == 0xFF); -} - -bool CEncoder::Create() -{ - if (!_mainStream.Create(1 << 16)) - return false; - if (!_callStream.Create(1 << 20)) - return false; - if (!_jumpStream.Create(1 << 20)) - return false; - if (!_rangeEncoder.Create(1 << 20)) - return false; - if (_buffer == 0) - { - _buffer = (Byte *)MidAlloc(kBufferSize); - if (_buffer == 0) - return false; - } - return true; -} - -CEncoder::~CEncoder() -{ - ::MidFree(_buffer); -} - -HRESULT CEncoder::Flush() -{ - RINOK(_mainStream.Flush()); - RINOK(_callStream.Flush()); - RINOK(_jumpStream.Flush()); - _rangeEncoder.FlushData(); - return _rangeEncoder.FlushStream(); -} - -const UInt32 kDefaultLimit = (1 << 24); - -HRESULT CEncoder::CodeReal(ISequentialInStream **inStreams, - const UInt64 **inSizes, - UInt32 numInStreams, - ISequentialOutStream **outStreams, - const UInt64 ** /* outSizes */, - UInt32 numOutStreams, - ICompressProgressInfo *progress) -{ - if (numInStreams != 1 || numOutStreams != 4) - return E_INVALIDARG; - - if (!Create()) - return E_OUTOFMEMORY; - - bool sizeIsDefined = false; - UInt64 inSize = 0; - if (inSizes != NULL) - if (inSizes[0] != NULL) - { - inSize = *inSizes[0]; - if (inSize <= kDefaultLimit) - sizeIsDefined = true; - } - - ISequentialInStream *inStream = inStreams[0]; - - _mainStream.SetStream(outStreams[0]); - _mainStream.Init(); - _callStream.SetStream(outStreams[1]); - _callStream.Init(); - _jumpStream.SetStream(outStreams[2]); - _jumpStream.Init(); - _rangeEncoder.SetStream(outStreams[3]); - _rangeEncoder.Init(); - for (int i = 0; i < 256 + 2; i++) - _statusEncoder[i].Init(); - CCoderReleaser releaser(this); - - CMyComPtr getSubStreamSize; - { - inStream->QueryInterface(IID_ICompressGetSubStreamSize, (void **)&getSubStreamSize); - } - - UInt32 nowPos = 0; - UInt64 nowPos64 = 0; - UInt32 bufferPos = 0; - - Byte prevByte = 0; - - UInt64 subStreamIndex = 0; - UInt64 subStreamStartPos = 0; - UInt64 subStreamEndPos = 0; - - for (;;) - { - UInt32 processedSize = 0; - for (;;) - { - UInt32 size = kBufferSize - (bufferPos + processedSize); - UInt32 processedSizeLoc; - if (size == 0) - break; - RINOK(inStream->Read(_buffer + bufferPos + processedSize, size, &processedSizeLoc)); - if (processedSizeLoc == 0) - break; - processedSize += processedSizeLoc; - } - UInt32 endPos = bufferPos + processedSize; - - if (endPos < 5) - { - // change it - for (bufferPos = 0; bufferPos < endPos; bufferPos++) - { - Byte b = _buffer[bufferPos]; - _mainStream.WriteByte(b); - UInt32 index; - if (b == 0xE8) - index = prevByte; - else if (b == 0xE9) - index = 256; - else if (IsJcc(prevByte, b)) - index = 257; - else - { - prevByte = b; - continue; - } - _statusEncoder[index].Encode(&_rangeEncoder, 0); - prevByte = b; - } - return Flush(); - } - - bufferPos = 0; - - UInt32 limit = endPos - 5; - while(bufferPos <= limit) - { - Byte b = _buffer[bufferPos]; - _mainStream.WriteByte(b); - if (!IsJ(prevByte, b)) - { - bufferPos++; - prevByte = b; - continue; - } - Byte nextByte = _buffer[bufferPos + 4]; - UInt32 src = - (UInt32(nextByte) << 24) | - (UInt32(_buffer[bufferPos + 3]) << 16) | - (UInt32(_buffer[bufferPos + 2]) << 8) | - (_buffer[bufferPos + 1]); - UInt32 dest = (nowPos + bufferPos + 5) + src; - // if (Test86MSByte(nextByte)) - bool convert; - if (getSubStreamSize != NULL) - { - UInt64 currentPos = (nowPos64 + bufferPos); - while (subStreamEndPos < currentPos) - { - UInt64 subStreamSize; - HRESULT result = getSubStreamSize->GetSubStreamSize(subStreamIndex, &subStreamSize); - if (result == S_OK) - { - subStreamStartPos = subStreamEndPos; - subStreamEndPos += subStreamSize; - subStreamIndex++; - } - else if (result == S_FALSE || result == E_NOTIMPL) - { - getSubStreamSize.Release(); - subStreamStartPos = 0; - subStreamEndPos = subStreamStartPos - 1; - } - else - return result; - } - if (getSubStreamSize == NULL) - { - if (sizeIsDefined) - convert = (dest < inSize); - else - convert = Test86MSByte(nextByte); - } - else if (subStreamEndPos - subStreamStartPos > kDefaultLimit) - convert = Test86MSByte(nextByte); - else - { - UInt64 dest64 = (currentPos + 5) + Int64(Int32(src)); - convert = (dest64 >= subStreamStartPos && dest64 < subStreamEndPos); - } - } - else if (sizeIsDefined) - convert = (dest < inSize); - else - convert = Test86MSByte(nextByte); - unsigned index = GetIndex(prevByte, b); - if (convert) - { - _statusEncoder[index].Encode(&_rangeEncoder, 1); - bufferPos += 5; - COutBuffer &s = (b == 0xE8) ? _callStream : _jumpStream; - for (int i = 24; i >= 0; i -= 8) - s.WriteByte((Byte)(dest >> i)); - prevByte = nextByte; - } - else - { - _statusEncoder[index].Encode(&_rangeEncoder, 0); - bufferPos++; - prevByte = b; - } - } - nowPos += bufferPos; - nowPos64 += bufferPos; - - if (progress != NULL) - { - /* - const UInt64 compressedSize = - _mainStream.GetProcessedSize() + - _callStream.GetProcessedSize() + - _jumpStream.GetProcessedSize() + - _rangeEncoder.GetProcessedSize(); - */ - RINOK(progress->SetRatioInfo(&nowPos64, NULL)); - } - - UInt32 i = 0; - while(bufferPos < endPos) - _buffer[i++] = _buffer[bufferPos++]; - bufferPos = i; - } -} - -STDMETHODIMP CEncoder::Code(ISequentialInStream **inStreams, - const UInt64 **inSizes, - UInt32 numInStreams, - ISequentialOutStream **outStreams, - const UInt64 **outSizes, - UInt32 numOutStreams, - ICompressProgressInfo *progress) -{ - try - { - return CodeReal(inStreams, inSizes, numInStreams, - outStreams, outSizes,numOutStreams, progress); - } - catch(const COutBufferException &e) { return e.ErrorCode; } - catch(...) { return S_FALSE; } -} - -#endif - -HRESULT CDecoder::CodeReal(ISequentialInStream **inStreams, - const UInt64 ** /* inSizes */, - UInt32 numInStreams, - ISequentialOutStream **outStreams, - const UInt64 ** /* outSizes */, - UInt32 numOutStreams, - ICompressProgressInfo *progress) -{ - if (numInStreams != 4 || numOutStreams != 1) - return E_INVALIDARG; - - if (!_mainInStream.Create(1 << 16)) - return E_OUTOFMEMORY; - if (!_callStream.Create(1 << 20)) - return E_OUTOFMEMORY; - if (!_jumpStream.Create(1 << 16)) - return E_OUTOFMEMORY; - if (!_rangeDecoder.Create(1 << 20)) - return E_OUTOFMEMORY; - if (!_outStream.Create(1 << 16)) - return E_OUTOFMEMORY; - - _mainInStream.SetStream(inStreams[0]); - _callStream.SetStream(inStreams[1]); - _jumpStream.SetStream(inStreams[2]); - _rangeDecoder.SetStream(inStreams[3]); - _outStream.SetStream(outStreams[0]); - - _mainInStream.Init(); - _callStream.Init(); - _jumpStream.Init(); - _rangeDecoder.Init(); - _outStream.Init(); - - for (int i = 0; i < 256 + 2; i++) - _statusDecoder[i].Init(); - - CCoderReleaser releaser(this); - - Byte prevByte = 0; - UInt32 processedBytes = 0; - for (;;) - { - if (processedBytes >= (1 << 20) && progress != NULL) - { - /* - const UInt64 compressedSize = - _mainInStream.GetProcessedSize() + - _callStream.GetProcessedSize() + - _jumpStream.GetProcessedSize() + - _rangeDecoder.GetProcessedSize(); - */ - const UInt64 nowPos64 = _outStream.GetProcessedSize(); - RINOK(progress->SetRatioInfo(NULL, &nowPos64)); - processedBytes = 0; - } - UInt32 i; - Byte b = 0; - const UInt32 kBurstSize = (1 << 18); - for (i = 0; i < kBurstSize; i++) - { - if (!_mainInStream.ReadByte(b)) - return Flush(); - _outStream.WriteByte(b); - if (IsJ(prevByte, b)) - break; - prevByte = b; - } - processedBytes += i; - if (i == kBurstSize) - continue; - unsigned index = GetIndex(prevByte, b); - if (_statusDecoder[index].Decode(&_rangeDecoder) == 1) - { - UInt32 src = 0; - CInBuffer &s = (b == 0xE8) ? _callStream : _jumpStream; - for (int i = 0; i < 4; i++) - { - Byte b0; - if(!s.ReadByte(b0)) - return S_FALSE; - src <<= 8; - src |= ((UInt32)b0); - } - UInt32 dest = src - (UInt32(_outStream.GetProcessedSize()) + 4) ; - _outStream.WriteByte((Byte)(dest)); - _outStream.WriteByte((Byte)(dest >> 8)); - _outStream.WriteByte((Byte)(dest >> 16)); - _outStream.WriteByte((Byte)(dest >> 24)); - prevByte = (Byte)(dest >> 24); - processedBytes += 4; - } - else - prevByte = b; - } -} - -STDMETHODIMP CDecoder::Code(ISequentialInStream **inStreams, - const UInt64 **inSizes, - UInt32 numInStreams, - ISequentialOutStream **outStreams, - const UInt64 **outSizes, - UInt32 numOutStreams, - ICompressProgressInfo *progress) -{ - try - { - return CodeReal(inStreams, inSizes, numInStreams, - outStreams, outSizes,numOutStreams, progress); - } - catch(const CInBufferException &e) { return e.ErrorCode; } - catch(const COutBufferException &e) { return e.ErrorCode; } - catch(...) { return S_FALSE; } -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/Bcj2Coder.h b/desmume/src/windows/7z/CPP/7zip/Compress/Bcj2Coder.h deleted file mode 100644 index fcbc2a411..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/Bcj2Coder.h +++ /dev/null @@ -1,125 +0,0 @@ -// Bcj2Coder.h - -#ifndef __COMPRESS_BCJ2_CODER_H -#define __COMPRESS_BCJ2_CODER_H - -#include "../../Common/MyCom.h" - -#include "../ICoder.h" - -#include "RangeCoderBit.h" - -namespace NCompress { -namespace NBcj2 { - -const int kNumMoveBits = 5; - -#ifndef EXTRACT_ONLY - -class CEncoder: - public ICompressCoder2, - public CMyUnknownImp -{ - Byte *_buffer; -public: - CEncoder(): _buffer(0) {}; - ~CEncoder(); - bool Create(); - - COutBuffer _mainStream; - COutBuffer _callStream; - COutBuffer _jumpStream; - NCompress::NRangeCoder::CEncoder _rangeEncoder; - NCompress::NRangeCoder::CBitEncoder _statusEncoder[256 + 2]; - - HRESULT Flush(); - void ReleaseStreams() - { - _mainStream.ReleaseStream(); - _callStream.ReleaseStream(); - _jumpStream.ReleaseStream(); - _rangeEncoder.ReleaseStream(); - } - - class CCoderReleaser - { - CEncoder *_coder; - public: - CCoderReleaser(CEncoder *coder): _coder(coder) {} - ~CCoderReleaser() { _coder->ReleaseStreams(); } - }; - -public: - - MY_UNKNOWN_IMP - - HRESULT CodeReal(ISequentialInStream **inStreams, - const UInt64 **inSizes, - UInt32 numInStreams, - ISequentialOutStream **outStreams, - const UInt64 **outSizes, - UInt32 numOutStreams, - ICompressProgressInfo *progress); - STDMETHOD(Code)(ISequentialInStream **inStreams, - const UInt64 **inSizes, - UInt32 numInStreams, - ISequentialOutStream **outStreams, - const UInt64 **outSizes, - UInt32 numOutStreams, - ICompressProgressInfo *progress); -}; - -#endif - -class CDecoder: - public ICompressCoder2, - public CMyUnknownImp -{ -public: - CInBuffer _mainInStream; - CInBuffer _callStream; - CInBuffer _jumpStream; - NCompress::NRangeCoder::CDecoder _rangeDecoder; - NCompress::NRangeCoder::CBitDecoder _statusDecoder[256 + 2]; - - COutBuffer _outStream; - - void ReleaseStreams() - { - _mainInStream.ReleaseStream(); - _callStream.ReleaseStream(); - _jumpStream.ReleaseStream(); - _rangeDecoder.ReleaseStream(); - _outStream.ReleaseStream(); - } - - HRESULT Flush() { return _outStream.Flush(); } - class CCoderReleaser - { - CDecoder *_coder; - public: - CCoderReleaser(CDecoder *coder): _coder(coder) {} - ~CCoderReleaser() { _coder->ReleaseStreams(); } - }; - -public: - MY_UNKNOWN_IMP - HRESULT CodeReal(ISequentialInStream **inStreams, - const UInt64 **inSizes, - UInt32 numInStreams, - ISequentialOutStream **outStreams, - const UInt64 **outSizes, - UInt32 numOutStreams, - ICompressProgressInfo *progress); - STDMETHOD(Code)(ISequentialInStream **inStreams, - const UInt64 **inSizes, - UInt32 numInStreams, - ISequentialOutStream **outStreams, - const UInt64 **outSizes, - UInt32 numOutStreams, - ICompressProgressInfo *progress); -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/Bcj2Register.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/Bcj2Register.cpp deleted file mode 100644 index b063f3f69..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/Bcj2Register.cpp +++ /dev/null @@ -1,19 +0,0 @@ -// Bcj2Register.cpp - -#include "StdAfx.h" - -#include "../Common/RegisterCodec.h" - -#include "Bcj2Coder.h" - -static void *CreateCodec() { return (void *)(ICompressCoder2 *)(new NCompress::NBcj2::CDecoder()); } -#ifndef EXTRACT_ONLY -static void *CreateCodecOut() { return (void *)(ICompressCoder2 *)(new NCompress::NBcj2::CEncoder()); } -#else -#define CreateCodecOut 0 -#endif - -static CCodecInfo g_CodecInfo = - { CreateCodec, CreateCodecOut, 0x0303011B, L"BCJ2", 4, false }; - -REGISTER_CODEC(BCJ2) diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/BcjCoder.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/BcjCoder.cpp deleted file mode 100644 index 108c573d5..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/BcjCoder.cpp +++ /dev/null @@ -1,15 +0,0 @@ -// BcjCoder.cpp - -#include "StdAfx.h" - -#include "BcjCoder.h" - -UInt32 CBCJ_x86_Encoder::SubFilter(Byte *data, UInt32 size) -{ - return (UInt32)::x86_Convert(data, size, _bufferPos, &_prevMask, 1); -} - -UInt32 CBCJ_x86_Decoder::SubFilter(Byte *data, UInt32 size) -{ - return (UInt32)::x86_Convert(data, size, _bufferPos, &_prevMask, 0); -} diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/BcjCoder.h b/desmume/src/windows/7z/CPP/7zip/Compress/BcjCoder.h deleted file mode 100644 index 3389b2092..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/BcjCoder.h +++ /dev/null @@ -1,22 +0,0 @@ -// BcjCoder.h - -#ifndef __COMPRESS_BCJ_CODER_H -#define __COMPRESS_BCJ_CODER_H - -extern "C" -{ -#include "../../../C/Bra.h" -} - -#include "BranchCoder.h" - -struct CBranch86 -{ - UInt32 _prevMask; - void x86Init() { x86_Convert_Init(_prevMask); } -}; - -MyClassB(BCJ_x86, 0x01, 3, CBranch86 , - virtual void SubInit() { x86Init(); }) - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/BcjRegister.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/BcjRegister.cpp deleted file mode 100644 index 09e53c655..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/BcjRegister.cpp +++ /dev/null @@ -1,19 +0,0 @@ -// BcjRegister.cpp - -#include "StdAfx.h" - -#include "../Common/RegisterCodec.h" - -#include "BcjCoder.h" - -static void *CreateCodec() { return (void *)(ICompressFilter *)(new CBCJ_x86_Decoder()); } -#ifndef EXTRACT_ONLY -static void *CreateCodecOut() { return (void *)(ICompressFilter *)(new CBCJ_x86_Encoder()); } -#else -#define CreateCodecOut 0 -#endif - -static CCodecInfo g_CodecInfo = - { CreateCodec, CreateCodecOut, 0x03030103, L"BCJ", 1, true }; - -REGISTER_CODEC(BCJ) diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/BitlDecoder.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/BitlDecoder.cpp deleted file mode 100644 index 6022e8bf5..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/BitlDecoder.cpp +++ /dev/null @@ -1,24 +0,0 @@ -// BitlDecoder.cpp - -#include "StdAfx.h" - -#include "BitlDecoder.h" - -namespace NBitl { - -Byte kInvertTable[256]; - -struct CInverterTableInitializer -{ - CInverterTableInitializer() - { - for (int i = 0; i < 256; i++) - { - int x = ((i & 0x55) << 1) | ((i & 0xAA) >> 1); - x = ((x & 0x33) << 2) | ((x & 0xCC) >> 2); - kInvertTable[i] = (Byte)(((x & 0x0F) << 4) | ((x & 0xF0) >> 4)); - } - } -} g_InverterTableInitializer; - -} diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/BitlDecoder.h b/desmume/src/windows/7z/CPP/7zip/Compress/BitlDecoder.h deleted file mode 100644 index f2e115d48..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/BitlDecoder.h +++ /dev/null @@ -1,125 +0,0 @@ -// BitlDecoder.h -- the Least Significant Bit of byte is First - -#ifndef __BITL_DECODER_H -#define __BITL_DECODER_H - -#include "../IStream.h" - -namespace NBitl { - -const int kNumBigValueBits = 8 * 4; - -const int kNumValueBytes = 3; -const int kNumValueBits = 8 * kNumValueBytes; - -const UInt32 kMask = (1 << kNumValueBits) - 1; - -extern Byte kInvertTable[256]; - -template -class CBaseDecoder -{ -protected: - int m_BitPos; - UInt32 m_Value; - TInByte m_Stream; -public: - UInt32 NumExtraBytes; - bool Create(UInt32 bufferSize) { return m_Stream.Create(bufferSize); } - void SetStream(ISequentialInStream *inStream) { m_Stream.SetStream(inStream); } - void ReleaseStream() { m_Stream.ReleaseStream(); } - void Init() - { - m_Stream.Init(); - m_BitPos = kNumBigValueBits; - m_Value = 0; - NumExtraBytes = 0; - } - UInt64 GetProcessedSize() const - { return m_Stream.GetProcessedSize() - (kNumBigValueBits - m_BitPos) / 8; } - UInt64 GetProcessedBitsSize() const - { return (m_Stream.GetProcessedSize() << 3) - (kNumBigValueBits - m_BitPos); } - int GetBitPosition() const { return (m_BitPos & 7); } - - void Normalize() - { - for (;m_BitPos >= 8; m_BitPos -= 8) - { - Byte b = 0; - if (!m_Stream.ReadByte(b)) - { - b = 0xFF; // check it - NumExtraBytes++; - } - m_Value = (b << (kNumBigValueBits - m_BitPos)) | m_Value; - } - } - - UInt32 ReadBits(int numBits) - { - Normalize(); - UInt32 res = m_Value & ((1 << numBits) - 1); - m_BitPos += numBits; - m_Value >>= numBits; - return res; - } - - bool ExtraBitsWereRead() const - { - if (NumExtraBytes == 0) - return false; - return ((UInt32)(kNumBigValueBits - m_BitPos) < (NumExtraBytes << 3)); - } -}; - -template -class CDecoder: public CBaseDecoder -{ - UInt32 m_NormalValue; - -public: - void Init() - { - CBaseDecoder::Init(); - m_NormalValue = 0; - } - - void Normalize() - { - for (; this->m_BitPos >= 8; this->m_BitPos -= 8) - { - Byte b = 0; - if (!this->m_Stream.ReadByte(b)) - { - b = 0xFF; // check it - this->NumExtraBytes++; - } - m_NormalValue = (b << (kNumBigValueBits - this->m_BitPos)) | m_NormalValue; - this->m_Value = (this->m_Value << 8) | kInvertTable[b]; - } - } - - UInt32 GetValue(int numBits) - { - Normalize(); - return ((this->m_Value >> (8 - this->m_BitPos)) & kMask) >> (kNumValueBits - numBits); - } - - void MovePos(int numBits) - { - this->m_BitPos += numBits; - m_NormalValue >>= numBits; - } - - UInt32 ReadBits(int numBits) - { - Normalize(); - UInt32 res = m_NormalValue & ( (1 << numBits) - 1); - MovePos(numBits); - return res; - } -}; - -} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/BitmDecoder.h b/desmume/src/windows/7z/CPP/7zip/Compress/BitmDecoder.h deleted file mode 100644 index f58ec29e5..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/BitmDecoder.h +++ /dev/null @@ -1,66 +0,0 @@ -// BitmDecoder.h -- the Most Significant Bit of byte is First - -#ifndef __BITM_DECODER_H -#define __BITM_DECODER_H - -#include "../IStream.h" - -namespace NBitm { - -const int kNumBigValueBits = 8 * 4; -const int kNumValueBytes = 3; -const int kNumValueBits = 8 * kNumValueBytes; - -const UInt32 kMask = (1 << kNumValueBits) - 1; - -template -class CDecoder -{ - UInt32 m_BitPos; - UInt32 m_Value; -public: - TInByte m_Stream; - bool Create(UInt32 bufferSize) { return m_Stream.Create(bufferSize); } - void SetStream(ISequentialInStream *inStream) { m_Stream.SetStream(inStream);} - void ReleaseStream() { m_Stream.ReleaseStream();} - - void Init() - { - m_Stream.Init(); - m_BitPos = kNumBigValueBits; - Normalize(); - } - - UInt64 GetProcessedSize() const - { return m_Stream.GetProcessedSize() - (kNumBigValueBits - m_BitPos) / 8; } - UInt32 GetBitPosition() const { return (m_BitPos & 7); } - - void Normalize() - { - for (;m_BitPos >= 8; m_BitPos -= 8) - m_Value = (m_Value << 8) | m_Stream.ReadByte(); - } - - UInt32 GetValue(UInt32 numBits) const - { - // return (m_Value << m_BitPos) >> (kNumBigValueBits - numBits); - return ((m_Value >> (8 - m_BitPos)) & kMask) >> (kNumValueBits - numBits); - } - - void MovePos(UInt32 numBits) - { - m_BitPos += numBits; - Normalize(); - } - - UInt32 ReadBits(UInt32 numBits) - { - UInt32 res = GetValue(numBits); - MovePos(numBits); - return res; - } -}; - -} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/BranchCoder.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/BranchCoder.cpp deleted file mode 100644 index 6cacc66ac..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/BranchCoder.cpp +++ /dev/null @@ -1,19 +0,0 @@ -// BranchCoder.cpp - -#include "StdAfx.h" - -#include "BranchCoder.h" - -STDMETHODIMP CBranchConverter::Init() -{ - _bufferPos = 0; - SubInit(); - return S_OK; -} - -STDMETHODIMP_(UInt32) CBranchConverter::Filter(Byte *data, UInt32 size) -{ - UInt32 processedSize = SubFilter(data, size); - _bufferPos += processedSize; - return processedSize; -} diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/BranchCoder.h b/desmume/src/windows/7z/CPP/7zip/Compress/BranchCoder.h deleted file mode 100644 index 473286af3..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/BranchCoder.h +++ /dev/null @@ -1,44 +0,0 @@ -// BranchCoder.h - -#ifndef __COMPRESS_BRANCH_CODER_H -#define __COMPRESS_BRANCH_CODER_H - -#include "../../Common/MyCom.h" - -#include "../ICoder.h" - -class CBranchConverter: - public ICompressFilter, - public CMyUnknownImp -{ -protected: - UInt32 _bufferPos; - virtual void SubInit() {} - virtual UInt32 SubFilter(Byte *data, UInt32 size) = 0; -public: - MY_UNKNOWN_IMP; - STDMETHOD(Init)(); - STDMETHOD_(UInt32, Filter)(Byte *data, UInt32 size); -}; - -#define MyClassEncoderA(Name) class C ## Name: public CBranchConverter \ - { public: UInt32 SubFilter(Byte *data, UInt32 size); }; - -#define MyClassDecoderA(Name) class C ## Name: public CBranchConverter \ - { public: UInt32 SubFilter(Byte *data, UInt32 size); }; - -#define MyClassEncoderB(Name, ADD_ITEMS, ADD_INIT) class C ## Name: public CBranchConverter, public ADD_ITEMS \ - { public: UInt32 SubFilter(Byte *data, UInt32 size); ADD_INIT}; - -#define MyClassDecoderB(Name, ADD_ITEMS, ADD_INIT) class C ## Name: public CBranchConverter, public ADD_ITEMS \ - { public: UInt32 SubFilter(Byte *data, UInt32 size); ADD_INIT}; - -#define MyClassA(Name, id, subId) \ -MyClassEncoderA(Name ## _Encoder) \ -MyClassDecoderA(Name ## _Decoder) - -#define MyClassB(Name, id, subId, ADD_ITEMS, ADD_INIT) \ -MyClassEncoderB(Name ## _Encoder, ADD_ITEMS, ADD_INIT) \ -MyClassDecoderB(Name ## _Decoder, ADD_ITEMS, ADD_INIT) - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/BranchMisc.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/BranchMisc.cpp deleted file mode 100644 index 238dbe311..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/BranchMisc.cpp +++ /dev/null @@ -1,40 +0,0 @@ -// BranchMisc.cpp - -#include "StdAfx.h" - -extern "C" -{ -#include "../../../C/Bra.h" -} - -#include "BranchMisc.h" - -UInt32 CBC_ARM_Encoder::SubFilter(Byte *data, UInt32 size) - { return (UInt32)::ARM_Convert(data, size, _bufferPos, 1); } - -UInt32 CBC_ARM_Decoder::SubFilter(Byte *data, UInt32 size) - { return (UInt32)::ARM_Convert(data, size, _bufferPos, 0); } - -UInt32 CBC_ARMT_Encoder::SubFilter(Byte *data, UInt32 size) - { return (UInt32)::ARMT_Convert(data, size, _bufferPos, 1); } - -UInt32 CBC_ARMT_Decoder::SubFilter(Byte *data, UInt32 size) - { return (UInt32)::ARMT_Convert(data, size, _bufferPos, 0); } - -UInt32 CBC_PPC_Encoder::SubFilter(Byte *data, UInt32 size) - { return (UInt32)::PPC_Convert(data, size, _bufferPos, 1); } - -UInt32 CBC_PPC_Decoder::SubFilter(Byte *data, UInt32 size) - { return (UInt32)::PPC_Convert(data, size, _bufferPos, 0); } - -UInt32 CBC_SPARC_Encoder::SubFilter(Byte *data, UInt32 size) - { return (UInt32)::SPARC_Convert(data, size, _bufferPos, 1); } - -UInt32 CBC_SPARC_Decoder::SubFilter(Byte *data, UInt32 size) - { return (UInt32)::SPARC_Convert(data, size, _bufferPos, 0); } - -UInt32 CBC_IA64_Encoder::SubFilter(Byte *data, UInt32 size) - { return (UInt32)::IA64_Convert(data, size, _bufferPos, 1); } - -UInt32 CBC_IA64_Decoder::SubFilter(Byte *data, UInt32 size) - { return (UInt32)::IA64_Convert(data, size, _bufferPos, 0); } diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/BranchMisc.h b/desmume/src/windows/7z/CPP/7zip/Compress/BranchMisc.h deleted file mode 100644 index 053e923a9..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/BranchMisc.h +++ /dev/null @@ -1,14 +0,0 @@ -// BranchMisc.h - -#ifndef __COMPRESS_BRANCH_MISC_H -#define __COMPRESS_BRANCH_MISC_H - -#include "BranchCoder.h" - -MyClassA(BC_ARM, 0x05, 1) -MyClassA(BC_ARMT, 0x07, 1) -MyClassA(BC_PPC, 0x02, 5) -MyClassA(BC_SPARC, 0x08, 5) -MyClassA(BC_IA64, 0x04, 1) - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/BranchRegister.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/BranchRegister.cpp deleted file mode 100644 index bc55dd668..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/BranchRegister.cpp +++ /dev/null @@ -1,30 +0,0 @@ -// BranchRegister.cpp - -#include "StdAfx.h" - -#include "../Common/RegisterCodec.h" - -#include "BranchMisc.h" - -#define CREATE_CODEC(x) \ - static void *CreateCodec ## x() { return (void *)(ICompressFilter *)(new C ## x ## _Decoder); } \ - static void *CreateCodec ## x ## Out() { return (void *)(ICompressFilter *)(new C ## x ## _Encoder); } - -CREATE_CODEC(BC_PPC) -CREATE_CODEC(BC_IA64) -CREATE_CODEC(BC_ARM) -CREATE_CODEC(BC_ARMT) -CREATE_CODEC(BC_SPARC) - -#define METHOD_ITEM(x, id1, id2, name) { CreateCodec ## x, CreateCodec ## x ## Out, 0x03030000 + (id1 * 256) + id2, name, 1, true } - -static CCodecInfo g_CodecsInfo[] = -{ - METHOD_ITEM(BC_PPC, 0x02, 0x05, L"PPC"), - METHOD_ITEM(BC_IA64, 0x04, 1, L"IA64"), - METHOD_ITEM(BC_ARM, 0x05, 1, L"ARM"), - METHOD_ITEM(BC_ARMT, 0x07, 1, L"ARMT"), - METHOD_ITEM(BC_SPARC, 0x08, 0x05, L"SPARC") -}; - -REGISTER_CODECS(Branch) diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/ByteSwap.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/ByteSwap.cpp deleted file mode 100644 index f21a7acfe..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/ByteSwap.cpp +++ /dev/null @@ -1,38 +0,0 @@ -// ByteSwap.cpp - -#include "StdAfx.h" - -#include "ByteSwap.h" - -STDMETHODIMP CByteSwap2::Init() { return S_OK; } - -STDMETHODIMP_(UInt32) CByteSwap2::Filter(Byte *data, UInt32 size) -{ - const UInt32 kStep = 2; - UInt32 i; - for (i = 0; i + kStep <= size; i += kStep) - { - Byte b = data[i]; - data[i] = data[i + 1]; - data[i + 1] = b; - } - return i; -} - -STDMETHODIMP CByteSwap4::Init() { return S_OK; } - -STDMETHODIMP_(UInt32) CByteSwap4::Filter(Byte *data, UInt32 size) -{ - const UInt32 kStep = 4; - UInt32 i; - for (i = 0; i + kStep <= size; i += kStep) - { - Byte b0 = data[i]; - Byte b1 = data[i + 1]; - data[i] = data[i + 3]; - data[i + 1] = data[i + 2]; - data[i + 2] = b1; - data[i + 3] = b0; - } - return i; -} diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/ByteSwap.h b/desmume/src/windows/7z/CPP/7zip/Compress/ByteSwap.h deleted file mode 100644 index ecf983db4..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/ByteSwap.h +++ /dev/null @@ -1,30 +0,0 @@ -// ByteSwap.h - -#ifndef __COMPRESS_BYTE_SWAP_H -#define __COMPRESS_BYTE_SWAP_H - -#include "../../Common/MyCom.h" - -#include "../ICoder.h" - -class CByteSwap2: - public ICompressFilter, - public CMyUnknownImp -{ -public: - MY_UNKNOWN_IMP - STDMETHOD(Init)(); - STDMETHOD_(UInt32, Filter)(Byte *data, UInt32 size); -}; - -class CByteSwap4: - public ICompressFilter, - public CMyUnknownImp -{ -public: - MY_UNKNOWN_IMP - STDMETHOD(Init)(); - STDMETHOD_(UInt32, Filter)(Byte *data, UInt32 size); -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/ByteSwapRegister.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/ByteSwapRegister.cpp deleted file mode 100644 index c3413f67b..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/ByteSwapRegister.cpp +++ /dev/null @@ -1,18 +0,0 @@ -// ByteSwapRegister.cpp - -#include "StdAfx.h" - -#include "../Common/RegisterCodec.h" - -#include "ByteSwap.h" - -static void *CreateCodec2() { return (void *)(ICompressFilter *)(new CByteSwap2); } -static void *CreateCodec4() { return (void *)(ICompressFilter *)(new CByteSwap4); } - -static CCodecInfo g_CodecsInfo[] = -{ - { CreateCodec2, CreateCodec4, 0x020302, L"Swap2", 1, true }, - { CreateCodec4, CreateCodec4, 0x020304, L"Swap4", 1, true } -}; - -REGISTER_CODECS(ByteSwap) diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/Codec.def b/desmume/src/windows/7z/CPP/7zip/Compress/Codec.def deleted file mode 100644 index aab87ef8e..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/Codec.def +++ /dev/null @@ -1,4 +0,0 @@ -EXPORTS - CreateObject PRIVATE - GetNumberOfMethods PRIVATE - GetMethodProperty PRIVATE diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/CodecExports.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/CodecExports.cpp deleted file mode 100644 index 0cf84e73f..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/CodecExports.cpp +++ /dev/null @@ -1,157 +0,0 @@ -// CodecExports.cpp - -#include "StdAfx.h" - -#include "../../Common/ComTry.h" -#include "../../Windows/PropVariant.h" -#include "../Common/RegisterCodec.h" -#include "../ICoder.h" - -extern unsigned int g_NumCodecs; -extern const CCodecInfo *g_Codecs[]; - -static const UInt16 kDecodeId = 0x2790; - -DEFINE_GUID(CLSID_CCodec, -0x23170F69, 0x40C1, kDecodeId, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00); - -static inline HRESULT SetPropString(const char *s, unsigned int size, PROPVARIANT *value) -{ - if ((value->bstrVal = ::SysAllocStringByteLen(s, size)) != 0) - value->vt = VT_BSTR; - return S_OK; -} - -static inline HRESULT SetPropGUID(const GUID &guid, PROPVARIANT *value) -{ - return SetPropString((const char *)&guid, sizeof(GUID), value); -} - -static HRESULT SetClassID(CMethodId id, bool encode, PROPVARIANT *value) -{ - GUID clsId = CLSID_CCodec; - for (int i = 0; i < sizeof(id); i++, id >>= 8) - clsId.Data4[i] = (Byte)(id & 0xFF); - if (encode) - clsId.Data3++; - return SetPropGUID(clsId, value); -} - -static HRESULT FindCodecClassId(const GUID *clsID, UInt32 isCoder2, bool isFilter, bool &encode, int &index) -{ - index = -1; - if (clsID->Data1 != CLSID_CCodec.Data1 || - clsID->Data2 != CLSID_CCodec.Data2 || - (clsID->Data3 & ~1) != kDecodeId) - return S_OK; - encode = (clsID->Data3 != kDecodeId); - UInt64 id = 0; - for (int j = 0; j < 8; j++) - id |= ((UInt64)clsID->Data4[j]) << (8 * j); - for (unsigned i = 0; i < g_NumCodecs; i++) - { - const CCodecInfo &codec = *g_Codecs[i]; - if (id != codec.Id || encode && !codec.CreateEncoder || !encode && !codec.CreateDecoder) - continue; - if (!isFilter && codec.IsFilter || isFilter && !codec.IsFilter || - codec.NumInStreams != 1 && !isCoder2 || codec.NumInStreams == 1 && isCoder2) - return E_NOINTERFACE; - index = i; - return S_OK; - } - return S_OK; -} - -STDAPI CreateCoder2(bool encode, UInt32 index, const GUID *iid, void **outObject) -{ - COM_TRY_BEGIN - *outObject = 0; - bool isCoder = (*iid == IID_ICompressCoder) != 0; - bool isCoder2 = (*iid == IID_ICompressCoder2) != 0; - bool isFilter = (*iid == IID_ICompressFilter) != 0; - const CCodecInfo &codec = *g_Codecs[index]; - if (!isFilter && codec.IsFilter || isFilter && !codec.IsFilter || - codec.NumInStreams != 1 && !isCoder2 || codec.NumInStreams == 1 && isCoder2) - return E_NOINTERFACE; - if (encode) - { - if (!codec.CreateEncoder) - return CLASS_E_CLASSNOTAVAILABLE; - *outObject = codec.CreateEncoder(); - } - else - { - if (!codec.CreateDecoder) - return CLASS_E_CLASSNOTAVAILABLE; - *outObject = codec.CreateDecoder(); - } - if (isCoder) - ((ICompressCoder *)*outObject)->AddRef(); - else if (isCoder2) - ((ICompressCoder2 *)*outObject)->AddRef(); - else - ((ICompressFilter *)*outObject)->AddRef(); - return S_OK; - COM_TRY_END -} - -STDAPI CreateCoder(const GUID *clsid, const GUID *iid, void **outObject) -{ - *outObject = 0; - bool isCoder = (*iid == IID_ICompressCoder) != 0; - bool isCoder2 = (*iid == IID_ICompressCoder2) != 0; - bool isFilter = (*iid == IID_ICompressFilter) != 0; - if (!isCoder && !isCoder2 && !isFilter) - return E_NOINTERFACE; - bool encode; - int codecIndex; - HRESULT res = FindCodecClassId(clsid, isCoder2, isFilter, encode, codecIndex); - if (res != S_OK) - return res; - if (codecIndex < 0) - return CLASS_E_CLASSNOTAVAILABLE; - return CreateCoder2(encode, codecIndex, iid, outObject); -} - -STDAPI GetMethodProperty(UInt32 codecIndex, PROPID propID, PROPVARIANT *value) -{ - ::VariantClear((VARIANTARG *)value); - const CCodecInfo &codec = *g_Codecs[codecIndex]; - switch(propID) - { - case NMethodPropID::kID: - { - value->uhVal.QuadPart = (UInt64)codec.Id; - value->vt = VT_UI8; - break; - } - case NMethodPropID::kName: - if ((value->bstrVal = ::SysAllocString(codec.Name)) != 0) - value->vt = VT_BSTR; - break; - case NMethodPropID::kDecoder: - if (codec.CreateDecoder) - return SetClassID(codec.Id, false, value); - break; - case NMethodPropID::kEncoder: - if (codec.CreateEncoder) - return SetClassID(codec.Id, true, value); - break; - case NMethodPropID::kInStreams: - { - if (codec.NumInStreams != 1) - { - value->vt = VT_UI4; - value->ulVal = (ULONG)codec.NumInStreams; - } - break; - } - } - return S_OK; -} - -STDAPI GetNumberOfMethods(UINT32 *numCodecs) -{ - *numCodecs = g_NumCodecs; - return S_OK; -} diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/CopyCoder.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/CopyCoder.cpp deleted file mode 100644 index 4c2f5e0fc..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/CopyCoder.cpp +++ /dev/null @@ -1,62 +0,0 @@ -// Compress/CopyCoder.cpp - -#include "StdAfx.h" - -extern "C" -{ -#include "../../../C/Alloc.h" -} - -#include "../Common/StreamUtils.h" - -#include "CopyCoder.h" - -namespace NCompress { - -static const UInt32 kBufferSize = 1 << 17; - -CCopyCoder::~CCopyCoder() -{ - ::MidFree(_buffer); -} - -STDMETHODIMP CCopyCoder::Code(ISequentialInStream *inStream, - ISequentialOutStream *outStream, - const UInt64 * /* inSize */, const UInt64 *outSize, - ICompressProgressInfo *progress) -{ - if (_buffer == 0) - { - _buffer = (Byte *)::MidAlloc(kBufferSize); - if (_buffer == 0) - return E_OUTOFMEMORY; - } - - TotalSize = 0; - for (;;) - { - UInt32 realProcessedSize; - UInt32 size = kBufferSize; - if (outSize != 0) - if (size > *outSize - TotalSize) - size = (UInt32)(*outSize - TotalSize); - RINOK(inStream->Read(_buffer, size, &realProcessedSize)); - if (realProcessedSize == 0) - break; - RINOK(WriteStream(outStream, _buffer, realProcessedSize)); - TotalSize += realProcessedSize; - if (progress != NULL) - { - RINOK(progress->SetRatioInfo(&TotalSize, &TotalSize)); - } - } - return S_OK; -} - -STDMETHODIMP CCopyCoder::GetInStreamProcessedSize(UInt64 *value) -{ - *value = TotalSize; - return S_OK; -} - -} diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/CopyCoder.h b/desmume/src/windows/7z/CPP/7zip/Compress/CopyCoder.h deleted file mode 100644 index 7c9d3d355..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/CopyCoder.h +++ /dev/null @@ -1,32 +0,0 @@ -// Compress/CopyCoder.h - -#ifndef __COMPRESS_COPY_CODER_H -#define __COMPRESS_COPY_CODER_H - -#include "../../Common/MyCom.h" - -#include "../ICoder.h" - -namespace NCompress { - -class CCopyCoder: - public ICompressCoder, - public ICompressGetInStreamProcessedSize, - public CMyUnknownImp -{ - Byte *_buffer; -public: - UInt64 TotalSize; - CCopyCoder(): TotalSize(0) , _buffer(0) {}; - ~CCopyCoder(); - - MY_UNKNOWN_IMP1(ICompressGetInStreamProcessedSize) - - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - STDMETHOD(GetInStreamProcessedSize)(UInt64 *value); -}; - -} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/CopyRegister.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/CopyRegister.cpp deleted file mode 100644 index 3ef245978..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/CopyRegister.cpp +++ /dev/null @@ -1,14 +0,0 @@ -// CopyRegister.cpp - -#include "StdAfx.h" - -#include "../Common/RegisterCodec.h" - -#include "CopyCoder.h" - -static void *CreateCodec() { return (void *)(ICompressCoder *)(new NCompress::CCopyCoder); } - -static CCodecInfo g_CodecInfo = -{ CreateCodec, CreateCodec, 0x00, L"Copy", 1, false }; - -REGISTER_CODEC(Copy) diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/Deflate64Register.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/Deflate64Register.cpp deleted file mode 100644 index 6d6a904d1..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/Deflate64Register.cpp +++ /dev/null @@ -1,20 +0,0 @@ -// Deflate64Register.cpp - -#include "StdAfx.h" - -#include "../Common/RegisterCodec.h" - -#include "DeflateDecoder.h" - -static void *CreateCodecDeflate64() { return (void *)(ICompressCoder *)(new NCompress::NDeflate::NDecoder::CCOMCoder64); } -#if !defined(EXTRACT_ONLY) && !defined(DEFLATE_EXTRACT_ONLY) -#include "DeflateEncoder.h" -static void *CreateCodecOutDeflate64() { return (void *)(ICompressCoder *)(new NCompress::NDeflate::NEncoder::CCOMCoder64); } -#else -#define CreateCodecOutDeflate64 0 -#endif - -static CCodecInfo g_CodecInfo = - { CreateCodecDeflate64, CreateCodecOutDeflate64, 0x040109, L"Deflate64", 1, false }; - -REGISTER_CODEC(Deflate64) diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/DeflateConst.h b/desmume/src/windows/7z/CPP/7zip/Compress/DeflateConst.h deleted file mode 100644 index b5c28d79e..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/DeflateConst.h +++ /dev/null @@ -1,134 +0,0 @@ -// DeflateConst.h - -#ifndef __DEFLATE_CONST_H -#define __DEFLATE_CONST_H - -namespace NCompress { -namespace NDeflate { - -const int kNumHuffmanBits = 15; - -const UInt32 kHistorySize32 = (1 << 15); -const UInt32 kHistorySize64 = (1 << 16); - -const UInt32 kDistTableSize32 = 30; -const UInt32 kDistTableSize64 = 32; - -const UInt32 kNumLenSymbols32 = 256; -const UInt32 kNumLenSymbols64 = 255; // don't change it. It must be <= 255. -const UInt32 kNumLenSymbolsMax = kNumLenSymbols32; - -const UInt32 kNumLenSlots = 29; - -const UInt32 kFixedDistTableSize = 32; -const UInt32 kFixedLenTableSize = 31; - -const UInt32 kSymbolEndOfBlock = 0x100; -const UInt32 kSymbolMatch = kSymbolEndOfBlock + 1; - -const UInt32 kMainTableSize = kSymbolMatch + kNumLenSlots; -const UInt32 kFixedMainTableSize = kSymbolMatch + kFixedLenTableSize; - -const UInt32 kLevelTableSize = 19; - -const UInt32 kTableDirectLevels = 16; -const UInt32 kTableLevelRepNumber = kTableDirectLevels; -const UInt32 kTableLevel0Number = kTableLevelRepNumber + 1; -const UInt32 kTableLevel0Number2 = kTableLevel0Number + 1; - -const UInt32 kLevelMask = 0xF; - -const Byte kLenStart32[kFixedLenTableSize] = - {0,1,2,3,4,5,6,7,8,10,12,14,16,20,24,28,32,40,48,56,64,80,96,112,128,160,192,224, 255, 0, 0}; -const Byte kLenStart64[kFixedLenTableSize] = - {0,1,2,3,4,5,6,7,8,10,12,14,16,20,24,28,32,40,48,56,64,80,96,112,128,160,192,224, 0, 0, 0}; - -const Byte kLenDirectBits32[kFixedLenTableSize] = - {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}; -const Byte kLenDirectBits64[kFixedLenTableSize] = - {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, 16, 0, 0}; - -const UInt32 kDistStart[kDistTableSize64] = - {0,1,2,3,4,6,8,12,16,24,32,48,64,96,128,192,256,384,512,768, - 1024,1536,2048,3072,4096,6144,8192,12288,16384,24576,32768,49152}; -const Byte kDistDirectBits[kDistTableSize64] = - {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,14,14}; - -const Byte kLevelDirectBits[3] = {2, 3, 7}; - -const Byte kCodeLengthAlphabetOrder[kLevelTableSize] = {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; - -const UInt32 kMatchMinLen = 3; -const UInt32 kMatchMaxLen32 = kNumLenSymbols32 + kMatchMinLen - 1; //256 + 2 -const UInt32 kMatchMaxLen64 = kNumLenSymbols64 + kMatchMinLen - 1; //255 + 2 -const UInt32 kMatchMaxLen = kMatchMaxLen32; - -const int kFinalBlockFieldSize = 1; - -namespace NFinalBlockField -{ - enum - { - kNotFinalBlock = 0, - kFinalBlock = 1 - }; -} - -const int kBlockTypeFieldSize = 2; - -namespace NBlockType -{ - enum - { - kStored = 0, - kFixedHuffman = 1, - kDynamicHuffman = 2 - }; -} - -const int kNumLenCodesFieldSize = 5; -const int kNumDistCodesFieldSize = 5; -const int kNumLevelCodesFieldSize = 4; - -const UInt32 kNumLitLenCodesMin = 257; -const UInt32 kNumDistCodesMin = 1; -const UInt32 kNumLevelCodesMin = 4; - -const int kLevelFieldSize = 3; - -const int kStoredBlockLengthFieldSize = 16; - -struct CLevels -{ - Byte litLenLevels[kFixedMainTableSize]; - Byte distLevels[kFixedDistTableSize]; - - void SubClear() - { - UInt32 i; - for(i = kNumLitLenCodesMin; i < kFixedMainTableSize; i++) - litLenLevels[i] = 0; - for(i = 0; i < kFixedDistTableSize; i++) - distLevels[i] = 0; - } - - void SetFixedLevels() - { - int i; - - for (i = 0; i < 144; i++) - litLenLevels[i] = 8; - for (; i < 256; i++) - litLenLevels[i] = 9; - for (; i < 280; i++) - litLenLevels[i] = 7; - for (; i < 288; i++) - litLenLevels[i] = 8; - for (i = 0; i < kFixedDistTableSize; i++) // test it: InfoZip only uses kDistTableSize - distLevels[i] = 5; - } -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/DeflateDecoder.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/DeflateDecoder.cpp deleted file mode 100644 index 31a61371b..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/DeflateDecoder.cpp +++ /dev/null @@ -1,345 +0,0 @@ -// DeflateDecoder.cpp - -#include "StdAfx.h" - -#include "DeflateDecoder.h" - -namespace NCompress { -namespace NDeflate { -namespace NDecoder { - -static const int kLenIdFinished = -1; -static const int kLenIdNeedInit = -2; - -CCoder::CCoder(bool deflate64Mode, bool deflateNSIS): - _deflate64Mode(deflate64Mode), - _deflateNSIS(deflateNSIS), - _keepHistory(false), - ZlibMode(false) {} - -UInt32 CCoder::ReadBits(int numBits) -{ - return m_InBitStream.ReadBits(numBits); -} - -bool CCoder::DeCodeLevelTable(Byte *values, int numSymbols) -{ - int i = 0; - do - { - UInt32 number = m_LevelDecoder.DecodeSymbol(&m_InBitStream); - if (number < kTableDirectLevels) - values[i++] = (Byte)number; - else if (number < kLevelTableSize) - { - if (number == kTableLevelRepNumber) - { - if (i == 0) - return false; - int num = ReadBits(2) + 3; - for (; num > 0 && i < numSymbols; num--, i++) - values[i] = values[i - 1]; - } - else - { - int num; - if (number == kTableLevel0Number) - num = ReadBits(3) + 3; - else - num = ReadBits(7) + 11; - for (;num > 0 && i < numSymbols; num--) - values[i++] = 0; - } - } - else - return false; - } - while(i < numSymbols); - return true; -} - -#define RIF(x) { if (!(x)) return false; } - -bool CCoder::ReadTables(void) -{ - m_FinalBlock = (ReadBits(kFinalBlockFieldSize) == NFinalBlockField::kFinalBlock); - UInt32 blockType = ReadBits(kBlockTypeFieldSize); - if (blockType > NBlockType::kDynamicHuffman) - return false; - - if (blockType == NBlockType::kStored) - { - m_StoredMode = true; - UInt32 currentBitPosition = m_InBitStream.GetBitPosition(); - int numBitsForAlign = (int)(currentBitPosition > 0 ? (8 - currentBitPosition): 0); - ReadBits(numBitsForAlign); - m_StoredBlockSize = ReadBits(kStoredBlockLengthFieldSize); - if (_deflateNSIS) - return true; - return (m_StoredBlockSize == (UInt16)~ReadBits(kStoredBlockLengthFieldSize)); - } - - m_StoredMode = false; - - CLevels levels; - if (blockType == NBlockType::kFixedHuffman) - { - levels.SetFixedLevels(); - _numDistLevels = _deflate64Mode ? kDistTableSize64 : kDistTableSize32; - } - else - { - int numLitLenLevels = ReadBits(kNumLenCodesFieldSize) + kNumLitLenCodesMin; - _numDistLevels = ReadBits(kNumDistCodesFieldSize) + kNumDistCodesMin; - int numLevelCodes = ReadBits(kNumLevelCodesFieldSize) + kNumLevelCodesMin; - - if (!_deflate64Mode) - if (_numDistLevels > kDistTableSize32) - return false; - - Byte levelLevels[kLevelTableSize]; - for (int i = 0; i < kLevelTableSize; i++) - { - int position = kCodeLengthAlphabetOrder[i]; - if(i < numLevelCodes) - levelLevels[position] = (Byte)ReadBits(kLevelFieldSize); - else - levelLevels[position] = 0; - } - - RIF(m_LevelDecoder.SetCodeLengths(levelLevels)); - - Byte tmpLevels[kFixedMainTableSize + kFixedDistTableSize]; - if (!DeCodeLevelTable(tmpLevels, numLitLenLevels + _numDistLevels)) - return false; - - levels.SubClear(); - memcpy(levels.litLenLevels, tmpLevels, numLitLenLevels); - memcpy(levels.distLevels, tmpLevels + numLitLenLevels, _numDistLevels); - } - RIF(m_MainDecoder.SetCodeLengths(levels.litLenLevels)); - return m_DistDecoder.SetCodeLengths(levels.distLevels); -} - -HRESULT CCoder::CodeSpec(UInt32 curSize) -{ - if (_remainLen == kLenIdFinished) - return S_OK; - if (_remainLen == kLenIdNeedInit) - { - if (!_keepHistory) - if (!m_OutWindowStream.Create(_deflate64Mode ? kHistorySize64: kHistorySize32)) - return E_OUTOFMEMORY; - if (!m_InBitStream.Create(1 << 17)) - return E_OUTOFMEMORY; - m_OutWindowStream.Init(_keepHistory); - m_InBitStream.Init(); - m_FinalBlock = false; - _remainLen = 0; - _needReadTable = true; - } - - if (curSize == 0) - return S_OK; - - while(_remainLen > 0 && curSize > 0) - { - _remainLen--; - Byte b = m_OutWindowStream.GetByte(_rep0); - m_OutWindowStream.PutByte(b); - curSize--; - } - - while(curSize > 0) - { - if (_needReadTable) - { - if (m_FinalBlock) - { - _remainLen = kLenIdFinished; - break; - } - if (!ReadTables()) - return S_FALSE; - _needReadTable = false; - } - - if(m_StoredMode) - { - for (; m_StoredBlockSize > 0 && curSize > 0; m_StoredBlockSize--, curSize--) - m_OutWindowStream.PutByte((Byte)m_InBitStream.ReadBits(8)); - _needReadTable = (m_StoredBlockSize == 0); - continue; - } - while(curSize > 0) - { - if (m_InBitStream.NumExtraBytes > 4) - return S_FALSE; - - UInt32 number = m_MainDecoder.DecodeSymbol(&m_InBitStream); - if (number < 0x100) - { - m_OutWindowStream.PutByte((Byte)number); - curSize--; - continue; - } - else if (number == kSymbolEndOfBlock) - { - _needReadTable = true; - break; - } - else if (number < kMainTableSize) - { - number -= kSymbolMatch; - UInt32 len; - { - int numBits; - if (_deflate64Mode) - { - len = kLenStart64[number]; - numBits = kLenDirectBits64[number]; - } - else - { - len = kLenStart32[number]; - numBits = kLenDirectBits32[number]; - } - len += kMatchMinLen + m_InBitStream.ReadBits(numBits); - } - UInt32 locLen = len; - if (locLen > curSize) - locLen = (UInt32)curSize; - number = m_DistDecoder.DecodeSymbol(&m_InBitStream); - if (number >= _numDistLevels) - return S_FALSE; - UInt32 distance = kDistStart[number] + m_InBitStream.ReadBits(kDistDirectBits[number]); - if (!m_OutWindowStream.CopyBlock(distance, locLen)) - return S_FALSE; - curSize -= locLen; - len -= locLen; - if (len != 0) - { - _remainLen = (Int32)len; - _rep0 = distance; - break; - } - } - else - return S_FALSE; - } - } - return S_OK; -} - -HRESULT CCoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *, const UInt64 *outSize, ICompressProgressInfo *progress) -{ - SetInStream(inStream); - m_OutWindowStream.SetStream(outStream); - SetOutStreamSize(outSize); - CCoderReleaser flusher(this); - - const UInt64 start = m_OutWindowStream.GetProcessedSize(); - for (;;) - { - UInt32 curSize = 1 << 18; - if (outSize != 0) - { - const UInt64 rem = *outSize - (m_OutWindowStream.GetProcessedSize() - start); - if (curSize > rem) - curSize = (UInt32)rem; - } - if (curSize == 0) - break; - RINOK(CodeSpec(curSize)); - if (_remainLen == kLenIdFinished) - break; - if (progress != NULL) - { - const UInt64 inSize = m_InBitStream.GetProcessedSize(); - const UInt64 nowPos64 = m_OutWindowStream.GetProcessedSize() - start; - RINOK(progress->SetRatioInfo(&inSize, &nowPos64)); - } - } - if (_remainLen == kLenIdFinished && ZlibMode) - { - UInt32 currentBitPosition = m_InBitStream.GetBitPosition(); - int numBitsForAlign = (int)(currentBitPosition > 0 ? (8 - currentBitPosition): 0); - ReadBits(numBitsForAlign); - for (int i = 0; i < 4; i++) - ZlibFooter[i] = (Byte)m_InBitStream.ReadBits(8); - } - flusher.NeedFlush = false; - return Flush(); -} - - -#ifdef _NO_EXCEPTIONS - -#define DEFLATE_TRY_BEGIN -#define DEFLATE_TRY_END - -#else - -#define DEFLATE_TRY_BEGIN try { -#define DEFLATE_TRY_END } \ - catch(const CInBufferException &e) { return e.ErrorCode; } \ - catch(const CLzOutWindowException &e) { return e.ErrorCode; } \ - catch(...) { return S_FALSE; } - -#endif - -HRESULT CCoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) -{ - DEFLATE_TRY_BEGIN - return CodeReal(inStream, outStream, inSize, outSize, progress); - DEFLATE_TRY_END -} - -STDMETHODIMP CCoder::GetInStreamProcessedSize(UInt64 *value) -{ - if (value == NULL) - return E_INVALIDARG; - *value = m_InBitStream.GetProcessedSize(); - return S_OK; -} - -STDMETHODIMP CCoder::SetInStream(ISequentialInStream *inStream) -{ - m_InBitStream.SetStream(inStream); - return S_OK; -} - -STDMETHODIMP CCoder::ReleaseInStream() -{ - m_InBitStream.ReleaseStream(); - return S_OK; -} - -STDMETHODIMP CCoder::SetOutStreamSize(const UInt64 * /* outSize */) -{ - _remainLen = kLenIdNeedInit; - m_OutWindowStream.Init(_keepHistory); - return S_OK; -} - -#ifndef NO_READ_FROM_CODER - -STDMETHODIMP CCoder::Read(void *data, UInt32 size, UInt32 *processedSize) -{ - DEFLATE_TRY_BEGIN - if (processedSize) - *processedSize = 0; - const UInt64 startPos = m_OutWindowStream.GetProcessedSize(); - m_OutWindowStream.SetMemStream((Byte *)data); - RINOK(CodeSpec(size)); - if (processedSize) - *processedSize = (UInt32)(m_OutWindowStream.GetProcessedSize() - startPos); - return Flush(); - DEFLATE_TRY_END -} - -#endif - -}}} diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/DeflateDecoder.h b/desmume/src/windows/7z/CPP/7zip/Compress/DeflateDecoder.h deleted file mode 100644 index 3a81e1657..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/DeflateDecoder.h +++ /dev/null @@ -1,136 +0,0 @@ -// DeflateDecoder.h - -#ifndef __DEFLATE_DECODER_H -#define __DEFLATE_DECODER_H - -#include "../../Common/MyCom.h" - -#include "../ICoder.h" - -#include "../Common/InBuffer.h" - -#include "BitlDecoder.h" -#include "DeflateConst.h" -#include "HuffmanDecoder.h" -#include "LzOutWindow.h" - -namespace NCompress { -namespace NDeflate { -namespace NDecoder { - -class CCoder: - public ICompressCoder, - public ICompressGetInStreamProcessedSize, - #ifndef NO_READ_FROM_CODER - public ICompressSetInStream, - public ICompressSetOutStreamSize, - public ISequentialInStream, - #endif - public CMyUnknownImp -{ - CLzOutWindow m_OutWindowStream; - NBitl::CDecoder m_InBitStream; - NCompress::NHuffman::CDecoder m_MainDecoder; - NCompress::NHuffman::CDecoder m_DistDecoder; - NCompress::NHuffman::CDecoder m_LevelDecoder; - - UInt32 m_StoredBlockSize; - - bool m_FinalBlock; - bool m_StoredMode; - UInt32 _numDistLevels; - - - bool _deflateNSIS; - bool _deflate64Mode; - bool _keepHistory; - Int32 _remainLen; - UInt32 _rep0; - bool _needReadTable; - - UInt32 ReadBits(int numBits); - - bool DeCodeLevelTable(Byte *values, int numSymbols); - bool ReadTables(); - - void ReleaseStreams() - { - m_OutWindowStream.ReleaseStream(); - ReleaseInStream(); - } - - HRESULT Flush() { return m_OutWindowStream.Flush(); } - class CCoderReleaser - { - CCoder *m_Coder; - public: - bool NeedFlush; - CCoderReleaser(CCoder *coder): m_Coder(coder), NeedFlush(true) {} - ~CCoderReleaser() - { - if (NeedFlush) - m_Coder->Flush(); - m_Coder->ReleaseStreams(); - } - }; - friend class CCoderReleaser; - - HRESULT CodeSpec(UInt32 curSize); -public: - bool ZlibMode; - Byte ZlibFooter[4]; - - CCoder(bool deflate64Mode, bool deflateNSIS = false); - void SetKeepHistory(bool keepHistory) { _keepHistory = keepHistory; } - - HRESULT CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - - #ifndef NO_READ_FROM_CODER - MY_UNKNOWN_IMP4( - ICompressGetInStreamProcessedSize, - ICompressSetInStream, - ICompressSetOutStreamSize, - ISequentialInStream - ) - #else - MY_UNKNOWN_IMP1( - ICompressGetInStreamProcessedSize) - #endif - - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - - STDMETHOD(SetInStream)(ISequentialInStream *inStream); - STDMETHOD(ReleaseInStream)(); - STDMETHOD(SetOutStreamSize)(const UInt64 *outSize); - - #ifndef NO_READ_FROM_CODER - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); - #endif - - // IGetInStreamProcessedSize - STDMETHOD(GetInStreamProcessedSize)(UInt64 *value); -}; - -class CCOMCoder : public CCoder -{ -public: - CCOMCoder(): CCoder(false) {} -}; - -class CNsisCOMCoder : public CCoder -{ -public: - CNsisCOMCoder(): CCoder(false, true) {} -}; - -class CCOMCoder64 : public CCoder -{ -public: - CCOMCoder64(): CCoder(true) {} -}; - -}}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/DeflateNsisRegister.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/DeflateNsisRegister.cpp deleted file mode 100644 index dbb128368..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/DeflateNsisRegister.cpp +++ /dev/null @@ -1,14 +0,0 @@ -// DeflateNsisRegister.cpp - -#include "StdAfx.h" - -#include "../Common/RegisterCodec.h" - -#include "DeflateDecoder.h" - -static void *CreateCodecDeflateNsis() { return (void *)(ICompressCoder *)(new NCompress::NDeflate::NDecoder::CNsisCOMCoder); } - -static CCodecInfo g_CodecInfo = - { CreateCodecDeflateNsis, 0, 0x040901, L"DeflateNSIS", 1, false }; - -REGISTER_CODEC(DeflateNsis) diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/DeflateRegister.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/DeflateRegister.cpp deleted file mode 100644 index d8a9c8dc8..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/DeflateRegister.cpp +++ /dev/null @@ -1,21 +0,0 @@ -// DeflateRegister.cpp - -#include "StdAfx.h" - -#include "../Common/RegisterCodec.h" - -#include "DeflateDecoder.h" - -static void *CreateCodecDeflate() { return (void *)(ICompressCoder *)(new NCompress::NDeflate::NDecoder::CCOMCoder); } - -#if !defined(EXTRACT_ONLY) && !defined(DEFLATE_EXTRACT_ONLY) -#include "DeflateEncoder.h" -static void *CreateCodecOutDeflate() { return (void *)(ICompressCoder *)(new NCompress::NDeflate::NEncoder::CCOMCoder); } -#else -#define CreateCodecOutDeflate 0 -#endif - -static CCodecInfo g_CodecInfo = - { CreateCodecDeflate, CreateCodecOutDeflate, 0x040108, L"Deflate", 1, false }; - -REGISTER_CODEC(Deflate) diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/HuffmanDecoder.h b/desmume/src/windows/7z/CPP/7zip/Compress/HuffmanDecoder.h deleted file mode 100644 index f71a58282..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/HuffmanDecoder.h +++ /dev/null @@ -1,89 +0,0 @@ -// Compress/HuffmanDecoder.h - -#ifndef __COMPRESS_HUFFMAN_DECODER_H -#define __COMPRESS_HUFFMAN_DECODER_H - -#include "../../Common/Types.h" - -namespace NCompress { -namespace NHuffman { - -const int kNumTableBits = 9; - -template -class CDecoder -{ - UInt32 m_Limits[kNumBitsMax + 1]; // m_Limits[i] = value limit for symbols with length = i - UInt32 m_Positions[kNumBitsMax + 1]; // m_Positions[i] = index in m_Symbols[] of first symbol with length = i - UInt32 m_Symbols[m_NumSymbols]; - Byte m_Lengths[1 << kNumTableBits]; // Table oh length for short codes. - -public: - - bool SetCodeLengths(const Byte *codeLengths) - { - int lenCounts[kNumBitsMax + 1]; - UInt32 tmpPositions[kNumBitsMax + 1]; - int i; - for(i = 1; i <= kNumBitsMax; i++) - lenCounts[i] = 0; - UInt32 symbol; - for (symbol = 0; symbol < m_NumSymbols; symbol++) - { - int len = codeLengths[symbol]; - if (len > kNumBitsMax) - return false; - lenCounts[len]++; - m_Symbols[symbol] = 0xFFFFFFFF; - } - lenCounts[0] = 0; - m_Positions[0] = m_Limits[0] = 0; - UInt32 startPos = 0; - UInt32 index = 0; - const UInt32 kMaxValue = (1 << kNumBitsMax); - for (i = 1; i <= kNumBitsMax; i++) - { - startPos += lenCounts[i] << (kNumBitsMax - i); - if (startPos > kMaxValue) - return false; - m_Limits[i] = (i == kNumBitsMax) ? kMaxValue : startPos; - m_Positions[i] = m_Positions[i - 1] + lenCounts[i - 1]; - tmpPositions[i] = m_Positions[i]; - if(i <= kNumTableBits) - { - UInt32 limit = (m_Limits[i] >> (kNumBitsMax - kNumTableBits)); - for (; index < limit; index++) - m_Lengths[index] = (Byte)i; - } - } - for (symbol = 0; symbol < m_NumSymbols; symbol++) - { - int len = codeLengths[symbol]; - if (len != 0) - m_Symbols[tmpPositions[len]++] = symbol; - } - return true; - } - - template - UInt32 DecodeSymbol(TBitDecoder *bitStream) - { - int numBits; - UInt32 value = bitStream->GetValue(kNumBitsMax); - if (value < m_Limits[kNumTableBits]) - numBits = m_Lengths[value >> (kNumBitsMax - kNumTableBits)]; - else - for (numBits = kNumTableBits + 1; value >= m_Limits[numBits]; numBits++); - bitStream->MovePos(numBits); - UInt32 index = m_Positions[numBits] + - ((value - m_Limits[numBits - 1]) >> (kNumBitsMax - numBits)); - if (index >= m_NumSymbols) - // throw CDecoderException(); // test it - return 0xFFFFFFFF; - return m_Symbols[index]; - } -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/ImplodeDecoder.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/ImplodeDecoder.cpp deleted file mode 100644 index 6c5e36284..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/ImplodeDecoder.cpp +++ /dev/null @@ -1,219 +0,0 @@ -// Implode/Decoder.cpp - -#include "StdAfx.h" - -#include "ImplodeDecoder.h" -#include "Common/Defs.h" - -namespace NCompress { -namespace NImplode { -namespace NDecoder { - -class CException -{ -public: - enum ECauseType - { - kData - } m_Cause; - CException(ECauseType cause): m_Cause(cause) {} -}; - -static const int kNumDistanceLowDirectBitsForBigDict = 7; -static const int kNumDistanceLowDirectBitsForSmallDict = 6; - -static const int kNumBitsInByte = 8; - -// static const int kLevelStructuresNumberFieldSize = kNumBitsInByte; -static const int kLevelStructuresNumberAdditionalValue = 1; - -static const int kNumLevelStructureLevelBits = 4; -static const int kLevelStructureLevelAdditionalValue = 1; - -static const int kNumLevelStructureRepNumberBits = 4; -static const int kLevelStructureRepNumberAdditionalValue = 1; - - -static const int kLiteralTableSize = (1 << kNumBitsInByte); -static const int kDistanceTableSize = 64; -static const int kLengthTableSize = 64; - -static const UInt32 kHistorySize = - (1 << MyMax(kNumDistanceLowDirectBitsForBigDict, - kNumDistanceLowDirectBitsForSmallDict)) * - kDistanceTableSize; // = 8 KB; - -static const int kNumAdditionalLengthBits = 8; - -static const UInt32 kMatchMinLenWhenLiteralsOn = 3; -static const UInt32 kMatchMinLenWhenLiteralsOff = 2; - -static const UInt32 kMatchMinLenMax = MyMax(kMatchMinLenWhenLiteralsOn, - kMatchMinLenWhenLiteralsOff); // 3 - -// static const UInt32 kMatchMaxLenMax = kMatchMinLenMax + (kLengthTableSize - 1) + (1 << kNumAdditionalLengthBits) - 1; // or 2 - -enum -{ - kMatchId = 0, - kLiteralId = 1 -}; - - -CCoder::CCoder(): - m_LiteralDecoder(kLiteralTableSize), - m_LengthDecoder(kLengthTableSize), - m_DistanceDecoder(kDistanceTableSize) -{ -} - -void CCoder::ReleaseStreams() -{ - m_OutWindowStream.ReleaseStream(); - m_InBitStream.ReleaseStream(); -} - -bool CCoder::ReadLevelItems(NImplode::NHuffman::CDecoder &decoder, - Byte *levels, int numLevelItems) -{ - int numCodedStructures = m_InBitStream.ReadBits(kNumBitsInByte) + - kLevelStructuresNumberAdditionalValue; - int currentIndex = 0; - for(int i = 0; i < numCodedStructures; i++) - { - int level = m_InBitStream.ReadBits(kNumLevelStructureLevelBits) + - kLevelStructureLevelAdditionalValue; - int rep = m_InBitStream.ReadBits(kNumLevelStructureRepNumberBits) + - kLevelStructureRepNumberAdditionalValue; - if (currentIndex + rep > numLevelItems) - throw CException(CException::kData); - for(int j = 0; j < rep; j++) - levels[currentIndex++] = (Byte)level; - } - if (currentIndex != numLevelItems) - return false; - return decoder.SetCodeLengths(levels); -} - - -bool CCoder::ReadTables(void) -{ - if (m_LiteralsOn) - { - Byte literalLevels[kLiteralTableSize]; - if (!ReadLevelItems(m_LiteralDecoder, literalLevels, kLiteralTableSize)) - return false; - } - - Byte lengthLevels[kLengthTableSize]; - if (!ReadLevelItems(m_LengthDecoder, lengthLevels, kLengthTableSize)) - return false; - - Byte distanceLevels[kDistanceTableSize]; - return ReadLevelItems(m_DistanceDecoder, distanceLevels, kDistanceTableSize); -} - -class CCoderReleaser -{ - CCoder *m_Coder; -public: - CCoderReleaser(CCoder *coder): m_Coder(coder) {} - ~CCoderReleaser() { m_Coder->ReleaseStreams(); } -}; - -HRESULT CCoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 * /* inSize */, const UInt64 *outSize, ICompressProgressInfo *progress) -{ - if (!m_InBitStream.Create(1 << 20)) - return E_OUTOFMEMORY; - if (!m_OutWindowStream.Create(kHistorySize)) - return E_OUTOFMEMORY; - if (outSize == NULL) - return E_INVALIDARG; - UInt64 pos = 0, unPackSize = *outSize; - - m_OutWindowStream.SetStream(outStream); - m_OutWindowStream.Init(false); - m_InBitStream.SetStream(inStream); - m_InBitStream.Init(); - CCoderReleaser coderReleaser(this); - - if (!ReadTables()) - return S_FALSE; - - while(pos < unPackSize) - { - if (progress != NULL && pos % (1 << 16) == 0) - { - UInt64 packSize = m_InBitStream.GetProcessedSize(); - RINOK(progress->SetRatioInfo(&packSize, &pos)); - } - if(m_InBitStream.ReadBits(1) == kMatchId) // match - { - UInt32 lowDistBits = m_InBitStream.ReadBits(m_NumDistanceLowDirectBits); - UInt32 distance = m_DistanceDecoder.DecodeSymbol(&m_InBitStream); - if (distance >= kDistanceTableSize) - return S_FALSE; - distance = (distance << m_NumDistanceLowDirectBits) + lowDistBits; - UInt32 lengthSymbol = m_LengthDecoder.DecodeSymbol(&m_InBitStream); - if (lengthSymbol >= kLengthTableSize) - return S_FALSE; - UInt32 length = lengthSymbol + m_MinMatchLength; - if (lengthSymbol == kLengthTableSize - 1) // special symbol = 63 - length += m_InBitStream.ReadBits(kNumAdditionalLengthBits); - while(distance >= pos && length > 0) - { - m_OutWindowStream.PutByte(0); - pos++; - length--; - } - if (length > 0) - m_OutWindowStream.CopyBlock(distance, length); - pos += length; - } - else - { - Byte b; - if (m_LiteralsOn) - { - UInt32 temp = m_LiteralDecoder.DecodeSymbol(&m_InBitStream); - if (temp >= kLiteralTableSize) - return S_FALSE; - b = (Byte)temp; - } - else - b = (Byte)m_InBitStream.ReadBits(kNumBitsInByte); - m_OutWindowStream.PutByte(b); - pos++; - } - } - if (pos > unPackSize) - return S_FALSE; - return m_OutWindowStream.Flush(); -} - -STDMETHODIMP CCoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) -{ - try { return CodeReal(inStream, outStream, inSize, outSize, progress); } - catch(const CLzOutWindowException &e) { return e.ErrorCode; } - catch(...) { return S_FALSE; } -} - -STDMETHODIMP CCoder::SetDecoderProperties2(const Byte *data, UInt32 size) -{ - if (size < 1) - return E_INVALIDARG; - Byte flag = data[0]; - m_BigDictionaryOn = ((flag & 2) != 0); - m_NumDistanceLowDirectBits = m_BigDictionaryOn ? - kNumDistanceLowDirectBitsForBigDict: - kNumDistanceLowDirectBitsForSmallDict; - m_LiteralsOn = ((flag & 4) != 0); - m_MinMatchLength = m_LiteralsOn ? - kMatchMinLenWhenLiteralsOn : - kMatchMinLenWhenLiteralsOff; - return S_OK; -} - -}}} diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/ImplodeDecoder.h b/desmume/src/windows/7z/CPP/7zip/Compress/ImplodeDecoder.h deleted file mode 100644 index 2b45f05da..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/ImplodeDecoder.h +++ /dev/null @@ -1,57 +0,0 @@ -// ImplodeDecoder.h - -#ifndef __COMPRESS_IMPLODE_DECODER_H -#define __COMPRESS_IMPLODE_DECODER_H - -#include "../../Common/MyCom.h" - -#include "../ICoder.h" - -#include "ImplodeHuffmanDecoder.h" -#include "LzOutWindow.h" - -namespace NCompress { -namespace NImplode { -namespace NDecoder { - -class CCoder: - public ICompressCoder, - public ICompressSetDecoderProperties2, - public CMyUnknownImp -{ - CLzOutWindow m_OutWindowStream; - NBitl::CDecoder m_InBitStream; - - NImplode::NHuffman::CDecoder m_LiteralDecoder; - NImplode::NHuffman::CDecoder m_LengthDecoder; - NImplode::NHuffman::CDecoder m_DistanceDecoder; - - bool m_BigDictionaryOn; - bool m_LiteralsOn; - - int m_NumDistanceLowDirectBits; - UInt32 m_MinMatchLength; - - bool ReadLevelItems(NImplode::NHuffman::CDecoder &table, Byte *levels, int numLevelItems); - bool ReadTables(); - void DeCodeLevelTable(Byte *newLevels, int numLevels); -public: - CCoder(); - - MY_UNKNOWN_IMP1(ICompressSetDecoderProperties2) - - void ReleaseStreams(); - HRESULT Flush() { return m_OutWindowStream.Flush(); } - - HRESULT CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - - STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size); -}; - -}}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/ImplodeHuffmanDecoder.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/ImplodeHuffmanDecoder.cpp deleted file mode 100644 index c7a163433..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/ImplodeHuffmanDecoder.cpp +++ /dev/null @@ -1,89 +0,0 @@ -// ImplodeHuffmanDecoder.cpp - -#include "StdAfx.h" - -#include "ImplodeHuffmanDecoder.h" - -namespace NCompress { -namespace NImplode { -namespace NHuffman { - -CDecoder::CDecoder(UInt32 numSymbols): - m_NumSymbols(numSymbols) -{ - m_Symbols = new UInt32[m_NumSymbols]; -} - -CDecoder::~CDecoder() -{ - delete []m_Symbols; -} - -bool CDecoder::SetCodeLengths(const Byte *codeLengths) -{ - // int lenCounts[kNumBitsInLongestCode + 1], tmpPositions[kNumBitsInLongestCode + 1]; - int lenCounts[kNumBitsInLongestCode + 2], tmpPositions[kNumBitsInLongestCode + 1]; - int i; - for(i = 0; i <= kNumBitsInLongestCode; i++) - lenCounts[i] = 0; - UInt32 symbolIndex; - for (symbolIndex = 0; symbolIndex < m_NumSymbols; symbolIndex++) - lenCounts[codeLengths[symbolIndex]]++; - // lenCounts[0] = 0; - - // tmpPositions[0] = m_Positions[0] = m_Limitits[0] = 0; - m_Limitits[kNumBitsInLongestCode + 1] = 0; - m_Positions[kNumBitsInLongestCode + 1] = 0; - lenCounts[kNumBitsInLongestCode + 1] = 0; - - - UInt32 startPos = 0; - static const UInt32 kMaxValue = (1 << kNumBitsInLongestCode); - - for (i = kNumBitsInLongestCode; i > 0; i--) - { - startPos += lenCounts[i] << (kNumBitsInLongestCode - i); - if (startPos > kMaxValue) - return false; - m_Limitits[i] = startPos; - m_Positions[i] = m_Positions[i + 1] + lenCounts[i + 1]; - tmpPositions[i] = m_Positions[i] + lenCounts[i]; - - } - - // if _ZIP_MODE do not throw exception for trees containing only one node - // #ifndef _ZIP_MODE - if (startPos != kMaxValue) - return false; - // #endif - - for (symbolIndex = 0; symbolIndex < m_NumSymbols; symbolIndex++) - if (codeLengths[symbolIndex] != 0) - m_Symbols[--tmpPositions[codeLengths[symbolIndex]]] = symbolIndex; - return true; -} - -UInt32 CDecoder::DecodeSymbol(CInBit *inStream) -{ - UInt32 numBits = 0; - UInt32 value = inStream->GetValue(kNumBitsInLongestCode); - int i; - for(i = kNumBitsInLongestCode; i > 0; i--) - { - if (value < m_Limitits[i]) - { - numBits = i; - break; - } - } - if (i == 0) - return 0xFFFFFFFF; - inStream->MovePos(numBits); - UInt32 index = m_Positions[numBits] + - ((value - m_Limitits[numBits + 1]) >> (kNumBitsInLongestCode - numBits)); - if (index >= m_NumSymbols) - return 0xFFFFFFFF; - return m_Symbols[index]; -} - -}}} diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/ImplodeHuffmanDecoder.h b/desmume/src/windows/7z/CPP/7zip/Compress/ImplodeHuffmanDecoder.h deleted file mode 100644 index 8936c09e6..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/ImplodeHuffmanDecoder.h +++ /dev/null @@ -1,34 +0,0 @@ -// ImplodeHuffmanDecoder.h - -#ifndef __IMPLODE_HUFFMAN_DECODER_H -#define __IMPLODE_HUFFMAN_DECODER_H - -#include "../Common/InBuffer.h" - -#include "BitlDecoder.h" - -namespace NCompress { -namespace NImplode { -namespace NHuffman { - -const int kNumBitsInLongestCode = 16; - -typedef NBitl::CDecoder CInBit; - -class CDecoder -{ - UInt32 m_Limitits[kNumBitsInLongestCode + 2]; // m_Limitits[i] = value limit for symbols with length = i - UInt32 m_Positions[kNumBitsInLongestCode + 2]; // m_Positions[i] = index in m_Symbols[] of first symbol with length = i - UInt32 m_NumSymbols; // number of symbols in m_Symbols - UInt32 *m_Symbols; // symbols: at first with len=1 then 2, ... 15. -public: - CDecoder(UInt32 numSymbols); - ~CDecoder(); - - bool SetCodeLengths(const Byte *codeLengths); - UInt32 DecodeSymbol(CInBit *inStream); -}; - -}}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/LzOutWindow.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/LzOutWindow.cpp deleted file mode 100644 index b04789471..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/LzOutWindow.cpp +++ /dev/null @@ -1,14 +0,0 @@ -// LzOutWindow.cpp - -#include "StdAfx.h" - -#include "LzOutWindow.h" - -void CLzOutWindow::Init(bool solid) -{ - if (!solid) - COutBuffer::Init(); - #ifdef _NO_EXCEPTIONS - ErrorCode = S_OK; - #endif -} diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/LzOutWindow.h b/desmume/src/windows/7z/CPP/7zip/Compress/LzOutWindow.h deleted file mode 100644 index bbec7ad5b..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/LzOutWindow.h +++ /dev/null @@ -1,66 +0,0 @@ -// LzOutWindow.h - -#ifndef __LZ_OUT_WINDOW_H -#define __LZ_OUT_WINDOW_H - -#include "../IStream.h" - -#include "../Common/OutBuffer.h" - -#ifndef _NO_EXCEPTIONS -typedef COutBufferException CLzOutWindowException; -#endif - -class CLzOutWindow: public COutBuffer -{ -public: - void Init(bool solid = false); - - // distance >= 0, len > 0, - bool CopyBlock(UInt32 distance, UInt32 len) - { - UInt32 pos = _pos - distance - 1; - if (distance >= _pos) - { - if (!_overDict || distance >= _bufferSize) - return false; - pos += _bufferSize; - } - if (_limitPos - _pos > len && _bufferSize - pos > len) - { - const Byte *src = _buffer + pos; - Byte *dest = _buffer + _pos; - _pos += len; - do - *dest++ = *src++; - while(--len != 0); - } - else do - { - if (pos == _bufferSize) - pos = 0; - _buffer[_pos++] = _buffer[pos++]; - if (_pos == _limitPos) - FlushWithCheck(); - } - while(--len != 0); - return true; - } - - void PutByte(Byte b) - { - _buffer[_pos++] = b; - if (_pos == _limitPos) - FlushWithCheck(); - } - - Byte GetByte(UInt32 distance) const - { - UInt32 pos = _pos - distance - 1; - if (pos >= _bufferSize) - pos += _bufferSize; - return _buffer[pos]; - } -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/LzhDecoder.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/LzhDecoder.cpp deleted file mode 100644 index e1591f46f..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/LzhDecoder.cpp +++ /dev/null @@ -1,220 +0,0 @@ -// LzhDecoder.cpp - -#include "StdAfx.h" - -#include "LzhDecoder.h" - -#include "Windows/Defs.h" - -namespace NCompress{ -namespace NLzh { -namespace NDecoder { - -static const UInt32 kHistorySize = (1 << 16); - -static const int kBlockSizeBits = 16; -static const int kNumCBits = 9; -static const int kNumLevelBits = 5; // smallest integer such that (1 << kNumLevelBits) > kNumLevelSymbols/ - -UInt32 CCoder::ReadBits(int numBits) { return m_InBitStream.ReadBits(numBits); } - -HRESULT CCoder::ReadLevelTable() -{ - int n = ReadBits(kNumLevelBits); - if (n == 0) - { - m_LevelHuffman.Symbol = ReadBits(kNumLevelBits); - if (m_LevelHuffman.Symbol >= kNumLevelSymbols) - return S_FALSE; - } - else - { - if (n > kNumLevelSymbols) - return S_FALSE; - m_LevelHuffman.Symbol = -1; - Byte lens[kNumLevelSymbols]; - int i = 0; - while (i < n) - { - int c = m_InBitStream.ReadBits(3); - if (c == 7) - while (ReadBits(1)) - if (c++ > kMaxHuffmanLen) - return S_FALSE; - lens[i++] = (Byte)c; - if (i == kNumSpecLevelSymbols) - { - c = ReadBits(2); - while (--c >= 0) - lens[i++] = 0; - } - } - while (i < kNumLevelSymbols) - lens[i++] = 0; - m_LevelHuffman.SetCodeLengths(lens); - } - return S_OK; -} - -HRESULT CCoder::ReadPTable(int numBits) -{ - int n = ReadBits(numBits); - if (n == 0) - { - m_PHuffmanDecoder.Symbol = ReadBits(numBits); - if (m_PHuffmanDecoder.Symbol >= kNumDistanceSymbols) - return S_FALSE; - } - else - { - if (n > kNumDistanceSymbols) - return S_FALSE; - m_PHuffmanDecoder.Symbol = -1; - Byte lens[kNumDistanceSymbols]; - int i = 0; - while (i < n) - { - int c = m_InBitStream.ReadBits(3); - if (c == 7) - while (ReadBits(1)) - { - if (c > kMaxHuffmanLen) - return S_FALSE; - c++; - } - lens[i++] = (Byte)c; - } - while (i < kNumDistanceSymbols) - lens[i++] = 0; - m_PHuffmanDecoder.SetCodeLengths(lens); - } - return S_OK; -} - -HRESULT CCoder::ReadCTable() -{ - int n = ReadBits(kNumCBits); - if (n == 0) - { - m_CHuffmanDecoder.Symbol = ReadBits(kNumCBits); - if (m_CHuffmanDecoder.Symbol >= kNumCSymbols) - return S_FALSE; - } - else - { - if (n > kNumCSymbols) - return S_FALSE; - m_CHuffmanDecoder.Symbol = -1; - Byte lens[kNumCSymbols]; - int i = 0; - while (i < n) - { - int c = m_LevelHuffman.Decode(&m_InBitStream); - if (c < kNumSpecLevelSymbols) - { - if (c == 0) - c = 1; - else if (c == 1) - c = ReadBits(4) + 3; - else - c = ReadBits(kNumCBits) + 20; - while (--c >= 0) - { - if (i > kNumCSymbols) - return S_FALSE; - lens[i++] = 0; - } - } - else - lens[i++] = (Byte)(c - 2); - } - while (i < kNumCSymbols) - lens[i++] = 0; - m_CHuffmanDecoder.SetCodeLengths(lens); - } - return S_OK; -} - -STDMETHODIMP CCoder::CodeReal(ISequentialInStream *inStream, - ISequentialOutStream *outStream, const UInt64 * /* inSize */, const UInt64 *outSize, - ICompressProgressInfo *progress) -{ - if (outSize == NULL) - return E_INVALIDARG; - - if (!m_OutWindowStream.Create(kHistorySize)) - return E_OUTOFMEMORY; - if (!m_InBitStream.Create(1 << 20)) - return E_OUTOFMEMORY; - - UInt64 pos = 0; - m_OutWindowStream.SetStream(outStream); - m_OutWindowStream.Init(false); - m_InBitStream.SetStream(inStream); - m_InBitStream.Init(); - - CCoderReleaser coderReleaser(this); - - int pbit; - if (m_NumDictBits <= 13) - pbit = 4; - else - pbit = 5; - - UInt32 blockSize = 0; - - while(pos < *outSize) - { - // for (i = 0; i < dictSize; i++) dtext[i] = 0x20; - - if (blockSize == 0) - { - if (progress != NULL) - { - UInt64 packSize = m_InBitStream.GetProcessedSize(); - RINOK(progress->SetRatioInfo(&packSize, &pos)); - } - blockSize = ReadBits(kBlockSizeBits); - ReadLevelTable(); - ReadCTable(); - RINOK(ReadPTable(pbit)); - } - blockSize--; - UInt32 c = m_CHuffmanDecoder.Decode(&m_InBitStream); - if (c < 256) - { - m_OutWindowStream.PutByte((Byte)c); - pos++; - } - else if (c >= kNumCSymbols) - return S_FALSE; - else - { - // offset = (interface->method == LARC_METHOD_NUM) ? 0x100 - 2 : 0x100 - 3; - UInt32 len = c - 256 + kMinMatch; - UInt32 distance = m_PHuffmanDecoder.Decode(&m_InBitStream); - if (distance != 0) - distance = (1 << (distance - 1)) + ReadBits(distance - 1); - if (distance >= pos) - return S_FALSE; - if (pos + len > *outSize) - len = (UInt32)(*outSize - pos); - pos += len; - m_OutWindowStream.CopyBlock(distance, len); - } - } - coderReleaser.NeedFlush = false; - return m_OutWindowStream.Flush(); -} - -STDMETHODIMP CCoder::Code(ISequentialInStream *inStream, - ISequentialOutStream *outStream, const UInt64 *inSize, const UInt64 *outSize, - ICompressProgressInfo *progress) -{ - try { return CodeReal(inStream, outStream, inSize, outSize, progress);} - catch(const CInBufferException &e) { return e.ErrorCode; } - catch(const CLzOutWindowException &e) { return e.ErrorCode; } - catch(...) { return S_FALSE; } -} - -}}} diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/LzhDecoder.h b/desmume/src/windows/7z/CPP/7zip/Compress/LzhDecoder.h deleted file mode 100644 index 3048797fb..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/LzhDecoder.h +++ /dev/null @@ -1,106 +0,0 @@ -// LzhDecoder.h - -#ifndef __COMPRESS_LZH_DECODER_H -#define __COMPRESS_LZH_DECODER_H - -#include "../../Common/MyCom.h" - -#include "../ICoder.h" - -#include "../Common/InBuffer.h" - -#include "BitmDecoder.h" -#include "HuffmanDecoder.h" -#include "LzOutWindow.h" - -namespace NCompress { -namespace NLzh { -namespace NDecoder { - -const int kMaxHuffmanLen = 16; // Check it - -const int kNumSpecLevelSymbols = 3; -const int kNumLevelSymbols = kNumSpecLevelSymbols + kMaxHuffmanLen; - -const int kDictBitsMax = 16; -const int kNumDistanceSymbols = kDictBitsMax + 1; - -const int kMaxMatch = 256; -const int kMinMatch = 3; -const int kNumCSymbols = 256 + kMaxMatch + 2 - kMinMatch; - -template -class CHuffmanDecoder:public NCompress::NHuffman::CDecoder -{ -public: - int Symbol; - template - UInt32 Decode(TBitDecoder *bitStream) - { - if (Symbol >= 0) - return (UInt32)Symbol; - return DecodeSymbol(bitStream); - } -}; - -class CCoder : - public ICompressCoder, - public CMyUnknownImp -{ - CLzOutWindow m_OutWindowStream; - NBitm::CDecoder m_InBitStream; - - int m_NumDictBits; - - CHuffmanDecoder m_LevelHuffman; - CHuffmanDecoder m_PHuffmanDecoder; - CHuffmanDecoder m_CHuffmanDecoder; - - void ReleaseStreams() - { - m_OutWindowStream.ReleaseStream(); - m_InBitStream.ReleaseStream(); - } - - class CCoderReleaser - { - CCoder *m_Coder; - public: - bool NeedFlush; - CCoderReleaser(CCoder *coder): m_Coder(coder), NeedFlush(true) {} - ~CCoderReleaser() - { - if (NeedFlush) - m_Coder->m_OutWindowStream.Flush(); - m_Coder->ReleaseStreams(); - } - }; - friend class CCoderReleaser; - - void MakeTable(int nchar, Byte *bitlen, int tablebits, - UInt32 *table, int tablesize); - - UInt32 ReadBits(int numBits); - HRESULT ReadLevelTable(); - HRESULT ReadPTable(int numBits); - HRESULT ReadCTable(); - -public: - - MY_UNKNOWN_IMP - - STDMETHOD(CodeReal)(ISequentialInStream *inStream, - ISequentialOutStream *outStream, const UInt64 *inSize, const UInt64 *outSize, - ICompressProgressInfo *progress); - - STDMETHOD(Code)(ISequentialInStream *inStream, - ISequentialOutStream *outStream, const UInt64 *inSize, const UInt64 *outSize, - ICompressProgressInfo *progress); - - void SetDictionary(int numDictBits) { m_NumDictBits = numDictBits; } - CCoder(): m_NumDictBits(0) {} -}; - -}}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/LzmaDecoder.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/LzmaDecoder.cpp deleted file mode 100644 index 61a8cc009..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/LzmaDecoder.cpp +++ /dev/null @@ -1,190 +0,0 @@ -// LzmaDecoder.cpp - -#include "StdAfx.h" - -extern "C" -{ -#include "../../../C/Alloc.h" -} - -#include "../Common/StreamUtils.h" - -#include "LzmaDecoder.h" - -static HRESULT SResToHRESULT(SRes res) -{ - switch(res) - { - case SZ_OK: return S_OK; - case SZ_ERROR_MEM: return E_OUTOFMEMORY; - case SZ_ERROR_PARAM: return E_INVALIDARG; - case SZ_ERROR_UNSUPPORTED: return E_NOTIMPL; - // case SZ_ERROR_PROGRESS: return E_ABORT; - case SZ_ERROR_DATA: return S_FALSE; - } - return E_FAIL; -} - -namespace NCompress { -namespace NLzma { - -static const UInt32 kInBufSize = 1 << 20; - -CDecoder::CDecoder(): _inBuf(0), _outSizeDefined(false), FinishStream(false) -{ - LzmaDec_Construct(&_state); -} - -static void *SzAlloc(void *p, size_t size) { p = p; return MyAlloc(size); } -static void SzFree(void *p, void *address) { p = p; MyFree(address); } -static ISzAlloc g_Alloc = { SzAlloc, SzFree }; - -CDecoder::~CDecoder() -{ - LzmaDec_Free(&_state, &g_Alloc); - MyFree(_inBuf); -} - -STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte *prop, UInt32 size) -{ - RINOK(SResToHRESULT(LzmaDec_Allocate(&_state, prop, size, &g_Alloc))); - - if (_inBuf == 0) - { - _inBuf = (Byte *)MyAlloc(kInBufSize); - if (_inBuf == 0) - return E_OUTOFMEMORY; - } - - return S_OK; -} - -STDMETHODIMP CDecoder::GetInStreamProcessedSize(UInt64 *value) { *value = _inSizeProcessed; return S_OK; } -STDMETHODIMP CDecoder::SetInStream(ISequentialInStream *inStream) { _inStream = inStream; return S_OK; } -STDMETHODIMP CDecoder::ReleaseInStream() { _inStream.Release(); return S_OK; } - -STDMETHODIMP CDecoder::SetOutStreamSize(const UInt64 *outSize) -{ - _outSizeDefined = (outSize != NULL); - if (_outSizeDefined) - _outSize = *outSize; - - LzmaDec_Init(&_state); - - _inPos = _inSize = 0; - _inSizeProcessed = _outSizeProcessed = 0; - return S_OK; -} - -STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 * /* inSize */, const UInt64 *outSize, ICompressProgressInfo *progress) -{ - if (_inBuf == 0) - return S_FALSE; - SetOutStreamSize(outSize); - - for (;;) - { - if (_inPos == _inSize) - { - _inPos = _inSize = 0; - RINOK(inStream->Read(_inBuf, kInBufSize, &_inSize)); - } - - SizeT dicPos = _state.dicPos; - SizeT curSize = _state.dicBufSize - dicPos; - const UInt32 kStepSize = ((UInt32)1 << 22); - if (curSize > kStepSize) - curSize = (SizeT)kStepSize; - - ELzmaFinishMode finishMode = LZMA_FINISH_ANY; - if (_outSizeDefined) - { - const UInt64 rem = _outSize - _outSizeProcessed; - if (rem < curSize) - { - curSize = (SizeT)rem; - if (FinishStream) - finishMode = LZMA_FINISH_END; - } - } - - SizeT inSizeProcessed = _inSize - _inPos; - ELzmaStatus status; - SRes res = LzmaDec_DecodeToDic(&_state, dicPos + curSize, _inBuf + _inPos, &inSizeProcessed, finishMode, &status); - - _inPos += (UInt32)inSizeProcessed; - _inSizeProcessed += inSizeProcessed; - SizeT outSizeProcessed = _state.dicPos - dicPos; - _outSizeProcessed += outSizeProcessed; - - bool finished = (inSizeProcessed == 0 && outSizeProcessed == 0); - bool stopDecoding = (_outSizeDefined && _outSizeProcessed >= _outSize); - - if (res != 0 || _state.dicPos == _state.dicBufSize || finished || stopDecoding) - { - HRESULT res2 = WriteStream(outStream, _state.dic, _state.dicPos); - if (res != 0) - return S_FALSE; - RINOK(res2); - if (stopDecoding) - return S_OK; - if (finished) - return (status == LZMA_STATUS_FINISHED_WITH_MARK ? S_OK : S_FALSE); - } - if (_state.dicPos == _state.dicBufSize) - _state.dicPos = 0; - - if (progress != NULL) - { - RINOK(progress->SetRatioInfo(&_inSizeProcessed, &_outSizeProcessed)); - } - } -} - -#ifndef NO_READ_FROM_CODER - -STDMETHODIMP CDecoder::Read(void *data, UInt32 size, UInt32 *processedSize) -{ - if (processedSize) - *processedSize = 0; - do - { - if (_inPos == _inSize) - { - _inPos = _inSize = 0; - RINOK(_inStream->Read(_inBuf, kInBufSize, &_inSize)); - } - { - SizeT inProcessed = _inSize - _inPos; - - if (_outSizeDefined) - { - const UInt64 rem = _outSize - _outSizeProcessed; - if (rem < size) - size = (UInt32)rem; - } - - SizeT outProcessed = size; - ELzmaStatus status; - SRes res = LzmaDec_DecodeToBuf(&_state, (Byte *)data, &outProcessed, - _inBuf + _inPos, &inProcessed, LZMA_FINISH_ANY, &status); - _inPos += (UInt32)inProcessed; - _inSizeProcessed += inProcessed; - _outSizeProcessed += outProcessed; - size -= (UInt32)outProcessed; - data = (Byte *)data + outProcessed; - if (processedSize) - *processedSize += (UInt32)outProcessed; - RINOK(SResToHRESULT(res)); - if (inProcessed == 0 && outProcessed == 0) - return S_OK; - } - } - while (size != 0); - return S_OK; -} - -#endif - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/LzmaDecoder.h b/desmume/src/windows/7z/CPP/7zip/Compress/LzmaDecoder.h deleted file mode 100644 index 16b4791b0..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/LzmaDecoder.h +++ /dev/null @@ -1,73 +0,0 @@ -// LzmaDecoder.h - -#ifndef __LZMA_DECODER_H -#define __LZMA_DECODER_H - -extern "C" -{ -#include "../../../C/LzmaDec.h" -} - -#include "../../Common/MyCom.h" -#include "../ICoder.h" - -namespace NCompress { -namespace NLzma { - -class CDecoder: - public ICompressCoder, - public ICompressSetDecoderProperties2, - public ICompressGetInStreamProcessedSize, - #ifndef NO_READ_FROM_CODER - public ICompressSetInStream, - public ICompressSetOutStreamSize, - public ISequentialInStream, - #endif - public CMyUnknownImp -{ - CMyComPtr _inStream; - Byte *_inBuf; - UInt32 _inPos; - UInt32 _inSize; - CLzmaDec _state; - bool _outSizeDefined; - UInt64 _outSize; - UInt64 _inSizeProcessed; - UInt64 _outSizeProcessed; -public: - - #ifndef NO_READ_FROM_CODER - MY_UNKNOWN_IMP5( - ICompressSetDecoderProperties2, - ICompressGetInStreamProcessedSize, - ICompressSetInStream, - ICompressSetOutStreamSize, - ISequentialInStream) - #else - MY_UNKNOWN_IMP2( - ICompressSetDecoderProperties2, - ICompressGetInStreamProcessedSize) - #endif - - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size); - STDMETHOD(GetInStreamProcessedSize)(UInt64 *value); - STDMETHOD(SetInStream)(ISequentialInStream *inStream); - STDMETHOD(ReleaseInStream)(); - STDMETHOD(SetOutStreamSize)(const UInt64 *outSize); - - #ifndef NO_READ_FROM_CODER - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); - #endif - - bool FinishStream; - - CDecoder(); - virtual ~CDecoder(); - -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/LzmaRegister.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/LzmaRegister.cpp deleted file mode 100644 index 9c67eaf94..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/LzmaRegister.cpp +++ /dev/null @@ -1,20 +0,0 @@ -// LzmaRegister.cpp - -#include "StdAfx.h" - -#include "../Common/RegisterCodec.h" - -#include "LzmaDecoder.h" - -static void *CreateCodec() { return (void *)(ICompressCoder *)(new NCompress::NLzma::CDecoder); } -#ifndef EXTRACT_ONLY -#include "LzmaEncoder.h" -static void *CreateCodecOut() { return (void *)(ICompressCoder *)(new NCompress::NLzma::CEncoder); } -#else -#define CreateCodecOut 0 -#endif - -static CCodecInfo g_CodecInfo = - { CreateCodec, CreateCodecOut, 0x030101, L"LZMA", 1, false }; - -REGISTER_CODEC(LZMA) diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/Mtf8.h b/desmume/src/windows/7z/CPP/7zip/Compress/Mtf8.h deleted file mode 100644 index e5e0046de..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/Mtf8.h +++ /dev/null @@ -1,196 +0,0 @@ -// Mtf8.h - -#ifndef __COMPRESS_MTF8_H -#define __COMPRESS_MTF8_H - -#include "../../Common/Types.h" - -namespace NCompress { - -struct CMtf8Encoder -{ - Byte Buf[256]; - - int FindAndMove(Byte v) - { - int pos; - for (pos = 0; Buf[pos] != v; pos++); - int resPos = pos; - for (; pos >= 8; pos -= 8) - { - Buf[pos] = Buf[pos - 1]; - Buf[pos - 1] = Buf[pos - 2]; - Buf[pos - 2] = Buf[pos - 3]; - Buf[pos - 3] = Buf[pos - 4]; - Buf[pos - 4] = Buf[pos - 5]; - Buf[pos - 5] = Buf[pos - 6]; - Buf[pos - 6] = Buf[pos - 7]; - Buf[pos - 7] = Buf[pos - 8]; - } - for (; pos > 0; pos--) - Buf[pos] = Buf[pos - 1]; - Buf[0] = v; - return resPos; - } -}; - -/* -struct CMtf8Decoder -{ - Byte Buf[256]; - - void Init(int) {}; - Byte GetHead() const { return Buf[0]; } - Byte GetAndMove(int pos) - { - Byte res = Buf[pos]; - for (; pos >= 8; pos -= 8) - { - Buf[pos] = Buf[pos - 1]; - Buf[pos - 1] = Buf[pos - 2]; - Buf[pos - 2] = Buf[pos - 3]; - Buf[pos - 3] = Buf[pos - 4]; - Buf[pos - 4] = Buf[pos - 5]; - Buf[pos - 5] = Buf[pos - 6]; - Buf[pos - 6] = Buf[pos - 7]; - Buf[pos - 7] = Buf[pos - 8]; - } - for (; pos > 0; pos--) - Buf[pos] = Buf[pos - 1]; - Buf[0] = res; - return res; - } -}; -*/ - -#ifdef _WIN64 -#define MODE_64BIT -#endif - -#ifdef MODE_64BIT -typedef UInt64 CMtfVar; -#define MTF_MOVS 3 -#else -typedef UInt32 CMtfVar; -#define MTF_MOVS 2 -#endif - -#define MTF_MASK ((1 << MTF_MOVS) - 1) - - -struct CMtf8Decoder -{ - CMtfVar Buf[256 >> MTF_MOVS]; - - void StartInit() { memset(Buf, 0, sizeof(Buf)); } - void Add(unsigned int pos, Byte val) { Buf[pos >> MTF_MOVS] |= ((CMtfVar)val << ((pos & MTF_MASK) << 3)); } - Byte GetHead() const { return (Byte)Buf[0]; } - Byte GetAndMove(unsigned int pos) - { - UInt32 lim = ((UInt32)pos >> MTF_MOVS); - pos = (pos & MTF_MASK) << 3; - CMtfVar prev = (Buf[lim] >> pos) & 0xFF; - - UInt32 i = 0; - if ((lim & 1) != 0) - { - CMtfVar next = Buf[0]; - Buf[0] = (next << 8) | prev; - prev = (next >> (MTF_MASK << 3)); - i = 1; - lim -= 1; - } - for (; i < lim; i += 2) - { - CMtfVar next = Buf[i]; - Buf[i] = (next << 8) | prev; - prev = (next >> (MTF_MASK << 3)); - next = Buf[i + 1]; - Buf[i + 1] = (next << 8) | prev; - prev = (next >> (MTF_MASK << 3)); - } - CMtfVar next = Buf[i]; - CMtfVar mask = (((CMtfVar)0x100 << pos) - 1); - Buf[i] = (next & ~mask) | (((next << 8) | prev) & mask); - return (Byte)Buf[0]; - } -}; - -/* -const int kSmallSize = 64; -class CMtf8Decoder -{ - Byte SmallBuffer[kSmallSize]; - int SmallSize; - Byte Counts[16]; - int Size; -public: - Byte Buf[256]; - - Byte GetHead() const - { - if (SmallSize > 0) - return SmallBuffer[kSmallSize - SmallSize]; - return Buf[0]; - } - - void Init(int size) - { - Size = size; - SmallSize = 0; - for (int i = 0; i < 16; i++) - { - Counts[i] = ((size >= 16) ? 16 : size); - size -= Counts[i]; - } - } - - Byte GetAndMove(int pos) - { - if (pos < SmallSize) - { - Byte *p = SmallBuffer + kSmallSize - SmallSize; - Byte res = p[pos]; - for (; pos > 0; pos--) - p[pos] = p[pos - 1]; - SmallBuffer[kSmallSize - SmallSize] = res; - return res; - } - if (SmallSize == kSmallSize) - { - int i = Size - 1; - int g = 16; - do - { - g--; - int offset = (g << 4); - for (int t = Counts[g] - 1; t >= 0; t--, i--) - Buf[i] = Buf[offset + t]; - } - while(g != 0); - - for (i = kSmallSize - 1; i >= 0; i--) - Buf[i] = SmallBuffer[i]; - Init(Size); - } - pos -= SmallSize; - int g; - for (g = 0; pos >= Counts[g]; g++) - pos -= Counts[g]; - int offset = (g << 4); - Byte res = Buf[offset + pos]; - for (pos; pos < 16 - 1; pos++) - Buf[offset + pos] = Buf[offset + pos + 1]; - - SmallSize++; - SmallBuffer[kSmallSize - SmallSize] = res; - - Counts[g]--; - return res; - } -}; -*/ - -} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/PpmdContext.h b/desmume/src/windows/7z/CPP/7zip/Compress/PpmdContext.h deleted file mode 100644 index 11502a951..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/PpmdContext.h +++ /dev/null @@ -1,489 +0,0 @@ -// PpmdContext.h -// This code is based on Dmitry Shkarin's PPMdH code - -#ifndef __COMPRESS_PPMD_CONTEXT_H -#define __COMPRESS_PPMD_CONTEXT_H - -#include "../../Common/Types.h" - -#include "PpmdSubAlloc.h" -#include "RangeCoder.h" - -namespace NCompress { -namespace NPpmd { - -const int INT_BITS=7, PERIOD_BITS=7, TOT_BITS=INT_BITS+PERIOD_BITS, - INTERVAL=1 << INT_BITS, BIN_SCALE=1 << TOT_BITS, MAX_FREQ=124; - -struct SEE2_CONTEXT -{ - // SEE-contexts for PPM-contexts with masked symbols - UInt16 Summ; - Byte Shift, Count; - void init(int InitVal) { Summ = (UInt16)(InitVal << (Shift=PERIOD_BITS-4)); Count=4; } - unsigned int getMean() - { - unsigned int RetVal=(Summ >> Shift); - Summ = (UInt16)(Summ - RetVal); - return RetVal+(RetVal == 0); - } - void update() - { - if (Shift < PERIOD_BITS && --Count == 0) - { - Summ <<= 1; - Count = (Byte)(3 << Shift++); - } - } -}; - -struct PPM_CONTEXT -{ - UInt16 NumStats; // sizeof(UInt16) > sizeof(Byte) - UInt16 SummFreq; - - struct STATE - { - Byte Symbol, Freq; - UInt16 SuccessorLow; - UInt16 SuccessorHigh; - - UInt32 GetSuccessor() const { return SuccessorLow | ((UInt32)SuccessorHigh << 16); } - void SetSuccessor(UInt32 v) - { - SuccessorLow = (UInt16)(v & 0xFFFF); - SuccessorHigh = (UInt16)((v >> 16) & 0xFFFF); - } - }; - - UInt32 Stats; - UInt32 Suffix; - - PPM_CONTEXT* createChild(CSubAllocator &subAllocator, STATE* pStats, STATE& FirstState) - { - PPM_CONTEXT* pc = (PPM_CONTEXT*) subAllocator.AllocContext(); - if (pc) - { - pc->NumStats = 1; - pc->oneState() = FirstState; - pc->Suffix = subAllocator.GetOffset(this); - pStats->SetSuccessor(subAllocator.GetOffsetNoCheck(pc)); - } - return pc; - } - - STATE& oneState() const { return (STATE&) SummFreq; } -}; - -///////////////////////////////// - -const UInt16 InitBinEsc[] = - {0x3CDD, 0x1F3F, 0x59BF, 0x48F3, 0x64A1, 0x5ABC, 0x6632, 0x6051}; - -struct CInfo -{ - CSubAllocator SubAllocator; - SEE2_CONTEXT SEE2Cont[25][16], DummySEE2Cont; - PPM_CONTEXT * MinContext, * MaxContext; - - PPM_CONTEXT::STATE* FoundState; // found next state transition - int NumMasked, InitEsc, OrderFall, RunLength, InitRL, MaxOrder; - Byte CharMask[256], NS2Indx[256], NS2BSIndx[256], HB2Flag[256]; - Byte EscCount, PrintCount, PrevSuccess, HiBitsFlag; - UInt16 BinSumm[128][64]; // binary SEE-contexts - - UInt16 &GetBinSumm(const PPM_CONTEXT::STATE &rs, int numStates) - { - HiBitsFlag = HB2Flag[FoundState->Symbol]; - return BinSumm[rs.Freq - 1][ - PrevSuccess + NS2BSIndx[numStates - 1] + - HiBitsFlag + 2 * HB2Flag[rs.Symbol] + - ((RunLength >> 26) & 0x20)]; - } - - PPM_CONTEXT *GetContext(UInt32 offset) const { return (PPM_CONTEXT *)SubAllocator.GetPtr(offset); } - PPM_CONTEXT *GetContextNoCheck(UInt32 offset) const { return (PPM_CONTEXT *)SubAllocator.GetPtrNoCheck(offset); } - PPM_CONTEXT::STATE *GetState(UInt32 offset) const { return (PPM_CONTEXT::STATE *)SubAllocator.GetPtr(offset); } - PPM_CONTEXT::STATE *GetStateNoCheck(UInt32 offset) const { return (PPM_CONTEXT::STATE *)SubAllocator.GetPtr(offset); } - - void RestartModelRare() - { - int i, k, m; - memset(CharMask,0,sizeof(CharMask)); - SubAllocator.InitSubAllocator(); - InitRL = -((MaxOrder < 12) ? MaxOrder : 12) - 1; - MinContext = MaxContext = (PPM_CONTEXT*) SubAllocator.AllocContext(); - MinContext->Suffix = 0; - OrderFall = MaxOrder; - MinContext->SummFreq = (UInt16)((MinContext->NumStats = 256) + 1); - FoundState = (PPM_CONTEXT::STATE*)SubAllocator.AllocUnits(256 / 2); - MinContext->Stats = SubAllocator.GetOffsetNoCheck(FoundState); - PrevSuccess = 0; - for (RunLength = InitRL, i = 0; i < 256; i++) - { - PPM_CONTEXT::STATE &state = FoundState[i]; - state.Symbol = (Byte)i; - state.Freq = 1; - state.SetSuccessor(0); - } - for (i = 0; i < 128; i++) - for (k = 0; k < 8; k++) - for ( m=0; m < 64; m += 8) - BinSumm[i][k + m] = (UInt16)(BIN_SCALE - InitBinEsc[k] / (i + 2)); - for (i = 0; i < 25; i++) - for (k = 0; k < 16; k++) - SEE2Cont[i][k].init(5*i+10); - } - - void StartModelRare(int maxOrder) - { - int i, k, m ,Step; - EscCount=PrintCount=1; - if (maxOrder < 2) - { - memset(CharMask,0,sizeof(CharMask)); - OrderFall = MaxOrder; - MinContext = MaxContext; - while (MinContext->Suffix != 0) - { - MinContext = GetContextNoCheck(MinContext->Suffix); - OrderFall--; - } - FoundState = GetState(MinContext->Stats); - MinContext = MaxContext; - } - else - { - MaxOrder = maxOrder; - RestartModelRare(); - NS2BSIndx[0] = 2 * 0; - NS2BSIndx[1] = 2 * 1; - memset(NS2BSIndx + 2, 2 * 2, 9); - memset(NS2BSIndx + 11, 2 * 3, 256 - 11); - for (i = 0; i < 3; i++) - NS2Indx[i] = (Byte)i; - for (m = i, k = Step = 1; i < 256; i++) - { - NS2Indx[i] = (Byte)m; - if ( !--k ) - { - k = ++Step; - m++; - } - } - memset(HB2Flag, 0, 0x40); - memset(HB2Flag + 0x40, 0x08, 0x100 - 0x40); - DummySEE2Cont.Shift = PERIOD_BITS; - } - } - - PPM_CONTEXT* CreateSuccessors(bool skip, PPM_CONTEXT::STATE* p1) - { - // static UpState declaration bypasses IntelC bug - // static PPM_CONTEXT::STATE UpState; - PPM_CONTEXT::STATE UpState; - - PPM_CONTEXT *pc = MinContext; - PPM_CONTEXT *UpBranch = GetContext(FoundState->GetSuccessor()); - PPM_CONTEXT::STATE * p, * ps[MAX_O], ** pps = ps; - if ( !skip ) - { - *pps++ = FoundState; - if ( !pc->Suffix ) - goto NO_LOOP; - } - if ( p1 ) - { - p = p1; - pc = GetContext(pc->Suffix); - goto LOOP_ENTRY; - } - do - { - pc = GetContext(pc->Suffix); - if (pc->NumStats != 1) - { - if ((p = GetStateNoCheck(pc->Stats))->Symbol != FoundState->Symbol) - do { p++; } while (p->Symbol != FoundState->Symbol); - } - else - p = &(pc->oneState()); -LOOP_ENTRY: - if (GetContext(p->GetSuccessor()) != UpBranch) - { - pc = GetContext(p->GetSuccessor()); - break; - } - *pps++ = p; - } - while ( pc->Suffix ); -NO_LOOP: - if (pps == ps) - return pc; - UpState.Symbol = *(Byte*) UpBranch; - UpState.SetSuccessor(SubAllocator.GetOffset(UpBranch) + 1); - if (pc->NumStats != 1) - { - if ((p = GetStateNoCheck(pc->Stats))->Symbol != UpState.Symbol) - do { p++; } while (p->Symbol != UpState.Symbol); - unsigned int cf = p->Freq-1; - unsigned int s0 = pc->SummFreq - pc->NumStats - cf; - UpState.Freq = (Byte)(1 + ((2 * cf <= s0) ? (5 * cf > s0) : - ((2 * cf + 3 * s0 - 1) / (2 * s0)))); - } - else - UpState.Freq = pc->oneState().Freq; - do - { - pc = pc->createChild(SubAllocator, *--pps, UpState); - if ( !pc ) - return NULL; - } - while (pps != ps); - return pc; - } - - void UpdateModel() - { - PPM_CONTEXT::STATE fs = *FoundState, * p = NULL; - PPM_CONTEXT* pc, * Successor; - unsigned int ns1, ns, cf, sf, s0; - if (fs.Freq < MAX_FREQ / 4 && MinContext->Suffix != 0) - { - pc = GetContextNoCheck(MinContext->Suffix); - - if (pc->NumStats != 1) - { - if ((p = GetStateNoCheck(pc->Stats))->Symbol != fs.Symbol) - { - do { p++; } while (p->Symbol != fs.Symbol); - if (p[0].Freq >= p[-1].Freq) - { - _PPMD_SWAP(p[0],p[-1]); - p--; - } - } - if (p->Freq < MAX_FREQ-9) - { - p->Freq += 2; - pc->SummFreq += 2; - } - } - else - { - p = &(pc->oneState()); - p->Freq = (Byte)(p->Freq + ((p->Freq < 32) ? 1 : 0)); - } - } - if ( !OrderFall ) - { - MinContext = MaxContext = CreateSuccessors(true, p); - FoundState->SetSuccessor(SubAllocator.GetOffset(MinContext)); - if (MinContext == 0) - goto RESTART_MODEL; - return; - } - *SubAllocator.pText++ = fs.Symbol; - Successor = (PPM_CONTEXT*) SubAllocator.pText; - if (SubAllocator.pText >= SubAllocator.UnitsStart) - goto RESTART_MODEL; - if (fs.GetSuccessor() != 0) - { - if ((Byte *)GetContext(fs.GetSuccessor()) <= SubAllocator.pText) - { - PPM_CONTEXT* cs = CreateSuccessors(false, p); - fs.SetSuccessor(SubAllocator.GetOffset(cs)); - if (cs == NULL) - goto RESTART_MODEL; - } - if ( !--OrderFall ) - { - Successor = GetContext(fs.GetSuccessor()); - SubAllocator.pText -= (MaxContext != MinContext); - } - } - else - { - FoundState->SetSuccessor(SubAllocator.GetOffsetNoCheck(Successor)); - fs.SetSuccessor(SubAllocator.GetOffsetNoCheck(MinContext)); - } - s0 = MinContext->SummFreq - (ns = MinContext->NumStats) - (fs.Freq - 1); - for (pc = MaxContext; pc != MinContext; pc = GetContext(pc->Suffix)) - { - if ((ns1 = pc->NumStats) != 1) - { - if ((ns1 & 1) == 0) - { - void *ppp = SubAllocator.ExpandUnits(GetState(pc->Stats), ns1 >> 1); - pc->Stats = SubAllocator.GetOffset(ppp); - if (!ppp) - goto RESTART_MODEL; - } - pc->SummFreq = (UInt16)(pc->SummFreq + (2 * ns1 < ns) + 2 * ((4 * ns1 <= ns) & - (pc->SummFreq <= 8 * ns1))); - } - else - { - p = (PPM_CONTEXT::STATE*) SubAllocator.AllocUnits(1); - if ( !p ) - goto RESTART_MODEL; - *p = pc->oneState(); - pc->Stats = SubAllocator.GetOffsetNoCheck(p); - if (p->Freq < MAX_FREQ / 4 - 1) - p->Freq <<= 1; - else - p->Freq = MAX_FREQ - 4; - pc->SummFreq = (UInt16)(p->Freq + InitEsc + (ns > 3)); - } - cf = 2 * fs.Freq * (pc->SummFreq+6); - sf = s0 + pc->SummFreq; - if (cf < 6 * sf) - { - cf = 1 + (cf > sf)+(cf >= 4 * sf); - pc->SummFreq += 3; - } - else - { - cf = 4 + (cf >= 9 * sf) + (cf >= 12 * sf) + (cf >= 15 * sf); - pc->SummFreq = (UInt16)(pc->SummFreq + cf); - } - p = GetState(pc->Stats) + ns1; - p->SetSuccessor(SubAllocator.GetOffset(Successor)); - p->Symbol = fs.Symbol; - p->Freq = (Byte)cf; - pc->NumStats = (UInt16)++ns1; - } - MaxContext = MinContext = GetContext(fs.GetSuccessor()); - return; -RESTART_MODEL: - RestartModelRare(); - EscCount = 0; - PrintCount = 0xFF; - } - - void ClearMask() - { - EscCount = 1; - memset(CharMask, 0, sizeof(CharMask)); - // if (++PrintCount == 0) - // PrintInfo(DecodedFile,EncodedFile); - } - - void update1(PPM_CONTEXT::STATE* p) - { - (FoundState = p)->Freq += 4; - MinContext->SummFreq += 4; - if (p[0].Freq > p[-1].Freq) - { - _PPMD_SWAP(p[0],p[-1]); - FoundState = --p; - if (p->Freq > MAX_FREQ) - rescale(); - } - } - - - void update2(PPM_CONTEXT::STATE* p) - { - (FoundState = p)->Freq += 4; - MinContext->SummFreq += 4; - if (p->Freq > MAX_FREQ) - rescale(); - EscCount++; - RunLength = InitRL; - } - - SEE2_CONTEXT* makeEscFreq2(int Diff, UInt32 &scale) - { - SEE2_CONTEXT* psee2c; - if (MinContext->NumStats != 256) - { - psee2c = SEE2Cont[NS2Indx[Diff-1]] + - (Diff < (GetContext(MinContext->Suffix))->NumStats - MinContext->NumStats) + - 2 * (MinContext->SummFreq < 11 * MinContext->NumStats) + - 4 * (NumMasked > Diff) + - HiBitsFlag; - scale = psee2c->getMean(); - } - else - { - psee2c = &DummySEE2Cont; - scale = 1; - } - return psee2c; - } - - - - void rescale() - { - int OldNS = MinContext->NumStats, i = MinContext->NumStats - 1, Adder, EscFreq; - PPM_CONTEXT::STATE* p1, * p; - PPM_CONTEXT::STATE *stats = GetStateNoCheck(MinContext->Stats); - for (p = FoundState; p != stats; p--) - _PPMD_SWAP(p[0], p[-1]); - stats->Freq += 4; - MinContext->SummFreq += 4; - EscFreq = MinContext->SummFreq - p->Freq; - Adder = (OrderFall != 0); - p->Freq = (Byte)((p->Freq + Adder) >> 1); - MinContext->SummFreq = p->Freq; - do - { - EscFreq -= (++p)->Freq; - p->Freq = (Byte)((p->Freq + Adder) >> 1); - MinContext->SummFreq = (UInt16)(MinContext->SummFreq + p->Freq); - if (p[0].Freq > p[-1].Freq) - { - PPM_CONTEXT::STATE tmp = *(p1 = p); - do - { - p1[0] = p1[-1]; - } - while (--p1 != stats && tmp.Freq > p1[-1].Freq); - *p1 = tmp; - } - } - while ( --i ); - if (p->Freq == 0) - { - do { i++; } while ((--p)->Freq == 0); - EscFreq += i; - MinContext->NumStats = (UInt16)(MinContext->NumStats - i); - if (MinContext->NumStats == 1) - { - PPM_CONTEXT::STATE tmp = *stats; - do { tmp.Freq = (Byte)(tmp.Freq - (tmp.Freq >> 1)); EscFreq >>= 1; } while (EscFreq > 1); - SubAllocator.FreeUnits(stats, (OldNS+1) >> 1); - *(FoundState = &MinContext->oneState()) = tmp; return; - } - } - EscFreq -= (EscFreq >> 1); - MinContext->SummFreq = (UInt16)(MinContext->SummFreq + EscFreq); - int n0 = (OldNS+1) >> 1, n1 = (MinContext->NumStats + 1) >> 1; - if (n0 != n1) - MinContext->Stats = SubAllocator.GetOffset(SubAllocator.ShrinkUnits(stats, n0, n1)); - FoundState = GetState(MinContext->Stats); - } - - void NextContext() - { - PPM_CONTEXT *c = GetContext(FoundState->GetSuccessor()); - if (!OrderFall && (Byte *)c > SubAllocator.pText) - MinContext = MaxContext = c; - else - { - UpdateModel(); - if (EscCount == 0) - ClearMask(); - } - } -}; - -// Tabulated escapes for exponential symbol distribution -const Byte ExpEscape[16]={ 25,14, 9, 7, 5, 5, 4, 4, 4, 3, 3, 3, 2, 2, 2, 2 }; -#define GET_MEAN(SUMM,SHIFT,ROUND) ((SUMM+(1 << (SHIFT-ROUND))) >> (SHIFT)) - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/PpmdDecode.h b/desmume/src/windows/7z/CPP/7zip/Compress/PpmdDecode.h deleted file mode 100644 index 3ad037da6..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/PpmdDecode.h +++ /dev/null @@ -1,154 +0,0 @@ -// PpmdDecode.h -// This code is based on Dmitry Shkarin's PPMdH code - -#ifndef __COMPRESS_PPMD_DECODE_H -#define __COMPRESS_PPMD_DECODE_H - -#include "PpmdContext.h" - -namespace NCompress { -namespace NPpmd { - -class CRangeDecoderVirt -{ -public: - virtual UInt32 GetThreshold(UInt32 total) = 0; - virtual void Decode(UInt32 start, UInt32 size) = 0; - virtual UInt32 DecodeBit(UInt32 size0, UInt32 numTotalBits) = 0; -}; - -typedef NRangeCoder::CDecoder CRangeDecoderMy; - -class CRangeDecoder:public CRangeDecoderVirt, public CRangeDecoderMy -{ - UInt32 GetThreshold(UInt32 total) { return CRangeDecoderMy::GetThreshold(total); } - void Decode(UInt32 start, UInt32 size) { CRangeDecoderMy::Decode(start, size); } - UInt32 DecodeBit(UInt32 size0, UInt32 numTotalBits) { return CRangeDecoderMy::DecodeBit(size0, numTotalBits); } -}; - -struct CDecodeInfo: public CInfo -{ - void DecodeBinSymbol(CRangeDecoderVirt *rangeDecoder) - { - PPM_CONTEXT::STATE& rs = MinContext->oneState(); - UInt16& bs = GetBinSumm(rs, GetContextNoCheck(MinContext->Suffix)->NumStats); - if (rangeDecoder->DecodeBit(bs, TOT_BITS) == 0) - { - FoundState = &rs; - rs.Freq = (Byte)(rs.Freq + (rs.Freq < 128 ? 1: 0)); - bs = (UInt16)(bs + INTERVAL - GET_MEAN(bs, PERIOD_BITS, 2)); - PrevSuccess = 1; - RunLength++; - } - else - { - bs = (UInt16)(bs - GET_MEAN(bs, PERIOD_BITS, 2)); - InitEsc = ExpEscape[bs >> 10]; - NumMasked = 1; - CharMask[rs.Symbol] = EscCount; - PrevSuccess = 0; - FoundState = NULL; - } - } - - void DecodeSymbol1(CRangeDecoderVirt *rangeDecoder) - { - PPM_CONTEXT::STATE* p = GetStateNoCheck(MinContext->Stats); - int i, count, hiCnt; - if ((count = rangeDecoder->GetThreshold(MinContext->SummFreq)) < (hiCnt = p->Freq)) - { - PrevSuccess = (2 * hiCnt > MinContext->SummFreq); - RunLength += PrevSuccess; - rangeDecoder->Decode(0, p->Freq); // MinContext->SummFreq); - (FoundState = p)->Freq = (Byte)(hiCnt += 4); - MinContext->SummFreq += 4; - if (hiCnt > MAX_FREQ) - rescale(); - return; - } - PrevSuccess = 0; - i = MinContext->NumStats - 1; - while ((hiCnt += (++p)->Freq) <= count) - if (--i == 0) - { - HiBitsFlag = HB2Flag[FoundState->Symbol]; - rangeDecoder->Decode(hiCnt, MinContext->SummFreq - hiCnt); // , MinContext->SummFreq); - CharMask[p->Symbol] = EscCount; - i = (NumMasked = MinContext->NumStats)-1; - FoundState = NULL; - do { CharMask[(--p)->Symbol] = EscCount; } while ( --i ); - return; - } - rangeDecoder->Decode(hiCnt - p->Freq, p->Freq); // , MinContext->SummFreq); - update1(p); - } - - - void DecodeSymbol2(CRangeDecoderVirt *rangeDecoder) - { - int count, hiCnt, i = MinContext->NumStats - NumMasked; - UInt32 freqSum; - SEE2_CONTEXT* psee2c = makeEscFreq2(i, freqSum); - PPM_CONTEXT::STATE* ps[256], ** pps = ps, * p = GetStateNoCheck(MinContext->Stats)-1; - hiCnt = 0; - do - { - do { p++; } while (CharMask[p->Symbol] == EscCount); - hiCnt += p->Freq; - *pps++ = p; - } - while ( --i ); - - freqSum += hiCnt; - count = rangeDecoder->GetThreshold(freqSum); - - p = *(pps = ps); - if (count < hiCnt) - { - hiCnt = 0; - while ((hiCnt += p->Freq) <= count) - p=*++pps; - rangeDecoder->Decode(hiCnt - p->Freq, p->Freq); // , freqSum); - - psee2c->update(); - update2(p); - } - else - { - rangeDecoder->Decode(hiCnt, freqSum - hiCnt); // , freqSum); - - i = MinContext->NumStats - NumMasked; - pps--; - do { CharMask[(*++pps)->Symbol] = EscCount; } while ( --i ); - psee2c->Summ = (UInt16)(psee2c->Summ + freqSum); - NumMasked = MinContext->NumStats; - } - } - - int DecodeSymbol(CRangeDecoderVirt *rangeDecoder) - { - if (MinContext->NumStats != 1) - DecodeSymbol1(rangeDecoder); - else - DecodeBinSymbol(rangeDecoder); - while ( !FoundState ) - { - do - { - OrderFall++; - MinContext = GetContext(MinContext->Suffix); - if (MinContext == 0) - return -1; - } - while (MinContext->NumStats == NumMasked); - DecodeSymbol2(rangeDecoder); - } - Byte symbol = FoundState->Symbol; - NextContext(); - return symbol; - } -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/PpmdDecoder.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/PpmdDecoder.cpp deleted file mode 100644 index 9049a472b..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/PpmdDecoder.cpp +++ /dev/null @@ -1,182 +0,0 @@ -// PpmdDecoder.cpp - -#include "StdAfx.h" - -#include "Common/Defs.h" -#include "Windows/Defs.h" - -#include "PpmdDecoder.h" - -namespace NCompress { -namespace NPpmd { - -const int kLenIdFinished = -1; -const int kLenIdNeedInit = -2; - -STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte *properties, UInt32 size) -{ - if (size < 5) - return E_INVALIDARG; - _order = properties[0]; - _usedMemorySize = 0; - for (int i = 0; i < 4; i++) - _usedMemorySize += ((UInt32)(properties[1 + i])) << (i * 8); - - if (_usedMemorySize > kMaxMemBlockSize) - return E_NOTIMPL; - - if (!_rangeDecoder.Create(1 << 20)) - return E_OUTOFMEMORY; - if (!_info.SubAllocator.StartSubAllocator(_usedMemorySize)) - return E_OUTOFMEMORY; - - return S_OK; -} - -class CDecoderFlusher -{ - CDecoder *_coder; -public: - bool NeedFlush; - CDecoderFlusher(CDecoder *coder): _coder(coder), NeedFlush(true) {} - ~CDecoderFlusher() - { - if (NeedFlush) - _coder->Flush(); - _coder->ReleaseStreams(); - } -}; - -HRESULT CDecoder::CodeSpec(UInt32 size, Byte *memStream) -{ - if (_outSizeDefined) - { - const UInt64 rem = _outSize - _processedSize; - if (size > rem) - size = (UInt32)rem; - } - const UInt32 startSize = size; - - if (_remainLen == kLenIdFinished) - return S_OK; - if (_remainLen == kLenIdNeedInit) - { - _rangeDecoder.Init(); - _remainLen = 0; - _info.MaxOrder = 0; - _info.StartModelRare(_order); - } - while (size != 0) - { - int symbol = _info.DecodeSymbol(&_rangeDecoder); - if (symbol < 0) - { - _remainLen = kLenIdFinished; - break; - } - if (memStream != 0) - *memStream++ = (Byte)symbol; - else - _outStream.WriteByte((Byte)symbol); - size--; - } - _processedSize += startSize - size; - return S_OK; -} - -STDMETHODIMP CDecoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 * /* inSize */, const UInt64 *outSize, ICompressProgressInfo *progress) -{ - if (!_outStream.Create(1 << 20)) - return E_OUTOFMEMORY; - - SetInStream(inStream); - _outStream.SetStream(outStream); - SetOutStreamSize(outSize); - CDecoderFlusher flusher(this); - - for (;;) - { - _processedSize = _outStream.GetProcessedSize(); - UInt32 curSize = (1 << 18); - RINOK(CodeSpec(curSize, NULL)); - if (_remainLen == kLenIdFinished) - break; - if (progress != NULL) - { - UInt64 inSize = _rangeDecoder.GetProcessedSize(); - RINOK(progress->SetRatioInfo(&inSize, &_processedSize)); - } - if (_outSizeDefined) - if (_outStream.GetProcessedSize() >= _outSize) - break; - } - flusher.NeedFlush = false; - return Flush(); -} - -#ifdef _NO_EXCEPTIONS - -#define PPMD_TRY_BEGIN -#define PPMD_TRY_END - -#else - -#define PPMD_TRY_BEGIN try { -#define PPMD_TRY_END } \ - catch(const CInBufferException &e) { return e.ErrorCode; } \ - catch(const COutBufferException &e) { return e.ErrorCode; } \ - catch(...) { return S_FALSE; } - -#endif - - -STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) -{ - PPMD_TRY_BEGIN - return CodeReal(inStream, outStream, inSize, outSize, progress); - PPMD_TRY_END -} - -STDMETHODIMP CDecoder::SetInStream(ISequentialInStream *inStream) -{ - _rangeDecoder.SetStream(inStream); - return S_OK; -} - -STDMETHODIMP CDecoder::ReleaseInStream() -{ - _rangeDecoder.ReleaseStream(); - return S_OK; -} - -STDMETHODIMP CDecoder::SetOutStreamSize(const UInt64 *outSize) -{ - _outSizeDefined = (outSize != NULL); - if (_outSizeDefined) - _outSize = *outSize; - _processedSize = 0; - _remainLen = kLenIdNeedInit; - _outStream.Init(); - return S_OK; -} - -#ifndef NO_READ_FROM_CODER - -STDMETHODIMP CDecoder::Read(void *data, UInt32 size, UInt32 *processedSize) -{ - PPMD_TRY_BEGIN - if (processedSize) - *processedSize = 0; - const UInt64 startPos = _processedSize; - RINOK(CodeSpec(size, (Byte *)data)); - if (processedSize) - *processedSize = (UInt32)(_processedSize - startPos); - return Flush(); - PPMD_TRY_END -} - -#endif - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/PpmdDecoder.h b/desmume/src/windows/7z/CPP/7zip/Compress/PpmdDecoder.h deleted file mode 100644 index e14d37303..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/PpmdDecoder.h +++ /dev/null @@ -1,86 +0,0 @@ -// PpmdDecoder.h - -#ifndef __COMPRESS_PPMD_DECODER_H -#define __COMPRESS_PPMD_DECODER_H - -#include "../../Common/MyCom.h" - -#include "../ICoder.h" - -#include "../Common/OutBuffer.h" - -#include "PpmdDecode.h" -#include "RangeCoder.h" - -namespace NCompress { -namespace NPpmd { - -class CDecoder : - public ICompressCoder, - public ICompressSetDecoderProperties2, - #ifndef NO_READ_FROM_CODER - public ICompressSetInStream, - public ICompressSetOutStreamSize, - public ISequentialInStream, - #endif - public CMyUnknownImp -{ - CRangeDecoder _rangeDecoder; - - COutBuffer _outStream; - - CDecodeInfo _info; - - Byte _order; - UInt32 _usedMemorySize; - - int _remainLen; - UInt64 _outSize; - bool _outSizeDefined; - UInt64 _processedSize; - - HRESULT CodeSpec(UInt32 num, Byte *memStream); - -public: - - #ifndef NO_READ_FROM_CODER - MY_UNKNOWN_IMP4( - ICompressSetDecoderProperties2, - ICompressSetInStream, - ICompressSetOutStreamSize, - ISequentialInStream) - #else - MY_UNKNOWN_IMP1( - ICompressSetDecoderProperties2) - #endif - - void ReleaseStreams() - { - ReleaseInStream(); - _outStream.ReleaseStream(); - } - - HRESULT Flush() { return _outStream.Flush(); } - - STDMETHOD(CodeReal)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - - STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size); - - STDMETHOD(SetInStream)(ISequentialInStream *inStream); - STDMETHOD(ReleaseInStream)(); - STDMETHOD(SetOutStreamSize)(const UInt64 *outSize); - - #ifndef NO_READ_FROM_CODER - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); - #endif - - CDecoder(): _outSizeDefined(false) {} -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/PpmdRegister.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/PpmdRegister.cpp deleted file mode 100644 index eed3d7b16..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/PpmdRegister.cpp +++ /dev/null @@ -1,20 +0,0 @@ -// PpmdRegister.cpp - -#include "StdAfx.h" - -#include "../Common/RegisterCodec.h" - -#include "PpmdDecoder.h" - -static void *CreateCodec() { return (void *)(ICompressCoder *)(new NCompress::NPpmd::CDecoder); } -#ifndef EXTRACT_ONLY -#include "PpmdEncoder.h" -static void *CreateCodecOut() { return (void *)(ICompressCoder *)(new NCompress::NPpmd::CEncoder); } -#else -#define CreateCodecOut 0 -#endif - -static CCodecInfo g_CodecInfo = - { CreateCodec, CreateCodecOut, 0x030401, L"PPMD", 1, false }; - -REGISTER_CODEC(PPMD) diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/PpmdSubAlloc.h b/desmume/src/windows/7z/CPP/7zip/Compress/PpmdSubAlloc.h deleted file mode 100644 index fdea6d5df..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/PpmdSubAlloc.h +++ /dev/null @@ -1,295 +0,0 @@ -// PpmdSubAlloc.h -// This code is based on Dmitry Shkarin's PPMdH code - -#ifndef __COMPRESS_PPMD_SUB_ALLOC_H -#define __COMPRESS_PPMD_SUB_ALLOC_H - -extern "C" -{ -#include "../../../C/Alloc.h" -} - -#include "PpmdType.h" - -const UINT N1=4, N2=4, N3=4, N4=(128+3-1*N1-2*N2-3*N3)/4; -const UINT UNIT_SIZE=12, N_INDEXES=N1+N2+N3+N4; - -// Extra 1 * UNIT_SIZE for NULL support -// Extra 2 * UNIT_SIZE for s0 in GlueFreeBlocks() -const UInt32 kExtraSize = (UNIT_SIZE * 3); -const UInt32 kMaxMemBlockSize = 0xFFFFFFFF - kExtraSize; - -struct MEM_BLK -{ - UInt16 Stamp, NU; - UInt32 Next, Prev; - void InsertAt(Byte *Base, UInt32 p) - { - Prev = p; - MEM_BLK *pp = (MEM_BLK *)(Base + p); - Next = pp->Next; - pp->Next = ((MEM_BLK *)(Base + Next))->Prev = (UInt32)((Byte *)this - Base); - } - void Remove(Byte *Base) - { - ((MEM_BLK *)(Base + Prev))->Next = Next; - ((MEM_BLK *)(Base + Next))->Prev = Prev; - } -}; - - -class CSubAllocator -{ - UInt32 SubAllocatorSize; - Byte Indx2Units[N_INDEXES], Units2Indx[128], GlueCount; - UInt32 FreeList[N_INDEXES]; - - Byte *Base; - Byte *HeapStart, *LoUnit, *HiUnit; -public: - Byte *pText, *UnitsStart; - CSubAllocator(): - SubAllocatorSize(0), - GlueCount(0), - LoUnit(0), - HiUnit(0), - pText(0), - UnitsStart(0) - { - memset(Indx2Units, 0, sizeof(Indx2Units)); - memset(FreeList, 0, sizeof(FreeList)); - } - ~CSubAllocator() - { - StopSubAllocator(); - }; - - void *GetPtr(UInt32 offset) const { return (offset == 0) ? 0 : (void *)(Base + offset); } - void *GetPtrNoCheck(UInt32 offset) const { return (void *)(Base + offset); } - UInt32 GetOffset(void *ptr) const { return (ptr == 0) ? 0 : (UInt32)((Byte *)ptr - Base); } - UInt32 GetOffsetNoCheck(void *ptr) const { return (UInt32)((Byte *)ptr - Base); } - MEM_BLK *GetBlk(UInt32 offset) const { return (MEM_BLK *)(Base + offset); } - UInt32 *GetNode(UInt32 offset) const { return (UInt32 *)(Base + offset); } - - void InsertNode(void* p, int indx) - { - *(UInt32 *)p = FreeList[indx]; - FreeList[indx] = GetOffsetNoCheck(p); - } - - void* RemoveNode(int indx) - { - UInt32 offset = FreeList[indx]; - UInt32 *p = GetNode(offset); - FreeList[indx] = *p; - return (void *)p; - } - - UINT U2B(int NU) const { return (UINT)(NU) * UNIT_SIZE; } - - void SplitBlock(void* pv, int oldIndx, int newIndx) - { - int i, UDiff = Indx2Units[oldIndx] - Indx2Units[newIndx]; - Byte* p = ((Byte*)pv) + U2B(Indx2Units[newIndx]); - if (Indx2Units[i = Units2Indx[UDiff-1]] != UDiff) - { - InsertNode(p, --i); - p += U2B(i = Indx2Units[i]); - UDiff -= i; - } - InsertNode(p, Units2Indx[UDiff - 1]); - } - - UInt32 GetUsedMemory() const - { - UInt32 RetVal = SubAllocatorSize - (UInt32)(HiUnit - LoUnit) - (UInt32)(UnitsStart - pText); - for (UInt32 i = 0; i < N_INDEXES; i++) - for (UInt32 pn = FreeList[i]; pn != 0; RetVal -= (UInt32)Indx2Units[i] * UNIT_SIZE) - pn = *GetNode(pn); - return (RetVal >> 2); - } - - UInt32 GetSubAllocatorSize() const { return SubAllocatorSize; } - - void StopSubAllocator() - { - if (SubAllocatorSize != 0) - { - BigFree(Base); - SubAllocatorSize = 0; - Base = 0; - } - } - - bool StartSubAllocator(UInt32 size) - { - if (SubAllocatorSize == size) - return true; - StopSubAllocator(); - if (size == 0) - Base = 0; - else - { - if ((Base = (Byte *)::BigAlloc(size + kExtraSize)) == 0) - return false; - HeapStart = Base + UNIT_SIZE; // we need such code to support NULL; - } - SubAllocatorSize = size; - return true; - } - - void InitSubAllocator() - { - int i, k; - memset(FreeList, 0, sizeof(FreeList)); - HiUnit = (pText = HeapStart) + SubAllocatorSize; - UINT Diff = UNIT_SIZE * (SubAllocatorSize / 8 / UNIT_SIZE * 7); - LoUnit = UnitsStart = HiUnit - Diff; - for (i = 0, k=1; i < N1 ; i++, k += 1) Indx2Units[i] = (Byte)k; - for (k++; i < N1 + N2 ;i++, k += 2) Indx2Units[i] = (Byte)k; - for (k++; i < N1 + N2 + N3 ;i++,k += 3) Indx2Units[i] = (Byte)k; - for (k++; i < N1 + N2 + N3 + N4; i++, k += 4) Indx2Units[i] = (Byte)k; - GlueCount = 0; - for (k = i = 0; k < 128; k++) - { - i += (Indx2Units[i] < k+1); - Units2Indx[k] = (Byte)i; - } - } - - void GlueFreeBlocks() - { - UInt32 s0 = (UInt32)(HeapStart + SubAllocatorSize - Base); - - // We need add exta MEM_BLK with Stamp=0 - GetBlk(s0)->Stamp = 0; - s0 += UNIT_SIZE; - MEM_BLK *ps0 = GetBlk(s0); - - UInt32 p; - int i; - if (LoUnit != HiUnit) - *LoUnit=0; - ps0->Next = ps0->Prev = s0; - - for (i = 0; i < N_INDEXES; i++) - while (FreeList[i] != 0) - { - MEM_BLK *pp = (MEM_BLK *)RemoveNode(i); - pp->InsertAt(Base, s0); - pp->Stamp = 0xFFFF; - pp->NU = Indx2Units[i]; - } - for (p = ps0->Next; p != s0; p = GetBlk(p)->Next) - { - for (;;) - { - MEM_BLK *pp = GetBlk(p); - MEM_BLK *pp1 = GetBlk(p + pp->NU * UNIT_SIZE); - if (pp1->Stamp != 0xFFFF || int(pp->NU) + pp1->NU >= 0x10000) - break; - pp1->Remove(Base); - pp->NU = (UInt16)(pp->NU + pp1->NU); - } - } - while ((p = ps0->Next) != s0) - { - MEM_BLK *pp = GetBlk(p); - pp->Remove(Base); - int sz; - for (sz = pp->NU; sz > 128; sz -= 128, p += 128 * UNIT_SIZE) - InsertNode(Base + p, N_INDEXES - 1); - if (Indx2Units[i = Units2Indx[sz-1]] != sz) - { - int k = sz - Indx2Units[--i]; - InsertNode(Base + p + (sz - k) * UNIT_SIZE, k - 1); - } - InsertNode(Base + p, i); - } - } - void* AllocUnitsRare(int indx) - { - if ( !GlueCount ) - { - GlueCount = 255; - GlueFreeBlocks(); - if (FreeList[indx] != 0) - return RemoveNode(indx); - } - int i = indx; - do - { - if (++i == N_INDEXES) - { - GlueCount--; - i = U2B(Indx2Units[indx]); - return (UnitsStart - pText > i) ? (UnitsStart -= i) : (NULL); - } - } while (FreeList[i] == 0); - void* RetVal = RemoveNode(i); - SplitBlock(RetVal, i, indx); - return RetVal; - } - - void* AllocUnits(int NU) - { - int indx = Units2Indx[NU - 1]; - if (FreeList[indx] != 0) - return RemoveNode(indx); - void* RetVal = LoUnit; - LoUnit += U2B(Indx2Units[indx]); - if (LoUnit <= HiUnit) - return RetVal; - LoUnit -= U2B(Indx2Units[indx]); - return AllocUnitsRare(indx); - } - - void* AllocContext() - { - if (HiUnit != LoUnit) - return (HiUnit -= UNIT_SIZE); - if (FreeList[0] != 0) - return RemoveNode(0); - return AllocUnitsRare(0); - } - - void* ExpandUnits(void* oldPtr, int oldNU) - { - int i0=Units2Indx[oldNU - 1], i1=Units2Indx[oldNU - 1 + 1]; - if (i0 == i1) - return oldPtr; - void* ptr = AllocUnits(oldNU + 1); - if (ptr) - { - memcpy(ptr, oldPtr, U2B(oldNU)); - InsertNode(oldPtr, i0); - } - return ptr; - } - - void* ShrinkUnits(void* oldPtr, int oldNU, int newNU) - { - int i0 = Units2Indx[oldNU - 1], i1 = Units2Indx[newNU - 1]; - if (i0 == i1) - return oldPtr; - if (FreeList[i1] != 0) - { - void* ptr = RemoveNode(i1); - memcpy(ptr, oldPtr, U2B(newNU)); - InsertNode(oldPtr,i0); - return ptr; - } - else - { - SplitBlock(oldPtr, i0, i1); - return oldPtr; - } - } - - void FreeUnits(void* ptr, int oldNU) - { - InsertNode(ptr, Units2Indx[oldNU - 1]); - } -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/PpmdType.h b/desmume/src/windows/7z/CPP/7zip/Compress/PpmdType.h deleted file mode 100644 index 313c5f28e..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/PpmdType.h +++ /dev/null @@ -1,20 +0,0 @@ -/**************************************************************************** - * This file is part of PPMd project * - * Written and distributed to public domain by Dmitry Shkarin 1997, * - * 1999-2001 * - * Contents: compilation parameters and miscelaneous definitions * - * Comments: system & compiler dependent file - - * modified by Igor Pavlov (2004-08-29). - ****************************************************************************/ - -#ifndef __COMPRESS_PPMD_TYPE_H -#define __COMPRESS_PPMD_TYPE_H - -const int kMaxOrderCompress = 32; -const int MAX_O = 255; /* maximum allowed model order */ - -template -inline void _PPMD_SWAP(T& t1,T& t2) { T tmp = t1; t1 = t2; t2 = tmp; } - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/RangeCoder.h b/desmume/src/windows/7z/CPP/7zip/Compress/RangeCoder.h deleted file mode 100644 index 8040bcd06..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/RangeCoder.h +++ /dev/null @@ -1,204 +0,0 @@ -// Compress/RangeCoder.h - -#ifndef __COMPRESS_RANGE_CODER_H -#define __COMPRESS_RANGE_CODER_H - -#include "../Common/InBuffer.h" -#include "../Common/OutBuffer.h" - -namespace NCompress { -namespace NRangeCoder { - -const int kNumTopBits = 24; -const UInt32 kTopValue = (1 << kNumTopBits); - -class CEncoder -{ - UInt32 _cacheSize; - Byte _cache; -public: - UInt64 Low; - UInt32 Range; - COutBuffer Stream; - bool Create(UInt32 bufferSize) { return Stream.Create(bufferSize); } - - void SetStream(ISequentialOutStream *stream) { Stream.SetStream(stream); } - void Init() - { - Stream.Init(); - Low = 0; - Range = 0xFFFFFFFF; - _cacheSize = 1; - _cache = 0; - } - - void FlushData() - { - // Low += 1; - for(int i = 0; i < 5; i++) - ShiftLow(); - } - - HRESULT FlushStream() { return Stream.Flush(); } - - void ReleaseStream() { Stream.ReleaseStream(); } - - void Encode(UInt32 start, UInt32 size, UInt32 total) - { - Low += start * (Range /= total); - Range *= size; - while (Range < kTopValue) - { - Range <<= 8; - ShiftLow(); - } - } - - void ShiftLow() - { - if ((UInt32)Low < (UInt32)0xFF000000 || (int)(Low >> 32) != 0) - { - Byte temp = _cache; - do - { - Stream.WriteByte((Byte)(temp + (Byte)(Low >> 32))); - temp = 0xFF; - } - while(--_cacheSize != 0); - _cache = (Byte)((UInt32)Low >> 24); - } - _cacheSize++; - Low = (UInt32)Low << 8; - } - - void EncodeDirectBits(UInt32 value, int numBits) - { - for (numBits--; numBits >= 0; numBits--) - { - Range >>= 1; - Low += Range & (0 - ((value >> numBits) & 1)); - if (Range < kTopValue) - { - Range <<= 8; - ShiftLow(); - } - } - } - - void EncodeBit(UInt32 size0, UInt32 numTotalBits, UInt32 symbol) - { - UInt32 newBound = (Range >> numTotalBits) * size0; - if (symbol == 0) - Range = newBound; - else - { - Low += newBound; - Range -= newBound; - } - while (Range < kTopValue) - { - Range <<= 8; - ShiftLow(); - } - } - - UInt64 GetProcessedSize() { return Stream.GetProcessedSize() + _cacheSize + 4; } -}; - -class CDecoder -{ -public: - CInBuffer Stream; - UInt32 Range; - UInt32 Code; - bool Create(UInt32 bufferSize) { return Stream.Create(bufferSize); } - - void Normalize() - { - while (Range < kTopValue) - { - Code = (Code << 8) | Stream.ReadByte(); - Range <<= 8; - } - } - - void SetStream(ISequentialInStream *stream) { Stream.SetStream(stream); } - void Init() - { - Stream.Init(); - Code = 0; - Range = 0xFFFFFFFF; - for(int i = 0; i < 5; i++) - Code = (Code << 8) | Stream.ReadByte(); - } - - void ReleaseStream() { Stream.ReleaseStream(); } - - UInt32 GetThreshold(UInt32 total) - { - return (Code) / ( Range /= total); - } - - void Decode(UInt32 start, UInt32 size) - { - Code -= start * Range; - Range *= size; - Normalize(); - } - - UInt32 DecodeDirectBits(int numTotalBits) - { - UInt32 range = Range; - UInt32 code = Code; - UInt32 result = 0; - for (int i = numTotalBits; i != 0; i--) - { - range >>= 1; - /* - result <<= 1; - if (code >= range) - { - code -= range; - result |= 1; - } - */ - UInt32 t = (code - range) >> 31; - code -= range & (t - 1); - result = (result << 1) | (1 - t); - - if (range < kTopValue) - { - code = (code << 8) | Stream.ReadByte(); - range <<= 8; - } - } - Range = range; - Code = code; - return result; - } - - UInt32 DecodeBit(UInt32 size0, UInt32 numTotalBits) - { - UInt32 newBound = (Range >> numTotalBits) * size0; - UInt32 symbol; - if (Code < newBound) - { - symbol = 0; - Range = newBound; - } - else - { - symbol = 1; - Code -= newBound; - Range -= newBound; - } - Normalize(); - return symbol; - } - - UInt64 GetProcessedSize() {return Stream.GetProcessedSize(); } -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/RangeCoderBit.h b/desmume/src/windows/7z/CPP/7zip/Compress/RangeCoderBit.h deleted file mode 100644 index f2fe45d7f..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/RangeCoderBit.h +++ /dev/null @@ -1,113 +0,0 @@ -// Compress/RangeCoderBit.h - -#ifndef __COMPRESS_RANGE_CODER_BIT_H -#define __COMPRESS_RANGE_CODER_BIT_H - -#include "RangeCoder.h" - -namespace NCompress { -namespace NRangeCoder { - -const int kNumBitModelTotalBits = 11; -const UInt32 kBitModelTotal = (1 << kNumBitModelTotalBits); - -const int kNumMoveReducingBits = 4; - -const int kNumBitPriceShiftBits = 4; -const UInt32 kBitPrice = 1 << kNumBitPriceShiftBits; - -extern UInt32 ProbPrices[kBitModelTotal >> kNumMoveReducingBits]; - -template -class CBitModel -{ -public: - UInt32 Prob; - void UpdateModel(UInt32 symbol) - { - /* - Prob -= (Prob + ((symbol - 1) & ((1 << numMoveBits) - 1))) >> numMoveBits; - Prob += (1 - symbol) << (kNumBitModelTotalBits - numMoveBits); - */ - if (symbol == 0) - Prob += (kBitModelTotal - Prob) >> numMoveBits; - else - Prob -= (Prob) >> numMoveBits; - } -public: - void Init() { Prob = kBitModelTotal / 2; } -}; - -template -class CBitEncoder: public CBitModel -{ -public: - void Encode(CEncoder *encoder, UInt32 symbol) - { - /* - encoder->EncodeBit(this->Prob, kNumBitModelTotalBits, symbol); - this->UpdateModel(symbol); - */ - UInt32 newBound = (encoder->Range >> kNumBitModelTotalBits) * this->Prob; - if (symbol == 0) - { - encoder->Range = newBound; - this->Prob += (kBitModelTotal - this->Prob) >> numMoveBits; - } - else - { - encoder->Low += newBound; - encoder->Range -= newBound; - this->Prob -= (this->Prob) >> numMoveBits; - } - if (encoder->Range < kTopValue) - { - encoder->Range <<= 8; - encoder->ShiftLow(); - } - } - UInt32 GetPrice(UInt32 symbol) const - { - return ProbPrices[(this->Prob ^ ((-(int)symbol)) & (kBitModelTotal - 1)) >> kNumMoveReducingBits]; - } - UInt32 GetPrice0() const { return ProbPrices[this->Prob >> kNumMoveReducingBits]; } - UInt32 GetPrice1() const { return ProbPrices[(this->Prob ^ (kBitModelTotal - 1)) >> kNumMoveReducingBits]; } -}; - - -template -class CBitDecoder: public CBitModel -{ -public: - UInt32 Decode(CDecoder *decoder) - { - UInt32 newBound = (decoder->Range >> kNumBitModelTotalBits) * this->Prob; - if (decoder->Code < newBound) - { - decoder->Range = newBound; - this->Prob += (kBitModelTotal - this->Prob) >> numMoveBits; - if (decoder->Range < kTopValue) - { - decoder->Code = (decoder->Code << 8) | decoder->Stream.ReadByte(); - decoder->Range <<= 8; - } - return 0; - } - else - { - decoder->Range -= newBound; - decoder->Code -= newBound; - this->Prob -= (this->Prob) >> numMoveBits; - if (decoder->Range < kTopValue) - { - decoder->Code = (decoder->Code << 8) | decoder->Stream.ReadByte(); - decoder->Range <<= 8; - } - return 1; - } - } -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/Rar1Decoder.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/Rar1Decoder.cpp deleted file mode 100644 index a6a7c854f..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/Rar1Decoder.cpp +++ /dev/null @@ -1,478 +0,0 @@ -// Rar1Decoder.cpp -// According to unRAR license, this code may not be used to develop -// a program that creates RAR archives - -#include "StdAfx.h" - -#include "Rar1Decoder.h" - -namespace NCompress { -namespace NRar1 { - -static UInt32 PosL1[]={0,0,0,2,3,5,7,11,16,20,24,32,32, 256}; -static UInt32 PosL2[]={0,0,0,0,5,7,9,13,18,22,26,34,36, 256}; -static UInt32 PosHf0[]={0,0,0,0,0,8,16,24,33,33,33,33,33, 257}; -static UInt32 PosHf1[]={0,0,0,0,0,0,4,44,60,76,80,80,127, 257}; -static UInt32 PosHf2[]={0,0,0,0,0,0,2,7,53,117,233, 257,0}; -static UInt32 PosHf3[]={0,0,0,0,0,0,0,2,16,218,251, 257,0}; -static UInt32 PosHf4[]={0,0,0,0,0,0,0,0,0,255, 257,0,0}; - -static const UInt32 kHistorySize = (1 << 16); - -class CCoderReleaser -{ - CDecoder *m_Coder; -public: - CCoderReleaser(CDecoder *coder): m_Coder(coder) {} - ~CCoderReleaser() { m_Coder->ReleaseStreams(); } -}; - -CDecoder::CDecoder(): m_IsSolid(false) { } - -void CDecoder::InitStructures() -{ - for(int i = 0; i < kNumRepDists; i++) - m_RepDists[i] = 0; - m_RepDistPtr = 0; - LastLength = 0; - LastDist = 0; -} - -UInt32 CDecoder::ReadBits(int numBits) { return m_InBitStream.ReadBits(numBits); } - -HRESULT CDecoder::CopyBlock(UInt32 distance, UInt32 len) -{ - m_UnpackSize -= len; - return m_OutWindowStream.CopyBlock(distance, len) ? S_OK : S_FALSE; -} - - -UInt32 CDecoder::DecodeNum(const UInt32 *posTab) -{ - UInt32 startPos = 2; - UInt32 num = m_InBitStream.GetValue(12); - for (;;) - { - UInt32 cur = (posTab[startPos + 1] - posTab[startPos]) << (12 - startPos); - if (num < cur) - break; - startPos++; - num -= cur; - } - m_InBitStream.MovePos(startPos); - return((num >> (12 - startPos)) + posTab[startPos]); -} - -static Byte kShortLen1[] = {1,3,4,4,5,6,7,8,8,4,4,5,6,6 }; -static Byte kShortLen1a[] = {1,4,4,4,5,6,7,8,8,4,4,5,6,6,4 }; -static Byte kShortLen2[] = {2,3,3,3,4,4,5,6,6,4,4,5,6,6 }; -static Byte kShortLen2a[] = {2,3,3,4,4,4,5,6,6,4,4,5,6,6,4 }; -static UInt32 kShortXor1[] = {0,0xa0,0xd0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff,0xc0,0x80,0x90,0x98,0x9c,0xb0}; -static UInt32 kShortXor2[] = {0,0x40,0x60,0xa0,0xd0,0xe0,0xf0,0xf8,0xfc,0xc0,0x80,0x90,0x98,0x9c,0xb0}; - -HRESULT CDecoder::ShortLZ() -{ - UInt32 len, saveLen, dist; - int distancePlace; - Byte *kShortLen; - const UInt32 *kShortXor; - NumHuf = 0; - - if (LCount == 2) - { - if (ReadBits(1)) - return CopyBlock(LastDist, LastLength); - LCount = 0; - } - - UInt32 bitField = m_InBitStream.GetValue(8); - - if (AvrLn1 < 37) - { - kShortLen = Buf60 ? kShortLen1a : kShortLen1; - kShortXor = kShortXor1; - } - else - { - kShortLen = Buf60 ? kShortLen2a : kShortLen2; - kShortXor = kShortXor2; - } - - for (len = 0; ((bitField ^ kShortXor[len]) & (~(0xff >> kShortLen[len]))) != 0; len++); - m_InBitStream.MovePos(kShortLen[len]); - - if (len >= 9) - { - if (len == 9) - { - LCount++; - return CopyBlock(LastDist, LastLength); - } - if (len == 14) - { - LCount = 0; - len = DecodeNum(PosL2) + 5; - dist = 0x8000 + ReadBits(15) - 1; - LastLength = len; - LastDist = dist; - return CopyBlock(dist, len); - } - - LCount = 0; - saveLen = len; - dist = m_RepDists[(m_RepDistPtr - (len - 9)) & 3]; - len = DecodeNum(PosL1) + 2; - if (len == 0x101 && saveLen == 10) - { - Buf60 ^= 1; - return S_OK; - } - if (dist >= 256) - len++; - if (dist >= MaxDist3 - 1) - len++; - } - else - { - LCount = 0; - AvrLn1 += len; - AvrLn1 -= AvrLn1 >> 4; - - distancePlace = DecodeNum(PosHf2) & 0xff; - dist = ChSetA[distancePlace]; - if (--distancePlace != -1) - { - PlaceA[dist]--; - UInt32 lastDistance = ChSetA[distancePlace]; - PlaceA[lastDistance]++; - ChSetA[distancePlace + 1] = lastDistance; - ChSetA[distancePlace] = dist; - } - len += 2; - } - m_RepDists[m_RepDistPtr++] = dist; - m_RepDistPtr &= 3; - LastLength = len; - LastDist = dist; - return CopyBlock(dist, len); -} - - -HRESULT CDecoder::LongLZ() -{ - UInt32 len; - UInt32 dist; - UInt32 distancePlace, newDistancePlace; - UInt32 oldAvr2, oldAvr3; - - NumHuf = 0; - Nlzb += 16; - if (Nlzb > 0xff) - { - Nlzb = 0x90; - Nhfb >>= 1; - } - oldAvr2=AvrLn2; - - if (AvrLn2 >= 122) - len = DecodeNum(PosL2); - else if (AvrLn2 >= 64) - len = DecodeNum(PosL1); - else - { - UInt32 bitField = m_InBitStream.GetValue(16); - if (bitField < 0x100) - { - len = bitField; - m_InBitStream.MovePos(16); - } - else - { - for (len = 0; ((bitField << len) & 0x8000) == 0; len++) - ; - m_InBitStream.MovePos(len + 1); - } - } - - AvrLn2 += len; - AvrLn2 -= AvrLn2 >> 5; - - if (AvrPlcB > 0x28ff) - distancePlace = DecodeNum(PosHf2); - else if (AvrPlcB > 0x6ff) - distancePlace = DecodeNum(PosHf1); - else - distancePlace = DecodeNum(PosHf0); - - AvrPlcB += distancePlace; - AvrPlcB -= AvrPlcB >> 8; - for (;;) - { - dist = ChSetB[distancePlace & 0xff]; - newDistancePlace = NToPlB[dist++ & 0xff]++; - if (!(dist & 0xff)) - CorrHuff(ChSetB,NToPlB); - else - break; - } - - ChSetB[distancePlace] = ChSetB[newDistancePlace]; - ChSetB[newDistancePlace] = dist; - - dist = ((dist & 0xff00) >> 1) | ReadBits(7); - - oldAvr3 = AvrLn3; - if (len != 1 && len != 4) - if (len == 0 && dist <= MaxDist3) - { - AvrLn3++; - AvrLn3 -= AvrLn3 >> 8; - } - else - if (AvrLn3 > 0) - AvrLn3--; - len += 3; - if (dist >= MaxDist3) - len++; - if (dist <= 256) - len += 8; - if (oldAvr3 > 0xb0 || AvrPlc >= 0x2a00 && oldAvr2 < 0x40) - MaxDist3 = 0x7f00; - else - MaxDist3 = 0x2001; - m_RepDists[m_RepDistPtr++] = --dist; - m_RepDistPtr &= 3; - LastLength = len; - LastDist = dist; - return CopyBlock(dist, len); -} - - -HRESULT CDecoder::HuffDecode() -{ - UInt32 curByte, newBytePlace; - UInt32 len; - UInt32 dist; - int bytePlace; - - if (AvrPlc > 0x75ff) bytePlace = DecodeNum(PosHf4); - else if (AvrPlc > 0x5dff) bytePlace = DecodeNum(PosHf3); - else if (AvrPlc > 0x35ff) bytePlace = DecodeNum(PosHf2); - else if (AvrPlc > 0x0dff) bytePlace = DecodeNum(PosHf1); - else bytePlace = DecodeNum(PosHf0); - if (StMode) - { - if (--bytePlace == -1) - { - if (ReadBits(1)) - { - NumHuf = StMode = 0; - return S_OK; - } - else - { - len = (ReadBits(1)) ? 4 : 3; - dist = DecodeNum(PosHf2); - dist = (dist << 5) | ReadBits(5); - return CopyBlock(dist - 1, len); - } - } - } - else if (NumHuf++ >= 16 && FlagsCnt == 0) - StMode = 1; - bytePlace &= 0xff; - AvrPlc += bytePlace; - AvrPlc -= AvrPlc >> 8; - Nhfb+=16; - if (Nhfb > 0xff) - { - Nhfb=0x90; - Nlzb >>= 1; - } - - m_UnpackSize --; - m_OutWindowStream.PutByte((Byte)(ChSet[bytePlace] >> 8)); - - for (;;) - { - curByte = ChSet[bytePlace]; - newBytePlace = NToPl[curByte++ & 0xff]++; - if ((curByte & 0xff) > 0xa1) - CorrHuff(ChSet, NToPl); - else - break; - } - - ChSet[bytePlace] = ChSet[newBytePlace]; - ChSet[newBytePlace] = curByte; - return S_OK; -} - - -void CDecoder::GetFlagsBuf() -{ - UInt32 flags, newFlagsPlace; - UInt32 flagsPlace = DecodeNum(PosHf2); - - for (;;) - { - flags = ChSetC[flagsPlace]; - FlagBuf = flags >> 8; - newFlagsPlace = NToPlC[flags++ & 0xff]++; - if ((flags & 0xff) != 0) - break; - CorrHuff(ChSetC, NToPlC); - } - - ChSetC[flagsPlace] = ChSetC[newFlagsPlace]; - ChSetC[newFlagsPlace] = flags; -} - -void CDecoder::InitData() -{ - if (!m_IsSolid) - { - AvrPlcB = AvrLn1 = AvrLn2 = AvrLn3 = NumHuf = Buf60 = 0; - AvrPlc = 0x3500; - MaxDist3 = 0x2001; - Nhfb = Nlzb = 0x80; - } - FlagsCnt = 0; - FlagBuf = 0; - StMode = 0; - LCount = 0; -} - -void CDecoder::CorrHuff(UInt32 *CharSet,UInt32 *NumToPlace) -{ - int i; - for (i = 7; i >= 0; i--) - for (int j = 0; j < 32; j++, CharSet++) - *CharSet = (*CharSet & ~0xff) | i; - memset(NumToPlace, 0, sizeof(NToPl)); - for (i = 6; i >= 0; i--) - NumToPlace[i] = (7 - i) * 32; -} - -void CDecoder::InitHuff() -{ - for (UInt32 i = 0; i < 256; i++) - { - Place[i] = PlaceA[i] = PlaceB[i] = i; - PlaceC[i] = (~i + 1) & 0xff; - ChSet[i] = ChSetB[i] = i << 8; - ChSetA[i] = i; - ChSetC[i] = ((~i + 1) & 0xff) << 8; - } - memset(NToPl, 0, sizeof(NToPl)); - memset(NToPlB, 0, sizeof(NToPlB)); - memset(NToPlC, 0, sizeof(NToPlC)); - CorrHuff(ChSetB, NToPlB); -} - -HRESULT CDecoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo * /* progress */) -{ - if (inSize == NULL || outSize == NULL) - return E_INVALIDARG; - - if (!m_OutWindowStream.Create(kHistorySize)) - return E_OUTOFMEMORY; - if (!m_InBitStream.Create(1 << 20)) - return E_OUTOFMEMORY; - - m_UnpackSize = (Int64)*outSize; - m_OutWindowStream.SetStream(outStream); - m_OutWindowStream.Init(m_IsSolid); - m_InBitStream.SetStream(inStream); - m_InBitStream.Init(); - - CCoderReleaser coderReleaser(this); - InitData(); - if (!m_IsSolid) - { - InitStructures(); - InitHuff(); - } - if (m_UnpackSize > 0) - { - GetFlagsBuf(); - FlagsCnt = 8; - } - - while (m_UnpackSize > 0) - { - if (StMode) - { - RINOK(HuffDecode()); - continue; - } - - if (--FlagsCnt < 0) - { - GetFlagsBuf(); - FlagsCnt=7; - } - - if (FlagBuf & 0x80) - { - FlagBuf <<= 1; - if (Nlzb > Nhfb) - { - RINOK(LongLZ()); - } - else - { - RINOK(HuffDecode()); - } - } - else - { - FlagBuf <<= 1; - if (--FlagsCnt < 0) - { - GetFlagsBuf(); - FlagsCnt = 7; - } - if (FlagBuf & 0x80) - { - FlagBuf <<= 1; - if (Nlzb > Nhfb) - { - RINOK(HuffDecode()); - } - else - { - RINOK(LongLZ()); - } - } - else - { - FlagBuf <<= 1; - RINOK(ShortLZ()); - } - } - } - if (m_UnpackSize < 0) - return S_FALSE; - return m_OutWindowStream.Flush(); -} - -STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) -{ - try { return CodeReal(inStream, outStream, inSize, outSize, progress); } - catch(const CInBufferException &e) { return e.ErrorCode; } - catch(const CLzOutWindowException &e) { return e.ErrorCode; } - catch(...) { return S_FALSE; } -} - -STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte *data, UInt32 size) -{ - if (size < 1) - return E_INVALIDARG; - m_IsSolid = (data[0] != 0); - return S_OK; -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/Rar1Decoder.h b/desmume/src/windows/7z/CPP/7zip/Compress/Rar1Decoder.h deleted file mode 100644 index 1b960e457..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/Rar1Decoder.h +++ /dev/null @@ -1,88 +0,0 @@ -// Rar1Decoder.h -// According to unRAR license, this code may not be used to develop -// a program that creates RAR archives - -#ifndef __COMPRESS_RAR1_DECODER_H -#define __COMPRESS_RAR1_DECODER_H - -#include "../../Common/MyCom.h" - -#include "../ICoder.h" - -#include "../Common/InBuffer.h" - -#include "BitmDecoder.h" -#include "HuffmanDecoder.h" -#include "LzOutWindow.h" - -namespace NCompress { -namespace NRar1 { - -const UInt32 kNumRepDists = 4; - -typedef NBitm::CDecoder CBitDecoder; - -class CDecoder : - public ICompressCoder, - public ICompressSetDecoderProperties2, - public CMyUnknownImp -{ -public: - CLzOutWindow m_OutWindowStream; - CBitDecoder m_InBitStream; - - UInt32 m_RepDists[kNumRepDists]; - UInt32 m_RepDistPtr; - - UInt32 LastDist; - UInt32 LastLength; - - Int64 m_UnpackSize; - bool m_IsSolid; - - UInt32 ReadBits(int numBits); - HRESULT CopyBlock(UInt32 distance, UInt32 len); - - UInt32 DecodeNum(const UInt32 *posTab); - HRESULT ShortLZ(); - HRESULT LongLZ(); - HRESULT HuffDecode(); - void GetFlagsBuf(); - void InitData(); - void InitHuff(); - void CorrHuff(UInt32 *CharSet, UInt32 *NumToPlace); - void OldUnpWriteBuf(); - - UInt32 ChSet[256],ChSetA[256],ChSetB[256],ChSetC[256]; - UInt32 Place[256],PlaceA[256],PlaceB[256],PlaceC[256]; - UInt32 NToPl[256],NToPlB[256],NToPlC[256]; - UInt32 FlagBuf,AvrPlc,AvrPlcB,AvrLn1,AvrLn2,AvrLn3; - int Buf60,NumHuf,StMode,LCount,FlagsCnt; - UInt32 Nhfb,Nlzb,MaxDist3; - - void InitStructures(); - - HRESULT CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - -public: - CDecoder(); - - MY_UNKNOWN_IMP1(ICompressSetDecoderProperties2) - - void ReleaseStreams() - { - m_OutWindowStream.ReleaseStream(); - m_InBitStream.ReleaseStream(); - } - - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - - STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size); - -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/Rar2Decoder.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/Rar2Decoder.cpp deleted file mode 100644 index 194a4bdf3..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/Rar2Decoder.cpp +++ /dev/null @@ -1,389 +0,0 @@ -// Rar2Decoder.cpp -// According to unRAR license, this code may not be used to develop -// a program that creates RAR archives - -#include "StdAfx.h" - -#include "Rar2Decoder.h" - -namespace NCompress { -namespace NRar2 { - -namespace NMultimedia { - -Byte CFilter::Decode(int &channelDelta, Byte deltaByte) -{ - D4 = D3; - D3 = D2; - D2 = LastDelta - D1; - D1 = LastDelta; - int predictedValue = ((8 * LastChar + K1 * D1 + K2 * D2 + K3 * D3 + K4 * D4 + K5 * channelDelta) >> 3); - - Byte realValue = (Byte)(predictedValue - deltaByte); - int i = ((int)(signed char)deltaByte) << 3; - - Dif[0] += abs(i); - Dif[1] += abs(i - D1); - Dif[2] += abs(i + D1); - Dif[3] += abs(i - D2); - Dif[4] += abs(i + D2); - Dif[5] += abs(i - D3); - Dif[6] += abs(i + D3); - Dif[7] += abs(i - D4); - Dif[8] += abs(i + D4); - Dif[9] += abs(i - channelDelta); - Dif[10] += abs(i + channelDelta); - - channelDelta = LastDelta = (signed char)(realValue - LastChar); - LastChar = realValue; - - if (((++ByteCount) & 0x1F) == 0) - { - UInt32 minDif = Dif[0]; - UInt32 numMinDif = 0; - Dif[0] = 0; - for (i = 1; i < sizeof(Dif) / sizeof(Dif[0]); i++) - { - if (Dif[i] < minDif) - { - minDif = Dif[i]; - numMinDif = i; - } - Dif[i] = 0; - } - switch(numMinDif) - { - case 1: if (K1 >= -16) K1--; break; - case 2: if (K1 < 16) K1++; break; - case 3: if (K2 >= -16) K2--; break; - case 4: if (K2 < 16) K2++; break; - case 5: if (K3 >= -16) K3--; break; - case 6: if (K3 < 16) K3++; break; - case 7: if (K4 >= -16) K4--; break; - case 8: if (K4 < 16) K4++; break; - case 9: if (K5 >= -16) K5--; break; - case 10:if (K5 < 16) K5++; break; - } - } - return realValue; -} -} - -static const char *kNumberErrorMessage = "Number error"; - -static const UInt32 kHistorySize = 1 << 20; - -static const int kNumStats = 11; - -static const UInt32 kWindowReservSize = (1 << 22) + 256; - -CDecoder::CDecoder(): - m_IsSolid(false) -{ -} - -void CDecoder::InitStructures() -{ - m_MmFilter.Init(); - for(int i = 0; i < kNumRepDists; i++) - m_RepDists[i] = 0; - m_RepDistPtr = 0; - m_LastLength = 0; - memset(m_LastLevels, 0, kMaxTableSize); -} - -UInt32 CDecoder::ReadBits(int numBits) { return m_InBitStream.ReadBits(numBits); } - -#define RIF(x) { if (!(x)) return false; } - -bool CDecoder::ReadTables(void) -{ - Byte levelLevels[kLevelTableSize]; - Byte newLevels[kMaxTableSize]; - m_AudioMode = (ReadBits(1) == 1); - - if (ReadBits(1) == 0) - memset(m_LastLevels, 0, kMaxTableSize); - int numLevels; - if (m_AudioMode) - { - m_NumChannels = ReadBits(2) + 1; - if (m_MmFilter.CurrentChannel >= m_NumChannels) - m_MmFilter.CurrentChannel = 0; - numLevels = m_NumChannels * kMMTableSize; - } - else - numLevels = kHeapTablesSizesSum; - - int i; - for (i = 0; i < kLevelTableSize; i++) - levelLevels[i] = (Byte)ReadBits(4); - RIF(m_LevelDecoder.SetCodeLengths(levelLevels)); - i = 0; - while (i < numLevels) - { - UInt32 number = m_LevelDecoder.DecodeSymbol(&m_InBitStream); - if (number < kTableDirectLevels) - { - newLevels[i] = (Byte)((number + m_LastLevels[i]) & kLevelMask); - i++; - } - else - { - if (number == kTableLevelRepNumber) - { - int t = ReadBits(2) + 3; - for (int reps = t; reps > 0 && i < numLevels ; reps--, i++) - newLevels[i] = newLevels[i - 1]; - } - else - { - int num; - if (number == kTableLevel0Number) - num = ReadBits(3) + 3; - else if (number == kTableLevel0Number2) - num = ReadBits(7) + 11; - else - return false; - for (;num > 0 && i < numLevels; num--) - newLevels[i++] = 0; - } - } - } - if (m_AudioMode) - for (i = 0; i < m_NumChannels; i++) - { - RIF(m_MMDecoders[i].SetCodeLengths(&newLevels[i * kMMTableSize])); - } - else - { - RIF(m_MainDecoder.SetCodeLengths(&newLevels[0])); - RIF(m_DistDecoder.SetCodeLengths(&newLevels[kMainTableSize])); - RIF(m_LenDecoder.SetCodeLengths(&newLevels[kMainTableSize + kDistTableSize])); - } - memcpy(m_LastLevels, newLevels, kMaxTableSize); - return true; -} - -bool CDecoder::ReadLastTables() -{ - // it differs a little from pure RAR sources; - // UInt64 ttt = m_InBitStream.GetProcessedSize() + 2; - // + 2 works for: return 0xFF; in CInBuffer::ReadByte. - if (m_InBitStream.GetProcessedSize() + 7 <= m_PackSize) // test it: probably incorrect; - // if (m_InBitStream.GetProcessedSize() + 2 <= m_PackSize) // test it: probably incorrect; - if (m_AudioMode) - { - UInt32 symbol = m_MMDecoders[m_MmFilter.CurrentChannel].DecodeSymbol(&m_InBitStream); - if (symbol == 256) - return ReadTables(); - if (symbol >= kMMTableSize) - return false; - } - else - { - UInt32 number = m_MainDecoder.DecodeSymbol(&m_InBitStream); - if (number == kReadTableNumber) - return ReadTables(); - if (number >= kMainTableSize) - return false; - } - return true; -} - -class CCoderReleaser -{ - CDecoder *m_Coder; -public: - CCoderReleaser(CDecoder *coder): m_Coder(coder) {} - ~CCoderReleaser() - { - m_Coder->ReleaseStreams(); - } -}; - -bool CDecoder::DecodeMm(UInt32 pos) -{ - while (pos-- > 0) - { - UInt32 symbol = m_MMDecoders[m_MmFilter.CurrentChannel].DecodeSymbol(&m_InBitStream); - if (symbol == 256) - return true; - if (symbol >= kMMTableSize) - return false; - /* - Byte byPredict = m_Predictor.Predict(); - Byte byReal = (Byte)(byPredict - (Byte)symbol); - m_Predictor.Update(byReal, byPredict); - */ - Byte byReal = m_MmFilter.Decode((Byte)symbol); - m_OutWindowStream.PutByte(byReal); - if (++m_MmFilter.CurrentChannel == m_NumChannels) - m_MmFilter.CurrentChannel = 0; - } - return true; -} - -bool CDecoder::DecodeLz(Int32 pos) -{ - while (pos > 0) - { - UInt32 number = m_MainDecoder.DecodeSymbol(&m_InBitStream); - UInt32 length, distance; - if (number < 256) - { - m_OutWindowStream.PutByte(Byte(number)); - pos--; - continue; - } - else if (number >= kMatchNumber) - { - number -= kMatchNumber; - length = kNormalMatchMinLen + UInt32(kLenStart[number]) + - m_InBitStream.ReadBits(kLenDirectBits[number]); - number = m_DistDecoder.DecodeSymbol(&m_InBitStream); - if (number >= kDistTableSize) - return false; - distance = kDistStart[number] + m_InBitStream.ReadBits(kDistDirectBits[number]); - if (distance >= kDistLimit3) - { - length += 2 - ((distance - kDistLimit4) >> 31); - // length++; - // if (distance >= kDistLimit4) - // length++; - } - } - else if (number == kRepBothNumber) - { - length = m_LastLength; - distance = m_RepDists[(m_RepDistPtr + 4 - 1) & 3]; - } - else if (number < kLen2Number) - { - distance = m_RepDists[(m_RepDistPtr - (number - kRepNumber + 1)) & 3]; - number = m_LenDecoder.DecodeSymbol(&m_InBitStream); - if (number >= kLenTableSize) - return false; - length = 2 + kLenStart[number] + m_InBitStream.ReadBits(kLenDirectBits[number]); - if (distance >= kDistLimit2) - { - length++; - if (distance >= kDistLimit3) - { - length += 2 - ((distance - kDistLimit4) >> 31); - // length++; - // if (distance >= kDistLimit4) - // length++; - } - } - } - else if (number < kReadTableNumber) - { - number -= kLen2Number; - distance = kLen2DistStarts[number] + - m_InBitStream.ReadBits(kLen2DistDirectBits[number]); - length = 2; - } - else if (number == kReadTableNumber) - return true; - else - return false; - m_RepDists[m_RepDistPtr++ & 3] = distance; - m_LastLength = length; - if (!m_OutWindowStream.CopyBlock(distance, length)) - return false; - pos -= length; - } - return true; -} - -HRESULT CDecoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) -{ - if (inSize == NULL || outSize == NULL) - return E_INVALIDARG; - - if (!m_OutWindowStream.Create(kHistorySize)) - return E_OUTOFMEMORY; - if (!m_InBitStream.Create(1 << 20)) - return E_OUTOFMEMORY; - - m_PackSize = *inSize; - - UInt64 pos = 0, unPackSize = *outSize; - - m_OutWindowStream.SetStream(outStream); - m_OutWindowStream.Init(m_IsSolid); - m_InBitStream.SetStream(inStream); - m_InBitStream.Init(); - - CCoderReleaser coderReleaser(this); - if (!m_IsSolid) - { - InitStructures(); - if (unPackSize == 0) - { - if (m_InBitStream.GetProcessedSize() + 2 <= m_PackSize) // test it: probably incorrect; - if (!ReadTables()) - return S_FALSE; - return S_OK; - } - if (!ReadTables()) - return S_FALSE; - } - - UInt64 startPos = m_OutWindowStream.GetProcessedSize(); - while(pos < unPackSize) - { - UInt32 blockSize = 1 << 20; - if (blockSize > unPackSize - pos) - blockSize = (UInt32)(unPackSize - pos); - UInt64 blockStartPos = m_OutWindowStream.GetProcessedSize(); - if (m_AudioMode) - { - if (!DecodeMm(blockSize)) - return S_FALSE; - } - else - { - if (!DecodeLz((Int32)blockSize)) - return S_FALSE; - } - UInt64 globalPos = m_OutWindowStream.GetProcessedSize(); - pos = globalPos - blockStartPos; - if (pos < blockSize) - if (!ReadTables()) - return S_FALSE; - pos = globalPos - startPos; - if (progress != 0) - { - UInt64 packSize = m_InBitStream.GetProcessedSize(); - RINOK(progress->SetRatioInfo(&packSize, &pos)); - } - } - if (pos > unPackSize) - return S_FALSE; - - if (!ReadLastTables()) - return S_FALSE; - return m_OutWindowStream.Flush(); -} - -STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) -{ - try { return CodeReal(inStream, outStream, inSize, outSize, progress); } - catch(const CInBufferException &e) { return e.ErrorCode; } - catch(const CLzOutWindowException &e) { return e.ErrorCode; } - catch(...) { return S_FALSE; } -} - -STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte *data, UInt32 size) -{ - if (size < 1) - return E_INVALIDARG; - m_IsSolid = (data[0] != 0); - return S_OK; -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/Rar2Decoder.h b/desmume/src/windows/7z/CPP/7zip/Compress/Rar2Decoder.h deleted file mode 100644 index 65cc97307..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/Rar2Decoder.h +++ /dev/null @@ -1,174 +0,0 @@ -// Rar2Decoder.h -// According to unRAR license, this code may not be used to develop -// a program that creates RAR archives - -#ifndef __COMPRESS_RAR2_DECODER_H -#define __COMPRESS_RAR2_DECODER_H - -#include "../../Common/MyCom.h" - -#include "../ICoder.h" - -#include "../Common/InBuffer.h" - -#include "BitmDecoder.h" -#include "HuffmanDecoder.h" -#include "LzOutWindow.h" - -namespace NCompress { -namespace NRar2 { - -const UInt32 kNumRepDists = 4; -const UInt32 kDistTableSize = 48; - -const int kMMTableSize = 256 + 1; - -const UInt32 kMainTableSize = 298; -const UInt32 kLenTableSize = 28; - -const UInt32 kDistTableStart = kMainTableSize; -const UInt32 kLenTableStart = kDistTableStart + kDistTableSize; - -const UInt32 kHeapTablesSizesSum = kMainTableSize + kDistTableSize + kLenTableSize; - -const UInt32 kLevelTableSize = 19; - -const UInt32 kMMTablesSizesSum = kMMTableSize * 4; - -const UInt32 kMaxTableSize = kMMTablesSizesSum; - -const UInt32 kTableDirectLevels = 16; -const UInt32 kTableLevelRepNumber = kTableDirectLevels; -const UInt32 kTableLevel0Number = kTableLevelRepNumber + 1; -const UInt32 kTableLevel0Number2 = kTableLevel0Number + 1; - -const UInt32 kLevelMask = 0xF; - - -const UInt32 kRepBothNumber = 256; -const UInt32 kRepNumber = kRepBothNumber + 1; -const UInt32 kLen2Number = kRepNumber + 4; - -const UInt32 kLen2NumNumbers = 8; -const UInt32 kReadTableNumber = kLen2Number + kLen2NumNumbers; -const UInt32 kMatchNumber = kReadTableNumber + 1; - -const Byte kLenStart[kLenTableSize] = {0,1,2,3,4,5,6,7,8,10,12,14,16,20,24,28,32,40,48,56,64,80,96,112,128,160,192,224}; -const Byte kLenDirectBits[kLenTableSize] = {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}; - -const UInt32 kDistStart[kDistTableSize] = {0,1,2,3,4,6,8,12,16,24,32,48,64,96,128,192,256,384,512,768,1024,1536,2048,3072,4096,6144,8192,12288,16384,24576,32768U,49152U,65536,98304,131072,196608,262144,327680,393216,458752,524288,589824,655360,720896,786432,851968,917504,983040}; -const Byte kDistDirectBits[kDistTableSize] = {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, 14, 14, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16}; - -const Byte kLevelDirectBits[kLevelTableSize] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7}; - -const Byte kLen2DistStarts[kLen2NumNumbers]={0,4,8,16,32,64,128,192}; -const Byte kLen2DistDirectBits[kLen2NumNumbers]={2,2,3, 4, 5, 6, 6, 6}; - -const UInt32 kDistLimit2 = 0x101 - 1; -const UInt32 kDistLimit3 = 0x2000 - 1; -const UInt32 kDistLimit4 = 0x40000 - 1; - -const UInt32 kMatchMaxLen = 255 + 2; -const UInt32 kMatchMaxLenMax = 255 + 5; -const UInt32 kNormalMatchMinLen = 3; - -namespace NMultimedia { - -struct CFilter -{ - int K1,K2,K3,K4,K5; - int D1,D2,D3,D4; - int LastDelta; - UInt32 Dif[11]; - UInt32 ByteCount; - int LastChar; - - Byte Decode(int &channelDelta, Byte delta); - - void Init() { memset(this, 0, sizeof(*this)); } - -}; - -const int kNumChanelsMax = 4; - -class CFilter2 -{ -public: - CFilter m_Filters[kNumChanelsMax]; - int m_ChannelDelta; - int CurrentChannel; - - void Init() { memset(this, 0, sizeof(*this)); } - Byte Decode(Byte delta) - { - return m_Filters[CurrentChannel].Decode(m_ChannelDelta, delta); - } - -}; - -} - -typedef NBitm::CDecoder CBitDecoder; - -const int kNumHuffmanBits = 15; - -class CDecoder : - public ICompressCoder, - public ICompressSetDecoderProperties2, - public CMyUnknownImp -{ - CLzOutWindow m_OutWindowStream; - CBitDecoder m_InBitStream; - NHuffman::CDecoder m_MainDecoder; - NHuffman::CDecoder m_DistDecoder; - NHuffman::CDecoder m_LenDecoder; - NHuffman::CDecoder m_MMDecoders[NMultimedia::kNumChanelsMax]; - NHuffman::CDecoder m_LevelDecoder; - - bool m_AudioMode; - - NMultimedia::CFilter2 m_MmFilter; - int m_NumChannels; - - UInt32 m_RepDists[kNumRepDists]; - UInt32 m_RepDistPtr; - - UInt32 m_LastLength; - - Byte m_LastLevels[kMaxTableSize]; - - UInt64 m_PackSize; - bool m_IsSolid; - - void InitStructures(); - UInt32 ReadBits(int numBits); - bool ReadTables(); - bool ReadLastTables(); - - bool DecodeMm(UInt32 pos); - bool DecodeLz(Int32 pos); - - HRESULT CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - -public: - CDecoder(); - - MY_UNKNOWN_IMP1(ICompressSetDecoderProperties2) - - void ReleaseStreams() - { - m_OutWindowStream.ReleaseStream(); - m_InBitStream.ReleaseStream(); - } - - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - - STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size); - -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/Rar3Decoder.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/Rar3Decoder.cpp deleted file mode 100644 index fb52437e7..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/Rar3Decoder.cpp +++ /dev/null @@ -1,834 +0,0 @@ -// Rar3Decoder.cpp -// According to unRAR license, this code may not be used to develop -// a program that creates RAR archives - -#include "StdAfx.h" - -#include "../Common/StreamUtils.h" - -#include "Rar3Decoder.h" - -namespace NCompress { -namespace NRar3 { - -static const UInt32 kNumAlignReps = 15; - -static const UInt32 kSymbolReadTable = 256; -static const UInt32 kSymbolRep = 259; -static const UInt32 kSymbolLen2 = kSymbolRep + kNumReps; - -static const Byte kLenStart[kLenTableSize] = {0,1,2,3,4,5,6,7,8,10,12,14,16,20,24,28,32,40,48,56,64,80,96,112,128,160,192,224}; -static const Byte kLenDirectBits[kLenTableSize] = {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}; - -static const Byte kDistDirectBits[kDistTableSize] = - {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,14,14,15,15, - 16,16,16,16,16,16,16,16,16,16,16,16,16,16, - 18,18,18,18,18,18,18,18,18,18,18,18}; - -static const Byte kLevelDirectBits[kLevelTableSize] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7}; - -static const Byte kLen2DistStarts[kNumLen2Symbols]={0,4,8,16,32,64,128,192}; -static const Byte kLen2DistDirectBits[kNumLen2Symbols]={2,2,3, 4, 5, 6, 6, 6}; - -static const UInt32 kDistLimit3 = 0x2000 - 2; -static const UInt32 kDistLimit4 = 0x40000 - 2; - -static const UInt32 kNormalMatchMinLen = 3; - -static const UInt32 kVmDataSizeMax = 1 << 16; -static const UInt32 kVmCodeSizeMax = 1 << 16; - -CDecoder::CDecoder(): - _window(0), - _winPos(0), - _wrPtr(0), - _lzSize(0), - _writtenFileSize(0), - _vmData(0), - _vmCode(0), - m_IsSolid(false) -{ -} - -CDecoder::~CDecoder() -{ - InitFilters(); - ::MidFree(_vmData); - ::MidFree(_window); -} - -HRESULT CDecoder::WriteDataToStream(const Byte *data, UInt32 size) -{ - return WriteStream(_outStream, data, size); -} - -HRESULT CDecoder::WriteData(const Byte *data, UInt32 size) -{ - HRESULT res = S_OK; - if (_writtenFileSize < _unpackSize) - { - UInt32 curSize = size; - UInt64 remain = _unpackSize - _writtenFileSize; - if (remain < curSize) - curSize = (UInt32)remain; - res = WriteDataToStream(data, curSize); - } - _writtenFileSize += size; - return res; -} - -HRESULT CDecoder::WriteArea(UInt32 startPtr, UInt32 endPtr) -{ - if (startPtr <= endPtr) - return WriteData(_window + startPtr, endPtr - startPtr); - RINOK(WriteData(_window + startPtr, kWindowSize - startPtr)); - return WriteData(_window, endPtr); -} - -void CDecoder::ExecuteFilter(int tempFilterIndex, NVm::CBlockRef &outBlockRef) -{ - CTempFilter *tempFilter = _tempFilters[tempFilterIndex]; - tempFilter->InitR[6] = (UInt32)_writtenFileSize; - NVm::SetValue32(&tempFilter->GlobalData[0x24], (UInt32)_writtenFileSize); - NVm::SetValue32(&tempFilter->GlobalData[0x28], (UInt32)(_writtenFileSize >> 32)); - CFilter *filter = _filters[tempFilter->FilterIndex]; - _vm.Execute(filter, tempFilter, outBlockRef, filter->GlobalData); - delete tempFilter; - _tempFilters[tempFilterIndex] = 0; -} - -HRESULT CDecoder::WriteBuf() -{ - UInt32 writtenBorder = _wrPtr; - UInt32 writeSize = (_winPos - writtenBorder) & kWindowMask; - for (int i = 0; i < _tempFilters.Size(); i++) - { - CTempFilter *filter = _tempFilters[i]; - if (filter == NULL) - continue; - if (filter->NextWindow) - { - filter->NextWindow = false; - continue; - } - UInt32 blockStart = filter->BlockStart; - UInt32 blockSize = filter->BlockSize; - if (((blockStart - writtenBorder) & kWindowMask) < writeSize) - { - if (writtenBorder != blockStart) - { - RINOK(WriteArea(writtenBorder, blockStart)); - writtenBorder = blockStart; - writeSize = (_winPos - writtenBorder) & kWindowMask; - } - if (blockSize <= writeSize) - { - UInt32 blockEnd = (blockStart + blockSize) & kWindowMask; - if (blockStart < blockEnd || blockEnd == 0) - _vm.SetMemory(0, _window + blockStart, blockSize); - else - { - UInt32 tailSize = kWindowSize - blockStart; - _vm.SetMemory(0, _window + blockStart, tailSize); - _vm.SetMemory(tailSize, _window, blockEnd); - } - NVm::CBlockRef outBlockRef; - ExecuteFilter(i, outBlockRef); - while (i + 1 < _tempFilters.Size()) - { - CTempFilter *nextFilter = _tempFilters[i + 1]; - if (nextFilter == NULL || nextFilter->BlockStart != blockStart || - nextFilter->BlockSize != outBlockRef.Size || nextFilter->NextWindow) - break; - _vm.SetMemory(0, _vm.GetDataPointer(outBlockRef.Offset), outBlockRef.Size); - ExecuteFilter(++i, outBlockRef); - } - WriteDataToStream(_vm.GetDataPointer(outBlockRef.Offset), outBlockRef.Size); - _writtenFileSize += outBlockRef.Size; - writtenBorder = blockEnd; - writeSize = (_winPos - writtenBorder) & kWindowMask; - } - else - { - for (int j = i; j < _tempFilters.Size(); j++) - { - CTempFilter *filter = _tempFilters[j]; - if (filter != NULL && filter->NextWindow) - filter->NextWindow = false; - } - _wrPtr = writtenBorder; - return S_OK; // check it - } - } - } - - _wrPtr = _winPos; - return WriteArea(writtenBorder, _winPos); -} - -void CDecoder::InitFilters() -{ - _lastFilter = 0; - int i; - for (i = 0; i < _tempFilters.Size(); i++) - delete _tempFilters[i]; - _tempFilters.Clear(); - for (i = 0; i < _filters.Size(); i++) - delete _filters[i]; - _filters.Clear(); -} - -bool CDecoder::AddVmCode(UInt32 firstByte, UInt32 codeSize) -{ - CMemBitDecoder inp; - inp.Init(_vmData, codeSize); - - UInt32 filterIndex; - if (firstByte & 0x80) - { - filterIndex = NVm::ReadEncodedUInt32(inp); - if (filterIndex == 0) - InitFilters(); - else - filterIndex--; - } - else - filterIndex = _lastFilter; - if (filterIndex > (UInt32)_filters.Size()) - return false; - _lastFilter = filterIndex; - bool newFilter = (filterIndex == (UInt32)_filters.Size()); - - CFilter *filter; - if (newFilter) - { - // check if too many filters - if (filterIndex > 1024) - return false; - filter = new CFilter; - _filters.Add(filter); - } - else - { - filter = _filters[filterIndex]; - filter->ExecCount++; - } - - int numEmptyItems = 0; - int i; - for (i = 0; i < _tempFilters.Size(); i++) - { - _tempFilters[i - numEmptyItems] = _tempFilters[i]; - if (_tempFilters[i] == NULL) - numEmptyItems++; - if (numEmptyItems > 0) - _tempFilters[i] = NULL; - } - if (numEmptyItems == 0) - { - _tempFilters.Add(NULL); - numEmptyItems = 1; - } - CTempFilter *tempFilter = new CTempFilter; - _tempFilters[_tempFilters.Size() - numEmptyItems] = tempFilter; - tempFilter->FilterIndex = filterIndex; - tempFilter->ExecCount = filter->ExecCount; - - UInt32 blockStart = NVm::ReadEncodedUInt32(inp); - if (firstByte & 0x40) - blockStart += 258; - tempFilter->BlockStart = (blockStart + _winPos) & kWindowMask; - if (firstByte & 0x20) - filter->BlockSize = NVm::ReadEncodedUInt32(inp); - tempFilter->BlockSize = filter->BlockSize; - tempFilter->NextWindow = _wrPtr != _winPos && ((_wrPtr - _winPos) & kWindowMask) <= blockStart; - - memset(tempFilter->InitR, 0, sizeof(tempFilter->InitR)); - tempFilter->InitR[3] = NVm::kGlobalOffset; - tempFilter->InitR[4] = tempFilter->BlockSize; - tempFilter->InitR[5] = tempFilter->ExecCount; - if (firstByte & 0x10) - { - UInt32 initMask = inp.ReadBits(NVm::kNumGpRegs); - for (int i = 0; i < NVm::kNumGpRegs; i++) - if (initMask & (1 << i)) - tempFilter->InitR[i] = NVm::ReadEncodedUInt32(inp); - } - if (newFilter) - { - UInt32 vmCodeSize = NVm::ReadEncodedUInt32(inp); - if (vmCodeSize >= kVmCodeSizeMax || vmCodeSize == 0) - return false; - for (UInt32 i = 0; i < vmCodeSize; i++) - _vmCode[i] = (Byte)inp.ReadBits(8); - _vm.PrepareProgram(_vmCode, vmCodeSize, filter); - } - - tempFilter->AllocateEmptyFixedGlobal(); - - Byte *globalData = &tempFilter->GlobalData[0]; - for (i = 0; i < NVm::kNumGpRegs; i++) - NVm::SetValue32(&globalData[i * 4], tempFilter->InitR[i]); - NVm::SetValue32(&globalData[NVm::NGlobalOffset::kBlockSize], tempFilter->BlockSize); - NVm::SetValue32(&globalData[NVm::NGlobalOffset::kBlockPos], 0); // It was commented. why? - NVm::SetValue32(&globalData[NVm::NGlobalOffset::kExecCount], tempFilter->ExecCount); - - if (firstByte & 8) - { - UInt32 dataSize = NVm::ReadEncodedUInt32(inp); - if (dataSize > NVm::kGlobalSize - NVm::kFixedGlobalSize) - return false; - CRecordVector &globalData = tempFilter->GlobalData; - int requredSize = (int)(dataSize + NVm::kFixedGlobalSize); - if (globalData.Size() < requredSize) - { - globalData.Reserve(requredSize); - for (; globalData.Size() < requredSize; i++) - globalData.Add(0); - } - for (UInt32 i = 0; i < dataSize; i++) - globalData[NVm::kFixedGlobalSize + i] = (Byte)inp.ReadBits(8); - } - return true; -} - -bool CDecoder::ReadVmCodeLZ() -{ - UInt32 firstByte = m_InBitStream.ReadBits(8); - UInt32 length = (firstByte & 7) + 1; - if (length == 7) - length = m_InBitStream.ReadBits(8) + 7; - else if (length == 8) - length = m_InBitStream.ReadBits(16); - if (length > kVmDataSizeMax) - return false; - for (UInt32 i = 0; i < length; i++) - _vmData[i] = (Byte)m_InBitStream.ReadBits(8); - return AddVmCode(firstByte, length); -} - -bool CDecoder::ReadVmCodePPM() -{ - int firstByte = DecodePpmSymbol(); - if (firstByte == -1) - return false; - UInt32 length = (firstByte & 7) + 1; - if (length == 7) - { - int b1 = DecodePpmSymbol(); - if (b1 == -1) - return false; - length = b1 + 7; - } - else if (length == 8) - { - int b1 = DecodePpmSymbol(); - if (b1 == -1) - return false; - int b2 = DecodePpmSymbol(); - if (b2 == -1) - return false; - length = b1 * 256 + b2; - } - if (length > kVmDataSizeMax) - return false; - for (UInt32 i = 0; i < length; i++) - { - int b = DecodePpmSymbol(); - if (b == -1) - return false; - _vmData[i] = (Byte)b; - } - return AddVmCode(firstByte, length); -} - -#define RIF(x) { if (!(x)) return S_FALSE; } - -UInt32 CDecoder::ReadBits(int numBits) { return m_InBitStream.ReadBits(numBits); } - -///////////////////////////////////////////////// -// PPM - -HRESULT CDecoder::InitPPM() -{ - Byte maxOrder = (Byte)ReadBits(7); - - bool reset = ((maxOrder & 0x20) != 0); - int maxMB = 0; - if (reset) - maxMB = (Byte)ReadBits(8); - else - { - if (_ppm.SubAllocator.GetSubAllocatorSize()== 0) - return S_FALSE; - } - if (maxOrder & 0x40) - PpmEscChar = (Byte)ReadBits(8); - m_InBitStream.InitRangeCoder(); - /* - if (m_InBitStream.m_BitPos != 0) - return S_FALSE; - */ - if (reset) - { - maxOrder = (maxOrder & 0x1F) + 1; - if (maxOrder > 16) - maxOrder = 16 + (maxOrder - 16) * 3; - if (maxOrder == 1) - { - // SubAlloc.StopSubAllocator(); - _ppm.SubAllocator.StopSubAllocator(); - return S_FALSE; - } - // SubAlloc.StartSubAllocator(MaxMB+1); - // StartModelRare(maxOrder); - - if (!_ppm.SubAllocator.StartSubAllocator((maxMB + 1) << 20)) - return E_OUTOFMEMORY; - _ppm.MaxOrder = 0; - _ppm.StartModelRare(maxOrder); - - } - // return (minContext != NULL); - - return S_OK; -} - -int CDecoder::DecodePpmSymbol() { return _ppm.DecodeSymbol(&m_InBitStream); } - -HRESULT CDecoder::DecodePPM(Int32 num, bool &keepDecompressing) -{ - keepDecompressing = false; - do - { - if (((_wrPtr - _winPos) & kWindowMask) < 260 && _wrPtr != _winPos) - { - RINOK(WriteBuf()); - if (_writtenFileSize > _unpackSize) - { - keepDecompressing = false; - return S_OK; - } - } - int c = DecodePpmSymbol(); - if (c == -1) - { - // Original code sets PPMError=true here and then it returns S_OK. Why ??? - // return S_OK; - return S_FALSE; - } - if (c == PpmEscChar) - { - int nextCh = DecodePpmSymbol(); - if (nextCh == 0) - return ReadTables(keepDecompressing); - if (nextCh == 2 || nextCh == -1) - return S_OK; - if (nextCh == 3) - { - if (!ReadVmCodePPM()) - return S_FALSE; - continue; - } - if (nextCh == 4 || nextCh == 5) - { - UInt32 distance = 0; - UInt32 length = 4; - if (nextCh == 4) - { - for (int i = 0; i < 3; i++) - { - int c = DecodePpmSymbol(); - if (c == -1) - return S_OK; - distance = (distance << 8) + (Byte)c; - } - distance++; - length += 28; - } - int c = DecodePpmSymbol(); - if (c == -1) - return S_OK; - length += c; - if (distance >= _lzSize) - return S_FALSE; - CopyBlock(distance, length); - num -= (Int32)length; - continue; - } - } - PutByte((Byte)c); - num--; - } - while (num >= 0); - keepDecompressing = true; - return S_OK; -} - -///////////////////////////////////////////////// -// LZ - -HRESULT CDecoder::ReadTables(bool &keepDecompressing) -{ - keepDecompressing = true; - ReadBits((8 - m_InBitStream.GetBitPosition()) & 7); - if (ReadBits(1) != 0) - { - _lzMode = false; - return InitPPM(); - } - - _lzMode = true; - PrevAlignBits = 0; - PrevAlignCount = 0; - - Byte levelLevels[kLevelTableSize]; - Byte newLevels[kTablesSizesSum]; - - if (ReadBits(1) == 0) - memset(m_LastLevels, 0, kTablesSizesSum); - - int i; - for (i = 0; i < kLevelTableSize; i++) - { - UInt32 length = ReadBits(4); - if (length == 15) - { - UInt32 zeroCount = ReadBits(4); - if (zeroCount != 0) - { - zeroCount += 2; - while (zeroCount-- > 0 && i < kLevelTableSize) - levelLevels[i++]=0; - i--; - continue; - } - } - levelLevels[i] = (Byte)length; - } - RIF(m_LevelDecoder.SetCodeLengths(levelLevels)); - i = 0; - while (i < kTablesSizesSum) - { - UInt32 number = m_LevelDecoder.DecodeSymbol(&m_InBitStream); - if (number < 16) - { - newLevels[i] = Byte((number + m_LastLevels[i]) & 15); - i++; - } - else if (number > kLevelTableSize) - return S_FALSE; - else - { - int num; - if (((number - 16) & 1) == 0) - num = ReadBits(3) + 3; - else - num = ReadBits(7) + 11; - if (number < 18) - { - if (i == 0) - return S_FALSE; - for (; num > 0 && i < kTablesSizesSum; num--, i++) - newLevels[i] = newLevels[i - 1]; - } - else - { - for (; num > 0 && i < kTablesSizesSum; num--) - newLevels[i++] = 0; - } - } - } - TablesRead = true; - - // original code has check here: - /* - if (InAddr > ReadTop) - { - keepDecompressing = false; - return true; - } - */ - - RIF(m_MainDecoder.SetCodeLengths(&newLevels[0])); - RIF(m_DistDecoder.SetCodeLengths(&newLevels[kMainTableSize])); - RIF(m_AlignDecoder.SetCodeLengths(&newLevels[kMainTableSize + kDistTableSize])); - RIF(m_LenDecoder.SetCodeLengths(&newLevels[kMainTableSize + kDistTableSize + kAlignTableSize])); - - memcpy(m_LastLevels, newLevels, kTablesSizesSum); - return S_OK; -} - -class CCoderReleaser -{ - CDecoder *m_Coder; -public: - CCoderReleaser(CDecoder *coder): m_Coder(coder) {} - ~CCoderReleaser() - { - // m_Coder->m_OutWindowStream.Flush(); - m_Coder->ReleaseStreams(); - } -}; - -HRESULT CDecoder::ReadEndOfBlock(bool &keepDecompressing) -{ - if (ReadBits(1) != 0) - { - // old file - TablesRead = false; - return ReadTables(keepDecompressing); - } - // new file - keepDecompressing = false; - TablesRead = (ReadBits(1) == 0); - return S_OK; -} - -UInt32 kDistStart[kDistTableSize]; - -class CDistInit -{ -public: - CDistInit() { Init(); } - void Init() - { - UInt32 start = 0; - for (UInt32 i = 0; i < kDistTableSize; i++) - { - kDistStart[i] = start; - start += (1 << kDistDirectBits[i]); - } - } -} g_DistInit; - -HRESULT CDecoder::DecodeLZ(bool &keepDecompressing) -{ - UInt32 rep0 = _reps[0]; - UInt32 rep1 = _reps[1]; - UInt32 rep2 = _reps[2]; - UInt32 rep3 = _reps[3]; - UInt32 length = _lastLength; - for (;;) - { - if (((_wrPtr - _winPos) & kWindowMask) < 260 && _wrPtr != _winPos) - { - RINOK(WriteBuf()); - if (_writtenFileSize > _unpackSize) - { - keepDecompressing = false; - return S_OK; - } - } - UInt32 number = m_MainDecoder.DecodeSymbol(&m_InBitStream); - if (number < 256) - { - PutByte(Byte(number)); - - continue; - } - else if (number == kSymbolReadTable) - { - RINOK(ReadEndOfBlock(keepDecompressing)); - break; - } - else if (number == 257) - { - if (!ReadVmCodeLZ()) - return S_FALSE; - continue; - } - else if (number == 258) - { - } - else if (number < kSymbolRep + 4) - { - if (number != kSymbolRep) - { - UInt32 distance; - if (number == kSymbolRep + 1) - distance = rep1; - else - { - if (number == kSymbolRep + 2) - distance = rep2; - else - { - distance = rep3; - rep3 = rep2; - } - rep2 = rep1; - } - rep1 = rep0; - rep0 = distance; - } - - UInt32 number = m_LenDecoder.DecodeSymbol(&m_InBitStream); - if (number >= kLenTableSize) - return S_FALSE; - length = 2 + kLenStart[number] + m_InBitStream.ReadBits(kLenDirectBits[number]); - } - else - { - rep3 = rep2; - rep2 = rep1; - rep1 = rep0; - if (number < 271) - { - number -= 263; - rep0 = kLen2DistStarts[number] + m_InBitStream.ReadBits(kLen2DistDirectBits[number]); - length = 2; - } - else if (number < 299) - { - number -= 271; - length = kNormalMatchMinLen + (UInt32)kLenStart[number] + m_InBitStream.ReadBits(kLenDirectBits[number]); - UInt32 number = m_DistDecoder.DecodeSymbol(&m_InBitStream); - if (number >= kDistTableSize) - return S_FALSE; - rep0 = kDistStart[number]; - int numBits = kDistDirectBits[number]; - if (number >= (kNumAlignBits * 2) + 2) - { - if (numBits > kNumAlignBits) - rep0 += (m_InBitStream.ReadBits(numBits - kNumAlignBits) << kNumAlignBits); - if (PrevAlignCount > 0) - { - PrevAlignCount--; - rep0 += PrevAlignBits; - } - else - { - UInt32 number = m_AlignDecoder.DecodeSymbol(&m_InBitStream); - if (number < (1 << kNumAlignBits)) - { - rep0 += number; - PrevAlignBits = number; - } - else if (number == (1 << kNumAlignBits)) - { - PrevAlignCount = kNumAlignReps; - rep0 += PrevAlignBits; - } - else - return S_FALSE; - } - } - else - rep0 += m_InBitStream.ReadBits(numBits); - length += ((kDistLimit4 - rep0) >> 31) + ((kDistLimit3 - rep0) >> 31); - } - else - return S_FALSE; - } - if (rep0 >= _lzSize) - return S_FALSE; - CopyBlock(rep0, length); - } - _reps[0] = rep0; - _reps[1] = rep1; - _reps[2] = rep2; - _reps[3] = rep3; - _lastLength = length; - - return S_OK; -} - -HRESULT CDecoder::CodeReal(ICompressProgressInfo *progress) -{ - _writtenFileSize = 0; - if (!m_IsSolid) - { - _lzSize = 0; - _winPos = 0; - _wrPtr = 0; - for (int i = 0; i < kNumReps; i++) - _reps[i] = 0; - _lastLength = 0; - memset(m_LastLevels, 0, kTablesSizesSum); - TablesRead = false; - PpmEscChar = 2; - InitFilters(); - } - if (!m_IsSolid || !TablesRead) - { - bool keepDecompressing; - RINOK(ReadTables(keepDecompressing)); - if (!keepDecompressing) - return S_OK; - } - - for(;;) - { - bool keepDecompressing; - if (_lzMode) - { - RINOK(DecodeLZ(keepDecompressing)) - } - else - { - RINOK(DecodePPM(1 << 18, keepDecompressing)) - } - UInt64 packSize = m_InBitStream.GetProcessedSize(); - RINOK(progress->SetRatioInfo(&packSize, &_writtenFileSize)); - if (!keepDecompressing) - break; - } - RINOK(WriteBuf()); - if (_writtenFileSize < _unpackSize) - return S_FALSE; - // return m_OutWindowStream.Flush(); - return S_OK; -} - -STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) -{ - try - { - if (inSize == NULL || outSize == NULL) - return E_INVALIDARG; - - if (_vmData == 0) - { - _vmData = (Byte *)::MidAlloc(kVmDataSizeMax + kVmCodeSizeMax); - if (_vmData == 0) - return E_OUTOFMEMORY; - _vmCode = _vmData + kVmDataSizeMax; - } - - if (_window == 0) - { - _window = (Byte *)::MidAlloc(kWindowSize); - if (_window == 0) - return E_OUTOFMEMORY; - } - if (!m_InBitStream.Create(1 << 20)) - return E_OUTOFMEMORY; - if (!_vm.Create()) - return E_OUTOFMEMORY; - - - m_InBitStream.SetStream(inStream); - m_InBitStream.Init(); - _outStream = outStream; - - CCoderReleaser coderReleaser(this); - _unpackSize = *outSize; - return CodeReal(progress); - } - catch(const CInBufferException &e) { return e.ErrorCode; } - catch(...) { return S_FALSE; } - // CNewException is possible here. But probably CNewException is caused - // by error in data stream. -} - -STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte *data, UInt32 size) -{ - if (size < 1) - return E_INVALIDARG; - m_IsSolid = (data[0] != 0); - return S_OK; -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/Rar3Decoder.h b/desmume/src/windows/7z/CPP/7zip/Compress/Rar3Decoder.h deleted file mode 100644 index da0b73f19..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/Rar3Decoder.h +++ /dev/null @@ -1,301 +0,0 @@ -// Rar3Decoder.h -// According to unRAR license, this code may not be used to develop -// a program that creates RAR archives - -#ifndef __COMPRESS_RAR3_DECODER_H -#define __COMPRESS_RAR3_DECODER_H - -#include "../../Common/MyCom.h" - -#include "../ICoder.h" - -#include "../Common/InBuffer.h" - -#include "BitmDecoder.h" -#include "HuffmanDecoder.h" -#include "PpmdDecode.h" -#include "Rar3Vm.h" - -namespace NCompress { -namespace NRar3 { - -const UInt32 kWindowSize = 1 << 22; -const UInt32 kWindowMask = (kWindowSize - 1); - -const UInt32 kNumReps = 4; -const UInt32 kNumLen2Symbols = 8; -const UInt32 kLenTableSize = 28; -const UInt32 kMainTableSize = 256 + 1 + 1 + 1 + kNumReps + kNumLen2Symbols + kLenTableSize; -const UInt32 kDistTableSize = 60; - -const int kNumAlignBits = 4; -const UInt32 kAlignTableSize = (1 << kNumAlignBits) + 1; - -const UInt32 kLevelTableSize = 20; - -const UInt32 kTablesSizesSum = kMainTableSize + kDistTableSize + kAlignTableSize + kLenTableSize; - -class CBitDecoder -{ - UInt32 m_Value; -public: - UInt32 m_BitPos; - CInBuffer m_Stream; - bool Create(UInt32 bufferSize) { return m_Stream.Create(bufferSize); } - void SetStream(ISequentialInStream *inStream) { m_Stream.SetStream(inStream);} - void ReleaseStream() { m_Stream.ReleaseStream();} - - void Init() - { - m_Stream.Init(); - m_BitPos = 0; - m_Value = 0; - // m_BitPos = kNumBigValueBits; - // Normalize(); - } - - UInt64 GetProcessedSize() const - { return m_Stream.GetProcessedSize() - (m_BitPos) / 8; } - UInt32 GetBitPosition() const { return ((8 - m_BitPos) & 7); } - - /* - void Normalize() - { - for (;m_BitPos >= 8; m_BitPos -= 8) - m_Value = (m_Value << 8) | m_Stream.ReadByte(); - } - */ - - UInt32 GetValue(UInt32 numBits) - { - // return (m_Value << m_BitPos) >> (kNumBigValueBits - numBits); - // return ((m_Value >> (8 - m_BitPos)) & kMask) >> (kNumValueBits - numBits); - if (m_BitPos < numBits) - { - m_BitPos += 8; - m_Value = (m_Value << 8) | m_Stream.ReadByte(); - if (m_BitPos < numBits) - { - m_BitPos += 8; - m_Value = (m_Value << 8) | m_Stream.ReadByte(); - } - } - return m_Value >> (m_BitPos - numBits); - } - - void MovePos(UInt32 numBits) - { - m_BitPos -= numBits; - m_Value = m_Value & ((1 << m_BitPos) - 1); - } - - UInt32 ReadBits(UInt32 numBits) - { - UInt32 res = GetValue(numBits); - MovePos(numBits); - return res; - } -}; - -const int kNumTopBits = 24; -const UInt32 kTopValue = (1 << kNumTopBits); -const UInt32 kBot = (1 << 15); - -class CRangeDecoder:public NPpmd::CRangeDecoderVirt, public CBitDecoder -{ -public: - UInt32 Range; - UInt32 Low; - UInt32 Code; - - void Normalize() - { - while ((Low ^ (Low + Range)) < kTopValue || - Range < kBot && ((Range = (0 - Low) & (kBot - 1)), 1)) - { - Code = (Code << 8) | m_Stream.ReadByte(); - Range <<= 8; - Low <<= 8; - } - } - - void InitRangeCoder() - { - Code = 0; - Low = 0; - Range = 0xFFFFFFFF; - for(int i = 0; i < 4; i++) - Code = (Code << 8) | ReadBits(8); - } - - virtual UInt32 GetThreshold(UInt32 total) - { - return (Code - Low) / ( Range /= total); - } - - virtual void Decode(UInt32 start, UInt32 size) - { - Low += start * Range; - Range *= size; - Normalize(); - } - - virtual UInt32 DecodeBit(UInt32 size0, UInt32 numTotalBits) - { - if (((Code - Low) / (Range >>= numTotalBits)) < size0) - { - Decode(0, size0); - return 0; - } - else - { - Decode(size0, (1 << numTotalBits) - size0); - return 1; - } - } - - // UInt64 GetProcessedSizeRangeCoder() {return Stream.GetProcessedSize(); } -}; - - -struct CFilter: public NVm::CProgram -{ - CRecordVector GlobalData; - UInt32 BlockStart; - UInt32 BlockSize; - UInt32 ExecCount; - CFilter(): BlockStart(0), BlockSize(0), ExecCount(0) {} -}; - -struct CTempFilter: public NVm::CProgramInitState -{ - UInt32 BlockStart; - UInt32 BlockSize; - UInt32 ExecCount; - bool NextWindow; - - UInt32 FilterIndex; -}; - -const int kNumHuffmanBits = 15; - -class CDecoder: - public ICompressCoder, - public ICompressSetDecoderProperties2, - public CMyUnknownImp -{ - CRangeDecoder m_InBitStream; - Byte *_window; - UInt32 _winPos; - UInt32 _wrPtr; - UInt64 _lzSize; - UInt64 _unpackSize; - UInt64 _writtenFileSize; // if it's > _unpackSize, then _unpackSize only written - CMyComPtr _outStream; - NHuffman::CDecoder m_MainDecoder; - NHuffman::CDecoder m_DistDecoder; - NHuffman::CDecoder m_AlignDecoder; - NHuffman::CDecoder m_LenDecoder; - NHuffman::CDecoder m_LevelDecoder; - - UInt32 _reps[kNumReps]; - UInt32 _lastLength; - - Byte m_LastLevels[kTablesSizesSum]; - - Byte *_vmData; - Byte *_vmCode; - NVm::CVm _vm; - CRecordVector _filters; - CRecordVector _tempFilters; - UInt32 _lastFilter; - - bool m_IsSolid; - - bool _lzMode; - - UInt32 PrevAlignBits; - UInt32 PrevAlignCount; - - bool TablesRead; - - NPpmd::CDecodeInfo _ppm; - int PpmEscChar; - - HRESULT WriteDataToStream(const Byte *data, UInt32 size); - HRESULT WriteData(const Byte *data, UInt32 size); - HRESULT WriteArea(UInt32 startPtr, UInt32 endPtr); - void ExecuteFilter(int tempFilterIndex, NVm::CBlockRef &outBlockRef); - HRESULT WriteBuf(); - - void InitFilters(); - bool AddVmCode(UInt32 firstByte, UInt32 codeSize); - bool ReadVmCodeLZ(); - bool ReadVmCodePPM(); - - UInt32 ReadBits(int numBits); - - HRESULT InitPPM(); - int DecodePpmSymbol(); - HRESULT DecodePPM(Int32 num, bool &keepDecompressing); - - HRESULT ReadTables(bool &keepDecompressing); - HRESULT ReadEndOfBlock(bool &keepDecompressing); - HRESULT DecodeLZ(bool &keepDecompressing); - HRESULT CodeReal(ICompressProgressInfo *progress); -public: - CDecoder(); - ~CDecoder(); - - MY_UNKNOWN_IMP1(ICompressSetDecoderProperties2) - - void ReleaseStreams() - { - _outStream.Release(); - m_InBitStream.ReleaseStream(); - } - - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - - STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size); - - void CopyBlock(UInt32 distance, UInt32 len) - { - _lzSize += len; - UInt32 pos = (_winPos - distance - 1) & kWindowMask; - Byte *window = _window; - UInt32 winPos = _winPos; - if (kWindowSize - winPos > len && kWindowSize - pos > len) - { - const Byte *src = window + pos; - Byte *dest = window + winPos; - _winPos += len; - do - *dest++ = *src++; - while(--len != 0); - return; - } - do - { - window[winPos] = window[pos]; - winPos = (winPos + 1) & kWindowMask; - pos = (pos + 1) & kWindowMask; - } - while(--len != 0); - _winPos = winPos; - } - - void PutByte(Byte b) - { - _window[_winPos] = b; - _winPos = (_winPos + 1) & kWindowMask; - _lzSize++; - } - - -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/Rar3Vm.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/Rar3Vm.cpp deleted file mode 100644 index 6aeabbccc..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/Rar3Vm.cpp +++ /dev/null @@ -1,1094 +0,0 @@ -// Rar3Vm.cpp -// According to unRAR license, this code may not be used to develop -// a program that creates RAR archives - -/* -Note: - Due to performance considerations Rar VM may set Flags C incorrectly - for some operands (SHL x, 0, ... ). - Check implementation of concrete VM command - to see if it sets flags right. -*/ - -#include "StdAfx.h" - -extern "C" -{ -#include "../../../C/7zCrc.h" -#include "../../../C/Alloc.h" -} - -#include "Rar3Vm.h" - -namespace NCompress { -namespace NRar3 { - -UInt32 CMemBitDecoder::ReadBits(int numBits) -{ - UInt32 res = 0; - for (;;) - { - Byte b = _bitPos < _bitSize ? _data[_bitPos >> 3] : 0; - int avail = (int)(8 - (_bitPos & 7)); - if (numBits <= avail) - { - _bitPos += numBits; - return res | (b >> (avail - numBits)) & ((1 << numBits) - 1); - } - numBits -= avail; - res |= (UInt32)(b & ((1 << avail) - 1)) << numBits; - _bitPos += avail; - } -} - -UInt32 CMemBitDecoder::ReadBit() { return ReadBits(1); } - -namespace NVm { - -static const UInt32 kStackRegIndex = kNumRegs - 1; - -static const UInt32 FLAG_C = 1; -static const UInt32 FLAG_Z = 2; -static const UInt32 FLAG_S = 0x80000000; - -static const Byte CF_OP0 = 0; -static const Byte CF_OP1 = 1; -static const Byte CF_OP2 = 2; -static const Byte CF_OPMASK = 3; -static const Byte CF_BYTEMODE = 4; -static const Byte CF_JUMP = 8; -static const Byte CF_PROC = 16; -static const Byte CF_USEFLAGS = 32; -static const Byte CF_CHFLAGS = 64; - -static Byte kCmdFlags[]= -{ - /* CMD_MOV */ CF_OP2 | CF_BYTEMODE, - /* CMD_CMP */ CF_OP2 | CF_BYTEMODE | CF_CHFLAGS, - /* CMD_ADD */ CF_OP2 | CF_BYTEMODE | CF_CHFLAGS, - /* CMD_SUB */ CF_OP2 | CF_BYTEMODE | CF_CHFLAGS, - /* CMD_JZ */ CF_OP1 | CF_JUMP | CF_USEFLAGS, - /* CMD_JNZ */ CF_OP1 | CF_JUMP | CF_USEFLAGS, - /* CMD_INC */ CF_OP1 | CF_BYTEMODE | CF_CHFLAGS, - /* CMD_DEC */ CF_OP1 | CF_BYTEMODE | CF_CHFLAGS, - /* CMD_JMP */ CF_OP1 | CF_JUMP, - /* CMD_XOR */ CF_OP2 | CF_BYTEMODE | CF_CHFLAGS, - /* CMD_AND */ CF_OP2 | CF_BYTEMODE | CF_CHFLAGS, - /* CMD_OR */ CF_OP2 | CF_BYTEMODE | CF_CHFLAGS, - /* CMD_TEST */ CF_OP2 | CF_BYTEMODE | CF_CHFLAGS, - /* CMD_JS */ CF_OP1 | CF_JUMP | CF_USEFLAGS, - /* CMD_JNS */ CF_OP1 | CF_JUMP | CF_USEFLAGS, - /* CMD_JB */ CF_OP1 | CF_JUMP | CF_USEFLAGS, - /* CMD_JBE */ CF_OP1 | CF_JUMP | CF_USEFLAGS, - /* CMD_JA */ CF_OP1 | CF_JUMP | CF_USEFLAGS, - /* CMD_JAE */ CF_OP1 | CF_JUMP | CF_USEFLAGS, - /* CMD_PUSH */ CF_OP1, - /* CMD_POP */ CF_OP1, - /* CMD_CALL */ CF_OP1 | CF_PROC, - /* CMD_RET */ CF_OP0 | CF_PROC, - /* CMD_NOT */ CF_OP1 | CF_BYTEMODE, - /* CMD_SHL */ CF_OP2 | CF_BYTEMODE | CF_CHFLAGS, - /* CMD_SHR */ CF_OP2 | CF_BYTEMODE | CF_CHFLAGS, - /* CMD_SAR */ CF_OP2 | CF_BYTEMODE | CF_CHFLAGS, - /* CMD_NEG */ CF_OP1 | CF_BYTEMODE | CF_CHFLAGS, - /* CMD_PUSHA */ CF_OP0, - /* CMD_POPA */ CF_OP0, - /* CMD_PUSHF */ CF_OP0 | CF_USEFLAGS, - /* CMD_POPF */ CF_OP0 | CF_CHFLAGS, - /* CMD_MOVZX */ CF_OP2, - /* CMD_MOVSX */ CF_OP2, - /* CMD_XCHG */ CF_OP2 | CF_BYTEMODE, - /* CMD_MUL */ CF_OP2 | CF_BYTEMODE, - /* CMD_DIV */ CF_OP2 | CF_BYTEMODE, - /* CMD_ADC */ CF_OP2 | CF_BYTEMODE | CF_USEFLAGS | CF_CHFLAGS , - /* CMD_SBB */ CF_OP2 | CF_BYTEMODE | CF_USEFLAGS | CF_CHFLAGS , - /* CMD_PRINT */ CF_OP0 -}; - -CVm::CVm(): Mem(NULL) {} - -bool CVm::Create() -{ - if (Mem == NULL) - Mem = (Byte *)::MyAlloc(kSpaceSize + 4); - return (Mem != NULL); -} - -CVm::~CVm() -{ - ::MyFree(Mem); -} - -// CVm::Execute can change CProgram object: it clears progarm if VM returns error. - -bool CVm::Execute(CProgram *prg, const CProgramInitState *initState, - CBlockRef &outBlockRef, CRecordVector &outGlobalData) -{ - memcpy(R, initState->InitR, sizeof(initState->InitR)); - R[kStackRegIndex] = kSpaceSize; - R[kNumRegs] = 0; - Flags = 0; - - UInt32 globalSize = MyMin((UInt32)initState->GlobalData.Size(), kGlobalSize); - if (globalSize != 0) - memcpy(Mem + kGlobalOffset, &initState->GlobalData[0], globalSize); - UInt32 staticSize = MyMin((UInt32)prg->StaticData.Size(), kGlobalSize - globalSize); - if (staticSize != 0) - memcpy(Mem + kGlobalOffset + globalSize, &prg->StaticData[0], staticSize); - - bool res = true; - #ifdef RARVM_STANDARD_FILTERS - if (prg->StandardFilterIndex >= 0) - ExecuteStandardFilter(prg->StandardFilterIndex); - else - #endif - { - res = ExecuteCode(prg); - if (!res) - prg->Commands[0].OpCode = CMD_RET; - } - UInt32 newBlockPos = GetFixedGlobalValue32(NGlobalOffset::kBlockPos) & kSpaceMask; - UInt32 newBlockSize = GetFixedGlobalValue32(NGlobalOffset::kBlockSize) & kSpaceMask; - if (newBlockPos + newBlockSize >= kSpaceSize) - newBlockPos = newBlockSize = 0; - outBlockRef.Offset = newBlockPos; - outBlockRef.Size = newBlockSize; - - outGlobalData.Clear(); - UInt32 dataSize = GetFixedGlobalValue32(NGlobalOffset::kGlobalMemOutSize); - dataSize = MyMin(dataSize, kGlobalSize - kFixedGlobalSize); - if (dataSize != 0) - { - dataSize += kFixedGlobalSize; - outGlobalData.Reserve(dataSize); - for (UInt32 i = 0; i < dataSize; i++) - outGlobalData.Add(Mem[kGlobalOffset + i]); - } - return res; -} - - -#define SET_IP(IP) \ - if ((IP) >= numCommands) return true; \ - if (--maxOpCount <= 0) return false; \ - cmd = commands + (IP); - -#define GET_FLAG_S_B(res) (((res) & 0x80) ? FLAG_S : 0) -#define SET_IP_OP1 { UInt32 val = GetOperand32(&cmd->Op1); SET_IP(val); } -#define FLAGS_UPDATE_SZ Flags = res == 0 ? FLAG_Z : res & FLAG_S -#define FLAGS_UPDATE_SZ_B Flags = (res & 0xFF) == 0 ? FLAG_Z : GET_FLAG_S_B(res) - -UInt32 CVm::GetOperand32(const COperand *op) const -{ - switch(op->Type) - { - case OP_TYPE_REG: return R[op->Data]; - case OP_TYPE_REGMEM: return GetValue32(&Mem[(op->Base + R[op->Data]) & kSpaceMask]); - default: return op->Data; - } -} - -void CVm::SetOperand32(const COperand *op, UInt32 val) -{ - switch(op->Type) - { - case OP_TYPE_REG: R[op->Data] = val; return; - case OP_TYPE_REGMEM: SetValue32(&Mem[(op->Base + R[op->Data]) & kSpaceMask], val); return; - } -} - -Byte CVm::GetOperand8(const COperand *op) const -{ - switch(op->Type) - { - case OP_TYPE_REG: return (Byte)R[op->Data]; - case OP_TYPE_REGMEM: return Mem[(op->Base + R[op->Data]) & kSpaceMask];; - default: return (Byte)op->Data; - } -} - -void CVm::SetOperand8(const COperand *op, Byte val) -{ - switch(op->Type) - { - case OP_TYPE_REG: R[op->Data] = (R[op->Data] & 0xFFFFFF00) | val; return; - case OP_TYPE_REGMEM: Mem[(op->Base + R[op->Data]) & kSpaceMask] = val; return; - } -} - -UInt32 CVm::GetOperand(bool byteMode, const COperand *op) const -{ - if (byteMode) - return GetOperand8(op); - return GetOperand32(op); -} - -void CVm::SetOperand(bool byteMode, const COperand *op, UInt32 val) -{ - if (byteMode) - SetOperand8(op, (Byte)(val & 0xFF)); - else - SetOperand32(op, val); -} - -bool CVm::ExecuteCode(const CProgram *prg) -{ - Int32 maxOpCount = 25000000; - const CCommand *commands = &prg->Commands[0]; - const CCommand *cmd = commands; - UInt32 numCommands = prg->Commands.Size(); - for (;;) - { - switch(cmd->OpCode) - { - #ifndef RARVM_NO_VM - - case CMD_MOV: - SetOperand32(&cmd->Op1, GetOperand32(&cmd->Op2)); - break; - case CMD_MOVB: - SetOperand8(&cmd->Op1, GetOperand8(&cmd->Op2)); - break; - case CMD_CMP: - { - UInt32 v1 = GetOperand32(&cmd->Op1); - UInt32 res = v1 - GetOperand32(&cmd->Op2); - Flags = res == 0 ? FLAG_Z : (res > v1) | (res & FLAG_S); - } - break; - case CMD_CMPB: - { - Byte v1 = GetOperand8(&cmd->Op1); - Byte res = v1 - GetOperand8(&cmd->Op2); - res &= 0xFF; - Flags = res == 0 ? FLAG_Z : (res > v1) | GET_FLAG_S_B(res); - } - break; - case CMD_ADD: - { - UInt32 v1 = GetOperand32(&cmd->Op1); - UInt32 res = v1 + GetOperand32(&cmd->Op2); - SetOperand32(&cmd->Op1, res); - Flags = (res < v1) | (res == 0 ? FLAG_Z : (res & FLAG_S)); - } - break; - case CMD_ADDB: - { - Byte v1 = GetOperand8(&cmd->Op1); - Byte res = v1 + GetOperand8(&cmd->Op2); - res &= 0xFF; - SetOperand8(&cmd->Op1, (Byte)res); - Flags = (res < v1) | (res == 0 ? FLAG_Z : GET_FLAG_S_B(res)); - } - break; - case CMD_ADC: - { - UInt32 v1 = GetOperand(cmd->ByteMode, &cmd->Op1); - UInt32 FC = (Flags & FLAG_C); - UInt32 res = v1 + GetOperand(cmd->ByteMode, &cmd->Op2) + FC; - if (cmd->ByteMode) - res &= 0xFF; - SetOperand(cmd->ByteMode, &cmd->Op1, res); - Flags = (res < v1 || res == v1 && FC) | (res == 0 ? FLAG_Z : (res & FLAG_S)); - } - break; - case CMD_SUB: - { - UInt32 v1 = GetOperand32(&cmd->Op1); - UInt32 res = v1 - GetOperand32(&cmd->Op2); - SetOperand32(&cmd->Op1, res); - Flags = res == 0 ? FLAG_Z : (res > v1) | (res & FLAG_S); - } - break; - case CMD_SUBB: - { - UInt32 v1 = GetOperand8(&cmd->Op1); - UInt32 res = v1 - GetOperand8(&cmd->Op2); - SetOperand8(&cmd->Op1, (Byte)res); - Flags = res == 0 ? FLAG_Z : (res > v1) | (res & FLAG_S); - } - break; - case CMD_SBB: - { - UInt32 v1 = GetOperand(cmd->ByteMode, &cmd->Op1); - UInt32 FC = (Flags & FLAG_C); - UInt32 res = v1 - GetOperand(cmd->ByteMode, &cmd->Op2) - FC; - // Flags = res == 0 ? FLAG_Z : (res > v1 || res == v1 && FC) | (res & FLAG_S); - if (cmd->ByteMode) - res &= 0xFF; - SetOperand(cmd->ByteMode, &cmd->Op1, res); - Flags = (res > v1 || res == v1 && FC) | (res == 0 ? FLAG_Z : (res & FLAG_S)); - } - break; - case CMD_INC: - { - UInt32 res = GetOperand32(&cmd->Op1) + 1; - SetOperand32(&cmd->Op1, res); - FLAGS_UPDATE_SZ; - } - break; - case CMD_INCB: - { - Byte res = GetOperand8(&cmd->Op1) + 1; - SetOperand8(&cmd->Op1, res);; - FLAGS_UPDATE_SZ_B; - } - break; - case CMD_DEC: - { - UInt32 res = GetOperand32(&cmd->Op1) - 1; - SetOperand32(&cmd->Op1, res); - FLAGS_UPDATE_SZ; - } - break; - case CMD_DECB: - { - Byte res = GetOperand8(&cmd->Op1) - 1; - SetOperand8(&cmd->Op1, res);; - FLAGS_UPDATE_SZ_B; - } - break; - case CMD_XOR: - { - UInt32 res = GetOperand32(&cmd->Op1) ^ GetOperand32(&cmd->Op2); - SetOperand32(&cmd->Op1, res); - FLAGS_UPDATE_SZ; - } - break; - case CMD_XORB: - { - Byte res = GetOperand8(&cmd->Op1) ^ GetOperand8(&cmd->Op2); - SetOperand8(&cmd->Op1, res); - FLAGS_UPDATE_SZ_B; - } - break; - case CMD_AND: - { - UInt32 res = GetOperand32(&cmd->Op1) & GetOperand32(&cmd->Op2); - SetOperand32(&cmd->Op1, res); - FLAGS_UPDATE_SZ; - } - break; - case CMD_ANDB: - { - Byte res = GetOperand8(&cmd->Op1) & GetOperand8(&cmd->Op2); - SetOperand8(&cmd->Op1, res); - FLAGS_UPDATE_SZ_B; - } - break; - case CMD_OR: - { - UInt32 res = GetOperand32(&cmd->Op1) | GetOperand32(&cmd->Op2); - SetOperand32(&cmd->Op1, res); - FLAGS_UPDATE_SZ; - } - break; - case CMD_ORB: - { - Byte res = GetOperand8(&cmd->Op1) | GetOperand8(&cmd->Op2); - SetOperand8(&cmd->Op1, res); - FLAGS_UPDATE_SZ_B; - } - break; - case CMD_TEST: - { - UInt32 res = GetOperand32(&cmd->Op1) & GetOperand32(&cmd->Op2); - FLAGS_UPDATE_SZ; - } - break; - case CMD_TESTB: - { - Byte res = GetOperand8(&cmd->Op1) & GetOperand8(&cmd->Op2); - FLAGS_UPDATE_SZ_B; - } - break; - case CMD_NOT: - SetOperand(cmd->ByteMode, &cmd->Op1, ~GetOperand(cmd->ByteMode, &cmd->Op1)); - break; - case CMD_NEG: - { - UInt32 res = 0 - GetOperand32(&cmd->Op1); - SetOperand32(&cmd->Op1, res); - Flags = res == 0 ? FLAG_Z : FLAG_C | (res & FLAG_S); - } - break; - case CMD_NEGB: - { - Byte res = (Byte)(0 - GetOperand8(&cmd->Op1)); - SetOperand8(&cmd->Op1, res); - Flags = res == 0 ? FLAG_Z : FLAG_C | GET_FLAG_S_B(res); - } - break; - - case CMD_SHL: - { - UInt32 v1 = GetOperand32(&cmd->Op1); - int v2 = (int)GetOperand32(&cmd->Op2); - UInt32 res = v1 << v2; - SetOperand32(&cmd->Op1, res); - Flags = (res == 0 ? FLAG_Z : (res & FLAG_S)) | ((v1 << (v2 - 1)) & 0x80000000 ? FLAG_C : 0); - } - break; - case CMD_SHLB: - { - Byte v1 = GetOperand8(&cmd->Op1); - int v2 = (int)GetOperand8(&cmd->Op2); - Byte res = (Byte)(v1 << v2); - SetOperand8(&cmd->Op1, res); - Flags = (res == 0 ? FLAG_Z : GET_FLAG_S_B(res)) | ((v1 << (v2 - 1)) & 0x80 ? FLAG_C : 0); - } - break; - case CMD_SHR: - { - UInt32 v1 = GetOperand32(&cmd->Op1); - int v2 = (int)GetOperand32(&cmd->Op2); - UInt32 res = v1 >> v2; - SetOperand32(&cmd->Op1, res); - Flags = (res == 0 ? FLAG_Z : (res & FLAG_S)) | ((v1 >> (v2 - 1)) & FLAG_C); - } - break; - case CMD_SHRB: - { - Byte v1 = GetOperand8(&cmd->Op1); - int v2 = (int)GetOperand8(&cmd->Op2); - Byte res = (Byte)(v1 >> v2); - SetOperand8(&cmd->Op1, res); - Flags = (res == 0 ? FLAG_Z : GET_FLAG_S_B(res)) | ((v1 >> (v2 - 1)) & FLAG_C); - } - break; - case CMD_SAR: - { - UInt32 v1 = GetOperand32(&cmd->Op1); - int v2 = (int)GetOperand32(&cmd->Op2); - UInt32 res = UInt32(((Int32)v1) >> v2); - SetOperand32(&cmd->Op1, res); - Flags= (res == 0 ? FLAG_Z : (res & FLAG_S)) | ((v1 >> (v2 - 1)) & FLAG_C); - } - break; - case CMD_SARB: - { - Byte v1 = GetOperand8(&cmd->Op1); - int v2 = (int)GetOperand8(&cmd->Op2); - Byte res = (Byte)(((signed char)v1) >> v2); - SetOperand8(&cmd->Op1, res); - Flags= (res == 0 ? FLAG_Z : GET_FLAG_S_B(res)) | ((v1 >> (v2 - 1)) & FLAG_C); - } - break; - - case CMD_JMP: - SET_IP_OP1; - continue; - case CMD_JZ: - if ((Flags & FLAG_Z) != 0) - { - SET_IP_OP1; - continue; - } - break; - case CMD_JNZ: - if ((Flags & FLAG_Z) == 0) - { - SET_IP_OP1; - continue; - } - break; - case CMD_JS: - if ((Flags & FLAG_S) != 0) - { - SET_IP_OP1; - continue; - } - break; - case CMD_JNS: - if ((Flags & FLAG_S) == 0) - { - SET_IP_OP1; - continue; - } - break; - case CMD_JB: - if ((Flags & FLAG_C) != 0) - { - SET_IP_OP1; - continue; - } - break; - case CMD_JBE: - if ((Flags & (FLAG_C | FLAG_Z)) != 0) - { - SET_IP_OP1; - continue; - } - break; - case CMD_JA: - if ((Flags & (FLAG_C | FLAG_Z)) == 0) - { - SET_IP_OP1; - continue; - } - break; - case CMD_JAE: - if ((Flags & FLAG_C) == 0) - { - SET_IP_OP1; - continue; - } - break; - - case CMD_PUSH: - R[kStackRegIndex] -= 4; - SetValue32(&Mem[R[kStackRegIndex] & kSpaceMask], GetOperand32(&cmd->Op1)); - break; - case CMD_POP: - SetOperand32(&cmd->Op1, GetValue32(&Mem[R[kStackRegIndex] & kSpaceMask])); - R[kStackRegIndex] += 4; - break; - case CMD_CALL: - R[kStackRegIndex] -= 4; - SetValue32(&Mem[R[kStackRegIndex] & kSpaceMask], (UInt32)(cmd - commands + 1)); - SET_IP_OP1; - continue; - - case CMD_PUSHA: - { - for (UInt32 i = 0, SP = R[kStackRegIndex] - 4; i < kNumRegs; i++, SP -= 4) - SetValue32(&Mem[SP & kSpaceMask], R[i]); - R[kStackRegIndex] -= kNumRegs * 4; - } - break; - case CMD_POPA: - { - for (UInt32 i = 0, SP = R[kStackRegIndex]; i < kNumRegs; i++, SP += 4) - R[kStackRegIndex - i] = GetValue32(&Mem[SP & kSpaceMask]); - } - break; - case CMD_PUSHF: - R[kStackRegIndex] -= 4; - SetValue32(&Mem[R[kStackRegIndex]&kSpaceMask], Flags); - break; - case CMD_POPF: - Flags = GetValue32(&Mem[R[kStackRegIndex] & kSpaceMask]); - R[kStackRegIndex] += 4; - break; - - case CMD_MOVZX: - SetOperand32(&cmd->Op1, GetOperand8(&cmd->Op2)); - break; - case CMD_MOVSX: - SetOperand32(&cmd->Op1, (UInt32)(Int32)(signed char)GetOperand8(&cmd->Op2)); - break; - case CMD_XCHG: - { - UInt32 v1 = GetOperand(cmd->ByteMode, &cmd->Op1); - SetOperand(cmd->ByteMode, &cmd->Op1, GetOperand(cmd->ByteMode, &cmd->Op2)); - SetOperand(cmd->ByteMode, &cmd->Op2, v1); - } - break; - case CMD_MUL: - { - UInt32 res = GetOperand32(&cmd->Op1) * GetOperand32(&cmd->Op2); - SetOperand32(&cmd->Op1, res); - } - break; - case CMD_MULB: - { - Byte res = GetOperand8(&cmd->Op1) * GetOperand8(&cmd->Op2); - SetOperand8(&cmd->Op1, res); - } - break; - case CMD_DIV: - { - UInt32 divider = GetOperand(cmd->ByteMode, &cmd->Op2); - if (divider != 0) - { - UInt32 res = GetOperand(cmd->ByteMode, &cmd->Op1) / divider; - SetOperand(cmd->ByteMode, &cmd->Op1, res); - } - } - break; - - #endif - - case CMD_RET: - { - if (R[kStackRegIndex] >= kSpaceSize) - return true; - UInt32 ip = GetValue32(&Mem[R[kStackRegIndex] & kSpaceMask]); - SET_IP(ip); - R[kStackRegIndex] += 4; - continue; - } - case CMD_PRINT: - break; - } - cmd++; - --maxOpCount; - } -} - - -////////////////////////////////////////////////////// -// Read program - -UInt32 ReadEncodedUInt32(CMemBitDecoder &inp) -{ - switch(inp.ReadBits(2)) - { - case 0: - return inp.ReadBits(4); - case 1: - { - UInt32 v = inp.ReadBits(4); - if (v == 0) - return 0xFFFFFF00 | inp.ReadBits(8); - else - return (v << 4) | inp.ReadBits(4); - } - case 2: - return inp.ReadBits(16); - default: - return inp.ReadBits(32); - } -} - -void CVm::DecodeArg(CMemBitDecoder &inp, COperand &op, bool byteMode) -{ - if (inp.ReadBit()) - { - op.Type = OP_TYPE_REG; - op.Data = inp.ReadBits(kNumRegBits); - } - else if (inp.ReadBit() == 0) - { - op.Type = OP_TYPE_INT; - if (byteMode) - op.Data = inp.ReadBits(8); - else - op.Data = ReadEncodedUInt32(inp); - } - else - { - op.Type = OP_TYPE_REGMEM; - if (inp.ReadBit() == 0) - { - op.Data = inp.ReadBits(kNumRegBits); - op.Base = 0; - } - else - { - if (inp.ReadBit() == 0) - op.Data = inp.ReadBits(kNumRegBits); - else - op.Data = kNumRegs; - op.Base = ReadEncodedUInt32(inp); - } - } -} - -void CVm::ReadVmProgram(const Byte *code, UInt32 codeSize, CProgram *prg) -{ - CMemBitDecoder inp; - inp.Init(code, codeSize); - - prg->StaticData.Clear(); - if (inp.ReadBit()) - { - UInt32 dataSize = ReadEncodedUInt32(inp) + 1; - for (UInt32 i = 0; inp.Avail() && i < dataSize; i++) - prg->StaticData.Add((Byte)inp.ReadBits(8)); - } - while (inp.Avail()) - { - prg->Commands.Add(CCommand()); - CCommand *cmd = &prg->Commands.Back(); - if (inp.ReadBit() == 0) - cmd->OpCode = (ECommand)inp.ReadBits(3); - else - cmd->OpCode = (ECommand)(8 + inp.ReadBits(5)); - if (kCmdFlags[cmd->OpCode] & CF_BYTEMODE) - cmd->ByteMode = (inp.ReadBit()) ? true : false; - else - cmd->ByteMode = 0; - int opNum = (kCmdFlags[cmd->OpCode] & CF_OPMASK); - if (opNum > 0) - { - DecodeArg(inp, cmd->Op1, cmd->ByteMode); - if (opNum == 2) - DecodeArg(inp, cmd->Op2, cmd->ByteMode); - else - { - if (cmd->Op1.Type == OP_TYPE_INT && (kCmdFlags[cmd->OpCode] & (CF_JUMP | CF_PROC))) - { - int Distance = cmd->Op1.Data; - if (Distance >= 256) - Distance -= 256; - else - { - if (Distance >= 136) - Distance -= 264; - else if (Distance >= 16) - Distance -= 8; - else if (Distance >= 8) - Distance -= 16; - Distance += prg->Commands.Size() - 1; - } - cmd->Op1.Data = Distance; - } - } - } - if (cmd->ByteMode) - { - switch (cmd->OpCode) - { - case CMD_MOV: cmd->OpCode = CMD_MOVB; break; - case CMD_CMP: cmd->OpCode = CMD_CMPB; break; - case CMD_ADD: cmd->OpCode = CMD_ADDB; break; - case CMD_SUB: cmd->OpCode = CMD_SUBB; break; - case CMD_INC: cmd->OpCode = CMD_INCB; break; - case CMD_DEC: cmd->OpCode = CMD_DECB; break; - case CMD_XOR: cmd->OpCode = CMD_XORB; break; - case CMD_AND: cmd->OpCode = CMD_ANDB; break; - case CMD_OR: cmd->OpCode = CMD_ORB; break; - case CMD_TEST: cmd->OpCode = CMD_TESTB; break; - case CMD_NEG: cmd->OpCode = CMD_NEGB; break; - case CMD_SHL: cmd->OpCode = CMD_SHLB; break; - case CMD_SHR: cmd->OpCode = CMD_SHRB; break; - case CMD_SAR: cmd->OpCode = CMD_SARB; break; - case CMD_MUL: cmd->OpCode = CMD_MULB; break; - } - } - } -} - -#ifdef RARVM_STANDARD_FILTERS - -enum EStandardFilter -{ - SF_E8, - SF_E8E9, - SF_ITANIUM, - SF_RGB, - SF_AUDIO, - SF_DELTA, - SF_UPCASE -}; - -struct StandardFilterSignature -{ - UInt32 Length; - UInt32 CRC; - EStandardFilter Type; -} -kStdFilters[]= -{ - 53, 0xad576887, SF_E8, - 57, 0x3cd7e57e, SF_E8E9, - 120, 0x3769893f, SF_ITANIUM, - 29, 0x0e06077d, SF_DELTA, - 149, 0x1c2c5dc8, SF_RGB, - 216, 0xbc85e701, SF_AUDIO, - 40, 0x46b9c560, SF_UPCASE -}; - -static int FindStandardFilter(const Byte *code, UInt32 codeSize) -{ - UInt32 crc = CrcCalc(code, codeSize); - for (int i = 0; i < sizeof(kStdFilters) / sizeof(kStdFilters[0]); i++) - { - StandardFilterSignature &sfs = kStdFilters[i]; - if (sfs.CRC == crc && sfs.Length == codeSize) - return i; - } - return -1; -} - -#endif - -void CVm::PrepareProgram(const Byte *code, UInt32 codeSize, CProgram *prg) -{ - Byte xorSum = 0; - for (UInt32 i = 1; i < codeSize; i++) - xorSum ^= code[i]; - - prg->Commands.Clear(); - #ifdef RARVM_STANDARD_FILTERS - prg->StandardFilterIndex = -1; - #endif - - if (xorSum == code[0] && codeSize > 0) - { - #ifdef RARVM_STANDARD_FILTERS - prg->StandardFilterIndex = FindStandardFilter(code, codeSize); - if (prg->StandardFilterIndex >= 0) - return; - #endif - // 1 byte for checksum - ReadVmProgram(code + 1, codeSize - 1, prg); - } - prg->Commands.Add(CCommand()); - CCommand *cmd = &prg->Commands.Back(); - cmd->OpCode = CMD_RET; -} - -void CVm::SetMemory(UInt32 pos, const Byte *data, UInt32 dataSize) -{ - if (pos < kSpaceSize && data != Mem + pos) - memmove(Mem + pos, data, MyMin(dataSize, kSpaceSize - pos)); -} - -#ifdef RARVM_STANDARD_FILTERS - -static void E8E9Decode(Byte *data, UInt32 dataSize, UInt32 fileOffset, bool e9) -{ - if (dataSize <= 4) - return; - dataSize -= 4; - const UInt32 kFileSize = 0x1000000; - Byte cmpByte2 = (e9 ? 0xE9 : 0xE8); - for (UInt32 curPos = 0; curPos < dataSize;) - { - Byte curByte = *(data++); - curPos++; - if (curByte == 0xE8 || curByte == cmpByte2) - { - UInt32 offset = curPos + fileOffset; - UInt32 addr = (Int32)GetValue32(data); - if (addr < kFileSize) - SetValue32(data, addr - offset); - else if ((Int32)addr < 0 && (Int32)(addr + offset) >= 0) - SetValue32(data, addr + kFileSize); - data += 4; - curPos += 4; - } - } -} - -static inline UInt32 ItaniumGetOpType(const Byte *data, int bitPos) -{ - return (data[(unsigned int)bitPos >> 3] >> (bitPos & 7)) & 0xF; -} - - -static void ItaniumDecode(Byte *data, UInt32 dataSize, UInt32 fileOffset) -{ - UInt32 curPos = 0; - fileOffset >>= 4; - while (curPos < dataSize - 21) - { - int b = (data[0] & 0x1F) - 0x10; - if (b >= 0) - { - static Byte kCmdMasks[16] = {4,4,6,6,0,0,7,7,4,4,0,0,4,4,0,0}; - Byte cmdMask = kCmdMasks[b]; - if (cmdMask != 0) - for (int i = 0; i < 3; i++) - if (cmdMask & (1 << i)) - { - int startPos = i * 41 + 18; - if (ItaniumGetOpType(data, startPos + 24) == 5) - { - const UInt32 kMask = 0xFFFFF; - Byte *p = data + ((unsigned int)startPos >> 3); - UInt32 bitField = ((UInt32)p[0]) | ((UInt32)p[1] << 8) | ((UInt32)p[2] << 16); - int inBit = (startPos & 7); - UInt32 offset = (bitField >> inBit) & kMask; - UInt32 andMask = ~(kMask << inBit); - bitField = ((offset - fileOffset) & kMask) << inBit; - for (int j = 0; j < 3; j++) - { - p[j] &= andMask; - p[j] |= bitField; - andMask >>= 8; - bitField >>= 8; - } - } - } - } - data += 16; - curPos += 16; - fileOffset++; - } -} - -static void DeltaDecode(Byte *data, UInt32 dataSize, UInt32 numChannels) -{ - UInt32 srcPos = 0; - UInt32 border = dataSize * 2; - for (UInt32 curChannel = 0; curChannel < numChannels; curChannel++) - { - Byte prevByte = 0; - for (UInt32 destPos = dataSize + curChannel; destPos < border; destPos += numChannels) - data[destPos] = (prevByte = prevByte - data[srcPos++]); - } -} - -static void RgbDecode(Byte *srcData, UInt32 dataSize, UInt32 width, UInt32 posR) -{ - Byte *destData = srcData + dataSize; - const UInt32 numChannels = 3; - for (UInt32 curChannel = 0; curChannel < numChannels; curChannel++) - { - Byte prevByte = 0; - - for (UInt32 i = curChannel; i < dataSize; i+= numChannels) - { - unsigned int predicted; - if (i < width) - predicted = prevByte; - else - { - unsigned int upperLeftByte = destData[i - width]; - unsigned int upperByte = destData[i - width + 3]; - predicted = prevByte + upperByte - upperLeftByte; - int pa = abs((int)(predicted - prevByte)); - int pb = abs((int)(predicted - upperByte)); - int pc = abs((int)(predicted - upperLeftByte)); - if (pa <= pb && pa <= pc) - predicted = prevByte; - else - if (pb <= pc) - predicted = upperByte; - else - predicted = upperLeftByte; - } - destData[i] = prevByte = (Byte)(predicted - *(srcData++)); - } - } - if (dataSize < 3) - return; - for (UInt32 i = posR, border = dataSize - 2; i < border; i += 3) - { - Byte g = destData[i + 1]; - destData[i] = destData[i] + g; - destData[i + 2] = destData[i + 2] + g; - } -} - -static void AudioDecode(Byte *srcData, UInt32 dataSize, UInt32 numChannels) -{ - Byte *destData = srcData + dataSize; - for (UInt32 curChannel = 0; curChannel < numChannels; curChannel++) - { - UInt32 prevByte = 0, prevDelta = 0, dif[7]; - Int32 D1 = 0, D2 = 0, D3; - Int32 K1 = 0, K2 = 0, K3 = 0; - memset(dif, 0, sizeof(dif)); - - for (UInt32 i = curChannel, byteCount = 0; i < dataSize; i += numChannels, byteCount++) - { - D3 = D2; - D2 = prevDelta - D1; - D1 = prevDelta; - - UInt32 predicted = 8 * prevByte + K1 * D1 + K2 * D2 + K3 * D3; - predicted = (predicted >> 3) & 0xFF; - - UInt32 curByte = *(srcData++); - - predicted -= curByte; - destData[i] = (Byte)predicted; - prevDelta = (UInt32)(Int32)(signed char)(predicted - prevByte); - prevByte = predicted; - - Int32 D = ((Int32)(signed char)curByte) << 3; - - dif[0] += abs(D); - dif[1] += abs(D - D1); - dif[2] += abs(D + D1); - dif[3] += abs(D - D2); - dif[4] += abs(D + D2); - dif[5] += abs(D - D3); - dif[6] += abs(D + D3); - - if ((byteCount & 0x1F) == 0) - { - UInt32 minDif = dif[0], numMinDif = 0; - dif[0] = 0; - for (int j = 1; j < sizeof(dif) / sizeof(dif[0]); j++) - { - if (dif[j] < minDif) - { - minDif = dif[j]; - numMinDif = j; - } - dif[j] = 0; - } - switch (numMinDif) - { - case 1: if (K1 >= -16) K1--; break; - case 2: if (K1 < 16) K1++; break; - case 3: if (K2 >= -16) K2--; break; - case 4: if (K2 < 16) K2++; break; - case 5: if (K3 >= -16) K3--; break; - case 6: if (K3 < 16) K3++; break; - } - } - } - } -} - -static UInt32 UpCaseDecode(Byte *data, UInt32 dataSize) -{ - UInt32 srcPos = 0, destPos = dataSize; - while (srcPos < dataSize) - { - Byte curByte = data[srcPos++]; - if (curByte == 2 && (curByte = data[srcPos++]) != 2) - curByte -= 32; - data[destPos++] = curByte; - } - return destPos - dataSize; -} - -void CVm::ExecuteStandardFilter(int filterIndex) -{ - UInt32 dataSize = R[4]; - if (dataSize >= kGlobalOffset) - return; - EStandardFilter filterType = kStdFilters[filterIndex].Type; - - switch (filterType) - { - case SF_E8: - case SF_E8E9: - E8E9Decode(Mem, dataSize, R[6], (filterType == SF_E8E9)); - break; - case SF_ITANIUM: - ItaniumDecode(Mem, dataSize, R[6]); - break; - case SF_DELTA: - if (dataSize >= kGlobalOffset / 2) - break; - SetBlockPos(dataSize); - DeltaDecode(Mem, dataSize, R[0]); - break; - case SF_RGB: - if (dataSize >= kGlobalOffset / 2) - break; - { - UInt32 width = R[0]; - if (width <= 3) - break; - SetBlockPos(dataSize); - RgbDecode(Mem, dataSize, width, R[1]); - } - break; - case SF_AUDIO: - if (dataSize >= kGlobalOffset / 2) - break; - SetBlockPos(dataSize); - AudioDecode(Mem, dataSize, R[0]); - break; - case SF_UPCASE: - if (dataSize >= kGlobalOffset / 2) - break; - UInt32 destSize = UpCaseDecode(Mem, dataSize); - SetBlockSize(destSize); - SetBlockPos(dataSize); - break; - } -} - -#endif - -}}} diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/Rar3Vm.h b/desmume/src/windows/7z/CPP/7zip/Compress/Rar3Vm.h deleted file mode 100644 index 0d16e42cc..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/Rar3Vm.h +++ /dev/null @@ -1,179 +0,0 @@ -// Rar3Vm.h -// According to unRAR license, this code may not be used to develop -// a program that creates RAR archives - -#ifndef __COMPRESS_RAR3_VM_H -#define __COMPRESS_RAR3_VM_H - -#include "../../../C/CpuArch.h" - -#include "Common/MyVector.h" -#include "Common/Types.h" - -#define RARVM_STANDARD_FILTERS - -namespace NCompress { -namespace NRar3 { - -class CMemBitDecoder -{ - const Byte *_data; - UInt32 _bitSize; - UInt32 _bitPos; -public: - void Init(const Byte *data, UInt32 byteSize) - { - _data = data; - _bitSize = (byteSize << 3); - _bitPos = 0; - } - UInt32 ReadBits(int numBits); - UInt32 ReadBit(); - bool Avail() const { return (_bitPos < _bitSize); } -}; - -namespace NVm { - -inline UInt32 GetValue32(const void *addr) { return GetUi32(addr); } -inline void SetValue32(void *addr, UInt32 value) { SetUi32(addr, value); } - -UInt32 ReadEncodedUInt32(CMemBitDecoder &inp); - -const int kNumRegBits = 3; -const UInt32 kNumRegs = 1 << kNumRegBits; -const UInt32 kNumGpRegs = kNumRegs - 1; - -const UInt32 kSpaceSize = 0x40000; -const UInt32 kSpaceMask = kSpaceSize -1; -const UInt32 kGlobalOffset = 0x3C000; -const UInt32 kGlobalSize = 0x2000; -const UInt32 kFixedGlobalSize = 64; - -namespace NGlobalOffset -{ - const UInt32 kBlockSize = 0x1C; - const UInt32 kBlockPos = 0x20; - const UInt32 kExecCount = 0x2C; - const UInt32 kGlobalMemOutSize = 0x30; -} - -enum ECommand -{ - CMD_MOV, CMD_CMP, CMD_ADD, CMD_SUB, CMD_JZ, CMD_JNZ, CMD_INC, CMD_DEC, - CMD_JMP, CMD_XOR, CMD_AND, CMD_OR, CMD_TEST, CMD_JS, CMD_JNS, CMD_JB, - CMD_JBE, CMD_JA, CMD_JAE, CMD_PUSH, CMD_POP, CMD_CALL, CMD_RET, CMD_NOT, - CMD_SHL, CMD_SHR, CMD_SAR, CMD_NEG, CMD_PUSHA,CMD_POPA, CMD_PUSHF,CMD_POPF, - CMD_MOVZX,CMD_MOVSX,CMD_XCHG, CMD_MUL, CMD_DIV, CMD_ADC, CMD_SBB, CMD_PRINT, - - CMD_MOVB, CMD_CMPB, CMD_ADDB, CMD_SUBB, CMD_INCB, CMD_DECB, - CMD_XORB, CMD_ANDB, CMD_ORB, CMD_TESTB,CMD_NEGB, - CMD_SHLB, CMD_SHRB, CMD_SARB, CMD_MULB -}; - -enum EOpType {OP_TYPE_REG, OP_TYPE_INT, OP_TYPE_REGMEM, OP_TYPE_NONE}; - -// Addr in COperand object can link (point) to CVm object!!! - -struct COperand -{ - EOpType Type; - UInt32 Data; - UInt32 Base; - COperand(): Type(OP_TYPE_NONE), Data(0), Base(0) {} -}; - -struct CCommand -{ - ECommand OpCode; - bool ByteMode; - COperand Op1, Op2; -}; - -struct CBlockRef -{ - UInt32 Offset; - UInt32 Size; -}; - -struct CProgram -{ - CRecordVector Commands; - #ifdef RARVM_STANDARD_FILTERS - int StandardFilterIndex; - #endif - CRecordVector StaticData; -}; - -struct CProgramInitState -{ - UInt32 InitR[kNumGpRegs]; - CRecordVector GlobalData; - - void AllocateEmptyFixedGlobal() - { - GlobalData.Clear(); - GlobalData.Reserve(NVm::kFixedGlobalSize); - for (UInt32 i = 0; i < NVm::kFixedGlobalSize; i++) - GlobalData.Add(0); - } -}; - -class CVm -{ - static UInt32 GetValue(bool byteMode, const void *addr) - { - if (byteMode) - return(*(const Byte *)addr); - else - return GetUi32(addr); - } - - static void SetValue(bool byteMode, void *addr, UInt32 value) - { - if (byteMode) - *(Byte *)addr = (Byte)value; - else - SetUi32(addr, value); - } - - UInt32 GetFixedGlobalValue32(UInt32 globalOffset) { return GetValue(false, &Mem[kGlobalOffset + globalOffset]); } - - void SetBlockSize(UInt32 v) { SetValue(&Mem[kGlobalOffset + NGlobalOffset::kBlockSize], v); } - void SetBlockPos(UInt32 v) { SetValue(&Mem[kGlobalOffset + NGlobalOffset::kBlockPos], v); } -public: - static void SetValue(void *addr, UInt32 value) { SetValue(false, addr, value); } -private: - UInt32 GetOperand32(const COperand *op) const; - void SetOperand32(const COperand *op, UInt32 val); - Byte GetOperand8(const COperand *op) const; - void SetOperand8(const COperand *op, Byte val); - UInt32 GetOperand(bool byteMode, const COperand *op) const; - void SetOperand(bool byteMode, const COperand *op, UInt32 val); - - void DecodeArg(CMemBitDecoder &inp, COperand &op, bool byteMode); - - bool ExecuteCode(const CProgram *prg); - - #ifdef RARVM_STANDARD_FILTERS - void ExecuteStandardFilter(int filterIndex); - #endif - - Byte *Mem; - UInt32 R[kNumRegs + 1]; // R[kNumRegs] = 0 always (speed optimization) - UInt32 Flags; - void ReadVmProgram(const Byte *code, UInt32 codeSize, CProgram *prg); -public: - CVm(); - ~CVm(); - bool Create(); - void PrepareProgram(const Byte *code, UInt32 codeSize, CProgram *prg); - void SetMemory(UInt32 pos, const Byte *data, UInt32 dataSize); - bool Execute(CProgram *prg, const CProgramInitState *initState, - CBlockRef &outBlockRef, CRecordVector &outGlobalData); - const Byte *GetDataPointer(UInt32 offset) const { return Mem + offset; } - -}; - -#endif - -}}} diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/RarCodecsRegister.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/RarCodecsRegister.cpp deleted file mode 100644 index cb6242b3d..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/RarCodecsRegister.cpp +++ /dev/null @@ -1,26 +0,0 @@ -// RarCodecsRegister.cpp - -#include "StdAfx.h" - -#include "../Common/RegisterCodec.h" - -#include "Rar1Decoder.h" -#include "Rar2Decoder.h" -#include "Rar3Decoder.h" - -#define CREATE_CODEC(x) static void *CreateCodec ## x() { return (void *)(ICompressCoder *)(new NCompress::NRar ## x::CDecoder); } - -CREATE_CODEC(1) -CREATE_CODEC(2) -CREATE_CODEC(3) - -#define RAR_CODEC(x, name) { CreateCodec ## x, 0, 0x040300 + x, L"Rar" name, 1, false } - -static CCodecInfo g_CodecsInfo[] = -{ - RAR_CODEC(1, L"1"), - RAR_CODEC(2, L"2"), - RAR_CODEC(3, L"3"), -}; - -REGISTER_CODECS(Rar) diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/ShrinkDecoder.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/ShrinkDecoder.cpp deleted file mode 100644 index 2146fa733..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/ShrinkDecoder.cpp +++ /dev/null @@ -1,148 +0,0 @@ -// ShrinkDecoder.cpp - -#include "StdAfx.h" - -extern "C" -{ -#include "../../../C/Alloc.h" -} - -#include "../Common/InBuffer.h" -#include "../Common/OutBuffer.h" - -#include "BitlDecoder.h" -#include "ShrinkDecoder.h" - -namespace NCompress { -namespace NShrink { - -static const UInt32 kBufferSize = (1 << 20); -static const int kNumMinBits = 9; - -HRESULT CDecoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 * /* inSize */, const UInt64 * /* outSize */, ICompressProgressInfo *progress) -{ - NBitl::CBaseDecoder inBuffer; - COutBuffer outBuffer; - - if (!inBuffer.Create(kBufferSize)) - return E_OUTOFMEMORY; - inBuffer.SetStream(inStream); - inBuffer.Init(); - - if (!outBuffer.Create(kBufferSize)) - return E_OUTOFMEMORY; - outBuffer.SetStream(outStream); - outBuffer.Init(); - - UInt64 prevPos = 0; - int numBits = kNumMinBits; - UInt32 head = 257; - bool needPrev = false; - UInt32 lastSymbol = 0; - - int i; - for (i = 0; i < kNumItems; i++) - _parents[i] = 0; - for (i = 0; i < kNumItems; i++) - _suffixes[i] = 0; - for (i = 0; i < 257; i++) - _isFree[i] = false; - for (; i < kNumItems; i++) - _isFree[i] = true; - - for (;;) - { - UInt32 symbol = inBuffer.ReadBits(numBits); - if (inBuffer.ExtraBitsWereRead()) - break; - if (_isFree[symbol]) - return S_FALSE; - if (symbol == 256) - { - UInt32 symbol = inBuffer.ReadBits(numBits); - if (symbol == 1) - { - if (numBits < kNumMaxBits) - numBits++; - } - else if (symbol == 2) - { - if (needPrev) - _isFree[head - 1] = true; - for (i = 257; i < kNumItems; i++) - _isParent[i] = false; - for (i = 257; i < kNumItems; i++) - if (!_isFree[i]) - _isParent[_parents[i]] = true; - for (i = 257; i < kNumItems; i++) - if (!_isParent[i]) - _isFree[i] = true; - head = 257; - while (head < kNumItems && !_isFree[head]) - head++; - if (head < kNumItems) - { - needPrev = true; - _isFree[head] = false; - _parents[head] = (UInt16)lastSymbol; - head++; - } - } - else - return S_FALSE; - continue; - } - UInt32 cur = symbol; - i = 0; - int corectionIndex = -1; - while (cur >= 256) - { - if (cur == head - 1) - corectionIndex = i; - _stack[i++] = _suffixes[cur]; - cur = _parents[cur]; - } - _stack[i++] = (Byte)cur; - if (needPrev) - { - _suffixes[head - 1] = (Byte)cur; - if (corectionIndex >= 0) - _stack[corectionIndex] = (Byte)cur; - } - while (i > 0) - outBuffer.WriteByte((_stack[--i])); - while (head < kNumItems && !_isFree[head]) - head++; - if (head < kNumItems) - { - needPrev = true; - _isFree[head] = false; - _parents[head] = (UInt16)symbol; - head++; - } - else - needPrev = false; - lastSymbol = symbol; - - UInt64 nowPos = outBuffer.GetProcessedSize(); - if (progress != NULL && nowPos - prevPos > (1 << 18)) - { - prevPos = nowPos; - UInt64 packSize = inBuffer.GetProcessedSize(); - RINOK(progress->SetRatioInfo(&packSize, &nowPos)); - } - } - return outBuffer.Flush(); -} - -STDMETHODIMP CDecoder ::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) -{ - try { return CodeReal(inStream, outStream, inSize, outSize, progress); } - catch(const CInBufferException &e) { return e.ErrorCode; } - catch(const COutBufferException &e) { return e.ErrorCode; } - catch(...) { return S_FALSE; } -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/ShrinkDecoder.h b/desmume/src/windows/7z/CPP/7zip/Compress/ShrinkDecoder.h deleted file mode 100644 index 00f416402..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/ShrinkDecoder.h +++ /dev/null @@ -1,38 +0,0 @@ -// ShrinkDecoder.h - -#ifndef __COMPRESS_SHRINK_DECODER_H -#define __COMPRESS_SHRINK_DECODER_H - -#include "../../Common/MyCom.h" - -#include "../ICoder.h" - -namespace NCompress { -namespace NShrink { - -const int kNumMaxBits = 13; -const UInt32 kNumItems = 1 << kNumMaxBits; - -class CDecoder : - public ICompressCoder, - public CMyUnknownImp -{ - UInt16 _parents[kNumItems]; - Byte _suffixes[kNumItems]; - Byte _stack[kNumItems]; - bool _isFree[kNumItems]; - bool _isParent[kNumItems]; - -public: - MY_UNKNOWN_IMP - - HRESULT CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/StdAfx.h b/desmume/src/windows/7z/CPP/7zip/Compress/StdAfx.h deleted file mode 100644 index c28ffcea7..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/StdAfx.h +++ /dev/null @@ -1,8 +0,0 @@ -// StdAfx.h - -#ifndef __STDAFX_H -#define __STDAFX_H - -#include "../../Common/MyWindows.h" - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/ZlibDecoder.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/ZlibDecoder.cpp deleted file mode 100644 index 505f21798..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/ZlibDecoder.cpp +++ /dev/null @@ -1,94 +0,0 @@ -// ZlibDecoder.cpp - -#include "StdAfx.h" - -#include "../Common/StreamUtils.h" - -#include "DeflateDecoder.h" -#include "ZlibDecoder.h" - -namespace NCompress { -namespace NZlib { - -#define DEFLATE_TRY_BEGIN try { -#define DEFLATE_TRY_END } \ - catch(...) { return S_FALSE; } - -#define ADLER_MOD 65521 -#define ADLER_LOOP_MAX 5550 - -static UInt32 Adler32_Update(UInt32 adler, const Byte *buf, size_t size) -{ - UInt32 a = adler & 0xFFFF; - UInt32 b = (adler >> 16) & 0xFFFF; - while (size > 0) - { - unsigned curSize = (size > ADLER_LOOP_MAX) ? ADLER_LOOP_MAX : (unsigned )size; - unsigned i; - for (i = 0; i < curSize; i++) - { - a += buf[i]; - b += a; - } - buf += curSize; - size -= curSize; - a %= ADLER_MOD; - b %= ADLER_MOD; - } - return (b << 16) + a; -} - -STDMETHODIMP COutStreamWithAdler::Write(const void *data, UInt32 size, UInt32 *processedSize) -{ - HRESULT result = _stream->Write(data, size, &size); - _adler = Adler32_Update(_adler, (const Byte *)data, size); - if (processedSize != NULL) - *processedSize = size; - return result; -} - -STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) -{ - DEFLATE_TRY_BEGIN - if (!AdlerStream) - { - AdlerSpec = new COutStreamWithAdler; - AdlerStream = AdlerSpec; - } - if (!DeflateDecoder) - { - DeflateDecoderSpec = new NCompress::NDeflate::NDecoder::CCOMCoder; - DeflateDecoderSpec->ZlibMode = true; - DeflateDecoder = DeflateDecoderSpec; - } - - Byte buf[2]; - RINOK(ReadStream_FALSE(inStream, buf, 2)); - int method = buf[0] & 0xF; - if (method != 8) - return S_FALSE; - // int dicSize = buf[0] >> 4; - if ((((UInt32)buf[0] << 8) + buf[1]) % 31 != 0) - return S_FALSE; - if ((buf[1] & 0x20) != 0) // dictPresent - return S_FALSE; - // int level = (buf[1] >> 6); - - AdlerSpec->SetStream(outStream); - AdlerSpec->Init(); - HRESULT res = DeflateDecoder->Code(inStream, AdlerStream, inSize, outSize, progress); - AdlerSpec->ReleaseStream(); - - if (res == S_OK) - { - const Byte *p = DeflateDecoderSpec->ZlibFooter; - UInt32 adler = ((UInt32)p[0] << 24) | ((UInt32)p[1] << 16) | ((UInt32)p[2] << 8) | p[3]; - if (adler != AdlerSpec->GetAdler()) - return S_FALSE; - } - return res; - DEFLATE_TRY_END -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/ZlibDecoder.h b/desmume/src/windows/7z/CPP/7zip/Compress/ZlibDecoder.h deleted file mode 100644 index a7ec07328..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/ZlibDecoder.h +++ /dev/null @@ -1,46 +0,0 @@ -// ZlibDecoder.h - -#ifndef __ZLIB_DECODER_H -#define __ZLIB_DECODER_H - -#include "DeflateDecoder.h" - -namespace NCompress { -namespace NZlib { - -const UInt32 ADLER_INIT_VAL = 1; - -class COutStreamWithAdler: - public ISequentialOutStream, - public CMyUnknownImp -{ - CMyComPtr _stream; - UInt32 _adler; -public: - MY_UNKNOWN_IMP - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); - void SetStream(ISequentialOutStream *stream) { _stream = stream; } - void ReleaseStream() { _stream.Release(); } - void Init() { _adler = ADLER_INIT_VAL; } - UInt32 GetAdler() const { return _adler; } -}; - -class CDecoder: - public ICompressCoder, - public CMyUnknownImp -{ - COutStreamWithAdler *AdlerSpec; - CMyComPtr AdlerStream; - - NCompress::NDeflate::NDecoder::CCOMCoder *DeflateDecoderSpec; - CMyComPtr DeflateDecoder; -public: - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - - MY_UNKNOWN_IMP -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Crypto/7zAes.cpp b/desmume/src/windows/7z/CPP/7zip/Crypto/7zAes.cpp deleted file mode 100644 index b5b5b4b43..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Crypto/7zAes.cpp +++ /dev/null @@ -1,245 +0,0 @@ -// 7zAes.cpp - -#include "StdAfx.h" - -extern "C" -{ -#include "../../../C/Sha256.h" -} - -#include "Windows/Synchronization.h" -#include "../Common/StreamObjects.h" -#include "../Common/StreamUtils.h" -#include "7zAes.h" -#include "MyAes.h" - -#ifndef EXTRACT_ONLY -#include "RandGen.h" -#endif - -using namespace NWindows; - -namespace NCrypto { -namespace NSevenZ { - -bool CKeyInfo::IsEqualTo(const CKeyInfo &a) const -{ - if (SaltSize != a.SaltSize || NumCyclesPower != a.NumCyclesPower) - return false; - for (UInt32 i = 0; i < SaltSize; i++) - if (Salt[i] != a.Salt[i]) - return false; - return (Password == a.Password); -} - -void CKeyInfo::CalculateDigest() -{ - if (NumCyclesPower == 0x3F) - { - UInt32 pos; - for (pos = 0; pos < SaltSize; pos++) - Key[pos] = Salt[pos]; - for (UInt32 i = 0; i < Password.GetCapacity() && pos < kKeySize; i++) - Key[pos++] = Password[i]; - for (; pos < kKeySize; pos++) - Key[pos] = 0; - } - else - { - CSha256 sha; - Sha256_Init(&sha); - const UInt64 numRounds = UInt64(1) << (NumCyclesPower); - Byte temp[8] = { 0,0,0,0,0,0,0,0 }; - for (UInt64 round = 0; round < numRounds; round++) - { - Sha256_Update(&sha, Salt, (size_t)SaltSize); - Sha256_Update(&sha, Password, Password.GetCapacity()); - Sha256_Update(&sha, temp, 8); - for (int i = 0; i < 8; i++) - if (++(temp[i]) != 0) - break; - } - Sha256_Final(&sha, Key); - } -} - -bool CKeyInfoCache::Find(CKeyInfo &key) -{ - for (int i = 0; i < Keys.Size(); i++) - { - const CKeyInfo &cached = Keys[i]; - if (key.IsEqualTo(cached)) - { - for (int j = 0; j < kKeySize; j++) - key.Key[j] = cached.Key[j]; - if (i != 0) - { - Keys.Insert(0, cached); - Keys.Delete(i+1); - } - return true; - } - } - return false; -} - -void CKeyInfoCache::Add(CKeyInfo &key) -{ - if (Find(key)) - return; - if (Keys.Size() >= Size) - Keys.DeleteBack(); - Keys.Insert(0, key); -} - -static CKeyInfoCache g_GlobalKeyCache(32); -static NSynchronization::CCriticalSection g_GlobalKeyCacheCriticalSection; - -CBase::CBase(): - _cachedKeys(16), - _ivSize(0) -{ - for (int i = 0; i < sizeof(_iv); i++) - _iv[i] = 0; -} - -void CBase::CalculateDigest() -{ - NSynchronization::CCriticalSectionLock lock(g_GlobalKeyCacheCriticalSection); - if (_cachedKeys.Find(_key)) - g_GlobalKeyCache.Add(_key); - else - { - if (!g_GlobalKeyCache.Find(_key)) - { - _key.CalculateDigest(); - g_GlobalKeyCache.Add(_key); - } - _cachedKeys.Add(_key); - } -} - -#ifndef EXTRACT_ONLY - -/* -STDMETHODIMP CEncoder::ResetSalt() -{ - _key.SaltSize = 4; - g_RandomGenerator.Generate(_key.Salt, _key.SaltSize); - return S_OK; -} -*/ - -STDMETHODIMP CEncoder::ResetInitVector() -{ - _ivSize = 8; - g_RandomGenerator.Generate(_iv, (unsigned)_ivSize); - return S_OK; -} - -STDMETHODIMP CEncoder::WriteCoderProperties(ISequentialOutStream *outStream) -{ - // _key.Init(); - for (UInt32 i = _ivSize; i < sizeof(_iv); i++) - _iv[i] = 0; - - UInt32 ivSize = _ivSize; - - // _key.NumCyclesPower = 0x3F; - _key.NumCyclesPower = 19; - - Byte firstByte = (Byte)(_key.NumCyclesPower | - (((_key.SaltSize == 0) ? 0 : 1) << 7) | - (((ivSize == 0) ? 0 : 1) << 6)); - RINOK(outStream->Write(&firstByte, 1, NULL)); - if (_key.SaltSize == 0 && ivSize == 0) - return S_OK; - Byte saltSizeSpec = (Byte)((_key.SaltSize == 0) ? 0 : (_key.SaltSize - 1)); - Byte ivSizeSpec = (Byte)((ivSize == 0) ? 0 : (ivSize - 1)); - Byte secondByte = (Byte)(((saltSizeSpec) << 4) | ivSizeSpec); - RINOK(outStream->Write(&secondByte, 1, NULL)); - if (_key.SaltSize > 0) - { - RINOK(WriteStream(outStream, _key.Salt, _key.SaltSize)); - } - if (ivSize > 0) - { - RINOK(WriteStream(outStream, _iv, ivSize)); - } - return S_OK; -} - -HRESULT CEncoder::CreateFilter() -{ - _aesFilter = new CAesCbcEncoder; - return S_OK; -} - -#endif - -STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte *data, UInt32 size) -{ - _key.Init(); - UInt32 i; - for (i = 0; i < sizeof(_iv); i++) - _iv[i] = 0; - if (size == 0) - return S_OK; - UInt32 pos = 0; - Byte firstByte = data[pos++]; - - _key.NumCyclesPower = firstByte & 0x3F; - if ((firstByte & 0xC0) == 0) - return S_OK; - _key.SaltSize = (firstByte >> 7) & 1; - UInt32 ivSize = (firstByte >> 6) & 1; - - if (pos >= size) - return E_INVALIDARG; - Byte secondByte = data[pos++]; - - _key.SaltSize += (secondByte >> 4); - ivSize += (secondByte & 0x0F); - - if (pos + _key.SaltSize + ivSize > size) - return E_INVALIDARG; - for (i = 0; i < _key.SaltSize; i++) - _key.Salt[i] = data[pos++]; - for (i = 0; i < ivSize; i++) - _iv[i] = data[pos++]; - return S_OK; -} - -STDMETHODIMP CBaseCoder::CryptoSetPassword(const Byte *data, UInt32 size) -{ - _key.Password.SetCapacity((size_t)size); - memcpy(_key.Password, data, (size_t)size); - return S_OK; -} - -STDMETHODIMP CBaseCoder::Init() -{ - CalculateDigest(); - if (_aesFilter == 0) - { - RINOK(CreateFilter()); - } - CMyComPtr cp; - RINOK(_aesFilter.QueryInterface(IID_ICryptoProperties, &cp)); - RINOK(cp->SetKey(_key.Key, sizeof(_key.Key))); - RINOK(cp->SetInitVector(_iv, sizeof(_iv))); - return S_OK; -} - -STDMETHODIMP_(UInt32) CBaseCoder::Filter(Byte *data, UInt32 size) -{ - return _aesFilter->Filter(data, size); -} - -HRESULT CDecoder::CreateFilter() -{ - _aesFilter = new CAesCbcDecoder; - return S_OK; -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Crypto/7zAes.h b/desmume/src/windows/7z/CPP/7zip/Crypto/7zAes.h deleted file mode 100644 index 08da66649..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Crypto/7zAes.h +++ /dev/null @@ -1,117 +0,0 @@ -// 7zAes.h - -#ifndef __CRYPTO_7Z_AES_H -#define __CRYPTO_7Z_AES_H - -#include "Common/Buffer.h" -#include "Common/MyCom.h" -#include "Common/MyVector.h" - -#include "../ICoder.h" -#include "../IPassword.h" - -namespace NCrypto { -namespace NSevenZ { - -const int kKeySize = 32; - -class CKeyInfo -{ -public: - int NumCyclesPower; - UInt32 SaltSize; - Byte Salt[16]; - CByteBuffer Password; - Byte Key[kKeySize]; - - bool IsEqualTo(const CKeyInfo &a) const; - void CalculateDigest(); - - CKeyInfo() { Init(); } - void Init() - { - NumCyclesPower = 0; - SaltSize = 0; - for (int i = 0; i < sizeof(Salt); i++) - Salt[i] = 0; - } -}; - -class CKeyInfoCache -{ - int Size; - CObjectVector Keys; -public: - CKeyInfoCache(int size): Size(size) {} - bool Find(CKeyInfo &key); - // HRESULT Calculate(CKeyInfo &key); - void Add(CKeyInfo &key); -}; - -class CBase -{ - CKeyInfoCache _cachedKeys; -protected: - CKeyInfo _key; - Byte _iv[16]; - UInt32 _ivSize; - void CalculateDigest(); - CBase(); -}; - -class CBaseCoder: - public ICompressFilter, - public ICryptoSetPassword, - public CMyUnknownImp, - public CBase -{ -protected: - CMyComPtr _aesFilter; - - virtual HRESULT CreateFilter() = 0; - #ifndef CRYPTO_AES - HRESULT CreateFilterFromDLL(REFCLSID clsID); - #endif -public: - STDMETHOD(Init)(); - STDMETHOD_(UInt32, Filter)(Byte *data, UInt32 size); - - STDMETHOD(CryptoSetPassword)(const Byte *data, UInt32 size); -}; - -#ifndef EXTRACT_ONLY - -class CEncoder: - public CBaseCoder, - public ICompressWriteCoderProperties, - // public ICryptoResetSalt, - public ICryptoResetInitVector -{ - virtual HRESULT CreateFilter(); -public: - MY_UNKNOWN_IMP3( - ICryptoSetPassword, - ICompressWriteCoderProperties, - // ICryptoResetSalt, - ICryptoResetInitVector) - STDMETHOD(WriteCoderProperties)(ISequentialOutStream *outStream); - // STDMETHOD(ResetSalt)(); - STDMETHOD(ResetInitVector)(); -}; -#endif - -class CDecoder: - public CBaseCoder, - public ICompressSetDecoderProperties2 -{ - virtual HRESULT CreateFilter(); -public: - MY_UNKNOWN_IMP2( - ICryptoSetPassword, - ICompressSetDecoderProperties2) - STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size); -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Crypto/7zAesRegister.cpp b/desmume/src/windows/7z/CPP/7zip/Crypto/7zAesRegister.cpp deleted file mode 100644 index 87f8ae9c8..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Crypto/7zAesRegister.cpp +++ /dev/null @@ -1,18 +0,0 @@ -// 7zAesRegister.cpp - -#include "StdAfx.h" - -#include "../Common/RegisterCodec.h" -#include "7zAes.h" - -static void *CreateCodec() { return (void *)(ICompressFilter *)(new NCrypto::NSevenZ::CDecoder()); } -#ifndef EXTRACT_ONLY -static void *CreateCodecOut() { return (void *)(ICompressFilter *)(new NCrypto::NSevenZ::CEncoder()); } -#else -#define CreateCodecOut 0 -#endif - -static CCodecInfo g_CodecInfo = - { CreateCodec, CreateCodecOut, 0x06F10701, L"7zAES", 1, true }; - -REGISTER_CODEC(7zAES) diff --git a/desmume/src/windows/7z/CPP/7zip/Crypto/HmacSha1.cpp b/desmume/src/windows/7z/CPP/7zip/Crypto/HmacSha1.cpp deleted file mode 100644 index 09621e958..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Crypto/HmacSha1.cpp +++ /dev/null @@ -1,109 +0,0 @@ -// HmacSha1.cpp - -#include "StdAfx.h" - -#include "HmacSha1.h" - -namespace NCrypto { -namespace NSha1 { - -void CHmac::SetKey(const Byte *key, size_t keySize) -{ - Byte keyTemp[kBlockSize]; - size_t i; - for (i = 0; i < kBlockSize; i++) - keyTemp[i] = 0; - if(keySize > kBlockSize) - { - _sha.Init(); - _sha.Update(key, keySize); - _sha.Final(keyTemp); - keySize = kDigestSize; - } - else - for (i = 0; i < keySize; i++) - keyTemp[i] = key[i]; - for (i = 0; i < kBlockSize; i++) - keyTemp[i] ^= 0x36; - _sha.Init(); - _sha.Update(keyTemp, kBlockSize); - for (i = 0; i < kBlockSize; i++) - keyTemp[i] ^= 0x36 ^ 0x5C; - _sha2.Init(); - _sha2.Update(keyTemp, kBlockSize); -} - -void CHmac::Final(Byte *mac, size_t macSize) -{ - Byte digest[kDigestSize]; - _sha.Final(digest); - _sha2.Update(digest, kDigestSize); - _sha2.Final(digest); - for(size_t i = 0; i < macSize; i++) - mac[i] = digest[i]; -} - - -void CHmac32::SetKey(const Byte *key, size_t keySize) -{ - UInt32 keyTemp[kBlockSizeInWords]; - size_t i; - for (i = 0; i < kBlockSizeInWords; i++) - keyTemp[i] = 0; - if(keySize > kBlockSize) - { - CContext sha; - sha.Init(); - sha.Update(key, keySize); - Byte digest[kDigestSize]; - sha.Final(digest); - - for (int i = 0 ; i < kDigestSizeInWords; i++) - keyTemp[i] = - ((UInt32)(digest[i * 4 + 0]) << 24) | - ((UInt32)(digest[i * 4 + 1]) << 16) | - ((UInt32)(digest[i * 4 + 2]) << 8) | - ((UInt32)(digest[i * 4 + 3])); - keySize = kDigestSizeInWords; - } - else - for (size_t i = 0; i < keySize; i++) - keyTemp[i / 4] |= (key[i] << (24 - 8 * (i & 3))); - for (i = 0; i < kBlockSizeInWords; i++) - keyTemp[i] ^= 0x36363636; - _sha.Init(); - _sha.Update(keyTemp, kBlockSizeInWords); - for (i = 0; i < kBlockSizeInWords; i++) - keyTemp[i] ^= 0x36363636 ^ 0x5C5C5C5C; - _sha2.Init(); - _sha2.Update(keyTemp, kBlockSizeInWords); -} - -void CHmac32::Final(UInt32 *mac, size_t macSize) -{ - UInt32 digest[kDigestSizeInWords]; - _sha.Final(digest); - _sha2.Update(digest, kDigestSizeInWords); - _sha2.Final(digest); - for(size_t i = 0; i < macSize; i++) - mac[i] = digest[i]; -} - -void CHmac32::GetLoopXorDigest(UInt32 *mac, UInt32 numIteration) -{ - UInt32 block[kBlockSizeInWords]; - UInt32 block2[kBlockSizeInWords]; - _sha.PrepareBlock(block, kDigestSizeInWords); - _sha2.PrepareBlock(block2, kDigestSizeInWords); - for(unsigned int s = 0; s < kDigestSizeInWords; s++) - block[s] = mac[s]; - for(UInt32 i = 0; i < numIteration; i++) - { - _sha.GetBlockDigest(block, block2); - _sha2.GetBlockDigest(block2, block); - for (unsigned int s = 0; s < kDigestSizeInWords; s++) - mac[s] ^= block[s]; - } -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Crypto/HmacSha1.h b/desmume/src/windows/7z/CPP/7zip/Crypto/HmacSha1.h deleted file mode 100644 index 2b12340ed..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Crypto/HmacSha1.h +++ /dev/null @@ -1,39 +0,0 @@ -// HmacSha1.h -// Implements HMAC-SHA-1 (RFC2104, FIPS-198) - -#ifndef __CRYPTO_HMAC_SHA1_H -#define __CRYPTO_HMAC_SHA1_H - -#include "Sha1.h" - -namespace NCrypto { -namespace NSha1 { - -// Use: SetKey(key, keySize); for () Update(data, size); Final(mac, macSize); - -class CHmac -{ - CContext _sha; - CContext _sha2; -public: - void SetKey(const Byte *key, size_t keySize); - void Update(const Byte *data, size_t dataSize) { _sha.Update(data, dataSize); } - void Final(Byte *mac, size_t macSize = kDigestSize); -}; - -class CHmac32 -{ - CContext32 _sha; - CContext32 _sha2; -public: - void SetKey(const Byte *key, size_t keySize); - void Update(const UInt32 *data, size_t dataSize) { _sha.Update(data, dataSize); } - void Final(UInt32 *mac, size_t macSize = kDigestSizeInWords); - - // It'sa for hmac function. in,out: mac[kDigestSizeInWords]. - void GetLoopXorDigest(UInt32 *mac, UInt32 numIteration); -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Crypto/MyAes.cpp b/desmume/src/windows/7z/CPP/7zip/Crypto/MyAes.cpp deleted file mode 100644 index 0f7b74b8d..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Crypto/MyAes.cpp +++ /dev/null @@ -1,57 +0,0 @@ -// Crypto/MyAes.cpp - -#include "StdAfx.h" - -#include "MyAes.h" - -namespace NCrypto { - -struct CAesTabInit { CAesTabInit() { AesGenTables();} } g_AesTabInit; - -STDMETHODIMP CAesCbcEncoder::Init() { return S_OK; } - -STDMETHODIMP_(UInt32) CAesCbcEncoder::Filter(Byte *data, UInt32 size) -{ - return (UInt32)AesCbc_Encode(&Aes, data, size); -} - -STDMETHODIMP CAesCbcEncoder::SetKey(const Byte *data, UInt32 size) -{ - if ((size & 0x7) != 0 || size < 16 || size > 32) - return E_INVALIDARG; - Aes_SetKeyEncode(&Aes.aes, data, size); - return S_OK; -} - -STDMETHODIMP CAesCbcEncoder::SetInitVector(const Byte *data, UInt32 size) -{ - if (size != AES_BLOCK_SIZE) - return E_INVALIDARG; - AesCbc_Init(&Aes, data); - return S_OK; -} - -STDMETHODIMP CAesCbcDecoder::Init() { return S_OK; } - -STDMETHODIMP_(UInt32) CAesCbcDecoder::Filter(Byte *data, UInt32 size) -{ - return (UInt32)AesCbc_Decode(&Aes, data, size); -} - -STDMETHODIMP CAesCbcDecoder::SetKey(const Byte *data, UInt32 size) -{ - if ((size & 0x7) != 0 || size < 16 || size > 32) - return E_INVALIDARG; - Aes_SetKeyDecode(&Aes.aes, data, size); - return S_OK; -} - -STDMETHODIMP CAesCbcDecoder::SetInitVector(const Byte *data, UInt32 size) -{ - if (size != AES_BLOCK_SIZE) - return E_INVALIDARG; - AesCbc_Init(&Aes, data); - return S_OK; -} - -} diff --git a/desmume/src/windows/7z/CPP/7zip/Crypto/MyAes.h b/desmume/src/windows/7z/CPP/7zip/Crypto/MyAes.h deleted file mode 100644 index bfa58cdba..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Crypto/MyAes.h +++ /dev/null @@ -1,48 +0,0 @@ -// Crypto/MyAes.h - -#ifndef __CRYPTO_MY_AES_H -#define __CRYPTO_MY_AES_H - -extern "C" -{ -#include "../../../C/Aes.h" -} - -#include "../../Common/MyCom.h" -#include "../../Common/Types.h" - -#include "../ICoder.h" - -namespace NCrypto { - -class CAesCbcEncoder: - public ICompressFilter, - public ICryptoProperties, - public CMyUnknownImp -{ - CAesCbc Aes; -public: - MY_UNKNOWN_IMP1(ICryptoProperties) - STDMETHOD(Init)(); - STDMETHOD_(UInt32, Filter)(Byte *data, UInt32 size); - STDMETHOD(SetKey)(const Byte *data, UInt32 size); - STDMETHOD(SetInitVector)(const Byte *data, UInt32 size); -}; - -class CAesCbcDecoder: - public ICompressFilter, - public ICryptoProperties, - public CMyUnknownImp -{ - CAesCbc Aes; -public: - MY_UNKNOWN_IMP1(ICryptoProperties) - STDMETHOD(Init)(); - STDMETHOD_(UInt32, Filter)(Byte *data, UInt32 size); - STDMETHOD(SetKey)(const Byte *data, UInt32 size); - STDMETHOD(SetInitVector)(const Byte *data, UInt32 size); -}; - -} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Crypto/Pbkdf2HmacSha1.cpp b/desmume/src/windows/7z/CPP/7zip/Crypto/Pbkdf2HmacSha1.cpp deleted file mode 100644 index 0ac6dc61b..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Crypto/Pbkdf2HmacSha1.cpp +++ /dev/null @@ -1,83 +0,0 @@ -// Pbkdf2HmacSha1.cpp - -#include "StdAfx.h" - -#include "HmacSha1.h" - -namespace NCrypto { -namespace NSha1 { - -void Pbkdf2Hmac(const Byte *pwd, size_t pwdSize, const Byte *salt, size_t saltSize, - UInt32 numIterations, Byte *key, size_t keySize) -{ - CHmac baseCtx; - baseCtx.SetKey(pwd, pwdSize); - for (UInt32 i = 1; keySize > 0; i++) - { - CHmac ctx = baseCtx; - ctx.Update(salt, saltSize); - Byte u[kDigestSize] = { (Byte)(i >> 24), (Byte)(i >> 16), (Byte)(i >> 8), (Byte)(i) }; - const unsigned int curSize = (keySize < kDigestSize) ? (unsigned int)keySize : kDigestSize; - ctx.Update(u, 4); - ctx.Final(u, kDigestSize); - - unsigned int s; - for (s = 0; s < curSize; s++) - key[s] = u[s]; - - for (UInt32 j = numIterations; j > 1; j--) - { - ctx = baseCtx; - ctx.Update(u, kDigestSize); - ctx.Final(u, kDigestSize); - for (s = 0; s < curSize; s++) - key[s] ^= u[s]; - } - - key += curSize; - keySize -= curSize; - } -} - -void Pbkdf2Hmac32(const Byte *pwd, size_t pwdSize, const UInt32 *salt, size_t saltSize, - UInt32 numIterations, UInt32 *key, size_t keySize) -{ - CHmac32 baseCtx; - baseCtx.SetKey(pwd, pwdSize); - for (UInt32 i = 1; keySize > 0; i++) - { - CHmac32 ctx = baseCtx; - ctx.Update(salt, saltSize); - UInt32 u[kDigestSizeInWords] = { i }; - const unsigned int curSize = (keySize < kDigestSizeInWords) ? (unsigned int)keySize : kDigestSizeInWords; - ctx.Update(u, 1); - ctx.Final(u, kDigestSizeInWords); - - // Speed-optimized code start - ctx = baseCtx; - ctx.GetLoopXorDigest(u, numIterations - 1); - // Speed-optimized code end - - unsigned int s; - for (s = 0; s < curSize; s++) - key[s] = u[s]; - - /* - // Default code start - for (UInt32 j = numIterations; j > 1; j--) - { - ctx = baseCtx; - ctx.Update(u, kDigestSizeInWords); - ctx.Final(u, kDigestSizeInWords); - for (s = 0; s < curSize; s++) - key[s] ^= u[s]; - } - // Default code end - */ - - key += curSize; - keySize -= curSize; - } -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Crypto/Pbkdf2HmacSha1.h b/desmume/src/windows/7z/CPP/7zip/Crypto/Pbkdf2HmacSha1.h deleted file mode 100644 index ea5d99f18..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Crypto/Pbkdf2HmacSha1.h +++ /dev/null @@ -1,21 +0,0 @@ -// Pbkdf2HmacSha1.h -// Password-Based Key Derivation Function (RFC 2898, PKCS #5) based on HMAC-SHA-1 - -#ifndef __CRYPTO_PBKDF2_HMAC_SHA1_H -#define __CRYPTO_PBKDF2_HMAC_SHA1_H - -#include -#include "../../Common/Types.h" - -namespace NCrypto { -namespace NSha1 { - -void Pbkdf2Hmac(const Byte *pwd, size_t pwdSize, const Byte *salt, size_t saltSize, - UInt32 numIterations, Byte *key, size_t keySize); - -void Pbkdf2Hmac32(const Byte *pwd, size_t pwdSize, const UInt32 *salt, size_t saltSize, - UInt32 numIterations, UInt32 *key, size_t keySize); - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Crypto/RandGen.cpp b/desmume/src/windows/7z/CPP/7zip/Crypto/RandGen.cpp deleted file mode 100644 index 66b323168..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Crypto/RandGen.cpp +++ /dev/null @@ -1,107 +0,0 @@ -// RandGen.cpp - -#include "StdAfx.h" - -#include -#include "Windows/Synchronization.h" -#include "RandGen.h" - -#ifndef _WIN32 -#include -#define USE_POSIX_TIME -#define USE_POSIX_TIME2 -#endif - -#ifdef USE_POSIX_TIME -#include -#ifdef USE_POSIX_TIME2 -#include -#endif -#endif - -// This is not very good random number generator. -// Please use it only for salt. -// First generated data block depends from timer and processID. -// Other generated data blocks depend from previous state -// Maybe it's possible to restore original timer value from generated value. - -void CRandomGenerator::Init() -{ - NCrypto::NSha1::CContext hash; - hash.Init(); - - #ifdef _WIN32 - DWORD w = ::GetCurrentProcessId(); - hash.Update((const Byte *)&w, sizeof(w)); - w = ::GetCurrentThreadId(); - hash.Update((const Byte *)&w, sizeof(w)); - #else - pid_t pid = getpid(); - hash.Update((const Byte *)&pid, sizeof(pid)); - pid = getppid(); - hash.Update((const Byte *)&pid, sizeof(pid)); - #endif - - for (int i = 0; i < 1000; i++) - { - #ifdef _WIN32 - LARGE_INTEGER v; - if (::QueryPerformanceCounter(&v)) - hash.Update((const Byte *)&v.QuadPart, sizeof(v.QuadPart)); - #endif - - #ifdef USE_POSIX_TIME - #ifdef USE_POSIX_TIME2 - timeval v; - if (gettimeofday(&v, 0) == 0) - { - hash.Update((const Byte *)&v.tv_sec, sizeof(v.tv_sec)); - hash.Update((const Byte *)&v.tv_usec, sizeof(v.tv_usec)); - } - #endif - time_t v2 = time(NULL); - hash.Update((const Byte *)&v2, sizeof(v2)); - #endif - - DWORD tickCount = ::GetTickCount(); - hash.Update((const Byte *)&tickCount, sizeof(tickCount)); - - for (int j = 0; j < 100; j++) - { - hash.Final(_buff); - hash.Init(); - hash.Update(_buff, NCrypto::NSha1::kDigestSize); - } - } - hash.Final(_buff); - _needInit = false; -} - -static NWindows::NSynchronization::CCriticalSection g_CriticalSection; - -void CRandomGenerator::Generate(Byte *data, unsigned int size) -{ - g_CriticalSection.Enter(); - if (_needInit) - Init(); - while (size > 0) - { - NCrypto::NSha1::CContext hash; - - hash.Init(); - hash.Update(_buff, NCrypto::NSha1::kDigestSize); - hash.Final(_buff); - - hash.Init(); - UInt32 salt = 0xF672ABD1; - hash.Update((const Byte *)&salt, sizeof(salt)); - hash.Update(_buff, NCrypto::NSha1::kDigestSize); - Byte buff[NCrypto::NSha1::kDigestSize]; - hash.Final(buff); - for (unsigned int i = 0; i < NCrypto::NSha1::kDigestSize && size > 0; i++, size--) - *data++ = buff[i]; - } - g_CriticalSection.Leave(); -} - -CRandomGenerator g_RandomGenerator; diff --git a/desmume/src/windows/7z/CPP/7zip/Crypto/RandGen.h b/desmume/src/windows/7z/CPP/7zip/Crypto/RandGen.h deleted file mode 100644 index a457897a9..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Crypto/RandGen.h +++ /dev/null @@ -1,21 +0,0 @@ -// RandGen.h - -#ifndef __CRYPTO_RAND_GEN_H -#define __CRYPTO_RAND_GEN_H - -#include "Sha1.h" - -class CRandomGenerator -{ - Byte _buff[NCrypto::NSha1::kDigestSize]; - bool _needInit; - - void Init(); -public: - CRandomGenerator(): _needInit(true) {}; - void Generate(Byte *data, unsigned size); -}; - -extern CRandomGenerator g_RandomGenerator; - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Crypto/Rar20Crypto.cpp b/desmume/src/windows/7z/CPP/7zip/Crypto/Rar20Crypto.cpp deleted file mode 100644 index bf5eb9894..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Crypto/Rar20Crypto.cpp +++ /dev/null @@ -1,136 +0,0 @@ -// Crypto/Rar20Crypto.cpp - -#include "StdAfx.h" - -extern "C" -{ - #include "../../../C/7zCrc.h" - #include "../../../C/CpuArch.h" - #include "../../../C/RotateDefs.h" -} - -#include "Rar20Crypto.h" - -namespace NCrypto { -namespace NRar20 { - -static const int kNumRounds = 32; - -static const Byte InitSubstTable[256] = { - 215, 19,149, 35, 73,197,192,205,249, 28, 16,119, 48,221, 2, 42, - 232, 1,177,233, 14, 88,219, 25,223,195,244, 90, 87,239,153,137, - 255,199,147, 70, 92, 66,246, 13,216, 40, 62, 29,217,230, 86, 6, - 71, 24,171,196,101,113,218,123, 93, 91,163,178,202, 67, 44,235, - 107,250, 75,234, 49,167,125,211, 83,114,157,144, 32,193,143, 36, - 158,124,247,187, 89,214,141, 47,121,228, 61,130,213,194,174,251, - 97,110, 54,229,115, 57,152, 94,105,243,212, 55,209,245, 63, 11, - 164,200, 31,156, 81,176,227, 21, 76, 99,139,188,127, 17,248, 51, - 207,120,189,210, 8,226, 41, 72,183,203,135,165,166, 60, 98, 7, - 122, 38,155,170, 69,172,252,238, 39,134, 59,128,236, 27,240, 80, - 131, 3, 85,206,145, 79,154,142,159,220,201,133, 74, 64, 20,129, - 224,185,138,103,173,182, 43, 34,254, 82,198,151,231,180, 58, 10, - 118, 26,102, 12, 50,132, 22,191,136,111,162,179, 45, 4,148,108, - 161, 56, 78,126,242,222, 15,175,146, 23, 33,241,181,190, 77,225, - 0, 46,169,186, 68, 95,237, 65, 53,208,253,168, 9, 18,100, 52, - 116,184,160, 96,109, 37, 30,106,140,104,150, 5,204,117,112, 84 -}; - -void CData::UpdateKeys(const Byte *data) -{ - for (int i = 0; i < 16; i += 4) - for (int j = 0; j < 4; j++) - Keys[j] ^= g_CrcTable[data[i + j]]; -} - -static void Swap(Byte *b1, Byte *b2) -{ - Byte b = *b1; - *b1 = *b2; - *b2 = b; -} - -void CData::SetPassword(const Byte *password, UInt32 passwordLen) -{ - Keys[0] = 0xD3A3B879L; - Keys[1] = 0x3F6D12F7L; - Keys[2] = 0x7515A235L; - Keys[3] = 0xA4E7F123L; - - Byte psw[256]; - memset(psw, 0, sizeof(psw)); - memcpy(psw, password, passwordLen); - memcpy(SubstTable, InitSubstTable, sizeof(SubstTable)); - - for (UInt32 j = 0; j < 256; j++) - for (UInt32 i = 0; i < passwordLen; i += 2) - { - UInt32 n2 = (Byte)g_CrcTable[(psw[i + 1] + j) & 0xFF]; - UInt32 n1 = (Byte)g_CrcTable[(psw[i] - j) & 0xFF]; - for (UInt32 k = 1; (n1 & 0xFF) != n2; n1++, k++) - Swap(&SubstTable[n1 & 0xFF], &SubstTable[(n1 + i + k) & 0xFF]); - } - for (UInt32 i = 0; i < passwordLen; i+= 16) - EncryptBlock(&psw[i]); -} - -void CData::CryptBlock(Byte *buf, bool encrypt) -{ - Byte inBuf[16]; - UInt32 A, B, C, D, T, TA, TB; - - A = GetUi32(buf + 0) ^ Keys[0]; - B = GetUi32(buf + 4) ^ Keys[1]; - C = GetUi32(buf + 8) ^ Keys[2]; - D = GetUi32(buf + 12) ^ Keys[3]; - - if (!encrypt) - memcpy(inBuf, buf, sizeof(inBuf)); - - for (int i = 0; i < kNumRounds; i++) - { - UInt32 key = Keys[(encrypt ? i : (kNumRounds - 1 - i)) & 3]; - T = ((C + rotlFixed(D, 11)) ^ key); - TA = A ^ SubstLong(T); - T = ((D ^ rotlFixed(C, 17)) + key); - TB = B ^ SubstLong(T); - A = C; - B = D; - C = TA; - D = TB; - } - - SetUi32(buf + 0, C ^ Keys[0]); - SetUi32(buf + 4, D ^ Keys[1]); - SetUi32(buf + 8, A ^ Keys[2]); - SetUi32(buf + 12, B ^ Keys[3]); - - UpdateKeys(encrypt ? buf : inBuf); -} - -STDMETHODIMP CDecoder::CryptoSetPassword(const Byte *data, UInt32 size) -{ - _cipher.SetPassword(data, size); - return S_OK; -} - -STDMETHODIMP CDecoder::Init() -{ - return S_OK; -} - -static const UInt32 kBlockSize = 16; - -STDMETHODIMP_(UInt32) CDecoder::Filter(Byte *data, UInt32 size) -{ - if (size == 0) - return 0; - if (size < kBlockSize) - return kBlockSize; - UInt32 i; - size -= kBlockSize; - for (i = 0; i <= size; i += kBlockSize) - _cipher.DecryptBlock(data + i); - return i; -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Crypto/Rar20Crypto.h b/desmume/src/windows/7z/CPP/7zip/Crypto/Rar20Crypto.h deleted file mode 100644 index 36f5590d1..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Crypto/Rar20Crypto.h +++ /dev/null @@ -1,50 +0,0 @@ -// Crypto/Rar20Crypto.h - -#ifndef __CRYPTO_RAR20_CRYPTO_H -#define __CRYPTO_RAR20_CRYPTO_H - -#include "Common/MyCom.h" - -#include "../ICoder.h" -#include "../IPassword.h" - -namespace NCrypto { -namespace NRar20 { - -class CData -{ - Byte SubstTable[256]; - UInt32 Keys[4]; - - UInt32 SubstLong(UInt32 t) - { - return (UInt32)SubstTable[(int)t & 255] | - ((UInt32)SubstTable[(int)(t >> 8) & 255] << 8) | - ((UInt32)SubstTable[(int)(t >> 16) & 255] << 16) | - ((UInt32)SubstTable[(int)(t >> 24) & 255] << 24); - } - void UpdateKeys(const Byte *data); - void CryptBlock(Byte *buf, bool encrypt); -public: - void EncryptBlock(Byte *buf) { CryptBlock(buf, true); } - void DecryptBlock(Byte *buf) { CryptBlock(buf, false); } - void SetPassword(const Byte *password, UInt32 passwordLen); -}; - -class CDecoder: - public ICompressFilter, - public ICryptoSetPassword, - public CMyUnknownImp -{ - CData _cipher; -public: - MY_UNKNOWN_IMP1(ICryptoSetPassword) - - STDMETHOD(Init)(); - STDMETHOD_(UInt32, Filter)(Byte *data, UInt32 size); - STDMETHOD(CryptoSetPassword)(const Byte *data, UInt32 size); -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Crypto/RarAes.cpp b/desmume/src/windows/7z/CPP/7zip/Crypto/RarAes.cpp deleted file mode 100644 index be3cefcc4..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Crypto/RarAes.cpp +++ /dev/null @@ -1,139 +0,0 @@ -// Crypto/RarAes.cpp -// Note: you must include MyAes.cpp to project to initialize AES tables - -#include "StdAfx.h" - -#include "RarAes.h" -#include "Sha1.h" - -namespace NCrypto { -namespace NRar29 { - -CDecoder::CDecoder(): - _thereIsSalt(false), - _needCalculate(true), - _rar350Mode(false) -{ - for (int i = 0; i < sizeof(_salt); i++) - _salt[i] = 0; -} - -STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte *data, UInt32 size) -{ - bool thereIsSaltPrev = _thereIsSalt; - _thereIsSalt = false; - if (size == 0) - return S_OK; - if (size < 8) - return E_INVALIDARG; - _thereIsSalt = true; - bool same = false; - if (_thereIsSalt == thereIsSaltPrev) - { - same = true; - if (_thereIsSalt) - { - for (int i = 0; i < sizeof(_salt); i++) - if (_salt[i] != data[i]) - { - same = false; - break; - } - } - } - for (int i = 0; i < sizeof(_salt); i++) - _salt[i] = data[i]; - if (!_needCalculate && !same) - _needCalculate = true; - return S_OK; -} - -static const int kMaxPasswordLength = 127 * 2; - -STDMETHODIMP CDecoder::CryptoSetPassword(const Byte *data, UInt32 size) -{ - if (size > kMaxPasswordLength) - size = kMaxPasswordLength; - bool same = false; - if (size == buffer.GetCapacity()) - { - same = true; - for (UInt32 i = 0; i < size; i++) - if (data[i] != buffer[i]) - { - same = false; - break; - } - } - if (!_needCalculate && !same) - _needCalculate = true; - buffer.SetCapacity(size); - memcpy(buffer, data, size); - return S_OK; -} - -STDMETHODIMP CDecoder::Init() -{ - Calculate(); - Aes_SetKeyDecode(&Aes.aes, aesKey, kRarAesKeySize); - AesCbc_Init(&Aes, aesInit); - return S_OK; -} - -STDMETHODIMP_(UInt32) CDecoder::Filter(Byte *data, UInt32 size) -{ - return (UInt32)AesCbc_Decode(&Aes, data, size); -} - -void CDecoder::Calculate() -{ - if (_needCalculate) - { - const int kSaltSize = 8; - - Byte rawPassword[kMaxPasswordLength + kSaltSize]; - - memcpy(rawPassword, buffer, buffer.GetCapacity()); - - size_t rawLength = buffer.GetCapacity(); - - if (_thereIsSalt) - { - memcpy(rawPassword + rawLength, _salt, kSaltSize); - rawLength += kSaltSize; - } - - NSha1::CContext sha; - sha.Init(); - - // seems rar reverts hash for sha. - const int hashRounds = 0x40000; - int i; - for (i = 0; i < hashRounds; i++) - { - sha.Update(rawPassword, rawLength, _rar350Mode); - Byte pswNum[3] = { (Byte)i, (Byte)(i >> 8), (Byte)(i >> 16) }; - sha.Update(pswNum, 3, _rar350Mode); - if (i % (hashRounds / 16) == 0) - { - NSha1::CContext shaTemp = sha; - Byte digest[NSha1::kDigestSize]; - shaTemp.Final(digest); - aesInit[i / (hashRounds / 16)] = (Byte)digest[4 * 4 + 3]; - } - } - /* - // it's test message for sha - const char *message = "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"; - sha.Update((const Byte *)message, strlen(message)); - */ - Byte digest[20]; - sha.Final(digest); - for (i = 0; i < 4; i++) - for (int j = 0; j < 4; j++) - aesKey[i * 4 + j] = (digest[i * 4 + 3 - j]); - } - _needCalculate = false; -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Crypto/RarAes.h b/desmume/src/windows/7z/CPP/7zip/Crypto/RarAes.h deleted file mode 100644 index d21d12a55..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Crypto/RarAes.h +++ /dev/null @@ -1,62 +0,0 @@ -// Crypto/RarAes.h - -#ifndef __CRYPTO_RAR_AES_H -#define __CRYPTO_RAR_AES_H - -extern "C" -{ -#include "../../../C/Aes.h" -} - -#include "Common/Buffer.h" -#include "Common/MyCom.h" - -#include "../ICoder.h" -#include "../IPassword.h" - -namespace NCrypto { -namespace NRar29 { - -const UInt32 kRarAesKeySize = 16; - -class CDecoder: - public ICompressFilter, - public ICompressSetDecoderProperties2, - public ICryptoSetPassword, - public CMyUnknownImp -{ - Byte _salt[8]; - bool _thereIsSalt; - CByteBuffer buffer; - Byte aesKey[kRarAesKeySize]; - Byte aesInit[AES_BLOCK_SIZE]; - bool _needCalculate; - - CAesCbc Aes; - - bool _rar350Mode; - - void Calculate(); - -public: - - MY_UNKNOWN_IMP2( - ICryptoSetPassword, - ICompressSetDecoderProperties2) - - STDMETHOD(Init)(); - - STDMETHOD_(UInt32, Filter)(Byte *data, UInt32 size); - - STDMETHOD(CryptoSetPassword)(const Byte *aData, UInt32 aSize); - - // ICompressSetDecoderProperties - STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size); - - CDecoder(); - void SetRar350Mode(bool rar350Mode) { _rar350Mode = rar350Mode; } -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Crypto/Sha1.cpp b/desmume/src/windows/7z/CPP/7zip/Crypto/Sha1.cpp deleted file mode 100644 index 08bb57c94..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Crypto/Sha1.cpp +++ /dev/null @@ -1,213 +0,0 @@ -// Crypto/Sha1.cpp -// This file is based on public domain -// Steve Reid and Wei Dai's code from Crypto++ - -#include "StdAfx.h" - -#include "Sha1.h" -extern "C" -{ -#include "../../../C/RotateDefs.h" -} - -namespace NCrypto { -namespace NSha1 { - -// define it for speed optimization -// #define _SHA1_UNROLL - -static const unsigned kNumW = - #ifdef _SHA1_UNROLL - 16; - #else - 80; - #endif - - -#define w0(i) (W[(i)] = data[(i)]) - -#ifdef _SHA1_UNROLL -#define w1(i) (W[(i)&15] = rotlFixed(W[((i)-3)&15] ^ W[((i)-8)&15] ^ W[((i)-14)&15] ^ W[((i)-16)&15], 1)) -#else -#define w1(i) (W[(i)] = rotlFixed(W[(i)-3] ^ W[(i)-8] ^ W[(i)-14] ^ W[(i)-16], 1)) -#endif - -#define f1(x,y,z) (z^(x&(y^z))) -#define f2(x,y,z) (x^y^z) -#define f3(x,y,z) ((x&y)|(z&(x|y))) -#define f4(x,y,z) (x^y^z) - -#define RK1(a,b,c,d,e,i, f, w, k) e += f(b,c,d) + w(i) + k + rotlFixed(a,5); b = rotlFixed(b,30); - -#define R0(a,b,c,d,e,i) RK1(a,b,c,d,e,i, f1, w0, 0x5A827999) -#define R1(a,b,c,d,e,i) RK1(a,b,c,d,e,i, f1, w1, 0x5A827999) -#define R2(a,b,c,d,e,i) RK1(a,b,c,d,e,i, f2, w1, 0x6ED9EBA1) -#define R3(a,b,c,d,e,i) RK1(a,b,c,d,e,i, f3, w1, 0x8F1BBCDC) -#define R4(a,b,c,d,e,i) RK1(a,b,c,d,e,i, f4, w1, 0xCA62C1D6) - -#define RX_1_4(rx1, rx4, i) rx1(a,b,c,d,e,i); rx4(e,a,b,c,d,i+1); rx4(d,e,a,b,c,i+2); rx4(c,d,e,a,b,i+3); rx4(b,c,d,e,a,i+4); -#define RX_5(rx, i) RX_1_4(rx, rx, i); - -void CContextBase::Init() -{ - _state[0] = 0x67452301; - _state[1] = 0xEFCDAB89; - _state[2] = 0x98BADCFE; - _state[3] = 0x10325476; - _state[4] = 0xC3D2E1F0; - _count = 0; -} - -void CContextBase::GetBlockDigest(UInt32 *data, UInt32 *destDigest, bool returnRes) -{ - UInt32 a, b, c, d, e; - UInt32 W[kNumW]; - - a = _state[0]; - b = _state[1]; - c = _state[2]; - d = _state[3]; - e = _state[4]; - #ifdef _SHA1_UNROLL - RX_5(R0, 0); RX_5(R0, 5); RX_5(R0, 10); - #else - int i; - for (i = 0; i < 15; i += 5) { RX_5(R0, i); } - #endif - - RX_1_4(R0, R1, 15); - - - #ifdef _SHA1_UNROLL - RX_5(R2, 20); RX_5(R2, 25); RX_5(R2, 30); RX_5(R2, 35); - RX_5(R3, 40); RX_5(R3, 45); RX_5(R3, 50); RX_5(R3, 55); - RX_5(R4, 60); RX_5(R4, 65); RX_5(R4, 70); RX_5(R4, 75); - #else - i = 20; - for (; i < 40; i += 5) { RX_5(R2, i); } - for (; i < 60; i += 5) { RX_5(R3, i); } - for (; i < 80; i += 5) { RX_5(R4, i); } - #endif - - destDigest[0] = _state[0] + a; - destDigest[1] = _state[1] + b; - destDigest[2] = _state[2] + c; - destDigest[3] = _state[3] + d; - destDigest[4] = _state[4] + e; - - if (returnRes) - for (int i = 0 ; i < 16; i++) - data[i] = W[kNumW - 16 + i]; - - // Wipe variables - // a = b = c = d = e = 0; -} - -void CContextBase::PrepareBlock(UInt32 *block, unsigned size) const -{ - unsigned curBufferPos = size & 0xF; - block[curBufferPos++] = 0x80000000; - while (curBufferPos != (16 - 2)) - block[curBufferPos++] = 0; - const UInt64 lenInBits = (_count << 9) + ((UInt64)size << 5); - block[curBufferPos++] = (UInt32)(lenInBits >> 32); - block[curBufferPos++] = (UInt32)(lenInBits); -} - -void CContext::Update(Byte *data, size_t size, bool rar350Mode) -{ - bool returnRes = false; - unsigned curBufferPos = _count2; - while (size-- > 0) - { - int pos = (int)(curBufferPos & 3); - if (pos == 0) - _buffer[curBufferPos >> 2] = 0; - _buffer[curBufferPos >> 2] |= ((UInt32)*data++) << (8 * (3 - pos)); - if (++curBufferPos == kBlockSize) - { - curBufferPos = 0; - CContextBase::UpdateBlock(_buffer, returnRes); - if (returnRes) - for (int i = 0; i < kBlockSizeInWords; i++) - { - UInt32 d = _buffer[i]; - data[i * 4 + 0 - kBlockSize] = (Byte)(d); - data[i * 4 + 1 - kBlockSize] = (Byte)(d >> 8); - data[i * 4 + 2 - kBlockSize] = (Byte)(d >> 16); - data[i * 4 + 3 - kBlockSize] = (Byte)(d >> 24); - } - returnRes = rar350Mode; - } - } - _count2 = curBufferPos; -} - -void CContext::Final(Byte *digest) -{ - const UInt64 lenInBits = (_count << 9) + ((UInt64)_count2 << 3); - unsigned curBufferPos = _count2; - int pos = (int)(curBufferPos & 3); - curBufferPos >>= 2; - if (pos == 0) - _buffer[curBufferPos] = 0; - _buffer[curBufferPos++] |= ((UInt32)0x80) << (8 * (3 - pos)); - - while (curBufferPos != (16 - 2)) - { - curBufferPos &= 0xF; - if (curBufferPos == 0) - UpdateBlock(); - _buffer[curBufferPos++] = 0; - } - _buffer[curBufferPos++] = (UInt32)(lenInBits >> 32); - _buffer[curBufferPos++] = (UInt32)(lenInBits); - UpdateBlock(); - - int i; - for (i = 0; i < kDigestSizeInWords; i++) - { - UInt32 state = _state[i] & 0xFFFFFFFF; - *digest++ = (Byte)(state >> 24); - *digest++ = (Byte)(state >> 16); - *digest++ = (Byte)(state >> 8); - *digest++ = (Byte)(state); - } - Init(); -} - -/////////////////////////// -// Words version - -void CContext32::Update(const UInt32 *data, size_t size) -{ - while (size-- > 0) - { - _buffer[_count2++] = *data++; - if (_count2 == kBlockSizeInWords) - { - _count2 = 0; - UpdateBlock(); - } - } -} - -void CContext32::Final(UInt32 *digest) -{ - const UInt64 lenInBits = (_count << 9) + ((UInt64)_count2 << 5); - unsigned curBufferPos = _count2; - _buffer[curBufferPos++] = 0x80000000; - while (curBufferPos != (16 - 2)) - { - curBufferPos &= 0xF; - if (curBufferPos == 0) - UpdateBlock(); - _buffer[curBufferPos++] = 0; - } - _buffer[curBufferPos++] = (UInt32)(lenInBits >> 32); - _buffer[curBufferPos++] = (UInt32)(lenInBits); - GetBlockDigest(_buffer, digest); - Init(); -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Crypto/Sha1.h b/desmume/src/windows/7z/CPP/7zip/Crypto/Sha1.h deleted file mode 100644 index 06ae27024..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Crypto/Sha1.h +++ /dev/null @@ -1,68 +0,0 @@ -// Crypto/Sha1.h -// This file is based on public domain -// Steve Reid and Wei Dai's code from Crypto++ - -#ifndef __CRYPTO_SHA1_H -#define __CRYPTO_SHA1_H - -#include -#include "../../Common/Types.h" - -// Sha1 implementation in RAR before version 3.60 has bug: -// it changes data bytes in some cases. -// So this class supports both versions: normal_SHA and rar3Mode - -namespace NCrypto { -namespace NSha1 { - -const unsigned kBlockSize = 64; -const unsigned kDigestSize = 20; - -const unsigned kBlockSizeInWords = (kBlockSize >> 2); -const unsigned kDigestSizeInWords = (kDigestSize >> 2); - -class CContextBase -{ -protected: - UInt32 _state[5]; - UInt64 _count; - void UpdateBlock(UInt32 *data, bool returnRes = false) - { - GetBlockDigest(data, _state, returnRes); - _count++; - } -public: - void Init(); - void GetBlockDigest(UInt32 *blockData, UInt32 *destDigest, bool returnRes = false); - // PrepareBlock can be used only when size <= 13. size in Words - void PrepareBlock(UInt32 *block, unsigned int size) const; -}; - -class CContextBase2: public CContextBase -{ -protected: - unsigned _count2; - UInt32 _buffer[kBlockSizeInWords]; - void UpdateBlock() { CContextBase::UpdateBlock(_buffer); } -public: - void Init() { CContextBase::Init(); _count2 = 0; } -}; - -class CContext: public CContextBase2 -{ -public: - void Update(Byte *data, size_t size, bool rar350Mode = false); - void Update(const Byte *data, size_t size) { Update((Byte *)data, size, false); } - void Final(Byte *digest); -}; - -class CContext32: public CContextBase2 -{ -public: - void Update(const UInt32 *data, size_t size); - void Final(UInt32 *digest); -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Crypto/StdAfx.h b/desmume/src/windows/7z/CPP/7zip/Crypto/StdAfx.h deleted file mode 100644 index c28ffcea7..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Crypto/StdAfx.h +++ /dev/null @@ -1,8 +0,0 @@ -// StdAfx.h - -#ifndef __STDAFX_H -#define __STDAFX_H - -#include "../../Common/MyWindows.h" - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Crypto/WzAes.cpp b/desmume/src/windows/7z/CPP/7zip/Crypto/WzAes.cpp deleted file mode 100644 index b8f003034..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Crypto/WzAes.cpp +++ /dev/null @@ -1,209 +0,0 @@ -// Crypto/WzAes.cpp -/* -This code implements Brian Gladman's scheme -specified in password Based File Encryption Utility. - -Note: you must include MyAes.cpp to project to initialize AES tables -*/ - -#include "StdAfx.h" - -#include "../Common/StreamObjects.h" -#include "../Common/StreamUtils.h" - -#include "Pbkdf2HmacSha1.h" -#include "RandGen.h" -#include "WzAes.h" - -// define it if you don't want to use speed-optimized version of Pbkdf2HmacSha1 -// #define _NO_WZAES_OPTIMIZATIONS - -namespace NCrypto { -namespace NWzAes { - -const unsigned int kAesKeySizeMax = 32; - -static const UInt32 kNumKeyGenIterations = 1000; - -STDMETHODIMP CBaseCoder::CryptoSetPassword(const Byte *data, UInt32 size) -{ - if(size > kPasswordSizeMax) - return E_INVALIDARG; - _key.Password.SetCapacity(size); - memcpy(_key.Password, data, size); - return S_OK; -} - -#define SetUi32(p, d) { UInt32 x = (d); (p)[0] = (Byte)x; (p)[1] = (Byte)(x >> 8); \ - (p)[2] = (Byte)(x >> 16); (p)[3] = (Byte)(x >> 24); } - -void CBaseCoder::EncryptData(Byte *data, UInt32 size) -{ - unsigned int pos = _blockPos; - for (; size > 0; size--) - { - if (pos == AES_BLOCK_SIZE) - { - if (++_counter[0] == 0) - _counter[1]++; - UInt32 temp[4]; - Aes_Encode32(&Aes, temp, _counter); - SetUi32(_buffer, temp[0]); - SetUi32(_buffer + 4, temp[1]); - SetUi32(_buffer + 8, temp[2]); - SetUi32(_buffer + 12, temp[3]); - pos = 0; - } - *data++ ^= _buffer[pos++]; - } - _blockPos = pos; -} - -#ifndef _NO_WZAES_OPTIMIZATIONS - -static void BytesToBeUInt32s(const Byte *src, UInt32 *dest, int destSize) -{ - for (int i = 0 ; i < destSize; i++) - dest[i] = - ((UInt32)(src[i * 4 + 0]) << 24) | - ((UInt32)(src[i * 4 + 1]) << 16) | - ((UInt32)(src[i * 4 + 2]) << 8) | - ((UInt32)(src[i * 4 + 3])); -} - -#endif - -STDMETHODIMP CBaseCoder::Init() -{ - UInt32 keySize = _key.GetKeySize(); - UInt32 keysTotalSize = 2 * keySize + kPwdVerifCodeSize; - Byte buf[2 * kAesKeySizeMax + kPwdVerifCodeSize]; - - // for (int ii = 0; ii < 1000; ii++) - { - #ifdef _NO_WZAES_OPTIMIZATIONS - - NSha1::Pbkdf2Hmac( - _key.Password, _key.Password.GetCapacity(), - _key.Salt, _key.GetSaltSize(), - kNumKeyGenIterations, - buf, keysTotalSize); - - #else - - UInt32 buf32[(2 * kAesKeySizeMax + kPwdVerifCodeSize + 3) / 4]; - UInt32 key32SizeTotal = (keysTotalSize + 3) / 4; - UInt32 salt[kSaltSizeMax * 4]; - UInt32 saltSizeInWords = _key.GetSaltSize() / 4; - BytesToBeUInt32s(_key.Salt, salt, saltSizeInWords); - NSha1::Pbkdf2Hmac32( - _key.Password, _key.Password.GetCapacity(), - salt, saltSizeInWords, - kNumKeyGenIterations, - buf32, key32SizeTotal); - for (UInt32 j = 0; j < keysTotalSize; j++) - buf[j] = (Byte)(buf32[j / 4] >> (24 - 8 * (j & 3))); - - #endif - } - - _hmac.SetKey(buf + keySize, keySize); - memcpy(_key.PwdVerifComputed, buf + 2 * keySize, kPwdVerifCodeSize); - - _blockPos = AES_BLOCK_SIZE; - for (int i = 0; i < 4; i++) - _counter[i] = 0; - - Aes_SetKeyEncode(&Aes, buf, keySize); - return S_OK; -} - -/* -STDMETHODIMP CEncoder::WriteCoderProperties(ISequentialOutStream *outStream) -{ - Byte keySizeMode = 3; - return outStream->Write(&keySizeMode, 1, NULL); -} -*/ - -HRESULT CEncoder::WriteHeader(ISequentialOutStream *outStream) -{ - UInt32 saltSize = _key.GetSaltSize(); - g_RandomGenerator.Generate(_key.Salt, saltSize); - Init(); - RINOK(WriteStream(outStream, _key.Salt, saltSize)); - return WriteStream(outStream, _key.PwdVerifComputed, kPwdVerifCodeSize); -} - -HRESULT CEncoder::WriteFooter(ISequentialOutStream *outStream) -{ - Byte mac[kMacSize]; - _hmac.Final(mac, kMacSize); - return WriteStream(outStream, mac, kMacSize); -} - -STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte *data, UInt32 size) -{ - if (size != 1) - return E_INVALIDARG; - _key.Init(); - Byte keySizeMode = data[0]; - if (keySizeMode < 1 || keySizeMode > 3) - return E_INVALIDARG; - _key.KeySizeMode = keySizeMode; - return S_OK; -} - -HRESULT CDecoder::ReadHeader(ISequentialInStream *inStream) -{ - UInt32 saltSize = _key.GetSaltSize(); - UInt32 extraSize = saltSize + kPwdVerifCodeSize; - Byte temp[kSaltSizeMax + kPwdVerifCodeSize]; - RINOK(ReadStream_FAIL(inStream, temp, extraSize)); - UInt32 i; - for (i = 0; i < saltSize; i++) - _key.Salt[i] = temp[i]; - for (i = 0; i < kPwdVerifCodeSize; i++) - _pwdVerifFromArchive[i] = temp[saltSize + i]; - return S_OK; -} - -static bool CompareArrays(const Byte *p1, const Byte *p2, UInt32 size) -{ - for (UInt32 i = 0; i < size; i++) - if (p1[i] != p2[i]) - return false; - return true; -} - -bool CDecoder::CheckPasswordVerifyCode() -{ - return CompareArrays(_key.PwdVerifComputed, _pwdVerifFromArchive, kPwdVerifCodeSize); -} - -HRESULT CDecoder::CheckMac(ISequentialInStream *inStream, bool &isOK) -{ - isOK = false; - Byte mac1[kMacSize]; - RINOK(ReadStream_FAIL(inStream, mac1, kMacSize)); - Byte mac2[kMacSize]; - _hmac.Final(mac2, kMacSize); - isOK = CompareArrays(mac1, mac2, kMacSize); - return S_OK; -} - -STDMETHODIMP_(UInt32) CEncoder::Filter(Byte *data, UInt32 size) -{ - EncryptData(data, size); - _hmac.Update(data, size); - return size; -} - -STDMETHODIMP_(UInt32) CDecoder::Filter(Byte *data, UInt32 size) -{ - _hmac.Update(data, size); - EncryptData(data, size); - return size; -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Crypto/WzAes.h b/desmume/src/windows/7z/CPP/7zip/Crypto/WzAes.h deleted file mode 100644 index 8d68cc2f3..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Crypto/WzAes.h +++ /dev/null @@ -1,119 +0,0 @@ -// Crypto/WzAes.h -/* -This code implements Brian Gladman's scheme -specified in password Based File Encryption Utility: - - AES encryption (128,192,256-bit) in Counter (CTR) mode. - - HMAC-SHA1 authentication for encrypted data (10 bytes) - - Keys are derived by PPKDF2(RFC2898)-HMAC-SHA1 from ASCII password and - Salt (saltSize = aesKeySize / 2). - - 2 bytes contain Password Verifier's Code -*/ - -#ifndef __CRYPTO_WZ_AES_H -#define __CRYPTO_WZ_AES_H - -extern "C" -{ -#include "../../../C/Aes.h" -} - -#include "Common/Buffer.h" -#include "Common/MyCom.h" -#include "Common/MyVector.h" - -#include "../ICoder.h" -#include "../IPassword.h" - -#include "HmacSha1.h" - -namespace NCrypto { -namespace NWzAes { - -const unsigned int kSaltSizeMax = 16; -const unsigned int kMacSize = 10; - -const UInt32 kPasswordSizeMax = 99; // 128; - -// Password Verification Code Size -const unsigned int kPwdVerifCodeSize = 2; - -class CKeyInfo -{ -public: - Byte KeySizeMode; // 1 - 128-bit , 2 - 192-bit , 3 - 256-bit - Byte Salt[kSaltSizeMax]; - Byte PwdVerifComputed[kPwdVerifCodeSize]; - - CByteBuffer Password; - - UInt32 GetKeySize() const { return (8 * (KeySizeMode & 3) + 8); } - UInt32 GetSaltSize() const { return (4 * (KeySizeMode & 3) + 4); } - - CKeyInfo() { Init(); } - void Init() { KeySizeMode = 3; } -}; - -class CBaseCoder: - public ICompressFilter, - public ICryptoSetPassword, - public CMyUnknownImp -{ -protected: - CKeyInfo _key; - UInt32 _counter[AES_BLOCK_SIZE / 4]; - Byte _buffer[AES_BLOCK_SIZE]; - NSha1::CHmac _hmac; - unsigned int _blockPos; - Byte _pwdVerifFromArchive[kPwdVerifCodeSize]; - - void EncryptData(Byte *data, UInt32 size); - - CAes Aes; - -public: - STDMETHOD(Init)(); - STDMETHOD_(UInt32, Filter)(Byte *data, UInt32 size) = 0; - - STDMETHOD(CryptoSetPassword)(const Byte *data, UInt32 size); - - UInt32 GetHeaderSize() const { return _key.GetSaltSize() + kPwdVerifCodeSize; } -}; - -class CEncoder: - public CBaseCoder - // public ICompressWriteCoderProperties -{ -public: - MY_UNKNOWN_IMP1(ICryptoSetPassword) - // ICompressWriteCoderProperties - // STDMETHOD(WriteCoderProperties)(ISequentialOutStream *outStream); - STDMETHOD_(UInt32, Filter)(Byte *data, UInt32 size); - HRESULT WriteHeader(ISequentialOutStream *outStream); - HRESULT WriteFooter(ISequentialOutStream *outStream); - bool SetKeyMode(Byte mode) - { - if (mode < 1 || mode > 3) - return false; - _key.KeySizeMode = mode; - return true; - } -}; - -class CDecoder: - public CBaseCoder, - public ICompressSetDecoderProperties2 -{ -public: - MY_UNKNOWN_IMP2( - ICryptoSetPassword, - ICompressSetDecoderProperties2) - STDMETHOD_(UInt32, Filter)(Byte *data, UInt32 size); - STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size); - HRESULT ReadHeader(ISequentialInStream *inStream); - bool CheckPasswordVerifyCode(); - HRESULT CheckMac(ISequentialInStream *inStream, bool &isOK); -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Crypto/ZipCrypto.cpp b/desmume/src/windows/7z/CPP/7zip/Crypto/ZipCrypto.cpp deleted file mode 100644 index b699d8950..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Crypto/ZipCrypto.cpp +++ /dev/null @@ -1,131 +0,0 @@ -// Crypto/ZipCrypto.cpp - -#include "StdAfx.h" - -extern "C" -{ -#include "../../../C/7zCrc.h" -} - -#include "../Common/StreamUtils.h" - -#include "RandGen.h" -#include "ZipCrypto.h" - -namespace NCrypto { -namespace NZip { - -void CCipher::UpdateKeys(Byte b) -{ - Keys[0] = CRC_UPDATE_BYTE(Keys[0], b); - Keys[1] += Keys[0] & 0xff; - Keys[1] = Keys[1] * 134775813L + 1; - Keys[2] = CRC_UPDATE_BYTE(Keys[2], (Byte)(Keys[1] >> 24)); -} - -void CCipher::SetPassword(const Byte *password, UInt32 passwordLen) -{ - Keys[0] = 305419896L; - Keys[1] = 591751049L; - Keys[2] = 878082192L; - for (UInt32 i = 0; i < passwordLen; i++) - UpdateKeys(password[i]); -} - -Byte CCipher::DecryptByteSpec() -{ - UInt32 temp = Keys[2] | 2; - return (Byte)((temp * (temp ^ 1)) >> 8); -} - -Byte CCipher::DecryptByte(Byte b) -{ - Byte c = (Byte)(b ^ DecryptByteSpec()); - UpdateKeys(c); - return c; -} - -Byte CCipher::EncryptByte(Byte b) -{ - Byte c = (Byte)(b ^ DecryptByteSpec()); - UpdateKeys(b); - return c; -} - -void CCipher::DecryptHeader(Byte *buf) -{ - for (unsigned i = 0; i < kHeaderSize; i++) - buf[i] = DecryptByte(buf[i]); -} - -void CCipher::EncryptHeader(Byte *buf) -{ - for (unsigned i = 0; i < kHeaderSize; i++) - buf[i] = EncryptByte(buf[i]); -} - -STDMETHODIMP CEncoder::CryptoSetPassword(const Byte *data, UInt32 size) -{ - _cipher.SetPassword(data, size); - return S_OK; -} - -STDMETHODIMP CEncoder::CryptoSetCRC(UInt32 crc) -{ - _crc = crc; - return S_OK; -} - -STDMETHODIMP CEncoder::Init() -{ - return S_OK; -} - -HRESULT CEncoder::WriteHeader(ISequentialOutStream *outStream) -{ - Byte header[kHeaderSize]; - g_RandomGenerator.Generate(header, kHeaderSize - 2); - - header[kHeaderSize - 1] = Byte(_crc >> 24); - header[kHeaderSize - 2] = Byte(_crc >> 16); - - _cipher.EncryptHeader(header); - return WriteStream(outStream, header, kHeaderSize); -} - -STDMETHODIMP_(UInt32) CEncoder::Filter(Byte *data, UInt32 size) -{ - UInt32 i; - for (i = 0; i < size; i++) - data[i] = _cipher.EncryptByte(data[i]); - return i; -} - -STDMETHODIMP CDecoder::CryptoSetPassword(const Byte *data, UInt32 size) -{ - _cipher.SetPassword(data, size); - return S_OK; -} - -HRESULT CDecoder::ReadHeader(ISequentialInStream *inStream) -{ - Byte header[kHeaderSize]; - RINOK(ReadStream_FAIL(inStream, header, kHeaderSize)); - _cipher.DecryptHeader(header); - return S_OK; -} - -STDMETHODIMP CDecoder::Init() -{ - return S_OK; -} - -STDMETHODIMP_(UInt32) CDecoder::Filter(Byte *data, UInt32 size) -{ - UInt32 i; - for (i = 0; i < size; i++) - data[i] = _cipher.DecryptByte(data[i]); - return i; -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Crypto/ZipCrypto.h b/desmume/src/windows/7z/CPP/7zip/Crypto/ZipCrypto.h deleted file mode 100644 index 2f8f335ae..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Crypto/ZipCrypto.h +++ /dev/null @@ -1,71 +0,0 @@ -// Crypto/ZipCrypto.h - -#ifndef __CRYPTO_ZIP_CRYPTO_H -#define __CRYPTO_ZIP_CRYPTO_H - -#include "Common/MyCom.h" - -#include "../ICoder.h" -#include "../IPassword.h" - -namespace NCrypto { -namespace NZip { - -const unsigned kHeaderSize = 12; - -class CCipher -{ - UInt32 Keys[3]; - - void UpdateKeys(Byte b); - Byte DecryptByteSpec(); -public: - void SetPassword(const Byte *password, UInt32 passwordLen); - Byte DecryptByte(Byte b); - Byte EncryptByte(Byte b); - void DecryptHeader(Byte *buf); - void EncryptHeader(Byte *buf); -}; - -class CEncoder : - public ICompressFilter, - public ICryptoSetPassword, - public ICryptoSetCRC, - public CMyUnknownImp -{ - CCipher _cipher; - UInt32 _crc; -public: - MY_UNKNOWN_IMP2( - ICryptoSetPassword, - ICryptoSetCRC - ) - STDMETHOD(Init)(); - STDMETHOD_(UInt32, Filter)(Byte *data, UInt32 size); - - STDMETHOD(CryptoSetPassword)(const Byte *data, UInt32 size); - STDMETHOD(CryptoSetCRC)(UInt32 crc); - HRESULT WriteHeader(ISequentialOutStream *outStream); -}; - - -class CDecoder: - public ICompressFilter, - public ICryptoSetPassword, - public CMyUnknownImp -{ - CCipher _cipher; -public: - MY_UNKNOWN_IMP1(ICryptoSetPassword) - - STDMETHOD(Init)(); - STDMETHOD_(UInt32, Filter)(Byte *data, UInt32 size); - STDMETHOD(CryptoSetPassword)(const Byte *data, UInt32 size); - - HRESULT ReadHeader(ISequentialInStream *inStream); -}; - - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Crypto/ZipStrong.cpp b/desmume/src/windows/7z/CPP/7zip/Crypto/ZipStrong.cpp deleted file mode 100644 index 2302450f5..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Crypto/ZipStrong.cpp +++ /dev/null @@ -1,180 +0,0 @@ -// Crypto/ZipStrong.cpp - -#include "StdAfx.h" - -extern "C" -{ -#include "../../../C/7zCrc.h" -#include "../../../C/CpuArch.h" -} - -#include "../Common/StreamUtils.h" - -#include "MyAES.h" -#include "Sha1.h" -#include "ZipStrong.h" - -namespace NCrypto { -namespace NZipStrong { - -static const UInt16 kAES128 = 0x660E; - -// DeriveKey* function is similar to CryptDeriveKey() from Windows. -// But MSDN tells that we need such scheme only if -// "the required key length is longer than the hash value" -// but ZipStrong uses it always. - -static void DeriveKey2(const Byte *digest, Byte c, Byte *dest) -{ - Byte buf[64]; - memset(buf, c, 64); - for (unsigned i = 0; i < NSha1::kDigestSize; i++) - buf[i] ^= digest[i]; - NSha1::CContext sha; - sha.Init(); - sha.Update(buf, 64); - sha.Final(dest); -} - -static void DeriveKey(NSha1::CContext &sha, Byte *key) -{ - Byte digest[NSha1::kDigestSize]; - sha.Final(digest); - Byte temp[NSha1::kDigestSize * 2]; - DeriveKey2(digest, 0x36, temp); - DeriveKey2(digest, 0x5C, temp + NSha1::kDigestSize); - memcpy(key, temp, 32); -} - -void CKeyInfo::SetPassword(const Byte *data, UInt32 size) -{ - NSha1::CContext sha; - sha.Init(); - sha.Update(data, size); - DeriveKey(sha, MasterKey); -} - -STDMETHODIMP CBaseCoder::CryptoSetPassword(const Byte *data, UInt32 size) -{ - _key.SetPassword(data, size); - return S_OK; -} - -STDMETHODIMP CBaseCoder::Init() -{ - return S_OK; -} - -HRESULT CDecoder::ReadHeader(ISequentialInStream *inStream, UInt32 /* crc */, UInt64 /* unpackSize */) -{ - Byte temp[4]; - RINOK(ReadStream_FALSE(inStream, temp, 2)); - _ivSize = GetUi16(temp); - if (_ivSize == 0) - { - return E_NOTIMPL; - /* - SetUi32(_iv, crc); - for (int i = 0; i < 8; i++) - _iv[4 + i] = (Byte)(unpackSize >> (8 * i)); - SetUi32(_iv + 12, 0); - */ - } - else if (_ivSize == 16) - { - RINOK(ReadStream_FALSE(inStream, _iv, _ivSize)); - } - else - return E_NOTIMPL; - RINOK(ReadStream_FALSE(inStream, temp, 4)); - _remSize = GetUi32(temp); - if (_remSize > _buf.GetCapacity()) - { - _buf.Free(); - _buf.SetCapacity(_remSize); - } - return ReadStream_FALSE(inStream, _buf, _remSize); -} - -HRESULT CDecoder::CheckPassword(bool &passwOK) -{ - passwOK = false; - if (_remSize < 10) - return E_NOTIMPL; - Byte *p = _buf; - UInt16 format = GetUi16(p); - if (format != 3) - return E_NOTIMPL; - UInt16 algId = GetUi16(p + 2); - if (algId < kAES128) - return E_NOTIMPL; - algId -= kAES128; - if (algId > 2) - return E_NOTIMPL; - UInt16 bitLen = GetUi16(p + 4); - UInt16 flags = GetUi16(p + 6); - if (algId * 64 + 128 != bitLen) - return E_NOTIMPL; - _key.KeySize = 16 + algId * 8; - if ((flags & 1) == 0) - return E_NOTIMPL; - UInt32 rdSize = GetUi16(p + 8); - UInt32 pos = 10; - Byte *rd = p + pos; - pos += rdSize; - if (pos + 4 > _remSize) - return E_NOTIMPL; - UInt32 reserved = GetUi32(p + pos); - pos += 4; - if (reserved != 0) - return E_NOTIMPL; - if (pos + 2 > _remSize) - return E_NOTIMPL; - UInt32 validSize = GetUi16(p + pos); - pos += 2; - Byte *validData = p + pos; - if (pos + validSize != _remSize) - return E_NOTIMPL; - - if (!_aesFilter) - _aesFilter = new CAesCbcDecoder; - - CMyComPtr cp; - RINOK(_aesFilter.QueryInterface(IID_ICryptoProperties, &cp)); - { - RINOK(cp->SetKey(_key.MasterKey, _key.KeySize)); - RINOK(cp->SetInitVector(_iv, 16)); - _aesFilter->Init(); - if (_aesFilter->Filter(rd, rdSize) != rdSize) - return E_NOTIMPL; - } - - Byte fileKey[32]; - NSha1::CContext sha; - sha.Init(); - sha.Update(_iv, 16); - sha.Update(rd, rdSize - 16); // we don't use last 16 bytes (PAD bytes) - DeriveKey(sha, fileKey); - - RINOK(cp->SetKey(fileKey, _key.KeySize)); - RINOK(cp->SetInitVector(_iv, 16)); - _aesFilter->Init(); - if (_aesFilter->Filter(validData, validSize) != validSize) - return E_NOTIMPL; - - if (validSize < 4) - return E_NOTIMPL; - validSize -= 4; - if (GetUi32(validData + validSize) != CrcCalc(validData, validSize)) - return S_OK; - passwOK = true; - _aesFilter->Init(); - return S_OK; -} - -STDMETHODIMP_(UInt32) CDecoder::Filter(Byte *data, UInt32 size) -{ - return _aesFilter->Filter(data, size); -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Crypto/ZipStrong.h b/desmume/src/windows/7z/CPP/7zip/Crypto/ZipStrong.h deleted file mode 100644 index 33adbaa2a..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Crypto/ZipStrong.h +++ /dev/null @@ -1,53 +0,0 @@ -// Crypto/ZipStrong.h - -#ifndef __CRYPTO_ZIP_STRONG_H -#define __CRYPTO_ZIP_STRONG_H - -#include "Common/MyCom.h" -#include "Common/Buffer.h" - -#include "../ICoder.h" -#include "../IPassword.h" - -namespace NCrypto { -namespace NZipStrong { - -struct CKeyInfo -{ - Byte MasterKey[32]; - UInt32 KeySize; - void SetPassword(const Byte *data, UInt32 size); -}; - -class CBaseCoder: - public ICompressFilter, - public ICryptoSetPassword, - public CMyUnknownImp -{ -protected: - CKeyInfo _key; - CMyComPtr _aesFilter; - CByteBuffer _buf; -public: - STDMETHOD(Init)(); - STDMETHOD_(UInt32, Filter)(Byte *data, UInt32 size) = 0; - - STDMETHOD(CryptoSetPassword)(const Byte *data, UInt32 size); -}; - -class CDecoder: - public CBaseCoder -{ - UInt32 _ivSize; - Byte _iv[16]; - UInt32 _remSize; -public: - MY_UNKNOWN_IMP1(ICryptoSetPassword) - STDMETHOD_(UInt32, Filter)(Byte *data, UInt32 size); - HRESULT ReadHeader(ISequentialInStream *inStream, UInt32 crc, UInt64 unpackSize); - HRESULT CheckPassword(bool &passwOK); -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/ICoder.h b/desmume/src/windows/7z/CPP/7zip/ICoder.h deleted file mode 100644 index 150118c2c..000000000 --- a/desmume/src/windows/7z/CPP/7zip/ICoder.h +++ /dev/null @@ -1,186 +0,0 @@ -// ICoder.h - -#ifndef __ICODER_H -#define __ICODER_H - -#include "IStream.h" - -#define CODER_INTERFACE(i, x) DECL_INTERFACE(i, 4, x) - -CODER_INTERFACE(ICompressProgressInfo, 0x04) -{ - STDMETHOD(SetRatioInfo)(const UInt64 *inSize, const UInt64 *outSize) PURE; -}; - -CODER_INTERFACE(ICompressCoder, 0x05) -{ - STDMETHOD(Code)(ISequentialInStream *inStream, - ISequentialOutStream *outStream, - const UInt64 *inSize, - const UInt64 *outSize, - ICompressProgressInfo *progress) PURE; -}; - -CODER_INTERFACE(ICompressCoder2, 0x18) -{ - STDMETHOD(Code)(ISequentialInStream **inStreams, - const UInt64 **inSizes, - UInt32 numInStreams, - ISequentialOutStream **outStreams, - const UInt64 **outSizes, - UInt32 numOutStreams, - ICompressProgressInfo *progress) PURE; -}; - -namespace NCoderPropID -{ - enum EEnum - { - kDictionarySize = 0x400, - kUsedMemorySize, - kOrder, - kBlockSize, - kPosStateBits = 0x440, - kLitContextBits, - kLitPosBits, - kNumFastBytes = 0x450, - kMatchFinder, - kMatchFinderCycles, - kNumPasses = 0x460, - kAlgorithm = 0x470, - kMultiThread = 0x480, - kNumThreads, - kEndMarker = 0x490 - }; -} - -CODER_INTERFACE(ICompressSetCoderProperties, 0x20) -{ - STDMETHOD(SetCoderProperties)(const PROPID *propIDs, - const PROPVARIANT *properties, UInt32 numProperties) PURE; -}; - -/* -CODER_INTERFACE(ICompressSetCoderProperties, 0x21) -{ - STDMETHOD(SetDecoderProperties)(ISequentialInStream *inStream) PURE; -}; -*/ - -CODER_INTERFACE(ICompressSetDecoderProperties2, 0x22) -{ - STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size) PURE; -}; - -CODER_INTERFACE(ICompressWriteCoderProperties, 0x23) -{ - STDMETHOD(WriteCoderProperties)(ISequentialOutStream *outStreams) PURE; -}; - -CODER_INTERFACE(ICompressGetInStreamProcessedSize, 0x24) -{ - STDMETHOD(GetInStreamProcessedSize)(UInt64 *value) PURE; -}; - -CODER_INTERFACE(ICompressSetCoderMt, 0x25) -{ - STDMETHOD(SetNumberOfThreads)(UInt32 numThreads) PURE; -}; - -CODER_INTERFACE(ICompressGetSubStreamSize, 0x30) -{ - STDMETHOD(GetSubStreamSize)(UInt64 subStream, UInt64 *value) PURE; -}; - -CODER_INTERFACE(ICompressSetInStream, 0x31) -{ - STDMETHOD(SetInStream)(ISequentialInStream *inStream) PURE; - STDMETHOD(ReleaseInStream)() PURE; -}; - -CODER_INTERFACE(ICompressSetOutStream, 0x32) -{ - STDMETHOD(SetOutStream)(ISequentialOutStream *outStream) PURE; - STDMETHOD(ReleaseOutStream)() PURE; -}; - -CODER_INTERFACE(ICompressSetInStreamSize, 0x33) -{ - STDMETHOD(SetInStreamSize)(const UInt64 *inSize) PURE; -}; - -CODER_INTERFACE(ICompressSetOutStreamSize, 0x34) -{ - STDMETHOD(SetOutStreamSize)(const UInt64 *outSize) PURE; -}; - -CODER_INTERFACE(ICompressFilter, 0x40) -{ - STDMETHOD(Init)() PURE; - STDMETHOD_(UInt32, Filter)(Byte *data, UInt32 size) PURE; - // Filter return outSize (UInt32) - // if (outSize <= size): Filter have converted outSize bytes - // if (outSize > size): Filter have not converted anything. - // and it needs at least outSize bytes to convert one block - // (it's for crypto block algorithms). -}; - -CODER_INTERFACE(ICompressCodecsInfo, 0x60) -{ - STDMETHOD(GetNumberOfMethods)(UInt32 *numMethods) PURE; - STDMETHOD(GetProperty)(UInt32 index, PROPID propID, PROPVARIANT *value) PURE; - STDMETHOD(CreateDecoder)(UInt32 index, const GUID *iid, void **coder) PURE; - STDMETHOD(CreateEncoder)(UInt32 index, const GUID *iid, void **coder) PURE; -}; -CODER_INTERFACE(ISetCompressCodecsInfo, 0x61) -{ - STDMETHOD(SetCompressCodecsInfo)(ICompressCodecsInfo *compressCodecsInfo) PURE; -}; - -CODER_INTERFACE(ICryptoProperties, 0x80) -{ - STDMETHOD(SetKey)(const Byte *data, UInt32 size) PURE; - STDMETHOD(SetInitVector)(const Byte *data, UInt32 size) PURE; -}; - -/* -CODER_INTERFACE(ICryptoResetSalt, 0x88) -{ - STDMETHOD(ResetSalt)() PURE; -}; -*/ - -CODER_INTERFACE(ICryptoResetInitVector, 0x8C) -{ - STDMETHOD(ResetInitVector)() PURE; -}; - -CODER_INTERFACE(ICryptoSetPassword, 0x90) -{ - STDMETHOD(CryptoSetPassword)(const Byte *data, UInt32 size) PURE; -}; - -CODER_INTERFACE(ICryptoSetCRC, 0xA0) -{ - STDMETHOD(CryptoSetCRC)(UInt32 crc) PURE; -}; - -////////////////////// -// It's for DLL file -namespace NMethodPropID -{ - enum EEnum - { - kID, - kName, - kDecoder, - kEncoder, - kInStreams, - kOutStreams, - kDescription, - kDecoderIsAssigned, - kEncoderIsAssigned - }; -} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/IDecl.h b/desmume/src/windows/7z/CPP/7zip/IDecl.h deleted file mode 100644 index 768bbe710..000000000 --- a/desmume/src/windows/7z/CPP/7zip/IDecl.h +++ /dev/null @@ -1,15 +0,0 @@ -// IDecl.h - -#ifndef __IDECL_H -#define __IDECL_H - -#include "../Common/MyUnknown.h" - -#define DECL_INTERFACE_SUB(i, base, groupId, subId) \ -DEFINE_GUID(IID_ ## i, \ -0x23170F69, 0x40C1, 0x278A, 0, 0, 0, (groupId), 0, (subId), 0, 0); \ -struct i: public base - -#define DECL_INTERFACE(i, groupId, subId) DECL_INTERFACE_SUB(i, IUnknown, groupId, subId) - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/IPassword.h b/desmume/src/windows/7z/CPP/7zip/IPassword.h deleted file mode 100644 index 5679d84ce..000000000 --- a/desmume/src/windows/7z/CPP/7zip/IPassword.h +++ /dev/null @@ -1,24 +0,0 @@ -// IPassword.h - -#ifndef __IPASSWORD_H -#define __IPASSWORD_H - -#include "../Common/MyUnknown.h" -#include "../Common/Types.h" - -#include "IDecl.h" - -#define PASSWORD_INTERFACE(i, x) DECL_INTERFACE(i, 5, x) - -PASSWORD_INTERFACE(ICryptoGetTextPassword, 0x10) -{ - STDMETHOD(CryptoGetTextPassword)(BSTR *password) PURE; -}; - -PASSWORD_INTERFACE(ICryptoGetTextPassword2, 0x11) -{ - STDMETHOD(CryptoGetTextPassword2)(Int32 *passwordIsDefined, BSTR *password) PURE; -}; - -#endif - diff --git a/desmume/src/windows/7z/CPP/7zip/IProgress.h b/desmume/src/windows/7z/CPP/7zip/IProgress.h deleted file mode 100644 index 09486baf3..000000000 --- a/desmume/src/windows/7z/CPP/7zip/IProgress.h +++ /dev/null @@ -1,33 +0,0 @@ -// Interface/IProgress.h - -#ifndef __IPROGRESS_H -#define __IPROGRESS_H - -#include "../Common/MyUnknown.h" -#include "../Common/Types.h" - -#include "IDecl.h" - -#define INTERFACE_IProgress(x) \ - STDMETHOD(SetTotal)(UInt64 total) x; \ - STDMETHOD(SetCompleted)(const UInt64 *completeValue) x; \ - -DECL_INTERFACE(IProgress, 0, 5) -{ - INTERFACE_IProgress(PURE) -}; - -/* -// {23170F69-40C1-278A-0000-000000050002} -DEFINE_GUID(IID_IProgress2, -0x23170F69, 0x40C1, 0x278A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x02); -MIDL_INTERFACE("23170F69-40C1-278A-0000-000000050002") -IProgress2: public IUnknown -{ -public: - STDMETHOD(SetTotal)(const UInt64 *total) PURE; - STDMETHOD(SetCompleted)(const UInt64 *completeValue) PURE; -}; -*/ - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/IStream.h b/desmume/src/windows/7z/CPP/7zip/IStream.h deleted file mode 100644 index d5ed723fe..000000000 --- a/desmume/src/windows/7z/CPP/7zip/IStream.h +++ /dev/null @@ -1,58 +0,0 @@ -// IStream.h - -#ifndef __ISTREAM_H -#define __ISTREAM_H - -#include "../Common/MyUnknown.h" -#include "../Common/Types.h" - -#include "IDecl.h" - -#define STREAM_INTERFACE_SUB(i, base, x) DECL_INTERFACE_SUB(i, base, 3, x) -#define STREAM_INTERFACE(i, x) STREAM_INTERFACE_SUB(i, IUnknown, x) - -STREAM_INTERFACE(ISequentialInStream, 0x01) -{ - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize) PURE; - /* - Out: if size != 0, return_value = S_OK and (*processedSize == 0), - then there are no more bytes in stream. - if (size > 0) && there are bytes in stream, - this function must read at least 1 byte. - This function is allowed to read less than number of remaining bytes in stream. - You must call Read function in loop, if you need exact amount of data - */ -}; - -STREAM_INTERFACE(ISequentialOutStream, 0x02) -{ - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize) PURE; - /* - if (size > 0) this function must write at least 1 byte. - This function is allowed to write less than "size". - You must call Write function in loop, if you need to write exact amount of data - */ -}; - -STREAM_INTERFACE_SUB(IInStream, ISequentialInStream, 0x03) -{ - STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) PURE; -}; - -STREAM_INTERFACE_SUB(IOutStream, ISequentialOutStream, 0x04) -{ - STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) PURE; - STDMETHOD(SetSize)(Int64 newSize) PURE; -}; - -STREAM_INTERFACE(IStreamGetSize, 0x06) -{ - STDMETHOD(GetSize)(UInt64 *size) PURE; -}; - -STREAM_INTERFACE(IOutStreamFlush, 0x07) -{ - STDMETHOD(Flush)() PURE; -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/PropID.h b/desmume/src/windows/7z/CPP/7zip/PropID.h deleted file mode 100644 index 695f80295..000000000 --- a/desmume/src/windows/7z/CPP/7zip/PropID.h +++ /dev/null @@ -1,69 +0,0 @@ -// PropID.h - -#ifndef __7ZIP_PROPID_H -#define __7ZIP_PROPID_H - -enum -{ - kpidNoProperty = 0, - - kpidHandlerItemIndex = 2, - kpidPath, - kpidName, - kpidExtension, - kpidIsDir, - kpidSize, - kpidPackSize, - kpidAttrib, - kpidCTime, - kpidATime, - kpidMTime, - kpidSolid, - kpidCommented, - kpidEncrypted, - kpidSplitBefore, - kpidSplitAfter, - kpidDictionarySize, - kpidCRC, - kpidType, - kpidIsAnti, - kpidMethod, - kpidHostOS, - kpidFileSystem, - kpidUser, - kpidGroup, - kpidBlock, - kpidComment, - kpidPosition, - kpidPrefix, - kpidNumSubDirs, - kpidNumSubFiles, - kpidUnpackVer, - kpidVolume, - kpidIsVolume, - kpidOffset, - kpidLinks, - kpidNumBlocks, - kpidNumVolumes, - kpidTimeType, - kpidBit64, - kpidBigEndian, - kpidCpu, - kpidPhySize, - kpidHeadersSize, - kpidChecksum, - kpidCharacts, - kpidVa, - - kpidTotalSize = 0x1100, - kpidFreeSpace, - kpidClusterSize, - kpidVolumeName, - - kpidLocalName = 0x1200, - kpidProvider, - - kpidUserDefined = 0x10000 -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/Common/Buffer.h b/desmume/src/windows/7z/CPP/Common/Buffer.h deleted file mode 100644 index b0959eddb..000000000 --- a/desmume/src/windows/7z/CPP/Common/Buffer.h +++ /dev/null @@ -1,77 +0,0 @@ -// Common/Buffer.h - -#ifndef __COMMON_BUFFER_H -#define __COMMON_BUFFER_H - -#include "Defs.h" - -template class CBuffer -{ -protected: - size_t _capacity; - T *_items; -public: - void Free() - { - delete []_items; - _items = 0; - _capacity = 0; - } - CBuffer(): _capacity(0), _items(0) {}; - CBuffer(const CBuffer &buffer): _capacity(0), _items(0) { *this = buffer; } - CBuffer(size_t size): _items(0), _capacity(0) { SetCapacity(size); } - virtual ~CBuffer() { delete []_items; } - operator T *() { return _items; }; - operator const T *() const { return _items; }; - size_t GetCapacity() const { return _capacity; } - void SetCapacity(size_t newCapacity) - { - if (newCapacity == _capacity) - return; - T *newBuffer; - if (newCapacity > 0) - { - newBuffer = new T[newCapacity]; - if (_capacity > 0) - memmove(newBuffer, _items, MyMin(_capacity, newCapacity) * sizeof(T)); - } - else - newBuffer = 0; - delete []_items; - _items = newBuffer; - _capacity = newCapacity; - } - CBuffer& operator=(const CBuffer &buffer) - { - Free(); - if (buffer._capacity > 0) - { - SetCapacity(buffer._capacity); - memmove(_items, buffer._items, buffer._capacity * sizeof(T)); - } - return *this; - } -}; - -template -bool operator==(const CBuffer& b1, const CBuffer& b2) -{ - if (b1.GetCapacity() != b2.GetCapacity()) - return false; - for (size_t i = 0; i < b1.GetCapacity(); i++) - if (b1[i] != b2[i]) - return false; - return true; -} - -template -bool operator!=(const CBuffer& b1, const CBuffer& b2) -{ - return !(b1 == b2); -} - -typedef CBuffer CCharBuffer; -typedef CBuffer CWCharBuffer; -typedef CBuffer CByteBuffer; - -#endif diff --git a/desmume/src/windows/7z/CPP/Common/CRC.cpp b/desmume/src/windows/7z/CPP/Common/CRC.cpp deleted file mode 100644 index 987b8a03a..000000000 --- a/desmume/src/windows/7z/CPP/Common/CRC.cpp +++ /dev/null @@ -1,10 +0,0 @@ -// Common/CRC.cpp - -#include "StdAfx.h" - -extern "C" -{ -#include "../../C/7zCrc.h" -} - -struct CCRCTableInit { CCRCTableInit() { CrcGenerateTable(); } } g_CRCTableInit; diff --git a/desmume/src/windows/7z/CPP/Common/ComTry.h b/desmume/src/windows/7z/CPP/Common/ComTry.h deleted file mode 100644 index 98e592766..000000000 --- a/desmume/src/windows/7z/CPP/Common/ComTry.h +++ /dev/null @@ -1,17 +0,0 @@ -// ComTry.h - -#ifndef __COM_TRY_H -#define __COM_TRY_H - -#include "MyWindows.h" -// #include "Exception.h" -// #include "NewHandler.h" - -#define COM_TRY_BEGIN try { -#define COM_TRY_END } catch(...) { return E_OUTOFMEMORY; } - - // catch(const CNewException &) { return E_OUTOFMEMORY; }\ - // catch(const CSystemException &e) { return e.ErrorCode; }\ - // catch(...) { return E_FAIL; } - -#endif diff --git a/desmume/src/windows/7z/CPP/Common/Defs.h b/desmume/src/windows/7z/CPP/Common/Defs.h deleted file mode 100644 index 69b8ecea8..000000000 --- a/desmume/src/windows/7z/CPP/Common/Defs.h +++ /dev/null @@ -1,20 +0,0 @@ -// Common/Defs.h - -#ifndef __COMMON_DEFS_H -#define __COMMON_DEFS_H - -template inline T MyMin(T a, T b) - { return a < b ? a : b; } -template inline T MyMax(T a, T b) - { return a > b ? a : b; } - -template inline int MyCompare(T a, T b) - { return a < b ? -1 : (a == b ? 0 : 1); } - -inline int BoolToInt(bool value) - { return (value ? 1: 0); } - -inline bool IntToBool(int value) - { return (value != 0); } - -#endif diff --git a/desmume/src/windows/7z/CPP/Common/DynamicBuffer.h b/desmume/src/windows/7z/CPP/Common/DynamicBuffer.h deleted file mode 100644 index 83ef0ea2c..000000000 --- a/desmume/src/windows/7z/CPP/Common/DynamicBuffer.h +++ /dev/null @@ -1,47 +0,0 @@ -// Common/DynamicBuffer.h - -#ifndef __COMMON_DYNAMICBUFFER_H -#define __COMMON_DYNAMICBUFFER_H - -#include "Buffer.h" - -template class CDynamicBuffer: public CBuffer -{ - void GrowLength(size_t size) - { - size_t delta; - if (this->_capacity > 64) - delta = this->_capacity / 4; - else if (this->_capacity > 8) - delta = 16; - else - delta = 4; - delta = MyMax(delta, size); - SetCapacity(this->_capacity + delta); - } -public: - CDynamicBuffer(): CBuffer() {}; - CDynamicBuffer(const CDynamicBuffer &buffer): CBuffer(buffer) {}; - CDynamicBuffer(size_t size): CBuffer(size) {}; - CDynamicBuffer& operator=(const CDynamicBuffer &buffer) - { - this->Free(); - if (buffer._capacity > 0) - { - SetCapacity(buffer._capacity); - memmove(this->_items, buffer._items, buffer._capacity * sizeof(T)); - } - return *this; - } - void EnsureCapacity(size_t capacity) - { - if (this->_capacity < capacity) - GrowLength(capacity - this->_capacity); - } -}; - -typedef CDynamicBuffer CCharDynamicBuffer; -typedef CDynamicBuffer CWCharDynamicBuffer; -typedef CDynamicBuffer CByteDynamicBuffer; - -#endif diff --git a/desmume/src/windows/7z/CPP/Common/InitializeStaticLib.h b/desmume/src/windows/7z/CPP/Common/InitializeStaticLib.h deleted file mode 100644 index a0d70b6fd..000000000 --- a/desmume/src/windows/7z/CPP/Common/InitializeStaticLib.h +++ /dev/null @@ -1,29 +0,0 @@ -// Common/InitializeStaticLib.h -// -// it's necessary to include this from one cpp file in order to use 7zip as a static library, -// otherwise the linker will optimize away some important internals of 7zip. - -#ifndef __COMMON_INITIALIZESTATICLIB_H -#define __COMMON_INITIALIZESTATICLIB_H - -#define FORCE_REF(dec, var) extern dec var; void* var##ref = (void*)&var; - -#include "../7zip/Common/DeclareCodecs.h" -#include "../7zip/Common/DeclareArcs.h" - -FORCE_REF(struct CCRCTableInit, g_CRCTableInit) - - -// these don't seem to be necessary with my compiler, -// but they're here in case a different compiler more aggressively strips out unreferenced code -FORCE_REF(class CBZip2CrcTableInit, g_BZip2CrcTableInit) -namespace NCrypto { struct CAesTabInit; FORCE_REF(CAesTabInit, g_AesTabInit) } -namespace NBitl { struct CInverterTableInitializer; FORCE_REF(CInverterTableInitializer, g_InverterTableInitializer) } -namespace NCompress { namespace NRar3 { class CDistInit; FORCE_REF(CDistInit, g_DistInit) }} -namespace NArchive { namespace NLzh { class CCRCTableInit; FORCE_REF(CCRCTableInit, g_CRCTableInit) }} -namespace NArchive { namespace N7z { class SignatureInitializer; FORCE_REF(SignatureInitializer, g_SignatureInitializer) }} -namespace NArchive{ namespace NRar{ namespace NHeader{ class CMarkerInitializer; FORCE_REF(CMarkerInitializer, g_MarkerInitializer) }}} -namespace NArchive { namespace NZip { namespace NSignature{ class CMarkersInitializer; FORCE_REF(CMarkersInitializer, g_MarkerInitializer) }}} - - -#endif diff --git a/desmume/src/windows/7z/CPP/Common/IntToString.cpp b/desmume/src/windows/7z/CPP/Common/IntToString.cpp deleted file mode 100644 index f0a499d6b..000000000 --- a/desmume/src/windows/7z/CPP/Common/IntToString.cpp +++ /dev/null @@ -1,63 +0,0 @@ -// Common/IntToString.cpp - -#include "StdAfx.h" - -#include "IntToString.h" - -void ConvertUInt64ToString(UInt64 value, char *s, UInt32 base) -{ - if (base < 2 || base > 36) - { - *s = '\0'; - return; - } - char temp[72]; - int pos = 0; - do - { - int delta = (int)(value % base); - temp[pos++] = (char)((delta < 10) ? ('0' + delta) : ('a' + (delta - 10))); - value /= base; - } - while (value != 0); - do - *s++ = temp[--pos]; - while (pos > 0); - *s = '\0'; -} - -void ConvertUInt64ToString(UInt64 value, wchar_t *s) -{ - wchar_t temp[32]; - int pos = 0; - do - { - temp[pos++] = (wchar_t)(L'0' + (int)(value % 10)); - value /= 10; - } - while (value != 0); - do - *s++ = temp[--pos]; - while (pos > 0); - *s = L'\0'; -} - -void ConvertInt64ToString(Int64 value, char *s) -{ - if (value < 0) - { - *s++ = '-'; - value = -value; - } - ConvertUInt64ToString(value, s); -} - -void ConvertInt64ToString(Int64 value, wchar_t *s) -{ - if (value < 0) - { - *s++ = L'-'; - value = -value; - } - ConvertUInt64ToString(value, s); -} diff --git a/desmume/src/windows/7z/CPP/Common/IntToString.h b/desmume/src/windows/7z/CPP/Common/IntToString.h deleted file mode 100644 index 2f50ba95a..000000000 --- a/desmume/src/windows/7z/CPP/Common/IntToString.h +++ /dev/null @@ -1,15 +0,0 @@ -// Common/IntToString.h - -#ifndef __COMMON_INTTOSTRING_H -#define __COMMON_INTTOSTRING_H - -#include -#include "Types.h" - -void ConvertUInt64ToString(UInt64 value, char *s, UInt32 base = 10); -void ConvertUInt64ToString(UInt64 value, wchar_t *s); - -void ConvertInt64ToString(Int64 value, char *s); -void ConvertInt64ToString(Int64 value, wchar_t *s); - -#endif diff --git a/desmume/src/windows/7z/CPP/Common/MyCom.h b/desmume/src/windows/7z/CPP/Common/MyCom.h deleted file mode 100644 index d04fa4c3d..000000000 --- a/desmume/src/windows/7z/CPP/Common/MyCom.h +++ /dev/null @@ -1,225 +0,0 @@ -// MyCom.h - -#ifndef __MYCOM_H -#define __MYCOM_H - -#include "MyWindows.h" - -#ifndef RINOK -#define RINOK(x) { HRESULT __result_ = (x); if (__result_ != S_OK) return __result_; } -#endif - -template -class CMyComPtr -{ - T* _p; -public: - // typedef T _PtrClass; - CMyComPtr() { _p = NULL;} - CMyComPtr(T* p) {if ((_p = p) != NULL) p->AddRef(); } - CMyComPtr(const CMyComPtr& lp) - { - if ((_p = lp._p) != NULL) - _p->AddRef(); - } - ~CMyComPtr() { if (_p) _p->Release(); } - void Release() { if (_p) { _p->Release(); _p = NULL; } } - operator T*() const { return (T*)_p; } - // T& operator*() const { return *_p; } - T** operator&() { return &_p; } - T* operator->() const { return _p; } - T* operator=(T* p) - { - if (p != 0) - p->AddRef(); - if (_p) - _p->Release(); - _p = p; - return p; - } - T* operator=(const CMyComPtr& lp) { return (*this = lp._p); } - bool operator!() const { return (_p == NULL); } - // bool operator==(T* pT) const { return _p == pT; } - // Compare two objects for equivalence - void Attach(T* p2) - { - Release(); - _p = p2; - } - T* Detach() - { - T* pt = _p; - _p = NULL; - return pt; - } - #ifdef _WIN32 - HRESULT CoCreateInstance(REFCLSID rclsid, REFIID iid, LPUNKNOWN pUnkOuter = NULL, DWORD dwClsContext = CLSCTX_ALL) - { - return ::CoCreateInstance(rclsid, pUnkOuter, dwClsContext, iid, (void**)&_p); - } - #endif - /* - HRESULT CoCreateInstance(LPCOLESTR szProgID, LPUNKNOWN pUnkOuter = NULL, DWORD dwClsContext = CLSCTX_ALL) - { - CLSID clsid; - HRESULT hr = CLSIDFromProgID(szProgID, &clsid); - ATLASSERT(_p == NULL); - if (SUCCEEDED(hr)) - hr = ::CoCreateInstance(clsid, pUnkOuter, dwClsContext, __uuidof(T), (void**)&_p); - return hr; - } - */ - template - HRESULT QueryInterface(REFGUID iid, Q** pp) const - { - return _p->QueryInterface(iid, (void**)pp); - } -}; - -////////////////////////////////////////////////////////// - -inline HRESULT StringToBstr(LPCOLESTR src, BSTR *bstr) -{ - *bstr = ::SysAllocString(src); - return (*bstr != 0) ? S_OK : E_OUTOFMEMORY; -} - -class CMyComBSTR -{ -public: - BSTR m_str; - CMyComBSTR(): m_str(NULL) {} - CMyComBSTR(LPCOLESTR src) { m_str = ::SysAllocString(src); } - // CMyComBSTR(int nSize) { m_str = ::SysAllocStringLen(NULL, nSize); } - // CMyComBSTR(int nSize, LPCOLESTR sz) { m_str = ::SysAllocStringLen(sz, nSize); } - CMyComBSTR(const CMyComBSTR& src) { m_str = src.MyCopy(); } - /* - CMyComBSTR(REFGUID src) - { - LPOLESTR szGuid; - StringFromCLSID(src, &szGuid); - m_str = ::SysAllocString(szGuid); - CoTaskMemFree(szGuid); - } - */ - ~CMyComBSTR() { ::SysFreeString(m_str); } - CMyComBSTR& operator=(const CMyComBSTR& src) - { - if (m_str != src.m_str) - { - if (m_str) - ::SysFreeString(m_str); - m_str = src.MyCopy(); - } - return *this; - } - CMyComBSTR& operator=(LPCOLESTR src) - { - ::SysFreeString(m_str); - m_str = ::SysAllocString(src); - return *this; - } - unsigned int Length() const { return ::SysStringLen(m_str); } - operator BSTR() const { return m_str; } - BSTR* operator&() { return &m_str; } - BSTR MyCopy() const - { - int byteLen = ::SysStringByteLen(m_str); - BSTR res = ::SysAllocStringByteLen(NULL, byteLen); - memcpy(res, m_str, byteLen); - return res; - } - /* - void Attach(BSTR src) { m_str = src; } - BSTR Detach() - { - BSTR s = m_str; - m_str = NULL; - return s; - } - */ - void Empty() - { - ::SysFreeString(m_str); - m_str = NULL; - } - bool operator!() const { return (m_str == NULL); } -}; - -////////////////////////////////////////////////////////// - -class CMyUnknownImp -{ -public: - ULONG __m_RefCount; - CMyUnknownImp(): __m_RefCount(0) {} -}; - -#define MY_QUERYINTERFACE_BEGIN STDMETHOD(QueryInterface) \ - (REFGUID iid, void **outObject) { - -#define MY_QUERYINTERFACE_ENTRY(i) if (iid == IID_ ## i) \ - { *outObject = (void *)(i *)this; AddRef(); return S_OK; } - -#define MY_QUERYINTERFACE_ENTRY_UNKNOWN(i) if (iid == IID_IUnknown) \ - { *outObject = (void *)(IUnknown *)(i *)this; AddRef(); return S_OK; } - -#define MY_QUERYINTERFACE_BEGIN2(i) MY_QUERYINTERFACE_BEGIN \ - MY_QUERYINTERFACE_ENTRY_UNKNOWN(i) \ - MY_QUERYINTERFACE_ENTRY(i) - -#define MY_QUERYINTERFACE_END return E_NOINTERFACE; } - -#define MY_ADDREF_RELEASE \ -STDMETHOD_(ULONG, AddRef)() { return ++__m_RefCount; } \ -STDMETHOD_(ULONG, Release)() { if (--__m_RefCount != 0) \ - return __m_RefCount; delete this; return 0; } - -#define MY_UNKNOWN_IMP_SPEC(i) \ - MY_QUERYINTERFACE_BEGIN \ - i \ - MY_QUERYINTERFACE_END \ - MY_ADDREF_RELEASE - - -#define MY_UNKNOWN_IMP MY_QUERYINTERFACE_BEGIN \ - MY_QUERYINTERFACE_ENTRY_UNKNOWN(IUnknown) \ - MY_QUERYINTERFACE_END \ - MY_ADDREF_RELEASE - -#define MY_UNKNOWN_IMP1(i) MY_UNKNOWN_IMP_SPEC( \ - MY_QUERYINTERFACE_ENTRY_UNKNOWN(i) \ - MY_QUERYINTERFACE_ENTRY(i) \ - ) - -#define MY_UNKNOWN_IMP2(i1, i2) MY_UNKNOWN_IMP_SPEC( \ - MY_QUERYINTERFACE_ENTRY_UNKNOWN(i1) \ - MY_QUERYINTERFACE_ENTRY(i1) \ - MY_QUERYINTERFACE_ENTRY(i2) \ - ) - -#define MY_UNKNOWN_IMP3(i1, i2, i3) MY_UNKNOWN_IMP_SPEC( \ - MY_QUERYINTERFACE_ENTRY_UNKNOWN(i1) \ - MY_QUERYINTERFACE_ENTRY(i1) \ - MY_QUERYINTERFACE_ENTRY(i2) \ - MY_QUERYINTERFACE_ENTRY(i3) \ - ) - -#define MY_UNKNOWN_IMP4(i1, i2, i3, i4) MY_UNKNOWN_IMP_SPEC( \ - MY_QUERYINTERFACE_ENTRY_UNKNOWN(i1) \ - MY_QUERYINTERFACE_ENTRY(i1) \ - MY_QUERYINTERFACE_ENTRY(i2) \ - MY_QUERYINTERFACE_ENTRY(i3) \ - MY_QUERYINTERFACE_ENTRY(i4) \ - ) - -#define MY_UNKNOWN_IMP5(i1, i2, i3, i4, i5) MY_UNKNOWN_IMP_SPEC( \ - MY_QUERYINTERFACE_ENTRY_UNKNOWN(i1) \ - MY_QUERYINTERFACE_ENTRY(i1) \ - MY_QUERYINTERFACE_ENTRY(i2) \ - MY_QUERYINTERFACE_ENTRY(i3) \ - MY_QUERYINTERFACE_ENTRY(i4) \ - MY_QUERYINTERFACE_ENTRY(i5) \ - ) - -#endif diff --git a/desmume/src/windows/7z/CPP/Common/MyException.h b/desmume/src/windows/7z/CPP/Common/MyException.h deleted file mode 100644 index cd9fe6948..000000000 --- a/desmume/src/windows/7z/CPP/Common/MyException.h +++ /dev/null @@ -1,14 +0,0 @@ -// Common/Exception.h - -#ifndef __COMMON_EXCEPTION_H -#define __COMMON_EXCEPTION_H - -#include "MyWindows.h" - -struct CSystemException -{ - HRESULT ErrorCode; - CSystemException(HRESULT errorCode): ErrorCode(errorCode) {} -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/Common/MyInitGuid.h b/desmume/src/windows/7z/CPP/Common/MyInitGuid.h deleted file mode 100644 index b1e70d868..000000000 --- a/desmume/src/windows/7z/CPP/Common/MyInitGuid.h +++ /dev/null @@ -1,15 +0,0 @@ -// Common/MyInitGuid.h - -#ifndef __COMMON_MYINITGUID_H -#define __COMMON_MYINITGUID_H - -#ifdef _WIN32 -#include -#else -#define INITGUID -#include "MyGuidDef.h" -DEFINE_GUID(IID_IUnknown, -0x00000000, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46); -#endif - -#endif diff --git a/desmume/src/windows/7z/CPP/Common/MyMap.cpp b/desmume/src/windows/7z/CPP/Common/MyMap.cpp deleted file mode 100644 index a69c61a04..000000000 --- a/desmume/src/windows/7z/CPP/Common/MyMap.cpp +++ /dev/null @@ -1,140 +0,0 @@ -// MyMap.cpp - -#include "StdAfx.h" - -#include "MyMap.h" - -static const unsigned kNumBitsMax = sizeof(UInt32) * 8; - -static UInt32 GetSubBits(UInt32 value, unsigned startPos, unsigned numBits) -{ - if (startPos == sizeof(value) * 8) - return 0; - value >>= startPos; - if (numBits == sizeof(value) * 8) - return value; - return value & (((UInt32)1 << numBits) - 1); -} - -static inline unsigned GetSubBit(UInt32 v, unsigned n) { return (unsigned)(v >> n) & 1; } - -bool CMap32::Find(UInt32 key, UInt32 &valueRes) const -{ - valueRes = (UInt32)(Int32)-1; - if (Nodes.Size() == 0) - return false; - if (Nodes.Size() == 1) - { - const CNode &n = Nodes[0]; - if (n.Len == kNumBitsMax) - { - valueRes = n.Values[0]; - return (key == n.Key); - } - } - - int cur = 0; - unsigned bitPos = kNumBitsMax; - for (;;) - { - const CNode &n = Nodes[cur]; - bitPos -= n.Len; - if (GetSubBits(key, bitPos, n.Len) != GetSubBits(n.Key, bitPos, n.Len)) - return false; - unsigned bit = GetSubBit(key, --bitPos); - if (n.IsLeaf[bit]) - { - valueRes = n.Values[bit]; - return (key == n.Keys[bit]); - } - cur = (int)n.Keys[bit]; - } -} - -bool CMap32::Set(UInt32 key, UInt32 value) -{ - if (Nodes.Size() == 0) - { - CNode n; - n.Key = n.Keys[0] = n.Keys[1] = key; - n.Values[0] = n.Values[1] = value; - n.IsLeaf[0] = n.IsLeaf[1] = 1; - n.Len = kNumBitsMax; - Nodes.Add(n); - return false; - } - if (Nodes.Size() == 1) - { - CNode &n = Nodes[0]; - if (n.Len == kNumBitsMax) - { - if (key == n.Key) - { - n.Values[0] = n.Values[1] = value; - return true; - } - unsigned i = kNumBitsMax - 1; - for (;GetSubBit(key, i) == GetSubBit(n.Key, i); i--); - n.Len = (UInt16)(kNumBitsMax - (1 + i)); - unsigned newBit = GetSubBit(key, i); - n.Values[newBit] = value; - n.Keys[newBit] = key; - return false; - } - } - - int cur = 0; - unsigned bitPos = kNumBitsMax; - for (;;) - { - CNode &n = Nodes[cur]; - bitPos -= n.Len; - if (GetSubBits(key, bitPos, n.Len) != GetSubBits(n.Key, bitPos, n.Len)) - { - unsigned i = n.Len - 1; - for (; GetSubBit(key, bitPos + i) == GetSubBit(n.Key, bitPos + i); i--); - - CNode e2(n); - e2.Len = (UInt16)i; - - n.Len = (UInt16)(n.Len - (1 + i)); - unsigned newBit = GetSubBit(key, bitPos + i); - n.Values[newBit] = value; - n.IsLeaf[newBit] = 1; - n.IsLeaf[1 - newBit] = 0; - n.Keys[newBit] = key; - n.Keys[1 - newBit] = Nodes.Size(); - Nodes.Add(e2); - return false; - } - unsigned bit = GetSubBit(key, --bitPos); - - if (n.IsLeaf[bit]) - { - if (key == n.Keys[bit]) - { - n.Values[bit] = value; - return true; - } - unsigned i = bitPos - 1; - for (;GetSubBit(key, i) == GetSubBit(n.Keys[bit], i); i--); - - CNode e2; - - unsigned newBit = GetSubBit(key, i); - e2.Values[newBit] = value; - e2.Values[1 - newBit] = n.Values[bit]; - e2.IsLeaf[newBit] = e2.IsLeaf[1 - newBit] = 1; - e2.Keys[newBit] = key; - e2.Keys[1 - newBit] = e2.Key = n.Keys[bit]; - e2.Len = (UInt16)(bitPos - (1 + i)); - - n.IsLeaf[bit] = 0; - n.Keys[bit] = Nodes.Size(); - - Nodes.Add(e2); - return false; - } - cur = (int)n.Keys[bit]; - } -} diff --git a/desmume/src/windows/7z/CPP/Common/MyMap.h b/desmume/src/windows/7z/CPP/Common/MyMap.h deleted file mode 100644 index 4545bcef4..000000000 --- a/desmume/src/windows/7z/CPP/Common/MyMap.h +++ /dev/null @@ -1,28 +0,0 @@ -// MyMap.h - -#ifndef __COMMON_MYMAP_H -#define __COMMON_MYMAP_H - -#include "MyVector.h" -#include "Types.h" - -class CMap32 -{ - struct CNode - { - UInt32 Key; - UInt32 Keys[2]; - UInt32 Values[2]; - UInt16 Len; - Byte IsLeaf[2]; - }; - CRecordVector Nodes; - -public: - - void Clear() { Nodes.Clear(); } - bool Find(UInt32 key, UInt32 &valueRes) const; - bool Set(UInt32 key, UInt32 value); // returns true, if there is such key already -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/Common/MyString.cpp b/desmume/src/windows/7z/CPP/Common/MyString.cpp deleted file mode 100644 index efab50350..000000000 --- a/desmume/src/windows/7z/CPP/Common/MyString.cpp +++ /dev/null @@ -1,198 +0,0 @@ -// Common/MyString.cpp - -#include "StdAfx.h" - -#ifdef _WIN32 -#include "StringConvert.h" -#else -#include -#endif - -#include "MyString.h" - - -#ifdef _WIN32 - -#ifndef _UNICODE - -wchar_t MyCharUpper(wchar_t c) -{ - if (c == 0) - return 0; - wchar_t *res = CharUpperW((LPWSTR)(UINT_PTR)(unsigned int)c); - if (res != 0 || ::GetLastError() != ERROR_CALL_NOT_IMPLEMENTED) - return (wchar_t)(unsigned int)(UINT_PTR)res; - const int kBufferSize = 4; - char s[kBufferSize + 1]; - int numChars = ::WideCharToMultiByte(CP_ACP, 0, &c, 1, s, kBufferSize, 0, 0); - if (numChars == 0 || numChars > kBufferSize) - return c; - s[numChars] = 0; - ::CharUpperA(s); - ::MultiByteToWideChar(CP_ACP, 0, s, numChars, &c, 1); - return c; -} - -wchar_t MyCharLower(wchar_t c) -{ - if (c == 0) - return 0; - wchar_t *res = CharLowerW((LPWSTR)(UINT_PTR)(unsigned int)c); - if (res != 0 || ::GetLastError() != ERROR_CALL_NOT_IMPLEMENTED) - return (wchar_t)(unsigned int)(UINT_PTR)res; - const int kBufferSize = 4; - char s[kBufferSize + 1]; - int numChars = ::WideCharToMultiByte(CP_ACP, 0, &c, 1, s, kBufferSize, 0, 0); - if (numChars == 0 || numChars > kBufferSize) - return c; - s[numChars] = 0; - ::CharLowerA(s); - ::MultiByteToWideChar(CP_ACP, 0, s, numChars, &c, 1); - return c; -} - -wchar_t * MyStringUpper(wchar_t *s) -{ - if (s == 0) - return 0; - wchar_t *res = CharUpperW(s); - if (res != 0 || ::GetLastError() != ERROR_CALL_NOT_IMPLEMENTED) - return res; - AString a = UnicodeStringToMultiByte(s); - a.MakeUpper(); - return MyStringCopy(s, (const wchar_t *)MultiByteToUnicodeString(a)); -} - -wchar_t * MyStringLower(wchar_t *s) -{ - if (s == 0) - return 0; - wchar_t *res = CharLowerW(s); - if (res != 0 || ::GetLastError() != ERROR_CALL_NOT_IMPLEMENTED) - return res; - AString a = UnicodeStringToMultiByte(s); - a.MakeLower(); - return MyStringCopy(s, (const wchar_t *)MultiByteToUnicodeString(a)); -} - -#endif - -/* -inline int ConvertCompareResult(int r) { return r - 2; } - -int MyStringCollate(const wchar_t *s1, const wchar_t *s2) -{ - int res = CompareStringW( - LOCALE_USER_DEFAULT, SORT_STRINGSORT, s1, -1, s2, -1); - #ifdef _UNICODE - return ConvertCompareResult(res); - #else - if (res != 0 || ::GetLastError() != ERROR_CALL_NOT_IMPLEMENTED) - return ConvertCompareResult(res); - return MyStringCollate(UnicodeStringToMultiByte(s1), - UnicodeStringToMultiByte(s2)); - #endif -} - -#ifndef _WIN32_WCE -int MyStringCollate(const char *s1, const char *s2) -{ - return ConvertCompareResult(CompareStringA( - LOCALE_USER_DEFAULT, SORT_STRINGSORT, s1, -1, s2, -1)); -} - -int MyStringCollateNoCase(const char *s1, const char *s2) -{ - return ConvertCompareResult(CompareStringA( - LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT, s1, -1, s2, -1)); -} -#endif - -int MyStringCollateNoCase(const wchar_t *s1, const wchar_t *s2) -{ - int res = CompareStringW( - LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT, s1, -1, s2, -1); - #ifdef _UNICODE - return ConvertCompareResult(res); - #else - if (res != 0 || ::GetLastError() != ERROR_CALL_NOT_IMPLEMENTED) - return ConvertCompareResult(res); - return MyStringCollateNoCase(UnicodeStringToMultiByte(s1), - UnicodeStringToMultiByte(s2)); - #endif -} -*/ - -#else - -wchar_t MyCharUpper(wchar_t c) -{ - return toupper(c); -} - -/* -int MyStringCollateNoCase(const wchar_t *s1, const wchar_t *s2) -{ - for (;;) - { - wchar_t c1 = *s1++; - wchar_t c2 = *s2++; - wchar_t u1 = MyCharUpper(c1); - wchar_t u2 = MyCharUpper(c2); - - if (u1 < u2) return -1; - if (u1 > u2) return 1; - if (u1 == 0) return 0; - } -} -*/ - -#endif - -int MyStringCompare(const char *s1, const char *s2) -{ - for (;;) - { - unsigned char c1 = (unsigned char)*s1++; - unsigned char c2 = (unsigned char)*s2++; - if (c1 < c2) return -1; - if (c1 > c2) return 1; - if (c1 == 0) return 0; - } -} - -int MyStringCompare(const wchar_t *s1, const wchar_t *s2) -{ - for (;;) - { - wchar_t c1 = *s1++; - wchar_t c2 = *s2++; - if (c1 < c2) return -1; - if (c1 > c2) return 1; - if (c1 == 0) return 0; - } -} - -int MyStringCompareNoCase(const wchar_t *s1, const wchar_t *s2) -{ - for (;;) - { - wchar_t c1 = *s1++; - wchar_t c2 = *s2++; - if (c1 != c2) - { - wchar_t u1 = MyCharUpper(c1); - wchar_t u2 = MyCharUpper(c2); - if (u1 < u2) return -1; - if (u1 > u2) return 1; - } - if (c1 == 0) return 0; - } -} - -#ifdef _WIN32 -int MyStringCompareNoCase(const char *s1, const char *s2) -{ - return MyStringCompareNoCase(MultiByteToUnicodeString(s1), MultiByteToUnicodeString(s2)); -} -#endif diff --git a/desmume/src/windows/7z/CPP/Common/MyString.h b/desmume/src/windows/7z/CPP/Common/MyString.h deleted file mode 100644 index 74c8af2fc..000000000 --- a/desmume/src/windows/7z/CPP/Common/MyString.h +++ /dev/null @@ -1,631 +0,0 @@ -// Common/String.h - -#ifndef __COMMON_STRING_H -#define __COMMON_STRING_H - -#include -// #include - -#include "MyVector.h" - -#ifdef _WIN32 -#include "MyWindows.h" -#endif - -template -inline int MyStringLen(const T *s) -{ - int i; - for (i = 0; s[i] != '\0'; i++); - return i; -} - -template -inline T * MyStringCopy(T *dest, const T *src) -{ - T *destStart = dest; - while ((*dest++ = *src++) != 0); - return destStart; -} - -inline wchar_t* MyStringGetNextCharPointer(wchar_t *p) - { return (p + 1); } -inline const wchar_t* MyStringGetNextCharPointer(const wchar_t *p) - { return (p + 1); } -inline wchar_t* MyStringGetPrevCharPointer(const wchar_t *, wchar_t *p) - { return (p - 1); } -inline const wchar_t* MyStringGetPrevCharPointer(const wchar_t *, const wchar_t *p) - { return (p - 1); } - -#ifdef _WIN32 - -inline char* MyStringGetNextCharPointer(char *p) - { return CharNextA(p); } -inline const char* MyStringGetNextCharPointer(const char *p) - { return CharNextA(p); } - -inline char* MyStringGetPrevCharPointer(char *base, char *p) - { return CharPrevA(base, p); } -inline const char* MyStringGetPrevCharPointer(const char *base, const char *p) - { return CharPrevA(base, p); } - -inline char MyCharUpper(char c) - { return (char)(unsigned int)(UINT_PTR)CharUpperA((LPSTR)(UINT_PTR)(unsigned int)(unsigned char)c); } -#ifdef _UNICODE -inline wchar_t MyCharUpper(wchar_t c) - { return (wchar_t)(unsigned int)(UINT_PTR)CharUpperW((LPWSTR)(UINT_PTR)(unsigned int)c); } -#else -wchar_t MyCharUpper(wchar_t c); -#endif - -inline char MyCharLower(char c) - { return (char)(unsigned int)(UINT_PTR)CharLowerA((LPSTR)(UINT_PTR)(unsigned int)(unsigned char)c); } -#ifdef _UNICODE -inline wchar_t MyCharLower(wchar_t c) - { return (wchar_t)(unsigned int)(UINT_PTR)CharLowerW((LPWSTR)(UINT_PTR)(unsigned int)c); } -#else -wchar_t MyCharLower(wchar_t c); -#endif - -inline char * MyStringUpper(char *s) { return CharUpperA(s); } -#ifdef _UNICODE -inline wchar_t * MyStringUpper(wchar_t *s) { return CharUpperW(s); } -#else -wchar_t * MyStringUpper(wchar_t *s); -#endif - -inline char * MyStringLower(char *s) { return CharLowerA(s); } -#ifdef _UNICODE -inline wchar_t * MyStringLower(wchar_t *s) { return CharLowerW(s); } -#else -wchar_t * MyStringLower(wchar_t *s); -#endif - -#else // Standard-C -wchar_t MyCharUpper(wchar_t c); -#endif - -////////////////////////////////////// -// Compare - -/* -#ifndef _WIN32_WCE -int MyStringCollate(const char *s1, const char *s2); -int MyStringCollateNoCase(const char *s1, const char *s2); -#endif -int MyStringCollate(const wchar_t *s1, const wchar_t *s2); -int MyStringCollateNoCase(const wchar_t *s1, const wchar_t *s2); -*/ - -int MyStringCompare(const char *s1, const char *s2); -int MyStringCompare(const wchar_t *s1, const wchar_t *s2); - -#ifdef _WIN32 -int MyStringCompareNoCase(const char *s1, const char *s2); -#endif - -int MyStringCompareNoCase(const wchar_t *s1, const wchar_t *s2); - -template -class CStringBase -{ - void TrimLeftWithCharSet(const CStringBase &charSet) - { - const T *p = _chars; - while (charSet.Find(*p) >= 0 && (*p != 0)) - p = GetNextCharPointer(p); - Delete(0, (int)(p - _chars)); - } - void TrimRightWithCharSet(const CStringBase &charSet) - { - const T *p = _chars; - const T *pLast = NULL; - while (*p != 0) - { - if (charSet.Find(*p) >= 0) - { - if (pLast == NULL) - pLast = p; - } - else - pLast = NULL; - p = GetNextCharPointer(p); - } - if (pLast != NULL) - { - int i = (int)(pLast - _chars); - Delete(i, _length - i); - } - - } - void MoveItems(int destIndex, int srcIndex) - { - memmove(_chars + destIndex, _chars + srcIndex, - sizeof(T) * (_length - srcIndex + 1)); - } - - void InsertSpace(int &index, int size) - { - CorrectIndex(index); - GrowLength(size); - MoveItems(index + size, index); - } - - static T *GetNextCharPointer(T *p) - { return MyStringGetNextCharPointer(p); } - static const T *GetNextCharPointer(const T *p) - { return MyStringGetNextCharPointer(p); } - static T *GetPrevCharPointer(T *base, T *p) - { return MyStringGetPrevCharPointer(base, p); } - static const T *GetPrevCharPointer(const T *base, const T *p) - { return MyStringGetPrevCharPointer(base, p); } -protected: - T *_chars; - int _length; - int _capacity; - - void SetCapacity(int newCapacity) - { - int realCapacity = newCapacity + 1; - if (realCapacity == _capacity) - return; - /* - const int kMaxStringSize = 0x20000000; - #ifndef _WIN32_WCE - if (newCapacity > kMaxStringSize || newCapacity < _length) - throw 1052337; - #endif - */ - T *newBuffer = new T[realCapacity]; - if (_capacity > 0) - { - for (int i = 0; i < _length; i++) - newBuffer[i] = _chars[i]; - delete []_chars; - } - _chars = newBuffer; - _chars[_length] = 0; - _capacity = realCapacity; - } - - void GrowLength(int n) - { - int freeSize = _capacity - _length - 1; - if (n <= freeSize) - return; - int delta; - if (_capacity > 64) - delta = _capacity / 2; - else if (_capacity > 8) - delta = 16; - else - delta = 4; - if (freeSize + delta < n) - delta = n - freeSize; - SetCapacity(_capacity + delta); - } - - void CorrectIndex(int &index) const - { - if (index > _length) - index = _length; - } - -public: - CStringBase(): _chars(0), _length(0), _capacity(0) { SetCapacity(3); } - CStringBase(T c): _chars(0), _length(0), _capacity(0) - { - SetCapacity(1); - _chars[0] = c; - _chars[1] = 0; - _length = 1; - } - CStringBase(const T *chars): _chars(0), _length(0), _capacity(0) - { - int length = MyStringLen(chars); - SetCapacity(length); - MyStringCopy(_chars, chars); // can be optimized by memove() - _length = length; - } - CStringBase(const CStringBase &s): _chars(0), _length(0), _capacity(0) - { - SetCapacity(s._length); - MyStringCopy(_chars, s._chars); - _length = s._length; - } - ~CStringBase() { delete []_chars; } - - operator const T*() const { return _chars;} - - // The minimum size of the character buffer in characters. - // This value does not include space for a null terminator. - T* GetBuffer(int minBufLength) - { - if (minBufLength >= _capacity) - SetCapacity(minBufLength); - return _chars; - } - void ReleaseBuffer() { ReleaseBuffer(MyStringLen(_chars)); } - void ReleaseBuffer(int newLength) - { - /* - #ifndef _WIN32_WCE - if (newLength >= _capacity) - throw 282217; - #endif - */ - _chars[newLength] = 0; - _length = newLength; - } - - CStringBase& operator=(T c) - { - Empty(); - SetCapacity(1); - _chars[0] = c; - _chars[1] = 0; - _length = 1; - return *this; - } - CStringBase& operator=(const T *chars) - { - Empty(); - int length = MyStringLen(chars); - SetCapacity(length); - MyStringCopy(_chars, chars); - _length = length; - return *this; - } - CStringBase& operator=(const CStringBase& s) - { - if (&s == this) - return *this; - Empty(); - SetCapacity(s._length); - MyStringCopy(_chars, s._chars); - _length = s._length; - return *this; - } - - CStringBase& operator+=(T c) - { - GrowLength(1); - _chars[_length] = c; - _chars[++_length] = 0; - return *this; - } - CStringBase& operator+=(const T *s) - { - int len = MyStringLen(s); - GrowLength(len); - MyStringCopy(_chars + _length, s); - _length += len; - return *this; - } - CStringBase& operator+=(const CStringBase &s) - { - GrowLength(s._length); - MyStringCopy(_chars + _length, s._chars); - _length += s._length; - return *this; - } - void Empty() - { - _length = 0; - _chars[0] = 0; - } - int Length() const { return _length; } - bool IsEmpty() const { return (_length == 0); } - - CStringBase Mid(int startIndex) const - { return Mid(startIndex, _length - startIndex); } - CStringBase Mid(int startIndex, int count ) const - { - if (startIndex + count > _length) - count = _length - startIndex; - - if (startIndex == 0 && startIndex + count == _length) - return *this; - - CStringBase result; - result.SetCapacity(count); - // MyStringNCopy(result._chars, _chars + startIndex, count); - for (int i = 0; i < count; i++) - result._chars[i] = _chars[startIndex + i]; - result._chars[count] = 0; - result._length = count; - return result; - } - CStringBase Left(int count) const - { return Mid(0, count); } - CStringBase Right(int count) const - { - if (count > _length) - count = _length; - return Mid(_length - count, count); - } - - void MakeUpper() - { MyStringUpper(_chars); } - void MakeLower() - { MyStringLower(_chars); } - - int Compare(const CStringBase& s) const - { return MyStringCompare(_chars, s._chars); } - - int Compare(const T *s) const - { return MyStringCompare(_chars, s); } - - int CompareNoCase(const CStringBase& s) const - { return MyStringCompareNoCase(_chars, s._chars); } - - int CompareNoCase(const T *s) const - { return MyStringCompareNoCase(_chars, s); } - - /* - int Collate(const CStringBase& s) const - { return MyStringCollate(_chars, s._chars); } - int CollateNoCase(const CStringBase& s) const - { return MyStringCollateNoCase(_chars, s._chars); } - */ - - int Find(T c) const { return Find(c, 0); } - int Find(T c, int startIndex) const - { - T *p = _chars + startIndex; - for (;;) - { - if (*p == c) - return (int)(p - _chars); - if (*p == 0) - return -1; - p = GetNextCharPointer(p); - } - } - int Find(const CStringBase &s) const { return Find(s, 0); } - int Find(const CStringBase &s, int startIndex) const - { - if (s.IsEmpty()) - return startIndex; - for (; startIndex < _length; startIndex++) - { - int j; - for (j = 0; j < s._length && startIndex + j < _length; j++) - if (_chars[startIndex+j] != s._chars[j]) - break; - if (j == s._length) - return startIndex; - } - return -1; - } - int ReverseFind(T c) const - { - if (_length == 0) - return -1; - T *p = _chars + _length - 1; - for (;;) - { - if (*p == c) - return (int)(p - _chars); - if (p == _chars) - return -1; - p = GetPrevCharPointer(_chars, p); - } - } - int FindOneOf(const CStringBase &s) const - { - for (int i = 0; i < _length; i++) - if (s.Find(_chars[i]) >= 0) - return i; - return -1; - } - - void TrimLeft(T c) - { - const T *p = _chars; - while (c == *p) - p = GetNextCharPointer(p); - Delete(0, p - _chars); - } - private: - CStringBase GetTrimDefaultCharSet() - { - CStringBase charSet; - charSet += (T)' '; - charSet += (T)'\n'; - charSet += (T)'\t'; - return charSet; - } - public: - - void TrimLeft() - { - TrimLeftWithCharSet(GetTrimDefaultCharSet()); - } - void TrimRight() - { - TrimRightWithCharSet(GetTrimDefaultCharSet()); - } - void TrimRight(T c) - { - const T *p = _chars; - const T *pLast = NULL; - while (*p != 0) - { - if (*p == c) - { - if (pLast == NULL) - pLast = p; - } - else - pLast = NULL; - p = GetNextCharPointer(p); - } - if (pLast != NULL) - { - int i = pLast - _chars; - Delete(i, _length - i); - } - } - void Trim() - { - TrimRight(); - TrimLeft(); - } - - int Insert(int index, T c) - { - InsertSpace(index, 1); - _chars[index] = c; - _length++; - return _length; - } - int Insert(int index, const CStringBase &s) - { - CorrectIndex(index); - if (s.IsEmpty()) - return _length; - int numInsertChars = s.Length(); - InsertSpace(index, numInsertChars); - for (int i = 0; i < numInsertChars; i++) - _chars[index + i] = s[i]; - _length += numInsertChars; - return _length; - } - - // !!!!!!!!!!!!!!! test it if newChar = '\0' - int Replace(T oldChar, T newChar) - { - if (oldChar == newChar) - return 0; - int number = 0; - int pos = 0; - while (pos < Length()) - { - pos = Find(oldChar, pos); - if (pos < 0) - break; - _chars[pos] = newChar; - pos++; - number++; - } - return number; - } - int Replace(const CStringBase &oldString, const CStringBase &newString) - { - if (oldString.IsEmpty()) - return 0; - if (oldString == newString) - return 0; - int oldStringLength = oldString.Length(); - int newStringLength = newString.Length(); - int number = 0; - int pos = 0; - while (pos < _length) - { - pos = Find(oldString, pos); - if (pos < 0) - break; - Delete(pos, oldStringLength); - Insert(pos, newString); - pos += newStringLength; - number++; - } - return number; - } - int Delete(int index, int count = 1 ) - { - if (index + count > _length) - count = _length - index; - if (count > 0) - { - MoveItems(index, index + count); - _length -= count; - } - return _length; - } -}; - -template -CStringBase operator+(const CStringBase& s1, const CStringBase& s2) -{ - CStringBase result(s1); - result += s2; - return result; -} - -template -CStringBase operator+(const CStringBase& s, T c) -{ - CStringBase result(s); - result += c; - return result; -} - -template -CStringBase operator+(T c, const CStringBase& s) -{ - CStringBase result(c); - result += s; - return result; -} - -template -CStringBase operator+(const CStringBase& s, const T * chars) -{ - CStringBase result(s); - result += chars; - return result; -} - -template -CStringBase operator+(const T * chars, const CStringBase& s) -{ - CStringBase result(chars); - result += s; - return result; -} - -template -bool operator==(const CStringBase& s1, const CStringBase& s2) - { return (s1.Compare(s2) == 0); } - -template -bool operator<(const CStringBase& s1, const CStringBase& s2) - { return (s1.Compare(s2) < 0); } - -template -bool operator==(const T *s1, const CStringBase& s2) - { return (s2.Compare(s1) == 0); } - -template -bool operator==(const CStringBase& s1, const T *s2) - { return (s1.Compare(s2) == 0); } - -template -bool operator!=(const CStringBase& s1, const CStringBase& s2) - { return (s1.Compare(s2) != 0); } - -template -bool operator!=(const T *s1, const CStringBase& s2) - { return (s2.Compare(s1) != 0); } - -template -bool operator!=(const CStringBase& s1, const T *s2) - { return (s1.Compare(s2) != 0); } - -typedef CStringBase AString; -typedef CStringBase UString; - -typedef CObjectVector AStringVector; -typedef CObjectVector UStringVector; - -#ifdef _UNICODE - typedef UString CSysString; -#else - typedef AString CSysString; -#endif - -typedef CObjectVector CSysStringVector; - -#endif diff --git a/desmume/src/windows/7z/CPP/Common/MyUnknown.h b/desmume/src/windows/7z/CPP/Common/MyUnknown.h deleted file mode 100644 index 257fa4ab7..000000000 --- a/desmume/src/windows/7z/CPP/Common/MyUnknown.h +++ /dev/null @@ -1,24 +0,0 @@ -// MyUnknown.h - -#ifndef __MYUNKNOWN_H -#define __MYUNKNOWN_H - -#ifdef _WIN32 - -#ifdef _WIN32_WCE -#if (_WIN32_WCE > 300) -#include -#else -#define MIDL_INTERFACE(x) struct -#endif -#else -#include -#endif - -#include - -#else -#include "MyWindows.h" -#endif - -#endif diff --git a/desmume/src/windows/7z/CPP/Common/MyVector.cpp b/desmume/src/windows/7z/CPP/Common/MyVector.cpp deleted file mode 100644 index e0788b751..000000000 --- a/desmume/src/windows/7z/CPP/Common/MyVector.cpp +++ /dev/null @@ -1,90 +0,0 @@ -// Common/MyVector.cpp - -#include "StdAfx.h" - -#include - -#include "MyVector.h" - -CBaseRecordVector::~CBaseRecordVector() { ClearAndFree(); } - -void CBaseRecordVector::ClearAndFree() -{ - Clear(); - delete []((unsigned char *)_items); - _capacity = 0; - _size = 0; - _items = 0; -} - -void CBaseRecordVector::Clear() { DeleteFrom(0); } -void CBaseRecordVector::DeleteBack() { Delete(_size - 1); } -void CBaseRecordVector::DeleteFrom(int index) -{ - Delete(index, _size - index); -} - -void CBaseRecordVector::ReserveOnePosition() -{ - if (_size != _capacity) - return; - int delta = 1; - if (_capacity >= 64) - delta = _capacity / 4; - else if (_capacity >= 8) - delta = 8; - Reserve(_capacity + delta); -} - -void CBaseRecordVector::Reserve(int newCapacity) -{ - // if (newCapacity <= _capacity) - if (newCapacity == _capacity) - return; - if ((unsigned)newCapacity >= ((unsigned)1 << (sizeof(unsigned) * 8 - 1))) - throw 1052353; - size_t newSize = (size_t)(unsigned)newCapacity * _itemSize; - if (newSize / _itemSize != (size_t)(unsigned)newCapacity) - throw 1052354; - unsigned char *p = NULL; - if (newSize > 0) - { - p = new unsigned char[newSize]; - if (p == 0) - throw 1052355; - int numRecordsToMove = (_size < newCapacity ? _size : newCapacity); - memcpy(p, _items, _itemSize * numRecordsToMove); - } - delete [](unsigned char *)_items; - _items = p; - _capacity = newCapacity; -} - -void CBaseRecordVector::ReserveDown() -{ - Reserve(_size); -} - -void CBaseRecordVector::MoveItems(int destIndex, int srcIndex) -{ - memmove(((unsigned char *)_items) + destIndex * _itemSize, - ((unsigned char *)_items) + srcIndex * _itemSize, - _itemSize * (_size - srcIndex)); -} - -void CBaseRecordVector::InsertOneItem(int index) -{ - ReserveOnePosition(); - MoveItems(index + 1, index); - _size++; -} - -void CBaseRecordVector::Delete(int index, int num) -{ - TestIndexAndCorrectNum(index, num); - if (num > 0) - { - MoveItems(index, index + num); - _size -= num; - } -} diff --git a/desmume/src/windows/7z/CPP/Common/MyVector.h b/desmume/src/windows/7z/CPP/Common/MyVector.h deleted file mode 100644 index b8f4cd929..000000000 --- a/desmume/src/windows/7z/CPP/Common/MyVector.h +++ /dev/null @@ -1,256 +0,0 @@ -// Common/Vector.h - -#ifndef __COMMON_VECTOR_H -#define __COMMON_VECTOR_H - -#include "Defs.h" - -class CBaseRecordVector -{ - void MoveItems(int destIndex, int srcIndex); -protected: - int _capacity; - int _size; - void *_items; - size_t _itemSize; - - void ReserveOnePosition(); - void InsertOneItem(int index); - void TestIndexAndCorrectNum(int index, int &num) const - { if (index + num > _size) num = _size - index; } -public: - CBaseRecordVector(size_t itemSize): _capacity(0), _size(0), _items(0), _itemSize(itemSize) {} - virtual ~CBaseRecordVector(); - void ClearAndFree(); - int Size() const { return _size; } - bool IsEmpty() const { return (_size == 0); } - void Reserve(int newCapacity); - void ReserveDown(); - virtual void Delete(int index, int num = 1); - void Clear(); - void DeleteFrom(int index); - void DeleteBack(); -}; - -template -class CRecordVector: public CBaseRecordVector -{ -public: - CRecordVector(): CBaseRecordVector(sizeof(T)){}; - CRecordVector(const CRecordVector &v): CBaseRecordVector(sizeof(T)) { *this = v; } - CRecordVector& operator=(const CRecordVector &v) - { - Clear(); - return (*this += v); - } - CRecordVector& operator+=(const CRecordVector &v) - { - int size = v.Size(); - Reserve(Size() + size); - for (int i = 0; i < size; i++) - Add(v[i]); - return *this; - } - int Add(T item) - { - ReserveOnePosition(); - ((T *)_items)[_size] = item; - return _size++; - } - void Insert(int index, T item) - { - InsertOneItem(index); - ((T *)_items)[index] = item; - } - // T* GetPointer() const { return (T*)_items; } - // operator const T *() const { return _items; }; - const T& operator[](int index) const { return ((T *)_items)[index]; } - T& operator[](int index) { return ((T *)_items)[index]; } - const T& Front() const { return operator[](0); } - T& Front() { return operator[](0); } - const T& Back() const { return operator[](_size - 1); } - T& Back() { return operator[](_size - 1); } - - void Swap(int i, int j) - { - T temp = operator[](i); - operator[](i) = operator[](j); - operator[](j) = temp; - } - - int FindInSorted(const T& item) const - { - int left = 0, right = Size(); - while (left != right) - { - int mid = (left + right) / 2; - const T& midValue = (*this)[mid]; - if (item == midValue) - return mid; - if (item < midValue) - right = mid; - else - left = mid + 1; - } - return -1; - } - - int AddToUniqueSorted(const T& item) - { - int left = 0, right = Size(); - while (left != right) - { - int mid = (left + right) / 2; - const T& midValue = (*this)[mid]; - if (item == midValue) - return mid; - if (item < midValue) - right = mid; - else - left = mid + 1; - } - Insert(right, item); - return right; - } - - static void SortRefDown(T* p, int k, int size, int (*compare)(const T*, const T*, void *), void *param) - { - T temp = p[k]; - for (;;) - { - int s = (k << 1); - if (s > size) - break; - if (s < size && compare(p + s + 1, p + s, param) > 0) - s++; - if (compare(&temp, p + s, param) >= 0) - break; - p[k] = p[s]; - k = s; - } - p[k] = temp; - } - - void Sort(int (*compare)(const T*, const T*, void *), void *param) - { - int size = _size; - if (size <= 1) - return; - T* p = (&Front()) - 1; - { - int i = size / 2; - do - SortRefDown(p, i, size, compare, param); - while (--i != 0); - } - do - { - T temp = p[size]; - p[size--] = p[1]; - p[1] = temp; - SortRefDown(p, 1, size, compare, param); - } - while (size > 1); - } -}; - -typedef CRecordVector CIntVector; -typedef CRecordVector CUIntVector; -typedef CRecordVector CBoolVector; -typedef CRecordVector CByteVector; -typedef CRecordVector CPointerVector; - -template -class CObjectVector: public CPointerVector -{ -public: - CObjectVector() {}; - ~CObjectVector() { Clear(); }; - CObjectVector(const CObjectVector &v) { *this = v; } - CObjectVector& operator=(const CObjectVector &v) - { - Clear(); - return (*this += v); - } - CObjectVector& operator+=(const CObjectVector &v) - { - int size = v.Size(); - Reserve(Size() + size); - for (int i = 0; i < size; i++) - Add(v[i]); - return *this; - } - const T& operator[](int index) const - { - return *((T *)CPointerVector::operator[](index)); - } - T& operator[](int index) - { - return *((T *)CPointerVector::operator[](index)); - } - T& Front() { return operator[](0); } - const T& Front() const { return operator[](0); } - T& Back() { return operator[](_size - 1); } - const T& Back() const { return operator[](_size - 1); } - int Add(const T& item) { return CPointerVector::Add(new T(item)); } - void Insert(int index, const T& item) { CPointerVector::Insert(index, new T(item)); } - virtual void Delete(int index, int num = 1) - { - TestIndexAndCorrectNum(index, num); - for (int i = 0; i < num; i++) - delete (T *)(((void **)_items)[index + i]); - CPointerVector::Delete(index, num); - } - int Find(const T& item) const - { - for (int i = 0; i < Size(); i++) - if (item == (*this)[i]) - return i; - return -1; - } - int FindInSorted(const T& item) const - { - int left = 0, right = Size(); - while (left != right) - { - int mid = (left + right) / 2; - const T& midValue = (*this)[mid]; - if (item == midValue) - return mid; - if (item < midValue) - right = mid; - else - left = mid + 1; - } - return -1; - } - int AddToSorted(const T& item) - { - int left = 0, right = Size(); - while (left != right) - { - int mid = (left + right) / 2; - const T& midValue = (*this)[mid]; - if (item == midValue) - { - right = mid + 1; - break; - } - if (item < midValue) - right = mid; - else - left = mid + 1; - } - Insert(right, item); - return right; - } - - void Sort(int (*compare)(void *const *, void *const *, void *), void *param) - { CPointerVector::Sort(compare, param); } - - static int CompareObjectItems(void *const *a1, void *const *a2, void * /* param */) - { return MyCompare(*(*((const T **)a1)), *(*((const T **)a2))); } - void Sort() { CPointerVector::Sort(CompareObjectItems, 0); } -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/Common/MyWindows.h b/desmume/src/windows/7z/CPP/Common/MyWindows.h deleted file mode 100644 index 0329ff709..000000000 --- a/desmume/src/windows/7z/CPP/Common/MyWindows.h +++ /dev/null @@ -1,214 +0,0 @@ -// MyWindows.h - -#ifndef __MYWINDOWS_H -#define __MYWINDOWS_H - -#ifdef _WIN32 - -#include - -#define CHAR_PATH_SEPARATOR '\\' -#define WCHAR_PATH_SEPARATOR L'\\' -#define STRING_PATH_SEPARATOR "\\" -#define WSTRING_PATH_SEPARATOR L"\\" - -#else - -#define CHAR_PATH_SEPARATOR '/' -#define WCHAR_PATH_SEPARATOR L'/' -#define STRING_PATH_SEPARATOR "/" -#define WSTRING_PATH_SEPARATOR L"/" - -#include // for wchar_t -#include - -#include "MyGuidDef.h" - -typedef char CHAR; -typedef unsigned char UCHAR; - -#undef BYTE -typedef unsigned char BYTE; - -typedef short SHORT; -typedef unsigned short USHORT; - -#undef WORD -typedef unsigned short WORD; -typedef short VARIANT_BOOL; - -typedef int INT; -typedef Int32 INT32; -typedef unsigned int UINT; -typedef UInt32 UINT32; -typedef INT32 LONG; // LONG, ULONG and DWORD must be 32-bit -typedef UINT32 ULONG; - -#undef DWORD -typedef UINT32 DWORD; - -typedef Int64 LONGLONG; -typedef UInt64 ULONGLONG; - -typedef struct LARGE_INTEGER { LONGLONG QuadPart; }LARGE_INTEGER; -typedef struct _ULARGE_INTEGER { ULONGLONG QuadPart;} ULARGE_INTEGER; - -typedef const CHAR *LPCSTR; -typedef CHAR TCHAR; -typedef const TCHAR *LPCTSTR; -typedef wchar_t WCHAR; -typedef WCHAR OLECHAR; -typedef const WCHAR *LPCWSTR; -typedef OLECHAR *BSTR; -typedef const OLECHAR *LPCOLESTR; -typedef OLECHAR *LPOLESTR; - -typedef struct _FILETIME -{ - DWORD dwLowDateTime; - DWORD dwHighDateTime; -}FILETIME; - -#define HRESULT LONG -#define FAILED(Status) ((HRESULT)(Status)<0) -typedef ULONG PROPID; -typedef LONG SCODE; - -#define S_OK ((HRESULT)0x00000000L) -#define S_FALSE ((HRESULT)0x00000001L) -#define E_NOTIMPL ((HRESULT)0x80004001L) -#define E_NOINTERFACE ((HRESULT)0x80004002L) -#define E_ABORT ((HRESULT)0x80004004L) -#define E_FAIL ((HRESULT)0x80004005L) -#define STG_E_INVALIDFUNCTION ((HRESULT)0x80030001L) -#define E_OUTOFMEMORY ((HRESULT)0x8007000EL) -#define E_INVALIDARG ((HRESULT)0x80070057L) - -#ifdef _MSC_VER -#define STDMETHODCALLTYPE __stdcall -#else -#define STDMETHODCALLTYPE -#endif - -#define STDMETHOD_(t, f) virtual t STDMETHODCALLTYPE f -#define STDMETHOD(f) STDMETHOD_(HRESULT, f) -#define STDMETHODIMP_(type) type STDMETHODCALLTYPE -#define STDMETHODIMP STDMETHODIMP_(HRESULT) - -#define PURE = 0 - -#define MIDL_INTERFACE(x) struct - -#ifdef __cplusplus - -DEFINE_GUID(IID_IUnknown, -0x00000000, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46); -struct IUnknown -{ - STDMETHOD(QueryInterface) (REFIID iid, void **outObject) PURE; - STDMETHOD_(ULONG, AddRef)() PURE; - STDMETHOD_(ULONG, Release)() PURE; - #ifndef _WIN32 - virtual ~IUnknown() {} - #endif -}; - -typedef IUnknown *LPUNKNOWN; - -#endif - -#define VARIANT_TRUE ((VARIANT_BOOL)-1) -#define VARIANT_FALSE ((VARIANT_BOOL)0) - -enum VARENUM -{ - VT_EMPTY = 0, - VT_NULL = 1, - VT_I2 = 2, - VT_I4 = 3, - VT_R4 = 4, - VT_R8 = 5, - VT_CY = 6, - VT_DATE = 7, - VT_BSTR = 8, - VT_DISPATCH = 9, - VT_ERROR = 10, - VT_BOOL = 11, - VT_VARIANT = 12, - VT_UNKNOWN = 13, - VT_DECIMAL = 14, - VT_I1 = 16, - VT_UI1 = 17, - VT_UI2 = 18, - VT_UI4 = 19, - VT_I8 = 20, - VT_UI8 = 21, - VT_INT = 22, - VT_UINT = 23, - VT_VOID = 24, - VT_HRESULT = 25, - VT_FILETIME = 64 -}; - -typedef unsigned short VARTYPE; -typedef WORD PROPVAR_PAD1; -typedef WORD PROPVAR_PAD2; -typedef WORD PROPVAR_PAD3; - -#ifdef __cplusplus - -typedef struct tagPROPVARIANT -{ - VARTYPE vt; - PROPVAR_PAD1 wReserved1; - PROPVAR_PAD2 wReserved2; - PROPVAR_PAD3 wReserved3; - union - { - CHAR cVal; - UCHAR bVal; - SHORT iVal; - USHORT uiVal; - LONG lVal; - ULONG ulVal; - INT intVal; - UINT uintVal; - LARGE_INTEGER hVal; - ULARGE_INTEGER uhVal; - VARIANT_BOOL boolVal; - SCODE scode; - FILETIME filetime; - BSTR bstrVal; - }; -} PROPVARIANT; - -typedef PROPVARIANT tagVARIANT; -typedef tagVARIANT VARIANT; -typedef VARIANT VARIANTARG; - -MY_EXTERN_C HRESULT VariantClear(VARIANTARG *prop); -MY_EXTERN_C HRESULT VariantCopy(VARIANTARG *dest, VARIANTARG *src); - -#endif - -MY_EXTERN_C BSTR SysAllocStringByteLen(LPCSTR psz, UINT len); -MY_EXTERN_C BSTR SysAllocString(const OLECHAR *sz); -MY_EXTERN_C void SysFreeString(BSTR bstr); -MY_EXTERN_C UINT SysStringByteLen(BSTR bstr); -MY_EXTERN_C UINT SysStringLen(BSTR bstr); - -MY_EXTERN_C DWORD GetLastError(); -MY_EXTERN_C LONG CompareFileTime(const FILETIME* ft1, const FILETIME* ft2); - -#define CP_ACP 0 -#define CP_OEMCP 1 - -typedef enum tagSTREAM_SEEK -{ - STREAM_SEEK_SET = 0, - STREAM_SEEK_CUR = 1, - STREAM_SEEK_END = 2 -} STREAM_SEEK; - -#endif -#endif diff --git a/desmume/src/windows/7z/CPP/Common/MyXml.cpp b/desmume/src/windows/7z/CPP/Common/MyXml.cpp deleted file mode 100644 index c18570e93..000000000 --- a/desmume/src/windows/7z/CPP/Common/MyXml.cpp +++ /dev/null @@ -1,209 +0,0 @@ -// MyXml.cpp - -#include "StdAfx.h" - -#include "MyXml.h" - -static bool IsValidChar(char c) -{ - return - c >= 'a' && c <= 'z' || - c >= 'A' && c <= 'Z' || - c >= '0' && c <= '9' || - c == '-'; -} - -static bool IsSpaceChar(char c) -{ - return (c == ' ' || c == '\t' || c == 0x0D || c == 0x0A); -} - -#define SKEEP_SPACES(s, pos) while (IsSpaceChar(s[pos])) pos++; - -static bool ReadProperty(const AString &s, int &pos, CXmlProp &prop) -{ - prop.Name.Empty(); - prop.Value.Empty(); - for (; pos < s.Length(); pos++) - { - char c = s[pos]; - if (!IsValidChar(c)) - break; - prop.Name += c; - } - - if (prop.Name.IsEmpty()) - return false; - - SKEEP_SPACES(s, pos); - if (s[pos++] != '=') - return false; - - SKEEP_SPACES(s, pos); - if (s[pos++] != '\"') - return false; - - while (pos < s.Length()) - { - char c = s[pos++]; - if (c == '\"') - return true; - prop.Value += c; - } - return false; -} - -int CXmlItem::FindProperty(const AString &propName) const -{ - for (int i = 0; i < Props.Size(); i++) - if (Props[i].Name == propName) - return i; - return -1; -} - -AString CXmlItem::GetPropertyValue(const AString &propName) const -{ - int index = FindProperty(propName); - if (index >= 0) - return Props[index].Value; - return AString(); -} - -bool CXmlItem::IsTagged(const AString &tag) const -{ - return (IsTag && Name == tag); -} - -int CXmlItem::FindSubTag(const AString &tag) const -{ - for (int i = 0; i < SubItems.Size(); i++) - if (SubItems[i].IsTagged(tag)) - return i; - return -1; -} - -AString CXmlItem::GetSubString() const -{ - if (SubItems.Size() == 1) - { - const CXmlItem &item = SubItems[0]; - if (!item.IsTag) - return item.Name; - } - return AString(); -} - -AString CXmlItem::GetSubStringForTag(const AString &tag) const -{ - int index = FindSubTag(tag); - if (index >= 0) - return SubItems[index].GetSubString(); - return AString(); -} - -bool CXmlItem::ParseItems(const AString &s, int &pos, int numAllowedLevels) -{ - if (numAllowedLevels == 0) - return false; - SubItems.Clear(); - AString finishString = "'); - } - if (s[pos] == '>') - { - if (!ParseItems(s, ++pos, numAllowedLevels)) - return false; - AString finishString = AString(""); - if (s.Mid(pos, finishString.Length()) != finishString) - return false; - pos += finishString.Length(); - return true; - } - if (posTemp == pos) - return false; - - CXmlProp prop; - if (!ReadProperty(s, pos, prop)) - return false; - Props.Add(prop); - posTemp = pos; - } -} - -bool SkeepHeader(const AString &s, int &pos, const AString &startString, const AString &endString) -{ - SKEEP_SPACES(s, pos); - if (s.Mid(pos, startString.Length()) == startString) - { - pos = s.Find(endString, pos); - if (pos < 0) - return false; - pos += endString.Length(); - SKEEP_SPACES(s, pos); - } - return true; -} - -bool CXml::Parse(const AString &s) -{ - int pos = 0; - if (!SkeepHeader(s, pos, "")) - return false; - if (!SkeepHeader(s, pos, "")) - return false; - if (!Root.ParseItem(s, pos, 1000)) - return false; - SKEEP_SPACES(s, pos); - return (pos == s.Length() && Root.IsTag); -} diff --git a/desmume/src/windows/7z/CPP/Common/MyXml.h b/desmume/src/windows/7z/CPP/Common/MyXml.h deleted file mode 100644 index 52e23d19c..000000000 --- a/desmume/src/windows/7z/CPP/Common/MyXml.h +++ /dev/null @@ -1,40 +0,0 @@ -// MyXml.h - -#ifndef __MYXML_H -#define __MYXML_H - -#include "MyString.h" - -struct CXmlProp -{ - AString Name; - AString Value; -}; - -class CXmlItem -{ - bool ParseItems(const AString &s, int &pos, int numAllowedLevels); - -public: - AString Name; - bool IsTag; - CObjectVector Props; - CObjectVector SubItems; - - bool ParseItem(const AString &s, int &pos, int numAllowedLevels); - - bool IsTagged(const AString &tag) const; - int FindProperty(const AString &propName) const; - AString GetPropertyValue(const AString &propName) const; - AString GetSubString() const; - int FindSubTag(const AString &tag) const; - AString GetSubStringForTag(const AString &tag) const; -}; - -struct CXml -{ - CXmlItem Root; - bool Parse(const AString &s); -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/Common/NewHandler.cpp b/desmume/src/windows/7z/CPP/Common/NewHandler.cpp deleted file mode 100644 index 611bbd8f5..000000000 --- a/desmume/src/windows/7z/CPP/Common/NewHandler.cpp +++ /dev/null @@ -1,116 +0,0 @@ -// NewHandler.cpp - -#include "StdAfx.h" - -#include - -#include "NewHandler.h" - -// #define DEBUG_MEMORY_LEAK - -#ifndef DEBUG_MEMORY_LEAK - -#ifdef _WIN32 -void * -#ifdef _MSC_VER -__cdecl -#endif -operator new(size_t size) -{ - // void *p = ::HeapAlloc(::GetProcessHeap(), 0, size); - void *p = ::malloc(size); - if (p == 0) - throw CNewException(); - return p; -} - -void -#ifdef _MSC_VER -__cdecl -#endif -operator delete(void *p) throw() -{ - /* - if (p == 0) - return; - ::HeapFree(::GetProcessHeap(), 0, p); - */ - ::free(p); -} -#endif - -#else - -#pragma init_seg(lib) -const int kDebugSize = 1000000; -static void *a[kDebugSize]; -static int index = 0; - -static int numAllocs = 0; -void * __cdecl operator new(size_t size) -{ - numAllocs++; - void *p = HeapAlloc(GetProcessHeap(), 0, size); - if (index == 40) - { - int t = 1; - } - if (index < kDebugSize) - { - a[index] = p; - index++; - } - if (p == 0) - throw CNewException(); - printf("Alloc %6d, size = %8d\n", numAllocs, size); - return p; -} - -class CC -{ -public: - CC() - { - for (int i = 0; i < kDebugSize; i++) - a[i] = 0; - } - ~CC() - { - for (int i = 0; i < kDebugSize; i++) - if (a[i] != 0) - return; - } -} g_CC; - - -void __cdecl operator delete(void *p) -{ - if (p == 0) - return; - /* - for (int i = 0; i < index; i++) - if (a[i] == p) - a[i] = 0; - */ - HeapFree(GetProcessHeap(), 0, p); - numAllocs--; - printf("Free %d\n", numAllocs); -} - -#endif - -/* -int MemErrorVC(size_t) -{ - throw CNewException(); - // return 1; -} -CNewHandlerSetter::CNewHandlerSetter() -{ - // MemErrorOldVCFunction = _set_new_handler(MemErrorVC); -} -CNewHandlerSetter::~CNewHandlerSetter() -{ - // _set_new_handler(MemErrorOldVCFunction); -} -*/ diff --git a/desmume/src/windows/7z/CPP/Common/NewHandler.h b/desmume/src/windows/7z/CPP/Common/NewHandler.h deleted file mode 100644 index 6f710cda1..000000000 --- a/desmume/src/windows/7z/CPP/Common/NewHandler.h +++ /dev/null @@ -1,16 +0,0 @@ -// Common/NewHandler.h - -#ifndef __COMMON_NEWHANDLER_H -#define __COMMON_NEWHANDLER_H - -class CNewException {}; - -#ifdef _WIN32 -void -#ifdef _MSC_VER -__cdecl -#endif -operator delete(void *p) throw(); -#endif - -#endif diff --git a/desmume/src/windows/7z/CPP/Common/StringConvert.cpp b/desmume/src/windows/7z/CPP/Common/StringConvert.cpp deleted file mode 100644 index ebd014831..000000000 --- a/desmume/src/windows/7z/CPP/Common/StringConvert.cpp +++ /dev/null @@ -1,102 +0,0 @@ -// Common/StringConvert.cpp - -#include "StdAfx.h" - -#include "StringConvert.h" - -#ifndef _WIN32 -#include -#endif - -#ifdef _WIN32 -UString MultiByteToUnicodeString(const AString &srcString, UINT codePage) -{ - UString resultString; - if (!srcString.IsEmpty()) - { - int numChars = MultiByteToWideChar(codePage, 0, srcString, - srcString.Length(), resultString.GetBuffer(srcString.Length()), - srcString.Length() + 1); - #ifndef _WIN32_WCE - if (numChars == 0) - throw 282228; - #endif - resultString.ReleaseBuffer(numChars); - } - return resultString; -} - -AString UnicodeStringToMultiByte(const UString &s, UINT codePage, char defaultChar, bool &defaultCharWasUsed) -{ - AString dest; - defaultCharWasUsed = false; - if (!s.IsEmpty()) - { - int numRequiredBytes = s.Length() * 2; - BOOL defUsed; - int numChars = WideCharToMultiByte(codePage, 0, s, s.Length(), - dest.GetBuffer(numRequiredBytes), numRequiredBytes + 1, - &defaultChar, &defUsed); - defaultCharWasUsed = (defUsed != FALSE); - #ifndef _WIN32_WCE - if (numChars == 0) - throw 282229; - #endif - dest.ReleaseBuffer(numChars); - } - return dest; -} - -AString UnicodeStringToMultiByte(const UString &srcString, UINT codePage) -{ - bool defaultCharWasUsed; - return UnicodeStringToMultiByte(srcString, codePage, '_', defaultCharWasUsed); -} - -#ifndef _WIN32_WCE -AString SystemStringToOemString(const CSysString &srcString) -{ - AString result; - CharToOem(srcString, result.GetBuffer(srcString.Length() * 2)); - result.ReleaseBuffer(); - return result; -} -#endif - -#else - -UString MultiByteToUnicodeString(const AString &srcString, UINT codePage) -{ - UString resultString; - for (int i = 0; i < srcString.Length(); i++) - resultString += wchar_t(srcString[i]); - /* - if (!srcString.IsEmpty()) - { - int numChars = mbstowcs(resultString.GetBuffer(srcString.Length()), srcString, srcString.Length() + 1); - if (numChars < 0) throw "Your environment does not support UNICODE"; - resultString.ReleaseBuffer(numChars); - } - */ - return resultString; -} - -AString UnicodeStringToMultiByte(const UString &srcString, UINT codePage) -{ - AString resultString; - for (int i = 0; i < srcString.Length(); i++) - resultString += char(srcString[i]); - /* - if (!srcString.IsEmpty()) - { - int numRequiredBytes = srcString.Length() * 6 + 1; - int numChars = wcstombs(resultString.GetBuffer(numRequiredBytes), srcString, numRequiredBytes); - if (numChars < 0) throw "Your environment does not support UNICODE"; - resultString.ReleaseBuffer(numChars); - } - */ - return resultString; -} - -#endif - diff --git a/desmume/src/windows/7z/CPP/Common/StringConvert.h b/desmume/src/windows/7z/CPP/Common/StringConvert.h deleted file mode 100644 index e0a2332c9..000000000 --- a/desmume/src/windows/7z/CPP/Common/StringConvert.h +++ /dev/null @@ -1,73 +0,0 @@ -// Common/StringConvert.h - -#ifndef __COMMON_STRINGCONVERT_H -#define __COMMON_STRINGCONVERT_H - -#include "MyWindows.h" -#include "MyString.h" -#include "Types.h" - -UString MultiByteToUnicodeString(const AString &srcString, UINT codePage = CP_ACP); -AString UnicodeStringToMultiByte(const UString &srcString, UINT codePage, char defaultChar, bool &defaultCharWasUsed); -AString UnicodeStringToMultiByte(const UString &srcString, UINT codePage = CP_ACP); - - -inline const wchar_t* GetUnicodeString(const wchar_t* unicodeString) - { return unicodeString; } -inline const UString& GetUnicodeString(const UString &unicodeString) - { return unicodeString; } -inline UString GetUnicodeString(const AString &ansiString) - { return MultiByteToUnicodeString(ansiString); } -inline UString GetUnicodeString(const AString &multiByteString, UINT codePage) - { return MultiByteToUnicodeString(multiByteString, codePage); } -inline const wchar_t* GetUnicodeString(const wchar_t* unicodeString, UINT) - { return unicodeString; } -inline const UString& GetUnicodeString(const UString &unicodeString, UINT) - { return unicodeString; } - -inline const char* GetAnsiString(const char* ansiString) - { return ansiString; } -inline const AString& GetAnsiString(const AString &ansiString) - { return ansiString; } -inline AString GetAnsiString(const UString &unicodeString) - { return UnicodeStringToMultiByte(unicodeString); } - -inline const char* GetOemString(const char* oemString) - { return oemString; } -inline const AString& GetOemString(const AString &oemString) - { return oemString; } -inline AString GetOemString(const UString &unicodeString) - { return UnicodeStringToMultiByte(unicodeString, CP_OEMCP); } - - -#ifdef _UNICODE - inline const wchar_t* GetSystemString(const wchar_t* unicodeString) - { return unicodeString;} - inline const UString& GetSystemString(const UString &unicodeString) - { return unicodeString;} - inline const wchar_t* GetSystemString(const wchar_t* unicodeString, UINT /* codePage */) - { return unicodeString;} - inline const UString& GetSystemString(const UString &unicodeString, UINT /* codePage */) - { return unicodeString;} - inline UString GetSystemString(const AString &multiByteString, UINT codePage) - { return MultiByteToUnicodeString(multiByteString, codePage);} - inline UString GetSystemString(const AString &multiByteString) - { return MultiByteToUnicodeString(multiByteString);} -#else - inline const char* GetSystemString(const char *ansiString) - { return ansiString; } - inline const AString& GetSystemString(const AString &multiByteString, UINT) - { return multiByteString; } - inline const char * GetSystemString(const char *multiByteString, UINT) - { return multiByteString; } - inline AString GetSystemString(const UString &unicodeString) - { return UnicodeStringToMultiByte(unicodeString); } - inline AString GetSystemString(const UString &unicodeString, UINT codePage) - { return UnicodeStringToMultiByte(unicodeString, codePage); } -#endif - -#ifndef _WIN32_WCE -AString SystemStringToOemString(const CSysString &srcString); -#endif - -#endif diff --git a/desmume/src/windows/7z/CPP/Common/StringToInt.cpp b/desmume/src/windows/7z/CPP/Common/StringToInt.cpp deleted file mode 100644 index 77ce7c50b..000000000 --- a/desmume/src/windows/7z/CPP/Common/StringToInt.cpp +++ /dev/null @@ -1,90 +0,0 @@ -// Common/StringToInt.cpp - -#include "StdAfx.h" - -#include "StringToInt.h" - -UInt64 ConvertStringToUInt64(const char *s, const char **end) -{ - UInt64 result = 0; - for (;;) - { - char c = *s; - if (c < '0' || c > '9') - { - if (end != NULL) - *end = s; - return result; - } - result *= 10; - result += (c - '0'); - s++; - } -} - -UInt64 ConvertOctStringToUInt64(const char *s, const char **end) -{ - UInt64 result = 0; - for (;;) - { - char c = *s; - if (c < '0' || c > '7') - { - if (end != NULL) - *end = s; - return result; - } - result <<= 3; - result += (c - '0'); - s++; - } -} - -UInt64 ConvertHexStringToUInt64(const char *s, const char **end) -{ - UInt64 result = 0; - for (;;) - { - char c = *s; - UInt32 v; - if (c >= '0' && c <= '9') v = (c - '0'); - else if (c >= 'A' && c <= 'F') v = 10 + (c - 'A'); - else if (c >= 'a' && c <= 'f') v = 10 + (c - 'a'); - else - { - if (end != NULL) - *end = s; - return result; - } - result <<= 4; - result |= v; - s++; - } -} - - -UInt64 ConvertStringToUInt64(const wchar_t *s, const wchar_t **end) -{ - UInt64 result = 0; - for (;;) - { - wchar_t c = *s; - if (c < '0' || c > '9') - { - if (end != NULL) - *end = s; - return result; - } - result *= 10; - result += (c - '0'); - s++; - } -} - - -Int64 ConvertStringToInt64(const char *s, const char **end) -{ - if (*s == '-') - return -(Int64)ConvertStringToUInt64(s + 1, end); - return ConvertStringToUInt64(s, end); -} diff --git a/desmume/src/windows/7z/CPP/Common/StringToInt.h b/desmume/src/windows/7z/CPP/Common/StringToInt.h deleted file mode 100644 index 16a1a4fc8..000000000 --- a/desmume/src/windows/7z/CPP/Common/StringToInt.h +++ /dev/null @@ -1,18 +0,0 @@ -// Common/StringToInt.h - -#ifndef __COMMON_STRINGTOINT_H -#define __COMMON_STRINGTOINT_H - -#include -#include "Types.h" - -UInt64 ConvertStringToUInt64(const char *s, const char **end); -UInt64 ConvertOctStringToUInt64(const char *s, const char **end); -UInt64 ConvertHexStringToUInt64(const char *s, const char **end); -UInt64 ConvertStringToUInt64(const wchar_t *s, const wchar_t **end); - -Int64 ConvertStringToInt64(const char *s, const char **end); - -#endif - - diff --git a/desmume/src/windows/7z/CPP/Common/Types.h b/desmume/src/windows/7z/CPP/Common/Types.h deleted file mode 100644 index ba696772d..000000000 --- a/desmume/src/windows/7z/CPP/Common/Types.h +++ /dev/null @@ -1,14 +0,0 @@ -// Common/Types.h - -#ifndef __COMMON_TYPES_H -#define __COMMON_TYPES_H - -extern "C" -{ -#include "../../C/Types.h" -} - -typedef int HRes; - -#endif - diff --git a/desmume/src/windows/7z/CPP/Common/UTFConvert.cpp b/desmume/src/windows/7z/CPP/Common/UTFConvert.cpp deleted file mode 100644 index dae8f551b..000000000 --- a/desmume/src/windows/7z/CPP/Common/UTFConvert.cpp +++ /dev/null @@ -1,145 +0,0 @@ -// UTFConvert.cpp - -#include "StdAfx.h" - -#include "UTFConvert.h" -#include "Types.h" - -static const Byte kUtf8Limits[5] = { 0xC0, 0xE0, 0xF0, 0xF8, 0xFC }; - -static Bool Utf8_To_Utf16(wchar_t *dest, size_t *destLen, const char *src, size_t srcLen) -{ - size_t destPos = 0, srcPos = 0; - for (;;) - { - Byte c; - int numAdds; - if (srcPos == srcLen) - { - *destLen = destPos; - return True; - } - c = (Byte)src[srcPos++]; - - if (c < 0x80) - { - if (dest) - dest[destPos] = (wchar_t)c; - destPos++; - continue; - } - if (c < 0xC0) - break; - for (numAdds = 1; numAdds < 5; numAdds++) - if (c < kUtf8Limits[numAdds]) - break; - UInt32 value = (c - kUtf8Limits[numAdds - 1]); - - do - { - Byte c2; - if (srcPos == srcLen) - break; - c2 = (Byte)src[srcPos++]; - if (c2 < 0x80 || c2 >= 0xC0) - break; - value <<= 6; - value |= (c2 - 0x80); - } - while (--numAdds != 0); - - if (value < 0x10000) - { - if (dest) - dest[destPos] = (wchar_t)value; - destPos++; - } - else - { - value -= 0x10000; - if (value >= 0x100000) - break; - if (dest) - { - dest[destPos + 0] = (wchar_t)(0xD800 + (value >> 10)); - dest[destPos + 1] = (wchar_t)(0xDC00 + (value & 0x3FF)); - } - destPos += 2; - } - } - *destLen = destPos; - return False; -} - -static Bool Utf16_To_Utf8(char *dest, size_t *destLen, const wchar_t *src, size_t srcLen) -{ - size_t destPos = 0, srcPos = 0; - for (;;) - { - unsigned numAdds; - UInt32 value; - if (srcPos == srcLen) - { - *destLen = destPos; - return True; - } - value = src[srcPos++]; - if (value < 0x80) - { - if (dest) - dest[destPos] = (char)value; - destPos++; - continue; - } - if (value >= 0xD800 && value < 0xE000) - { - UInt32 c2; - if (value >= 0xDC00 || srcPos == srcLen) - break; - c2 = src[srcPos++]; - if (c2 < 0xDC00 || c2 >= 0xE000) - break; - value = ((value - 0xD800) << 10) | (c2 - 0xDC00); - } - for (numAdds = 1; numAdds < 5; numAdds++) - if (value < (((UInt32)1) << (numAdds * 5 + 6))) - break; - if (dest) - dest[destPos] = (char)(kUtf8Limits[numAdds - 1] + (value >> (6 * numAdds))); - destPos++; - do - { - numAdds--; - if (dest) - dest[destPos] = (char)(0x80 + ((value >> (6 * numAdds)) & 0x3F)); - destPos++; - } - while (numAdds != 0); - } - *destLen = destPos; - return False; -} - -bool ConvertUTF8ToUnicode(const AString &src, UString &dest) -{ - dest.Empty(); - size_t destLen = 0; - Utf8_To_Utf16(NULL, &destLen, src, src.Length()); - wchar_t *p = dest.GetBuffer((int)destLen); - Bool res = Utf8_To_Utf16(p, &destLen, src, src.Length()); - p[destLen] = 0; - dest.ReleaseBuffer(); - return res ? true : false; -} - -bool ConvertUnicodeToUTF8(const UString &src, AString &dest) -{ - dest.Empty(); - size_t destLen = 0; - Utf16_To_Utf8(NULL, &destLen, src, src.Length()); - char *p = dest.GetBuffer((int)destLen); - Bool res = Utf16_To_Utf8(p, &destLen, src, src.Length()); - p[destLen] = 0; - dest.ReleaseBuffer(); - return res ? true : false; -} diff --git a/desmume/src/windows/7z/CPP/Common/UTFConvert.h b/desmume/src/windows/7z/CPP/Common/UTFConvert.h deleted file mode 100644 index d55310144..000000000 --- a/desmume/src/windows/7z/CPP/Common/UTFConvert.h +++ /dev/null @@ -1,11 +0,0 @@ -// Common/UTFConvert.h - -#ifndef __COMMON_UTFCONVERT_H -#define __COMMON_UTFCONVERT_H - -#include "MyString.h" - -bool ConvertUTF8ToUnicode(const AString &utfString, UString &resultString); -bool ConvertUnicodeToUTF8(const UString &unicodeString, AString &resultString); - -#endif diff --git a/desmume/src/windows/7z/CPP/Common/Wildcard.cpp b/desmume/src/windows/7z/CPP/Common/Wildcard.cpp deleted file mode 100644 index b4a86cadb..000000000 --- a/desmume/src/windows/7z/CPP/Common/Wildcard.cpp +++ /dev/null @@ -1,458 +0,0 @@ -// Common/Wildcard.cpp - -#include "StdAfx.h" - -#include "Wildcard.h" - -bool g_CaseSensitive = - #ifdef _WIN32 - false; - #else - true; - #endif - -static const wchar_t kAnyCharsChar = L'*'; -static const wchar_t kAnyCharChar = L'?'; - -#ifdef _WIN32 -static const wchar_t kDirDelimiter1 = L'\\'; -#endif -static const wchar_t kDirDelimiter2 = L'/'; - -static const UString kWildCardCharSet = L"?*"; - -static const UString kIllegalWildCardFileNameChars= - L"\x1\x2\x3\x4\x5\x6\x7\x8\x9\xA\xB\xC\xD\xE\xF" - L"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F" - L"\"/:<>\\|"; - - -static inline bool IsCharDirLimiter(wchar_t c) -{ - return ( - #ifdef _WIN32 - c == kDirDelimiter1 || - #endif - c == kDirDelimiter2); -} - -int CompareFileNames(const UString &s1, const UString &s2) -{ - if (g_CaseSensitive) - return s1.Compare(s2); - return s1.CompareNoCase(s2); -} - -// ----------------------------------------- -// this function compares name with mask -// ? - any char -// * - any char or empty - -static bool EnhancedMaskTest(const wchar_t *mask, const wchar_t *name) -{ - for (;;) - { - wchar_t m = *mask; - wchar_t c = *name; - if (m == 0) - return (c == 0); - if (m == kAnyCharsChar) - { - if (EnhancedMaskTest(mask + 1, name)) - return true; - if (c == 0) - return false; - } - else - { - if (m == kAnyCharChar) - { - if (c == 0) - return false; - } - else if (m != c) - if (g_CaseSensitive || MyCharUpper(m) != MyCharUpper(c)) - return false; - mask++; - } - name++; - } -} - -// -------------------------------------------------- -// Splits path to strings - -void SplitPathToParts(const UString &path, UStringVector &pathParts) -{ - pathParts.Clear(); - UString name; - int len = path.Length(); - if (len == 0) - return; - for (int i = 0; i < len; i++) - { - wchar_t c = path[i]; - if (IsCharDirLimiter(c)) - { - pathParts.Add(name); - name.Empty(); - } - else - name += c; - } - pathParts.Add(name); -} - -void SplitPathToParts(const UString &path, UString &dirPrefix, UString &name) -{ - int i; - for (i = path.Length() - 1; i >= 0; i--) - if (IsCharDirLimiter(path[i])) - break; - dirPrefix = path.Left(i + 1); - name = path.Mid(i + 1); -} - -UString ExtractDirPrefixFromPath(const UString &path) -{ - int i; - for (i = path.Length() - 1; i >= 0; i--) - if (IsCharDirLimiter(path[i])) - break; - return path.Left(i + 1); -} - -UString ExtractFileNameFromPath(const UString &path) -{ - int i; - for (i = path.Length() - 1; i >= 0; i--) - if (IsCharDirLimiter(path[i])) - break; - return path.Mid(i + 1); -} - - -bool CompareWildCardWithName(const UString &mask, const UString &name) -{ - return EnhancedMaskTest(mask, name); -} - -bool DoesNameContainWildCard(const UString &path) -{ - return (path.FindOneOf(kWildCardCharSet) >= 0); -} - - -// ----------------------------------------------------------' -// NWildcard - -namespace NWildcard { - - -/* -M = MaskParts.Size(); -N = TestNameParts.Size(); - - File Dir -ForFile req M<=N [N-M, N) - - nonreq M=N [0, M) - - -ForDir req M 1) - return true; - } - return false; -} - -bool CCensorNode::AreThereIncludeItems() const -{ - if (IncludeItems.Size() > 0) - return true; - for (int i = 0; i < SubNodes.Size(); i++) - if (SubNodes[i].AreThereIncludeItems()) - return true; - return false; -} - -bool CCensorNode::CheckPathCurrent(bool include, const UStringVector &pathParts, bool isFile) const -{ - const CObjectVector &items = include ? IncludeItems : ExcludeItems; - for (int i = 0; i < items.Size(); i++) - if (items[i].CheckPath(pathParts, isFile)) - return true; - return false; -} - -bool CCensorNode::CheckPath(UStringVector &pathParts, bool isFile, bool &include) const -{ - if (CheckPathCurrent(false, pathParts, isFile)) - { - include = false; - return true; - } - include = true; - bool finded = CheckPathCurrent(true, pathParts, isFile); - if (pathParts.Size() == 1) - return finded; - int index = FindSubNode(pathParts.Front()); - if (index >= 0) - { - UStringVector pathParts2 = pathParts; - pathParts2.Delete(0); - if (SubNodes[index].CheckPath(pathParts2, isFile, include)) - return true; - } - return finded; -} - -bool CCensorNode::CheckPath(const UString &path, bool isFile, bool &include) const -{ - UStringVector pathParts; - SplitPathToParts(path, pathParts); - return CheckPath(pathParts, isFile, include); -} - -bool CCensorNode::CheckPath(const UString &path, bool isFile) const -{ - bool include; - if (CheckPath(path, isFile, include)) - return include; - return false; -} - -bool CCensorNode::CheckPathToRoot(bool include, UStringVector &pathParts, bool isFile) const -{ - if (CheckPathCurrent(include, pathParts, isFile)) - return true; - if (Parent == 0) - return false; - pathParts.Insert(0, Name); - return Parent->CheckPathToRoot(include, pathParts, isFile); -} - -/* -bool CCensorNode::CheckPathToRoot(bool include, const UString &path, bool isFile) const -{ - UStringVector pathParts; - SplitPathToParts(path, pathParts); - return CheckPathToRoot(include, pathParts, isFile); -} -*/ - -void CCensorNode::AddItem2(bool include, const UString &path, bool recursive) -{ - if (path.IsEmpty()) - return; - bool forFile = true; - bool forFolder = true; - UString path2 = path; - if (IsCharDirLimiter(path[path.Length() - 1])) - { - path2.Delete(path.Length() - 1); - forFile = false; - } - AddItem(include, path2, recursive, forFile, forFolder); -} - -void CCensorNode::ExtendExclude(const CCensorNode &fromNodes) -{ - ExcludeItems += fromNodes.ExcludeItems; - for (int i = 0; i < fromNodes.SubNodes.Size(); i++) - { - const CCensorNode &node = fromNodes.SubNodes[i]; - int subNodeIndex = FindSubNode(node.Name); - if (subNodeIndex < 0) - subNodeIndex = SubNodes.Add(CCensorNode(node.Name, this)); - SubNodes[subNodeIndex].ExtendExclude(node); - } -} - -int CCensor::FindPrefix(const UString &prefix) const -{ - for (int i = 0; i < Pairs.Size(); i++) - if (CompareFileNames(Pairs[i].Prefix, prefix) == 0) - return i; - return -1; -} - -void CCensor::AddItem(bool include, const UString &path, bool recursive) -{ - UStringVector pathParts; - SplitPathToParts(path, pathParts); - bool forFile = true; - if (pathParts.Back().IsEmpty()) - { - forFile = false; - pathParts.DeleteBack(); - } - const UString &front = pathParts.Front(); - bool isAbs = false; - if (front.IsEmpty()) - isAbs = true; - else if (front.Length() == 2 && front[1] == L':') - isAbs = true; - else - { - for (int i = 0; i < pathParts.Size(); i++) - { - const UString &part = pathParts[i]; - if (part == L".." || part == L".") - { - isAbs = true; - break; - } - } - } - int numAbsParts = 0; - if (isAbs) - if (pathParts.Size() > 1) - numAbsParts = pathParts.Size() - 1; - else - numAbsParts = 1; - UString prefix; - for (int i = 0; i < numAbsParts; i++) - { - const UString &front = pathParts.Front(); - if (DoesNameContainWildCard(front)) - break; - prefix += front; - prefix += WCHAR_PATH_SEPARATOR; - pathParts.Delete(0); - } - int index = FindPrefix(prefix); - if (index < 0) - index = Pairs.Add(CPair(prefix)); - - CItem item; - item.PathParts = pathParts; - item.ForDir = true; - item.ForFile = forFile; - item.Recursive = recursive; - Pairs[index].Head.AddItem(include, item); -} - -bool CCensor::CheckPath(const UString &path, bool isFile) const -{ - bool finded = false; - for (int i = 0; i < Pairs.Size(); i++) - { - bool include; - if (Pairs[i].Head.CheckPath(path, isFile, include)) - { - if (!include) - return false; - finded = true; - } - } - return finded; -} - -void CCensor::ExtendExclude() -{ - int i; - for (i = 0; i < Pairs.Size(); i++) - if (Pairs[i].Prefix.IsEmpty()) - break; - if (i == Pairs.Size()) - return; - int index = i; - for (i = 0; i < Pairs.Size(); i++) - if (index != i) - Pairs[i].Head.ExtendExclude(Pairs[index].Head); -} - -} diff --git a/desmume/src/windows/7z/CPP/Common/Wildcard.h b/desmume/src/windows/7z/CPP/Common/Wildcard.h deleted file mode 100644 index e2a42c831..000000000 --- a/desmume/src/windows/7z/CPP/Common/Wildcard.h +++ /dev/null @@ -1,80 +0,0 @@ -// Common/Wildcard.h - -#ifndef __COMMON_WILDCARD_H -#define __COMMON_WILDCARD_H - -#include "MyString.h" - -int CompareFileNames(const UString &s1, const UString &s2); - -void SplitPathToParts(const UString &path, UStringVector &pathParts); -void SplitPathToParts(const UString &path, UString &dirPrefix, UString &name); -UString ExtractDirPrefixFromPath(const UString &path); -UString ExtractFileNameFromPath(const UString &path); -bool DoesNameContainWildCard(const UString &path); -bool CompareWildCardWithName(const UString &mask, const UString &name); - -namespace NWildcard { - -struct CItem -{ - UStringVector PathParts; - bool Recursive; - bool ForFile; - bool ForDir; - bool CheckPath(const UStringVector &pathParts, bool isFile) const; -}; - -class CCensorNode -{ - CCensorNode *Parent; - bool CheckPathCurrent(bool include, const UStringVector &pathParts, bool isFile) const; - void AddItemSimple(bool include, CItem &item); - bool CheckPath(UStringVector &pathParts, bool isFile, bool &include) const; -public: - CCensorNode(): Parent(0) { }; - CCensorNode(const UString &name, CCensorNode *parent): Name(name), Parent(parent) { }; - UString Name; - CObjectVector SubNodes; - CObjectVector IncludeItems; - CObjectVector ExcludeItems; - - int FindSubNode(const UString &path) const; - - void AddItem(bool include, CItem &item); - void AddItem(bool include, const UString &path, bool recursive, bool forFile, bool forDir); - void AddItem2(bool include, const UString &path, bool recursive); - - bool NeedCheckSubDirs() const; - bool AreThereIncludeItems() const; - - bool CheckPath(const UString &path, bool isFile, bool &include) const; - bool CheckPath(const UString &path, bool isFile) const; - - bool CheckPathToRoot(bool include, UStringVector &pathParts, bool isFile) const; - // bool CheckPathToRoot(const UString &path, bool isFile, bool include) const; - void ExtendExclude(const CCensorNode &fromNodes); -}; - -struct CPair -{ - UString Prefix; - CCensorNode Head; - CPair(const UString &prefix): Prefix(prefix) { }; -}; - -class CCensor -{ - int FindPrefix(const UString &prefix) const; -public: - CObjectVector Pairs; - bool AllAreRelative() const - { return (Pairs.Size() == 1 && Pairs.Front().Prefix.IsEmpty()); } - void AddItem(bool include, const UString &path, bool recursive); - bool CheckPath(const UString &path, bool isFile) const; - void ExtendExclude(); -}; - -} - -#endif diff --git a/desmume/src/windows/7z/CPP/Windows/Defs.h b/desmume/src/windows/7z/CPP/Windows/Defs.h deleted file mode 100644 index e8a655a4b..000000000 --- a/desmume/src/windows/7z/CPP/Windows/Defs.h +++ /dev/null @@ -1,23 +0,0 @@ -// Windows/Defs.h - -#ifndef __WINDOWS_DEFS_H -#define __WINDOWS_DEFS_H - -inline bool BOOLToBool(BOOL value) - { return (value != FALSE); } - -#ifdef _WIN32 -inline bool LRESULTToBool(LRESULT value) - { return (value != FALSE); } -#endif - -inline BOOL BoolToBOOL(bool value) - { return (value ? TRUE: FALSE); } - -inline VARIANT_BOOL BoolToVARIANT_BOOL(bool value) - { return (value ? VARIANT_TRUE: VARIANT_FALSE); } - -inline bool VARIANT_BOOLToBool(VARIANT_BOOL value) - { return (value != VARIANT_FALSE); } - -#endif diff --git a/desmume/src/windows/7z/CPP/Windows/FileDir.cpp b/desmume/src/windows/7z/CPP/Windows/FileDir.cpp deleted file mode 100644 index 38eb1083c..000000000 --- a/desmume/src/windows/7z/CPP/Windows/FileDir.cpp +++ /dev/null @@ -1,841 +0,0 @@ -// Windows/FileDir.cpp - -#include "StdAfx.h" - -#include "FileDir.h" -#include "FileName.h" -#include "FileFind.h" -#include "Defs.h" -#ifndef _UNICODE -#include "../Common/StringConvert.h" -#endif - -#ifndef _UNICODE -extern bool g_IsNT; -#endif - -namespace NWindows { -namespace NFile { - -#if defined(WIN_LONG_PATH) && defined(_UNICODE) -#define WIN_LONG_PATH2 -#endif - -// SetCurrentDirectory doesn't support \\?\ prefix - -#ifdef WIN_LONG_PATH -bool GetLongPathBase(LPCWSTR fileName, UString &res); -bool GetLongPath(LPCWSTR fileName, UString &res); -#endif - -namespace NDirectory { - -#ifndef _UNICODE -static inline UINT GetCurrentCodePage() { return ::AreFileApisANSI() ? CP_ACP : CP_OEMCP; } -static UString GetUnicodePath(const CSysString &sysPath) - { return MultiByteToUnicodeString(sysPath, GetCurrentCodePage()); } -static CSysString GetSysPath(LPCWSTR sysPath) - { return UnicodeStringToMultiByte(sysPath, GetCurrentCodePage()); } -#endif - -bool MyGetWindowsDirectory(CSysString &path) -{ - UINT needLength = ::GetWindowsDirectory(path.GetBuffer(MAX_PATH + 1), MAX_PATH + 1); - path.ReleaseBuffer(); - return (needLength > 0 && needLength <= MAX_PATH); -} - -bool MyGetSystemDirectory(CSysString &path) -{ - UINT needLength = ::GetSystemDirectory(path.GetBuffer(MAX_PATH + 1), MAX_PATH + 1); - path.ReleaseBuffer(); - return (needLength > 0 && needLength <= MAX_PATH); -} - -#ifndef _UNICODE -bool MyGetWindowsDirectory(UString &path) -{ - if (g_IsNT) - { - UINT needLength = ::GetWindowsDirectoryW(path.GetBuffer(MAX_PATH + 1), MAX_PATH + 1); - path.ReleaseBuffer(); - return (needLength > 0 && needLength <= MAX_PATH); - } - CSysString sysPath; - if (!MyGetWindowsDirectory(sysPath)) - return false; - path = GetUnicodePath(sysPath); - return true; -} - -bool MyGetSystemDirectory(UString &path) -{ - if (g_IsNT) - { - UINT needLength = ::GetSystemDirectoryW(path.GetBuffer(MAX_PATH + 1), MAX_PATH + 1); - path.ReleaseBuffer(); - return (needLength > 0 && needLength <= MAX_PATH); - } - CSysString sysPath; - if (!MyGetSystemDirectory(sysPath)) - return false; - path = GetUnicodePath(sysPath); - return true; -} -#endif - -bool SetDirTime(LPCWSTR fileName, const FILETIME *cTime, const FILETIME *aTime, const FILETIME *mTime) -{ - #ifndef _UNICODE - if (!g_IsNT) - { - ::SetLastError(ERROR_CALL_NOT_IMPLEMENTED); - return false; - } - #endif - HANDLE hDir = ::CreateFileW(fileName, GENERIC_WRITE, - FILE_SHARE_READ | FILE_SHARE_WRITE, - NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL); - #ifdef WIN_LONG_PATH - if (hDir == INVALID_HANDLE_VALUE) - { - UString longPath; - if (GetLongPath(fileName, longPath)) - hDir = ::CreateFileW(longPath, GENERIC_WRITE, - FILE_SHARE_READ | FILE_SHARE_WRITE, - NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL); - } - #endif - - bool res = false; - if (hDir != INVALID_HANDLE_VALUE) - { - res = BOOLToBool(::SetFileTime(hDir, cTime, aTime, mTime)); - ::CloseHandle(hDir); - } - return res; -} - -bool MySetFileAttributes(LPCTSTR fileName, DWORD fileAttributes) -{ - if (::SetFileAttributes(fileName, fileAttributes)) - return true; - #ifdef WIN_LONG_PATH2 - UString longPath; - if (GetLongPath(fileName, longPath)) - return BOOLToBool(::SetFileAttributesW(longPath, fileAttributes)); - #endif - return false; -} - -bool MyRemoveDirectory(LPCTSTR pathName) -{ - if (::RemoveDirectory(pathName)) - return true; - #ifdef WIN_LONG_PATH2 - UString longPath; - if (GetLongPath(pathName, longPath)) - return BOOLToBool(::RemoveDirectoryW(longPath)); - #endif - return false; -} - -#ifdef WIN_LONG_PATH -bool GetLongPaths(LPCWSTR s1, LPCWSTR s2, UString &d1, UString &d2) -{ - if (!GetLongPathBase(s1, d1) || !GetLongPathBase(s2, d2)) - return false; - if (d1.IsEmpty() && d2.IsEmpty()) return false; - if (d1.IsEmpty()) d1 = s1; - if (d2.IsEmpty()) d2 = s2; - return true; -} -#endif - -bool MyMoveFile(LPCTSTR existFileName, LPCTSTR newFileName) -{ - if (::MoveFile(existFileName, newFileName)) - return true; - #ifdef WIN_LONG_PATH2 - UString d1, d2; - if (GetLongPaths(existFileName, newFileName, d1, d2)) - return BOOLToBool(::MoveFileW(d1, d2)); - #endif - return false; -} - -#ifndef _UNICODE -bool MySetFileAttributes(LPCWSTR fileName, DWORD fileAttributes) -{ - if (!g_IsNT) - return MySetFileAttributes(GetSysPath(fileName), fileAttributes); - if (::SetFileAttributesW(fileName, fileAttributes)) - return true; - #ifdef WIN_LONG_PATH - UString longPath; - if (GetLongPath(fileName, longPath)) - return BOOLToBool(::SetFileAttributesW(longPath, fileAttributes)); - #endif - return false; -} - - -bool MyRemoveDirectory(LPCWSTR pathName) -{ - if (!g_IsNT) - return MyRemoveDirectory(GetSysPath(pathName)); - if (::RemoveDirectoryW(pathName)) - return true; - #ifdef WIN_LONG_PATH - UString longPath; - if (GetLongPath(pathName, longPath)) - return BOOLToBool(::RemoveDirectoryW(longPath)); - #endif - return false; -} - -bool MyMoveFile(LPCWSTR existFileName, LPCWSTR newFileName) -{ - if (!g_IsNT) - return MyMoveFile(GetSysPath(existFileName), GetSysPath(newFileName)); - if (::MoveFileW(existFileName, newFileName)) - return true; - #ifdef WIN_LONG_PATH - UString d1, d2; - if (GetLongPaths(existFileName, newFileName, d1, d2)) - return BOOLToBool(::MoveFileW(d1, d2)); - #endif - return false; -} -#endif - -bool MyCreateDirectory(LPCTSTR pathName) -{ - if (::CreateDirectory(pathName, NULL)) - return true; - #ifdef WIN_LONG_PATH2 - if (::GetLastError() != ERROR_ALREADY_EXISTS) - { - UString longPath; - if (GetLongPath(pathName, longPath)) - return BOOLToBool(::CreateDirectoryW(longPath, NULL)); - } - #endif - return false; -} - -#ifndef _UNICODE -bool MyCreateDirectory(LPCWSTR pathName) -{ - if (!g_IsNT) - return MyCreateDirectory(GetSysPath(pathName)); - if (::CreateDirectoryW(pathName, NULL)) - return true; - #ifdef WIN_LONG_PATH - if (::GetLastError() != ERROR_ALREADY_EXISTS) - { - UString longPath; - if (GetLongPath(pathName, longPath)) - return BOOLToBool(::CreateDirectoryW(longPath, NULL)); - } - #endif - return false; -} -#endif - -/* -bool CreateComplexDirectory(LPCTSTR pathName) -{ - NName::CParsedPath path; - path.ParsePath(pathName); - CSysString fullPath = path.Prefix; - DWORD errorCode = ERROR_SUCCESS; - for (int i = 0; i < path.PathParts.Size(); i++) - { - const CSysString &string = path.PathParts[i]; - if (string.IsEmpty()) - { - if (i != path.PathParts.Size() - 1) - return false; - return true; - } - fullPath += path.PathParts[i]; - if (!MyCreateDirectory(fullPath)) - { - DWORD errorCode = GetLastError(); - if (errorCode != ERROR_ALREADY_EXISTS) - return false; - } - fullPath += NName::kDirDelimiter; - } - return true; -} -*/ - -bool CreateComplexDirectory(LPCTSTR _aPathName) -{ - CSysString pathName = _aPathName; - int pos = pathName.ReverseFind(TEXT(CHAR_PATH_SEPARATOR)); - if (pos > 0 && pos == pathName.Length() - 1) - { - if (pathName.Length() == 3 && pathName[1] == ':') - return true; // Disk folder; - pathName.Delete(pos); - } - CSysString pathName2 = pathName; - pos = pathName.Length(); - for (;;) - { - if (MyCreateDirectory(pathName)) - break; - if (::GetLastError() == ERROR_ALREADY_EXISTS) - { - NFind::CFileInfo fileInfo; - if (!NFind::FindFile(pathName, fileInfo)) // For network folders - return true; - if (!fileInfo.IsDir()) - return false; - break; - } - pos = pathName.ReverseFind(TEXT(CHAR_PATH_SEPARATOR)); - if (pos < 0 || pos == 0) - return false; - if (pathName[pos - 1] == ':') - return false; - pathName = pathName.Left(pos); - } - pathName = pathName2; - while (pos < pathName.Length()) - { - pos = pathName.Find(TEXT(CHAR_PATH_SEPARATOR), pos + 1); - if (pos < 0) - pos = pathName.Length(); - if (!MyCreateDirectory(pathName.Left(pos))) - return false; - } - return true; -} - -#ifndef _UNICODE - -bool CreateComplexDirectory(LPCWSTR _aPathName) -{ - UString pathName = _aPathName; - int pos = pathName.ReverseFind(WCHAR_PATH_SEPARATOR); - if (pos > 0 && pos == pathName.Length() - 1) - { - if (pathName.Length() == 3 && pathName[1] == L':') - return true; // Disk folder; - pathName.Delete(pos); - } - UString pathName2 = pathName; - pos = pathName.Length(); - for (;;) - { - if (MyCreateDirectory(pathName)) - break; - if (::GetLastError() == ERROR_ALREADY_EXISTS) - { - NFind::CFileInfoW fileInfo; - if (!NFind::FindFile(pathName, fileInfo)) // For network folders - return true; - if (!fileInfo.IsDir()) - return false; - break; - } - pos = pathName.ReverseFind(WCHAR_PATH_SEPARATOR); - if (pos < 0 || pos == 0) - return false; - if (pathName[pos - 1] == L':') - return false; - pathName = pathName.Left(pos); - } - pathName = pathName2; - while (pos < pathName.Length()) - { - pos = pathName.Find(WCHAR_PATH_SEPARATOR, pos + 1); - if (pos < 0) - pos = pathName.Length(); - if (!MyCreateDirectory(pathName.Left(pos))) - return false; - } - return true; -} - -#endif - -bool DeleteFileAlways(LPCTSTR name) -{ - if (!MySetFileAttributes(name, 0)) - return false; - if (::DeleteFile(name)) - return true; - #ifdef WIN_LONG_PATH2 - UString longPath; - if (GetLongPath(name, longPath)) - return BOOLToBool(::DeleteFileW(longPath)); - #endif - return false; -} - -#ifndef _UNICODE -bool DeleteFileAlways(LPCWSTR name) -{ - if (!g_IsNT) - return DeleteFileAlways(GetSysPath(name)); - if (!MySetFileAttributes(name, 0)) - return false; - if (::DeleteFileW(name)) - return true; - #ifdef WIN_LONG_PATH - UString longPath; - if (GetLongPath(name, longPath)) - return BOOLToBool(::DeleteFileW(longPath)); - #endif - return false; -} -#endif - -static bool RemoveDirectorySubItems2(const CSysString pathPrefix, const NFind::CFileInfo &fileInfo) -{ - if (fileInfo.IsDir()) - return RemoveDirectoryWithSubItems(pathPrefix + fileInfo.Name); - return DeleteFileAlways(pathPrefix + fileInfo.Name); -} - -bool RemoveDirectoryWithSubItems(const CSysString &path) -{ - NFind::CFileInfo fileInfo; - CSysString pathPrefix = path + NName::kDirDelimiter; - { - NFind::CEnumerator enumerator(pathPrefix + TCHAR(NName::kAnyStringWildcard)); - while (enumerator.Next(fileInfo)) - if (!RemoveDirectorySubItems2(pathPrefix, fileInfo)) - return false; - } - if (!MySetFileAttributes(path, 0)) - return false; - return MyRemoveDirectory(path); -} - -#ifndef _UNICODE -static bool RemoveDirectorySubItems2(const UString pathPrefix, const NFind::CFileInfoW &fileInfo) -{ - if (fileInfo.IsDir()) - return RemoveDirectoryWithSubItems(pathPrefix + fileInfo.Name); - return DeleteFileAlways(pathPrefix + fileInfo.Name); -} -bool RemoveDirectoryWithSubItems(const UString &path) -{ - NFind::CFileInfoW fileInfo; - UString pathPrefix = path + UString(NName::kDirDelimiter); - { - NFind::CEnumeratorW enumerator(pathPrefix + UString(NName::kAnyStringWildcard)); - while (enumerator.Next(fileInfo)) - if (!RemoveDirectorySubItems2(pathPrefix, fileInfo)) - return false; - } - if (!MySetFileAttributes(path, 0)) - return false; - return MyRemoveDirectory(path); -} -#endif - -#ifndef _WIN32_WCE - -bool MyGetShortPathName(LPCTSTR longPath, CSysString &shortPath) -{ - DWORD needLength = ::GetShortPathName(longPath, shortPath.GetBuffer(MAX_PATH + 1), MAX_PATH + 1); - shortPath.ReleaseBuffer(); - return (needLength > 0 && needLength < MAX_PATH); -} - -bool MyGetFullPathName(LPCTSTR fileName, CSysString &resultPath, int &fileNamePartStartIndex) -{ - resultPath.Empty(); - LPTSTR fileNamePointer = 0; - LPTSTR buffer = resultPath.GetBuffer(MAX_PATH); - DWORD needLength = ::GetFullPathName(fileName, MAX_PATH + 1, buffer, &fileNamePointer); - resultPath.ReleaseBuffer(); - if (needLength == 0) - return false; - if (needLength >= MAX_PATH) - { - #ifdef WIN_LONG_PATH2 - needLength++; - buffer = resultPath.GetBuffer(needLength + 1); - DWORD needLength2 = ::GetFullPathNameW(fileName, needLength, buffer, &fileNamePointer); - resultPath.ReleaseBuffer(); - if (needLength2 == 0 || needLength2 > needLength) - #endif - return false; - } - if (fileNamePointer == 0) - fileNamePartStartIndex = lstrlen(fileName); - else - fileNamePartStartIndex = (int)(fileNamePointer - buffer); - return true; -} - -#ifndef _UNICODE -bool MyGetFullPathName(LPCWSTR fileName, UString &resultPath, int &fileNamePartStartIndex) -{ - resultPath.Empty(); - if (g_IsNT) - { - LPWSTR fileNamePointer = 0; - LPWSTR buffer = resultPath.GetBuffer(MAX_PATH); - DWORD needLength = ::GetFullPathNameW(fileName, MAX_PATH + 1, buffer, &fileNamePointer); - resultPath.ReleaseBuffer(); - if (needLength == 0) - return false; - if (needLength >= MAX_PATH) - { - #ifdef WIN_LONG_PATH - needLength++; - buffer = resultPath.GetBuffer(needLength + 1); - DWORD needLength2 = ::GetFullPathNameW(fileName, needLength, buffer, &fileNamePointer); - resultPath.ReleaseBuffer(); - if (needLength2 == 0 || needLength2 > needLength) - #endif - return false; - } - if (fileNamePointer == 0) - fileNamePartStartIndex = MyStringLen(fileName); - else - fileNamePartStartIndex = (int)(fileNamePointer - buffer); - } - else - { - CSysString sysPath; - if (!MyGetFullPathName(GetSysPath(fileName), sysPath, fileNamePartStartIndex)) - return false; - UString resultPath1 = GetUnicodePath(sysPath.Left(fileNamePartStartIndex)); - UString resultPath2 = GetUnicodePath(sysPath.Mid(fileNamePartStartIndex)); - fileNamePartStartIndex = resultPath1.Length(); - resultPath = resultPath1 + resultPath2; - } - return true; -} -#endif - - -bool MyGetFullPathName(LPCTSTR fileName, CSysString &path) -{ - int index; - return MyGetFullPathName(fileName, path, index); -} - -#ifndef _UNICODE -bool MyGetFullPathName(LPCWSTR fileName, UString &path) -{ - int index; - return MyGetFullPathName(fileName, path, index); -} -#endif - -bool GetOnlyName(LPCTSTR fileName, CSysString &resultName) -{ - int index; - if (!MyGetFullPathName(fileName, resultName, index)) - return false; - resultName = resultName.Mid(index); - return true; -} - -#ifndef _UNICODE -bool GetOnlyName(LPCWSTR fileName, UString &resultName) -{ - int index; - if (!MyGetFullPathName(fileName, resultName, index)) - return false; - resultName = resultName.Mid(index); - return true; -} -#endif - -bool GetOnlyDirPrefix(LPCTSTR fileName, CSysString &resultName) -{ - int index; - if (!MyGetFullPathName(fileName, resultName, index)) - return false; - resultName = resultName.Left(index); - return true; -} - -#ifndef _UNICODE -bool GetOnlyDirPrefix(LPCWSTR fileName, UString &resultName) -{ - int index; - if (!MyGetFullPathName(fileName, resultName, index)) - return false; - resultName = resultName.Left(index); - return true; -} -#endif - -bool MyGetCurrentDirectory(CSysString &path) -{ - DWORD needLength = ::GetCurrentDirectory(MAX_PATH + 1, path.GetBuffer(MAX_PATH + 1)); - path.ReleaseBuffer(); - return (needLength > 0 && needLength <= MAX_PATH); -} - -#ifndef _UNICODE -bool MySetCurrentDirectory(LPCWSTR path) -{ - if (g_IsNT) - return BOOLToBool(::SetCurrentDirectoryW(path)); - return MySetCurrentDirectory(GetSysPath(path)); -} -bool MyGetCurrentDirectory(UString &path) -{ - if (g_IsNT) - { - DWORD needLength = ::GetCurrentDirectoryW(MAX_PATH + 1, path.GetBuffer(MAX_PATH + 1)); - path.ReleaseBuffer(); - return (needLength > 0 && needLength <= MAX_PATH); - } - CSysString sysPath; - if (!MyGetCurrentDirectory(sysPath)) - return false; - path = GetUnicodePath(sysPath); - return true; -} -#endif -#endif - -bool MySearchPath(LPCTSTR path, LPCTSTR fileName, LPCTSTR extension, - CSysString &resultPath, UINT32 &filePart) -{ - LPTSTR filePartPointer; - DWORD value = ::SearchPath(path, fileName, extension, - MAX_PATH, resultPath.GetBuffer(MAX_PATH + 1), &filePartPointer); - filePart = (UINT32)(filePartPointer - (LPCTSTR)resultPath); - resultPath.ReleaseBuffer(); - return (value > 0 && value <= MAX_PATH); -} - -#ifndef _UNICODE -bool MySearchPath(LPCWSTR path, LPCWSTR fileName, LPCWSTR extension, - UString &resultPath, UINT32 &filePart) -{ - if (g_IsNT) - { - LPWSTR filePartPointer = 0; - DWORD value = ::SearchPathW(path, fileName, extension, - MAX_PATH, resultPath.GetBuffer(MAX_PATH + 1), &filePartPointer); - filePart = (UINT32)(filePartPointer - (LPCWSTR)resultPath); - resultPath.ReleaseBuffer(); - return (value > 0 && value <= MAX_PATH); - } - - CSysString sysPath; - if (!MySearchPath( - path != 0 ? (LPCTSTR)GetSysPath(path): 0, - fileName != 0 ? (LPCTSTR)GetSysPath(fileName): 0, - extension != 0 ? (LPCTSTR)GetSysPath(extension): 0, - sysPath, filePart)) - return false; - UString resultPath1 = GetUnicodePath(sysPath.Left(filePart)); - UString resultPath2 = GetUnicodePath(sysPath.Mid(filePart)); - filePart = resultPath1.Length(); - resultPath = resultPath1 + resultPath2; - return true; -} -#endif - -bool MyGetTempPath(CSysString &path) -{ - DWORD needLength = ::GetTempPath(MAX_PATH + 1, path.GetBuffer(MAX_PATH + 1)); - path.ReleaseBuffer(); - return (needLength > 0 && needLength <= MAX_PATH); -} - -#ifndef _UNICODE -bool MyGetTempPath(UString &path) -{ - path.Empty(); - if (g_IsNT) - { - DWORD needLength = ::GetTempPathW(MAX_PATH + 1, path.GetBuffer(MAX_PATH + 1)); - path.ReleaseBuffer(); - return (needLength > 0 && needLength <= MAX_PATH); - } - CSysString sysPath; - if (!MyGetTempPath(sysPath)) - return false; - path = GetUnicodePath(sysPath); - return true; -} -#endif - -UINT MyGetTempFileName(LPCTSTR dirPath, LPCTSTR prefix, CSysString &path) -{ - UINT number = ::GetTempFileName(dirPath, prefix, 0, path.GetBuffer(MAX_PATH + 1)); - path.ReleaseBuffer(); - return number; -} - -#ifndef _UNICODE -UINT MyGetTempFileName(LPCWSTR dirPath, LPCWSTR prefix, UString &path) -{ - if (g_IsNT) - { - UINT number = ::GetTempFileNameW(dirPath, prefix, 0, path.GetBuffer(MAX_PATH)); - path.ReleaseBuffer(); - return number; - } - CSysString sysPath; - UINT number = MyGetTempFileName( - dirPath ? (LPCTSTR)GetSysPath(dirPath): 0, - prefix ? (LPCTSTR)GetSysPath(prefix): 0, - sysPath); - path = GetUnicodePath(sysPath); - return number; -} -#endif - -UINT CTempFile::Create(LPCTSTR dirPath, LPCTSTR prefix, CSysString &resultPath) -{ - Remove(); - UINT number = MyGetTempFileName(dirPath, prefix, resultPath); - if (number != 0) - { - _fileName = resultPath; - _mustBeDeleted = true; - } - return number; -} - -bool CTempFile::Create(LPCTSTR prefix, CSysString &resultPath) -{ - CSysString tempPath; - if (!MyGetTempPath(tempPath)) - return false; - if (Create(tempPath, prefix, resultPath) != 0) - return true; - if (!MyGetWindowsDirectory(tempPath)) - return false; - return (Create(tempPath, prefix, resultPath) != 0); -} - -bool CTempFile::Remove() -{ - if (!_mustBeDeleted) - return true; - _mustBeDeleted = !DeleteFileAlways(_fileName); - return !_mustBeDeleted; -} - -#ifndef _UNICODE - -UINT CTempFileW::Create(LPCWSTR dirPath, LPCWSTR prefix, UString &resultPath) -{ - Remove(); - UINT number = MyGetTempFileName(dirPath, prefix, resultPath); - if (number != 0) - { - _fileName = resultPath; - _mustBeDeleted = true; - } - return number; -} - -bool CTempFileW::Create(LPCWSTR prefix, UString &resultPath) -{ - UString tempPath; - if (!MyGetTempPath(tempPath)) - return false; - if (Create(tempPath, prefix, resultPath) != 0) - return true; - if (!MyGetWindowsDirectory(tempPath)) - return false; - return (Create(tempPath, prefix, resultPath) != 0); -} - -bool CTempFileW::Remove() -{ - if (!_mustBeDeleted) - return true; - _mustBeDeleted = !DeleteFileAlways(_fileName); - return !_mustBeDeleted; -} - -#endif - -bool CreateTempDirectory(LPCTSTR prefix, CSysString &dirName) -{ - /* - CSysString prefix = tempPath + prefixChars; - CRandom random; - random.Init(); - */ - for (;;) - { - CTempFile tempFile; - if (!tempFile.Create(prefix, dirName)) - return false; - if (!::DeleteFile(dirName)) - return false; - /* - UINT32 randomNumber = random.Generate(); - TCHAR randomNumberString[32]; - _stprintf(randomNumberString, _T("%04X"), randomNumber); - dirName = prefix + randomNumberString; - */ - if (NFind::DoesFileExist(dirName)) - continue; - if (MyCreateDirectory(dirName)) - return true; - if (::GetLastError() != ERROR_ALREADY_EXISTS) - return false; - } -} - -bool CTempDirectory::Create(LPCTSTR prefix) -{ - Remove(); - return (_mustBeDeleted = CreateTempDirectory(prefix, _tempDir)); -} - -#ifndef _UNICODE - -bool CreateTempDirectory(LPCWSTR prefix, UString &dirName) -{ - /* - CSysString prefix = tempPath + prefixChars; - CRandom random; - random.Init(); - */ - for (;;) - { - CTempFileW tempFile; - if (!tempFile.Create(prefix, dirName)) - return false; - if (!DeleteFileAlways(dirName)) - return false; - /* - UINT32 randomNumber = random.Generate(); - TCHAR randomNumberString[32]; - _stprintf(randomNumberString, _T("%04X"), randomNumber); - dirName = prefix + randomNumberString; - */ - if (NFind::DoesFileExist(dirName)) - continue; - if (MyCreateDirectory(dirName)) - return true; - if (::GetLastError() != ERROR_ALREADY_EXISTS) - return false; - } -} - -bool CTempDirectoryW::Create(LPCWSTR prefix) -{ - Remove(); - return (_mustBeDeleted = CreateTempDirectory(prefix, _tempDir)); -} - -#endif - -}}} diff --git a/desmume/src/windows/7z/CPP/Windows/FileDir.h b/desmume/src/windows/7z/CPP/Windows/FileDir.h deleted file mode 100644 index ea49264b5..000000000 --- a/desmume/src/windows/7z/CPP/Windows/FileDir.h +++ /dev/null @@ -1,178 +0,0 @@ -// Windows/FileDir.h - -#ifndef __WINDOWS_FILEDIR_H -#define __WINDOWS_FILEDIR_H - -#include "../Common/MyString.h" -#include "Defs.h" - -namespace NWindows { -namespace NFile { -namespace NDirectory { - -#ifdef WIN_LONG_PATH -bool GetLongPaths(LPCWSTR s1, LPCWSTR s2, UString &d1, UString &d2); -#endif - -bool MyGetWindowsDirectory(CSysString &path); -bool MyGetSystemDirectory(CSysString &path); -#ifndef _UNICODE -bool MyGetWindowsDirectory(UString &path); -bool MyGetSystemDirectory(UString &path); -#endif - -bool SetDirTime(LPCWSTR fileName, const FILETIME *cTime, const FILETIME *aTime, const FILETIME *mTime); - -bool MySetFileAttributes(LPCTSTR fileName, DWORD fileAttributes); -bool MyMoveFile(LPCTSTR existFileName, LPCTSTR newFileName); -bool MyRemoveDirectory(LPCTSTR pathName); -bool MyCreateDirectory(LPCTSTR pathName); -bool CreateComplexDirectory(LPCTSTR pathName); -bool DeleteFileAlways(LPCTSTR name); -bool RemoveDirectoryWithSubItems(const CSysString &path); - -#ifndef _UNICODE -bool MySetFileAttributes(LPCWSTR fileName, DWORD fileAttributes); -bool MyMoveFile(LPCWSTR existFileName, LPCWSTR newFileName); -bool MyRemoveDirectory(LPCWSTR pathName); -bool MyCreateDirectory(LPCWSTR pathName); -bool CreateComplexDirectory(LPCWSTR pathName); -bool DeleteFileAlways(LPCWSTR name); -bool RemoveDirectoryWithSubItems(const UString &path); -#endif - -#ifndef _WIN32_WCE -bool MyGetShortPathName(LPCTSTR longPath, CSysString &shortPath); - -bool MyGetFullPathName(LPCTSTR fileName, CSysString &resultPath, - int &fileNamePartStartIndex); -bool MyGetFullPathName(LPCTSTR fileName, CSysString &resultPath); -bool GetOnlyName(LPCTSTR fileName, CSysString &resultName); -bool GetOnlyDirPrefix(LPCTSTR fileName, CSysString &resultName); -#ifndef _UNICODE -bool MyGetFullPathName(LPCWSTR fileName, UString &resultPath, - int &fileNamePartStartIndex); -bool MyGetFullPathName(LPCWSTR fileName, UString &resultPath); -bool GetOnlyName(LPCWSTR fileName, UString &resultName); -bool GetOnlyDirPrefix(LPCWSTR fileName, UString &resultName); -#endif - -inline bool MySetCurrentDirectory(LPCTSTR path) - { return BOOLToBool(::SetCurrentDirectory(path)); } -bool MyGetCurrentDirectory(CSysString &resultPath); -#ifndef _UNICODE -bool MySetCurrentDirectory(LPCWSTR path); -bool MyGetCurrentDirectory(UString &resultPath); -#endif -#endif - -bool MySearchPath(LPCTSTR path, LPCTSTR fileName, LPCTSTR extension, - CSysString &resultPath, UINT32 &filePart); -#ifndef _UNICODE -bool MySearchPath(LPCWSTR path, LPCWSTR fileName, LPCWSTR extension, - UString &resultPath, UINT32 &filePart); -#endif - -inline bool MySearchPath(LPCTSTR path, LPCTSTR fileName, LPCTSTR extension, - CSysString &resultPath) -{ - UINT32 value; - return MySearchPath(path, fileName, extension, resultPath, value); -} - -#ifndef _UNICODE -inline bool MySearchPath(LPCWSTR path, LPCWSTR fileName, LPCWSTR extension, - UString &resultPath) -{ - UINT32 value; - return MySearchPath(path, fileName, extension, resultPath, value); -} -#endif - -bool MyGetTempPath(CSysString &resultPath); -#ifndef _UNICODE -bool MyGetTempPath(UString &resultPath); -#endif - -UINT MyGetTempFileName(LPCTSTR dirPath, LPCTSTR prefix, CSysString &resultPath); -#ifndef _UNICODE -UINT MyGetTempFileName(LPCWSTR dirPath, LPCWSTR prefix, UString &resultPath); -#endif - -class CTempFile -{ - bool _mustBeDeleted; - CSysString _fileName; -public: - CTempFile(): _mustBeDeleted(false) {} - ~CTempFile() { Remove(); } - void DisableDeleting() { _mustBeDeleted = false; } - UINT Create(LPCTSTR dirPath, LPCTSTR prefix, CSysString &resultPath); - bool Create(LPCTSTR prefix, CSysString &resultPath); - bool Remove(); -}; - -#ifdef _UNICODE -typedef CTempFile CTempFileW; -#else -class CTempFileW -{ - bool _mustBeDeleted; - UString _fileName; -public: - CTempFileW(): _mustBeDeleted(false) {} - ~CTempFileW() { Remove(); } - void DisableDeleting() { _mustBeDeleted = false; } - UINT Create(LPCWSTR dirPath, LPCWSTR prefix, UString &resultPath); - bool Create(LPCWSTR prefix, UString &resultPath); - bool Remove(); -}; -#endif - -bool CreateTempDirectory(LPCTSTR prefixChars, CSysString &dirName); - -class CTempDirectory -{ - bool _mustBeDeleted; - CSysString _tempDir; -public: - const CSysString &GetPath() const { return _tempDir; } - CTempDirectory(): _mustBeDeleted(false) {} - ~CTempDirectory() { Remove(); } - bool Create(LPCTSTR prefix) ; - bool Remove() - { - if (!_mustBeDeleted) - return true; - _mustBeDeleted = !RemoveDirectoryWithSubItems(_tempDir); - return (!_mustBeDeleted); - } - void DisableDeleting() { _mustBeDeleted = false; } -}; - -#ifdef _UNICODE -typedef CTempDirectory CTempDirectoryW; -#else -class CTempDirectoryW -{ - bool _mustBeDeleted; - UString _tempDir; -public: - const UString &GetPath() const { return _tempDir; } - CTempDirectoryW(): _mustBeDeleted(false) {} - ~CTempDirectoryW() { Remove(); } - bool Create(LPCWSTR prefix) ; - bool Remove() - { - if (!_mustBeDeleted) - return true; - _mustBeDeleted = !RemoveDirectoryWithSubItems(_tempDir); - return (!_mustBeDeleted); - } - void DisableDeleting() { _mustBeDeleted = false; } -}; -#endif - -}}} - -#endif diff --git a/desmume/src/windows/7z/CPP/Windows/FileFind.cpp b/desmume/src/windows/7z/CPP/Windows/FileFind.cpp deleted file mode 100644 index 7e6b30a6b..000000000 --- a/desmume/src/windows/7z/CPP/Windows/FileFind.cpp +++ /dev/null @@ -1,402 +0,0 @@ -// Windows/FileFind.cpp - -#include "StdAfx.h" - -#include "FileFind.h" -#ifndef _UNICODE -#include "../Common/StringConvert.h" -#endif - -#ifndef _UNICODE -extern bool g_IsNT; -#endif - -namespace NWindows { -namespace NFile { - -#if defined(WIN_LONG_PATH) && defined(_UNICODE) -#define WIN_LONG_PATH2 -#endif - -bool GetLongPath(LPCWSTR fileName, UString &res); - -namespace NFind { - -static const TCHAR kDot = TEXT('.'); - -bool CFileInfo::IsDots() const -{ - if (!IsDir() || Name.IsEmpty()) - return false; - if (Name[0] != kDot) - return false; - return Name.Length() == 1 || (Name[1] == kDot && Name.Length() == 2); -} - -#ifndef _UNICODE -bool CFileInfoW::IsDots() const -{ - if (!IsDir() || Name.IsEmpty()) - return false; - if (Name[0] != kDot) - return false; - return Name.Length() == 1 || (Name[1] == kDot && Name.Length() == 2); -} -#endif - -static void ConvertWIN32_FIND_DATA_To_FileInfo(const WIN32_FIND_DATA &fd, CFileInfo &fi) -{ - fi.Attrib = fd.dwFileAttributes; - fi.CTime = fd.ftCreationTime; - fi.ATime = fd.ftLastAccessTime; - fi.MTime = fd.ftLastWriteTime; - fi.Size = (((UInt64)fd.nFileSizeHigh) << 32) + fd.nFileSizeLow; - fi.Name = fd.cFileName; - #ifndef _WIN32_WCE - fi.ReparseTag = fd.dwReserved0; - #else - fi.ObjectID = fd.dwOID; - #endif -} - -#ifndef _UNICODE - -static inline UINT GetCurrentCodePage() { return ::AreFileApisANSI() ? CP_ACP : CP_OEMCP; } - -static void ConvertWIN32_FIND_DATA_To_FileInfo(const WIN32_FIND_DATAW &fd, CFileInfoW &fi) -{ - fi.Attrib = fd.dwFileAttributes; - fi.CTime = fd.ftCreationTime; - fi.ATime = fd.ftLastAccessTime; - fi.MTime = fd.ftLastWriteTime; - fi.Size = (((UInt64)fd.nFileSizeHigh) << 32) + fd.nFileSizeLow; - fi.Name = fd.cFileName; - #ifndef _WIN32_WCE - fi.ReparseTag = fd.dwReserved0; - #else - fi.ObjectID = fd.dwOID; - #endif -} - -static void ConvertWIN32_FIND_DATA_To_FileInfo(const WIN32_FIND_DATA &fd, CFileInfoW &fi) -{ - fi.Attrib = fd.dwFileAttributes; - fi.CTime = fd.ftCreationTime; - fi.ATime = fd.ftLastAccessTime; - fi.MTime = fd.ftLastWriteTime; - fi.Size = (((UInt64)fd.nFileSizeHigh) << 32) + fd.nFileSizeLow; - fi.Name = GetUnicodeString(fd.cFileName, GetCurrentCodePage()); - #ifndef _WIN32_WCE - fi.ReparseTag = fd.dwReserved0; - #else - fi.ObjectID = fd.dwOID; - #endif -} -#endif - -//////////////////////////////// -// CFindFile - -bool CFindFile::Close() -{ - if (_handle == INVALID_HANDLE_VALUE) - return true; - if (!::FindClose(_handle)) - return false; - _handle = INVALID_HANDLE_VALUE; - return true; -} - - -bool CFindFile::FindFirst(LPCTSTR wildcard, CFileInfo &fileInfo) -{ - if (!Close()) - return false; - WIN32_FIND_DATA fd; - _handle = ::FindFirstFile(wildcard, &fd); - #ifdef WIN_LONG_PATH2 - if (_handle == INVALID_HANDLE_VALUE) - { - UString longPath; - if (GetLongPath(wildcard, longPath)) - _handle = ::FindFirstFileW(longPath, &fd); - } - #endif - if (_handle == INVALID_HANDLE_VALUE) - return false; - ConvertWIN32_FIND_DATA_To_FileInfo(fd, fileInfo); - return true; -} - -#ifndef _UNICODE -bool CFindFile::FindFirst(LPCWSTR wildcard, CFileInfoW &fileInfo) -{ - if (!Close()) - return false; - if (g_IsNT) - { - WIN32_FIND_DATAW fd; - _handle = ::FindFirstFileW(wildcard, &fd); - #ifdef WIN_LONG_PATH - if (_handle == INVALID_HANDLE_VALUE) - { - UString longPath; - if (GetLongPath(wildcard, longPath)) - _handle = ::FindFirstFileW(longPath, &fd); - } - #endif - if (_handle != INVALID_HANDLE_VALUE) - ConvertWIN32_FIND_DATA_To_FileInfo(fd, fileInfo); - } - else - { - WIN32_FIND_DATAA fd; - _handle = ::FindFirstFileA(UnicodeStringToMultiByte(wildcard, - GetCurrentCodePage()), &fd); - if (_handle != INVALID_HANDLE_VALUE) - ConvertWIN32_FIND_DATA_To_FileInfo(fd, fileInfo); - } - return (_handle != INVALID_HANDLE_VALUE); -} -#endif - -bool CFindFile::FindNext(CFileInfo &fileInfo) -{ - WIN32_FIND_DATA fd; - bool result = BOOLToBool(::FindNextFile(_handle, &fd)); - if (result) - ConvertWIN32_FIND_DATA_To_FileInfo(fd, fileInfo); - return result; -} - -#ifndef _UNICODE -bool CFindFile::FindNext(CFileInfoW &fileInfo) -{ - if (g_IsNT) - { - WIN32_FIND_DATAW fd; - if (!::FindNextFileW(_handle, &fd)) - return false; - ConvertWIN32_FIND_DATA_To_FileInfo(fd, fileInfo); - } - else - { - WIN32_FIND_DATAA fd; - if (!::FindNextFileA(_handle, &fd)) - return false; - ConvertWIN32_FIND_DATA_To_FileInfo(fd, fileInfo); - } - return true; -} -#endif - -bool FindFile(LPCTSTR wildcard, CFileInfo &fileInfo) -{ - CFindFile finder; - return finder.FindFirst(wildcard, fileInfo); -} - -#ifndef _UNICODE -bool FindFile(LPCWSTR wildcard, CFileInfoW &fileInfo) -{ - CFindFile finder; - return finder.FindFirst(wildcard, fileInfo); -} -#endif - -bool DoesFileExist(LPCTSTR name) -{ - CFileInfo fileInfo; - return FindFile(name, fileInfo); -} - -#ifndef _UNICODE -bool DoesFileExist(LPCWSTR name) -{ - CFileInfoW fileInfo; - return FindFile(name, fileInfo); -} -#endif - -///////////////////////////////////// -// CEnumerator - -bool CEnumerator::NextAny(CFileInfo &fileInfo) -{ - if (_findFile.IsHandleAllocated()) - return _findFile.FindNext(fileInfo); - else - return _findFile.FindFirst(_wildcard, fileInfo); -} - -bool CEnumerator::Next(CFileInfo &fileInfo) -{ - for (;;) - { - if (!NextAny(fileInfo)) - return false; - if (!fileInfo.IsDots()) - return true; - } -} - -bool CEnumerator::Next(CFileInfo &fileInfo, bool &found) -{ - if (Next(fileInfo)) - { - found = true; - return true; - } - found = false; - return (::GetLastError() == ERROR_NO_MORE_FILES); -} - -#ifndef _UNICODE -bool CEnumeratorW::NextAny(CFileInfoW &fileInfo) -{ - if (_findFile.IsHandleAllocated()) - return _findFile.FindNext(fileInfo); - else - return _findFile.FindFirst(_wildcard, fileInfo); -} - -bool CEnumeratorW::Next(CFileInfoW &fileInfo) -{ - for (;;) - { - if (!NextAny(fileInfo)) - return false; - if (!fileInfo.IsDots()) - return true; - } -} - -bool CEnumeratorW::Next(CFileInfoW &fileInfo, bool &found) -{ - if (Next(fileInfo)) - { - found = true; - return true; - } - found = false; - return (::GetLastError() == ERROR_NO_MORE_FILES); -} - -#endif - -//////////////////////////////// -// CFindChangeNotification -// FindFirstChangeNotification can return 0. MSDN doesn't tell about it. - -bool CFindChangeNotification::Close() -{ - if (!IsHandleAllocated()) - return true; - if (!::FindCloseChangeNotification(_handle)) - return false; - _handle = INVALID_HANDLE_VALUE; - return true; -} - -HANDLE CFindChangeNotification::FindFirst(LPCTSTR pathName, bool watchSubtree, DWORD notifyFilter) -{ - _handle = ::FindFirstChangeNotification(pathName, BoolToBOOL(watchSubtree), notifyFilter); - #ifdef WIN_LONG_PATH2 - if (!IsHandleAllocated()) - { - UString longPath; - if (GetLongPath(pathName, longPath)) - _handle = ::FindFirstChangeNotificationW(longPath, BoolToBOOL(watchSubtree), notifyFilter); - } - #endif - return _handle; -} - -#ifndef _UNICODE -HANDLE CFindChangeNotification::FindFirst(LPCWSTR pathName, bool watchSubtree, DWORD notifyFilter) -{ - if (!g_IsNT) - return FindFirst(UnicodeStringToMultiByte(pathName, GetCurrentCodePage()), watchSubtree, notifyFilter); - _handle = ::FindFirstChangeNotificationW(pathName, BoolToBOOL(watchSubtree), notifyFilter); - #ifdef WIN_LONG_PATH - if (!IsHandleAllocated()) - { - UString longPath; - if (GetLongPath(pathName, longPath)) - _handle = ::FindFirstChangeNotificationW(longPath, BoolToBOOL(watchSubtree), notifyFilter); - } - #endif - return _handle; -} -#endif - -#ifndef _WIN32_WCE -bool MyGetLogicalDriveStrings(CSysStringVector &driveStrings) -{ - driveStrings.Clear(); - UINT32 size = GetLogicalDriveStrings(0, NULL); - if (size == 0) - return false; - CSysString buffer; - UINT32 newSize = GetLogicalDriveStrings(size, buffer.GetBuffer(size)); - if (newSize == 0) - return false; - if (newSize > size) - return false; - CSysString string; - for (UINT32 i = 0; i < newSize; i++) - { - TCHAR c = buffer[i]; - if (c == TEXT('\0')) - { - driveStrings.Add(string); - string.Empty(); - } - else - string += c; - } - if (!string.IsEmpty()) - return false; - return true; -} - -#ifndef _UNICODE -bool MyGetLogicalDriveStrings(UStringVector &driveStrings) -{ - driveStrings.Clear(); - if (g_IsNT) - { - UINT32 size = GetLogicalDriveStringsW(0, NULL); - if (size == 0) - return false; - UString buffer; - UINT32 newSize = GetLogicalDriveStringsW(size, buffer.GetBuffer(size)); - if (newSize == 0) - return false; - if (newSize > size) - return false; - UString string; - for (UINT32 i = 0; i < newSize; i++) - { - WCHAR c = buffer[i]; - if (c == L'\0') - { - driveStrings.Add(string); - string.Empty(); - } - else - string += c; - } - return string.IsEmpty(); - } - CSysStringVector driveStringsA; - bool res = MyGetLogicalDriveStrings(driveStringsA); - for (int i = 0; i < driveStringsA.Size(); i++) - driveStrings.Add(GetUnicodeString(driveStringsA[i])); - return res; -} -#endif - -#endif - -}}} diff --git a/desmume/src/windows/7z/CPP/Windows/FileFind.h b/desmume/src/windows/7z/CPP/Windows/FileFind.h deleted file mode 100644 index f01c1357e..000000000 --- a/desmume/src/windows/7z/CPP/Windows/FileFind.h +++ /dev/null @@ -1,153 +0,0 @@ -// Windows/FileFind.h - -#ifndef __WINDOWS_FILEFIND_H -#define __WINDOWS_FILEFIND_H - -#include "../Common/MyString.h" -#include "../Common/Types.h" -#include "FileName.h" -#include "Defs.h" - -namespace NWindows { -namespace NFile { -namespace NFind { - -namespace NAttributes -{ - inline bool IsReadOnly(DWORD attrib) { return (attrib & FILE_ATTRIBUTE_READONLY) != 0; } - inline bool IsHidden(DWORD attrib) { return (attrib & FILE_ATTRIBUTE_HIDDEN) != 0; } - inline bool IsSystem(DWORD attrib) { return (attrib & FILE_ATTRIBUTE_SYSTEM) != 0; } - inline bool IsDir(DWORD attrib) { return (attrib & FILE_ATTRIBUTE_DIRECTORY) != 0; } - inline bool IsArchived(DWORD attrib) { return (attrib & FILE_ATTRIBUTE_ARCHIVE) != 0; } - inline bool IsCompressed(DWORD attrib) { return (attrib & FILE_ATTRIBUTE_COMPRESSED) != 0; } - inline bool IsEncrypted(DWORD attrib) { return (attrib & FILE_ATTRIBUTE_ENCRYPTED) != 0; } -} - -class CFileInfoBase -{ - bool MatchesMask(UINT32 mask) const { return ((Attrib & mask) != 0); } -public: - UInt64 Size; - FILETIME CTime; - FILETIME ATime; - FILETIME MTime; - DWORD Attrib; - - #ifndef _WIN32_WCE - UINT32 ReparseTag; - #else - DWORD ObjectID; - #endif - - bool IsArchived() const { return MatchesMask(FILE_ATTRIBUTE_ARCHIVE); } - bool IsCompressed() const { return MatchesMask(FILE_ATTRIBUTE_COMPRESSED); } - bool IsDir() const { return MatchesMask(FILE_ATTRIBUTE_DIRECTORY); } - bool IsEncrypted() const { return MatchesMask(FILE_ATTRIBUTE_ENCRYPTED); } - bool IsHidden() const { return MatchesMask(FILE_ATTRIBUTE_HIDDEN); } - bool IsNormal() const { return MatchesMask(FILE_ATTRIBUTE_NORMAL); } - bool IsOffline() const { return MatchesMask(FILE_ATTRIBUTE_OFFLINE); } - bool IsReadOnly() const { return MatchesMask(FILE_ATTRIBUTE_READONLY); } - bool HasReparsePoint() const { return MatchesMask(FILE_ATTRIBUTE_REPARSE_POINT); } - bool IsSparse() const { return MatchesMask(FILE_ATTRIBUTE_SPARSE_FILE); } - bool IsSystem() const { return MatchesMask(FILE_ATTRIBUTE_SYSTEM); } - bool IsTemporary() const { return MatchesMask(FILE_ATTRIBUTE_TEMPORARY); } -}; - -class CFileInfo: public CFileInfoBase -{ -public: - CSysString Name; - bool IsDots() const; -}; - -#ifdef _UNICODE -typedef CFileInfo CFileInfoW; -#else -class CFileInfoW: public CFileInfoBase -{ -public: - UString Name; - bool IsDots() const; -}; -#endif - -class CFindFile -{ - friend class CEnumerator; - HANDLE _handle; -public: - bool IsHandleAllocated() const { return _handle != INVALID_HANDLE_VALUE; } - CFindFile(): _handle(INVALID_HANDLE_VALUE) {} - ~CFindFile() { Close(); } - bool FindFirst(LPCTSTR wildcard, CFileInfo &fileInfo); - bool FindNext(CFileInfo &fileInfo); - #ifndef _UNICODE - bool FindFirst(LPCWSTR wildcard, CFileInfoW &fileInfo); - bool FindNext(CFileInfoW &fileInfo); - #endif - bool Close(); -}; - -bool FindFile(LPCTSTR wildcard, CFileInfo &fileInfo); - -bool DoesFileExist(LPCTSTR name); -#ifndef _UNICODE -bool FindFile(LPCWSTR wildcard, CFileInfoW &fileInfo); -bool DoesFileExist(LPCWSTR name); -#endif - -class CEnumerator -{ - CFindFile _findFile; - CSysString _wildcard; - bool NextAny(CFileInfo &fileInfo); -public: - CEnumerator(): _wildcard(NName::kAnyStringWildcard) {} - CEnumerator(const CSysString &wildcard): _wildcard(wildcard) {} - bool Next(CFileInfo &fileInfo); - bool Next(CFileInfo &fileInfo, bool &found); -}; - -#ifdef _UNICODE -typedef CEnumerator CEnumeratorW; -#else -class CEnumeratorW -{ - CFindFile _findFile; - UString _wildcard; - bool NextAny(CFileInfoW &fileInfo); -public: - CEnumeratorW(): _wildcard(NName::kAnyStringWildcard) {} - CEnumeratorW(const UString &wildcard): _wildcard(wildcard) {} - bool Next(CFileInfoW &fileInfo); - bool Next(CFileInfoW &fileInfo, bool &found); -}; -#endif - -class CFindChangeNotification -{ - HANDLE _handle; -public: - operator HANDLE () { return _handle; } - bool IsHandleAllocated() const { return _handle != INVALID_HANDLE_VALUE && _handle != 0; } - CFindChangeNotification(): _handle(INVALID_HANDLE_VALUE) {} - ~CFindChangeNotification() { Close(); } - bool Close(); - HANDLE FindFirst(LPCTSTR pathName, bool watchSubtree, DWORD notifyFilter); - #ifndef _UNICODE - HANDLE FindFirst(LPCWSTR pathName, bool watchSubtree, DWORD notifyFilter); - #endif - bool FindNext() { return BOOLToBool(::FindNextChangeNotification(_handle)); } -}; - -#ifndef _WIN32_WCE -bool MyGetLogicalDriveStrings(CSysStringVector &driveStrings); -#ifndef _UNICODE -bool MyGetLogicalDriveStrings(UStringVector &driveStrings); -#endif -#endif - -}}} - -#endif - diff --git a/desmume/src/windows/7z/CPP/Windows/FileIO.cpp b/desmume/src/windows/7z/CPP/Windows/FileIO.cpp deleted file mode 100644 index 520d9a2ba..000000000 --- a/desmume/src/windows/7z/CPP/Windows/FileIO.cpp +++ /dev/null @@ -1,317 +0,0 @@ -// Windows/FileIO.cpp - -#include "StdAfx.h" - -#include "FileIO.h" -#include "Defs.h" -#ifdef WIN_LONG_PATH -#include "../Common/MyString.h" -#endif -#ifndef _UNICODE -#include "../Common/StringConvert.h" -#endif - -#ifndef _UNICODE -extern bool g_IsNT; -#endif - -namespace NWindows { -namespace NFile { - -#if defined(WIN_LONG_PATH) && defined(_UNICODE) -#define WIN_LONG_PATH2 -#endif - -#ifdef WIN_LONG_PATH -bool GetLongPathBase(LPCWSTR s, UString &res) -{ - res.Empty(); - int len = MyStringLen(s); - wchar_t c = s[0]; - if (len < 1 || c == L'\\' || c == L'.' && (len == 1 || len == 2 && s[1] == L'.')) - return true; - UString curDir; - bool isAbs = false; - if (len > 3) - isAbs = (s[1] == L':' && s[2] == L'\\' && (c >= L'a' && c <= L'z' || c >= L'A' && c <= L'Z')); - - if (!isAbs) - { - DWORD needLength = ::GetCurrentDirectoryW(MAX_PATH + 1, curDir.GetBuffer(MAX_PATH + 1)); - curDir.ReleaseBuffer(); - if (needLength == 0 || needLength > MAX_PATH) - return false; - if (curDir[curDir.Length() - 1] != L'\\') - curDir += L'\\'; - } - res = UString(L"\\\\?\\") + curDir + s; - return true; -} - -bool GetLongPath(LPCWSTR path, UString &longPath) -{ - if (GetLongPathBase(path, longPath)) - return !longPath.IsEmpty(); - return false; -} -#endif - -namespace NIO { - -CFileBase::~CFileBase() { Close(); } - -bool CFileBase::Create(LPCTSTR fileName, DWORD desiredAccess, - DWORD shareMode, DWORD creationDisposition, DWORD flagsAndAttributes) -{ - if (!Close()) - return false; - _handle = ::CreateFile(fileName, desiredAccess, shareMode, - (LPSECURITY_ATTRIBUTES)NULL, creationDisposition, - flagsAndAttributes, (HANDLE)NULL); - #ifdef WIN_LONG_PATH2 - if (_handle == INVALID_HANDLE_VALUE) - { - UString longPath; - if (GetLongPath(fileName, longPath)) - _handle = ::CreateFileW(longPath, desiredAccess, shareMode, - (LPSECURITY_ATTRIBUTES)NULL, creationDisposition, - flagsAndAttributes, (HANDLE)NULL); - } - #endif - return (_handle != INVALID_HANDLE_VALUE); -} - -#ifndef _UNICODE -bool CFileBase::Create(LPCWSTR fileName, DWORD desiredAccess, - DWORD shareMode, DWORD creationDisposition, DWORD flagsAndAttributes) -{ - if (!g_IsNT) - return Create(UnicodeStringToMultiByte(fileName, ::AreFileApisANSI() ? CP_ACP : CP_OEMCP), - desiredAccess, shareMode, creationDisposition, flagsAndAttributes); - if (!Close()) - return false; - _handle = ::CreateFileW(fileName, desiredAccess, shareMode, - (LPSECURITY_ATTRIBUTES)NULL, creationDisposition, - flagsAndAttributes, (HANDLE)NULL); - #ifdef WIN_LONG_PATH - if (_handle == INVALID_HANDLE_VALUE) - { - UString longPath; - if (GetLongPath(fileName, longPath)) - _handle = ::CreateFileW(longPath, desiredAccess, shareMode, - (LPSECURITY_ATTRIBUTES)NULL, creationDisposition, - flagsAndAttributes, (HANDLE)NULL); - } - #endif - return (_handle != INVALID_HANDLE_VALUE); -} -#endif - -bool CFileBase::Close() -{ - if (_handle == INVALID_HANDLE_VALUE) - return true; - if (!::CloseHandle(_handle)) - return false; - _handle = INVALID_HANDLE_VALUE; - return true; -} - -bool CFileBase::GetPosition(UInt64 &position) const -{ - return Seek(0, FILE_CURRENT, position); -} - -bool CFileBase::GetLength(UInt64 &length) const -{ - DWORD sizeHigh; - DWORD sizeLow = ::GetFileSize(_handle, &sizeHigh); - if (sizeLow == 0xFFFFFFFF) - if (::GetLastError() != NO_ERROR) - return false; - length = (((UInt64)sizeHigh) << 32) + sizeLow; - return true; -} - -bool CFileBase::Seek(Int64 distanceToMove, DWORD moveMethod, UInt64 &newPosition) const -{ - LARGE_INTEGER value; - value.QuadPart = distanceToMove; - value.LowPart = ::SetFilePointer(_handle, value.LowPart, &value.HighPart, moveMethod); - if (value.LowPart == 0xFFFFFFFF) - if (::GetLastError() != NO_ERROR) - return false; - newPosition = value.QuadPart; - return true; -} - -bool CFileBase::Seek(UInt64 position, UInt64 &newPosition) -{ - return Seek(position, FILE_BEGIN, newPosition); -} - -bool CFileBase::SeekToBegin() -{ - UInt64 newPosition; - return Seek(0, newPosition); -} - -bool CFileBase::SeekToEnd(UInt64 &newPosition) -{ - return Seek(0, FILE_END, newPosition); -} - -bool CFileBase::GetFileInformation(CByHandleFileInfo &fileInfo) const -{ - BY_HANDLE_FILE_INFORMATION winFileInfo; - if (!::GetFileInformationByHandle(_handle, &winFileInfo)) - return false; - fileInfo.Attributes = winFileInfo.dwFileAttributes; - fileInfo.CTime = winFileInfo.ftCreationTime; - fileInfo.ATime = winFileInfo.ftLastAccessTime; - fileInfo.MTime = winFileInfo.ftLastWriteTime; - fileInfo.VolumeSerialNumber = winFileInfo.dwFileAttributes; - fileInfo.Size = (((UInt64)winFileInfo.nFileSizeHigh) << 32) + winFileInfo.nFileSizeLow; - fileInfo.NumberOfLinks = winFileInfo.nNumberOfLinks; - fileInfo.FileIndex = (((UInt64)winFileInfo.nFileIndexHigh) << 32) + winFileInfo.nFileIndexLow; - return true; -} - -///////////////////////// -// CInFile - -bool CInFile::Open(LPCTSTR fileName, DWORD shareMode, DWORD creationDisposition, DWORD flagsAndAttributes) - { return Create(fileName, GENERIC_READ, shareMode, creationDisposition, flagsAndAttributes); } - -bool CInFile::OpenShared(LPCTSTR fileName, bool shareForWrite) -{ return Open(fileName, FILE_SHARE_READ | (shareForWrite ? FILE_SHARE_WRITE : 0), OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL); } - -bool CInFile::Open(LPCTSTR fileName) - { return OpenShared(fileName, false); } - -#ifndef _UNICODE -bool CInFile::Open(LPCWSTR fileName, DWORD shareMode, DWORD creationDisposition, DWORD flagsAndAttributes) - { return Create(fileName, GENERIC_READ, shareMode, creationDisposition, flagsAndAttributes); } - -bool CInFile::OpenShared(LPCWSTR fileName, bool shareForWrite) -{ return Open(fileName, FILE_SHARE_READ | (shareForWrite ? FILE_SHARE_WRITE : 0), OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL); } - -bool CInFile::Open(LPCWSTR fileName) - { return OpenShared(fileName, false); } -#endif - -// ReadFile and WriteFile functions in Windows have BUG: -// If you Read or Write 64MB or more (probably min_failure_size = 64MB - 32KB + 1) -// from/to Network file, it returns ERROR_NO_SYSTEM_RESOURCES -// (Insufficient system resources exist to complete the requested service). - -// Probably in some version of Windows there are problems with other sizes: -// for 32 MB (maybe also for 16 MB). -// And message can be "Network connection was lost" - -static UInt32 kChunkSizeMax = (1 << 22); - -bool CInFile::ReadPart(void *data, UInt32 size, UInt32 &processedSize) -{ - if (size > kChunkSizeMax) - size = kChunkSizeMax; - DWORD processedLoc = 0; - bool res = BOOLToBool(::ReadFile(_handle, data, size, &processedLoc, NULL)); - processedSize = (UInt32)processedLoc; - return res; -} - -bool CInFile::Read(void *data, UInt32 size, UInt32 &processedSize) -{ - processedSize = 0; - do - { - UInt32 processedLoc = 0; - bool res = ReadPart(data, size, processedLoc); - processedSize += processedLoc; - if (!res) - return false; - if (processedLoc == 0) - return true; - data = (void *)((unsigned char *)data + processedLoc); - size -= processedLoc; - } - while (size > 0); - return true; -} - -///////////////////////// -// COutFile - -bool COutFile::Open(LPCTSTR fileName, DWORD shareMode, DWORD creationDisposition, DWORD flagsAndAttributes) - { return CFileBase::Create(fileName, GENERIC_WRITE, shareMode, creationDisposition, flagsAndAttributes); } - -static inline DWORD GetCreationDisposition(bool createAlways) - { return createAlways? CREATE_ALWAYS: CREATE_NEW; } - -bool COutFile::Open(LPCTSTR fileName, DWORD creationDisposition) - { return Open(fileName, FILE_SHARE_READ, creationDisposition, FILE_ATTRIBUTE_NORMAL); } - -bool COutFile::Create(LPCTSTR fileName, bool createAlways) - { return Open(fileName, GetCreationDisposition(createAlways)); } - -#ifndef _UNICODE - -bool COutFile::Open(LPCWSTR fileName, DWORD shareMode, DWORD creationDisposition, DWORD flagsAndAttributes) - { return CFileBase::Create(fileName, GENERIC_WRITE, shareMode, creationDisposition, flagsAndAttributes); } - -bool COutFile::Open(LPCWSTR fileName, DWORD creationDisposition) - { return Open(fileName, FILE_SHARE_READ, creationDisposition, FILE_ATTRIBUTE_NORMAL); } - -bool COutFile::Create(LPCWSTR fileName, bool createAlways) - { return Open(fileName, GetCreationDisposition(createAlways)); } - -#endif - -bool COutFile::SetTime(const FILETIME *cTime, const FILETIME *aTime, const FILETIME *mTime) - { return BOOLToBool(::SetFileTime(_handle, cTime, aTime, mTime)); } - -bool COutFile::SetMTime(const FILETIME *mTime) { return SetTime(NULL, NULL, mTime); } - -bool COutFile::WritePart(const void *data, UInt32 size, UInt32 &processedSize) -{ - if (size > kChunkSizeMax) - size = kChunkSizeMax; - DWORD processedLoc = 0; - bool res = BOOLToBool(::WriteFile(_handle, data, size, &processedLoc, NULL)); - processedSize = (UInt32)processedLoc; - return res; -} - -bool COutFile::Write(const void *data, UInt32 size, UInt32 &processedSize) -{ - processedSize = 0; - do - { - UInt32 processedLoc = 0; - bool res = WritePart(data, size, processedLoc); - processedSize += processedLoc; - if (!res) - return false; - if (processedLoc == 0) - return true; - data = (const void *)((const unsigned char *)data + processedLoc); - size -= processedLoc; - } - while (size > 0); - return true; -} - -bool COutFile::SetEndOfFile() { return BOOLToBool(::SetEndOfFile(_handle)); } - -bool COutFile::SetLength(UInt64 length) -{ - UInt64 newPosition; - if (!Seek(length, newPosition)) - return false; - if (newPosition != length) - return false; - return SetEndOfFile(); -} - -}}} diff --git a/desmume/src/windows/7z/CPP/Windows/FileIO.h b/desmume/src/windows/7z/CPP/Windows/FileIO.h deleted file mode 100644 index 930a13d94..000000000 --- a/desmume/src/windows/7z/CPP/Windows/FileIO.h +++ /dev/null @@ -1,99 +0,0 @@ -// Windows/FileIO.h - -#ifndef __WINDOWS_FILEIO_H -#define __WINDOWS_FILEIO_H - -#include "../Common/Types.h" - -namespace NWindows { -namespace NFile { -namespace NIO { - -struct CByHandleFileInfo -{ - DWORD Attributes; - FILETIME CTime; - FILETIME ATime; - FILETIME MTime; - DWORD VolumeSerialNumber; - UInt64 Size; - DWORD NumberOfLinks; - UInt64 FileIndex; -}; - -class CFileBase -{ -protected: - HANDLE _handle; - bool Create(LPCTSTR fileName, DWORD desiredAccess, - DWORD shareMode, DWORD creationDisposition, DWORD flagsAndAttributes); - #ifndef _UNICODE - bool Create(LPCWSTR fileName, DWORD desiredAccess, - DWORD shareMode, DWORD creationDisposition, DWORD flagsAndAttributes); - #endif - -public: - CFileBase(): _handle(INVALID_HANDLE_VALUE){}; - ~CFileBase(); - - bool Close(); - - bool GetPosition(UInt64 &position) const; - bool GetLength(UInt64 &length) const; - - bool Seek(Int64 distanceToMove, DWORD moveMethod, UInt64 &newPosition) const; - bool Seek(UInt64 position, UInt64 &newPosition); - bool SeekToBegin(); - bool SeekToEnd(UInt64 &newPosition); - - bool GetFileInformation(CByHandleFileInfo &fileInfo) const; -}; - -class CInFile: public CFileBase -{ -public: - bool Open(LPCTSTR fileName, DWORD shareMode, DWORD creationDisposition, DWORD flagsAndAttributes); - bool OpenShared(LPCTSTR fileName, bool shareForWrite); - bool Open(LPCTSTR fileName); - #ifndef _UNICODE - bool Open(LPCWSTR fileName, DWORD shareMode, DWORD creationDisposition, DWORD flagsAndAttributes); - bool OpenShared(LPCWSTR fileName, bool shareForWrite); - bool Open(LPCWSTR fileName); - #endif - bool ReadPart(void *data, UInt32 size, UInt32 &processedSize); - bool Read(void *data, UInt32 size, UInt32 &processedSize); -}; - -class COutFile: public CFileBase -{ - // DWORD m_CreationDisposition; -public: - // COutFile(): m_CreationDisposition(CREATE_NEW){}; - bool Open(LPCTSTR fileName, DWORD shareMode, DWORD creationDisposition, DWORD flagsAndAttributes); - bool Open(LPCTSTR fileName, DWORD creationDisposition); - bool Create(LPCTSTR fileName, bool createAlways); - - #ifndef _UNICODE - bool Open(LPCWSTR fileName, DWORD shareMode, DWORD creationDisposition, DWORD flagsAndAttributes); - bool Open(LPCWSTR fileName, DWORD creationDisposition); - bool Create(LPCWSTR fileName, bool createAlways); - #endif - - /* - void SetOpenCreationDisposition(DWORD creationDisposition) - { m_CreationDisposition = creationDisposition; } - void SetOpenCreationDispositionCreateAlways() - { m_CreationDisposition = CREATE_ALWAYS; } - */ - - bool SetTime(const FILETIME *cTime, const FILETIME *aTime, const FILETIME *mTime); - bool SetMTime(const FILETIME *mTime); - bool WritePart(const void *data, UInt32 size, UInt32 &processedSize); - bool Write(const void *data, UInt32 size, UInt32 &processedSize); - bool SetEndOfFile(); - bool SetLength(UInt64 length); -}; - -}}} - -#endif diff --git a/desmume/src/windows/7z/CPP/Windows/FileName.h b/desmume/src/windows/7z/CPP/Windows/FileName.h deleted file mode 100644 index 02dba3b69..000000000 --- a/desmume/src/windows/7z/CPP/Windows/FileName.h +++ /dev/null @@ -1,25 +0,0 @@ -// Windows/FileName.h - -#ifndef __WINDOWS_FILENAME_H -#define __WINDOWS_FILENAME_H - -#include "../Common/MyString.h" - -namespace NWindows { -namespace NFile { -namespace NName { - -const TCHAR kDirDelimiter = CHAR_PATH_SEPARATOR; -const TCHAR kAnyStringWildcard = '*'; - -void NormalizeDirPathPrefix(CSysString &dirPath); // ensures that it ended with '\\' -#ifndef _UNICODE -void NormalizeDirPathPrefix(UString &dirPath); // ensures that it ended with '\\' -#endif - -void SplitNameToPureNameAndExtension(const UString &fullName, - UString &pureName, UString &extensionDelimiter, UString &extension); - -}}} - -#endif diff --git a/desmume/src/windows/7z/CPP/Windows/Handle.h b/desmume/src/windows/7z/CPP/Windows/Handle.h deleted file mode 100644 index 16546079d..000000000 --- a/desmume/src/windows/7z/CPP/Windows/Handle.h +++ /dev/null @@ -1,37 +0,0 @@ -// Windows/Handle.h - -#ifndef __WINDOWS_HANDLE_H -#define __WINDOWS_HANDLE_H - -namespace NWindows { - -class CHandle -{ -protected: - HANDLE _handle; -public: - operator HANDLE() { return _handle; } - CHandle(): _handle(NULL) {} - ~CHandle() { Close(); } - bool Close() - { - if (_handle == NULL) - return true; - if (!::CloseHandle(_handle)) - return false; - _handle = NULL; - return true; - } - void Attach(HANDLE handle) - { _handle = handle; } - HANDLE Detach() - { - HANDLE handle = _handle; - _handle = NULL; - return handle; - } -}; - -} - -#endif diff --git a/desmume/src/windows/7z/CPP/Windows/PropVariant.cpp b/desmume/src/windows/7z/CPP/Windows/PropVariant.cpp deleted file mode 100644 index fff513d18..000000000 --- a/desmume/src/windows/7z/CPP/Windows/PropVariant.cpp +++ /dev/null @@ -1,312 +0,0 @@ -// Windows/PropVariant.cpp - -#include "StdAfx.h" - -#include "PropVariant.h" - -#include "../Common/Defs.h" - -namespace NWindows { -namespace NCOM { - -CPropVariant::CPropVariant(const PROPVARIANT& varSrc) -{ - vt = VT_EMPTY; - InternalCopy(&varSrc); -} - -CPropVariant::CPropVariant(const CPropVariant& varSrc) -{ - vt = VT_EMPTY; - InternalCopy(&varSrc); -} - -CPropVariant::CPropVariant(BSTR bstrSrc) -{ - vt = VT_EMPTY; - *this = bstrSrc; -} - -CPropVariant::CPropVariant(LPCOLESTR lpszSrc) -{ - vt = VT_EMPTY; - *this = lpszSrc; -} - -CPropVariant& CPropVariant::operator=(const CPropVariant& varSrc) -{ - InternalCopy(&varSrc); - return *this; -} -CPropVariant& CPropVariant::operator=(const PROPVARIANT& varSrc) -{ - InternalCopy(&varSrc); - return *this; -} - -CPropVariant& CPropVariant::operator=(BSTR bstrSrc) -{ - *this = (LPCOLESTR)bstrSrc; - return *this; -} - -CPropVariant& CPropVariant::operator=(LPCOLESTR lpszSrc) -{ - InternalClear(); - vt = VT_BSTR; - wReserved1 = 0; - bstrVal = ::SysAllocString(lpszSrc); - if (bstrVal == NULL && lpszSrc != NULL) - { - vt = VT_ERROR; - scode = E_OUTOFMEMORY; - } - return *this; -} - - -CPropVariant& CPropVariant::operator=(bool bSrc) -{ - if (vt != VT_BOOL) - { - InternalClear(); - vt = VT_BOOL; - } - boolVal = bSrc ? VARIANT_TRUE : VARIANT_FALSE; - return *this; -} - -CPropVariant& CPropVariant::operator=(UInt32 value) -{ - if (vt != VT_UI4) - { - InternalClear(); - vt = VT_UI4; - } - ulVal = value; - return *this; -} - -CPropVariant& CPropVariant::operator=(UInt64 value) -{ - if (vt != VT_UI8) - { - InternalClear(); - vt = VT_UI8; - } - uhVal.QuadPart = value; - return *this; -} - -CPropVariant& CPropVariant::operator=(const FILETIME &value) -{ - if (vt != VT_FILETIME) - { - InternalClear(); - vt = VT_FILETIME; - } - filetime = value; - return *this; -} - -CPropVariant& CPropVariant::operator=(Int32 value) -{ - if (vt != VT_I4) - { - InternalClear(); - vt = VT_I4; - } - lVal = value; - - return *this; -} - -CPropVariant& CPropVariant::operator=(Byte value) -{ - if (vt != VT_UI1) - { - InternalClear(); - vt = VT_UI1; - } - bVal = value; - return *this; -} - -CPropVariant& CPropVariant::operator=(Int16 value) -{ - if (vt != VT_I2) - { - InternalClear(); - vt = VT_I2; - } - iVal = value; - return *this; -} - -/* -CPropVariant& CPropVariant::operator=(LONG value) -{ - if (vt != VT_I4) - { - InternalClear(); - vt = VT_I4; - } - lVal = value; - return *this; -} -*/ - -static HRESULT MyPropVariantClear(PROPVARIANT *propVariant) -{ - switch(propVariant->vt) - { - case VT_UI1: - case VT_I1: - case VT_I2: - case VT_UI2: - case VT_BOOL: - case VT_I4: - case VT_UI4: - case VT_R4: - case VT_INT: - case VT_UINT: - case VT_ERROR: - case VT_FILETIME: - case VT_UI8: - case VT_R8: - case VT_CY: - case VT_DATE: - propVariant->vt = VT_EMPTY; - propVariant->wReserved1 = 0; - return S_OK; - } - return ::VariantClear((VARIANTARG *)propVariant); -} - -HRESULT CPropVariant::Clear() -{ - return MyPropVariantClear(this); -} - -HRESULT CPropVariant::Copy(const PROPVARIANT* pSrc) -{ - ::VariantClear((tagVARIANT *)this); - switch(pSrc->vt) - { - case VT_UI1: - case VT_I1: - case VT_I2: - case VT_UI2: - case VT_BOOL: - case VT_I4: - case VT_UI4: - case VT_R4: - case VT_INT: - case VT_UINT: - case VT_ERROR: - case VT_FILETIME: - case VT_UI8: - case VT_R8: - case VT_CY: - case VT_DATE: - memmove((PROPVARIANT*)this, pSrc, sizeof(PROPVARIANT)); - return S_OK; - } - return ::VariantCopy((tagVARIANT *)this, (tagVARIANT *)(pSrc)); -} - - -HRESULT CPropVariant::Attach(PROPVARIANT* pSrc) -{ - HRESULT hr = Clear(); - if (FAILED(hr)) - return hr; - memcpy(this, pSrc, sizeof(PROPVARIANT)); - pSrc->vt = VT_EMPTY; - return S_OK; -} - -HRESULT CPropVariant::Detach(PROPVARIANT* pDest) -{ - HRESULT hr = MyPropVariantClear(pDest); - if (FAILED(hr)) - return hr; - memcpy(pDest, this, sizeof(PROPVARIANT)); - vt = VT_EMPTY; - return S_OK; -} - -HRESULT CPropVariant::InternalClear() -{ - HRESULT hr = Clear(); - if (FAILED(hr)) - { - vt = VT_ERROR; - scode = hr; - } - return hr; -} - -void CPropVariant::InternalCopy(const PROPVARIANT* pSrc) -{ - HRESULT hr = Copy(pSrc); - if (FAILED(hr)) - { - vt = VT_ERROR; - scode = hr; - } -} - -int CPropVariant::Compare(const CPropVariant &a) -{ - if (vt != a.vt) - return 0; // it's mean some bug - switch (vt) - { - case VT_EMPTY: - return 0; - - /* - case VT_I1: - return MyCompare(cVal, a.cVal); - */ - case VT_UI1: - return MyCompare(bVal, a.bVal); - - case VT_I2: - return MyCompare(iVal, a.iVal); - case VT_UI2: - return MyCompare(uiVal, a.uiVal); - - case VT_I4: - return MyCompare(lVal, a.lVal); - /* - case VT_INT: - return MyCompare(intVal, a.intVal); - */ - case VT_UI4: - return MyCompare(ulVal, a.ulVal); - /* - case VT_UINT: - return MyCompare(uintVal, a.uintVal); - */ - case VT_I8: - return MyCompare(hVal.QuadPart, a.hVal.QuadPart); - case VT_UI8: - return MyCompare(uhVal.QuadPart, a.uhVal.QuadPart); - - case VT_BOOL: - return -MyCompare(boolVal, a.boolVal); - - case VT_FILETIME: - return ::CompareFileTime(&filetime, &a.filetime); - case VT_BSTR: - return 0; // Not implemented - // return MyCompare(aPropVarint.cVal); - - default: - return 0; - } -} - -}} diff --git a/desmume/src/windows/7z/CPP/Windows/PropVariant.h b/desmume/src/windows/7z/CPP/Windows/PropVariant.h deleted file mode 100644 index 85284e030..000000000 --- a/desmume/src/windows/7z/CPP/Windows/PropVariant.h +++ /dev/null @@ -1,57 +0,0 @@ -// Windows/PropVariant.h - -#ifndef __WINDOWS_PROPVARIANT_H -#define __WINDOWS_PROPVARIANT_H - -#include "../Common/MyWindows.h" -#include "../Common/Types.h" - -namespace NWindows { -namespace NCOM { - -class CPropVariant : public tagPROPVARIANT -{ -public: - CPropVariant() { vt = VT_EMPTY; wReserved1 = 0; } - ~CPropVariant() { Clear(); } - CPropVariant(const PROPVARIANT& varSrc); - CPropVariant(const CPropVariant& varSrc); - CPropVariant(BSTR bstrSrc); - CPropVariant(LPCOLESTR lpszSrc); - CPropVariant(bool bSrc) { vt = VT_BOOL; wReserved1 = 0; boolVal = (bSrc ? VARIANT_TRUE : VARIANT_FALSE); }; - CPropVariant(UInt32 value) { vt = VT_UI4; wReserved1 = 0; ulVal = value; } - CPropVariant(UInt64 value) { vt = VT_UI8; wReserved1 = 0; uhVal = *(ULARGE_INTEGER*)&value; } - CPropVariant(const FILETIME &value) { vt = VT_FILETIME; wReserved1 = 0; filetime = value; } - CPropVariant(Int32 value) { vt = VT_I4; wReserved1 = 0; lVal = value; } - CPropVariant(Byte value) { vt = VT_UI1; wReserved1 = 0; bVal = value; } - CPropVariant(Int16 value) { vt = VT_I2; wReserved1 = 0; iVal = value; } - // CPropVariant(LONG value, VARTYPE vtSrc = VT_I4) { vt = vtSrc; lVal = value; } - - CPropVariant& operator=(const CPropVariant& varSrc); - CPropVariant& operator=(const PROPVARIANT& varSrc); - CPropVariant& operator=(BSTR bstrSrc); - CPropVariant& operator=(LPCOLESTR lpszSrc); - CPropVariant& operator=(bool bSrc); - CPropVariant& operator=(UInt32 value); - CPropVariant& operator=(UInt64 value); - CPropVariant& operator=(const FILETIME &value); - - CPropVariant& operator=(Int32 value); - CPropVariant& operator=(Byte value); - CPropVariant& operator=(Int16 value); - // CPropVariant& operator=(LONG value); - - HRESULT Clear(); - HRESULT Copy(const PROPVARIANT* pSrc); - HRESULT Attach(PROPVARIANT* pSrc); - HRESULT Detach(PROPVARIANT* pDest); - - HRESULT InternalClear(); - void InternalCopy(const PROPVARIANT* pSrc); - - int Compare(const CPropVariant &a1); -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/Windows/StdAfx.h b/desmume/src/windows/7z/CPP/Windows/StdAfx.h deleted file mode 100644 index 5308d632d..000000000 --- a/desmume/src/windows/7z/CPP/Windows/StdAfx.h +++ /dev/null @@ -1,9 +0,0 @@ -// StdAfx.h - -#ifndef __STDAFX_H -#define __STDAFX_H - -#include "../Common/MyWindows.h" -#include "../Common/NewHandler.h" - -#endif diff --git a/desmume/src/windows/7z/CPP/Windows/Synchronization.h b/desmume/src/windows/7z/CPP/Windows/Synchronization.h deleted file mode 100644 index 1aeb91a6e..000000000 --- a/desmume/src/windows/7z/CPP/Windows/Synchronization.h +++ /dev/null @@ -1,168 +0,0 @@ -// Windows/Synchronization.h - -#ifndef __WINDOWS_SYNCHRONIZATION_H -#define __WINDOWS_SYNCHRONIZATION_H - -#include "Defs.h" - -extern "C" -{ -#include "../../C/Threads.h" -} - -#ifdef _WIN32 -#include "Handle.h" -#endif - -namespace NWindows { -namespace NSynchronization { - -class CBaseEvent -{ -protected: - ::CEvent _object; -public: - bool IsCreated() { return Event_IsCreated(&_object) != 0; } - operator HANDLE() { return _object.handle; } - CBaseEvent() { Event_Construct(&_object); } - ~CBaseEvent() { Close(); } - WRes Close() { return Event_Close(&_object); } - #ifdef _WIN32 - WRes Create(bool manualReset, bool initiallyOwn, LPCTSTR name = NULL, - LPSECURITY_ATTRIBUTES securityAttributes = NULL) - { - _object.handle = ::CreateEvent(securityAttributes, BoolToBOOL(manualReset), - BoolToBOOL(initiallyOwn), name); - if (_object.handle != 0) - return 0; - return ::GetLastError(); - } - WRes Open(DWORD desiredAccess, bool inheritHandle, LPCTSTR name) - { - _object.handle = ::OpenEvent(desiredAccess, BoolToBOOL(inheritHandle), name); - if (_object.handle != 0) - return 0; - return ::GetLastError(); - } - #endif - - WRes Set() { return Event_Set(&_object); } - // bool Pulse() { return BOOLToBool(::PulseEvent(_handle)); } - WRes Reset() { return Event_Reset(&_object); } - WRes Lock() { return Event_Wait(&_object); } -}; - -class CManualResetEvent: public CBaseEvent -{ -public: - WRes Create(bool initiallyOwn = false) - { - return ManualResetEvent_Create(&_object, initiallyOwn ? 1: 0); - } - WRes CreateIfNotCreated() - { - if (IsCreated()) - return 0; - return ManualResetEvent_CreateNotSignaled(&_object); - } - #ifdef _WIN32 - WRes CreateWithName(bool initiallyOwn, LPCTSTR name) - { - return CBaseEvent::Create(true, initiallyOwn, name); - } - #endif -}; - -class CAutoResetEvent: public CBaseEvent -{ -public: - WRes Create() - { - return AutoResetEvent_CreateNotSignaled(&_object); - } - WRes CreateIfNotCreated() - { - if (IsCreated()) - return 0; - return AutoResetEvent_CreateNotSignaled(&_object); - } -}; - -#ifdef _WIN32 -class CObject: public CHandle -{ -public: - WRes Lock(DWORD timeoutInterval = INFINITE) - { return (::WaitForSingleObject(_handle, timeoutInterval) == WAIT_OBJECT_0 ? 0 : ::GetLastError()); } -}; -class CMutex: public CObject -{ -public: - WRes Create(bool initiallyOwn, LPCTSTR name = NULL, - LPSECURITY_ATTRIBUTES securityAttributes = NULL) - { - _handle = ::CreateMutex(securityAttributes, BoolToBOOL(initiallyOwn), name); - if (_handle != 0) - return 0; - return ::GetLastError(); - } - WRes Open(DWORD desiredAccess, bool inheritHandle, LPCTSTR name) - { - _handle = ::OpenMutex(desiredAccess, BoolToBOOL(inheritHandle), name); - if (_handle != 0) - return 0; - return ::GetLastError(); - } - WRes Release() - { - return ::ReleaseMutex(_handle) ? 0 : ::GetLastError(); - } -}; -class CMutexLock -{ - CMutex *_object; -public: - CMutexLock(CMutex &object): _object(&object) { _object->Lock(); } - ~CMutexLock() { _object->Release(); } -}; -#endif - -class CSemaphore -{ - ::CSemaphore _object; -public: - CSemaphore() { Semaphore_Construct(&_object); } - ~CSemaphore() { Close(); } - WRes Close() { return Semaphore_Close(&_object); } - operator HANDLE() { return _object.handle; } - WRes Create(UInt32 initiallyCount, UInt32 maxCount) - { - return Semaphore_Create(&_object, initiallyCount, maxCount); - } - WRes Release() { return Semaphore_Release1(&_object); } - WRes Release(UInt32 releaseCount) { return Semaphore_ReleaseN(&_object, releaseCount); } - WRes Lock() { return Semaphore_Wait(&_object); } -}; - -class CCriticalSection -{ - ::CCriticalSection _object; -public: - CCriticalSection() { CriticalSection_Init(&_object); } - ~CCriticalSection() { CriticalSection_Delete(&_object); } - void Enter() { CriticalSection_Enter(&_object); } - void Leave() { CriticalSection_Leave(&_object); } -}; - -class CCriticalSectionLock -{ - CCriticalSection *_object; - void Unlock() { _object->Leave(); } -public: - CCriticalSectionLock(CCriticalSection &object): _object(&object) {_object->Enter(); } - ~CCriticalSectionLock() { Unlock(); } -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/Windows/Thread.h b/desmume/src/windows/7z/CPP/Windows/Thread.h deleted file mode 100644 index 6a1e63f23..000000000 --- a/desmume/src/windows/7z/CPP/Windows/Thread.h +++ /dev/null @@ -1,38 +0,0 @@ -// Windows/Thread.h - -#ifndef __WINDOWS_THREAD_H -#define __WINDOWS_THREAD_H - -#include "Defs.h" - -extern "C" -{ -#include "../../C/Threads.h" -} - -namespace NWindows { - -class CThread -{ - ::CThread thread; -public: - CThread() { Thread_Construct(&thread); } - ~CThread() { Close(); } - bool IsCreated() { return Thread_WasCreated(&thread) != 0; } - WRes Close() { return Thread_Close(&thread); } - WRes Create(THREAD_FUNC_RET_TYPE (THREAD_FUNC_CALL_TYPE *startAddress)(void *), LPVOID parameter) - { return Thread_Create(&thread, startAddress, parameter); } - WRes Wait() { return Thread_Wait(&thread); } - - #ifdef _WIN32 - DWORD Resume() { return ::ResumeThread(thread.handle); } - DWORD Suspend() { return ::SuspendThread(thread.handle); } - bool Terminate(DWORD exitCode) { return BOOLToBool(::TerminateThread(thread.handle, exitCode)); } - int GetPriority() { return ::GetThreadPriority(thread.handle); } - bool SetPriority(int priority) { return BOOLToBool(::SetThreadPriority(thread.handle, priority)); } - #endif -}; - -} - -#endif diff --git a/desmume/src/windows/7z/CPP/Windows/Time.cpp b/desmume/src/windows/7z/CPP/Windows/Time.cpp deleted file mode 100644 index ff49803ab..000000000 --- a/desmume/src/windows/7z/CPP/Windows/Time.cpp +++ /dev/null @@ -1,86 +0,0 @@ -// Windows/Time.cpp - -#include "StdAfx.h" - -#include "Time.h" -#include "Windows/Defs.h" - -namespace NWindows { -namespace NTime { - -bool DosTimeToFileTime(UInt32 dosTime, FILETIME &fileTime) -{ - return BOOLToBool(::DosDateTimeToFileTime((UInt16)(dosTime >> 16), (UInt16)(dosTime & 0xFFFF), &fileTime)); -} - -static const UInt32 kHighDosTime = 0xFF9FBF7D; -static const UInt32 kLowDosTime = 0x210000; - -bool FileTimeToDosTime(const FILETIME &fileTime, UInt32 &dosTime) -{ - WORD datePart, timePart; - if (!::FileTimeToDosDateTime(&fileTime, &datePart, &timePart)) - { - dosTime = (fileTime.dwHighDateTime >= 0x01C00000) ? kHighDosTime : kLowDosTime; - return false; - } - dosTime = (((UInt32)datePart) << 16) + timePart; - return true; -} - -static const UInt32 kNumTimeQuantumsInSecond = 10000000; -static const UInt64 kUnixTimeStartValue = ((UInt64)kNumTimeQuantumsInSecond) * 60 * 60 * 24 * 134774; - -void UnixTimeToFileTime(UInt32 unixTime, FILETIME &fileTime) -{ - UInt64 v = kUnixTimeStartValue + ((UInt64)unixTime) * kNumTimeQuantumsInSecond; - fileTime.dwLowDateTime = (DWORD)v; - fileTime.dwHighDateTime = (DWORD)(v >> 32); -} - -bool FileTimeToUnixTime(const FILETIME &fileTime, UInt32 &unixTime) -{ - UInt64 winTime = (((UInt64)fileTime.dwHighDateTime) << 32) + fileTime.dwLowDateTime; - if (winTime < kUnixTimeStartValue) - { - unixTime = 0; - return false; - } - winTime = (winTime - kUnixTimeStartValue) / kNumTimeQuantumsInSecond; - if (winTime > 0xFFFFFFFF) - { - unixTime = 0xFFFFFFFF; - return false; - } - unixTime = (UInt32)winTime; - return true; -} - -bool GetSecondsSince1601(unsigned year, unsigned month, unsigned day, - unsigned hour, unsigned min, unsigned sec, UInt64 &resSeconds) -{ - resSeconds = 0; - if (year < 1601 || year >= 10000 || month < 1 || month > 12 || - day < 1 || day > 31 || hour > 23 || min > 59 || sec > 59) - return false; - UInt32 numYears = year - 1601; - UInt32 numDays = numYears * 365 + numYears / 4 - numYears / 100 + numYears / 400; - Byte ms[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; - if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) - ms[1] = 29; - month--; - for (unsigned i = 0; i < month; i++) - numDays += ms[i]; - numDays += day - 1; - resSeconds = ((UInt64)(numDays * 24 + hour) * 60 + min) * 60 + sec; - return true; -} - -void GetCurUtcFileTime(FILETIME &ft) -{ - SYSTEMTIME st; - GetSystemTime(&st); - SystemTimeToFileTime(&st, &ft); -} - -}} diff --git a/desmume/src/windows/7z/CPP/Windows/Time.h b/desmume/src/windows/7z/CPP/Windows/Time.h deleted file mode 100644 index 7ecb204b2..000000000 --- a/desmume/src/windows/7z/CPP/Windows/Time.h +++ /dev/null @@ -1,21 +0,0 @@ -// Windows/Time.h - -#ifndef __WINDOWS_TIME_H -#define __WINDOWS_TIME_H - -#include "Common/Types.h" - -namespace NWindows { -namespace NTime { - -bool DosTimeToFileTime(UInt32 dosTime, FILETIME &fileTime); -bool FileTimeToDosTime(const FILETIME &fileTime, UInt32 &dosTime); -void UnixTimeToFileTime(UInt32 unixTime, FILETIME &fileTime); -bool FileTimeToUnixTime(const FILETIME &fileTime, UInt32 &unixTime); -bool GetSecondsSince1601(unsigned year, unsigned month, unsigned day, - unsigned hour, unsigned min, unsigned sec, UInt64 &resSeconds); -void GetCurUtcFileTime(FILETIME &ft); - -}} - -#endif diff --git a/desmume/src/windows/7z/DOC/License.txt b/desmume/src/windows/7z/DOC/License.txt deleted file mode 100644 index b472b97a8..000000000 --- a/desmume/src/windows/7z/DOC/License.txt +++ /dev/null @@ -1,57 +0,0 @@ -NOTE: The 7-zip library source is available under the LGPL, -however, this copy of it is distributed under the GPL 2.0. -This license has been modified accordingly. - - - 7-Zip source code - ~~~~~~~~~~~~~~~~~ - License for use and distribution - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - 7-Zip Copyright (C) 1999-2009 Igor Pavlov. - - Licenses for files are: - - 1) The 8 files in CPP/7zip/Compress/Rar*: GNU GPL 2.0 + unRAR restriction - 2) All other files: GNU GPL 2.0 - - The GNU GPL + unRAR restriction means that you must follow both - GNU GPL rules and unRAR restriction rules. - - - GNU GPL information - -------------------- - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; either version 2 - of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - - - unRAR restriction - ----------------- - - The decompression engine for RAR archives was developed using source - code of unRAR program. - All copyrights to original unRAR code are owned by Alexander Roshal. - - The license for original unRAR code has the following restriction: - - The unRAR sources cannot be used to re-create the RAR compression algorithm, - which is proprietary. Distribution of modified unRAR sources in separate form - or as a part of other software is permitted, provided that it is clearly - stated in the documentation and source comments that the code may - not be used to develop a RAR (WinRAR) compatible archiver. - - - -- - Igor Pavlov diff --git a/desmume/src/windows/7z/DOC/gpl.txt b/desmume/src/windows/7z/DOC/gpl.txt deleted file mode 100644 index 82fa1daad..000000000 --- a/desmume/src/windows/7z/DOC/gpl.txt +++ /dev/null @@ -1,339 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 - - Copyright (C) 1989, 1991 Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Lesser General Public License instead.) You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -this service if you wish), that you receive source code or can get it -if you want it, that you can change the software or use pieces of it -in new free programs; and that you know you can do these things. - - To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. - - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. - - The precise terms and conditions for copying, distribution and -modification follow. - - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - - 1. You may copy and distribute verbatim copies of the Program's -source code as you receive it, in any medium, provided that you -conspicuously and appropriately publish on each copy an appropriate -copyright notice and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. - -You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a fee. - - 2. You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. - -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: - - a) Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. - -If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this License. -However, parties who have received copies, or rights, from you under -this License will not have their licenses terminated so long as such -parties remain in full compliance. - - 5. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject to -these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to -this License. - - 7. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 9. The Free Software Foundation may publish revised and/or new versions -of the General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - -Each version is given a distinguishing version number. If the Program -specifies a version number of this License which applies to it and "any -later version", you have the option of following the terms and conditions -either of that version or of any later version published by the Free -Software Foundation. If the Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. - - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the author -to ask for permission. For software which is copyrighted by the Free -Software Foundation, write to the Free Software Foundation; we sometimes -make exceptions for this. Our decision will be guided by the two goals -of preserving the free status of all derivatives of our free software and -of promoting the sharing and reuse of software generally. - - NO WARRANTY - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS -TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, -REPAIR OR CORRECTION. - - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR -REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING -OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED -TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER -PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License along - with this program; if not, write to the Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - -Also add information on how to contact you by electronic and paper mail. - -If the program is interactive, make it output a short notice like this -when it starts in an interactive mode: - - Gnomovision version 69, Copyright (C) year name of author - Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, the commands you use may -be called something other than `show w' and `show c'; they could even be -mouse-clicks or menu items--whatever suits your program. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the program, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the program - `Gnomovision' (which makes passes at compilers) written by James Hacker. - - , 1 April 1989 - Ty Coon, President of Vice - -This General Public License does not permit incorporating your program into -proprietary programs. If your program is a subroutine library, you may -consider it more useful to permit linking proprietary applications with the -library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. diff --git a/desmume/src/windows/7z/DOC/readme.txt b/desmume/src/windows/7z/DOC/readme.txt deleted file mode 100644 index d7de5c264..000000000 --- a/desmume/src/windows/7z/DOC/readme.txt +++ /dev/null @@ -1,48 +0,0 @@ -This copy of the 7-zip source code has been modified as follows: -- Encoding support has been disabled, so only archive extraction is supported. -- Some archive formats have been removed, so only 7z, bzip2, gzip, lzh, lzma, rar, split, tar, and zip are supported. -- Support for using it as a static library has been added. (specifically, a file called InitializeStaticLib.h) -- Occasional minor fixes/customization not really worth describing in detail. -- The LGPL part of the 7-zip library source license has been upgraded to GPL 2.0 (as per condition 3 of the LGPL 2.1) - -You can find most of the files in this library in the "7-Zip Source code" download at http://www.7-zip.org/ distributed under the LGPL 2.1. A small subset of them are in the LZMA SDK which is public domain and can be found at http://www.7-zip.org/sdk.html - - - -7-Zip 4.64 Sources ------------------- - -7-Zip is a file archiver for Windows 95/98/ME/NT/2000/2003/XP/Vista. - -7-Zip Copyright (C) 1999-2009 Igor Pavlov. - - -License Info ------------- - -This copy of 7-Zip is free software distributed under the GNU GPL 2.0 -(with an additional restriction that has always applied to the unRar code). -read License.txt for more infomation about license. - -Notes about unRAR license: - -Please check main restriction from unRar license: - - 2. The unRAR sources may be used in any software to handle RAR - archives without limitations free of charge, but cannot be used - to re-create the RAR compression algorithm, which is proprietary. - Distribution of modified unRAR sources in separate form or as a - part of other software is permitted, provided that it is clearly - stated in the documentation and source comments that the code may - not be used to develop a RAR (WinRAR) compatible archiver. - -In brief it means: -1) You can compile and use compiled files under GNU GPL rules, since - unRAR license almost has no restrictions for compiled files. - You can link these compiled files to GPL programs. -2) You can fix bugs in source code and use compiled fixed version. -3) You can not use unRAR sources to re-create the RAR compression algorithm. - ---- -Igor Pavlov -http://www.7-zip.org diff --git a/desmume/src/windows/7z/DOC/unRarLicense.txt b/desmume/src/windows/7z/DOC/unRarLicense.txt deleted file mode 100644 index 5f78b728d..000000000 --- a/desmume/src/windows/7z/DOC/unRarLicense.txt +++ /dev/null @@ -1,41 +0,0 @@ - ****** ***** ****** unRAR - free utility for RAR archives - ** ** ** ** ** ** ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ****** ******* ****** License for use and distribution of - ** ** ** ** ** ** ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ** ** ** ** ** ** FREE portable version - ~~~~~~~~~~~~~~~~~~~~~ - - The source code of unRAR utility is freeware. This means: - - 1. All copyrights to RAR and the utility unRAR are exclusively - owned by the author - Alexander Roshal. - - 2. The unRAR sources may be used in any software to handle RAR - archives without limitations free of charge, but cannot be used - to re-create the RAR compression algorithm, which is proprietary. - Distribution of modified unRAR sources in separate form or as a - part of other software is permitted, provided that it is clearly - stated in the documentation and source comments that the code may - not be used to develop a RAR (WinRAR) compatible archiver. - - 3. The unRAR utility may be freely distributed. No person or company - may charge a fee for the distribution of unRAR without written - permission from the copyright holder. - - 4. THE RAR ARCHIVER AND THE UNRAR UTILITY ARE DISTRIBUTED "AS IS". - NO WARRANTY OF ANY KIND IS EXPRESSED OR IMPLIED. YOU USE AT - YOUR OWN RISK. THE AUTHOR WILL NOT BE LIABLE FOR DATA LOSS, - DAMAGES, LOSS OF PROFITS OR ANY OTHER KIND OF LOSS WHILE USING - OR MISUSING THIS SOFTWARE. - - 5. Installing and using the unRAR utility signifies acceptance of - these terms and conditions of the license. - - 6. If you don't agree with terms of the license you must remove - unRAR files from your storage devices and cease to use the - utility. - - Thank you for your interest in RAR and unRAR. - - - Alexander L. Roshal \ No newline at end of file diff --git a/desmume/src/windows/CWindow.cpp b/desmume/src/windows/CWindow.cpp index e6581e5bd..d8535577c 100644 --- a/desmume/src/windows/CWindow.cpp +++ b/desmume/src/windows/CWindow.cpp @@ -1,6 +1,5 @@ /* Copyright (C) 2006 yopyop - yopyop156@ifrance.com - yopyop156.ifrance.com + Copyright (C) 2006-2009 DeSmuME team This file is part of DeSmuME diff --git a/desmume/src/windows/CWindow.h b/desmume/src/windows/CWindow.h index 96640a260..c30de934d 100644 --- a/desmume/src/windows/CWindow.h +++ b/desmume/src/windows/CWindow.h @@ -1,6 +1,5 @@ /* Copyright (C) 2006 yopyop - yopyop156@ifrance.com - yopyop156.ifrance.com + Copyright (C) 2006-2009 DeSmuME team This file is part of DeSmuME diff --git a/desmume/src/windows/DeSmuME_2005.vcproj b/desmume/src/windows/DeSmuME_2005.vcproj index 8f599c4b4..76581a658 100644 --- a/desmume/src/windows/DeSmuME_2005.vcproj +++ b/desmume/src/windows/DeSmuME_2005.vcproj @@ -78,7 +78,7 @@ />