Esempio n. 1
0
  private int readBytes(Entry entry, byte[] buffer) throws IOException {
    byte[] header = getHeader(entry);

    // entry is not compressed?
    if (get2ByteLittleEndian(header, 8) == 0) {
      zipRandomFile.skipBytes(get2ByteLittleEndian(header, 26) + get2ByteLittleEndian(header, 28));
      int offset = 0;
      int size = buffer.length;
      while (offset < size) {
        int count = zipRandomFile.read(buffer, offset, size - offset);
        if (count == -1) break;
        offset += count;
      }
      return entry.size;
    }

    int csize = entry.compressedSize;
    byte[] cbuf = new byte[csize];
    zipRandomFile.skipBytes(get2ByteLittleEndian(header, 26) + get2ByteLittleEndian(header, 28));
    zipRandomFile.readFully(cbuf, 0, csize);

    int count = inflate(cbuf, buffer);
    if (count == -1) throw new ZipException("corrupted zip file");

    return entry.size;
  }
  private boolean 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
     *
     *  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;
     *		}
     *	}
     *
     *
     *
     */
    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;
  }
 @Override
 protected void parseBody(final RandomAccessFile mpegFile) throws IOException {
   final int size = (int) (super.seekToBodyStart(mpegFile) - 4);
   mpegFile.skipBytes(4); // Reserved
   rawBytes = new byte[size];
   mpegFile.readFully(rawBytes);
 }
Esempio n. 4
0
 /** {@inheritDoc} */
 public int skipBytes(final int n) throws IOException {
   fileSize -= n;
   if (fileSize < 0) {
     throw new EOFException();
   }
   return dataInput.skipBytes(n);
 }
Esempio n. 5
0
  /**
   * Seek for box with the specified id starting from the current location of filepointer,
   *
   * <p>Note it wont find the box if it is contained with a level below the current level, nor if we
   * are at a parent atom that also contains data and we havent yet processed the data. It will work
   * if we are at the start of a child box even if it not the required box as long as the box we are
   * looking for is the same level (or the level above in some cases).
   *
   * @param raf
   * @param id
   * @throws java.io.IOException
   */
  public static Mp4BoxHeader seekWithinLevel(RandomAccessFile raf, String id) throws IOException {
    logger.finer("Started searching for:" + id + " in file at:" + raf.getChannel().position());

    Mp4BoxHeader boxHeader = new Mp4BoxHeader();
    ByteBuffer headerBuffer = ByteBuffer.allocate(HEADER_LENGTH);
    int bytesRead = raf.getChannel().read(headerBuffer);
    if (bytesRead != HEADER_LENGTH) {
      return null;
    }
    headerBuffer.rewind();
    boxHeader.update(headerBuffer);
    while (!boxHeader.getId().equals(id)) {
      logger.finer("Still searching for:" + id + " in file at:" + raf.getChannel().position());

      // Something gone wrong probably not at the start of an atom so return null;
      if (boxHeader.getLength() < Mp4BoxHeader.HEADER_LENGTH) {
        return null;
      }
      int noOfBytesSkipped = raf.skipBytes(boxHeader.getDataLength());
      logger.finer("Skipped:" + noOfBytesSkipped);
      if (noOfBytesSkipped < boxHeader.getDataLength()) {
        return null;
      }
      headerBuffer.rewind();
      bytesRead = raf.getChannel().read(headerBuffer);
      logger.finer("Header Bytes Read:" + bytesRead);
      headerBuffer.rewind();
      if (bytesRead == Mp4BoxHeader.HEADER_LENGTH) {
        boxHeader.update(headerBuffer);
      } else {
        return null;
      }
    }
    return boxHeader;
  }
 private static void alterLastIFDOffset(RandomAccessFile rFile, int fileLen) throws IOException {
   rFile.seek(0);
   rFile.skipBytes(4);
   int offsetIFD = rFile.readInt();
   while (true) {
     rFile.seek(offsetIFD);
     int dirs = rFile.readShort();
     rFile.skipBytes(dirs * 12);
     offsetIFD = rFile.readInt();
     if (offsetIFD == 0) {
       int pointer = (int) rFile.getFilePointer();
       rFile.seek(pointer - 4);
       rFile.writeInt(fileLen);
       break;
     }
   }
 }
Esempio n. 7
0
  public static ZipFile.EocdRecord parseZip64EocdRecord(
      RandomAccessFile raf, long eocdRecordOffset, int commentLength) throws IOException {
    raf.seek(eocdRecordOffset);
    final int signature = Integer.reverseBytes(raf.readInt());
    if (signature != ZIP64_EOCD_RECORD_SIGNATURE) {
      throw new ZipException(
          "Invalid zip64 eocd record offset, sig="
              + Integer.toHexString(signature)
              + " offset="
              + eocdRecordOffset);
    }

    // The zip64 eocd record specifies its own size as an 8 byte integral type. It is variable
    // length because of the "zip64 extensible data sector" but that field is reserved for
    // pkware's proprietary use. We therefore disregard it altogether and treat the end of
    // central directory structure as fixed length.
    //
    // We also skip "version made by" (2 bytes) and "version needed to extract" (2 bytes)
    // fields. We perform additional validation at the ZipEntry level, where applicable.
    //
    // That's a total of 12 bytes to skip
    raf.skipBytes(12);

    byte[] zip64Eocd = new byte[ZIP64_EOCD_RECORD_EFFECTIVE_SIZE];
    raf.readFully(zip64Eocd);

    ByteBuffer buf = ByteBuffer.wrap(zip64Eocd).order(ByteOrder.LITTLE_ENDIAN);
    try {
      int diskNumber = buf.getInt();
      int diskWithCentralDirStart = buf.getInt();
      long numEntries = buf.getLong();
      long totalNumEntries = buf.getLong();
      buf.getLong(); // Ignore the size of the central directory
      long centralDirOffset = buf.getLong();

      if (numEntries != totalNumEntries || diskNumber != 0 || diskWithCentralDirStart != 0) {
        throw new ZipException(
            "Spanned archives not supported :"
                + " numEntries="
                + numEntries
                + ", totalNumEntries="
                + totalNumEntries
                + ", diskNumber="
                + diskNumber
                + ", diskWithCentralDirStart="
                + diskWithCentralDirStart);
      }

      return new ZipFile.EocdRecord(numEntries, centralDirOffset, commentLength);
    } catch (BufferUnderflowException bue) {
      ZipException zipException = new ZipException("Error parsing zip64 eocd record.");
      zipException.initCause(bue);
      throw zipException;
    }
  }
  private void parse(String path, long len) throws IOException {
    ByteBuffer byteBuffer;
    long sum = 0, newlen = 0;
    byte[] buffer = new byte[8];
    String name = "";

    if (!path.equals("")) mBoxes.put(path, mPos - 8);

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

      if (validBoxName(buffer)) {
        name = new 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.getFilePointer() - 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;
        }
      }
    }
  }
  public void init() throws IOException {
    mSound.skipBytes(8);
    int count = readInt();

    int type;
    for (int i = 0; i < count; i++) {
      type = readInt();

      mapping.put(type, new Sound(readInt(), readInt()));
    }
  }
Esempio n. 10
0
  /* Package visible for testing */
  static CentralDirectory findCentralDirectory(RandomAccessFile raf)
      throws IOException, ZipException {
    long scanOffset = raf.length() - ENDHDR;
    if (scanOffset < 0) {
      throw new ZipException("File too short to be a zip file: " + raf.length());
    }

    long stopOffset = scanOffset - 0x10000 /* ".ZIP file comment"'s max length */;
    if (stopOffset < 0) {
      stopOffset = 0;
    }

    int endSig = Integer.reverseBytes(ENDSIG);
    while (true) {
      raf.seek(scanOffset);
      if (raf.readInt() == endSig) {
        break;
      }

      scanOffset--;
      if (scanOffset < stopOffset) {
        throw new ZipException("End Of Central Directory signature not found");
      }
    }
    // Read the End Of Central Directory. ENDHDR includes the signature
    // bytes,
    // which we've already read.

    // Pull out the information we need.
    raf.skipBytes(2); // diskNumber
    raf.skipBytes(2); // diskWithCentralDir
    raf.skipBytes(2); // numEntries
    raf.skipBytes(2); // totalNumEntries
    CentralDirectory dir = new CentralDirectory();
    dir.size = Integer.reverseBytes(raf.readInt()) & 0xFFFFFFFFL;
    dir.offset = Integer.reverseBytes(raf.readInt()) & 0xFFFFFFFFL;
    return dir;
  }
Esempio n. 11
0
  @Override
  public int write(AudioInputStream stream, AudioFileFormat.Type fileType, File out)
      throws IOException {
    Objects.requireNonNull(stream);
    Objects.requireNonNull(fileType);
    Objects.requireNonNull(out);

    // throws IllegalArgumentException if not supported
    WaveFileFormat waveFileFormat = (WaveFileFormat) getAudioFileFormat(fileType, stream);

    // first write the file without worrying about length fields
    FileOutputStream fos = new FileOutputStream(out); // throws IOException
    BufferedOutputStream bos = new BufferedOutputStream(fos, bisBufferSize);
    int bytesWritten = writeWaveFile(stream, waveFileFormat, bos);
    bos.close();

    // now, if length fields were not specified, calculate them,
    // open as a random access file, write the appropriate fields,
    // close again....
    if (waveFileFormat.getByteLength() == AudioSystem.NOT_SPECIFIED) {

      int dataLength = bytesWritten - waveFileFormat.getHeaderSize();
      int riffLength = dataLength + waveFileFormat.getHeaderSize() - 8;

      RandomAccessFile raf = new RandomAccessFile(out, "rw");
      // skip RIFF magic
      raf.skipBytes(4);
      raf.writeInt(big2little(riffLength));
      // skip WAVE magic, fmt_ magic, fmt_ length, fmt_ chunk, data magic
      raf.skipBytes(4 + 4 + 4 + WaveFileFormat.getFmtChunkSize(waveFileFormat.getWaveType()) + 4);
      raf.writeInt(big2little(dataLength));
      // that's all
      raf.close();
    }

    return bytesWritten;
  }
 private void insertLine(File file, HttpSample httpSample) throws IOException {
   RandomAccessFile randomAccessFile = null;
   try {
     randomAccessFile = new RandomAccessFile(file, "rw");
     randomAccessFile.skipBytes((int) (file.length() - "\n</httpSamples>".getBytes().length));
     randomAccessFile.write("\n".getBytes());
     randomAccessFile.write(httpSample.toXML().getBytes());
     randomAccessFile.write("\n".getBytes());
     randomAccessFile.write("</httpSamples>".getBytes());
   } finally {
     if (randomAccessFile != null) {
       randomAccessFile.close();
     }
   }
 }
Esempio n. 13
0
  private byte[] readBytes(Entry entry) throws IOException {
    byte[] header = getHeader(entry);
    int csize = entry.compressedSize;
    byte[] cbuf = new byte[csize];
    zipRandomFile.skipBytes(get2ByteLittleEndian(header, 26) + get2ByteLittleEndian(header, 28));
    zipRandomFile.readFully(cbuf, 0, csize);

    // is this compressed - offset 8 in the ZipEntry header
    if (get2ByteLittleEndian(header, 8) == 0) return cbuf;

    int size = entry.size;
    byte[] buf = new byte[size];
    if (inflate(cbuf, buf) != size) throw new ZipException("corrupted zip file");

    return buf;
  }
 public static void appendData(File outfile, float[] data) throws IOException {
   RandomAccessFile raFile = new RandomAccessFile(outfile, "rw");
   try {
     SacHeader header = new SacHeader(raFile);
     if (header.getLeven() == FALSE
         || header.getIftype() == IRLIM
         || header.getIftype() == IAMPH) {
       raFile.close();
       throw new IOException("Can only append to evenly sampled sac files, ie only Y");
     }
     int origNpts = header.getNpts();
     header.setNpts(header.getNpts() + data.length);
     header.setE((header.getNpts() - 1) * header.getDelta());
     raFile.seek(0);
     header.writeHeader(raFile);
     raFile.skipBytes(origNpts * 4); // four bytes per float
     if (header.getByteOrder() == LITTLE_ENDIAN) {
       // Phil Crotwell's solution:
       // careful here as dos.writeFloat() will collapse all NaN floats
       // to
       // a single NaN value. But we are trying to write out byte
       // swapped values
       // so different floats that are all NaN are different values in
       // the
       // other byte order. Solution is to swap on the integer bits,
       // not the float.
       for (int i = 0; i < data.length; i++) {
         raFile.writeInt(SacHeader.swapBytes(Float.floatToRawIntBits(data[i])));
       }
     } else {
       for (int i = 0; i < data.length; i++) {
         raFile.writeFloat(data[i]);
       }
     }
   } finally {
     raFile.close();
   }
 }
  @Override
  public void write(OutputStream output) throws IOException, WebApplicationException {

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

    int length;
    int totalWrittenLength = 0;
    byte[] bytes = new byte[BLOCK_SIZE];

    if (range != null) {

      int lengthOfTheBytesRange = range.getlengthOfTheBytesRange();

      raf.skipBytes((int) range.getMin());

      while ((length = raf.read(bytes)) != -1) {
        if (totalWrittenLength + length < lengthOfTheBytesRange) {
          output.write(bytes, 0, length);
          totalWrittenLength += length;
        } else {
          int lengthToWrite = lengthOfTheBytesRange - totalWrittenLength;
          output.write(bytes, 0, lengthToWrite);
          totalWrittenLength += lengthToWrite;
          break;
        }
      }

    } else {
      while ((length = raf.read(bytes)) != -1) {
        output.write(bytes, 0, length);
        totalWrittenLength += length;
      }
    }

    raf.close();
  }
Esempio n. 16
0
 private long findNextEOLPosition(RandomAccessFile seeakable, long blocksize)
     throws IOException, EndReachedException {
   if (seeakable.skipBytes((int) blocksize) < blocksize) throw new EndReachedException();
   else seeakable.readLine();
   return seeakable.getFilePointer();
 }
  /**
   * The Vorbis Setup Header may span multiple(2) pages, athough it doesnt normally. We pass the
   * start of the file offset of the OggPage it belongs on, it probably won't be first packet, also
   * returns any addditional packets that immediately follow the setup header in original file
   *
   * @param fileOffsetOfStartingOggPage
   * @param raf
   * @return
   * @throws org.jaudiotagger.audio.exceptions.CannotReadException
   * @throws java.io.IOException
   */
  public byte[] convertToVorbisSetupHeaderPacketAndAdditionalPackets(
      long fileOffsetOfStartingOggPage, RandomAccessFile raf)
      throws IOException, CannotReadException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    // Seek to specified offset
    raf.seek(fileOffsetOfStartingOggPage);

    // Read Page
    OggPageHeader setupPageHeader = OggPageHeader.read(raf);

    // Assume that if multiple packets first packet is VorbisComment and second packet
    // is setupheader
    if (setupPageHeader.getPacketList().size() > 1) {
      raf.skipBytes(setupPageHeader.getPacketList().get(0).getLength());
    }

    // Now should be at start of next packet, check this is the vorbis setup header
    byte[] b =
        new byte[VorbisHeader.FIELD_PACKET_TYPE_LENGTH + VorbisHeader.FIELD_CAPTURE_PATTERN_LENGTH];
    raf.read(b);
    if (!isVorbisSetupHeader(b)) {
      throw new CannotReadException("Unable to find setup header(2), unable to write ogg file");
    }

    // Go back to start of setupheader data
    raf.seek(
        raf.getFilePointer()
            - (VorbisHeader.FIELD_PACKET_TYPE_LENGTH + VorbisHeader.FIELD_CAPTURE_PATTERN_LENGTH));

    // Read data
    if (setupPageHeader.getPacketList().size() > 1) {
      b = new byte[setupPageHeader.getPacketList().get(1).getLength()];
      raf.read(b);
      baos.write(b);
    } else {
      b = new byte[setupPageHeader.getPacketList().get(0).getLength()];
      raf.read(b);
      baos.write(b);
    }

    // Return Data
    if (!setupPageHeader.isLastPacketIncomplete() || setupPageHeader.getPacketList().size() > 2) {
      //            //logger.info("Setupheader finishes on this page");
      if (setupPageHeader.getPacketList().size() > 2) {
        for (int i = 2; i < setupPageHeader.getPacketList().size(); i++) {
          b = new byte[setupPageHeader.getPacketList().get(i).getLength()];
          raf.read(b);
          baos.write(b);
        }
      }
      return baos.toByteArray();
    }

    // The Setupheader extends to the next page, so should be at end of page already
    // so carry on reading pages until we get to the end of comment
    while (true) {
      //            //logger.info("Reading another page");
      OggPageHeader nextPageHeader = OggPageHeader.read(raf);
      b = new byte[nextPageHeader.getPacketList().get(0).getLength()];
      raf.read(b);
      baos.write(b);

      // Because there is at least one other packet this means the Setupheader Packet has finished
      // on this page so thats all we need and we can return
      if (nextPageHeader.getPacketList().size() > 1) {
        //                //logger.info("Setupheader finishes on this page");
        return baos.toByteArray();
      }

      // There is only the Setupheader packet on page if it has completed on this page we can return
      if (!nextPageHeader.isLastPacketIncomplete()) {
        //                //logger.info("Setupheader finish on Page because this packet is
        // complete");
        return baos.toByteArray();
      }
    }
  }
  /**
   * Calculate the size of the packet data for the comment and setup headers
   *
   * @param raf
   * @return
   * @throws CannotReadException
   * @throws IOException
   */
  public OggVorbisHeaderSizes readOggVorbisHeaderSizes(RandomAccessFile raf)
      throws CannotReadException, IOException {
    //        //logger.fine("Started to read comment and setup header sizes:");

    // Stores filepointers so return file in same state
    long filepointer = raf.getFilePointer();

    // Extra Packets on same page as setup header
    List<OggPageHeader.PacketStartAndLength> extraPackets =
        new ArrayList<OggPageHeader.PacketStartAndLength>();

    long commentHeaderStartPosition;
    long setupHeaderStartPosition;
    int commentHeaderSize = 0;
    int setupHeaderSize;
    // 1st page = codec infos
    OggPageHeader pageHeader = OggPageHeader.read(raf);
    // Skip over data to end of page header 1
    raf.seek(raf.getFilePointer() + pageHeader.getPageLength());

    // 2nd page = comment, may extend to additional pages or not , may also have setup header
    pageHeader = OggPageHeader.read(raf);
    commentHeaderStartPosition =
        raf.getFilePointer()
            - (OggPageHeader.OGG_PAGE_HEADER_FIXED_LENGTH + pageHeader.getSegmentTable().length);

    // Now at start of packets on page 2 , check this is the vorbis comment header
    byte[] b =
        new byte[VorbisHeader.FIELD_PACKET_TYPE_LENGTH + VorbisHeader.FIELD_CAPTURE_PATTERN_LENGTH];
    raf.read(b);
    if (!isVorbisCommentHeader(b)) {
      throw new CannotReadException("Cannot find comment block (no vorbiscomment header)");
    }
    raf.seek(
        raf.getFilePointer()
            - (VorbisHeader.FIELD_PACKET_TYPE_LENGTH + VorbisHeader.FIELD_CAPTURE_PATTERN_LENGTH));
    //        //logger.fine("Found start of comment header at:" + raf.getFilePointer());

    // Calculate Comment Size (not inc header)
    while (true) {
      List<OggPageHeader.PacketStartAndLength> packetList = pageHeader.getPacketList();
      commentHeaderSize += packetList.get(0).getLength();
      raf.skipBytes(packetList.get(0).getLength());

      // If this page contains multiple packets or if this last packet is complete then the Comment
      // header
      // end son this page and we can break
      if (packetList.size() > 1 || !pageHeader.isLastPacketIncomplete()) {
        // done comment size
        //                //logger.fine("Found end of comment:size:" + commentHeaderSize + "finishes
        // at file position:" + raf.getFilePointer());
        break;
      }
      pageHeader = OggPageHeader.read(raf);
    }

    // If there are no more packets on this page we need to go to next page to get the setup header
    OggPageHeader.PacketStartAndLength packet;
    if (pageHeader.getPacketList().size() == 1) {
      pageHeader = OggPageHeader.read(raf);
      List<OggPageHeader.PacketStartAndLength> packetList = pageHeader.getPacketList();
      packet = pageHeader.getPacketList().get(0);

      // Now at start of next packet , check this is the vorbis setup header
      b =
          new byte
              [VorbisHeader.FIELD_PACKET_TYPE_LENGTH + VorbisHeader.FIELD_CAPTURE_PATTERN_LENGTH];
      raf.read(b);
      if (!isVorbisSetupHeader(b)) {
        throw new CannotReadException(ErrorMessage.OGG_VORBIS_NO_VORBIS_HEADER_FOUND.getMsg());
      }
      raf.seek(
          raf.getFilePointer()
              - (VorbisHeader.FIELD_PACKET_TYPE_LENGTH
                  + VorbisHeader.FIELD_CAPTURE_PATTERN_LENGTH));
      //        //logger.fine("Found start of vorbis setup header at file position:" +
      // raf.getFilePointer());

      // Set this to the  start of the OggPage that setupheader was found on
      setupHeaderStartPosition =
          raf.getFilePointer()
              - (OggPageHeader.OGG_PAGE_HEADER_FIXED_LENGTH + pageHeader.getSegmentTable().length);

      // Add packet data to size to the setup header size
      setupHeaderSize = packet.getLength();
      //        //logger.fine("Adding:" + packetList.get(1).getLength() + " to setup header size");

      // Skip over the packet data
      raf.skipBytes(packet.getLength());

      // If there are other packets that follow this one, or if the last packet is complete then we
      // must have
      // got the size of the setup header.
      if (packetList.size() > 1 || !pageHeader.isLastPacketIncomplete()) {
        //                logger.info("Found end of setupheader:size:" + setupHeaderSize + "finishes
        // at:" + raf.getFilePointer());
        if (packetList.size() > 1) {
          extraPackets = packetList.subList(1, packetList.size());
        }
      }
      // The setup header continues onto the next page
      else {
        pageHeader = OggPageHeader.read(raf);
        packetList = pageHeader.getPacketList();
        while (true) {
          setupHeaderSize += packetList.get(0).getLength();
          //                    logger.fine("Adding:" + packetList.get(0).getLength() + " to setup
          // header size");
          raf.skipBytes(packetList.get(0).getLength());
          if (packetList.size() > 1 || !pageHeader.isLastPacketIncomplete()) {
            // done setup size
            //                        logger.fine("Found end of setupheader:size:" + setupHeaderSize
            // + "finishes at:" + raf.getFilePointer());
            if (packetList.size() > 1) {
              extraPackets = packetList.subList(1, packetList.size());
            }
            break;
          }
          // Continues onto another page
          pageHeader = OggPageHeader.read(raf);
        }
      }
    }
    // else its next packet on this page
    else {
      packet = pageHeader.getPacketList().get(1);
      List<OggPageHeader.PacketStartAndLength> packetList = pageHeader.getPacketList();

      // Now at start of next packet , check this is the vorbis setup header
      b =
          new byte
              [VorbisHeader.FIELD_PACKET_TYPE_LENGTH + VorbisHeader.FIELD_CAPTURE_PATTERN_LENGTH];
      raf.read(b);
      if (!isVorbisSetupHeader(b)) {
        // logger.warning("Expecting but got:" + new String(b) + "at " + (raf.getFilePointer() -
        // b.length));
        throw new CannotReadException(ErrorMessage.OGG_VORBIS_NO_VORBIS_HEADER_FOUND.getMsg());
      }
      raf.seek(
          raf.getFilePointer()
              - (VorbisHeader.FIELD_PACKET_TYPE_LENGTH
                  + VorbisHeader.FIELD_CAPTURE_PATTERN_LENGTH));
      //            logger.info("Found start of vorbis setup header at file position:" +
      // raf.getFilePointer());

      // Set this to the  start of the OggPage that setupheader was found on
      setupHeaderStartPosition =
          raf.getFilePointer()
              - (OggPageHeader.OGG_PAGE_HEADER_FIXED_LENGTH + pageHeader.getSegmentTable().length)
              - pageHeader.getPacketList().get(0).getLength();

      // Add packet data to size to the setup header size
      setupHeaderSize = packet.getLength();
      //            logger.fine("Adding:" + packet.getLength() + " to setup header size");

      // Skip over the packet data
      raf.skipBytes(packet.getLength());

      // If there are other packets that follow this one, or if the last packet is complete then we
      // must have
      // got the size of the setup header.
      if (packetList.size() > 2 || !pageHeader.isLastPacketIncomplete()) {
        //                logger.fine("Found end of setupheader:size:" + setupHeaderSize + "finishes
        // at:" + raf.getFilePointer());
        if (packetList.size() > 2) {
          extraPackets = packetList.subList(2, packetList.size());
        }
      }
      // The setup header continues onto the next page
      else {
        pageHeader = OggPageHeader.read(raf);
        packetList = pageHeader.getPacketList();
        while (true) {
          setupHeaderSize += packetList.get(0).getLength();
          //                    logger.fine("Adding:" + packetList.get(0).getLength() + " to setup
          // header size");
          raf.skipBytes(packetList.get(0).getLength());
          if (packetList.size() > 1 || !pageHeader.isLastPacketIncomplete()) {
            // done setup size
            //                        logger.fine("Found end of setupheader:size:" + setupHeaderSize
            // + "finishes at:" + raf.getFilePointer());
            if (packetList.size() > 1) {
              extraPackets = packetList.subList(1, packetList.size());
            }
            break;
          }
          // Continues onto another page
          pageHeader = OggPageHeader.read(raf);
        }
      }
    }

    // Reset filepointer to location that it was in at start of method
    raf.seek(filepointer);
    return new OggVorbisHeaderSizes(
        commentHeaderStartPosition,
        setupHeaderStartPosition,
        commentHeaderSize,
        setupHeaderSize,
        extraPackets);
  }
 /* @see java.io.DataInput.skipBytes(int) */
 public int skipBytes(int n) throws IOException {
   return raf.skipBytes(n);
 }
Esempio n. 20
0
    public void skipBytes(int num) throws IOException {

      raf.skipBytes(num);
    }
 public int skipBytes(int n) throws IOException {
   return wrapper.skipBytes(n);
 }
 @Override
 public long skip(long n) throws IOException {
   return raf.skipBytes((int) n);
 }
Esempio n. 23
0
    private void doRead(
        long classId,
        long testId,
        boolean allClassOutput,
        TestOutputEvent.Destination destination,
        java.io.Writer writer) {
      if (dataFile == null) {
        return;
      }

      Index targetIndex = index.children.get(classId);
      if (targetIndex != null && testId != 0) {
        targetIndex = targetIndex.children.get(testId);
      }

      if (targetIndex == null) {
        return;
      }

      boolean stdout = destination == TestOutputEvent.Destination.StdOut;
      Region region = stdout ? targetIndex.stdOut : targetIndex.stdErr;

      if (region.start < 0) {
        return;
      }

      boolean ignoreClassLevel = !allClassOutput && testId != 0;
      boolean ignoreTestLevel = !allClassOutput && testId == 0;

      try {
        dataFile.seek(region.start);

        while (dataFile.getFilePointer() <= region.stop) {
          dataFile.read(recordHeaderBuffer);
          Input input = new Input(recordHeaderBuffer);
          boolean readStdout = input.readBoolean();
          long readClassId = input.readLong();
          long readTestId = input.readLong();
          int readLength = input.readInt();
          input.close();

          boolean isClassLevel = readTestId == 0;

          if (stdout != readStdout || classId != readClassId) {
            dataFile.skipBytes(readLength);
            continue;
          }

          if (ignoreClassLevel && isClassLevel) {
            dataFile.skipBytes(readLength);
            continue;
          }

          if (ignoreTestLevel && !isClassLevel) {
            dataFile.skipBytes(readLength);
            continue;
          }

          if (testId == 0 || testId == readTestId) {
            byte[] stringBytes = new byte[readLength];
            dataFile.read(stringBytes);
            String message;
            try {
              message = new String(stringBytes, messageStorageCharset.name());
            } catch (UnsupportedEncodingException e) {
              // shouldn't happen
              throw UncheckedException.throwAsUncheckedException(e);
            }

            writer.write(message);
          } else {
            dataFile.skipBytes(readLength);
            continue;
          }
        }
      } catch (IOException e1) {
        throw new UncheckedIOException(e1);
      }
    }
Esempio n. 24
0
 /** Reads a MIDI track without doing anything to the data */
 private void skipATrack(RandomAccessFile dos) throws IOException {
   if (VERBOSE) System.out.println("Skipping the tempo track . . .");
   dos.readInt();
   dos.skipBytes(dos.readInt());
 }