private PropertyRecord getRecordFromBuffer(long id, Buffer buffer) {
    int offsetAtBeggining = buffer.getOffset();
    PropertyRecord record = new PropertyRecord(id);

    /*
     * [pppp,nnnn] previous, next high bits
     */
    byte modifiers = buffer.get();
    long prevMod = ((modifiers & 0xF0L) << 28);
    long nextMod = ((modifiers & 0x0FL) << 32);
    long prevProp = buffer.getUnsignedInt();
    long nextProp = buffer.getUnsignedInt();
    record.setPrevProp(longFromIntAndMod(prevProp, prevMod));
    record.setNextProp(longFromIntAndMod(nextProp, nextMod));

    while (buffer.getOffset() - offsetAtBeggining < RECORD_SIZE) {
      PropertyBlock newBlock = getPropertyBlock(buffer);
      if (newBlock != null) {
        record.addPropertyBlock(newBlock);
        record.setInUse(true);
      } else {
        // We assume that storage is defragged
        break;
      }
    }
    return record;
  }
  @Test
  public void testGetOffset() throws Exception {
    Buffer buffer = new FixedBuffer();
    Assert.assertEquals(buffer.getOffset(), 0);

    buffer.put(4);
    Assert.assertEquals(buffer.getOffset(), 4);
  }
 private void checkSVarInt(int v, int offset) {
   Buffer buffer = new FixedBuffer(32);
   buffer.putSVar(v);
   if (offset != -1) {
     Assert.assertEquals(buffer.getOffset(), offset);
   } else {
     logger.info("{} offsetSize:{}", v, buffer.getOffset());
   }
   buffer.setOffset(0);
   int readV = buffer.readSVarInt();
   Assert.assertEquals(readV, v);
 }
 private void checkVarInt_bufferSize(int v, int offset, int bufferSize) {
   final Buffer buffer = new FixedBuffer(bufferSize);
   buffer.putVar(v);
   if (offset != -1) {
     Assert.assertEquals(buffer.getOffset(), offset);
   } else {
     logger.info("{} offsetSize:{}", v, buffer.getOffset());
   }
   buffer.setOffset(0);
   int readV = buffer.readVarInt();
   Assert.assertEquals(readV, v);
 }
  // @Override
  @Override
  public int read() throws IOException {
    // TODO: how do we detect IOException?
    fillBuffer();
    if (buffer.getLength() == 0 && buffer.isEOM()) // TODO: will always be
      // EOM if length is 0
      return -1;
    final byte[] data = (byte[]) buffer.getData();
    final int result = data[buffer.getOffset()] & 0xff;
    buffer.setOffset(buffer.getOffset() + 1);
    buffer.setLength(buffer.getLength() - 1);

    return result;
  }
  // @Override
  @Override
  public int read(byte[] b, int off, int len) throws IOException {
    // TODO: how do we detect IOException?
    fillBuffer();
    if (buffer.getLength() == 0 && buffer.isEOM()) // TODO: will always be
      // EOM if length is 0
      return -1;
    final byte[] data = (byte[]) buffer.getData();

    int lengthToCopy = buffer.getLength() < len ? buffer.getLength() : len;
    System.arraycopy(data, buffer.getOffset(), b, off, lengthToCopy);
    buffer.setOffset(buffer.getOffset() + lengthToCopy);
    buffer.setLength(buffer.getLength() - lengthToCopy);

    return lengthToCopy;
  }
Exemple #7
0
 private static void _testMessage(Message msg) throws Exception {
   Buffer buf = Util.messageToByteBuffer(msg);
   Message msg2 = Util.byteBufferToMessage(buf.getBuf(), buf.getOffset(), buf.getLength());
   Assert.assertEquals(msg.getSrc(), msg2.getSrc());
   Assert.assertEquals(msg.getDest(), msg2.getDest());
   Assert.assertEquals(msg.getLength(), msg2.getLength());
 }
    public void run() {

      for (int i = 1; i <= number_of_msgs; i++) {
        try {
          Message msg = new Message(null, buf);
          if (oob) msg.setFlag(Message.Flag.OOB);
          if (dont_bundle) msg.setFlag(Message.Flag.DONT_BUNDLE);
          if (i > 0 && do_print > 0 && i % do_print == 0) System.out.println("-- sent " + i);

          Buffer buffer = writeMessage(msg);

          output_lock.lock(); // need to sync if we have more than 1 sender
          try {
            // msg.writeTo(output);
            output.writeInt(buffer.getLength());
            output.write(buffer.getBuf(), buffer.getOffset(), buffer.getLength());
            // output.flush();
          } finally {
            output_lock.unlock();
          }
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
    public VideoTrack(PullSourceStream stream) throws ResourceUnavailableException {
      super();

      this.stream = stream;
      // set format

      // read first frame to determine format
      final Buffer buffer = new Buffer();
      readFrame(buffer);
      if (buffer.isDiscard() || buffer.isEOM())
        throw new ResourceUnavailableException("Unable to read first frame");
      // TODO: catch runtime exception too?

      // parse jpeg
      final java.awt.Image image;
      try {
        image =
            ImageIO.read(
                new ByteArrayInputStream(
                    (byte[]) buffer.getData(), buffer.getOffset(), buffer.getLength()));
      } catch (IOException e) {
        logger.log(Level.WARNING, "" + e, e);
        throw new ResourceUnavailableException("Error reading image: " + e);
      }

      if (image == null) {
        logger.log(Level.WARNING, "Failed to read image (ImageIO.read returned null).");
        throw new ResourceUnavailableException();
      }

      if (frameContentType.equals("image/jpeg"))
        format =
            new JPEGFormat(
                new Dimension(image.getWidth(null), image.getHeight(null)),
                Format.NOT_SPECIFIED,
                Format.byteArray,
                -1.f,
                Format.NOT_SPECIFIED,
                Format.NOT_SPECIFIED);
      else if (frameContentType.equals("image/gif"))
        format =
            new GIFFormat(
                new Dimension(image.getWidth(null), image.getHeight(null)),
                Format.NOT_SPECIFIED,
                Format.byteArray,
                -1.f);
      else if (frameContentType.equals("image/png"))
        format =
            new PNGFormat(
                new Dimension(image.getWidth(null), image.getHeight(null)),
                Format.NOT_SPECIFIED,
                Format.byteArray,
                -1.f);
      else
        throw new ResourceUnavailableException(
            "Unsupported frame content type: " + frameContentType);
      // TODO: this discards first image. save and return first time
      // readFrame is called.

    }
  @Test
  public void testSliceGetBuffer() throws Exception {
    Buffer buffer = new FixedBuffer(5);
    buffer.put(1);
    Assert.assertEquals(buffer.getOffset(), 4);
    Assert.assertEquals(buffer.getBuffer().length, 4);

    byte[] buffer1 = buffer.getBuffer();
    byte[] buffer2 = buffer.getBuffer();
    Assert.assertTrue(buffer1 != buffer2);
  }
  @Test
  public void readVarInt_errorCase() {
    byte[] errorCode = new byte[] {-118, -41, -17, -117, -81, -115, -64, -64, -108, -88};
    Buffer buffer = new FixedBuffer(errorCode);
    try {
      buffer.readVarInt();
      Assert.fail("invalid varInt");
    } catch (IllegalArgumentException ignore) {
    }

    Assert.assertEquals(0, buffer.getOffset());
  }
Exemple #12
0
  private void updateRecord(PropertyRecord record, PersistenceWindow window) {
    long id = record.getId();
    registerIdFromUpdateRecord(id);
    Buffer buffer = window.getOffsettedBuffer(id);
    if (record.inUse()) {
      // Set up the record header
      short prevModifier =
          record.getPrevProp() == Record.NO_NEXT_RELATIONSHIP.intValue()
              ? 0
              : (short) ((record.getPrevProp() & 0xF00000000L) >> 28);
      short nextModifier =
          record.getNextProp() == Record.NO_NEXT_RELATIONSHIP.intValue()
              ? 0
              : (short) ((record.getNextProp() & 0xF00000000L) >> 32);
      byte modifiers = (byte) (prevModifier | nextModifier);
      /*
       * [pppp,nnnn] previous, next high bits
       */
      buffer.put(modifiers);
      buffer.putInt((int) record.getPrevProp()).putInt((int) record.getNextProp());

      // Then go through the blocks
      int longsAppended = 0; // For marking the end of blocks
      for (PropertyBlock block : record.getPropertyBlocks()) {
        long[] propBlockValues = block.getValueBlocks();
        for (long propBlockValue : propBlockValues) {
          buffer.putLong(propBlockValue);
        }

        longsAppended += propBlockValues.length;
        /*
         * For each block we need to update its dynamic record chain if
         * it is just created. Deleted dynamic records are in the property
         * record and dynamic records are never modified. Also, they are
         * assigned as a whole, so just checking the first should be enough.
         */
        if (!block.isLight() && block.getValueRecords().get(0).isCreated()) {
          updateDynamicRecords(block.getValueRecords());
        }
      }
      if (longsAppended < PropertyType.getPayloadSizeLongs()) {
        buffer.putLong(0);
      }
    } else {
      if (!isInRecoveryMode()) {
        freeId(id);
      }
      // skip over the record header, nothing useful there
      buffer.setOffset(buffer.getOffset() + 9);
      buffer.putLong(0);
    }
    updateDynamicRecords(record.getDeletedRecords());
  }
  @Test
  public void readVarLong_errorCase() {
    byte[] errorCode = new byte[] {-25, -45, -47, -14, -16, -104, -53, -48, -72, -9};
    Buffer buffer = new FixedBuffer(errorCode);
    try {
      buffer.readVarLong();
      Assert.fail("invalid varLong");
    } catch (IllegalArgumentException ignore) {
    }

    Assert.assertEquals(0, buffer.getOffset());
  }
  private void checkVarLong_bufferSize(long v, int bufferSize) {
    final Buffer buffer = new FixedBuffer(bufferSize);
    buffer.putVar(v);

    buffer.setOffset(0);
    long readV = buffer.readVarLong();
    Assert.assertEquals(readV, v);

    if (logger.isTraceEnabled()) {
      logger.trace("v:{} offset:{}", v, buffer.getOffset());
    }
  }
Exemple #15
0
  @Override
  public int process(Buffer input, Buffer output) {
    if (!checkInputBuffer(input)) {
      return BUFFER_PROCESSED_FAILED;
    }

    if (isEOM(input)) {
      propagateEOM(output); // TODO: what about data? can there be any?
      return BUFFER_PROCESSED_OK;
    }

    try {
      // TODO: this is very inefficient - it allocates a new byte array
      // (or more) every time
      final ByteArrayInputStream is =
          new ByteArrayInputStream((byte[]) input.getData(), input.getOffset(), input.getLength());
      final BufferedImage image = ImageIO.read(is);
      is.close();
      final Buffer b =
          ImageToBuffer.createBuffer(image, ((VideoFormat) outputFormat).getFrameRate());

      output.setData(b.getData());
      output.setOffset(b.getOffset());
      output.setLength(b.getLength());
      output.setFormat(b.getFormat()); // TODO: this is a bit hacky, this
      // format will be more specific
      // than the actual set output
      // format, because now we know what
      // ImageIO gave us for a
      // BufferedImage as far as pixel
      // masks, etc.

      return BUFFER_PROCESSED_OK;

    } catch (IOException e) {
      output.setDiscard(true);
      output.setLength(0);
      return BUFFER_PROCESSED_FAILED;
    }
  }
  void sendMessages() throws Exception {
    if (num_threads > 1 && num_msgs % num_threads != 0) {
      System.err.println(
          "num_msgs (" + num_msgs + " ) has to be divisible by num_threads (" + num_threads + ")");
      return;
    }

    System.out.println(
        "sending "
            + num_msgs
            + " messages ("
            + Util.printBytes(msg_size)
            + ") to "
            + remote
            + ": oob="
            + oob
            + ", "
            + num_threads
            + " sender thread(s)");
    ByteBuffer buf =
        ByteBuffer.allocate(Global.BYTE_SIZE + Global.LONG_SIZE).put(START).putLong(num_msgs);
    Message msg = new Message(null, buf.array());
    // msg.writeTo(output);

    ExposedByteArrayOutputStream out_stream = new ExposedByteArrayOutputStream((int) (msg.size()));
    ExposedDataOutputStream dos = new ExposedDataOutputStream(out_stream);
    byte flags = 0;
    dos.writeShort(Version.version); // write the version
    if (msg.getDest() == null) flags += (byte) 2;
    dos.writeByte(flags);
    msg.writeTo(dos);
    Buffer buffer = new Buffer(out_stream.getRawBuffer(), 0, out_stream.size());

    output_lock.lock(); // need to sync if we have more than 1 sender
    try {
      // msg.writeTo(output);
      output.writeInt(buffer.getLength());
      output.write(buffer.getBuf(), buffer.getOffset(), buffer.getLength());
    } finally {
      output_lock.unlock();
    }

    int msgs_per_sender = num_msgs / num_threads;
    Sender[] senders = new Sender[num_threads];
    for (int i = 0; i < senders.length; i++)
      senders[i] = new Sender(msgs_per_sender, msg_size, num_msgs / 10);
    for (Sender sender : senders) sender.start();
    for (Sender sender : senders) sender.join();
    output.flush();
    System.out.println("done sending " + num_msgs + " to " + remote);
  }
  public synchronized void write(Buffer buffer) throws IOException {
    long bufOffset = buffer.getOffset();

    if (bufOffset == -1) {
      if (file.getFilePointer() != this.offset) {
        throw new IOException("Invalid offset: " + bufOffset);
      }
    } else {
      file.seek(bufOffset);
    }

    file.write(buffer.getBuffer(), 0, buffer.getLength());
    this.offset += buffer.getLength();
  }
    /**
     * Reads media data from this <tt>PullBufferStream</tt> into a specific <tt>Buffer</tt> with
     * blocking.
     *
     * @param buffer the <tt>Buffer</tt> in which media data is to be read from this
     *     <tt>PullBufferStream</tt>
     * @throws IOException if anything goes wrong while reading media data from this
     *     <tt>PullBufferStream</tt> into the specified <tt>buffer</tt>
     * @see javax.media.protocol.PullBufferStream#read(javax.media.Buffer)
     */
    public void read(Buffer buffer) throws IOException {
      if (setThreadPriority) {
        setThreadPriority = false;
        setThreadPriority();
      }

      Object data = buffer.getData();
      int length = this.length;

      if (data instanceof byte[]) {
        if (((byte[]) data).length < length) data = null;
      } else data = null;
      if (data == null) {
        data = new byte[length];
        buffer.setData(data);
      }

      int toRead = length;
      byte[] bytes = (byte[]) data;
      int offset = 0;

      buffer.setLength(0);
      while (toRead > 0) {
        int read;

        synchronized (this) {
          if (audioRecord.getRecordingState() == AudioRecord.RECORDSTATE_RECORDING)
            read = audioRecord.read(bytes, offset, toRead);
          else break;
        }

        if (read < 0) {
          throw new IOException(
              AudioRecord.class.getName() + "#read(byte[], int, int) returned " + read);
        } else {
          buffer.setLength(buffer.getLength() + read);
          offset += read;
          toRead -= read;
        }
      }
      buffer.setOffset(0);

      // Apply software gain.
      if (gainControl != null) {
        BasicVolumeControl.applyGain(gainControl, bytes, buffer.getOffset(), buffer.getLength());
      }
    }
Exemple #19
0
  /** decode the buffer * */
  public int process(Buffer inputBuffer, Buffer outputBuffer) {

    if (!checkInputBuffer(inputBuffer)) {
      return BUFFER_PROCESSED_FAILED;
    }

    if (isEOM(inputBuffer)) {
      propagateEOM(outputBuffer);
      return BUFFER_PROCESSED_OK;
    }

    Object outData = outputBuffer.getData();
    outputBuffer.setData(inputBuffer.getData());
    inputBuffer.setData(outData);
    outputBuffer.setLength(inputBuffer.getLength());
    outputBuffer.setFormat(outputFormat);
    outputBuffer.setOffset(inputBuffer.getOffset());
    return BUFFER_PROCESSED_OK;
  }
Exemple #20
0
  /** {@inheritDoc} */
  @Override
  protected int doProcess(Buffer inBuffer, Buffer outBuffer) {
    byte[] inData = (byte[]) inBuffer.getData();
    int inOffset = inBuffer.getOffset();

    if (!VP8PayloadDescriptor.isValid(inData, inOffset)) {
      logger.warn("Invalid RTP/VP8 packet discarded.");
      outBuffer.setDiscard(true);
      return BUFFER_PROCESSED_FAILED; // XXX: FAILED or OK?
    }

    long inSeq = inBuffer.getSequenceNumber();
    long inRtpTimestamp = inBuffer.getRtpTimeStamp();
    int inPictureId = VP8PayloadDescriptor.getPictureId(inData, inOffset);
    boolean inMarker = (inBuffer.getFlags() & Buffer.FLAG_RTP_MARKER) != 0;
    boolean inIsStartOfFrame = VP8PayloadDescriptor.isStartOfFrame(inData, inOffset);
    int inLength = inBuffer.getLength();
    int inPdSize = VP8PayloadDescriptor.getSize(inData, inOffset);
    int inPayloadLength = inLength - inPdSize;

    if (empty && lastSentSeq != -1 && seqNumComparator.compare(inSeq, lastSentSeq) != 1) {
      if (logger.isInfoEnabled()) logger.info("Discarding old packet (while empty) " + inSeq);
      outBuffer.setDiscard(true);
      return BUFFER_PROCESSED_OK;
    }

    if (!empty) {
      // if the incoming packet has a different PictureID or timestamp
      // than those of the current frame, then it belongs to a different
      // frame.
      if ((inPictureId != -1 && pictureId != -1 && inPictureId != pictureId)
          | (timestamp != -1 && inRtpTimestamp != -1 && inRtpTimestamp != timestamp)) {
        if (seqNumComparator.compare(inSeq, firstSeq) != 1) // inSeq <= firstSeq
        {
          // the packet belongs to a previous frame. discard it
          if (logger.isInfoEnabled()) logger.info("Discarding old packet " + inSeq);
          outBuffer.setDiscard(true);
          return BUFFER_PROCESSED_OK;
        } else // inSeq > firstSeq (and also presumably isSeq > lastSeq)
        {
          // the packet belongs to a subsequent frame (to the one
          // currently being held). Drop the current frame.

          if (logger.isInfoEnabled())
            logger.info(
                "Discarding saved packets on arrival of"
                    + " a packet for a subsequent frame: "
                    + inSeq);

          // TODO: this would be the place to complain about the
          // not-well-received PictureID by sending a RTCP SLI or NACK.
          reinit();
        }
      }
    }

    // a whole frame in a single packet. avoid the extra copy to
    // this.data and output it immediately.
    if (empty && inMarker && inIsStartOfFrame) {
      byte[] outData = validateByteArraySize(outBuffer, inPayloadLength, false);
      System.arraycopy(inData, inOffset + inPdSize, outData, 0, inPayloadLength);
      outBuffer.setOffset(0);
      outBuffer.setLength(inPayloadLength);
      outBuffer.setRtpTimeStamp(inBuffer.getRtpTimeStamp());

      if (TRACE) logger.trace("Out PictureID=" + inPictureId);

      lastSentSeq = inSeq;

      return BUFFER_PROCESSED_OK;
    }

    // add to this.data
    Container container = free.poll();
    if (container == null) container = new Container();
    if (container.buf == null || container.buf.length < inPayloadLength)
      container.buf = new byte[inPayloadLength];

    if (data.get(inSeq) != null) {
      if (logger.isInfoEnabled())
        logger.info("(Probable) duplicate packet detected, discarding " + inSeq);
      outBuffer.setDiscard(true);
      return BUFFER_PROCESSED_OK;
    }

    System.arraycopy(inData, inOffset + inPdSize, container.buf, 0, inPayloadLength);
    container.len = inPayloadLength;
    data.put(inSeq, container);

    // update fields
    frameLength += inPayloadLength;
    if (firstSeq == -1 || (seqNumComparator.compare(firstSeq, inSeq) == 1)) firstSeq = inSeq;
    if (lastSeq == -1 || (seqNumComparator.compare(inSeq, lastSeq) == 1)) lastSeq = inSeq;

    if (empty) {
      // the first received packet for the current frame was just added
      empty = false;
      timestamp = inRtpTimestamp;
      pictureId = inPictureId;
    }

    if (inMarker) haveEnd = true;
    if (inIsStartOfFrame) haveStart = true;

    // check if we have a full frame
    if (frameComplete()) {
      byte[] outData = validateByteArraySize(outBuffer, frameLength, false);
      int ptr = 0;
      Container b;
      for (Map.Entry<Long, Container> entry : data.entrySet()) {
        b = entry.getValue();
        System.arraycopy(b.buf, 0, outData, ptr, b.len);
        ptr += b.len;
      }

      outBuffer.setOffset(0);
      outBuffer.setLength(frameLength);
      outBuffer.setRtpTimeStamp(inBuffer.getRtpTimeStamp());

      if (TRACE) logger.trace("Out PictureID=" + inPictureId);
      lastSentSeq = lastSeq;

      // prepare for the next frame
      reinit();

      return BUFFER_PROCESSED_OK;
    } else {
      // frame not complete yet
      outBuffer.setDiscard(true);
      return OUTPUT_BUFFER_NOT_FILLED;
    }
  }
  public int process(Buffer inputBuffer, Buffer outputBuffer) {

    if (pendingFrames > 0) {
      // System.out.println("packetizing");
      return BUFFER_PROCESSED_OK;
    }

    if (!checkInputBuffer(inputBuffer)) {
      return BUFFER_PROCESSED_FAILED;
    }

    if (isEOM(inputBuffer)) {
      propagateEOM(outputBuffer);
      return BUFFER_PROCESSED_OK;
    }

    int inpOffset = inputBuffer.getOffset();
    int inpLength = inputBuffer.getLength();
    int outLength = 0;
    int outOffset = 0;
    byte[] inpData = (byte[]) inputBuffer.getData();
    byte[] outData =
        validateByteArraySize(outputBuffer, calculateOutputSize(inpData.length + historySize));
    int historyLength = history.getLength();
    byte[] historyData = validateByteArraySize(history, historySize);
    int framesNumber = calculateFramesNumber(inpData.length + historySize);

    if ((regions == null) || (regions.length < framesNumber + 1))
      regions = new int[framesNumber + 1];

    if ((regionsTypes == null) || (regionsTypes.length < framesNumber))
      regionsTypes = new int[framesNumber];

    if (historyLength != 0) {
      int bytesToCopy = (historyData.length - historyLength);
      if (bytesToCopy > inpLength) {
        bytesToCopy = inpLength;
      }

      System.arraycopy(inpData, inpOffset, historyData, historyLength, bytesToCopy);

      codecProcess(
          historyData,
          0,
          outData,
          outOffset,
          historyLength + bytesToCopy,
          readBytes,
          writeBytes,
          frameNumber,
          regions,
          regionsTypes);

      if (readBytes[0] <= 0) {
        if (writeBytes[0] <= 0) {
          // System.err.println("Returning output buffer not filled");
          return OUTPUT_BUFFER_NOT_FILLED;
        } else {
          updateOutput(outputBuffer, outputFormat, writeBytes[0], 0);
          // System.err.println("Returning OK");
          return BUFFER_PROCESSED_OK;
        }
      }

      // System.out.println("1: "+inpLength+" "+readBytes[0]+" "+writeBytes[0]);

      outOffset += writeBytes[0];
      outLength += writeBytes[0];

      inpOffset += (readBytes[0] - historyLength);
      inpLength += (historyLength - readBytes[0]);
    }

    codecProcess(
        inpData,
        inpOffset,
        outData,
        outOffset,
        inpLength,
        readBytes,
        writeBytes,
        frameNumber,
        regions,
        regionsTypes);
    // System.out.println("2: "+inpLength+" "+readBytes[0]+" "+writeBytes[0]);

    // debug
    // for (int i=0; i<frameNumber[0];i++ ) {
    // System.out.println(i+" "+regions[i]+" - "+regions[i+1]+" type "+regionsTypes[i]);
    // }

    outLength += writeBytes[0];

    inpOffset += readBytes[0];
    inpLength -= readBytes[0];

    System.arraycopy(inpData, inpOffset, historyData, 0, inpLength);
    history.setLength(inpLength);

    updateOutput(outputBuffer, outputFormat, outLength, 0);

    return BUFFER_PROCESSED_OK;
  }