Ejemplo n.º 1
0
  @Override
  public void get(ByteBuffer key, Result result) throws IOException {
    result.requiresBufferSize(readBufferSize);

    keyfile.get(key, result);

    if (result.isFound()) {
      ByteBuffer buffer = result.getBuffer();
      long recordFileOffset = EncodingHelper.decodeLittleEndianFixedWidthLong(buffer);

      buffer.rewind();
      buffer.limit(readBufferSize);
      recordFile.read(buffer, recordFileOffset);
      buffer.rewind();
      int recordSize = EncodingHelper.decodeLittleEndianVarInt(buffer);
      int bytesInRecordSize = buffer.position();
      if (buffer.remaining() < recordSize) {
        int newSize = recordSize + EncodingHelper.MAX_VARINT_SIZE;
        result.requiresBufferSize(newSize);
        recordFile.read(buffer, recordFileOffset + bytesInRecordSize);
        buffer.position(0);
      }
      buffer.limit(recordSize + buffer.position());
    }
  }
Ejemplo n.º 2
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;
  }
Ejemplo n.º 3
0
  // Test the connected case to see if PUE is thrown
  public static void test2() throws Exception {

    setup();
    server.configureBlocking(true);
    server.connect(isa);
    server.configureBlocking(false);
    outBuf.rewind();
    server.write(outBuf);
    server.receive(inBuf);

    client.close();
    Thread.sleep(2000);
    outBuf.rewind();

    try {
      server.write(outBuf);
      Thread.sleep(2000);
      inBuf.clear();
      server.read(inBuf);
      if (onSolarisOrLinux()) throw new Exception("Expected PUE not thrown");
    } catch (PortUnreachableException pue) {
      System.err.println("received PUE");
    }
    server.close();
  }
Ejemplo n.º 4
0
  public static WavInfo readHeader(InputStream wavStream) throws IOException, DecoderException {

    ByteBuffer buffer = ByteBuffer.allocate(HEADER_SIZE);
    buffer.order(ByteOrder.LITTLE_ENDIAN);

    wavStream.read(buffer.array(), buffer.arrayOffset(), buffer.capacity());

    buffer.rewind();
    buffer.position(buffer.position() + 20);
    int format = buffer.getShort();
    checkFormat(format == 1, "Unsupported encoding: " + format); // 1 means Linear PCM
    int channels = buffer.getShort();
    checkFormat(channels == 1 || channels == 2, "Unsupported channels: " + channels);
    int rate = buffer.getInt();
    checkFormat(rate <= 48000 && rate >= 11025, "Unsupported rate: " + rate);
    buffer.position(buffer.position() + 6);
    int bits = buffer.getShort();
    checkFormat(bits == 16, "Unsupported bits: " + bits);
    int dataSize = 0;
    while (buffer.getInt() != 0x61746164) { // "data" marker
      Log.d(TAG, "Skipping non-data chunk");
      int size = buffer.getInt();
      wavStream.skip(size);

      buffer.rewind();
      wavStream.read(buffer.array(), buffer.arrayOffset(), 8);
      buffer.rewind();
    }
    dataSize = buffer.getInt();
    checkFormat(dataSize > 0, "wrong datasize: " + dataSize);

    return new WavInfo(rate, channels == 2, dataSize);
  }
Ejemplo n.º 5
0
  // Writes a C string and expands the frame if necessary
  // FIXME: Property strings containing nul ('\0') characters will corrupt the frame when they are
  // written.
  //        Figure out how to throw an exception here if any nul chars are encountered
  private static ByteBuffer writeCString(ByteBuffer frame, String string) {
    Byte b = propertyAbbreviations.get(string);
    if (b != null) {
      if (frame.remaining() < 2)
        frame = ByteBuffer.allocate(frame.capacity() << 1).put((ByteBuffer) frame.rewind());
      frame.put(b);
      frame.put((byte) 0);
    } else {
      CharsetEncoder cStringEncoder = cStringCharset.newEncoder();

      CharBuffer chars = CharBuffer.wrap(string);
      for (int size = frame.capacity(); ; cStringEncoder.flush(frame)) {
        cStringEncoder.reset();
        if (cStringEncoder.encode(chars, frame, true) == CoderResult.OVERFLOW) {
          // debug output
          // System.out.println("overflow, reallocating to size " + (size << 1) + " (printing \"" +
          // string + "\")");
          frame = ByteBuffer.allocate(size = (size << 1)).put((ByteBuffer) frame.rewind());
        } else break;
      }
      cStringEncoder.flush(frame);
      frame.put((byte) 0);
    }
    return frame;
  }
Ejemplo n.º 6
0
  // Creates the first frame, which contains the message properties
  final ByteBuffer makeFirstFrame() {
    // Write the properties into a bytebuffer first:
    ByteBuffer frame;
    frame = ByteBuffer.allocate(0x20);
    for (Map.Entry<String, String> entry : this.properties.entrySet()) {
      frame = writeCString(frame, entry.getKey());
      frame = writeCString(frame, entry.getValue());
    }
    int len = frame.position();
    frame.limit(len);
    frame.rewind();

    // Setup compression objects if this message should be compressed
    if (this.isCompressed) {
      try {
        this.gzipIn = new ByteBufferInputStream(this.body);
        this.gzipOut = new GZIPOutputStream(new ByteArrayOutputStream());
      } catch (IOException e) {
      }
    }

    // Then make another bytebuffer and copy them into it after writing the header
    // This is because the header is written as varints and the space it will occupy
    // cannot be determined before writing the properties
    // Since the properties are almost always small, this has little cost
    ByteBuffer outFrame = ByteBuffer.allocate(len + 12);
    writeVarint(outFrame, this.number);
    writeVarint(outFrame, this.flags | MORECOMING);
    writeVarint(outFrame, len);
    outFrame.put(frame);
    outFrame.limit(outFrame.position());
    outFrame.rewind();
    return outFrame;
  }
Ejemplo n.º 7
0
 public void init() {
   // determine what type of video data we have
   if (data.limit() > 0) {
     byte flgs = data.get();
     data.rewind();
     detectFrameType();
     if ((flgs & 0x0f) == VideoCodec.H263.getId()) {
       // log.debug("h.263 / Sorenson");
     } else if ((flgs & 0x0f) == VideoCodec.AVC.getId()) {
       // log.debug("h.264 / AVC");
       // keyframe
       if (frameType == FrameType.KEYFRAME) {
         // log.debug("Keyframe");
         byte AVCPacketType = data.get();
         // rewind
         data.rewind();
         if (AVCPacketType == 0) {
           // log.debug("AVC decoder configuration found");
         }
       }
     } else {
       // unsupported video frame type
     }
   }
 }
Ejemplo n.º 8
0
  public static String readInFile(final File file) {
    try {
      final FileChannel fc = new FileInputStream(file).getChannel();
      final ByteBuffer buf = allocateDirect(10);
      final StringBuilder appender = new StringBuilder();
      int read;

      while (true) {
        buf.rewind();
        if ((read = fc.read(buf)) != -1) {
          buf.rewind();
          for (; read != 0; read--) {
            appender.append((char) buf.get());
          }
        } else {
          break;
        }
      }

      fc.close();

      return appender.toString();
    } catch (final FileNotFoundException e) {
      throw new TemplateError("cannot include template '" + file.getName() + "': file not found.");
    } catch (final IOException e) {
      throw new TemplateError(
          "unknown I/O exception while including '" + file.getName() + "' (stacktrace nested)", e);
    }
  }
Ejemplo n.º 9
0
  /**
   * Read, validate, and discard a single message, returning the next valid offset, and the message
   * being validated
   *
   * @throws IOException
   */
  private long validateMessage(FileChannel channel, long start, long len, ByteBuffer buffer)
      throws IOException {
    buffer.rewind();
    int read = channel.read(buffer, start);
    if (read < 4) return -1;

    // check that we have sufficient bytes left in the file
    int size = buffer.getInt(0);
    if (size < Message.MinHeaderSize) return -1;

    long next = start + 4 + size;
    if (next > len) return -1;

    // read the message
    ByteBuffer messageBuffer = ByteBuffer.allocate(size);
    long curr = start + 4;
    while (messageBuffer.hasRemaining()) {
      read = channel.read(messageBuffer, curr);
      if (read < 0) throw new IllegalStateException("File size changed during recovery!");
      else curr += read;
    }
    messageBuffer.rewind();
    Message message = new Message(messageBuffer);
    if (!message.isValid()) return -1;
    else return next;
  }
Ejemplo n.º 10
0
 /** Caclulates an MD5 hash for each file in the archive. */
 public String[] getMD5s() throws FileNotFoundException, NoSuchAlgorithmException, IOException {
   /**
    * This could be more efficiently handled during the output phase using a filtering channel, but
    * would require placeholder values in the archive and some state. This is left for a later
    * refactoring.
    */
   final ByteBuffer buffer = ByteBuffer.allocate(4096);
   String[] array = new String[headers.size()];
   int x = 0;
   for (CpioHeader header : headers) {
     Object object = sources.get(header);
     String value = "";
     if (object instanceof File) {
       final ReadableChannelWrapper input =
           new ReadableChannelWrapper(new FileInputStream((File) object).getChannel());
       final Key<byte[]> key = input.start("MD5");
       while (input.read(buffer) != -1) buffer.rewind();
       value = new String(Util.hex(input.finish(key)));
       input.close();
     } else if (object instanceof URL) {
       final ReadableChannelWrapper input =
           new ReadableChannelWrapper(
               Channels.newChannel(((URL) object).openConnection().getInputStream()));
       final Key<byte[]> key = input.start("MD5");
       while (input.read(buffer) != -1) buffer.rewind();
       value = new String(Util.hex(input.finish(key)));
       input.close();
     }
     array[x++] = value;
   }
   return array;
 }
Ejemplo n.º 11
0
  // Read Packet for GameStateVisualizer
  public boolean readPacket(DatagramPacket packet, MainGUI gui) {
    ByteBuffer packetData = ByteBuffer.allocate(GameState.packet_size * 3);
    packetData.order(Constants.NETWORK_BYTEORDER);
    packetData.rewind();
    packetData.put(packet.getData());

    packetData.rewind();

    byte[] header = new byte[4];
    packetData.get(header);
    if (!GameState.STRUCT_HEADER.equals(new String(header))) {
      if (gui.getDebug()) {
        System.out.println("Bad header");
      }
      return false;
    }

    int version = packetData.getInt();
    if (version != 6 && version != 7) {
      if (gui.getDebug()) {
        System.out.println("Bad packet version: " + version + " expecting: 6 or 7");
      }
      return false;
    }

    packetData.get(); // playersPerTeam
    byte gameState = packetData.get(); // gameState
    byte firstHalf = packetData.get(); // firstHalf
    packetData.get(); // kickOffTeam
    byte secondaryState = packetData.get(); // secondaryState
    packetData.get(); // dropInTeam
    packetData.getShort(); // dropInTime
    int secsRemaining = packetData.getInt(); // secsRemaining

    // team blue
    byte team1Number = packetData.get(); // teamNumber
    packetData.get(); // teamColor
    if (version == 7) packetData.get();
    int team1Score = version == 6 ? packetData.getShort() : packetData.get(); // score
    packetData.position(packetData.position() + Constants.MAX_NUM_PLAYERS * 4);
    // team red
    byte team2Number = packetData.get(); // teamNumber
    packetData.get(); // teamColor
    if (version == 7) packetData.get();
    int team2Score = version == 6 ? packetData.getShort() : packetData.get(); // score
    this.setVersion(version);
    this.setGameState(gameState);
    this.setSecondaryGameState(secondaryState);
    this.setHalf(firstHalf);
    this.setEstimatedSecs(secsRemaining, false);
    this.getTeam(Constants.TEAM_BLUE).setTeamNumber(team1Number);
    this.getTeam(Constants.TEAM_BLUE).setTeamScore((byte) team1Score);
    this.getTeam(Constants.TEAM_RED).setTeamNumber(team2Number);
    this.getTeam(Constants.TEAM_RED).setTeamScore((byte) team2Score);
    return true;
  }
 @Test
 public void byteBufferToByteBuffer() throws Exception {
   byte[] bytes = new byte[] {1, 2, 3};
   ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
   ByteBuffer convert = this.conversionService.convert(byteBuffer, ByteBuffer.class);
   assertThat(convert, not(sameInstance(byteBuffer.rewind())));
   assertThat(convert, equalTo(byteBuffer.rewind()));
   assertThat(convert, equalTo(ByteBuffer.wrap(bytes)));
   assertThat(convert.array(), equalTo(bytes));
 }
Ejemplo n.º 13
0
  /** Add an entry to a ledger as specified by handle. */
  private void addEntryInternal(
      LedgerDescriptor handle, ByteBuffer entry, WriteCallback cb, Object ctx)
      throws IOException, BookieException {
    long ledgerId = handle.getLedgerId();
    entry.rewind();
    long entryId = handle.addEntry(entry);

    entry.rewind();
    LOG.trace("Adding {}@{}", entryId, ledgerId);
    journal.logAddEntry(entry, cb, ctx);
  }
  @Override
  public void clearBuffer(final ByteBuffer buffer) {
    final int limit = buffer.limit();
    buffer.rewind();

    for (int i = 0; i < limit; i++) {
      buffer.put((byte) 0);
    }

    buffer.rewind();
  }
  @Test
  public void testSerializeImmutable() throws IOException {
    MutableRoaringBitmap mr = new MutableRoaringBitmap();
    mr.add(5);
    ByteBuffer buffer = serializeRoaring(mr);

    buffer.rewind();
    buffer = serializeRoaring(new ImmutableRoaringBitmap(buffer));

    buffer.rewind();
    ImmutableRoaringBitmap ir = new ImmutableRoaringBitmap(buffer);
    Assert.assertTrue(ir.contains(5));
  }
Ejemplo n.º 16
0
 public static void main(String[] args) {
   ByteBuffer bb = ByteBuffer.wrap(new byte[12]);
   bb.asCharBuffer().put("abcdef");
   System.out.println(Arrays.toString(bb.array()));
   bb.rewind();
   bb.order(ByteOrder.BIG_ENDIAN);
   bb.asCharBuffer().put("abcdef");
   System.out.println(Arrays.toString(bb.array()));
   bb.rewind();
   bb.order(ByteOrder.LITTLE_ENDIAN);
   bb.asCharBuffer().put("abcdef");
   System.out.println(Arrays.toString(bb.array()));
 }
Ejemplo n.º 17
0
 /** Read the VBRI Properties from the buffer */
 private VbriFrame() {
   // Go to start of Buffer
   header.rewind();
   header.position(10);
   setAudioSize();
   setFrameCount();
 }
Ejemplo n.º 18
0
  @Override
  public void append(Framedata nextframe) throws InvalidFrameException {
    ByteBuffer b = nextframe.getPayloadData();
    if (unmaskedpayload == null) {
      unmaskedpayload = ByteBuffer.allocate(b.remaining());
      b.mark();
      unmaskedpayload.put(b);
      b.reset();
    } else {
      b.mark();
      unmaskedpayload.position(unmaskedpayload.limit());
      unmaskedpayload.limit(unmaskedpayload.capacity());

      if (b.remaining() > unmaskedpayload.remaining()) {
        ByteBuffer tmp = ByteBuffer.allocate(b.remaining() + unmaskedpayload.capacity());
        unmaskedpayload.flip();
        tmp.put(unmaskedpayload);
        tmp.put(b);
        unmaskedpayload = tmp;

      } else {
        unmaskedpayload.put(b);
      }
      unmaskedpayload.rewind();
      b.reset();
    }
    fin = nextframe.isFin();
  }
Ejemplo n.º 19
0
    /** Regenerates any dirty mimaps. */
    public void regenerateMipmaps() {
      if (mipmapDirty) {
        ByteBuffer data1 =
            BufferUtils.createByteBuffer(size.getWidth() * size.getHeight() * format.bytes);
        ByteBuffer data = data1;

        GL11.glBindTexture(GL11.GL_TEXTURE_2D, id);

        // read the texture out
        GL11.glGetTexImage(GL11.GL_TEXTURE_2D, 0, format.glFormat, GL11.GL_UNSIGNED_BYTE, data);

        data.rewind();

        // regenerate the mipmaps
        GLU.gluBuild2DMipmaps(
            GL11.GL_TEXTURE_2D,
            format.glInternalFormat,
            size.getWidth(),
            size.getHeight(),
            format.glFormat,
            GL11.GL_UNSIGNED_BYTE,
            data);

        mipmapDirty = false;
      }
    }
Ejemplo n.º 20
0
 private void addTimelineDelegationToken(ContainerLaunchContext clc)
     throws YarnException, IOException {
   Credentials credentials = new Credentials();
   DataInputByteBuffer dibb = new DataInputByteBuffer();
   ByteBuffer tokens = clc.getTokens();
   if (tokens != null) {
     dibb.reset(tokens);
     credentials.readTokenStorageStream(dibb);
     tokens.rewind();
   }
   // If the timeline delegation token is already in the CLC, no need to add
   // one more
   for (org.apache.hadoop.security.token.Token<? extends TokenIdentifier> token :
       credentials.getAllTokens()) {
     if (token.getKind().equals(TimelineDelegationTokenIdentifier.KIND_NAME)) {
       return;
     }
   }
   org.apache.hadoop.security.token.Token<TimelineDelegationTokenIdentifier>
       timelineDelegationToken = getTimelineDelegationToken();
   if (timelineDelegationToken == null) {
     return;
   }
   credentials.addToken(timelineService, timelineDelegationToken);
   if (LOG.isDebugEnabled()) {
     LOG.debug("Add timline delegation token into credentials: " + timelineDelegationToken);
   }
   DataOutputBuffer dob = new DataOutputBuffer();
   credentials.writeTokenStorageToStream(dob);
   tokens = ByteBuffer.wrap(dob.getData(), 0, dob.getLength());
   clc.setTokens(tokens);
 }
Ejemplo n.º 21
0
  public void close() throws IOException {
    decode(true);
    flushOutput();
    writer.close();

    buf.rewind();
  }
Ejemplo n.º 22
0
  /** Preps the send buffer for next transmission */
  public void prepSendBuffer() {
    // sendBuffer.rewind();
    // Put the protocol ID and the localSequence
    sendBuffer.put(protocol);
    sendBuffer.putShort(localSequence);
    // Put analog values
    sendBuffer.putShort(controller.analogState.get(0));
    sendBuffer.putShort(controller.analogState.get(1));
    sendBuffer.putShort(controller.analogState.get(2));
    sendBuffer.putShort(controller.analogState.get(3));

    // Build first byte and put
    byte firstByte = 0;
    for (int n = 0; n < 7; n++, firstByte <<= 1) if (controller.buttonState.get(n)) firstByte |= 1;
    if (controller.buttonState.get(7)) firstByte |= 1;
    sendBuffer.put(firstByte);

    // Build second byte and put
    byte secondByte = 0;
    for (int n = 8; n < 15; n++, secondByte <<= 1)
      if (controller.buttonState.get(n)) secondByte |= 1;
    if (controller.buttonState.get(15)) secondByte |= 1;
    sendBuffer.put(secondByte);

    // Put the extra button (not implemented in touch yet)
    // sendBuffer.put((byte) (controller.buttons.get(16) ? 1 : 0));
    sendBuffer.rewind();
  }
Ejemplo n.º 23
0
  /**
   * Parses the FileChannel, in the range [start, end) and prints the elements found
   *
   * <p>Elements are printed, indented by "level" number of spaces. If an element is a container,
   * then its contents will be, recursively, printed, with a greater indentation.
   *
   * @param fc
   * @param level
   * @param start
   * @param end
   * @throws IOException
   */
  private void print(FileChannel fc, int level, long start, long end) throws IOException {
    fc.position(start);
    if (end <= 0) {
      end = start + fc.size();
      System.out.println("Setting END to " + end);
    }
    while (end - fc.position() > 8) {
      long begin = fc.position();
      ByteBuffer bb = ByteBuffer.allocate(8);
      fc.read(bb);
      bb.rewind();
      long size = IsoTypeReader.readUInt32(bb);
      String type = IsoTypeReader.read4cc(bb);
      long fin = begin + size;
      // indent by the required number of spaces
      for (int i = 0; i < level; i++) {
        System.out.print(" ");
      }

      System.out.println(type + "@" + (begin) + " size: " + size);
      if (containers.contains(type)) {
        print(fc, level + 1, begin + 8, fin);
        if (fc.position() != fin) {
          System.out.println("End of container contents at " + fc.position());
          System.out.println("  FIN = " + fin);
        }
      } else {

      }

      fc.position(fin);
    }
  }
Ejemplo n.º 24
0
  public synchronized void write(final PagedMessage message) throws Exception {
    if (!file.isOpen()) {

      return;
    }

    ByteBuffer buffer = fileFactory.newBuffer(message.getEncodeSize() + Page.SIZE_RECORD);

    HornetQBuffer wrap = HornetQBuffers.wrappedBuffer(buffer);
    wrap.clear();

    wrap.writeByte(Page.START_BYTE);
    wrap.writeInt(0);
    int startIndex = wrap.writerIndex();
    message.encode(wrap);
    int endIndex = wrap.writerIndex();
    wrap.setInt(1, endIndex - startIndex); // The encoded length
    wrap.writeByte(Page.END_BYTE);

    buffer.rewind();

    file.writeDirect(buffer, false);

    if (pageCache != null) {
      pageCache.addLiveMessage(message);
    }

    numberOfMessages.incrementAndGet();
    size.addAndGet(buffer.limit());

    storageManager.pageWrite(message, pageId);
  }
Ejemplo n.º 25
0
  private void testAlgorithm(
      byte[] encodedData, ByteBuffer unencodedDataBuf, DataBlockEncoder encoder)
      throws IOException {
    // decode
    ByteArrayInputStream bais =
        new ByteArrayInputStream(
            encodedData, ENCODED_DATA_OFFSET, encodedData.length - ENCODED_DATA_OFFSET);
    DataInputStream dis = new DataInputStream(bais);
    ByteBuffer actualDataset;
    HFileContext meta =
        new HFileContextBuilder()
            .withHBaseCheckSum(false)
            .withIncludesMvcc(includesMemstoreTS)
            .withIncludesTags(includesTags)
            .withCompression(Compression.Algorithm.NONE)
            .build();
    actualDataset = encoder.decodeKeyValues(dis, encoder.newDataBlockDecodingContext(meta));
    actualDataset.rewind();

    // this is because in case of prefix tree the decoded stream will not have
    // the
    // mvcc in it.
    assertEquals(
        "Encoding -> decoding gives different results for " + encoder,
        Bytes.toStringBinary(unencodedDataBuf),
        Bytes.toStringBinary(actualDataset));
  }
Ejemplo n.º 26
0
 static ByteBuffer encodeKeyValues(
     DataBlockEncoding encoding,
     List<KeyValue> kvs,
     HFileBlockEncodingContext encodingContext,
     boolean useOffheapData)
     throws IOException {
   DataBlockEncoder encoder = encoding.getEncoder();
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   baos.write(HConstants.HFILEBLOCK_DUMMY_HEADER);
   DataOutputStream dos = new DataOutputStream(baos);
   encoder.startBlockEncoding(encodingContext, dos);
   for (KeyValue kv : kvs) {
     encoder.encode(kv, encodingContext, dos);
   }
   encoder.endBlockEncoding(encodingContext, dos, baos.getBuffer());
   byte[] encodedData = new byte[baos.size() - ENCODED_DATA_OFFSET];
   System.arraycopy(baos.toByteArray(), ENCODED_DATA_OFFSET, encodedData, 0, encodedData.length);
   if (useOffheapData) {
     ByteBuffer bb = ByteBuffer.allocateDirect(encodedData.length);
     bb.put(encodedData);
     bb.rewind();
     return bb;
   }
   return ByteBuffer.wrap(encodedData);
 }
Ejemplo n.º 27
0
  /** Read the Xing Properties from the buffer */
  private XingFrame() {
    // Go to start of Buffer
    header.rewind();

    // Set Vbr
    setVbr();

    // Read Flags, only the fourth byte of interest to us
    byte flagBuffer[] = new byte[XING_FLAG_BUFFER_SIZE];
    header.get(flagBuffer);

    // Read FrameCount if flag set
    if ((flagBuffer[BYTE_4] & (byte) (1)) != 0) {
      setFrameCount();
    }

    // Read Size if flag set
    if ((flagBuffer[BYTE_4] & (byte) (1 << 1)) != 0) {
      setAudioSize();
    }

    // TODO TOC
    // TODO VBR Quality

    // Look for LAME Header as long as we have enough bytes to do it properly
    if (header.limit() >= XING_HEADER_BUFFER_SIZE + LameFrame.LAME_HEADER_BUFFER_SIZE) {
      header.position(XING_HEADER_BUFFER_SIZE);
      lameFrame = LameFrame.parseLameFrame(header);
    }
  }
 private byte getOneByte() throws IOException {
   oneByte.rewind();
   if (file.read(oneByte) < 1) {
     throw new EndOfFileException(getFileName());
   }
   return oneByte.get(0);
 }
Ejemplo n.º 29
0
  /**
   * Get the data of this RTP packet as a byte array.
   *
   * @return The data of this RTP packet as a byte array.
   */
  private ByteBuffer getData() {

    ByteBuffer byteBuffer = ByteBuffer.allocate(12 + payloadLength);

    /* Since V..SN are 32 bits, create a (int) byte array for V..SN. */
    long V_SN = 0;
    V_SN =
        ((long) version) << 30
            | this.padding << 29
            | extension << 28
            | csrcCount << 24
            | this.marker << 23
            | this.payloadType << 16
            | (sequenceNumber & 0xffff);

    byteBuffer.putInt((int) V_SN);

    // offset = 4 from the start of packet
    byteBuffer.putInt((int) this.timeStamp);

    // offset = 8 from start of packet
    byteBuffer.putInt((int) this.SSRC);

    if (payloadLength != 0) {
      // This only applies if somebody has tinkered with the payload.
      // offset = 12 from start of packet.
      byteBuffer.put(payload);
    }
    // Reset pointer to start of buffer.
    byteBuffer.rewind();

    return byteBuffer;
  }
Ejemplo n.º 30
0
  public void testSimpleRoundWithEntriesTrip(
      int baseOffsetSize, int indexSize, int lengthSize, int offsetSize) throws IOException {
    ItemLocationBox ilocOrig = new ItemLocationBox();
    ilocOrig.setVersion(1);
    ilocOrig.setBaseOffsetSize(baseOffsetSize);
    ilocOrig.setIndexSize(indexSize);
    ilocOrig.setLengthSize(lengthSize);
    ilocOrig.setOffsetSize(offsetSize);
    ItemLocationBox.Item item =
        ilocOrig.createItem(12, 0, 13, 123, Collections.<ItemLocationBox.Extent>emptyList());
    ilocOrig.setItems(Collections.singletonList(item));
    ByteBuffer bb = ByteBuffer.allocate(l2i(ilocOrig.getSize()));
    ilocOrig.getBox(new ByteBufferByteChannel(bb));

    bb.rewind();

    IsoFile isoFile = new IsoFile(new ByteBufferByteChannel(bb));

    ItemLocationBox iloc = (ItemLocationBox) isoFile.getBoxes().get(0);

    Assert.assertEquals(ilocOrig.getBaseOffsetSize(), iloc.getBaseOffsetSize());
    Assert.assertEquals(ilocOrig.getContentSize(), iloc.getContentSize());
    Assert.assertEquals(ilocOrig.getIndexSize(), iloc.getIndexSize());
    Assert.assertEquals(ilocOrig.getLengthSize(), iloc.getLengthSize());
    Assert.assertEquals(ilocOrig.getOffsetSize(), iloc.getOffsetSize());
    Assert.assertEquals(ilocOrig.getItems(), iloc.getItems());
  }