示例#1
0
 protected static void CloseDecompressor()
 {
     compReader.Close();
     compReader = null;
     inf = null;
     input = null;
     output = null;
 }
示例#2
0
文件: BSAArchive.cs 项目: vjmira/fomm
            public MemoryStream Data()
            {
                br.BaseStream.Seek(offset, SeekOrigin.Begin);
                if (compressed)
                {
                    byte[] b      = new byte[size - 4];
                    byte[] output = new byte[br.ReadUInt32()];
                    br.Read(b, 0, size - 4);

                    ICSharpCode.SharpZipLib.Zip.Compression.Inflater inf = new ICSharpCode.SharpZipLib.Zip.Compression.Inflater();
                    inf.SetInput(b, 0, b.Length);
                    inf.Inflate(output);

                    return(new MemoryStream(output));
                }
                else
                {
                    return(new MemoryStream(br.ReadBytes(size)));
                }
            }
示例#3
0
        //解压
        public byte[] Decompress(byte[] bytes)
        {
            MemoryStream memory = new MemoryStream();

            ICSharpCode.SharpZipLib.Zip.Compression.Inflater inf = new ICSharpCode.SharpZipLib.Zip.Compression.Inflater();
            inf.SetInput(bytes);
            while (!inf.IsFinished)
            {
                int extracted = inf.Inflate(temp);
                if (extracted > 0)
                {
                    memory.Write(temp, 0, extracted);
                }
                else
                {
                    break;
                }
            }
            return(memory.ToArray());
        }
			internal byte[] GetRawData()
			{
				bsa.br.BaseStream.Seek(offset, SeekOrigin.Begin);
				if (bsa.SkipNames) bsa.br.BaseStream.Position += bsa.br.ReadByte() + 1;
				if (compressed)
				{
					byte[] b = new byte[size - 4];
					byte[] output = new byte[bsa.br.ReadUInt32()];
					bsa.br.Read(b, 0, size - 4);

					ICSharpCode.SharpZipLib.Zip.Compression.Inflater inf = new ICSharpCode.SharpZipLib.Zip.Compression.Inflater();
					inf.SetInput(b, 0, b.Length);
					inf.Inflate(output);

					return output;
				}
				else
				{
					return bsa.br.ReadBytes(size);
				}
			}
示例#5
0
        /// <summary>
        /// Inflater解压缩
        /// </summary>
        /// <param name="inputByte"></param>
        /// <returns></returns>
        public static byte[] inflater(byte[] inputByte)
        {
            byte[]       temp   = new byte[1024];
            MemoryStream memory = new MemoryStream();

            ICSharpCode.SharpZipLib.Zip.Compression.Inflater inf = new ICSharpCode.SharpZipLib.Zip.Compression.Inflater();
            inf.SetInput(inputByte);
            while (!inf.IsFinished)
            {
                int extracted = inf.Inflate(temp);
                if (extracted > 0)
                {
                    memory.Write(temp, 0, extracted);
                }
                else
                {
                    break;
                }
            }
            return(memory.ToArray());
        }
示例#6
0
        public static void DecompressData(byte[] inData, out byte[] outData, int tgt_size)
        {
            ICSharpCode.SharpZipLib.Zip.Compression.Inflater infl =
                new ICSharpCode.SharpZipLib.Zip.Compression.Inflater(false);
            var inStream = new InflaterInputStream(new MemoryStream(inData), infl);

            outData = new byte[tgt_size];
            try
            {
                int numRead = inStream.Read(outData, 0, tgt_size);
                if (numRead != tgt_size)
                {
                    throw  new Exception();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Unexpected exception - '{0}'", ex.Message);
                throw;
            }
        }
示例#7
0
        private void _acceptor_OnClientConnected(object sender, ClientConnectedEventArgs args)
        {
            try
            {
                logger.Info("Recebeu conexao. Conectando initiator em [" + conflatedServer + ":" + conflatedPort + "]");

                compressedStream = new MemoryStream();
                //zlib = new Ionic.Zlib.ZlibStream(compressedStream, Ionic.Zlib.CompressionMode.Decompress, true);
                //zlib.BufferSize = BUFFER_SIZE;
                zlib = new ICSharpCode.SharpZipLib.Zip.Compression.Inflater();
                //zlib.FlushMode = Ionic.Zlib.FlushType.Full;

                _initiator.Port   = conflatedPort.ToString();
                _initiator.IpAddr = conflatedServer;
                _initiator.OpenConnection();
            }
            catch (Exception ex)
            {
                logger.Error("_acceptor_OnClientConnected: " + ex.Message, ex);
            }
        }
示例#8
0
        /// <summary>
        /// Treats the data extracted from the myp archive
        /// Uncompress the data if said data was compressed
        /// </summary>
        /// <param name="archFile"></param>
        private void TreatExtractedFile(FileInArchive archFile)
        {
            MemoryStream inputMS  = new MemoryStream(archFile.data, 0, archFile.data.Length);
            MemoryStream outputMS = new MemoryStream();

            byte[] output_buffer = new byte[archFile.descriptor.uncompressedSize];

            try
            {
                if (archFile.descriptor.compressionMethod == 1) //ZLib compression
                {
                    try
                    {
                        ICSharpCode.SharpZipLib.Zip.Compression.Inflater inf = new ICSharpCode.SharpZipLib.Zip.Compression.Inflater();
                        inf.SetInput(archFile.data);
                        inf.Inflate(output_buffer);

                        SaveBufferToFile(output_buffer, archFile.descriptor.foundFileName, archFile.descriptor.filename, archFile.descriptor.extension);
                        TriggerExtractionEvent(new MYPFileEventArgs(Event_ExtractionType.FileExtracted, numExtractedFiles++));
                    }
                    catch
                    {
                        TriggerExtractionEvent(new MYPFileEventArgs(Event_ExtractionType.FileExtractionError, error_ExtractionNumber++));
                    }
                }
                else if (archFile.descriptor.compressionMethod == 0) //No compression
                {
                    SaveBufferToFile(archFile.data, archFile.descriptor.foundFileName, archFile.descriptor.filename, archFile.descriptor.extension);
                    TriggerExtractionEvent(new MYPFileEventArgs(Event_ExtractionType.FileExtracted, numExtractedFiles++));
                }
                else
                {
                    TriggerExtractionEvent(new MYPFileEventArgs(Event_ExtractionType.UnknownCompressionMethod, error_ExtractionNumber++));
                }
            }
            catch
            {
                TriggerExtractionEvent(new MYPFileEventArgs(Event_ExtractionType.UnknownError, error_ExtractionNumber++));
            }
        }
示例#9
0
        private static ByteVector Inflate(ByteVector data)
        {
#if HAVE_SHARPZIPLIB
            using (System.IO.MemoryStream out_stream = new System.IO.MemoryStream()) {
                ICSharpCode.SharpZipLib.Zip.Compression.Inflater inflater =
                    new ICSharpCode.SharpZipLib.Zip.Compression.Inflater();

                inflater.SetInput(data.Data);

                byte [] buffer = new byte [1024];
                int     written_bytes;

                while ((written_bytes = inflater.Inflate(buffer)) > 0)
                {
                    out_stream.Write(buffer, 0, written_bytes);
                }

                return(new ByteVector(out_stream.ToArray()));
            }
#else
            return(null);
#endif
        }
示例#10
0
        /// <summary>
        /// 字节数组解压缩
        /// 返回:已解压缩的字节数组
        /// </summary>
        /// <param name="data">待解压缩的字节数组</param>
        /// <returns></returns>
        public static byte[] DecompressBytes(byte[] data)
        {
            var f = new ICSharpCode.SharpZipLib.Zip.Compression.Inflater();

            f.SetInput(data);

            var o = new MemoryStream(data.Length);

            try
            {
                var buf = new byte[1024];
                while (!f.IsFinished)
                {
                    var got = f.Inflate(buf);
                    o.Write(buf, 0, got);
                }
            }
            finally
            {
                o.Close();
            }

            return(o.ToArray());
        }
        public byte[] ReadFile(Stream outstream, FileInArchive file)
        {
            if (file.Descriptor.CompressionMethod == 1) //ZLib compression
            {
                outstream.Position = file.Descriptor.StartingPosition + file.Descriptor.FileHeaderSize;
                byte[] compressedData = new byte[file.Descriptor.CompressedSize];
                outstream.Read(compressedData, 0, (int)file.Descriptor.CompressedSize);

                byte[] output_buffer = new byte[file.Descriptor.UncompressedSize];

                ICSharpCode.SharpZipLib.Zip.Compression.Inflater inf = new ICSharpCode.SharpZipLib.Zip.Compression.Inflater();
                inf.SetInput(compressedData);
                inf.Inflate(output_buffer);
                return(output_buffer);
            }
            else
            {
                outstream.Position = file.Descriptor.StartingPosition + file.Descriptor.FileHeaderSize;
                byte[] compressedData = new byte[file.Descriptor.CompressedSize];
                outstream.Read(compressedData, 0, (int)file.Descriptor.CompressedSize);

                return(compressedData);
            }
        }
示例#12
0
            internal byte[] GetRawData()
            {
                bsa.br.BaseStream.Seek(offset, SeekOrigin.Begin);
                if (bsa.SkipNames)
                {
                    bsa.br.BaseStream.Position += bsa.br.ReadByte() + 1;
                }
                if (compressed)
                {
                    byte[] b      = new byte[size - 4];
                    byte[] output = new byte[bsa.br.ReadUInt32()];
                    bsa.br.Read(b, 0, size - 4);

                    ICSharpCode.SharpZipLib.Zip.Compression.Inflater inf = new ICSharpCode.SharpZipLib.Zip.Compression.Inflater();
                    inf.SetInput(b, 0, b.Length);
                    inf.Inflate(output);

                    return(output);
                }
                else
                {
                    return(bsa.br.ReadBytes(size));
                }
            }
示例#13
0
        public void ExtractFiles(object oinfo)
        {
            long succeeded, failed, current;
            ExtractThreadInfo info = (ExtractThreadInfo)oinfo;

            FileStream inputfs = new FileStream(info.Path, FileMode.Open, FileAccess.Read, FileShare.Read);
            Stream     input   = inputfs as Stream;

            succeeded = failed = current = 0;

            this.Log(String.Format("{0} files in package.", info.Package.Entries.Count));

            foreach (PackageEntry entry in info.Package.Entries)
            {
                this.SetProgress(++current);

                input.Seek(entry.Offset, SeekOrigin.Begin);

                string outputName = entry.Name + "." + entry.Extension;
                this.Log(outputName);

                FileStream outputfs = new FileStream(Path.Combine(info.Save, outputName), FileMode.Create, FileAccess.Write, FileShare.None);
                Stream     output   = outputfs as Stream;

                if (entry.CompressedSize == -1)
                {
                    long   left = entry.UncompressedSize;
                    byte[] data = new byte[4096];
                    while (left > 0)
                    {
                        int block = (int)(Math.Min(left, 4096));
                        input.Read(data, 0, block);
                        output.Write(data, 0, block);
                        left -= block;
                    }
                }
                else
                {
                    ICSharpCode.SharpZipLib.Zip.Compression.Inflater inflater =
                        new ICSharpCode.SharpZipLib.Zip.Compression.Inflater();

                    // compressed using zlib
                    long   left           = entry.CompressedSize;
                    byte[] compressedData = new byte[4096];
                    byte[] data           = new byte[4096];

                    while (inflater.TotalOut < entry.UncompressedSize)
                    {
                        if (inflater.IsNeedingInput == true)
                        {
                            if (left == 0)
                            {
                                throw new Exception();
                            }

                            int block = (int)(Math.Min(left, 4096));
                            input.Read(compressedData, 0, block);
                            inflater.SetInput(compressedData, 0, block);
                            left -= block;
                        }

                        int inflated = inflater.Inflate(data);
                        output.Write(data, 0, inflated);
                    }
                }

                output.Close();
                succeeded++;
            }

            input.Close();

            this.Log(String.Format("Done, {0} succeeded, {1} failed, {2} total.", succeeded, failed, info.Package.Entries.Count));
            this.EnableButtons(true);
        }
示例#14
0
		/// <summary>Release the current window cursor.</summary>
		/// <remarks>Release the current window cursor.</remarks>
		public override void Release()
		{
			window = null;
			try
			{
				InflaterCache.Release(inf);
			}
			finally
			{
				inf = null;
			}
		}
示例#15
0
		private void PrepareInflater()
		{
			if (inf == null)
			{
				inf = InflaterCache.Get();
			}
			else
			{
				inf.Reset();
			}
		}
示例#16
0
        public void Send(OP code, byte[] data)
        {
            if (sock == null)
            {
                return;
            }

            #region debug
#if DEBUG
            //    StreamWriter w=new StreamWriter("d:\\msend.txt", true);
            StreamWriter  w   = new StreamWriter("c:\\msend.txt", true);
            StringBuilder str = new StringBuilder();

            byte[] cdata = data;
            if (code == OP.SMSG_COMPRESSED_UPDATE_OBJECT)
            {
                ICSharpCode.SharpZipLib.Zip.Compression.Inflater inflater = new ICSharpCode.SharpZipLib.Zip.Compression.Inflater();
                inflater.SetInput(data, 4, data.Length - 4);

                cdata = new byte[data[0] + data[1] * 256 + data[2] * 256 * 256];
                inflater.Inflate(cdata);
                //  ZLib.Decompress(cdata);
            }

            str.AppendFormat("[{0} {1}] {2} length={3} ", Const.Tick, sock.RemoteEndPoint.ToString(), code, cdata.Length);
            if (code == OP.SMSG_UPDATE_OBJECT || code == OP.SMSG_COMPRESSED_UPDATE_OBJECT)
            {
                int pos = 5;
                str.AppendFormat("count={0}\r\n", cdata[0]);
                for (int i = 0; i < cdata[0]; i++)
                {
                    if (pos >= cdata.Length)
                    {
                        break;
                    }

                    byte type = cdata[pos];
                    str.AppendFormat(" {0} TYPE={1} GUID={2:X} ", i + 1, type, BitConverter.ToUInt32(cdata, pos + 1));
                    pos += 9;

                    if (type > 0)
                    {
                        byte obtype = cdata[pos]; pos += 9;
                        str.AppendFormat("OBTYPE={0} MOVE [", obtype);
                        for (int j = 0; j < 10; j++)
                        {
                            str.AppendFormat("{0} ", BitConverter.ToSingle(cdata, pos));
                            pos += 4;
                        }
                        pos += 20;
                        str.AppendFormat("] ");
                    }
                    str.AppendFormat("UPDATE [");
                    byte cnt  = cdata[pos]; pos++;
                    int  cpos = pos; pos += cnt * 4;
                    for (int j = 0; j < cnt * 32; j++)
                    {
                        if ((cdata[cpos + j / 8] & (1 << (j % 8))) != 0)
                        {
                            if (pos >= cdata.Length)
                            {
                                break;
                            }

                            str.AppendFormat("{0}={1:X} ", j, BitConverter.ToUInt32(cdata, pos));
                            pos += 4;
                        }
                    }
                    str.AppendFormat("]\r\n");
                }
                str.Length = str.Length - 2;
            }             //
            else
            {
                str.Append("{ ");
                for (int i = 0; i < data.Length; i++)
                {
                    string s = data[i].ToString("X");
                    if (s.Length == 2)
                    {
                        str.Append(s + " ");
                    }
                    else
                    {
                        str.Append("0" + s + " ");
                    }
                }
                str.Append("}");
            }

            w.WriteLine(str.ToString());
            w.Close();
#endif
            #endregion
            ByteArrayBuilder pack = new ByteArrayBuilder();
            pack.Add((ushort)(data.Length + 2));
            pack.Add((byte)code, (byte)((ushort)code >> 8));
            pack.Add(data);
            if (SS_Hash != null)
            {
                Encode(pack);
            }
            Send(pack);
        }
示例#17
0
 /// <summary>
 /// Inflater解压缩
 /// </summary>
 /// <param name="inputByte"></param>
 /// <returns></returns>
 public static byte[] inflater(byte[] inputByte)
 {
     byte[] temp = new byte[1024];
     MemoryStream memory = new MemoryStream();
     ICSharpCode.SharpZipLib.Zip.Compression.Inflater inf = new ICSharpCode.SharpZipLib.Zip.Compression.Inflater();
     inf.SetInput(inputByte);
     while (!inf.IsFinished)
     {
         int extracted = inf.Inflate(temp);
         if (extracted > 0)
         {
             memory.Write(temp, 0, extracted);
         }
         else
         {
             break;
         }
     }
     return memory.ToArray();
 }
示例#18
0
        public Form1()
        {
            InitializeComponent();

            var dicProvider = new Typography.TextBreak.IcuSimpleTextFileDictionaryProvider()
            {
                DataDir = "../../../../../Typography.TextBreak/icu62/brkitr"
            };

            Typography.TextBreak.CustomBreakerBuilder.Setup(dicProvider);

            this.Load += new System.EventHandler(this.Form1_Load);


            //
            //Woff
            WoffDefaultZlibDecompressFunc.DecompressHandler = (byte[] compressedBytes, byte[] decompressedResult) =>
            {
                //ZLIB
                //****
                //YOU can change to  your prefer decode libs***
                //****

                bool result = false;
                try
                {
                    var inflater = new ICSharpCode.SharpZipLib.Zip.Compression.Inflater();
                    inflater.SetInput(compressedBytes);
                    inflater.Inflate(decompressedResult);
#if DEBUG
                    long outputLen = inflater.TotalOut;
                    if (outputLen != decompressedResult.Length)
                    {
                    }
#endif

                    result = true;
                }
                catch (Exception ex)
                {
                }
                return(result);
            };
            //Woff2

            Woff2DefaultBrotliDecompressFunc.DecompressHandler = (byte[] compressedBytes, Stream output) =>
            {
                //BROTLI
                //****
                //YOU can change to  your prefer decode libs***
                //****

                bool result = false;
                try
                {
                    using (MemoryStream ms = new MemoryStream(compressedBytes))
                    {
                        ms.Position = 0;//set to start pos
                        DecompressAndCalculateCrc1(ms, output);
                        //
                        //

                        //Decompress(ms, output);
                    }
                    //DecompressBrotli(compressedBytes, output);
                    result = true;
                }
                catch (Exception ex)
                {
                }
                return(result);
            };
        }
示例#19
0
        unsafe void AcquireScreen()
        {
            Message msg = new Message();
            msg.type = MessageType.Message_DisplayCapture;
            msg.Send(ns);

            msg.Recv(ns);
            int zipped_size = msg.dispcap_size;
            BinaryReader br = new BinaryReader(ns);
            byte[] zipbuf = new byte[zipped_size];
            for (int i = 0; i < zipped_size; i++)
                zipbuf[i] = br.ReadByte();

            var inf = new ICSharpCode.SharpZipLib.Zip.Compression.Inflater();
            inf.SetInput(zipbuf);
            byte[] bscreen = new byte[256 * 192 * 2];
            inf.Inflate(bscreen);

            var bmp = new Bitmap(256, 192, PixelFormat.Format32bppArgb);
            BitmapData bmpdata = bmp.LockBits(new System.Drawing.Rectangle(0, 0, 256, 192), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
            byte* bp = (byte*)bmpdata.Scan0.ToPointer();
            for (int i = 0; i < 256 * 192; i++)
            {
                int r = bscreen[i * 2] & 0x1F;
                int g = ((bscreen[i * 2] & 0xE0)>>5) | ((bscreen[i*2+1] & 3)<<3);
                int b = (bscreen[i * 2 + 1] >> 2) & 0x1F;
                int a = bscreen[i * 2 + 1] >> 7;

                //todo - use same color conversion as desmume (whatever that is)
                r <<= 3;
                g <<= 3;
                b <<= 3;

                bp[i * 4 + 0] = (byte)b;
                bp[i * 4 + 1] = (byte)g;
                bp[i * 4 + 2] = (byte)r;
                bp[i * 4 + 3] = 255;
            }
            bmp.UnlockBits(bmpdata);

            if (lastScreen != null) lastScreen.Dispose();
            lastScreen = bmp;
            SetViewport(lastScreen);
        }
示例#20
0
        /// <summary>
        /// Treats the data extracted from the myp archive
        /// Uncompress the data if said data was compressed
        /// </summary>
        /// <param name="archFile"></param>
        private void TreatExtractedFile(FileInArchive archFile)
        {
            try
            {
                if (archFile.descriptor.compressionMethod == 1) //ZLib compression
                {
                    try
                    {
                        //Create the output_buffer, useless to create it if no compression
                        byte[] output_buffer = new byte[archFile.descriptor.uncompressedSize];

                        ICSharpCode.SharpZipLib.Zip.Compression.Inflater inf = new ICSharpCode.SharpZipLib.Zip.Compression.Inflater();
                        inf.SetInput(archFile.data);
                        inf.Inflate(output_buffer);

                        if (!MypHandlerConfig.MultithreadedExtraction)
                        {
                            //Treat directly the write
                            SaveBufferToFile(output_buffer, archFile.descriptor.foundFileName, archFile.descriptor.filename, archFile.descriptor.extension);
                        }
                        else
                        {
                            boList.AddBufferItemToQueue(output_buffer, archFile.descriptor.foundFileName, archFile.descriptor.filename, archFile.descriptor.extension);
                        }
                        //Clear the buffer (useless in CSharp)
                        output_buffer = null;
                    }
                    catch (Exception)
                    {
                        TriggerExtractionEvent(new MYPFileEventArgs(Event_ExtractionType.FileExtractionError, error_ExtractionNumber++));
                    }
                }
                else if (archFile.descriptor.compressionMethod == 0) //No compression
                {
                    if (!MypHandlerConfig.MultithreadedExtraction)
                    {
                        //Treat directly the write
                        SaveBufferToFile(archFile.data, archFile.descriptor.foundFileName, archFile.descriptor.filename, archFile.descriptor.extension);
                    }
                    else
                    {
                        boList.AddBufferItemToQueue(archFile.data, archFile.descriptor.foundFileName, archFile.descriptor.filename, archFile.descriptor.extension);
                    }
                }
                else
                {
                    TriggerExtractionEvent(new MYPFileEventArgs(Event_ExtractionType.UnknownCompressionMethod, error_ExtractionNumber++));
                }
            }
            catch (Exception)
            {
                TriggerExtractionEvent(new MYPFileEventArgs(Event_ExtractionType.UnknownError, error_ExtractionNumber++));
            }
        }
示例#21
0
        public override Stream Open()
        {
            lock (Archive) {
                BinaryReader reader = Archive.Reader;
                reader.BaseStream.Position = Offset;

                byte[] data = new byte[Size];

                switch (Mode) {
                    case ArchiveRecordMode.Deflate:
                        var inflater = new ICSharpCode.SharpZipLib.Zip.Compression.Inflater();
                        inflater.SetInput(reader.ReadBytes(SizeCompressed), 0, SizeCompressed);
                        if (inflater.Inflate(data, 0, Size) != Size)
                            throw new InvalidDataException();
                        break;

                    case ArchiveRecordMode.Uncompressed:
                        if (reader.Read(data, 0, Size) != Size)
                            throw new InvalidDataException();
                        break;

                    default:
                        throw new NotSupportedException();
                }

                return new MemoryStream(data, false);
            }
        }
示例#22
0
            public byte[] GetData()
            {
                FileInfo     file   = new FileInfo(bsa.name);
                BinaryReader binary = new BinaryReader(file.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite), System.Text.Encoding.Default);

                binary.BaseStream.Seek((Int64)offset, SeekOrigin.Begin);
                byte start = 0;

                if (bsa.defaultFlag9)
                {
                    start = binary.ReadByte();
                    string str = new string(binary.ReadChars(start));
                    //Console.WriteLine("filename found");
                }
                if (compressed)
                {
                    // https://github.com/IonKiwi/lz4.net for interop C++ version
                    // https://github.com/Fody/Costura to merge dlls into exe
                    if (bsa.compressionType)
                    {
                        if (zsize != 0)
                        {
                            byte[] b      = new byte[size - start];
                            byte[] output = new byte[zsize];
                            binary.Read(b, 0, (int)size - start);
                            output = lz4.LZ4Helper.Decompress(b);
                            return(output);
                        }
                        else
                        {
                            byte[] b      = new byte[size - 4 - start];
                            uint   l      = binary.ReadUInt32();
                            byte[] output = new byte[l];
                            binary.Read(b, 0, (int)size - 4 - start);
                            output = lz4.LZ4Helper.Decompress(b);
                            return(output);
                        }
                    }
                    else
                    {
                        if (zsize != 0)
                        {
                            byte[] b      = new byte[size - start];
                            byte[] output = new byte[zsize];
                            binary.Read(b, 0, (int)size - start);
                            ICSharpCode.SharpZipLib.Zip.Compression.Inflater inf = new ICSharpCode.SharpZipLib.Zip.Compression.Inflater();
                            inf.SetInput(b, 0, b.Length);
                            inf.Inflate(output);
                            binary.Close();
                            return(output);
                        }
                        else
                        {
                            byte[] b      = new byte[size - 4 - start];
                            byte[] output = new byte[binary.ReadUInt32()];
                            binary.Read(b, 0, (int)size - 4 - start);
                            ICSharpCode.SharpZipLib.Zip.Compression.Inflater inf = new ICSharpCode.SharpZipLib.Zip.Compression.Inflater();
                            inf.SetInput(b, 0, b.Length);
                            inf.Inflate(output);
                            binary.Close();
                            return(output);
                        }
                    }
                }
                else
                {
                    byte[] output = binary.ReadBytes((int)size);
                    binary.Close();
                    return(output);
                }
            }
 public byte[] GetData()
 {
     FileInfo file = new FileInfo(bsa.name);
     BinaryReader binary = new BinaryReader(file.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite), System.Text.Encoding.Default);
     binary.BaseStream.Seek(offset, SeekOrigin.Begin);
     byte start = 0;
     if (bsa.defaultFlag9)
     {
         start = binary.ReadByte();
         string str = new string(binary.ReadChars(start));
         //Console.WriteLine(bsa.name + " name " + start + " " + str);
     }
     if (compressed)
     {
         //Console.WriteLine(bsa.name + " compressed " + size);
         byte[] b = new byte[size - 4 - start];
         byte[] output = new byte[binary.ReadUInt32()];
         binary.Read(b, 0, size - 4 - start);
         ICSharpCode.SharpZipLib.Zip.Compression.Inflater inf = new ICSharpCode.SharpZipLib.Zip.Compression.Inflater();
         inf.SetInput(b, 0, b.Length);
         inf.Inflate(output);
         binary.Close();
         return output;
     }
     else
     {
         //Console.WriteLine(bsa.name + " not compressed "+ size);
         byte[] output = binary.ReadBytes(size);
         binary.Close();
         return output;
     }
 }
示例#24
0
        private void mainProc()
        {
            try
            {
                logger.Info("Iniciando thread principal");


                _acceptor.OnClientConnected    += new ClientConnectedHandler(_acceptor_OnClientConnected);
                _acceptor.OnClientDisconnected += new ClientDisconnectedHandler(_acceptor_OnClientDisconnected);
                _acceptor.OnRequestReceived    += new MessageReceivedHandler(_acceptor_OnRequestReceived);

                _initiator.OnRequestReceived    += new MessageReceivedHandler(_initiator_OnDataReceived);
                _initiator.OnClientDisconnected += new ClientDisconnectedHandler(_initiator_OnClientDisconnected);

                logger.Info("Inicializando deflater");

                unzipped = new byte[BUFFER_SIZE];



                //zlib = new Ionic.Zlib.ZlibStream(compressedStream, Ionic.Zlib.CompressionMode.Decompress, true);
                //zlib.BufferSize = BUFFER_SIZE;
                zlib = new ICSharpCode.SharpZipLib.Zip.Compression.Inflater();
                //zlib.FlushMode = Ionic.Zlib.FlushType.Full;

                logger.Info("Iniciando acceptor listening at " + acceptorPort);
                _acceptor.StartListen(acceptorPort);

                while (_bKeepRunning)
                {
                    try
                    {
                        UncompressedPacket pkt;

                        if (qUnpack.TryDequeue(out pkt))
                        {
                            _acceptor.SendToAll(pkt.Buffer);

                            continue;
                        }

                        Thread.Sleep(25);
                    }
                    catch (Exception ex)
                    {
                        logger.Error("mainProc(while{}): " + ex.Message, ex);
                    }
                }

                if (_acceptor != null && _acceptor.IsConectado())
                {
                    _acceptor.CloseSocket();
                }

                if (_initiator != null && _initiator.IsConectado())
                {
                    _initiator.CloseSocket();
                }
            }
            catch (Exception ex)
            {
                logger.Error("mainProc(): " + ex.Message, ex);
            }
        }
示例#25
0
		/// <summary>
		/// Initializes teh decompressor.
		/// </summary>
		protected static void InitDecompressor()
		{
			inf = new ICSharpCode.SharpZipLib.Zip.Compression.Inflater(false);
			ms = new MemoryStream();
			compReader = new BinaryReader(ms);
			input = new byte[0x1000];
			output = new byte[0x4000];
		}
示例#26
0
        static void SetupWoffDecompressFunctions()
        {
            //
            //Woff
            WoffDefaultZlibDecompressFunc.DecompressHandler = (byte[] compressedBytes, byte[] decompressedResult) =>
            {
                //ZLIB
                //****
                //YOU can change to  your prefer decode libs***
                //****

                bool result = false;
                try
                {
                    var inflater = new ICSharpCode.SharpZipLib.Zip.Compression.Inflater();
                    inflater.SetInput(compressedBytes);
                    inflater.Inflate(decompressedResult);
#if DEBUG
                    long outputLen = inflater.TotalOut;
                    if (outputLen != decompressedResult.Length)
                    {
                    }
#endif

                    result = true;
                }
                catch (Exception ex)
                {
                }
                return(result);
            };
            //Woff2

            Woff2DefaultBrotliDecompressFunc.DecompressHandler = (byte[] compressedBytes, Stream output) =>
            {
                //BROTLI
                //****
                //YOU can change to  your prefer decode libs***
                //****

                bool result = false;
                try
                {
                    using (MemoryStream ms = new MemoryStream(compressedBytes))
                    {
                        ms.Position = 0;//set to start pos
                        DecompressAndCalculateCrc1(ms, output);
                        //
                        //

                        //Decompress(ms, output);
                    }
                    //DecompressBrotli(compressedBytes, output);
                    result = true;
                }
                catch (Exception ex)
                {
                }
                return(result);
            };
        }
示例#27
0
        private static ByteVector Inflate(ByteVector data)
        {
            #if HAVE_SHARPZIPLIB
            using (System.IO.MemoryStream out_stream = new System.IO.MemoryStream ()) {

                ICSharpCode.SharpZipLib.Zip.Compression.Inflater inflater =
                    new ICSharpCode.SharpZipLib.Zip.Compression.Inflater ();

                inflater.SetInput (data.Data);

                byte [] buffer = new byte [1024];
                int written_bytes;

                while ((written_bytes = inflater.Inflate (buffer)) > 0)
                    out_stream.Write (buffer, 0, written_bytes);

                return new ByteVector (out_stream.ToArray ());
            }
            #else
            return null;
            #endif
        }
示例#28
0
        /// <summary>
        /// Tries to identify the file extension
        /// Updates the file descriptor in response
        /// </summary>
        /// <param name="archFile">file to consider</param>
        private void TreatHeader(FileInArchive archFile)
        {
            MemoryStream outputMS = new MemoryStream();

            byte[] output_buffer = new byte[4096];

            if (archFile.descriptor.compressionMethod == 1)
            {
                try
                {
                    ICSharpCode.SharpZipLib.Zip.Compression.Inflater inf = new ICSharpCode.SharpZipLib.Zip.Compression.Inflater();
                    inf.SetInput(archFile.data_start_200);
                    inf.Inflate(output_buffer);
                }
                catch (Exception)
                {
                    Error_FileTableEntry(archFile);
                }

                archFile.descriptor.extension = GetExtension(output_buffer);
                //In order to sort the filenames in folders in the treeView. Yeah I cheat!
                //archFile.descriptor.filename = archFile.descriptor.extension + "/" + archFile.descriptor.filename;
            }
            else if (archFile.descriptor.compressionMethod == 0)
            {
                archFile.descriptor.extension = GetExtension(archFile.data_start_200);
            }
            else
            {
            }
        }
示例#29
0
        public bool LoadRom(string path, CoreComm nextComm, bool forceAccurateCore = false,
                            int recursiveCount = 0) // forceAccurateCore is currently just for Quicknes vs Neshawk but could be used for other situations
        {
            if (recursiveCount > 1)                 // hack to stop recursive calls from endlessly rerunning if we can't load it
            {
                DoLoadErrorCallback("Failed multiple attempts to load ROM.", "");
                return(false);
            }

            bool cancel = false;

            if (path == null)
            {
                return(false);
            }

            using (var file = new HawkFile())
            {
                //only try mounting a file if a filename was given
                if (!string.IsNullOrEmpty(path))
                {
                    // lets not use this unless we need to
                    // file.NonArchiveExtensions = romExtensions;
                    file.Open(path);

                    // if the provided file doesnt even exist, give up!
                    if (!file.Exists)
                    {
                        return(false);
                    }
                }

                CanonicalFullPath = file.CanonicalFullPath;

                IEmulator nextEmulator = null;
                RomGame   rom          = null;
                GameInfo  game         = null;

                try
                {
                    string ext = null;

                    if (AsLibretro)
                    {
                        string codePathPart = Path.GetFileNameWithoutExtension(nextComm.LaunchLibretroCore);

                        var retro = new LibRetroEmulator(nextComm, nextComm.LaunchLibretroCore);
                        nextEmulator = retro;

                        //kind of dirty.. we need to stash this, and then we can unstash it in a moment, in case the core doesnt fail
                        var oldGame = Global.Game;

                        if (retro.Description.SupportsNoGame && string.IsNullOrEmpty(path))
                        {
                            //must be done before LoadNoGame (which triggers retro_init and the paths to be consumed by the core)
                            //game name == name of core
                            var gameName = codePathPart;
                            Global.Game = game = new GameInfo {
                                Name = gameName, System = "Libretro"
                            };

                            //if we are allowed to run NoGame and we dont have a game, boot up the core that way
                            bool ret = retro.LoadNoGame();

                            Global.Game = oldGame;

                            if (!ret)
                            {
                                DoLoadErrorCallback("LibretroNoGame failed to load. This is weird", "Libretro");
                                retro.Dispose();
                                return(false);
                            }
                        }
                        else
                        {
                            bool ret;

                            //must be done before LoadNoGame (which triggers retro_init and the paths to be consumed by the core)
                            //game name == name of core + extensionless_game_filename
                            var gameName = Path.Combine(codePathPart, Path.GetFileNameWithoutExtension(file.Name));
                            Global.Game = game = new GameInfo {
                                Name = gameName, System = "Libretro"
                            };

                            //if the core requires an archive file, then try passing the filename of the archive
                            //(but do we ever need to actually load the contents of the archive file into ram?)
                            if (retro.Description.NeedsArchives)
                            {
                                if (file.IsArchiveMember)
                                {
                                    throw new InvalidOperationException("Should not have bound file member for libretro block_extract core");
                                }
                                ret = retro.LoadPath(file.FullPathWithoutMember);
                            }
                            else
                            {
                                //otherwise load the data or pass the filename, as requested. but..
                                if (retro.Description.NeedsRomAsPath && file.IsArchiveMember)
                                {
                                    throw new InvalidOperationException("Cannot pass archive member to libretro needs_fullpath core");
                                }

                                if (retro.Description.NeedsRomAsPath)
                                {
                                    ret = retro.LoadPath(file.FullPathWithoutMember);
                                }
                                else
                                {
                                    ret = HandleArchiveBinding(file);
                                    if (ret)
                                    {
                                        ret = retro.LoadData(file.ReadAllBytes());
                                    }
                                }
                            }

                            Global.Game = oldGame;

                            if (!ret)
                            {
                                DoLoadErrorCallback("Libretro failed to load the given file. This is probably due to a core/content mismatch. Moreover, the process is now likely to be hosed. We suggest you restart the program.", "Libretro");
                                retro.Dispose();
                                return(false);
                            }
                        }
                    }
                    else
                    {
                        //if not libretro:

                        //do extension checknig
                        ext = file.Extension.ToLowerInvariant();

                        //do the archive binding we had to skip
                        if (!HandleArchiveBinding(file))
                        {
                            return(false);
                        }
                    }

                    if (string.IsNullOrEmpty(ext))
                    {
                    }
                    else if (ext == ".m3u")
                    {
                        //HACK ZONE - currently only psx supports m3u
                        M3U_File m3u;
                        using (var sr = new StreamReader(path))
                            m3u = M3U_File.Read(sr);
                        if (m3u.Entries.Count == 0)
                        {
                            throw new InvalidOperationException("Can't load an empty M3U");
                        }
                        //load discs for all the m3u
                        m3u.Rebase(Path.GetDirectoryName(path));
                        List <Disc>   discs     = new List <Disc>();
                        List <string> discNames = new List <string>();
                        StringWriter  sw        = new StringWriter();
                        foreach (var e in m3u.Entries)
                        {
                            Disc   disc     = null;
                            string discPath = e.Path;

                            //--- load the disc in a context which will let us abort if it's going to take too long
                            var discMountJob = new DiscMountJob {
                                IN_FromPath = discPath
                            };
                            discMountJob.IN_SlowLoadAbortThreshold = 8;
                            discMountJob.Run();
                            disc = discMountJob.OUT_Disc;

                            if (discMountJob.OUT_SlowLoadAborted)
                            {
                                DoLoadErrorCallback("This disc would take too long to load. Run it through discohawk first, or find a new rip because this one is probably junk", "", LoadErrorType.DiscError);
                                return(false);
                            }

                            if (discMountJob.OUT_ErrorLevel)
                            {
                                throw new InvalidOperationException("\r\n" + discMountJob.OUT_Log);
                            }

                            if (disc == null)
                            {
                                throw new InvalidOperationException("Can't load one of the files specified in the M3U");
                            }

                            var discName = Path.GetFileNameWithoutExtension(discPath);
                            discNames.Add(discName);
                            discs.Add(disc);

                            var discType = new DiscIdentifier(disc).DetectDiscType();
                            sw.WriteLine("{0}", Path.GetFileName(discPath));
                            if (discType == DiscType.SonyPSX)
                            {
                                string discHash = new DiscHasher(disc).Calculate_PSX_BizIDHash().ToString("X8");
                                game = Database.CheckDatabase(discHash);
                                if (game == null || game.IsRomStatusBad() || game.Status == RomStatus.NotInDatabase)
                                {
                                    sw.WriteLine("Disc could not be identified as known-good. Look for a better rip.");
                                }
                                else
                                {
                                    sw.WriteLine("Disc was identified (99.99% confidently) as known good with disc id hash CRC32:{0:X8}", discHash);
                                    sw.WriteLine("Nonetheless it could be an unrecognized romhack or patched version.");
                                    sw.WriteLine("According to redump.org, the ideal hash for entire disc is: CRC32:{0:X8}", game.GetStringValue("dh"));
                                    sw.WriteLine("The file you loaded hasn't been hashed entirely (it would take too long)");
                                    sw.WriteLine("Compare it with the full hash calculated by the PSX menu's Hash Discs tool");
                                }
                            }
                            else
                            {
                                sw.WriteLine("Not a PSX disc");
                            }
                            sw.WriteLine("-------------------------");
                        }

                        nextEmulator = new Octoshock(nextComm, discs, discNames, null, GetCoreSettings <Octoshock>(), GetCoreSyncSettings <Octoshock>());
                        nextEmulator.CoreComm.RomStatusDetails = sw.ToString();
                        game = new GameInfo {
                            Name = Path.GetFileNameWithoutExtension(file.Name)
                        };
                        game.System = "PSX";
                    }
                    else if (ext == ".iso" || ext == ".cue" || ext == ".ccd")
                    {
                        if (file.IsArchive)
                        {
                            throw new InvalidOperationException("Can't load CD files from archives!");
                        }

                        string discHash = null;

                        //--- load the disc in a context which will let us abort if it's going to take too long
                        var discMountJob = new DiscMountJob {
                            IN_FromPath = path
                        };
                        discMountJob.IN_SlowLoadAbortThreshold = 8;
                        discMountJob.Run();

                        if (discMountJob.OUT_SlowLoadAborted)
                        {
                            DoLoadErrorCallback("This disc would take too long to load. Run it through discohawk first, or find a new rip because this one is probably junk", "", LoadErrorType.DiscError);
                            return(false);
                        }

                        if (discMountJob.OUT_ErrorLevel)
                        {
                            throw new InvalidOperationException("\r\n" + discMountJob.OUT_Log);
                        }

                        var disc = discMountJob.OUT_Disc;
                        //-----------

                        //TODO - use more sophisticated IDer
                        var discType = new DiscIdentifier(disc).DetectDiscType();
                        if (discType == DiscType.SonyPSX)
                        {
                            discHash = new DiscHasher(disc).Calculate_PSX_BizIDHash().ToString("X8");
                        }
                        else
                        {
                            discHash = new DiscHasher(disc).OldHash();
                        }

                        game = Database.CheckDatabase(discHash);
                        if (game == null)
                        {
                            // try to use our wizard methods
                            game = new GameInfo {
                                Name = Path.GetFileNameWithoutExtension(file.Name), Hash = discHash
                            };

                            switch (new DiscIdentifier(disc).DetectDiscType())
                            {
                            case DiscType.SegaSaturn:
                                game.System = "SAT";
                                break;

                            case DiscType.SonyPSP:
                                game.System = "PSP";
                                break;

                            default:
                            case DiscType.SonyPSX:
                                game.System = "PSX";
                                break;

                            case DiscType.MegaCD:
                                game.System = "GEN";
                                break;

                            case DiscType.AudioDisc:
                            case DiscType.TurboCD:
                            case DiscType.UnknownCDFS:
                            case DiscType.UnknownFormat:
                                game.System = "PCECD";
                                break;
                            }
                        }

                        switch (game.System)
                        {
                        case "GEN":
                            var genesis = new GPGX(
                                nextComm, null, disc, GetCoreSettings <GPGX>(), GetCoreSyncSettings <GPGX>());
                            nextEmulator = genesis;
                            break;

                        case "SAT":
                            nextEmulator = new Yabause(nextComm, disc, GetCoreSyncSettings <Yabause>());
                            break;

                        case "PSP":
                            nextEmulator = new PSP(nextComm, file.Name);
                            break;

                        case "PSX":
                            nextEmulator = new Octoshock(nextComm, new List <Disc>(new[] { disc }), new List <string>(new[] { Path.GetFileNameWithoutExtension(path) }), null, GetCoreSettings <Octoshock>(), GetCoreSyncSettings <Octoshock>());
                            if (game.IsRomStatusBad() || game.Status == RomStatus.NotInDatabase)
                            {
                                nextEmulator.CoreComm.RomStatusDetails = "Disc could not be identified as known-good. Look for a better rip.";
                            }
                            else
                            {
                                StringWriter sw = new StringWriter();
                                sw.WriteLine("Disc was identified (99.99% confidently) as known good with disc id hash CRC32:{0:X8}", discHash);
                                sw.WriteLine("Nonetheless it could be an unrecognized romhack or patched version.");
                                sw.WriteLine("According to redump.org, the ideal hash for entire disc is: CRC32:{0:X8}", game.GetStringValue("dh"));
                                sw.WriteLine("The file you loaded hasn't been hashed entirely (it would take too long)");
                                sw.WriteLine("Compare it with the full hash calculated by the PSX menu's Hash Discs tool");
                                nextEmulator.CoreComm.RomStatusDetails = sw.ToString();
                            }
                            break;

                        case "PCE":
                        case "PCECD":
                            nextEmulator = new PCEngine(nextComm, game, disc, GetCoreSettings <PCEngine>(), GetCoreSyncSettings <PCEngine>());
                            break;
                        }
                    }
                    else if (file.Extension.ToLowerInvariant() == ".xml")
                    {
                        try
                        {
                            var xmlGame = XmlGame.Create(file);                             // if load fails, are we supposed to retry as a bsnes XML????????
                            game = xmlGame.GI;

                            switch (game.System)
                            {
                            case "GB":
                            case "DGB":
                                // adelikat: remove need for tags to be hardcoded to left and right, we should clean this up, also maybe the DGB core should just take the xml file and handle it itself
                                var leftBytes  = xmlGame.Assets.First().Value;
                                var rightBytes = xmlGame.Assets.Skip(1).First().Value;

                                var left  = Database.GetGameInfo(leftBytes, "left.gb");
                                var right = Database.GetGameInfo(rightBytes, "right.gb");
                                nextEmulator = new GambatteLink(
                                    nextComm,
                                    left,
                                    leftBytes,
                                    right,
                                    rightBytes,
                                    GetCoreSettings <GambatteLink>(),
                                    GetCoreSyncSettings <GambatteLink>(),
                                    Deterministic);

                                // other stuff todo
                                break;

                            case "AppleII":
                                var assets = xmlGame.Assets.Select(a => Database.GetGameInfo(a.Value, a.Key));
                                var roms   = xmlGame.Assets.Select(a => a.Value);
                                nextEmulator = new AppleII(
                                    nextComm,
                                    assets,
                                    roms,
                                    (AppleII.Settings)GetCoreSettings <AppleII>());
                                break;

                            case "C64":
                                nextEmulator = new C64(
                                    nextComm,
                                    xmlGame.Assets.Select(a => a.Value),
                                    (C64.C64Settings)GetCoreSettings <C64>(),
                                    (C64.C64SyncSettings)GetCoreSyncSettings <C64>()
                                    );
                                break;

                            case "PSX":
                                var entries   = xmlGame.AssetFullPaths;
                                var discs     = new List <Disc>();
                                var discNames = new List <string>();
                                var sw        = new StringWriter();
                                foreach (var e in entries)
                                {
                                    Disc   disc     = null;
                                    string discPath = e;

                                    //--- load the disc in a context which will let us abort if it's going to take too long
                                    var discMountJob = new DiscMountJob {
                                        IN_FromPath = discPath
                                    };
                                    discMountJob.IN_SlowLoadAbortThreshold = 8;
                                    discMountJob.Run();
                                    disc = discMountJob.OUT_Disc;

                                    if (discMountJob.OUT_SlowLoadAborted)
                                    {
                                        DoLoadErrorCallback("This disc would take too long to load. Run it through discohawk first, or find a new rip because this one is probably junk", "PSX", LoadErrorType.DiscError);
                                        return(false);
                                    }

                                    if (discMountJob.OUT_ErrorLevel)
                                    {
                                        throw new InvalidOperationException("\r\n" + discMountJob.OUT_Log);
                                    }

                                    if (disc == null)
                                    {
                                        throw new InvalidOperationException("Can't load one of the files specified in the M3U");
                                    }

                                    var discName = Path.GetFileNameWithoutExtension(discPath);
                                    discNames.Add(discName);
                                    discs.Add(disc);

                                    var discType = new DiscIdentifier(disc).DetectDiscType();
                                    sw.WriteLine("{0}", Path.GetFileName(discPath));
                                    if (discType == DiscType.SonyPSX)
                                    {
                                        string discHash = new DiscHasher(disc).Calculate_PSX_BizIDHash().ToString("X8");
                                        game = Database.CheckDatabase(discHash);
                                        if (game == null || game.IsRomStatusBad() || game.Status == RomStatus.NotInDatabase)
                                        {
                                            sw.WriteLine("Disc could not be identified as known-good. Look for a better rip.");
                                        }
                                        else
                                        {
                                            sw.WriteLine("Disc was identified (99.99% confidently) as known good with disc id hash CRC32:{0:X8}", discHash);
                                            sw.WriteLine("Nonetheless it could be an unrecognized romhack or patched version.");
                                            sw.WriteLine("According to redump.org, the ideal hash for entire disc is: CRC32:{0:X8}", game.GetStringValue("dh"));
                                            sw.WriteLine("The file you loaded hasn't been hashed entirely (it would take too long)");
                                            sw.WriteLine("Compare it with the full hash calculated by the PSX menu's Hash Discs tool");
                                        }
                                    }
                                    else
                                    {
                                        sw.WriteLine("Not a PSX disc");
                                    }
                                    sw.WriteLine("-------------------------");
                                }

                                // todo: copy pasta from PSX .cue section
                                nextEmulator = new Octoshock(nextComm, discs, discNames, null, GetCoreSettings <Octoshock>(), GetCoreSyncSettings <Octoshock>());
                                nextEmulator.CoreComm.RomStatusDetails = sw.ToString();
                                game = new GameInfo {
                                    Name = Path.GetFileNameWithoutExtension(file.Name)
                                };
                                game.System = "PSX";

                                break;

                            default:
                                return(false);
                            }
                        }
                        catch (Exception ex)
                        {
                            try
                            {
                                // need to get rid of this hack at some point
                                rom = new RomGame(file);
                                ((CoreFileProvider)nextComm.CoreFileProvider).SubfileDirectory = Path.GetDirectoryName(path.Replace("|", string.Empty));                                 // Dirty hack to get around archive filenames (since we are just getting the directory path, it is safe to mangle the filename
                                byte[] romData = null;
                                byte[] xmlData = rom.FileData;

                                game        = rom.GameInfo;
                                game.System = "SNES";

                                var snes = new LibsnesCore(game, romData, Deterministic, xmlData, nextComm, GetCoreSettings <LibsnesCore>(), GetCoreSyncSettings <LibsnesCore>());
                                nextEmulator = snes;
                            }
                            catch
                            {
                                DoLoadErrorCallback(ex.ToString(), "DGB", LoadErrorType.XML);
                                return(false);
                            }
                        }
                    }
                    else if (file.Extension.ToLowerInvariant() == ".psf" || file.Extension.ToLowerInvariant() == ".minipsf")
                    {
                        Func <Stream, int, byte[]> cbDeflater = (Stream instream, int size) =>
                        {
                            var          inflater = new ICSharpCode.SharpZipLib.Zip.Compression.Inflater(false);
                            var          iis      = new ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputStream(instream, inflater);
                            MemoryStream ret      = new MemoryStream();
                            iis.CopyTo(ret);
                            return(ret.ToArray());
                        };
                        PSF psf = new PSF();
                        psf.Load(path, cbDeflater);
                        nextEmulator = new Octoshock(nextComm, psf, GetCoreSettings <Octoshock>(), GetCoreSyncSettings <Octoshock>());
                        nextEmulator.CoreComm.RomStatusDetails = "It's a PSF, what do you want. Oh, tags maybe?";

                        //total garbage, this
                        rom  = new RomGame(file);
                        game = rom.GameInfo;
                    }
                    else if (ext != null)                     // most extensions
                    {
                        rom = new RomGame(file);

                        //hacky for now
                        if (file.Extension.ToLowerInvariant() == ".exe")
                        {
                            rom.GameInfo.System = "PSX";
                        }
                        else if (file.Extension.ToLowerInvariant() == ".nsf")
                        {
                            rom.GameInfo.System = "NES";
                        }


                        if (string.IsNullOrEmpty(rom.GameInfo.System))
                        {
                            // Has the user picked a preference for this extension?
                            if (PreferredPlatformIsDefined(rom.Extension.ToLowerInvariant()))
                            {
                                rom.GameInfo.System = Global.Config.PreferredPlatformsForExtensions[rom.Extension.ToLowerInvariant()];
                            }
                            else if (ChoosePlatform != null)
                            {
                                var result = ChoosePlatform(rom);
                                if (!string.IsNullOrEmpty(result))
                                {
                                    rom.GameInfo.System = result;
                                }
                                else
                                {
                                    cancel = true;
                                }
                            }
                        }

                        game = rom.GameInfo;

                        var isXml = false;

                        // other xml has already been handled
                        if (file.Extension.ToLowerInvariant() == ".xml")
                        {
                            game.System = "SNES";
                            isXml       = true;
                        }


                        CoreInventory.Core core = null;

                        switch (game.System)
                        {
                        default:
                            core = CoreInventory.Instance[game.System];
                            break;

                        case null:
                            // The user picked nothing in the Core picker
                            break;

                        case "83P":
                            var ti83Bios     = ((CoreFileProvider)nextComm.CoreFileProvider).GetFirmware("TI83", "Rom", true);
                            var ti83BiosPath = ((CoreFileProvider)nextComm.CoreFileProvider).GetFirmwarePath("TI83", "Rom", true);
                            using (var ti83AsHawkFile = new HawkFile())
                            {
                                ti83AsHawkFile.Open(ti83BiosPath);
                                var ti83BiosAsRom = new RomGame(ti83AsHawkFile);
                                var ti83          = new TI83(nextComm, ti83BiosAsRom.GameInfo, ti83Bios, GetCoreSettings <TI83>());
                                ti83.LinkPort.SendFileToCalc(File.OpenRead(path), false);
                                nextEmulator = ti83;
                            }
                            break;

                        case "SNES":
                            if (Global.Config.SNES_InSnes9x && VersionInfo.DeveloperBuild)
                            {
                                core = CoreInventory.Instance["SNES", "Snes9x"];
                            }
                            else
                            {
                                // need to get rid of this hack at some point
                                ((CoreFileProvider)nextComm.CoreFileProvider).SubfileDirectory = Path.GetDirectoryName(path.Replace("|", String.Empty));                                         // Dirty hack to get around archive filenames (since we are just getting the directory path, it is safe to mangle the filename
                                var romData = isXml ? null : rom.FileData;
                                var xmlData = isXml ? rom.FileData : null;
                                var snes    = new LibsnesCore(game, romData, Deterministic, xmlData, nextComm, GetCoreSettings <LibsnesCore>(), GetCoreSyncSettings <LibsnesCore>());
                                nextEmulator = snes;
                            }

                            break;

                        case "NES":
                            if (!Global.Config.NES_InQuickNES || forceAccurateCore)
                            {
                                core = CoreInventory.Instance["NES", "NesHawk"];
                            }
                            else
                            {
                                core = CoreInventory.Instance["NES", "QuickNes"];
                            }

                            break;

                        case "GB":
                        case "GBC":
                            if (!Global.Config.GB_AsSGB)
                            {
                                core = CoreInventory.Instance["GB", "Gambatte"];
                            }
                            else
                            {
                                try
                                {
                                    game.System = "SNES";
                                    game.AddOption("SGB");
                                    var snes = new LibsnesCore(game, rom.FileData, Deterministic, null, nextComm, GetCoreSettings <LibsnesCore>(), GetCoreSyncSettings <LibsnesCore>());
                                    nextEmulator = snes;
                                }
                                catch
                                {
                                    // failed to load SGB bios or game does not support SGB mode.
                                    // To avoid catch-22, disable SGB mode
                                    Global.Config.GB_AsSGB = false;
                                    throw;
                                }
                            }

                            break;

                        case "A78":
                            var gamedbpath = Path.Combine(PathManager.GetExeDirectoryAbsolute(), "gamedb", "EMU7800.csv");
                            nextEmulator = new Atari7800(nextComm, game, rom.RomData, gamedbpath);
                            break;

                        case "C64":
                            var c64 = new C64(nextComm, Enumerable.Repeat(rom.RomData, 1), GetCoreSettings <C64>(), GetCoreSyncSettings <C64>());
                            nextEmulator = c64;
                            break;

                        case "GBA":
                            //core = CoreInventory.Instance["GBA", "Meteor"];
                            if (Global.Config.GBA_UsemGBA)
                            {
                                core = CoreInventory.Instance["GBA", "mGBA"];
                            }
                            else
                            {
                                core = CoreInventory.Instance["GBA", "VBA-Next"];
                            }
                            break;

                        case "PSX":
                            nextEmulator = new Octoshock(nextComm, null, null, rom.FileData, GetCoreSettings <Octoshock>(), GetCoreSyncSettings <Octoshock>());
                            nextEmulator.CoreComm.RomStatusDetails = "PSX etc.";
                            break;
                        }

                        if (core != null)
                        {
                            // use coreinventory
                            nextEmulator = core.Create(nextComm, game, rom.RomData, rom.FileData, Deterministic, GetCoreSettings(core.Type), GetCoreSyncSettings(core.Type));
                        }
                    }

                    if (nextEmulator == null)
                    {
                        if (!cancel)
                        {
                            DoLoadErrorCallback("No core could load the rom.", null);
                        }
                        return(false);
                    }
                }
                catch (Exception ex)
                {
                    string system = null;
                    if (game != null)
                    {
                        system = game.System;
                    }

                    // all of the specific exceptions we're trying to catch here aren't expected to have inner exceptions,
                    // so drill down in case we got a TargetInvocationException or something like that
                    while (ex.InnerException != null)
                    {
                        ex = ex.InnerException;
                    }

                    // Specific hack here, as we get more cores of the same system, this isn't scalable
                    if (ex is UnsupportedGameException)
                    {
                        if (system == "NES")
                        {
                            DoMessageCallback("Unable to use quicknes, using NESHawk instead");
                        }

                        return(LoadRom(path, nextComm, true, recursiveCount + 1));
                    }
                    else if (ex is MissingFirmwareException)
                    {
                        DoLoadErrorCallback(ex.Message, system, path, Deterministic, LoadErrorType.MissingFirmware);
                    }
                    else if (ex is CGBNotSupportedException)
                    {
                        // Note: GB as SGB was set to false by this point, otherwise we would want to do it here
                        DoMessageCallback("Failed to load a GB rom in SGB mode.  Disabling SGB Mode.");
                        return(LoadRom(path, nextComm, false, recursiveCount + 1));
                    }
                    else
                    {
                        DoLoadErrorCallback("A core accepted the rom, but threw an exception while loading it:\n\n" + ex, system);
                    }

                    return(false);
                }

                Rom            = rom;
                LoadedEmulator = nextEmulator;
                Game           = game;
                return(true);
            }
        }
示例#30
0
        public static void Trim(IntPtr hwnd, string In, string Out, ReportProgressDelegate del)
        {
            NativeMethods.ddsInit(hwnd);
            BinaryReader br=new BinaryReader(File.OpenRead(In), System.Text.Encoding.Default);
            BinaryWriter bw=new BinaryWriter(File.Create(Out), System.Text.Encoding.Default);
            System.Text.StringBuilder sb=new System.Text.StringBuilder(64);
            ICSharpCode.SharpZipLib.Zip.Compression.Inflater inf=new ICSharpCode.SharpZipLib.Zip.Compression.Inflater();
            bool Compressed, SkipName;

            if(br.ReadInt32()!=0x00415342) throw new Exception("Invalid bsa");
            uint version=br.ReadUInt32();
            bw.Write((int)0x00415342);
            bw.Write(version);
            bw.Write(br.ReadInt32());
            uint flags=br.ReadUInt32();
            if((flags&0x004)>0) { Compressed=true; flags^=0x4; } else Compressed=false;
            if((flags&0x100)>0&&version==0x68) SkipName=true; else SkipName=false;
            flags^=0x2;
            int FolderCount=br.ReadInt32();
            int FileCount=br.ReadInt32();
            bw.Write(flags);

            bw.Write(FolderCount);
            bw.Write(FileCount);
            bw.Write(br.ReadInt32());
            bw.Write(br.ReadInt32());
            bw.Write(br.ReadInt32());

            int[] folderFileCount=new int[FolderCount];
            for(int i=0;i<FolderCount;i++) {
                bw.Write(br.ReadInt64());
                folderFileCount[i]=br.ReadInt32();
                bw.Write(folderFileCount[i]);
                bw.Write(br.ReadInt32());
            }
            int[] fileLengths=new int[FileCount];
            long[] offsetOffsets=new long[FileCount];
            uint[] fileOffsets=new uint[FileCount];
            bool[] parsefiles=new bool[FileCount];
            int file=0;
            for(int i=0;i<FolderCount;i++) {
                byte len=br.ReadByte();
                bw.Write(len);
                sb.Length=0;
                while(--len>0) {
                    char c=br.ReadChar();
                    sb.Append(c);
                    bw.Write(c);
                }
                br.ReadByte();
                bw.Write((byte)0);
                bool parse=true;
                if(sb.ToString().StartsWith("textures\\interface\\")) parse=false;

                for(int j=0;j<folderFileCount[i];j++) {
                    bw.Write(br.ReadUInt64());
                    offsetOffsets[file]=br.BaseStream.Position;
                    fileLengths[file]=br.ReadInt32();
                    bw.Write(fileLengths[file]);
                    fileOffsets[file]=br.ReadUInt32();
                    bw.Write(fileOffsets[file]);
                    parsefiles[file]=parse;
                    file++;
                }
            }

            for(int i=0;i<FileCount;i++) {
                sb.Length=0;
                while(true) {
                    char c=(char)br.ReadByte();
                    //bw.Write(c);
                    if(c=='\0') break;
                    sb.Append(c);
                }
                if(!sb.ToString().EndsWith(".dds", StringComparison.OrdinalIgnoreCase)) parsefiles[i]=false;
            }

            int count=0;
            for(int i=0;i<FileCount;i++) {
                if((i%100)==0) del("Processing file "+i+" of "+FileCount);
                br.BaseStream.Position=fileOffsets[i];
                long offset=bw.BaseStream.Position;
                int add=0;
                if(SkipName) {
                    byte len=br.ReadByte();
                    bw.Write(len);
                    bw.Write(br.ReadBytes(len+1));
                    add=len+2;
                }
                bool compressed2=Compressed;
                if((fileLengths[i]&(1<<30))!=0) {
                    compressed2=!compressed2;
                    fileLengths[i]^=(1<<30);
                }
                if(!compressed2) {
                    byte[] bytes=new byte[fileLengths[i]];
                    br.Read(bytes, 0, fileLengths[i]);
                    Commit(bw, offsetOffsets[i], bytes, offset, add, parsefiles[i]);
                } else {
                    count++;
                    byte[] uncompressed=new byte[br.ReadUInt32()];
                    byte[] compressed=new byte[fileLengths[i]-4];
                    br.Read(compressed, 0, fileLengths[i]-4);
                    inf.Reset();
                    inf.SetInput(compressed);
                    inf.Inflate(uncompressed);
                    Commit(bw, offsetOffsets[i], uncompressed, offset, add, parsefiles[i]);
                }
            }

            br.Close();
            bw.Close();
            NativeMethods.ddsClose();
        }