private void ReadInitialLoadSegment(ref ShockwaveReader input, AfterBurnerMapEntry[] entries, Dictionary <int, ChunkItem> chunks)
        {
            //First entry in the AfterBurnerMap must be ILS.
            AfterBurnerMapEntry ilsEntry = entries[0];

            input.Advance(ilsEntry.Offset);

            //TODO: this shouldn't be here
            ReadOnlySpan <byte> compressedData = input.ReadBytes(ilsEntry.Length);

            Span <byte> decompressedData = ilsEntry.DecompressedLength <= 1024 ?
                                           stackalloc byte[ilsEntry.DecompressedLength] : new byte[ilsEntry.DecompressedLength];

            ZLib.Decompress(compressedData, decompressedData);

            ShockwaveReader ilsReader = new ShockwaveReader(decompressedData, input.IsBigEndian);

            while (ilsReader.IsDataAvailable)
            {
                int id = ilsReader.Read7BitEncodedInt();

                AfterBurnerMapEntry entry = entries.FirstOrDefault(e => e.Id == id); //TODO: Chunk entries as dictionary
                if (entry == null)
                {
                    break;
                }

                chunks.Add(id, Read(ref ilsReader, entry.Header));
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Read the metadata using the supplied reader.
        /// </summary>
        /// <param name="reader">The reader to use to read the metadata with. It is
        /// already positioned at the first byte of metadata.</param>
        /// <param name="nCompressedLen">The length of the compressed metadata. The first
        /// four bytes is the size of the uncompressed data.</param>
        public BookMetaData DeserializeMetaData(BinaryReader reader, int nCompressedLen)
        {
            Debug.WriteLineIf(s_bDebugMode, "Reading metadata");

            byte[] byUncompressedData = ZLib.Decompress(reader, nCompressedLen);

            Debug.WriteLineIf(s_bDebugMode, "Parsing metadata");
            MemoryStream xmlStream = new MemoryStream(byUncompressedData);

            XmlSerializer serializer = new XmlSerializer(typeof(BookMetaData));
            XmlTextReader xreader    = new XmlTextReader(xmlStream);
            BookMetaData  metaData   = null;

            try
            {
                metaData = (BookMetaData)serializer.Deserialize(xreader);
            }
            catch (Exception e)
            {
                Debug.WriteLineIf(s_bDebugMode, e.ToString());
            }
            xreader.Close();

            return(metaData);
        }
Esempio n. 3
0
        //public unsafe T[] GetData<T>(int compressedSize, int uncompressedSize) where T : struct
        //{
        //    T[] data = new T[uncompressedSize];
        //    IntPtr destPtr = (IntPtr) UnsafeMemoryManager.AsPointer(ref data);
        //    ZLib.Decompress(PositionAddress, compressedSize, 0, destPtr, uncompressedSize);

        //    return data;
        //}

        public unsafe byte[] GetData(int compressedSize, int uncompressedSize)
        {
            byte[] data = new byte[uncompressedSize];

            fixed(byte *destPtr = data)
            ZLib.Decompress(PositionAddress, compressedSize, 0, (IntPtr)destPtr, uncompressedSize);

            return(data);
        }
Esempio n. 4
0
        public void Load(string filename)
        {
            FileInfo = new FileInfo(filename);

            using (var br = new BinaryReaderX(FileInfo.OpenRead()))
            {
                br.ReadBytes(4);
                _sarc = new SARC(new MemoryStream(ZLib.Decompress(new MemoryStream(br.ReadBytes((int)FileInfo.Length - 4)))));
            }
        }
Esempio n. 5
0
        public override Task Load()
        {
            return(Task.Run(() =>
            {
                string path = Path.Combine(FileManager.UoFolderPath, "multi.mul");
                string pathidx = Path.Combine(FileManager.UoFolderPath, "multi.idx");

                if (File.Exists(path) && File.Exists(pathidx))
                {
                    _file = new UOFileMul(path, pathidx, Constants.MAX_MULTI_DATA_INDEX_COUNT, 14);
                }
                else
                {
                    throw new FileNotFoundException();
                }

                Count = _itemOffset = FileManager.ClientVersion >= ClientVersions.CV_7090 ? UnsafeMemoryManager.SizeOf <MultiBlockNew>() : UnsafeMemoryManager.SizeOf <MultiBlock>();


                string uopPath = Path.Combine(FileManager.UoFolderPath, "MultiCollection.uop");

                if (File.Exists(uopPath))
                {
                    Count = Constants.MAX_MULTI_DATA_INDEX_COUNT;
                    _fileUop = new UOFileUopNoFormat(uopPath);
                    _reader = new DataReader();

                    for (int i = 0; i < _fileUop.Entries.Length; i++)
                    {
                        long offset = _fileUop.Entries[i].Offset;
                        int csize = _fileUop.Entries[i].Length;
                        int dsize = _fileUop.Entries[i].DecompressedLength;

                        _fileUop.Seek(offset);
                        byte[] cdata = _fileUop.ReadArray <byte>(csize);
                        byte[] ddata = new byte[dsize];

                        ZLib.Decompress(cdata, 0, ddata, dsize);
                        _reader.SetData(ddata, dsize);

                        uint id = _reader.ReadUInt();

                        if (id < Constants.MAX_MULTI_DATA_INDEX_COUNT && id < _file.Entries.Length)
                        {
                            ref UOFileIndex3D index = ref _file.Entries[id];
                            int count = _reader.ReadInt();

                            index = new UOFileIndex3D(offset, csize, dsize, (int)MathHelper.Combine(count, index.Extra));
                        }
                    }

                    _reader.ReleaseData();
                }
            }));
Esempio n. 6
0
        public static void OnAuthSession(RealmServerSession session, CmsgAuthSession handler)
        {
            // Check the version of client trying to connect [5875]

            // DONE: Check Account
            session.Users = MainForm.Database.GetAccount(handler.ClientAccount);

            // Kick if existing

            // Check if account is banned

            // DONE: Set Crypt Hash Player
            session.PacketCrypto = new VanillaCrypt();
            session.PacketCrypto.Init(session.Users.sessionkey);

            // Disconnect clients trying to enter with an invalid build
            //if (handler.Build < 5875 || handler.Build > 6141)

            // Disconnect clients trying to enter with an invalid build

            // If server full then queue, If GM/Admin let in

            // DONE: Addons info reading
            #region NOT USED
            var addonData    = handler.ReadBytes((int)handler.BaseStream.Length - (int)handler.BaseStream.Position);
            var decompressed = ZLib.Decompress(addonData);
            //RealmServerSession.DumpPacket(decompressed);
            List <string> addOnsNames = new List <string>();
            using (var reader = new PacketReader(new MemoryStream(decompressed)))
            {
                var count = reader.BaseStream.Length / sizeof(int);
                for (var i = 0; i < count; ++i)
                {
                    //var addonName = reader.ReadString();
                    //if (addonName.Equals("")) continue;
                    //addOnsNames.Add(addonName);
                }
            }
            #endregion

            // Update [IP / Build]

            // Create Log

            // Init Warden

            // DONE: Send Addon Packet
            session.SendPacket(new SmsgAddonInfo(addOnsNames));

            // DONE: Send packet
            session.SendPacket(new SmsgAuthResponse());
        }
Esempio n. 7
0
        public LoadResult Load(string filename)
        {
            FileInfo = new FileInfo(filename);
            if (!FileInfo.Exists)
            {
                return(LoadResult.FileNotFound);
            }

            using (var br = new BinaryReaderX(File.OpenRead(filename)))
            {
                br.ReadBytes(4);
                _sarc = new SARC(new MemoryStream(ZLib.Decompress(br.ReadBytes((int)FileInfo.Length - 4))));
                return(LoadResult.Success);
            }
        }
Esempio n. 8
0
        public X3(Stream input)
        {
            _stream = input;
            using (var br = new BinaryReaderX(input, true))
            {
                //Header
                _header = br.ReadStruct <FileHeader>();

                _fileEntries = br.ReadMultiple <FileEntry>(_header.FileCount);

                foreach (var entry in _fileEntries)
                {
                    var compressed = entry.UncompressedSize != entry.CompressedSize && entry.UncompressedSize > 0;
                    br.BaseStream.Position = entry.Offset * _header.Alignment + (compressed ? 0x4 : 0);

                    byte[] firstBlock;
                    if (compressed)
                    {
                        var firstBlockLength = br.ReadInt32();
                        firstBlock = ZLib.Decompress(new MemoryStream(br.ReadBytes(firstBlockLength)));
                    }
                    else
                    {
                        firstBlock = br.ReadBytes(4);
                    }
                    var magic     = Encoding.ASCII.GetString(firstBlock.Take(4).ToArray());
                    var extension = ".bin";

                    if (magic == "GT1G")
                    {
                        extension = ".3ds.g1t";
                    }
                    else if (magic == "SMDH")
                    {
                        extension = ".icn";
                    }

                    Files.Add(new X3FileInfo
                    {
                        State            = ArchiveFileState.Archived,
                        FileName         = Files.Count.ToString("000000") + extension,
                        FileData         = new SubStream(br.BaseStream, entry.Offset * _header.Alignment, entry.CompressedSize),
                        Entry            = entry,
                        CompressionLevel = compressed ? CompressionLevel.Optimal : CompressionLevel.NoCompression
                    });
                }
            }
        }
Esempio n. 9
0
 public bool Identify(string filename)
 {
     using (var br = new BinaryReaderX(File.OpenRead(filename), ByteOrder.BigEndian))
     {
         try
         {
             var decompSize = br.ReadUInt32();
             var decomp     = ZLib.Decompress(new MemoryStream(br.ReadBytes((int)br.BaseStream.Length - 4)));
             return(decompSize == decomp.Length);
         }
         catch
         {
             return(false);
         }
     }
 }
Esempio n. 10
0
        public override long Seek(long offset, SeekOrigin origin)
        {
            if (!this.m_Compressed)
            {
                return(this.RawStream.Seek(offset, origin));
            }
            long num = offset;

            if (origin == SeekOrigin.Current)
            {
                num += this.m_Uncomp.Position;
            }
            if (num < 0L)
            {
                throw new Exception("Cannot seek past the begining of the stream.");
            }
            long position = this.m_Uncomp.Position;

            this.m_Uncomp.Seek(0L, SeekOrigin.End);
            while ((origin == SeekOrigin.End || num >= this.m_Uncomp.Length) && this.RawStream.Position < this.RawStream.Length)
            {
                int count1 = this.Raw.ReadInt32();
                int count2 = this.Raw.ReadInt32();
                if (GZBlockIn.m_ReadBuff == null || GZBlockIn.m_ReadBuff.Length < count1)
                {
                    GZBlockIn.m_ReadBuff = new byte[count1];
                }
                if (GZBlockIn.m_CompBuff == null || GZBlockIn.m_CompBuff.Length < count2)
                {
                    GZBlockIn.m_CompBuff = new byte[count2];
                }
                else
                {
                    count2 = GZBlockIn.m_CompBuff.Length;
                }
                this.Raw.Read(GZBlockIn.m_ReadBuff, 0, count1);
                Z_RESULT zResult = ZLib.Decompress(GZBlockIn.m_CompBuff, ref count2, GZBlockIn.m_ReadBuff, count1);
                if (zResult != null)
                {
                    throw new Exception("ZLib error uncompressing: " + ((object)zResult).ToString());
                }
                this.m_Uncomp.Write(GZBlockIn.m_CompBuff, 0, count2);
            }
            this.m_Uncomp.Position = position;
            return(this.m_Uncomp.Seek(offset, origin));
        }
Esempio n. 11
0
        public override int Read(byte[] buffer, int offset, int count)
        {
            if (!this.m_Compressed)
            {
                return(this.RawStream.Read(buffer, offset, count));
            }
            long position = this.m_Uncomp.Position;

            this.m_Uncomp.Seek(0L, SeekOrigin.End);
            while (position + (long)count > this.m_Uncomp.Length && this.RawStream.Position + 8L < this.RawStream.Length)
            {
                int count1 = this.Raw.ReadInt32();
                int count2 = this.Raw.ReadInt32();
                if (count1 <= 268435456 && count1 > 0 && (count2 <= 268435456 && count2 > 0) && this.RawStream.Position + (long)count1 <= this.RawStream.Length)
                {
                    if (GZBlockIn.m_ReadBuff == null || GZBlockIn.m_ReadBuff.Length < count1)
                    {
                        GZBlockIn.m_ReadBuff = new byte[count1];
                    }
                    if (GZBlockIn.m_CompBuff == null || GZBlockIn.m_CompBuff.Length < count2)
                    {
                        GZBlockIn.m_CompBuff = new byte[count2];
                    }
                    else
                    {
                        count2 = GZBlockIn.m_CompBuff.Length;
                    }
                    this.Raw.Read(GZBlockIn.m_ReadBuff, 0, count1);
                    Z_RESULT zResult = ZLib.Decompress(GZBlockIn.m_CompBuff, ref count2, GZBlockIn.m_ReadBuff, count1);
                    if (zResult != null)
                    {
                        throw new Exception("ZLib error uncompressing: " + ((object)zResult).ToString());
                    }
                    this.m_Uncomp.Write(GZBlockIn.m_CompBuff, 0, count2);
                }
                else
                {
                    break;
                }
            }
            this.m_Uncomp.Position = position;
            return(this.m_Uncomp.Read(buffer, offset, count));
        }
Esempio n. 12
0
        void HandleUpdateAccountData(UserClientUpdateAccountData packet)
        {
            if (packet.DataType > AccountDataTypes.Max)
                return;

            if (packet.Size == 0)
            {
                SetAccountData(packet.DataType, 0, "");
                return;
            }

            if (packet.Size > 0xFFFF)
            {
                Log.outError(LogFilter.Network, "UpdateAccountData: Account data packet too big, size {0}", packet.Size);
                return;
            }

            byte[] data = ZLib.Decompress(packet.CompressedData.GetData(), packet.Size);
            SetAccountData(packet.DataType, packet.Time, Encoding.Default.GetString(data));
        }
Esempio n. 13
0
        private static void CheckAddons(BinaryReader handler)
        {
            var addonData    = handler.ReadBytes((int)handler.BaseStream.Length - (int)handler.BaseStream.Position);
            var decompressed = ZLib.Decompress(addonData);

            using (var reader = new Common.Network.PacketReader(new MemoryStream(decompressed)))
            {
                // TODO: find length addons
                for (var i = 0; i < 12; ++i)
                {
                    var addonName = reader.ReadCString();
                    var enabled   = reader.ReadByte();
                    var crc       = reader.ReadUInt32();
                    var unk7      = reader.ReadUInt32();
                    AddOnsNames.Add(addonName);

                    Console.WriteLine(@"Addon {0}: [ {1} ] enabled: {2} | crc: {3} | unk7: {4}", i.ToString().PadRight(2, ' '), addonName.PadRight(30, ' '), enabled,
                                      crc, unk7);
                }
            }
        }
Esempio n. 14
0
        public bool Identify(string filename)
        {
            using (var br = new BinaryReaderX(File.OpenRead(filename)))
            {
                if (br.BaseStream.Length < 4)
                {
                    return(false);
                }
                if (br.ReadString(4) == "NUS3")
                {
                    return(true);
                }
                else
                {
                    try
                    {
                        br.BaseStream.Position = 0;
                        byte[] decomp = ZLib.Decompress(br.ReadBytes((int)br.BaseStream.Length));
                        using (var br2 = new BinaryReaderX(new MemoryStream(decomp)))
                        {
                            if (br.BaseStream.Length < 4)
                            {
                                return(false);
                            }
                            if (br.ReadString(4) == "NUS3")
                            {
                                isZlibCompressed = true;
                                return(true);
                            }
                        }
                    }
                    catch (Exception)
                    {
                        return(false);
                    }
                };

                return(false);
            }
        }
Esempio n. 15
0
        public bool Identify(string filename)
        {
            using (var br = new BinaryReaderX(File.OpenRead(filename)))
            {
                if (br.BaseStream.Length < 4)
                {
                    return(false);
                }
                if (br.ReadString(4) == "NUS3")
                {
                    return(true);
                }

                try
                {
                    // TODO: Replace this decompression with zLib magic detection to speed things up.
                    br.BaseStream.Position = 0;
                    byte[] decomp = ZLib.Decompress(new MemoryStream(br.ReadBytes((int)br.BaseStream.Length)));
                    using (var br2 = new BinaryReaderX(new MemoryStream(decomp)))
                    {
                        if (br.BaseStream.Length < 4)
                        {
                            return(false);
                        }
                        if (br.ReadString(4) == "NUS3")
                        {
                            _isZlibCompressed = true;
                            return(true);
                        }
                    }
                }
                catch (Exception)
                {
                    return(false);
                }

                return(false);
            }
        }
Esempio n. 16
0
        public static unsafe void LoadDeflated(int xMin, int yMin, int xMax, int yMax, byte[] buffer, ArrayList list)
        {
            int num1 = yMax - yMin + 1;

            fixed(byte *numPtr1 = buffer)
            {
                IntPtr num2    = new IntPtr(1);
                byte * numPtr2 = numPtr1 + num2.ToInt64();
                int    num3    = (int)numPtr1[0];

                for (int index1 = 0; index1 < num3; ++index1)
                {
                    int num4    = (int)*numPtr2 >> 4 & 15;
                    int num5    = (int)*numPtr2 & 15;
                    int length1 = (int)numPtr2[1] | (int)numPtr2[3] << 4 & 3840;
                    int length2 = (int)numPtr2[2] | (int)numPtr2[3] << 8 & 3840;
                    numPtr2 += 4;
                    if (CustomMultiEntry.m_InflateBuffer == null || CustomMultiEntry.m_InflateBuffer.Length < length1)
                        CustomMultiEntry.m_InflateBuffer = new byte[length1];
                    fixed(byte *numPtr3 = CustomMultiEntry.m_InflateBuffer)
                    {
                        IntPtr ptr      = (IntPtr)numPtr3;
                        var    localPtr = (byte *)ptr;

                        byte[] numArray = new byte[length2];
                        for (int index2 = 0; index2 < numArray.Length; ++index2)
                        {
                            numArray[index2] = *numPtr2++;
                        }
                        ZLib.Decompress(CustomMultiEntry.m_InflateBuffer, ref length1, numArray, numArray.Length);
                        byte *numPtr4 = localPtr + length1;

                        switch (num4)
                        {
                        case 0:
                            while (localPtr < numPtr4)
                            {
                                MultiItem multiItem = new MultiItem();
                                multiItem.Flags  = 1;
                                multiItem.ItemID = (short)(localPtr[0] << 8 | localPtr[1]);
                                multiItem.X      = (short)localPtr[2];
                                multiItem.Y      = (short)localPtr[3];
                                multiItem.Z      = (short)localPtr[4];
                                localPtr        += 5;
                                if ((int)multiItem.ItemID != 0)
                                {
                                    list.Add((object)multiItem);
                                }
                            }
                            break;

                        case 1:
                            int num6 = 0;
                            switch (num5)
                            {
                            case 0:
                                num6 = 0;
                                break;

                            case 1:
                            case 5:
                                num6 = 7;
                                break;

                            case 2:
                            case 6:
                                num6 = 27;
                                break;

                            case 3:
                            case 7:
                                num6 = 47;
                                break;

                            case 4:
                            case 8:
                                num6 = 67;
                                break;
                            }
                            while (localPtr < numPtr4)
                            {
                                MultiItem multiItem = new MultiItem();
                                multiItem.Flags  = 1;
                                multiItem.ItemID = (short)((int)localPtr[0] << 8 | (int)localPtr[1]);
                                multiItem.X      = (short)(sbyte)localPtr[2];
                                multiItem.Y      = (short)(sbyte)localPtr[3];
                                multiItem.Z      = (short)(sbyte)num6;
                                localPtr        += 4;
                                if ((int)multiItem.ItemID != 0)
                                {
                                    list.Add((object)multiItem);
                                }
                            }
                            break;

                        case 2:
                            int num7 = 0;
                            switch (num5)
                            {
                            case 0:
                                num7 = 0;
                                break;

                            case 1:
                            case 5:
                                num7 = 7;
                                break;

                            case 2:
                            case 6:
                                num7 = 27;
                                break;

                            case 3:
                            case 7:
                                num7 = 47;
                                break;

                            case 4:
                            case 8:
                                num7 = 67;
                                break;
                            }
                            int num8;
                            int num9;
                            int num10;
                            if (num5 <= 0)
                            {
                                num8  = xMin;
                                num9  = yMin;
                                num10 = num1 + 1;
                            }
                            else if (num5 <= 4)
                            {
                                num8  = xMin + 1;
                                num9  = yMin + 1;
                                num10 = num1 - 1;
                            }
                            else
                            {
                                num8  = xMin;
                                num9  = yMin;
                                num10 = num1;
                            }
                            int num11 = 0;
                            while (localPtr < numPtr4)
                            {
                                short num12 = (short)((int)localPtr[0] << 8 | (int)localPtr[1]);
                                ++num11;
                                localPtr += 2;
                                if ((int)num12 != 0)
                                {
                                    list.Add((object)new MultiItem()
                                    {
                                        Flags  = 1,
                                        ItemID = num12,
                                        X      = (short)(num8 + (num11 - 1) / num10),
                                        Y      = (short)(sbyte)(num9 + (num11 - 1) % num10),
                                        Z      = (short)(sbyte)num7
                                    });
                                }
                            }
                            break;
                        }
                    }
                }
            }
        }
Esempio n. 17
0
        public static void Decompress(object sender, EventArgs e)
        {
            var tsi = sender as ToolStripMenuItem;

            if (!Shared.PrepareFiles("Open a " + tsi?.Tag + " compressed file...", "Save your decompressed file...", ".decomp", out var openFile, out var saveFile))
            {
                return;
            }

            try
            {
                using (openFile)
                    using (var outFs = new BinaryWriterX(saveFile))
                        switch (tsi?.Tag)
                        {
                        case Compression.Level5:
                            outFs.Write(Level5.Decompress(openFile));
                            break;

                        case Compression.Nintendo:
                            outFs.Write(Nintendo.Decompress(openFile));
                            break;

                        case Compression.LZ77:
                            outFs.Write(LZ77.Decompress(openFile));
                            break;

                        case Compression.RevLZ77:
                            outFs.Write(RevLZ77.Decompress(openFile));
                            break;

                        case Compression.LZOvl:
                            outFs.Write(LZOvl.Decompress(openFile));
                            break;

                        case Compression.LZ4:
                            outFs.Write(Kontract.Compression.LZ4.Decompress(openFile));
                            break;

                        case Compression.MIO0LE:
                            outFs.Write(MIO0.Decompress(openFile, ByteOrder.LittleEndian));
                            break;

                        case Compression.MIO0BE:
                            outFs.Write(MIO0.Decompress(openFile, ByteOrder.BigEndian));
                            break;

                        case Compression.Yay0LE:
                            outFs.Write(Yay0.Decompress(openFile, ByteOrder.LittleEndian));
                            break;

                        case Compression.Yay0BE:
                            outFs.Write(Yay0.Decompress(openFile, ByteOrder.BigEndian));
                            break;

                        case Compression.Yaz0LE:
                            outFs.Write(Yaz0.Decompress(openFile, ByteOrder.LittleEndian));
                            break;

                        case Compression.Yaz0BE:
                            outFs.Write(Yaz0.Decompress(openFile, ByteOrder.BigEndian));
                            break;

                        case Compression.LZECD:
                            outFs.Write(LZECD.Decompress(openFile));
                            break;

                        case Compression.LZ10VLE:
                            outFs.Write(LZSSVLE.Decompress(openFile));
                            break;

                        case Compression.GZip:
                            outFs.Write(GZip.Decompress(openFile));
                            break;

                        case Compression.ZLib:
                            outFs.Write(ZLib.Decompress(openFile));
                            break;

                        case Compression.PSVSpikeChun:
                            outFs.Write(PSVSpikeChun.Decompress(openFile));
                            break;
                        }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), tsi?.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            MessageBox.Show($"Successfully decompressed {Path.GetFileName(openFile.Name)}.", tsi.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
Esempio n. 18
0
        public NUS3(string filename, bool isZlibCompressed = false)
        {
            // Compression
            if (isZlibCompressed)
            {
                using (BinaryReaderX br = new BinaryReaderX(File.OpenRead(filename)))
                {
                    byte[] decomp = ZLib.Decompress(new MemoryStream(br.ReadBytes((int)br.BaseStream.Length)));
                    File.Create(filename + ".decomp").Write(decomp, 0, decomp.Length);
                }

                _stream = File.OpenRead(filename + ".decomp");
            }
            else
            {
                _stream = File.OpenRead(filename);
            }

            using (var br = new BinaryReaderX(_stream, true))
            {
                // Header
                Header = br.ReadStruct <Header>();

                // BankTOC
                BankTOC = br.ReadStruct <BankTOC>();

                // Sections
                Sections = br.ReadMultiple <SectionHeader>(BankTOC.SectionCount);

                // Load Sections
                foreach (var section in Sections)
                {
                    switch (section.Magic)
                    {
                    case "PROP":
                        Prop = new PROP(br.BaseStream);
                        break;

                    case "BINF":
                        Binf = new BINF(br.BaseStream);
                        break;

                    case "GRP ":
                        Grp = new GRP(br.BaseStream);
                        break;

                    case "DTON":
                        Dton = new DTON(br.BaseStream);
                        break;

                    case "TONE":
                        Tone = new TONE(br.BaseStream);
                        break;

                    case "JUNK":
                        Junk = new JUNK(br.BaseStream);
                        break;

                    case "PACK":
                        Pack = br.ReadStruct <SectionHeader>();
                        break;
                    }
                }

                // Pack
                var packOffset = br.BaseStream.Position;
                for (int i = 0; i < Tone.ToneCount; i++)
                {
                    // Determine Extension
                    var extension = ".idsp";
                    if (br.PeekString(4) == "RIFF")
                    {
                        extension = ".wav";
                        br.BaseStream.Position += 0x14;
                        var format = br.ReadUInt16();
                        if (format == 0xFFFE)
                        {
                            extension = ".at9";
                        }
                    }

                    Files.Add(new NUS3FileInfo
                    {
                        FileName = Tone.Name + extension,
                        FileData = new SubStream(_stream, packOffset, Tone.PackSize),
                        State    = ArchiveFileState.Archived
                    });
                }
            }
        }
Esempio n. 19
0
        public static void Decompress(object sender, EventArgs e)
        {
            var tsi = sender as ToolStripMenuItem;

            if (!PrepareFiles("Open a " + tsi.Tag.ToString() + " compressed file...", "Save your decompressed file...", ".decomp", out FileStream openFile, out FileStream saveFile))
            {
                return;
            }

            try
            {
                using (openFile)
                    using (var outFs = new BinaryWriterX(saveFile))
                        switch (tsi.Tag)
                        {
                        case Compression.Level5:
                            outFs.Write(Level5.Decompress(openFile));
                            break;

                        case Compression.GZip:
                            outFs.Write(GZip.Decompress(openFile));
                            break;

                        case Compression.Huff4:
                            outFs.Write(Huffman.Decompress(openFile, 4));
                            break;

                        case Compression.Huff8:
                            outFs.Write(Huffman.Decompress(openFile, 8));
                            break;

                        case Compression.LZ10:
                            outFs.Write(LZ10.Decompress(openFile));
                            break;

                        case Compression.LZ11:
                            outFs.Write(LZ11.Decompress(openFile));
                            break;

                        case Compression.LZ77:
                            outFs.Write(LZ77.Decompress(openFile));
                            break;

                        /*case Compression.LZSS:
                         *  outFs.Write(LZSS.Decompress(openFile, LZSS.GetDecompressedSize(openFile)));
                         *  break;*/
                        case Compression.RevLZ77:
                            outFs.Write(RevLZ77.Decompress(openFile));
                            break;

                        case Compression.RLE:
                            outFs.Write(RLE.Decompress(openFile));
                            break;

                        case Compression.ZLib:
                            outFs.Write(ZLib.Decompress(openFile));
                            break;
                        }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), tsi?.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            MessageBox.Show($"Successfully decompressed {Path.GetFileName(openFile.Name)}.", tsi?.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
Esempio n. 20
0
        internal Record(string name, uint dataSize, BinaryReader recordReader, bool oblivion)
        {
            this.dataSize = dataSize;

            this.SubRecords = new AdvancedList <SubRecord>(1)
            {
                AllowSorting = false
            };
            Name        = name;
            this.Flags1 = recordReader.ReadUInt32();
            this.FormID = recordReader.ReadUInt32();
            this.Flags2 = recordReader.ReadUInt32();
            if (!oblivion)
            {
                this.Flags3 = recordReader.ReadUInt32();
            }

            var  compressed = (this.Flags1 & 0x00040000) != 0;
            uint amountRead = 0;

            var realSize = dataSize;

            if (compressed)
            {
                realSize  = recordReader.ReadUInt32();
                dataSize -= 4;
            }

            using (var stream = new MemoryStream(recordReader.ReadBytes((int)dataSize)))
            {
                using (var dataReader = compressed ? ZLib.Decompress(stream, (int)realSize) : new BinaryReader(stream))
                {
                    while (dataReader.BaseStream.Position < dataReader.BaseStream.Length)
                    {
                        var  type = ReadRecName(dataReader);
                        uint size;
                        if (type == "XXXX")
                        {
                            dataReader.ReadUInt16();
                            size = dataReader.ReadUInt32();
                            type = ReadRecName(dataReader);
                            dataReader.ReadUInt16();
                        }
                        else
                        {
                            size = dataReader.ReadUInt16();
                        }

                        var record = new SubRecord(this, type, dataReader, size);
                        this.SubRecords.Add(record);
                        amountRead += (uint)record.Size2;
                    }
                }
            }

            if (amountRead > realSize)
            {
                Debug.Print(" * ERROR: SUB-RECORD {0} DATA DOESN'T MATCH THE SIZE SPECIFIED IN THE HEADER: DATA-SIZE={1} REAL-SIZE={2} AMOUNT-READ={3}", name, dataSize, realSize, amountRead);
                throw new TESParserException(
                          string.Format("Subrecord block did not match the size specified in the record header: ExpectedSize={0} ReadSize={1} DataSize={2}", realSize, amountRead, dataSize));
            }

            this.descNameOverride = this.DefaultDescriptiveName;
            this.UpdateShortDescription();

            // br.BaseStream.Position+=Size;
        }
Esempio n. 21
0
        internal Record(string name, uint dataSizeParam, SnipStreamWrapper snipStreamWrapper, bool oblivion)  //internal Record(string name, uint dataSize, BinaryReader recordReader, bool oblivion)
        {
            bool compressed = false;
            uint amountRead = 0;
            uint realSize   = 0;

            //MemoryStream stream = null;
            //BinaryReader dataReader = null;
            SubRecord record = null;

            //long ws;

            try
            {
                this.dataSize = dataSizeParam;

                this.SubRecords = new AdvancedList <SubRecord>(1)
                {
                    AllowSorting = false
                };

                //if (snipStreamWrapper.SnipStream.Position >= 1330432)
                //    Name = name;

                Name = name;
                RecordsTace.AddRecordToRecordsList(Name);
                this.Flags1 = snipStreamWrapper.ReadUInt32(); //recordReader.ReadUInt32();
                this.FormID = snipStreamWrapper.ReadUInt32(); //recordReader.ReadUInt32();
                this.Flags2 = snipStreamWrapper.ReadUInt32(); //recordReader.ReadUInt32();
                if (!oblivion)
                {
                    this.Flags3 = snipStreamWrapper.ReadUInt32(); //recordReader.ReadUInt32();
                }

                //if (this.FormID == 496431)
                //    Name = name;

                compressed = (this.Flags1 & 0x00040000) != 0;
                amountRead = 0;
                realSize   = dataSizeParam;

                if (!compressed)
                {
                    realSize = dataSizeParam;
                }

                if (compressed)
                {
                    realSize = snipStreamWrapper.ReadUInt32(); // recordReader.ReadUInt32();
                    // snipStreamWrapper.JumpTo(-4,SeekOrigin.Current);
                    //if (realSize > 0)
                    dataSizeParam -= 4;
                    RecordsTace.AddRecordToCompressedRecordsList(Name);
                }

#if DEBUGCOMPRESSREALSIZE
                if (compressed & realSize == 0)
                {
                    Clipboard.SetText(name + " - " + this.FormID.ToString(CultureInfo.InvariantCulture));
                }
#endif

                //using (var stream = new MemoryStream(recordReader.ReadBytes((int) dataSize)))
                //{
                //using (var dataReader = compressed ? ZLib.Decompress(stream, (int) realSize) : new BinaryReader(stream))
                //{.
                try
                {
                    //if (dataSize == 0)
                    //    throw new TESParserException("Record.Record: ZLib inflate error. Output buffer is empty.");

                    if (dataSizeParam > 0) //dawnguard.esm at position 6.812.369 at a dataSize == 0 - Record=NAVM
                    {
                        ZLibWrapper.CopyStreamToInputBuffer(snipStreamWrapper.SnipStream, dataSizeParam);
                        //stream = new MemoryStream(recordReader.ReadBytes((int) dataSize));
                        //dataReader = compressed ? ZLib.Decompress(stream, out compressLevel, (int)realSize) : new BinaryReader(stream);
                        if (compressed & realSize > 0)
                        {
                            //Clipboard.SetText(Name + realSize.ToString(CultureInfo.InvariantCulture));
                            ZLib.Decompress(compressLevel: out compressLevel, expectedSize: (int)realSize);
                            //Array.Copy();
                        }
                        else
                        {
                            ZLibWrapper.CopyInputBufferToOutputBuffer(dataSizeParam);
                        }
                    }
                    else
                    {
                        ZLibWrapper.ResetBufferSizeAndPosition();
                    }
                }
                catch (Exception ex)
                {
                    throw new TESParserException("Record.Record: ZLib error" + Environment.NewLine +
                                                 "Message: " + ex.Message +
                                                 Environment.NewLine +
                                                 "StackTrace: " + ex.StackTrace);
                }

                if (compressed & dataSizeParam > 0)          //dawnguard.esm at position 6.812.369 at a dataSize == 0 - Record=NAVM
                {
                    if (ZLibWrapper.OutputBufferLength <= 0) //if (dataReader == null)
                    {
                        throw new TESParserException("Record.Record: ZLib inflate error. Output buffer is empty.");
                    }
                }

                while (ZLibWrapper.OutputBufferPosition < ZLibWrapper.OutputBufferLength)
                //while (dataReader.BaseStream.Position < dataReader.BaseStream.Length)
                {
                    var  type = "XXXX";
                    uint size = 0;
                    if (realSize == 0)     //compressed &
                    {
                        type = "????";     //ReadRecName(ZLibWrapper.Read4Bytes());
                        size = dataSizeParam;
                        //realSize = dataSizeParam;
                        //this.dataSize = dataSizeParam;
                    }
                    else
                    {
                        type = ReadRecName(ZLibWrapper.Read4Bytes());     //var type = ReadRecName(dataReader);

                        if (type == "XXXX")
                        {
                            ZLibWrapper.ReadUInt16();                     //dataReader.ReadUInt16();
                            size = ZLibWrapper.ReadUInt32();              //dataReader.ReadUInt32();
                            type = ReadRecName(ZLibWrapper.Read4Bytes()); //ReadRecName(dataReader);
                            ZLibWrapper.ReadUInt16();                     //dataReader.ReadUInt16();
                        }
                        else
                        {
                            size = ZLibWrapper.ReadUInt16();     //dataReader.ReadUInt16();
                        }
                    }
                    record = new SubRecord(this, type, snipStreamWrapper, size);
                    //record = new SubRecord(this, type, dataReader, size); //var record = new SubRecord(this, type, dataReader, size);
                    this.SubRecords.Add(record);
                    amountRead += (uint)record.Size2;
                }

                //} //using (var dataReader = compressed ? ZLib.Decompress(stream, (int) realSize) : new BinaryReader(stream))
                //if (dataReader != null)
                //{
                //    dataReader.Close();
                //    dataReader.Dispose();
                //    dataReader = null;
                //}

                if ((compressed & realSize != 0) | (!compressed))
                {
                    if (amountRead > realSize)
                    {
                        Debug.Print(
                            " * ERROR: SUB-RECORD {0} DATA DOESN'T MATCH THE SIZE SPECIFIED IN THE HEADER: DATA-SIZE={1} REAL-SIZE={2} AMOUNT-READ={3}",
                            name, dataSizeParam, realSize, amountRead);
                        throw new TESParserException(
                                  string.Format(
                                      "Subrecord block did not match the size specified in the record header: ExpectedSize={0} ReadSize={1} DataSize={2}",
                                      realSize, amountRead, dataSizeParam));
                    }
                }


                this.descNameOverride = this.DefaultDescriptiveName;
                this.UpdateShortDescription();

                // br.BaseStream.Position+=Size;

                //} //using (var stream = new MemoryStream(recordReader.ReadBytes((int) dataSize)))
            }
            catch (Exception ex)
            {
                string errMsg =
                    "Message: " + ex.Message +
                    Environment.NewLine +
                    Environment.NewLine +
                    "StackTrace: " + ex.StackTrace +
                    Environment.NewLine +
                    Environment.NewLine +
                    "Source: " + ex.Source +
                    Environment.NewLine +
                    Environment.NewLine +
                    "GetType: " + ex.GetType().ToString();

                System.Windows.Forms.Clipboard.SetDataObject(errMsg, true);

                // Create an EventLog instance and assign its source.
                EventLog myLog = new EventLog();
                myLog.Source = "ThreadException";
                myLog.WriteEntry(errMsg);

                MessageBox.Show(errMsg, "Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
            finally
            {
                //if (stream != null)
                //{
                //    stream.Close();
                //    stream.Dispose();
                //}
            }
        }
Esempio n. 22
0
        public NUS3(String filename, bool isZlibCompressed = false)
        {
            Stream stream;

            if (isZlibCompressed)
            {
                using (BinaryReaderX br = new BinaryReaderX(File.OpenRead(filename)))
                {
                    byte[] decomp = ZLib.Decompress(br.ReadBytes((int)br.BaseStream.Length));
                    File.OpenWrite(filename + ".decomp").Write(decomp, 0, decomp.Length);
                }

                stream = File.OpenRead(filename + ".decomp");
            }
            else
            {
                stream = File.OpenRead(filename);
            }

            using (var br = new BinaryReaderX(stream, true))
            {
                //Header
                header = br.ReadStruct <Header>();

                //Banktoc
                banktocHeader = br.ReadStruct <BankToc>();

                int offset = 0x18 + banktocHeader.entryCount * 0x8;
                banktocEntries = new List <BankTocEntry>();
                for (int i = 0; i < banktocHeader.entryCount; i++)
                {
                    banktocEntries.Add(new BankTocEntry(br.BaseStream));
                    banktocEntries[i].offset = offset;
                    offset += banktocEntries[i].secSize + 8;
                }

                //PROP
                if (br.ReadStruct <Header>().magic != "PROP")
                {
                    throw new Exception();
                }
                prop = new PROP(br.BaseStream);

                //BINF
                br.BaseStream.Position = banktocEntries[1].offset;
                if (br.ReadStruct <Header>().magic != "BINF")
                {
                    throw new Exception();
                }
                binf = new BINF(br.BaseStream);

                //GRP - not yet mapped
                br.BaseStream.Position = banktocEntries[2].offset;
                if (br.ReadStruct <Header>().magic != "GRP ")
                {
                    throw new Exception();
                }
                grp = br.ReadBytes(banktocEntries[2].secSize);

                //DTON - not yet mapped
                br.BaseStream.Position = banktocEntries[3].offset;
                if (br.ReadStruct <Header>().magic != "DTON")
                {
                    throw new Exception();
                }
                dton = br.ReadBytes(banktocEntries[3].secSize);

                //TONE
                br.BaseStream.Position = banktocEntries[4].offset;
                if (br.ReadStruct <Header>().magic != "TONE")
                {
                    throw new Exception();
                }
                tone = new TONE(br.BaseStream, banktocEntries[4].offset, banktocEntries[6].offset);

                //JUNK - not yet mapped
                br.BaseStream.Position = banktocEntries[5].offset;
                if (br.ReadStruct <Header>().magic != "JUNK")
                {
                    throw new Exception();
                }
                junk = br.ReadBytes(banktocEntries[5].secSize);

                //PACK and finishing
                br.BaseStream.Position = banktocEntries[6].offset;
                if (br.ReadStruct <Header>().magic != "PACK")
                {
                    throw new Exception();
                }
                for (int i = 0; i < tone.toneCount; i++)
                {
                    br.BaseStream.Position = tone.toneEntries[i].packOffset;

                    Files.Add(new NUS3FileInfo
                    {
                        FileName = tone.toneEntries[i].name + ".idsp",
                        Entry    = tone.toneEntries[i],
                        FileData = new SubStream(stream, tone.toneEntries[i].packOffset, tone.toneEntries[i].size)
                    });
                }
            }
        }
Esempio n. 23
0
 public byte[] Get(byte[] key)
 {
     return(ZLib.Decompress(key));
 }