Posted By

rowntreerob on 08/18/11


Tagged

rtsp audio stream rtp


Versions (?)

RTP packet handler


 / Published in: Java
 

java handler for RTP raw audio packet in: com.biasedbit.com.efflux.packet.DataPacket

  1. public static DataPacket decode(ChannelBuffer buffer) throws IndexOutOfBoundsException {
  2. if (buffer.readableBytes() < 12) {
  3. throw new IllegalArgumentException("A RTP packet must be at least 12 octets long");
  4. }
  5.  
  6. // Version, Padding, eXtension, CSRC Count
  7. DataPacket packet = new DataPacket();
  8. byte b = buffer.readByte();
  9. packet.version = RtpVersion.fromByte(b);
  10. boolean padding = (b & 0x20) > 0; // mask 0010 0000
  11. boolean extension = (b & 0x10) > 0; // mask 0001 0000
  12. int contributingSourcesCount = b & 0x0f; // mask 0000 1111
  13.  
  14. // Marker, Payload Type
  15. b = buffer.readByte();
  16. packet.marker = (b & 0x80) > 0; // mask 0000 0001
  17. packet.payloadType = (b & 0x7f); // mask 0111 1111
  18.  
  19. packet.sequenceNumber = buffer.readUnsignedShort();
  20. packet.timestamp = buffer.readUnsignedInt();
  21. packet.ssrc = buffer.readUnsignedInt();
  22.  
  23. // Read extension headers & data
  24. if (extension) {
  25. packet.extensionHeaderData = buffer.readShort();
  26. packet.extensionData = new byte[buffer.readUnsignedShort()];
  27. buffer.readBytes(packet.extensionData);
  28. }
  29.  
  30. // Read CCRC's
  31. if (contributingSourcesCount > 0) {
  32. packet.contributingSourceIds = new ArrayList<Long>(contributingSourcesCount);
  33. for (int i = 0; i < contributingSourcesCount; i++) {
  34. long contributingSource = buffer.readUnsignedInt();
  35. packet.contributingSourceIds.add(contributingSource);
  36. }
  37. }
  38.  
  39. if (!padding) {
  40. // No padding used, assume remaining data is the packet
  41. byte[] remainingBytes = new byte[buffer.readableBytes()];
  42. buffer.readBytes(remainingBytes);
  43. packet.setData(remainingBytes);
  44. } else {
  45. // Padding bit was set, so last byte contains the number of padding octets that should be discarded.
  46. short lastByte = buffer.getUnsignedByte(buffer.readerIndex() + buffer.readableBytes() - 1);
  47. byte[] dataBytes = new byte[buffer.readableBytes() - lastByte];
  48. buffer.readBytes(dataBytes);
  49. packet.setData(dataBytes);
  50. // Discard rest of buffer.
  51. buffer.skipBytes(buffer.readableBytes());
  52. }
  53.  
  54. return packet;
  55. }

Report this snippet  

You need to login to post a comment.