Save @packet to a new file beginning with @prefix. Append a sequential suffix to ensure we don't
overwrite existing files.
@param packet The data packet to dump to disk
@param prefix The start of the file name
188963
@SuppressWarnings("unused")
    public static void dumpPacket(DatagramPacket packet, String prefix) {
        byte[] buffer = new byte[packet.getLength()];
        System.arraycopy(packet.getData(), packet.getOffset(), buffer, 0, packet.getLength());
        printBuffer(buffer, "Buffer to save");
        try {
            Path path = getNextPath(prefix);
            logger.info("Dumping buffer to {}", path);
            Files.write(path, buffer);
        } catch (IOException e) {
            logger.error("Error writing file: {}", e.getLocalizedMessage());
        }
    }
457513
protected OggStreamPacket createNext(OggPacket packet) {
        if (type == OggStreamIdentifier.OGG_VORBIS) {
            return VorbisPacketFactory.create(packet);
        } else if (type == OggStreamIdentifier.SPEEX_AUDIO) {
            return SpeexPacketFactory.create(packet);
        } else if (type == OggStreamIdentifier.OPUS_AUDIO) {
            return OpusPacketFactory.create(packet);
        } else if (type == OggStreamIdentifier.OGG_FLAC) {
            // TODO Finish FLAC support
            return null;
        } else {
            throw new IllegalArgumentException("Unsupported stream of type " + type);
        }
    }
172103
public File createDirectorySync(String prefix) throws IOException {
		Path path = Files.createTempDirectory(tempDir.toPath(), this.prefix + prefix);
		File dir = path.toFile();
		/*
		app.toClose(new Closeable() {
			@Override
			public void close() {
				new RemoveDirectoryTask(dir, null, 0, null, Task.PRIORITY_NORMAL, false).start();
			}
		});*/
		return dir;
	}
649878
@Override
	public boolean appendOutgoingData()
	{
		while (outputBuffer.remaining() > 0)
		{
			if (packetOutputBuffer.size() == 0)
			{
				if (sendQueue.size() == 0)
					return true; // No more packet to send
				
				if (outputBuffer.remaining() < 4) // packet_size = sizeof(int) = 4
					return true; // Not enough space to proceed
				
				// Write packet size
				if (!serializePacket(sendQueue.getFirst(),packetOutputBuffer))
					return false; // Invalid packet
				outputBuffer.putInt(packetOutputBuffer.size());
				currentOutputOffset = 0;
			}
			else
			{
				int writeAmount = Math.min(outputBuffer.remaining(),packetOutputBuffer.size() - currentOutputOffset);
				packetOutputBuffer.putTo(outputBuffer, currentOutputOffset, writeAmount);
				currentOutputOffset += writeAmount;
				
				// Packet completly sent ?
				if (currentOutputOffset == packetOutputBuffer.size())
				{
					AbstractPacket sentPacket;
					synchronized (sendQueue)
					{
						sentPacket = sendQueue.removeFirst();
					}
					packetOutputBuffer.clear();
					
					if (listener != null)
						listener.packetSent(sentPacket);
				}
			}
		}
		return true;
	}
1272142
public static boolean startsWith(byte[] bytes, byte[] prefix) {
    return bytes != null && prefix != null &&
        bytes.length >= prefix.length &&
        LexicographicalComparerHolder.BEST_COMPARER.
        compareTo(bytes, 0, prefix.length, prefix, 0, prefix.length) == 0;
  }
697008
public void append(byte[] data, int start, int len) {
        if (len <= 0) {
            return;
        }
        byte[] newData = new byte[len];
        System.arraycopy(data, 0, newData, 0, len);
        append(newData);
    }
717674
public void append(final byte[] data, final int start, final int len) {
		final int oldLength = this.bytes.length;
		setCapacity(this.bytes.length + len, true);
		System.arraycopy(data, start, this.bytes, oldLength, len);
	}
1021226
def write(self, pkt):
        
        if isinstance(pkt, bytes):
            if not self.header_present:
                self._write_header(pkt)
            self._write_packet(pkt)
        else:
            pkt = pkt.__iter__()
            for p in pkt:
                if not self.header_present:
                    self._write_header(p)
                self._write_packet(p)
1198660
public void writeTo(final PacketOutputStream pos) throws IOException {
    pos.write(BINARY_INTRODUCER);
    if (length == Long.MAX_VALUE) {
      pos.write(is, true, noBackslashEscapes);
    } else {
      pos.write(is, length, true, noBackslashEscapes);
    }
    pos.write(QUOTE);

  }
315662
protected Packet createPacket() throws IOException {
		synchronized (packets) {
			if (packets.size() == 0)
				return new Packet();
			Packet p = (Packet) packets.elementAt(0);
			packets.removeElementAt(0);
			return p;
		}
	}
856101
public IoBuffer encodePacket(Packet packet) {
        IoBuffer out = null;
        Header header = packet.getHeader();
        int channelId = header.getChannelId();
        //log.trace("Channel id: {}", channelId);
        IRTMPEvent message = packet.getMessage();
        if (message instanceof ChunkSize) {
            ChunkSize chunkSizeMsg = (ChunkSize) message;
            ((RTMPConnection) Red5.getConnectionLocal()).getState().setWriteChunkSize(chunkSizeMsg.getSize());
        }
        // normally the message is expected not to be dropped
        if (!dropMessage(channelId, message)) {
            //log.trace("Header time: {} message timestamp: {}", header.getTimer(), message.getTimestamp());
            IoBuffer data = encodeMessage(header, message);
            if (data != null) {
                RTMP rtmp = ((RTMPConnection) Red5.getConnectionLocal()).getState();
                // set last write packet
                rtmp.setLastWritePacket(channelId, packet);
                // ensure we're at the beginning
                if (data.position() != 0) {
                    data.flip();
                } else {
                    data.rewind();
                }
                // length of the data to be chunked
                int dataLen = data.limit();
                header.setSize(dataLen);
                //if (log.isTraceEnabled()) {
                    //log.trace("Message: {}", data);
                //}
                // chunk size for writing
                int chunkSize = rtmp.getWriteChunkSize();
                // number of chunks to write
                int numChunks = (int) Math.ceil(dataLen / (float) chunkSize);
                // get last header
                Header lastHeader = rtmp.getLastWriteHeader(channelId);
                if (log.isTraceEnabled()) {
                    log.trace("Channel id: {} chunkSize: {}", channelId, chunkSize);
                }
                // attempt to properly guess the size of the buffer we'll need
                int bufSize = dataLen + 18 + (numChunks * 2);
                //log.trace("Allocated buffer size: {}", bufSize);
                out = IoBuffer.allocate(bufSize, false);
                out.setAutoExpand(true);
                do {
                    // encode the header
                    encodeHeader(header, lastHeader, out);
                    // write a chunk
                    byte[] buf = new byte[Math.min(chunkSize, data.remaining())];
                    data.get(buf);
                    //log.trace("Buffer: {}", Hex.encodeHexString(buf));
                    out.put(buf);
                    // move header over to last header
                    lastHeader = header.clone();
                } while (data.hasRemaining());
                // collapse the time stamps on the last header after decode is complete
                lastHeader.setTimerBase(lastHeader.getTimer());
                // clear the delta
                lastHeader.setTimerDelta(0);
                // set last write header
                rtmp.setLastWriteHeader(channelId, lastHeader);
                data.free();
                out.flip();
                data = null;
            }
        }
        message.release();
        return out;
    }
1015409
public void processPacket(OggPacket packet) {
        SkeletonPacket skel = SkeletonPacketFactory.create(packet);

        // First packet must be the head
        if (packet.isBeginningOfStream()) {
            fishead = (SkeletonFishead)skel;
        } else if (skel instanceof SkeletonFisbone) {
            SkeletonFisbone bone = (SkeletonFisbone)skel;
            fisbones.add(bone);
            bonesByStream.put(bone.getSerialNumber(), bone);
        } else if (skel instanceof SkeletonKeyFramePacket) {
            keyFrames.add((SkeletonKeyFramePacket)skel);
        } else {
            throw new IllegalStateException("Unexpected Skeleton " + skel);
        }

        if (packet.isEndOfStream()) {
            hasWholeStream = true;
        }
    }
149215
public static SpeexPacket create(OggPacket packet) {
       // Special header types detection
       if(isSpeexSpecial(packet)) {
           return new SpeexInfo(packet);
       }
       if (packet.getSequenceNumber() == 1 && packet.getGranulePosition() == 0) {
           return new SpeexTags(packet);
       }

       return new SpeexAudioData(packet);
   }
160848
private Packet addTcpdumpInfoToPacket(Packet parsedPacket){ 

        int packetSize = parsedPacket.getPacketSize();
        
        tcpdumpReader.readNewPacket(packetSize);

        // Get Tcp Payload
        if ( parsedPacket.isTcp() ) {       
            int payloadSize = parsedPacket.getTcpPayloadSize();
            int payloadStart = parsedPacket.getTcpPayloadStart();
            parsedPacket.setTcpPayload(tcpdumpReader.getPayload(payloadStart, payloadSize));
        }
        
        tcpdumpReader.packetReadComplete();
        
        return parsedPacket;
    }
1131747
private void makeNewFile() throws IOException {
		String filename=prefix+(files.size()+1)+suffix;
		File file=new File(parent, filename);
		out=new FileOutputStream(file);
		bytesOut=0;
		files.add(file);
	}
1228552
@Override
	public void send( AbstractPacket packet ) throws PacketTransportException
    {
        if (closed)
   			throw new PacketTransportException("Transport is closed");
        
        sender.send(packet);
    }
749470
def encode(self, packet):
        

        id = identifier.get_packet_id(packet)
        if id is None:
            raise EncoderException('unknown packet')

        self._write_variunt(id)
        self._write(packet.SerializeToString())

        return bytes(self.buffer)