code
stringlengths
3
1.18M
language
stringclasses
1 value
package com.ams.so; public class SoEventSuceess extends SoEvent { private String name; public SoEventSuceess(String name) { super(SO_EVT_SUCCESS); this.name = name; } public String getName() { return name; } }
Java
package com.ams.so; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.EOFException; import java.io.IOException; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import com.ams.amf.Amf0Deserializer; import com.ams.amf.Amf0Serializer; import com.ams.amf.AmfException; import com.ams.amf.AmfValue; public class SoEvent { public static final int SO_EVT_USE = 1; public static final int SO_EVT_RELEASE = 2; public static final int SO_EVT_REQUEST_CHANGE = 3; public static final int SO_EVT_CHANGE = 4; public static final int SO_EVT_SUCCESS = 5; public static final int SO_EVT_SEND_MESSAGE = 6; public static final int SO_EVT_STATUS = 7; public static final int SO_EVT_CLEAR = 8; public static final int SO_EVT_REMOVE = 9; public static final int SO_EVT_REQUEST_REMOVE = 10; public static final int SO_EVT_USE_SUCCESS = 11; private int kind = 0; public SoEvent(int kind) { this.kind = kind; } public int getKind() { return kind; } public static SoEvent read(DataInputStream in, int kind, int size) throws IOException, AmfException { Amf0Deserializer deserializer = new Amf0Deserializer(in); SoEvent event = null; switch(kind) { case SoEvent.SO_EVT_USE: event = new SoEvent(SoEvent.SO_EVT_USE); break; case SoEvent.SO_EVT_RELEASE: event = new SoEvent(SoEvent.SO_EVT_RELEASE); break; case SoEvent.SO_EVT_REQUEST_CHANGE: event = new SoEventRequestChange(in.readUTF(), deserializer.read()); break; case SoEvent.SO_EVT_CHANGE: Map<String, AmfValue> hash = new LinkedHashMap<String, AmfValue>(); while( true ) { String key = null; try { key = in.readUTF(); }catch(EOFException e) { break; } hash.put(key, deserializer.read()); } event = new SoEventChange(hash); break; case SoEvent.SO_EVT_SUCCESS: event = new SoEventSuceess(in.readUTF()); break; case SoEvent.SO_EVT_SEND_MESSAGE: event = new SoEventSendMessage(deserializer.read()); break; case SoEvent.SO_EVT_STATUS: String msg = in.readUTF(); String type = in.readUTF(); event = new SoEventStatus(msg, type); break; case SoEvent.SO_EVT_CLEAR: event = new SoEvent(SoEvent.SO_EVT_CLEAR); break; case SoEvent.SO_EVT_REMOVE: event = new SoEvent(SoEvent.SO_EVT_REMOVE); break; case SoEvent.SO_EVT_REQUEST_REMOVE: event = new SoEventRequestRemove(in.readUTF()); break; case SoEvent.SO_EVT_USE_SUCCESS: event = new SoEvent(SoEvent.SO_EVT_USE_SUCCESS); } return event; } public static void write(DataOutputStream out, SoEvent event) throws IOException { Amf0Serializer serializer = new Amf0Serializer(out); switch(event.getKind()) { case SoEvent.SO_EVT_USE: case SoEvent.SO_EVT_RELEASE: case SoEvent.SO_EVT_CLEAR: case SoEvent.SO_EVT_REMOVE: case SoEvent.SO_EVT_USE_SUCCESS: // nothing break; case SoEvent.SO_EVT_REQUEST_CHANGE: out.writeUTF(((SoEventRequestChange)event).getName()); serializer.write(((SoEventRequestChange)event).getValue()); break; case SoEvent.SO_EVT_CHANGE: Map<String, AmfValue> data = ((SoEventChange)event).getData(); Iterator<String> it = data.keySet().iterator(); while (it.hasNext()) { String key = it.next(); out.writeUTF(key); serializer.write(data.get(key)); } break; case SoEvent.SO_EVT_SUCCESS: out.writeUTF(((SoEventSuceess)event).getName()); break; case SoEvent.SO_EVT_SEND_MESSAGE: serializer.write(((SoEventSendMessage)event).getMsg()); break; case SoEvent.SO_EVT_STATUS: out.writeUTF(((SoEventStatus)event).getMsg()); out.writeUTF(((SoEventStatus)event).getMsgType()); break; case SoEvent.SO_EVT_REQUEST_REMOVE: out.writeUTF(((SoEventRequestRemove)event).getName()); break; } } }
Java
package com.ams.so; import com.ams.amf.AmfValue; public class SoEventRequestChange extends SoEvent { private String name; private AmfValue value; public SoEventRequestChange(String name, AmfValue value) { super(SO_EVT_REQUEST_CHANGE); this.name = name; this.value = value; } public String getName() { return name; } public AmfValue getValue() { return value; } }
Java
package com.ams.so; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.EOFException; import java.io.IOException; import java.util.ArrayList; import com.ams.amf.AmfException; public class SoMessage { private String name; private int version; private boolean persist; private int unknown; private ArrayList<SoEvent> events; public SoMessage(String name, int version, boolean persist, int unknown, ArrayList<SoEvent> events) { this.name = name; this.version = version; this.persist = persist; this.unknown = unknown; this.events = events; } public ArrayList<SoEvent> getEvents() { return events; } public String getName() { return name; } public boolean isPersist() { return persist; } public int getVersion() { return version; } public int getUnknown() { return unknown; } public static SoMessage read( DataInputStream in ) throws IOException, AmfException { String name = in.readUTF(); int version = in.readInt(); boolean persist = (in.readInt() == 2); int unknown = in.readInt(); ArrayList<SoEvent> events = new ArrayList<SoEvent>(); while( true ) { int kind; try { kind = in.readByte() & 0xFF; } catch(EOFException e) { break; } int size = in.readInt(); SoEvent event = SoEvent.read(in, kind, size); if (event != null) { events.add(event); } } return new SoMessage(name, version, persist, unknown, events); } public static void write(DataOutputStream out, SoMessage so) throws IOException { out.writeUTF(so.getName()); out.writeInt(so.getVersion()); out.writeInt(so.isPersist()?2:0); out.writeInt(so.getUnknown()); ArrayList<SoEvent> events = so.getEvents(); for(int i=0; i < events.size(); i++) { SoEvent event = events.get(i); out.writeByte(event.getKind()); ByteArrayOutputStream bos = new ByteArrayOutputStream(); SoEvent.write(new DataOutputStream(bos), event); byte[] data = bos.toByteArray(); out.writeInt(data.length); out.write(data); } } }
Java
/** * */ package com.ams.http; public class Cookie { public String value=""; public long expires=0; public String domain=""; public String path=""; public boolean secure=false; public Cookie(String value, long expires, String domain, String path, boolean secure) { this.value = value; this.expires = expires; this.domain = domain; this.path = path; this.secure = secure; } }
Java
package com.ams.http; import java.io.*; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import com.ams.util.Log; import com.ams.util.ObjectCache; public class DefaultServlet { private class MapedFile { public long size; public String contentType; public long lastModified; public ByteBuffer data; } private ServletContext context = null; private static ObjectCache<MapedFile> fileCache = new ObjectCache<MapedFile>(); public DefaultServlet(ServletContext context) { this.context = context; } public void service(HttpRequest req, HttpResponse res) throws IOException { String realPath = null; try { realPath = context.getRealPath(req.getLocation()); } catch (Exception e) { Log.logger.warning(e.getMessage()); } File file = new File(realPath); if (!file.exists()) { res.setHttpResult(HTTP.HTTP_NOT_FOUND); res.flush(); } else if (!context.securize(file)) { res.setHttpResult(HTTP.HTTP_FORBIDDEN); res.flush(); } else { if (!writeFile(req.getLocation(), file, res)) { res.setHttpResult(HTTP.HTTP_INTERNAL_ERROR); res.flush(); } } } private boolean writeFile(String url, File file, HttpResponse res) { boolean result = true; try { MapedFile mapedFile = fileCache.get(url); if (mapedFile == null) { // open the resource stream mapedFile = new MapedFile(); mapedFile.lastModified = file.lastModified(); mapedFile.size = file.length(); mapedFile.contentType = context.getMimeType(file.getName()); FileChannel fileChannel = new FileInputStream(file) .getChannel(); mapedFile.data = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileChannel.size()); fileChannel.close(); fileCache.put(url, mapedFile, 60); } res.setContentLength(mapedFile.size); res.setContentType(mapedFile.contentType); res.setLastModified(mapedFile.lastModified); res.setHttpResult(HTTP.HTTP_OK); // read all bytes and send them res.flush(mapedFile.data.slice()); } catch (IOException e) { result = false; Log.logger.warning(e.getMessage()); } return result; } }
Java
/** * */ package com.ams.http; import java.io.File; public class HttpFileUpload { public final static int RESULT_OK = 0; public final static int RESULT_SIZE = 1; public final static int RESULT_PARTIAL = 3; public final static int RESULT_NOFILE = 4; public final static long MAXSIZE_FILE_UPLOAD = 10 * 1024 * 1024; // max 10M public String filename; public File tempFile; public int result; public HttpFileUpload(String filename, File tempFile, int result) { this.filename = filename; this.tempFile = tempFile; this.result = result; } }
Java
package com.ams.http; import java.io.File; import java.io.IOException; public final class ServletContext { private final File contextRoot; public ServletContext(String root) { contextRoot = new File(root); } public String getMimeType(String file) { int index = file.lastIndexOf('.'); return (index++ > 0) ? MimeTypes.getContentType(file.substring(index)) : "unkown/unkown"; } public String getRealPath(String path) { return new File(contextRoot, path).getAbsolutePath(); } // security check public boolean securize(File file) throws IOException { if (file.getCanonicalPath().startsWith(contextRoot.getCanonicalPath())) { return true; } return false; } }
Java
package com.ams.http; public final class HTTP { /** HTTP method */ public final static int HTTP_METHOD_GET = 0; public final static int HTTP_METHOD_POST = 1; public final static int HTTP_METHOD_HEAD = 2; public final static int HTTP_METHOD_PUT = 3; public final static int HTTP_METHOD_DELETE = 4; public final static int HTTP_METHOD_TRACE = 5; public final static int HTTP_METHOD_OPTIONS = 6; /** HTTP Status-Code */ public final static int HTTP_OK = 200; public final static int HTTP_MOVED_PERMANENTLY = 301; public final static int HTTP_BAD_REQUEST = 400; public final static int HTTP_UNAUTHORIZED = 401; public final static int HTTP_FORBIDDEN = 403; public final static int HTTP_NOT_FOUND = 404; public final static int HTTP_BAD_METHOD = 405; public final static int HTTP_LENGTH_REQUIRED = 411; public final static int HTTP_INTERNAL_ERROR = 500; /** HTTP header definitions */ public static final String HEADER_ACCEPT = "Accept"; public static final String HEADER_ACCEPT_CHARSET = "Accept-Charset"; public static final String HEADER_ACCEPT_LANGUAGE = "Accept-Language"; public static final String HEADER_AGE = "Age"; public static final String HEADER_ALLOW = "Allow"; public static final String HEADER_AUTHORIZATION = "Authorization"; public static final String HEADER_CACHE_CONTROL = "Cache-Control"; public static final String HEADER_CONN_DIRECTIVE = "Connection"; public static final String HEADER_CONTENT_LANGUAGE = "Content-Language"; public static final String HEADER_CONTENT_LENGTH = "Content-Length"; public static final String HEADER_CONTENT_LOCATION = "Content-Location"; public static final String HEADER_CONTENT_MD5 = "Content-MD5"; public static final String HEADER_CONTENT_RANGE = "Content-Range"; public static final String HEADER_CONTENT_TYPE = "Content-Type"; public static final String HEADER_DATE = "Date"; public static final String HEADER_EXPECT = "Expect"; public static final String HEADER_EXPIRES = "Expires"; public static final String HEADER_FROM = "From"; public static final String HEADER_HOST = "Host"; public static final String HEADER_IF_MODIFIED_SINCE = "If-Modified-Since"; public static final String HEADER_IF_UNMODIFIED_SINCE = "If-Unmodified-Since"; public static final String HEADER_LAST_MODIFIED = "Last-Modified"; public static final String HEADER_LOCATION = "Location"; public static final String HEADER_MAX_FORWARDS = "Max-Forwards"; public static final String HEADER_PRAGMA = "Pragma"; public static final String HEADER_RANGE = "Range"; public static final String HEADER_REFER = "Referer"; public static final String HEADER_REFER_AFTER = "Retry-After"; public static final String HEADER_SERVER = "Server"; public static final String HEADER_UPGRADE = "Upgrade"; public static final String HEADER_USER_AGENT = "User-Agent"; public static final String HEADER_VARY = "Vary"; public static final String HEADER_VIA = "Via"; public static final String HEADER_WWW_AUTHORIZATION = "WWW-Authenticate"; public static final String HEADER_CONTENT_DISPOSITION = "Content-Disposition"; public static final String HEADER_COOKIE = "Cookie"; public static final String HEADER_SET_COOKIE = "Set-Cookie"; public static final String HEADER_TRANSFER_ENCODING = "Transfer-Encoding"; public static final String HEADER_CONTENT_ENCODING = "Content-Encoding"; /** HTTP expectations */ public static final String EXPECT_CONTINUE = "100-Continue"; /** HTTP connection control */ public static final String CONN_CLOSE = "Close"; public static final String CONN_KEEP_ALIVE = "Keep-Alive"; /** Transfer encoding definitions */ public static final String CHUNK_CODING = "chunked"; public static final String IDENTITY_CODING = "identity"; /** Common charset definitions */ public static final String UTF_8 = "UTF-8"; public static final String UTF_16 = "UTF-16"; public static final String US_ASCII = "US-ASCII"; public static final String ASCII = "ASCII"; public static final String ISO_8859_1 = "ISO-8859-1"; /** Default charsets */ public static final String DEFAULT_CONTENT_CHARSET = ISO_8859_1; public static final String DEFAULT_PROTOCOL_CHARSET = US_ASCII; /** Content type definitions */ public final static String OCTET_STREAM_TYPE = "application/octet-stream"; public final static String PLAIN_TEXT_TYPE = "text/plain"; public final static String HTML_TEXT_TYPE = "html/text"; public final static String CHARSET_PARAM = "; charset="; /** Default content type */ public final static String DEFAULT_CONTENT_TYPE = OCTET_STREAM_TYPE; }
Java
package com.ams.http; import java.io.*; import java.net.URLEncoder; import java.nio.ByteBuffer; import java.text.SimpleDateFormat; import java.util.*; import com.ams.io.ByteBufferOutputStream; import com.ams.server.ByteBufferFactory; public class HttpResponse { private ByteBufferOutputStream out; private StringBuilder headerBuffer = new StringBuilder(1024); private StringBuilder bodyBuffer = new StringBuilder(); private String resultHeader; private Map<String, String> headers = new LinkedHashMap<String, String>(); private Map<String, Cookie> cookies = new LinkedHashMap<String, Cookie>(); private boolean headerWrote = false; private static String NEWLINE = "\r\n"; private static SimpleDateFormat dateFormatGMT; static { dateFormatGMT = new SimpleDateFormat("d MMM yyyy HH:mm:ss 'GMT'"); dateFormatGMT.setTimeZone(TimeZone.getTimeZone("GMT")); } public HttpResponse(ByteBufferOutputStream out) { this.out = out; init(); } public void clear() { headerBuffer = new StringBuilder(1024); bodyBuffer = new StringBuilder(); resultHeader = null; headers.clear(); cookies.clear(); headerWrote = false; init(); } private void init() { resultHeader = "HTTP/1.1 200 OK"; headers.put(HTTP.HEADER_DATE, dateFormatGMT.format(new Date())); headers.put(HTTP.HEADER_SERVER, "annuus http server"); headers.put(HTTP.HEADER_CONTENT_TYPE, "text/html; charset=utf-8"); headers.put(HTTP.HEADER_CACHE_CONTROL, "no-cache, no-store, must-revalidate, private"); headers.put(HTTP.HEADER_PRAGMA, "no-cache"); } private void putHeader(String data) throws IOException { headerBuffer.append(data); } private void putHeaderValue(String name, String value) throws IOException { putHeader(name + ": " + value + NEWLINE); } public void setHttpResult(int code) { StringBuilder message = new StringBuilder(); message.append("HTTP/1.1 " + code + " "); switch (code) { case HTTP.HTTP_OK: message.append("OK"); break; case HTTP.HTTP_BAD_REQUEST: message.append("Bad Request"); break; case HTTP.HTTP_NOT_FOUND: message.append("Not Found"); break; case HTTP.HTTP_BAD_METHOD: message.append("Method Not Allowed"); break; case HTTP.HTTP_LENGTH_REQUIRED: message.append("Length Required"); break; case HTTP.HTTP_INTERNAL_ERROR: default: message.append("Internal Server Error"); break; } this.resultHeader = message.toString(); } public void setContentLength(long length) { setHeader(HTTP.HEADER_CONTENT_LENGTH, Long.toString(length)); } public void setContentType(String contentType) { setHeader(HTTP.HEADER_CONTENT_TYPE, contentType); } public void setLastModified(long lastModified) { setHeader(HTTP.HEADER_LAST_MODIFIED, dateFormatGMT.format(new Date(lastModified))); } public void setKeepAlive(boolean keepAlive) { if (keepAlive) { setHeader(HTTP.HEADER_CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE); } else { setHeader(HTTP.HEADER_CONN_DIRECTIVE, HTTP.CONN_CLOSE); } } public void setHeader(String name, String value) { if (headers.containsKey(name)) { headers.remove(name); } headers.put(name, value); } public void setCookie(String name, Cookie cookie) { if (cookies.containsKey(name)) { cookies.remove(name); } cookies.put(name, cookie); } public void print(String data) throws IOException { bodyBuffer.append(data); } public void println(String data) throws IOException { print(data + NEWLINE); } public ByteBuffer writeHeader() throws IOException { if (headerWrote) { return null; } headerWrote = true; // write the headers putHeader(resultHeader + NEWLINE); // write all headers Iterator<String> it = this.headers.keySet().iterator(); while (it.hasNext()) { String name = it.next(); String value = headers.get(name); putHeaderValue(name, value); } // write all cookies it = this.cookies.keySet().iterator(); while (it.hasNext()) { String key = it.next(); Cookie cookie = cookies.get(key); StringBuilder cookieString = new StringBuilder(); cookieString.append(key + "=" + URLEncoder.encode(cookie.value, "UTF-8")); if (cookie.expires != 0) { Date d = new Date(cookie.expires); cookieString.append("; expires=" + dateFormatGMT.format(d)); } if (!cookie.path.equals("")) { cookieString.append("; path=" + cookie.path); } if (!cookie.domain.equals("")) { cookieString.append("; domain=" + cookie.domain); } if (cookie.secure) { cookieString.append("; secure"); } putHeaderValue(HTTP.HEADER_SET_COOKIE, cookieString.toString()); } putHeader(NEWLINE); // write header to socket channel byte[] data = headerBuffer.toString().getBytes("UTF-8"); ByteBuffer buffer = ByteBufferFactory.allocate(data.length); buffer.put(data); buffer.flip(); return buffer; } public void flush() throws IOException { byte[] body = bodyBuffer.toString().getBytes("UTF-8"); // write header setHeader(HTTP.HEADER_CONTENT_LENGTH, Long.toString(body.length)); ByteBuffer headerBuffer = writeHeader(); ByteBuffer bodyBuffer = ByteBufferFactory.allocate(body.length); bodyBuffer.put(body); bodyBuffer.flip(); ByteBuffer[] buf = { headerBuffer, bodyBuffer }; // write to socket out.writeByteBuffer(buf); } public void flush(ByteBuffer data) throws IOException { // write header ByteBuffer headerBuffer = writeHeader(); // write body ByteBuffer[] buf = { headerBuffer, data }; // write to socket out.writeByteBuffer(buf); } }
Java
package com.ams.http; import java.util.HashMap; public class MimeTypes { public static HashMap<String, String> mimeMap = new HashMap<String, String>(); static { mimeMap.put("", "content/unknown"); mimeMap.put("uu", "application/octet-stream"); mimeMap.put("exe", "application/octet-stream"); mimeMap.put("ps", "application/postscript"); mimeMap.put("zip", "application/zip"); mimeMap.put("sh", "application/x-shar"); mimeMap.put("tar", "application/x-tar"); mimeMap.put("snd", "audio/basic"); mimeMap.put("au", "audio/basic"); mimeMap.put("avi", "video/avi"); mimeMap.put("wav", "audio/x-wav"); mimeMap.put("gif", "image/gif"); mimeMap.put("jpe", "image/jpeg"); mimeMap.put("jpg", "image/jpeg"); mimeMap.put("jpeg", "image/jpeg"); mimeMap.put("png", "image/png"); mimeMap.put("bmp", "image/bmp"); mimeMap.put("htm", "text/html"); mimeMap.put("html", "text/html"); mimeMap.put("text", "text/plain"); mimeMap.put("c", "text/plain"); mimeMap.put("cc", "text/plain"); mimeMap.put("c++", "text/plain"); mimeMap.put("h", "text/plain"); mimeMap.put("pl", "text/plain"); mimeMap.put("txt", "text/plain"); mimeMap.put("java", "text/plain"); mimeMap.put("js", "application/x-javascript"); mimeMap.put("css", "text/css"); mimeMap.put("xml", "text/xml"); }; public static String getContentType(String extension) { String contentType = mimeMap.get(extension); if (contentType == null) contentType = "unkown/unkown"; return contentType; } }
Java
package com.ams.http; import java.io.*; import java.net.*; import java.text.SimpleDateFormat; import java.util.*; import com.ams.io.ByteBufferInputStream; public class HttpRequest { private ByteBufferInputStream in = null; private int method; private String location; private String rawGet; private String rawPost; private Map<String, String> headers = new LinkedHashMap<String, String>(); private Map<String, String> cookies = new LinkedHashMap<String, String>(); private Map<String, String> getValues = new LinkedHashMap<String, String>(); private Map<String, String> postValues = new LinkedHashMap<String, String>(); private Map<String, HttpFileUpload> postFiles = new LinkedHashMap<String, HttpFileUpload>(); private static SimpleDateFormat dateFormatGMT; static { dateFormatGMT = new SimpleDateFormat("d MMM yyyy HH:mm:ss 'GMT'"); dateFormatGMT.setTimeZone(TimeZone.getTimeZone("GMT")); } public HttpRequest(ByteBufferInputStream in) throws IOException { super(); this.in = in; } public void clear() { method = -1; location = null; rawGet = null; rawPost = null; headers.clear(); cookies.clear(); getValues.clear(); postValues.clear(); postFiles.clear(); } public void parse() throws IOException { if (in == null) { throw new IOException("no input stream"); } if (HTTP.HTTP_OK != parseHttp()) { throw new IOException("bad http"); } } private void parseRawString(String options, Map<String, String> output, String seperator) { String[] tokens = options.split(seperator); for (int i = 0; i < tokens.length; i++) { String[] items = tokens[i].split("="); String key = ""; String value = ""; key = items[0]; if (items.length > 1) { try { value = URLDecoder.decode(items[1], "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } output.put(key, value); } } private int parseRequestLine() throws IOException { // first read and parse the first line String line = in.readLine(); // parse the request line String[] tokens = line.split(" "); if (tokens.length < 2) { return HTTP.HTTP_BAD_REQUEST; } // get the method String token = tokens[0].toUpperCase(); if ("GET".equals(token)) { method = HTTP.HTTP_METHOD_GET; } else if ("POST".equals(token)) { method = HTTP.HTTP_METHOD_POST; } else if ("HEAD".equals(token)) { method = HTTP.HTTP_METHOD_HEAD; } else { return HTTP.HTTP_BAD_METHOD; } // get the raw url String rawUrl = tokens[1]; // parse the get methods // remove anchor tag location = (rawUrl.indexOf('#') > 0) ? rawUrl.split("#")[0] : rawUrl; // get 'GET' part rawGet = ""; if (location.indexOf('?') > 0) { tokens = location.split("\\?"); location = tokens[0]; rawGet = tokens[1]; parseRawString(rawGet, getValues, "&"); } // return ok return HTTP.HTTP_OK; } private int parseHeader() throws IOException { String line = null; // parse the header while (((line = in.readLine()) != null) && !line.equals("")) { String[] tokens = line.split(": "); headers.put(tokens[0].toLowerCase(), tokens[1].toLowerCase()); } // get cookies if (headers.containsKey("cookie")) { parseRawString(headers.get("cookie"), cookies, ";"); } return HTTP.HTTP_OK; } private int parseMessageBody() throws IOException { // if method is post, parse the post values if (method == HTTP.HTTP_METHOD_POST) { String contentType = headers.get("content-type"); // if multi-form part if ((contentType != null) && contentType.startsWith("multipart/form-data")) { rawPost = ""; int result = parseMultipartBody(); if (result != HTTP.HTTP_OK) { return result; } } else { if (!headers.containsKey("content-length")) { return HTTP.HTTP_LENGTH_REQUIRED; } int len = Integer.parseInt( headers.get("content-length"), 10); byte[] buf = new byte[len]; in.read(buf, 0, len); rawPost = new String(buf, "UTF-8"); parseRawString(rawPost, postValues, "&"); } } // handle POST end return HTTP.HTTP_OK; } private int parseMultipartBody() throws IOException { String contentType = headers.get("content-type"); String boundary = "--" + contentType.replaceAll("^.*boundary=\"?([^\";,]+)\"?.*$", "$1"); int blength = boundary.length(); if ((blength > 80) || (blength < 2)) { return HTTP.HTTP_BAD_REQUEST; } boolean done = false; String line = in.readLine(); while (!done && (line != null)) { if (boundary.equals(line)) { line = in.readLine(); } // parse the header HashMap<String, String> item = new HashMap<String, String>(); while (!line.equals("")) { String[] tokens = line.split(": "); item.put(tokens[0].toLowerCase(), tokens[1].toLowerCase()); line = in.readLine(); } // read body String disposition = item.get("content-disposition"); String name = disposition.replaceAll("^.* name=\"?([^\";]*)\"?.*$", "$1"); String filename = disposition.replaceAll( "^.* filename=\"?([^\";]*)\"?.*$", "$1"); if (disposition.equals(filename)) { filename = null; } // normal field if (filename == null) { String value = ""; // shouldn't be used more than once. while (((line = in.readLine()) != null) && !line.startsWith(boundary)) { value += line; } // read end if ((boundary + "--").equals(line)) { done = true; } // save post field postValues.put(name, value); // make rawPost if (rawPost.length() > 0) { rawPost += "&"; } try { rawPost += name + "=" + URLEncoder.encode(value, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } else { // read file data // should we create a temporary file ? File tempfile = File.createTempFile("httpd", ".file"); FileOutputStream out = new FileOutputStream(tempfile); // read the data until we much the content boundry byte[] buf = new byte[boundary.length() + 2]; byte[] bound = ("\r\n" + boundary).getBytes(); int len = in.read(buf, 0, buf.length); if (len < buf.length) { return HTTP.HTTP_BAD_REQUEST; } while (!Arrays.equals(buf, bound)) { // check boundry out.write(buf[0]); // write a byte to file // shift buffer to left System.arraycopy(buf, 1, buf, 0, buf.length - 1); // read a byte if (0 > in.read(buf, buf.length - 1, 1)) { return HTTP.HTTP_BAD_REQUEST; } } // close tempofle if (tempfile != null) { out.close(); } // result of reading file int fileResult = HttpFileUpload.RESULT_NOFILE; if (tempfile.length() > HttpFileUpload.MAXSIZE_FILE_UPLOAD) { fileResult = HttpFileUpload.RESULT_SIZE; } else if (tempfile.length() > 0) { fileResult = HttpFileUpload.RESULT_OK; } postFiles.put(name, new HttpFileUpload(filename, tempfile, fileResult)); // read the newline and check the end int ch = in.read(); if (ch != '\r') { if ((ch == '-') && (in.read() == '-')) { // is "--" done = true; } } else { // '\n' ch = in.read(); } if (ch == -1) { // eof done = true; } line = in.readLine(); } // if normal field or file } // while readLine // return ok return HTTP.HTTP_OK; } private int parseHttp() throws IOException { // parse request line int result = parseRequestLine(); if (result != HTTP.HTTP_OK) { return result; } // parse eader part result = parseHeader(); if (result != HTTP.HTTP_OK) { return result; } // parse body part result = parseMessageBody(); if (result != HTTP.HTTP_OK) { return result; } return HTTP.HTTP_OK; } public int getMethod() { return method; } public boolean isKeepAlive() { String connection = getHeader("connection"); if (connection != null) { return connection.charAt(0) == 'k'; // keep-alive or close } return false; } public String getHeader(String key) { return headers.get(key); } public String getCookie(String key) { return cookies.get(key); } public String getGet(String key) { return getValues.get(key); } public String getPost(String key) { return postValues.get(key); } public String getParameter(String key) { String value = getGet(key); if (value == null) { value = getPost(key); } if (value == null) { value = getCookie(key); } return value; } public String getLocation() { return location; } public Map<String, String> getCookies() { return cookies; } public Map<String, String> getGetValues() { return getValues; } public Map<String, String> getHeaders() { return headers; } public Map<String, HttpFileUpload> getPostFiles() { return postFiles; } public Map<String, String> getPostValues() { return postValues; } public String getRawGet() { return rawGet; } public String getRawPost() { return rawPost; } }
Java
package com.ams.amf; import java.io.DataInputStream; import java.util.ArrayList; import java.util.Date; import java.util.LinkedHashMap; import java.util.Map; import java.io.IOException; public class Amf0Deserializer { protected ArrayList<AmfValue> storedObjects = new ArrayList<AmfValue>(); protected ArrayList<AmfValue> storedStrings = new ArrayList<AmfValue>(); protected DataInputStream in; public Amf0Deserializer(DataInputStream in) { this.in = in; } private String readLongString() throws IOException { int len = in.readInt(); //32bit read byte[] buf = new byte[len]; in.read(buf, 0, len); return new String(buf, "UTF-8"); } private AmfValue readByType(int type) throws IOException, AmfException { AmfValue amfValue = null; switch(type) { case 0x00: //This specifies the data in the AMF packet is a numeric value. //All numeric values in Flash are 64 bit, big-endian. amfValue = new AmfValue(in.readDouble()); break; case 0x01: //This specifies the data in the AMF packet is a boolean value. amfValue = new AmfValue(in.readBoolean()); break; case 0x02: //This specifies the data in the AMF packet is an ASCII string. amfValue = new AmfValue(in.readUTF()); break; case 0x04: //This specifies the data in the AMF packet is a Flash movie. break; case 0x05: //This specifies the data in the AMF packet is a NULL value. amfValue = new AmfValue(null); break; case 0x06: //This specifies the data in the AMF packet is a undefined. amfValue = new AmfValue(); break; case 0x07: //This specifies the data in the AMF packet is a reference. break; case 0x03: //This specifies the data in the AMF packet is a Flash object. case 0x08: //This specifies the data in the AMF packet is a ECMA array. Map<String, AmfValue> hash = new LinkedHashMap<String, AmfValue>(); boolean isEcmaArray = (type == 0x08); int size = -1; if(isEcmaArray) { size = in.readInt(); // 32bit read } while(true) { String key = in.readUTF(); int k = in.readByte() & 0xFF; if (k == 0x09) break; // end of Object hash.put(key, readByType(k)); } amfValue = new AmfValue(hash); break; case 0x09: //This specifies the data in the AMF packet is the end of an object definition. break; case 0x0A: //This specifies the data in the AMF packet is a Strict array. ArrayList<AmfValue> array = new ArrayList<AmfValue>(); int len = in.readInt(); for(int i = 0; i < len; i++) { int k = in.readByte() & 0xFF; array.add(readByType(k)); } amfValue = new AmfValue(array); break; case 0x0B: //This specifies the data in the AMF packet is a date. double time_ms = in.readDouble(); int tz_min = in.readInt(); //16bit amfValue = new AmfValue(new Date((long)(time_ms + tz_min * 60 * 1000.0))); break; case 0x0C: //This specifies the data in the AMF packet is a multi-byte string. amfValue = new AmfValue(readLongString()); //32bit case 0x0D: //This specifies the data in the AMF packet is a an unsupported feature. break; case 0x0E: //This specifies the data in the AMF packet is a record set. break; case 0x0F: //This specifies the data in the AMF packet is a XML object. amfValue = new AmfXml(readLongString()); //32bit break; case 0x10: //This specifies the data in the AMF packet is a typed object. case 0x11: //the AMF 0 format was extended to allow an AMF 0 encoding context to be switched to AMF 3. throw new AmfSwitchToAmf3Exception("Switch To AMF3"); default: throw new AmfException("Unknown AMF0: " + type); } return amfValue; } public AmfValue read() throws IOException, AmfException { int type = in.readByte() & 0xFF; return readByType(type); } }
Java
package com.ams.amf; public class AmfSwitchToAmf3Exception extends AmfException { private static final long serialVersionUID = 1L; public AmfSwitchToAmf3Exception() { super(); } public AmfSwitchToAmf3Exception(String arg0) { super(arg0); } }
Java
package com.ams.amf; import java.io.DataOutputStream; import java.util.Date; import java.util.Map; import java.io.IOException; public class Amf0Serializer { protected DataOutputStream out; public Amf0Serializer(DataOutputStream out) { this.out = out; } private void writeLongString(String s) throws IOException { byte[] b = s.getBytes("UTF-8"); out.writeInt(b.length); out.write(b); } public void write(AmfValue amfValue) throws IOException { switch(amfValue.getKind()) { case AmfValue.AMF_INT: case AmfValue.AMF_NUMBER: out.writeByte(0x00); out.writeDouble(amfValue.number()); break; case AmfValue.AMF_BOOL: out.writeByte(0x01); out.writeBoolean(amfValue.bool()); break; case AmfValue.AMF_STRING: String s = amfValue.string(); if( s.length() <= 0xFFFF ) { out.writeByte(0x02); out.writeUTF(s); } else { out.writeByte(0x0C); writeLongString(s); } break; case AmfValue.AMF_OBJECT: if (amfValue.isEcmaArray()) { out.writeByte(0x08); // ECMA Array out.writeInt(0); } else { out.writeByte(0x03); } Map<String, AmfValue> v = amfValue.object(); for(String key : v.keySet()) { out.writeUTF(key); write(v.get(key)); } //end of Object out.writeByte(0); out.writeByte(0); out.writeByte(0x09); break; case AmfValue.AMF_ARRAY: out.writeByte(0x0A); AmfValue[] array = amfValue.array(); int len = array.length; out.writeInt(len); for(int i = 0; i < len; i++) { write(array[i]); } break; case AmfValue.AMF_DATE: Date d = amfValue.date(); out.writeDouble(d.getTime()); out.writeShort(0); // loose TZ break; case AmfValue.AMF_XML: String xml = amfValue.xml(); out.writeByte(0x0F); writeLongString(xml); break; case AmfValue.AMF_NULL: out.writeByte(0x05); break; case AmfValue.AMF_UNDEFINED: out.writeByte(0x06); break; } } }
Java
package com.ams.amf; public class AmfXml extends AmfValue { public AmfXml(String value) { this.kind = AMF_XML; this.value = value; } }
Java
package com.ams.amf; import java.io.DataOutputStream; import java.io.IOException; import java.util.Date; import java.util.LinkedHashMap; import java.util.Map; import com.ams.io.ByteBufferArray; import com.ams.io.ByteBufferOutputStream; public class AmfValue { public final static int AMF_INT = 1; public final static int AMF_NUMBER = 2; public final static int AMF_BOOL = 3; public final static int AMF_STRING = 4; public final static int AMF_OBJECT = 5; public final static int AMF_ARRAY = 6; public final static int AMF_DATE = 7; public final static int AMF_XML = 8; public final static int AMF_NULL = 9; public final static int AMF_UNDEFINED = 0; protected int kind = 0; protected Object value; protected boolean ecmaArray = false; public AmfValue() { this.kind = AMF_UNDEFINED; } public AmfValue(Object value) { if (value == null) this.kind = AMF_NULL; else if (value instanceof Byte || value instanceof Short || value instanceof Integer || value instanceof Long) this.kind = AMF_INT; else if (value instanceof Float || value instanceof Double) this.kind = AMF_NUMBER; else if (value instanceof Boolean) this.kind = AMF_BOOL; else if (value instanceof String) this.kind = AMF_STRING; else if (value instanceof Map) this.kind = AMF_OBJECT; else if (value instanceof Object[]) this.kind = AMF_ARRAY; else if (value instanceof Date) this.kind = AMF_DATE; this.value = value; } public AmfValue put(String key, Object v) { object().put(key, v instanceof AmfValue ? (AmfValue) v : new AmfValue(v)); return this; } public static AmfValue newObject() { return new AmfValue(new LinkedHashMap<String, AmfValue>()); } public static AmfValue newEcmaArray() { AmfValue value = new AmfValue(new LinkedHashMap<String, AmfValue>()); value.setEcmaArray(true); return value; } public static AmfValue newArray(Object ...values) { AmfValue[] array = new AmfValue[values.length]; for(int i = 0; i < values.length; i++) { Object v = values[i]; array[i] = v instanceof AmfValue ? (AmfValue) v : new AmfValue(v); } return new AmfValue(array); } public static AmfValue[] array(Object ...values) { AmfValue[] array = new AmfValue[values.length]; for(int i = 0; i < values.length; i++) { Object v = values[i]; array[i] = v instanceof AmfValue ? (AmfValue) v : new AmfValue(v); } return array; } public int getKind() { return kind; } public Integer integer() { if( value == null ) { throw new NullPointerException("parameter is null"); } if( kind != AmfValue.AMF_INT && kind != AmfValue.AMF_NUMBER ) { throw new IllegalArgumentException("parameter is not a Amf Integer or Amf Number"); } return ((Number)value).intValue(); } public Double number() { if( value == null ) { throw new NullPointerException("parameter is null"); } if( kind != AmfValue.AMF_INT && kind != AmfValue.AMF_NUMBER ) { throw new IllegalArgumentException("parameter is not a Amf Integer or Amf Number"); } return ((Number)value).doubleValue(); } public Boolean bool() { if( value == null ) { throw new NullPointerException("parameter is null"); } if( kind != AmfValue.AMF_BOOL ) { throw new IllegalArgumentException("parameter is not a Amf Bool"); } return (Boolean)value; } public String string() { if( value == null ) { throw new NullPointerException("parameter is null"); } if( kind != AmfValue.AMF_STRING ) { throw new IllegalArgumentException("parameter is not a Amf String"); } return (String)value; } public AmfValue[] array() { if( value == null ) { throw new NullPointerException("parameter is null"); } if( kind != AmfValue.AMF_ARRAY ) { throw new IllegalArgumentException("parameter is not a Amf Array"); } return (AmfValue[])value; } public Map<String, AmfValue> object() { if( value == null ) { throw new NullPointerException("parameter is null"); } if( kind != AmfValue.AMF_ARRAY && kind != AmfValue.AMF_OBJECT) { throw new IllegalArgumentException("parameter is not a Amf Object"); } return (Map<String, AmfValue>)value; } public Date date() { if( value == null ) { throw new NullPointerException("parameter is null"); } if( kind != AmfValue.AMF_DATE ) { throw new IllegalArgumentException("parameter is not a Amf Date"); } return (Date)value; } public String xml() { if( value == null ) { throw new NullPointerException("parameter is null"); } if( kind != AmfValue.AMF_XML ) { throw new IllegalArgumentException("parameter is not a Amf Xml"); } return (String)value; } public boolean isNull() { return kind == AmfValue.AMF_NULL; } public boolean isUndefined() { return kind == AmfValue.AMF_UNDEFINED; } public String toString() { String result; boolean first; switch(kind) { case AmfValue.AMF_INT: case AmfValue.AMF_NUMBER: case AmfValue.AMF_BOOL: case AmfValue.AMF_DATE: return value.toString(); case AmfValue.AMF_STRING: return "'" + (String)value + "'"; case AmfValue.AMF_OBJECT: Map<String, AmfValue> v = object(); result = "{"; first = true; for(String key : v.keySet()) { result += (first ? " " : ", ") + key + " => " + v.get(key).toString(); first = false; } result += "}"; return result; case AmfValue.AMF_ARRAY: AmfValue[] array = array(); result = "["; first = true; int len = array.length; for(int i = 0; i < len; i++) { result += (first ? " " : ", ") + array[i].toString(); first = false; } result += "]"; return result; case AmfValue.AMF_XML: return (String)value; case AmfValue.AMF_NULL: return "null"; case AmfValue.AMF_UNDEFINED: return "undefined"; } return ""; } public boolean isEcmaArray() { return ecmaArray; } public void setEcmaArray(boolean ecmaArray) { this.ecmaArray = ecmaArray; } public static ByteBufferArray toBinary(AmfValue[] values) { ByteBufferArray buf = new ByteBufferArray(); ByteBufferOutputStream out = new ByteBufferOutputStream(buf); Amf0Serializer serializer = new Amf0Serializer(new DataOutputStream(out)); try { for(int i = 0; i < values.length; i++) { serializer.write(values[i]); } out.flush(); } catch (IOException e) { return null; } return buf; } }
Java
package com.ams.amf; import java.io.DataOutputStream; import java.util.ArrayList; import java.util.Date; import java.util.Map; import java.io.IOException; public class Amf3Serializer { protected ArrayList<String> stringRefTable = new ArrayList<String>(); protected ArrayList<AmfValue> objectRefTable = new ArrayList<AmfValue>(); protected DataOutputStream out; public Amf3Serializer(DataOutputStream out) { this.out = out; } private void writeAmf3Int(int value) throws IOException { //Sign contraction - the high order bit of the resulting value must match every bit removed from the number //Clear 3 bits value &= 0x1fffffff; if(value < 0x80) { out.writeByte(value); } else if(value < 0x4000) { out.writeByte(value >> 7 & 0x7f | 0x80); out.writeByte(value & 0x7f); } else if(value < 0x200000) { out.writeByte(value >> 14 & 0x7f | 0x80); out.writeByte(value >> 7 & 0x7f | 0x80); out.writeByte(value & 0x7f); } else { out.writeByte(value >> 22 & 0x7f | 0x80); out.writeByte(value >> 15 & 0x7f | 0x80); out.writeByte(value >> 8 & 0x7f | 0x80); out.writeByte(value & 0xff); } } private void writeAmf3RefInt(int value) throws IOException { writeAmf3Int(value << 1); // low bit is 0 } private void writeAmf3ValueInt(int value) throws IOException { writeAmf3Int(value << 1 + 1); // low bit is 1 } private void writeAmf3EmptyString() throws IOException { out.writeByte(0x01); } private void writeAmf3String(String s) throws IOException { if( s.length() == 0) { //Write 0x01 to specify the empty string writeAmf3EmptyString(); } else { for(int i = 0; i < stringRefTable.size(); i++) { if (s.equals(stringRefTable.get(i))) { writeAmf3RefInt(i); return; } } byte[] b = s.getBytes("UTF-8"); writeAmf3ValueInt(b.length); out.write(b); stringRefTable.add(s); } } private void writeAmf3Object(AmfValue amfValue) throws IOException { for(int i = 0; i < objectRefTable.size(); i++) { if (amfValue.equals(objectRefTable.get(i))) { writeAmf3RefInt(i); return; } } writeAmf3ValueInt(0); Map<String, AmfValue> obj = amfValue.object(); for(String key : obj.keySet()) { writeAmf3String(key); write(obj.get(key)); } //end of Object writeAmf3EmptyString(); objectRefTable.add(amfValue); } private void writeAmf3Array(AmfValue amfValue) throws IOException { for(int i = 0; i < objectRefTable.size(); i++) { if (amfValue.equals(objectRefTable.get(i))) { writeAmf3RefInt(i); return; } } AmfValue[] array = amfValue.array(); int len = array.length; writeAmf3ValueInt(len); writeAmf3EmptyString(); for(int i = 0; i < len; i++) { write(array[i]); } objectRefTable.add(amfValue); } public void write(AmfValue amfValue) throws IOException { switch(amfValue.getKind()) { case AmfValue.AMF_INT: int v = amfValue.integer(); if (v >= -0x10000000 && v <= 0xFFFFFFF) { //check valid range for 29bits out.writeByte(0x04); writeAmf3Int(v); } else { //overflow condition would occur upon int conversion out.writeByte(0x05); out.writeDouble(v); } break; case AmfValue.AMF_NUMBER: out.writeByte(0x05); out.writeDouble(amfValue.number()); break; case AmfValue.AMF_BOOL: out.writeByte(amfValue.bool() ? 0x02 : 0x03); break; case AmfValue.AMF_STRING: out.writeByte(0x06); writeAmf3String(amfValue.string()); break; case AmfValue.AMF_OBJECT: //out.writeByte(0x0A); out.writeByte(0x09); writeAmf3Object(amfValue); break; case AmfValue.AMF_ARRAY: out.writeByte(0x09); writeAmf3Array(amfValue); break; case AmfValue.AMF_DATE: out.writeByte(0x08); writeAmf3Int(0x01); Date d = amfValue.date(); out.writeDouble(d.getTime()); break; case AmfValue.AMF_XML: out.writeByte(0x07); writeAmf3String(amfValue.string()); break; case AmfValue.AMF_NULL: out.writeByte(0x01); break; case AmfValue.AMF_UNDEFINED: out.writeByte(0x00); break; } } }
Java
package com.ams.amf; public class AmfException extends Exception { private static final long serialVersionUID = 1L; public AmfException() { super(); } public AmfException(String arg0) { super(arg0); } }
Java
package com.ams.amf; import java.io.DataInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.Map; public class Amf3Deserializer { protected ArrayList<String> stringRefTable = new ArrayList<String>(); protected ArrayList<AmfValue> objectRefTable = new ArrayList<AmfValue>(); protected DataInputStream in; public Amf3Deserializer(DataInputStream in) { this.in = in; } private int readAmf3Int() throws IOException { byte b1 = in.readByte(); if (b1 >= 0 && b1 <= 0x7f) { return b1; } byte b2 = in.readByte(); if (b2 >= 0 && b2 <= 0x7f) { return (b1 & 0x7f) << 7 | b2; } byte b3 = in.readByte(); if (b3 >= 0 && b3 <= 0x7f) { return (b1 & 0x7f) << 14 | (b2 & 0x7f) << 7 | b3 ; } byte b4 = in.readByte(); return (b1 & 0x7f) << 22 | (b2 & 0x7f) << 15 | (b3 & 0x7f) << 8 | b4 ; } private String readAmf3String() throws IOException { int v = readAmf3Int(); if (v == 1) { return ""; } if ((v & 0x01) == 0) { return stringRefTable.get(v >> 1); } byte[] b = new byte[v >> 1]; in.read(b); String str = new String(b, "UTF-8"); stringRefTable.add(str); return str; } private AmfValue readAmf3Array() throws IOException, AmfException { int v = readAmf3Int(); if ((v & 0x01) == 0) { //ref return objectRefTable.get(v >> 1); } int len = v >> 1; String s = readAmf3String(); if (s.equals("")) { //Strict Array ArrayList<AmfValue> array = new ArrayList<AmfValue>(); for(int i = 0; i < len; i++) { int k = in.readByte() & 0xFF; array.add(readByType(k)); } AmfValue obj = new AmfValue(array); objectRefTable.add(obj); return obj; } else { //assoc Array Map<String, AmfValue> hash = new LinkedHashMap<String, AmfValue>(); String key = s; while(true) { int k = in.readByte() & 0xFF; if (k == 0x01) break; // end of Object hash.put(key, readByType(k)); key = readAmf3String(); } AmfValue obj = new AmfValue(hash); objectRefTable.add(obj); return obj; } } private AmfValue readAmf3Object() throws IOException, AmfException { int v = readAmf3Int(); if ((v & 0x01) == 0) { //ref return objectRefTable.get(v >> 1); } readAmf3String(); //class name Map<String, AmfValue> hash = new LinkedHashMap<String, AmfValue>(); while(true) { String key = readAmf3String(); int k = in.readByte() & 0xFF; if (k == 0x01) break; // end of Object hash.put(key, readByType(k)); } AmfValue obj = new AmfValue(hash); objectRefTable.add(obj); return obj; } private AmfValue readByType(int type) throws IOException, AmfException { AmfValue amfValue = null; switch(type) { case 0x00: //This specifies the data in the AMF packet is a undefined. amfValue = new AmfValue(); break; case 0x01: //This specifies the data in the AMF packet is a NULL value. amfValue = new AmfValue(null); break; case 0x02: //This specifies the data in the AMF packet is a false boolean value. amfValue = new AmfValue(false); break; case 0x03: //This specifies the data in the AMF packet is a true boolean value. amfValue = new AmfValue(true); break; case 0x04: //This specifies the data in the AMF packet is a integer value. amfValue = new AmfValue(readAmf3Int()); break; case 0x05: //This specifies the data in the AMF packet is a double value. amfValue = new AmfValue(in.readDouble()); break; case 0x06: //This specifies the data in the AMF packet is a string value. amfValue = new AmfValue(readAmf3String()); break; case 0x07: //This specifies the data in the AMF packet is a xml doc value. // TODO break; case 0x08: //This specifies the data in the AMF packet is a date value. // TODO break; case 0x09: //This specifies the data in the AMF packet is a array value. amfValue = readAmf3Array(); break; case 0x0A: //This specifies the data in the AMF packet is a object value. amfValue = readAmf3Object(); break; case 0x0B: //This specifies the data in the AMF packet is a xml value. // TODO break; case 0x0C: //This specifies the data in the AMF packet is a byte array value. // TODO break; default: throw new AmfException("Unknown AMF3: " + type); } return amfValue; } public AmfValue read() throws IOException, AmfException { int type = in.readByte() & 0xFF; return readByType(type); } }
Java
package com.ams.server; import java.io.EOFException; import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.channels.*; public class SocketConnector extends Connector { private static final int MIN_READ_BUFFER_SIZE = 256; private static final int MAX_READ_BUFFER_SIZE = 64*1024; private SocketChannel channel = null; private ByteBuffer readBuffer = null; public SocketConnector() { super(); } public SocketConnector(SocketChannel channel) { super(); this.channel = channel; } public void connect(String host, int port) throws IOException { if (channel == null || !channel.isOpen()) { channel = SocketChannel.open(); channel.configureBlocking(false); } ConnectionListner listener = new ConnectionListner() { public void connectionEstablished(Connector conn) { synchronized(conn) { conn.notifyAll(); } } public void connectionClosed(Connector conn) { } }; addListner(listener); getDispatcher().addChannelToRegister(new ChannelInterestOps(channel, SelectionKey.OP_CONNECT, this)); long start = System.currentTimeMillis(); try { synchronized (this) { channel.connect(new InetSocketAddress(host, port)); wait(DEFAULT_TIMEOUT_MS); } } catch (InterruptedException e) { throw new IOException("connect interrupted"); } finally { removeListner(listener); } long now = System.currentTimeMillis(); if (now - start >= timeout) { throw new IOException("connect time out"); } } public void finishConnect(SelectionKey key) throws IOException { if (channel.isConnectionPending()) { channel.finishConnect(); open(); key.interestOps(SelectionKey.OP_READ); } } public void readChannel(SelectionKey key) throws IOException { if (readBuffer == null || readBuffer.remaining() < MIN_READ_BUFFER_SIZE ) { readBuffer = ByteBufferFactory.allocate(MAX_READ_BUFFER_SIZE); } long readBytes = channel.read(readBuffer); if (readBytes > 0) { ByteBuffer slicedBuffer = readBuffer.slice(); readBuffer.flip(); offerReadBuffer(new ByteBuffer[]{readBuffer}); readBuffer = slicedBuffer; if (isClosed()) { open(); } } else if (readBytes == -1) { close(); key.cancel(); key.attach(null); } keepAlive(); } protected synchronized void writeToChannel(ByteBuffer[] data) throws IOException { Selector writeSelector = null; SelectionKey writeKey = null; int retry = 0; int writeTimeout = 1000; try { while (data != null) { long len = channel.write(data); if (len < 0) { throw new EOFException(); } boolean hasRemaining = false; for (ByteBuffer buf : data) { if (buf.hasRemaining()) { hasRemaining = true; break; } } if (!hasRemaining) { break; } if (len > 0) { retry = 0; } else { retry++; // Check if there are more to be written. if (writeSelector == null) { writeSelector = SelectorFactory.getInstance().get(); try { writeKey = channel.register(writeSelector, SelectionKey.OP_WRITE); } catch (Exception e) { e.printStackTrace(); } } if (writeSelector.select(writeTimeout) == 0) { if (retry > 2) { throw new IOException("Client disconnected"); } } } } } finally { if (writeKey != null) { writeKey.cancel(); writeKey = null; } if (writeSelector != null) { SelectorFactory.getInstance().free(writeSelector); } keepAlive(); } } public SocketAddress getLocalEndpoint() { return channel.socket().getLocalSocketAddress(); } public SocketAddress getRemoteEndpoint() { return channel.socket().getRemoteSocketAddress(); } public SelectableChannel getChannel() { return channel; } }
Java
package com.ams.server; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.net.DatagramSocketImpl; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.NetworkInterface; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.channels.DatagramChannel; import java.nio.channels.SelectableChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.util.ArrayList; import java.util.HashMap; import java.util.concurrent.TimeUnit; public class MulticastConnector extends Connector { class ReadFrameBuffer { private ByteBuffer[] buffers; private int lastFrameIndex = 0; public ReadFrameBuffer(int capacity) { buffers = new ByteBuffer[capacity]; } public void set(int index, ByteBuffer buf) { int capacity = buffers.length; if (index >= capacity) { ByteBuffer[] tmp = new ByteBuffer[capacity * 3 / 2]; System.arraycopy(buffers, 0, tmp, 0, index); buffers = tmp; } buffers[index] = buf; } public void lastFrame(int index) { lastFrameIndex = index; } public boolean hasLostFrame() { for(int i = 0; i <= lastFrameIndex; i++ ) { if (buffers[i] == null) return true; } return false; } public ByteBuffer[] getFrames() { ByteBuffer[] buf = new ByteBuffer[lastFrameIndex + 1]; System.arraycopy(buffers, 0, buf, 0, lastFrameIndex + 1); return buf; } public void clear() { for(int i = 0; i < buffers.length; i++ ) { buffers[i] = null; } lastFrameIndex = 0; } } private static final int MAX_DATA_SIZE = 8192; private HashMap<SocketAddress, MulticastConnector> connectorMap = new HashMap<SocketAddress, MulticastConnector>(); private DatagramChannel channel; private SocketAddress groupAddr; private SocketAddress peer; private static ArrayList<InetAddress> localAddress = new ArrayList<InetAddress>(); static { try { localAddress = getLocalAddress(); } catch (IOException e) { } } private int currentSession = 0; private ReadFrameBuffer readFrameBuffer = new ReadFrameBuffer(256); private int session = (int) System.currentTimeMillis(); private int writeDelayTime = 10; // nano second public MulticastConnector() { super(); } public MulticastConnector(DatagramChannel channel, SocketAddress groupAddr) { super(); this.channel = channel; this.groupAddr = groupAddr; } @SuppressWarnings({ "unchecked", "unused" }) private void invokeSocketMethod(String method, Class[] paramClass, Object[] param) { try { // http://www.mernst.org/blog/archives/12-01-2006_12-31-2006.html // UGLY UGLY HACK: multicast support for NIO // create a temporary instanceof PlainDatagramSocket, set its fd and configure it Constructor<? extends DatagramSocketImpl> c = (Constructor<? extends DatagramSocketImpl>)Class.forName("java.net.PlainDatagramSocketImpl").getDeclaredConstructor(); c.setAccessible(true); DatagramSocketImpl socketImpl = c.newInstance(); Field channelFd = Class.forName("sun.nio.ch.DatagramChannelImpl").getDeclaredField("fd"); channelFd.setAccessible(true); Field socketFd = DatagramSocketImpl.class.getDeclaredField("fd"); socketFd.setAccessible(true); socketFd.set(socketImpl, channelFd.get(channel)); try { Method m = DatagramSocketImpl.class.getDeclaredMethod(method, paramClass); m.setAccessible(true); m.invoke(socketImpl, param); } catch (Exception e) { throw e; } finally { // important, otherwise the fake socket's finalizer will nuke the fd socketFd.set(socketImpl, null); } } catch (Exception e) { } } @SuppressWarnings("unchecked") public void joinGroup(SocketAddress groupAddr) { invokeSocketMethod("joinGroup", new Class[]{SocketAddress.class, NetworkInterface.class}, new Object[]{groupAddr, null}); } public void configureSocket() { invokeSocketMethod("setTimeToLive", new Class[]{Integer.class}, new Object[]{1}); invokeSocketMethod("setLoopbackMode", new Class[]{Boolean.class}, new Object[]{true}); } public void connect(String host, int port) throws IOException { if (channel == null || !channel.isOpen()) { channel = DatagramChannel.open(); channel.configureBlocking(false); channel.socket().bind(new InetSocketAddress(0)); configureSocket(); getDispatcher().addChannelToRegister(new ChannelInterestOps(channel, SelectionKey.OP_READ, this)); groupAddr = new InetSocketAddress(host, port); open(); } } public void finishConnect(SelectionKey key) throws IOException { // nothing to do } public void readChannel(SelectionKey key) throws IOException { ByteBuffer readBuffer = ByteBufferFactory.allocate(MAX_DATA_SIZE); SocketAddress remote = null; if ((remote = channel.receive(readBuffer)) != null) { // if remote is self, drop the packet if (localAddress.contains(((InetSocketAddress)remote).getAddress())) { return; } MulticastConnector conn = connectorMap.get(remote); if (conn == null) { conn = new MulticastConnector(channel, groupAddr); conn.setPeer(remote); for(ConnectionListner listener : listners) { conn.addListner(listener); } connectorMap.put(remote, conn); } readBuffer.flip(); conn.handleIncoming(readBuffer); } } protected synchronized void writeToChannel(ByteBuffer[] buf) throws IOException { ArrayList<ByteBuffer> buffers = new ArrayList<ByteBuffer>(); ByteBuffer frame = null; short sequnce = 0; int i = 0; session++; while (i < buf.length) { if (frame == null) { frame = ByteBufferFactory.allocate(MAX_DATA_SIZE); frame.putInt(session); frame.put((byte) 0); frame.putShort(sequnce++); } ByteBuffer data = buf[i]; int remaining = frame.remaining(); if (remaining >= data.remaining()) { frame.put(data); i++; } else { if (remaining > 0) { ByteBuffer slice = data.slice(); slice.limit(remaining); data.position(data.position() + remaining); frame.put(slice); } buffers.add(frame); frame = null; } } if (frame != null) { buffers.add(frame); } // session id: 4 byte // payload type: 1 byte, 0: data frame, 1: last frame, 0x10: join group, 0x11: leave group // sequnce number: 2 byte ByteBuffer[] frames = buffers.toArray(new ByteBuffer[buffers.size()]); frames[frames.length - 1].put(4, (byte) 1); handleOutgoing(groupAddr, frames); } private void handleIncoming(ByteBuffer frame) { keepAlive(); int sessionId = frame.getInt(); byte payloadType = frame.get(); short sequnceNum = frame.getShort(); ByteBuffer data = frame.slice(); if (currentSession == 0) { currentSession = sessionId; } if (sessionId < currentSession) { // drop this frame return; } if (sessionId > currentSession) { currentSession = sessionId; readFrameBuffer.clear(); } readFrameBuffer.set(sequnceNum, data); if (payloadType == 1) { // last frame? readFrameBuffer.lastFrame(sequnceNum); if (!readFrameBuffer.hasLostFrame()) { offerReadBuffer(readFrameBuffer.getFrames()); if (isClosed()) { open(); } } currentSession = 0; readFrameBuffer.clear(); } } private void handleOutgoing(SocketAddress remote, ByteBuffer[] frames) throws IOException { Selector writeSelector = null; SelectionKey writeKey = null; int writeTimeout = 1000; try { for(ByteBuffer frame : frames) { int retry = 0; frame.flip(); while(channel.send(frame, remote) == 0) { retry++; writeDelayTime += 10; // Check if there are more to be written. if (writeSelector == null) { writeSelector = SelectorFactory.getInstance().get(); try { writeKey = channel.register(writeSelector, SelectionKey.OP_WRITE); } catch (Exception e) { e.printStackTrace(); } } if (writeSelector.select(writeTimeout) == 0) { if (retry > 2) { throw new IOException("Client disconnected"); } } } try { TimeUnit.NANOSECONDS.sleep(writeDelayTime); } catch (InterruptedException e) { } } } finally { if (writeKey != null) { writeKey.cancel(); writeKey = null; } if (writeSelector != null) { SelectorFactory.getInstance().free(writeSelector); } keepAlive(); } } public long getKeepAliveTime() { return System.currentTimeMillis(); } public SocketAddress getLocalEndpoint() { return channel.socket().getLocalSocketAddress(); } public SocketAddress getRemoteEndpoint() { return channel.socket().getRemoteSocketAddress(); } public SelectableChannel getChannel() { return channel; } public SocketAddress getPeer() { return peer; } public void setPeer(SocketAddress addr) { this.peer = addr; } }
Java
package com.ams.server; import java.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 SlabByteBufferAllocator implements IByteBufferAllocator{ 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 = 1000; public ByteBufferCollector() { super(); try { setDaemon(true); } catch (Exception e) { } } public void run() { try { while (! Thread.interrupted()) { sleep(COLLECT_INTERVAL_MS); collect(); } } catch (InterruptedException e) { interrupt(); } } } public SlabByteBufferAllocator (){ 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; int index = (int) Math.ceil(Math.log((float)size / minChunkSize) / logFactor); if (index < 0) return 0; return index; } 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) { if (slabs == null) { init(); } // 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.InetAddress; import java.net.NetworkInterface; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.channels.*; import java.util.ArrayList; import java.util.Enumeration; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicLong; import com.ams.io.ByteBufferInputStream; import com.ams.io.ByteBufferOutputStream; import com.ams.io.IByteBufferReader; import com.ams.io.IByteBufferWriter; public abstract class Connector implements IByteBufferReader, IByteBufferWriter { protected static final int DEFAULT_TIMEOUT_MS = 30000; protected static final int MAX_QUEUE_SIZE = 1024; protected ConcurrentLinkedQueue<ByteBuffer> readQueue = new ConcurrentLinkedQueue<ByteBuffer>(); protected ConcurrentLinkedQueue<ByteBuffer> writeQueue = new ConcurrentLinkedQueue<ByteBuffer>(); protected ByteBuffer writeBuffer = null; protected AtomicLong available = new AtomicLong(0); protected int timeout = DEFAULT_TIMEOUT_MS; protected long keepAliveTime; protected boolean keepAlive = false; protected boolean closed = true; protected ArrayList<ConnectionListner> listners = new ArrayList<ConnectionListner>(); protected ByteBufferInputStream in; protected ByteBufferOutputStream out; private static Dispatcher dispatcher = null; private static Object dispatcherLock = new Object(); public Connector() { this.in = new ByteBufferInputStream(this); this.out = new ByteBufferOutputStream(this); keepAlive(); } public abstract void connect(String host, int port) throws IOException; public abstract void finishConnect(SelectionKey key) throws IOException; public abstract void readChannel(SelectionKey key) throws IOException; protected abstract void writeToChannel(ByteBuffer[] data) throws IOException; public abstract SocketAddress getLocalEndpoint(); public abstract SocketAddress getRemoteEndpoint(); public abstract SelectableChannel getChannel(); protected Dispatcher getDispatcher() throws IOException { if (dispatcher == null) { synchronized(dispatcherLock) { dispatcher = new Dispatcher(); Thread t = new Thread(dispatcher, "dispatcher"); t.setDaemon(true); t.start(); } } return dispatcher; } protected void keepAlive() { keepAliveTime = System.currentTimeMillis(); } public boolean isKeepAlive() { return keepAlive; } public void setKeepAlive(boolean keepAlive) { this.keepAlive = keepAlive; } public long getKeepAliveTime() { return keepAliveTime; } public synchronized void open() { keepAlive(); if (!isClosed()) return; closed = false; for (ConnectionListner listner : listners) { listner.connectionEstablished(this); } } public synchronized void close() { if (isClosed()) return; closed = true; if (!isKeepAlive()) { Channel channel = getChannel(); try { channel.close(); } catch (IOException e) { e.printStackTrace(); } } for (ConnectionListner listner : listners) { listner.connectionClosed(this); } } public boolean isClosed() { return closed; } public boolean isWriteBlocking() { return writeQueue.size() > MAX_QUEUE_SIZE; } public long available() { return available.get(); } public ByteBuffer peek() { return readQueue.peek(); } protected void offerReadBuffer(ByteBuffer buffers[]) { for(ByteBuffer buffer : buffers) { readQueue.offer(buffer); available.addAndGet(buffer.remaining()); } keepAlive(); synchronized (readQueue) { readQueue.notifyAll(); } } public synchronized ByteBuffer[] read(int size) throws IOException { ArrayList<ByteBuffer> list = new ArrayList<ByteBuffer>(); int length = size; while (length > 0) { // read a buffer with blocking ByteBuffer buffer = readQueue.peek(); if (buffer != null) { int remain = buffer.remaining(); if (length >= remain) { list.add(readQueue.poll()); length -= remain; available.addAndGet(-remain); } else { ByteBuffer slice = buffer.slice(); slice.limit(length); buffer.position(buffer.position() + length); list.add(slice); available.addAndGet(-length); length = 0; } } else { // wait new buffer append to queue // sleep for timeout ms long start = System.currentTimeMillis(); try { synchronized (readQueue) { readQueue.wait(timeout); } } catch (InterruptedException e) { throw new IOException("read interrupted"); } long now = System.currentTimeMillis(); if (now - start >= timeout) { throw new IOException("read time out"); } } } // end while return list.toArray(new ByteBuffer[list.size()]); } public synchronized void write(ByteBuffer[] data) throws IOException { for (ByteBuffer buf : data) { writeQueue.offer(buf); } } public synchronized void flush() throws IOException { if (out != null) out.flush(); ArrayList<ByteBuffer> writeBuffers = new ArrayList<ByteBuffer>(); ByteBuffer data; boolean hasData = false; while ((data = writeQueue.poll()) != null) { writeBuffers.add(data); hasData = true; } if (hasData) { writeToChannel(writeBuffers.toArray(new ByteBuffer[writeBuffers.size()])); } } public boolean waitDataReceived(int time) { if (available.get() == 0) { long start = System.currentTimeMillis(); try { synchronized (readQueue) { readQueue.wait(time); } } catch (InterruptedException e) { } long now = System.currentTimeMillis(); if (now - start >= timeout) { return false; } } return true; } public int getTimeout() { return timeout; } public void setTimeout(int timeout) { this.timeout = timeout; } public ByteBufferInputStream getInputStream() { return in; } public ByteBufferOutputStream getOutputStream() { return out; } public synchronized void addListner(ConnectionListner listener) { this.listners.add(listener); } public synchronized boolean removeListner(ConnectionListner listener) { return this.listners.remove(listener); } public static ArrayList<InetAddress> getLocalAddress() throws IOException { ArrayList<InetAddress> address = new ArrayList<InetAddress>(); for (Enumeration<NetworkInterface> ifaces = NetworkInterface .getNetworkInterfaces(); ifaces.hasMoreElements();) { NetworkInterface iface = ifaces.nextElement(); for (Enumeration<InetAddress> ips = iface.getInetAddresses(); ips .hasMoreElements();) { InetAddress ia = ips.nextElement(); address.add(ia); } } return address; } }
Java
package com.ams.server.protocol; import java.io.IOException; import java.util.HashMap; import com.ams.amf.AmfException; import com.ams.amf.AmfValue; import com.ams.message.MediaMessage; import com.ams.rtmp.RtmpConnection; import com.ams.rtmp.RtmpException; import com.ams.rtmp.RtmpHeader; import com.ams.rtmp.message.RtmpMessage; import com.ams.rtmp.message.RtmpMessageCommand; import com.ams.rtmp.net.NetConnectionException; import com.ams.rtmp.net.PublisherManager; import com.ams.rtmp.net.StreamPublisher; import com.ams.server.Connector; import com.ams.util.Log; public class SlaveHandler implements IProtocolHandler { private Connector conn; private RtmpConnection rtmp; private boolean keepAlive = true; private HashMap<Integer, String> streams = new HashMap<Integer, String>(); public void readAndProcessRtmpMessage() throws NetConnectionException, IOException, RtmpException, AmfException { if (!rtmp.readRtmpMessage()) return; RtmpHeader header = rtmp.getCurrentHeader(); RtmpMessage message = rtmp.getCurrentMessage(); switch( message.getType() ) { case RtmpMessage.MESSAGE_AMF0_COMMAND: RtmpMessageCommand command = (RtmpMessageCommand)message; if ("publish".equals(command.getName())) { int streamId = header.getStreamId(); AmfValue[] args = command.getArgs(); String publishName = args[1].string(); streams.put(streamId, publishName); if (PublisherManager.getPublisher(publishName) == null) { PublisherManager.addPublisher(new StreamPublisher(publishName)); } } else if ("closeStream".equals(command.getName())) { int streamId = header.getStreamId(); String publishName = streams.get(streamId); if (publishName == null) break; streams.remove(streamId); StreamPublisher publisher = (StreamPublisher) PublisherManager.getPublisher(publishName); publisher.close(); PublisherManager.removePublisher(publishName); } break; case RtmpMessage.MESSAGE_AUDIO: case RtmpMessage.MESSAGE_VIDEO: case RtmpMessage.MESSAGE_AMF0_DATA: int streamId = header.getStreamId(); String publishName = streams.get(streamId); if (publishName == null) break; StreamPublisher publisher = (StreamPublisher) PublisherManager.getPublisher(publishName); if (publisher != null) { publisher.publish(new MediaMessage(header.getTimestamp(), message)); } break; } } public void run() { if (conn.isClosed()) { clear(); return; } try { // waiting for data arriving if (conn.waitDataReceived(10)) { // read & process rtmp message readAndProcessRtmpMessage(); } } catch (Exception e) { e.printStackTrace(); } } public IProtocolHandler newInstance(Connector conn) { IProtocolHandler handle = new SlaveHandler(); handle.setConnection(conn); return handle; } public void clear() { conn.close(); keepAlive = false; } public void setConnection(Connector conn) { this.conn = conn; this.rtmp = new RtmpConnection(conn); } public boolean isKeepAlive() { return keepAlive; } }
Java
package com.ams.server.protocol; import java.io.IOException; import com.ams.http.DefaultServlet; import com.ams.http.HttpRequest; import com.ams.http.HttpResponse; import com.ams.http.ServletContext; import com.ams.server.Connector; import com.ams.util.Log; public class HttpHandler implements IProtocolHandler { private Connector conn; private ServletContext context; public HttpHandler(String contextRoot) throws IOException { this.context = new ServletContext(contextRoot); } public HttpHandler(ServletContext context) { this.context = context; } public void run() { try { Log.logger.info("http handler start"); HttpRequest request = new HttpRequest(conn.getInputStream()); HttpResponse response = new HttpResponse(conn.getOutputStream()); DefaultServlet servlet = new DefaultServlet(context); request.parse(); servlet.service(request, response); if (request.isKeepAlive()) { conn.setKeepAlive(true); } conn.flush(); conn.close(); Log.logger.info("http handler end"); } catch (IOException e) { Log.logger.warning(e.getMessage()); } } public void clear() { conn.close(); } public IProtocolHandler newInstance(Connector conn) { IProtocolHandler handle = new HttpHandler(context); handle.setConnection(conn); return handle; } public void setConnection(Connector conn) { this.conn = conn; } public boolean isKeepAlive() { return false; } }
Java
package com.ams.server.protocol; import com.ams.rtmp.net.NetConnection; import com.ams.rtmp.net.NetContext; import com.ams.rtmp.RtmpConnection; import com.ams.server.Connector; public class RtmpHandler implements IProtocolHandler { private Connector conn; private RtmpConnection rtmp; private NetConnection netConn; private NetContext context; private boolean keepAlive = true; public RtmpHandler(String contextRoot) { this.context = new NetContext(contextRoot); } public RtmpHandler(NetContext context) { this.context = context; } public void run() { if (conn.isClosed()) { clear(); return; } try { // waiting for data arriving if (conn.waitDataReceived(10)) { // read & process rtmp message netConn.readAndProcessRtmpMessage(); } // write client video/audio streams netConn.playStreams(); // write to socket channel conn.flush(); } catch (Exception e) { e.printStackTrace(); clear(); } } public IProtocolHandler newInstance(Connector conn) { IProtocolHandler handle = new RtmpHandler(context); handle.setConnection(conn); return handle; } public void clear() { conn.close(); netConn.close(); keepAlive = false; } public void setConnection(Connector conn) { this.conn = conn; this.rtmp = new RtmpConnection(conn); this.netConn = new NetConnection(rtmp, context); } public boolean isKeepAlive() { return keepAlive; } }
Java
package com.ams.server.protocol; import com.ams.server.Connector; public interface IProtocolHandler extends Runnable { public IProtocolHandler newInstance(Connector conn); public void setConnection(Connector conn); public void clear(); public boolean isKeepAlive(); }
Java
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 SELECT_TIMEOUT = 2 * 1000; private 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(); } } private void doSelect() { int selectedKeys = 0; try { selectedKeys = selector.select(SELECT_TIMEOUT); } catch (Exception e) { e.printStackTrace(); if (selector.isOpen()) { return; } } 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) { 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("close expired idle connector!"); 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 setTimeExpire(long timeExpire) { this.timeExpire = timeExpire; } 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.nio.ByteBuffer; public class SliceByteBufferAllocator { private ByteBuffer byteBuffer = null; private int poolSize = 8192 * 1024; public synchronized ByteBuffer allocate(int size) { if (byteBuffer == null || byteBuffer.capacity() - byteBuffer.limit() < size) { byteBuffer = ByteBuffer.allocateDirect(poolSize); } byteBuffer.limit(byteBuffer.position() + size); ByteBuffer slice = byteBuffer.slice(); byteBuffer.position(byteBuffer.limit()); return slice; } public void setPoolSize(int poolSize) { this.poolSize = poolSize; byteBuffer = null; } }
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) { SlabByteBufferAllocator allocator = new SlabByteBufferAllocator(); allocator.setPageSize(config.getSlabPageSize()); allocator.init(); ByteBufferFactory.setAllocator(allocator); } 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, "dispatcher").start(); } for (SocketAddress endpoint : acceptorMap.keySet()) { IAcceptor acceptor = acceptorMap.get(endpoint); acceptor.start(); new Thread(acceptor, "acceptor").start(); Log.logger.info("Start service on port: " + acceptor.getListenEndpoint()); } // establish replicate cluster if (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 handlerMap.get(endpoint); } else { if (endpoint instanceof InetSocketAddress) { SocketAddress endpointAny = new InetSocketAddress("0.0.0.0", ((InetSocketAddress)endpoint).getPort()); if (handlerMap.containsKey(endpointAny)) { return handlerMap.get(endpointAny); } } } return null; } 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.message.MediaMessage; 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, "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, "replicator").start(); } public static void publishMessage(String publishName, MediaMessage msg) { for (Replicator replicator : replicators) { replicator.publishMessage(publishName, msg); } } 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.AmfValue; import com.ams.message.MediaMessage; 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<MediaMessage> msgQueue = new ConcurrentLinkedQueue<MediaMessage>(); 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 addMessage(MediaMessage msg) { if (msgQueue.size() > MAX_EVENT_QUEUE_LENGTH) { msgQueue.clear(); } msgQueue.offer(msg); } public void replicate() throws IOException { ConcurrentLinkedQueue<MediaMessage> queue = msgQueue; MediaMessage msg = null; while((msg = queue.poll()) != null) { keepAliveTime = System.currentTimeMillis(); rtmp.writeRtmpMessage(CHANNEL_RTMP_PUBLISH, streamId, msg.getTimestamp(), (RtmpMessage)msg.getData()); } } public void publish() throws IOException { AmfValue[] args = AmfValue.array(null, publishName, "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 AmfValue(null)}; 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(); 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, MediaMessage msg) { if (!isConnected) return; Publisher publisher = publishMap.get(publishName); if (publisher != null) { publisher.addMessage(msg); } 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.nio.ByteBuffer; public interface IByteBufferAllocator { ByteBuffer allocate(int size); }
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.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 { Configuration config; private ServerSocket commandSocket; private Server server; public DaemonThread(Configuration config) throws IOException { this.config = config; this.commandSocket = new ServerSocket(config.getCommandPort()); createServerInstance(); } private void createServerInstance() { 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(); } } 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.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.net.Socket; import com.ams.config.Configuration; import com.ams.util.Log; public class Main { public static void main(String[] args) { System.setSecurityManager(null); DaemonThread daemon = null; 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!"); return; } try { daemon = new DaemonThread(config); } 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", config.getCommandPort()); 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 IByteBufferAllocator allocator = null; public static ByteBuffer allocate(int size) { if (allocator == null) { return ByteBuffer.allocateDirect(size); } return allocator.allocate(size); } public static void setAllocator(IByteBufferAllocator alloc) { allocator = alloc; } }
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.LinkedList; import java.util.Map; import com.ams.amf.AmfException; import com.ams.amf.AmfValue; import com.ams.rtmp.message.RtmpMessage; import com.ams.rtmp.message.RtmpMessageCommand; import com.ams.rtmp.net.StreamPlayer; 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 StreamPlayer 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); player = stream.createPlayer(null, fileName); player.seek(0); Log.logger.info("rtmp stream published."); } else { Log.logger.info(errorMsg); } break; } } private void connect() throws IOException { AmfValue[] args = {AmfValue.newObject().put("app", "")}; 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(); Map<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(); Map<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 AmfValue(null)}; 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 = AmfValue.array(null, publishName, "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(); Map<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 AmfValue(null)}; RtmpMessage message = new RtmpMessageCommand("closeStream", 0, args); rtmp.writeRtmpMessage(CHANNEL_RTMP_COMMAND, streamId, System.currentTimeMillis(), message); } private boolean handShake() { boolean success = true; while (!handshake.isHandshakeDone()) { try { handshake.doClientHandshake(); // write to socket channel conn.flush(); } catch (Exception e) { Log.logger.warning(e.toString()); success = false; break; } } return success; } public void run() { if (!handShake()) return; Log.logger.info("handshake done."); commands.add(CMD_CONNECT); while (true) { try { 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 (Exception e) { Log.logger.warning(e.toString()); break; } } try { closeStream(streamId); conn.flush(); Log.logger.info("stream closed."); } catch (IOException e) { Log.logger.warning(e.toString()); } } public static void main(String[] args) { if (args.length < 3) { 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) { Log.logger.warning(e.toString()); } } }
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 (! Thread.interrupted()) { sleep(30000); collect(); } } catch (InterruptedException e) { interrupt(); } } } private CacheCollector collector; private ConcurrentHashMap<String, CacheItem> items = new ConcurrentHashMap<String, CacheItem>(); public ObjectCache() { collector = new CacheCollector(); collector.start(); } public T get(String key) { T obj = null; if (items.containsKey(key)) { CacheItem item = items.get(key); // check for timeout if (!item.isExpired()) { item.access(); obj = item.getObject(); } else { items.remove(key); } } return obj; } public void put(String key, T obj) { items.put(key, new CacheItem(obj)); } public void put(String key, T obj, int expire) { items.put(key, new CacheItem(obj, expire)); } public void remove(String key) { items.remove(key); } }
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; public final class Utils { public static int from16Bit(byte[] b) { return (((b[0] & 0xFF) << 8) | (b[1] & 0xFF)) & 0xFFFF; } public static int from24Bit(byte[] b) { return (((b[0] & 0xFF) << 16) | ((b[1] & 0xFF) << 8) | (b[2] & 0xFF)) & 0xFFFFFF; } public static long from32Bit(byte[] b) { return (((b[0] & 0xFF) << 24) | ((b[1] & 0xFF) << 16) | ((b[2] & 0xFF) << 8) | (b[3] & 0xFF)) & 0xFFFFFFFFL; } public static int from16BitLittleEndian(byte[] b) { // 16 Bit read, LITTLE-ENDIAN return (((b[1] & 0xFF) << 8) | (b[0] & 0xFF)) & 0xFFFF; } public static int from24BitLittleEndian(byte[] b) { // 24 Bit read, LITTLE-ENDIAN return (((b[2] & 0xFF) << 16) | ((b[1] & 0xFF) << 8) | (b[0] & 0xFF)) & 0xFFFFFF; } public static long from32BitLittleEndian(byte[] b) { // 32 Bit read, LITTLE-ENDIAN return (((b[3] & 0xFF) << 24) | ((b[2] & 0xFF) << 16) | ((b[1] & 0xFF) << 8) | (b[0] & 0xFF)) & 0xFFFFFFFFL; } public static byte[] to16Bit(int v) { byte[] b = new byte[2]; b[1] = (byte) (v & 0xFF); b[0] = (byte) ((v & 0xFF00) >>> 8); return b; } public static byte[] to24Bit(int v) { byte[] b = new byte[3]; b[2] = (byte) (v & 0xFF); b[1] = (byte) ((v & 0xFF00) >>> 8); b[0] = (byte) ((v & 0xFF0000) >>> 16); return b; } public static byte[] to32Bit(long v) { byte[] b = new byte[4]; b[3] = (byte) (v & 0xFF); b[2] = (byte) ((v & 0xFF00) >>> 8); b[1] = (byte) ((v & 0xFF0000) >>> 16); b[0] = (byte) ((v & 0xFF000000) >>> 24); return b; } public static byte[] to16BitLittleEndian(int v) { // 16bit write, LITTLE-ENDIAN byte[] b = new byte[2]; b[0] = (byte) (v & 0xFF); b[1] = (byte) ((v & 0xFF00) >>> 8); return b; } public static byte[] to24BitLittleEndian(int v) { byte[] b = new byte[3]; b[0] = (byte) (v & 0xFF); b[1] = (byte) ((v & 0xFF00) >>> 8); b[2] = (byte) ((v & 0xFF0000) >>> 16); return b; } public static byte[] to32BitLittleEndian(long v) { byte[] b = new byte[4]; // 32bit write, LITTLE-ENDIAN b[0] = (byte) (v & 0xFF); b[1] = (byte) ((v & 0xFF00) >>> 8); b[2] = (byte) ((v & 0xFF0000) >>> 16); b[3] = (byte) ((v & 0xFF000000) >>> 24); return b; } }
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 int commandPort = 55555; 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("server.dispatchers"); if (dispatchersProp != null) { dispatcherThreadPoolSize = Integer.parseInt(dispatchersProp); } String workersProp = prop.getProperty("server.workers"); if (workersProp != null) { workerThreadPoolSize = Integer.parseInt(workersProp); } String commandProp = prop.getProperty("server.command.port"); if (workersProp != null) { commandPort = Integer.parseInt(commandProp); } 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.unicast.host"); if (host != null) { replicationHost = host; } portProp = prop.getProperty("replication.unicast.port"); if (portProp != null) { replicationPort = Integer.parseInt(portProp); } String slavesProp = prop.getProperty("replication.unicast.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 int getCommandPort() { return commandPort; } 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.Random; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; 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 static final byte[] HANDSHAKE_SERVER_BYTES = { (byte) 0x01, (byte) 0x86, (byte) 0x4f, (byte) 0x7f, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x6b, (byte) 0x04, (byte) 0x67, (byte) 0x52, (byte) 0xa2, (byte) 0x70, (byte) 0x5b, (byte) 0x51, (byte) 0xa2, (byte) 0x89, (byte) 0xca, (byte) 0xcc, (byte) 0x8e, (byte) 0x70, (byte) 0xf0, (byte) 0x06, (byte) 0x70, (byte) 0x0e, (byte) 0xd7, (byte) 0xb3, (byte) 0x73, (byte) 0x7f, (byte) 0x07, (byte) 0xc1, (byte) 0x72, (byte) 0xd6, (byte) 0xcb, (byte) 0x4c, (byte) 0xc0, (byte) 0x45, (byte) 0x0f, (byte) 0xf5, (byte) 0x4f, (byte) 0xec, (byte) 0xd0, (byte) 0x2f, (byte) 0x46, (byte) 0x2b, (byte) 0x76, (byte) 0x10, (byte) 0x92, (byte) 0x1b, (byte) 0x0e, (byte) 0xb6, (byte) 0xed, (byte) 0x71, (byte) 0x73, (byte) 0x45, (byte) 0xc1, (byte) 0xc6, (byte) 0x26, (byte) 0x0c, (byte) 0x69, (byte) 0x59, (byte) 0x7b, (byte) 0xbb, (byte) 0x53, (byte) 0xb9, (byte) 0x10, (byte) 0x4d, (byte) 0xea, (byte) 0xc1, (byte) 0xe7, (byte) 0x7b, (byte) 0x70, (byte) 0xde, (byte) 0xdc, (byte) 0xf8, (byte) 0x84, (byte) 0x90, (byte) 0xbf, (byte) 0x80, (byte) 0xe8, (byte) 0x85, (byte) 0xb2, (byte) 0x46, (byte) 0x2c, (byte) 0x78, (byte) 0xa1, (byte) 0x85, (byte) 0x01, (byte) 0x8f, (byte) 0x8b, (byte) 0x05, (byte) 0x3f, (byte) 0xa1, (byte) 0x0c, (byte) 0x1a, (byte) 0x78, (byte) 0x70, (byte) 0x8c, (byte) 0x8e, (byte) 0x77, (byte) 0x67, (byte) 0xbc, (byte) 0x19, (byte) 0x2f, (byte) 0xab, (byte) 0x26, (byte) 0xa1, (byte) 0x7e, (byte) 0x88, (byte) 0xd8, (byte) 0xce, (byte) 0x24, (byte) 0x63, (byte) 0x21, (byte) 0x75, (byte) 0x3a, (byte) 0x5a, (byte) 0x6f, (byte) 0xc2, (byte) 0xa1, (byte) 0x2d, (byte) 0x4f, (byte) 0x64, (byte) 0xb7, (byte) 0x7b, (byte) 0xf7, (byte) 0xef, (byte) 0xda, (byte) 0x45, (byte) 0xb2, (byte) 0x51, (byte) 0xfd, (byte) 0xcb, (byte) 0x74, (byte) 0x49, (byte) 0xfd, (byte) 0x63, (byte) 0x8b, (byte) 0x88, (byte) 0xfb, (byte) 0xde, (byte) 0x5a, (byte) 0x3b, (byte) 0xab, (byte) 0x7f, (byte) 0x75, (byte) 0x25, (byte) 0xbb, (byte) 0x35, (byte) 0x51, (byte) 0x03, (byte) 0x81, (byte) 0x12, (byte) 0xff, (byte) 0x66, (byte) 0x02, (byte) 0x3d, (byte) 0x88, (byte) 0xdc, (byte) 0x66, (byte) 0xa2, (byte) 0xfb, (byte) 0x09, (byte) 0x24, (byte) 0x9d, (byte) 0x86, (byte) 0xfd, (byte) 0xc4, (byte) 0x00, (byte) 0xc2, (byte) 0x8b, (byte) 0x6f, (byte) 0xb7, (byte) 0xb2, (byte) 0x15, (byte) 0x10, (byte) 0xc0, (byte) 0x1b, (byte) 0x71, (byte) 0xa8, (byte) 0x3e, (byte) 0x88, (byte) 0xeb, (byte) 0x7e, (byte) 0xf3, (byte) 0xb2, (byte) 0xe3, (byte) 0xe8, (byte) 0x3c, (byte) 0x00, (byte) 0x9b, (byte) 0x26, (byte) 0xba, (byte) 0xb4, (byte) 0x5f, (byte) 0x2c, (byte) 0x36, (byte) 0xf3, (byte) 0x4a, (byte) 0x59, (byte) 0x09, (byte) 0x1b, (byte) 0xe5, (byte) 0x00, (byte) 0x9d, (byte) 0xe4, (byte) 0x66, (byte) 0x4d, (byte) 0x05, (byte) 0x66, (byte) 0xd0, (byte) 0xd1, (byte) 0xd6, (byte) 0x94, (byte) 0x4f, (byte) 0x64, (byte) 0xa1, (byte) 0x2e, (byte) 0x8d, (byte) 0x2f, (byte) 0xb0, (byte) 0x06, (byte) 0x01, (byte) 0xb3, (byte) 0x00, (byte) 0x3d, (byte) 0x77, (byte) 0xcd, (byte) 0x1b, (byte) 0xdd, (byte) 0xcc, (byte) 0xbf, (byte) 0xe9, (byte) 0xcd, (byte) 0x1a, (byte) 0x6b, (byte) 0x68, (byte) 0xdd, (byte) 0x1c, (byte) 0x7b, (byte) 0xfd, (byte) 0x2e, (byte) 0xb1, (byte) 0x8b, (byte) 0x45, (byte) 0xfd, (byte) 0x5b, (byte) 0x48, (byte) 0x52, (byte) 0x03, (byte) 0x01, (byte) 0xe8, (byte) 0xf1, (byte) 0x0f, (byte) 0xe7, (byte) 0x27, (byte) 0xfc, (byte) 0x2a, (byte) 0x52, (byte) 0x7c, (byte) 0x14, (byte) 0x22, (byte) 0x8b, (byte) 0x74, (byte) 0xbd, (byte) 0xd9, (byte) 0x97, (byte) 0x63, (byte) 0xef, (byte) 0xfa, (byte) 0xa3, (byte) 0xd9, (byte) 0x21, (byte) 0x12, (byte) 0x0b, (byte) 0x04, (byte) 0x62, (byte) 0x02, (byte) 0x98, (byte) 0x41, (byte) 0xf2, (byte) 0xb4, (byte) 0xc3, (byte) 0xe3, (byte) 0xe2, (byte) 0x2b, (byte) 0x2a, (byte) 0xff, (byte) 0xca, (byte) 0xb4, (byte) 0x48, (byte) 0x1e, (byte) 0x82, (byte) 0x50, (byte) 0x90, (byte) 0x94, (byte) 0x37, (byte) 0x24, (byte) 0x7e, (byte) 0xa1, (byte) 0x03, (byte) 0x1a, (byte) 0xf0, (byte) 0x9f, (byte) 0x2b, (byte) 0xbe, (byte) 0x64, (byte) 0xe5, (byte) 0x53, (byte) 0xb9, (byte) 0xb6, (byte) 0x43, (byte) 0x8e, (byte) 0x26, (byte) 0x6c, (byte) 0x63, (byte) 0x72, (byte) 0x8d, (byte) 0xb7, (byte) 0x7c, (byte) 0xb8, (byte) 0x21, (byte) 0x8f, (byte) 0xbb, (byte) 0x1c, (byte) 0x2a, (byte) 0x4e, (byte) 0xc7, (byte) 0xec, (byte) 0xa7, (byte) 0xa9, (byte) 0xbc, (byte) 0x15, (byte) 0x10, (byte) 0xe9, (byte) 0x4c, (byte) 0x46, (byte) 0xa5, (byte) 0x60, (byte) 0xa9, (byte) 0x71, (byte) 0x41, (byte) 0xdd, (byte) 0x25, (byte) 0xf5, (byte) 0xc1, (byte) 0xf6, (byte) 0xbd, (byte) 0x75, (byte) 0x1f, (byte) 0xb0, (byte) 0x15, (byte) 0xe0, (byte) 0xed, (byte) 0xc2, (byte) 0x4b, (byte) 0xac, (byte) 0xf1, (byte) 0xc8, (byte) 0xef, (byte) 0xa3, (byte) 0x44, (byte) 0xbe, (byte) 0x90, (byte) 0xab, (byte) 0x77, (byte) 0x28, (byte) 0xbf, (byte) 0xc0, (byte) 0xe0, (byte) 0x63, (byte) 0xaf, (byte) 0xd9, (byte) 0x07, (byte) 0x9d, (byte) 0x93, (byte) 0x16, (byte) 0x90, (byte) 0x7a, (byte) 0xe2, (byte) 0xb4, (byte) 0xe8, (byte) 0xe2, (byte) 0x3e, (byte) 0x4b, (byte) 0x18, (byte) 0x5f, (byte) 0x3e, (byte) 0x87, (byte) 0x09, (byte) 0xbe, (byte) 0x36, (byte) 0xd0, (byte) 0x8f, (byte) 0x7c, (byte) 0x22, (byte) 0x13, (byte) 0x9f, (byte) 0xc5, (byte) 0x78, (byte) 0xe0, (byte) 0x54, (byte) 0x4c, (byte) 0xa7, (byte) 0x77, (byte) 0x3f, (byte) 0xdf, (byte) 0x87, (byte) 0x4a, (byte) 0x28, (byte) 0x7b, (byte) 0x47, (byte) 0x80, (byte) 0x6a, (byte) 0xf0, (byte) 0x50, (byte) 0xcc, (byte) 0xde, (byte) 0x4c, (byte) 0x44, (byte) 0x41, (byte) 0x74, (byte) 0x3d, (byte) 0x03, (byte) 0x37, (byte) 0x8b, (byte) 0xbf, (byte) 0x79, (byte) 0x5b, (byte) 0x8c, (byte) 0xb0, (byte) 0x2f, (byte) 0x6e, (byte) 0x9c, (byte) 0x98, (byte) 0x29, (byte) 0x22, (byte) 0x49, (byte) 0x2f, (byte) 0xc9, (byte) 0x6d, (byte) 0xf1, (byte) 0x08, (byte) 0xc4, (byte) 0x4f, (byte) 0xb1, (byte) 0x91, (byte) 0xb3, (byte) 0xee, (byte) 0x57, (byte) 0xc1, (byte) 0x17, (byte) 0x5d, (byte) 0xd0, (byte) 0xe8, (byte) 0x19, (byte) 0xfb, (byte) 0x9b, (byte) 0xd6, (byte) 0xa8, (byte) 0x56, (byte) 0x92, (byte) 0x04, (byte) 0x4c, (byte) 0x0e, (byte) 0xe0, (byte) 0x52, (byte) 0x93, (byte) 0x9a, (byte) 0xec, (byte) 0xed, (byte) 0xf3, (byte) 0xf7, (byte) 0xef, (byte) 0xd7, (byte) 0x33, (byte) 0xe3, (byte) 0xcd, (byte) 0xc7, (byte) 0x4b, (byte) 0xac, (byte) 0xb7, (byte) 0xa9, (byte) 0xa5, (byte) 0x13, (byte) 0x09, (byte) 0x6c, (byte) 0x94, (byte) 0x49, (byte) 0x72, (byte) 0x03, (byte) 0xf3, (byte) 0xcf, (byte) 0x15, (byte) 0x31, (byte) 0xbc, (byte) 0xb5, (byte) 0x68, (byte) 0xc2, (byte) 0x49, (byte) 0xe1, (byte) 0x6e, (byte) 0x7d, (byte) 0xcb, (byte) 0x4e, (byte) 0xec, (byte) 0xfc, (byte) 0xa7, (byte) 0xb7, (byte) 0xed, (byte) 0x1c, (byte) 0x02, (byte) 0x49, (byte) 0x0e, (byte) 0x7f, (byte) 0x25, (byte) 0xeb, (byte) 0xd1, (byte) 0x81, (byte) 0x81, (byte) 0xc0, (byte) 0xa7, (byte) 0x49, (byte) 0x32, (byte) 0x16, (byte) 0x11, (byte) 0x31, (byte) 0x59, (byte) 0x12, (byte) 0x43, (byte) 0xd3, (byte) 0xa6, (byte) 0x95, (byte) 0x4a, (byte) 0xc5, (byte) 0xfe, (byte) 0xdf, (byte) 0x14, (byte) 0xda, (byte) 0xa6, (byte) 0x5a, (byte) 0xc0, (byte) 0xd5, (byte) 0x6a, (byte) 0xaf, (byte) 0xb3, (byte) 0xde, (byte) 0x32, (byte) 0x2a, (byte) 0x13, (byte) 0x03, (byte) 0xd3, (byte) 0x10, (byte) 0x71, (byte) 0x0b, (byte) 0xc0, (byte) 0x1e, (byte) 0xcf, (byte) 0xdb, (byte) 0xaa, (byte) 0xcc, (byte) 0xa6, (byte) 0xb5, (byte) 0x65, (byte) 0x2e, (byte) 0xc4, (byte) 0x0b, (byte) 0x5c, (byte) 0xa7, (byte) 0x1c, (byte) 0x8b, (byte) 0x2d, (byte) 0x7f, (byte) 0xc0, (byte) 0x4c, (byte) 0x4a, (byte) 0xa4, (byte) 0x0b, (byte) 0xa0, (byte) 0x60, (byte) 0xc4, (byte) 0xcf, (byte) 0xb1, (byte) 0xbe, (byte) 0xe4, (byte) 0xe4, (byte) 0x50, (byte) 0xc9, (byte) 0xcc, (byte) 0xa0, (byte) 0xe8, (byte) 0x79, (byte) 0x12, (byte) 0xc4, (byte) 0xb4, (byte) 0x70, (byte) 0xf5, (byte) 0x84, (byte) 0x98, (byte) 0x83, (byte) 0xe2, (byte) 0xa9, (byte) 0x8f, (byte) 0xba, (byte) 0xff, (byte) 0x88, (byte) 0xa2, (byte) 0x21, (byte) 0xba, (byte) 0x00, (byte) 0x3d, (byte) 0xc4, (byte) 0x57, (byte) 0xe6, (byte) 0x6a, (byte) 0xf4, (byte) 0xdc, (byte) 0x01, (byte) 0x1e, (byte) 0xac, (byte) 0x0a, (byte) 0xcc, (byte) 0x49, (byte) 0xaf, (byte) 0x9c, (byte) 0xc7, (byte) 0xcd, (byte) 0xc1, (byte) 0x14, (byte) 0x6e, (byte) 0x12, (byte) 0x87, (byte) 0xf8, (byte) 0x22, (byte) 0xeb, (byte) 0xdf, (byte) 0x48, (byte) 0xda, (byte) 0x9f, (byte) 0xf2, (byte) 0x8b, (byte) 0xc1, (byte) 0xd2, (byte) 0x44, (byte) 0x94, (byte) 0xe4, (byte) 0x3e, (byte) 0xd0, (byte) 0x85, (byte) 0x56, (byte) 0xe4, (byte) 0x9a, (byte) 0xfd, (byte) 0xb9, (byte) 0xb3, (byte) 0x35, (byte) 0x38, (byte) 0x1d, (byte) 0x15, (byte) 0x4d, (byte) 0x28, (byte) 0xab, (byte) 0xb0, (byte) 0x17, (byte) 0xc0, (byte) 0x5b, (byte) 0x09, (byte) 0x86, (byte) 0x07, (byte) 0xfa, (byte) 0x69, (byte) 0xda, (byte) 0x65, (byte) 0xb8, (byte) 0xd9, (byte) 0x8f, (byte) 0xe6, (byte) 0xa1, (byte) 0x83, (byte) 0xab, (byte) 0x07, (byte) 0x98, (byte) 0x3c, (byte) 0x79, (byte) 0xf4, (byte) 0x59, (byte) 0x08, (byte) 0x8f, (byte) 0x83, (byte) 0x77, (byte) 0xbd, (byte) 0xa1, (byte) 0xa1, (byte) 0x76, (byte) 0x28, (byte) 0x9c, (byte) 0x0f, (byte) 0xcc, (byte) 0xdc, (byte) 0xce, (byte) 0x1f, (byte) 0x16, (byte) 0x02, (byte) 0x47, (byte) 0x98, (byte) 0x37, (byte) 0x96, (byte) 0x87, (byte) 0xb1, (byte) 0x70, (byte) 0x3a, (byte) 0xea, (byte) 0xa4, (byte) 0x65, (byte) 0x77, (byte) 0x98, (byte) 0x12, (byte) 0x27, (byte) 0x23, (byte) 0x47, (byte) 0xa8, (byte) 0x1b, (byte) 0x79, (byte) 0xc0, (byte) 0xec, (byte) 0x53, (byte) 0x32, (byte) 0xe6, (byte) 0xc1, (byte) 0x61, (byte) 0x7b, (byte) 0xa0, (byte) 0x98, (byte) 0x9f, (byte) 0xfc, (byte) 0x8d, (byte) 0xe8, (byte) 0x5c, (byte) 0xaf, (byte) 0xc6, (byte) 0xbf, (byte) 0x1f, (byte) 0xd1, (byte) 0x40, (byte) 0xdc, (byte) 0x28, (byte) 0x81, (byte) 0x34, (byte) 0x68, (byte) 0xb7, (byte) 0xda, (byte) 0x10, (byte) 0xf2, (byte) 0x63, (byte) 0x52, (byte) 0xcb, (byte) 0xe7, (byte) 0x18, (byte) 0x85, (byte) 0xd5, (byte) 0x99, (byte) 0x33, (byte) 0xee, (byte) 0x9a, (byte) 0x28, (byte) 0xfa, (byte) 0xdf, (byte) 0x6d, (byte) 0xcb, (byte) 0xc2, (byte) 0xce, (byte) 0x9d, (byte) 0xed, (byte) 0x9d, (byte) 0xbd, (byte) 0xfd, (byte) 0xd7, (byte) 0x0a, (byte) 0xe4, (byte) 0x89, (byte) 0xd3, (byte) 0x10, (byte) 0x9b, (byte) 0xdb, (byte) 0x6f, (byte) 0xd9, (byte) 0x37, (byte) 0x8b, (byte) 0x79, (byte) 0x9c, (byte) 0x94, (byte) 0xc2, (byte) 0x44, (byte) 0x31, (byte) 0x9f, (byte) 0x24, (byte) 0xef, (byte) 0x21, (byte) 0x1d, (byte) 0x5f, (byte) 0xd6, (byte) 0xf9, (byte) 0x99, (byte) 0x7b, (byte) 0xef, (byte) 0x59, (byte) 0xe6, (byte) 0xd6, (byte) 0xdd, (byte) 0x6a, (byte) 0x74, (byte) 0x82, (byte) 0xb8, (byte) 0xc5, (byte) 0xfb, (byte) 0x1d, (byte) 0xe8, (byte) 0xfc, (byte) 0x67, (byte) 0x4f, (byte) 0x4d, (byte) 0xb5, (byte) 0xcf, (byte) 0xa9, (byte) 0x52, (byte) 0x94, (byte) 0xc5, (byte) 0xb7, (byte) 0x32, (byte) 0xa0, (byte) 0x45, (byte) 0x0a, (byte) 0x35, (byte) 0x44, (byte) 0x59, (byte) 0x1e, (byte) 0x1c, (byte) 0x64, (byte) 0x89, (byte) 0x51, (byte) 0x80, (byte) 0x7b, (byte) 0x1f, (byte) 0x02, (byte) 0x77, (byte) 0x81, (byte) 0xfa, (byte) 0xe9, (byte) 0x26, (byte) 0x4c, (byte) 0x5f, (byte) 0xe2, (byte) 0x0d, (byte) 0x05, (byte) 0x55, (byte) 0xee, (byte) 0x71, (byte) 0x71, (byte) 0xfc, (byte) 0x35, (byte) 0x33, (byte) 0x22, (byte) 0x63, (byte) 0xf5, (byte) 0x36, (byte) 0x45, (byte) 0xf6, (byte) 0x2f, (byte) 0xd0, (byte) 0x13, (byte) 0xb7, (byte) 0x58, (byte) 0x4f, (byte) 0x35, (byte) 0x19, (byte) 0x59, (byte) 0x0a, (byte) 0xe5, (byte) 0xf8, (byte) 0x8a, (byte) 0x4c, (byte) 0x59, (byte) 0x32, (byte) 0xbf, (byte) 0xca, (byte) 0xb0, (byte) 0x06, (byte) 0xc2, (byte) 0x6c, (byte) 0xa9, (byte) 0x48, (byte) 0x5b, (byte) 0x4c, (byte) 0x76, (byte) 0x24, (byte) 0xae, (byte) 0x9d, (byte) 0x5b, (byte) 0x7b, (byte) 0x79, (byte) 0x38, (byte) 0x4e, (byte) 0x9e, (byte) 0x47, (byte) 0x12, (byte) 0x8a, (byte) 0xc6, (byte) 0xe0, (byte) 0x04, (byte) 0x37, (byte) 0x72, (byte) 0xdd, (byte) 0xaf, (byte) 0x3d, (byte) 0x0d, (byte) 0x68, (byte) 0x7e, (byte) 0xd8, (byte) 0x80, (byte) 0x7b, (byte) 0x07, (byte) 0x23, (byte) 0xce, (byte) 0x40, (byte) 0x4a, (byte) 0xed, (byte) 0x83, (byte) 0x55, (byte) 0x56, (byte) 0xfd, (byte) 0xdb, (byte) 0x95, (byte) 0xb3, (byte) 0x1c, (byte) 0x33, (byte) 0xf1, (byte) 0x43, (byte) 0xa8, (byte) 0x0e, (byte) 0x5e, (byte) 0x67, (byte) 0xd6, (byte) 0x3a, (byte) 0xd0, (byte) 0x89, (byte) 0x5e, (byte) 0x72, (byte) 0x77, (byte) 0x7f, (byte) 0x10, (byte) 0x3c, (byte) 0xc4, (byte) 0x7c, (byte) 0x9a, (byte) 0xa3, (byte) 0x55, (byte) 0xc5, (byte) 0xd3, (byte) 0x5b, (byte) 0x3a, (byte) 0xae, (byte) 0x12, (byte) 0x0c, (byte) 0x71, (byte) 0x73, (byte) 0xa0, (byte) 0x58, (byte) 0x90, (byte) 0x54, (byte) 0xa8, (byte) 0x1c, (byte) 0x31, (byte) 0x20, (byte) 0xdb, (byte) 0xde, (byte) 0xdd, (byte) 0x35, (byte) 0xb1, (byte) 0x09, (byte) 0xa2, (byte) 0xd0, (byte) 0x6e, (byte) 0x39, (byte) 0x39, (byte) 0xa5, (byte) 0x0a, (byte) 0x3d, (byte) 0x8a, (byte) 0x00, (byte) 0x4b, (byte) 0x95, (byte) 0x6f, (byte) 0x8c, (byte) 0x12, (byte) 0x41, (byte) 0xc6, (byte) 0x46, (byte) 0x10, (byte) 0x5e, (byte) 0x9d, (byte) 0x50, (byte) 0x85, (byte) 0x0e, (byte) 0x6b, (byte) 0x81, (byte) 0xa7, (byte) 0x3b, (byte) 0x35, (byte) 0xa6, (byte) 0x38, (byte) 0xf5, (byte) 0xc2, (byte) 0xba, (byte) 0x6c, (byte) 0x02, (byte) 0xda, (byte) 0x27, (byte) 0x29, (byte) 0x6e, (byte) 0xe9, (byte) 0x54, (byte) 0x41, (byte) 0xa4, (byte) 0x94, (byte) 0x75, (byte) 0xe8, (byte) 0x55, (byte) 0xc0, (byte) 0xe3, (byte) 0xc2, (byte) 0x91, (byte) 0x8a, (byte) 0x1d, (byte) 0xfb, (byte) 0x2b, (byte) 0xba, (byte) 0x43, (byte) 0xe7, (byte) 0x45, (byte) 0x85, (byte) 0xe8, (byte) 0x13, (byte) 0x07, (byte) 0x1d, (byte) 0x9c, (byte) 0x37, (byte) 0xa8, (byte) 0xf3, (byte) 0xca, (byte) 0xf4, (byte) 0x19, (byte) 0x77, (byte) 0xc4, (byte) 0x65, (byte) 0xd6, (byte) 0x18, (byte) 0x3e, (byte) 0x60, (byte) 0x08, (byte) 0x74, (byte) 0x49, (byte) 0xba, (byte) 0xc8, (byte) 0x86, (byte) 0x37, (byte) 0x8a, (byte) 0x0f, (byte) 0x79, (byte) 0x91, (byte) 0x53, (byte) 0x20, (byte) 0x23, (byte) 0x00, (byte) 0xb9, (byte) 0xc5, (byte) 0x1b, (byte) 0x01, (byte) 0xdd, (byte) 0x10, (byte) 0x34, (byte) 0x05, (byte) 0x42, (byte) 0xa0, (byte) 0x64, (byte) 0xab, (byte) 0x4d, (byte) 0x51, (byte) 0xf4, (byte) 0x53, (byte) 0x35, (byte) 0x18, (byte) 0xde, (byte) 0x20, (byte) 0x1f, (byte) 0xaa, (byte) 0xe2, (byte) 0x40, (byte) 0x0d, (byte) 0x6d, (byte) 0x77, (byte) 0x36, (byte) 0x1f, (byte) 0xee, (byte) 0x3a, (byte) 0x93, (byte) 0xdb, (byte) 0x1d, (byte) 0xd6, (byte) 0xa0, (byte) 0x23, (byte) 0xcc, (byte) 0xe6, (byte) 0xa8, (byte) 0x44, (byte) 0x8e, (byte) 0xae, (byte) 0x9c, (byte) 0xd7, (byte) 0x97, (byte) 0x6a, (byte) 0x99, (byte) 0xee, (byte) 0x40, (byte) 0x15, (byte) 0xd5, (byte) 0x5a, (byte) 0x6d, (byte) 0xf6, (byte) 0x9c, (byte) 0x2c, (byte) 0x52, (byte) 0xcd, (byte) 0xfa, (byte) 0xf4, (byte) 0xc8, (byte) 0x02, (byte) 0xee, (byte) 0xf2, (byte) 0x76, (byte) 0x8b, (byte) 0x49, (byte) 0x6d, (byte) 0x66, (byte) 0x83, (byte) 0x5f, (byte) 0xbe, (byte) 0x05, (byte) 0x8e, (byte) 0xf2, (byte) 0x27, (byte) 0x73, (byte) 0xdb, (byte) 0x00, (byte) 0xeb, (byte) 0x9a, (byte) 0xb4, (byte) 0xbf, (byte) 0x47, (byte) 0x9a, (byte) 0xbd, (byte) 0xf1, (byte) 0x4f, (byte) 0x70, (byte) 0xed, (byte) 0x33, (byte) 0xce, (byte) 0x31, (byte) 0x9d, (byte) 0x9f, (byte) 0x95, (byte) 0x80, (byte) 0x9e, (byte) 0x73, (byte) 0x11, (byte) 0x6c, (byte) 0x03, (byte) 0x7b, (byte) 0x6e, (byte) 0x62, (byte) 0x9c, (byte) 0xd0, (byte) 0xaa, (byte) 0xf6, (byte) 0x5d, (byte) 0xe0, (byte) 0xd8, (byte) 0x96, (byte) 0x94, (byte) 0x46, (byte) 0xd1, (byte) 0x10, (byte) 0x3c, (byte) 0x1b, (byte) 0x9d, (byte) 0x40, (byte) 0xdd, (byte) 0xab, (byte) 0xec, (byte) 0x8a, (byte) 0x5b, (byte) 0x1a, (byte) 0xb6, (byte) 0x19, (byte) 0x57, (byte) 0x99, (byte) 0x09, (byte) 0xe8, (byte) 0xec, (byte) 0x82, (byte) 0xdc, (byte) 0x06, (byte) 0x39, (byte) 0x86, (byte) 0x25, (byte) 0x3b, (byte) 0x67, (byte) 0xb5, (byte) 0x17, (byte) 0xc5, (byte) 0x6e, (byte) 0x6e, (byte) 0x1c, (byte) 0x6c, (byte) 0xea, (byte) 0xbe, (byte) 0xb8, (byte) 0xdd, (byte) 0x68, (byte) 0xf8, (byte) 0xf3, (byte) 0x18, (byte) 0xf2, (byte) 0x3c, (byte) 0x99, (byte) 0xdc, (byte) 0xa9, (byte) 0xd3, (byte) 0xb2, (byte) 0x7a, (byte) 0x40, (byte) 0x70, (byte) 0x4b, (byte) 0xc2, (byte) 0xd2, (byte) 0xa7, (byte) 0xb3, (byte) 0x42, (byte) 0x19, (byte) 0xff, (byte) 0x0b, (byte) 0xdf, (byte) 0x07, (byte) 0x0e, (byte) 0x6b, (byte) 0x8e, (byte) 0xef, (byte) 0x63, (byte) 0x92, (byte) 0xd6, (byte) 0x15, (byte) 0x57, (byte) 0x62, (byte) 0x12, (byte) 0x99, (byte) 0x96, (byte) 0x96, (byte) 0xa5, (byte) 0x34, (byte) 0x5a, (byte) 0x2c, (byte) 0x7c, (byte) 0xf6, (byte) 0xbc, (byte) 0x16, (byte) 0xb2, (byte) 0x90, (byte) 0xc3, (byte) 0x11, (byte) 0x5e, (byte) 0xba, (byte) 0x0e, (byte) 0xe4, (byte) 0x22, (byte) 0x84, (byte) 0x32, (byte) 0x50, (byte) 0xda, (byte) 0x1e, (byte) 0x37, (byte) 0x06, (byte) 0x5b, (byte) 0xef, (byte) 0x69, (byte) 0xb7, (byte) 0x6f, (byte) 0x10, (byte) 0xcb, (byte) 0xdc, (byte) 0x4d, (byte) 0xfd, (byte) 0xdb, (byte) 0xa3, (byte) 0xef, (byte) 0x54, (byte) 0xea, (byte) 0xda, (byte) 0x55, (byte) 0xba, (byte) 0x32, (byte) 0xf4, (byte) 0x86, (byte) 0x6b, (byte) 0xb1, (byte) 0xc8, (byte) 0xfc, (byte) 0x12, (byte) 0x9a, (byte) 0xfc, (byte) 0xda, (byte) 0xfd, (byte) 0x2a, (byte) 0xc2, (byte) 0x7f, (byte) 0x70, (byte) 0xce, (byte) 0x34, (byte) 0x38, (byte) 0xe6, (byte) 0x6a, (byte) 0x7d, (byte) 0x33, (byte) 0xa0, (byte) 0x16, (byte) 0xfb, (byte) 0xfd, (byte) 0xa7, (byte) 0xdf, (byte) 0x2e, (byte) 0xe3, (byte) 0x5f, (byte) 0x93, (byte) 0x39, (byte) 0xaa, (byte) 0x00, (byte) 0xc7, (byte) 0x38, (byte) 0x2e, (byte) 0x9c, (byte) 0xf3, (byte) 0xc4, (byte) 0x12, (byte) 0x46, (byte) 0xcf, (byte) 0x06, (byte) 0xfe, (byte) 0x0f, (byte) 0x82, (byte) 0x82, (byte) 0x74, (byte) 0x00, (byte) 0x71, (byte) 0xf8, (byte) 0x28, (byte) 0x2f, (byte) 0x9b, (byte) 0x3f, (byte) 0x9a, (byte) 0x42, (byte) 0x1b, (byte) 0x3e, (byte) 0xa6, (byte) 0x0e, (byte) 0x90, (byte) 0xa7, (byte) 0x45, (byte) 0xa6, (byte) 0xcd, (byte) 0x6e, (byte) 0x88, (byte) 0x94, (byte) 0x08, (byte) 0x3a, (byte) 0xe5, (byte) 0x56, (byte) 0x36, (byte) 0x77, (byte) 0x68, (byte) 0x2e, (byte) 0x39, (byte) 0xd3, (byte) 0x45, (byte) 0xee, (byte) 0x89, (byte) 0xf0, (byte) 0x71, (byte) 0x42, (byte) 0x2d, (byte) 0xe2, (byte) 0x1b, (byte) 0xf5, (byte) 0x11, (byte) 0xf0, (byte) 0xff, (byte) 0x05, (byte) 0x0c, (byte) 0x78, (byte) 0xa1, (byte) 0x65, (byte) 0xcf, (byte) 0x3c, (byte) 0x9e, (byte) 0xe3, (byte) 0x37, (byte) 0x72, (byte) 0x3a, (byte) 0x32, (byte) 0xcb, (byte) 0x1f, (byte) 0xfd, (byte) 0x9d, (byte) 0x4a, (byte) 0x0e, (byte) 0xf7, (byte) 0x0b, (byte) 0x2b, (byte) 0xaa, (byte) 0x57, (byte) 0x2c, (byte) 0x27, (byte) 0xb3, (byte) 0xa0, (byte) 0x2a, (byte) 0x0f, (byte) 0x85, (byte) 0x16, (byte) 0x6c, (byte) 0xe2, (byte) 0xe0, (byte) 0xa1, (byte) 0x48, (byte) 0x8e, (byte) 0x00, (byte) 0x8d, (byte) 0x6d, (byte) 0xc8, (byte) 0x10, (byte) 0xfd, (byte) 0x43, (byte) 0x96, (byte) 0x50, (byte) 0x07, (byte) 0x07, (byte) 0x9a, (byte) 0xbf, (byte) 0x50, (byte) 0x62, (byte) 0x76, (byte) 0x3e, (byte) 0xe1, (byte) 0xf7, (byte) 0x70, (byte) 0xc1, (byte) 0xb0, (byte) 0x79, (byte) 0x8e, (byte) 0x61, (byte) 0xe3, (byte) 0xfb, (byte) 0x05, (byte) 0x5f, (byte) 0xbb, (byte) 0x2d, (byte) 0x76, (byte) 0x69, (byte) 0x89, (byte) 0xf3, (byte) 0x1e, (byte) 0x62, (byte) 0xf6, (byte) 0x27, (byte) 0x3d, (byte) 0x3e, (byte) 0x41, (byte) 0x0f, (byte) 0xf5, (byte) 0x0f, (byte) 0xc7, (byte) 0xf3, (byte) 0x0e, (byte) 0x3b, (byte) 0xd5, (byte) 0xed, (byte) 0xcf, (byte) 0xef, (byte) 0x58, (byte) 0xfa, (byte) 0x39, (byte) 0xdf, (byte) 0x75, (byte) 0x85, (byte) 0x2b, (byte) 0x8b, (byte) 0xaa, (byte) 0x08, (byte) 0x72, (byte) 0x52, (byte) 0xa7, (byte) 0x98, (byte) 0x42, (byte) 0x95, (byte) 0x7b, (byte) 0xb7, (byte) 0xe7, (byte) 0x10, (byte) 0xfe, (byte) 0xdb, (byte) 0x54, (byte) 0x34, (byte) 0xfb, (byte) 0x91, (byte) 0x24, (byte) 0x1c, (byte) 0x07, (byte) 0xfb, (byte) 0x9c, (byte) 0xce, (byte) 0xd0, (byte) 0x46, (byte) 0xcf, (byte) 0xc4, (byte) 0x9d, (byte) 0x09, (byte) 0x49, (byte) 0x24, (byte) 0xec, }; private final static byte[] GenuineFMSConst = { (byte) 0x47, (byte) 0x65, (byte) 0x6e, (byte) 0x75, (byte) 0x69, (byte) 0x6e, (byte) 0x65, (byte) 0x20, (byte) 0x41, (byte) 0x64, (byte) 0x6f, (byte) 0x62, (byte) 0x65, (byte) 0x20, (byte) 0x46, (byte) 0x6c, (byte) 0x61, (byte) 0x73, (byte) 0x68, (byte) 0x20, (byte) 0x4d, (byte) 0x65, (byte) 0x64, (byte) 0x69, (byte) 0x61, (byte) 0x20, (byte) 0x53, (byte) 0x65, (byte) 0x72, (byte) 0x76, (byte) 0x65, (byte) 0x72, (byte) 0x20, (byte) 0x30, (byte) 0x30, (byte) 0x31, (byte) 0xf0, (byte) 0xee, (byte) 0xc2, (byte) 0x4a, (byte) 0x80, (byte) 0x68, (byte) 0xbe, (byte) 0xe8, (byte) 0x2e, (byte) 0x00, (byte) 0xd0, (byte) 0xd1, (byte) 0x02, (byte) 0x9e, (byte) 0x7e, (byte) 0x57, (byte) 0x6e, (byte) 0xec, (byte) 0x5d, (byte) 0x2d, (byte) 0x29, (byte) 0x80, (byte) 0x6f, (byte) 0xab, (byte) 0x93, (byte) 0xb8, (byte) 0xe6, (byte) 0x36, (byte) 0xcf, (byte) 0xeb, (byte) 0x31, (byte) 0xae }; private int state = STATE_UNINIT; private byte[] handShake; private Mac hmacSHA256; 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(); try { hmacSHA256 = Mac.getInstance("HmacSHA256"); } catch (Exception e) { e.printStackTrace(); } } private void readVersion() throws IOException, RtmpException { if( (in.readByte() & 0xFF) != 3 ) //version throw new RtmpException("Invalid version"); } 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 { byte[] b = new byte[HANDSHAKE_SIZE]; in.read(b, 0, b.length); return b; } private void writeHandshake(byte[] b) throws IOException { out.write(b, 0, b.length); } private byte[] calculateHmacSHA256(byte[] key, byte[] in) { byte[] out = null; try { hmacSHA256.init(new SecretKeySpec(key, "HmacSHA256")); out = hmacSHA256.doFinal(in); } catch (Exception e) { e.printStackTrace(); } return out; } private int GetClientGenuineConstDigestOffset(byte[] b) { return ((b[8] & 0x0ff) + (b[9] & 0x0ff) + (b[10] & 0x0ff) + (b[11] & 0x0ff)) % 728 + 12; } private int GetServerGenuineConstDigestOffset(byte[] b) { return ((b[772] & 0x0ff) + (b[773] & 0x0ff) + (b[774] & 0x0ff) + (b[775] & 0x0ff)) % 728 + 776; } private byte[] getHandshake(byte[] b) { long schema = (((b[4] & 0xFF) << 24) | ((b[5] & 0xFF) << 16) | ((b[6] & 0xFF) << 8) | (b[7] & 0xFF)) & 0xFFFFFFFFL; //Flash Player 10.0.32.18 int offset = schema < 0x80000302L ? GetClientGenuineConstDigestOffset(b) : GetServerGenuineConstDigestOffset(b); byte[] digest = new byte[32]; System.arraycopy(b, offset, digest, 0, 32); byte[] newKey = calculateHmacSHA256(GenuineFMSConst, digest); byte[] hash = new byte[HANDSHAKE_SIZE - 32]; Random rnd = new Random(); rnd.nextBytes(hash); byte[] newHandShake = new byte[HANDSHAKE_SIZE]; System.arraycopy(hash, 0, newHandShake, 0, hash.length); byte[] newPart = calculateHmacSHA256(newKey, hash); System.arraycopy(newPart, 0, newHandShake, hash.length, newPart.length); return newHandShake; } 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(HANDSHAKE_SERVER_BYTES); //write S1 message state = STATE_VERSION_SENT; break; case STATE_VERSION_SENT: if( available < HANDSHAKE_SIZE ) break; byte[] hs1 = readHandshake(); //read C1 message if (hs1[4] == 0) { // < Flash Player 9.0.115.0(Flash Player 9 update 3) writeHandshake(hs1); //write S2 message } else { writeHandshake(getHandshake(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; long timestamp = header.getTimestamp(); int size = header.getSize(); int type = header.getType(); int streamId = header.getStreamId(); if (timestamp != -1 && size != -1 && type != -1 && streamId != -1) fmt = 0; else if (timestamp != -1 && size != -1 && type != -1) fmt = 1; else if (timestamp != -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 if (timestamp >= 0x00FFFFFF) timestamp = 0x00FFFFFF; // send extended time stamp out.write24Bit((int)timestamp); } if(fmt == 0 || fmt == 1) { // type 0, type 1 header out.write24Bit(size); out.writeByte(type); } if(fmt == 0) { // type 0 header out.write32BitLittleEndian(streamId); } if(fmt == 3) { // type 3 header } // write extended time stamp if ((fmt ==0 || fmt == 1 || fmt == 2) && timestamp >= 0x00FFFFFF ) { out.write32Bit(timestamp); } } }
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 com.ams.io.ByteBufferArray; public class RtmpMessageUnknown extends RtmpMessage { private int messageType; private ByteBufferArray data; public RtmpMessageUnknown(int type, ByteBufferArray data) { super(MESSAGE_UNKNOWN); this.messageType = type; this.data = data; } public int getMessageType() { return messageType; } public ByteBufferArray 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 com.ams.io.ByteBufferArray; public class RtmpMessageAudio extends RtmpMessage { private ByteBufferArray data; public RtmpMessageAudio(ByteBufferArray data) { super(MESSAGE_AUDIO); this.data = data; } public ByteBufferArray getData() { return data.duplicate(); } }
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 com.ams.io.ByteBufferArray; public class RtmpMessageData extends RtmpMessage { private ByteBufferArray data; public RtmpMessageData(ByteBufferArray data) { super(MESSAGE_AMF0_DATA); this.data = data; } public ByteBufferArray getData() { return data.duplicate(); } }
Java
package com.ams.rtmp.message; import com.ams.io.ByteBufferArray; public class RtmpMessageVideo extends RtmpMessage { private ByteBufferArray data; public RtmpMessageVideo(ByteBufferArray data) { super(MESSAGE_VIDEO); this.data = data; } public ByteBufferArray getData() { return data.duplicate(); } }
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.ByteBufferArray; 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 ByteBufferArray getChunkData() { return new ByteBufferArray(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.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.ByteBufferArray; 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(); ByteBufferArray 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); //case RtmpMessage.MESSAGE_AGGREGATE: default: 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, 0, 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, 0, 0, 0, 0); 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; long ts = 0; if (fmt == 0) { // type 0 header ts = in.read24Bit(); lastHeader.setTimestamp(ts); // absolute timestamp } long lastTimestamp = lastHeader.getTimestamp(); if (fmt == 1 || fmt == 2) { // type 1, type 2 header ts = in.read24Bit(); lastHeader.setTimestamp(lastTimestamp + ts); // delta timestamp } 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 && ts >= 0x00FFFFFF ) { ts = in.read32Bit(); lastHeader.setTimestamp(ts); } if ((fmt == 1 || fmt == 2) && ts >= 0x00FFFFFF ) { ts = in.read32Bit(); lastHeader.setTimestamp(lastTimestamp + 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.ByteBufferArray; import com.ams.io.ByteBufferInputStream; import com.ams.io.ByteBufferOutputStream; import com.ams.rtmp.message.*; import com.ams.so.SoMessage; 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 { ByteBufferArray data = new ByteBufferArray(); ByteBufferOutputStream bos = new ByteBufferOutputStream(data); int msgType = message.getType(); switch(msgType) { case RtmpMessage.MESSAGE_USER_CONTROL: int event = ((RtmpMessageUserControl)message).getEvent(); int sid = ((RtmpMessageUserControl)message).getStreamId(); int ts = ((RtmpMessageUserControl)message).getTimestamp(); bos.write16Bit(event); switch(event) { case RtmpMessageUserControl.EVT_STREAM_BEGIN: case RtmpMessageUserControl.EVT_STREAM_EOF: case RtmpMessageUserControl.EVT_STREAM_DRY: case RtmpMessageUserControl.EVT_STREAM_IS_RECORDED: bos.write32Bit(sid); break; case RtmpMessageUserControl.EVT_SET_BUFFER_LENGTH: bos.write32Bit(sid); bos.write32Bit(ts); break; case RtmpMessageUserControl.EVT_PING_REQUEST: case RtmpMessageUserControl.EVT_PING_RESPONSE: bos.write32Bit(ts); break; } break; case RtmpMessage.MESSAGE_AMF0_COMMAND: { Amf0Serializer serializer = new Amf0Serializer(new DataOutputStream(bos)); String name = ((RtmpMessageCommand)message).getName(); int transactionId = ((RtmpMessageCommand)message).getTransactionId(); AmfValue[] args = ((RtmpMessageCommand)message).getArgs(); serializer.write(new AmfValue(name)); serializer.write(new AmfValue(transactionId)); for(int i = 0; i < args.length; i++) { serializer.write(args[i]); } break; } case RtmpMessage.MESSAGE_AMF3_COMMAND: { bos.writeByte(0); // no used byte Amf0Serializer serializer = new Amf0Serializer(new DataOutputStream(bos)); String name = ((RtmpMessageCommand)message).getName(); int transactionId = ((RtmpMessageCommand)message).getTransactionId(); AmfValue[] args = ((RtmpMessageCommand)message).getArgs(); serializer.write(new AmfValue(name)); serializer.write(new AmfValue(transactionId)); for(int i = 0; i < args.length; i++) { serializer.write(args[i]); } break; } case RtmpMessage.MESSAGE_AUDIO: data = ((RtmpMessageAudio)message).getData(); break; case RtmpMessage.MESSAGE_VIDEO: data = ((RtmpMessageVideo)message).getData(); break; case RtmpMessage.MESSAGE_AMF0_DATA: data = ((RtmpMessageData)message).getData(); break; case RtmpMessage.MESSAGE_AMF3_DATA: data = ((RtmpMessageData)message).getData(); break; case RtmpMessage.MESSAGE_SHARED_OBJECT: SoMessage so = ((RtmpMessageSharedObject)message).getData(); SoMessage.write(new DataOutputStream(bos), so); break; case RtmpMessage.MESSAGE_CHUNK_SIZE: int chunkSize = ((RtmpMessageChunkSize)message).getChunkSize(); bos.write32Bit(chunkSize); writeChunkSize = chunkSize; break; case RtmpMessage.MESSAGE_ABORT: sid = ((RtmpMessageAbort)message).getStreamId(); bos.write32Bit(sid); break; case RtmpMessage.MESSAGE_ACK: int nbytes = ((RtmpMessageAck)message).getBytes(); bos.write32Bit(nbytes); break; case RtmpMessage.MESSAGE_WINDOW_ACK_SIZE: int size = ((RtmpMessageWindowAckSize)message).getSize(); bos.write32Bit(size); break; case RtmpMessage.MESSAGE_PEER_BANDWIDTH: int windowAckSize = ((RtmpMessagePeerBandwidth)message).getWindowAckSize(); byte limitType = ((RtmpMessagePeerBandwidth)message).getLimitType(); bos.write32Bit(windowAckSize); bos.writeByte(limitType); break; case RtmpMessage.MESSAGE_UNKNOWN: int t = ((RtmpMessageUnknown)message).getMessageType(); data = ((RtmpMessageUnknown)message).getData(); break; } bos.flush(); int dataSize = data.size(); RtmpHeader header = new RtmpHeader( chunkStreamId, timestamp, dataSize, msgType, streamId); // write packet header + data headerSerializer.write(header); if (data == null) return; 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.Map; import com.ams.amf.*; import com.ams.flv.FlvDeserializer; import com.ams.flv.FlvException; import com.ams.flv.FlvSerializer; import com.ams.message.IMediaDeserializer; import com.ams.io.*; import com.ams.mp4.Mp4Deserializer; import com.ams.rtmp.RtmpConnection; import com.ams.rtmp.message.*; public class NetStream { private RtmpConnection rtmp; private int chunkStreamId = 3; private int streamId; private String streamName; private int transactionId = 0; private long timeStamp = 0; private StreamPublisher publisher = null; private StreamPlayer player = null; public NetStream(RtmpConnection rtmp, int streamId) { this.rtmp = rtmp; this.streamId = streamId; } public void writeMessage(RtmpMessage message) throws IOException { rtmp.writeRtmpMessage(chunkStreamId, streamId, timeStamp, message); } public void writeMessage(long time, RtmpMessage message) throws IOException { rtmp.writeRtmpMessage(chunkStreamId, streamId, time, message); } public void writeVideoMessage(RtmpMessage message) throws IOException { rtmp.writeRtmpMessage(5, streamId, timeStamp, message); } public void writeAudioMessage(RtmpMessage message) throws IOException { rtmp.writeRtmpMessage(6, streamId, timeStamp, message); } public void writeStatusMessage(String status, AmfValue info) throws IOException { AmfValue value = AmfValue.newObject(); value.put("level", "status") .put("code", status); Map<String, AmfValue> v = info.object(); for(String key : v.keySet()) { value.put(key, v.get(key).toString()); } writeMessage(new RtmpMessageCommand("onStatus", transactionId, AmfValue.array(null, value))); } public void writeErrorMessage(String msg) throws IOException { AmfValue value = AmfValue.newObject(); value.put("level", "error") .put("code", "NetStream.Error") .put("details", msg); writeMessage(new RtmpMessageCommand("onStatus", transactionId, AmfValue.array(null, value))); } public void writeDataMessage(AmfValue[] values) throws IOException { writeMessage(new RtmpMessageData(AmfValue.toBinary(values))); } public 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 StreamPlayer getPlayer() { return player; } public void setPlayer(StreamPlayer player) { this.player = player; } public StreamPublisher getPublisher() { return publisher; } public long getTimeStamp() { return timeStamp; } public void setTimeStamp(long timeStamp) { this.timeStamp = timeStamp; } public void seek(int time) throws NetConnectionException, IOException, FlvException { if (player == null) { writeErrorMessage("Invalid 'Seek' stream id " + streamId); return; } // clear rtmp.writeProtocolControlMessage(new RtmpMessageUserControl(RtmpMessageUserControl.EVT_STREAM_EOF, streamId)); rtmp.writeProtocolControlMessage(new RtmpMessageUserControl(RtmpMessageUserControl.EVT_STREAM_IS_RECORDED, streamId)); rtmp.writeProtocolControlMessage(new RtmpMessageUserControl(RtmpMessageUserControl.EVT_STREAM_BEGIN, streamId)); player.seek(time); writeStatusMessage("NetStream.Seek.Notify", AmfValue.newObject() .put("description", "Seeking " + time + ".") .put("details", streamName) .put("clientId", streamId)); writeStatusMessage("NetStream.Play.Start", AmfValue.newObject() .put("description", "Start playing " + streamName + ".") .put("clientId", streamId)); } public void play(NetContext context, String streamName, int start, int len) throws NetConnectionException, IOException, FlvException { if (player != null) { writeErrorMessage("This channel is already playing"); return; } this.streamName = streamName; // set chunk size rtmp.writeProtocolControlMessage(new RtmpMessageChunkSize(1024)); //NetStream.Play.Reset writeStatusMessage("NetStream.Play.Reset", AmfValue.newObject() .put("description", "Resetting " + streamName + ".") .put("details", streamName) .put("clientId", streamId)); // clear rtmp.writeProtocolControlMessage(new RtmpMessageUserControl(RtmpMessageUserControl.EVT_STREAM_IS_RECORDED, streamId)); rtmp.writeProtocolControlMessage(new RtmpMessageUserControl(RtmpMessageUserControl.EVT_STREAM_BEGIN, streamId)); //NetStream.Play.Start writeStatusMessage("NetStream.Play.Start", AmfValue.newObject() .put("description", "Start playing " + streamName + ".") .put("clientId", streamId)); 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; } StreamSubscriber subscriber = new StreamSubscriber(publisher); player = new StreamPlayer(subscriber, this); publisher.addSubscriber(subscriber); player.seek(0); } break; case -2: // first find live { StreamPublisher publisher = (StreamPublisher) PublisherManager.getPublisher(streamName); if (publisher != null) { StreamSubscriber subscriber = new StreamSubscriber(publisher); player = new StreamPlayer(subscriber, this); publisher.addSubscriber(subscriber); player.seek(0); } else { String tokens[] = streamName.split(":"); String type = ""; String file = streamName; if (tokens.length >= 2) { type = tokens[0]; file = tokens[1]; } String path = context.getRealPath(app, file, type); player = createPlayer(type, path); player.seek(0); } } break; default: // >= 0 String tokens[] = streamName.split(":"); String type = ""; String file = streamName; if (tokens.length >= 2) { type = tokens[0]; file = tokens[1]; } String path = context.getRealPath(app, file, type); player = createPlayer(type, path); player.seek(start); } } public StreamPlayer createPlayer(String type, String file) throws IOException { RandomAccessFileReader reader = new RandomAccessFileReader(file, 0); IMediaDeserializer sampleDeserializer = null; if ("mp4".equalsIgnoreCase(type)) { sampleDeserializer = new Mp4Deserializer(reader); } else { String ext = file.substring(file.lastIndexOf('.') + 1); if ("f4v".equalsIgnoreCase(ext) || "mp4".equalsIgnoreCase(ext)) { sampleDeserializer = new Mp4Deserializer(reader); } else { sampleDeserializer = new FlvDeserializer(reader); } } return new StreamPlayer(sampleDeserializer, this); } public void stop() throws IOException { //clear rtmp.writeProtocolControlMessage(new RtmpMessageUserControl(RtmpMessageUserControl.EVT_STREAM_EOF, streamId)); //NetStream.Play.Complete writeDataMessage(AmfValue.array("onPlayStatus", AmfValue.newObject() .put("level", "status") .put("code", "NetStream.Play.Complete"))); //clear rtmp.writeProtocolControlMessage(new RtmpMessageUserControl(RtmpMessageUserControl.EVT_STREAM_EOF, streamId)); //NetStream.Play.Stop writeStatusMessage("NetStream.Play.Stop", AmfValue.newObject() .put("description", "Stoped playing " + streamName + ".") .put("clientId", streamId)); setPlayer(null); } public void pause(boolean pause, long time) throws IOException, NetConnectionException, FlvException { if( player == null ) { writeErrorMessage("This channel is already closed"); return; } player.pause(pause); writeStatusMessage((pause ? "NetStream.Pause.Notify" : "NetStream.Unpause.Notify"), AmfValue.newObject()); } 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, ""); RandomAccessFileWriter writer = new RandomAccessFileWriter(file, false); publisher.setRecorder(new FlvSerializer(writer)); } else if ("append".equals(type)) { String file = context.getRealPath(app, name, ""); RandomAccessFileWriter writer = new RandomAccessFileWriter(file, true); publisher.setRecorder(new FlvSerializer(writer)); } else if ("live".equals(type)) { // nothing to do } PublisherManager.addPublisher(publisher); writeStatusMessage("NetStream.Publish.Start", AmfValue.newObject().put("details", name)); } 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.util.concurrent.ConcurrentLinkedQueue; import com.ams.message.IMediaDeserializer; import com.ams.message.MediaSample; import com.ams.message.IMsgSubscriber; public class StreamSubscriber implements IMediaDeserializer, IMsgSubscriber<MediaSample> { private StreamPublisher publisher; private ConcurrentLinkedQueue<MediaSample> receivedQueue; private static int MAX_QUEUE_LENGTH = 100; public StreamSubscriber(StreamPublisher publisher) { this.publisher = publisher; this.receivedQueue = new ConcurrentLinkedQueue<MediaSample>(); } public MediaSample metaData() { return publisher.getMetaData(); } public MediaSample videoHeaderData() { return publisher.getVideoHeader(); } public MediaSample audioHeaderData() { return publisher.getAudioHeader(); } public MediaSample seek(long seekTime) throws IOException { return publisher.getCurrentSample(); } public MediaSample readNext() throws IOException { return receivedQueue.poll(); } public void messageNotify(MediaSample msg) { if (receivedQueue.size() > MAX_QUEUE_LENGTH && msg.isVideoKeyframe()) { receivedQueue.clear(); } receivedQueue.offer(msg); } public synchronized void close() { receivedQueue.clear(); publisher.removeSubscriber(this); } }
Java
package com.ams.rtmp.net; import java.io.IOException; import com.ams.amf.AmfValue; import com.ams.io.ByteBufferArray; import com.ams.message.IMediaDeserializer; import com.ams.message.MediaSample; import com.ams.rtmp.message.*; public class StreamPlayer { private static int BUFFER_TIME = 3 * 1000; // x seconds of buffering private NetStream stream = null; private IMediaDeserializer deserializer; private long startTime = -1; private long bufferTime = BUFFER_TIME; private boolean pause = false; private boolean audioPlaying = true; private boolean videoPlaying = true; public StreamPlayer(IMediaDeserializer deserializer, NetStream stream) throws IOException { this.deserializer = deserializer; this.stream = stream; } public void close() throws IOException { deserializer.close(); } private void writeStartData() throws IOException { //|RtmpSampleAccess stream.writeDataMessage(AmfValue.array("|RtmpSampleAccess", false, false)); //NetStream.Data.Start stream.writeDataMessage(AmfValue.array("onStatus", AmfValue.newObject().put("code", "NetStream.Data.Start"))); MediaSample metaData = deserializer.metaData(); if (metaData != null) { stream.writeMessage(metaData.toRtmpMessage()); } MediaSample videoHeaderData = deserializer.videoHeaderData(); if (videoHeaderData != null) { stream.writeVideoMessage(videoHeaderData.toRtmpMessage()); } MediaSample audioHeaderData = deserializer.audioHeaderData(); if (audioHeaderData != null) { stream.writeAudioMessage(audioHeaderData.toRtmpMessage()); } } public void seek(long seekTime) throws IOException { MediaSample sample = deserializer.seek(seekTime); if (sample != null) { long currentTime = sample.getTimestamp(); startTime = System.currentTimeMillis() - bufferTime - currentTime; stream.setTimeStamp(currentTime); } writeStartData(); } public void play() throws IOException { if (pause) return; long time = System.currentTimeMillis() - startTime; while(stream.getTimeStamp() < time ) { MediaSample sample = deserializer.readNext(); if( sample == null ) { break; } long timestamp = sample.getTimestamp(); stream.setTimeStamp(timestamp); ByteBufferArray data = sample.getData(); if (sample.isAudioSample() && audioPlaying) { stream.writeAudioMessage(new RtmpMessageAudio(data)); } else if (sample.isVideoSample() && videoPlaying) { stream.writeVideoMessage(new RtmpMessageVideo(data)); } else if (sample.isMetaSample()) { stream.writeMessage(new RtmpMessageData(data)); } } } public void pause(boolean pause) { this.pause = pause; } public boolean isPaused() { return pause; } public void audioPlaying(boolean flag) { this.audioPlaying = flag; } public void videoPlaying(boolean flag) { this.videoPlaying = flag; } public void setBufferTime(long bufferTime) { this.bufferTime = bufferTime; } }
Java
package com.ams.rtmp.net; import com.ams.message.IMsgPublisher; import com.ams.util.ObjectCache; public class PublisherManager { private static int DEFAULT_EXPIRE_TIME = 24 * 60 * 60; private static ObjectCache<IMsgPublisher> streamPublishers = new ObjectCache<IMsgPublisher>(); public static IMsgPublisher 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.util.HashMap; import java.util.Map; import com.ams.amf.*; import com.ams.flv.FlvException; import com.ams.message.MediaMessage; 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()); } MediaMessage<RtmpMessage> msg = new MediaMessage<RtmpMessage>(header.getTimestamp(), message); publisher.publish(msg); if (publisher.isPing()) { rtmp.writeProtocolControlMessage(new RtmpMessageAck(publisher.getPingBytes())); } // replicate to all slave server ReplicateCluster.publishMessage(publisher.getPublishName(), msg); } 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(); Log.logger.info("command:" + cmdName); if ("connect".equals(cmdName)) { onConnect(header, command); } else if ("createStream".equals(cmdName)) { onCreateStream(header, command); } else if ("deleteStream".equals(cmdName)) { onDeleteStream(header, command); } else if ("closeStream".equals(cmdName)) { onCloseStream(header, command); } else if ("getStreamLength".equals(cmdName)) { onGetStreamLength(header, command); } else if ("play".equals(cmdName)) { onPlay(header, command); } else if ("play2".equals(cmdName)) { onPlay2(header, command); } else if ("publish".equals(cmdName)) { onPublish(header, command) ; } else if ("pause".equals(cmdName) || "pauseRaw".equals(cmdName)) { onPause(header, command); } else if ("receiveAudio".equals(cmdName)) { onReceiveAudio(header, command); } else if ("receiveVideo".equals(cmdName)) { onReceiveVideo(header, command); } else if ("seek".equals(cmdName)) { onSeek(header, command); } else { //remote rpc call onCall(header, command); } } private void onConnect(RtmpHeader header, RtmpMessageCommand command) throws NetConnectionException, IOException { AmfValue amfObject = command.getCommandObject(); Map<String, AmfValue> obj = amfObject.object(); String app = obj.get("app").string(); if (app == null) { netConnectionError(header.getChunkStreamId(), header.getStreamId(), command.getTransactionId(), "Invalid 'Connect' parameters"); return; } context.setAttribute("app", app); rtmp.writeProtocolControlMessage(new RtmpMessageWindowAckSize(128*1024)); rtmp.writeProtocolControlMessage(new RtmpMessagePeerBandwidth(128*1024, (byte)2)); rtmp.writeProtocolControlMessage(new RtmpMessageUserControl(RtmpMessageUserControl.EVT_STREAM_BEGIN, header.getStreamId())); AmfValue value0 = AmfValue.newObject(); value0.put("capabilities", 31) .put("fmsver", "AMS/0,1,0,0") .put("mode", 1); AmfValue value = AmfValue.newObject(); value.put("level", "status") .put("code", "NetConnection.Connect.Success") .put("description", "Connection succeeded."); AmfValue objectEncoding = obj.get("objectEncoding"); if (objectEncoding != null) { value.put("objectEncoding", objectEncoding); } rtmp.writeRtmpMessage(header.getChunkStreamId(), 0, 0, new RtmpMessageCommand("_result", command.getTransactionId(), AmfValue.array(value0, value))); } private void onGetStreamLength(RtmpHeader header, RtmpMessageCommand command) throws IOException, NetConnectionException, FlvException { AmfValue[] args = command.getArgs(); String streamName = args[1].string(); // rtmp.writeRtmpMessage(header.getChunkStreamId(), 0, 0, // new RtmpMessageCommand("_result", command.getTransactionId(), AmfValue.array(null, 140361))); } private void onPlay(RtmpHeader header, RtmpMessageCommand command) throws IOException, NetConnectionException, FlvException { AmfValue[] args = command.getArgs(); String streamName = args[1].string(); int start = (args.length > 2)?args[2].integer() : -2; int duration = (args.length > 3)?args[3].integer() : -1; NetStream stream = streams.get(header.getStreamId()); if( stream == null ) { streamError(header.getChunkStreamId(), header.getStreamId(), command.getTransactionId(), "Invalid 'Play' stream id "+ header.getStreamId()); return; } stream.setTransactionId(command.getTransactionId()); Log.logger.info("play stream:" + streamName); 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; } Log.logger.info("publish stream:" + publishName); 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(); rtmp.writeRtmpMessage(header.getChunkStreamId(), 0, 0, new RtmpMessageCommand("_result", command.getTransactionId(), AmfValue.array(null, stream.getStreamId()))); } private void onDeleteStream(RtmpHeader header, RtmpMessageCommand command) throws IOException, NetConnectionException { AmfValue[] args = command.getArgs(); int streamId = args[1].integer(); NetStream stream = 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 { AmfValue value = AmfValue.newObject(); value.put("level", "error") .put("code", code) .put("details", msg); rtmp.writeRtmpMessage(chunkStreamId, streamId, 0, new RtmpMessageCommand("onStatus", transactionId, AmfValue.array(null, value))); } public void netConnectionError(int chunkStreamId, int streamId, int transactionId, String msg) throws IOException { writeError(chunkStreamId, streamId, transactionId, "NetConnection", msg); } public void streamError(int chunkStreamId, int streamId, int transactionId, String msg) throws IOException { writeError(chunkStreamId, streamId, transactionId, "NetStream.Error", msg); } public void readAndProcessRtmpMessage() throws IOException, RtmpException, AmfException { if (!handshake.isHandshakeDone()) { handshake.doServerHandshake(); return; } 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; Log.logger.info("read message USER_CONTROL:" + userControl.getEvent() + ":" + userControl.getStreamId() + ":" + userControl.getTimestamp()); break; case RtmpMessage.MESSAGE_SHARED_OBJECT: onSharedMessage(header, message); break; case RtmpMessage.MESSAGE_CHUNK_SIZE: RtmpMessageChunkSize chunkSize = (RtmpMessageChunkSize)message; Log.logger.info("read message chunk size:" + chunkSize.getChunkSize()); break; case RtmpMessage.MESSAGE_ABORT: RtmpMessageAbort abort = (RtmpMessageAbort)message; Log.logger.info("read message abort:" + abort.getStreamId()); break; case RtmpMessage.MESSAGE_ACK: RtmpMessageAck ack = (RtmpMessageAck)message; //Log.logger.info("read message ack:" + ack.getBytes()); break; case RtmpMessage.MESSAGE_WINDOW_ACK_SIZE: RtmpMessageWindowAckSize ackSize = (RtmpMessageWindowAckSize)message; Log.logger.info("read message window ack size:" + ackSize.getSize()); break; case RtmpMessage.MESSAGE_PEER_BANDWIDTH: RtmpMessagePeerBandwidth peer = (RtmpMessagePeerBandwidth)message; Log.logger.info("read message peer bandwidth:" + peer.getWindowAckSize() + ":" + peer.getLimitType()); break; //case RtmpMessage.MESSAGE_AGGREGATE: // break; case RtmpMessage.MESSAGE_UNKNOWN: Log.logger.warning("read message UNKNOWN!"); break; } } catch(Exception e) { e.printStackTrace(); } } public void playStreams() { for(NetStream stream : streams.values()) { if(stream != null) { StreamPlayer player = stream.getPlayer(); if (player != null) { try { player.play(); } catch (EOFException e) { try { stream.stop(); } catch (IOException e1) { } } 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.util.LinkedList; import com.ams.message.*; import com.ams.rtmp.message.*; public class StreamPublisher implements IMsgPublisher<MediaMessage<RtmpMessage>, MediaSample> { private String publishName = null; private int pingBytes = 0; private int lastPing = 0; private boolean ping = false; private MediaSample videoHeader = null; private MediaSample audioHeader = null; private MediaSample meta = null; private MediaSample currentSample = null; private LinkedList<IMsgSubscriber<MediaSample>> subscribers = new LinkedList<IMsgSubscriber<MediaSample>>(); private IMediaSerializer recorder = null; // record to file stream public StreamPublisher(String publishName) { this.publishName = publishName; String tokens[] = publishName.split(":"); if (tokens.length >= 2) { this.publishName = tokens[1]; } } public synchronized void publish(MediaMessage<RtmpMessage> msg) throws IOException { long timestamp = msg.getTimestamp(); MediaSample sample = null; RtmpMessage message = msg.getData(); switch (message.getType()) { case RtmpMessage.MESSAGE_AUDIO: RtmpMessageAudio audio = (RtmpMessageAudio) message; sample = new MediaSample(MediaSample.SAMPLE_AUDIO, timestamp, audio.getData()); if (audioHeader == null) { if (sample.isH264AudioHeader()) { audioHeader = sample; } } break; case RtmpMessage.MESSAGE_VIDEO: RtmpMessageVideo video = (RtmpMessageVideo) message; sample = new MediaSample(MediaSample.SAMPLE_VIDEO, timestamp, video.getData()); if (videoHeader == null) { if (sample.isH264VideoHeader()) { videoHeader = sample; } } break; case RtmpMessage.MESSAGE_AMF0_DATA: RtmpMessageData m = (RtmpMessageData) message; sample = new MediaSample(MediaSample.SAMPLE_META, timestamp, m.getData()); meta = sample; break; } // record to file if (recorder != null) { recorder.write(sample); } // publish packet to other stream subscriber notify(sample); // ping ping(sample.getDataSize()); currentSample = sample; } public synchronized void close() { if (recorder != null) { recorder.close(); } subscribers.clear(); videoHeader = null; audioHeader = null; meta = null; } private void notify(MediaSample sample) { for (IMsgSubscriber<MediaSample> subscriber : subscribers) { subscriber.messageNotify(sample); } } private void ping(int dataSize) { pingBytes += dataSize; // ping ping = false; if (pingBytes - lastPing > 1024 * 10) { lastPing = pingBytes; ping = true; } } public void addSubscriber(IMsgSubscriber<MediaSample> subscrsiber) { synchronized (subscribers) { subscribers.add(subscrsiber); } } public void removeSubscriber(IMsgSubscriber<MediaSample> subscriber) { synchronized (subscribers) { subscribers.remove(subscriber); } } public void setRecorder(IMediaSerializer recorder) { this.recorder = recorder; } public boolean isPing() { return ping; } public int getPingBytes() { return pingBytes; } public String getPublishName() { return publishName; } public MediaSample getVideoHeader() { return videoHeader; } public MediaSample getAudioHeader() { return audioHeader; } public MediaSample getMetaData() { return meta; } public MediaSample getCurrentSample() { return currentSample; } }
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 getRealPath(String app, String path, String type) { if ("unkown/unkown".equals(MimeTypes.getMimeType(path))) { if (type == null || "".equals(type)) { path += ".flv"; } else { path += "." + type; } } if (app !=null && app.length() > 0) { return new File(contextRoot, app + File.separatorChar + path).getAbsolutePath(); } return new File(contextRoot, path).getAbsolutePath(); } }
Java
package com.ams.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("mp4", "video/mp4"); mimeMap.put("flv", "video/x-flv "); }; public static String getContentType(String extension) { String contentType = mimeMap.get(extension); if (contentType == null) contentType = "unkown/unkown"; return contentType; } public static String getMimeType(String file) { int index = file.lastIndexOf('.'); return (index++ > 0) ? MimeTypes.getContentType(file.substring(index)) : "unkown/unkown"; } }
Java
package com.ams.mp4; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import com.ams.util.Utils; public class BOX { public static class Header { public String type; public long headerSize; public long payloadSize; }; protected int version; public BOX(int version) { super(); this.version = version; } public static Header readHeader(InputStream in) throws IOException { Header header = new Header(); byte[] b = new byte[4]; int bytes = in.read(b, 0, 4); if (bytes == -1) throw new EOFException(); long size = Utils.from32Bit(b); b = new byte[4]; in.read(b, 0, 4); header.type = new String(b); header.headerSize = 8; if (size == 1) { // extended size header.headerSize = 16; b = new byte[4]; in.read(b, 0, 4); long size0 = Utils.from32Bit(b); in.read(b, 0, 4); size = (size0 << 32) + Utils.from32Bit(b); } header.payloadSize = size - header.headerSize; return header; } }
Java
package com.ams.mp4; import java.util.ArrayList; import com.ams.mp4.STSC.STSCRecord; import com.ams.mp4.STSD.AudioSampleDescription; import com.ams.mp4.STSD.SampleDescription; import com.ams.mp4.STSD.VideoSampleDescription; import com.ams.mp4.STTS.STTSRecord; public final class TRAK { private MDHD mdhd; private STSD stsd; private STSC stsc; private STTS stts; private STCO stco; private STSS stss; private STSZ stsz; public void setMdhd(MDHD mdhd) { this.mdhd = mdhd; } public void setStsd(STSD stsd) { this.stsd = stsd; } public void setStsc(STSC stsc) { this.stsc = stsc; } public void setStts(STTS stts) { this.stts = stts; } public void setStco(STCO stco) { this.stco = stco; } public void setStss(STSS stss) { this.stss = stss; } public void setStsz(STSZ stsz) { this.stsz = stsz; } public int getSampleIndex(long timeStamp) { long duration = 0; int index = 0; for (STTSRecord entry : stts.getEntries()) { int delta = entry.sampleDelta * entry.sampleCount; if (duration + delta >= timeStamp) { index += (timeStamp - duration) / entry.sampleDelta; break; } duration += delta; index += entry.sampleCount; } return index; } private long getSampleTimeStamp(int index) { long timeStamp = 0; int sampleCount = 0; for (STTSRecord entry : stts.getEntries()) { int delta = entry.sampleCount; if (sampleCount + delta >= index) { timeStamp += (index - sampleCount) * entry.sampleDelta; break; } timeStamp += entry.sampleDelta * entry.sampleCount; sampleCount += delta; } return timeStamp; } private long getChunkOffset(int chunk) { return stco.getOffsets()[chunk]; } private int getSampleSize(int index) { return stsz.getSizeTable()[index]; } private boolean isKeyFrameSample(int index) { if (stss == null) return false; for(int sync : stss.getSyncTable()) { if (index < sync - 1) return false; if (index == sync - 1) return true; } return true; } public Mp4Sample[] getAllSamples(int sampleType) { ArrayList<Mp4Sample> list = new ArrayList<Mp4Sample>(); int sampleIndex = 0; int prevFirstChunk = 0; int prevSamplesPerChunk = 0; int prevSampleDescIndex = 0; for (STSCRecord entry : stsc.getEntries()) { for (int chunk = prevFirstChunk; chunk < entry.firstChunk - 1; chunk++) { // chunk offset long sampleOffset = getChunkOffset(chunk); for (int i = 0; i < prevSamplesPerChunk; i++ ) { // sample size int sampleSize = getSampleSize(sampleIndex); // time stamp long timeStamp = 1000 * getSampleTimeStamp(sampleIndex) / getTimeScale(); // keyframe boolean keyframe = isKeyFrameSample(sampleIndex); // description index int sampleDescIndex = prevSampleDescIndex; list.add(new Mp4Sample(sampleType, timeStamp, keyframe, sampleOffset, sampleSize, sampleDescIndex)); sampleOffset += sampleSize; sampleIndex++; } } prevFirstChunk = entry.firstChunk - 1; prevSamplesPerChunk = entry.samplesPerChunk; prevSampleDescIndex = entry.sampleDescIndex; } int chunkSize = this.stco.getOffsets().length; for (int chunk = prevFirstChunk; chunk < chunkSize; chunk++) { // chunk offset long sampleOffset = getChunkOffset(chunk); for (int i = 0; i < prevSamplesPerChunk; i++ ) { // sample size int sampleSize = getSampleSize(sampleIndex); // time stamp long timeStamp = 1000 * getSampleTimeStamp(sampleIndex) / getTimeScale(); // keyframe boolean keyframe = isKeyFrameSample(sampleIndex); // description index int sampleDescIndex = prevSampleDescIndex; list.add(new Mp4Sample(sampleType, timeStamp, keyframe, sampleOffset, sampleSize, sampleDescIndex)); sampleOffset += sampleSize; sampleIndex++; } } return list.toArray(new Mp4Sample[list.size()]); } public byte[] getVideoDecoderConfigData() { if (stsd.getVideoSampleDescription() == null) return null; return stsd.getVideoSampleDescription().decoderConfig; } public byte[] getAudioDecoderConfigData() { if (stsd.getAudioSampleDescription() == null) return null; return stsd.getAudioSampleDescription().decoderSpecificConfig; } public VideoSampleDescription getVideoSampleDescription() { return stsd.getVideoSampleDescription(); } public AudioSampleDescription getAudioSampleDescription() { return stsd.getAudioSampleDescription(); } public int getTimeScale() { return mdhd.getTimeScale(); } public long getDuration() { return mdhd.getDuration(); } public float getDurationBySecond() { return (float)mdhd.getDuration() / (float)mdhd.getTimeScale(); } public String getLanguage() { return mdhd.getLanguage(); } public String getType() { SampleDescription desc = stsd.getDescription(); return desc.type; } public boolean isVideoTrack() { SampleDescription desc = stsd.getDescription(); return stsd.isVideoSampleDescription(desc); } public boolean isAudioTrack() { SampleDescription desc = stsd.getDescription(); return stsd.isAudioSampleDescription(desc); } }
Java
package com.ams.mp4; import java.io.DataInputStream; import java.io.IOException; public final class STSS extends BOX { private int[] syncTable; public STSS(int version) { super(version); } public void read(DataInputStream in) throws IOException { int count = in.readInt(); syncTable = new int[count]; for (int i=0; i < count; i++) { syncTable[i] = in.readInt(); } } public int[] getSyncTable() { return syncTable; } }
Java
package com.ams.mp4; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.EOFException; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import com.ams.amf.AmfValue; import com.ams.message.MediaSample; import com.ams.message.IMediaDeserializer; import com.ams.mp4.STSD.AudioSampleDescription; import com.ams.mp4.STSD.VideoSampleDescription; import com.ams.io.ByteBufferArray; import com.ams.io.ByteBufferInputStream; import com.ams.io.RandomAccessFileReader; import com.ams.server.ByteBufferFactory; public class Mp4Deserializer implements IMediaDeserializer { private RandomAccessFileReader reader; private TRAK videoTrak = null; private TRAK audioTrak = null; private Mp4Sample[] videoSamples; private Mp4Sample[] audioSamples; private ArrayList<Mp4Sample> samples = new ArrayList<Mp4Sample>(); private int sampleIndex = 0; private long moovPosition = 0; private static Comparator<Mp4Sample> sampleTimestampComparator = new Comparator<Mp4Sample>() { public int compare(Mp4Sample s, Mp4Sample t) { return (int)(s.getTimestamp() - t.getTimestamp()); } }; public Mp4Deserializer(RandomAccessFileReader reader) { this.reader = reader; MOOV moov = readMoov(reader); TRAK trak = moov.getVideoTrak(); if (trak != null) { videoTrak = trak; videoSamples = trak.getAllSamples(MediaSample.SAMPLE_VIDEO); samples.addAll(Arrays.asList(videoSamples)); } trak = moov.getAudioTrak(); if (trak != null) { audioTrak = trak; audioSamples = trak.getAllSamples(MediaSample.SAMPLE_AUDIO); samples.addAll(Arrays.asList(audioSamples)); } Collections.sort(samples, sampleTimestampComparator); } private MOOV readMoov(RandomAccessFileReader reader) { MOOV moov = null; try { reader.seek(0); for(;;) { // find moov box BOX.Header header = BOX.readHeader(new ByteBufferInputStream(reader)); long payloadSize = header.payloadSize; if ("moov".equalsIgnoreCase(header.type)) { moovPosition = reader.getPosition(); byte[] b = new byte[(int) payloadSize]; reader.read(b, 0, b.length); DataInputStream bin = new DataInputStream(new ByteArrayInputStream(b)); moov = new MOOV(); moov.read(bin); break; } else { reader.skip(payloadSize); } } } catch(IOException e) { moov = null; } return moov; } private ByteBuffer[] readSampleData(Mp4Sample sample) throws IOException { reader.seek(sample.getOffset()); return reader.read(sample.getSize()); } public MediaSample metaData() { AmfValue track1 = null; if (videoTrak != null) { track1 = AmfValue.newEcmaArray(); track1.put("length", videoTrak.getDuration()) .put("timescale", videoTrak.getTimeScale()) .put("language", videoTrak.getLanguage()) .put("sampledescription", AmfValue.newArray(AmfValue.newEcmaArray().put("sampletype", videoTrak.getType()))); } AmfValue track2 = null; if (audioTrak != null) { track2 = AmfValue.newEcmaArray(); track2.put("length", audioTrak.getDuration()) .put("timescale", audioTrak.getTimeScale()) .put("language", audioTrak.getLanguage()) .put("sampledescription", AmfValue.newArray(AmfValue.newEcmaArray().put("sampletype", audioTrak.getType()))); } AmfValue value = AmfValue.newEcmaArray(); if (videoTrak != null) { VideoSampleDescription videoSd = videoTrak.getVideoSampleDescription(); value.put("duration", videoTrak.getDurationBySecond()) .put("moovPosition", moovPosition) .put("width", videoSd.width) .put("height", videoSd.height) .put("canSeekToEnd", videoSamples[videoSamples.length - 1].isKeyframe()) .put("videocodecid", videoTrak.getType()) .put("avcprofile", videoSd.getAvcProfile()) .put("avclevel", videoSd.getAvcLevel()) .put("videoframerate", (float)videoSamples.length / videoTrak.getDurationBySecond()); } if (audioTrak != null) { AudioSampleDescription audioSd = audioTrak.getAudioSampleDescription(); value.put("audiocodecid", audioTrak.getType()) .put("aacaot", audioSd.getAudioCodecType()) .put("audiosamplerate", audioSd.sampleRate) .put("audiochannels", audioSd.channelCount); } value.put("trackinfo", AmfValue.newArray(track1, track2)); return new MediaSample(MediaSample.SAMPLE_META, 0, AmfValue.toBinary(AmfValue.array("onMetaData", value))); } public MediaSample videoHeaderData() { if (videoTrak == null) return null; byte[] data = videoTrak.getVideoDecoderConfigData(); int dataSize = (data != null) ? data.length : 0; ByteBuffer[] buf = new ByteBuffer[1]; buf[0] = ByteBufferFactory.allocate(5 + dataSize); buf[0].put(new byte[]{0x17, 0x00, 0x00, 0x00, 0x00}); if (data != null) { buf[0].put(data); } buf[0].flip(); return new MediaSample(MediaSample.SAMPLE_VIDEO, 0, new ByteBufferArray(buf)); } public MediaSample audioHeaderData() { if (audioTrak == null) return null; byte[] data = audioTrak.getAudioDecoderConfigData(); int dataSize = (data != null) ? data.length : 0; ByteBuffer[] buf = new ByteBuffer[1]; buf[0] = ByteBufferFactory.allocate(2 + dataSize); buf[0].put(new byte[]{(byte)0xaf, 0x00}); if (data != null) { buf[0].put(data); } buf[0].flip(); return new MediaSample(MediaSample.SAMPLE_AUDIO, 0, new ByteBufferArray(buf)); } private ByteBufferArray createVideoTag(Mp4Sample sample) throws IOException { ByteBuffer[] data = readSampleData(sample); ByteBuffer[] buf = new ByteBuffer[data.length + 1]; System.arraycopy(data, 0, buf, 1, data.length); buf[0] = ByteBufferFactory.allocate(5); byte type = (byte) (sample.isKeyframe() ? 0x17 : 0x27); buf[0].put(new byte[]{type, 0x01, 0, 0, 0}); buf[0].flip(); return new ByteBufferArray(buf); } private ByteBufferArray createAudioTag(Mp4Sample sample) throws IOException { ByteBuffer[] data = readSampleData(sample); ByteBuffer[] buf = new ByteBuffer[data.length + 1]; System.arraycopy(data, 0, buf, 1, data.length); buf[0] = ByteBufferFactory.allocate(2); buf[0].put(new byte[]{(byte)0xaf, 0x01}); buf[0].flip(); return new ByteBufferArray(buf); } public MediaSample seek(long seekTime) { Mp4Sample seekSample = videoSamples[0]; int idx = Collections.binarySearch(samples, new Mp4Sample(MediaSample.SAMPLE_VIDEO, seekTime, true, 0, 0, 0) , sampleTimestampComparator); int i = (idx >= 0) ? idx : -(idx + 1); while(i > 0) { seekSample = samples.get(i); if (seekSample.isVideoSample() && seekSample.isKeyframe()) { break; } i--; } sampleIndex = i; return seekSample; } public MediaSample readNext() throws IOException { if (sampleIndex < samples.size()) { Mp4Sample sample = samples.get(sampleIndex ++); if (sample.isVideoSample()) { return new MediaSample(MediaSample.SAMPLE_VIDEO, sample.getTimestamp(), createVideoTag(sample)); } if (sample.isAudioSample()) { return new MediaSample(MediaSample.SAMPLE_AUDIO, sample.getTimestamp(), createAudioTag(sample)); } } throw new EOFException(); } public void close() { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } }
Java
package com.ams.mp4; import java.io.DataInputStream; import java.io.IOException; public final class MDHD extends BOX { private long creationTime; private long modificationTime; private int timeScale; private long duration; private String language; public MDHD(int version) { super(version); } public void read(DataInputStream in) throws IOException { if (version == 0) { creationTime = in.readInt(); modificationTime = in.readInt(); } else { creationTime = in.readLong(); modificationTime = in.readLong(); } timeScale = in.readInt(); if (version == 0) { duration = in.readInt(); } else { duration = in.readLong(); } short l = in.readShort(); byte[] b = new byte[3]; b[2] = (byte) (0x60 + (l & 0x1F)); l >>>=5; b[1] = (byte) (0x60 + (l & 0x1F)); l >>>=5; b[0] = (byte) (0x60 + (l & 0x1F)); language = new String(b); } public long getCreationTime() { return creationTime; } public long getModificationTime() { return modificationTime; } public int getTimeScale() { return timeScale; } public long getDuration() { return duration; } public String getLanguage() { return language; } }
Java
package com.ams.mp4; import java.io.DataInputStream; import java.io.IOException; public final class STCO extends BOX { private long[] offsets; public STCO(int version) { super(version); } public void read(DataInputStream in) throws IOException { int count = in.readInt(); offsets = new long[count]; for (int i=0; i < count; i++) { offsets[i] = in.readInt(); } } public void read64(DataInputStream in) throws IOException { int count = in.readInt(); offsets = new long[count]; for (int i=0; i < count; i++) { offsets[i] = in.readLong(); } } public long[] getOffsets() { return offsets; } }
Java
package com.ams.mp4; import java.io.DataInputStream; import java.io.IOException; public final class STTS extends BOX { public final class STTSRecord { public int sampleCount; public int sampleDelta; } private STTSRecord[] entries; public STTS(int version) { super(version); } public void read(DataInputStream in) throws IOException { int count = in.readInt(); entries = new STTSRecord[count]; for (int i=0; i < count; i++) { entries[i] = new STTSRecord(); entries[i].sampleCount = in.readInt(); entries[i].sampleDelta = in.readInt(); } } public STTSRecord[] getEntries() { return entries; } }
Java
package com.ams.mp4; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.EOFException; import java.io.IOException; import java.util.ArrayList; public final class MOOV { private ArrayList<TRAK> traks = new ArrayList<TRAK>(); public void read(DataInputStream in) throws IOException { try { TRAK trak = null; while(true) { BOX.Header header = BOX.readHeader(in); String box = header.type; if ("trak".equalsIgnoreCase(box)) { trak = new TRAK(); traks.add(trak); continue; } else if ("mdia".equalsIgnoreCase(box)) { continue; } else if ("minf".equalsIgnoreCase(box)) { continue; } else if ("stbl".equalsIgnoreCase(box)) { continue; } byte[] b = new byte[(int) header.payloadSize]; in.read(b); DataInputStream bin = new DataInputStream(new ByteArrayInputStream(b)); int version = bin.readByte(); // version & flags bin.skipBytes(3); if ("mdhd".equalsIgnoreCase(box)) { MDHD mdhd = new MDHD(version); mdhd.read(bin); trak.setMdhd(mdhd); } else if ("stco".equalsIgnoreCase(box)) { STCO stco = new STCO(version); stco.read(bin); trak.setStco(stco); } else if ("co64".equalsIgnoreCase(box)) { STCO stco = new STCO(version); stco.read64(bin); trak.setStco(stco); } else if ("stsc".equalsIgnoreCase(box)) { STSC stsc = new STSC(version); stsc.read(bin); trak.setStsc(stsc); } else if ("stsd".equalsIgnoreCase(box)) { STSD stsd = new STSD(version); stsd.read(bin); trak.setStsd(stsd); } else if ("stss".equalsIgnoreCase(box)) { STSS stss = new STSS(version); stss.read(bin); trak.setStss(stss); } else if ("stsz".equalsIgnoreCase(box)) { STSZ stsz = new STSZ(version); stsz.read(bin); trak.setStsz(stsz); } else if ("stts".equalsIgnoreCase(box)) { STTS stts = new STTS(version); stts.read(bin); trak.setStts(stts); } } } catch(EOFException e) { } } public TRAK getVideoTrak() { for(TRAK trak : traks) { if (trak.isVideoTrack()) { return trak; } } return null; } public TRAK getAudioTrak() { for(TRAK trak : traks) { if (trak.isAudioTrack()) { return trak; } } return null; } }
Java
package com.ams.mp4; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.IOException; import com.ams.util.Utils; public final class STSD extends BOX { private SampleDescription[] descriptions; private VideoSampleDescription videoSampleDescription = null; private AudioSampleDescription audioSampleDescription = null; public static class SampleDescription { public String type; public byte[] description; } public static class VideoSampleDescription { public short index; public short preDefined1; public short reserved1; public int preDefined2; public int preDefined3; public int preDefined4; public short width; public short height; public int horizontalResolution; public int verticalResolution; public int reserved2; public short frameCount; public String compressorName; public short depth; public short preDefined5; public String configType; public byte[] decoderConfig; public byte getAvcProfile() { return decoderConfig[1]; } public byte getAvcLevel() { return decoderConfig[3]; } public void read(DataInputStream in) throws IOException { in.skipBytes(6); // reserved index = in.readShort(); preDefined1 = in.readShort(); reserved1 = in.readShort(); preDefined2 = in.readInt(); preDefined3 = in.readInt(); preDefined4 = in.readInt(); width = in.readShort(); height = in.readShort(); horizontalResolution = in.readInt(); verticalResolution = in.readInt(); reserved2 = in.readInt(); frameCount = in.readShort(); int nameSize = in.readByte(); byte[] nameBytes = new byte[nameSize]; in.read(nameBytes); compressorName = new String(nameBytes); in.skipBytes(31 - nameSize); depth = in.readShort(); preDefined5 = in.readShort(); int configSize = in.readInt(); byte[] b = new byte[4]; in.read(b); configType = new String(b); // avcC decoderConfig = new byte[configSize - 8]; in.read(decoderConfig); } } public static class AudioSampleDescription { public final static int ES_TAG = 3; public final static int DECODER_CONFIG_TAG = 4; public final static int DECODER_SPECIFIC_CONFIG_TAG = 5; public short index; public short innerVersion; public short revisionLevel; public int vendor; public short channelCount; public short sampleSize; public short compressionId; public short packetSize; public int sampleRate; public int samplesPerPacket; public int bytesPerPacket; public int bytesPerFrame; public int samplesPerFrame; public byte[] decoderSpecificConfig; public int getAudioCodecType() { int audioCodecType; switch(decoderSpecificConfig[0]) { case 0x12: default: //AAC LC - 12 10 audioCodecType = 1; break; case 0x0a: //AAC Main - 0A 10 audioCodecType = 0; break; case 0x11: case 0x13: //AAC LC SBR - 11 90 & 13 xx audioCodecType = 2; break; } return audioCodecType; } private int readDescriptor(DataInputStream in) throws IOException { int tag = in.readByte(); int size = 0; int c = 0; do { c = in.readByte(); size = (size << 7) | (c & 0x7f); } while ((c & 0x80) == 0x80); if (tag == DECODER_SPECIFIC_CONFIG_TAG) { decoderSpecificConfig = new byte[size]; in.read(decoderSpecificConfig); } return tag; } public void read(DataInputStream in) throws IOException { in.skipBytes(6); // reserved index = in.readShort(); innerVersion = in.readShort(); revisionLevel = in.readShort(); vendor = in.readInt(); channelCount = in.readShort(); sampleSize = in.readShort(); compressionId = in.readShort(); packetSize = in.readShort(); byte[] b = new byte[4]; in.read(b); sampleRate = Utils.from16Bit(b); if (innerVersion != 0) { samplesPerPacket = in.readInt(); bytesPerPacket = in.readInt(); bytesPerFrame = in.readInt(); samplesPerFrame = in.readInt(); } //read MP4Descriptor(in); int size = in.readInt(); in.read(new byte[4]); // "esds" in.readInt(); // version and flags int tag = readDescriptor(in); if (tag == ES_TAG) { in.skipBytes(3); } else { in.skipBytes(2); } tag = readDescriptor(in); if (tag == DECODER_CONFIG_TAG) { in.skipBytes(13); // DECODER_SPECIFIC_CONFIG_TAG tag = readDescriptor(in); } } } public STSD(int version) { super(version); } public void read(DataInputStream in) throws IOException { int count = in.readInt(); descriptions = new SampleDescription[count]; for (int i = 0 ; i < count; i++) { int length = in.readInt(); byte[] b = new byte[4]; in.read(b); String type = new String(b); byte[] description = new byte[length]; in.read(description); descriptions[i] = new SampleDescription(); descriptions[i].type = type; descriptions[i].description = description; } SampleDescription desc = getDescription(); if (isVideoSampleDescription(desc)) { videoSampleDescription = getVideoSampleDescription(desc); } else if (isAudioSampleDescription(desc)) { audioSampleDescription = getAudioSampleDescription(desc); } } public boolean isVideoSampleDescription(SampleDescription desc) { if ("avc1".equalsIgnoreCase(desc.type)) { return true; } return false; } public boolean isAudioSampleDescription(SampleDescription desc) { if ("mp4a".equalsIgnoreCase(desc.type)) { return true; } return false; } public SampleDescription getDescription() { return descriptions[0]; } public static VideoSampleDescription getVideoSampleDescription(SampleDescription desc) throws IOException { VideoSampleDescription sd = new VideoSampleDescription(); DataInputStream bin = new DataInputStream(new ByteArrayInputStream(desc.description)); sd.read(bin); return sd; } public static AudioSampleDescription getAudioSampleDescription(SampleDescription desc) throws IOException { AudioSampleDescription sd = new AudioSampleDescription(); DataInputStream bin = new DataInputStream(new ByteArrayInputStream(desc.description)); sd.read(bin); return sd; } public VideoSampleDescription getVideoSampleDescription() { return videoSampleDescription; } public AudioSampleDescription getAudioSampleDescription() { return audioSampleDescription; } }
Java
package com.ams.mp4; import java.io.DataInputStream; import java.io.IOException; public final class STSC extends BOX { public final class STSCRecord { public int firstChunk; public int samplesPerChunk; public int sampleDescIndex; } private STSCRecord[] entries; public STSC(int version) { super(version); } public void read(DataInputStream in) throws IOException { int count = in.readInt(); entries = new STSCRecord[count]; for (int i=0; i < count; i++) { entries[i] = new STSCRecord(); entries[i].firstChunk = in.readInt(); entries[i].samplesPerChunk = in.readInt(); entries[i].sampleDescIndex = in.readInt(); } } public STSCRecord[] getEntries() { return entries; } }
Java
package com.ams.mp4; import com.ams.message.MediaSample; public class Mp4Sample extends MediaSample { private int descriptionIndex; public Mp4Sample(int sampleType, long timestamp, boolean keyframe, long offset, int size, int sampleDescIndex) { super(sampleType, timestamp, keyframe, offset, size); this.descriptionIndex = sampleDescIndex; } public int getDescriptionIndex() { return descriptionIndex; } }
Java
package com.ams.mp4; import java.io.DataInputStream; import java.io.IOException; public final class STSZ extends BOX { private int constantSize; private int[] sizeTable; public STSZ(int version) { super(version); } public void read(DataInputStream in) throws IOException { constantSize = in.readInt(); int sizeCount = in.readInt(); if (sizeCount > 0) { sizeTable = new int[sizeCount]; for (int i = 0; i < sizeCount; i++) { sizeTable[i] = in.readInt(); } } } public int getConstantSize() { return constantSize; } public int[] getSizeTable() { return sizeTable; } }
Java
package org.clockworkmages.games.anno1186.generator; import java.util.ArrayList; import java.util.List; import org.clockworkmages.games.anno1186.GameApplication; import org.clockworkmages.games.anno1186.GameBeansContext; import org.clockworkmages.games.anno1186.GameDataService; import org.clockworkmages.games.anno1186.dao.FileUtil; import org.clockworkmages.games.anno1186.dao.GameFilesList; import org.clockworkmages.games.anno1186.dao.GameObjectsList; import org.clockworkmages.games.anno1186.dao.SerializationUtil; import org.clockworkmages.games.anno1186.generator.sets.BaseObjects; import org.clockworkmages.games.anno1186.generator.sets.BasicItems; import org.clockworkmages.games.anno1186.generator.sets.Beach; import org.clockworkmages.games.anno1186.generator.sets.CharacterCreation; import org.clockworkmages.games.anno1186.generator.sets.Jungle; import org.clockworkmages.games.anno1186.generator.sets.Palos; import org.clockworkmages.games.anno1186.generator.sets.PalosCardPlayer; import org.clockworkmages.games.anno1186.generator.sets.PalosFence; import org.clockworkmages.games.anno1186.generator.sets.PalosJuan; import org.clockworkmages.games.anno1186.generator.sets.Tiles; public class GenerateAndRun { // private Logger logger = LogManager.getLogger(this.getClass()); public static final String ROOT_DIR = "C:/developer/workspace/anno1186/src/main/resources/data/"; private List<String> gameObjectResourceFiles = new ArrayList<String>(); public void run() { GameApplication.initContextBeans(); GameApplication.createAndShowGUI(); add(new BaseObjects()); add(new Tiles()); add(new BasicItems()); add(new CharacterCreation()); add(new Palos()); add(new PalosJuan()); add(new PalosCardPlayer()); add(new PalosFence()); add(new Beach()); add(new Jungle()); createResourceListFile(); // javax.swing.SwingUtilities.invokeLater(new Runnable() { // public void run() { GameApplication.initTechnicalOptionsAndSituations(); GameApplication.initGuiResources(); GameApplication.startNewGame(); // } // }); } private void add(GameObjectGenerator gameObjectGenerator) { GameObjectsList gameObjects = gameObjectGenerator.generate(); GameBeansContext.getBean(GameDataService.class).getGameData() .merge(gameObjects); String serializedXml = SerializationUtil.serializeGameData(gameObjects, true); FileUtil.write(ROOT_DIR + gameObjectGenerator.getFileName() + ".xml", serializedXml); gameObjectResourceFiles.add("data/" + gameObjectGenerator.getFileName() + ".xml"); } private void createResourceListFile() { GameFilesList gameFilesList = new GameFilesList(); gameFilesList.setFiles(gameObjectResourceFiles); String serializedXml = SerializationUtil.serialize(gameFilesList, true); FileUtil.write(ROOT_DIR + "gameFiles" + ".xml", serializedXml); } public static void main(String[] args) { new GenerateAndRun().run(); } }
Java
package org.clockworkmages.games.anno1186.generator.sets; import org.clockworkmages.games.anno1186.DamageConstants; import org.clockworkmages.games.anno1186.TimeConstants; import org.clockworkmages.games.anno1186.dao.GameObjectsList; import org.clockworkmages.games.anno1186.generator.GameObjectGenerator; import org.clockworkmages.games.anno1186.model.FetishConstants; import org.clockworkmages.games.anno1186.model.character.GenderConstants; import org.clockworkmages.games.anno1186.model.character.IncapacitatedState; import org.clockworkmages.games.anno1186.model.character.NonPlayerCharacter; import org.clockworkmages.games.anno1186.model.character.SkillConstants; import org.clockworkmages.games.anno1186.model.character.SpecialAttack; import org.clockworkmages.games.anno1186.model.character.StatConstants; import org.clockworkmages.games.anno1186.model.effect.ConditionConstanst; import org.clockworkmages.games.anno1186.model.option.GenericOption; import org.clockworkmages.games.anno1186.model.situation.GenericSituation; import org.clockworkmages.games.anno1186.scripting.tools.EffectBuilder; import org.clockworkmages.games.anno1186.scripting.tools.ScriptBuilder; import org.clockworkmages.games.anno1186.scripting.tools.TextBuilder; public class PalosFence extends GameObjectGenerator // implements StatConstants, SkillConstants, TechnicalSituationConstants, TimeConstants, DamageConstants, ConditionConstanst, GenderConstants { public String getFileName() { return "palos_fence"; } @Override public GameObjectsList generate() { GameObjectsList gameObjects = new GameObjectsList(); GenericOption option = new GenericOption(); GenericSituation situation = new GenericSituation(); String PLOT_PALOS_ALLEY_FENCE_ISGONE = "PALOS_ALLEY_FENCE_ISGONE"; // located options option = new GenericOption(); option.setSituationId("PALOS_ALLEY"); option.setAddToStack(true); option.setSee("a local thug leaning against a wall, watching you from the shadows"); option.setLabel("Thug"); option.setIcon("talk"); option.setGoToCombat("PALOS_THUG"); option.setCondition("!" + ScriptBuilder.NEW().util().isDay().and().not().plot() .is(PLOT_PALOS_ALLEY_FENCE_ISGONE).toString()); gameObjects.getOptions().add(option); NonPlayerCharacter enemy = new NonPlayerCharacter(); enemy.setId("PALOS_THUG"); enemy.setName("Criminal"); enemy.setGender(MALE); enemy.setDescription("The local thug..."); enemy.setLevel(2); enemy.getDamageMinimals().put(PHYSICAL, 5d); enemy.getDamageRanges().put(PHYSICAL, 10d); enemy.getDamageResistances().put(HOLY, -1d); enemy.getBaseStats().put(STRENGTH, 20d); enemy.getBaseStats().put(ENDURANCE, 20d); enemy.getBaseStats().put(AGILITY, 20d); enemy.getSpecialAttacks() .add(new SpecialAttack( "The thug hits you in the stomach with a fist, stunning you for a moment", ScriptBuilder .NEW() .enemy() .incapacitate( IncapacitatedState.STUNNED.name(), 40) .toString(), // ScriptBuilder.NEW().util().random(100).le(15) .toString()) // ); enemy.setFleeTo("PALOS_MARKET"); gameObjects.getNpcs().add(enemy); // victorious // automatically option = new GenericOption(); option.setLabel("Next"); option.setTextAfter("After the thug breaths his last breath, you loot his corpse and take all valuable items."); option.getEffects().add( EffectBuilder.NEW().me().addGold(30).compileEffect()); option.getEffects().add( EffectBuilder.NEW().plot().set(PLOT_PALOS_ALLEY_FENCE_ISGONE) .compileEffect()); option.setGoToSituation(ST_EMPTY_RETURN); enemy.getVictoriousOptions().add(option); // Defeated option = new GenericOption(); option.setLabel("Next"); option.setTextAfter("Having taken some terrible beating you black out completely to wake up several hours later lying in the pool of your blood and robbed of your money. Still, by some dumb luck you're still alive. You probably should be more careful in the future - eventually your luck will run out."); option.getEffects().add( EffectBuilder.NEW().me().addGold(-50).compileEffect()); option.getEffects() .add(EffectBuilder.NEW().me().increaseStat(FATE, -1) .compileEffect()); option.getEffects().add( EffectBuilder.NEW().me().increaseStat(REPUTATION, -1) .compileEffect()); option.getEffects().add( EffectBuilder.NEW().plot().set(PLOT_PALOS_ALLEY_FENCE_ISGONE) .compileEffect()); option.setGoToSituation(ST_EMPTY_RETURN); enemy.getDefeatedOptions().add(option); // Victorious option = new GenericOption(); option.setLabel("Next"); option.setTextAfter("You loot the bloody corpse of your enemy"); option.getEffects().add( EffectBuilder.NEW().me().addGold(30).compileEffect()); option.getEffects().add( EffectBuilder.NEW().plot().set(PLOT_PALOS_ALLEY_FENCE_ISGONE) .compileEffect()); option.setGoToSituation(ST_EMPTY_RETURN); enemy.getDefeatedOptions().add(option); // Subduing - if none are available, present the // VictoriousOption enemy.setSubduingText("The thug lies at your feet, defeated. He breaths heavily and seems to have a few ribs broken, but seems otherwise alive. What do you want to do with him?"); option = new GenericOption(); option.setLabel("Take all valuable items you can find, but let the poor loser live"); option.setTextAfter("You search your weakly protesting victim and manage to find some money. Once finished, you walk away and leave the poor loser to live or die, who cares?"); option.setCondition(ScriptBuilder.NEW().enemy().survived().toString()); option.getEffects().add( EffectBuilder.NEW().me().addGold(30).compileEffect()); option.getEffects().add( EffectBuilder.NEW().plot().set(PLOT_PALOS_ALLEY_FENCE_ISGONE) .compileEffect()); option.setGoToSituation(ST_EMPTY_RETURN); enemy.getSubduingOptions().add(option); option = new GenericOption(); option.setLabel("Slit his throat and loot the corpse"); option.setTextAfter("You slit the bastard's throat without as much as blinking and loot the still warm corpse. Once you took the thug's money you walk away."); option.getEffects().add( EffectBuilder.NEW().me().addGold(30).compileEffect()); option.getEffects().add( EffectBuilder.NEW().me().increaseStat(VIRTUE, -2) .compileEffect()); option.getEffects().add( EffectBuilder.NEW().plot().set(PLOT_PALOS_ALLEY_FENCE_ISGONE) .compileEffect()); option.setGoToSituation(ST_EMPTY_RETURN); enemy.getSubduingOptions().add(option); option = new GenericOption(); option.setLabel("Make sure his wounds are not fatal and leave him be."); option.setTextAfter("You quickly check the poor loser's life signs to make sure that he'll live. Having found no fatal wounds you leave him be and you walk away - the poor sod learned is lesson already so there's no need to torment him any more."); option.getEffects().add( EffectBuilder.NEW().plot().set(PLOT_PALOS_ALLEY_FENCE_ISGONE) .compileEffect()); option.getEffects().add( EffectBuilder.NEW().me().increaseStat(VIRTUE, 2) .compileEffect()); option.setGoToSituation(ST_EMPTY_RETURN); enemy.getSubduingOptions().add(option); option = new GenericOption(); option.setCondition(ScriptBuilder .NEW() .me() .isMale() .and() .util() .fetishesEnabled(FetishConstants.MEN, FetishConstants.DOMINATION).toString()); option.setLabel("Rape him."); option.setTextAfter("Alone in a dark alley with a handsome stud at your mercy, it would be a waste to not take advantage of the situation. You kick the thug a few times in the ribs and stomach to make sure he won't try to fight back and then you force him to lie face down on the ground as you pull his trousers down and untie your breeches.[TODO]. Once you're satisfied, you grab the thug's purse and walk away."); option.getEffects().add( EffectBuilder.NEW().plot().set(PLOT_PALOS_ALLEY_FENCE_ISGONE) .compileEffect()); option.getEffects().add( EffectBuilder.NEW().me().increaseStat(VIRTUE, -2) .compileEffect()); option.getEffects().add( EffectBuilder.NEW().me().addGold(30).compileEffect()); option.getEffects().add( EffectBuilder.NEW().me().addCondition(SATISFIED, 2, DAY) .compileEffect()); option.setGoToSituation(ST_EMPTY_RETURN); enemy.getSubduingOptions().add(option); // Subdued - if none are available, present the // DefeatedOptions // complex condition with different scenarios for male and female // players: String submissionCondition = "(" + ScriptBuilder .NEW() .me() .survived() .and() .me() .isMale() .and() .util() .fetishesEnabled(FetishConstants.MEN, FetishConstants.SUBMISSION, FetishConstants.URINATION, FetishConstants.FEET) .toString() + ") || (" + ScriptBuilder .NEW() .me() .survived() .and() .not() .me() .isMale() .and() .util() .fetishesEnabled(FetishConstants.MEN, FetishConstants.SUBMISSION).toString() + ")"; enemy.setSubduedText("As you lie on the ground, bruised and defeated, the thug comes closer, a knife in his hand.\n"// + " - Had enough, " + TextBuilder.NEW().iff().me().isMale().then("cocksucker") .elsee("bitch").asText() + "? - he says with an evil smile - I should gut you now, and perhaps I yet will. But maybe there's some way you can entertain me instead. How about you hand me over all your money " + TextBuilder .NEW() .iff() .me() .isMale() .then("and lick my boots clean to prove that you learned to respect your betters, you worthless piece of shit.") .elsee(", take off your clothes and get on all fours so I can fuck you like a good little bitch.") .asText()); option = new GenericOption(); option.setLabel("Try to run away (keep the gold but lose 1 Fate point)"); option.setTextAfter("You gather all your strength and bolt towards the exit of the alley. Before the thug manages to catch you you turn the corner, and bump right into a pair of city guards on patrol duty. You aplogise for them and as you do, you hear your captor cusing loudly behind you and running away. You were lucky tonight, but you probably should be more careful in the future - eventually your luck will run out."); option.setCondition(submissionCondition); option.getEffects() .add(EffectBuilder.NEW().me().increaseStat(FATE, -1) .compileEffect()); option.getEffects().add( EffectBuilder.NEW().plot().set(PLOT_PALOS_ALLEY_FENCE_ISGONE) .compileEffect()); option.setGoToSituation(ST_EMPTY_RETURN); enemy.getSubduedOptions().add(option); option = new GenericOption(); option.setLabel("Beg for mercy! (Submit)"); option.setTextAfter(TextBuilder .NEW() .iff() .me() .isMale() .then("You thank the thug for his mercy and take your eyes off the gleaming blade in the his hand only to kneel at his feet, lowering your lips to lick his boots in complete submission. As you lick the mud of his boots, without raising your head you hear the bandit sheath his knife and untie his trousers. After a moment, you feel a stream of hot liquid hit the back of your head and your back. Though shoucked, you continue to obediently work on your oppressors boots with your tongue. Once the thug's finished pissing, he spits on you, turns away with an amused grunt and walks away.") .elsee("Terrified by the perspective of having your throat slit, you do exactly as your oppressor demands.") .asText() ); option.setCondition(submissionCondition); option.getEffects().add( EffectBuilder.NEW().me().increaseStat(REPUTATION, -3) .compileEffect()); option.getEffects().add( EffectBuilder.NEW().plot().set(PLOT_PALOS_ALLEY_FENCE_ISGONE) .compileEffect()); option.getEffects().add( EffectBuilder.NEW().me().addGold(-50).compileEffect()); option.setGoToSituation(ST_EMPTY_RETURN); enemy.getSubduedOptions().add(option); addDefaultEffectsToCombatOptions(gameObjects); return gameObjects; } }
Java
package org.clockworkmages.games.anno1186.generator.sets; import org.clockworkmages.games.anno1186.DamageConstants; import org.clockworkmages.games.anno1186.TimeConstants; import org.clockworkmages.games.anno1186.dao.GameObjectsList; import org.clockworkmages.games.anno1186.generator.GameObjectGenerator; import org.clockworkmages.games.anno1186.model.character.GenderConstants; import org.clockworkmages.games.anno1186.model.character.SkillConstants; import org.clockworkmages.games.anno1186.model.character.StatConstants; import org.clockworkmages.games.anno1186.model.effect.ConditionConstanst; public class Beach extends GameObjectGenerator // implements StatConstants, SkillConstants, TechnicalSituationConstants, TimeConstants, DamageConstants, ConditionConstanst, GenderConstants { public String getFileName() { return "beach"; } @Override public GameObjectsList generate() { GameObjectsList gameObjects = new GameObjectsList(); // ExplorableArea explorableArea; // explorableArea = new ExplorableArea(); // explorableArea.setId("BEACH"); // explorableArea.setName("Beach"); // explorableArea.setDescription("You stand on the beach..."); // explorableArea.setX(10); // explorableArea.setY(10); // gameObjects.getAreas().add(explorableArea); // // CampSite campSite; // campSite = new CampSite(); // campSite.setAreaId("BEACH"); // campSite.setId("BEACH_CLIFF_CAVE"); // gameObjects.getCampSites().add(campSite); // // addDefaultEffectsToCombatOptions(gameObjects); return gameObjects; } }
Java
package org.clockworkmages.games.anno1186.generator.sets; import org.clockworkmages.games.anno1186.dao.GameObjectsList; import org.clockworkmages.games.anno1186.generator.GameObjectGenerator; import org.clockworkmages.games.anno1186.model.character.SkillConstants; import org.clockworkmages.games.anno1186.model.character.StatConstants; import org.clockworkmages.games.anno1186.model.effect.Effect; import org.clockworkmages.games.anno1186.model.option.GenericOption; import org.clockworkmages.games.anno1186.model.situation.GenericSituation; import org.clockworkmages.games.anno1186.scripting.tools.EffectBuilder; import org.clockworkmages.games.anno1186.scripting.tools.ScriptBuilder; public class PalosJuan extends GameObjectGenerator // implements StatConstants, SkillConstants, TechnicalSituationConstants { public String getFileName() { return "palos_juan"; } @Override public GameObjectsList generate() { GameObjectsList gameObjects = new GameObjectsList(); GenericOption option = new GenericOption(); GenericSituation situation = new GenericSituation(); // located options: option = new GenericOption(); option.setSituationId("PALOS_TAVERN"); option.setSee("captain Juan de la Cosa"); option.setLabel("Juan de la Cosa"); option.setIcon("talk"); option.setCondition(ScriptBuilder.NEW().not().plot() .is("PALOS_JOINED_THE_CREW").toString()); option.setGoToSituation("PALOS_TAVERN_JUAN"); option.setAddToStack(true); gameObjects.getOptions().add(option); // located options: option = new GenericOption(); option.setSituationId("PALOS_DOCKS"); option.setSee("Santa Maria - the ship that you signed up to"); option.setLabel("come aboard Santa Maria"); option.setIcon("in"); option.setCondition(ScriptBuilder.NEW().plot() .is("PALOS_JOINED_THE_CREW").and().not().util().isNight() .toString()); option.setAddToStack(false); gameObjects.getOptions().add(option); // Situations: situation = new GenericSituation(); situation.setClearScreen(true); situation.setId("PALOS_TAVERN_JUAN"); situation.setText("As you were finishing your supper..."); gameObjects.getSituations().add(situation); option = new GenericOption(); option.setLabel("Expedition"); option.setTooltip("'Tell me more about that expedition of yours'"); option.getEffects().add( new Effect("situation.addState('ASKED_ABOUT_EXPEDITION')")); situation.getOptions().add(option); option = new GenericOption(); option.setCondition("situation.hasState('ASKED_ABOUT_EXPEDITION')"); option.setLabel("Crew"); option.setTooltip("'Who's on your crew?'"); situation.getOptions().add(option); option = new GenericOption(); option.setCondition("situation.hasState('ASKED_ABOUT_EXPEDITION')"); option.setLabel("Uncharted territories"); option.setTooltip("'Unknown land beyond the ocean, seriously?'"); situation.getOptions().add(option); option = new GenericOption(); option.setCondition("situation.hasState('ASKED_ABOUT_EXPEDITION')"); option.getEffects().add( new Effect("situation.addState('ASKED_ABOUT_PROFIT')")); option.setLabel("Profit"); option.setTooltip("'How much would I earn if I joined you?'"); situation.getOptions().add(option); option = new GenericOption(); option.setCondition("situation.hasState('ASKED_ABOUT_PROFIT')" + " && !situation.hasState('BARGAINED')" + " && " + ScriptBuilder.ME().skillRoll(SPEECH, -10).toString()); option.getEffects() .add(new Effect("plot.set('PALOS_JOINED_THE_CREW')")); option.getEffects().add(EffectBuilder.me().addGold(50).compileEffect()); option.setGoToSituation("PALOS_TAVERN_JUAN_AGREE"); option.setLabel("Agreed, but I want 50 coins paid in advance! (Speech, " + ScriptBuilder.ME().skillChance(SPEECH, -10).asPlaceholder() + "%)"); option.setTextAfter("The captains assesses you with his stare in silence for a longer moment.\n" + " - All right then, ${if me.male}lad{$else}lass${fi} - he says eventually - I don't normally do that, but I'm in desperate need of men, and you look like you look resourceful. Here's your gold, just be sure you'll be in the docks thing in the morning. We sail out at noon!"); situation.getOptions().add(option); option = new GenericOption(); option.setOr(true); option.setCondition("situation.hasState('ASKED_ABOUT_PROFIT') && !situation.hasState('BARGAINED')"); option.getEffects().add(new Effect("situation.addState('BARGAINED')")); option.setLabel("Agreed, but I want 50 coins paid in advance! (Speech, Reputation, " + ScriptBuilder.ME().skillChance(SPEECH, -10).asPlaceholder() + "%)"); option.setTextAfter(" - Sorry ${if me.isMale()}lad${else}lass${fi}, but that is not an option. - says the captain - But you'll get your money once we're back, every copper of it, you have my word."); situation.getOptions().add(option); option = new GenericOption(); option.setGoToSituation("PALOS_TAVERN_JUAN_AGREE"); option.getEffects() .add(new Effect("plot.set('PALOS_JOINED_THE_CREW')")); option.setLabel("Great! Where do I sign?"); option.setTextAfter(" - Splendid! - exclaims the captain - Make sure you'll be in the docks in the morning - we sail out at noon! You won't regret it my friend, it's going to be a once-in-a-lifetime adveture, you'll see!"); situation.getOptions().add(option); option = new GenericOption(); option.setGoToSituation(ST_EMPTY_RETURN); option.setLabel("I need to think about it"); option.setTextAfter(" - Well don't think too long, it's a once-in-a lifetime opportunity! - says the captain - But sure, take your time. I'll be around here a bit longer."); situation.getOptions().add(option); // situation = new GenericSituation(); situation.setClearScreen(false); situation.setId("PALOS_TAVERN_JUAN_AGREE"); situation .setText(" - Now, it's getting late and I need to be going back to my place to get some sleep. I'd advice that you do the same, ${if me.male}lad{$else}lass${fi}. It's going to be a busy day tomorrow."); situation .setText("The captains gets up from his chair and walks towards the door."); gameObjects.getSituations().add(situation); option = new GenericOption(); option.setGoToSituation("EMPTY_RETURN"); option.setLabel("I'll see you in the morning!"); situation.getOptions().add(option); option = new GenericOption(); option.setCondition(ScriptBuilder.ME().getSkillLevel(STEALTH).gt(0) .and().me().skillRoll(STEALTH, -10).toString()); option.getEffects().add(EffectBuilder.me().addGold(50).compileEffect()); option.setGoToSituation(ST_EMPTY_RETURN); option.setLabel("Pickpocket him as he passes you! (Stealth, " + ScriptBuilder.ME().skillChance(STEALTH, -10).asPlaceholder() + "%)"); option.setTextAfter("[Success!] You quickly steal the captain's purse without the old man noticing anything."); situation.getOptions().add(option); option = new GenericOption(); option.setCondition(ScriptBuilder.ME().getSkillLevel(STEALTH).gt(0) .toString()); option.setOr(true); option.setGoToSituation(ST_EMPTY_RETURN); option.setLabel("Pickpocket him as he passes you! (Stealth, Agility, " + ScriptBuilder.ME().skillChance(STEALTH, -10).asPlaceholder() + "%)"); option.setTextAfter("[Fail] With so many people in the inn it's not easy to find the right moment to steal the captain's purse unnoticed, and the old seaman leaves the tavern before you could make your move."); situation.getOptions().add(option); return gameObjects; } }
Java
package org.clockworkmages.games.anno1186.generator.sets; import org.clockworkmages.games.anno1186.DamageConstants; import org.clockworkmages.games.anno1186.dao.GameObjectsList; import org.clockworkmages.games.anno1186.dao.ImageIconDescriptor; import org.clockworkmages.games.anno1186.generator.GameObjectGenerator; import org.clockworkmages.games.anno1186.model.Fetish; import org.clockworkmages.games.anno1186.model.FetishConstants; import org.clockworkmages.games.anno1186.model.character.Mutation; import org.clockworkmages.games.anno1186.model.character.Skill; import org.clockworkmages.games.anno1186.model.character.SkillConstants; import org.clockworkmages.games.anno1186.model.character.Stat; import org.clockworkmages.games.anno1186.model.character.StatConstants; import org.clockworkmages.games.anno1186.model.effect.Condition; import org.clockworkmages.games.anno1186.model.effect.ConditionConstanst; import org.clockworkmages.games.anno1186.model.effect.Effect; import org.clockworkmages.games.anno1186.model.effect.Perk; import org.clockworkmages.games.anno1186.model.item.EquipmentSlot; import org.clockworkmages.games.anno1186.model.item.ItemConstants; import org.clockworkmages.games.anno1186.model.option.GenericOption; import org.clockworkmages.games.anno1186.model.situation.GenericSituation; import org.clockworkmages.games.anno1186.scripting.tools.EffectBuilder; import org.clockworkmages.games.anno1186.scripting.tools.ScriptBuilder; public class BaseObjects extends GameObjectGenerator implements StatConstants, SkillConstants, TechnicalSituationConstants, ItemConstants, DamageConstants, FetishConstants { public String getFileName() { return "base"; } @Override public GameObjectsList generate() { GameObjectsList gameData = new GameObjectsList(); gameData.getIcons().add( new ImageIconDescriptor("none", "images/icons/none.png")); gameData.getIcons().add( new ImageIconDescriptor("up", "images/icons/up.png")); gameData.getIcons().add( new ImageIconDescriptor("down", "images/icons/down.png")); gameData.getIcons().add( new ImageIconDescriptor("in", "images/icons/in.png")); gameData.getIcons().add( new ImageIconDescriptor("out", "images/icons/out.png")); gameData.getIcons().add( new ImageIconDescriptor("west", "images/icons/west.png")); gameData.getIcons().add( new ImageIconDescriptor("east", "images/icons/east.png")); gameData.getIcons().add( new ImageIconDescriptor("north", "images/icons/north.png")); gameData.getIcons().add( new ImageIconDescriptor("south", "images/icons/south.png")); gameData.getIcons().add( new ImageIconDescriptor("fight", "images/icons/fight.png")); gameData.getIcons().add( new ImageIconDescriptor("sleep", "images/icons/sleep.png")); gameData.getIcons().add( new ImageIconDescriptor("trade", "images/icons/trade.png")); gameData.getIcons().add( new ImageIconDescriptor("talk", "images/icons/talk.png")); gameData.getIcons().add( new ImageIconDescriptor("back", "images/icons/back.png")); gameData.getStats().add(new Stat(STRENGTH, "Strength")); gameData.getStats().add(new Stat(ENDURANCE, "Endurance")); gameData.getStats().add(new Stat(AGILITY, "Agility")); gameData.getStats().add(new Stat(CHARM, "Charm")); gameData.getStats().add(new Stat(PERCEPTION, "Perception")); gameData.getStats().add(new Stat(INTELLIGENCE, "Intelligence")); gameData.getStats().add(new Stat(WILLPOWER, "Willpower")); // gameData.getStats().add(new Stat(REPUTATION, "Reputation")); gameData.getStats().add(new Stat(VIRTUE, "Virtue")); // gameData.getStats() .add(new Stat("STATUS_CRIMINALS", "Criminals", true)); gameData.getSkills().add(new Skill("BODYBUILDING", "Bodybuilding")); gameData.getSkills().add( new Skill("BARTER", "Barter", CHARM, REPUTATION)); gameData.getSkills().add(new Skill("MEDITATION", "Meditation")); gameData.getSkills().add( new Skill("ALCHEMY", "Alchemy", 0.5, INTELLIGENCE)); gameData.getSkills().add(new Skill("SMITHING", "Smithing", STRENGTH)); gameData.getSkills().add( new Skill("SURVIVAL", "Survival", PERCEPTION, AGILITY)); gameData.getSkills().add( new Skill("SPEECH", "Speech", CHARM, REPUTATION)); gameData.getSkills().add( new Skill("STEALTH", "Stealth", PERCEPTION, AGILITY)); // gameData.getSkills().add(new Skill("BLUDGEON", "Bludgeon")); gameData.getSkills().add(new Skill("SWORD", "Sword")); gameData.getSkills().add(new Skill("DAGGER", "Dagger")); gameData.getSkills().add(new Skill("AXE", "Axe")); gameData.getSkills().add(new Skill("POLEARM", "Polearm")); Skill skill = new Skill("UNARMED", "Unarmed", AGILITY, STRENGTH); skill.getEffects().add( EffectBuilder .me() .modifyDamage(PHYSICAL, ScriptBuilder.LEVEL + "/2", ScriptBuilder.LEVEL + "/2").iff().me() .isUnarmed().compileEffect()); gameData.getSkills().add(skill); // gameData.getSkills().add( new Skill("HISTORY", "History", 0.5, INTELLIGENCE)); gameData.getSkills().add( new Skill("THEOLOGY", "Theology", 0.5, INTELLIGENCE)); gameData.getSkills().add( new Skill("DEMONOLOGY", "Demonology", 0.5, INTELLIGENCE)); gameData.getSkills().add( new Skill(INTERROGATION, "Interrogation", WILLPOWER)); Mutation mutation = new Mutation( "GOAT_HOOVES", "Goat's hooves", EQUIPMENT_SLOT_SHOES, "Your legs are covered with thick black fur like that of an animal, and instead of human feet you have a pair of hooves like a goat's. You won't be putting any shoes on those but then again, hey, who needs shoes if they have hooves!", false); gameData.getMutations().add(mutation); EquipmentSlot equipmentSlot = new EquipmentSlot(); equipmentSlot.setId(EQUIPMENT_SLOT_HEAD); equipmentSlot .setDescription("On your head you wear ${item.shortDescription}."); gameData.getEquipmentSlots().add(equipmentSlot); equipmentSlot = new EquipmentSlot(); equipmentSlot.setId(EQUIPMENT_SLOT_R_HAND); equipmentSlot .setDescription("In your right hand you hold ${item.shortDescription}."); gameData.getEquipmentSlots().add(equipmentSlot); gameData.getBaseEffects().add( new Effect("me.modifyDerivate('" + D_MAX_HEALTH + "', 2*me.getEffectiveStat('" + ENDURANCE + "'))")); gameData.getBaseEffects().add( new Effect("me.modifyDerivate('" + D_MAX_STAMINA + "', me.getEffectiveStat('" + ENDURANCE + "')+me.getEffectiveStat('" + WILLPOWER + "'))")); gameData.getBaseEffects().add( new Effect("me.modifyDerivate('" + D_ACCURACY + "', 1*me.getEffectiveStat('" + AGILITY + "'))")); gameData.getBaseEffects().add( new Effect("me.modifyDerivate('" + D_EVASION + "', 1*me.getEffectiveStat('" + AGILITY + "'))")); gameData.getBaseEffects().add( new Effect("me.modifyDerivate('" + D_EXPERIENCE_MODIFIER + "', 1+me.getEffectiveStat('" + INTELLIGENCE + "'))/100")); Perk perk; perk = new Perk(); perk.setId("CHANNELER"); perk.setName("Channeler"); perk.setDescription("All spells you cast cost 25% less fatigue."); perk.getEffects().add( new Effect("me.modifyStat(\'" + SPELL_COST_REDUCTION + "\', 25)")); gameData.getPerks().add(perk); Effect effect; Condition condition; condition = new Condition(); condition.setName("Tired"); condition .setDescription("You are very tired, which makes it difficult for you to fight. Try taking a rest or go to sleep."); condition.setId(ConditionConstanst.TIRED); condition.setCombatOnly(true); gameData.getConditions().add(condition); effect = EffectBuilder.NEW().me().modifyDerivatePerc(D_ACCURACY, -30) .compileEffect(); effect = EffectBuilder.NEW().me().modifyDerivatePerc(D_EVASION, -30) .compileEffect(); condition.getEffects().add(effect); condition = new Condition(); condition.setName("Satisfied"); condition .setDescription("You feel satisfied, optimistic and ready for adventure! All experience you gain is increased by 25%"); condition.setId(ConditionConstanst.SATISFIED); condition.setCombatOnly(true); gameData.getConditions().add(condition); effect = EffectBuilder.NEW().me() .modifyDerivatePerc(D_EXPERIENCE_MODIFIER, 25).compileEffect(); condition.getEffects().add(effect); gameData.getFetishes() .add(new Fetish(MEN, "Sex with men", "You like having sex with men, or at least don't mind.")); gameData.getFetishes() .add(new Fetish(WOMEN, "Sex with women", "You like having sex with women, or at least don't mind.")); gameData.getFetishes() .add(new Fetish( MYTHICAL, "Mythical creatures (orcs, werewolves, harpies, mermaids, giants... ", "You like to sexually fantasize about fantasy creatures like orcs, harpies, satyrs or mermaids.")); gameData.getFetishes() .add(new Fetish(DOMINATION, "Domination", "You like to brutally dominate and humiliate your sexual partners.")); gameData.getFetishes() .add(new Fetish(SUBMISSION, "Submission", "You like to be humiliated and brutally dominated by your sexual partners.")); gameData.getFetishes().add( new Fetish(ANAL, "Anal sex", "You like anal sex.")); gameData.getFetishes() .add(new Fetish(URINATION, "Watersports/urination", "You think urination is a nice addition to some rough sex games.")); gameData.getFetishes().add( new Fetish(FEET, "Feet/boots", "You consider feet and boots worship a turnon.")); gameData.getFetishes() .add(new Fetish( ALIEN, "Alien/hentai", "Haing sex with some grotesque monster - a many-limbed demon or an alien monstrosity with tentacles - seem like a cool idea to you.")); GenericSituation situation = new GenericSituation(); situation.setClearScreen(false); situation.setId(ST_EMPTY_RETURN); gameData.getSituations().add(situation); GenericOption option = new GenericOption(); option.setGoBack(true); option.setLabel("Next"); situation.getOptions().add(option); return gameData; } }
Java
package org.clockworkmages.games.anno1186.generator.sets; import org.clockworkmages.games.anno1186.DamageConstants; import org.clockworkmages.games.anno1186.TimeConstants; import org.clockworkmages.games.anno1186.dao.GameObjectsList; import org.clockworkmages.games.anno1186.generator.GameObjectGenerator; import org.clockworkmages.games.anno1186.model.character.GenderConstants; import org.clockworkmages.games.anno1186.model.character.SkillConstants; import org.clockworkmages.games.anno1186.model.character.StatConstants; import org.clockworkmages.games.anno1186.model.effect.ConditionConstanst; public class Jungle extends GameObjectGenerator // implements StatConstants, SkillConstants, TechnicalSituationConstants, TimeConstants, DamageConstants, ConditionConstanst, GenderConstants { public String getFileName() { return "jungle"; } @Override public GameObjectsList generate() { GameObjectsList gameObjects = new GameObjectsList(); // ExplorableArea explorableArea; // explorableArea = new ExplorableArea(); // explorableArea.setId("JUNGLE"); // explorableArea.setName("Jungle"); // explorableArea // .setDescription("You are in the middle of a dense jungle..."); // explorableArea.setX(9); // explorableArea.setY(10); // gameObjects.getAreas().add(explorableArea); // // CampSite campSite; // campSite = new CampSite(); // campSite.setAreaId("JUNGLE"); // campSite.setId("JUNGLE_GOBLIN_HUT"); // gameObjects.getCampSites().add(campSite); // // addDefaultEffectsToCombatOptions(gameObjects); return gameObjects; } }
Java