code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
package com.ams.server;
import java.nio.channels.SelectableChannel;
public class ChannelInterestOps {
private SelectableChannel channel;
private int interestOps;
private Connector connector;
public ChannelInterestOps(SelectableChannel channel, int interestOps, Connector connector) {
this.channel = channel;
this.interestOps = interestOps;
this.connector = connector;
}
public SelectableChannel getChannel() {
return channel;
}
public int getInterestOps() {
return interestOps;
}
public Connector getConnector() {
return connector;
}
}
| Java |
package com.ams.server;
import java.io.IOException;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedQueue;
import com.ams.util.Log;
public class Dispatcher implements Runnable {
private static final long selectTimeOut = 2 * 1000;
private static final long timeExpire = 2 * 60 * 1000;
private long lastExpirationTime = 0;
private Selector selector = null;
private ConcurrentLinkedQueue<ChannelInterestOps> registerChannelQueue = null;
private boolean running = true;
public Dispatcher() throws IOException {
selector = SelectorFactory.getInstance().get();
registerChannelQueue = new ConcurrentLinkedQueue<ChannelInterestOps>();
}
public void addChannelToRegister(ChannelInterestOps channelInterestOps) {
registerChannelQueue.offer(channelInterestOps);
selector.wakeup();
}
public void run() {
while (running) {
// register a new channel
registerNewChannel();
// do select
doSelect();
// collect idle keys that will not be used
expireIdleKeys();
}
closeAllKeys();
}
private void registerNewChannel() {
try {
ChannelInterestOps channelInterestOps = null;
while ((channelInterestOps = registerChannelQueue.poll()) != null) {
SelectableChannel channel = channelInterestOps.getChannel();
int interestOps = channelInterestOps.getInterestOps();
Connector connector = channelInterestOps.getConnector();
channel.configureBlocking(false);
channel.register(selector, interestOps, connector);
}
} catch (Exception e) {
e.printStackTrace();
Log.logger.warning(e.getMessage());
}
}
private void doSelect() {
int selectedKeys = 0;
try {
selectedKeys = selector.select(selectTimeOut);
} catch (Exception e) {
e.printStackTrace();
if (selector.isOpen()) {
return;
} else {
Log.logger.warning(e.getMessage());
}
}
if (selectedKeys == 0) {
return;
}
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
while (it.hasNext()) {
SelectionKey key = it.next();
it.remove();
if (!key.isValid()) {
continue;
}
Connector connector = (Connector)key.attachment();
try {
if (key.isConnectable()) {
connector.finishConnect(key);
}
if (key.isReadable()) {
connector.readChannel(key);
}
} catch (Exception e) {
e.printStackTrace();
Log.logger.warning(e.toString());
key.cancel();
key.attach(null);
connector.close();
}
}
}
private void expireIdleKeys() {
// check every timeExpire
long now = System.currentTimeMillis();
long elapsedTime = now - lastExpirationTime;
if (elapsedTime < timeExpire) {
return;
}
lastExpirationTime = now;
for (SelectionKey key : selector.keys()) {
// Keep-alive expired
Connector connector = (Connector)key.attachment();
if (connector != null) {
long keepAliveTime = connector.getKeepAliveTime();
if (now - keepAliveTime > timeExpire) {
Log.logger.warning("key expired");
key.cancel();
key.attach(null);
connector.close();
}
}
}
}
private void closeAllKeys() {
// close all keys
for (SelectionKey key : selector.keys()) {
// Keep-alive expired
Connector connector = (Connector)key.attachment();
if (connector != null) {
key.cancel();
key.attach(null);
connector.close();
}
}
}
public void start() {
running = true;
}
public void stop() {
running = false;
}
}
| Java |
package com.ams.server;
import java.net.Socket;
import java.net.SocketException;
public final class SocketProperties {
private int rxBufSize = 25188;
private int txBufSize = 43800;
private boolean tcpNoDelay = true;
private boolean soKeepAlive = false;
private boolean ooBInline = true;
private boolean soReuseAddress = true;
private boolean soLingerOn = true;
private int soLingerTime = 25;
private int soTimeout = 5000;
private int soTrafficClass = 0x04 | 0x08 | 0x010;
private int performanceConnectionTime = 1;
private int performanceLatency = 0;
private int performanceBandwidth = 1;
public void setSocketProperties(Socket socket) throws SocketException {
socket.setReceiveBufferSize(rxBufSize);
socket.setSendBufferSize(txBufSize);
socket.setOOBInline(ooBInline);
socket.setKeepAlive(soKeepAlive);
socket.setPerformancePreferences(performanceConnectionTime,
performanceLatency, performanceBandwidth);
socket.setReuseAddress(soReuseAddress);
socket.setSoLinger(soLingerOn, soLingerTime);
socket.setSoTimeout(soTimeout);
socket.setTcpNoDelay(tcpNoDelay);
socket.setTrafficClass(soTrafficClass);
}
}
| Java |
package com.ams.server;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import com.ams.util.Log;
public final class ByteBufferAllocator {
private int minChunkSize = 16;
private int maxChunkSize = 128 * 1024;
private int pageSize = 8 * 1024 * 1024;
private float factor = 2.0f;
private double logFactor;
private ArrayList<Slab> slabs;
private class Slab {
private ArrayList<Page> pages;
private int chunkSize;
public Slab(int chunkSize) {
this.chunkSize = chunkSize;
pages = new ArrayList<Page>();
pages.add(new Page(chunkSize, pageSize / chunkSize ));
}
public synchronized ByteBuffer allocate() {
ByteBuffer buf = null;
for(Page page : pages) {
if (page.isEmpty()) {
buf = page.allocate();
if (buf != null) {
return buf;
}
}
}
return null;
}
public synchronized Page grow() {
Page page = new Page(chunkSize, pageSize / chunkSize );
pages.add(page);
Log.logger.info("grow a page: " + chunkSize);
return page;
}
public boolean isEmpty() {
for(Page page : pages) {
if (page.isEmpty()) {
return true;
}
}
return false;
}
}
private class Page {
private boolean empty = true;
private int chunkSize;
private ByteBuffer chunks;
private BitSet chunkBitSet;
private int bitSize;
private int currentIndex = 0;
public Page(int chunkSize, int n) {
this.chunks = ByteBuffer.allocateDirect(chunkSize * n);
this.chunkSize = chunkSize;
this.chunkBitSet = new BitSet(n);
this.bitSize = n;
}
public synchronized ByteBuffer allocate() {
int index = chunkBitSet.nextClearBit(currentIndex);
if (index >= bitSize) {
index = chunkBitSet.nextClearBit(0);
if (index >= bitSize) {
empty = false;
return null; // should allocate a new page
}
}
// slice a buffer
chunkBitSet.set(index, true);
chunks.position(index * chunkSize);
chunks.limit(chunks.position() + chunkSize);
ByteBuffer slice = chunks.slice();
referenceList.add(new ChunkReference(slice, this, index));
currentIndex = index + 1;
chunks.clear();
return slice;
}
public synchronized void free(int index) {
chunkBitSet.set(index, false);
empty = true;
}
public boolean isEmpty() {
return empty;
}
}
private class ChunkReference extends WeakReference<ByteBuffer> {
private Page page;
private int chunkIndex;
public ChunkReference(ByteBuffer buf, Page page , int index) {
super(buf, chunkReferenceQueue);
this.page = page;
this.chunkIndex = index;
}
public Page getPage() {
return page;
}
public int getChunkIndex() {
return chunkIndex;
}
}
private static ReferenceQueue<ByteBuffer> chunkReferenceQueue = new ReferenceQueue<ByteBuffer>();
private static List<ChunkReference> referenceList = Collections.synchronizedList(new LinkedList<ChunkReference>());
private void collect() {
System.gc();
ChunkReference r;
while((r = (ChunkReference)chunkReferenceQueue.poll()) != null) {
Page page = r.getPage();
int index = r.getChunkIndex();
page.free(index);
referenceList.remove(r);
}
}
private class ByteBufferCollector extends Thread {
private static final int COLLECT_INTERVAL_MS = 100;
public ByteBufferCollector() {
super();
try {
setDaemon(true);
} catch (Exception e) {
}
}
public void run() {
try {
while (!interrupted()) {
sleep(COLLECT_INTERVAL_MS);
collect();
}
} catch (InterruptedException e) {
interrupt();
}
}
}
public ByteBufferAllocator (){
ByteBufferCollector collector = new ByteBufferCollector();
collector.start();
logFactor = Math.log(factor);
}
public void init() {
// Initialize Slabs
slabs = new ArrayList<Slab>();
int size = minChunkSize;
while(size <= maxChunkSize) {
slabs.add(new Slab(size));
size *= factor;
}
logFactor = Math.log(factor);
}
private int getSlabIndex(int size) {
if (size <= 0) return 0;
return (int) Math.ceil(Math.log((float)size / minChunkSize) / logFactor);
}
public void setMinChunkSize(int minChunkSize) {
this.minChunkSize = minChunkSize;
}
public void setMaxChunkSize(int maxChunkSize) {
this.maxChunkSize = maxChunkSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public void setFactor(float factor) {
this.factor = factor;
}
public synchronized ByteBuffer allocate(int size) {
// find a slab to allocate
ByteBuffer buf = null;
Slab slab = null;
int index = getSlabIndex(size);
for (int retry = 0; retry < 2; retry ++) {
for (int i = 0, slabSize = slabs.size(); i < 3 && index + i < slabSize; i++) {
slab = slabs.get(index + i);
if (slab.isEmpty()) {
buf = slab.allocate();
if (buf != null) {
return buf;
}
}
}
// collect free buffers
Log.logger.info("collect free buffers");
collect();
}
//grow the selected slab and allocate a chunk
slab = slabs.get(index);
Page page = slab.grow();
return page.allocate();
}
}
| 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 com.ams.config.Configuration;
import com.ams.server.protocol.IProtocolHandler;
import com.ams.server.replicator.ReplicateCluster;
import com.ams.util.Log;
public final class Server implements ConnectionListner {
private Configuration config;
private HashMap<SocketAddress, IAcceptor> acceptorMap;
private ArrayList<Dispatcher> dispatchers;
private HashMap<SocketAddress, IProtocolHandler> handlerMap;
private WorkerQueue workerQueue;
public Server(Configuration config) throws IOException {
initByteBufferFactory(config);
this.config = config;
this.acceptorMap = new HashMap<SocketAddress, IAcceptor>();
this.dispatchers = new ArrayList<Dispatcher>();
this.handlerMap = new HashMap<SocketAddress, IProtocolHandler>();
int dispatcherSize = config.getDispatcherThreadPoolSize();
for (int i = 0; i < dispatcherSize; i++) {
Dispatcher dispatcher = new Dispatcher();
dispatchers.add(dispatcher);
}
int poolSize = config.getWokerThreadPoolSize();
workerQueue = new WorkerQueue(poolSize);
}
private void initByteBufferFactory(Configuration config) {
ByteBufferFactory.setPageSize(config.getSlabPageSize());
}
public void addTcpListenEndpoint(SocketAddress endpoint, IProtocolHandler handler) throws IOException {
SocketAcceptor acceptor = new SocketAcceptor(endpoint);
acceptor.setConnectionListner(this);
acceptor.setSocketProperties(config.getSocketProperties());
acceptor.setDispatchers(dispatchers);
acceptorMap.put(endpoint, acceptor);
handlerMap.put(endpoint, handler);
}
public void addMulticastListenEndpoint(SocketAddress endpoint, SocketAddress group, IProtocolHandler handler) throws IOException {
MulticastAcceptor acceptor = new MulticastAcceptor(endpoint, group);
acceptor.setConnectionListner(this);
acceptor.setDispatchers(dispatchers);
acceptorMap.put(endpoint, acceptor);
handlerMap.put(endpoint, handler);
}
public void removeListenEndpoint(SocketAddress endpoint) {
IAcceptor acceptor = acceptorMap.get(endpoint);
if (acceptor != null) {
acceptor.stop();
acceptorMap.remove(acceptor);
}
IProtocolHandler handler = handlerMap.get(endpoint);
if (handler != null) {
handler.clear();
handlerMap.remove(handler);
}
}
public void start() {
workerQueue.start();
for (int i = 0; i < dispatchers.size(); i++) {
Dispatcher dispatcher = dispatchers.get(i);
new Thread(dispatcher).start();
}
for (SocketAddress endpoint : acceptorMap.keySet()) {
IAcceptor acceptor = acceptorMap.get(endpoint);
acceptor.start();
new Thread(acceptor).start();
Log.logger.info("Start service on port: " + acceptor.getListenEndpoint());
}
// establish replicate cluster
if (config.getReplicationHost() != null && config.getReplicationSlaves() != null) {
try {
ReplicateCluster.establishTcpReplicator(config.getReplicationSlaves(), config.getReplicationPort());
} catch (IOException e) {
e.printStackTrace();
}
}
if (config.getMulticastHost() != null && config.getMulticastGroup() != null) {
try {
ReplicateCluster.establishMulticastReplicator(config.getMulticastGroup(), config.getMulticastPort());
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void stop() {
for (SocketAddress endpoint : acceptorMap.keySet()) {
IAcceptor acceptor = acceptorMap.get(endpoint);
acceptor.stop();
}
for (int i = 0; i < dispatchers.size(); i++) {
dispatchers.get(i).stop();
}
workerQueue.stop();
ReplicateCluster.close();
Log.logger.info("Server is Stoped.");
}
public IProtocolHandler getHandler(SocketAddress endpoint) {
if (handlerMap.containsKey(endpoint)) {
return (IProtocolHandler)handlerMap.get(endpoint);
} else {
if (endpoint instanceof InetSocketAddress) {
SocketAddress endpointAny = new InetSocketAddress("0.0.0.0",
((InetSocketAddress)endpoint).getPort());
if (handlerMap.containsKey(endpointAny)) {
return (IProtocolHandler)handlerMap.get(endpointAny);
}
}
}
return null;
}
public void connectionEstablished(Connector conn) {
SocketAddress endpoint = conn.getLocalEndpoint();
IProtocolHandler handler = getHandler(endpoint);
if (handler != null) {
workerQueue.execute(handler.newInstance(conn));
} else {
Log.logger.warning("unkown connection port:" + endpoint);
}
}
public void connectionClosed(Connector conn) {
}
} | Java |
package com.ams.server.replicator;
import java.io.IOException;
import java.net.InetAddress;
import java.util.ArrayList;
import com.ams.event.Event;
import com.ams.server.Connector;
import com.ams.server.MulticastConnector;
import com.ams.server.SocketConnector;
public class ReplicateCluster {
private static ArrayList<Replicator> replicators = new ArrayList<Replicator>();
public static void establishTcpReplicator(String[] slaves, int port)
throws IOException {
if (slaves == null)
return;
for (int i = 0; i < slaves.length; i++) {
String host = slaves[i];
if (!isLocalHost(host)) {
Replicator replicator = new Replicator(new SocketConnector(), host, port);
replicators.add(replicator);
new Thread(replicator).start();
}
}
}
public static boolean isLocalHost(String host) throws IOException {
InetAddress hostAddr = InetAddress.getByName(host);
ArrayList<InetAddress> address = Connector.getLocalAddress();
return address.contains(hostAddr);
}
public static void establishMulticastReplicator(String group, int port)
throws IOException {
Replicator replicator = new Replicator(new MulticastConnector(), group,
port);
replicators.add(replicator);
new Thread(replicator).start();
}
public static void publishMessage(String publishName, Event event) {
for (Replicator replicator : replicators) {
replicator.publishMessage(publishName, event);
}
}
public static void close() {
for (Replicator replicator : replicators) {
replicator.close();
}
replicators.clear();
}
}
| Java |
package com.ams.server.replicator;
import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;
import com.ams.amf.AmfNull;
import com.ams.amf.AmfValue;
import com.ams.event.Event;
import com.ams.rtmp.message.RtmpMessage;
import com.ams.rtmp.message.RtmpMessageCommand;
import com.ams.rtmp.RtmpConnection;
import com.ams.server.Connector;
import com.ams.server.MulticastConnector;
import com.ams.util.Log;
class Replicator implements Runnable {
private String slaveHost = null;
private int slavePort;
private Connector conn = null;
private RtmpConnection rtmp;
private boolean running = true;
private boolean isConnected = false;
private static int MAX_EVENT_QUEUE_LENGTH = 100;
private final static int CHANNEL_RTMP_COMMAND = 3;
private final static int CHANNEL_RTMP_PUBLISH = 20;
private static final int DEFAULT_TIMEOUT_MS = 24 * 60 * 60 * 1000;
private static final int MAX_STREAM_ID = 10000;
private AtomicInteger currentStreamId = new AtomicInteger(1);
private HashMap<String, Publisher> publishMap = new HashMap<String, Publisher>();
private class Publisher {
private int streamId = -1;
private String publishName;
private long keepAliveTime = 0;
private boolean start = false;
private ConcurrentLinkedQueue<Event> msgQueue = new ConcurrentLinkedQueue<Event>();
public Publisher(int streamId, String publishName) {
this.streamId = streamId;
this.publishName = publishName;
this.keepAliveTime = System.currentTimeMillis();
}
public boolean expire() {
long currentTime = System.currentTimeMillis();
return (currentTime - keepAliveTime > DEFAULT_TIMEOUT_MS);
}
public void addEvent(Event event) {
if (msgQueue.size() > MAX_EVENT_QUEUE_LENGTH) {
msgQueue.clear();
}
msgQueue.offer(event);
}
public void replicate() throws IOException {
ConcurrentLinkedQueue<Event> queue = msgQueue;
Event msg = null;
while((msg = queue.poll()) != null) {
keepAliveTime = System.currentTimeMillis();
rtmp.writeRtmpMessage(CHANNEL_RTMP_PUBLISH, streamId, msg.getTimestamp(), (RtmpMessage)msg.getEvent());
}
}
public void publish() throws IOException {
AmfValue[] args = {new AmfNull(), new AmfValue(publishName), new AmfValue("live")};
RtmpMessage message = new RtmpMessageCommand("publish", 1, args);
rtmp.writeRtmpMessage(CHANNEL_RTMP_COMMAND, streamId, System.currentTimeMillis(), message);
}
public void closeStream() throws IOException {
AmfValue[] args = {new AmfNull()};
RtmpMessage message = new RtmpMessageCommand("closeStream", 0, args);
rtmp.writeRtmpMessage(CHANNEL_RTMP_COMMAND, streamId, System.currentTimeMillis(), message);
}
}
public Replicator(Connector connector, String host, int port) throws IOException {
this.slaveHost = host;
this.slavePort = port;
conn = connector;
conn.setTimeout(DEFAULT_TIMEOUT_MS);
rtmp = new RtmpConnection(conn);
}
public void run() {
long publishTime = System.currentTimeMillis();
while (running) {
try {
if (conn.isClosed()) {
Log.logger.info("connect to " + slaveHost + ":" + slavePort);
conn.connect(slaveHost, slavePort);
isConnected = true;
Log.logger.info("connected to " + slaveHost + ":" + slavePort);
}
try {
synchronized (this) {
wait();
}
} catch (InterruptedException e) {}
for (Publisher publisher : publishMap.values()) {
if (!publisher.start) {
publisher.publish();
publisher.start = true;
continue;
}
// send publish command every 3 seconds.
if (conn instanceof MulticastConnector) {
long now = System.currentTimeMillis();
if (now - publishTime > 5000) {
publishTime = now;
publisher.publish();
}
}
if (!publisher.expire()) {
publisher.replicate();
} else {
publisher.closeStream();
publishMap.remove(publisher.publishName);
}
}
conn.flush();
} catch (IOException e) {
e.printStackTrace();
Log.logger.warning(e.toString());
clear();
}
}
clear();
}
private void closeAllStreams() {
for(Publisher publisher : publishMap.values()) {
try {
publisher.closeStream();
} catch (IOException e) {}
}
try {
conn.flush();
} catch (IOException e) {}
}
private void clear() {
currentStreamId.set(1);
publishMap.clear();
if (!conn.isClosed()) {
closeAllStreams();
conn.close();
}
}
private int allocStreamId() {
int id = currentStreamId.addAndGet(1);
if (id > MAX_STREAM_ID) {
currentStreamId.set(1);
}
return id;
}
public void publishMessage(String publishName, Event event) {
if (!isConnected) return;
Publisher publisher = publishMap.get(publishName);
if (publisher != null) {
publisher.addEvent(event);
} else {
int streamId = allocStreamId();
publishMap.put(publishName, new Publisher(streamId, publishName));
}
synchronized (this) {
notifyAll();
}
}
public void close() {
running = false;
}
} | Java |
package com.ams.server;
public interface ConnectionListner {
public void connectionEstablished(Connector conn);
public void connectionClosed(Connector conn);
}
| Java |
package com.ams.server;
import java.io.*;
import java.net.*;
import java.nio.channels.*;
import java.util.ArrayList;
public class MulticastAcceptor implements IAcceptor {
private SocketAddress listenEndpoint;
private DatagramChannel datagramChannel;
private ConnectionListner listner;
public MulticastAcceptor(SocketAddress host, SocketAddress multicastGroupAddr) throws IOException {
datagramChannel = DatagramChannel.open();
datagramChannel.socket().bind(host);
datagramChannel.configureBlocking(false);
listenEndpoint = multicastGroupAddr;
}
public void setDispatchers(ArrayList<Dispatcher> dispatchers) {
MulticastConnector connector = new MulticastConnector(datagramChannel, listenEndpoint);
connector.joinGroup(listenEndpoint);
connector.configureSocket();
connector.addListner(listner);
dispatchers.get(0).addChannelToRegister(new ChannelInterestOps(datagramChannel, SelectionKey.OP_READ, connector));
}
public SocketAddress getListenEndpoint() {
return listenEndpoint;
}
public synchronized void stop() {
try {
datagramChannel.close();
} catch (IOException e) {
}
notifyAll();
}
public void run() {
try {
synchronized (this) {
this.wait();
}
} catch (InterruptedException e) {
}
}
public void start() {
}
public void setConnectionListner(ConnectionListner listner) {
this.listner = listner;
}
}
| Java |
package com.ams.server;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import com.ams.config.Configuration;
import com.ams.server.protocol.HttpHandler;
import com.ams.server.protocol.RtmpHandler;
import com.ams.server.protocol.SlaveHandler;
import com.ams.util.Log;
public class DaemonThread extends Thread {
private ServerSocket commandSocket;
private Server server;
public DaemonThread() throws IOException {
commandSocket = new ServerSocket(5555);
createServerInstance();
}
private void createServerInstance() {
Configuration config = new Configuration();
try {
if (!config.read()) {
Log.logger.info("read config error!");
return;
}
} catch (FileNotFoundException e) {
Log.logger
.info("Not found server.conf file, using default setting!");
}
try {
server = new Server(config);
// http service
InetSocketAddress httpEndpoint = new InetSocketAddress(
config.getHttpHost(), config.getHttpPort());
server.addTcpListenEndpoint(httpEndpoint, new HttpHandler(config.getHttpContextRoot()));
// rtmp service
InetSocketAddress rtmpEndpoint = new InetSocketAddress(
config.getRtmpHost(), config.getRtmpPort());
server.addTcpListenEndpoint(rtmpEndpoint, new RtmpHandler(config.getRtmpContextRoot()));
// tcp replication service
if (config.getReplicationHost() != null) {
InetSocketAddress replicationEndpoint = new InetSocketAddress(config.getReplicationHost(), config.getReplicationPort());
server.addTcpListenEndpoint(replicationEndpoint, new SlaveHandler());
}
// multicast replication service
if (config.getMulticastHost() != null) {
InetSocketAddress multicastEndpoint = new InetSocketAddress(
config.getMulticastHost(), config.getMulticastPort());
InetSocketAddress multicastGroup = new InetSocketAddress(
config.getMulticastGroup(), config.getMulticastPort());
server.addMulticastListenEndpoint(multicastEndpoint,
multicastGroup, new SlaveHandler());
}
} catch (Exception e) {
e.printStackTrace();
Log.logger.info(e.getMessage());
}
}
public void run() {
Log.logger.info("Daemon thread is started.");
while (true) {
try {
Socket socket = commandSocket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
String cmd = in.readLine();
socket.close();
if ("stop".equalsIgnoreCase(cmd)) {
server.stop();
} else if ("start".equalsIgnoreCase(cmd)) {
server.start();
} else if ("restart".equalsIgnoreCase(cmd)) {
server.stop();
createServerInstance();
server.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
| Java |
package com.ams.server;
import java.net.SocketAddress;
import java.util.ArrayList;
public interface IAcceptor extends Runnable {
public void setDispatchers(ArrayList<Dispatcher> dispatchers);
public SocketAddress getListenEndpoint();
public void start();
public void stop();
} | Java |
package com.ams.server;
import java.util.concurrent.ConcurrentLinkedQueue;
import com.ams.server.protocol.IProtocolHandler;
public class WorkerQueue {
private int nThreads;
private Worker[] threads;
private ConcurrentLinkedQueue<IProtocolHandler> handlerQueue;
private boolean running = true;
public WorkerQueue(int nThreads) {
this.handlerQueue = new ConcurrentLinkedQueue<IProtocolHandler>();
this.nThreads = nThreads;
this.threads = new Worker[nThreads];
}
public void execute(IProtocolHandler h) {
synchronized (handlerQueue) {
handlerQueue.add(h);
handlerQueue.notify();
}
}
public void start() {
running = true;
for (int i = 0; i < nThreads; i++) {
threads[i] = new Worker(handlerQueue);
threads[i].start();
}
}
public void stop() {
running = false;
handlerQueue.clear();
}
private class Worker extends Thread {
private ConcurrentLinkedQueue<IProtocolHandler> handlerQueue;
public Worker(ConcurrentLinkedQueue<IProtocolHandler> handlerQueue) {
this.handlerQueue = handlerQueue;
}
public void run() {
while (running) {
IProtocolHandler handler;
synchronized (handlerQueue) {
while (handlerQueue.isEmpty()) {
try {
handlerQueue.wait();
} catch (InterruptedException ignored) {
}
}
handler = handlerQueue.poll();
}
try {
handler.run();
} catch (RuntimeException e) {
e.printStackTrace();
}
if (handler.isKeepAlive()) {
synchronized (handlerQueue) {
handlerQueue.add(handler);
handlerQueue.notify();
}
}
}
}
}
} | Java |
package com.ams.server;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
public class Main {
public static void main(String[] args) {
System.setSecurityManager(null);
DaemonThread daemon = null;
try {
daemon = new DaemonThread();
} catch (IOException e) {
e.printStackTrace();
}
if (daemon != null) {
daemon.start();
}
// send control command to daemon thread
String cmd = args.length == 1 ? args[0] : "start";
if ("start".equalsIgnoreCase(cmd) ||
"stop".equalsIgnoreCase(cmd) ||
"restart".equalsIgnoreCase(cmd)) {
try{
Socket socket = new Socket("127.0.0.1", 5555);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println(cmd);
out.close();
socket.close();
} catch(Exception e){
e.printStackTrace();
}
}
}
}
| Java |
package com.ams.server;
import java.io.IOException;
import java.nio.channels.Selector;
import com.ams.util.ObjectPool;
public final class SelectorFactory extends ObjectPool<Selector> {
private static SelectorFactory instance = null;
public static int poolSize = 16;
public SelectorFactory() {
super();
grow(poolSize);
}
public static synchronized SelectorFactory getInstance() {
if (instance == null) {
instance = new SelectorFactory();
}
return instance;
}
public void free(Selector selector) {
recycle(selector);
}
protected void assemble(Selector obj) {
}
protected void dispose(Selector obj) {
try {
obj.selectNow();
} catch (IOException e) {
}
}
protected Selector newInstance() {
Selector selector = null;
try {
selector = Selector.open();
} catch (IOException e) {
}
return selector;
}
}
| Java |
package com.ams.server;
import java.nio.ByteBuffer;
public final class ByteBufferFactory {
private static ByteBufferAllocator allocator = new ByteBufferAllocator();
public static ByteBuffer allocate(int size) {
return allocator.allocate(size);
}
public static void setPageSize(int pageSize) {
allocator.setPageSize(pageSize);
allocator.init();
}
}
| Java |
package com.ams.server;
import java.io.*;
import java.net.SocketAddress;
import java.nio.channels.*;
import java.util.ArrayList;
import java.util.Iterator;
import com.ams.util.Log;
public class SocketAcceptor implements IAcceptor {
private SocketAddress listenEndpoint;
private SocketProperties socketProperties = null;
private ServerSocketChannel serverChannel;
private Selector selector;
private ArrayList<Dispatcher> dispatchers;
private int nextDispatcher = 0;
private boolean running = true;
private ConnectionListner listner;
public SocketAcceptor(SocketAddress host) throws IOException {
serverChannel = ServerSocketChannel.open();
listenEndpoint = host;
serverChannel.socket().bind(host);
serverChannel.configureBlocking(false);
selector = SelectorFactory.getInstance().get();
serverChannel.register(selector, SelectionKey.OP_ACCEPT);
}
public void run() {
int selectedKeys = 0;
while (running) {
try {
selectedKeys = selector.select();
} catch (Exception e) {
if (selector.isOpen()) {
continue;
} else {
Log.logger.warning(e.getMessage());
try {
SelectorFactory.getInstance().free(selector);
selector = SelectorFactory.getInstance().get();
serverChannel
.register(selector, SelectionKey.OP_ACCEPT);
} catch (Exception e1) {
}
;
}
}
if (selectedKeys == 0) {
continue;
}
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
while (it.hasNext()) {
SelectionKey key = it.next();
it.remove();
if (!key.isValid()) {
continue;
}
try {
ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();
SocketChannel channel = serverChannel.accept();
if (socketProperties != null) {
socketProperties.setSocketProperties(channel.socket());
}
if (dispatchers != null) {
Dispatcher dispatcher = dispatchers.get(nextDispatcher++);
SocketConnector connector = new SocketConnector(channel);
connector.addListner(listner);
dispatcher.addChannelToRegister(new ChannelInterestOps(channel, SelectionKey.OP_READ, connector));
if (nextDispatcher >= dispatchers.size()) {
nextDispatcher = 0;
}
}
} catch (Exception e) {
key.cancel();
Log.logger.warning(e.getMessage());
}
}
}
try {
serverChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void setSocketProperties(SocketProperties socketProperties) {
this.socketProperties = socketProperties;
}
public void setDispatchers(ArrayList<Dispatcher> dispatchers) {
this.dispatchers = dispatchers;
}
public SocketAddress getListenEndpoint() {
return this.listenEndpoint;
}
public void stop() {
running = false;
}
public void start() {
running = true;
}
public void setConnectionListner(ConnectionListner listner) {
this.listner = listner;
}
}
| Java |
package com.ams.util;
import java.util.concurrent.ConcurrentLinkedQueue;
public abstract class ObjectPool<T> {
protected ConcurrentLinkedQueue<T> pool = new ConcurrentLinkedQueue<T>();
protected abstract void assemble(T obj);
protected abstract void dispose(T obj);
protected abstract T newInstance();
public void grow(int size) {
for (int i = 0; i < size; i++) {
T obj = newInstance();
if (obj != null) {
pool.offer(obj);
}
}
}
public boolean recycle(T obj) {
if (obj != null) {
dispose(obj);
return pool.offer(obj);
} else {
return false;
}
}
public T get() {
T obj = pool.poll();
if (obj == null) {
obj = newInstance();
}
assemble(obj);
return obj;
}
}
| Java |
package com.ams.util;
import java.io.EOFException;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import com.ams.amf.AmfException;
import com.ams.amf.AmfNull;
import com.ams.amf.AmfValue;
import com.ams.rtmp.message.RtmpMessage;
import com.ams.rtmp.message.RtmpMessageCommand;
import com.ams.rtmp.net.FlvPlayer;
import com.ams.rtmp.net.NetStream;
import com.ams.rtmp.RtmpConnection;
import com.ams.rtmp.RtmpException;
import com.ams.rtmp.RtmpHandShake;
import com.ams.server.SocketConnector;
public class RtmpClient implements Runnable {
private String fileName;
private SocketConnector conn;
private RtmpConnection rtmp;
private RtmpHandShake handshake;
private FlvPlayer player;
private final static int CMD_CONNECT = 1;
private final static int CMD_CREATE_STREAM = 2;
private final static int CMD_PUBLISH = 3;
private final static int TANSACTION_ID_CONNECT = 1;
private final static int TANSACTION_ID_CREATE_STREAM = 2;
private final static int TANSACTION_ID_PUBLISH = 3;
private final static int CHANNEL_RTMP_COMMAND = 3;
private final static int CHANNEL_RTMP_PUBLISH = 7;
private LinkedList<Integer> commands = new LinkedList<Integer>();
int streamId = 0;
String publishName;
String errorMsg;
public RtmpClient(String fileName, String publishName, String host, int port) throws IOException {
this.fileName = fileName;
this.publishName = publishName;
conn = new SocketConnector();
conn.connect(host, port);
rtmp = new RtmpConnection(conn);
handshake = new RtmpHandShake(rtmp);
}
private void readResponse() throws IOException, AmfException, RtmpException {
// waiting for data arriving
conn.waitDataReceived(100);
rtmp.readRtmpMessage();
if (!rtmp.isRtmpMessageReady()) return;
RtmpMessage message = rtmp.getCurrentMessage();
if (!(message instanceof RtmpMessageCommand)) return;
RtmpMessageCommand msg = (RtmpMessageCommand)message;
switch (msg.getTransactionId()) {
case TANSACTION_ID_CONNECT:
boolean isConnected = connectResult(msg);
if (isConnected) {
commands.add(CMD_CREATE_STREAM);
Log.logger.info("rtmp connected.");
} else {
Log.logger.info(errorMsg);
}
break;
case TANSACTION_ID_CREATE_STREAM:
streamId = createStreamResult(msg);
if (streamId > 0) {
commands.add(CMD_PUBLISH);
Log.logger.info("rtmp stream created.");
}
break;
case TANSACTION_ID_PUBLISH:
String publishName = publishResult(msg);
if (publishName != null) {
NetStream stream = new NetStream(rtmp, streamId);
stream.setChunkStreamId(CHANNEL_RTMP_PUBLISH);
player = new FlvPlayer(fileName, stream);
player.seek(0);
Log.logger.info("rtmp stream published.");
} else {
Log.logger.info(errorMsg);
}
break;
}
}
private void connect() throws IOException {
HashMap<String, AmfValue> value = new HashMap<String, AmfValue>();
value.put("app", new AmfValue(""));
AmfValue[] args = {new AmfValue(value)};
RtmpMessage message = new RtmpMessageCommand("connect", TANSACTION_ID_CONNECT, args);
rtmp.writeRtmpMessage(CHANNEL_RTMP_COMMAND, 0, System.currentTimeMillis(), message);
}
private boolean connectResult(RtmpMessageCommand msg) {
if ("_result".equals(msg.getName())) {
AmfValue[] args = msg.getArgs();
HashMap<String, AmfValue> result = args[1].object();
if ("NetConnection.Connect.Success".equals(result.get("code").string())) {
return true;
}
}
if ("onStatus".equals(msg.getName())) {
errorMsg = "";
AmfValue[] args = msg.getArgs();
HashMap<String, AmfValue> result = args[1].object();
if ("NetConnection.Error".equals(result.get("code").string())) {
errorMsg = result.get("details").string();
}
}
return false;
}
private void createStream() throws IOException {
AmfValue[] args = {new AmfNull()};
RtmpMessage message = new RtmpMessageCommand("createStream", TANSACTION_ID_CREATE_STREAM, args);
rtmp.writeRtmpMessage(CHANNEL_RTMP_COMMAND, 0, System.currentTimeMillis(), message);
}
private int createStreamResult(RtmpMessageCommand msg) {
int streamId = -1;
if ("_result".equals(msg.getName())) {
AmfValue[] args = msg.getArgs();
streamId = args[1].integer();
}
return streamId;
}
private void publish(String publishName, int streamId) throws IOException {
AmfValue[] args = {new AmfNull(), new AmfValue(publishName), new AmfValue("live")};
RtmpMessage message = new RtmpMessageCommand("publish", TANSACTION_ID_PUBLISH, args);
rtmp.writeRtmpMessage(CHANNEL_RTMP_PUBLISH, streamId, System.currentTimeMillis(), message);
}
private String publishResult(RtmpMessageCommand msg) {
errorMsg = "";
if ("onStatus".equals(msg.getName())) {
AmfValue[] args = msg.getArgs();
HashMap<String, AmfValue> result = args[1].object();
String level = result.get("level").string();
if ("status".equals(level)) {
String publishName = result.get("details").string();
return publishName;
} else {
errorMsg = result.get("details").string();
}
}
return null;
}
private void closeStream(int streamId) throws IOException {
AmfValue[] args = {new AmfNull()};
RtmpMessage message = new RtmpMessageCommand("closeStream", 0, args);
rtmp.writeRtmpMessage(CHANNEL_RTMP_COMMAND, streamId, System.currentTimeMillis(), message);
}
public void run() {
commands.add(CMD_CONNECT);
while (true) {
try {
if (!handshake.isHandshakeDone()) {
handshake.doClientHandshake();
} else {
Integer cmd = commands.poll();
if (cmd != null) {
switch(cmd) {
case CMD_CONNECT: connect();break;
case CMD_CREATE_STREAM: createStream();break;
case CMD_PUBLISH: publish(publishName, streamId);break;
}
}
if (player != null) {
player.play();
}
readResponse();
}
// write to socket channel
conn.flush();
} catch (EOFException e) {
Log.logger.warning("publish end");
break;
} catch (IOException e) {
e.printStackTrace();
Log.logger.warning(e.toString());
break;
} catch (AmfException e) {
e.printStackTrace();
} catch (RtmpException e) {
e.printStackTrace();
}
}
try {
closeStream(streamId);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
if (args.length < 2) {
System.out.println("RtmpClient.main fileName publishName host [port]");
return;
}
String fileName = args[0];
String publishName = args[1];
String host = args[2];
int port;
if (args.length == 4)
port = Integer.parseInt(args[3]);
else
port = 1935;
RtmpClient client;
try {
client = new RtmpClient(fileName, publishName, host, port);
client.run();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| Java |
package com.ams.util;
import java.util.Iterator;
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 (!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);
}
}
| Java |
package com.ams.util;
import java.util.logging.*;
public final class Log {
public static final Logger logger = Logger.getLogger(Log.class.getName());
static {
try {
FileHandler handle = new FileHandler("ams_%g.log", 100 * 1024, 10,
true);
handle.setFormatter(new SimpleFormatter());
logger.addHandler(handle);
logger.setLevel(Level.ALL);
} catch (Exception e) {
e.printStackTrace();
}
}
}
| Java |
package com.ams.util;
import java.nio.ByteBuffer;
public final class ByteBufferHelper {
public static boolean hasRemaining(ByteBuffer[] buffers) {
boolean hasRemaining = false;
if (buffers != null) {
for (ByteBuffer buf : buffers) {
if (buf.hasRemaining()) {
hasRemaining = true;
break;
}
}
}
return hasRemaining;
}
public static int size(ByteBuffer[] buffers) {
int dataSize = 0;
for(ByteBuffer buf : buffers) {
dataSize += buf.remaining();
}
return dataSize;
}
public static ByteBuffer[] duplicate(ByteBuffer[] buffers) {
if (buffers == null) {
return null;
}
ByteBuffer[] bufferDup = new ByteBuffer[buffers.length];
for(int i =0 ; i < bufferDup.length; i++) {
bufferDup[i] = buffers[i].duplicate();
}
return bufferDup;
}
public static ByteBuffer cut(ByteBuffer buffer, int length) {
ByteBuffer slice = buffer.slice();
slice.limit(length);
buffer.position(buffer.position() + length);
return slice;
}
}
| Java |
package com.ams.config;
import com.ams.server.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 slabPageSize = 10 * 1024 * 1024;
private int dispatcherThreadPoolSize = 8;
private int workerThreadPoolSize = 16;
private String httpHost = "0.0.0.0";
private int httpPort = 80;
private String httpContextRoot = "www";
private String rtmpHost = "0.0.0.0";
private int rtmpPort = 1935;
private String rtmpContextRoot = "video";
private String replicationHost = null;
private int replicationPort = 1936;
private String[] replicationSlaves = null;
private String multicastHost = null;
private int multicastPort = 5000;
private String multicastGroup = "239.0.0.0";
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 host = prop.getProperty("http.host");
if (host != null) {
httpHost = host;
}
String portProp = prop.getProperty("http.port");
if (portProp != null) {
httpPort = Integer.parseInt(portProp);
}
String root = prop.getProperty("http.root");
if (root != null) {
httpContextRoot = root;
}
host = prop.getProperty("rtmp.host");
if (host != null) {
rtmpHost = host;
}
portProp = prop.getProperty("rtmp.port");
if (portProp != null) {
rtmpPort = Integer.parseInt(portProp);
}
root = prop.getProperty("rtmp.root");
if (root != null) {
rtmpContextRoot = root;
}
host = prop.getProperty("replication.host");
if (host != null) {
replicationHost = host;
}
portProp = prop.getProperty("replication.port");
if (portProp != null) {
replicationPort = Integer.parseInt(portProp);
}
String slavesProp = prop.getProperty("replication.slaves");
if (slavesProp != null) {
replicationSlaves = slavesProp.split(",");
}
host = prop.getProperty("replication.multicast.host");
if (host != null) {
multicastHost = host;
}
portProp = prop.getProperty("replication..multicast.port");
if (portProp != null) {
multicastPort = Integer.parseInt(portProp);
}
host = prop.getProperty("replication.multicast.group");
if (host != null) {
multicastGroup = host;
}
} catch (FileNotFoundException e) {
throw e;
} catch (IOException e) {
result = false;
}
return result;
}
public int getSlabPageSize() {
return slabPageSize;
}
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 SocketProperties getSocketProperties() {
return socketProperties;
}
public String getReplicationHost() {
return replicationHost;
}
public int getReplicationPort() {
return replicationPort;
}
public String[] getReplicationSlaves() {
return replicationSlaves;
}
public String getMulticastHost() {
return multicastHost;
}
public int getMulticastPort() {
return multicastPort;
}
public String getMulticastGroup() {
return multicastGroup;
}
}
| Java |
package com.ams.rtmp;
import java.io.IOException;
import java.util.Arrays;
import java.util.Random;
import com.ams.io.ByteBufferInputStream;
import com.ams.io.ByteBufferOutputStream;
import com.ams.server.Connector;
public class RtmpHandShake {
private final static int HANDSHAKE_SIZE = 0x600;
private final static int STATE_UNINIT = 0;
private final static int STATE_VERSION_SENT = 1;
private final static int STATE_ACK_SENT = 2;
private final static int STATE_HANDSHAKE_DONE = 3;
private int state = STATE_UNINIT;
private long handShakeTime;
private long handShakeTime2;
private byte[] handShake;
private Connector conn;
private ByteBufferInputStream in;
private ByteBufferOutputStream out;
public RtmpHandShake(RtmpConnection rtmp) {
this.conn = rtmp.getConnector();
this.in = conn.getInputStream();
this.out = conn.getOutputStream();
}
private void readVersion() throws IOException, RtmpException {
if( (in.readByte() & 0xFF) != 3 ) //version
throw new RtmpException("Invalid Welcome");
}
private void writeVersion() throws IOException {
out.writeByte(3);
}
private void writeHandshake() throws IOException {
out.write32Bit(0);
out.write32Bit(0);
handShake = new byte[HANDSHAKE_SIZE - 8];
Random rnd = new Random();
rnd.nextBytes(handShake);
out.write(handShake, 0, handShake.length);
}
private byte[] readHandshake() throws IOException {
handShakeTime = in.read32Bit();
handShakeTime2 = in.read32Bit();
byte[] b = new byte[HANDSHAKE_SIZE - 8];
in.read(b, 0, b.length);
return b;
}
private void writeHandshake(byte[] b) throws IOException {
out.write32Bit(handShakeTime); // TODO, time
out.write32Bit(handShakeTime2); // TODO, time2
out.write(b, 0, b.length);
}
public boolean doClientHandshake() throws IOException, RtmpException {
boolean stateChanged = false;
long available = conn.available();
switch( state ) {
case STATE_UNINIT:
writeVersion(); //write C0 message
writeHandshake(); //write c1 message
state = STATE_VERSION_SENT;
stateChanged = true;
break;
case STATE_VERSION_SENT:
if( available < 1 + HANDSHAKE_SIZE ) break;
readVersion(); //read S0 message
byte[] hs1 = readHandshake(); //read S1 message
writeHandshake(hs1); //write C2 message
state = STATE_ACK_SENT;
stateChanged = true;
break;
case STATE_ACK_SENT:
if(available < HANDSHAKE_SIZE) break;
byte[] hs2 = readHandshake(); //read S2 message
if(!Arrays.equals(handShake, hs2)) {
throw new RtmpException("Invalid Handshake");
}
state = STATE_HANDSHAKE_DONE;
stateChanged = true;
break;
}
return stateChanged;
}
public void doServerHandshake() throws IOException, RtmpException {
long available = conn.available();
switch( state ) {
case STATE_UNINIT:
if( available < 1 ) break;
readVersion(); //read C0 message
writeVersion(); //write S0 message
writeHandshake(); //write S1 message
state = STATE_VERSION_SENT;
break;
case STATE_VERSION_SENT:
if( available < HANDSHAKE_SIZE ) break;
byte[] hs1 = readHandshake(); //read C1 message
writeHandshake(hs1); //write S2 message
state = STATE_ACK_SENT;
break;
case STATE_ACK_SENT:
if(available < HANDSHAKE_SIZE) break;
byte[] hs2 = readHandshake(); //read C2 message
if(!Arrays.equals(handShake, hs2)) {
throw new RtmpException("Invalid Handshake");
}
state = STATE_HANDSHAKE_DONE;
break;
}
}
public boolean isHandshakeDone() {
return (state == STATE_HANDSHAKE_DONE);
}
}
| Java |
package com.ams.rtmp;
import java.io.IOException;
import com.ams.io.ByteBufferOutputStream;
public class RtmpHeaderSerializer {
private ByteBufferOutputStream out;
public RtmpHeaderSerializer(ByteBufferOutputStream out) {
super();
this.out = out;
}
public void write( RtmpHeader header) throws IOException {
int fmt;
if( header.getStreamId() != -1 )
fmt = 0;
else if( header.getType() != -1 )
fmt = 1;
else if( header.getTimestamp() != -1 )
fmt = 2;
else
fmt = 3;
// write Chunk Basic Header
int chunkStreamId = header.getChunkStreamId();
if (chunkStreamId >=2 && chunkStreamId <= 63 ) { // 1 byte version
out.writeByte(fmt << 6 | chunkStreamId); // csid = 2 indicates Protocol Control Messages
} else if (chunkStreamId >=64 && chunkStreamId <= 319 ) { // 2 byte version
out.writeByte(fmt << 6 | 0 );
out.writeByte(chunkStreamId - 64);
} else { // 3 byte version
out.writeByte(fmt << 6 | 1 );
int h = chunkStreamId - 64;
out.write16BitLittleEndian(h);
}
if(fmt == 0 || fmt == 1 || fmt == 2) { // type 0, type 1, type 2 header
long ts = header.getTimestamp();
if (ts >= 0x00FFFFFF) ts = 0x00FFFFFF; // send extended time stamp
out.write24Bit((int)ts);
}
if(fmt == 0 || fmt == 1) { // type 0, type 1 header
int size = header.getSize();
out.write24Bit(size);
out.writeByte(header.getType());
}
if(fmt == 0) { // type 0 header
int streamId = header.getStreamId();
out.write32BitLittleEndian(streamId);
}
if(fmt == 3) { // type 3 header
}
// write extended time stamp
long ts = header.getTimestamp();
if ((fmt ==0 || fmt == 1 || fmt == 2) && ts >= 0x00FFFFFF ) {
out.write32Bit(ts);
}
}
}
| Java |
package com.ams.rtmp.message;
public class RtmpMessageWindowAckSize extends RtmpMessage {
private int size;
public RtmpMessageWindowAckSize(int size) {
super(MESSAGE_WINDOW_ACK_SIZE);
this.size = size;
}
public int getSize() {
return size;
}
}
| Java |
package com.ams.rtmp.message;
import com.ams.amf.AmfValue;
public class RtmpMessageCommand extends RtmpMessage {
private String name;
private int transactionId;
private AmfValue[] args;
public RtmpMessageCommand(String name, int transactionId, AmfValue[] args) {
super(MESSAGE_AMF0_COMMAND);
this.name = name;
this.transactionId = transactionId;
this.args = args;
}
public AmfValue[] getArgs() {
return args;
}
public AmfValue getCommandObject() {
return args[0];
}
public int getTransactionId() {
return transactionId;
}
public String getName() {
return name;
}
}
| Java |
package com.ams.rtmp.message;
public class RtmpMessageAbort extends RtmpMessage {
private int streamId;
public RtmpMessageAbort(int streamId) {
super(MESSAGE_ABORT);
this.streamId = streamId;
}
public int getStreamId() {
return streamId;
}
}
| Java |
package com.ams.rtmp.message;
public class RtmpMessageChunkSize extends RtmpMessage {
private int chunkSize;
public RtmpMessageChunkSize(int chunkSize) {
super(MESSAGE_CHUNK_SIZE);
this.chunkSize = chunkSize;
}
public int getChunkSize() {
return chunkSize;
}
}
| Java |
package com.ams.rtmp.message;
import java.nio.ByteBuffer;
public class RtmpMessageUnknown extends RtmpMessage {
private int messageType;
private ByteBuffer[] data;
public RtmpMessageUnknown(int type, ByteBuffer[] data) {
super(MESSAGE_UNKNOWN);
this.messageType = type;
this.data = data;
}
public int getMessageType() {
return messageType;
}
public ByteBuffer[] getData() {
return data;
}
}
| Java |
package com.ams.rtmp.message;
public class RtmpMessagePeerBandwidth extends RtmpMessage {
private int windowAckSize;
private byte limitType;
public RtmpMessagePeerBandwidth(int windowAckSize, byte limitTypemitType) {
super(MESSAGE_PEER_BANDWIDTH);
this.windowAckSize = windowAckSize;
this.limitType = limitTypemitType;
}
public int getWindowAckSize() {
return windowAckSize;
}
public byte getLimitType() {
return limitType;
}
}
| Java |
package com.ams.rtmp.message;
import java.nio.ByteBuffer;
import com.ams.util.ByteBufferHelper;
public class RtmpMessageAudio extends RtmpMessage {
private ByteBuffer[] data;
public RtmpMessageAudio(ByteBuffer[] data) {
super(MESSAGE_AUDIO);
this.data = data;
}
public ByteBuffer[] getData() {
return ByteBufferHelper.duplicate(data);
}
}
| Java |
package com.ams.rtmp.message;
import com.ams.so.SoMessage;
public class RtmpMessageSharedObject extends RtmpMessage {
private SoMessage data;
public RtmpMessageSharedObject(SoMessage data) {
super(MESSAGE_SHARED_OBJECT);
this.data = data;
}
public SoMessage getData() {
return data;
}
}
| Java |
package com.ams.rtmp.message;
public class RtmpMessageAck extends RtmpMessage {
private int bytes;
public RtmpMessageAck(int bytes) {
super(MESSAGE_ACK);
this.bytes = bytes;
}
public int getBytes() {
return bytes;
}
}
| Java |
package com.ams.rtmp.message;
public class RtmpMessage {
/*
01 Protocol control message 1, Set Chunk Size
02 Protocol control message 2, Abort Message
03 Protocol control message 3, Acknowledgement
04 Protocol control message 4, User Control Message
05 Protocol control message 5, Window Acknowledgement Size
06 Protocol control message 6, Set Peer Bandwidth
07 Protocol control message 7, used between edge server and origin server
08 Audio Data packet containing audio
09 Video Data packet containing video data
0F AMF3 data message
11 AMF3 command message
12 AMF0 data message
13 Shared Object has subtypes
14 AMF0 command message
16 Aggregate message
[FMS3] Set of one or more FLV tags, as documented on the Flash Video (FLV) page.
Each tag will have an 11 byte header -
[1 byte Type][3 bytes Size][3 bytes Timestamp][1 byte timestamp extention][3 bytes streamID],
followed by the body, followed by a 4 byte footer containing the size of the body.
*/
public final static int MESSAGE_CHUNK_SIZE = 0x01;
public final static int MESSAGE_ABORT = 0x02;
public final static int MESSAGE_ACK = 0x03;
public final static int MESSAGE_USER_CONTROL = 0x04;
public final static int MESSAGE_WINDOW_ACK_SIZE = 0x05;
public final static int MESSAGE_PEER_BANDWIDTH = 0x06;
public final static int MESSAGE_AUDIO = 0x08;
public final static int MESSAGE_VIDEO = 0x09;
public final static int MESSAGE_AMF3_DATA = 0x0F;
public final static int MESSAGE_AMF3_COMMAND = 0x11;
public final static int MESSAGE_AMF0_DATA = 0x12;
public final static int MESSAGE_AMF0_COMMAND = 0x14;
public final static int MESSAGE_SHARED_OBJECT = 0x13;
public final static int MESSAGE_AGGREGATE = 0x16;
public final static int MESSAGE_UNKNOWN = 0xFF;
protected int type = 0;
public RtmpMessage(int type) {
this.type = type;
}
public int getType() {
return type;
}
}
| Java |
package com.ams.rtmp.message;
import java.nio.ByteBuffer;
import com.ams.util.ByteBufferHelper;
public class RtmpMessageData extends RtmpMessage {
private ByteBuffer[] data;
public RtmpMessageData(ByteBuffer[] data) {
super(MESSAGE_AMF0_DATA);
this.data = data;
}
public ByteBuffer[] getData() {
return ByteBufferHelper.duplicate(data);
}
}
| Java |
package com.ams.rtmp.message;
import java.nio.ByteBuffer;
import com.ams.util.ByteBufferHelper;
public class RtmpMessageVideo extends RtmpMessage {
private ByteBuffer[] data;
public RtmpMessageVideo(ByteBuffer[] data) {
super(MESSAGE_VIDEO);
this.data = data;
}
public ByteBuffer[] getData() {
return ByteBufferHelper.duplicate(data);
}
}
| Java |
package com.ams.rtmp.message;
public class RtmpMessageUserControl extends RtmpMessage {
public final static int EVT_STREAM_BEGIN = 0;
public final static int EVT_STREAM_EOF = 1;
public final static int EVT_STREAM_DRY = 2;
public final static int EVT_SET_BUFFER_LENGTH = 3;
public final static int EVT_STREAM_IS_RECORDED = 4;
public final static int EVT_PING_REQUEST = 6;
public final static int EVT_PING_RESPONSE = 7;
public final static int EVT_UNKNOW = 0xFF;
private int event;
private int streamId = -1;
private int timestamp = -1;
public RtmpMessageUserControl(int event, int streamId, int timestamp) {
super(MESSAGE_USER_CONTROL);
this.event = event;
this.streamId = streamId;
this.timestamp = timestamp;
}
public RtmpMessageUserControl(int event, int streamId ) {
super(MESSAGE_USER_CONTROL);
this.event = event;
this.streamId = streamId;
}
public int getStreamId() {
return streamId;
}
public int getEvent() {
return event;
}
public int getTimestamp() {
return timestamp;
}
}
| Java |
package com.ams.rtmp;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import com.ams.io.ByteBufferInputStream;
class RtmpChunkData {
private RtmpHeader header;
private ArrayList<ByteBuffer> chunkData = new ArrayList<ByteBuffer>();
private int chunkSize;
public RtmpChunkData(RtmpHeader header) {
this.header = header;
this.chunkSize = header.getSize();
}
public void read(ByteBufferInputStream in, int length) throws IOException {
ByteBuffer[] buffers = in.readByteBuffer(length);
if (buffers != null) {
for (ByteBuffer buffer : buffers) {
chunkData.add(buffer);
}
}
chunkSize -= length;
}
public ByteBuffer[] getChunkData() {
return chunkData.toArray(new ByteBuffer[chunkData.size()]);
}
public int getRemainBytes() {
return chunkSize;
}
public RtmpHeader getHeader() {
return header;
}
}
| Java |
package com.ams.rtmp;
import java.io.DataInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import com.ams.amf.Amf0Deserializer;
import com.ams.amf.Amf3Deserializer;
import com.ams.amf.AmfException;
import com.ams.amf.AmfSwitchToAmf3Exception;
import com.ams.amf.AmfValue;
import com.ams.io.ByteBufferInputStream;
import com.ams.rtmp.message.RtmpMessage;
import com.ams.rtmp.message.RtmpMessageAbort;
import com.ams.rtmp.message.RtmpMessageAck;
import com.ams.rtmp.message.RtmpMessageAudio;
import com.ams.rtmp.message.RtmpMessageChunkSize;
import com.ams.rtmp.message.RtmpMessageCommand;
import com.ams.rtmp.message.RtmpMessageData;
import com.ams.rtmp.message.RtmpMessagePeerBandwidth;
import com.ams.rtmp.message.RtmpMessageSharedObject;
import com.ams.rtmp.message.RtmpMessageUnknown;
import com.ams.rtmp.message.RtmpMessageUserControl;
import com.ams.rtmp.message.RtmpMessageVideo;
import com.ams.rtmp.message.RtmpMessageWindowAckSize;
import com.ams.so.SoMessage;
public class RtmpMessageDeserializer {
private int readChunkSize = 128;
protected HashMap<Integer, RtmpChunkData> chunkDataMap;
protected ByteBufferInputStream in;
public RtmpMessageDeserializer(ByteBufferInputStream in) {
super();
this.in = in;
this.chunkDataMap = new HashMap<Integer, RtmpChunkData>();
}
public RtmpMessage read(RtmpHeader header) throws IOException, AmfException, RtmpException {
int chunkStreamId = header.getChunkStreamId();
RtmpChunkData chunkData = chunkDataMap.get(chunkStreamId);
if( chunkData == null ) {
chunkData = new RtmpChunkData(header);
int remain = chunkData.getRemainBytes();
if( header.getSize() <= readChunkSize ) {
chunkData.read(in, remain);
return parseChunkData(chunkData);
}
// continue to read
chunkData.read(in, readChunkSize);
chunkDataMap.put(chunkStreamId, chunkData);
} else {
int remain = chunkData.getRemainBytes();
if(remain <= readChunkSize) {
chunkData.read(in, remain);
chunkDataMap.remove(chunkStreamId);
return parseChunkData(chunkData);
}
chunkData.read(in, readChunkSize);
}
return null;
}
private RtmpMessage parseChunkData(RtmpChunkData chunk) throws IOException, AmfException, RtmpException {
RtmpHeader header = chunk.getHeader();
ByteBuffer[] data = chunk.getChunkData();
ByteBufferInputStream bis = new ByteBufferInputStream(data);
switch(header.getType()) {
case RtmpMessage.MESSAGE_USER_CONTROL:
int event = bis.read16Bit();
int streamId = -1;
int timestamp = -1;
switch(event) {
case RtmpMessageUserControl.EVT_STREAM_BEGIN:
case RtmpMessageUserControl.EVT_STREAM_EOF:
case RtmpMessageUserControl.EVT_STREAM_DRY:
case RtmpMessageUserControl.EVT_STREAM_IS_RECORDED:
streamId = (int)bis.read32Bit();
break;
case RtmpMessageUserControl.EVT_SET_BUFFER_LENGTH:
streamId = (int)bis.read32Bit();
timestamp = (int)bis.read32Bit(); // buffer length
break;
case RtmpMessageUserControl.EVT_PING_REQUEST:
case RtmpMessageUserControl.EVT_PING_RESPONSE:
timestamp = (int)bis.read32Bit(); // timestamp
break;
default:
event = RtmpMessageUserControl.EVT_UNKNOW;
}
return new RtmpMessageUserControl(event, streamId, timestamp);
case RtmpMessage.MESSAGE_AMF3_COMMAND:
bis.readByte(); // no used byte, continue to amf0 parsing
case RtmpMessage.MESSAGE_AMF0_COMMAND:
{
DataInputStream dis = new DataInputStream(bis);
Amf0Deserializer amf0Deserializer = new Amf0Deserializer(dis);
Amf3Deserializer amf3Deserializer = new Amf3Deserializer(dis);
String name = amf0Deserializer.read().string();
int transactionId = amf0Deserializer.read().integer();
ArrayList<AmfValue> argArray = new ArrayList<AmfValue>();
boolean amf3Object = false;
while(true) {
try {
if (amf3Object) {
argArray.add(amf3Deserializer.read());
} else {
argArray.add(amf0Deserializer.read());
}
} catch (AmfSwitchToAmf3Exception e){
amf3Object = true;
}
catch(IOException e) {
break;
}
}
AmfValue[] args = new AmfValue[argArray.size()];
argArray.toArray(args);
return new RtmpMessageCommand(name, transactionId, args);
}
case RtmpMessage.MESSAGE_VIDEO:
return new RtmpMessageVideo(data);
case RtmpMessage.MESSAGE_AUDIO:
return new RtmpMessageAudio(data);
case RtmpMessage.MESSAGE_AMF0_DATA:
case RtmpMessage.MESSAGE_AMF3_DATA:
return new RtmpMessageData(data);
case RtmpMessage.MESSAGE_SHARED_OBJECT:
SoMessage so = SoMessage.read(new DataInputStream(bis));
return new RtmpMessageSharedObject(so);
case RtmpMessage.MESSAGE_CHUNK_SIZE:
readChunkSize = (int)bis.read32Bit();
return new RtmpMessageChunkSize(readChunkSize);
case RtmpMessage.MESSAGE_ABORT:
return new RtmpMessageAbort((int)bis.read32Bit());
case RtmpMessage.MESSAGE_ACK:
return new RtmpMessageAck((int)bis.read32Bit());
case RtmpMessage.MESSAGE_WINDOW_ACK_SIZE:
return new RtmpMessageWindowAckSize((int)bis.read32Bit());
case RtmpMessage.MESSAGE_PEER_BANDWIDTH:
int windowAckSize = (int)bis.read32Bit();
byte limitType = bis.readByte();
return new RtmpMessagePeerBandwidth(windowAckSize, limitType);
default:
System.out.println("UNKNOWN HEADER TYPE:" + header.getType());
return new RtmpMessageUnknown(header.getType(), data);
}
}
public int getReadChunkSize() {
return readChunkSize;
}
public void setReadChunkSize(int readChunkSize) {
this.readChunkSize = readChunkSize;
}
}
| Java |
package com.ams.rtmp;
import java.io.IOException;
import com.ams.amf.*;
import com.ams.io.*;
import com.ams.server.Connector;
import com.ams.rtmp.message.*;
public class RtmpConnection {
private Connector conn;
private ByteBufferInputStream in;
private ByteBufferOutputStream out;
private RtmpHeaderDeserializer headerDeserializer;
private RtmpMessageSerializer messageSerializer;
private RtmpMessageDeserializer messageDeserializer;
private RtmpHeader currentHeader = null;
private RtmpMessage currentMessage = null;
public RtmpConnection(Connector conn) {
this.conn = conn;
this.in = conn.getInputStream();
this.out = conn.getOutputStream();
this.headerDeserializer = new RtmpHeaderDeserializer(in);
this.messageSerializer = new RtmpMessageSerializer(out);
this.messageDeserializer = new RtmpMessageDeserializer(in);
}
public boolean readRtmpMessage() throws IOException, AmfException, RtmpException {
if (currentHeader != null && currentMessage != null) {
currentHeader = null;
currentMessage = null;
}
if (conn.available() == 0) {
return false;
}
// read header every time, a message maybe break into several chunks
if (currentHeader == null) {
currentHeader = headerDeserializer.read();
}
if (currentMessage == null) {
currentMessage = messageDeserializer.read(currentHeader);
if (currentMessage == null) {
currentHeader = null;
}
}
return isRtmpMessageReady();
}
public boolean isRtmpMessageReady() {
return (currentHeader != null && currentMessage != null);
}
public void writeRtmpMessage(int chunkStreamId, int streamId, long timestamp, RtmpMessage message) throws IOException {
messageSerializer.write(chunkStreamId, streamId, timestamp, message);
}
public void writeProtocolControlMessage(RtmpMessage message) throws IOException {
messageSerializer.write(2, 0, -1, message);
}
public Connector getConnector() {
return conn;
}
public RtmpHeader getCurrentHeader() {
return currentHeader;
}
public RtmpMessage getCurrentMessage() {
return currentMessage;
}
} | Java |
package com.ams.rtmp;
import java.io.IOException;
import java.util.HashMap;
import com.ams.io.ByteBufferInputStream;
public class RtmpHeaderDeserializer {
private HashMap<Integer, RtmpHeader> chunkHeaderMap;
private ByteBufferInputStream in;
public RtmpHeaderDeserializer(ByteBufferInputStream in) {
super();
this.in = in;
this.chunkHeaderMap = new HashMap<Integer, RtmpHeader>();
}
private RtmpHeader getLastHeader(int chunkStreamId) {
RtmpHeader h = chunkHeaderMap.get(chunkStreamId);
if( h == null ) {
h = new RtmpHeader( chunkStreamId, -1, -1, -1, -1);
chunkHeaderMap.put(chunkStreamId, h);
}
return h;
}
public RtmpHeader read() throws IOException {
int h = in.readByte() & 0xFF; // Chunk Basic Header
int chunkStreamId = h & 0x3F; // 1 byte version
if (chunkStreamId == 0) { // 2 byte version
chunkStreamId = in.readByte() & 0xFF + 64;
} else if (chunkStreamId == 1) { // 3 byte version
chunkStreamId = in.read16BitLittleEndian() + 64;
}
RtmpHeader lastHeader = getLastHeader(chunkStreamId);
int fmt = h >>> 6;
if( fmt == 0 || fmt == 1 || fmt == 2) { // type 0, type 1, type 2 header
int ts = in.read24Bit();
lastHeader.setTimestamp(ts);
}
if( fmt == 0 || fmt == 1 ) { // type 0, type 1 header
int size = in.read24Bit();
lastHeader.setSize(size);
lastHeader.setType(in.readByte() & 0xFF);
}
if( fmt == 0 ) { // type 0 header
int streamId = (int)in.read32BitLittleEndian();
lastHeader.setStreamId(streamId);
}
if(fmt == 3) { // type 3
// 0 bytes
}
// extended time stamp
if ((fmt ==0 || fmt == 1 || fmt == 2) && lastHeader.getTimestamp() == 0x00FFFFFF ) {
long ts = in.read32Bit();
lastHeader.setTimestamp(ts);
}
return new RtmpHeader( chunkStreamId,
lastHeader.getTimestamp(),
lastHeader.getSize(),
lastHeader.getType(),
lastHeader.getStreamId()
);
}
}
| Java |
package com.ams.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.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.rtmp;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import com.ams.amf.Amf0Serializer;
import com.ams.amf.AmfValue;
import com.ams.io.ByteBufferInputStream;
import com.ams.io.ByteBufferOutputStream;
import com.ams.rtmp.message.*;
import com.ams.so.SoMessage;
import com.ams.util.ByteBufferHelper;
public class RtmpMessageSerializer {
private int writeChunkSize = 128;
private ByteBufferOutputStream out;
private RtmpHeaderSerializer headerSerializer;
public RtmpMessageSerializer(ByteBufferOutputStream out) {
super();
this.out = out;
this.headerSerializer = new RtmpHeaderSerializer(out);
}
public void write(int chunkStreamId, int streamId, long timestamp, RtmpMessage message) throws IOException {
ByteBuffer[] data = null;
ByteBufferOutputStream bos = new ByteBufferOutputStream();
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;
};
data = bos.toByteBufferArray();
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; i < args.length; i++) {
serializer.write(args[i]);
}
data = bos.toByteBufferArray();
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; i < args.length; i++) {
serializer.write(args[i]);
}
data = bos.toByteBufferArray();
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);
data = bos.toByteBufferArray();
break;
case RtmpMessage.MESSAGE_CHUNK_SIZE:
int chunkSize = ((RtmpMessageChunkSize)message).getChunkSize();
bos.write32Bit(chunkSize);
data = bos.toByteBufferArray();
writeChunkSize = chunkSize;
break;
case RtmpMessage.MESSAGE_ABORT:
sid = ((RtmpMessageAbort)message).getStreamId();
bos.write32Bit(sid);
data = bos.toByteBufferArray();
break;
case RtmpMessage.MESSAGE_ACK:
int nbytes = ((RtmpMessageAck)message).getBytes();
bos.write32Bit(nbytes);
data = bos.toByteBufferArray();
break;
case RtmpMessage.MESSAGE_WINDOW_ACK_SIZE:
int size = ((RtmpMessageWindowAckSize)message).getSize();
bos.write32Bit(size);
data = bos.toByteBufferArray();
break;
case RtmpMessage.MESSAGE_PEER_BANDWIDTH:
int windowAckSize = ((RtmpMessagePeerBandwidth)message).getWindowAckSize();
byte limitType = ((RtmpMessagePeerBandwidth)message).getLimitType();
bos.write32Bit(windowAckSize);
bos.writeByte(limitType);
data = bos.toByteBufferArray();
break;
case RtmpMessage.MESSAGE_UNKNOWN:
int t = ((RtmpMessageUnknown)message).getMessageType();
data = ((RtmpMessageUnknown)message).getData();
break;
}
int dataSize = ByteBufferHelper.size(data);
RtmpHeader header = new RtmpHeader(
chunkStreamId,
(timestamp != -1)? timestamp : 0,
dataSize,
msgType,
(streamId != -1)? streamId : 0
);
// write packet header + data
headerSerializer.write(header);
ByteBufferInputStream ds = new ByteBufferInputStream(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.rtmp.net;
import java.io.IOException;
import java.util.HashMap;
import com.ams.amf.*;
import com.ams.flv.FlvException;
import com.ams.io.*;
import com.ams.rtmp.RtmpConnection;
import com.ams.rtmp.message.*;
import com.ams.event.*;
public class NetStream {
private RtmpConnection rtmp;
private int chunkStreamId = -1;
private int streamId;
private int transactionId = 0;
private StreamPublisher publisher = null;
private IPlayer player = null;
public NetStream(RtmpConnection rtmp, int streamId) {
this.rtmp = rtmp;
this.streamId = streamId;
}
public void writeMessage(long timestamp, RtmpMessage message) throws IOException {
rtmp.writeRtmpMessage(chunkStreamId, streamId, timestamp, message);
}
public void writeStatusMessage(String status, HashMap<String, AmfValue> info) throws IOException {
info.put("level", new AmfValue("status"));
info.put("code", new AmfValue(status));
AmfValue[] argsMessageCommand = { new AmfNull(), new AmfValue(info) };
rtmp.writeRtmpMessage(chunkStreamId, streamId, -1,
new RtmpMessageCommand("onStatus", transactionId, argsMessageCommand));
}
public void writeErrorMessage(String msg) throws IOException {
HashMap<String, AmfValue> value = new HashMap<String, AmfValue>();
value.put("level", new AmfValue("error"));
value.put("code", new AmfValue("NetStream.Error"));
value.put("details", new AmfValue(msg));
AmfValue[] argsMessageCommand = { new AmfNull(), new AmfValue(value) };
rtmp.writeRtmpMessage(chunkStreamId, streamId, -1,
new RtmpMessageCommand("onStatus", transactionId, argsMessageCommand));
}
public synchronized void close() throws IOException {
if(player != null) {
player.close();
}
if (publisher != null) {
publisher.close();
PublisherManager.removePublisher(publisher.getPublishName());
}
}
public boolean isWriteBlocking() {
return rtmp.getConnector().isWriteBlocking();
}
public void setChunkStreamId(int chunkStreamId) {
this.chunkStreamId = chunkStreamId;
}
public void setTransactionId(int transactionId) {
this.transactionId = transactionId;
}
public int getStreamId() {
return streamId;
}
public IPlayer getPlayer() {
return player;
}
public void setPlayer(IPlayer player) {
this.player = player;
}
public StreamPublisher getPublisher() {
return publisher;
}
public void play(NetContext context, String streamName, int start, int len) throws NetConnectionException, IOException, FlvException {
if (player != null) {
writeErrorMessage("This channel is already playing");
return;
}
// set chunk size
rtmp.writeProtocolControlMessage(new RtmpMessageChunkSize(1024));
// clear
rtmp.writeProtocolControlMessage(new RtmpMessageUserControl(RtmpMessageUserControl.EVT_STREAM_IS_RECORDED, streamId));
rtmp.writeProtocolControlMessage(new RtmpMessageUserControl(RtmpMessageUserControl.EVT_STREAM_BEGIN, streamId));
String app = context.getAttribute("app");
switch(start) {
case -1: // live only
{
StreamPublisher publisher = (StreamPublisher) PublisherManager.getPublisher(streamName);
if (publisher == null) {
writeErrorMessage("Unknown shared stream '" + streamName + "'");
return;
}
player = new StreamPlayer(this, publisher);
publisher.addSubscriber((IEventSubscriber)player);
}
break;
case -2: // first find live
{
StreamPublisher publisher = (StreamPublisher) PublisherManager.getPublisher(streamName);
if (publisher != null) {
player = new StreamPlayer(this, publisher);
publisher.addSubscriber((IEventSubscriber)player);
} else {
String file = context.getRealPath(app, streamName);
player = new FlvPlayer(file, this);
player.seek(0);
}
}
break;
default: // >= 0
String file = context.getRealPath(app, streamName);
player = new FlvPlayer(file, this);
player.seek(start);
}
HashMap<String, AmfValue> status = new HashMap<String, AmfValue>();
status.put("description", new AmfValue("Resetting " + streamName + "."));
status.put("details", new AmfValue(streamName));
status.put("clientId", new AmfValue(streamId));
writeStatusMessage("NetStream.Play.Reset", status);
status = new HashMap<String, AmfValue>();
status.put("description", new AmfValue("Start playing " + streamName + "."));
status.put("clientId", new AmfValue(streamId));
writeStatusMessage("NetStream.Play.Start", status);
}
public void seek(int offset) throws NetConnectionException, IOException, FlvException {
if (player == null) {
writeErrorMessage("Invalid 'Seek' stream id " + streamId);
return;
}
player.seek(offset);
HashMap<String, AmfValue> value = new HashMap<String, AmfValue>();
value.put("level", new AmfValue("status"));
value.put("code", new AmfValue("NetStream.Seek.Notify"));
AmfValue[] argsMessageCommand = { new AmfNull(), new AmfValue(value) };
writeMessage(-1, new RtmpMessageCommand("_result", transactionId, argsMessageCommand));
HashMap<String, AmfValue> status = new HashMap<String, AmfValue>();
status.put("time", new AmfValue(offset));
writeStatusMessage("NetStream.Play.Start", status);
}
public void pause(boolean pause, long time) throws IOException, NetConnectionException, FlvException {
if( player == null ) {
writeErrorMessage("This channel is already closed");
return;
}
player.pause(pause);
player.seek(time);
if (pause) {
rtmp.writeProtocolControlMessage(new RtmpMessageUserControl(RtmpMessageUserControl.EVT_STREAM_EOF, streamId));
}
HashMap<String, AmfValue> value = new HashMap<String, AmfValue>();
value.put("level", new AmfValue("status"));
value.put("code", new AmfValue(pause ? "NetStream.Pause.Notify" : "NetStream.Unpause.Notify"));
AmfValue[] argsMessageCommand = { new AmfNull(), new AmfValue(value) };
rtmp.writeRtmpMessage(chunkStreamId, -1, -1,
new RtmpMessageCommand("_result", transactionId, argsMessageCommand));
}
public void publish(NetContext context, String name, String type) throws NetConnectionException, IOException {
String app = context.getAttribute("app");
//save to share or file
publisher = new StreamPublisher(name);
if ("record".equals(type)) {
String file = context.getRealPath(app, name);
publisher.setRecorder(new FlvRecorder(new RandomAccessFileWriter(file, false)));
} else if ("append".equals(type)) {
String file = context.getRealPath(app, name);
publisher.setRecorder(new FlvRecorder(new RandomAccessFileWriter(file, true)));
} else if ("live".equals(type)) {
// nothing to do
}
PublisherManager.addPublisher(publisher);
HashMap<String, AmfValue> status = new HashMap<String, AmfValue>();
status.put("details", new AmfValue(name));
writeStatusMessage("NetStream.Publish.Start", status);
}
public void receiveAudio(boolean flag) throws IOException {
if (player != null) {
player.audioPlaying(flag);
}
}
public void receiveVideo(boolean flag) throws IOException {
if (player != null) {
player.videoPlaying(flag);
}
}
} | Java |
package com.ams.rtmp.net;
import java.io.IOException;
import java.nio.ByteBuffer;
import com.ams.flv.FlvHeader;
import com.ams.flv.FlvTag;
import com.ams.io.ByteBufferOutputStream;
import com.ams.io.RandomAccessFileWriter;
public class FlvRecorder {
private ByteBufferOutputStream outputStream; //record to file stream
private boolean headerWrite = false;
public FlvRecorder(RandomAccessFileWriter writer) {
super();
this.outputStream = new ByteBufferOutputStream(writer);
}
public void record(int type, ByteBuffer[] data, long time) throws IOException {
if (!headerWrite) {
FlvHeader header = new FlvHeader(true, true);
FlvHeader.write(outputStream, header);
headerWrite = true;
}
FlvTag flvTag = new FlvTag(type, data, time);
FlvTag.write(outputStream, flvTag);
outputStream.flush();
/*
if (type == FlvTag.FLV_VIDEO && Flv.isVideoKeyFrame(data)) {
// add meta tag for http pseudo streaming
HashMap<String, AmfValue> metaData = new HashMap<String, AmfValue>();
metaData.put("duration", new AmfValue((double)time / 1000));
HashMap<String, AmfValue> onMetaData = new HashMap<String, AmfValue>();
onMetaData.put("onMetaData", new AmfValue(metaData));
ByteBufferOutputStream bos = new ByteBufferOutputStream();
AmfSerializer serializer = new Amf0Serializer(new DataOutputStream(bos));
serializer.write(new AmfValue(onMetaData));
FlvTag metaTag = new FlvTag(FlvTag.FLV_META, bos.toByteBufferArray(), time);
Flv.writeFlvTag(outputStream, metaTag);
}
*/
}
public synchronized void close() {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| Java |
package com.ams.rtmp.net;
import java.io.IOException;
import java.util.concurrent.ConcurrentLinkedQueue;
import com.ams.rtmp.message.*;
import com.ams.event.Event;
import com.ams.event.IEventSubscriber;
public class StreamPlayer implements IPlayer, IEventSubscriber {
private NetStream stream;
private StreamPublisher publisher;
private long pausedTime = -1;
private boolean audioPlaying = true;
private boolean videoPlaying = true;
private ConcurrentLinkedQueue<Event> receivedEventQueue;
private static int MAX_EVENT_QUEUE_LENGTH = 100;
public StreamPlayer(NetStream stream, StreamPublisher publisher) {
this.stream = stream;
this.publisher = publisher;
this.receivedEventQueue = new ConcurrentLinkedQueue<Event>();
}
public void seek(long seekTime) throws IOException {
}
public void play() throws IOException {
Event msg;
while ((msg = receivedEventQueue.poll()) != null) {
RtmpMessage message = (RtmpMessage) msg.getEvent();
if ((message instanceof RtmpMessageAudio && audioPlaying)
|| (message instanceof RtmpMessageVideo && videoPlaying)) {
stream.writeMessage(msg.getTimestamp(), message);
}
if (stream.isWriteBlocking()) {
break;
}
}
}
public void messageNotify(Event msg) {
if (!isPaused()) {
if (receivedEventQueue.size() > MAX_EVENT_QUEUE_LENGTH) {
receivedEventQueue.clear();
}
receivedEventQueue.offer(msg);
}
}
public void pause(boolean pause) {
if (pause) {
pausedTime = System.currentTimeMillis();
} else {
pausedTime = -1;
}
}
public boolean isPaused() {
return pausedTime != -1;
}
public synchronized void close() {
receivedEventQueue.clear();
// remove from publisher
publisher.removeSubscriber(this);
}
public void audioPlaying(boolean flag) {
this.audioPlaying = flag;
}
public void videoPlaying(boolean flag) {
this.videoPlaying = flag;
}
}
| Java |
package com.ams.rtmp.net;
import com.ams.event.IEventPublisher;
import com.ams.util.ObjectCache;
public class PublisherManager {
private static int DEFAULT_EXPIRE_TIME = 24 * 60 * 60;
private static ObjectCache<IEventPublisher> streamPublishers = new ObjectCache<IEventPublisher>();
public static IEventPublisher getPublisher(String publishName) {
return streamPublishers.get(publishName);
}
public static void addPublisher(StreamPublisher publisher) {
String publishName = publisher.getPublishName();
streamPublishers.put(publishName, publisher, DEFAULT_EXPIRE_TIME);
}
public static void removePublisher(String publishName) {
streamPublishers.remove(publishName);
}
}
| Java |
package com.ams.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.rtmp.net;
import java.io.EOFException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.LinkedList;
import com.ams.flv.*;
import com.ams.io.*;
import com.ams.rtmp.message.*;
import com.ams.event.*;
public class FlvPlayer implements IPlayer{
private static int FLV_BUFFER_TIME = 5 * 1000; // 5 seconds of buffering
private NetStream stream = null;
private String fileName = null;
private ByteBufferInputStream input = null;
private long startTime = -1;
private long currentTime = 0;
private long blockedTime = -1;
private long pausedTime = -1;
private boolean audioPlaying = true;
private boolean videoPlaying = true;
private LinkedList<Event> readMsgQueue;
public FlvPlayer(String fileName, NetStream stream) {
this.fileName = fileName;
this.stream = stream;
this.readMsgQueue = new LinkedList<Event>();
}
public void close() throws IOException {
if (input != null) {
input.close();
}
input = null;
}
public void seek(long seekTime) throws IOException {
// reset infos
long now = System.currentTimeMillis();
startTime = now - FLV_BUFFER_TIME - seekTime;
if( pausedTime != -1 ) {
pausedTime = now;
}
blockedTime = -1;
// close the flv file
if( input != null ) {
input.close();
}
// open the flv file
input = new ByteBufferInputStream(new RandomAccessFileReader(fileName, 0));
readMsgQueue.clear();
try {
// prepare to send first audio + video chunk (with null time stamp)
FlvHeader flvHeader = FlvHeader.read(input);
boolean hasAudio = flvHeader.isHasAudio();
boolean hasVideo = flvHeader.isHasVideo();
// TODO seek key frame from index file
//long startPosition = 0;
//input = new RandomAccessFileInputStream(raInputFile, startPosition, raInputFile.length());
while(hasAudio || hasVideo) {
FlvTag flvTag = FlvTag.read(input);
if( flvTag == null ) {
break;
}
ByteBuffer[] data = flvTag.getData();
long time = flvTag.getTimestamp();
switch( flvTag.getTagType() ) {
case FlvTag.FLV_AUDIO:
if( time < seekTime ) {
continue;
}
if(audioPlaying) {
readMsgQueue.offer(new Event(time, new RtmpMessageAudio(data)));
}
hasAudio = false;
break;
case FlvTag.FLV_VIDEO:
if(FlvTag.isVideoKeyFrame(data)) {
readMsgQueue.clear();
}
if(videoPlaying) {
readMsgQueue.offer(new Event(time, new RtmpMessageVideo(data)));
}
if(time < seekTime) {
continue;
}
hasVideo = false;
break;
case FlvTag.FLV_META:
if(time < seekTime) {
continue;
}
readMsgQueue.offer(new Event(time, new RtmpMessageData(data)));
}
}
} catch(FlvException e) {
e.printStackTrace();
throw new IOException(e.getMessage());
}
}
public void play() throws IOException {
long now = System.currentTimeMillis();
if (input == null) {
return;
}
if (pausedTime != -1) {
return;
}
if (blockedTime != -1) {
startTime += (now - blockedTime);
blockedTime = -1;
}
while (true) {
Event msg = readMsgQueue.poll();
if (msg == null) {
break;
}
stream.writeMessage(msg.getTimestamp(), (RtmpMessage)msg.getEvent());
currentTime = msg.getTimestamp();
if( stream.isWriteBlocking() ) {
blockedTime = now;
return;
}
}
try {
long relativeTime = now - startTime;
while(relativeTime > currentTime) {
FlvTag flvTag = FlvTag.read(input);
if( flvTag == null ) { // eof
input.close();
stream.setPlayer(null);
throw new EOFException();
}
ByteBuffer[] data = flvTag.getData();
long time = flvTag.getTimestamp();
currentTime = time;
switch(flvTag.getTagType()) {
case FlvTag.FLV_AUDIO:
if(audioPlaying) {
stream.writeMessage(time, new RtmpMessageAudio(data));
}
break;
case FlvTag.FLV_VIDEO:
if(videoPlaying) {
stream.writeMessage(time, new RtmpMessageVideo(data));
}
break;
case FlvTag.FLV_META:
stream.writeMessage(time, new RtmpMessageData(data));
break;
}
if( stream.isWriteBlocking() ) {
blockedTime = now;
return;
}
}
} catch(FlvException e) {
throw new IOException(e.getMessage());
}
}
public void pause(boolean pause) {
if (pause) {
long now = System.currentTimeMillis();
if( pausedTime == -1 ) {
pausedTime = now;
}
} else {
if( pausedTime != -1 ) {
pausedTime = -1;
}
}
}
public boolean isPaused() {
return pausedTime != -1;
}
public void audioPlaying(boolean flag) {
this.audioPlaying = flag;
}
public void videoPlaying(boolean flag) {
this.videoPlaying = flag;
}
}
| Java |
package com.ams.rtmp.net;
import java.io.IOException;
public interface IPlayer {
public void seek(long seekTime) throws IOException;
public void play() throws IOException;
public void pause(boolean pause);
public boolean isPaused();
public void close() throws IOException;
public void audioPlaying(boolean flag);
public void videoPlaying(boolean flag);
}
| Java |
package com.ams.rtmp.net;
import java.io.IOException;
import java.util.HashMap;
import com.ams.amf.*;
import com.ams.flv.FlvException;
import com.ams.event.Event;
import com.ams.rtmp.message.*;
import com.ams.rtmp.*;
import com.ams.server.replicator.ReplicateCluster;
import com.ams.util.Log;
public class NetConnection {
private RtmpHandShake handshake;
private RtmpConnection rtmp;
private NetContext context;
private HashMap<Integer, NetStream> streams;
public NetConnection(RtmpConnection rtmp, NetContext context) {
this.rtmp = rtmp;
this.handshake = new RtmpHandShake(rtmp);
this.streams = new HashMap<Integer, NetStream>();
this.context = context;
}
private void onMediaMessage(RtmpHeader header, RtmpMessage message) throws NetConnectionException, IOException {
NetStream stream = streams.get(header.getStreamId());
if( stream == null ) {
throw new NetConnectionException("Unknown stream " + header.getStreamId());
}
StreamPublisher publisher = stream.getPublisher();
if( publisher == null ) {
throw new NetConnectionException("Publish not done on stream " + header.getStreamId());
}
publisher.publish(new Event(header.getTimestamp(), message));
if (publisher.isPing()) {
rtmp.writeProtocolControlMessage(new RtmpMessageAck(publisher.getBytes()));
}
// replicate to all slave server
ReplicateCluster.publishMessage(publisher.getPublishName(), new Event(header.getTimestamp(), message));
}
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();
System.out.println("command name:" + 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 ("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();
HashMap<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;
}
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()));
HashMap<String, AmfValue> value = new HashMap<String, AmfValue>();
value.put("level", new AmfValue("status"));
value.put("code", new AmfValue("NetConnection.Connect.Success"));
value.put("description", new AmfValue("Connection succeeded."));
AmfValue objectEncoding = obj.get("objectEncoding");
if (objectEncoding != null) {
value.put("objectEncoding", objectEncoding);
}
AmfValue[] argsMessageCommand = { new AmfNull(), new AmfValue(value)};
rtmp.writeRtmpMessage(header.getChunkStreamId(), -1, -1,
new RtmpMessageCommand("_result", command.getTransactionId(), argsMessageCommand));
}
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 = streams.get(header.getStreamId());
if( stream == null ) {
streamError(header.getChunkStreamId(), header.getStreamId(), command.getTransactionId(), "Invalid 'Play' stream id "+ header.getStreamId());
return;
}
stream.setChunkStreamId(header.getChunkStreamId());
stream.setTransactionId(command.getTransactionId());
stream.play(context, streamName, start, duration);
}
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 = streams.get(header.getStreamId());
if( stream == null ) {
streamError(header.getChunkStreamId(), header.getStreamId(), command.getTransactionId(), "Invalid 'Seek' stream id "+ header.getStreamId());
return;
}
stream.setTransactionId(command.getTransactionId());
stream.seek(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 = streams.get(header.getStreamId());
if( stream == null ) {
streamError(header.getChunkStreamId(), header.getStreamId(), command.getTransactionId(), "Invalid 'Pause' stream id "+ header.getStreamId());
return;
}
stream.setTransactionId(command.getTransactionId());
stream.pause(pause, time);
}
private void onPublish(RtmpHeader header, RtmpMessageCommand command) throws IOException, NetConnectionException {
AmfValue[] args = command.getArgs();
String publishName = args[1].string();
if(PublisherManager.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 = streams.get(header.getStreamId());
if( stream == null) {
streamError(header.getChunkStreamId(), header.getStreamId(), command.getTransactionId(), "Invalid 'Publish' stream id "+ header.getStreamId());
return;
}
stream.setChunkStreamId(header.getChunkStreamId());
stream.setTransactionId(command.getTransactionId());
stream.publish(context, publishName, type);
}
private void onReceiveAudio(RtmpHeader header, RtmpMessageCommand command) throws IOException {
AmfValue[] args = command.getArgs();
boolean flag = args[1].bool();
NetStream stream = streams.get(header.getStreamId());
if( stream == null) {
streamError(header.getChunkStreamId(), header.getStreamId(), command.getTransactionId(), "Invalid 'ReceiveAudio' stream id "+ header.getStreamId());
return;
}
stream.receiveAudio(flag);
}
private void onReceiveVideo(RtmpHeader header, RtmpMessageCommand command) throws IOException {
AmfValue[] args = command.getArgs();
boolean flag = args[1].bool();
NetStream stream = streams.get(header.getStreamId());
if( stream == null) {
streamError(header.getChunkStreamId(), header.getStreamId(), command.getTransactionId(), "Invalid 'ReceiveVideo' stream id "+ header.getStreamId());
return;
}
stream.receiveVideo(flag);
}
private void onCreateStream(RtmpHeader header, RtmpMessageCommand command) throws IOException {
NetStream stream = createStream();
AmfValue[] argsMessageCommand = { new AmfNull(), new AmfValue(stream.getStreamId()) };
rtmp.writeRtmpMessage(header.getChunkStreamId(), -1, -1,
new RtmpMessageCommand("_result", command.getTransactionId(), argsMessageCommand));
}
private void onDeleteStream(RtmpHeader header, RtmpMessageCommand command) throws IOException, NetConnectionException {
AmfValue[] args = command.getArgs();
int streamId = args[1].integer();
NetStream stream = streams.get(streamId);
if( stream == null ) {
streamError(header.getChunkStreamId(), header.getStreamId(), command.getTransactionId(), "Invalid 'deleteStream' stream id");
return;
}
closeStream(stream);
}
private void onCloseStream(RtmpHeader header, RtmpMessageCommand command) throws NetConnectionException, IOException {
NetStream stream = streams.get(header.getStreamId());
if( stream == null ) {
streamError(header.getChunkStreamId(), header.getStreamId(), command.getTransactionId(), "Invalid 'CloseStream' stream id " + header.getStreamId());
return;
}
closeStream(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 {
HashMap<String, AmfValue> value = new HashMap<String, AmfValue>();
value.put("level", new AmfValue("error"));
value.put("code", new AmfValue());
value.put("details", new AmfValue(msg));
AmfValue[] argsMessageCommand = { new AmfNull(), new AmfValue(value) };
rtmp.writeRtmpMessage(chunkStreamId, streamId, -1,
new RtmpMessageCommand("onStatus", transactionId, argsMessageCommand));
}
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;
}
if (!rtmp.readRtmpMessage()) return;
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;
//System.out.println("read message USER_CONTROL:" + userControl.getEvent() + ":" + userControl.getStreamId() + ":" + userControl.getTimestamp());
break;
case RtmpMessage.MESSAGE_SHARED_OBJECT:
System.out.println("read message SHARED OBJECT:");
onSharedMessage(header, message);
break;
case RtmpMessage.MESSAGE_CHUNK_SIZE:
System.out.println("read message chunk size:");
break;
case RtmpMessage.MESSAGE_ABORT:
System.out.println("read message abort:");
break;
case RtmpMessage.MESSAGE_ACK:
RtmpMessageAck ack = (RtmpMessageAck)message;
//System.out.println("read message ACK:" + ack.getBytes());
break;
case RtmpMessage.MESSAGE_WINDOW_ACK_SIZE:
RtmpMessageWindowAckSize ackSize = (RtmpMessageWindowAckSize)message;
//System.out.println("read message window ack size:" + ackSize.getSize());
break;
case RtmpMessage.MESSAGE_PEER_BANDWIDTH:
System.out.println("read message peer bandwidth:");
break;
case RtmpMessage.MESSAGE_AGGREGATE:
System.out.println("read message aggregate:");
break;
case RtmpMessage.MESSAGE_UNKNOWN:
System.out.println("read message UNKNOWN:");
break;
}
} catch(Exception e) {
e.printStackTrace();
}
}
public void playStreams() {
for(NetStream stream : streams.values()) {
if(stream != null) {
IPlayer player = stream.getPlayer();
if (player != null) {
try {
player.play();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
public void close() {
for(NetStream stream : streams.values()) {
if( stream != null )
try {
closeStream(stream);
} catch (IOException e) {
e.printStackTrace();
}
}
streams.clear();
}
private NetStream createStream() {
int id;
for(id = 1; id <= streams.size(); id++ ) {
if( streams.get(id) == null )
break;
}
NetStream stream = new NetStream(rtmp, id);
streams.put(id, stream);
return stream;
}
private void closeStream(NetStream stream) throws IOException {
stream.close();
streams.remove(stream.getStreamId());
}
}
| Java |
package com.ams.rtmp.net;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.LinkedList;
import com.ams.flv.*;
import com.ams.rtmp.message.*;
import com.ams.util.ByteBufferHelper;
import com.ams.event.*;
public class StreamPublisher implements IEventPublisher {
private String publishName = null;
private int bytes = 0;
private int lastPing = 0;
private boolean ping = false;
private LinkedList<IEventSubscriber> subscribers = new LinkedList<IEventSubscriber>();
private FlvRecorder recorder = null; // record to file stream
public StreamPublisher(String publishName) {
this.publishName = publishName;
}
public synchronized void publish(Event msg) throws IOException {
long timestamp = msg.getTimestamp();
int type = 0;
ByteBuffer[] data = null;
RtmpMessage message = (RtmpMessage) msg.getEvent();
switch (message.getType()) {
case RtmpMessage.MESSAGE_AUDIO:
RtmpMessageAudio audio = (RtmpMessageAudio) message;
data = audio.getData();
type = FlvTag.FLV_AUDIO;
break;
case RtmpMessage.MESSAGE_VIDEO:
RtmpMessageVideo video = (RtmpMessageVideo) message;
data = video.getData();
type = FlvTag.FLV_VIDEO;
break;
case RtmpMessage.MESSAGE_AMF0_DATA:
RtmpMessageData meta = (RtmpMessageData) message;
data = meta.getData();
type = FlvTag.FLV_META;
break;
}
// record to file
if (recorder != null) {
recorder.record(type, data, timestamp);
}
// publish packet to other stream subscriber
notify(msg);
// ping
ping(ByteBufferHelper.size(data));
}
public synchronized void close() {
if (recorder != null) {
recorder.close();
}
subscribers.clear();
}
private void notify(Event msg) {
for (IEventSubscriber subscriber : subscribers) {
subscriber.messageNotify(msg);
}
}
private void ping(int dataSize) {
bytes += dataSize;
// ping
ping = false;
if (bytes - lastPing > 100000) {
// if (bytes - lastPing > 1024*20) {
lastPing = bytes;
ping = true;
}
}
public void addSubscriber(IEventSubscriber subscrsiber) {
synchronized (subscribers) {
subscribers.add(subscrsiber);
}
}
public void removeSubscriber(IEventSubscriber subscriber) {
synchronized (subscribers) {
subscribers.remove(subscriber);
}
}
public void setRecorder(FlvRecorder recorder) {
this.recorder = recorder;
}
public boolean isPing() {
return ping;
}
public int getBytes() {
return bytes;
}
public String getPublishName() {
return publishName;
}
}
| Java |
package com.ams.rtmp.net;
import java.io.File;
import java.util.HashMap;
public final class NetContext {
private final String contextRoot;
private HashMap<String, String> attributes;
public NetContext(String root) {
contextRoot = root;
attributes = new HashMap<String, String>();
}
public void setAttribute(String key, String value) {
attributes.put(key, value);
}
public String getAttribute(String key) {
return attributes.get(key);
}
public String getMimeType(String file) {
int index = file.lastIndexOf('.');
return (index++ > 0)
? MimeTypes.getContentType(file.substring(index))
: "unkown/unkown";
}
public String getRealPath(String app, String path) {
if ("unkown/unkown".equals(getMimeType(path))) {
path += ".flv";
}
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.rtmp.net;
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("flv", "video/x-flv ");
};
public static String getContentType(String extension) {
String contentType = (String) mimeMap.get(extension);
if (contentType == null)
contentType = "unkown/unkown";
return contentType;
}
} | Java |
package com.ams.f4v.box;
public final class UDTA {
}
| Java |
package com.ams.f4v.box;
public final class CTTS {
}
| Java |
package com.ams.f4v.box;
public final class STBL {
}
| Java |
package com.ams.f4v.box;
public final class META {
}
| Java |
package com.ams.f4v.box;
public final class TRAK {
}
| Java |
package com.ams.f4v.box;
public final class TKHD {
}
| Java |
package com.ams.f4v.box;
public final class STSS {
}
| Java |
package com.ams.f4v.box;
public final class MDHD {
}
| Java |
package com.ams.f4v.box;
public final class MDIA {
}
| Java |
package com.ams.f4v.box;
public final class STCO {
}
| Java |
package com.ams.f4v.box;
public final class STTS {
}
| Java |
package com.ams.f4v.box;
public final class MINF {
}
| Java |
package com.ams.f4v.box;
public final class MDAT {
}
| Java |
package com.ams.f4v.box;
public final class PDIN {
}
| Java |
package com.ams.f4v.box;
public final class MOOV {
}
| Java |
package com.ams.f4v.box;
public final class STSD {
}
| Java |
package com.ams.f4v.box;
public final class STSC {
}
| Java |
package com.ams.f4v.box;
public final class MVHD {
}
| Java |
package com.ams.f4v.box;
public final class STSZ {
}
| Java |
package com.ams.f4v.box;
public final class CHPL {
}
| Java |
package com.ams.f4v.box;
public final class FTYP {
}
| Java |
package com.ams.io;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ByteBufferArray implements IByteBufferReader, IByteBufferWriter {
private List<ByteBuffer> buffers;
private int index = 0;
public ByteBufferArray() {
this.buffers = new ArrayList<ByteBuffer>();
}
public ByteBufferArray(ArrayList<ByteBuffer> buffers) {
if (buffers == null) throw new NullPointerException();
this.buffers = buffers;
init();
}
public ByteBufferArray(ByteBuffer[] buffers) {
if (buffers == null) throw new NullPointerException();
this.buffers = Arrays.asList(buffers);
init();
}
private void init() {
index = 0;
for (ByteBuffer buf : buffers) {
if (buf.hasRemaining()) break;
index++;
}
}
public ByteBuffer[] getBuffers() {
return buffers.toArray(new ByteBuffer[buffers.size()]);
}
public boolean hasRemaining() {
boolean hasRemaining = false;
for (ByteBuffer buf : buffers) {
if (buf.hasRemaining()) {
hasRemaining = true;
break;
}
}
return hasRemaining;
}
public int size() {
int dataSize = 0;
for(ByteBuffer buf : buffers) {
dataSize += buf.remaining();
}
return dataSize;
}
public ByteBufferArray duplicate() {
ArrayList<ByteBuffer> dup = new ArrayList<ByteBuffer>();
for(ByteBuffer buf : buffers) {
dup.add(buf.duplicate());
}
return new ByteBufferArray(dup);
}
public synchronized ByteBuffer[] read(int size) throws IOException {
if (index >= buffers.size()) return null;
ArrayList<ByteBuffer> list = new ArrayList<ByteBuffer>();
int length = size;
while (length > 0 && index < buffers.size()) {
// read a buffer
ByteBuffer buffer = buffers.get(index);
int remain = buffer.remaining();
if (length >= remain) {
list.add(buffer);
index++;
length -= remain;
} else {
ByteBuffer slice = buffer.slice();
slice.limit(length);
buffer.position(buffer.position() + length);
list.add(slice);
length = 0;
}
}
return list.toArray(new ByteBuffer[list.size()]);
}
public void write(ByteBuffer[] data) throws IOException {
for (ByteBuffer buf : data) {
buffers.add(buf);
}
}
}
| 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;
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 readByte() 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 synchronized 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(8 * 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 synchronized 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 = buffer.slice();
slice.limit(length);
buffer.position(buffer.position() + 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 synchronized 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;
}
}
position = startPosition;
file.seek(position);
this.buffer = null;
this.eof = false;
}
public void skip(long bytes) throws IOException {
seek(position + bytes);
}
public boolean isEof() {
return eof;
}
public void close() throws IOException {
file.close();
}
public long getPosition() {
return position;
}
}
| Java |
package com.ams.io;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import com.ams.server.ByteBufferFactory;
import com.ams.util.Utils;
public class ByteBufferOutputStream extends OutputStream {
protected static final int WRITE_BUFFER_SIZE = 512;
protected ByteBuffer writeBuffer = null;
protected IByteBufferWriter writer = null;
public ByteBufferOutputStream(IByteBufferWriter writer) {
this.writer = writer;
}
public synchronized void flush() throws IOException {
if (writeBuffer != null) {
writeBuffer.flip();
writer.write(new ByteBuffer[] {writeBuffer});
writeBuffer = null;
}
}
public synchronized 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 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 {
write(Utils.to16Bit(v));
}
public void write24Bit(int v) throws IOException {
write(Utils.to24Bit(v)); // 24bit
}
public void write32Bit(long v) throws IOException {
write(Utils.to32Bit(v)); // 32bit
}
public void write16BitLittleEndian(int v) throws IOException {
// 16bit write, LITTLE-ENDIAN
write(Utils.to16BitLittleEndian(v));
}
public void write24BitLittleEndian(int v) throws IOException {
write(Utils.to24BitLittleEndian(v)); // 24bit
}
public void write32BitLittleEndian(long v) throws IOException {
// 32bit write, LITTLE-ENDIAN
write(Utils.to32BitLittleEndian(v));
}
public void writeByteBuffer(ByteBufferArray data) throws IOException {
writeByteBuffer(data.getBuffers());
}
public void writeByteBuffer(ByteBuffer[] data) throws IOException {
flush();
writer.write(data);
}
}
| Java |
package com.ams.io;
import java.io.*;
import java.nio.ByteBuffer;
import com.ams.util.Utils;
public class ByteBufferInputStream extends InputStream {
protected IByteBufferReader reader = null;
protected byte[] line = new byte[4096];
public ByteBufferInputStream(ByteBuffer[] buffers) {
this.reader = new ByteBufferArray(buffers);
}
public ByteBufferInputStream(IByteBufferReader reader) {
this.reader = reader;
}
public synchronized 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();
}
ByteBuffer[] buffers = reader.read(length);
if (buffers == null) return -1;
int readBytes = 0;
for(ByteBuffer buffer : buffers) {
int size = buffer.remaining();
buffer.get(data, offset, size);
offset += size;
readBytes += size;
}
return readBytes;
}
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 Utils.from16Bit(b);
}
public int read24Bit() throws IOException {
byte[] b = new byte[3];
read(b, 0, 3); // 24Bit read
return Utils.from24Bit(b);
}
public long read32Bit() throws IOException {
byte[] b = new byte[4];
read(b, 0, 4); // 32Bit read
return Utils.from32Bit(b);
}
public int read16BitLittleEndian() throws IOException {
byte[] b = new byte[2];
read(b, 0, 2);
// 16 Bit read, LITTLE-ENDIAN
return Utils.from16BitLittleEndian(b);
}
public int read24BitLittleEndian() throws IOException {
byte[] b = new byte[3];
read(b, 0, 3);
// 24 Bit read, LITTLE-ENDIAN
return Utils.from24BitLittleEndian(b);
}
public long read32BitLittleEndian() throws IOException {
byte[] b = new byte[4];
read(b, 0, 4);
// 32 Bit read, LITTLE-ENDIAN
return Utils.from32BitLittleEndian(b);
}
public ByteBuffer[] readByteBuffer(int size) throws IOException {
return reader.read(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.message;
public class MediaMessage<T> {
protected long timestamp = 0;
protected T data;
public MediaMessage(long timestamp, T data) {
this.timestamp = timestamp;
this.data = data;
}
public long getTimestamp() {
return timestamp;
}
public T getData() {
return data;
}
}
| Java |
package com.ams.message;
import java.io.IOException;
public interface IMsgPublisher<T1, T2> {
public void publish(T1 msg) throws IOException;
public void addSubscriber(IMsgSubscriber<T2> subscriber);
public void removeSubscriber(IMsgSubscriber<T2> subscriber);
}
| Java |
package com.ams.message;
import java.io.IOException;
public interface IMediaSerializer {
public void write(MediaSample sample) throws IOException;
public void close();
}
| Java |
package com.ams.message;
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.message;
public interface IMsgSubscriber<T> {
public void messageNotify(T msg);
}
| Java |
package com.ams.message;
import java.io.IOException;
import java.nio.ByteBuffer;
import com.ams.io.ByteBufferArray;
import com.ams.io.RandomAccessFileReader;
import com.ams.rtmp.message.RtmpMessage;
import com.ams.rtmp.message.RtmpMessageAudio;
import com.ams.rtmp.message.RtmpMessageData;
import com.ams.rtmp.message.RtmpMessageVideo;
public class MediaSample extends MediaMessage<ByteBufferArray> {
public static final int SAMPLE_AUDIO = 0;
public static final int SAMPLE_VIDEO = 1;
public static final int SAMPLE_META = 2;
protected int sampleType;
protected boolean keyframe;
protected long offset;
protected int size;
public MediaSample(int sampleType, long timestamp, ByteBufferArray data) {
super(timestamp, data);
this.sampleType = sampleType;
this.data = data;
}
public MediaSample(int sampleType, long timestamp, boolean keyframe, long offset, int size) {
super(timestamp, null);
this.sampleType = sampleType;
this.keyframe = keyframe;
this.offset = offset;
this.size = size;
}
public void readData(RandomAccessFileReader reader) throws IOException {
reader.seek(offset);
data = new ByteBufferArray(reader.read(size));
}
public int getSampleType() {
return sampleType;
}
public long getOffset() {
return offset;
}
public int getSize() {
return size;
}
public int getDataSize() {
return data.size();
}
public boolean isKeyframe() {
return keyframe;
}
public boolean isAudioSample() {
return sampleType == SAMPLE_AUDIO;
}
public boolean isVideoSample() {
return sampleType == SAMPLE_VIDEO;
}
public boolean isMetaSample() {
return sampleType == SAMPLE_META;
}
public boolean isVideoKeyframe() {
ByteBuffer buf = data.getBuffers()[0];
int h = buf.get(buf.position()) & 0xFF;
return isVideoSample() && ((h >>> 4) == 1 || h == 0x17);
}
public boolean isH264VideoSample() {
ByteBuffer buf = data.getBuffers()[0];
int h = buf.get(buf.position()) & 0xFF;
return h == 0x17 || h == 0x27;
}
public boolean isH264AudioHeader() {
ByteBuffer buf = data.getBuffers()[0];
int pos = buf.position();
int h1 = buf.get(pos) & 0xFF;
int h2 = buf.get(pos + 1) & 0xFF;
return h1 == 0xAF && h2 == 0x00;
}
public boolean isH264VideoHeader() {
ByteBuffer buf = data.getBuffers()[0];
int pos = buf.position();
int h1 = buf.get(pos) & 0xFF;
int h2 = buf.get(pos + 1) & 0xFF;
return h1 == 0x17 && h2 == 0x00;
}
public RtmpMessage toRtmpMessage() {
RtmpMessage msg = null;
switch(sampleType) {
case SAMPLE_META:
msg = new RtmpMessageData(data);
break;
case SAMPLE_VIDEO:
msg = new RtmpMessageVideo(data);
break;
case SAMPLE_AUDIO:
msg = new RtmpMessageAudio(data);
break;
}
return msg;
}
}
| Java |
package com.ams.flv;
import java.io.IOException;
import com.ams.io.ByteBufferArray;
import com.ams.io.ByteBufferOutputStream;
import com.ams.io.RandomAccessFileWriter;
import com.ams.message.IMediaSerializer;
import com.ams.message.MediaSample;
public class FlvSerializer implements IMediaSerializer {
private ByteBufferOutputStream out; //record to file stream
private boolean headerWrite = false;
public FlvSerializer(RandomAccessFileWriter writer) {
super();
this.out = new ByteBufferOutputStream(writer);
}
public void write(MediaSample flvTag) throws IOException {
write(out, flvTag);
out.flush();
}
private void write(ByteBufferOutputStream out, MediaSample flvTag) throws IOException {
if (!headerWrite) {
FlvHeader header = new FlvHeader(true, true);
FlvHeader.write(out, header);
headerWrite = true;
}
byte tagType = -1;
switch (flvTag.getSampleType()) {
case MediaSample.SAMPLE_AUDIO:
tagType = 0x08;
break;
case MediaSample.SAMPLE_VIDEO:
tagType = 0x09;
break;
case MediaSample.SAMPLE_META:
tagType = 0x12;
break;
}
// tag type
out.writeByte(tagType);
ByteBufferArray data = flvTag.getData();
// data size
int dataSize = data.size();
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 void close() {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| Java |
package com.ams.flv;
import java.io.EOFException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import com.ams.amf.AmfValue;
import com.ams.io.ByteBufferArray;
import com.ams.io.ByteBufferInputStream;
import com.ams.io.RandomAccessFileReader;
import com.ams.message.IMediaDeserializer;
import com.ams.message.MediaSample;
import com.ams.server.ByteBufferFactory;
public class FlvDeserializer implements IMediaDeserializer {
private RandomAccessFileReader reader;
private ArrayList<MediaSample> samples = new ArrayList<MediaSample>();
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 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 static Comparator<MediaSample> sampleTimestampComparator = new Comparator<MediaSample>() {
public int compare(MediaSample s, MediaSample t) {
return (int)(s.getTimestamp() - t.getTimestamp());
}
};
public FlvDeserializer(RandomAccessFileReader reader) {
this.reader = reader;
getAllSamples();
}
private MediaSample readSampleData(ByteBufferInputStream 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 ByteBufferArray(data));
case 0x09:
return new VideoTag(timestamp, new ByteBufferArray(data));
case 0x12:
return new MetaTag(timestamp, new ByteBufferArray(data));
default:
throw new FlvException("Invalid FLV tag " + tagType);
}
}
private MediaSample readSampleOffset(RandomAccessFileReader reader) throws IOException, FlvException {
int tagType;
ByteBufferInputStream in = new ByteBufferInputStream(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 getAllSamples() {
try {
reader.seek(0);
ByteBufferInputStream in = new ByteBufferInputStream(reader);
FlvHeader.read(in);
MediaSample tag = null;
while((tag = readSampleOffset(reader)) != null) {
if (tag.isVideoSample()) {
videoFrames++;
videoDataSize += tag.getSize();
if (firstVideoTag == null)
firstVideoTag = (VideoTag)tag;
if (tag.isKeyframe())
samples.add(tag);
lastVideoTag = (VideoTag)tag;
}
if (tag.isAudioSample()) {
audioFrames++;
audioDataSize += tag.getSize();
if (firstAudioTag == null)
firstAudioTag = (AudioTag)tag;
lastAudioTag = (AudioTag)tag;
}
if (tag.isMetaSample()) {
if (firstMetaTag == null)
firstMetaTag = (MetaTag)tag;
lastMetaTag = (MetaTag)tag;
}
lastTimestamp = tag.getTimestamp();
}
if (firstVideoTag != null) {
firstVideoTag.readData(reader);
firstVideoTag.getParameters();
}
if (firstAudioTag != null) {
firstAudioTag.readData(reader);
firstAudioTag.getParameters();
}
if (firstMetaTag != null) {
firstMetaTag.readData(reader);
firstMetaTag.getParameters();
}
} 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.SAMPLE_META, 0, AmfValue.toBinary(metaData));
}
public MediaSample videoHeaderData() {
if (firstVideoTag != null && firstVideoTag.isH264VideoSample()) {
byte[] data = H264_VIDEO_HEADER;
ByteBuffer[] buf = new ByteBuffer[1];
buf[0] = ByteBufferFactory.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.SAMPLE_VIDEO, 0, new ByteBufferArray(buf));
}
return null;
}
public MediaSample audioHeaderData() {
if (firstAudioTag != null && firstVideoTag.isH264VideoSample()) {
byte[] data = H264_AUDIO_HEADER;
ByteBuffer[] buf = new ByteBuffer[1];
buf[0] = ByteBufferFactory.allocate(2 + data.length);
buf[0].put(new byte[]{(byte)0xaf, 0x00});
buf[0].put(data);
buf[0].flip();
return new MediaSample(MediaSample.SAMPLE_AUDIO, 0, new ByteBufferArray(buf));
}
return null;
}
public MediaSample seek(long seekTime) throws IOException {
MediaSample flvTag = firstVideoTag;
int idx = Collections.binarySearch(samples, new MediaSample(MediaSample.SAMPLE_VIDEO, seekTime, true, 0, 0) , sampleTimestampComparator);
int i = (idx >= 0) ? idx : -(idx + 1);
while(i > 0) {
flvTag = samples.get(i);
if (flvTag.isVideoSample() && flvTag.isKeyframe()) {
break;
}
i--;
}
reader.seek(flvTag.getOffset() - 11);
return flvTag;
}
public MediaSample readNext() throws IOException {
try {
return readSampleData(new ByteBufferInputStream(reader));
} catch (Exception e) {
throw new EOFException();
}
}
public void close() {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| Java |
package com.ams.flv;
import java.io.IOException;
import com.ams.io.ByteBufferArray;
import com.ams.io.ByteBufferInputStream;
import com.ams.message.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, ByteBufferArray data) {
super(MediaSample.SAMPLE_AUDIO, timestamp, data);
}
public AudioTag(long timestamp, long offset, int size) {
super(MediaSample.SAMPLE_AUDIO, timestamp, true, offset, size);
}
public void getParameters() throws IOException {
ByteBufferInputStream bi = new ByteBufferInputStream(data.duplicate());
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.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.DataInputStream;
import java.io.IOException;
import com.ams.amf.Amf0Deserializer;
import com.ams.amf.AmfException;
import com.ams.amf.AmfValue;
import com.ams.io.ByteBufferArray;
import com.ams.io.ByteBufferInputStream;
import com.ams.message.MediaSample;
public class MetaTag extends MediaSample {
private String event = null;
private AmfValue metaData = null;
public MetaTag(long timestamp, ByteBufferArray data) {
super(MediaSample.SAMPLE_META, timestamp, data);
}
public MetaTag(long timestamp, long offset, int size) {
super(MediaSample.SAMPLE_META, timestamp, false, offset, size);
}
public void getParameters() throws IOException {
ByteBufferInputStream bi = new ByteBufferInputStream(data.duplicate());
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.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.flv;
import java.io.IOException;
import com.ams.io.ByteBufferArray;
import com.ams.io.ByteBufferInputStream;
import com.ams.message.MediaSample;
public class VideoTag extends MediaSample {
private int codecId = -1;
private int width = 0, height = 0;
public VideoTag(long timestamp, ByteBufferArray data) {
super(MediaSample.SAMPLE_VIDEO, timestamp, data);
}
public VideoTag(long timestamp, boolean keyframe, long offset, int size) {
super(MediaSample.SAMPLE_VIDEO, timestamp, keyframe, offset, size);
}
public void getParameters() throws IOException {
ByteBufferInputStream bi = new ByteBufferInputStream(data.duplicate());
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.so;
import java.util.Map;
import com.ams.amf.AmfValue;
public class SoEventChange extends SoEvent {
private Map<String, AmfValue> data;
public SoEventChange(Map<String, AmfValue> data) {
super(SO_EVT_CHANGE);
this.data = data;
}
public Map<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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.