/** * Modifies current position. * * @param pos Current position in file */ private void setCurrentPosition(long pos) { if (pos == Long.MAX_VALUE) { pos = file.length(); } if (!useLoadBuf) { in.position((int) pos); return; } try { if (pos >= (channel.position() - in.limit()) && pos < channel.position()) { in.position((int) (pos - (channel.position() - in.limit()))); } else { channel.position(pos); fillBuffer(bufferSize, true); } } catch (Exception e) { log.error("Error setCurrentPosition", e); } }
@Override protected boolean doDecode(IoSession session, ByteBuffer in, ProtocolDecoderOutput out) throws Exception { final int origonPos = in.position(); if (in.remaining() < 16) { in.position(origonPos); return false; } int magic = in.getInt(); if (magic != Const.MAGIC) throw new IOException("flag error, except: " + Const.MAGIC + ", but get " + magic); int request = in.getInt(); int pcode = in.getInt(); int len = in.getInt(); if (in.remaining() < len) { in.position(origonPos); return false; } byte[] data = new byte[len]; in.get(data); BaseResponsePacket packet = PacketCode.createPacket(pcode, request, data); out.write(packet); return true; }
/** * Get the current position in a file or ByteBuffer. * * @return Current position in a file */ private long getCurrentPosition() { long pos; if (!useLoadBuf) { return in.position(); } try { if (in != null) { pos = (channel.position() - in.remaining()); } else { pos = channel.position(); } return pos; } catch (Exception e) { log.error("Error getCurrentPosition", e); return 0; } }
/** {@inheritDoc} */ public synchronized ITag readTag() { long oldPos = getCurrentPosition(); ITag tag = readTagHeader(); if (tagPosition == 0 && tag.getDataType() != TYPE_METADATA && generateMetadata) { // Generate initial metadata automatically setCurrentPosition(oldPos); KeyFrameMeta meta = analyzeKeyFrames(); tagPosition++; if (meta != null) { return createFileMeta(); } } ByteBuffer body = ByteBuffer.allocate(tag.getBodySize(), false); // XXX Paul: this assists in 'properly' handling damaged FLV files long newPosition = getCurrentPosition() + tag.getBodySize(); if (newPosition <= getTotalBytes()) { int limit; while (getCurrentPosition() < newPosition) { fillBuffer(newPosition - getCurrentPosition()); if (getCurrentPosition() + in.remaining() > newPosition) { limit = in.limit(); in.limit((int) (newPosition - getCurrentPosition()) + in.position()); body.put(in); in.limit(limit); } else { body.put(in); } } body.flip(); tag.setBody(body); tagPosition++; } return tag; }