/// <summary>
        ///
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="Input"></param>
        /// <param name="Output"></param>
        /// <param name="Size"></param>
        static public void DecryptAes(byte[] Key, byte *Input, byte *Output, int Size)
        {
            var InputArray  = PointerUtils.PointerToByteArray(Input, Size);
            var OutputArray = DecryptAes(InputArray, Key);

            PointerUtils.ByteArrayToPointer(OutputArray, Output);
        }
Exemple #2
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="OutputBuffer"></param>
        /// <param name="InputBuffer"></param>
        /// <param name="Size"></param>
        /// <returns></returns>
        public int kirk_CMD11(byte *OutputBuffer, byte *InputBuffer, int Size)
        {
            if (!is_kirk_initialized)
            {
                return(KIRK_NOT_INITIALIZED);
            }

            var Header = (KIRK_SHA1_HEADER *)InputBuffer;

            if (Size == 0 || Header->DataSize == 0)
            {
                return(KIRK_DATA_SIZE_ZERO);
            }

            //Size <<= 4;
            //Size >>= 4;
            Size &= 0x0FFFFFFF;
            Size  = (Size < Header->DataSize) ? Size : Header->DataSize;

            var Sha1Hash = (new SHA1CryptoServiceProvider()).ComputeHash(
                PointerUtils.PointerToByteArray(InputBuffer + 4, Size)
                );

            Marshal.Copy(Sha1Hash, 0, new IntPtr(OutputBuffer), Sha1Hash.Length);

            return(KIRK_OPERATION_SUCCESS);
        }
Exemple #3
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="key"></param>
        /// <param name="input"></param>
        /// <param name="output"></param>
        /// <param name="size"></param>
        public static void DecryptAes(byte[] key, byte *input, byte *output, int size)
        {
            var inputArray  = PointerUtils.PointerToByteArray(input, size);
            var outputArray = DecryptAes(inputArray, key);

            PointerUtils.ByteArrayToPointer(outputArray, output);
        }
Exemple #4
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="outbuff"></param>
        /// <param name="inbuff"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        public void kirk_CMD7(byte *outbuff, byte *inbuff, int size)
        {
            check_initialized();

            var header = (KirkAes128CbcHeader *)inbuff;

            if (header->Mode != KirkMode.DecryptCbc)
            {
                throw (new KirkException(ResultEnum.PspKirkInvalidMode));
            }
            if (header->Datasize == 0)
            {
                throw (new KirkException(ResultEnum.PspKirkDataSizeIsZero));
            }

#if USE_DOTNET_CRYPTO
            var Output = DecryptAes(
                PointerUtils.PointerToByteArray(inbuff + sizeof(KIRK_AES128CBC_HEADER), size),
                _kirk_4_7_get_key(Header->KeySeed)
                );

            PointerUtils.ByteArrayToPointer(Output, outbuff);
#else
            kirk_4_7_get_key(header->KeySeed, (key) =>
            {
                //Set the key
                Crypto.AesCtx aesKey;
                Crypto.AES_set_key(&aesKey, key, 128);

                Crypto.AES_cbc_decrypt(&aesKey, inbuff + sizeof(KirkAes128CbcHeader), outbuff, size);
            });
#endif
        }
Exemple #5
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="outbuff"></param>
        /// <param name="inbuff"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        public void kirk_CMD7(byte *outbuff, byte *inbuff, int size)
        {
            check_initialized();

            var Header = (KIRK_AES128CBC_HEADER *)inbuff;

            if (Header->Mode != KirkMode.DecryptCbc)
            {
                throw (new KirkException(ResultEnum.PSP_KIRK_INVALID_MODE));
            }
            if (Header->Datasize == 0)
            {
                throw (new KirkException(ResultEnum.PSP_KIRK_DATA_SIZE_IS_ZERO));
            }

#if USE_DOTNET_CRYPTO
            var Output = DecryptAes(
                PointerUtils.PointerToByteArray(inbuff + sizeof(KIRK_AES128CBC_HEADER), size),
                _kirk_4_7_get_key(Header->KeySeed)
                );

            PointerUtils.ByteArrayToPointer(Output, outbuff);
#else
            kirk_4_7_get_key(Header->KeySeed, (key) =>
            {
                //Set the key
                Crypto.AES_ctx aesKey;
                Crypto.AES_set_key(&aesKey, key, 128);

                Crypto.AES_cbc_decrypt(&aesKey, inbuff + sizeof(KIRK_AES128CBC_HEADER), outbuff, size);
            });
#endif
        }
Exemple #6
0
        public int sceNetAdhocMatchingSetHelloOpt(Matching Matching, int DataLength, byte *DataPointer)
        {
            var Data = PointerUtils.PointerToByteArray(DataPointer, DataLength);

            Matching.SetHelloOpt(Data);
            return(0);
        }
Exemple #7
0
        public int sceMpegQueryStreamSize(byte *pmfHeader, out uint size)
        {
            var pmf = new Pmf().Load(new MemoryStream(PointerUtils.PointerToByteArray(pmfHeader, 2048)));

            size = pmf.Header.StreamSize;
            //*Size = 0;
            return(0);
        }
 public int sceMp3NotifyAddStreamData(Mp3Stream Mp3Stream, int Size)
 {
     Mp3Stream.AddStreamData(
         PointerUtils.PointerToByteArray(
             (byte *)Mp3Stream.Mp3Arguments->Mp3BufferPointer.GetPointer(Memory, Size), Size)
         );
     return(0);
 }
Exemple #9
0
 public int sceKernelUtilsSha1Digest(byte *Data, uint Size, byte *Digest)
 {
     PointerUtils.Memcpy(
         Digest,
         SHA1.Create().ComputeHash(PointerUtils.PointerToByteArray(Data, (int)Size)),
         20
         );
     return(0);
 }
        public Font sceFontOpenUserMemory(FontLibrary FontLibrary, byte *MemoryFontAddress, int MemoryFontLength,
                                          uint *ErrorCode)
        {
            var MemoryFont = PointerUtils.PointerToByteArray(MemoryFontAddress, MemoryFontLength);
            var PGF        = new Pgf().Load(new MemoryStream(MemoryFont));
            var Font       = new Font(FontLibrary, PGF);

            *ErrorCode = 0;
            return(Font);
        }
Exemple #11
0
        public int sceMpegQueryStreamOffset(SceMpegPointer *mpegPointer, byte *pmfHeader, out uint offset)
        {
            var pmf = new Pmf().Load(new MemoryStream(PointerUtils.PointerToByteArray(pmfHeader, 2048)));

            var mpeg    = GetMpeg(mpegPointer);
            var sceMpeg = mpegPointer->GetSceMpeg(Memory);

            mpeg.ParsePmfHeader(pmfHeader);
            sceMpeg->StreamSize = (int)(uint)pmf.Header.StreamSize;

            offset = pmf.Header.StreamOffset;
            return(0);
        }
Exemple #12
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="Out"></param>
        /// <param name="OutSize"></param>
        /// <param name="In"></param>
        /// <param name="InSize"></param>
        /// <param name="Command"></param>
        /// <param name="DoChecks"></param>
        /// <returns></returns>
        public ResultEnum hleUtilsBufferCopyWithRange(byte *Out, int OutSize, byte *In, int InSize, CommandEnum Command, ref byte[] ReturnBytes, bool DoChecks = true)
        {
            try
            {
                switch (Command)
                {
                case CommandEnum.PSP_KIRK_CMD_DECRYPT_PRIVATE: kirk_CMD1(Out, In, InSize, DoChecks); break;

                case CommandEnum.PSP_KIRK_CMD_ENCRYPT: kirk_CMD4(Out, In, InSize); break;

                case CommandEnum.PSP_KIRK_CMD_ENCRYPT_FUSE: kirk_CMD5(Out, In, InSize); break;

                case CommandEnum.PSP_KIRK_CMD_DECRYPT: kirk_CMD7(Out, In, InSize); break;

                case CommandEnum.PSP_KIRK_CMD_DECRYPT_FUSE: executeKIRKCmd8(Out, In, InSize); break;

                case CommandEnum.PSP_KIRK_CMD_PRIV_SIG_CHECK: kirk_CMD10(In, InSize); break;

                case CommandEnum.PSP_KIRK_CMD_SHA1_HASH: KirkSha1(Out, In, InSize); break;

                case CommandEnum.PSP_KIRK_CMD_ECDSA_GEN_KEYS: executeKIRKCmd12(Out, OutSize); break;

                case CommandEnum.PSP_KIRK_CMD_ECDSA_MULTIPLY_POINT: executeKIRKCmd13(Out, OutSize, In, InSize); break;

                case CommandEnum.PSP_KIRK_CMD_PRNG:
                    kirk_CMD14(Out, InSize);
                    Console.WriteLine("Output:");
                    ArrayUtils.HexDump(PointerUtils.PointerToByteArray(Out, 0x10));
                    ReturnBytes = PointerUtils.PointerToByteArray(Out, 0x10);
                    Console.WriteLine("LOADADDR:{0:X8}", ((uint *)Out)[0]);
                    Console.WriteLine("BLOCKSIZE:{0:X8}", ((uint *)Out)[1]);
                    Console.WriteLine("ENTRY:{0:X8}", ((uint *)Out)[2]);
                    Console.WriteLine("CHECKSUM:{0:X8}", ((uint *)Out)[3]);
                    break;

                case CommandEnum.PSP_KIRK_CMD_ECDSA_SIGN: executeKIRKCmd16(Out, OutSize, In, InSize); break;

                case CommandEnum.PSP_KIRK_CMD_ECDSA_VERIFY: executeKIRKCmd17(In, InSize); break;

                default: throw(new KirkException(ResultEnum.PSP_KIRK_INVALID_OPERATION));
                }

                return(ResultEnum.OK);
            }
            catch (KirkException KirkException)
            {
                return(KirkException.Result);
            }
        }
        public int sceZlibDecompress(byte *OutBuffer, int OutBufferLength, byte *InBuffer, uint *Crc32Addr)
        {
            var InStream  = new PointerStream(InBuffer);
            var OutStream = new PointerStream(OutBuffer, OutBufferLength);

            _Decompress(InStream, OutStream);

            var OutLength = (int)OutStream.Position;

            if (Crc32Addr != null)
            {
                *Crc32Addr = Crc32.Compute(PointerUtils.PointerToByteArray(OutBuffer, OutLength));
            }

            return(OutLength);
        }
 public void WriteData(void *DataPointer, int DataLength)
 {
     Console.Out.WriteLineColored(ConsoleColor.Cyan, "{0}: {1}", new IntPtr(DataPointer), DataLength);
     try
     {
         var Data = PointerUtils.PointerToByteArray((byte *)DataPointer, DataLength);
         if (DumpStreams)
         {
             FileUtils.CreateAndAppendStream(@"c:\isos\psp\out\mpeg.stream", new MemoryStream(Data));
         }
         MpegStream.WriteBytes(Data);
     }
     catch (Exception Exception)
     {
         Console.Error.WriteLineColored(ConsoleColor.Red, "{0}", Exception);
     }
 }
Exemple #15
0
        /// <summary>
        /// Cypher-Block Chaining decoding.
        /// Master decryption command, used by firmware modules. Applies CMAC checking.
        /// </summary>
        /// <param name="outbuff"></param>
        /// <param name="inbuff"></param>
        /// <param name="size"></param>
        /// <param name="do_check"></param>
        /// <returns></returns>
        public void kirk_CMD1(byte *outbuff, byte *inbuff, int size, bool do_check = true)
        {
            fixed(Crypto.AES_ctx *aes_kirk1_ptr = &_aes_kirk1)
            {
                check_initialized();
                var header = (AES128CMACHeader *)inbuff;

                if (header->Mode != KirkMode.Cmd1)
                {
                    throw (new KirkException(ResultEnum.PSP_KIRK_INVALID_MODE));
                }

                header_keys keys;                 //0-15 AES key, 16-31 CMAC key

#if USE_DOTNET_CRYPTO
                DecryptAes(kirk1_key, inbuff, (byte *)&keys, 16 * 2);                //decrypt AES & CMAC key to temp buffer
#else
                Crypto.AES_cbc_decrypt(aes_kirk1_ptr, inbuff, (byte *)&keys, 16 * 2);
#endif

                //AES.CreateDecryptor(

                // HOAX WARRING! I have no idea why the hash check on last IPL block fails, so there is an option to disable checking
                if (do_check)
                {
                    kirk_CMD10(inbuff, size);
                }

                //var AES = new RijndaelManaged();

#if USE_DOTNET_CRYPTO
                DecryptAes(
                    PointerUtils.PointerToByteArray(keys.AES, 16),
                    inbuff + sizeof(AES128CMACHeader) + header->DataOffset,
                    outbuff,
                    header->DataSize
                    );
#else
                Crypto.AES_ctx k1;
                Crypto.AES_set_key(&k1, keys.AES, 128);

                Crypto.AES_cbc_decrypt(&k1, inbuff + sizeof(AES128CMACHeader) + header->DataOffset, outbuff, header->DataSize);
#endif
            }
        }
Exemple #16
0
        public void TestEncodeUnoptimizedWhiteAlpha()
        {
            var Block = default(DXT5.AlphaColorBlock);

            Block.EncodeSimpleUnoptimizedWhiteAlpha(
                new ARGB_Rev[] {
                Color.FromArgb(0xFF, 0xFF, 0xFF, 0xFF),                         // 0
                Color.FromArgb(0x77, 0xFF, 0xFF, 0xFF),                         // 1
                Color.FromArgb(0x33, 0xFF, 0xFF, 0xFF),                         // 2
                Color.FromArgb(0x77, 0xFF, 0xFF, 0xFF),                         // 3
                Color.FromArgb(0xFF, 0xFF, 0xFF, 0xFF),                         // 4
                Color.FromArgb(0x33, 0xFF, 0xFF, 0xFF),                         // 5
                Color.FromArgb(0xFF, 0xFF, 0xFF, 0xFF),                         // 6
                Color.FromArgb(0x00, 0xFF, 0xFF, 0xFF),                         // 7
                Color.FromArgb(0x77, 0xFF, 0xFF, 0xFF),                         // 8
                Color.FromArgb(0x77, 0xFF, 0xFF, 0xFF),                         // 9
                Color.FromArgb(0x55, 0xFF, 0xFF, 0xFF),                         // 10
                Color.FromArgb(0x77, 0xFF, 0xFF, 0xFF),                         // 11
                Color.FromArgb(0xFF, 0xFF, 0xFF, 0xFF),                         // 12
                Color.FromArgb(0x77, 0xFF, 0xFF, 0xFF),                         // 13
                Color.FromArgb(0xAA, 0xFF, 0xFF, 0xFF),                         // 14
                Color.FromArgb(0x77, 0xFF, 0xFF, 0xFF),                         // 15
            }
                );

            var Blocks = new[] { Block };

            byte[] Bytes;

            fixed(DXT5.AlphaColorBlock *Pointer = &Blocks[0])
            {
                Bytes = PointerUtils.PointerToByteArray((byte *)Pointer, 16);
            }

            Assert.AreEqual(
                "00-FF-8B-E8-AD-23-B2-8B-FF-FF-FF-FF-00-00-00-00",
                BitConverter.ToString(Bytes)
                );

            //var Bitmap = (new DXT5()).LoadSwizzled2D(File.OpenRead("../../../TestInput/FONTTEX05.TXV.mod.TXV"), 2048, 2048);
            //Bitmap.Save("../../../Lol.png");
        }
        /// <summary>
        /// Creates a SHA1 Hash
        ///
        /// Command: 11, 0xB
        /// </summary>
        /// <param name="outputBuffer"></param>
        /// <param name="inputBuffer"></param>
        /// <param name="inputSize"></param>
        /// <returns></returns>
        public void KirkSha1(byte *outputBuffer, byte *inputBuffer, int inputSize)
        {
            //CheckInitialized();

            var header = (KirkSha1Header *)inputBuffer;

            if (inputSize == 0 || header->DataSize == 0)
            {
                throw(new KirkException(ResultEnum.PspKirkDataSizeIsZero));
            }

            //Size <<= 4;
            //Size >>= 4;
            inputSize &= 0x0FFFFFFF;
            inputSize  = (inputSize < header->DataSize) ? inputSize : header->DataSize;

            var sha1Hash = Sha1(
                PointerUtils.PointerToByteArray(inputBuffer + 4, inputSize)
                );

            PointerUtils.Memcpy(outputBuffer, sha1Hash, sha1Hash.Length);
        }
Exemple #18
0
        /// <summary>
        /// Creates a SHA1 Hash
        ///
        /// Command: 11, 0xB
        /// </summary>
        /// <param name="OutputBuffer"></param>
        /// <param name="InputBuffer"></param>
        /// <param name="InputSize"></param>
        /// <returns></returns>
        public void KirkSha1(byte *OutputBuffer, byte *InputBuffer, int InputSize)
        {
            check_initialized();

            var Header = (KIRK_SHA1_HEADER *)InputBuffer;

            if (InputSize == 0 || Header->DataSize == 0)
            {
                throw(new KirkException(ResultEnum.PSP_KIRK_DATA_SIZE_IS_ZERO));
            }

            //Size <<= 4;
            //Size >>= 4;
            InputSize &= 0x0FFFFFFF;
            InputSize  = (InputSize < Header->DataSize) ? InputSize : Header->DataSize;

            var Sha1Hash = Sha1(
                PointerUtils.PointerToByteArray(InputBuffer + 4, InputSize)
                );

            Marshal.Copy(Sha1Hash, 0, new IntPtr(OutputBuffer), Sha1Hash.Length);
        }
Exemple #19
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="iplData"></param>
        /// <param name="outputStream"></param>
        /// <param name="toMemoryAddress"></param>
        /// <returns></returns>
        public static IplInfo DecryptIplToMemory(byte[] iplData, Stream outputStream, bool toMemoryAddress = true)
        {
            var buffer  = new byte[0x1000];
            var iplInfo = default(IplInfo);

            //ArrayUtils.HexDump(IplData);

            fixed(byte *iplPtr = iplData)
            fixed(byte *bufferPtr = buffer)
            {
                for (var n = 0; n < iplData.Length; n += 0x1000)
                {
                    var ptr = iplPtr + n;

                    var header = *(Kirk.Aes128CmacHeader *)ptr;
                    //Console.WriteLine(Header.DataSize);
                    var kirk = new Kirk();
                    kirk.kirk_init();
                    kirk.kirk_CMD1(bufferPtr, ptr, 0x1000, doCheck: false);
                    var iplBlock = *(IplBlock *)bufferPtr;
                    //Console.WriteLine(IplBlock.ToStringDefault());
                    if (toMemoryAddress)
                    {
                        outputStream.Position = iplBlock.LoadAddress;
                        Console.WriteLine("IplBlock.LoadAddress: 0x{0:X8}", iplBlock.LoadAddress);
                    }
                    outputStream.WriteBytes(PointerUtils.PointerToByteArray(&iplBlock.BlockData,
                                                                            (int)iplBlock.BlockSize));
                    if (iplBlock.EntryFunction != 0)
                    {
                        iplInfo.EntryFunction = iplBlock.EntryFunction;
                    }
                }
            }

            return(iplInfo);
        }
Exemple #20
0
        /// <summary>
        /// Cypher-Block Chaining decoding.
        /// Master decryption command, used by firmware modules. Applies CMAC checking.
        /// </summary>
        /// <param name="outbuff"></param>
        /// <param name="inbuff"></param>
        /// <param name="size"></param>
        /// <param name="doCheck"></param>
        /// <returns></returns>
        public void kirk_CMD1(byte *outbuff, byte *inbuff, int size, bool doCheck = true)
        {
            fixed(Crypto.AesCtx *aesKirk1Ptr = &_aesKirk1)
            {
                check_initialized();
                var header = *(Aes128CmacHeader *)inbuff;

                if (header.Mode != KirkMode.Cmd1)
                {
                    //Console.Error.WriteLine("ResultEnum.PSP_KIRK_INVALID_MODE");
                    Console.Error.WriteLine("{0}", header.ToStringDefault(true));
                    Console.WriteLine("Input:");
                    ArrayUtils.HexDump(PointerUtils.PointerToByteArray(inbuff, 0x100));
                    Console.WriteLine("Output:");
                    ArrayUtils.HexDump(PointerUtils.PointerToByteArray(outbuff, 0x100));
                    throw (new KirkException(ResultEnum.PspKirkInvalidMode,
                                             $"Expected mode Cmd1 but found {header.Mode}"));
                }

                Console.WriteLine("Input:");
                ArrayUtils.HexDump(PointerUtils.PointerToByteArray(inbuff, 0x100));

                //Console.WriteLine("header.DataOffset = 0x{0:X8}", header.DataOffset);
                //Console.WriteLine("header.DataSize = 0x{0:X8}", header.DataSize);

                // Decrypts AES and CMAC keys.

                HeaderKeys keys; //0-15 AES key, 16-31 CMAC key

#if USE_DOTNET_CRYPTO
                DecryptAes(kirk1_key, inbuff, (byte *)&keys, 16 * 2);                //decrypt AES & CMAC key to temp buffer
#else
                Crypto.AES_cbc_decrypt(aesKirk1Ptr, inbuff, (byte *)&keys, 16 * 2);
#endif

                // HOAX WARRING! I have no idea why the hash check on last IPL block fails, so there is an option to disable checking
                if (doCheck)
                {
                    kirk_CMD10(inbuff, size);
                }

                //var AES = new RijndaelManaged();

#if USE_DOTNET_CRYPTO
                DecryptAes(
                    PointerUtils.PointerToByteArray(keys.AES, 16),
                    inbuff + sizeof(AES128CMACHeader) + header->DataOffset,
                    outbuff,
                    header->DataSize
                    );
#else
                Crypto.AesCtx k1;
                Crypto.AES_set_key(&k1, keys.Aes, 128);

                Crypto.AES_cbc_decrypt(
                    ctx: &k1,
                    src: inbuff + sizeof(Aes128CmacHeader) + header.DataOffset,
                    dst: outbuff,
                    size: header.DataSize
                    );
#endif
            }
        }
Exemple #21
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="Input"></param>
        /// <param name="OutputMaxSize"></param>
        /// <param name="Version"></param>
        /// <returns></returns>
        public static byte[] Decode13(byte[] Input, int OutputMaxSize, int Version)
        {
            if ((Version != 1) && (Version != 3))
            {
                throw(new InvalidOperationException("Can't handle version '" + Version + "'"));
            }

            var       Output      = new byte[OutputMaxSize + 0x1000];
            bool      HasRle      = (Version == 3);
            const int WindowSize  = 0x1000;
            var       MinLength   = 3;
            int       MaxLength   = HasRle ? 0x11 : 0x12;
            var       OffsetStart = WindowSize - MaxLength;

            WritePrependData(Output, OffsetStart);

#if DEBUG_COMPRESSION
            Console.WriteLine("Decoding at 0x{0:X8}", OffsetStart);
#endif

            //File.WriteAllBytes("c:/temp/lol.bin", Input);

#if false
            Console.WriteLine("");
            Console.WriteLine("START: 0x{0:X3}", OffsetStart);
#endif

            fixed(byte *InStart = &Input[0])
            fixed(byte *OutStart = &Output[OffsetStart])
            {
                byte *InCurrent = InStart, InEnd = InStart + Input.Length;
                byte *OutCurrent = OutStart, OutEnd = OutStart + OutputMaxSize;

                uint Data = 0x001;

                while (InCurrent < InEnd)
                {
                    if (Data == 0x001)
                    {
                        Data = (uint)(*InCurrent++ | 0x100);
#if DEBUG_COMPRESSION
                        Console.WriteLine("ControlByte: 0x{0:X2}", (byte)Data);
#endif
                    }
                    bool Uncompressed = ((Data & 1) != 0); Data >>= 1;

                    // UNCOMPRESSED
                    if (Uncompressed)
                    {
#if DEBUG_COMPRESSION
                        Console.WriteLine("{0:X8}: BYTE(0x{1:X2})", (OutCurrent - OutStart) + OffsetStart, *InCurrent);
#endif
                        *OutCurrent++ = *InCurrent++;
                    }
                    // COMPRESSED
                    else
                    {
                        int Byte1        = *InCurrent++;
                        int Byte2        = *InCurrent++;
                        var WindowOffset = Byte1 | ((Byte2 & 0xF0) << 4);
                        var Length       = (Byte2 & 0x0F) + MinLength;

                        // RLE
                        if (HasRle && Length > MaxLength)
                        {
                            int  RleLength;
                            byte RleByte;

                            /*
                             * if ((WindowOffset >> 8) == 0)
                             * {
                             *      RleByte = (byte)(*InCurrent++);
                             *      RleLength = (WindowOffset & 0xFF) + MaxLength + 1 + 1;
                             * }
                             * else
                             * {
                             *      RleByte = (byte)(WindowOffset & 0xFF);
                             *      RleLength = (WindowOffset >> 8) + MinLength;
                             * }
                             */

                            //int Type;
                            if (WindowOffset < 0x100)
                            {
                                //Type = 1;
                                RleByte   = *InCurrent++;
                                RleLength = WindowOffset + MaxLength + 1 + 1;
                            }
                            else
                            {
                                //Type = 0;
                                RleByte   = (byte)WindowOffset;
                                RleLength = (WindowOffset >> 8) + MinLength;
                            }

#if DEBUG_COMPRESSION
                            Console.WriteLine("{0:X8}: RLE(Byte: 0x{1:X2}, Length: {2}, Type: {3})", (OutCurrent - OutStart) + OffsetStart, RleByte, RleLength, Type);
#endif

                            PointerUtils.Memset(OutCurrent, RleByte, RleLength);
                            OutCurrent += RleLength;
                        }
                        // LZ
                        else
                        {
                            //int CurrentWindowPos = (OffsetStart + (int)(OutCurrent - OutStart)) % WindowSize;
                            //int MinusDisp = (CurrentWindowPos - WindowOffset + WindowSize) % WindowSize;

                            int MinusDisp = ((OffsetStart + (int)(OutCurrent - OutStart)) - WindowOffset + WindowSize) % WindowSize;
                            if (MinusDisp == 0)
                            {
                                MinusDisp = WindowSize;
                            }

#if false
                            Console.WriteLine(
                                "LZ(0x{0:X3}, {1}) : CUR:0x{2:X3} : MIN:{3}",
                                WindowOffset, Length, CurrentWindowPos, -MinusDisp
                                );
#endif

                            //SourcePointer = (OutCurrent - WindowSize) + (WindowOffset + Offset) % WindowSize;
                            PointerUtils.Memcpy(OutCurrent, (OutCurrent - MinusDisp), Length);

#if DEBUG_COMPRESSION
                            Console.WriteLine("{0:X8}: LZ(Offset: {1}, Length: {2})", (OutCurrent - OutStart) + OffsetStart, -MinusDisp, Length);
                            for (int n = 0; n < Length; n++)
                            {
                                Console.WriteLine("  {0:X8}: 0x{1:X2}", (OutCurrent - OutStart) + OffsetStart - MinusDisp + n, OutCurrent[-MinusDisp + n]);
                            }
#endif

                            OutCurrent += Length;
                        }
                    }
                }
                return(PointerUtils.PointerToByteArray(OutStart, (int)(OutCurrent - OutStart)));
            }
        }
Exemple #22
0
 public int sceNetAdhocMatchingSendData(Matching Matching, ref MacAddress MacAddress, int DataLength,
                                        byte *DataPointer)
 {
     Matching.SendData(MacAddress, PointerUtils.PointerToByteArray(DataPointer, DataLength));
     return(0);
 }
Exemple #23
0
 public int sceNetAdhocMatchingCancelTargetWithOpt(Matching Matching, ref MacAddress MacAddress, int DataLength,
                                                   byte *DataPointer)
 {
     Matching.CancelTarget(MacAddress, PointerUtils.PointerToByteArray(DataPointer, DataLength));
     return(0);
 }
Exemple #24
0
        public void Transfer(Dma.Direction direction, int size, DmaEnum address, ref uint value)
        {
            switch (address)
            {
            case DmaEnum.KIRK_PATTERN:
                value = 1;
                break;

            case DmaEnum.KIRK_COMMAND:
                TransferUtils.Transfer(direction, ref _kirkCommand, ref value);
                break;

            case DmaEnum.KIRK_RESULT:
                TransferUtils.Transfer(direction, ref _kirkResult, ref value);
                break;

            case DmaEnum.KIRK_SOURCE_ADDRESS:
                TransferUtils.Transfer(direction, ref _kirkSource, ref value);
                break;

            case DmaEnum.KIRK_DESTINATION_ADDRESS:
                TransferUtils.Transfer(direction, ref _kirkDestination, ref value);
                break;

            case DmaEnum.KIRK_START:
                if (_kirkCommand != 1)
                {
                    throw new NotImplementedException();
                }

                var sourcePtr      = (byte *)Memory.PspAddressToPointerSafe(_kirkSource);
                var destinationPtr = (byte *)Memory.PspAddressToPointerSafe(_kirkDestination);

                //var Out = new byte[10000];

                //fixed (byte* OutPtr = Out)
                {
                    //DestinationPtr = OutPtr;
                    Console.WriteLine("Input:");
                    ArrayUtils.HexDump(PointerUtils.PointerToByteArray(sourcePtr, 0x200));

                    /*
                     * try
                     * {
                     *  Kirk.kirk_CMD1(DestinationPtr, SourcePtr, -1, true);
                     *  this.KirkResult = (uint)Kirk.ResultEnum.OK;
                     * }
                     * catch (Kirk.KirkException KirkException)
                     * {
                     *  this.KirkResult = (uint)KirkException.Result;
                     *  Console.Error.WriteLine("Kirk.KirkException : {0}", KirkException);
                     * }
                     */

                    this._kirkResult = (uint)Kirk.SceUtilsBufferCopyWithRange(destinationPtr, -1, sourcePtr, -1, 1);

                    Console.WriteLine("Output:");
                    ArrayUtils.HexDump(PointerUtils.PointerToByteArray(destinationPtr, 0x200));
                    Console.WriteLine("LOADADDR:{0:X8}", ((uint *)destinationPtr)[0]);
                    Console.WriteLine("BLOCKSIZE:{0:X8}", ((uint *)destinationPtr)[1]);
                    Console.WriteLine("ENTRY:{0:X8}", ((uint *)destinationPtr)[2]);
                    Console.WriteLine("CHECKSUM:{0:X8}", ((uint *)destinationPtr)[3]);
                }

                //Thread.Sleep(4);
                break;
            }
        }
Exemple #25
0
 public byte[] GetAddressBytes()
 {
     fixed(byte *DataPointer = Data) return(PointerUtils.PointerToByteArray(DataPointer, 8));
 }
Exemple #26
0
        public void LoadTest()
        {
            var pmf = new Pmf();

            //Pmf.Load(File.OpenRead("../../../TestInput/test.pmf"));
            //Pmf.Load(File.OpenRead("../../../TestInput/sample.pmf"));
            pmf.Load(File.OpenRead("c:/isos/psp/op.pmf"));
            //Console.WriteLine(Pmf.InfoHeader.ToStringDefault());

            //Assert.Equal(0x800, Pmf.Header.StreamOffset);
            //Assert.Equal(137216, Pmf.Header.StreamSize);
            //Assert.Equal(144, Pmf.InfoHeader.Width);
            //Assert.Equal(80, Pmf.InfoHeader.Height);

            var mpegPs = pmf.GetMpegPs();
            // ReSharper disable once UnusedVariable
            var pmfWidth = pmf.InfoHeader.Width;
            // ReSharper disable once UnusedVariable
            var pmfHeight = pmf.InfoHeader.Height;

            var videoOutStream = new ProduceConsumerBufferStream();
            var audioOutStream = new ProduceConsumerBufferStream();

            try
            {
                while (mpegPs.HasMorePackets)
                {
                    var packet = mpegPs.ReadPacketizedElementaryStreamHeader();
                    var info   = mpegPs.ParsePacketizedStream(packet.Stream);

                    if (packet.Type == MpegPsDemuxer.ChunkType.ST_Video1)
                    {
                        info.Stream.CopyToFast(videoOutStream);
                    }
                    if (packet.Type == MpegPsDemuxer.ChunkType.ST_Private1)
                    {
                        //Console.WriteLine(Info.dts);
                        //Info
                        var channel = info.Stream.ReadByte();
                        info.Stream.Skip(3);
                        if (channel >= 0xB0 && channel <= 0xBF)
                        {
                            info.Stream.Skip(1);
                        }

                        //Info.Stream.Skip(8);
                        info.Stream.CopyToFast(audioOutStream);
                    }

                    //if (VideoOutStream.Length >= 1 * 1024 * 1024) break;
                    //Console.WriteLine(Packet.Type);
                }
            }
            catch (EndOfStreamException)
            {
            }

            var at3Data = audioOutStream.ReadAll();

            File.WriteAllBytes(@"c:\isos\psp\out\audio.raw", at3Data);
            fixed(byte *at3DataPtr = at3Data)
            {
                var at3Ptr = at3DataPtr;
                // ReSharper disable once UnusedVariable
                var at3End = &at3DataPtr[at3Data.Length];
                var maiAt3PlusFrameDecoder = new MaiAt3PlusFrameDecoder();
                var frame = 0;

                for (int n = 0; n < 1000; n++, frame++)
                {
                    var frameSize = (*(UshortBe *)&at3Ptr[2] & 0x3FF) * 8 + 8;
                    at3Ptr += 8;
                    //Console.WriteLine(FrameSize);

                    var     channels = 0;
                    short[] samplesData;
                    File.WriteAllBytes(@"c:\isos\psp\out\samples" + frame + ".in",
                                       new MemoryStream().WriteBytes(PointerUtils.PointerToByteArray(at3Ptr, frameSize)).ToArray());
                    Console.WriteLine("{0}, {1}, {2}", 0, channels, frameSize);
                    // ReSharper disable once UnusedVariable
                    var Out = maiAt3PlusFrameDecoder.DecodeFrame(at3Ptr, frameSize, out channels, out samplesData);
                    //Console.WriteLine("{0}, {1}, {2}", Out, channels, FrameSize);
                    File.WriteAllBytes(@"c:\isos\psp\out\samples" + frame + ".out",
                                       new MemoryStream().WriteStructVector(samplesData).ToArray());
                    at3Ptr += frameSize;
                }
            }

            /*
             * return;
             *
             * //FileUtils.CreateAndAppendStream(@"c:/isos/psp/out/opening.h264", VideoOutStream.Slice());
             * //FileUtils.CreateAndAppendStream(@"c:/isos/psp/out/opening.at3", AudioOutStream.Slice());
             *
             * //return;
             * //
             * //VideoOutStream.Slice().CopyToFile(@"c:/isos/psp/opening.h264");
             * //AudioOutStream.Slice().CopyToFile(@"c:/isos/psp/opening.at3");
             * //
             *
             * //var AudioDecoder = new At3pFrameDecoder(AudioOutStream.Slice());
             * //FrameNumber = 0;
             * //while (AudioDecoder.HasMorePackets)
             * //{
             * //	var AudioFrame = AudioDecoder.DecodeFrame();
             * //	var Stream = new MemoryStream();
             * //	Stream.WriteStructVector(AudioFrame);
             * //	File.WriteAllBytes(@"c:\isos\psp\samples" + (FrameNumber++) + ".raw", Stream.ToArray());
             * //	//Console.WriteLine(AudioFrame);
             * //}
             *
             * //var Data = AudioOutStream2.ReadBytes((int)2048);
             * //int BlockSize = Data.Length;
             * //short[] buf;
             * //int channels;
             * //fixed (byte* DataPtr = Data)
             * //{
             * //	int Decoded = MaiAT3PlusFrameDecoder.decodeFrame(DataPtr, BlockSize, out channels, out buf);
             * //	Console.WriteLine("[1] : {0} : {1} : {2}", channels, BlockSize, Decoded);
             * //}
             *
             *
             * //return;
             *
             * var sample5Reference = new Bitmap(Image.FromFile("../../../TestInput/sample_5.png"));
             *
             * var frameDecoder = new H264FrameDecoder(videoOutStream);
             * frameNumber = 0;
             * while (frameDecoder.HasMorePackets)
             * {
             *  var frame = frameDecoder.DecodeFrame();
             *  //Console.WriteLine(Frame.imageWidth);
             *  //Console.WriteLine(Frame.imageWidthWOEdge);
             *  //Console.WriteLine(Frame.imageHeight);
             *  //Console.WriteLine(Frame.imageHeightWOEdge);
             *  if (frameNumber <= 70)
             *  {
             *      if (frameNumber == 70)
             *      {
             *          var sample5Output = FrameUtils.imageFromFrameWithoutEdges(frame, pmfWidth, pmfHeight);
             *          sample5Output.Save(@"c:\isos\psp\out\frame_" + (frameNumber) + ".png");
             *          var compareResult = BitmapUtils.CompareBitmaps(sample5Reference, sample5Output);
             *      }
             *  }
             *  else
             *  {
             *      break;
             *  }
             *  frameNumber++;
             * }
             */
        }