Ejemplo n.º 1
0
        public bool IsGZipped(BlobKey key)
        {
            int      magic = 0;
            string   path  = PathForKey(key);
            FilePath file  = new FilePath(path);

            if (file.CanRead())
            {
                try
                {
                    var raf = new RandomAccessFile(file, "r");
                    magic = raf.Read() & unchecked ((0xff)) | ((raf.Read() << 8) & unchecked ((0xff00)));
                    raf.Close();
                }
                catch (Exception e)
                {
                                        #if PORTABLE
                    Runtime.PrintStackTrace(e);
                                        #else
                    Runtime.PrintStackTrace(e, Console.Error);
                                        #endif
                }
            }
            return(magic == GZIPInputStream.GzipMagic);
        }
        /// <exception cref="System.IO.IOException"/>
        protected internal override sbyte GetByte(int index)
        {
            if (index != _currentIndex)
            {
                Seek(index);
            }
            int b = _file.Read();

            if (b < 0)
            {
                throw new BufferBoundsException("Unexpected end of file encountered.");
            }
            System.Diagnostics.Debug.Assert((b <= unchecked ((int)(0xff))));
            _currentIndex++;
            return(unchecked ((sbyte)b));
        }
Ejemplo n.º 3
0
        private bool findSPSandPPS()
        {
            /*
             *  SPS and PPS parameters are stored in the avcC box
             *  You may find really useful information about this box
             *  in the document ISO-IEC 14496-15, part 5.2.4.1.1
             *  The box's structure is described there
             *  <pre>
             *  aligned(8) class AVCDecoderConfigurationRecord {
             *		unsigned int(8) configurationVersion = 1;
             *		unsigned int(8) AVCProfileIndication;
             *		unsigned int(8) profile_compatibility;
             *		unsigned int(8) AVCLevelIndication;
             *		bit(6) reserved = ‘111111’b;
             *		unsigned int(2) lengthSizeMinusOne;
             *		bit(3) reserved = ‘111’b;
             *		unsigned int(5) numOfSequenceParameterSets;
             *		for (i=0; i< numOfSequenceParameterSets; i++) {
             *			unsigned int(16) sequenceParameterSetLength ;
             *			bit(8*sequenceParameterSetLength) sequenceParameterSetNALUnit;
             *		}
             *		unsigned int(8) numOfPictureParameterSets;
             *		for (i=0; i< numOfPictureParameterSets; i++) {
             *			unsigned int(16) pictureParameterSetLength;
             *			bit(8*pictureParameterSetLength) pictureParameterSetNALUnit;
             *		}
             *	}
             *  </pre>
             */
            try {
                // TODO: Here we assume that numOfSequenceParameterSets = 1, numOfPictureParameterSets = 1 !
                // Here we extract the SPS parameter
                fis.SkipBytes(7);
                spsLength = 0xFF & fis.ReadByte();
                sps       = new byte[spsLength];
                fis.Read(sps, 0, spsLength);
                // Here we extract the PPS parameter
                fis.SkipBytes(2);
                ppsLength = 0xFF & fis.ReadByte();
                pps       = new byte[ppsLength];
                fis.Read(pps, 0, ppsLength);
            } catch (IOException e) {
                return(false);
            }

            return(true);
        }
Ejemplo n.º 4
0
        public virtual void TestWriteFully()
        {
            int InputBufferLen = 10000;
            int Halfway        = 1 + (InputBufferLen / 2);

            byte[] input = new byte[InputBufferLen];
            for (int i = 0; i < input.Length; i++)
            {
                input[i] = unchecked ((byte)(i & unchecked ((int)(0xff))));
            }
            byte[] output = new byte[input.Length];
            try
            {
                RandomAccessFile raf = new RandomAccessFile(TestFileName, "rw");
                FileChannel      fc  = raf.GetChannel();
                ByteBuffer       buf = ByteBuffer.Wrap(input);
                IOUtils.WriteFully(fc, buf);
                raf.Seek(0);
                raf.Read(output);
                for (int i_1 = 0; i_1 < input.Length; i_1++)
                {
                    Assert.Equal(input[i_1], output[i_1]);
                }
                buf.Rewind();
                IOUtils.WriteFully(fc, buf, Halfway);
                for (int i_2 = 0; i_2 < Halfway; i_2++)
                {
                    Assert.Equal(input[i_2], output[i_2]);
                }
                raf.Seek(0);
                raf.Read(output);
                for (int i_3 = Halfway; i_3 < input.Length; i_3++)
                {
                    Assert.Equal(input[i_3 - Halfway], output[i_3]);
                }
            }
            finally
            {
                FilePath f = new FilePath(TestFileName);
                if (f.Exists())
                {
                    f.Delete();
                }
            }
        }
Ejemplo n.º 5
0
 /// <exception cref="System.IO.IOException"></exception>
 private byte[] ReadAllBytes(string fileName)
 {
     var length = (int) new Sharpen.IO.File(fileName).Length();
     var raf = new RandomAccessFile(fileName, "rw");
     var buffer = new byte[length];
     raf.Read(buffer);
     raf.Close();
     return buffer;
 }
Ejemplo n.º 6
0
        public byte[] getAsBinary(string key)
        {
            RandomAccessFile raFile     = null;
            bool             removeFile = false;

            try
            {
                File file = mCache.get(key);

                if (!file.Exists())
                {
                    return(null);
                }

                raFile = new RandomAccessFile(file, "r");
                byte[] byteArray = new byte[(int)raFile.Length()];

                raFile.Read(byteArray);

                if (!Utils.isDue(byteArray))
                {
                    return(Utils.clearDateInfo(byteArray));
                }
                else
                {
                    removeFile = true;

                    return(null);
                }
            }
            catch (System.Exception ex)
            {
                VPNLog.d("ACache", ex.ToString());

                return(null);
            }
            finally
            {
                if (raFile != null)
                {
                    try
                    {
                        raFile.Dispose();
                    }
                    catch (IOException ex)
                    {
                        ex.PrintStackTrace();
                    }
                }

                if (removeFile)
                {
                    remove(key);
                }
            }
        }
Ejemplo n.º 7
0
        /// <exception cref="System.IO.IOException"></exception>
        private byte[] ReadAllBytes(string fileName)
        {
            var length = (int)new Sharpen.IO.File(fileName).Length();
            var raf    = new RandomAccessFile(fileName, "rw");
            var buffer = new byte[length];

            raf.Read(buffer);
            raf.Close();
            return(buffer);
        }
 /// <exception cref="Db4objects.Db4o.Ext.Db4oIOException"></exception>
 public override int Read(byte[] bytes, int length)
 {
     try
     {
         return(_delegate.Read(bytes, 0, length));
     }
     catch (IOException e)
     {
         throw new Db4oIOException(e);
     }
 }
Ejemplo n.º 9
0
        public bool IsGZipped(BlobKey key)
        {
            var magic = 0;
            var path  = PathForKey(key);
            var file  = new FilePath(path);

            if (file.CanRead())
            {
                try {
                    var raf = new RandomAccessFile(file, "r");
                    magic = raf.Read() & unchecked ((0xff)) | ((raf.Read() << 8) & unchecked ((0xff00)));
                    raf.Close();
                }
                catch (Exception e) {
                    Runtime.PrintStackTrace(e, Console.Error);
                }
            }

            return(magic == 0);
        }
Ejemplo n.º 10
0
        /// <exception cref="System.IO.IOException"></exception>
        public virtual void TestLockDatabaseFileFalse()
        {
            IObjectContainer container = OpenObjectContainer(false);
            RandomAccessFile raf       = RandomAccessFileFactory.NewRandomAccessFile(TempFile(), false
                                                                                     , false);

            byte[] bytes = new byte[1];
            raf.Read(bytes);
            raf.Close();
            container.Close();
        }
Ejemplo n.º 11
0
        /// <exception cref="System.IO.IOException"></exception>
        public static byte FileHeaderVersion(string testFile)
        {
            RandomAccessFile raf = new RandomAccessFile(testFile, "r");

            byte[] bytes = new byte[1];
            raf.Read(bytes);
            // readByte() doesn't convert to .NET.
            byte db4oHeaderVersion = bytes[0];

            raf.Close();
            return(db4oHeaderVersion);
        }
Ejemplo n.º 12
0
        public virtual bool IsGZipped(BlobKey key)
        {
            int      magic = 0;
            string   path  = PathForKey(key);
            FilePath file  = new FilePath(path);

            if (file.CanRead())
            {
                try
                {
                    RandomAccessFile raf = new RandomAccessFile(file, "r");
                    magic = raf.Read() & unchecked ((int)(0xff)) | ((raf.Read() << 8) & unchecked ((int
                                                                                                    )(0xff00)));
                    raf.Close();
                }
                catch (Exception e)
                {
                    Sharpen.Runtime.PrintStackTrace(e, System.Console.Error);
                }
            }
            return(magic == GZIPInputStream.GzipMagic);
        }
Ejemplo n.º 13
0
        /// <exception cref="System.IO.IOException"/>
        private void LoadData()
        {
            Preconditions.CheckState(data == null);
            byte[] rawData = new byte[count];
            raf.Seek(dumpFileOffset);
            int size = raf.Read(rawData, 0, count);

            if (size != count)
            {
                throw new IOException("Data count is " + count + ", but read back " + size + "bytes"
                                      );
            }
            data = ByteBuffer.Wrap(rawData);
        }
        //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
        //ORIGINAL LINE: @Override public int readAt(long position, byte[] buffer, int offset, int size) throws java.io.IOException
        public int ReadAt(long position, byte[] buffer, int offset, int size)
        {
            if (mFile.FilePointer != position)
            {
                mFile.Seek(position);
            }

            if (size == 0)
            {
                return(0);
            }

            return(mFile.Read(buffer, 0, size));
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Corrupt the byte at the given offset in the given file,
        /// by subtracting 1 from it.
        /// </summary>
        /// <exception cref="System.IO.IOException"/>
        private void CorruptByteInFile(FilePath file, long offset)
        {
            RandomAccessFile raf = new RandomAccessFile(file, "rw");

            try
            {
                raf.Seek(offset);
                int origByte = raf.Read();
                raf.Seek(offset);
                raf.WriteByte(origByte - 1);
            }
            finally
            {
                IOUtils.CloseStream(raf);
            }
        }
Ejemplo n.º 16
0
 /// <exception cref="Db4objects.Db4o.Ext.Db4oIOException"></exception>
 public virtual int Read(long pos, byte[] bytes, int length)
 {
     try
     {
         Seek(pos);
         if (DTrace.enabled)
         {
             DTrace.FileRead.LogLength(pos, length);
         }
         return(_file.Read(bytes, 0, length));
     }
     catch (IOException e)
     {
         throw new Db4oIOException(e);
     }
 }
Ejemplo n.º 17
0
        public override byte[] GetServerBlob()
        {
#if SILVERLIGHT
            if (this.UseElevatedTrust)
            {
                string     filePath     = siaqodb.GetDBPath() + System.IO.Path.DirectorySeparatorChar + "anchor_" + CacheController.ControllerBehavior.ScopeName + ".anc";
                FileStream phisicalFile = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                byte[]     fullFile     = new byte[phisicalFile.Length];
                phisicalFile.Read(fullFile, 0, fullFile.Length);
                phisicalFile.Close();
                return(fullFile);
            }
            else
            {
                IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();

                IsolatedStorageFileStream phisicalFile = new IsolatedStorageFileStream(siaqodb.GetDBPath() + System.IO.Path.DirectorySeparatorChar + "anchor_" + CacheController.ControllerBehavior.ScopeName + ".anc", FileMode.OpenOrCreate, FileAccess.ReadWrite, isf);
                byte[] fullFile = new byte[phisicalFile.Length];

                phisicalFile.Read(fullFile, 0, fullFile.Length);
                phisicalFile.Close();
                return(fullFile);
            }
#elif MONODROID
            string           filePath     = siaqodb.GetDBPath() + System.IO.Path.DirectorySeparatorChar + "anchor_" + CacheController.ControllerBehavior.ScopeName + ".anc";
            RandomAccessFile phisicalFile = new RandomAccessFile(filePath, "rw");
            byte[]           fullFile     = new byte[phisicalFile.Length()];
            phisicalFile.Read(fullFile, 0, fullFile.Length);
            phisicalFile.Close();
            return(fullFile);
#else
            string     filePath     = siaqodb.GetDBPath() + System.IO.Path.DirectorySeparatorChar + "anchor_" + CacheController.ControllerBehavior.ScopeName + ".anc";
            FileStream phisicalFile = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            byte[]     fullFile     = new byte[phisicalFile.Length];
            phisicalFile.Read(fullFile, 0, fullFile.Length);
            phisicalFile.Close();
            return(fullFile);
#endif
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Read a sequence of bytes from this stream and advance the position of this stream.
        /// </summary>
        /// <param name="buffer">Destination</param>
        /// <param name="offset">Offset within the buffer</param>
        /// <param name="count">Number of bytes to read.</param>
        /// <returns>The total number of bytes read or 0 if the end of the stream has been reached.</returns>
        public override int Read(byte[] buffer, int offset, int count)
        {
            var rc = file.Read(buffer, offset, count);

            return((rc < 0) ? 0 : rc);
        }
Ejemplo n.º 19
0
 // Helper I/O functions
 int ReadByte()
 {
     return(m_file.Read() & 0xFF);
 }
Ejemplo n.º 20
0
        private void parse(System.String path, long len)
        {
            ByteBuffer byteBuffer;
            long       sum = 0, newlen = 0;

            byte[]           buffer = new byte[8];
            Java.Lang.String name   = null;

            if (!path.Equals(""))
            {
                mBoxes.Add(path, (Long)(mPos - 8));
            }

            while (sum < len)
            {
                mFile.Read(buffer, 0, 8);
                mPos += 8; sum += 8;

                if (validBoxName(buffer))
                {
                    name = new Java.Lang.String(buffer, 4, 4);

                    if (buffer[3] == 1)
                    {
                        // 64 bits atom size
                        mFile.Read(buffer, 0, 8);
                        mPos      += 8; sum += 8;
                        byteBuffer = ByteBuffer.Wrap(buffer, 0, 8);
                        newlen     = byteBuffer.GetLong() - 16;
                    }
                    else
                    {
                        // 32 bits atom size
                        byteBuffer = ByteBuffer.Wrap(buffer, 0, 4);
                        newlen     = byteBuffer.GetInt() - 8;
                    }

                    // 1061109559+8 correspond to "????" in ASCII the HTC Desire S seems to write that sometimes, maybe other phones do
                    // "wide" atom would produce a newlen == 0, and we shouldn't throw an exception because of that
                    if (newlen < 0 || newlen == 1061109559)
                    {
                        throw new IOException();
                    }

                    Log.d(TAG, "Atom -> name: " + name + " position: " + mPos + ", length: " + newlen);
                    sum += newlen;
                    parse(path + '/' + name, newlen);
                }
                else
                {
                    if (len < 8)
                    {
                        mFile.Seek(mFile.FilePointer - 8 + len);
                        sum += len - 8;
                    }
                    else
                    {
                        int skipped = mFile.SkipBytes((int)(len - 8));
                        if (skipped < ((int)(len - 8)))
                        {
                            throw new IOException();
                        }
                        mPos += len - 8;
                        sum  += len - 8;
                    }
                }
            }
        }
Ejemplo n.º 21
0
 public virtual int Read(long pos, byte[] buf)
 {
     file.Seek(pos);
     return(file.Read(buf, 0, buf.Length));
 }
Ejemplo n.º 22
0
        public byte[] getArchiveData(int id)
        {
            if (_index.getLength() < 6 * id + 6)
            {
                return(null);
            }

            _index.Seek(6 * id);
            _index.Read(_readCacheBuffer, 0, 6);

            int archiveLength = (_readCacheBuffer[2] & 0xFF) + (((0xFF & _readCacheBuffer[0]) << 16) + (_readCacheBuffer[1] << 8 & 0xFF00));

            if (archiveLength < 0 || archiveLength > 1000000)
            {
                return(null);
            }

            int sector = ((_readCacheBuffer[3] & 0xFF) << 16) - (-(0xFF00 & _readCacheBuffer[4] << 8) - (_readCacheBuffer[5] & 0xFF));

            if (sector <= 0 || _data.getLength() / 520L < sector)
            {
                return(null);
            }

            byte[] data           = new byte[archiveLength];
            int    readBytesCount = 0;
            int    part           = 0;

            while (archiveLength > readBytesCount)
            {
                if (sector == 0)
                {
                    return(null);
                }

                int dataBlockSize = archiveLength - readBytesCount;

                byte headerSize;
                int  currentIndex;
                int  currentArchive;
                int  currentPart;
                int  nextSector;

                _data.Seek(520 * sector);

                if (65535 < id && _newProtocol)                 // 2^16 - 1
                {
                    headerSize = 10;

                    if (dataBlockSize > 510)
                    {
                        dataBlockSize = 510;
                    }

                    _data.Read(_readCacheBuffer, 0, headerSize + dataBlockSize);

                    currentIndex   = _readCacheBuffer[9] & 0xFF;
                    currentArchive = ((_readCacheBuffer[1] & 0xFF) << 16) + ((_readCacheBuffer[0] & 0xFF) << 24) + ((0xFF00 & _readCacheBuffer[2] << 8) - -(_readCacheBuffer[3] & 0xFF));
                    currentPart    = ((_readCacheBuffer[4] & 0xFF) << 8) + (0xFF & _readCacheBuffer[5]);
                    nextSector     = (_readCacheBuffer[8] & 0xFF) + (0xFF00 & _readCacheBuffer[7] << 8) + ((0xFF & _readCacheBuffer[6]) << 16);
                }
                else
                {
                    headerSize = 8;

                    if (dataBlockSize > 512)
                    {
                        dataBlockSize = 512;
                    }

                    _data.Read(_readCacheBuffer, 0, headerSize + dataBlockSize);

                    currentIndex   = _readCacheBuffer[7] & 0xFF;
                    currentArchive = (0xFF & _readCacheBuffer[1]) + (0xFF00 & _readCacheBuffer[0] << 8);
                    currentPart    = ((_readCacheBuffer[2] & 0xFF) << 8) + (0xFF & _readCacheBuffer[3]);
                    nextSector     = (_readCacheBuffer[6] & 0xFF) + (0xFF00 & _readCacheBuffer[5] << 8) + ((0xFF & _readCacheBuffer[4]) << 16);
                }

                if ((_newProtocol && id != currentArchive) || currentPart != part || _id != currentIndex)
                {
                    return(null);
                }

                if (nextSector < 0 || _data.getLength() / 520L < nextSector)
                {
                    return(null);
                }

                for (int i = headerSize; dataBlockSize + headerSize > i; i++)
                {
                    data[readBytesCount++] = _readCacheBuffer[i];
                }

                part++;
                sector = nextSector;
            }

            return(data);
        }
Ejemplo n.º 23
0
 /// <exception cref="System.IO.IOException"></exception>
 protected internal override int ReadDatabase(byte[] dst, int pos, int cnt)
 {
     return(@out.Read(dst, pos, cnt));
 }
Ejemplo n.º 24
0
 // Helper I/O functions
 private int ReadByte()
 {
     return(_mFile.Read() & 0xFF);
 }
Ejemplo n.º 25
0
        /**
         * Records a short sample of AAC ADTS from the microphone to find out what the sampling rate really is
         * On some phone indeed, no error will be reported if the sampling rate used differs from the
         * one selected with setAudioSamplingRate
         * @throws IOException
         * @throws IllegalStateException
         */

        private void testADTS()
        {
            setAudioEncoder((int)Android.Media.AudioEncoder.Aac);
            try
            {
                Type mType = typeof(MediaRecorder.OutputFormat);

                if (mType.GetField("AAC_ADTS") == null)
                {
                    return;
                }

                setOutputFormat((int)Android.Media.AudioEncoder.Aac);
            }
            catch (System.Exception ignore)
            {
                setOutputFormat(6);
            }

            System.String key = PREF_PREFIX + "aac-" + mQuality.samplingRate;

            if (mSettings != null && mSettings.Contains(key))
            {
                System.String[] s = mSettings.GetString(key, "").Split(',');
                mQuality.samplingRate = (int)Integer.ValueOf(s[0]);
                mConfig  = (int)Integer.ValueOf(s[1]);
                mChannel = (int)Integer.ValueOf(s[2]);
                return;
            }

            System.String TESTFILE = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/spydroid-test.adts";

            if (!Android.OS.Environment.ExternalStorageState.Equals(Android.OS.Environment.MediaMounted))
            {
                throw new IllegalStateException("No external storage or external storage not ready !");
            }

            // The structure of an ADTS packet is described here: http://wiki.multimedia.cx/index.php?title=ADTS

            // ADTS header is 7 or 9 bytes long
            byte[] buffer = new byte[9];

            mMediaRecorder = new MediaRecorder();
            mMediaRecorder.SetAudioSource((AudioSource)mAudioSource);
            mMediaRecorder.SetOutputFormat((OutputFormat)mOutputFormat);
            mMediaRecorder.SetAudioEncoder((AudioEncoder)mAudioEncoder);
            mMediaRecorder.SetAudioChannels(1);
            mMediaRecorder.SetAudioSamplingRate(mQuality.samplingRate);
            mMediaRecorder.SetAudioEncodingBitRate(mQuality.bitRate);
            mMediaRecorder.SetOutputFile(TESTFILE);
            mMediaRecorder.SetMaxDuration(1000);
            mMediaRecorder.Prepare();
            mMediaRecorder.Start();

            // We record for 1 sec
            // TODO: use the MediaRecorder.OnInfoListener
            try
            {
                Thread.Sleep(2000);
            }
            catch (InterruptedException e) { }

            mMediaRecorder.Stop();
            mMediaRecorder.Release();
            mMediaRecorder = null;

            File             file = new File(TESTFILE);
            RandomAccessFile raf  = new RandomAccessFile(file, "r");

            // ADTS packets start with a sync word: 12bits set to 1
            while (true)
            {
                if ((raf.ReadByte() & 0xFF) == 0xFF)
                {
                    buffer[0] = (byte)raf.ReadByte();
                    if ((buffer[0] & 0xF0) == 0xF0)
                    {
                        break;
                    }
                }
            }

            raf.Read(buffer, 1, 5);

            mSamplingRateIndex    = (buffer[1] & 0x3C) >> 2;
            mProfile              = ((buffer[1] & 0xC0) >> 6) + 1;
            mChannel              = (buffer[1] & 0x01) << 2 | (buffer[2] & 0xC0) >> 6;
            mQuality.samplingRate = AUDIO_SAMPLING_RATES[mSamplingRateIndex];

            // 5 bits for the object type / 4 bits for the sampling rate / 4 bits for the channel / padding
            mConfig = (mProfile & 0x1F) << 11 | (mSamplingRateIndex & 0x0F) << 7 | (mChannel & 0x0F) << 3;

            Log.Info(TAG, "MPEG VERSION: " + ((buffer[0] & 0x08) >> 3));
            Log.Info(TAG, "PROTECTION: " + (buffer[0] & 0x01));
            Log.Info(TAG, "PROFILE: " + AUDIO_OBJECT_TYPES[mProfile]);
            Log.Info(TAG, "SAMPLING FREQUENCY: " + mQuality.samplingRate);
            Log.Info(TAG, "CHANNEL: " + mChannel);

            raf.Close();

            if (mSettings != null)
            {
                ISharedPreferencesEditor editor = mSettings.Edit();
                editor.PutString(key, mQuality.samplingRate + "," + mConfig + "," + mChannel);
                editor.Commit();
            }

            if (!file.Delete())
            {
                Log.Error(TAG, "Temp file could not be erased");
            }
        }