private void CompressString(string str) { MemoryStream memoryStream = new MemoryStream(); CompressionMethod method = (CompressionMethod)Enum.Parse(typeof(CompressionMethod), CompressionMethods.SelectedValue.ToString(), false); CompressionSettings settins = null; switch (method) { case CompressionMethod.Stored: settins = new StoreSettings(); break; case CompressionMethod.Deflate: settins = new DeflateSettings(); break; case CompressionMethod.Lzma: settins = new LzmaSettings(); break; } CompressedStream zipOutputStream = new CompressedStream(memoryStream, StreamOperationMode.Write, settins); StreamWriter writer = new StreamWriter(zipOutputStream); writer.Write(str); writer.Flush(); CompressedText.Text = Convert.ToBase64String(memoryStream.ToArray()); }
public ImapReplayCommand(Encoding encoding, string command, byte[] response, bool compressed = false) { CommandBuffer = encoding.GetBytes(command); Compressed = compressed; Response = response; Encoding = encoding; Command = command; if (compressed) { using (var memory = new MemoryStream()) { using (var compress = new CompressedStream(memory)) { compress.Write(CommandBuffer, 0, CommandBuffer.Length); compress.Flush(); CommandBuffer = memory.ToArray(); } } } }
public static bool Compress(Stream sourceStream, Stream destinationStream) { sourceStream.Position = 0; destinationStream.Position = 0; using (CompressedStream compStream = new CompressedStream(destinationStream, CompressionMethod.Deflated, CompressionLevel.Highest)) { compStream.Transient = true; byte[] buffer = new byte[32768]; int bytesRead = 0; while ((bytesRead = sourceStream.Read(buffer, 0, buffer.Length)) > 0) { compStream.Write(buffer, 0, bytesRead); } } return(true); }
public void TestReadWrite() { using (var stream = new CompressedStream(new DummyNetworkStream())) { string command = "A00000001 APPEND INBOX (\\Seen \\Draft) {4096+}\r\nFrom: Sample Sender <*****@*****.**>\r\nTo: Sample Recipient <*****@*****.**>\r\nSubject: This is a test message...\r\nDate: Mon, 22 Oct 2018 18:22:56 EDT\r\nMessage-Id: <*****@*****.**>\r\n\r\nTesting... 1. 2. 3.\r\nTesting.\r\nOver and out.\r\n"; var output = Encoding.ASCII.GetBytes(command); const int compressedLength = 221; var buffer = new byte[1024]; int n; stream.Write(output, 0, output.Length); stream.Flush(); Assert.AreEqual(compressedLength, stream.BaseStream.Position, "Compressed output length"); stream.BaseStream.Position = 0; n = stream.Read(buffer, 0, buffer.Length); Assert.AreEqual(output.Length, n, "Decompressed input length"); var text = Encoding.ASCII.GetString(buffer, 0, n); Assert.AreEqual(command, text); } }
public void TestArgumentExceptions() { using (var stream = new CompressedStream(new DummyNetworkStream())) { var buffer = new byte[16]; Assert.Throws <ArgumentNullException> (() => stream.Read(null, 0, buffer.Length)); Assert.Throws <ArgumentOutOfRangeException> (() => stream.Read(buffer, -1, buffer.Length)); Assert.Throws <ArgumentOutOfRangeException> (() => stream.Read(buffer, 0, -1)); Assert.AreEqual(0, stream.Read(buffer, 0, 0)); Assert.Throws <ArgumentNullException> (async() => await stream.ReadAsync(null, 0, buffer.Length)); Assert.Throws <ArgumentOutOfRangeException> (async() => await stream.ReadAsync(buffer, -1, buffer.Length)); Assert.Throws <ArgumentOutOfRangeException> (async() => await stream.ReadAsync(buffer, 0, -1)); Assert.Throws <ArgumentNullException> (() => stream.Write(null, 0, buffer.Length)); Assert.Throws <ArgumentOutOfRangeException> (() => stream.Write(buffer, -1, buffer.Length)); Assert.Throws <ArgumentOutOfRangeException> (() => stream.Write(buffer, 0, -1)); stream.Write(buffer, 0, 0); Assert.Throws <ArgumentNullException> (async() => await stream.WriteAsync(null, 0, buffer.Length)); Assert.Throws <ArgumentOutOfRangeException> (async() => await stream.WriteAsync(buffer, -1, buffer.Length)); Assert.Throws <ArgumentOutOfRangeException> (async() => await stream.WriteAsync(buffer, 0, -1)); } }
private void Decrypt(object obj) { try { using (Stream sourceStream = new MemoryStream()) { sourceStream.Write(this.bytes, 0, this.bytes.Length); sourceStream.Seek(0, SeekOrigin.Begin); DefaultEncryptionSettings encryptionSettings = new DefaultEncryptionSettings(); encryptionSettings.Password = this.DecryptionPassword ?? string.Empty; using (CompressedStream compressedStream = new CompressedStream(sourceStream, StreamOperationMode.Read, new DeflateSettings(), false, encryptionSettings)) { StreamReader reader = new StreamReader(compressedStream); this.Output = reader.ReadToEnd(); } } } catch { this.Output = "Can not decompress with this password"; } }
private void WriteHeader(System.IO.Stream s, byte[] bytes) { // write the header info int i = 0; // signature bytes[i++] = (byte)(ZipEntrySignature & 0x000000FF); bytes[i++] = (byte)((ZipEntrySignature & 0x0000FF00) >> 8); bytes[i++] = (byte)((ZipEntrySignature & 0x00FF0000) >> 16); bytes[i++] = (byte)((ZipEntrySignature & 0xFF000000) >> 24); // version needed Int16 FixedVersionNeeded = 0x14; // from examining existing zip files bytes[i++] = (byte)(FixedVersionNeeded & 0x00FF); bytes[i++] = (byte)((FixedVersionNeeded & 0xFF00) >> 8); // bitfield Int16 BitField = 0x00; // from examining existing zip files bytes[i++] = (byte)(BitField & 0x00FF); bytes[i++] = (byte)((BitField & 0xFF00) >> 8); // compression method Int16 CompressionMethod = 0x08; // 0x08 = Deflate bytes[i++] = (byte)(CompressionMethod & 0x00FF); bytes[i++] = (byte)((CompressionMethod & 0xFF00) >> 8); // LastMod bytes[i++] = (byte)(_LastModDateTime & 0x000000FF); bytes[i++] = (byte)((_LastModDateTime & 0x0000FF00) >> 8); bytes[i++] = (byte)((_LastModDateTime & 0x00FF0000) >> 16); bytes[i++] = (byte)((_LastModDateTime & 0xFF000000) >> 24); // CRC32 (Int32) CRC32 crc32 = new CRC32(); UInt32 crc = 0; using (System.IO.Stream input = System.IO.File.OpenRead(FileName)) { crc = crc32.GetCrc32AndCopy(input, CompressedStream); } CompressedStream.Close(); // to get the footer bytes written to the underlying stream bytes[i++] = (byte)(crc & 0x000000FF); bytes[i++] = (byte)((crc & 0x0000FF00) >> 8); bytes[i++] = (byte)((crc & 0x00FF0000) >> 16); bytes[i++] = (byte)((crc & 0xFF000000) >> 24); // CompressedSize (Int32) Int32 isz = (Int32)_UnderlyingMemoryStream.Length; UInt32 sz = (UInt32)isz; bytes[i++] = (byte)(sz & 0x000000FF); bytes[i++] = (byte)((sz & 0x0000FF00) >> 8); bytes[i++] = (byte)((sz & 0x00FF0000) >> 16); bytes[i++] = (byte)((sz & 0xFF000000) >> 24); // UncompressedSize (Int32) if (_Debug) { System.Console.WriteLine("Uncompressed Size: {0}", crc32.TotalBytesRead); } bytes[i++] = (byte)(crc32.TotalBytesRead & 0x000000FF); bytes[i++] = (byte)((crc32.TotalBytesRead & 0x0000FF00) >> 8); bytes[i++] = (byte)((crc32.TotalBytesRead & 0x00FF0000) >> 16); bytes[i++] = (byte)((crc32.TotalBytesRead & 0xFF000000) >> 24); string internalFileName = IncludeDirectoryTree ? FileName : Path.GetFileName(FileName); // filename length (Int16) Int16 length = (Int16)internalFileName.Length; // see note below about TrimVolumeFromFullyQualifiedPaths. if ((TrimVolumeFromFullyQualifiedPaths) && (internalFileName[1] == ':') && (internalFileName[2] == '\\')) { length -= 3; } bytes[i++] = (byte)(length & 0x00FF); bytes[i++] = (byte)((length & 0xFF00) >> 8); // extra field length (short) Int16 ExtraFieldLength = 0x00; bytes[i++] = (byte)(ExtraFieldLength & 0x00FF); bytes[i++] = (byte)((ExtraFieldLength & 0xFF00) >> 8); // Tue, 27 Mar 2007 16:35 // Creating a zip that contains entries with "fully qualified" pathnames // can result in a zip archive that is unreadable by Windows Explorer. // Such archives are valid according to other tools but not to explorer. // To avoid this, we can trim off the leading volume name and slash (eg // c:\) when creating (writing) a zip file. We do this by default and we // leave the old behavior available with the // TrimVolumeFromFullyQualifiedPaths flag - set it to false to get the old // behavior. It only affects zip creation. // actual filename char[] c = ((TrimVolumeFromFullyQualifiedPaths) && (internalFileName[1] == ':') && (internalFileName[2] == '\\')) ? internalFileName.Substring(3).ToCharArray() : // trim off volume letter, colon, and slash internalFileName.ToCharArray(); int j = 0; if (_Debug) { System.Console.WriteLine("local header: writing filename, {0} chars", c.Length); System.Console.WriteLine("starting offset={0}", i); } for (j = 0; (j < c.Length) && (i + j < bytes.Length); j++) { bytes[i + j] = System.BitConverter.GetBytes(c[j])[0]; if (_Debug) { System.Console.Write(" {0:X2}", bytes[i + j]); } } if (_Debug) { System.Console.WriteLine(); } i += j; // extra field (we always write nothing in this implementation) // ;; // remember the file offset of this header _RelativeOffsetOfHeader = (int)s.Length; if (_Debug) { System.Console.WriteLine("\nAll header data:"); for (j = 0; j < i; j++) { System.Console.Write(" {0:X2}", bytes[j]); } System.Console.WriteLine(); } // finally, write the header to the stream s.Write(bytes, 0, i); // preserve this header data for use with the central directory structure. _header = new byte[i]; if (_Debug) { System.Console.WriteLine("preserving header of {0} bytes", _header.Length); } for (j = 0; j < i; j++) { _header[j] = bytes[j]; } }
private static void DecoratorSection() { var stream = new CompressedStream(new EncryptedStream(new CloudStream())); stream.Write("1234-1234-1234-1234"); }
public override void Read(CPlugEntRecordData n, GameBoxReader r, GameBoxWriter unknownW) { Version = r.ReadInt32(); UncompressedSize = r.ReadInt32(); CompressedSize = r.ReadInt32(); Data = r.ReadBytes(CompressedSize); // ... WIP ... Task.Run(() => { using (var ms = new MemoryStream(Data)) using (var cs = new CompressedStream(ms, System.IO.Compression.CompressionMode.Decompress)) using (var gbxr = new GameBoxReader(cs)) { var u01 = gbxr.ReadInt32(); var numSamples = gbxr.ReadInt32(); var objects = gbxr.ReadArray <object>(i => { var nodeId = gbxr.ReadUInt32(); Names.TryGetValue(nodeId, out string nodeName); return(new { id = nodeId, name = nodeName, rest = gbxr.ReadArray <int>(5) }); }); if (Version >= 2) { var objcts2 = gbxr.ReadArray <object>(i => { var u02 = gbxr.ReadInt32(); var u03 = gbxr.ReadInt32(); uint?clas = null; string clasName = null; if (Version >= 4) { clas = gbxr.ReadUInt32(); Names.TryGetValue(clas.Value, out clasName); } return(new object[] { u02, u03, clas, clasName }); }); } var u04 = gbxr.ReadByte(); var u05 = gbxr.ReadArray <int>(4); if (Version >= 6) { //var u06 = gbxr.ReadUInt32(); } var u07 = gbxr.ReadByte(); var u08 = gbxr.ReadByte(); if (Version >= 2) { var u09 = gbxr.ReadByte(); var u10 = gbxr.ReadArray <int>(3); var u11 = gbxr.ReadByte(); if (Version >= 3) { var u12 = gbxr.ReadByte(); if (Version == 7) { } if (Version >= 8) { var u13 = gbxr.ReadInt32(); } } } var u14 = gbxr.ReadArray <int>(5); } }); }
internal async Task ListenAsync() { await Task.Yield(); var buff = new byte[BUFFER_SIZE]; var buffseg = new ArraySegment <byte>(buff); byte[] resultbuff = null; WebSocketReceiveResult result = null; SocketCloseEventArgs close = null; var token = Token; try { while (!token.IsCancellationRequested && Socket.State == WebSocketState.Open) { using (var ms = new MemoryStream()) { do { result = await Socket.ReceiveAsync(buffseg, token).ConfigureAwait(false); if (result.MessageType == WebSocketMessageType.Close) { var cc = result.CloseStatus != null ? (int)result.CloseStatus.Value : -1; close = new SocketCloseEventArgs(null) { CloseCode = cc, CloseMessage = result.CloseStatusDescription }; } else { ms.Write(buff, 0, result.Count); } }while (!result.EndOfMessage); resultbuff = ms.ToArray(); } if (close != null) { break; } var resultstr = ""; if (result.MessageType == WebSocketMessageType.Binary) { if (resultbuff[0] == 0x78) { await CompressedStream.WriteAsync(resultbuff, 2, resultbuff.Length - 2).ConfigureAwait(false); } else { await CompressedStream.WriteAsync(resultbuff, 0, resultbuff.Length).ConfigureAwait(false); } await CompressedStream.FlushAsync().ConfigureAwait(false); CompressedStream.Position = 0; // partial credit to FiniteReality // overall idea is their // I tuned the finer details // -Emzi var sfix = BitConverter.ToUInt16(resultbuff, resultbuff.Length - 2); if (sfix != ZLIB_STREAM_SUFFIX) { using (var zlib = new DeflateStream(CompressedStream, CompressionMode.Decompress, true)) { await zlib.CopyToAsync(DecompressedStream).ConfigureAwait(false); } } else { await StreamDecompressor.CopyToAsync(DecompressedStream).ConfigureAwait(false); } resultbuff = DecompressedStream.ToArray(); DecompressedStream.Position = 0; DecompressedStream.SetLength(0); CompressedStream.Position = 0; CompressedStream.SetLength(0); } resultstr = UTF8.GetString(resultbuff, 0, resultbuff.Length); await CallOnMessageAsync(resultstr).ConfigureAwait(false); } } catch (Exception e) { close = new SocketCloseEventArgs(null) { CloseCode = -1, CloseMessage = e.Message }; } await DisconnectAsync(close).ConfigureAwait(false); }
private void WritePartition(string Name, string FilePath, Action <int, TimeSpan?> ProgressUpdateCallback, ProgressUpdater UpdaterPerSector, bool Compress = false) { Partition Target = GPT.Partitions.Find(p => string.Equals(p.Name, Name, StringComparison.CurrentCultureIgnoreCase)); if (Target == null) { throw new ArgumentOutOfRangeException(); } int FirstChunk = GetChunkIndexFromSectorIndex((int)Target.FirstSector); int LastChunk = GetChunkIndexFromSectorIndex((int)Target.LastSector); ProgressUpdater Updater = UpdaterPerSector; if ((Updater == null) && (ProgressUpdateCallback != null)) { Updater = new ProgressUpdater(Target.LastSector - Target.FirstSector + 1, ProgressUpdateCallback); } byte[] Buffer = new byte[ChunkSize]; OpenFile(); FileStream OutputFile = new(FilePath, FileMode.Create, FileAccess.Write); Stream OutStream = OutputFile; // We use gzip compression // // LZMA is about 60 times slower (compression is twice as good, but compressed size is already really small, so it doesnt matter much) // OutStream = new LZMACompressionStream(OutputFile, System.IO.Compression.CompressionMode.Compress, false); // // DeflateStream is a raw compression stream without recognizable header // Deflate has almost no performance penalty // OutStream = new DeflateStream(OutputFile, CompressionLevel.Optimal, false); // // GZip can be recognized. It always starts with 1F 8B 08 (1F 8B is the magic value, 08 is the Deflate compression method) // With GZip compression, dump time goes from 1m to 1m37s. So that doesnt matter much. if (Compress) { OutStream = new CompressedStream(OutputFile, (Target.LastSector - Target.FirstSector + 1) * 0x200); } for (int j = FirstChunk; j <= LastChunk; j++) { GetChunk(Buffer, j); int FirstSector = 0; int LastSector = (ChunkSize / 0x200) - 1; if (j == FirstChunk) { FirstSector = GetSectorNumberInChunkFromSectorIndex((int)Target.FirstSector); } if (j == LastChunk) { LastSector = GetSectorNumberInChunkFromSectorIndex((int)Target.LastSector); } int Offset = FirstSector * 0x200; int Size = (LastSector - FirstSector + 1) * 0x200; OutStream.Write(Buffer, Offset, Size); Updater?.IncreaseProgress((UInt64)(ChunkSize / 0x200)); } OutStream.Close(); CloseFile(); }
/// <summary> /// Connects to the WebSocket server. /// </summary> /// <param name="uri">The URI of the WebSocket server.</param> /// <param name="customHeaders">Custom headers to send with the request.</param> /// <returns></returns> public override Task ConnectAsync(Uri uri, IReadOnlyDictionary <string, string> customHeaders = null) { StreamDecompressor?.Dispose(); CompressedStream?.Dispose(); DecompressedStream?.Dispose(); DecompressedStream = new MemoryStream(); CompressedStream = new MemoryStream(); StreamDecompressor = new DeflateStream(CompressedStream, CompressionMode.Decompress); _socket = new ws4net.WebSocket(uri.ToString(), customHeaderItems: customHeaders?.ToList()); if (Proxy != null) // f**k this, I ain't working with that shit { throw new NotImplementedException("Proxies are not supported on non-Microsoft WebSocket client implementations."); } _socket.Opened += HandlerOpen; _socket.Closed += HandlerClose; _socket.MessageReceived += HandlerMessage; _socket.DataReceived += HandlerData; _socket.Error += _socket_Error; _socket.Open(); return(Task.FromResult <BaseWebSocketClient>(this)); void HandlerOpen(object sender, s.EventArgs e) => _connect.InvokeAsync().ConfigureAwait(false).GetAwaiter().GetResult(); void HandlerClose(object sender, s.EventArgs e) { if (e is ws4net.ClosedEventArgs ea) { _disconnect.InvokeAsync(new SocketCloseEventArgs(null) { CloseCode = ea.Code, CloseMessage = ea.Reason }).ConfigureAwait(false).GetAwaiter().GetResult(); } else { _disconnect.InvokeAsync(new SocketCloseEventArgs(null) { CloseCode = -1, CloseMessage = "unknown" }).ConfigureAwait(false).GetAwaiter().GetResult(); } } void HandlerMessage(object sender, ws4net.MessageReceivedEventArgs e) { _message.InvokeAsync(new SocketMessageEventArgs { Message = e.Message }).ConfigureAwait(false).GetAwaiter().GetResult(); } void HandlerData(object sender, ws4net.DataReceivedEventArgs e) { string msg; if (e.Data[0] == 0x78) { CompressedStream.Write(e.Data, 2, e.Data.Length - 2); } else { CompressedStream.Write(e.Data, 0, e.Data.Length); } CompressedStream.Flush(); CompressedStream.Position = 0; // partial credit to FiniteReality // overall idea is his // I tuned the finer details // -Emzi var sfix = BitConverter.ToUInt16(e.Data, e.Data.Length - 2); if (sfix != ZLIB_STREAM_SUFFIX) { using (var zlib = new DeflateStream(CompressedStream, CompressionMode.Decompress, true)) zlib.CopyTo(DecompressedStream); } else { StreamDecompressor.CopyTo(DecompressedStream); } msg = UTF8.GetString(DecompressedStream.ToArray(), 0, (int)DecompressedStream.Length); DecompressedStream.Position = 0; DecompressedStream.SetLength(0); CompressedStream.Position = 0; CompressedStream.SetLength(0); _message.InvokeAsync(new SocketMessageEventArgs { Message = msg }).ConfigureAwait(false).GetAwaiter().GetResult(); } }
internal static void LoadAssemblyFromStore(string strAssemblyName, int intAssemblyProjectID) { //_strExecutableName Licenser.LicenseKey = MyClasses.strXceedLicenseKey; try { if (File.Exists(Settings.Default.ExecutableNameNew)) { File.Delete(Settings.Default.ExecutableNameNew); } if (File.Exists(strTempFileName)) { File.Delete(strTempFileName); } byte[] readByteAssembly; using (var versionDb = new VersionDBDataContext(_strConnection)) { readByteAssembly = versionDb.AssemblyFiles.Single( one => one.AssemblyName == strAssemblyName && one.AssemblyProjectID == intAssemblyProjectID).AssemblyFiles.ToArray(); } File.WriteAllBytes((strTempFileName), readByteAssembly); var readBlob = new FileStream(strTempFileName, FileMode.Open, FileAccess.Read); var destStream = new FileStream(Settings.Default.ExecutableNameNew, FileMode.Create, FileAccess.Write); var compStream = new CompressedStream(readBlob); MyClasses.StreamCopy(compStream, destStream); destStream.Close(); if (File.Exists(strTempFileName)) { File.Delete(strTempFileName); } } catch (Exception ex) { string err = ex.Message; } }
internal static void LoadBatchHandler(string strBatchHandlerName) { Licenser.LicenseKey = MyClasses.strXceedLicenseKey; try { var versionDb = new VersionDBDataContext(_strConnection); string strAssemblyNames = string.Empty; if (File.Exists(strBatchHandlerName)) { File.Delete(strBatchHandlerName); } if (File.Exists(strTempFileName)) { File.Delete(strTempFileName); } foreach (var oneAssembly in (versionDb.AssemblyFiles.Where(oneAssembly => (oneAssembly.AssemblyProjectID == MyClasses._intProjectId))).ToList()) { if (oneAssembly.AssemblyName.Equals(strBatchHandlerName)) { byte[] readByteAssembly; readByteAssembly = versionDb.AssemblyFiles.Single( one => one.AssemblyName == strBatchHandlerName && one.AssemblyProjectID == MyClasses._intProjectId).AssemblyFiles.ToArray(); File.WriteAllBytes((strTempFileName), readByteAssembly); var readBlob = new FileStream(strTempFileName, FileMode.Open, FileAccess.Read); var destStream = new FileStream(strBatchHandlerName, FileMode.Create, FileAccess.Write); var compStream = new CompressedStream(readBlob); MyClasses.StreamCopy(compStream, destStream); destStream.Close(); } } if (File.Exists(strTempFileName)) { File.Delete(strTempFileName); } versionDb.Dispose(); } catch (Exception ex) { string err = ex.Message; } return; }
protected void CompressSourceToCompressionStream(IO.EndianWriter blockStream, Stream sourceFile) { // Build a CompressedStream from the source file and write it to the block stream CompressedStream.CompressFromStream(blockStream, sourceFile, out Adler32, out DataSize); // Update this ECF's checksum and size }
byte[] DecompressFromStream(IO.EndianStream blockStream) { SeekTo(blockStream); return(CompressedStream.DecompressFromStream(blockStream)); }
public override void Read(CPlugEntRecordData n, GameBoxReader r) { Version = r.ReadInt32(); // 10 UncompressedSize = r.ReadInt32(); CompressedSize = r.ReadInt32(); data = r.ReadBytes(CompressedSize); n.samples = Task.Run(() => { var samples = new ObservableCollection <Sample>(); using var ms = new MemoryStream(data); using var cs = new CompressedStream(ms, CompressionMode.Decompress); using var r = new GameBoxReader(cs); var u01 = r.ReadInt32(); var ghostLength = r.ReadInt32(); // milliseconds var objects = r.ReadArray <object>(r => { var nodeId = r.ReadUInt32(); NodeCacheManager.Names.TryGetValue(nodeId, out string?nodeName); return(new { nodeId, nodeName, obj_u01 = r.ReadInt32(), obj_u02 = r.ReadInt32(), obj_u03 = r.ReadInt32(), mwbuffer = r.ReadInt32(), obj_u05 = r.ReadInt32() }); }); if (Version >= 2) { var objcts2 = r.ReadArray <object>(r => { var u02 = r.ReadInt32(); var u03 = r.ReadInt32(); uint?clas = null; string?clasName = null; if (Version >= 4) { clas = r.ReadUInt32(); NodeCacheManager.Names.TryGetValue(clas.Value, out clasName); } return(new { u02, u03, clas, clasName }); }); } var u04 = r.ReadByte(); while (u04 != 0) { var bufferType = r.ReadInt32(); var u06 = r.ReadInt32(); var u07 = r.ReadInt32(); var ghostLengthFinish = r.ReadInt32(); // ms if (Version < 6) { // temp_79f24995b2b->field_0x28 = temp_79f24995b2b->field_0xc } else { var u08 = r.ReadInt32(); } // Reads byte on every loop until the byte is 0, should be 1 otherwise for (byte x; (x = r.ReadByte()) != 0;) { var timestamp = r.ReadInt32(); var buffer = r.ReadBytes(); // MwBuffer if (buffer.Length > 0) { using var bufferMs = new MemoryStream(buffer); using var bufferR = new GameBoxReader(bufferMs); var sampleProgress = (int)bufferMs.Position; var sample = new Sample(buffer) { BufferType = (byte)bufferType }; switch (bufferType) { case 0: break; case 2: { bufferMs.Position = 5; var(position, rotation, speed, velocity) = bufferR.ReadTransform(); // Only position matches sample.Timestamp = TimeSpan.FromMilliseconds(timestamp); sample.Position = position; sample.Rotation = rotation; sample.Speed = speed * 3.6f; sample.Velocity = velocity; break; } case 4: { bufferMs.Position = 5; var rpmByte = bufferR.ReadByte(); bufferMs.Position = 14; var steerByte = bufferR.ReadByte(); var steer = ((steerByte / 255f) - 0.5f) * 2; bufferMs.Position = 91; var gearByte = bufferR.ReadByte(); var gear = gearByte / 5f; sample.Gear = gear; sample.RPM = rpmByte; sample.Steer = steer; bufferMs.Position = 15; var u15 = bufferR.ReadByte(); bufferMs.Position = 18; var brakeByte = bufferR.ReadByte(); var brake = brakeByte / 255f; var gas = u15 / 255f + brake; sample.Brake = brake; sample.Gas = gas; bufferMs.Position = 47; var(position, rotation, speed, velocity) = bufferR.ReadTransform(); sample.Timestamp = TimeSpan.FromMilliseconds(timestamp); sample.Position = position; sample.Rotation = rotation; sample.Speed = speed * 3.6f; sample.Velocity = velocity; break; } case 10: break; default: break; } samples.Add(sample); } } u04 = r.ReadByte(); if (Version >= 2) { while (r.ReadByte() != 0) { var type = r.ReadInt32(); var timestamp = r.ReadInt32(); var buffer = r.ReadBytes(); // MwBuffer } } } if (Version >= 3) { while (r.ReadByte() != 0) { var u19 = r.ReadInt32(); var u20 = r.ReadInt32(); var u21 = r.ReadBytes(); // MwBuffer } if (Version == 7) { while (r.ReadByte() != 0) { var u23 = r.ReadInt32(); var u24 = r.ReadBytes(); // MwBuffer } } if (Version >= 8) { var u23 = r.ReadInt32(); if (u23 != 0) { if (Version == 8) { while (r.ReadByte() != 0) { var u25 = r.ReadInt32(); var u26 = r.ReadBytes(); // MwBuffer } } else { while (r.ReadByte() != 0) { var u28 = r.ReadInt32(); var u29 = r.ReadBytes(); // MwBuffer var u30 = r.ReadBytes(); // MwBuffer } if (Version >= 10) { var period = r.ReadInt32(); } } } } } return(samples); }); }
public override void Read(CPlugEntRecordData n, GameBoxReader r) { Version = r.ReadInt32(); UncompressedSize = r.ReadInt32(); CompressedSize = r.ReadInt32(); Data = r.ReadBytes(CompressedSize); n.Samples = Task.Run(() => { var samples = new ObservableCollection <Sample>(); using (var ms = new MemoryStream(Data)) using (var cs = new CompressedStream(ms, CompressionMode.Decompress)) using (var gbxr = new GameBoxReader(cs)) { var u01 = gbxr.ReadInt32(); var ghostLength = gbxr.ReadInt32(); // milliseconds var objects = gbxr.ReadArray <object>(r1 => { var nodeId = r1.ReadUInt32(); NodeCacheManager.Names.TryGetValue(nodeId, out string nodeName); return(new { nodeId, nodeName, obj_u01 = r1.ReadInt32(), obj_u02 = r1.ReadInt32(), obj_u03 = r1.ReadInt32(), mwbuffer = r1.ReadInt32(), obj_u05 = r1.ReadInt32() }); }); if (Version >= 2) { var objcts2 = gbxr.ReadArray <object>(r1 => { var u02 = r1.ReadInt32(); var u03 = r1.ReadInt32(); uint?clas = null; string clasName = null; if (Version >= 4) { clas = r1.ReadUInt32(); NodeCacheManager.Names.TryGetValue(clas.Value, out clasName); } return(new { u02, u03, clas, clasName }); }); } var u04 = gbxr.ReadByte(); while (u04 != 0) { var bufferType = gbxr.ReadInt32(); var u06 = gbxr.ReadInt32(); var u07 = gbxr.ReadInt32(); var ghostLengthFinish = gbxr.ReadInt32(); // ms if (Version < 6) { // temp_79f24995b2b->field_0x28 = temp_79f24995b2b->field_0xc } else { var u08 = gbxr.ReadInt32(); } // Reads byte on every loop until the byte is 0, should be 1 otherwise for (byte x; (x = gbxr.ReadByte()) != 0;) { var timestamp = gbxr.ReadInt32(); var buffer = gbxr.ReadBytes(); // MwBuffer if (buffer.Length > 0) { var unknownData = new byte[buffer.Length]; using (var bufMs = new MemoryStream(buffer)) using (var bufR = new GameBoxReader(bufMs)) { var sampleProgress = (int)bufMs.Position; Sample sample = new Sample() { BufferType = (byte)bufferType }; switch (bufferType) { case 0: break; case 2: var buf2unknownData = bufR.ReadBytes(5); Buffer.BlockCopy(buf2unknownData, 0, unknownData, 0, buf2unknownData.Length); var(position, rotation, speed, velocity) = bufR.ReadTransform(); // Only position matches sample.Timestamp = TimeSpan.FromMilliseconds(timestamp); sample.Position = position; sample.Rotation = rotation; sample.Speed = speed * 3.6f; sample.Velocity = velocity; break; case 4: var buf4unknownData = bufR.ReadBytes(47); Buffer.BlockCopy(buf4unknownData, 0, unknownData, 0, buf4unknownData.Length); var buf4transform = bufR.ReadTransform(); var buf4unknownData2 = bufR.ReadBytes(4); sample.Timestamp = TimeSpan.FromMilliseconds(timestamp); sample.Position = buf4transform.position; sample.Rotation = buf4transform.rotation; sample.Speed = buf4transform.speed * 3.6f; sample.Velocity = buf4transform.velocity; sample.Unknown = buf4unknownData; break; case 10: break; default: break; } sampleProgress = (int)(bufMs.Position - sampleProgress); var moreUnknownData = bufR.ReadBytes((int)bufMs.Length - sampleProgress); Buffer.BlockCopy(moreUnknownData, 0, unknownData, sampleProgress, moreUnknownData.Length); sample.Unknown = unknownData; samples.Add(sample); } } } u04 = gbxr.ReadByte(); if (Version >= 2) { for (byte x; (x = gbxr.ReadByte()) != 0;) { var type = gbxr.ReadInt32(); var timestamp = gbxr.ReadInt32(); var buffer = gbxr.ReadBytes(); // MwBuffer } } } if (Version >= 3) { for (byte x; (x = gbxr.ReadByte()) != 0;) { var u19 = gbxr.ReadInt32(); var u20 = gbxr.ReadInt32(); var u21 = gbxr.ReadBytes(); // MwBuffer } if (Version == 7) { for (byte x; (x = gbxr.ReadByte()) != 0;) { var u23 = gbxr.ReadInt32(); var u24 = gbxr.ReadBytes(); // MwBuffer } } if (Version >= 8) { var u23 = gbxr.ReadInt32(); if (u23 != 0) { if (Version == 8) { for (byte x; (x = gbxr.ReadByte()) != 0;) { var u25 = gbxr.ReadInt32(); var u26 = gbxr.ReadBytes(); // MwBuffer } } else { for (byte x; (x = gbxr.ReadByte()) != 0;) { var u28 = gbxr.ReadInt32(); var u29 = gbxr.ReadBytes(); // MwBuffer var u30 = gbxr.ReadBytes(); // MwBuffer } if (Version >= 10) { var period = gbxr.ReadInt32(); } } } } } } return(samples); }); }
private void WriteHeader(System.IO.Stream s, byte[] bytes) { // write the header info int i = 0; // signature bytes[i++] = (byte)(ZipEntrySignature & 0x000000FF); bytes[i++] = (byte)((ZipEntrySignature & 0x0000FF00) >> 8); bytes[i++] = (byte)((ZipEntrySignature & 0x00FF0000) >> 16); bytes[i++] = (byte)((ZipEntrySignature & 0xFF000000) >> 24); // version needed Int16 FixedVersionNeeded = 0x14; // from examining existing zip files bytes[i++] = (byte)(FixedVersionNeeded & 0x00FF); bytes[i++] = (byte)((FixedVersionNeeded & 0xFF00) >> 8); // bitfield Int16 BitField = 0x00; // from examining existing zip files bytes[i++] = (byte)(BitField & 0x00FF); bytes[i++] = (byte)((BitField & 0xFF00) >> 8); // compression method Int16 CompressionMethod = 0x08; // 0x08 = Deflate bytes[i++] = (byte)(CompressionMethod & 0x00FF); bytes[i++] = (byte)((CompressionMethod & 0xFF00) >> 8); // LastMod bytes[i++] = (byte)(_LastModDateTime & 0x000000FF); bytes[i++] = (byte)((_LastModDateTime & 0x0000FF00) >> 8); bytes[i++] = (byte)((_LastModDateTime & 0x00FF0000) >> 16); bytes[i++] = (byte)((_LastModDateTime & 0xFF000000) >> 24); // CRC32 (Int32) CRC32 crc32 = new CRC32(); UInt32 crc = 0; using (System.IO.Stream input = System.IO.File.OpenRead(FileName)) { crc = crc32.GetCrc32AndCopy(input, CompressedStream); } CompressedStream.Close(); // to get the footer bytes written to the underlying stream bytes[i++] = (byte)(crc & 0x000000FF); bytes[i++] = (byte)((crc & 0x0000FF00) >> 8); bytes[i++] = (byte)((crc & 0x00FF0000) >> 16); bytes[i++] = (byte)((crc & 0xFF000000) >> 24); // CompressedSize (Int32) Int32 isz = (Int32)_UnderlyingMemoryStream.Length; UInt32 sz = (UInt32)isz; bytes[i++] = (byte)(sz & 0x000000FF); bytes[i++] = (byte)((sz & 0x0000FF00) >> 8); bytes[i++] = (byte)((sz & 0x00FF0000) >> 16); bytes[i++] = (byte)((sz & 0xFF000000) >> 24); // UncompressedSize (Int32) bytes[i++] = (byte)(crc32.TotalBytesRead & 0x000000FF); bytes[i++] = (byte)((crc32.TotalBytesRead & 0x0000FF00) >> 8); bytes[i++] = (byte)((crc32.TotalBytesRead & 0x00FF0000) >> 16); bytes[i++] = (byte)((crc32.TotalBytesRead & 0xFF000000) >> 24); // filename length (Int16) Int16 length = (Int16)FileName.Length; bytes[i++] = (byte)(length & 0x00FF); bytes[i++] = (byte)((length & 0xFF00) >> 8); // extra field length (short) Int16 ExtraFieldLength = 0x00; bytes[i++] = (byte)(ExtraFieldLength & 0x00FF); bytes[i++] = (byte)((ExtraFieldLength & 0xFF00) >> 8); // actual filename char[] c = FileName.ToCharArray(); int j = 0; for (j = 0; (j < c.Length) && (i + j < bytes.Length); j++) { bytes[i + j] = System.BitConverter.GetBytes(c[j])[0]; } i += j; // extra field (we always write null in this implementation) // ;; // remember the file offset of this header _RelativeOffsetOfHeader = (int)s.Length; // finally, write the header to the stream s.Write(bytes, 0, i); // preserve this header data for use with the central directory structure. _header = new byte[i]; for (j = 0; j < i; j++) { _header[j] = bytes[j]; } }
public void Close() { CompressedStream.Close(); }
private static byte[] CompressDataWithDeflate(byte[] data) { using (MemoryStream stream = new MemoryStream()) { CompressedStream compressedStream = new CompressedStream(stream, StreamOperationMode.Write, new DeflateSettings()); compressedStream.Write(data, 0, data.Length); compressedStream.Flush(); return stream.ToArray(); } }
private void WriteHeader(System.IO.Stream s, byte[] bytes) { // write the header info int i = 0; // signature bytes[i++] = (byte)(ZipConstants.ZipEntrySignature & 0x000000FF); bytes[i++] = (byte)((ZipConstants.ZipEntrySignature & 0x0000FF00) >> 8); bytes[i++] = (byte)((ZipConstants.ZipEntrySignature & 0x00FF0000) >> 16); bytes[i++] = (byte)((ZipConstants.ZipEntrySignature & 0xFF000000) >> 24); // version needed Int16 FixedVersionNeeded = 0x14; // from examining existing zip files bytes[i++] = (byte)(FixedVersionNeeded & 0x00FF); bytes[i++] = (byte)((FixedVersionNeeded & 0xFF00) >> 8); // bitfield Int16 BitField = 0x00; // from examining existing zip files bytes[i++] = (byte)(BitField & 0x00FF); bytes[i++] = (byte)((BitField & 0xFF00) >> 8); Int16 CompressionMethod = 0x00; // 0x08 = Deflate, 0x00 == No Compression // compression for directories = 0x00 (No Compression) if (!IsDirectory) { CompressionMethod = 0x08; // CRC32 (Int32) if (_FileData != null) { // If we have FileData, that means we've read this entry from an // existing zip archive. We must just copy the existing file data, // CRC, compressed size, and uncompressed size // over to the new (updated) archive. } else { // special case zero-length files System.IO.FileInfo fi = new System.IO.FileInfo(LocalFileName); if (fi.Length == 0) { CompressionMethod = 0x00; _UncompressedSize = 0; _CompressedSize = 0; _Crc32 = 0; } else { // Read in the data from the file in the filesystem, comress it, and // calculate a CRC on it as we read. CRC32 crc32 = new CRC32(); using (System.IO.Stream input = System.IO.File.OpenRead(LocalFileName)) { UInt32 crc = crc32.GetCrc32AndCopy(input, CompressedStream); _Crc32 = (Int32)crc; } CompressedStream.Close(); // to get the footer bytes written to the underlying stream _UncompressedSize = crc32.TotalBytesRead; _CompressedSize = (Int32)_UnderlyingMemoryStream.Length; // It is possible that applying this stream compression on a previously compressed // file will actually increase the size of the data. In that case, we back-off // and just store the uncompressed (really, already compressed) data. // We need to recompute the CRC, and point to the right data. if (_CompressedSize > _UncompressedSize) { using (System.IO.Stream input = System.IO.File.OpenRead(LocalFileName)) { _UnderlyingMemoryStream = new System.IO.MemoryStream(); UInt32 crc = crc32.GetCrc32AndCopy(input, _UnderlyingMemoryStream); _Crc32 = (Int32)crc; } _UncompressedSize = crc32.TotalBytesRead; _CompressedSize = (Int32)_UnderlyingMemoryStream.Length; if (_CompressedSize != _UncompressedSize) { throw new Exception("No compression but unequal stream lengths!"); } CompressionMethod = 0x00; } } } } // compression method bytes[i++] = (byte)(CompressionMethod & 0x00FF); bytes[i++] = (byte)((CompressionMethod & 0xFF00) >> 8); // LastMod bytes[i++] = (byte)(_LastModDateTime & 0x000000FF); bytes[i++] = (byte)((_LastModDateTime & 0x0000FF00) >> 8); bytes[i++] = (byte)((_LastModDateTime & 0x00FF0000) >> 16); bytes[i++] = (byte)((_LastModDateTime & 0xFF000000) >> 24); // calculated above bytes[i++] = (byte)(_Crc32 & 0x000000FF); bytes[i++] = (byte)((_Crc32 & 0x0000FF00) >> 8); bytes[i++] = (byte)((_Crc32 & 0x00FF0000) >> 16); bytes[i++] = (byte)((_Crc32 & 0xFF000000) >> 24); // CompressedSize (Int32) bytes[i++] = (byte)(_CompressedSize & 0x000000FF); bytes[i++] = (byte)((_CompressedSize & 0x0000FF00) >> 8); bytes[i++] = (byte)((_CompressedSize & 0x00FF0000) >> 16); bytes[i++] = (byte)((_CompressedSize & 0xFF000000) >> 24); // UncompressedSize (Int32) if (_Debug) { System.Console.WriteLine("Uncompressed Size: {0}", _UncompressedSize); } bytes[i++] = (byte)(_UncompressedSize & 0x000000FF); bytes[i++] = (byte)((_UncompressedSize & 0x0000FF00) >> 8); bytes[i++] = (byte)((_UncompressedSize & 0x00FF0000) >> 16); bytes[i++] = (byte)((_UncompressedSize & 0xFF000000) >> 24); // filename length (Int16) Int16 filenameLength = (Int16)FileName.Length; // see note below about TrimVolumeFromFullyQualifiedPaths. if ((TrimVolumeFromFullyQualifiedPaths) && (FileName[1] == ':') && (FileName[2] == '\\')) { filenameLength -= 3; } // apply upper bound to the length if (filenameLength + i > bytes.Length) { filenameLength = (Int16)(bytes.Length - (Int16)i); } bytes[i++] = (byte)(filenameLength & 0x00FF); bytes[i++] = (byte)((filenameLength & 0xFF00) >> 8); // extra field length (short) Int16 ExtraFieldLength = 0x00; bytes[i++] = (byte)(ExtraFieldLength & 0x00FF); bytes[i++] = (byte)((ExtraFieldLength & 0xFF00) >> 8); // Tue, 27 Mar 2007 16:35 // Creating a zip that contains entries with "fully qualified" pathnames // can result in a zip archive that is unreadable by Windows Explorer. // Such archives are valid according to other tools but not to explorer. // To avoid this, we can trim off the leading volume name and slash (eg // c:\) when creating (writing) a zip file. We do this by default and we // leave the old behavior available with the // TrimVolumeFromFullyQualifiedPaths flag - set it to false to get the old // behavior. It only affects zip creation. // actual filename char[] c = ((TrimVolumeFromFullyQualifiedPaths) && (FileName[1] == ':') && (FileName[2] == '\\')) ? FileName.Substring(3).ToCharArray() : // trim off volume letter, colon, and slash FileName.ToCharArray(); int j = 0; if (_Debug) { System.Console.WriteLine("local header: writing filename, {0} chars", c.Length); System.Console.WriteLine("starting offset={0}", i); } for (j = 0; (j < c.Length) && (i + j < bytes.Length); j++) { bytes[i + j] = System.BitConverter.GetBytes(c[j])[0]; if (_Debug) { System.Console.Write(" {0:X2}", bytes[i + j]); } } if (_Debug) { System.Console.WriteLine(); } i += j; // extra field (we always write nothing in this implementation) // ;; // remember the file offset of this header _RelativeOffsetOfHeader = (int)s.Length; if (_Debug) { System.Console.WriteLine("\nAll header data:"); for (j = 0; j < i; j++) { System.Console.Write(" {0:X2}", bytes[j]); } System.Console.WriteLine(); } // finally, write the header to the stream s.Write(bytes, 0, i); // preserve this header data for use with the central directory structure. _header = new byte[i]; if (_Debug) { System.Console.WriteLine("preserving header of {0} bytes", _header.Length); } for (j = 0; j < i; j++) { _header[j] = bytes[j]; } }
public void Dispose() { CompressedEmptyStream?.Dispose(); CompressedStream?.Dispose(); CompressedIndexedStream?.Dispose(); }