code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
package com.ams.protocol.rtmp;
import java.io.IOException;
import com.ams.io.BufferList;
import com.ams.io.BufferInputStream;
class RtmpChunkDataReader {
private RtmpHeader header;
private BufferList chunkData = new BufferList();
private int chunkSize;
public RtmpChunkDataReader(RtmpHeader header) {
this.header = header;
this.chunkSize = header.getSize();
}
public void read(BufferInputStream in, int size) throws IOException {
if (size <= 0)
return;
chunkData.write(in.readByteBuffer(size));
chunkSize -= size;
}
public BufferList getChunkData() {
return chunkData;
}
public int getChunkSize() {
return chunkSize;
}
public RtmpHeader getHeader() {
return header;
}
}
| Java |
package com.ams.protocol.rtmp;
public class RtmpHeader {
private int chunkStreamId;
private long timestamp;
private int size;
private int type;
private int streamId;
public RtmpHeader(int chunkStreamId, long timestamp, int size, int type,
int streamId) {
this.chunkStreamId = chunkStreamId;
this.timestamp = timestamp;
this.size = size;
this.type = type;
this.streamId = streamId;
}
public int getChunkStreamId() {
return chunkStreamId;
}
public void setChunkStreamId(int chunkStreamId) {
this.chunkStreamId = chunkStreamId;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public int getStreamId() {
return streamId;
}
public void setStreamId(int streamId) {
this.streamId = streamId;
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
public String toString() {
return chunkStreamId + ":" + timestamp + ":" + size + ":" + type + ":"
+ streamId;
}
} | Java |
package com.ams.protocol.rtmp;
public class RtmpException extends Exception {
private static final long serialVersionUID = 1L;
public RtmpException() {
super();
}
public RtmpException(String arg0) {
super(arg0);
}
}
| Java |
package com.ams.protocol.rtmp;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import com.ams.io.BufferList;
import com.ams.io.BufferInputStream;
import com.ams.io.BufferOutputStream;
import com.ams.protocol.rtmp.amf.Amf0Serializer;
import com.ams.protocol.rtmp.amf.AmfValue;
import com.ams.protocol.rtmp.message.*;
import com.ams.protocol.rtmp.so.SoMessage;
public class RtmpMessageSerializer {
private int writeChunkSize = 128;
private BufferOutputStream out;
private RtmpHeaderSerializer headerSerializer;
public RtmpMessageSerializer(BufferOutputStream out) {
super();
this.out = out;
this.headerSerializer = new RtmpHeaderSerializer(out);
}
public void write(int chunkStreamId, int streamId, long timestamp,
RtmpMessage message) throws IOException {
BufferList data = new BufferList();
BufferOutputStream bos = new BufferOutputStream(data);
int msgType = message.getType();
switch (msgType) {
case RtmpMessage.MESSAGE_USER_CONTROL:
int event = ((RtmpMessageUserControl) message).getEvent();
int sid = ((RtmpMessageUserControl) message).getStreamId();
int ts = ((RtmpMessageUserControl) message).getTimestamp();
bos.write16Bit(event);
switch (event) {
case RtmpMessageUserControl.EVT_STREAM_BEGIN:
case RtmpMessageUserControl.EVT_STREAM_EOF:
case RtmpMessageUserControl.EVT_STREAM_DRY:
case RtmpMessageUserControl.EVT_STREAM_IS_RECORDED:
bos.write32Bit(sid);
break;
case RtmpMessageUserControl.EVT_SET_BUFFER_LENGTH:
bos.write32Bit(sid);
bos.write32Bit(ts);
break;
case RtmpMessageUserControl.EVT_PING_REQUEST:
case RtmpMessageUserControl.EVT_PING_RESPONSE:
bos.write32Bit(ts);
break;
}
break;
case RtmpMessage.MESSAGE_AMF0_COMMAND: {
Amf0Serializer serializer = new Amf0Serializer(
new DataOutputStream(bos));
String name = ((RtmpMessageCommand) message).getName();
int transactionId = ((RtmpMessageCommand) message)
.getTransactionId();
AmfValue[] args = ((RtmpMessageCommand) message).getArgs();
serializer.write(new AmfValue(name));
serializer.write(new AmfValue(transactionId));
for (int i = 0, len = args.length; i < len; i++) {
serializer.write(args[i]);
}
break;
}
case RtmpMessage.MESSAGE_AMF3_COMMAND: {
bos.writeByte(0); // no used byte
Amf0Serializer serializer = new Amf0Serializer(
new DataOutputStream(bos));
String name = ((RtmpMessageCommand) message).getName();
int transactionId = ((RtmpMessageCommand) message)
.getTransactionId();
AmfValue[] args = ((RtmpMessageCommand) message).getArgs();
serializer.write(new AmfValue(name));
serializer.write(new AmfValue(transactionId));
for (int i = 0, len = args.length; i < len; i++) {
serializer.write(args[i]);
}
break;
}
case RtmpMessage.MESSAGE_AUDIO:
data = ((RtmpMessageAudio) message).getData();
break;
case RtmpMessage.MESSAGE_VIDEO:
data = ((RtmpMessageVideo) message).getData();
break;
case RtmpMessage.MESSAGE_AMF0_DATA:
data = ((RtmpMessageData) message).getData();
break;
case RtmpMessage.MESSAGE_AMF3_DATA:
data = ((RtmpMessageData) message).getData();
break;
case RtmpMessage.MESSAGE_SHARED_OBJECT:
SoMessage so = ((RtmpMessageSharedObject) message).getData();
SoMessage.write(new DataOutputStream(bos), so);
break;
case RtmpMessage.MESSAGE_CHUNK_SIZE:
int chunkSize = ((RtmpMessageChunkSize) message).getChunkSize();
bos.write32Bit(chunkSize);
writeChunkSize = chunkSize;
break;
case RtmpMessage.MESSAGE_ABORT:
sid = ((RtmpMessageAbort) message).getStreamId();
bos.write32Bit(sid);
break;
case RtmpMessage.MESSAGE_ACK:
int nbytes = ((RtmpMessageAck) message).getBytes();
bos.write32Bit(nbytes);
break;
case RtmpMessage.MESSAGE_WINDOW_ACK_SIZE:
int size = ((RtmpMessageWindowAckSize) message).getSize();
bos.write32Bit(size);
break;
case RtmpMessage.MESSAGE_PEER_BANDWIDTH:
int windowAckSize = ((RtmpMessagePeerBandwidth) message)
.getWindowAckSize();
byte limitType = ((RtmpMessagePeerBandwidth) message)
.getLimitType();
bos.write32Bit(windowAckSize);
bos.writeByte(limitType);
break;
case RtmpMessage.MESSAGE_UNKNOWN:
int t = ((RtmpMessageUnknown) message).getMessageType();
data = ((RtmpMessageUnknown) message).getData();
break;
}
bos.flush();
int dataSize = data.remaining();
RtmpHeader header = new RtmpHeader(chunkStreamId, timestamp, dataSize,
msgType, streamId);
// write packet header + data
headerSerializer.write(header);
if (data == null)
return;
BufferInputStream ds = new BufferInputStream(data);
ByteBuffer[] packet = null;
if (dataSize <= writeChunkSize) {
packet = ds.readByteBuffer(dataSize);
out.writeByteBuffer(packet);
} else {
packet = ds.readByteBuffer(writeChunkSize);
out.writeByteBuffer(packet);
int len = dataSize - writeChunkSize;
RtmpHeader h = new RtmpHeader(chunkStreamId, -1, -1, -1, -1);
while (len > 0) {
headerSerializer.write(h);
int bytes = (len > writeChunkSize) ? writeChunkSize : len;
packet = ds.readByteBuffer(bytes);
out.writeByteBuffer(packet);
len -= bytes;
}
}
}
public int getWriteChunkSize() {
return writeChunkSize;
}
public void setWriteChunkSize(int writeChunkSize) {
this.writeChunkSize = writeChunkSize;
}
}
| Java |
package com.ams.protocol.rtmp.net;
import java.io.IOException;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ams.media.MediaMessage;
import com.ams.protocol.rtmp.amf.*;
import com.ams.protocol.rtmp.RtmpConnection;
import com.ams.protocol.rtmp.message.*;
public class NetStream {
final private Logger logger = LoggerFactory.getLogger(NetStream.class);
private RtmpConnection rtmp;
private int chunkStreamId = 3;
private int streamId;
private String streamName;
private int transactionId = 0;
private long timestamp = 0;
public NetStream(RtmpConnection rtmp, int streamId) {
this.rtmp = rtmp;
this.streamId = streamId;
}
public void writeMessage(RtmpMessage message) throws IOException {
if (message instanceof RtmpMessageVideo) {
rtmp.writeRtmpMessage(5, streamId, timestamp, message);
} else if (message instanceof RtmpMessageAudio) {
rtmp.writeRtmpMessage(6, streamId, timestamp, message);
} else {
rtmp.writeRtmpMessage(chunkStreamId, streamId, timestamp, message);
}
}
public void writeMessage(long time, RtmpMessage message) throws IOException {
rtmp.writeRtmpMessage(chunkStreamId, streamId, time, message);
}
public void sendMediaMessage(MediaMessage msg) throws IOException {
setTimestamp(msg.getTimestamp());
writeMessage(msg.toRtmpMessage());
}
public void writeStatusMessage(String status, AmfValue info)
throws IOException {
AmfValue value = AmfValue.newObject();
value.put("level", "status").put("code", status);
Map<String, AmfValue> v = info.object();
for (String key : v.keySet()) {
value.put(key, v.get(key).toString());
}
writeMessage(new RtmpMessageCommand("onStatus", transactionId,
AmfValue.array(null, value)));
}
public void writeErrorMessage(String msg) throws IOException {
AmfValue value = AmfValue.newObject();
value.put("level", "error").put("code", "NetStream.Error")
.put("details", msg);
writeMessage(new RtmpMessageCommand("onStatus", transactionId,
AmfValue.array(null, value)));
}
public void writeDataMessage(AmfValue[] values) throws IOException {
writeMessage(new RtmpMessageData(AmfValue.toBinary(values)));
}
public void writeSeekMessage(int time) throws IOException {
// clear
rtmp.writeProtocolControlMessage(new RtmpMessageUserControl(
RtmpMessageUserControl.EVT_STREAM_EOF, streamId));
rtmp.writeProtocolControlMessage(new RtmpMessageUserControl(
RtmpMessageUserControl.EVT_STREAM_IS_RECORDED, streamId));
rtmp.writeProtocolControlMessage(new RtmpMessageUserControl(
RtmpMessageUserControl.EVT_STREAM_BEGIN, streamId));
writeStatusMessage(
"NetStream.Seek.Notify",
AmfValue.newObject()
.put("description", "Seeking " + time + ".")
.put("details", streamName).put("clientId", streamId));
writeStatusMessage(
"NetStream.Play.Start",
AmfValue.newObject()
.put("description", "Start playing " + streamName + ".")
.put("clientId", streamId));
}
public void writePlayMessage() throws IOException {
// set chunk size
//rtmp.writeProtocolControlMessage(new RtmpMessageChunkSize(1024));
// NetStream.Play.Reset
writeStatusMessage(
"NetStream.Play.Reset",
AmfValue.newObject()
.put("description", "Resetting " + streamName + ".")
.put("details", streamName).put("clientId", streamId));
// clear
rtmp.writeProtocolControlMessage(new RtmpMessageUserControl(
RtmpMessageUserControl.EVT_STREAM_IS_RECORDED, streamId));
rtmp.writeProtocolControlMessage(new RtmpMessageUserControl(
RtmpMessageUserControl.EVT_STREAM_BEGIN, streamId));
// NetStream.Play.Start
writeStatusMessage(
"NetStream.Play.Start",
AmfValue.newObject()
.put("description", "Start playing " + streamName + ".")
.put("clientId", streamId));
}
public void writeStopMessage() throws IOException {
// clear
rtmp.writeProtocolControlMessage(new RtmpMessageUserControl(
RtmpMessageUserControl.EVT_STREAM_EOF, streamId));
// NetStream.Play.Complete
writeDataMessage(AmfValue.array("onPlayStatus", AmfValue.newObject()
.put("level", "status").put("code", "NetStream.Play.Complete")));
// NetStream.Play.Stop
writeStatusMessage(
"NetStream.Play.Stop",
AmfValue.newObject()
.put("description",
"Stoped playing " + streamName + ".")
.put("clientId", streamId));
}
public void writePauseMessage(boolean pause) throws IOException {
writeStatusMessage((pause ? "NetStream.Pause.Notify"
: "NetStream.Unpause.Notify"), AmfValue.newObject());
}
public void writePublishMessage(String publishName) throws IOException {
writeStatusMessage("NetStream.Publish.Start",
AmfValue.newObject().put("details", publishName));
}
public void flush() throws IOException {
rtmp.flush();
}
public void setStreamName(String streamName) {
this.streamName = streamName;
}
public void setChunkStreamId(int chunkStreamId) {
this.chunkStreamId = chunkStreamId;
}
public void setTransactionId(int transactionId) {
this.transactionId = transactionId;
}
public int getStreamId() {
return streamId;
}
public String getStreamName() {
return streamName;
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
} | Java |
package com.ams.protocol.rtmp.net;
import java.util.ArrayList;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ams.server.handler.ProtocolHandler;
import com.ams.util.ObjectCache;
public class StreamPublisherManager {
final private static Logger logger = LoggerFactory
.getLogger(StreamPublisherManager.class);
private static int DEFAULT_EXPIRE_TIME = 24 * 60 * 60;
private static ObjectCache<StreamPublisher> streamPublishers = new ObjectCache<StreamPublisher>();
private static ArrayList<ProtocolHandler> replicationSubscribeHandlers;
public static StreamPublisher getPublisher(String publishName) {
return streamPublishers.get(publishName);
}
public static void addPublisher(StreamPublisher publisher) {
String publishName = publisher.getPublishName();
streamPublishers.put(publishName, publisher, DEFAULT_EXPIRE_TIME);
logger.debug("add publisher:{}", publishName);
}
public static void removePublisher(String publishName) {
streamPublishers.remove(publishName);
logger.debug("remove publisher:{}", publishName);
}
public static Set<String> getAllPublishName() {
return streamPublishers.keySet();
}
}
| Java |
package com.ams.protocol.rtmp.net;
import java.io.IOException;
import com.ams.io.BufferInputStream;
import com.ams.io.BufferList;
import com.ams.io.RandomAccessFileReader;
import com.ams.media.IMediaDeserializer;
import com.ams.media.MediaMessage;
import com.ams.media.flv.FlvDeserializer;
import com.ams.media.mp4.Mp4Deserializer;
import com.ams.protocol.rtmp.amf.AmfValue;
import com.ams.protocol.rtmp.message.*;
public class StreamPlayer {
private static int BUFFER_TIME = 3 * 1000; // x seconds of buffering
private NetStream stream = null;
private IMediaDeserializer deserializer;
private long startTime = -1;
private long bufferTime = BUFFER_TIME;
private boolean pause = false;
private boolean audioPlaying = true;
private boolean videoPlaying = true;
public StreamPlayer(IMediaDeserializer deserializer, NetStream stream)
throws IOException {
this.deserializer = deserializer;
this.stream = stream;
}
public void close() {
deserializer.close();
}
private void writeStartData() throws IOException {
// |RtmpSampleAccess
stream.writeDataMessage(AmfValue.array("|RtmpSampleAccess", false,
false));
// NetStream.Data.Start
stream.writeDataMessage(AmfValue.array("onStatus", AmfValue.newObject()
.put("code", "NetStream.Data.Start")));
MediaMessage metaData = deserializer.metaData();
if (metaData != null) {
stream.writeMessage(metaData.toRtmpMessage());
}
MediaMessage videoHeaderData = deserializer.videoHeaderData();
if (videoHeaderData != null) {
stream.writeMessage(videoHeaderData.toRtmpMessage());
}
MediaMessage audioHeaderData = deserializer.audioHeaderData();
if (audioHeaderData != null) {
stream.writeMessage(audioHeaderData.toRtmpMessage());
}
}
public void seek(long seekTime) throws IOException {
MediaMessage sample = deserializer.seek(seekTime);
if (sample != null) {
long currentTime = sample.getTimestamp();
startTime = System.currentTimeMillis() - bufferTime - currentTime;
stream.setTimestamp(currentTime);
}
pause(false);
writeStartData();
}
public void play() throws IOException {
if (pause)
return;
long time = System.currentTimeMillis() - startTime;
while (stream.getTimestamp() < time) {
MediaMessage sample = deserializer.readNext();
if (sample == null) {
break;
}
long timestamp = sample.getTimestamp();
stream.setTimestamp(timestamp);
BufferList data = sample.getData();
if (sample.isAudio() && audioPlaying) {
stream.writeMessage(new RtmpMessageAudio(data));
} else if (sample.isVideo() && videoPlaying) {
stream.writeMessage(new RtmpMessageVideo(data));
} else if (sample.isMeta()) {
stream.writeMessage(new RtmpMessageData(data));
}
}
}
public void pause(boolean pause) {
this.pause = pause;
}
public boolean isPaused() {
return pause;
}
public void audioPlaying(boolean flag) {
this.audioPlaying = flag;
}
public void videoPlaying(boolean flag) {
this.videoPlaying = flag;
}
public void setBufferTime(long bufferTime) {
this.bufferTime = bufferTime;
}
public NetStream getStream() {
return stream;
}
public static StreamPlayer createPlayer(NetStream stream, String type,
String file) throws IOException {
RandomAccessFileReader reader;
try {
reader = new RandomAccessFileReader(file, 0);
} catch (IOException e) {
return null;
}
IMediaDeserializer sampleDeserializer = null;
if ("mp4".equalsIgnoreCase(type)) {
sampleDeserializer = new Mp4Deserializer(reader);
} else {
String ext = file.substring(file.lastIndexOf('.') + 1);
if ("f4v".equalsIgnoreCase(ext) || "mp4".equalsIgnoreCase(ext)) {
sampleDeserializer = new Mp4Deserializer(reader);
} else {
FlvDeserializer flvDeserializer = new FlvDeserializer(reader);
try {
RandomAccessFileReader indexReader = new RandomAccessFileReader(
file + ".idx", 0);
FlvDeserializer.FlvIndex flvIndex = flvDeserializer.new FlvIndex();
flvIndex.read(new BufferInputStream(indexReader));
indexReader.close();
} catch (Exception e) {
flvDeserializer.readSamples();
}
sampleDeserializer = flvDeserializer;
}
}
return new StreamPlayer(sampleDeserializer, stream);
}
}
| Java |
package com.ams.protocol.rtmp.net;
public class NetConnectionException extends Exception {
private static final long serialVersionUID = 1L;
public NetConnectionException() {
super();
}
public NetConnectionException(String arg0) {
super(arg0);
}
}
| Java |
package com.ams.protocol.rtmp.net;
import java.util.HashMap;
import com.ams.protocol.rtmp.RtmpConnection;
public class NetStreamManager {
private HashMap<Integer, NetStream> streams;
public NetStreamManager() {
this.streams = new HashMap<Integer, NetStream>();
}
public NetStream get(int streamId) {
return streams.get(streamId);
}
public NetStream createStream(RtmpConnection rtmp) {
int id = 1;
for (int len = streams.size(); id <= len; id++) {
if (streams.get(id) == null)
break;
}
NetStream stream = new NetStream(rtmp, id);
streams.put(id, stream);
return stream;
}
public void removeStream(NetStream stream) {
streams.remove(stream.getStreamId());
}
public void clear() {
streams.clear();
}
}
| Java |
package com.ams.protocol.rtmp.net;
import java.io.EOFException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ams.protocol.rtmp.amf.*;
import com.ams.io.RandomAccessFileWriter;
import com.ams.media.flv.FlvException;
import com.ams.media.flv.FlvSerializer;
import com.ams.protocol.rtmp.message.*;
import com.ams.protocol.rtmp.*;
public class NetConnection {
final private Logger logger = LoggerFactory.getLogger(NetConnection.class);
private RtmpHandShake handshake;
private RtmpConnection rtmp;
private NetContext context;
private NetStreamManager streamManager;
private HashMap<Integer, StreamPlayer> streamPlayers;
private HashMap<Integer, StreamPublisher> streamPublishers;
public NetConnection(RtmpConnection rtmp, NetContext context) {
this.rtmp = rtmp;
this.handshake = new RtmpHandShake(rtmp);
this.streamManager = new NetStreamManager();
this.streamPlayers = new HashMap<Integer, StreamPlayer>();
this.streamPublishers = new HashMap<Integer, StreamPublisher>();
this.context = context;
}
private void onMediaMessage(RtmpHeader header, RtmpMessage message)
throws NetConnectionException, IOException {
NetStream stream = streamManager.get(header.getStreamId());
if (stream == null) {
throw new NetConnectionException("Unknown stream "
+ header.getStreamId());
}
StreamPublisher publisher = streamPublishers.get(header.getStreamId());
if (publisher == null) {
return;
}
publisher.publish(message.toMediaMessage(header.getTimestamp()));
if (publisher.isPing()) {
rtmp.writeProtocolControlMessage(new RtmpMessageAck(publisher
.getPingBytes()));
}
}
private void onSharedMessage(RtmpHeader header, RtmpMessage message) {
// TODO
}
private void onCommandMessage(RtmpHeader header, RtmpMessage message)
throws NetConnectionException, IOException, FlvException {
RtmpMessageCommand command = (RtmpMessageCommand) message;
String cmdName = command.getName();
logger.info("command: {}", cmdName);
if ("connect".equals(cmdName)) {
onConnect(header, command);
} else if ("createStream".equals(cmdName)) {
onCreateStream(header, command);
} else if ("deleteStream".equals(cmdName)) {
onDeleteStream(header, command);
} else if ("closeStream".equals(cmdName)) {
onCloseStream(header, command);
} else if ("getStreamLength".equals(cmdName)) {
onGetStreamLength(header, command);
} else if ("play".equals(cmdName)) {
onPlay(header, command);
} else if ("play2".equals(cmdName)) {
onPlay2(header, command);
} else if ("publish".equals(cmdName)) {
onPublish(header, command);
} else if ("pause".equals(cmdName) || "pauseRaw".equals(cmdName)) {
onPause(header, command);
} else if ("receiveAudio".equals(cmdName)) {
onReceiveAudio(header, command);
} else if ("receiveVideo".equals(cmdName)) {
onReceiveVideo(header, command);
} else if ("seek".equals(cmdName)) {
onSeek(header, command);
} else { // remote rpc call
onCall(header, command);
}
}
private void onConnect(RtmpHeader header, RtmpMessageCommand command)
throws NetConnectionException, IOException {
AmfValue amfObject = command.getCommandObject();
Map<String, AmfValue> obj = amfObject.object();
String app = obj.get("app").string();
if (app == null) {
netConnectionError(header.getChunkStreamId(), header.getStreamId(),
command.getTransactionId(), "Invalid 'Connect' parameters");
return;
}
logger.info("connected app: {}", app);
context.setAttribute("app", app);
rtmp.writeProtocolControlMessage(new RtmpMessageWindowAckSize(
128 * 1024));
rtmp.writeProtocolControlMessage(new RtmpMessagePeerBandwidth(
128 * 1024, (byte) 2));
rtmp.writeProtocolControlMessage(new RtmpMessageUserControl(
RtmpMessageUserControl.EVT_STREAM_BEGIN, header.getStreamId()));
AmfValue value0 = AmfValue.newObject();
value0.put("capabilities", 31).put("fmsver", "AMS/0,1,0,0")
.put("mode", 1);
AmfValue value = AmfValue.newObject();
value.put("level", "status")
.put("code", "NetConnection.Connect.Success")
.put("description", "Connection succeeded.");
AmfValue objectEncoding = obj.get("objectEncoding");
if (objectEncoding != null) {
value.put("objectEncoding", objectEncoding);
}
rtmp.writeRtmpMessage(header.getChunkStreamId(), 0, 0,
new RtmpMessageCommand("_result", command.getTransactionId(),
AmfValue.array(value0, value)));
}
private void onGetStreamLength(RtmpHeader header, RtmpMessageCommand command)
throws IOException, NetConnectionException, FlvException {
AmfValue[] args = command.getArgs();
String streamName = args[1].string();
// rtmp.writeRtmpMessage(header.getChunkStreamId(), 0, 0,
// new RtmpMessageCommand("_result", command.getTransactionId(),
// AmfValue.array(null, 140361)));
}
private void onPlay(RtmpHeader header, RtmpMessageCommand command)
throws IOException, NetConnectionException, FlvException {
AmfValue[] args = command.getArgs();
String streamName = args[1].string();
int start = (args.length > 2) ? args[2].integer() : -2;
int duration = (args.length > 3) ? args[3].integer() : -1;
NetStream stream = streamManager.get(header.getStreamId());
if (stream == null) {
streamError(header.getChunkStreamId(), header.getStreamId(),
command.getTransactionId(), "Invalid 'Play' stream id "
+ header.getStreamId());
return;
}
stream.setTransactionId(command.getTransactionId());
stream.setStreamName(streamName);
logger.info("play stream: {}", streamName);
// write status message
stream.writePlayMessage();
// create player
String app = context.getAttribute("app");
switch (start) {
case -1: // live only
{
String publishName = context.getPublishName(app, streamName);
StreamPublisher publisher = StreamPublisherManager
.getPublisher(publishName);
if (publisher == null) {
stream.writeErrorMessage("Unknown stream '" + streamName
+ "'");
return;
}
publisher.addSubscriber(stream);
}
break;
case -2: // first find live
{
String publishName = context.getPublishName(app, streamName);
StreamPublisher publisher = StreamPublisherManager
.getPublisher(publishName);
if (publisher != null) {
publisher.addSubscriber(stream);
} else {
String tokens[] = streamName.split(":");
String type = "";
String file = streamName;
if (tokens.length >= 2) {
type = tokens[0];
file = tokens[1];
}
String path = context.getRealPath(app, file, type);
StreamPlayer player = StreamPlayer.createPlayer(stream, type,
path);
if (player != null) {
streamPlayers.put(header.getStreamId(), player);
player.seek(0);
}
}
}
break;
default: // >= 0
String tokens[] = streamName.split(":");
String type = "";
String file = streamName;
if (tokens.length >= 2) {
type = tokens[0];
file = tokens[1];
}
String path = context.getRealPath(app, file, type);
StreamPlayer player = StreamPlayer.createPlayer(stream, type, path);
if (player != null) {
streamPlayers.put(header.getStreamId(), player);
player.seek(start);
}
}
}
private void onPlay2(RtmpHeader header, RtmpMessageCommand command)
throws IOException, NetConnectionException, FlvException {
AmfValue[] args = command.getArgs();
int startTime = args[0].integer();
String oldStreamName = args[1].string();
String streamName = args[2].string();
int duration = (args.length > 3) ? args[3].integer() : -1;
String transition = (args.length > 4) ? args[4].string() : "switch"; // switch
// or
// swap
// TODO
}
private void onSeek(RtmpHeader header, RtmpMessageCommand command)
throws IOException, NetConnectionException, FlvException {
AmfValue[] args = command.getArgs();
int offset = args[1].integer();
NetStream stream = streamManager.get(header.getStreamId());
if (stream == null) {
streamError(header.getChunkStreamId(), header.getStreamId(),
command.getTransactionId(), "Invalid 'Seek' stream id "
+ header.getStreamId());
return;
}
stream.setTransactionId(command.getTransactionId());
int streamId = header.getStreamId();
StreamPlayer player = streamPlayers.get(streamId);
if (player == null) {
stream.writeErrorMessage("Invalid 'Seek' stream id " + streamId);
return;
}
stream.writeSeekMessage(offset);
}
private void onPause(RtmpHeader header, RtmpMessageCommand command)
throws IOException, NetConnectionException, FlvException {
AmfValue[] args = command.getArgs();
boolean pause = args[1].bool();
int time = args[2].integer();
NetStream stream = streamManager.get(header.getStreamId());
if (stream == null) {
streamError(header.getChunkStreamId(), header.getStreamId(),
command.getTransactionId(), "Invalid 'Pause' stream id "
+ header.getStreamId());
return;
}
stream.setTransactionId(command.getTransactionId());
StreamPlayer player = streamPlayers.get(header.getStreamId());
if (player == null) {
stream.writeErrorMessage("This channel is already closed");
return;
}
logger.info("pause stream: {}", stream.getStreamName());
player.pause(pause);
stream.writePauseMessage(pause);
}
private void onPublish(RtmpHeader header, RtmpMessageCommand command)
throws IOException, NetConnectionException {
AmfValue[] args = command.getArgs();
String publishName = args[1].string();
if (StreamPublisherManager.getPublisher(publishName) != null) {
streamError(header.getChunkStreamId(), header.getStreamId(),
command.getTransactionId(), "The publish '" + publishName
+ "' is already used");
return;
}
String type = (args.length > 2) ? args[2].string() : null;
NetStream stream = streamManager.get(header.getStreamId());
if (stream == null) {
streamError(header.getChunkStreamId(), header.getStreamId(),
command.getTransactionId(), "Invalid 'Publish' stream id "
+ header.getStreamId());
return;
}
stream.setTransactionId(command.getTransactionId());
String app = context.getAttribute("app");
String streamName = publishName.split("\\?")[0];
logger.info("publish stream: {}", streamName);
// save to share or file
String publishFullName = context.getPublishName(app, streamName);
StreamPublisher publisher = new StreamPublisher(publishFullName);
streamPublishers.put(header.getStreamId(), publisher);
if ("record".equals(type)) {
String file = context.getRealPath(app, streamName, "");
try {
RandomAccessFileWriter writer = new RandomAccessFileWriter(
file, false);
publisher.setRecorder(new FlvSerializer(writer));
} catch (IOException e) {
logger.debug(e.getMessage());
}
} else if ("append".equals(type)) {
String file = context.getRealPath(app, streamName, "");
RandomAccessFileWriter writer = new RandomAccessFileWriter(file,
true);
publisher.setRecorder(new FlvSerializer(writer));
} else if ("live".equals(type)) {
// nothing to do
}
StreamPublisherManager.addPublisher(publisher);
stream.writePublishMessage(publishName);
}
private void onReceiveAudio(RtmpHeader header, RtmpMessageCommand command)
throws IOException {
AmfValue[] args = command.getArgs();
boolean flag = args[1].bool();
NetStream stream = streamManager.get(header.getStreamId());
if (stream == null) {
streamError(header.getChunkStreamId(), header.getStreamId(),
command.getTransactionId(),
"Invalid 'ReceiveAudio' stream id " + header.getStreamId());
return;
}
StreamPlayer player = streamPlayers.get(header.getStreamId());
if (player != null) {
player.audioPlaying(flag);
}
}
private void onReceiveVideo(RtmpHeader header, RtmpMessageCommand command)
throws IOException {
AmfValue[] args = command.getArgs();
boolean flag = args[1].bool();
NetStream stream = streamManager.get(header.getStreamId());
if (stream == null) {
streamError(header.getChunkStreamId(), header.getStreamId(),
command.getTransactionId(),
"Invalid 'ReceiveVideo' stream id " + header.getStreamId());
return;
}
StreamPlayer player = streamPlayers.get(header.getStreamId());
if (player != null) {
player.videoPlaying(flag);
}
}
private void onCreateStream(RtmpHeader header, RtmpMessageCommand command)
throws IOException {
NetStream stream = streamManager.createStream(rtmp);
rtmp.writeRtmpMessage(header.getChunkStreamId(), 0, 0,
new RtmpMessageCommand("_result", command.getTransactionId(),
AmfValue.array(null, stream.getStreamId())));
}
private void onDeleteStream(RtmpHeader header, RtmpMessageCommand command)
throws IOException, NetConnectionException {
AmfValue[] args = command.getArgs();
int streamId = args[1].integer();
NetStream stream = streamManager.get(streamId);
if (stream == null) {
streamError(header.getChunkStreamId(), header.getStreamId(),
command.getTransactionId(),
"Invalid 'deleteStream' stream id");
return;
}
streamManager.removeStream(stream);
}
private void onCloseStream(RtmpHeader header, RtmpMessageCommand command)
throws NetConnectionException, IOException {
NetStream stream = streamManager.get(header.getStreamId());
if (stream == null) {
streamError(header.getChunkStreamId(), header.getStreamId(),
command.getTransactionId(),
"Invalid 'CloseStream' stream id " + header.getStreamId());
return;
}
logger.info("close stream: {}", stream.getStreamName());
streamManager.removeStream(stream);
}
private void onCall(RtmpHeader header, RtmpMessageCommand command) {
// String procedureName = command.getName();
}
public void writeError(int chunkStreamId, int streamId, int transactionId,
String code, String msg) throws IOException {
AmfValue value = AmfValue.newObject();
value.put("level", "error").put("code", code).put("details", msg);
rtmp.writeRtmpMessage(
chunkStreamId,
streamId,
0,
new RtmpMessageCommand("onStatus", transactionId, AmfValue
.array(null, value)));
}
public void netConnectionError(int chunkStreamId, int streamId,
int transactionId, String msg) throws IOException {
writeError(chunkStreamId, streamId, transactionId, "NetConnection", msg);
}
public void streamError(int chunkStreamId, int streamId, int transactionId,
String msg) throws IOException {
writeError(chunkStreamId, streamId, transactionId, "NetStream.Error",
msg);
}
public void readAndProcessRtmpMessage() throws IOException, RtmpException,
AmfException {
if (!handshake.isHandshakeDone()) {
handshake.doServerHandshake();
return;
}
do {
if (!rtmp.readRtmpMessage()) {
return;
}
} while (!rtmp.isRtmpMessageReady());
RtmpHeader header = rtmp.getCurrentHeader();
RtmpMessage message = rtmp.getCurrentMessage();
try {
switch (message.getType()) {
case RtmpMessage.MESSAGE_AMF0_COMMAND:
case RtmpMessage.MESSAGE_AMF3_COMMAND:
onCommandMessage(header, message);
break;
case RtmpMessage.MESSAGE_AUDIO:
case RtmpMessage.MESSAGE_VIDEO:
case RtmpMessage.MESSAGE_AMF0_DATA:
case RtmpMessage.MESSAGE_AMF3_DATA:
onMediaMessage(header, message);
break;
case RtmpMessage.MESSAGE_USER_CONTROL:
RtmpMessageUserControl userControl = (RtmpMessageUserControl) message;
logger.debug(
"read message USER_CONTROL: {}, {}, {}",
new Integer[] { userControl.getEvent(),
userControl.getStreamId(),
userControl.getTimestamp() });
break;
case RtmpMessage.MESSAGE_SHARED_OBJECT:
onSharedMessage(header, message);
break;
case RtmpMessage.MESSAGE_CHUNK_SIZE:
RtmpMessageChunkSize chunkSize = (RtmpMessageChunkSize) message;
logger.debug("read message chunk size: {}",
chunkSize.getChunkSize());
break;
case RtmpMessage.MESSAGE_ABORT:
RtmpMessageAbort abort = (RtmpMessageAbort) message;
logger.debug("read message abort: {}", abort.getStreamId());
break;
case RtmpMessage.MESSAGE_ACK:
RtmpMessageAck ack = (RtmpMessageAck) message;
// logger.debug("read message ack: {}", ack.getBytes());
break;
case RtmpMessage.MESSAGE_WINDOW_ACK_SIZE:
RtmpMessageWindowAckSize ackSize = (RtmpMessageWindowAckSize) message;
logger.debug("read message window ack size: {}",
ackSize.getSize());
break;
case RtmpMessage.MESSAGE_PEER_BANDWIDTH:
RtmpMessagePeerBandwidth peer = (RtmpMessagePeerBandwidth) message;
logger.debug("read message peer bandwidth: {}, {}",
peer.getWindowAckSize(), peer.getLimitType());
break;
// case RtmpMessage.MESSAGE_AGGREGATE:
// break;
case RtmpMessage.MESSAGE_UNKNOWN:
logger.warn("read message UNKNOWN!");
break;
}
} catch (Exception e) {
logger.debug("Exception", e);
}
}
public void play() throws IOException {
for (StreamPlayer player : streamPlayers.values()) {
try {
player.play();
} catch (EOFException e) {
player.pause(true);
NetStream stream = player.getStream();
stream.writeStopMessage();
}
}
rtmp.flush();
}
}
| Java |
package com.ams.protocol.rtmp.net;
import java.io.IOException;
import java.util.LinkedList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ams.media.IMediaSerializer;
import com.ams.media.MediaMessage;
public class StreamPublisher {
final private Logger logger = LoggerFactory
.getLogger(StreamPublisher.class);
protected String publishName = null;
private int pingBytes = 0;
private int lastPing = 0;
private boolean ping = false;
protected MediaMessage videoH264Header = null;
protected MediaMessage audioH264Header = null;
protected MediaMessage meta = null;
protected LinkedList<NetStream> subscribers = new LinkedList<NetStream>();
protected IMediaSerializer recorder = null; // record to file stream
public StreamPublisher(String publishName) {
this.publishName = publishName;
String tokens[] = publishName.split(":");
if (tokens.length >= 2) {
this.publishName = tokens[1];
}
}
public void publish(MediaMessage msg) throws IOException {
if (audioH264Header == null && msg.isH264AudioHeader()) {
audioH264Header = msg;
logger.info("received h264 audio header.");
} else if (videoH264Header == null && msg.isH264VideoHeader()) {
videoH264Header = msg;
logger.info("received h264 video header.");
} else if (msg.isMeta()) {
meta = msg;
}
// ping
ping(msg.getDataSize());
// record to file
record(msg);
// publish packet to subscriber stream
notify(msg);
}
public synchronized void close() {
if (recorder != null) {
recorder.close();
}
subscribers.clear();
videoH264Header = null;
audioH264Header = null;
meta = null;
}
private void ping(int dataSize) {
pingBytes += dataSize;
// ping
ping = false;
if (pingBytes - lastPing > 1024 * 1) {
lastPing = pingBytes;
ping = true;
}
}
private void record(MediaMessage msg) throws IOException {
if (recorder != null) {
recorder.write(msg);
}
}
private void notify(MediaMessage msg) {
for (NetStream subscriber : subscribers) {
try {
subscriber.sendMediaMessage(msg);
subscriber.flush();
} catch (IOException e) {
removeSubscriber(subscriber);
}
}
}
public void addSubscriber(NetStream subscriber) {
try {
if (audioH264Header != null) {
subscriber.sendMediaMessage(audioH264Header);
}
if (videoH264Header != null) {
subscriber.sendMediaMessage(videoH264Header);
}
} catch (IOException e) {}
synchronized (subscribers) {
subscribers.add(subscriber);
}
}
public void removeSubscriber(NetStream subscriber) {
synchronized (subscribers) {
subscribers.remove(subscriber);
}
}
public void setRecorder(IMediaSerializer recorder) {
this.recorder = recorder;
}
public boolean isPing() {
return ping;
}
public int getPingBytes() {
return pingBytes;
}
public String getPublishName() {
return publishName;
}
}
| Java |
package com.ams.protocol.rtmp.net;
import java.io.File;
import java.util.HashMap;
import com.ams.media.MimeTypes;
import com.ams.protocol.Context;
public final class NetContext extends Context {
private final String contextRoot;
public NetContext(String root) {
contextRoot = root;
attributes = new HashMap<String, String>();
}
public String getPublishName(String app, String streamName) {
return app + "/" + streamName;
}
public String getRealPath(String app, String path, String type) {
if ("unkown/unkown".equals(MimeTypes.getMimeType(path))) {
if (type == null || "".equals(type)) {
path += ".flv";
} else {
path += "." + type;
}
}
if (app != null && app.length() > 0) {
return new File(contextRoot, app + File.separatorChar + path)
.getAbsolutePath();
}
return new File(contextRoot, path).getAbsolutePath();
}
}
| Java |
package com.ams.media;
import com.ams.io.BufferList;
import com.ams.protocol.rtmp.message.RtmpMessage;
import com.ams.protocol.rtmp.message.RtmpMessageAudio;
import com.ams.protocol.rtmp.message.RtmpMessageData;
import com.ams.protocol.rtmp.message.RtmpMessageVideo;
public class MediaMessage {
public static final int MEDIA_AUDIO = 0;
public static final int MEDIA_VIDEO = 1;
public static final int MEDIA_META = 2;
protected int mediaType;
protected long timestamp = 0;
protected BufferList data;
public MediaMessage(int mediaType, long timestamp, BufferList data) {
this.mediaType = mediaType;
this.timestamp = timestamp;
this.data = data;
}
public int getMediaType() {
return mediaType;
}
public long getTimestamp() {
return timestamp;
}
public BufferList getData() {
return data.duplicate();
}
public int getDataSize() {
return data.remaining();
}
public boolean isAudio() {
return mediaType == MEDIA_AUDIO;
}
public boolean isVideo() {
return mediaType == MEDIA_VIDEO;
}
public boolean isMeta() {
return mediaType == MEDIA_META;
}
public boolean isVideoKeyframe() {
if (mediaType != MEDIA_VIDEO)
return false;
int h = data.get(0) & 0xFF;
return isVideo() && ((h >>> 4) == 1 || h == 0x17);
}
public boolean isH264Video() {
if (mediaType != MEDIA_VIDEO)
return false;
int h = data.get(0) & 0xFF;
return h == 0x17 || h == 0x27;
}
public boolean isH264Audio() {
if (mediaType != MEDIA_AUDIO)
return false;
int h = data.get(0) & 0xFF;
return h == 0xAF;
}
public boolean isH264AudioHeader() {
if (mediaType != MEDIA_AUDIO)
return false;
int h1 = data.get(0) & 0xFF;
int h2 = data.get(1) & 0xFF;
return h1 == 0xAF && h2 == 0x00;
}
public boolean isH264VideoHeader() {
if (mediaType != MEDIA_VIDEO)
return false;
int h1 = data.get(0) & 0xFF;
int h2 = data.get(1) & 0xFF;
return h1 == 0x17 && h2 == 0x00;
}
public RtmpMessage toRtmpMessage() {
RtmpMessage msg = null;
switch (mediaType) {
case MEDIA_META:
msg = new RtmpMessageData(getData());
break;
case MEDIA_VIDEO:
msg = new RtmpMessageVideo(getData());
break;
case MEDIA_AUDIO:
msg = new RtmpMessageAudio(getData());
break;
}
return msg;
}
}
| Java |
package com.ams.media.flv;
import java.io.IOException;
import com.ams.io.BufferList;
import com.ams.io.BufferOutputStream;
import com.ams.io.RandomAccessFileWriter;
import com.ams.media.IMediaSerializer;
import com.ams.media.MediaMessage;
import com.ams.media.MediaSample;
public class FlvSerializer implements IMediaSerializer {
private BufferOutputStream writer; // record to file stream
private boolean headerWrite = false;
public FlvSerializer(RandomAccessFileWriter writer) {
this.writer = new BufferOutputStream(writer);
}
public void write(MediaMessage flvTag) throws IOException {
write(writer, flvTag);
writer.flush();
}
private void write(BufferOutputStream out, MediaMessage flvTag)
throws IOException {
if (!headerWrite) {
FlvHeader header = new FlvHeader(true, true);
FlvHeader.write(out, header);
headerWrite = true;
}
byte tagType = -1;
switch (flvTag.getMediaType()) {
case MediaSample.MEDIA_AUDIO:
tagType = 0x08;
break;
case MediaSample.MEDIA_VIDEO:
tagType = 0x09;
break;
case MediaSample.MEDIA_META:
tagType = 0x12;
break;
}
// tag type
out.writeByte(tagType);
BufferList data = flvTag.getData();
// data size
int dataSize = data.remaining();
out.write24Bit(dataSize); // 24Bit write
// time stamp
int timestamp = (int) flvTag.getTimestamp();
out.write32Bit(timestamp); // 32Bit write
out.writeByte((byte) ((timestamp & 0xFF000000) >>> 24));
// stream ID
out.write24Bit(0);
// data
out.writeByteBuffer(data);
// previousTagSize
out.write32Bit(dataSize + 11);
}
public void close() {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| Java |
package com.ams.media.flv;
import java.io.EOFException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collections;
import com.ams.io.BufferList;
import com.ams.io.BufferInputStream;
import com.ams.io.BufferOutputStream;
import com.ams.io.RandomAccessFileReader;
import com.ams.media.IMediaDeserializer;
import com.ams.media.MediaSample;
import com.ams.protocol.rtmp.amf.AmfValue;
import com.ams.io.BufferFactory;
public class FlvDeserializer implements IMediaDeserializer {
private RandomAccessFileReader reader;
private long videoFrames = 0, audioFrames = 0;
private long videoDataSize = 0, audioDataSize = 0;
private long lastTimestamp = 0;
private VideoTag firstVideoTag = null;
private AudioTag firstAudioTag = null;
private MetaTag firstMetaTag = null;
private VideoTag lastVideoTag = null;
private AudioTag lastAudioTag = null;
private MetaTag lastMetaTag = null;
private ArrayList<MediaSample> samples = new ArrayList<MediaSample>();
private static final byte[] H264_VIDEO_HEADER = { (byte) 0x01, (byte) 0x4d,
(byte) 0x40, (byte) 0x1e, (byte) 0xff, (byte) 0xe1, (byte) 0x00,
(byte) 0x17, (byte) 0x67, (byte) 0x4d, (byte) 0x40, (byte) 0x1e,
(byte) 0x92, (byte) 0x42, (byte) 0x01, (byte) 0x40, (byte) 0x5f,
(byte) 0xd4, (byte) 0xb0, (byte) 0x80, (byte) 0x00, (byte) 0x01,
(byte) 0xf4, (byte) 0x80, (byte) 0x00, (byte) 0x75, (byte) 0x30,
(byte) 0x07, (byte) 0x8b, (byte) 0x17, (byte) 0x24, (byte) 0x01,
(byte) 0x00, (byte) 0x04, (byte) 0x68, (byte) 0xee, (byte) 0x3c,
(byte) 0x8 };
private static final byte[] H264_AUDIO_HEADER = { (byte) 0x12, (byte) 0x10 };
private class SampleTimestampComparator implements
java.util.Comparator<MediaSample> {
public int compare(MediaSample s, MediaSample t) {
return (int) (s.getTimestamp() - t.getTimestamp());
}
};
public class FlvIndex {
private MediaSample readTag(BufferInputStream in) {
try {
int tagType = in.readByte() & 0xFF;
int size = in.read24Bit();
long timestamp = in.read32Bit();
long offset = in.read32Bit();
if (size == 0) {
return null;
}
switch (tagType) {
case MediaSample.MEDIA_AUDIO:
return new AudioTag(timestamp, offset, size);
case MediaSample.MEDIA_VIDEO:
return new VideoTag(timestamp, true, offset, size);
case MediaSample.MEDIA_META:
return new MetaTag(timestamp, offset, size);
default:
return null;
}
} catch (IOException e) {
return null;
}
}
public boolean read(BufferInputStream in) {
try {
int b1 = in.readByte() & 0xFF;
int b2 = in.readByte() & 0xFF;
int b3 = in.readByte() & 0xFF;
if (b1 != 'F' || b2 != 'L' || b3 != 'X')
return false;
videoFrames = in.read32Bit();
audioFrames = in.read32Bit();
videoDataSize = in.read32Bit();
audioDataSize = in.read32Bit();
lastTimestamp = in.read32Bit();
} catch (IOException e) {
return false;
}
firstVideoTag = (VideoTag) readTag(in);
firstAudioTag = (AudioTag) readTag(in);
firstMetaTag = (MetaTag) readTag(in);
lastVideoTag = (VideoTag) readTag(in);
lastAudioTag = (AudioTag) readTag(in);
lastMetaTag = (MetaTag) readTag(in);
MediaSample sample = null;
samples.clear();
while ((sample = readTag(in)) != null) {
samples.add(sample);
}
try {
getTagParameter();
} catch (IOException e) {
}
return samples.size() > 0;
}
public void writeTag(BufferOutputStream out, MediaSample sample)
throws IOException {
if (sample == null) {
out.writeByte(0);
out.write24Bit(0);
out.write32Bit(0);
out.write32Bit(0);
return;
}
out.writeByte(sample.getMediaType());
out.write24Bit(sample.getSize());
out.write32Bit(sample.getTimestamp());
out.write32Bit(sample.getOffset());
}
public void write(BufferOutputStream out) {
try {
out.writeByte('F');
out.writeByte('L');
out.writeByte('X');
out.write32Bit(videoFrames);
out.write32Bit(audioFrames);
out.write32Bit(videoDataSize);
out.write32Bit(audioDataSize);
out.write32Bit(lastTimestamp);
writeTag(out, firstVideoTag);
writeTag(out, firstAudioTag);
writeTag(out, firstMetaTag);
writeTag(out, lastVideoTag);
writeTag(out, lastAudioTag);
writeTag(out, lastMetaTag);
for (MediaSample sample : samples) {
writeTag(out, sample);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public FlvDeserializer(RandomAccessFileReader reader) {
this.reader = reader;
}
private MediaSample readSampleData(BufferInputStream in)
throws IOException, FlvException {
int tagType = in.readByte() & 0xFF;
int dataSize = in.read24Bit(); // 24Bit read
long timestamp = in.read24Bit(); // 24Bit read
timestamp |= (in.readByte() & 0xFF) << 24; // time stamp extended
int streamId = in.read24Bit(); // 24Bit read
ByteBuffer[] data = in.readByteBuffer(dataSize);
int previousTagSize = (int) in.read32Bit();
switch (tagType) {
case 0x08:
return new AudioTag(timestamp, new BufferList(data));
case 0x09:
return new VideoTag(timestamp, new BufferList(data));
case 0x12:
return new MetaTag(timestamp, new BufferList(data));
default:
throw new FlvException("Invalid FLV tag " + tagType);
}
}
private MediaSample readSampleOffset(RandomAccessFileReader reader)
throws IOException, FlvException {
int tagType;
BufferInputStream in = new BufferInputStream(reader);
try {
tagType = in.readByte() & 0xFF;
} catch (EOFException e) {
return null;
}
int dataSize = in.read24Bit(); // 24Bit read
long timestamp = in.read24Bit(); // 24Bit read
timestamp |= (in.readByte() & 0xFF) << 24; // time stamp extended
int streamId = in.read24Bit(); // 24Bit read
long offset = reader.getPosition();
int header = in.readByte();
boolean keyframe = (header >>> 4) == 1 || header == 0x17;
reader.seek(offset + dataSize);
int previousTagSize = (int) in.read32Bit();
switch (tagType) {
case 0x08:
return new AudioTag(timestamp, offset, dataSize);
case 0x09:
return new VideoTag(timestamp, keyframe, offset, dataSize);
case 0x12:
return new MetaTag(timestamp, offset, dataSize);
default:
throw new FlvException("Invalid FLV tag " + tagType);
}
}
private void getTagParameter() throws IOException {
if (firstVideoTag != null) {
firstVideoTag.readData(reader);
firstVideoTag.getParameters();
}
if (firstAudioTag != null) {
firstAudioTag.readData(reader);
firstAudioTag.getParameters();
}
if (firstMetaTag != null) {
firstMetaTag.readData(reader);
firstMetaTag.getParameters();
}
}
public void readSamples() {
try {
reader.seek(0);
BufferInputStream in = new BufferInputStream(reader);
FlvHeader.read(in);
MediaSample tag = null;
while ((tag = readSampleOffset(reader)) != null) {
if (tag.isVideo()) {
videoFrames++;
videoDataSize += tag.getSize();
if (firstVideoTag == null)
firstVideoTag = (VideoTag) tag;
if (tag.isKeyframe())
samples.add(tag);
lastVideoTag = (VideoTag) tag;
}
if (tag.isAudio()) {
audioFrames++;
audioDataSize += tag.getSize();
if (firstAudioTag == null)
firstAudioTag = (AudioTag) tag;
lastAudioTag = (AudioTag) tag;
}
if (tag.isMeta()) {
if (firstMetaTag == null)
firstMetaTag = (MetaTag) tag;
lastMetaTag = (MetaTag) tag;
}
lastTimestamp = tag.getTimestamp();
}
getTagParameter();
} catch (Exception e) {
}
}
public MediaSample metaData() {
AmfValue[] metaData;
if (firstMetaTag != null
&& "onMetaData".equals(firstMetaTag.getEvent())
&& firstMetaTag.getMetaData() != null) {
metaData = AmfValue.array("onMetaData", firstMetaTag.getMetaData());
} else {
AmfValue value = AmfValue.newEcmaArray();
float duration = (float) lastTimestamp / 1000;
value.put("duration", duration);
if (firstVideoTag != null) {
value.put("width", firstVideoTag.getWidth())
.put("height", firstVideoTag.getHeight())
.put("videodatarate",
(float) videoDataSize * 8 / duration / 1024)
// kBits/sec
.put("canSeekToEnd", lastVideoTag.isKeyframe())
.put("videocodecid", firstVideoTag.getCodecId())
.put("framerate", (float) videoFrames / duration);
}
if (firstAudioTag != null) {
value.put("audiodatarate",
(float) audioDataSize * 8 / duration / 1024) // kBits/sec
.put("audiocodecid", firstAudioTag.getSoundFormat());
}
metaData = AmfValue.array("onMetaData", value);
}
return new MediaSample(MediaSample.MEDIA_META, 0,
AmfValue.toBinary(metaData));
}
public MediaSample videoHeaderData() {
if (firstVideoTag != null && firstVideoTag.isH264Video()) {
byte[] data = H264_VIDEO_HEADER;
ByteBuffer[] buf = new ByteBuffer[1];
buf[0] = BufferFactory.allocate(5 + data.length);
buf[0].put(new byte[] { 0x17, 0x00, 0x00, 0x00, 0x00 });
buf[0].put(data);
buf[0].flip();
return new MediaSample(MediaSample.MEDIA_VIDEO, 0, new BufferList(
buf));
}
return null;
}
public MediaSample audioHeaderData() {
if (firstAudioTag != null && firstAudioTag.isH264Audio()) {
byte[] data = H264_AUDIO_HEADER;
ByteBuffer[] buf = new ByteBuffer[1];
buf[0] = BufferFactory.allocate(2 + data.length);
buf[0].put(new byte[] { (byte) 0xaf, 0x00 });
buf[0].put(data);
buf[0].flip();
return new MediaSample(MediaSample.MEDIA_AUDIO, 0, new BufferList(
buf));
}
return null;
}
public MediaSample seek(long seekTime) throws IOException {
MediaSample flvTag = firstVideoTag;
int idx = Collections.binarySearch(samples, new MediaSample(
MediaSample.MEDIA_VIDEO, seekTime, true, 0, 0),
new SampleTimestampComparator());
int i = (idx >= 0) ? idx : -(idx + 1);
while (i > 0) {
flvTag = samples.get(i);
if (flvTag.isVideo() && flvTag.isKeyframe()) {
break;
}
i--;
}
reader.seek(flvTag.getOffset() - 11);
return flvTag;
}
public MediaSample readNext() throws IOException {
try {
return readSampleData(new BufferInputStream(reader));
} catch (Exception e) {
throw new EOFException();
}
}
public void close() {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| Java |
package com.ams.media.flv;
import java.io.IOException;
import com.ams.io.BufferList;
import com.ams.io.BufferInputStream;
import com.ams.media.MediaSample;
public class AudioTag extends MediaSample {
private int soundFormat = -1;
private int soundRate = 0;
private int soundSize = 0;
private int soundType = -1;
public AudioTag(long timestamp, BufferList data) {
super(MediaSample.MEDIA_AUDIO, timestamp, data);
}
public AudioTag(long timestamp, long offset, int size) {
super(MediaSample.MEDIA_AUDIO, timestamp, true, offset, size);
}
public void getParameters() throws IOException {
BufferInputStream bi = new BufferInputStream(getData());
byte b = bi.readByte();
soundFormat = (b & 0xF0) >>> 4;
soundRate = (b & 0x0C) >>> 2;
soundRate = ((b & 0x02) >>> 1) == 0 ? 8 : 16;
soundType = b & 0x01;
}
public int getSoundFormat() {
return soundFormat;
}
public int getSoundRate() {
return soundRate;
}
public int getSoundSize() {
return soundSize;
}
public int getSoundType() {
return soundType;
}
}
| Java |
package com.ams.media.flv;
public class FlvException extends Exception {
private static final long serialVersionUID = 1L;
public FlvException() {
super();
}
public FlvException(String arg0) {
super(arg0);
}
}
| Java |
package com.ams.media.flv;
import java.io.DataInputStream;
import java.io.IOException;
import com.ams.io.BufferList;
import com.ams.io.BufferInputStream;
import com.ams.media.MediaSample;
import com.ams.protocol.rtmp.amf.Amf0Deserializer;
import com.ams.protocol.rtmp.amf.AmfException;
import com.ams.protocol.rtmp.amf.AmfValue;
public class MetaTag extends MediaSample {
private String event = null;
private AmfValue metaData = null;
public MetaTag(long timestamp, BufferList data) {
super(MediaSample.MEDIA_META, timestamp, data);
}
public MetaTag(long timestamp, long offset, int size) {
super(MediaSample.MEDIA_META, timestamp, false, offset, size);
}
public void getParameters() throws IOException {
BufferInputStream bi = new BufferInputStream(getData());
Amf0Deserializer amf0 = new Amf0Deserializer(new DataInputStream(bi));
AmfValue value;
try {
value = amf0.read();
event = value.string();
metaData = amf0.read();
} catch (AmfException e) {
e.printStackTrace();
}
}
public String getEvent() {
return event;
}
public AmfValue getMetaData() {
return metaData;
}
}
| Java |
package com.ams.media.flv;
import java.io.IOException;
import com.ams.io.BufferInputStream;
import com.ams.io.BufferOutputStream;
public class FlvHeader {
private byte[] signature = { 'F', 'L', 'V' };
private int version = 0x01;
private boolean hasAudio;
private boolean hasVideo;
private int dataOffset = 0x09;
public FlvHeader(boolean hasAudio, boolean hasVideo) {
this.hasAudio = hasAudio;
this.hasVideo = hasVideo;
}
public boolean isHasAudio() {
return hasAudio;
}
public boolean isHasVideo() {
return hasVideo;
}
public byte[] getSignature() {
return signature;
}
public int getVersion() {
return version;
}
public int getDataOffset() {
return dataOffset;
}
public static FlvHeader read(BufferInputStream in) throws IOException,
FlvException {
int b1 = in.readByte() & 0xFF;
int b2 = in.readByte() & 0xFF;
int b3 = in.readByte() & 0xFF;
if (b1 != 'F' || b2 != 'L' || b3 != 'V')
throw new FlvException("Invalid signature");
int version = in.readByte() & 0xFF;
if (version != 0x01)
throw new FlvException("Invalid version");
int flags = in.readByte() & 0xFF;
if ((flags & 0xF2) != 0)
throw new FlvException("Invalid tag type flags: " + flags);
int dataOffset = (int) in.read32Bit();
if (dataOffset != 0x09)
throw new FlvException("Invalid data offset: " + dataOffset);
int previousTagSize0 = (int) in.read32Bit();
if (previousTagSize0 != 0)
throw new FlvException("Invalid previous tag size 0: "
+ previousTagSize0);
boolean hasAudio = (flags & 1) != 1;
boolean hasVideo = (flags & 4) != 4;
return new FlvHeader(hasAudio, hasVideo);
}
public static void write(BufferOutputStream out, FlvHeader header)
throws IOException {
out.writeByte('F');
out.writeByte('L');
out.writeByte('V');
out.writeByte(0x01); // version
int flgs = 0;
flgs += header.isHasAudio() ? 1 : 0;
flgs += header.isHasVideo() ? 4 : 0;
out.writeByte(flgs & 0xFF); // hasAudio && hasVideo
out.write32Bit(0x09); // dataOffset
out.write32Bit(0x00); // previousTagSize0
}
} | Java |
package com.ams.media.flv;
import java.io.IOException;
import com.ams.io.BufferList;
import com.ams.io.BufferInputStream;
import com.ams.media.MediaSample;
public class VideoTag extends MediaSample {
private int codecId = -1;
private int width = 0, height = 0;
public VideoTag(long timestamp, BufferList data) {
super(MediaSample.MEDIA_VIDEO, timestamp, data);
}
public VideoTag(long timestamp, boolean keyframe, long offset, int size) {
super(MediaSample.MEDIA_VIDEO, timestamp, keyframe, offset, size);
}
public void getParameters() throws IOException {
BufferInputStream bi = new BufferInputStream(getData());
byte b = bi.readByte();
keyframe = (b >>> 4) == 1;
codecId = b & 0x0F;
byte[] videoData = new byte[9];
bi.read(videoData);
if (codecId == 2) { // H263VIDEOPACKET
int pictureSize = (videoData[3] & 0x03) << 2 + (videoData[4] & 0x80) >>> 7;
switch (pictureSize) {
case 0:
width = (videoData[4] & 0x7F) << 1 + (videoData[5] & 0x80) >>> 7;
height = (videoData[5] & 0x7F) << 1 + (videoData[6] & 0x80) >>> 7;
break;
case 1:
width = (videoData[4] & 0x7F) << 9 + (videoData[5] & 0x80) << 1 + (videoData[6] & 0x80) >>> 7;
height = (videoData[6] & 0x7F) << 9 + (videoData[7] & 0x80) << 1 + (videoData[8] & 0x80) >>> 7;
break;
case 2:
width = 352;
height = 288;
break;
case 3:
width = 176;
height = 144;
break;
case 4:
width = 128;
height = 96;
break;
case 5:
width = 320;
height = 240;
break;
case 6:
width = 160;
height = 120;
break;
}
} else if (codecId == 3) {
width = (videoData[0] & 0x0F) << 4 + videoData[1];
height = videoData[2] << 4 + (videoData[3] & 0xF0) >>> 4;
}
}
public int getCodecId() {
return codecId;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
}
| Java |
package com.ams.media;
import java.io.IOException;
public interface IMediaSerializer {
public void write(MediaMessage sample) throws IOException;
public void close();
}
| Java |
package com.ams.media;
import java.io.IOException;
public interface IMediaDeserializer {
public MediaSample metaData();
public MediaSample videoHeaderData();
public MediaSample audioHeaderData();
public MediaSample seek(long seekTime) throws IOException;
public MediaSample readNext() throws IOException;
public void close();
}
| Java |
package com.ams.media;
import java.io.IOException;
import com.ams.io.BufferList;
import com.ams.io.RandomAccessFileReader;
public class MediaSample extends MediaMessage {
protected boolean keyframe;
protected long offset;
protected int size;
public MediaSample(int mediaType, long timestamp, BufferList data) {
super(mediaType, timestamp, data);
}
public MediaSample(int mediaType, long timestamp, boolean keyframe,
long offset, int size) {
super(mediaType, timestamp, null);
this.keyframe = keyframe;
this.offset = offset;
this.size = size;
}
public void readData(RandomAccessFileReader reader) throws IOException {
reader.seek(offset);
data = new BufferList(reader.read(size));
}
public long getOffset() {
return offset;
}
public int getSize() {
return size;
}
public boolean isKeyframe() {
return keyframe;
}
}
| Java |
package com.ams.media.mp3;
// Copy from MP3Header.java of Red5 project.
public class Mp3Header {
/**
* MP3 bitrates
*/
private static final int[][] BITRATES = {
{ 0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416,
448, -1 },
{ 0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320,
384, -1 },
{ 0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320,
-1 },
{ 0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224,
256, -1 },
{ 0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, -1 }, };
/**
* Sample rates
*/
private static final int[][] SAMPLERATES = {
// Version 2.5
{ 11025, 12000, 8000, -1 },
// Unknown version
{ -1, -1, -1, -1 },
// Version 2
{ 22050, 24000, 16000, -1 },
// Version 1
{ 44100, 48000, 32000, -1 }, };
/**
* Frame sync data
*/
private int data;
/**
* Audio version id
*/
private byte audioVersionId;
/**
* Layer description
*/
private byte layerDescription;
/**
* Protection bit
*/
private boolean protectionBit;
/**
* Bitrate used (index in array of bitrates)
*/
private byte bitRateIndex;
/**
* Sampling rate used (index in array of sample rates)
*/
private byte samplingRateIndex;
/**
* Padding bit
*/
private boolean paddingBit;
/**
* Channel mode
*/
private byte channelMode;
/**
* Creates MP3 header from frame sync value
*
* @param data
* Frame sync data
* @throws Exception
* On invalid frame synchronization
*/
public Mp3Header(int data) throws Exception {
if ((data & 0xffe00000) != 0xffe00000) {
throw new Exception("invalid frame sync word");
}
this.data = data;
// Strip signed bit
data &= 0x1fffff;
audioVersionId = (byte) ((data >> 19) & 3);
layerDescription = (byte) ((data >> 17) & 3);
protectionBit = ((data >> 16) & 1) == 0;
bitRateIndex = (byte) ((data >> 12) & 15);
samplingRateIndex = (byte) ((data >> 10) & 3);
paddingBit = ((data >> 9) & 1) != 0;
channelMode = (byte) ((data >> 6) & 3);
}
/**
* Getter for frame sync word data
*
* @return Frame sync word data
*/
public int getData() {
return data;
}
/**
* Whether stereo playback mode is used
*
* @return <code>true</code> if stereo mode is used, <code>false</code>
* otherwise
*/
public boolean isStereo() {
return (channelMode != 3);
}
/**
* Whether MP3 has protection bit
*
* @return <code>true</code> if MP3 has protection bit, <code>false</code>
* otherwise
*/
public boolean isProtected() {
return protectionBit;
}
/**
* Getter for bitrate
*
* @return File bitrate
*/
public int getBitRate() {
int result;
switch (audioVersionId) {
case 1:
// Unknown
return -1;
case 0:
case 2:
// Version 2 or 2.5
if (layerDescription == 3) {
// Layer 1
result = BITRATES[3][bitRateIndex];
} else if (layerDescription == 2 || layerDescription == 1) {
// Layer 2 or 3
result = BITRATES[4][bitRateIndex];
} else {
// Unknown layer
return -1;
}
break;
case 3:
// Version 1
if (layerDescription == 3) {
// Layer 1
result = BITRATES[0][bitRateIndex];
} else if (layerDescription == 2) {
// Layer 2
result = BITRATES[1][bitRateIndex];
} else if (layerDescription == 1) {
// Layer 3
result = BITRATES[2][bitRateIndex];
} else {
// Unknown layer
return -1;
}
break;
default:
// Unknown version
return -1;
}
return result * 1000;
}
/**
* Getter for sample rate
*
* @return Sampling rate
*/
public int getSampleRate() {
return SAMPLERATES[audioVersionId][samplingRateIndex];
}
/**
* Calculate the size of a MP3 frame for this header.
*
* @return size of the frame including the header
*/
public int frameSize() {
switch (layerDescription) {
case 3:
// Layer 1
return (12 * getBitRate() / getSampleRate() + (paddingBit ? 1 : 0)) * 4;
case 2:
case 1:
// Layer 2 and 3
if (audioVersionId == 3) {
// MPEG 1
return 144 * getBitRate() / getSampleRate()
+ (paddingBit ? 1 : 0);
} else {
// MPEG 2 or 2.5
return 72 * getBitRate() / getSampleRate()
+ (paddingBit ? 1 : 0);
}
default:
// Unknown
return -1;
}
}
/**
* Return the duration of the frame for this header.
*
* @return The duration in milliseconds
*/
public double frameDuration() {
switch (layerDescription) {
case 3:
// Layer 1
return 384 / (getSampleRate() * 0.001);
case 2:
case 1:
if (audioVersionId == 3) {
// MPEG 1, Layer 2 and 3
return 1152 / (getSampleRate() * 0.001);
} else {
// MPEG 2 or 2.5, Layer 2 and 3
return 576 / (getSampleRate() * 0.001);
}
default:
// Unknown
return -1;
}
}
}
| Java |
package com.ams.media.mp3;
import com.ams.io.BufferList;
import com.ams.media.MediaSample;
public class Mp3Sample extends MediaSample {
public Mp3Sample(int sampleType, long timestamp, BufferList data) {
super(sampleType, timestamp, data);
}
}
| Java |
package com.ams.media;
import java.util.HashMap;
public class MimeTypes {
public static HashMap<String, String> mimeMap = new HashMap<String, String>();
static {
mimeMap.put("", "content/unknown");
mimeMap.put("f4v", "video/mp4");
mimeMap.put("f4p", "video/mp4");
mimeMap.put("f4a", "video/mp4");
mimeMap.put("f4b", "video/mp4");
mimeMap.put("mp4", "video/mp4");
mimeMap.put("flv", "video/x-flv ");
};
public static String getContentType(String extension) {
String contentType = mimeMap.get(extension);
if (contentType == null)
contentType = "unkown/unkown";
return contentType;
}
public static String getMimeType(String file) {
int index = file.lastIndexOf('.');
return (index++ > 0) ? MimeTypes.getContentType(file.substring(index))
: "unkown/unkown";
}
} | Java |
package com.ams.media.mp4;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import com.ams.util.Utils;
public class BOX {
public static class Header {
public String type;
public long headerSize;
public long payloadSize;
};
protected int version;
public BOX(int version) {
super();
this.version = version;
}
public static Header readHeader(InputStream in) throws IOException {
Header header = new Header();
byte[] b = new byte[4];
int bytes = in.read(b, 0, 4);
if (bytes == -1)
throw new EOFException();
long size = Utils.from32Bit(b);
b = new byte[4];
in.read(b, 0, 4);
header.type = new String(b);
header.headerSize = 8;
if (size == 1) { // extended size
header.headerSize = 16;
b = new byte[4];
in.read(b, 0, 4);
long size0 = Utils.from32Bit(b);
in.read(b, 0, 4);
size = (size0 << 32) + Utils.from32Bit(b);
}
header.payloadSize = size - header.headerSize;
return header;
}
}
| Java |
package com.ams.media.mp4;
import java.util.ArrayList;
import com.ams.media.mp4.STSC.STSCRecord;
import com.ams.media.mp4.STSD.AudioSampleDescription;
import com.ams.media.mp4.STSD.SampleDescription;
import com.ams.media.mp4.STSD.VideoSampleDescription;
import com.ams.media.mp4.STTS.STTSRecord;
public final class TRAK {
private MDHD mdhd;
private STSD stsd;
private STSC stsc;
private STTS stts;
private STCO stco;
private STSS stss;
private STSZ stsz;
public void setMdhd(MDHD mdhd) {
this.mdhd = mdhd;
}
public void setStsd(STSD stsd) {
this.stsd = stsd;
}
public void setStsc(STSC stsc) {
this.stsc = stsc;
}
public void setStts(STTS stts) {
this.stts = stts;
}
public void setStco(STCO stco) {
this.stco = stco;
}
public void setStss(STSS stss) {
this.stss = stss;
}
public void setStsz(STSZ stsz) {
this.stsz = stsz;
}
public int getSampleIndex(long timeStamp) {
long duration = 0;
int index = 0;
for (STTSRecord entry : stts.getEntries()) {
int delta = entry.sampleDelta * entry.sampleCount;
if (duration + delta >= timeStamp) {
index += (timeStamp - duration) / entry.sampleDelta;
break;
}
duration += delta;
index += entry.sampleCount;
}
return index;
}
private long getSampleTimeStamp(int index) {
long timeStamp = 0;
int sampleCount = 0;
for (STTSRecord entry : stts.getEntries()) {
int delta = entry.sampleCount;
if (sampleCount + delta >= index) {
timeStamp += (index - sampleCount) * entry.sampleDelta;
break;
}
timeStamp += entry.sampleDelta * entry.sampleCount;
sampleCount += delta;
}
return timeStamp;
}
private long getChunkOffset(int chunk) {
return stco.getOffsets()[chunk];
}
private int getSampleSize(int index) {
return stsz.getSizeTable()[index];
}
private boolean isKeyFrameSample(int index) {
if (stss == null)
return false;
for (int sync : stss.getSyncTable()) {
if (index < sync - 1)
return false;
if (index == sync - 1)
return true;
}
return true;
}
public Mp4Sample[] getAllSamples(int sampleType) {
ArrayList<Mp4Sample> list = new ArrayList<Mp4Sample>();
int sampleIndex = 0;
int prevFirstChunk = 0;
int prevSamplesPerChunk = 0;
int prevSampleDescIndex = 0;
for (STSCRecord entry : stsc.getEntries()) {
for (int chunk = prevFirstChunk; chunk < entry.firstChunk - 1; chunk++) {
// chunk offset
long sampleOffset = getChunkOffset(chunk);
for (int i = 0; i < prevSamplesPerChunk; i++) {
// sample size
int sampleSize = getSampleSize(sampleIndex);
// time stamp
long timeStamp = 1000 * getSampleTimeStamp(sampleIndex)
/ getTimeScale();
// keyframe
boolean keyframe = isKeyFrameSample(sampleIndex);
// description index
int sampleDescIndex = prevSampleDescIndex;
list.add(new Mp4Sample(sampleType, timeStamp, keyframe,
sampleOffset, sampleSize, sampleDescIndex));
sampleOffset += sampleSize;
sampleIndex++;
}
}
prevFirstChunk = entry.firstChunk - 1;
prevSamplesPerChunk = entry.samplesPerChunk;
prevSampleDescIndex = entry.sampleDescIndex;
}
int chunkSize = this.stco.getOffsets().length;
for (int chunk = prevFirstChunk; chunk < chunkSize; chunk++) {
// chunk offset
long sampleOffset = getChunkOffset(chunk);
for (int i = 0; i < prevSamplesPerChunk; i++) {
// sample size
int sampleSize = getSampleSize(sampleIndex);
// time stamp
long timeStamp = 1000 * getSampleTimeStamp(sampleIndex)
/ getTimeScale();
// keyframe
boolean keyframe = isKeyFrameSample(sampleIndex);
// description index
int sampleDescIndex = prevSampleDescIndex;
list.add(new Mp4Sample(sampleType, timeStamp, keyframe,
sampleOffset, sampleSize, sampleDescIndex));
sampleOffset += sampleSize;
sampleIndex++;
}
}
return list.toArray(new Mp4Sample[list.size()]);
}
public byte[] getVideoDecoderConfigData() {
if (stsd.getVideoSampleDescription() == null)
return null;
return stsd.getVideoSampleDescription().decoderConfig;
}
public byte[] getAudioDecoderConfigData() {
if (stsd.getAudioSampleDescription() == null)
return null;
return stsd.getAudioSampleDescription().decoderSpecificConfig;
}
public VideoSampleDescription getVideoSampleDescription() {
return stsd.getVideoSampleDescription();
}
public AudioSampleDescription getAudioSampleDescription() {
return stsd.getAudioSampleDescription();
}
public int getTimeScale() {
return mdhd.getTimeScale();
}
public long getDuration() {
return mdhd.getDuration();
}
public float getDurationBySecond() {
return (float) mdhd.getDuration() / (float) mdhd.getTimeScale();
}
public String getLanguage() {
return mdhd.getLanguage();
}
public String getType() {
SampleDescription desc = stsd.getDescription();
return desc.type;
}
public boolean isVideoTrack() {
SampleDescription desc = stsd.getDescription();
return stsd.isVideoSampleDescription(desc);
}
public boolean isAudioTrack() {
SampleDescription desc = stsd.getDescription();
return stsd.isAudioSampleDescription(desc);
}
}
| Java |
package com.ams.media.mp4;
import java.io.DataInputStream;
import java.io.IOException;
public final class STSS extends BOX {
private int[] syncTable;
public STSS(int version) {
super(version);
}
public void read(DataInputStream in) throws IOException {
int count = in.readInt();
syncTable = new int[count];
for (int i = 0; i < count; i++) {
syncTable[i] = in.readInt();
}
}
public int[] getSyncTable() {
return syncTable;
}
}
| Java |
package com.ams.media.mp4;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import com.ams.media.IMediaDeserializer;
import com.ams.media.MediaSample;
import com.ams.media.mp4.STSD.AudioSampleDescription;
import com.ams.media.mp4.STSD.VideoSampleDescription;
import com.ams.protocol.rtmp.amf.AmfValue;
import com.ams.io.BufferList;
import com.ams.io.BufferInputStream;
import com.ams.io.RandomAccessFileReader;
public class Mp4Deserializer implements IMediaDeserializer {
private RandomAccessFileReader reader;
private TRAK videoTrak = null;
private TRAK audioTrak = null;
private Mp4Sample[] videoSamples;
private Mp4Sample[] audioSamples;
private List<Mp4Sample> samples = new ArrayList<Mp4Sample>();
private int sampleIndex = 0;
private long moovPosition = 0;
private static Comparator<Mp4Sample> sampleTimestampComparator = new Comparator<Mp4Sample>() {
public int compare(Mp4Sample s, Mp4Sample t) {
return (int) (s.getTimestamp() - t.getTimestamp());
}
};
public Mp4Deserializer(RandomAccessFileReader reader) {
this.reader = reader;
MOOV moov = readMoov(reader);
TRAK trak = moov.getVideoTrak();
if (trak != null) {
videoTrak = trak;
videoSamples = trak.getAllSamples(MediaSample.MEDIA_VIDEO);
samples.addAll(Arrays.asList(videoSamples));
}
trak = moov.getAudioTrak();
if (trak != null) {
audioTrak = trak;
audioSamples = trak.getAllSamples(MediaSample.MEDIA_AUDIO);
samples.addAll(Arrays.asList(audioSamples));
}
Collections.sort(samples, sampleTimestampComparator);
}
private MOOV readMoov(RandomAccessFileReader reader) {
MOOV moov = null;
try {
reader.seek(0);
for (;;) {
// find moov box
BOX.Header header = BOX
.readHeader(new BufferInputStream(reader));
long payloadSize = header.payloadSize;
if ("moov".equalsIgnoreCase(header.type)) {
moovPosition = reader.getPosition();
byte[] b = new byte[(int) payloadSize];
reader.read(b, 0, b.length);
DataInputStream bin = new DataInputStream(
new ByteArrayInputStream(b));
moov = new MOOV();
moov.read(bin);
break;
} else {
reader.skip(payloadSize);
}
}
} catch (IOException e) {
moov = null;
}
return moov;
}
private ByteBuffer[] readSampleData(Mp4Sample sample) throws IOException {
reader.seek(sample.getOffset());
return reader.read(sample.getSize());
}
public MediaSample metaData() {
AmfValue track1 = null;
if (videoTrak != null) {
track1 = AmfValue.newEcmaArray();
track1.put("length", videoTrak.getDuration())
.put("timescale", videoTrak.getTimeScale())
.put("language", videoTrak.getLanguage())
.put("sampledescription",
AmfValue.newArray(AmfValue.newEcmaArray().put(
"sampletype", videoTrak.getType())));
}
AmfValue track2 = null;
if (audioTrak != null) {
track2 = AmfValue.newEcmaArray();
track2.put("length", audioTrak.getDuration())
.put("timescale", audioTrak.getTimeScale())
.put("language", audioTrak.getLanguage())
.put("sampledescription",
AmfValue.newArray(AmfValue.newEcmaArray().put(
"sampletype", audioTrak.getType())));
}
AmfValue value = AmfValue.newEcmaArray();
if (videoTrak != null) {
VideoSampleDescription videoSd = videoTrak
.getVideoSampleDescription();
value.put("duration", videoTrak.getDurationBySecond())
.put("moovPosition", moovPosition)
.put("width", videoSd.width)
.put("height", videoSd.height)
.put("canSeekToEnd",
videoSamples[videoSamples.length - 1].isKeyframe())
.put("videocodecid", videoTrak.getType())
.put("avcprofile", videoSd.getAvcProfile())
.put("avclevel", videoSd.getAvcLevel())
.put("videoframerate",
(float) videoSamples.length
/ videoTrak.getDurationBySecond());
}
if (audioTrak != null) {
AudioSampleDescription audioSd = audioTrak
.getAudioSampleDescription();
value.put("audiocodecid", audioTrak.getType())
.put("aacaot", audioSd.getAudioCodecType())
.put("audiosamplerate", audioSd.sampleRate)
.put("audiochannels", audioSd.channelCount);
}
value.put("trackinfo", AmfValue.newArray(track1, track2));
return new MediaSample(MediaSample.MEDIA_META, 0,
AmfValue.toBinary(AmfValue.array("onMetaData", value)));
}
public MediaSample videoHeaderData() {
if (videoTrak == null)
return null;
BufferList buf = new BufferList();
buf.put(new byte[] { 0x17, 0x00, 0x00, 0x00, 0x00 });
buf.put(videoTrak.getVideoDecoderConfigData());
return new MediaSample(MediaSample.MEDIA_VIDEO, 0, buf);
}
public MediaSample audioHeaderData() {
if (audioTrak == null)
return null;
BufferList buf = new BufferList();
buf.put(new byte[] { (byte) 0xaf, 0x00 });
buf.put(audioTrak.getAudioDecoderConfigData());
return new MediaSample(MediaSample.MEDIA_AUDIO, 0, buf);
}
private BufferList createVideoTag(Mp4Sample sample) throws IOException {
BufferList buf = new BufferList();
byte type = (byte) (sample.isKeyframe() ? 0x17 : 0x27);
buf.put(new byte[] { type, 0x01, 0, 0, 0 });
ByteBuffer[] data = readSampleData(sample);
buf.write(data);
return buf;
}
private BufferList createAudioTag(Mp4Sample sample) throws IOException {
BufferList buf = new BufferList();
buf.put(new byte[] { (byte) 0xaf, 0x01 });
ByteBuffer[] data = readSampleData(sample);
buf.write(data);
return buf;
}
public MediaSample seek(long seekTime) {
Mp4Sample seekSample = videoSamples[0];
int idx = Collections.binarySearch(samples, new Mp4Sample(
MediaSample.MEDIA_VIDEO, seekTime, true, 0, 0, 0),
sampleTimestampComparator);
int i = (idx >= 0) ? idx : -(idx + 1);
while (i > 0) {
seekSample = samples.get(i);
if (seekSample.isVideo() && seekSample.isKeyframe()) {
break;
}
i--;
}
sampleIndex = i;
return seekSample;
}
public MediaSample readNext() throws IOException {
if (sampleIndex >= samples.size()) {
throw new EOFException();
}
Mp4Sample sample = samples.get(sampleIndex++);
if (sample.isVideo()) {
return new MediaSample(MediaSample.MEDIA_VIDEO,
sample.getTimestamp(), createVideoTag(sample));
}
if (sample.isAudio()) {
return new MediaSample(MediaSample.MEDIA_AUDIO,
sample.getTimestamp(), createAudioTag(sample));
}
return null;
}
public void close() {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| Java |
package com.ams.media.mp4;
import java.io.DataInputStream;
import java.io.IOException;
public final class MDHD extends BOX {
private long creationTime;
private long modificationTime;
private int timeScale;
private long duration;
private String language;
public MDHD(int version) {
super(version);
}
public void read(DataInputStream in) throws IOException {
if (version == 0) {
creationTime = in.readInt();
modificationTime = in.readInt();
} else {
creationTime = in.readLong();
modificationTime = in.readLong();
}
timeScale = in.readInt();
if (version == 0) {
duration = in.readInt();
} else {
duration = in.readLong();
}
short l = in.readShort();
byte[] b = new byte[3];
b[2] = (byte) (0x60 + (l & 0x1F));
l >>>= 5;
b[1] = (byte) (0x60 + (l & 0x1F));
l >>>= 5;
b[0] = (byte) (0x60 + (l & 0x1F));
language = new String(b);
}
public long getCreationTime() {
return creationTime;
}
public long getModificationTime() {
return modificationTime;
}
public int getTimeScale() {
return timeScale;
}
public long getDuration() {
return duration;
}
public String getLanguage() {
return language;
}
}
| Java |
package com.ams.media.mp4;
import java.io.DataInputStream;
import java.io.IOException;
public final class STCO extends BOX {
private long[] offsets;
public STCO(int version) {
super(version);
}
public void read(DataInputStream in) throws IOException {
int count = in.readInt();
offsets = new long[count];
for (int i = 0; i < count; i++) {
offsets[i] = in.readInt();
}
}
public void read64(DataInputStream in) throws IOException {
int count = in.readInt();
offsets = new long[count];
for (int i = 0; i < count; i++) {
offsets[i] = in.readLong();
}
}
public long[] getOffsets() {
return offsets;
}
} | Java |
package com.ams.media.mp4;
import java.io.DataInputStream;
import java.io.IOException;
public final class STTS extends BOX {
public final class STTSRecord {
public int sampleCount;
public int sampleDelta;
}
private STTSRecord[] entries;
public STTS(int version) {
super(version);
}
public void read(DataInputStream in) throws IOException {
int count = in.readInt();
entries = new STTSRecord[count];
for (int i = 0; i < count; i++) {
entries[i] = new STTSRecord();
entries[i].sampleCount = in.readInt();
entries[i].sampleDelta = in.readInt();
}
}
public STTSRecord[] getEntries() {
return entries;
}
}
| Java |
package com.ams.media.mp4;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public final class MOOV {
private List<TRAK> traks = new ArrayList<TRAK>();
public void read(DataInputStream in) throws IOException {
try {
TRAK trak = null;
while (true) {
BOX.Header header = BOX.readHeader(in);
String box = header.type;
if ("trak".equalsIgnoreCase(box)) {
trak = new TRAK();
traks.add(trak);
continue;
} else if ("mdia".equalsIgnoreCase(box)) {
continue;
} else if ("minf".equalsIgnoreCase(box)) {
continue;
} else if ("stbl".equalsIgnoreCase(box)) {
continue;
}
byte[] b = new byte[(int) header.payloadSize];
in.read(b);
DataInputStream bin = new DataInputStream(
new ByteArrayInputStream(b));
int version = bin.readByte(); // version & flags
bin.skipBytes(3);
if ("mdhd".equalsIgnoreCase(box)) {
MDHD mdhd = new MDHD(version);
mdhd.read(bin);
trak.setMdhd(mdhd);
} else if ("stco".equalsIgnoreCase(box)) {
STCO stco = new STCO(version);
stco.read(bin);
trak.setStco(stco);
} else if ("co64".equalsIgnoreCase(box)) {
STCO stco = new STCO(version);
stco.read64(bin);
trak.setStco(stco);
} else if ("stsc".equalsIgnoreCase(box)) {
STSC stsc = new STSC(version);
stsc.read(bin);
trak.setStsc(stsc);
} else if ("stsd".equalsIgnoreCase(box)) {
STSD stsd = new STSD(version);
stsd.read(bin);
trak.setStsd(stsd);
} else if ("stss".equalsIgnoreCase(box)) {
STSS stss = new STSS(version);
stss.read(bin);
trak.setStss(stss);
} else if ("stsz".equalsIgnoreCase(box)) {
STSZ stsz = new STSZ(version);
stsz.read(bin);
trak.setStsz(stsz);
} else if ("stts".equalsIgnoreCase(box)) {
STTS stts = new STTS(version);
stts.read(bin);
trak.setStts(stts);
}
}
} catch (EOFException e) {
}
}
public TRAK getVideoTrak() {
for (TRAK trak : traks) {
if (trak.isVideoTrack()) {
return trak;
}
}
return null;
}
public TRAK getAudioTrak() {
for (TRAK trak : traks) {
if (trak.isAudioTrack()) {
return trak;
}
}
return null;
}
}
| Java |
package com.ams.media.mp4;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import com.ams.util.Utils;
public final class STSD extends BOX {
private SampleDescription[] descriptions;
private VideoSampleDescription videoSampleDescription = null;
private AudioSampleDescription audioSampleDescription = null;
public static class SampleDescription {
public String type;
public byte[] description;
}
public static class VideoSampleDescription {
public short index;
public short preDefined1;
public short reserved1;
public int preDefined2;
public int preDefined3;
public int preDefined4;
public short width;
public short height;
public int horizontalResolution;
public int verticalResolution;
public int reserved2;
public short frameCount;
public String compressorName;
public short depth;
public short preDefined5;
public String configType;
public byte[] decoderConfig;
public byte getAvcProfile() {
return decoderConfig[1];
}
public byte getAvcLevel() {
return decoderConfig[3];
}
public void read(DataInputStream in) throws IOException {
in.skipBytes(6); // reserved
index = in.readShort();
preDefined1 = in.readShort();
reserved1 = in.readShort();
preDefined2 = in.readInt();
preDefined3 = in.readInt();
preDefined4 = in.readInt();
width = in.readShort();
height = in.readShort();
horizontalResolution = in.readInt();
verticalResolution = in.readInt();
reserved2 = in.readInt();
frameCount = in.readShort();
int nameSize = in.readByte();
byte[] nameBytes = new byte[nameSize];
in.read(nameBytes);
compressorName = new String(nameBytes);
in.skipBytes(31 - nameSize);
depth = in.readShort();
preDefined5 = in.readShort();
int configSize = in.readInt();
byte[] b = new byte[4];
in.read(b);
configType = new String(b); // avcC
decoderConfig = new byte[configSize - 8];
in.read(decoderConfig);
}
}
public static class AudioSampleDescription {
public final static int ES_TAG = 3;
public final static int DECODER_CONFIG_TAG = 4;
public final static int DECODER_SPECIFIC_CONFIG_TAG = 5;
public short index;
public short innerVersion;
public short revisionLevel;
public int vendor;
public short channelCount;
public short sampleSize;
public short compressionId;
public short packetSize;
public int sampleRate;
public int samplesPerPacket;
public int bytesPerPacket;
public int bytesPerFrame;
public int samplesPerFrame;
public byte[] decoderSpecificConfig;
public int getAudioCodecType() {
int audioCodecType;
switch (decoderSpecificConfig[0]) {
case 0x12:
default:
// AAC LC - 12 10
audioCodecType = 1;
break;
case 0x0a:
// AAC Main - 0A 10
audioCodecType = 0;
break;
case 0x11:
case 0x13:
// AAC LC SBR - 11 90 & 13 xx
audioCodecType = 2;
break;
}
return audioCodecType;
}
private int readDescriptor(DataInputStream in) throws IOException {
int tag = in.readByte();
int size = 0;
int c = 0;
do {
c = in.readByte();
size = (size << 7) | (c & 0x7f);
} while ((c & 0x80) == 0x80);
if (tag == DECODER_SPECIFIC_CONFIG_TAG) {
decoderSpecificConfig = new byte[size];
in.read(decoderSpecificConfig);
}
return tag;
}
public void read(DataInputStream in) throws IOException {
in.skipBytes(6); // reserved
index = in.readShort();
innerVersion = in.readShort();
revisionLevel = in.readShort();
vendor = in.readInt();
channelCount = in.readShort();
sampleSize = in.readShort();
compressionId = in.readShort();
packetSize = in.readShort();
byte[] b = new byte[4];
in.read(b);
sampleRate = Utils.from16Bit(b);
if (innerVersion != 0) {
samplesPerPacket = in.readInt();
bytesPerPacket = in.readInt();
bytesPerFrame = in.readInt();
samplesPerFrame = in.readInt();
}
// read MP4Descriptor(in);
int size = in.readInt();
in.read(new byte[4]); // "esds"
in.readInt(); // version and flags
int tag = readDescriptor(in);
if (tag == ES_TAG) {
in.skipBytes(3);
} else {
in.skipBytes(2);
}
tag = readDescriptor(in);
if (tag == DECODER_CONFIG_TAG) {
in.skipBytes(13);
// DECODER_SPECIFIC_CONFIG_TAG
tag = readDescriptor(in);
}
}
}
public STSD(int version) {
super(version);
}
public void read(DataInputStream in) throws IOException {
int count = in.readInt();
descriptions = new SampleDescription[count];
for (int i = 0; i < count; i++) {
int length = in.readInt();
byte[] b = new byte[4];
in.read(b);
String type = new String(b);
byte[] description = new byte[length];
in.read(description);
descriptions[i] = new SampleDescription();
descriptions[i].type = type;
descriptions[i].description = description;
}
SampleDescription desc = getDescription();
if (isVideoSampleDescription(desc)) {
videoSampleDescription = getVideoSampleDescription(desc);
} else if (isAudioSampleDescription(desc)) {
audioSampleDescription = getAudioSampleDescription(desc);
}
}
public boolean isVideoSampleDescription(SampleDescription desc) {
if ("avc1".equalsIgnoreCase(desc.type)) {
return true;
}
return false;
}
public boolean isAudioSampleDescription(SampleDescription desc) {
if ("mp4a".equalsIgnoreCase(desc.type)) {
return true;
}
return false;
}
public SampleDescription getDescription() {
return descriptions[0];
}
public static VideoSampleDescription getVideoSampleDescription(
SampleDescription desc) throws IOException {
VideoSampleDescription sd = new VideoSampleDescription();
DataInputStream bin = new DataInputStream(new ByteArrayInputStream(
desc.description));
sd.read(bin);
return sd;
}
public static AudioSampleDescription getAudioSampleDescription(
SampleDescription desc) throws IOException {
AudioSampleDescription sd = new AudioSampleDescription();
DataInputStream bin = new DataInputStream(new ByteArrayInputStream(
desc.description));
sd.read(bin);
return sd;
}
public VideoSampleDescription getVideoSampleDescription() {
return videoSampleDescription;
}
public AudioSampleDescription getAudioSampleDescription() {
return audioSampleDescription;
}
}
| Java |
package com.ams.media.mp4;
import java.io.DataInputStream;
import java.io.IOException;
public final class STSC extends BOX {
public final class STSCRecord {
public int firstChunk;
public int samplesPerChunk;
public int sampleDescIndex;
}
private STSCRecord[] entries;
public STSC(int version) {
super(version);
}
public void read(DataInputStream in) throws IOException {
int count = in.readInt();
entries = new STSCRecord[count];
for (int i = 0; i < count; i++) {
entries[i] = new STSCRecord();
entries[i].firstChunk = in.readInt();
entries[i].samplesPerChunk = in.readInt();
entries[i].sampleDescIndex = in.readInt();
}
}
public STSCRecord[] getEntries() {
return entries;
}
}
| Java |
package com.ams.media.mp4;
import com.ams.media.MediaSample;
public class Mp4Sample extends MediaSample {
private int descriptionIndex;
public Mp4Sample(int sampleType, long timestamp, boolean keyframe,
long offset, int size, int sampleDescIndex) {
super(sampleType, timestamp, keyframe, offset, size);
this.descriptionIndex = sampleDescIndex;
}
public int getDescriptionIndex() {
return descriptionIndex;
}
}
| Java |
package com.ams.media.mp4;
import java.io.DataInputStream;
import java.io.IOException;
public final class STSZ extends BOX {
private int constantSize;
private int[] sizeTable;
public STSZ(int version) {
super(version);
}
public void read(DataInputStream in) throws IOException {
constantSize = in.readInt();
int sizeCount = in.readInt();
if (sizeCount > 0) {
sizeTable = new int[sizeCount];
for (int i = 0; i < sizeCount; i++) {
sizeTable[i] = in.readInt();
}
}
}
public int getConstantSize() {
return constantSize;
}
public int[] getSizeTable() {
return sizeTable;
}
}
| Java |
package com.ams.server;
import com.ams.io.network.SocketProperties;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
public final class Configuration {
private SocketProperties socketProperties = new SocketProperties();
private int memPoolSize = 0;
private int dispatcherThreadPoolSize = 8;
private int workerThreadPoolSize = 16;
private String httpHost = null;
private int httpPort = 80;
private String httpContextRoot = "www";
private String rtmpHost = null;
private int rtmpPort = 1935;
private int rtmptPort = 80;
private String rtmpContextRoot = "video";
private String replicationRtmpHost = null;
private int replicationRtmpPort = 1936;
private String[] replicationPublisherHosts = null;
private int replicationPublisherPort = 1936;
public boolean read() throws FileNotFoundException {
boolean result = true;
Properties prop = new Properties();
try {
prop.load(new FileInputStream("server.conf"));
String dispatchersProp = prop.getProperty("dispatchers");
if (dispatchersProp != null) {
dispatcherThreadPoolSize = Integer.parseInt(dispatchersProp);
}
String workersProp = prop.getProperty("workers");
if (workersProp != null) {
workerThreadPoolSize = Integer.parseInt(workersProp);
}
String poolProp = prop.getProperty("mempool");
if (poolProp != null) {
memPoolSize = Integer.parseInt(poolProp) * 1024 * 1024;
}
String hostProp = prop.getProperty("http.host");
if (hostProp != null) {
httpHost = hostProp;
}
String portProp = prop.getProperty("http.port");
if (portProp != null) {
httpPort = Integer.parseInt(portProp);
}
String root = prop.getProperty("http.root");
if (root != null) {
httpContextRoot = root;
}
hostProp = prop.getProperty("rtmp.host");
if (hostProp != null) {
rtmpHost = hostProp;
}
portProp = prop.getProperty("rtmp.port");
if (portProp != null) {
rtmpPort = Integer.parseInt(portProp);
}
portProp = prop.getProperty("rtmp.tunnel");
if (portProp != null) {
rtmptPort = Integer.parseInt(portProp);
}
root = prop.getProperty("rtmp.root");
if (root != null) {
rtmpContextRoot = root;
}
hostProp = prop.getProperty("repl.rtmp.host");
if (hostProp != null) {
replicationRtmpHost = hostProp;
}
portProp = prop.getProperty("repl.rtmp.port");
if (portProp != null) {
replicationRtmpPort = Integer.parseInt(portProp);
}
String hostsProp = prop.getProperty("repl.publisher.hosts");
if (hostsProp != null) {
replicationPublisherHosts = hostsProp.replaceAll(" ", "")
.split(",");
}
portProp = prop.getProperty("repl.publisher.port");
if (portProp != null) {
replicationPublisherPort = Integer.parseInt(portProp);
}
} catch (FileNotFoundException e) {
throw e;
} catch (IOException e) {
result = false;
}
return result;
}
public int getMemPoolSize() {
return memPoolSize;
}
public int getDispatcherThreadPoolSize() {
return dispatcherThreadPoolSize;
}
public int getWokerThreadPoolSize() {
return workerThreadPoolSize;
}
public String getHttpHost() {
return httpHost;
}
public int getHttpPort() {
return httpPort;
}
public String getHttpContextRoot() {
return httpContextRoot;
}
public String getRtmpHost() {
return rtmpHost;
}
public int getRtmpPort() {
return rtmpPort;
}
public String getRtmpContextRoot() {
return rtmpContextRoot;
}
public int getRtmptPort() {
return rtmptPort;
}
public SocketProperties getSocketProperties() {
return socketProperties;
}
public String getReplicationRtmpHost() {
return replicationRtmpHost;
}
public int getReplicationRtmpPort() {
return replicationRtmpPort;
}
public String[] getReplicationPublisherHosts() {
return replicationPublisherHosts;
}
public int getReplicationPublisherPort() {
return replicationPublisherPort;
}
}
| Java |
package com.ams.server;
public class Version {
public static final String SERVER_NAME = "AMS";
public static final String FMSVER = Version.SERVER_NAME + "/0,3,1,0";
public static final String VERSION = "0.3.1";
public static final String BUILD_DATE = "2013-05-01 00:00:00";
}
| Java |
package com.ams.server.replication;
import java.io.IOException;
import java.util.HashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ams.protocol.rtmp.RtmpConnection;
import com.ams.protocol.rtmp.RtmpException;
import com.ams.protocol.rtmp.RtmpHeader;
import com.ams.protocol.rtmp.amf.AmfException;
import com.ams.protocol.rtmp.amf.AmfValue;
import com.ams.protocol.rtmp.message.RtmpMessage;
import com.ams.protocol.rtmp.message.RtmpMessageCommand;
import com.ams.protocol.rtmp.net.NetConnectionException;
import com.ams.protocol.rtmp.net.StreamPublisher;
import com.ams.protocol.rtmp.net.StreamPublisherManager;
public class ReplSubscriber {
final private Logger logger = LoggerFactory.getLogger(ReplSubscriber.class);
private RtmpConnection rtmp;
private HashMap<Integer, String> streams = new HashMap<Integer, String>();
public ReplSubscriber(RtmpConnection rtmp) {
this.rtmp = rtmp;
}
public void sendSubscriptionCommand(String streamName) throws IOException {
AmfValue[] args = AmfValue.array(streamName);
RtmpMessage message = new RtmpMessageCommand("subscribe", 0, args);
rtmp.writeRtmpMessage(0, 0, 0, message);
}
public void acceptPublisherCommand() throws NetConnectionException,
IOException, RtmpException, AmfException {
// publisher will send publish command to subscriber
if (!rtmp.readRtmpMessage())
return;
RtmpHeader header = rtmp.getCurrentHeader();
RtmpMessage message = rtmp.getCurrentMessage();
switch (message.getType()) {
case RtmpMessage.MESSAGE_AMF0_COMMAND:
RtmpMessageCommand command = (RtmpMessageCommand) message;
if ("publish".equals(command.getName())) {
int streamId = header.getStreamId();
AmfValue[] args = command.getArgs();
String publishName = args[1].string();
streams.put(streamId, publishName);
if (StreamPublisherManager.getPublisher(publishName) == null) {
StreamPublisherManager
.addPublisher(new StreamPublisher(publishName));
}
logger.info("received publish command: {}", publishName);
} else if ("closeStream".equals(command.getName())) {
int streamId = header.getStreamId();
String publishName = streams.get(streamId);
if (publishName == null)
break;
streams.remove(streamId);
StreamPublisher publisher = StreamPublisherManager
.getPublisher(publishName);
if (publisher != null) {
publisher.close();
StreamPublisherManager.removePublisher(publishName);
logger.info("received close stream command: {}",
publishName);
}
}
break;
case RtmpMessage.MESSAGE_AUDIO:
case RtmpMessage.MESSAGE_VIDEO:
case RtmpMessage.MESSAGE_AMF0_DATA:
int streamId = header.getStreamId();
String publishName = streams.get(streamId);
if (publishName == null)
break;
// publish to local subscriber
StreamPublisher publisher = StreamPublisherManager
.getPublisher(publishName);
if (publisher != null) {
publisher.publish(message.toMediaMessage(header.getTimestamp()));
}
break;
case RtmpMessage.MESSAGE_ACK:
logger.debug("received publisher ping");
break;
}
}
} | Java |
package com.ams.server.replication;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ams.io.network.connection.Connection;
import com.ams.protocol.rtmp.RtmpConnection;
import com.ams.protocol.rtmp.RtmpHandShake;
import com.ams.server.handler.ProtocolHandler;
public class ReplPublishHandler extends ProtocolHandler {
final private Logger logger = LoggerFactory
.getLogger(ReplPublishHandler.class);
private RtmpHandShake handshake;
private ReplPublisher publisher;
private boolean keepAlive = true;
public void run() {
if (conn.isClosed()) {
close();
return;
}
try {
// wait until server handshake done
if (!handshake.isHandshakeDone()) {
handshake.doServerHandshake();
if (handshake.isHandshakeDone()) {
logger.info("replication rtmp handshake done.");
}
conn.flush();
return;
}
// publish stream to subscriber
publisher.acceptSubscription();
publisher.tryToCloseSubscribeStreams();
publisher.pingSubscriber();
Thread.sleep(10);
conn.flush();
} catch (Exception e) {
logger.debug(e.getMessage());
close();
}
}
public void close() {
conn.close();
keepAlive = false;
}
public void setConnection(Connection conn) {
this.conn = conn;
RtmpConnection rtmp = new RtmpConnection(conn);
this.publisher = new ReplPublisher(rtmp);
this.handshake = new RtmpHandShake(rtmp);
}
public boolean isKeepAlive() {
return keepAlive;
}
public ProtocolHandler handlerFactory() {
return new ReplPublishHandler();
}
} | Java |
package com.ams.server.replication;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ams.io.network.connection.Connection;
import com.ams.io.network.connection.SocketConnector;
import com.ams.protocol.rtmp.RtmpConnection;
import com.ams.protocol.rtmp.RtmpHandShake;
import com.ams.server.handler.ProtocolHandler;
public class ReplSubscribeHandler extends ProtocolHandler {
final private Logger logger = LoggerFactory
.getLogger(ReplSubscribeHandler.class);
private static final int CONNECT_RETRY_INTERVAL = 5 * 1000;
private String publisherHost = null;
private int publisherPort;
private RtmpConnection rtmp;
private RtmpHandShake handshake;
private boolean keepAlive = true;
private ReplSubscriber subscriber;
private ConcurrentLinkedQueue<String> subscriptionQueue = new ConcurrentLinkedQueue<String>();
public ReplSubscribeHandler(String host, int port) {
this.publisherHost = host;
this.publisherPort = port;
}
private boolean connectToPublisher() {
logger.info("connect to publisher {}:{} ...", publisherHost,
publisherPort);
try {
SocketConnector conn = SocketConnector
.connect(new InetSocketAddress(publisherHost, publisherPort));
setConnection(conn);
logger.info("connected.");
} catch (IOException e) {
logger.info("connect error");
return false;
}
return true;
}
private void doClientHandshake() {
logger.info("publisher rtmp handshake...");
while (!handshake.isHandshakeDone()) {
try {
handshake.doClientHandshake();
// write to socket channel
conn.flush();
} catch (Exception e) {
break;
}
}
}
private void handshakePublisher() {
if (!connectToPublisher()) {
logger.info("connect to publisher error, retry.");
try {
Thread.sleep(CONNECT_RETRY_INTERVAL);
} catch (InterruptedException e) {
}
return;
}
// do client handshake
doClientHandshake();
logger.info("replication rtmp handshake done.");
}
public void run() {
if (conn == null || conn.isClosed()) {
handshakePublisher();
}
try {
// wait&process publish command from publisher.
subscriber.acceptPublisherCommand();
// subscribe
String streamName = subscriptionQueue.poll();
if (streamName != null) {
logger.info("subscribe stream: {}", streamName);
subscriber.sendSubscriptionCommand(streamName);
}
Thread.sleep(10);
conn.flush();
} catch (Exception e) {
logger.debug(e.getMessage());
}
}
public void subscribe(String streamName) {
subscriptionQueue.add(streamName);
}
public void setConnection(Connection conn) {
this.conn = conn;
this.rtmp = new RtmpConnection(conn);
this.subscriber = new ReplSubscriber(rtmp);
this.handshake = new RtmpHandShake(rtmp);
}
public boolean isKeepAlive() {
return keepAlive;
}
public ProtocolHandler handlerFactory() {
return null;
}
public void close() {
conn.close();
keepAlive = false;
}
} | Java |
package com.ams.server.replication;
import java.io.IOException;
import java.util.HashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ams.protocol.rtmp.RtmpConnection;
import com.ams.protocol.rtmp.RtmpException;
import com.ams.protocol.rtmp.amf.AmfException;
import com.ams.protocol.rtmp.amf.AmfValue;
import com.ams.protocol.rtmp.message.RtmpMessage;
import com.ams.protocol.rtmp.message.RtmpMessageAck;
import com.ams.protocol.rtmp.message.RtmpMessageCommand;
import com.ams.protocol.rtmp.net.NetStream;
import com.ams.protocol.rtmp.net.NetStreamManager;
import com.ams.protocol.rtmp.net.StreamPublisherManager;
import com.ams.protocol.rtmp.net.StreamPublisher;
import com.ams.server.handler.RtmpHandler;
public class ReplPublisher {
final private Logger logger = LoggerFactory.getLogger(RtmpHandler.class);
final static int PING_SUBSCRIBER_INTERVAL = 1000;
private RtmpConnection rtmp;
private NetStreamManager streamManager;
private HashMap<String, NetStream> publishStreams = new HashMap<String, NetStream>();
private long lastPingTime = 0;;
public ReplPublisher(RtmpConnection rtmp) {
this.rtmp = rtmp;
this.streamManager = new NetStreamManager();
}
private void sendPublishCommand(NetStream stream, String publishName) {
try {
AmfValue[] args = AmfValue.array(null, publishName, "live");
RtmpMessage message = new RtmpMessageCommand("publish", 1, args);
stream.writeMessage(message);
} catch (IOException e) {
}
}
private void sendCloseStreamCommand(NetStream stream) throws IOException {
AmfValue[] args = { new AmfValue(null) };
RtmpMessage message = new RtmpMessageCommand("closeStream", 0, args);
stream.writeMessage(message);
}
private void startPublishStream(String publishName) {
// is publishing
if (publishStreams.containsKey(publishName)) {
logger.info("the stream is publishing: {}", publishName);
return;
}
StreamPublisher publisher = (StreamPublisher) StreamPublisherManager
.getPublisher(publishName);
if (publisher == null) {
logger.info("not found publisher: {}", publishName);
return;
}
NetStream stream = streamManager.createStream(rtmp);
publisher.addSubscriber(stream);
// this subscriber will publish stream to remote subscriber
publishStreams.put(publishName, stream);
// send publish command
sendPublishCommand(stream, publishName);
}
public void pingSubscriber() throws IOException {
// ping subscriber every 1s to keep subscriber alive.
long now = System.currentTimeMillis();
if (now - lastPingTime > PING_SUBSCRIBER_INTERVAL) {
rtmp.writeProtocolControlMessage(new RtmpMessageAck(1));
lastPingTime = now;
}
}
public void tryToCloseSubscribeStreams() throws IOException {
// try to close the streams that have been closed
for (String publishName : publishStreams.keySet()) {
NetStream subscriberStream = publishStreams.get(publishName);
if (StreamPublisherManager.getPublisher(publishName) == null) {
logger.info("close publish stream: {}", publishName);
sendCloseStreamCommand(subscriberStream);
publishStreams.remove(publishName);
}
}
}
public void acceptSubscription() throws IOException, AmfException,
RtmpException {
if (!rtmp.readRtmpMessage())
return;
RtmpMessage message = rtmp.getCurrentMessage();
if (message.getType() == RtmpMessage.MESSAGE_AMF0_COMMAND) {
RtmpMessageCommand command = (RtmpMessageCommand) message;
if ("subscribe".equals(command.getName())) {
AmfValue[] args = command.getArgs();
// subscriber want to play this stream
String streamName = args[1].string();
logger.info("received subscription, start to publish stream: {}", streamName);
startPublishStream(streamName);
}
}
}
} | Java |
package com.ams.server;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.LogManager;
public class Startup {
private static Server server;
private static Server createServerInstance(Configuration config) {
Server server = null;
try {
server = new Server(config);
} catch (IOException e) {
System.out.println("Creating server instance failed.");
return null;
}
return server;
}
public static void main(String[] args) {
System.out.println("Start " + Version.SERVER_NAME + " server "
+ Version.VERSION + ".");
System.setSecurityManager(null);
try {
InputStream in = new FileInputStream("log.properties");
LogManager.getLogManager().readConfiguration(in);
in.close();
} catch (Exception e) {
}
Configuration config = new Configuration();
try {
if (!config.read()) {
System.out.println("read config error!");
return;
}
} catch (FileNotFoundException e) {
System.out
.println("Not found server.conf file, use default setting!");
return;
}
server = createServerInstance(config);
if (server != null) {
server.startup();
}
}
}
| Java |
package com.ams.server;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ams.io.BufferAllocator;
import com.ams.io.BufferFactory;
import com.ams.io.network.NetworkHandler;
import com.ams.io.network.SocketAcceptor;
import com.ams.io.network.connection.ConnectionListener;
import com.ams.io.network.connection.Connection;
import com.ams.io.network.connection.NetworkConnector;
import com.ams.server.handler.HttpHandler;
import com.ams.server.handler.ProtocolHandler;
import com.ams.server.handler.RtmpHandler;
import com.ams.server.handler.RtmpTunnelHandler;
import com.ams.server.replication.ReplPublishHandler;
import com.ams.server.replication.ReplSubscribeHandler;
public class Server implements ConnectionListener {
private Logger logger = LoggerFactory.getLogger(Server.class);
private class WorkerThreadPoolExecutor extends ThreadPoolExecutor {
private static final int CORE_POOL_SIZE = 8;
private static final int QUEUE_SIZE = 256;
public WorkerThreadPoolExecutor(int maxPoolSize) {
super(CORE_POOL_SIZE, maxPoolSize, 60, TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(QUEUE_SIZE));
}
protected void afterExecute(Runnable r, Throwable t) {
if (r instanceof ProtocolHandler) {
ProtocolHandler handler = (ProtocolHandler) r;
if (handler.isKeepAlive()) {
execute(handler);
}
}
}
}
private Configuration config;
private HashMap<SocketAddress, NetworkHandler> acceptorMap;
private HashMap<SocketAddress, ProtocolHandler> handlerMap;
private ArrayList<ProtocolHandler> replicationSubscribeHandlers;
private WorkerThreadPoolExecutor executor;
public Server(Configuration config) throws IOException {
initByteBufferFactory(config);
this.config = config;
this.acceptorMap = new HashMap<SocketAddress, NetworkHandler>();
this.handlerMap = new HashMap<SocketAddress, ProtocolHandler>();
this.replicationSubscribeHandlers = new ArrayList<ProtocolHandler>();
int poolSize = config.getWokerThreadPoolSize();
executor = new WorkerThreadPoolExecutor(poolSize);
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
shutdown();
}
});
}
private void initByteBufferFactory(Configuration config) {
BufferAllocator allocator = new BufferAllocator();
if (config.getMemPoolSize() > 0) {
allocator.setPoolSize(config.getMemPoolSize());
}
allocator.init();
BufferFactory.setAllocator(allocator);
}
public void addTcpListenEndpoint(SocketAddress endpoint,
ProtocolHandler handler) throws IOException {
int dispatcherSize = config.getDispatcherThreadPoolSize();
SocketAcceptor acceptor = new SocketAcceptor(endpoint, dispatcherSize);
acceptor.setConnectionListener(this);
acceptor.setSocketProperties(config.getSocketProperties());
acceptorMap.put(endpoint, acceptor);
handlerMap.put(endpoint, handler);
}
private void createServiceHandler() {
try {
// http service
if (config.getHttpHost() != null) {
InetSocketAddress httpEndpoint = new InetSocketAddress(
config.getHttpHost(), config.getHttpPort());
addTcpListenEndpoint(httpEndpoint,
new HttpHandler(config.getHttpContextRoot()));
}
} catch (Exception e) {
logger.info("Creating http service failed.");
}
// normal rtmp service
if (config.getRtmpHost() != null) {
try {
InetSocketAddress rtmpEndpoint = new InetSocketAddress(
config.getRtmpHost(), config.getRtmpPort());
addTcpListenEndpoint(rtmpEndpoint,
new RtmpHandler(config.getRtmpContextRoot()));
} catch (Exception e) {
logger.info("Creating rtmp service failed.");
}
try {
// rtmpt service
InetSocketAddress rtmptEndpoint = new InetSocketAddress(
config.getRtmpHost(), config.getRtmptPort());
RtmpTunnelHandler handler = new RtmpTunnelHandler(
config.getRtmpContextRoot());
handler.setExecutor(executor);
addTcpListenEndpoint(rtmptEndpoint, handler);
} catch (Exception e) {
logger.info("Creating rtmpt service failed.");
}
}
}
public void createReplicationHandler() {
// create replication publisher handler
if (config.getReplicationRtmpHost() != null) {
try {
InetSocketAddress replicationEndpoint = new InetSocketAddress(
config.getReplicationRtmpHost(),
config.getReplicationRtmpPort());
addTcpListenEndpoint(replicationEndpoint,
new ReplPublishHandler());
} catch (Exception e) {
logger.info("Creating replication rtmp service failed.");
}
}
// create replication subscriber handlers
if (config.getReplicationPublisherHosts() != null) {
int publisherPort = config.getReplicationPublisherPort();
for (String publisherHost : config.getReplicationPublisherHosts()) {
ProtocolHandler handler = new ReplSubscribeHandler(
publisherHost, publisherPort);
replicationSubscribeHandlers.add(handler);
}
}
}
private void startupService() {
for (SocketAddress endpoint : acceptorMap.keySet()) {
NetworkHandler acceptor = acceptorMap.get(endpoint);
acceptor.start("acceptor");
logger.info("Start service on port: {}", endpoint);
}
for (ProtocolHandler handler : replicationSubscribeHandlers) {
executor.execute(handler);
}
}
public void startup() {
createServiceHandler();
createReplicationHandler();
startupService();
logger.info("Server is started.");
}
public void shutdown() {
for (ProtocolHandler handler : replicationSubscribeHandlers) {
handler.close();
}
for (SocketAddress endpoint : acceptorMap.keySet()) {
NetworkHandler acceptor = acceptorMap.get(endpoint);
acceptor.stop();
logger.info("Shutdown service on port: {}", endpoint);
System.out.println("Shutdown service on port: " + endpoint);
}
executor.shutdown();
logger.info("Server is shutdown.");
System.out.println("Server is shutdown.");
}
public ProtocolHandler getProtocolHandler(SocketAddress endpoint) {
if (handlerMap.containsKey(endpoint)) {
return handlerMap.get(endpoint);
} else {
if (endpoint instanceof InetSocketAddress) {
SocketAddress endpointAny = new InetSocketAddress("0.0.0.0",
((InetSocketAddress) endpoint).getPort());
if (handlerMap.containsKey(endpointAny)) {
return handlerMap.get(endpointAny);
}
}
}
return null;
}
protected void launchNewHandler(ProtocolHandler handler, Connection conn) {
ProtocolHandler newHandler = handler.handlerFactory();
newHandler.setConnection(conn);
newHandler.setExecutor(executor);
executor.execute(newHandler);
}
public void connectionEstablished(Connection conn) {
NetworkConnector networkConn = (NetworkConnector) conn;
SocketAddress endpoint = networkConn.getLocalEndpoint();
ProtocolHandler protocolHandler = getProtocolHandler(endpoint);
if (protocolHandler != null) {
launchNewHandler(protocolHandler, conn);
} else {
logger.warn("unkown connection port:{}", endpoint);
}
}
public void connectionClosed(Connection conn) {
}
} | Java |
package com.ams.server.handler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ams.protocol.http.DefaultServlet;
import com.ams.protocol.http.HttpContext;
import com.ams.protocol.http.HttpRequest;
import com.ams.protocol.http.HttpResponse;
public class HttpHandler extends ProtocolHandler {
final private Logger logger = LoggerFactory.getLogger(HttpHandler.class);
private String docRoot;
public HttpHandler(String docRoot) {
this.docRoot = docRoot;
}
public void run() {
try {
HttpRequest request = new HttpRequest(conn.getInputStream());
HttpResponse response = new HttpResponse(conn.getOutputStream());
request.parse();
DefaultServlet servlet = new DefaultServlet(
new HttpContext(docRoot));
servlet.service(request, response);
if (request.isKeepAlive()) {
conn.close(true);
} else {
conn.close();
}
} catch (Exception e) {
logger.debug(e.getMessage());
}
}
public ProtocolHandler handlerFactory() {
return new HttpHandler(docRoot);
}
} | Java |
package com.ams.server.handler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ams.io.network.connection.Connection;
import com.ams.protocol.rtmp.RtmpConnection;
import com.ams.protocol.rtmp.net.NetConnection;
import com.ams.protocol.rtmp.net.NetContext;
public class RtmpHandler extends ProtocolHandler {
final private Logger logger = LoggerFactory.getLogger(RtmpHandler.class);
private String docRoot;
private NetConnection netConn;
private boolean keepAlive = true;
public RtmpHandler(String docRoot) {
this.docRoot = docRoot;
}
public void run() {
if (conn.isClosed()) {
close();
return;
}
try {
if (conn.available() == 0) {
Thread.sleep(1);
}
// read & process rtmp message
netConn.readAndProcessRtmpMessage();
// play video
netConn.play();
} catch (Exception e) {
close();
}
}
public void setConnection(Connection conn) {
this.conn = conn;
RtmpConnection rtmp = new RtmpConnection(conn);
netConn = new NetConnection(rtmp, new NetContext(docRoot));
}
public boolean isKeepAlive() {
return keepAlive;
}
public ProtocolHandler handlerFactory() {
return new RtmpHandler(docRoot);
}
public void close() {
conn.close();
keepAlive = false;
}
} | Java |
package com.ams.server.handler;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Random;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ams.io.BufferFactory;
import com.ams.io.network.connection.Connection;
import com.ams.protocol.http.HTTP;
import com.ams.protocol.http.HttpRequest;
import com.ams.protocol.http.HttpResponse;
import com.ams.protocol.http.MimeTypes;
import com.ams.util.BufferUtils;
public class RtmpTunnelHandler extends ProtocolHandler {
final private Logger logger = LoggerFactory
.getLogger(RtmpTunnelHandler.class);
private String docRoot;
private static HashMap<String, Connection> sessions = new HashMap<String, Connection>();
private static byte[] pollInterval = { (byte) 0x01, (byte) 0x03,
(byte) 0x05, (byte) 0x09, (byte) 0x11, (byte) 0x21 };
private static int currentInterval = 0;
private static int emptyReplies = 0;
public RtmpTunnelHandler(String docRoot) {
this.docRoot = docRoot;
}
private String newSessionId() {
byte[] seed = new byte[15];
Random rnd = new Random();
rnd.nextBytes(seed);
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < seed.length; i++) {
hexString.append(Integer.toHexString(0xFF & seed[i]));
}
return hexString.toString();
}
private String getSessionId(String loc) {
return loc.split("/")[2];
}
private void nextInterval() {
if (currentInterval < pollInterval.length - 1) {
currentInterval++;
}
}
private byte getInterval(boolean isEmpty) {
if (isEmpty) {
emptyReplies++;
if (emptyReplies >= 10) {
emptyReplies = 0;
nextInterval();
}
} else {
currentInterval = 0;
}
return pollInterval[currentInterval];
}
private Connection launchHandler(ProtocolHandler handler) {
Connection conn = new Connection();
conn.open();
handler.setConnection(conn);
// put to worker queue to run
executor.execute(handler);
return conn;
}
private void openCommand(HttpRequest request, HttpResponse response)
throws IOException {
String sessionId = newSessionId();
// create rtmp handle
Connection tunnelConn = launchHandler(new RtmpHandler(docRoot));
sessions.put(sessionId, tunnelConn);
// return session id
response.print(sessionId);
response.print("\n");
response.flush();
}
private void sendCommand(HttpRequest request, HttpResponse response)
throws IOException {
String sessionId = getSessionId(request.getLocation());
if (sessionId == null) {
response.flush();
return;
}
Connection tunnelConn = sessions.get(sessionId);
if (tunnelConn == null) {
response.flush();
return;
}
ByteBuffer[] buf = request.getRawPostBodyData();
tunnelConn.offerInBuffers(buf);
ByteBuffer[] data = tunnelConn.pollOutBuffers();
// return interval & RTMP data
responseData(response, data);
}
private void idleCommand(HttpRequest request, HttpResponse response)
throws IOException {
String sessionId = getSessionId(request.getLocation());
if (sessionId == null) {
response.flush();
return;
}
Connection tunnelConn = sessions.get(sessionId);
if (tunnelConn == null) {
response.flush();
return;
}
ByteBuffer[] data = tunnelConn.pollOutBuffers();
// return interval & RTMP data
responseData(response, data);
}
private void closeCommand(HttpRequest request, HttpResponse response)
throws IOException {
String sessionId = getSessionId(request.getLocation());
if (sessionId == null) {
response.flush();
return;
}
Connection tunnelConn = sessions.get(sessionId);
sessions.remove(sessionId);
if (tunnelConn != null) {
tunnelConn.close();
}
// replay 0x00
ByteBuffer[] buf = new ByteBuffer[1];
buf[0] = BufferFactory.allocate(1);
buf[0].put((byte) 0x00);
buf[0].flip();
response.flush(buf);
}
private void responseData(HttpResponse response, ByteBuffer[] data)
throws IOException {
ByteBuffer[] buf = new ByteBuffer[1];
buf[0] = BufferFactory.allocate(1);
byte interval = getInterval(data.length == 0);
buf[0].put(interval);
buf[0].flip();
response.flush(BufferUtils.concat(buf, data));
}
private void responseError(HttpResponse response, int code)
throws IOException {
response.setContentType(MimeTypes.getContentType("text"));
response.setHttpResult(code);
response.flush();
}
public void run() {
HttpRequest request = new HttpRequest(conn.getInputStream());
HttpResponse response = new HttpResponse(conn.getOutputStream());
try {
request.parse();
response.setContentType(MimeTypes.getContentType("fcs"));
response.setKeepAlive(true);
response.setHttpResult(HTTP.HTTP_OK);
if (HTTP.HTTP_METHOD_POST == request.getMethod()) {
// OPEN, SEND, IDLE, CLOSE command
String loc = request.getLocation().toUpperCase();
if (loc.startsWith("/OPEN")) {
openCommand(request, response);
} else if (loc.startsWith("/SEND")) {
sendCommand(request, response);
} else if (loc.startsWith("/IDLE")) {
idleCommand(request, response);
} else if (loc.startsWith("/CLOSE")) {
closeCommand(request, response);
} else {
responseError(response, HTTP.HTTP_BAD_REQUEST);
}
}
if (request.isKeepAlive()) {
conn.close(true);
} else {
conn.close();
}
} catch (IOException e) {
logger.debug(e.getMessage());
try {
responseError(response, HTTP.HTTP_INTERNAL_ERROR);
} catch (IOException e1) {
}
close();
}
}
public ProtocolHandler handlerFactory() {
return new RtmpTunnelHandler(docRoot);
}
} | Java |
package com.ams.server.handler;
import java.util.concurrent.ExecutorService;
import com.ams.io.network.connection.Connection;
public abstract class ProtocolHandler implements Runnable {
protected Connection conn;
protected ExecutorService executor;
public void setConnection(Connection conn) {
this.conn = conn;
}
public void setExecutor(ExecutorService executor) {
this.executor = executor;
}
public abstract ProtocolHandler handlerFactory();
public boolean isKeepAlive() {
return false;
}
public void close() {
conn.close();
}
} | Java |
package com.ams.util;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
public class ObjectCache<T> {
private static int DEFAULT_EXPIRE_TIME = 60 * 60;
private class CacheItem {
private int expire = DEFAULT_EXPIRE_TIME;
private long accessTime = 0;
private T object = null;
public CacheItem(T object) {
this.object = object;
this.accessTime = System.currentTimeMillis();
}
public CacheItem(T object, int expire) {
this.object = object;
this.expire = expire;
this.accessTime = System.currentTimeMillis();
}
public void access() {
accessTime = System.currentTimeMillis();
}
public boolean isExpired() {
if (expire == -1)
return false;
else
return (accessTime + expire * 1000) < System
.currentTimeMillis();
}
public T getObject() {
return object;
}
}
private class CacheCollector extends Thread {
public CacheCollector() {
super();
try {
setDaemon(true);
} catch (Exception e) {
}
}
private void collect() {
// check all cache item
Iterator<String> it = items.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
CacheItem item = items.get(key);
// timeout
if (item.isExpired()) {
it.remove();
}
}
}
public void run() {
try {
while (!Thread.interrupted()) {
sleep(30000);
collect();
}
} catch (InterruptedException e) {
interrupt();
}
}
}
private CacheCollector collector;
private ConcurrentHashMap<String, CacheItem> items = new ConcurrentHashMap<String, CacheItem>();
public ObjectCache() {
collector = new CacheCollector();
collector.start();
}
public T get(String key) {
T obj = null;
if (items.containsKey(key)) {
CacheItem item = items.get(key);
// check for timeout
if (!item.isExpired()) {
item.access();
obj = item.getObject();
} else {
items.remove(key);
}
}
return obj;
}
public void put(String key, T obj) {
items.put(key, new CacheItem(obj));
}
public void put(String key, T obj, int expire) {
items.put(key, new CacheItem(obj, expire));
}
public void remove(String key) {
items.remove(key);
}
public Set<String> keySet() {
return items.keySet();
}
}
| Java |
package com.ams.util;
import java.nio.ByteBuffer;
public final class BufferUtils {
public static ByteBuffer slice(ByteBuffer buf, int start, int end) {
ByteBuffer b = buf.duplicate();
b.position(start);
b.limit(end);
return b.slice();
}
public static ByteBuffer trim(ByteBuffer buf, int length) {
ByteBuffer b = buf.duplicate();
b.limit(b.position() + length);
buf.position(buf.position() + length);
return b.slice();
}
public static ByteBuffer[] concat(ByteBuffer[] buf1, ByteBuffer[] buf2) {
ByteBuffer[] buf = new ByteBuffer[buf1.length + buf2.length];
int j = 0;
for (int i = 0, len = buf1.length; i < len; i++) {
buf[j++] = buf1[i];
}
for (int i = 0, len = buf2.length; i < len; i++) {
buf[j++] = buf2[i];
}
return buf;
}
}
| Java |
package com.ams.util;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public final class Utils {
public static int from16Bit(byte[] b) {
return (((b[0] & 0xFF) << 8) | (b[1] & 0xFF)) & 0xFFFF;
}
public static int from24Bit(byte[] b) {
return (((b[0] & 0xFF) << 16) | ((b[1] & 0xFF) << 8) | (b[2] & 0xFF)) & 0xFFFFFF;
}
public static long from32Bit(byte[] b) {
return (((b[0] & 0xFF) << 24) | ((b[1] & 0xFF) << 16)
| ((b[2] & 0xFF) << 8) | (b[3] & 0xFF)) & 0xFFFFFFFFL;
}
public static int from16BitLittleEndian(byte[] b) {
// 16 Bit read, LITTLE-ENDIAN
return (((b[1] & 0xFF) << 8) | (b[0] & 0xFF)) & 0xFFFF;
}
public static int from24BitLittleEndian(byte[] b) {
// 24 Bit read, LITTLE-ENDIAN
return (((b[2] & 0xFF) << 16) | ((b[1] & 0xFF) << 8) | (b[0] & 0xFF)) & 0xFFFFFF;
}
public static long from32BitLittleEndian(byte[] b) {
// 32 Bit read, LITTLE-ENDIAN
return (((b[3] & 0xFF) << 24) | ((b[2] & 0xFF) << 16)
| ((b[1] & 0xFF) << 8) | (b[0] & 0xFF)) & 0xFFFFFFFFL;
}
public static byte[] to16Bit(int v) {
byte[] b = new byte[2];
b[1] = (byte) (v & 0xFF);
b[0] = (byte) ((v & 0xFF00) >>> 8);
return b;
}
public static byte[] to24Bit(int v) {
byte[] b = new byte[3];
b[2] = (byte) (v & 0xFF);
b[1] = (byte) ((v & 0xFF00) >>> 8);
b[0] = (byte) ((v & 0xFF0000) >>> 16);
return b;
}
public static byte[] to32Bit(long v) {
byte[] b = new byte[4];
b[3] = (byte) (v & 0xFF);
b[2] = (byte) ((v & 0xFF00) >>> 8);
b[1] = (byte) ((v & 0xFF0000) >>> 16);
b[0] = (byte) ((v & 0xFF000000) >>> 24);
return b;
}
public static byte[] to16BitLittleEndian(int v) {
// 16bit write, LITTLE-ENDIAN
byte[] b = new byte[2];
b[0] = (byte) (v & 0xFF);
b[1] = (byte) ((v & 0xFF00) >>> 8);
return b;
}
public static byte[] to24BitLittleEndian(int v) {
byte[] b = new byte[3];
b[0] = (byte) (v & 0xFF);
b[1] = (byte) ((v & 0xFF00) >>> 8);
b[2] = (byte) ((v & 0xFF0000) >>> 16);
return b;
}
public static byte[] to32BitLittleEndian(long v) {
byte[] b = new byte[4];
// 32bit write, LITTLE-ENDIAN
b[0] = (byte) (v & 0xFF);
b[1] = (byte) ((v & 0xFF00) >>> 8);
b[2] = (byte) ((v & 0xFF0000) >>> 16);
b[3] = (byte) ((v & 0xFF000000) >>> 24);
return b;
}
public static String hexDigest(byte[] data) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA"); // SHA, MD5
md.update(data);
byte[] digest = md.digest();
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < digest.length; i++) {
hexString.append(Integer.toHexString(0xFF & digest[i]));
}
return hexString.toString();
}
}
| Java |
package com.ams.misc;
import java.nio.ByteBuffer;
import com.ams.io.BufferAllocator;
public class MemBenchmark {
public static void main(String[] args) {
int n = 10000;
int size = 10 * 1024;
long t1 = System.currentTimeMillis();
for (int i = 0; i < n; i++) {
byte[] a = new byte[size];
}
long t2 = System.currentTimeMillis();
System.out.println("heap time = " + (t2 - t1));
BufferAllocator allocator = new BufferAllocator();
allocator.setPoolSize(n * size + 100 * size);
allocator.init();
long tt1 = System.currentTimeMillis();
for (int i = 0; i < n; i++) {
ByteBuffer a = allocator.allocate(size);
}
long tt2 = System.currentTimeMillis();
System.out.println("slab time = " + (tt2 - tt1));
long ttt1 = System.currentTimeMillis();
for (int i = 0; i < n; i++) {
ByteBuffer a = ByteBuffer.allocateDirect(size);
}
long ttt2 = System.currentTimeMillis();
System.out.println("direct buffer time = " + (ttt2 - ttt1));
}
}
| Java |
package com.ams.misc;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ams.io.BufferOutputStream;
import com.ams.io.RandomAccessFileReader;
import com.ams.io.RandomAccessFileWriter;
import com.ams.media.flv.FlvDeserializer;
public class MakeFlvIndex {
final static private Logger logger = LoggerFactory
.getLogger(MakeFlvIndex.class);
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("MakeFlvIndex.main fileName");
return;
}
String fileName = args[0];
try {
logger.info("Start creating index...");
RandomAccessFileReader reader = new RandomAccessFileReader(
fileName, 0);
FlvDeserializer flvDeserializer = new FlvDeserializer(reader);
flvDeserializer.readSamples();
RandomAccessFileWriter writer = new RandomAccessFileWriter(fileName
+ ".idx", false);
FlvDeserializer.FlvIndex flvIndex = flvDeserializer.new FlvIndex();
BufferOutputStream bos = new BufferOutputStream(writer);
flvIndex.write(bos);
bos.flush();
bos.close();
logger.info("End creating index");
} catch (IOException e) {
e.printStackTrace();
logger.debug(e.toString());
}
}
}
| Java |
package com.ams.misc;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ams.protocol.rtmp.client.RtmpClient;
public class VideoPublisher {
final static private Logger logger = LoggerFactory
.getLogger(VideoPublisher.class);
public static void publish(String publishName, String fileName,
String host, int port) throws IOException {
logger.info("connect to server...");
RtmpClient client = new RtmpClient(host, port);
client.connect("webcam");
logger.info("create stream...");
int streamId = client.createStream();
logger.info("start publish...");
if (!client.publish(streamId, publishName, fileName)) {
logger.info(client.getErrorMsg());
client.close();
}
}
public static void main(String[] args) {
if (args.length < 3) {
System.out
.println("VideoPublisher.main publishName fileName host [port]");
return;
}
String publishName = args[0];
String fileName = args[1];
String host = args[2];
int port = args.length == 4 ? Integer.parseInt(args[3]) : 1935;
try {
publish(publishName, fileName, host, port);
} catch (IOException e) {
logger.debug(e.toString());
}
}
}
| Java |
package com.ams.io;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class RandomAccessFileWriter implements IByteBufferWriter {
private RandomAccessFile file;
private FileChannel channel = null;
private RandomAccessFile openFile(String fileName) throws IOException {
RandomAccessFile raFile = null;
try {
raFile = new RandomAccessFile(new File(fileName), "rw");
} catch (Exception e) {
if (raFile != null) {
raFile.close();
throw new IOException("Corrupted File '" + fileName + "'");
}
throw new IOException("File not found '" + fileName + "'");
}
return raFile;
}
public RandomAccessFileWriter(String fileName, boolean append)
throws IOException {
this.file = openFile(fileName);
if (append) {
this.file.seek(this.file.length());
}
this.channel = file.getChannel();
}
public void write(ByteBuffer[] data) throws IOException {
channel.write(data);
}
public void close() throws IOException {
file.close();
}
public void write(byte[] data, int offset, int len) throws IOException {
}
}
| Java |
package com.ams.io;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import com.ams.server.ByteBufferFactory;
import com.ams.util.ByteBufferHelper;
public class RandomAccessFileReader implements IByteBufferReader {
private RandomAccessFile file;
private FileChannel channel = null;
private ByteBuffer buffer = null;
private long position = 0;
private boolean eof = false;
private RandomAccessFile openFile(String fileName) throws IOException {
RandomAccessFile raFile = null;
try {
raFile = new RandomAccessFile(new File(fileName), "r");
} catch (Exception e) {
if (raFile != null) {
raFile.close();
throw new IOException("Corrupted File '" + fileName + "'");
}
throw new IOException("File not found '" + fileName + "'");
}
return raFile;
}
public RandomAccessFileReader(String fileName, long startPosition)
throws IOException {
this.file = openFile(fileName);
this.channel = file.getChannel();
file.seek(startPosition);
position = startPosition;
}
public int read(byte[] data, int offset, int size) throws IOException {
// throw an exception if eof
if (eof) {
throw new EOFException("stream is eof");
}
int amount = 0;
int length = size;
while (length > 0) {
// read a buffer
if (buffer != null && buffer.hasRemaining()) {
int remain = buffer.remaining();
if (length >= remain) {
buffer.get(data, offset, remain);
buffer = null;
length -= remain;
position += remain;
offset += remain;
amount += remain;
} else {
buffer.get(data, offset, length);
position += length;
offset += length;
amount += length;
length = 0;
}
} else {
this.buffer = ByteBufferFactory.allocate(32 * 1024);
int len = channel.read(buffer);
if (len < 0) {
eof = true;
this.buffer = null;
throw new EOFException("stream is eof");
}
buffer.flip();
}
} // end while
return amount;
}
public ByteBuffer[] read(int size) throws IOException {
// throw an exception if eof
if (eof) {
throw new EOFException("stream is eof");
}
ArrayList<ByteBuffer> list = new ArrayList<ByteBuffer>();
int length = size;
while (length > 0) {
// read a buffer
if (buffer != null && buffer.hasRemaining()) {
int remain = buffer.remaining();
if (length >= remain) {
list.add(buffer);
buffer = null;
length -= remain;
position += remain;
} else {
ByteBuffer slice = ByteBufferHelper.cut(buffer, length);
list.add(slice);
position += length;
length = 0;
}
} else {
this.buffer = ByteBufferFactory.allocate(32 * 1024);
int len = channel.read(buffer);
if (len < 0) {
eof = true;
this.buffer = null;
throw new EOFException("stream is eof");
}
buffer.flip();
}
} // end while
return list.toArray(new ByteBuffer[list.size()]);
}
public void seek(long startPosition) throws IOException {
if (this.buffer != null) {
int bufferPosition = buffer.position();
if (startPosition >= position - bufferPosition
&& startPosition < position + buffer.remaining()) {
buffer.position((int) (startPosition - position + bufferPosition));
position = startPosition;
return;
}
}
file.seek(position);
position = startPosition;
this.buffer = null;
this.eof = false;
}
public boolean isEof() {
return eof;
}
public void close() throws IOException {
file.close();
}
}
| Java |
package com.ams.io;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import com.ams.server.ByteBufferFactory;
public class ByteBufferOutputStream extends OutputStream {
protected static final int WRITE_BUFFER_SIZE = 512;
protected ArrayList<ByteBuffer> buffers = null;
protected ByteBuffer writeBuffer = null;
protected IByteBufferWriter writer = null;
public ByteBufferOutputStream() {
this.buffers = new ArrayList<ByteBuffer>();
this.writer = null;
}
public ByteBufferOutputStream(IByteBufferWriter writer) {
this.buffers = null;
this.writer = writer;
}
private void offerWriteBuffer() {
if (writeBuffer != null) {
writeBuffer.flip();
buffers.add(writeBuffer);
writeBuffer = null;
}
}
private void flushWriteBuffer() throws IOException {
if (writeBuffer != null) {
writeBuffer.flip();
writer.write(new ByteBuffer[] {writeBuffer});
writeBuffer = null;
}
}
public void flush() throws IOException {
if (writer != null) {
flushWriteBuffer();
} else {
offerWriteBuffer();
}
}
public void write(byte[] data, int offset, int len) throws IOException {
while (true) {
if (writeBuffer == null) {
int size = Math.max(len, WRITE_BUFFER_SIZE);
writeBuffer = ByteBufferFactory.allocate(size);
}
if (writeBuffer.remaining() >= len) {
writeBuffer.put(data, offset, len);
break;
}
flush();
}
}
public void write(byte[] data) throws IOException {
write(data, 0, data.length);
}
public void write(int data) throws IOException {
byte[] b = new byte[1];
b[0] = (byte) (data & 0xFF);
write(b, 0, 1);
}
public ByteBuffer[] toByteBufferArray() {
offerWriteBuffer();
return buffers.toArray(new ByteBuffer[buffers.size()]);
}
public void writeByte(int v) throws IOException {
byte[] b = new byte[1];
b[0] = (byte) (v & 0xFF);
write(b, 0, 1);
}
public void write16Bit(int v) throws IOException {
// 16bit write, LITTLE-ENDIAN
byte[] b = new byte[2];
b[1] = (byte) (v & 0xFF);
b[0] = (byte) ((v & 0xFF00) >>> 8);
write(b, 0, 2);
}
public void write24Bit(int v) throws IOException {
byte[] b = new byte[3];
b[2] = (byte) (v & 0xFF);
b[1] = (byte) ((v & 0xFF00) >>> 8);
b[0] = (byte) ((v & 0xFF0000) >>> 16);
write(b, 0, 3); // 24bit
}
public void write32Bit(long v) throws IOException {
byte[] b = new byte[4];
b[3] = (byte) (v & 0xFF);
b[2] = (byte) ((v & 0xFF00) >>> 8);
b[1] = (byte) ((v & 0xFF0000) >>> 16);
b[0] = (byte) ((v & 0xFF000000) >>> 24);
write(b, 0, 4); // 32bit
}
public void write16BitLittleEndian(int v) throws IOException {
// 16bit write, LITTLE-ENDIAN
byte[] b = new byte[2];
b[0] = (byte) (v & 0xFF);
b[1] = (byte) ((v & 0xFF00) >>> 8);
write(b, 0, 2);
}
public void write24BitLittleEndian(int v) throws IOException {
byte[] b = new byte[3];
b[0] = (byte) (v & 0xFF);
b[1] = (byte) ((v & 0xFF00) >>> 8);
b[2] = (byte) ((v & 0xFF0000) >>> 16);
write(b, 0, 3); // 24bit
}
public void write32BitLittleEndian(long v) throws IOException {
byte[] b = new byte[4];
// 32bit write, LITTLE-ENDIAN
b[0] = (byte) (v & 0xFF);
b[1] = (byte) ((v & 0xFF00) >>> 8);
b[2] = (byte) ((v & 0xFF0000) >>> 16);
b[3] = (byte) ((v & 0xFF000000) >>> 24);
write(b, 0, 4);
}
public void writeByteBuffer(ByteBuffer[] data) throws IOException {
if (writer != null) {
flushWriteBuffer();
writer.write(data);
} else {
offerWriteBuffer();
for (ByteBuffer buf : data)
buffers.add(buf);
}
}
}
| Java |
package com.ams.io;
import java.io.*;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import com.ams.util.ByteBufferHelper;
public class ByteBufferInputStream extends InputStream {
protected IByteBufferReader reader = null;
// buffer queue
protected ByteBuffer[] buffers = null;
protected int index = 0;
protected int mark = -1;
protected byte[] line = new byte[4096];
public ByteBufferInputStream(ByteBuffer[] buffers) {
this.buffers = buffers;
this.reader = null;
}
public ByteBufferInputStream(IByteBufferReader reader) {
this.buffers = null;
this.reader = reader;
}
public String readLine() throws IOException {
// throw an exception if the stream is closed
// closedCheck();
int index = 0;
boolean marked = false;
while (true) {
int c = read();
if (c != -1) {
byte ch = (byte) c;
if (ch == '\r') { // expect next byte is CR
marked = true;
} else if (ch == '\n') { // have read a line, exit
if (marked)
index--;
break;
} else {
marked = false;
}
line[index++] = ch;
// need to expand the line buffer
int capacity = line.length;
if (index >= capacity) {
capacity = capacity * 2 + 1;
byte[] tmp = new byte[capacity];
System.arraycopy(line, 0, tmp, 0, index);
line = tmp;
}
} else {
if (marked) {
index--;
}
break;
}
} // while
return new String(line, 0, index, "UTF-8");
}
public int read() throws IOException {
byte[] one = new byte[1];
// read 1 byte
int amount = read(one, 0, 1);
// return EOF / the byte
return (amount < 0) ? -1 : one[0] & 0xff;
}
public int read(byte data[], int offset, int length) throws IOException {
// check parameters
if (data == null) {
throw new NullPointerException();
} else if ((offset < 0) || (offset + length > data.length)
|| (length < 0)) { // check indices
throw new IndexOutOfBoundsException();
}
if (buffers == null) {
ByteBuffer[] buffers = reader.read(length);
for(ByteBuffer buffer : buffers) {
int size = buffer.remaining();
buffer.get(data, offset, size);
offset += size;
}
return length;
}
if (index >= buffers.length) {
return -1;
} else if (index == buffers.length - 1
&& !buffers[index].hasRemaining()) {
return -1;
} else if (length == 0 || data.length == 0) {
return (available() > 0 ? 0 : -1);
}
int readBytes = 0;
while (index < buffers.length) {
ByteBuffer buf = buffers[index];
int size = Math.min(length - readBytes, buf.remaining());
buf.get(data, offset + readBytes, size);
readBytes += size;
if (readBytes >= length)
break;
index++;
}
return (readBytes > 0 ? readBytes : -1);
}
public long skip(long n) {
if (buffers == null)
return -1;
long cnt = 0;
while (index < buffers.length) {
ByteBuffer buf = buffers[index];
long size = Math.min(buf.remaining(), n - cnt);
buf.position(buf.position() + (int) size);
cnt += size;
if (cnt == n) {
break;
}
index++;
}
return cnt;
}
public int available() {
if (buffers == null)
return -1;
int available = 0;
for (int i = buffers.length - 1; i >= index; i--) {
available += buffers[i].remaining();
}
return available;
}
public void close() throws IOException {
index = 0;
mark = -1;
buffers = null;
// if (reader != null) reader.close();
}
public void mark(final int readlimit) {
if (buffers == null)
return;
if (index < buffers.length) {
mark = index;
for (int i = buffers.length - 1; i >= mark; i--) {
buffers[i].mark();
}
}
}
public void reset() throws IOException {
if (buffers == null)
return;
if (mark != -1) {
index = mark;
for (int i = buffers.length - 1; i >= index; i--) {
buffers[i].reset();
}
mark = -1;
}
}
public boolean markSupported() {
if (buffers == null)
return false;
return true;
}
public byte readByte() throws IOException {
byte[] b = new byte[1];
read(b, 0, 1);
return b[0];
}
public int read16Bit() throws IOException {
byte[] b = new byte[2];
read(b, 0, 2); // 16Bit read
return ((b[0] & 0xFF) << 8) | (b[1] & 0xFF);
}
public int read24Bit() throws IOException {
byte[] b = new byte[3];
read(b, 0, 3); // 24Bit read
return ((b[0] & 0xFF) << 16) | ((b[1] & 0xFF) << 8) | (b[2] & 0xFF);
}
public long read32Bit() throws IOException {
byte[] b = new byte[4];
read(b, 0, 4); // 32Bit read
return ((b[0] & 0xFF) << 24) | ((b[1] & 0xFF) << 16)
| ((b[2] & 0xFF) << 8) | (b[3] & 0xFF);
}
public int read16BitLittleEndian() throws IOException {
byte[] b = new byte[2];
read(b, 0, 2);
// 16 Bit read, LITTLE-ENDIAN
return ((b[1] & 0xFF) << 8) | (b[0] & 0xFF);
}
public int read24BitLittleEndian() throws IOException {
byte[] b = new byte[3];
read(b, 0, 3);
// 24 Bit read, LITTLE-ENDIAN
return ((b[2] & 0xFF) << 16) | ((b[1] & 0xFF) << 8) | (b[0] & 0xFF);
}
public long read32BitLittleEndian() throws IOException {
byte[] b = new byte[4];
read(b, 0, 4);
// 32 Bit read, LITTLE-ENDIAN
return ((b[3] & 0xFF) << 24) | ((b[2] & 0xFF) << 16)
| ((b[1] & 0xFF) << 8) | (b[0] & 0xFF);
}
public ByteBuffer[] readByteBuffer(int size) throws IOException {
if (reader != null) {
return reader.read(size);
} else {
ArrayList<ByteBuffer> list = new ArrayList<ByteBuffer>();
int length = size;
while (length > 0 && index < buffers.length) {
// read a buffer
ByteBuffer buffer = buffers[index];
int remain = buffer.remaining();
if (length >= remain) {
list.add(buffer);
index++;
length -= remain;
} else {
ByteBuffer slice = ByteBufferHelper.cut(buffer, length);
list.add(slice);
length = 0;
}
}
return list.toArray(new ByteBuffer[list.size()]);
}
}
}
| Java |
package com.ams.io;
import java.io.IOException;
import java.nio.ByteBuffer;
public interface IByteBufferReader {
public ByteBuffer[] read(int size) throws IOException;
}
| Java |
package com.ams.io;
import java.io.IOException;
import java.nio.ByteBuffer;
public interface IByteBufferWriter {
public void write(ByteBuffer[] data) throws IOException;
}
| Java |
package com.ams.flv;
import java.io.EOFException;
import java.io.IOException;
import java.nio.ByteBuffer;
import com.ams.io.ByteBufferInputStream;
import com.ams.io.ByteBufferOutputStream;
import com.ams.util.ByteBufferHelper;
public class FlvTag {
public static final int FLV_AUDIO = 0;
public static final int FLV_VIDEO = 1;
public static final int FLV_META = 2;
private int tagType;
private ByteBuffer[] data;
private long timestamp;
public FlvTag(int tagType, ByteBuffer[] data, long timestamp) {
super();
this.tagType = tagType;
this.data = data;
this.timestamp = timestamp;
}
public ByteBuffer[] getData() {
return data;
}
public long getTimestamp() {
return timestamp;
}
public int getTagType() {
return tagType;
}
public static FlvTag read(ByteBufferInputStream in) throws IOException,
FlvException {
int tagType;
try {
tagType = in.readByte() & 0xFF;
} catch (EOFException e) {
return null;
}
int dataSize = in.read24Bit(); // 24Bit read
long timestamp = in.read24Bit(); // 24Bit read
timestamp |= (in.readByte() & 0xFF) << 24; // time stamp extended
int streamId = in.read24Bit(); // 24Bit read
// if( streamId != 0 ) {
// throw new FlvException("Invalid stream Id: " + streamId);
// }
ByteBuffer[] data = in.readByteBuffer(dataSize);
int previousTagSize = (int) in.read32Bit();
// if( previousTagSize != 0 && previousTagSize != dataSize + 11 ) {
// throw new FlvException("Invalid previous tag size (" + dataSize +
// " != " + previousTagSize + ")");
// }
switch (tagType) {
case 0x08:
return new FlvTag(FlvTag.FLV_AUDIO, data, timestamp);
case 0x09:
return new FlvTag(FlvTag.FLV_VIDEO, data, timestamp);
case 0x12:
return new FlvTag(FlvTag.FLV_META, data, timestamp);
default:
throw new FlvException("Invalid FLV tag " + tagType);
}
}
public static void write(ByteBufferOutputStream out, FlvTag flvTag)
throws IOException {
byte tagType = -1;
switch (flvTag.getTagType()) {
case FlvTag.FLV_AUDIO:
tagType = 0x08;
break;
case FlvTag.FLV_VIDEO:
tagType = 0x09;
break;
case FlvTag.FLV_META:
tagType = 0x12;
break;
}
// tag type
out.writeByte(tagType);
ByteBuffer[] data = flvTag.getData();
// data size
int dataSize = ByteBufferHelper.size(data);
out.write24Bit(dataSize); // 24Bit write
// time stamp
int timestamp = (int) flvTag.getTimestamp();
out.write24Bit(timestamp); // 24Bit write
out.writeByte((byte) ((timestamp & 0xFF000000) >>> 32));
// stream ID
out.write24Bit(0);
// data
out.writeByteBuffer(data);
// previousTagSize
out.write32Bit(dataSize + 11);
}
public static boolean isVideoKeyFrame(ByteBuffer[] data) {
return (data[0].get(0) >>> 4) == 1;
}
}
| Java |
package com.ams.flv;
public class FlvException extends Exception {
private static final long serialVersionUID = 1L;
public FlvException() {
super();
}
public FlvException(String arg0) {
super(arg0);
}
}
| Java |
package com.ams.flv;
import java.io.IOException;
import com.ams.io.ByteBufferInputStream;
import com.ams.io.ByteBufferOutputStream;
public class FlvHeader {
private byte[] signature = { 'F', 'L', 'V' };
private int version = 0x01;
private boolean hasAudio;
private boolean hasVideo;
private int dataOffset = 0x09;
public FlvHeader(boolean hasAudio, boolean hasVideo) {
this.hasAudio = hasAudio;
this.hasVideo = hasVideo;
}
public boolean isHasAudio() {
return hasAudio;
}
public boolean isHasVideo() {
return hasVideo;
}
public byte[] getSignature() {
return signature;
}
public int getVersion() {
return version;
}
public int getDataOffset() {
return dataOffset;
}
public static FlvHeader read(ByteBufferInputStream in) throws IOException,
FlvException {
int b1 = in.readByte() & 0xFF;
int b2 = in.readByte() & 0xFF;
int b3 = in.readByte() & 0xFF;
if (b1 != 'F' || b2 != 'L' || b3 != 'V')
throw new FlvException("Invalid signature");
int version = in.readByte() & 0xFF;
if (version != 0x01)
throw new FlvException("Invalid version");
int flags = in.readByte() & 0xFF;
if ((flags & 0xF2) != 0)
throw new FlvException("Invalid tag type flags: " + flags);
int dataOffset = (int) in.read32Bit();
if (dataOffset != 0x09)
throw new FlvException("Invalid data offset: " + dataOffset);
int previousTagSize0 = (int) in.read32Bit();
if (previousTagSize0 != 0)
throw new FlvException("Invalid previous tag size 0: "
+ previousTagSize0);
boolean hasAudio = (flags & 1) != 1;
boolean hasVideo = (flags & 4) != 1;
return new FlvHeader(hasAudio, hasVideo);
}
public static void write(ByteBufferOutputStream out, FlvHeader header)
throws IOException {
out.writeByte('F');
out.writeByte('L');
out.writeByte('V');
out.writeByte(0x01); // version
int flgs = 0;
flgs += header.isHasAudio() ? 1 : 0;
flgs += header.isHasVideo() ? 4 : 0;
out.writeByte(flgs & 0xFF); // hasAudio && hasVideo
out.write32Bit(0x09); // dataOffset
out.write32Bit(0x00); // previousTagSize0
}
} | Java |
package com.ams.so;
import java.util.HashMap;
import com.ams.amf.AmfValue;
public class SoEventChange extends SoEvent {
private HashMap<String, AmfValue> data;
public SoEventChange(HashMap<String, AmfValue> data) {
super(SO_EVT_CHANGE);
this.data = data;
}
public HashMap<String, AmfValue> getData() {
return data;
}
}
| Java |
package com.ams.so;
import com.ams.amf.AmfValue;
public class SoEventSendMessage extends SoEvent {
private AmfValue msg;
public SoEventSendMessage(AmfValue msg) {
super(SO_EVT_SEND_MESSAGE);
this.msg = msg;
}
public AmfValue getMsg() {
return msg;
}
}
| Java |
package com.ams.so;
public class SoEventStatus extends SoEvent {
private String msg;
private String msgType;
public SoEventStatus(String msg, String msgType) {
super(SO_EVT_STATUS);
this.msg = msg;
this.msgType = msgType;
}
public String getMsg() {
return msg;
}
public String getMsgType() {
return msgType;
}
}
| Java |
package com.ams.so;
public class SoEventRequestRemove extends SoEvent {
private String name;
public SoEventRequestRemove(String name) {
super(SO_EVT_REQUEST_REMOVE);
this.name = name;
}
public String getName() {
return name;
}
}
| Java |
package com.ams.so;
public class SoEventSuceess extends SoEvent {
private String name;
public SoEventSuceess(String name) {
super(SO_EVT_SUCCESS);
this.name = name;
}
public String getName() {
return name;
}
}
| Java |
package com.ams.so;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import com.ams.amf.Amf0Deserializer;
import com.ams.amf.Amf0Serializer;
import com.ams.amf.AmfException;
import com.ams.amf.AmfValue;
public class SoEvent {
public static final int SO_EVT_USE = 1;
public static final int SO_EVT_RELEASE = 2;
public static final int SO_EVT_REQUEST_CHANGE = 3;
public static final int SO_EVT_CHANGE = 4;
public static final int SO_EVT_SUCCESS = 5;
public static final int SO_EVT_SEND_MESSAGE = 6;
public static final int SO_EVT_STATUS = 7;
public static final int SO_EVT_CLEAR = 8;
public static final int SO_EVT_REMOVE = 9;
public static final int SO_EVT_REQUEST_REMOVE = 10;
public static final int SO_EVT_USE_SUCCESS = 11;
private int kind = 0;
public SoEvent(int kind) {
this.kind = kind;
}
public int getKind() {
return kind;
}
public static SoEvent read(DataInputStream in, int kind, int size) throws IOException, AmfException {
Amf0Deserializer deserializer = new Amf0Deserializer(in);
SoEvent event = null;
switch(kind) {
case SoEvent.SO_EVT_USE:
event = new SoEvent(SoEvent.SO_EVT_USE);
break;
case SoEvent.SO_EVT_RELEASE:
event = new SoEvent(SoEvent.SO_EVT_RELEASE);
break;
case SoEvent.SO_EVT_REQUEST_CHANGE:
event = new SoEventRequestChange(in.readUTF(), deserializer.read());
break;
case SoEvent.SO_EVT_CHANGE:
HashMap<String, AmfValue> hash = new HashMap<String, AmfValue>();
while( true ) {
String key = null;
try {
key = in.readUTF();
}catch(EOFException e) {
break;
}
hash.put(key, deserializer.read());
}
event = new SoEventChange(hash);
break;
case SoEvent.SO_EVT_SUCCESS:
event = new SoEventSuceess(in.readUTF());
break;
case SoEvent.SO_EVT_SEND_MESSAGE:
event = new SoEventSendMessage(deserializer.read());
break;
case SoEvent.SO_EVT_STATUS:
String msg = in.readUTF();
String type = in.readUTF();
event = new SoEventStatus(msg, type);
break;
case SoEvent.SO_EVT_CLEAR:
event = new SoEvent(SoEvent.SO_EVT_CLEAR);
break;
case SoEvent.SO_EVT_REMOVE:
event = new SoEvent(SoEvent.SO_EVT_REMOVE);
break;
case SoEvent.SO_EVT_REQUEST_REMOVE:
event = new SoEventRequestRemove(in.readUTF());
break;
case SoEvent.SO_EVT_USE_SUCCESS:
event = new SoEvent(SoEvent.SO_EVT_USE_SUCCESS);
}
return event;
}
public static void write(DataOutputStream out, SoEvent event) throws IOException {
Amf0Serializer serializer = new Amf0Serializer(out);
switch(event.getKind()) {
case SoEvent.SO_EVT_USE:
case SoEvent.SO_EVT_RELEASE:
case SoEvent.SO_EVT_CLEAR:
case SoEvent.SO_EVT_REMOVE:
case SoEvent.SO_EVT_USE_SUCCESS:
// nothing
break;
case SoEvent.SO_EVT_REQUEST_CHANGE:
out.writeUTF(((SoEventRequestChange)event).getName());
serializer.write(((SoEventRequestChange)event).getValue());
break;
case SoEvent.SO_EVT_CHANGE:
HashMap<String, AmfValue> data = ((SoEventChange)event).getData();
Iterator<String> it = data.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
out.writeUTF(key);
serializer.write(data.get(key));
}
break;
case SoEvent.SO_EVT_SUCCESS:
out.writeUTF(((SoEventSuceess)event).getName());
break;
case SoEvent.SO_EVT_SEND_MESSAGE:
serializer.write(((SoEventSendMessage)event).getMsg());
break;
case SoEvent.SO_EVT_STATUS:
out.writeUTF(((SoEventStatus)event).getMsg());
out.writeUTF(((SoEventStatus)event).getMsgType());
break;
case SoEvent.SO_EVT_REQUEST_REMOVE:
out.writeUTF(((SoEventRequestRemove)event).getName());
break;
}
}
}
| Java |
package com.ams.so;
import com.ams.amf.AmfValue;
public class SoEventRequestChange extends SoEvent {
private String name;
private AmfValue value;
public SoEventRequestChange(String name, AmfValue value) {
super(SO_EVT_REQUEST_CHANGE);
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public AmfValue getValue() {
return value;
}
}
| Java |
package com.ams.so;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.util.ArrayList;
import com.ams.amf.AmfException;
public class SoMessage {
private String name;
private int version;
private boolean persist;
private int unknown;
private ArrayList<SoEvent> events;
public SoMessage(String name, int version, boolean persist, int unknown, ArrayList<SoEvent> events) {
this.name = name;
this.version = version;
this.persist = persist;
this.unknown = unknown;
this.events = events;
}
public ArrayList<SoEvent> getEvents() {
return events;
}
public String getName() {
return name;
}
public boolean isPersist() {
return persist;
}
public int getVersion() {
return version;
}
public int getUnknown() {
return unknown;
}
public static SoMessage read( DataInputStream in ) throws IOException, AmfException {
String name = in.readUTF();
int version = in.readInt();
boolean persist = (in.readInt() == 2);
int unknown = in.readInt();
ArrayList<SoEvent> events = new ArrayList<SoEvent>();
while( true ) {
int kind;
try {
kind = in.readByte() & 0xFF;
} catch(EOFException e) {
break;
}
int size = in.readInt();
SoEvent event = SoEvent.read(in, kind, size);
if (event != null) {
events.add(event);
}
}
return new SoMessage(name, version, persist, unknown, events);
}
public static void write(DataOutputStream out, SoMessage so) throws IOException {
out.writeUTF(so.getName());
out.writeInt(so.getVersion());
out.writeInt(so.isPersist()?2:0);
out.writeInt(so.getUnknown());
ArrayList<SoEvent> events = so.getEvents();
for(int i=0; i < events.size(); i++) {
SoEvent event = events.get(i);
out.writeByte(event.getKind());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
SoEvent.write(new DataOutputStream(bos), event);
byte[] data = bos.toByteArray();
out.writeInt(data.length);
out.write(data);
}
}
}
| Java |
package com.ams.event;
import com.ams.rtmp.message.RtmpMessage;
public class Event {
public final static int EVT_RTMP = 0;
public final static int EVT_TEXT = 1;
protected long timestamp = 0;
protected int type = 0;
protected Object event;
public Event(long timestamp, int type, Object event) {
this.timestamp = timestamp;
this.type = type;
this.event = event;
}
public Event(long timestamp, RtmpMessage message) {
this.timestamp = timestamp;
this.type = EVT_RTMP;
this.event = message;
}
public Event(long timestamp, String message) {
this.timestamp = timestamp;
this.type = EVT_TEXT;
this.event = message;
}
public long getTimestamp() {
return timestamp;
}
public Object getEvent() {
return event;
}
public int getType() {
return type;
}
}
| Java |
package com.ams.event;
import java.io.IOException;
public interface IEventPublisher {
public void publish(Event event) throws IOException;
public void addSubscriber(IEventSubscriber subscriber);
public void removeSubscriber(IEventSubscriber subscriber);
}
| Java |
package com.ams.event;
import com.ams.event.Event;
public interface IEventSubscriber {
public void messageNotify(Event event);
}
| Java |
/**
*
*/
package com.ams.http;
public class Cookie {
public String value="";
public long expires=0;
public String domain="";
public String path="";
public boolean secure=false;
public Cookie(String value, long expires, String domain, String path, boolean secure) {
this.value = value;
this.expires = expires;
this.domain = domain;
this.path = path;
this.secure = secure;
}
} | Java |
package com.ams.http;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import com.ams.util.Log;
import com.ams.util.ObjectCache;
public class DefaultServlet {
private class MapedFile {
public long size;
public String contentType;
public long lastModified;
public ByteBuffer data;
}
private ServletContext context = null;
private static ObjectCache<MapedFile> fileCache = new ObjectCache<MapedFile>();
public DefaultServlet(ServletContext context) {
this.context = context;
}
public void service(HttpRequest req, HttpResponse res) throws IOException {
String realPath = null;
try {
realPath = context.getRealPath(req.getLocation());
} catch (Exception e) {
e.printStackTrace();
Log.logger.warning(e.getMessage());
}
File file = new File(realPath);
if (!file.exists()) {
res.setHttpResult(HTTP.HTTP_NOT_FOUND);
res.flush();
} else if (!context.securize(file)) {
res.setHttpResult(HTTP.HTTP_FORBIDDEN);
res.flush();
} else {
if (!writeFile(req.getLocation(), file, res)) {
res.setHttpResult(HTTP.HTTP_INTERNAL_ERROR);
res.flush();
}
}
}
private boolean writeFile(String url, File file, HttpResponse res) {
boolean result = true;
try {
MapedFile mapedFile = (MapedFile) fileCache.get(url);
if (mapedFile == null) {
// open the resource stream
mapedFile = new MapedFile();
mapedFile.lastModified = file.lastModified();
mapedFile.size = file.length();
mapedFile.contentType = context.getMimeType(file.getName());
FileChannel fileChannel = new FileInputStream(file)
.getChannel();
mapedFile.data = fileChannel.map(FileChannel.MapMode.READ_ONLY,
0, fileChannel.size());
fileChannel.close();
fileCache.put(url, mapedFile, 60);
}
res.setContentLength(mapedFile.size);
res.setContentType(mapedFile.contentType);
res.setLastModified(mapedFile.lastModified);
res.setHttpResult(HTTP.HTTP_OK);
// read all bytes and send them
res.flush(mapedFile.data.slice());
} catch (IOException e) {
result = false;
Log.logger.warning(e.getMessage());
}
return result;
}
} | Java |
/**
*
*/
package com.ams.http;
import java.io.File;
public class HttpFileUpload {
public final static int RESULT_OK = 0;
public final static int RESULT_SIZE = 1;
public final static int RESULT_PARTIAL = 3;
public final static int RESULT_NOFILE = 4;
public final static long MAXSIZE_FILE_UPLOAD = 10 * 1024 * 1024; // max 10M
public String filename;
public File tempFile;
public int result;
public HttpFileUpload(String filename, File tempFile, int result) {
this.filename = filename;
this.tempFile = tempFile;
this.result = result;
}
} | Java |
package com.ams.http;
import java.io.File;
import java.io.IOException;
public final class ServletContext {
private final File contextRoot;
public ServletContext(String root) {
contextRoot = new File(root);
}
public String getMimeType(String file) {
int index = file.lastIndexOf('.');
return (index++ > 0)
? MimeTypes.getContentType(file.substring(index))
: "unkown/unkown";
}
public String getRealPath(String path) {
return new File(contextRoot, path).getAbsolutePath();
}
// security check
public boolean securize(File file) throws IOException {
if (file.getCanonicalPath().startsWith(contextRoot.getCanonicalPath())) {
return true;
}
return false;
}
}
| Java |
package com.ams.http;
public final class HTTP {
/** HTTP method */
public final static int HTTP_METHOD_GET = 0;
public final static int HTTP_METHOD_POST = 1;
public final static int HTTP_METHOD_HEAD = 2;
public final static int HTTP_METHOD_PUT = 3;
public final static int HTTP_METHOD_DELETE = 4;
public final static int HTTP_METHOD_TRACE = 5;
public final static int HTTP_METHOD_OPTIONS = 6;
/** HTTP Status-Code */
public final static int HTTP_OK = 200;
public final static int HTTP_MOVED_PERMANENTLY = 301;
public final static int HTTP_BAD_REQUEST = 400;
public final static int HTTP_UNAUTHORIZED = 401;
public final static int HTTP_FORBIDDEN = 403;
public final static int HTTP_NOT_FOUND = 404;
public final static int HTTP_BAD_METHOD = 405;
public final static int HTTP_LENGTH_REQUIRED = 411;
public final static int HTTP_INTERNAL_ERROR = 500;
/** HTTP header definitions */
public static final String HEADER_ACCEPT = "Accept";
public static final String HEADER_ACCEPT_CHARSET = "Accept-Charset";
public static final String HEADER_ACCEPT_LANGUAGE = "Accept-Language";
public static final String HEADER_AGE = "Age";
public static final String HEADER_ALLOW = "Allow";
public static final String HEADER_AUTHORIZATION = "Authorization";
public static final String HEADER_CACHE_CONTROL = "Cache-Control";
public static final String HEADER_CONN_DIRECTIVE = "Connection";
public static final String HEADER_CONTENT_LANGUAGE = "Content-Language";
public static final String HEADER_CONTENT_LENGTH = "Content-Length";
public static final String HEADER_CONTENT_LOCATION = "Content-Location";
public static final String HEADER_CONTENT_MD5 = "Content-MD5";
public static final String HEADER_CONTENT_RANGE = "Content-Range";
public static final String HEADER_CONTENT_TYPE = "Content-Type";
public static final String HEADER_DATE = "Date";
public static final String HEADER_EXPECT = "Expect";
public static final String HEADER_EXPIRES = "Expires";
public static final String HEADER_FROM = "From";
public static final String HEADER_HOST = "Host";
public static final String HEADER_IF_MODIFIED_SINCE = "If-Modified-Since";
public static final String HEADER_IF_UNMODIFIED_SINCE = "If-Unmodified-Since";
public static final String HEADER_LAST_MODIFIED = "Last-Modified";
public static final String HEADER_LOCATION = "Location";
public static final String HEADER_MAX_FORWARDS = "Max-Forwards";
public static final String HEADER_PRAGMA = "Pragma";
public static final String HEADER_RANGE = "Range";
public static final String HEADER_REFER = "Referer";
public static final String HEADER_REFER_AFTER = "Retry-After";
public static final String HEADER_SERVER = "Server";
public static final String HEADER_UPGRADE = "Upgrade";
public static final String HEADER_USER_AGENT = "User-Agent";
public static final String HEADER_VARY = "Vary";
public static final String HEADER_VIA = "Via";
public static final String HEADER_WWW_AUTHORIZATION = "WWW-Authenticate";
public static final String HEADER_CONTENT_DISPOSITION = "Content-Disposition";
public static final String HEADER_COOKIE = "Cookie";
public static final String HEADER_SET_COOKIE = "Set-Cookie";
public static final String HEADER_TRANSFER_ENCODING = "Transfer-Encoding";
public static final String HEADER_CONTENT_ENCODING = "Content-Encoding";
/** HTTP expectations */
public static final String EXPECT_CONTINUE = "100-Continue";
/** HTTP connection control */
public static final String CONN_CLOSE = "Close";
public static final String CONN_KEEP_ALIVE = "Keep-Alive";
/** Transfer encoding definitions */
public static final String CHUNK_CODING = "chunked";
public static final String IDENTITY_CODING = "identity";
/** Common charset definitions */
public static final String UTF_8 = "UTF-8";
public static final String UTF_16 = "UTF-16";
public static final String US_ASCII = "US-ASCII";
public static final String ASCII = "ASCII";
public static final String ISO_8859_1 = "ISO-8859-1";
/** Default charsets */
public static final String DEFAULT_CONTENT_CHARSET = ISO_8859_1;
public static final String DEFAULT_PROTOCOL_CHARSET = US_ASCII;
/** Content type definitions */
public final static String OCTET_STREAM_TYPE = "application/octet-stream";
public final static String PLAIN_TEXT_TYPE = "text/plain";
public final static String HTML_TEXT_TYPE = "html/text";
public final static String CHARSET_PARAM = "; charset=";
/** Default content type */
public final static String DEFAULT_CONTENT_TYPE = OCTET_STREAM_TYPE;
}
| Java |
package com.ams.http;
import java.io.*;
import java.net.URLEncoder;
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.*;
import com.ams.io.ByteBufferOutputStream;
import com.ams.server.ByteBufferFactory;
public class HttpResponse {
private ByteBufferOutputStream out;
private StringBuilder headerBuffer = new StringBuilder(1024);
private StringBuilder bodyBuffer = new StringBuilder();
private String resultHeader;
private LinkedHashMap<String, String> headers = new LinkedHashMap<String, String>();
private LinkedHashMap<String, Cookie> cookies = new LinkedHashMap<String, Cookie>();
private boolean headerWrote = false;
private static String NEWLINE = "\r\n";
private static SimpleDateFormat dateFormatGMT;
static {
dateFormatGMT = new SimpleDateFormat("d MMM yyyy HH:mm:ss 'GMT'");
dateFormatGMT.setTimeZone(TimeZone.getTimeZone("GMT"));
}
public HttpResponse(ByteBufferOutputStream out) {
this.out = out;
init();
}
public void clear() {
headerBuffer = new StringBuilder(1024);
bodyBuffer = new StringBuilder();
resultHeader = null;
headers.clear();
cookies.clear();
headerWrote = false;
init();
}
private void init() {
resultHeader = "HTTP/1.1 200 OK";
headers.put(HTTP.HEADER_DATE, dateFormatGMT.format(new Date()));
headers.put(HTTP.HEADER_SERVER, "annuus http server");
headers.put(HTTP.HEADER_CONTENT_TYPE, "text/html; charset=utf-8");
headers.put(HTTP.HEADER_CACHE_CONTROL,
"no-cache, no-store, must-revalidate, private");
headers.put(HTTP.HEADER_PRAGMA, "no-cache");
}
private void putHeader(String data) throws IOException {
headerBuffer.append(data);
}
private void putHeaderValue(String name, String value) throws IOException {
putHeader(name + ": " + value + NEWLINE);
}
public void setHttpResult(int code) {
StringBuilder message = new StringBuilder();
message.append("HTTP/1.1 " + code + " ");
switch (code) {
case HTTP.HTTP_OK:
message.append("OK");
break;
case HTTP.HTTP_BAD_REQUEST:
message.append("Bad Request");
break;
case HTTP.HTTP_NOT_FOUND:
message.append("Not Found");
break;
case HTTP.HTTP_BAD_METHOD:
message.append("Method Not Allowed");
break;
case HTTP.HTTP_LENGTH_REQUIRED:
message.append("Length Required");
break;
case HTTP.HTTP_INTERNAL_ERROR:
default:
message.append("Internal Server Error");
break;
}
this.resultHeader = message.toString();
}
public void setContentLength(long length) {
setHeader(HTTP.HEADER_CONTENT_LENGTH, Long.toString(length));
}
public void setContentType(String contentType) {
setHeader(HTTP.HEADER_CONTENT_TYPE, contentType);
}
public void setLastModified(long lastModified) {
setHeader(HTTP.HEADER_LAST_MODIFIED,
dateFormatGMT.format(new Date(lastModified)));
}
public void setKeepAlive(boolean keepAlive) {
if (keepAlive) {
setHeader(HTTP.HEADER_CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE);
} else {
setHeader(HTTP.HEADER_CONN_DIRECTIVE, HTTP.CONN_CLOSE);
}
}
public void setHeader(String name, String value) {
if (headers.containsKey(name)) {
headers.remove(name);
}
headers.put(name, value);
}
public void setCookie(String name, Cookie cookie) {
if (cookies.containsKey(name)) {
cookies.remove(name);
}
cookies.put(name, cookie);
}
public void print(String data) throws IOException {
bodyBuffer.append(data);
}
public void println(String data) throws IOException {
print(data + NEWLINE);
}
public ByteBuffer writeHeader() throws IOException {
if (headerWrote) {
return null;
}
headerWrote = true;
// write the headers
putHeader(resultHeader + NEWLINE);
// write all headers
Iterator<String> it = this.headers.keySet().iterator();
while (it.hasNext()) {
String name = it.next();
String value = headers.get(name);
putHeaderValue(name, value);
}
// write all cookies
it = this.cookies.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
Cookie cookie = cookies.get(key);
StringBuilder cookieString = new StringBuilder();
cookieString.append(key + "="
+ URLEncoder.encode((String) cookie.value, "UTF-8"));
if (cookie.expires != 0) {
Date d = new Date(cookie.expires);
cookieString.append("; expires=" + dateFormatGMT.format(d));
}
if (!cookie.path.equals("")) {
cookieString.append("; path=" + cookie.path);
}
if (!cookie.domain.equals("")) {
cookieString.append("; domain=" + cookie.domain);
}
if (cookie.secure) {
cookieString.append("; secure");
}
putHeaderValue(HTTP.HEADER_SET_COOKIE, cookieString.toString());
}
putHeader(NEWLINE);
// write header to socket channel
byte[] data = headerBuffer.toString().getBytes("UTF-8");
ByteBuffer buffer = ByteBufferFactory.allocate(data.length);
buffer.put(data);
buffer.flip();
return buffer;
}
public void flush() throws IOException {
byte[] body = bodyBuffer.toString().getBytes("UTF-8");
// write header
setHeader(HTTP.HEADER_CONTENT_LENGTH, Long.toString(body.length));
ByteBuffer headerBuffer = writeHeader();
ByteBuffer bodyBuffer = ByteBufferFactory.allocate(body.length);
bodyBuffer.put(body);
bodyBuffer.flip();
ByteBuffer[] buf = { headerBuffer, bodyBuffer };
// write to socket
out.writeByteBuffer(buf);
}
public void flush(ByteBuffer data) throws IOException {
// write header
ByteBuffer headerBuffer = writeHeader();
// write body
ByteBuffer[] buf = { headerBuffer, data };
// write to socket
out.writeByteBuffer(buf);
}
} | Java |
package com.ams.http;
import java.util.HashMap;
public class MimeTypes {
public static HashMap<String, String> mimeMap = new HashMap<String, String>();
static {
mimeMap.put("", "content/unknown");
mimeMap.put("uu", "application/octet-stream");
mimeMap.put("exe", "application/octet-stream");
mimeMap.put("ps", "application/postscript");
mimeMap.put("zip", "application/zip");
mimeMap.put("sh", "application/x-shar");
mimeMap.put("tar", "application/x-tar");
mimeMap.put("snd", "audio/basic");
mimeMap.put("au", "audio/basic");
mimeMap.put("avi", "video/avi");
mimeMap.put("wav", "audio/x-wav");
mimeMap.put("gif", "image/gif");
mimeMap.put("jpe", "image/jpeg");
mimeMap.put("jpg", "image/jpeg");
mimeMap.put("jpeg", "image/jpeg");
mimeMap.put("png", "image/png");
mimeMap.put("bmp", "image/bmp");
mimeMap.put("htm", "text/html");
mimeMap.put("html", "text/html");
mimeMap.put("text", "text/plain");
mimeMap.put("c", "text/plain");
mimeMap.put("cc", "text/plain");
mimeMap.put("c++", "text/plain");
mimeMap.put("h", "text/plain");
mimeMap.put("pl", "text/plain");
mimeMap.put("txt", "text/plain");
mimeMap.put("java", "text/plain");
mimeMap.put("js", "application/x-javascript");
mimeMap.put("css", "text/css");
mimeMap.put("xml", "text/xml");
};
public static String getContentType(String extension) {
String contentType = (String) mimeMap.get(extension);
if (contentType == null)
contentType = "unkown/unkown";
return contentType;
}
} | Java |
package com.ams.http;
import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.*;
import com.ams.io.ByteBufferInputStream;
public class HttpRequest {
private ByteBufferInputStream in = null;
private int method;
private String location;
private String rawGet;
private String rawPost;
private HashMap<String, String> headers = new HashMap<String, String>();
private HashMap<String, String> cookies = new HashMap<String, String>();
private HashMap<String, String> getValues = new HashMap<String, String>();
private HashMap<String, String> postValues = new HashMap<String, String>();
private HashMap<String, HttpFileUpload> postFiles = new HashMap<String, HttpFileUpload>();
private static SimpleDateFormat dateFormatGMT;
static {
dateFormatGMT = new SimpleDateFormat("d MMM yyyy HH:mm:ss 'GMT'");
dateFormatGMT.setTimeZone(TimeZone.getTimeZone("GMT"));
}
public HttpRequest(ByteBufferInputStream in) throws IOException {
super();
this.in = in;
}
public void clear() {
method = -1;
location = null;
rawGet = null;
rawPost = null;
headers.clear();
cookies.clear();
getValues.clear();
postValues.clear();
postFiles.clear();
}
public void parse() throws IOException {
if (in == null) {
throw new IOException("no input stream");
}
if (HTTP.HTTP_OK != parseHttp()) {
throw new IOException("bad http");
}
}
private void parseRawString(String options, HashMap<String, String> output,
String seperator) {
String[] tokens = options.split(seperator);
for (int i = 0; i < tokens.length; i++) {
String[] items = tokens[i].split("=");
String key = "";
String value = "";
key = items[0];
if (items.length > 1) {
try {
value = URLDecoder.decode(items[1], "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
output.put(key, value);
}
}
private int parseRequestLine() throws IOException {
// first read and parse the first line
String line = in.readLine();
// parse the request line
String[] tokens = line.split(" ");
if (tokens.length < 2) {
return HTTP.HTTP_BAD_REQUEST;
}
// get the method
String token = tokens[0].toUpperCase();
if ("GET".equals(token)) {
method = HTTP.HTTP_METHOD_GET;
} else if ("POST".equals(token)) {
method = HTTP.HTTP_METHOD_POST;
} else if ("HEAD".equals(token)) {
method = HTTP.HTTP_METHOD_HEAD;
} else {
return HTTP.HTTP_BAD_METHOD;
}
// get the raw url
String rawUrl = tokens[1];
// parse the get methods
// remove anchor tag
location = (rawUrl.indexOf('#') > 0) ? rawUrl.split("#")[0] : rawUrl;
// get 'GET' part
rawGet = "";
if (location.indexOf('?') > 0) {
tokens = location.split("\\?");
location = tokens[0];
rawGet = tokens[1];
parseRawString(rawGet, getValues, "&");
}
// return ok
return HTTP.HTTP_OK;
}
private int parseHeader() throws IOException {
String line = null;
// parse the header
while (((line = in.readLine()) != null) && !line.equals("")) {
String[] tokens = line.split(": ");
headers.put(tokens[0].toLowerCase(), tokens[1].toLowerCase());
}
// get cookies
if (headers.containsKey("cookie")) {
parseRawString((String) headers.get("cookie"), cookies, ";");
}
return HTTP.HTTP_OK;
}
private int parseMessageBody() throws IOException {
// if method is post, parse the post values
if (method == HTTP.HTTP_METHOD_POST) {
String contentType = (String) headers.get("content-type");
// if multi-form part
if ((contentType != null)
&& contentType.startsWith("multipart/form-data")) {
rawPost = "";
int result = parseMultipartBody();
if (result != HTTP.HTTP_OK) {
return result;
}
} else {
if (!headers.containsKey("content-length")) {
return HTTP.HTTP_LENGTH_REQUIRED;
}
int len = Integer.parseInt(
(String) headers.get("content-length"), 10);
byte[] buf = new byte[len];
in.read(buf, 0, len);
rawPost = new String(buf, "UTF-8");
parseRawString(rawPost, postValues, "&");
}
} // handle POST end
return HTTP.HTTP_OK;
}
private int parseMultipartBody() throws IOException {
String contentType = (String) headers.get("content-type");
String boundary = "--"
+ contentType.replaceAll("^.*boundary=\"?([^\";,]+)\"?.*$",
"$1");
int blength = boundary.length();
if ((blength > 80) || (blength < 2)) {
return HTTP.HTTP_BAD_REQUEST;
}
boolean done = false;
String line = in.readLine();
while (!done && (line != null)) {
if (boundary.equals(line)) {
line = in.readLine();
}
// parse the header
HashMap<String, String> item = new HashMap<String, String>();
while (!line.equals("")) {
String[] tokens = line.split(": ");
item.put(tokens[0].toLowerCase(), tokens[1].toLowerCase());
line = in.readLine();
}
// read body
String disposition = (String) item.get("content-disposition");
String name = disposition.replaceAll("^.* name=\"?([^\";]*)\"?.*$",
"$1");
String filename = disposition.replaceAll(
"^.* filename=\"?([^\";]*)\"?.*$", "$1");
if (disposition.equals(filename)) {
filename = null;
}
// normal field
if (filename == null) {
String value = "";
// shouldn't be used more than once.
while (((line = in.readLine()) != null)
&& !line.startsWith(boundary)) {
value += line;
}
// read end
if ((boundary + "--").equals(line)) {
done = true;
}
// save post field
postValues.put(name, value);
// make rawPost
if (rawPost.length() > 0) {
rawPost += "&";
}
try {
rawPost += name + "=" + URLEncoder.encode(value, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else { // read file data
// should we create a temporary file ?
File tempfile = File.createTempFile("httpd", ".file");
FileOutputStream out = new FileOutputStream(tempfile);
// read the data until we much the content boundry
byte[] buf = new byte[boundary.length() + 2];
byte[] bound = ("\r\n" + boundary).getBytes();
int len = in.read(buf, 0, buf.length);
if (len < buf.length) {
return HTTP.HTTP_BAD_REQUEST;
}
while (!Arrays.equals(buf, bound)) { // check boundry
out.write(buf[0]); // write a byte to file
// shift buffer to left
System.arraycopy(buf, 1, buf, 0, buf.length - 1);
// read a byte
if (0 > in.read(buf, buf.length - 1, 1)) {
return HTTP.HTTP_BAD_REQUEST;
}
}
// close tempofle
if (tempfile != null) {
out.close();
}
// result of reading file
int fileResult = HttpFileUpload.RESULT_NOFILE;
if (tempfile.length() > HttpFileUpload.MAXSIZE_FILE_UPLOAD) {
fileResult = HttpFileUpload.RESULT_SIZE;
} else if (tempfile.length() > 0) {
fileResult = HttpFileUpload.RESULT_OK;
}
postFiles.put(name, new HttpFileUpload(filename, tempfile,
fileResult));
// read the newline and check the end
int ch = in.read();
if (ch != '\r') {
if ((ch == '-') && (in.read() == '-')) { // is "--"
done = true;
}
} else { // '\n'
ch = in.read();
}
if (ch == -1) { // eof
done = true;
}
line = in.readLine();
} // if normal field or file
} // while readLine
// return ok
return HTTP.HTTP_OK;
}
private int parseHttp() throws IOException {
// parse request line
int result = parseRequestLine();
if (result != HTTP.HTTP_OK) {
return result;
}
// parse eader part
result = parseHeader();
if (result != HTTP.HTTP_OK) {
return result;
}
// parse body part
result = parseMessageBody();
if (result != HTTP.HTTP_OK) {
return result;
}
return HTTP.HTTP_OK;
}
public int getMethod() {
return method;
}
public boolean isKeepAlive() {
String connection = getHeader("connection");
if (connection != null) {
return connection.charAt(0) == 'k'; // keep-alive or close
}
return false;
}
public String getHeader(String key) {
return headers.get(key);
}
public String getCookie(String key) {
return cookies.get(key);
}
public String getGet(String key) {
return getValues.get(key);
}
public String getPost(String key) {
return postValues.get(key);
}
public String getParameter(String key) {
String value = getGet(key);
if (value == null) {
value = getPost(key);
}
if (value == null) {
value = getCookie(key);
}
return value;
}
public String getLocation() {
return location;
}
public HashMap<String, String> getCookies() {
return cookies;
}
public HashMap<String, String> getGetValues() {
return getValues;
}
public HashMap<String, String> getHeaders() {
return headers;
}
public HashMap<String, HttpFileUpload> getPostFiles() {
return postFiles;
}
public HashMap<String, String> getPostValues() {
return postValues;
}
public String getRawGet() {
return rawGet;
}
public String getRawPost() {
return rawPost;
}
}
| Java |
package com.ams.amf;
import java.io.DataInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.io.IOException;
public class Amf0Deserializer {
protected ArrayList<AmfValue> storedObjects = new ArrayList<AmfValue>();
protected ArrayList<AmfValue> storedStrings = new ArrayList<AmfValue>();
protected DataInputStream in;
public Amf0Deserializer(DataInputStream in) {
this.in = in;
}
private String readLongString() throws IOException {
int len = in.readInt(); //32bit read
byte[] buf = new byte[len];
in.read(buf, 0, len);
return new String(buf, "UTF-8");
}
private AmfValue readByType(int type) throws IOException, AmfException {
AmfValue amfValue = null;
switch(type) {
case 0x00:
//This specifies the data in the AMF packet is a numeric value.
//All numeric values in Flash are 64 bit, big-endian.
amfValue = new AmfValue(in.readDouble());
break;
case 0x01:
//This specifies the data in the AMF packet is a boolean value.
amfValue = new AmfValue(in.readBoolean());
break;
case 0x02:
//This specifies the data in the AMF packet is an ASCII string.
amfValue = new AmfValue(in.readUTF());
break;
case 0x04:
//This specifies the data in the AMF packet is a Flash movie.
break;
case 0x05:
//This specifies the data in the AMF packet is a NULL value.
amfValue = new AmfNull();
break;
case 0x06:
//This specifies the data in the AMF packet is a undefined.
amfValue = new AmfValue();
break;
case 0x07:
//This specifies the data in the AMF packet is a reference.
break;
case 0x03:
//This specifies the data in the AMF packet is a Flash object.
case 0x08:
//This specifies the data in the AMF packet is a ECMA array.
HashMap<String, AmfValue> hash = new HashMap<String, AmfValue>();
boolean ismixed = (type == 0x08);
int size = -1;
if(ismixed) {
size = in.readInt(); // 32bit read
}
while(true) {
String key = in.readUTF();
int k = in.readByte() & 0xFF;
if (k == 0x09) break; // end of Object
hash.put(key, readByType(k));
}
amfValue = new AmfValue(hash);
break;
case 0x09:
//This specifies the data in the AMF packet is the end of an object definition.
break;
case 0x0A:
//This specifies the data in the AMF packet is a Strict array.
ArrayList<AmfValue> array = new ArrayList<AmfValue>();
int len = in.readInt();
for(int i = 0; i < len; i++) {
int k = in.readByte() & 0xFF;
array.add(readByType(k));
}
amfValue = new AmfValue(array);
break;
case 0x0B:
//This specifies the data in the AMF packet is a date.
double time_ms = in.readDouble();
int tz_min = in.readInt(); //16bit
amfValue = new AmfValue(new Date((long)(time_ms + tz_min * 60 * 1000.0)));
break;
case 0x0C:
//This specifies the data in the AMF packet is a multi-byte string.
amfValue = new AmfValue(readLongString()); //32bit
case 0x0D:
//This specifies the data in the AMF packet is a an unsupported feature.
break;
case 0x0E:
//This specifies the data in the AMF packet is a record set.
break;
case 0x0F:
//This specifies the data in the AMF packet is a XML object.
amfValue = new AmfXml(readLongString()); //32bit
break;
case 0x10:
//This specifies the data in the AMF packet is a typed object.
case 0x11:
//the AMF 0 format was extended to allow an AMF 0 encoding context to be switched to AMF 3.
throw new AmfSwitchToAmf3Exception("Switch To AMF3");
default:
throw new AmfException("Unknown AMF0: " + type);
}
return amfValue;
}
public AmfValue read() throws IOException, AmfException {
int type = in.readByte() & 0xFF;
return readByType(type);
}
}
| Java |
package com.ams.amf;
public class AmfSwitchToAmf3Exception extends AmfException {
private static final long serialVersionUID = 1L;
public AmfSwitchToAmf3Exception() {
super();
}
public AmfSwitchToAmf3Exception(String arg0) {
super(arg0);
}
}
| Java |
package com.ams.amf;
import java.io.DataOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.io.IOException;
public class Amf0Serializer {
protected DataOutputStream out;
public Amf0Serializer(DataOutputStream out) {
this.out = out;
}
private void writeLongString(String s) throws IOException {
byte[] b = s.getBytes("UTF-8");
out.writeInt(b.length);
out.write(b);
}
public void write(AmfValue amfValue) throws IOException {
switch(amfValue.getKind()) {
case AmfValue.AMF_INT:
case AmfValue.AMF_NUMBER:
out.writeByte(0x00);
out.writeDouble(amfValue.number());
break;
case AmfValue.AMF_BOOL:
out.writeByte(0x01);
out.writeBoolean(amfValue.bool());
break;
case AmfValue.AMF_STRING:
String s = amfValue.string();
if( s.length() <= 0xFFFF ) {
out.writeByte(0x02);
out.writeUTF(s);
} else {
out.writeByte(0x0C);
writeLongString(s);
}
break;
case AmfValue.AMF_OBJECT:
out.writeByte(0x03); // only support Flash object
HashMap<String, AmfValue> v = amfValue.object();
for(String key : v.keySet()) {
out.writeUTF(key);
write((AmfValue) v.get(key));
}
//end of Object
out.writeByte(0);
out.writeByte(0);
out.writeByte(0x09);
break;
case AmfValue.AMF_ARRAY:
out.writeByte(0x0A);
ArrayList<AmfValue> array = amfValue.array();
int len = array.size();
out.writeInt(len);
for(int i = 0; i < len; i++) {
write((AmfValue) array.get(i));
}
break;
case AmfValue.AMF_DATE:
Date d = amfValue.date();
out.writeDouble(d.getTime());
out.writeShort(0); // loose TZ
break;
case AmfValue.AMF_XML:
String xml = amfValue.xml();
out.writeByte(0x0F);
writeLongString(xml);
break;
case AmfValue.AMF_NULL:
out.writeByte(0x05);
break;
case AmfValue.AMF_UNDEFINED:
out.writeByte(0x06);
break;
}
}
}
| Java |
package com.ams.amf;
public class AmfXml extends AmfValue {
public AmfXml(String value) {
this.kind = AMF_XML;
this.value = value;
}
}
| Java |
package com.ams.amf;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
public class AmfValue {
public final static int AMF_INT = 1;
public final static int AMF_NUMBER = 2;
public final static int AMF_BOOL = 3;
public final static int AMF_STRING = 4;
public final static int AMF_OBJECT = 5;
public final static int AMF_ARRAY = 6;
public final static int AMF_DATE = 7;
public final static int AMF_XML = 8;
public final static int AMF_NULL = 9;
public final static int AMF_UNDEFINED = 0;
protected int kind = 0;
protected Object value;
public AmfValue() {
this.kind = AMF_UNDEFINED;
}
public AmfValue(int value) {
this.kind = AMF_INT;
this.value = value;
}
public AmfValue(double value) {
this.kind = AMF_NUMBER;
this.value = value;
}
public AmfValue(boolean value) {
this.kind = AMF_BOOL;
this.value = value;
}
public AmfValue(String value) {
this.kind = AMF_STRING;
this.value = value;
}
public AmfValue(HashMap<String, AmfValue> value) {
this.kind = AMF_OBJECT;
this.value = value;
}
public AmfValue(ArrayList<AmfValue> value) {
this.kind = AMF_ARRAY;
this.value = value;
}
public AmfValue(Date value) {
this.kind = AMF_DATE;
this.value = value;
}
public int getKind() {
return kind;
}
public int integer() {
if( value == null ) {
throw new NullPointerException("parameter is null");
}
if( kind != AmfValue.AMF_INT && kind != AmfValue.AMF_NUMBER ) {
throw new IllegalArgumentException("parameter is not a Amf Integer or Amf Number");
}
return ((Number)value).intValue();
}
public double number() {
if( value == null ) {
throw new NullPointerException("parameter is null");
}
if( kind != AmfValue.AMF_INT && kind != AmfValue.AMF_NUMBER ) {
throw new IllegalArgumentException("parameter is not a Amf Integer or Amf Number");
}
return ((Number)value).doubleValue();
}
public boolean bool() {
if( value == null ) {
throw new NullPointerException("parameter is null");
}
if( kind != AmfValue.AMF_BOOL ) {
throw new IllegalArgumentException("parameter is not a Amf Bool");
}
return (Boolean)value;
}
public String string() {
if( value == null ) {
throw new NullPointerException("parameter is null");
}
if( kind != AmfValue.AMF_STRING ) {
throw new IllegalArgumentException("parameter is not a Amf String");
}
return (String)value;
}
@SuppressWarnings("unchecked")
public ArrayList<AmfValue> array() {
if( value == null ) {
throw new NullPointerException("parameter is null");
}
if( kind != AmfValue.AMF_ARRAY ) {
throw new IllegalArgumentException("parameter is not a Amf Array");
}
return (ArrayList<AmfValue>)value;
}
@SuppressWarnings("unchecked")
public HashMap<String, AmfValue> object() {
if( value == null ) {
throw new NullPointerException("parameter is null");
}
if( kind != AmfValue.AMF_ARRAY && kind != AmfValue.AMF_OBJECT) {
throw new IllegalArgumentException("parameter is not a Amf Object");
}
return (HashMap<String, AmfValue>)value;
}
public Date date() {
if( value == null ) {
throw new NullPointerException("parameter is null");
}
if( kind != AmfValue.AMF_DATE ) {
throw new IllegalArgumentException("parameter is not a Amf Date");
}
return (Date)value;
}
public String xml() {
if( value == null ) {
throw new NullPointerException("parameter is null");
}
if( kind != AmfValue.AMF_XML ) {
throw new IllegalArgumentException("parameter is not a Amf Xml");
}
return (String)value;
}
public boolean isNull() {
return kind == AmfValue.AMF_NULL;
}
public boolean isUndefined() {
return kind == AmfValue.AMF_UNDEFINED;
}
public String toString() {
String result;
boolean first;
switch(kind) {
case AmfValue.AMF_INT:
return ((Integer)value).toString();
case AmfValue.AMF_NUMBER:
return ((Number)value).toString();
case AmfValue.AMF_BOOL:
return ((Boolean)value).toString();
case AmfValue.AMF_STRING:
return "'" + (String)value + "'";
case AmfValue.AMF_OBJECT:
HashMap<String, AmfValue> v = object();
result = "{";
first = true;
for(String key : v.keySet()) {
result += (first ? " " : ", ") + key + " => " + v.get(key).toString();
first = false;
}
result += "}";
return result;
case AmfValue.AMF_ARRAY:
ArrayList<AmfValue> array = array();
result = "[";
first = true;
int len = array.size();
for(int i = 0; i < len; i++) {
result += (first ? " " : ", ") + array.get(i).toString();
first = false;
}
result += "]";
return result;
case AmfValue.AMF_DATE:
return ((Date)value).toString();
case AmfValue.AMF_XML:
return (String)value;
case AmfValue.AMF_NULL:
return "null";
case AmfValue.AMF_UNDEFINED:
return "undefined";
}
return "";
}
}
| Java |
package com.ams.amf;
import java.io.DataOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.io.IOException;
public class Amf3Serializer {
protected ArrayList<String> stringRefTable = new ArrayList<String>();
protected ArrayList<AmfValue> objectRefTable = new ArrayList<AmfValue>();
protected DataOutputStream out;
public Amf3Serializer(DataOutputStream out) {
this.out = out;
}
private void writeAmf3Int(int value) throws IOException {
//Sign contraction - the high order bit of the resulting value must match every bit removed from the number
//Clear 3 bits
value &= 0x1fffffff;
if(value < 0x80) {
out.writeByte(value);
} else if(value < 0x4000) {
out.writeByte(value >> 7 & 0x7f | 0x80);
out.writeByte(value & 0x7f);
} else if(value < 0x200000) {
out.writeByte(value >> 14 & 0x7f | 0x80);
out.writeByte(value >> 7 & 0x7f | 0x80);
out.writeByte(value & 0x7f);
} else {
out.writeByte(value >> 22 & 0x7f | 0x80);
out.writeByte(value >> 15 & 0x7f | 0x80);
out.writeByte(value >> 8 & 0x7f | 0x80);
out.writeByte(value & 0xff);
}
}
private void writeAmf3RefInt(int value) throws IOException {
writeAmf3Int(value << 1); // low bit is 0
}
private void writeAmf3ValueInt(int value) throws IOException {
writeAmf3Int(value << 1 + 1); // low bit is 1
}
private void writeAmf3EmptyString() throws IOException {
out.writeByte(0x01);
}
private void writeAmf3String(String s) throws IOException {
if( s.length() == 0) {
//Write 0x01 to specify the empty string
writeAmf3EmptyString();
} else {
for(int i = 0; i < stringRefTable.size(); i++) {
if (s.equals(stringRefTable.get(i))) {
writeAmf3RefInt(i);
return;
}
}
byte[] b = s.getBytes("UTF-8");
writeAmf3ValueInt(b.length);
out.write(b);
stringRefTable.add(s);
}
}
/*
private void writeAmf3Object(AmfValue amfValue) throws IOException {
for(int i = 0; i < objectRefTable.size(); i++) {
if (amfValue.equals(objectRefTable.get(i))) {
writeAmf3RefInt(i);
return;
}
}
out.writeByte(0x0B); //dynamic object
writeAmf3EmptyString(); //anonymous class
HashMap<String, AmfValue> obj = amfValue.object();
for(String key : obj.keySet()) {
writeAmf3String(key);
write((AmfValue) obj.get(key));
}
//end of Object
writeAmf3EmptyString();
objectRefTable.add(amfValue);
}
*/
private void writeAmf3Object(AmfValue amfValue) throws IOException {
for(int i = 0; i < objectRefTable.size(); i++) {
if (amfValue.equals(objectRefTable.get(i))) {
writeAmf3RefInt(i);
return;
}
}
writeAmf3ValueInt(0);
HashMap<String, AmfValue> obj = amfValue.object();
for(String key : obj.keySet()) {
writeAmf3String(key);
write((AmfValue) obj.get(key));
}
//end of Object
writeAmf3EmptyString();
objectRefTable.add(amfValue);
}
private void writeAmf3Array(AmfValue amfValue) throws IOException {
for(int i = 0; i < objectRefTable.size(); i++) {
if (amfValue.equals(objectRefTable.get(i))) {
writeAmf3RefInt(i);
return;
}
}
ArrayList<AmfValue> array = amfValue.array();
int len = array.size();
writeAmf3ValueInt(len);
writeAmf3EmptyString();
for(int i = 0; i < len; i++) {
write((AmfValue) array.get(i));
}
objectRefTable.add(amfValue);
}
public void write(AmfValue amfValue) throws IOException {
switch(amfValue.getKind()) {
case AmfValue.AMF_INT:
int v = amfValue.integer();
if (v >= -0x10000000 && v <= 0xFFFFFFF) { //check valid range for 29bits
out.writeByte(0x04);
writeAmf3Int(v);
} else {
//overflow condition would occur upon int conversion
out.writeByte(0x05);
out.writeDouble(v);
}
break;
case AmfValue.AMF_NUMBER:
out.writeByte(0x05);
out.writeDouble(amfValue.number());
break;
case AmfValue.AMF_BOOL:
out.writeByte(amfValue.bool() ? 0x02 : 0x03);
break;
case AmfValue.AMF_STRING:
out.writeByte(0x06);
writeAmf3String(amfValue.string());
break;
case AmfValue.AMF_OBJECT:
//out.writeByte(0x0A);
System.out.println("amf3 obj");
out.writeByte(0x09);
writeAmf3Object(amfValue);
break;
case AmfValue.AMF_ARRAY:
out.writeByte(0x09);
writeAmf3Array(amfValue);
break;
case AmfValue.AMF_DATE:
out.writeByte(0x08);
writeAmf3Int(0x01);
Date d = amfValue.date();
out.writeDouble(d.getTime());
break;
case AmfValue.AMF_XML:
out.writeByte(0x07);
writeAmf3String(amfValue.string());
break;
case AmfValue.AMF_NULL:
out.writeByte(0x01);
break;
case AmfValue.AMF_UNDEFINED:
out.writeByte(0x00);
break;
}
}
}
| Java |
package com.ams.amf;
public class AmfNull extends AmfValue {
public AmfNull() {
this.kind = AMF_NULL;
this.value = null;
}
}
| Java |
package com.ams.amf;
public class AmfException extends Exception {
private static final long serialVersionUID = 1L;
public AmfException() {
super();
}
public AmfException(String arg0) {
super(arg0);
}
}
| Java |
package com.ams.amf;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
public class Amf3Deserializer {
protected ArrayList<String> stringRefTable = new ArrayList<String>();
protected ArrayList<AmfValue> objectRefTable = new ArrayList<AmfValue>();
protected DataInputStream in;
public Amf3Deserializer(DataInputStream in) {
this.in = in;
}
private int readAmf3Int() throws IOException {
byte b1 = in.readByte();
if (b1 >= 0 && b1 <= 0x7f) {
return b1;
}
byte b2 = in.readByte();
if (b2 >= 0 && b2 <= 0x7f) {
return (b1 & 0x7f) << 7 | b2;
}
byte b3 = in.readByte();
if (b3 >= 0 && b3 <= 0x7f) {
return (b1 & 0x7f) << 14 | (b2 & 0x7f) << 7 | b3 ;
}
byte b4 = in.readByte();
return (b1 & 0x7f) << 22 | (b2 & 0x7f) << 15 | (b3 & 0x7f) << 8 | b4 ;
}
private String readAmf3String() throws IOException {
int v = readAmf3Int();
if (v == 1) {
return "";
}
if ((v & 0x01) == 0) {
return stringRefTable.get(v >> 1);
}
byte[] b = new byte[v >> 1];
in.read(b);
String str = new String(b, "UTF-8");
stringRefTable.add(str);
return str;
}
private AmfValue readAmf3Array() throws IOException, AmfException {
int v = readAmf3Int();
if ((v & 0x01) == 0) { //ref
return objectRefTable.get(v >> 1);
}
int len = v >> 1;
String s = readAmf3String();
if (s.equals("")) { //Strict Array
ArrayList<AmfValue> array = new ArrayList<AmfValue>();
for(int i = 0; i < len; i++) {
int k = in.readByte() & 0xFF;
array.add(readByType(k));
}
AmfValue obj = new AmfValue(array);
objectRefTable.add(obj);
return obj;
} else { //assoc Array
HashMap<String, AmfValue> hash = new HashMap<String, AmfValue>();
String key = s;
while(true) {
int k = in.readByte() & 0xFF;
if (k == 0x01) break; // end of Object
hash.put(key, readByType(k));
key = readAmf3String();
}
AmfValue obj = new AmfValue(hash);
objectRefTable.add(obj);
return obj;
}
}
private AmfValue readAmf3Object() throws IOException, AmfException {
int v = readAmf3Int();
if ((v & 0x01) == 0) { //ref
return objectRefTable.get(v >> 1);
}
readAmf3String(); //class name
HashMap<String, AmfValue> hash = new HashMap<String, AmfValue>();
while(true) {
String key = readAmf3String();
int k = in.readByte() & 0xFF;
if (k == 0x01) break; // end of Object
hash.put(key, readByType(k));
}
AmfValue obj = new AmfValue(hash);
objectRefTable.add(obj);
return obj;
}
private AmfValue readByType(int type) throws IOException, AmfException {
AmfValue amfValue = null;
System.out.println("type:"+type);
switch(type) {
case 0x00:
//This specifies the data in the AMF packet is a undefined.
amfValue = new AmfValue();
break;
case 0x01:
//This specifies the data in the AMF packet is a NULL value.
amfValue = new AmfNull();
break;
case 0x02:
//This specifies the data in the AMF packet is a false boolean value.
amfValue = new AmfValue(false);
break;
case 0x03:
//This specifies the data in the AMF packet is a true boolean value.
amfValue = new AmfValue(true);
break;
case 0x04:
//This specifies the data in the AMF packet is a integer value.
amfValue = new AmfValue(readAmf3Int());
break;
case 0x05:
//This specifies the data in the AMF packet is a double value.
amfValue = new AmfValue(in.readDouble());
break;
case 0x06:
//This specifies the data in the AMF packet is a string value.
amfValue = new AmfValue(readAmf3String());
break;
case 0x07:
//This specifies the data in the AMF packet is a xml doc value.
// TODO
break;
case 0x08:
//This specifies the data in the AMF packet is a date value.
// TODO
break;
case 0x09:
//This specifies the data in the AMF packet is a array value.
amfValue = readAmf3Array();
break;
case 0x0A:
//This specifies the data in the AMF packet is a object value.
amfValue = readAmf3Object();
break;
case 0x0B:
//This specifies the data in the AMF packet is a xml value.
// TODO
break;
case 0x0C:
//This specifies the data in the AMF packet is a byte array value.
// TODO
break;
default:
throw new AmfException("Unknown AMF3: " + type);
}
return amfValue;
}
public AmfValue read() throws IOException, AmfException {
int type = in.readByte() & 0xFF;
return readByType(type);
}
}
| Java |
package com.ams.server;
import java.io.EOFException;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import com.ams.util.ByteBufferHelper;
public class SocketConnector extends Connector {
private static final int MIN_READ_BUFFER_SIZE = 256;
private static final int MAX_READ_BUFFER_SIZE = 64*1024;
private SocketChannel channel = null;
private ByteBuffer readBuffer = null;
private boolean connectSleeping = false;
public SocketConnector() {
super();
}
public SocketConnector(SocketChannel channel) {
super();
this.channel = channel;
}
public void connect(String host, int port) throws IOException {
if (channel == null || !channel.isOpen()) {
channel = SocketChannel.open();
channel.configureBlocking(false);
}
ConnectionListner listener = new ConnectionListner() {
public void connectionEstablished(Connector conn) {
connectSleeping = false;
synchronized(conn) {
conn.notifyAll();
}
}
public void connectionClosed(Connector conn) {
}
};
addListner(listener);
getDispatcher().addChannelToRegister(new ChannelInterestOps(channel,
SelectionKey.OP_CONNECT, this));
try {
synchronized (this) {
channel.connect(new InetSocketAddress(host, port));
connectSleeping = true;
wait(DEFAULT_TIMEOUT_MS);
}
} catch (InterruptedException e) {
connectSleeping = false;
throw new IOException("connect interrupted");
} finally {
removeListner(listener);
}
if (connectSleeping) {
throw new IOException("connect time out");
}
}
public void finishConnect(SelectionKey key) throws IOException {
if (channel.isConnectionPending()) {
channel.finishConnect();
open();
key.interestOps(SelectionKey.OP_READ);
}
}
public void readChannel(SelectionKey key) throws IOException {
if (readBuffer == null || readBuffer.remaining() < MIN_READ_BUFFER_SIZE ) {
readBuffer = ByteBufferFactory.allocate(MAX_READ_BUFFER_SIZE);
}
long readBytes = channel.read(readBuffer);
if (readBytes > 0) {
ByteBuffer slicedBuffer = readBuffer.slice();
readBuffer.flip();
offerReadBuffer(new ByteBuffer[]{readBuffer});
readBuffer = slicedBuffer;
if (isClosed()) {
open();
}
} else if (readBytes == -1) {
close();
key.cancel();
key.attach(null);
}
}
protected void writeToChannel(ByteBuffer[] data) throws IOException {
Selector writeSelector = null;
SelectionKey writeKey = null;
int retry = 0;
int writeTimeout = 1000;
try {
while (data != null) {
long len = channel.write(data);
if (len < 0) {
throw new EOFException();
}
if (!ByteBufferHelper.hasRemaining(data)) {
break;
}
if (len > 0) {
retry = 0;
} else {
retry++;
// Check if there are more to be written.
if (writeSelector == null) {
writeSelector = SelectorFactory.getInstance().get();
try {
writeKey = channel.register(writeSelector,
SelectionKey.OP_WRITE);
} catch (Exception e) {
e.printStackTrace();
}
}
if (writeSelector.select(writeTimeout) == 0) {
if (retry > 2) {
throw new IOException("Client disconnected");
}
}
}
}
} finally {
if (writeKey != null) {
writeKey.cancel();
writeKey = null;
}
if (writeSelector != null) {
SelectorFactory.getInstance().free(writeSelector);
}
keepAlive();
}
}
public SocketAddress getLocalEndpoint() {
return channel.socket().getLocalSocketAddress();
}
public SocketAddress getRemoteEndpoint() {
return channel.socket().getRemoteSocketAddress();
}
public SelectableChannel getChannel() {
return channel;
}
}
| Java |
package com.ams.server;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.DatagramSocketImpl;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;
import com.ams.util.ByteBufferHelper;
public class MulticastConnector extends Connector {
class ReadFrameBuffer {
private ByteBuffer[] buffers;
private int lastFrameIndex = 0;
public ReadFrameBuffer(int capacity) {
buffers = new ByteBuffer[capacity];
}
public void set(int index, ByteBuffer buf) {
int capacity = buffers.length;
if (index >= capacity) {
ByteBuffer[] tmp = new ByteBuffer[capacity * 3 / 2];
System.arraycopy(buffers, 0, tmp, 0, index);
buffers = tmp;
}
buffers[index] = buf;
}
public void lastFrame(int index) {
lastFrameIndex = index;
}
public boolean hasLostFrame() {
for(int i = 0; i <= lastFrameIndex; i++ ) {
if (buffers[i] == null) return true;
}
return false;
}
public ByteBuffer[] getFrames() {
ByteBuffer[] buf = new ByteBuffer[lastFrameIndex + 1];
System.arraycopy(buffers, 0, buf, 0, lastFrameIndex + 1);
return buf;
}
public void clear() {
for(int i = 0; i < buffers.length; i++ ) {
buffers[i] = null;
}
lastFrameIndex = 0;
}
}
private static final int MAX_DATA_SIZE = 8192;
private HashMap<SocketAddress, MulticastConnector> connectorMap = new HashMap<SocketAddress, MulticastConnector>();
private DatagramChannel channel;
private SocketAddress groupAddr;
private SocketAddress peer;
private static ArrayList<InetAddress> localAddress = new ArrayList<InetAddress>();
static {
try {
localAddress = getLocalAddress();
} catch (IOException e) {
}
}
private int currentSession = 0;
private ReadFrameBuffer readFrameBuffer = new ReadFrameBuffer(256);
private int session = (int) System.currentTimeMillis();
private int writeDelayTime = 10; // nano second
public MulticastConnector() {
super();
}
public MulticastConnector(DatagramChannel channel, SocketAddress groupAddr) {
super();
this.channel = channel;
this.groupAddr = groupAddr;
}
@SuppressWarnings({ "unchecked", "unused" })
private void invokeSocketMethod(String method, Class[] paramClass, Object[] param) {
try {
// http://www.mernst.org/blog/archives/12-01-2006_12-31-2006.html
// UGLY UGLY HACK: multicast support for NIO
// create a temporary instanceof PlainDatagramSocket, set its fd and configure it
Constructor<? extends DatagramSocketImpl> c =
(Constructor<? extends DatagramSocketImpl>)Class.forName("java.net.PlainDatagramSocketImpl").getDeclaredConstructor();
c.setAccessible(true);
DatagramSocketImpl socketImpl = c.newInstance();
Field channelFd = Class.forName("sun.nio.ch.DatagramChannelImpl").getDeclaredField("fd");
channelFd.setAccessible(true);
Field socketFd = DatagramSocketImpl.class.getDeclaredField("fd");
socketFd.setAccessible(true);
socketFd.set(socketImpl, channelFd.get(channel));
try {
Method m = DatagramSocketImpl.class.getDeclaredMethod(method, paramClass);
m.setAccessible(true);
m.invoke(socketImpl, param);
} catch (Exception e) {
throw e;
} finally {
// important, otherwise the fake socket's finalizer will nuke the fd
socketFd.set(socketImpl, null);
}
} catch (Exception e) {
}
}
@SuppressWarnings("unchecked")
public void joinGroup(SocketAddress groupAddr) {
invokeSocketMethod("joinGroup", new Class[]{SocketAddress.class, NetworkInterface.class}, new Object[]{groupAddr, null});
}
public void configureSocket() {
invokeSocketMethod("setTimeToLive", new Class[]{Integer.class}, new Object[]{1});
invokeSocketMethod("setLoopbackMode", new Class[]{Boolean.class}, new Object[]{true});
}
public void connect(String host, int port) throws IOException {
if (channel == null || !channel.isOpen()) {
channel = DatagramChannel.open();
channel.configureBlocking(false);
channel.socket().bind(new InetSocketAddress(0));
configureSocket();
getDispatcher().addChannelToRegister(new ChannelInterestOps(channel, SelectionKey.OP_READ, this));
groupAddr = new InetSocketAddress(host, port);
open();
}
}
public void finishConnect(SelectionKey key) throws IOException {
// nothing to do
}
public void readChannel(SelectionKey key) throws IOException {
ByteBuffer readBuffer = ByteBufferFactory.allocate(MAX_DATA_SIZE);
SocketAddress remote = null;
if ((remote = channel.receive(readBuffer)) != null) {
// if remote is self, drop the packet
if (localAddress.contains(((InetSocketAddress)remote).getAddress())) {
return;
}
MulticastConnector conn = connectorMap.get(remote);
if (conn == null) {
conn = new MulticastConnector(channel, groupAddr);
conn.setPeer(remote);
for(ConnectionListner listener : listners) {
conn.addListner(listener);
}
connectorMap.put(remote, conn);
}
readBuffer.flip();
conn.handleIncoming(readBuffer);
}
}
protected void writeToChannel(ByteBuffer[] buf) throws IOException {
ArrayList<ByteBuffer> buffers = new ArrayList<ByteBuffer>();
ByteBuffer frame = null;
short sequnce = 0;
int i = 0;
session++;
while (i < buf.length) {
if (frame == null) {
frame = ByteBufferFactory.allocate(MAX_DATA_SIZE);
frame.putInt(session);
frame.put((byte) 0);
frame.putShort(sequnce++);
}
ByteBuffer data = buf[i];
int remaining = frame.remaining();
if (remaining >= data.remaining()) {
frame.put(data);
i++;
} else {
if (remaining > 0) {
ByteBuffer slice = ByteBufferHelper.cut(data, remaining);
frame.put(slice);
}
buffers.add(frame);
frame = null;
}
}
if (frame != null) {
buffers.add(frame);
}
// session id: 4 byte
// payload type: 1 byte, 0: data frame, 1: last frame, 0x10: join group, 0x11: leave group
// sequnce number: 2 byte
ByteBuffer[] frames = buffers.toArray(new ByteBuffer[buffers.size()]);
frames[frames.length - 1].put(4, (byte) 1);
handleOutgoing(groupAddr, frames);
}
private void handleIncoming(ByteBuffer frame) {
int sessionId = frame.getInt();
byte payloadType = frame.get();
short sequnceNum = frame.getShort();
ByteBuffer data = frame.slice();
if (currentSession == 0) {
currentSession = sessionId;
}
if (sessionId < currentSession) {
// drop this frame
return;
}
if (sessionId > currentSession) {
currentSession = sessionId;
readFrameBuffer.clear();
}
readFrameBuffer.set(sequnceNum, data);
if (payloadType == 1) { // last frame?
readFrameBuffer.lastFrame(sequnceNum);
if (!readFrameBuffer.hasLostFrame()) {
offerReadBuffer(readFrameBuffer.getFrames());
if (isClosed()) {
open();
}
}
currentSession = 0;
readFrameBuffer.clear();
}
}
private void handleOutgoing(SocketAddress remote, ByteBuffer[] frames) throws IOException {
Selector writeSelector = null;
SelectionKey writeKey = null;
int writeTimeout = 1000;
try {
for(ByteBuffer frame : frames) {
int retry = 0;
frame.flip();
while(channel.send(frame, remote) == 0) {
retry++;
writeDelayTime += 10;
// Check if there are more to be written.
if (writeSelector == null) {
writeSelector = SelectorFactory.getInstance().get();
try {
writeKey = channel.register(writeSelector, SelectionKey.OP_WRITE);
} catch (Exception e) {
e.printStackTrace();
}
}
if (writeSelector.select(writeTimeout) == 0) {
if (retry > 2) {
throw new IOException("Client disconnected");
}
}
}
try {
TimeUnit.NANOSECONDS.sleep(writeDelayTime);
} catch (InterruptedException e) {
}
}
} finally {
if (writeKey != null) {
writeKey.cancel();
writeKey = null;
}
if (writeSelector != null) {
SelectorFactory.getInstance().free(writeSelector);
}
keepAlive();
}
}
public long getKeepAliveTime() {
return System.currentTimeMillis();
}
public SocketAddress getLocalEndpoint() {
return channel.socket().getLocalSocketAddress();
}
public SocketAddress getRemoteEndpoint() {
return channel.socket().getRemoteSocketAddress();
}
public SelectableChannel getChannel() {
return channel;
}
public SocketAddress getPeer() {
return peer;
}
public void setPeer(SocketAddress addr) {
this.peer = addr;
}
}
| Java |
package com.ams.server;
import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicLong;
import com.ams.io.ByteBufferInputStream;
import com.ams.io.ByteBufferOutputStream;
import com.ams.io.IByteBufferReader;
import com.ams.io.IByteBufferWriter;
import com.ams.util.ByteBufferHelper;
public abstract class Connector implements IByteBufferReader, IByteBufferWriter {
protected static final int DEFAULT_TIMEOUT_MS = 30000;
protected static final int MAX_QUEUE_SIZE = 1024;
protected ConcurrentLinkedQueue<ByteBuffer> readQueue = new ConcurrentLinkedQueue<ByteBuffer>();
protected ConcurrentLinkedQueue<ByteBuffer> writeQueue = new ConcurrentLinkedQueue<ByteBuffer>();
protected ByteBuffer writeBuffer = null;
protected AtomicLong available = new AtomicLong(0);
protected int timeout = DEFAULT_TIMEOUT_MS;
protected long keepAliveTime;
protected boolean keepAlive = false;
protected boolean closed = true;
protected boolean sleepingForRead = false;
protected boolean sleepingForWaitData = false;
protected ArrayList<ConnectionListner> listners = new ArrayList<ConnectionListner>();
protected ByteBufferInputStream in;
protected ByteBufferOutputStream out;
private static Dispatcher dispatcher = null;
private static Object dispatcherLock = new Object();
public Connector() {
this.in = new ByteBufferInputStream(this);
this.out = new ByteBufferOutputStream(this);
keepAlive();
}
public abstract void connect(String host, int port) throws IOException;
public abstract void finishConnect(SelectionKey key) throws IOException;
public abstract void readChannel(SelectionKey key) throws IOException;
protected abstract void writeToChannel(ByteBuffer[] data) throws IOException;
public abstract SocketAddress getLocalEndpoint();
public abstract SocketAddress getRemoteEndpoint();
public abstract SelectableChannel getChannel();
protected Dispatcher getDispatcher() throws IOException {
if (dispatcher == null) {
synchronized(dispatcherLock) {
dispatcher = new Dispatcher();
Thread t = new Thread(dispatcher);
t.setDaemon(true);
t.start();
}
}
return dispatcher;
}
protected void keepAlive() {
keepAliveTime = System.currentTimeMillis();
}
public boolean isKeepAlive() {
return keepAlive;
}
public void setKeepAlive(boolean keepAlive) {
this.keepAlive = keepAlive;
}
public long getKeepAliveTime() {
return keepAliveTime;
}
public synchronized void open() {
keepAlive();
if (!isClosed()) return;
closed = false;
for (ConnectionListner listner : listners) {
listner.connectionEstablished(this);
}
}
public synchronized void close() {
if (isClosed()) return;
closed = true;
if (!isKeepAlive()) {
Channel channel = getChannel();
try {
channel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
for (ConnectionListner listner : listners) {
listner.connectionClosed(this);
}
}
public boolean isClosed() {
return closed;
}
public boolean isWriteBlocking() {
return writeQueue.size() > MAX_QUEUE_SIZE;
}
public long available() {
return available.get();
}
public ByteBuffer peek() {
return readQueue.peek();
}
protected void offerReadBuffer(ByteBuffer buffers[]) {
for(ByteBuffer buffer : buffers) {
readQueue.offer(buffer);
available.addAndGet(buffer.remaining());
}
keepAlive();
if (sleepingForRead || sleepingForWaitData) {
synchronized (readQueue) {
sleepingForRead = false;
sleepingForWaitData = false;
readQueue.notifyAll();
}
}
}
public ByteBuffer[] read(int size) throws IOException {
ArrayList<ByteBuffer> list = new ArrayList<ByteBuffer>();
int length = size;
while (length > 0) {
// read a buffer with blocking
ByteBuffer buffer = readQueue.peek();
if (buffer != null) {
int remain = buffer.remaining();
if (length >= remain) {
list.add(readQueue.poll());
length -= remain;
} else {
ByteBuffer slice = ByteBufferHelper.cut(buffer, length);
list.add(slice);
length = 0;
}
} else {
// wait new buffer append to queue
// sleep for timeout ms
try {
synchronized (readQueue) {
sleepingForRead = true;
readQueue.wait(timeout);
}
} catch (InterruptedException e) {
sleepingForRead = false;
throw new IOException("read interrupted");
}
if (sleepingForRead) {
sleepingForRead = false;
throw new IOException("read time out");
}
}
} // end while
available.addAndGet(-size);
return list.toArray(new ByteBuffer[list.size()]);
}
public void write(ByteBuffer[] data) throws IOException {
for (ByteBuffer buf : data) {
writeQueue.offer(buf);
}
}
public void flush() throws IOException {
if (out != null) out.flush();
ArrayList<ByteBuffer> writeBuffers = new ArrayList<ByteBuffer>();
ByteBuffer data;
boolean hasData = false;
while ((data = writeQueue.poll()) != null) {
writeBuffers.add(data);
hasData = true;
}
if (hasData) {
writeToChannel(writeBuffers.toArray(new ByteBuffer[writeBuffers.size()]));
}
}
public boolean waitDataReceived(int time) {
if (available.get() == 0) {
try {
synchronized (readQueue) {
sleepingForWaitData = true;
readQueue.wait(time);
}
} catch (InterruptedException e) {
}
if (sleepingForWaitData) { // timeout
return false;
}
}
return true;
}
public int getTimeout() {
return timeout;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
public ByteBufferInputStream getInputStream() {
return in;
}
public ByteBufferOutputStream getOutputStream() {
return out;
}
public synchronized void addListner(ConnectionListner listener) {
this.listners.add(listener);
}
public synchronized boolean removeListner(ConnectionListner listener) {
return this.listners.remove(listener);
}
public static ArrayList<InetAddress> getLocalAddress() throws IOException {
ArrayList<InetAddress> address = new ArrayList<InetAddress>();
for (Enumeration<NetworkInterface> ifaces = NetworkInterface
.getNetworkInterfaces(); ifaces.hasMoreElements();) {
NetworkInterface iface = (NetworkInterface) ifaces.nextElement();
for (Enumeration<InetAddress> ips = iface.getInetAddresses(); ips
.hasMoreElements();) {
InetAddress ia = (InetAddress) ips.nextElement();
address.add(ia);
}
}
return address;
}
}
| Java |
package com.ams.server.protocol;
import java.io.IOException;
import java.util.HashMap;
import com.ams.amf.AmfException;
import com.ams.amf.AmfValue;
import com.ams.event.Event;
import com.ams.rtmp.RtmpConnection;
import com.ams.rtmp.RtmpException;
import com.ams.rtmp.RtmpHeader;
import com.ams.rtmp.message.RtmpMessage;
import com.ams.rtmp.message.RtmpMessageCommand;
import com.ams.rtmp.net.NetConnectionException;
import com.ams.rtmp.net.PublisherManager;
import com.ams.rtmp.net.StreamPublisher;
import com.ams.server.Connector;
import com.ams.util.Log;
public class SlaveHandler implements IProtocolHandler {
private Connector conn;
private RtmpConnection rtmp;
private boolean keepAlive = true;
private HashMap<Integer, String> streams = new HashMap<Integer, String>();
public void readAndProcessRtmpMessage() throws NetConnectionException, IOException, RtmpException, AmfException {
if (!rtmp.readRtmpMessage()) return;
RtmpHeader header = rtmp.getCurrentHeader();
RtmpMessage message = rtmp.getCurrentMessage();
switch( message.getType() ) {
case RtmpMessage.MESSAGE_AMF0_COMMAND:
RtmpMessageCommand command = (RtmpMessageCommand)message;
if ("publish".equals(command.getName())) {
int streamId = header.getStreamId();
AmfValue[] args = command.getArgs();
String publishName = args[1].string();
streams.put(streamId, publishName);
if (PublisherManager.getPublisher(publishName) == null) {
PublisherManager.addPublisher(new StreamPublisher(publishName));
}
} else if ("closeStream".equals(command.getName())) {
int streamId = header.getStreamId();
String publishName = streams.get(streamId);
if (publishName == null) break;
streams.remove(streamId);
StreamPublisher publisher = (StreamPublisher) PublisherManager.getPublisher(publishName);
publisher.close();
PublisherManager.removePublisher(publishName);
}
break;
case RtmpMessage.MESSAGE_AUDIO:
case RtmpMessage.MESSAGE_VIDEO:
case RtmpMessage.MESSAGE_AMF0_DATA:
int streamId = header.getStreamId();
String publishName = streams.get(streamId);
if (publishName == null) break;
StreamPublisher publisher = (StreamPublisher) PublisherManager.getPublisher(publishName);
if (publisher != null) {
publisher.publish(new Event(header.getTimestamp(), message));
}
break;
}
}
public void run() {
if (conn.isClosed()) {
clear();
return;
}
try {
// waiting for data arriving
if (conn.waitDataReceived(10)) {
// read & process rtmp message
readAndProcessRtmpMessage();
}
} catch (Exception e) {
e.printStackTrace();
Log.logger.info("slave handler exception");
}
}
public IProtocolHandler newInstance(Connector conn) {
IProtocolHandler handle = new SlaveHandler();
handle.setConnection(conn);
return handle;
}
public void clear() {
conn.close();
keepAlive = false;
}
public void setConnection(Connector conn) {
this.conn = conn;
this.rtmp = new RtmpConnection(conn);
}
public boolean isKeepAlive() {
return keepAlive;
}
} | Java |
package com.ams.server.protocol;
import java.io.IOException;
import com.ams.http.DefaultServlet;
import com.ams.http.HttpRequest;
import com.ams.http.HttpResponse;
import com.ams.http.ServletContext;
import com.ams.server.Connector;
import com.ams.util.Log;
public class HttpHandler implements IProtocolHandler {
private Connector conn;
private ServletContext context;
public HttpHandler(String contextRoot) throws IOException {
this.context = new ServletContext(contextRoot);
}
public HttpHandler(ServletContext context) {
this.context = context;
}
public void run() {
try {
Log.logger.info("http handler start");
HttpRequest request = new HttpRequest(conn.getInputStream());
HttpResponse response = new HttpResponse(conn.getOutputStream());
DefaultServlet servlet = new DefaultServlet(context);
request.parse();
servlet.service(request, response);
if (request.isKeepAlive()) {
conn.setKeepAlive(true);
}
conn.flush();
conn.close();
Log.logger.info("http handler end");
} catch (IOException e) {
Log.logger.warning(e.getMessage());
}
}
public void clear() {
conn.close();
}
public IProtocolHandler newInstance(Connector conn) {
IProtocolHandler handle = new HttpHandler(context);
handle.setConnection(conn);
return handle;
}
public void setConnection(Connector conn) {
this.conn = conn;
}
public boolean isKeepAlive() {
return false;
}
} | Java |
package com.ams.server.protocol;
import com.ams.rtmp.net.NetConnection;
import com.ams.rtmp.net.NetContext;
import com.ams.rtmp.RtmpConnection;
import com.ams.server.Connector;
import com.ams.util.Log;
public class RtmpHandler implements IProtocolHandler {
private Connector conn;
private RtmpConnection rtmp;
private NetConnection netConn;
private NetContext context;
private boolean keepAlive = true;
public RtmpHandler(String contextRoot) {
this.context = new NetContext(contextRoot);
}
public RtmpHandler(NetContext context) {
this.context = context;
}
public void run() {
if (conn.isClosed()) {
clear();
return;
}
try {
// waiting for data arriving
if (conn.waitDataReceived(10)) {
// read & process rtmp message
netConn.readAndProcessRtmpMessage();
}
// write client video/audio streams
netConn.playStreams();
// write to socket channel
conn.flush();
} catch (Exception e) {
e.printStackTrace();
Log.logger.info("rtmp handler exception");
clear();
}
}
public IProtocolHandler newInstance(Connector conn) {
IProtocolHandler handle = new RtmpHandler(context);
handle.setConnection(conn);
return handle;
}
public void clear() {
conn.close();
netConn.close();
keepAlive = false;
}
public void setConnection(Connector conn) {
this.conn = conn;
this.rtmp = new RtmpConnection(conn);
this.netConn = new NetConnection(rtmp, context);
}
public boolean isKeepAlive() {
return keepAlive;
}
} | Java |
package com.ams.server.protocol;
import com.ams.server.Connector;
public interface IProtocolHandler extends Runnable {
public IProtocolHandler newInstance(Connector conn);
public void setConnection(Connector conn);
public void clear();
public boolean isKeepAlive();
} | Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.