code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/* -*- Java -*-
*
* Copyright (c) 2009
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.sls.wami.recognition.lm.exceptions;
import edu.mit.csail.sls.wami.recognition.exceptions.RecognizerException;
/**
* Thrown when an unsupported type of language model is passed to the portal
*
* @author alexgru
*
*/
public class UnsupportedLanguageModelException extends RecognizerException {
public UnsupportedLanguageModelException(String message) {
super(message);
}
}
| Java |
/* -*- Java -*-
*
* Copyright (c) 2009
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.sls.wami.recognition.lm.jsgf;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import edu.mit.csail.sls.wami.recognition.lm.LanguageModel;
public class JsgfGrammar implements LanguageModel {
private String grammar;
private String dictionaryLanguage;
/**
* Reads a JSGF grammar from an {@link InputStream}
*
* @param in
* The {@link InputStream} from which to read the grammar
*/
public JsgfGrammar(InputStream in, String dictionaryLanguage)
throws IOException {
char[] buf = new char[10000];
Reader r = new InputStreamReader(in);
StringBuffer sb = new StringBuffer();
while (true) {
int nRead = r.read(buf);
if (nRead == -1) {
break;
}
sb.append(buf, 0, nRead);
}
grammar = sb.toString();
this.dictionaryLanguage = dictionaryLanguage;
}
/**
* Create a new Jsgf grammar using the grammar contained in the string.
*
* @param grammar
*/
public JsgfGrammar(String grammar, String dictionaryLanguage) {
this.grammar = grammar;
this.dictionaryLanguage = dictionaryLanguage;
}
public String getGrammar() {
return grammar;
}
public String getType() {
return "jsgf";
}
public String getDictionaryLanguage() {
return dictionaryLanguage;
}
}
| Java |
package edu.mit.csail.sls.wami.util;
import java.util.Map;
import javax.servlet.ServletContext;
public interface Instantiable {
public void setParameters(ServletContext sc, Map<String, String> params);
}
| Java |
/* -*- Java -*-
*
* Copyright (c) 2009
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.sls.wami.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.TimeZone;
import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcLocalStreamTransport;
import org.apache.xmlrpc.common.XmlRpcStreamRequestConfig;
import org.apache.xmlrpc.server.XmlRpcLocalStreamServer;
/**
* Utilities which allow serialization and deserialization into xml appropriate
* for an xmlrpc server response
*
* @author alexgru
*
*/
public class WamiXmlRpcUtils {
private static final MyXmlRpcLocalStreamServer fakeServer = new MyXmlRpcLocalStreamServer();
private static final MyXmlRpcLocalStreamTransport fakeTransport = new MyXmlRpcLocalStreamTransport();
public static Object parseResponse(String xmlStr) {
return parseResponse(new ByteArrayInputStream(xmlStr.getBytes()));
}
public static Object parseResponse(InputStream xmlIn) {
try {
return fakeTransport.read(xmlIn);
} catch (XmlRpcException e) {
e.printStackTrace();
}
return null;
}
/**
* Serializes the passed in object to the passed in output stream
*
* @param o
* @throws XmlRpcException
*/
public static void serializeResponse(Object o, OutputStream xmlOut)
throws XmlRpcException {
fakeServer.write(o, xmlOut);
}
public static String serializeResponse(Object o) {
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
serializeResponse(o, out);
return out.toString();
} catch (XmlRpcException e) {
e.printStackTrace();
}
return null;
}
/**
* Simple configuration for serialization
*
* @author alexgru
*
*/
private static class MyXmlRpcStreamRequestConfig implements
XmlRpcStreamRequestConfig {
public String getEncoding() {
return UTF8_ENCODING;
}
public TimeZone getTimeZone() {
return TimeZone.getDefault();
}
public boolean isEnabledForExtensions() {
return false;
}
public boolean isEnabledForExceptions() {
return false;
}
public boolean isGzipCompressing() {
return false;
}
public boolean isGzipRequesting() {
return false;
}
}
/**
* provides access into protected writeResponse method
*
* @author alexgru
*/
private static class MyXmlRpcLocalStreamServer extends
XmlRpcLocalStreamServer {
private final static XmlRpcStreamRequestConfig pConfig = new MyXmlRpcStreamRequestConfig();
public void write(Object obj, OutputStream out) throws XmlRpcException {
writeResponse(pConfig, out, obj);
}
}
/**
* provides access into protected readResponse method
*
* @author alexgru
*/
private static class MyXmlRpcLocalStreamTransport extends
XmlRpcLocalStreamTransport {
private final static XmlRpcStreamRequestConfig pConfig = new MyXmlRpcStreamRequestConfig();
public MyXmlRpcLocalStreamTransport() {
super(new XmlRpcClient(), null);
}
public Object read(InputStream xmlIn) throws XmlRpcException {
return readResponse(pConfig, xmlIn);
}
}
// test main
public static void main(String[] args) throws XmlRpcException {
HashMap<String, String> map = new HashMap<String, String>();
map.put("hello", "world");
map.put("foo", "bar");
String xml = WamiXmlRpcUtils.serializeResponse(map);
System.out.println(xml);
Object obj = WamiXmlRpcUtils.parseResponse(xml);
System.out.println(obj);
}
}
| Java |
package edu.mit.csail.sls.wami.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import javax.servlet.http.HttpServletRequest;
public class ServletUtils {
public static void sendStream(InputStream in, OutputStream out)
throws IOException {
sendStream(in, out, 2048);
}
public static void sendStream(InputStream is, OutputStream os, int bufsize)
throws IOException {
byte[] buf = new byte[bufsize];
int n;
while ((n = is.read(buf)) > 0) {
// System.out.println("Sending bytes: " + n);
os.write(buf, 0, n);
}
}
public static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
public static String getClientAddress(HttpServletRequest request) {
String clientAddress = request.getRemoteAddr();
String forwardedFor = request.getHeader("x-forwarded-for");
if (forwardedFor != null) {
clientAddress = forwardedFor;
}
return clientAddress;
}
final static String[] hex = { "%00", "%01", "%02", "%03", "%04", "%05",
"%06", "%07", "%08", "%09", "%0a", "%0b", "%0c", "%0d", "%0e",
"%0f", "%10", "%11", "%12", "%13", "%14", "%15", "%16", "%17",
"%18", "%19", "%1a", "%1b", "%1c", "%1d", "%1e", "%1f", "%20",
"%21", "%22", "%23", "%24", "%25", "%26", "%27", "%28", "%29",
"%2a", "%2b", "%2c", "%2d", "%2e", "%2f", "%30", "%31", "%32",
"%33", "%34", "%35", "%36", "%37", "%38", "%39", "%3a", "%3b",
"%3c", "%3d", "%3e", "%3f", "%40", "%41", "%42", "%43", "%44",
"%45", "%46", "%47", "%48", "%49", "%4a", "%4b", "%4c", "%4d",
"%4e", "%4f", "%50", "%51", "%52", "%53", "%54", "%55", "%56",
"%57", "%58", "%59", "%5a", "%5b", "%5c", "%5d", "%5e", "%5f",
"%60", "%61", "%62", "%63", "%64", "%65", "%66", "%67", "%68",
"%69", "%6a", "%6b", "%6c", "%6d", "%6e", "%6f", "%70", "%71",
"%72", "%73", "%74", "%75", "%76", "%77", "%78", "%79", "%7a",
"%7b", "%7c", "%7d", "%7e", "%7f", "%80", "%81", "%82", "%83",
"%84", "%85", "%86", "%87", "%88", "%89", "%8a", "%8b", "%8c",
"%8d", "%8e", "%8f", "%90", "%91", "%92", "%93", "%94", "%95",
"%96", "%97", "%98", "%99", "%9a", "%9b", "%9c", "%9d", "%9e",
"%9f", "%a0", "%a1", "%a2", "%a3", "%a4", "%a5", "%a6", "%a7",
"%a8", "%a9", "%aa", "%ab", "%ac", "%ad", "%ae", "%af", "%b0",
"%b1", "%b2", "%b3", "%b4", "%b5", "%b6", "%b7", "%b8", "%b9",
"%ba", "%bb", "%bc", "%bd", "%be", "%bf", "%c0", "%c1", "%c2",
"%c3", "%c4", "%c5", "%c6", "%c7", "%c8", "%c9", "%ca", "%cb",
"%cc", "%cd", "%ce", "%cf", "%d0", "%d1", "%d2", "%d3", "%d4",
"%d5", "%d6", "%d7", "%d8", "%d9", "%da", "%db", "%dc", "%dd",
"%de", "%df", "%e0", "%e1", "%e2", "%e3", "%e4", "%e5", "%e6",
"%e7", "%e8", "%e9", "%ea", "%eb", "%ec", "%ed", "%ee", "%ef",
"%f0", "%f1", "%f2", "%f3", "%f4", "%f5", "%f6", "%f7", "%f8",
"%f9", "%fa", "%fb", "%fc", "%fd", "%fe", "%ff" };
/**
* Encode a string to the "x-www-form-urlencoded" form, enhanced
* with the UTF-8-in-URL proposal. This is what happens:
*
* <ul>
* <li><p>The ASCII characters 'a' through 'z', 'A' through 'Z',
* and '0' through '9' remain the same.
*
* <li><p>The unreserved characters - _ . ! ~ * ' ( ) remain the same.
*
* <li><p>The space character ' ' is converted into a plus sign '+'.
*
* <li><p>All other ASCII characters are converted into the
* 3-character string "%xy", where xy is
* the two-digit hexadecimal representation of the character
* code
*
* <li><p>All non-ASCII characters are encoded in two steps: first
* to a sequence of 2 or 3 bytes, using the UTF-8 algorithm;
* secondly each of these bytes is encoded as "%xx".
* </ul>
*
* @param s The string to be encoded
* @return The encoded string
*/
public static String encode(String s) {
StringBuffer sbuf = new StringBuffer();
int len = s.length();
for (int i = 0; i < len; i++) {
int ch = s.charAt(i);
if ('A' <= ch && ch <= 'Z') { // 'A'..'Z'
sbuf.append((char) ch);
} else if ('a' <= ch && ch <= 'z') { // 'a'..'z'
sbuf.append((char) ch);
} else if ('0' <= ch && ch <= '9') { // '0'..'9'
sbuf.append((char) ch);
} else if (ch == ' ') { // space
sbuf.append('+');
} else if (ch == '-'
|| ch == '_' // unreserved
|| ch == '.' || ch == '!' || ch == '~' || ch == '*'
|| ch == '\'' || ch == '(' || ch == ')') {
sbuf.append((char) ch);
} else if (ch <= 0x007f) { // other ASCII
sbuf.append(hex[ch]);
} else if (ch <= 0x07FF) { // non-ASCII <= 0x7FF
sbuf.append(hex[0xc0 | (ch >> 6)]);
sbuf.append(hex[0x80 | (ch & 0x3F)]);
} else { // 0x7FF < ch <= 0xFFFF
sbuf.append(hex[0xe0 | (ch >> 12)]);
sbuf.append(hex[0x80 | ((ch >> 6) & 0x3F)]);
sbuf.append(hex[0x80 | (ch & 0x3F)]);
}
}
return sbuf.toString();
}
public static String getStackTrace(Throwable e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
return sw.toString();
}
}
| Java |
/* -*- Java -*-
*
* Copyright (c) 2009
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.sls.wami.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
public class AudioUtils {
/**
* Creates an audio input stream using the passed in byte array and the
* given format. Returns null if audioBytes or audioFormat is null
*
*/
public static AudioInputStream createAudioInputStream(byte[] audioBytes,
AudioFormat audioFormat) {
if (audioBytes != null && audioFormat != null) {
int frameSize = audioFormat.getFrameSize();
int length = (int) Math.ceil(audioBytes.length / frameSize);
return new AudioInputStream(new ByteArrayInputStream(audioBytes),
audioFormat, length);
} else {
return null;
}
}
/**
* Creates an InputStream that reads from the audio input stream provided,
* and first provides WAVE header information
*
* Note, the passed in stream should have length information associated with
* it
*/
public static InputStream createInputStreamWithWaveHeader(
AudioInputStream audioIn) throws IOException {
return new ByteArrayInputStream(createByteArrayWithWaveHeader(audioIn));
}
public static byte[] createByteArrayWithWaveHeader(AudioInputStream audioIn)
throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
AudioSystem.write(audioIn, AudioFileFormat.Type.WAVE, baos);
byte[] arrayWithHeader = baos.toByteArray();
return arrayWithHeader;
}
}
| Java |
package edu.mit.csail.sls.wami.util;
import javax.servlet.http.HttpServletRequest;
public class Parameter {
public static String get(HttpServletRequest request, String param,
String def) {
String result = request.getParameter(param);
return result == null ? def : result;
}
public static boolean get(HttpServletRequest request, String param,
boolean def) {
return get(request.getParameter(param), def);
}
public static boolean get(String param, boolean def) {
if (param == null) {
return def;
}
return Boolean.parseBoolean(param);
}
public static int get(String param, int def) {
if (param == null) {
return def;
}
return Integer.parseInt(param);
}
}
| Java |
package edu.mit.csail.sls.wami.util;
import java.util.HashMap;
public class ContentType {
String major;
String minor;
HashMap<String, String> parameters = new HashMap<String, String>();
public static ContentType parse(String contentType) {
return new ContentType().initialize(contentType);
}
protected ContentType initialize(String contentType) {
if (contentType == null) {
return this;
}
contentType = contentType.toUpperCase();
int length = contentType.length();
StringBuffer buf = new StringBuffer();
char c;
int i = 0;
while (i < length) {
c = contentType.charAt(i++);
if (c == '/' || c == ';')
break;
buf.append(c);
}
major = buf.toString().trim();
buf.delete(0, buf.length());
while (i < length) {
c = contentType.charAt(i++);
if (c == ';')
break;
buf.append(c);
}
minor = buf.toString().trim();
buf.delete(0, buf.length());
while (true) {
String key;
String value;
while (i < length) {
c = contentType.charAt(i++);
if (c == '=')
break;
buf.append(c);
}
key = buf.toString().trim();
buf.delete(0, buf.length());
// Values can be quoted (see RFC 2045 sec. 5.1) but for now
// we just handle what we need for audio.
while (i < length) {
c = contentType.charAt(i++);
if (c == ';')
break;
buf.append(c);
}
value = buf.toString().trim();
buf.delete(0, buf.length());
if (key.length() == 0)
break;
parameters.put(key, value);
}
return this;
}
public String getMajor() {
return major;
}
public String getMinor() {
return minor;
}
public String getParameter(String key) {
return parameters.get(key.toUpperCase());
}
public int getIntParameter(String key, int def) {
String value = getParameter(key);
return value == null ? def : Integer.parseInt(value);
}
public boolean getBooleanParameter(String key, boolean def) {
String value = getParameter(key);
return value == null ? def : Boolean.parseBoolean(value);
}
}
| Java |
/* -*- Java -*-
*
* Copyright (c) 2009
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.sls.wami.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
/**
* Basic utils for XML manipulation.
*/
public class XmlUtils {
// //////////////////////////
// // XML STUFF ////////
// //////////////////////////
private static final DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
private static final TransformerFactory tFactory = TransformerFactory
.newInstance();
public static Document toXMLDocument(String xmlString) {
return toXMLDocument(new InputSource(new StringReader(xmlString)));
}
public static Document toXMLDocument(InputStream in) {
return toXMLDocument(new InputSource(in));
}
public static Document toXMLDocument(InputSource source) {
Document xmlDoc = null;
try {
xmlDoc = getBuilder().parse(source);
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return xmlDoc;
}
public static DocumentBuilder getBuilder() {
try {
return factory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
return null;
}
}
public static Document newXMLDocument() {
Document document = getBuilder().newDocument();
return document;
}
/**
* Convert an XML node to a string. Node can be a document or an element.
*
* @param node
* @return
*/
public static String toXMLString(Node node) {
Transformer transformer = null;
try {
transformer = tFactory.newTransformer();
// System.err.format("Using transformer: %s%n", transformer);
} catch (TransformerConfigurationException e) {
e.printStackTrace();
}
DOMSource source = new DOMSource(node);
StringWriter xmlWriter = new StringWriter();
StreamResult result = new StreamResult(xmlWriter);
try {
transformer.transform(source, result);
} catch (TransformerException e) {
e.printStackTrace();
}
return xmlWriter.toString();
}
public static class ValidationErrorHandler implements ErrorHandler {
public void error(SAXParseException e) throws SAXException {
System.out.println(e);
}
public void fatalError(SAXParseException e) throws SAXException {
System.out.println(e);
}
public void warning(SAXParseException e) throws SAXException {
System.out.println(e);
}
}
}
| Java |
/* -*- Java -*-
*
* Copyright (c) 2009
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.sls.wami.util;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import edu.mit.csail.sls.wami.log.ILoggable;
public class LoggableUtils {
public static ILoggable recreateLoggable(String className, String event,
String eventtype) {
//System.out.println("Creating new loggable class: " + className);
ILoggable loggable = null;
if (className != null) {
try {
Class<?> acClass = Class.forName(className);
Class<?>[] paramTypes = {};
Constructor<?> cons = acClass.getConstructor(paramTypes);
Object[] args = {};
loggable = (ILoggable) cons.newInstance(args);
loggable.fromLogEvent(event, eventtype);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
return loggable;
}
}
| Java |
/* -*- Java -*-
*
* Copyright (c) 2009
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.sls.wami.app;
import java.io.InputStream;
import org.w3c.dom.Document;
import edu.mit.csail.sls.wami.WamiConfig;
import edu.mit.csail.sls.wami.log.IEventLogger;
import edu.mit.csail.sls.wami.log.IEventPlayer;
import edu.mit.csail.sls.wami.log.ILoggable;
import edu.mit.csail.sls.wami.recognition.lm.LanguageModel;
import edu.mit.csail.sls.wami.recognition.lm.exceptions.LanguageModelCompilationException;
import edu.mit.csail.sls.wami.recognition.lm.exceptions.LanguageModelServerException;
import edu.mit.csail.sls.wami.recognition.lm.exceptions.UnsupportedLanguageModelException;
/**
* An instance of this interface will be passed to implementors of
* {@link IApplication}
*
* @author alexgru
*
*/
public interface IApplicationController {
/**
* Set the language model in the current session
*
* @param lm
* @throws LanguageModelCompilationException
* If there was a problem with the language model which meant it
* couldn't be compiled or loaded
* @throws LanguageModelServerException
* When an unexpected error occurred with the language
* model/recognition server
* @throws UnsupportedLanguageModelException
* When an unsupported language model is provided
*/
public void setLanguageModel(LanguageModel lm)
throws LanguageModelCompilationException,
UnsupportedLanguageModelException, LanguageModelServerException;
/**
* Use TTS to speak a particular string (requires that you have specified a
* synthesizer in the config file).
*
* @param ttsString
* The string to say
*/
public void speak(String ttsString);
/**
* Send a message to the handler in the javascript client running in the
* browser
*
* @param message
* The message to send
*/
public void sendMessage(Document xmlMessage);
/**
* Play an arbitrary audio stream through to the client. Audio header
* information should appear at the beginning of the stream
*
* @param audioIn
* A stream of audio to play
*/
public void play(InputStream audioIn);
/**
* Returns the audio most recently recorded from the client. Returns null if
* no sound has been recorded yet. Appropriate header information will be
* available in the stream.
*
* @return
*/
public InputStream getLastRecordedAudio();
/**
* Log an application-specific event. The event will only be logged if an
* event logger has been specified in the configuration file. The event's
* meta info will be filled in with the name of the class of the
* {@link ILoggable} item
*
* @param loggable
* The event to be logged
* @param timestampMillis
* The timestamp to associate with the event; typically
* System.currentTimeMillis()
*/
public void logEvent(ILoggable loggable, long timestampMillis);
/**
* Set the event logger for this application.
*
* @param logger
*/
public void setEventLogger(IEventLogger logger);
/**
* Returns the log player associated with the application.
*
* @return null if no log player is specified.
*/
public IEventPlayer getLogPlayer();
/**
* Returns the WAMI Configuration associated with the application.
*/
public WamiConfig getWamiConfig();
/**
* Returns an audio input stream found given a "fileName". Really, it's just
* a string representation of the WAV's location, which could be a database,
* a file system, a URL, depending on how the app controller decides to
* implement IAudioRetriever.
*
* @param wsessionid
* @param utt_id
* @return
*/
public InputStream getRecording(String fileName);
}
| Java |
/* -*- Java -*-
*
* Copyright (c) 2009
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.sls.wami.app;
import java.util.Map;
import javax.servlet.http.HttpSession;
import org.w3c.dom.Element;
import edu.mit.csail.sls.wami.recognition.IRecognitionListener;
/**
* Application developers should create an instance of this class specific to
* their application. The name of that class should be set in the config.xml
* file, as in e.g.
*
* <pre>
* <portal appClass="com.mycompany.MyWamiApplication" .../>
* </pre>
*
* @author alexgru
*
*/
public interface IWamiApplication extends IRecognitionListener {
/**
* A new instance is created for each user interacting with the system. If a
* user presses 'reload', then a new instance of the application may be
* called with the same session
*
* @param appController
* The application "controller" which may be used to send
* messages to the client, and speak TTS
* @param session
* The servlet session which will be associated with this
* @param paramMap
* The parameters provided in the application tag of the
* config.xml
*/
public void initialize(IApplicationController appController,
HttpSession session, Map<String, String> paramMap);
/**
* Called when the client (browser) has sent a message to the server
*
* @param xmlRoot
* the root of the xml message received from the client The
* message received from the client
*/
public void onClientMessage(Element xmlRoot);
/**
* Called when this application should "close", either due to a timeout or
* the user navigating away from the page, or hitting reload to start a new
* instance. It is not guaranteed that this method will always be called,
* for instance if the servlet engine is shutdown before a session times out
*/
public void onClosed();
/**
* This is called every time the java applet has finished playing a piece of
* audio.
*/
public abstract void onFinishedPlayingAudio();
}
| Java |
/* -*- Java -*-
*
* Copyright (c) 2009
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.sls.wami.log;
import java.io.IOException;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.sound.sampled.AudioInputStream;
/**
* Interface which allows for WAMI logging on a particular session
*
* @author alexgru
*/
public interface IEventLogger {
// these are type core event types used internally by the wami system
static final String RecognitionStarted = "RecognitionStarted";
static final String IncrementalRecResult = "IncrementalRecResult";
static final String FinalRecResult = "FinalRecResult";
static final String ClientMessage = "ClientMessage";
static final String Speak = "Speak";
static final String SentMessage = "SentMessage";
static final String Instantiation = "Instantiation";
static final String ClientLog = "ClientLog";
static final String RequestHeaders = "RequestHeaders";
/**
* Set any initialization parameters from the xml
*/
void setParameters(ServletContext sc, Map<String, String> map)
throws EventLoggerException;
/**
* This will be called before any events are logged, it sets a unique
* session id for this logger. It will be called exactly once.
*
* @param serverAddress
* The address of the server
* @param clientAddress
* The address of the client
* @param wsessionid
* @throws EventLoggerException
* If a logging exception occurs
*/
void createSession(String serverAddress, String clientAddress,
String wsessionid, long timestampMillis, String recDomain) throws EventLoggerException;
/**
* Log a single event, with the given timestamp
*
* @param logEvent
* The event to log
* @param timestampMillis
* The timestamp to associate with the event * @throws
* EventLoggerException If a logging exception occurs
*/
void logEvent(ILoggable logEvent, long timestampMillis)
throws EventLoggerException;
/**
* Log a recorded utterance
*
* @param audioIn
* An input stream with the utterance to log
* @param timestampMillis
* The timestamp for the utterance
* @throws EventLoggerException
* If a logging exception occurs
* @throws IOException
* If there is an error reading the audioIn stream
*/
void logUtterance(AudioInputStream audioIn, long timestampMillis)
throws EventLoggerException, IOException;
/**
* Close the logger. The logger should finish logging any events sent to it,
* and then close down.
*/
void close() throws EventLoggerException;
public void addSessionCreatedListener(IEventLoggerListener l);
}
| Java |
/* -*- Java -*-
*
* Copyright (c) 2009
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.sls.wami.log;
import java.util.Map;
import javax.servlet.ServletContext;
public interface IEventPlayer {
public void setParameters(ServletContext sc, Map<String, String> params);
public void addListener(IPlaybackListener listener);
public void removeListener(IPlaybackListener listener);
public void clearListeners();
public void playSession(String logSessionId) throws EventPlayerException;
}
| Java |
/* -*- Java -*-
*
* Copyright (c) 2009
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.sls.wami.log;
import org.w3c.dom.Document;
import edu.mit.csail.sls.wami.util.XmlUtils;
/**
* An easy way to log strings
*
*/
public class StringLogEvent implements ILoggable {
private String event;
private String eventType;
public StringLogEvent(String event, String eventType) {
fromLogEvent(event, eventType);
}
/**
* Empty constructor for log playback
*/
public StringLogEvent() {
}
public void fromLogEvent(String event, String eventType) {
this.event = event;
this.eventType = eventType;
}
public String getEventType() {
return eventType;
}
public String toLogEvent() {
return event;
}
public String getEvent() {
return toLogEvent();
}
/**
* Parse the event string as xml and return the
* document
*/
public Document getEventAsXml() {
return XmlUtils.toXMLDocument(event);
}
@Override
public String toString() {
return toLogEvent();
}
}
| Java |
/* -*- Java -*-
*
* Copyright (c) 2009
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.sls.wami.log;
/**
* An exception which can be thrown by the {@link EventLogger}
*
* @author alexgru
*
*/
public class EventLoggerException extends Exception {
public EventLoggerException(String message) {
super(message);
}
public EventLoggerException(Throwable cause) {
super(cause);
}
public EventLoggerException(String message, Throwable cause) {
super(message, cause);
}
}
| Java |
package edu.mit.csail.sls.wami.log;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import javax.servlet.ServletContext;
import javax.sound.sampled.AudioInputStream;
public class EventLoggerDaemonAdapter implements IEventLogger {
private ExecutorService eventLoggerService;
private IEventLogger logger;
private ServletContext sc;
static class LogThreadFactory implements ThreadFactory {
public Thread newThread(Runnable runnable) {
Thread t = new Thread(runnable, "Event Logger");
t.setPriority(Thread.MIN_PRIORITY);
return t;
}
}
public EventLoggerDaemonAdapter(IEventLogger logger) {
this.logger = logger;
this.eventLoggerService = Executors
.newSingleThreadExecutor(new LogThreadFactory());
}
@Override
public void setParameters(ServletContext sc, Map<String, String> map)
throws EventLoggerException {
this.sc = sc;
logger.setParameters(sc, map);
}
@Override
public void createSession(final String serverAddress,
final String clientAddress, final String wsessionid,
final long timestampMillis, final String recDomain)
throws EventLoggerException {
eventLoggerService.submit(new Runnable() {
public void run() {
try {
logger.createSession(serverAddress, clientAddress,
wsessionid, timestampMillis, recDomain);
} catch (EventLoggerException e) {
e.printStackTrace();
sc.log("Event Logger Error", e);
}
}
});
}
@Override
public void addSessionCreatedListener(IEventLoggerListener l) {
logger.addSessionCreatedListener(l);
}
@Override
public void close() throws EventLoggerException {
eventLoggerService.submit(new Runnable() {
public void run() {
try {
logger.close();
logger = null;
} catch (Exception e) {
sc.log("Event Logger Error", e);
e.printStackTrace();
}
}
});
eventLoggerService.shutdown();
try {
eventLoggerService.awaitTermination(60, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
eventLoggerService.shutdownNow();
eventLoggerService = null;
}
@Override
public void logEvent(final ILoggable logEvent, final long timestampMillis)
throws EventLoggerException {
eventLoggerService.submit(new Runnable() {
public void run() {
try {
logger.logEvent(logEvent, timestampMillis);
} catch (Exception e) {
e.printStackTrace();
sc.log("Event Logger Error", e);
}
}
});
}
@Override
public void logUtterance(final AudioInputStream audioIn,
final long timestampMillis) throws EventLoggerException,
IOException {
eventLoggerService.submit(new Runnable() {
public void run() {
try {
logger.logUtterance(audioIn, timestampMillis);
} catch (Exception e) {
e.printStackTrace();
sc.log("Event Logger Error", e);
}
}
});
}
}
| Java |
/* -*- Java -*-
*
* Copyright (c) 2009
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.sls.wami.log;
import java.io.InputStream;
/**
* This listener is used by {@link IEventPlayer} which plays back events from a
* log in the order they were recorded. Each time a listener method is called,
* the player will block until it has finished
*
* @author alexgru
*/
public interface IPlaybackListener {
/**
* Called to simulate the next event recorded in the log
*/
public void onNextEvent(ILoggable event, long timestamp);
/**
* Immediately after RecognitionStarted event has occurred, this method will
* be called with the audio stream which was recorded as part of that event
*
* @param audioIn
* An input stream, containing audio with header information
* @param timestamp
* The timestamp associated with this audio stream. In this case,
* the timestamp will actually be "in the future" - it will
* correspond to the FinalRecResult event which will be received
* eventually via
* {@link #nextEvent(String, String, String, long)
*/
public void onNextEvent(InputStream audioOut, long timestamp);
/**
* This method is called before any of the events of a log file have started
* firing.
* @param sessionid
*/
public void onStartLog(String sessionid);
/**
* This is called once all the events of a log file have finished firing.
*/
public void onLogFinished();
/**
* Allows error handling in the playback listener.
* @param e
*/
public void onEventPlayerException(EventPlayerException e);
}
| Java |
/* -*- Java -*-
*
* Copyright (c) 2009
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.sls.wami.log;
/**
* An exception which can be thrown by the {@link EventLogger}
*
* @author alexgru
*
*/
public class EventPlayerException extends Exception {
public EventPlayerException(String message) {
super(message);
}
public EventPlayerException(Throwable cause) {
super(cause);
}
public EventPlayerException(String message, Throwable cause) {
super(message, cause);
}
}
| Java |
/* -*- Java -*-
*
* Copyright (c) 2009
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.sls.wami.log;
public interface ILoggable {
/**
* Returns a string representation of this item to be logged
*/
public String toLogEvent();
/**
* This will be called immediately after the required no-argument
* constructor and will be passed the string created by the logStr method
* @param logStr The string created by {@link #toLogEvent()}
* @param eventType The type of event
*/
public void fromLogEvent(String logStr, String eventType);
public String getEventType();
}
| Java |
package edu.mit.csail.sls.wami.log;
public interface IEventLoggerListener {
public void reportSessionId(Object sessionId);
}
| Java |
/* -*- Java -*-
*
* Copyright (c) 2009
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.sls.wami.log;
import java.io.InputStream;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import edu.mit.csail.sls.wami.app.IApplicationController;
import edu.mit.csail.sls.wami.app.IWamiApplication;
import edu.mit.csail.sls.wami.recognition.IRecognitionResult;
import edu.mit.csail.sls.wami.recognition.RecognitionResult;
import edu.mit.csail.sls.wami.recognition.RecognitionStartedLogEvent;
import edu.mit.csail.sls.wami.relay.ClientMessageLogEvent;
import edu.mit.csail.sls.wami.relay.SentMessageLogEvent;
import edu.mit.csail.sls.wami.synthesis.SpeakLogEvent;
import edu.mit.csail.sls.wami.util.XmlUtils;
/**
* This is an example implementation of the ILogPlayerListener class. The
* purpose of this class is to convert logged events back into messages that the
* client can understand and replay. For example to the browser during the
* original session should also be resent.
*
* There are two ways that one might wish to re-send the XML messages to the
* client. The first is to re-send them directly, ignoring everything else (like
* the recognition results, and onClientMessage). The second version of playback
* is one that uses the IWamiApplication, and recomputes onRecognitionResult and
* onClientMessage. In this case we can IGNORE the logged "sent messages",
* because we expect our IWamiApplication to reproduce them.
*
* In either case, it might be useful to have a way of automatically sending
* back the XML originally received in onClientMessage. Thus, if a client
* message is of the form >update send_back_during_replay="true"< ...>, the
* update will get sent directly to the client.
*
* You can use this class by defining an instance in your WamiApplication. Then
* you can add it as a listener to the log player, which is made available on
* the controller. You can then start the player from your application.
*
* @author imcgraw
*/
public class WamiLogPlayerListener implements IPlaybackListener {
private final IApplicationController controller;
private final IWamiApplication application;
/**
* Creates a log listener that only passes along events sent to the client.
*
* @param controller
*/
public WamiLogPlayerListener(IApplicationController controller) {
this.controller = controller;
this.application = null;
}
/**
* Creates a log listener that sends events to the application. The only
* events that get sent to the controller will be those SentMessage events
* with the attribute send_back="true"; All SentMessage events will be give
* to onClientMessage in the application.
*
* @param application
* @param controller
*/
public WamiLogPlayerListener(IWamiApplication application,
IApplicationController controller) {
this.application = application;
this.controller = controller;
}
public void onNextEvent(ILoggable event, long timestamp) {
if (event instanceof ClientMessageLogEvent) {
relayEvent((ClientMessageLogEvent) event);
} else if (event instanceof SentMessageLogEvent) {
relayEvent((SentMessageLogEvent) event);
} else if (event instanceof RecognitionResult) {
relayEvent((IRecognitionResult) event);
} else if (event instanceof SpeakLogEvent) {
relayEvent((SpeakLogEvent) event);
} else if (event instanceof RecognitionStartedLogEvent) {
relayEvent((RecognitionStartedLogEvent) event);
}
}
public void onNextEvent(InputStream audioIn, long timestamp) {
System.out.println("Attempting to play audio!");
controller.play(audioIn);
}
private void relayEvent(IRecognitionResult result) {
if (application != null) {
application.onRecognitionResult(result);
}
}
private void relayEvent(SpeakLogEvent event) {
if (application == null) {
controller.speak(event.getText());
}
}
private void relayEvent(SentMessageLogEvent event) {
if (application == null) {
// We're not using a wami application, so just resend directly
controller.sendMessage(event.getEventAsXml());
}
}
private boolean hasBooleanAttribute(Element e, String name) {
return e.getAttribute(name) != null
&& Boolean.parseBoolean(e.getAttribute(name));
}
private Document replaceRootTagName(Element root, String newName) {
Document doc = XmlUtils.newXMLDocument();
// Convert this to a "reply" as if it had been a "sent message"
Element newroot = doc.createElement(newName);
doc.appendChild(newroot);
// Copy the attributes to the new element
NamedNodeMap attrs = root.getAttributes();
for (int i = 0; i < attrs.getLength(); i++) {
Attr attr2 = (Attr) doc.importNode(attrs.item(i), true);
newroot.getAttributes().setNamedItem(attr2);
}
// Move all the children
NodeList list = root.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
Node node = list.item(i);
newroot.appendChild(doc.importNode(node, true));
}
return doc;
}
private void relayEvent(ClientMessageLogEvent event) {
Element root = (Element) event.getEventAsXml().getFirstChild();
if (hasBooleanAttribute(root, "send_back_during_replay")) {
Document doc = replaceRootTagName(root, "reply");
controller.sendMessage(doc);
}
if (application != null) {
application.onClientMessage(root);
}
}
private void relayEvent(RecognitionStartedLogEvent event) {
if (application != null) {
application.onRecognitionStarted();
}
}
public void onLogFinished() {
// TODO Auto-generated method stub
}
public void onStartLog(String sessionId) {
// TODO Auto-generated method stub
}
public void onEventPlayerException(EventPlayerException e) {
// TODO Auto-generated method stub
}
}
| Java |
/* -*- Java -*-
*
* Copyright (c) 2009
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.sls.wami.portal.xmlrpc;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import javax.servlet.ServletContext;
import javax.sound.sampled.AudioInputStream;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpVersion;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfig;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;
import org.apache.xmlrpc.client.XmlRpcCommonsTransportFactory;
import edu.mit.csail.sls.wami.recognition.IRecognitionListener;
import edu.mit.csail.sls.wami.recognition.IRecognitionResult;
import edu.mit.csail.sls.wami.recognition.IRecognizer;
import edu.mit.csail.sls.wami.recognition.RecognitionResult;
import edu.mit.csail.sls.wami.recognition.exceptions.LanguageModelNotSetException;
import edu.mit.csail.sls.wami.recognition.exceptions.RecognizerException;
import edu.mit.csail.sls.wami.recognition.exceptions.RecognizerUnreachableException;
import edu.mit.csail.sls.wami.recognition.lm.LanguageModel;
import edu.mit.csail.sls.wami.recognition.lm.exceptions.LanguageModelCompilationException;
import edu.mit.csail.sls.wami.recognition.lm.exceptions.UnsupportedLanguageModelException;
import edu.mit.csail.sls.wami.recognition.lm.jsgf.JsgfGrammar;
public class XmlRpcPortalRecognizer implements IRecognizer {
private XmlRpcClient client;
private String sessionId = null;
private boolean hasSetLanguageModel = false;
private boolean incrementalResults = true;
private boolean recordOnly = false;
private ExecutorService recognizeCallbackExecutor = Executors
.newSingleThreadExecutor();
private ServletContext sc;
private URL serverAddress;
private static XmlRpcClientConfig createClientConfig(URL serverAddress,
int connectionTimeout, int replyTimeout) {
XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
config.setServerURL(serverAddress);
// the server supports extensions, so allow it for efficiency
config.setEnabledForExtensions(true);
config.setConnectionTimeout(connectionTimeout);
config.setReplyTimeout(replyTimeout);
return config;
}
public void setDynamicParameter(String name, String value)
throws RecognizerException {
if ("incrementalResults".equals(name)) {
incrementalResults = Boolean.parseBoolean(value);
} else if ("recordOnly".equals(name)) {
recordOnly = Boolean.parseBoolean(value);
} else {
throw new RecognizerException("Unknown parameter: '" + name + "'");
}
}
public void setParameters(ServletContext sc, Map<String, String> map)
throws RecognizerException {
this.sc = sc;
String recDomain = (String) sc.getAttribute("recDomain");
String developerEmail = map.get("developerEmail");
String developerKey = map.get("developerKey");
String recordFormat = map.get("recordFormat");
int recordSampleRate = Integer.parseInt(map.get("recordSampleRate"));
boolean recordIsLittleEndian = Boolean.parseBoolean(map
.get("recordIsLittleEndian"));
String incrementalResultsStr = map.get("incrementalResults");
incrementalResults = (incrementalResultsStr == null || Boolean
.parseBoolean(incrementalResultsStr));
serverAddress = null;
try {
serverAddress = new URL(map.get("url"));
} catch (MalformedURLException e) {
throw new RecognizerException("Invalid recognizer url", e);
}
XmlRpcClientConfig config = createClientConfig(serverAddress,
10 * 1000, 10 * 1000);
client = new XmlRpcClient();
XmlRpcCommonsTransportFactory factory = new XmlRpcCommonsTransportFactory(
client);
// Use HTTP 1.1
HttpClient httpClient = new HttpClient();
httpClient.getParams().setParameter(HttpMethodParams.PROTOCOL_VERSION,
HttpVersion.HTTP_1_1);
factory.setHttpClient(httpClient);
client.setTransportFactory(factory);
client.setConfig(config);
Object[] createParams = { developerEmail, developerKey, recordFormat,
recordSampleRate, recordIsLittleEndian, recDomain };
try {
sessionId = (String) client.execute(
"Portal.createRecognizerSession", createParams);
} catch (XmlRpcException e) {
if (e.code == ErrorCodes.SERVER_ERROR_CODE) {
throw new RecognizerException(e);
} else {
throw new RecognizerUnreachableException(e);
}
}
String jsgfGrammarPath = map.get("jsgfGrammarPath");
String jsgfGrammarLanguage = map.get("jsgfGrammarLanguage");
if (jsgfGrammarPath != null) {
InputStream in = sc.getResourceAsStream(jsgfGrammarPath);
if (in == null) {
throw new RecognizerException("Couldn't find grammar: "
+ jsgfGrammarPath);
}
String language = (jsgfGrammarLanguage != null) ? jsgfGrammarLanguage
: "en-us";
try {
JsgfGrammar grammar = new JsgfGrammar(in, language);
setLanguageModel(grammar);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void recognize(AudioInputStream audioIn,
final IRecognitionListener listener) throws RecognizerException,
IOException {
ArrayList<Future<?>> futures = new ArrayList<Future<?>>();
synchronized (this) {
checkSessionId();
Object[] sessionIdParams = { sessionId };
if (!recordOnly) {
if (!hasSetLanguageModel) {
throw new LanguageModelNotSetException();
}
try {
client.execute("Portal.openUtterance", sessionIdParams);
} catch (XmlRpcException e) {
throw new RecognizerException(e);
}
}
// we will always wait for the last task in the queue to be finished
futures.add(recognizeCallbackExecutor.submit(new Runnable() {
public void run() {
listener.onRecognitionStarted();
}
}));
try {
List<String> hyps = new ArrayList<String>();
if (recordOnly) {
pretendToRecognize(audioIn);
} else {
hyps = getRecognitionResults(audioIn, futures, listener);
}
final IRecognitionResult finalResult = new RecognitionResult(
false, hyps);
futures.add(recognizeCallbackExecutor.submit(new Runnable() {
public void run() {
listener.onRecognitionResult(finalResult);
}
}));
// System.out.println("XmlRpcPortaleRecognizer sent: " +
// totalSent
// + " bytes");
} catch (XmlRpcException e) {
e.printStackTrace();
}
}
// wait for futures outside of synchronized block
for (Future<?> future : futures) {
try {
future.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
private void pretendToRecognize(AudioInputStream audioIn)
throws IOException {
int chunkSize = 1024 * 10;
byte[] buffer = new byte[chunkSize];
while (true) {
int nRead = audioIn.read(buffer);
System.out.println("Read Bytes:" + nRead);
if (nRead <= 0) {
break;
}
}
}
private List<String> getRecognitionResults(AudioInputStream audioIn,
ArrayList<Future<?>> futures, final IRecognitionListener listener)
throws XmlRpcException, IOException {
int chunkSize = 1024 * 10;
// int chunkSize = 2 << 10; // kB
byte[] buffer = new byte[chunkSize];
byte[] sendBuffer = new byte[chunkSize];
String lastPartial = null;
Object[] sessionIdParams = { sessionId };
int totalSent = 0;
while (true) {
int nRead = audioIn.read(buffer);
System.out.println("Read Bytes:" + nRead);
if (nRead <= 0) {
break;
}
if (nRead > 0) {
// reuse buffer when possible
byte[] toSend = (nRead == chunkSize) ? sendBuffer
: new byte[nRead];
System.arraycopy(buffer, 0, toSend, 0, nRead);
Object[] writeParams = { sessionId, toSend };
totalSent += nRead;
if (incrementalResults) {
final String partial = (String) client.execute(
"Portal.writePartial", writeParams);
if (!partial.equals(lastPartial)) {
// System.out.println("partial: " + partial);
futures.add(recognizeCallbackExecutor
.submit(new Runnable() {
public void run() {
List<String> hyps = Collections
.singletonList(partial);
final IRecognitionResult result = new RecognitionResult(
true, hyps);
listener.onRecognitionResult(result);
}
}));
// listener.result(result, isIncremental)
lastPartial = partial;
}
} else {
client.execute("Portal.write", writeParams);
}
}
}
Object[] nbest = (Object[]) client.execute("Portal.closeUtterance",
sessionIdParams);
ArrayList<String> hyps = new ArrayList<String>(nbest.length);
for (Object o : nbest) {
Map<String, String> map = (Map<String, String>) o;
hyps.add(map.get("text"));
}
// System.out.println("hyps:");
// System.out.println(hyps);
return hyps;
}
public synchronized void setLanguageModel(LanguageModel model)
throws RecognizerException {
if (model instanceof JsgfGrammar) {
JsgfGrammar jsgf = (JsgfGrammar) model;
Object[] grammarParams = { sessionId, jsgf.getGrammar(),
jsgf.getDictionaryLanguage() };
try {
client.execute("Portal.setJsgfGrammar", grammarParams);
hasSetLanguageModel = true;
} catch (XmlRpcException e) {
if (e.code == ErrorCodes.GRAMMAR_COMPILATION_ERROR) {
throw new LanguageModelCompilationException(e.getMessage());
} else if (e.code == ErrorCodes.SERVER_ERROR_CODE
|| e.code == ErrorCodes.INVALID_SESSION_CODE) {
throw new RecognizerException(e);
} else {
throw new RecognizerUnreachableException(e);
}
}
} else {
throw new UnsupportedLanguageModelException(
"Only jsgf language models are currently supported");
}
}
public synchronized void destroy() throws RecognizerException {
System.out.println("destroying XmlRpcPortalRecognizer instance");
recognizeCallbackExecutor.shutdownNow();
if (sessionId != null) {
Object[] sessionIdParams = { sessionId };
try {
// need to close up quickly when we are destroyed
XmlRpcClientConfig config = createClientConfig(serverAddress,
2 * 1000, 2 * 1000);
client.execute(config, "Portal.closeRecognizerSession",
sessionIdParams);
} catch (XmlRpcException e) {
if (e.code == ErrorCodes.SERVER_ERROR_CODE
|| e.code == ErrorCodes.INVALID_SESSION_CODE) {
throw new RecognizerException(e);
}
}
}
}
private void checkSessionId() throws RecognizerException {
if (sessionId == null) {
throw new RecognizerException("Not connected");
}
}
}
| Java |
/* -*- Java -*-
*
* Copyright (c) 2009
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.sls.wami.portal.xmlrpc;
public class ErrorCodes {
public final static int SERVER_ERROR_CODE = 1;
public final static int INVALID_SESSION_CODE = 2;
public final static int GRAMMAR_COMPILATION_ERROR = 3;
public static final int UNSUPPORTED_LANGUAGE = 4;
}
| Java |
package edu.mit.csail.sls.wami.validation;
import java.io.PrintWriter;
import java.io.StringWriter;
public class ValidationUtils {
public static String stackTraceToString(Throwable e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String stacktrace = sw.toString();
return stacktrace;
}
}
| Java |
package edu.mit.csail.sls.wami.validation;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import edu.mit.csail.sls.wami.util.Instantiable;
public interface IValidator extends Instantiable {
/**
* Validates the state of the entire servlet. Returns an empty list if
* everything's fine. For most people, this will suffice. For those who want
* to make sure the servlet always up and running properly, this can be used
* in conjunction with a cron job to validate the servlet every so often.
*
* @param params
* The default options.
* @return
*/
public List<String> validate(HttpServletRequest request);
}
| Java |
package edu.mit.csail.sls.wami.audio;
import java.io.InputStream;
import edu.mit.csail.sls.wami.util.Instantiable;
public interface IAudioRetriever extends Instantiable {
public InputStream retrieveAudio(String fileName);
}
| Java |
/* -*- Java -*-
*
* Copyright (c) 2008
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.sls.wami.audio;
import edu.mit.csail.sls.wami.applet.sound.ByteFifo;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.ShortBuffer;
import java.util.Map;
import java.util.TreeMap;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
public class WamiResampleInputStream extends InputStream {
private static final int APPROXIMATION = 100;
private static final int FILTER_SCALE = 25;
private AudioFormat targetFormat;
private AudioFormat sourceFormat;
private AudioInputStream sourceStream;
private int L = 0; // interpolation factor
private int M = 0; // decimation factor
private float h[] = null; // resampling filter
private short z[] = null; // delay line
private int pZ = 0;
private int phase = 0;
private ByteFifo sourceByteFifo;
private ByteFifo targetByteFifo;
// For source byte to short conversion. Byte order set in initialize().
//
private byte[] sourceBytes = new byte[1024];
private ByteBuffer sourceByteBuffer = ByteBuffer.wrap(sourceBytes);
private ShortBuffer sourceShortBuffer = null;
// For target short to byte conversion. Byte order set in initialize().
//
private byte[] targetBytes = new byte[2];
private ByteBuffer targetByteBuffer = ByteBuffer.wrap(targetBytes);
private ShortBuffer targetShortBuffer = null;
// For caching interpolation filter.
private static Map<Integer, float[]> filterCache = new TreeMap<Integer, float[]>();
int gcd(int x, int y) {
int r;
while ((r = x % y) > 0) {
x = y;
y = r;
}
return y;
}
public WamiResampleInputStream(AudioFormat targetFormat,
AudioInputStream sourceStream) {
this.targetFormat = targetFormat;
this.sourceFormat = sourceStream.getFormat();
this.sourceStream = sourceStream;
int targetRate = Math.round(targetFormat.getSampleRate()
/ APPROXIMATION)
* APPROXIMATION;
int sourceRate = Math.round(sourceFormat.getSampleRate()
/ APPROXIMATION)
* APPROXIMATION;
int gcd = gcd(targetRate, sourceRate);
this.L = targetRate / gcd;
this.M = sourceRate / gcd;
sourceByteFifo = new ByteFifo(sourceRate / 5);
targetByteFifo = new ByteFifo(targetRate / 5);
initialize();
}
private void initialize() {
int f = Math.max(L, M);
int n = FILTER_SCALE * f;
int mod = n % L;
if (mod != 0)
n += L - mod;
z = new short[n / L];
boolean cached = true;
Integer cacheKey = new Integer(f);
h = filterCache.get(cacheKey);
if (h == null) {
h = InterpolationFilter.design(f, n, InterpolationFilter.HAMMING);
filterCache.put(cacheKey, h);
cached = false;
}
System.err.println("ResampleInputStream:" + " L=" + L + " M=" + M
+ " taps=" + h.length + " perPhase=" + z.length + " cached="
+ cached);
// Cause the delay buffer z to be fully loaded before first output.
//
phase = z.length * L;
// Finish initializing byte-swapping buffers now that we know the byte
// orders.
//
sourceByteBuffer.order(byteOrder(sourceFormat));
sourceShortBuffer = sourceByteBuffer.asShortBuffer();
targetByteBuffer.order(byteOrder(targetFormat));
targetShortBuffer = targetByteBuffer.asShortBuffer();
}
private ByteOrder byteOrder(AudioFormat format) {
return format.isBigEndian() ? ByteOrder.BIG_ENDIAN
: ByteOrder.LITTLE_ENDIAN;
}
@Override
public int available() throws IOException {
convert(false);
return targetByteFifo.size();
}
@Override
public int read() throws IOException {
throw new Error("not supported");
}
// This must read at least one byte, blocking until something is available
@Override
public int read(byte[] b, int offset, int length) throws IOException {
if (targetByteFifo.size() == 0) {
convert(true);
}
if (targetByteFifo.size() < length)
convert(false);
int m = Math.min(length, targetByteFifo.size());
if (m > 0) {
targetByteFifo.pop(b, offset, m);
}
// System.out.println("Read: " + m);
return m;
}
@Override
public void close() {
h = null;
z = null;
sourceByteFifo = null;
targetByteFifo = null;
}
// Convert as many samples as possible without blocking.
//
private void convert(boolean wait) throws IOException {
// Return if not operational (e.g., bad sample rates during
// initialization).
//
if (h == null)
return;
if (wait) {
int nRead = sourceStream.read(sourceBytes, 0, sourceBytes.length);
if (nRead > 0) {
sourceByteFifo.push(sourceBytes, 0, nRead);
}
}
// Read some source bytes without blocking.
if (sourceStream.available() > 0) {
int chunksize = 372;
int totalRead = 0;
// TODO(imcgraw): Talk to Lee about getting this code right
while (totalRead < chunksize) {
int nRead = sourceStream.read(sourceBytes);
if (nRead <= 0)
break;
totalRead += nRead;
sourceByteFifo.push(sourceBytes, 0, nRead);
}
// System.out.println("Finished chunk: " + totalRead);
}
// Perform conversion from sourceByteFifo to targetByteFifo.
//
int thisWhack = sourceByteFifo.size();
if (thisWhack > 1024) {
// System.err.format("Backlog: %d%n", thisWhack-1024);
thisWhack = 1024;
}
while (thisWhack > 1) {
// Shift source samples into delay buffer z.
//
while (phase >= L) {
phase -= L;
sourceByteFifo.pop(sourceBytes, 0, 2);
thisWhack -= 2;
short sourceSample = sourceShortBuffer.get(0);
z[pZ++] = sourceSample;
if (pZ == z.length)
pZ = 0;
if (thisWhack < 2) {
break;
}
}
// Possibly generate output samples.
//
while (phase < L) {
int pH = L - 1 - phase;
phase += M;
float sum = 0;
for (int t = pZ; t < z.length; t++) {
sum += h[pH] * z[t];
pH += L;
}
for (int t = 0; t < pZ; t++) {
sum += h[pH] * z[t];
pH += L;
}
short targetSample = (short) Math.round(L * sum);
targetShortBuffer.put(0, targetSample);
targetByteFifo.push(targetBytes);
}
}
// System.out.println("Bytes Pushed:" + targetByteFifo.size());
}
}
| Java |
/* -*- Java -*-
*
* Copyright (c) 2008
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.sls.wami.audio;
import edu.mit.csail.sls.wami.audio.WamiResampleAudioInputStream;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
public class WamiResampleAudioInputStream extends AudioInputStream {
public WamiResampleAudioInputStream(AudioFormat targetFormat,
AudioInputStream sourceStream) {
super(new WamiResampleInputStream(targetFormat, sourceStream),
targetFormat, AudioSystem.NOT_SPECIFIED);
}
}
| Java |
/* -*- Java -*-
*
* Copyright (c) 2009
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.sls.wami.audio;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import edu.mit.csail.sls.wami.util.ContentType;
import edu.mit.csail.sls.wami.WamiConfig;
import edu.mit.csail.sls.wami.WamiServlet;
import edu.mit.csail.sls.wami.relay.WamiRelay;
/**
* Receives audio bytes from the server and passes them on to the portal
* associated with this session
*
* @author alexgru
*
*/
public class RecordServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("Pinging the record servlet.");
WamiRelay relay = (WamiRelay) WamiServlet.getRelay(request);
relay.sendReadyMessage();
}
@Override
public void doPut(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Need PUT protocol for some mobile device audio controllers.
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//System.out.println("Request: "
// + WamiConfig.reconstructRequestURLandParams(request));
System.out.println("Handling portal recognize() post on session: "
+ request.getSession().getId());
// BufferedReader reader = new BufferedReader(new InputStreamReader(
// request.getInputStream()));
// String line;
// System.out.println("Reading lines:");
// while ((line = reader.readLine()) != null) {
// System.out.println(line);
// }
// if (line == null) {
// return;
// }
// The audio format of the recording device (and thus the sound coming
// in)
AudioFormat audioFormat = getAudioFormatFromParams(request,
"recordAudioFormat", "recordSampleRate", "recordIsLittleEndian");
System.out.println("RecordServlet; audioFormat=" + audioFormat);
AudioInputStream audioIn = new AudioInputStream(
new BufferedInputStream(request.getInputStream()), audioFormat,
AudioSystem.NOT_SPECIFIED);
AudioFormat requiredFormat = getRecognizerRequiredAudioFormat();
if (audioFormat.getEncoding() != requiredFormat.getEncoding()
|| audioFormat.getSampleRate() != requiredFormat
.getSampleRate()
|| audioFormat.getSampleSizeInBits() != requiredFormat
.getSampleSizeInBits()
|| audioFormat.getChannels() != requiredFormat.getChannels()
|| audioFormat.getFrameSize() != requiredFormat.getFrameSize()
|| audioFormat.getFrameRate() != requiredFormat.getFrameRate()
|| audioFormat.isBigEndian() != requiredFormat.isBigEndian()) {
System.out.println("Resampling");
audioIn = new WamiResampleAudioInputStream(
getRecognizerRequiredAudioFormat(), audioIn);
}
WamiRelay relay = (WamiRelay) WamiServlet.getRelay(request);
try {
relay.recognize(audioIn);
} catch (Exception e) {
// TODO: something smarter? We should really notify the application
// that an error occurred
throw new ServletException(e);
}
}
private AudioFormat getRecognizerRequiredAudioFormat() {
return new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 8000, 16, 1, 2,
8000, false);
}
public static String slurp(InputStream in) throws IOException {
StringBuffer out = new StringBuffer();
byte[] b = new byte[4096];
for (int n; (n = in.read(b)) != -1;) {
out.append(new String(b, 0, n));
}
return out.toString();
}
private AudioFormat getAudioFormatFromParams(HttpServletRequest request,
String formatParam, String sampleRateParam,
String isLittleEndianParam) {
System.out.println("Record Content-Type " + request.getContentType());
ContentType contentType = ContentType.parse(request.getContentType());
String contentMajor = contentType.getMajor();
String contentMinor = contentType.getMinor();
// If Content-Type is valid, go with it
if ("AUDIO".equals(contentMajor)) {
if (contentMinor.equals("L16")) {
// Content-Type = AUDIO/L16; CHANNELS=1; RATE=8000; BIG=false
int rate = contentType.getIntParameter("RATE", 8000);
int channels = contentType.getIntParameter("CHANNELS", 1);
boolean big = contentType.getBooleanParameter("BIG", true);
return new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, rate,
16, channels, 2, rate, big);
}
}
// One of the clients that does not specify ContentType, or
// sets it to something bogus
String audioFormatStr = request.getParameter(formatParam);
int sampleRate = Integer
.parseInt(request.getParameter(sampleRateParam));
boolean isLittleEndian = Boolean.parseBoolean(request
.getParameter(isLittleEndianParam));
if ("MULAW".equals(audioFormatStr)) {
return new AudioFormat(AudioFormat.Encoding.ULAW, sampleRate, 8, 1,
2, 8000, !isLittleEndian);
} else if ("LIN16".equals(audioFormatStr)) {
return new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, sampleRate,
16, 1, 2, sampleRate, !isLittleEndian);
}
throw new UnsupportedOperationException("Unsupported audio format: '"
+ audioFormatStr + "'");
}
}
| Java |
/* -*- Java -*-
*
* Copyright (c) 2008
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.sls.wami.audio;
class InterpolationFilter {
public static final int RECTANGULAR = 1;
public static final int HANNING = 2;
public static final int HAMMING = 3;
public static final int BLACKMAN = 4;
public static float[] design(float f, int n, int windowType) {
f = 1 / f;
float[] h = new float[n];
double c = 0.5 * (n - 1);
for (int i = 0; i < n; ++i) {
h[i] = (float) sinc(f * (i - c));
}
window(h, windowType);
normalize(h);
return h;
}
private static double sinc(double x) {
if (x == 0.0) {
return 1.0f;
} else {
double y = Math.PI * x;
return Math.sin(y) / y;
}
}
private static void window(float[] h, int windowType) {
int n = h.length;
double s;
switch (windowType) {
default:
case RECTANGULAR:
break;
case HANNING:
s = 2 * Math.PI / (n + 1);
for (int i = 0; i < n; ++i)
h[i] *= (float) (0.5 * (1 - Math.cos(s * (i + 1))));
break;
case HAMMING:
s = 2 * Math.PI / (n - 1);
for (int i = 0; i < n; ++i)
h[i] *= (float) (0.54 - 0.46 * Math.cos(s * i));
break;
case BLACKMAN:
s = 2 * Math.PI / (n - 1);
for (int i = 0; i < n; ++i)
h[i] *= (float) (0.42 - 0.5 * Math.cos(s * i) + 0.08 * Math
.cos(2 * s * i));
break;
}
}
private static void normalize(float[] h) {
float s = 0;
for (int i = 0; i < h.length; ++i)
s += h[i];
s = 1 / s;
for (int i = 0; i < h.length; ++i)
h[i] *= s;
}
private static float transitionBand(int windowType) {
switch (windowType) {
default:
case RECTANGULAR:
return 1.84f;
case HANNING:
return 6.22f;
case HAMMING:
return 6.64f;
case BLACKMAN:
return 11.13f;
}
}
public static int computeN(float f, float r, int w) {
return (int) Math.round(transitionBand(w) * f / r) + 1;
}
public static void _main(String[] args) {
int a = 0;
int f = Integer.parseInt(args[a++]);
float r = Float.parseFloat(args[a++]);
int w = Integer.parseInt(args[a++]);
int n = computeN((float) f, r, w);
System.out.println("n = " + n);
float[] h = design((float) f, n, w);
for (int i = 0; i < h.length; i++) {
System.out.println(h[i]);
}
}
public static void main(String[] args) {
int a = 0;
int f = Integer.parseInt(args[a++]);
int n = Integer.parseInt(args[a++]);
int w = Integer.parseInt(args[a++]);
float[] h = design((float) f, n, w);
for (int i = 0; i < h.length; i++) {
System.out.println(f * h[i]);
}
}
}
| Java |
/* -*- Java -*-
*
* Copyright (c) 2009
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.sls.wami.audio;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;
import edu.mit.csail.sls.wami.WamiConfig;
import edu.mit.csail.sls.wami.WamiServlet;
import edu.mit.csail.sls.wami.relay.WamiRelay;
import edu.mit.csail.sls.wami.util.ServletUtils;
/**
* This servlet is polled for audio by the applet. Audio may be posted, a URL
* passed, or the "play" called on the relay.
*
* @author imcgraw
*
*/
@SuppressWarnings("serial")
public class PlayServlet extends HttpServlet {
public static final AudioFormat playFormat = new AudioFormat(
AudioFormat.Encoding.PCM_SIGNED, 16000, 16, 1, 2, 16000, false);
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws IOException {
System.out.println("Request: "
+ WamiConfig.reconstructRequestURLandParams(request));
System.out.println("Audio Session ID: " + request.getSession().getId());
if (isPollRequest(request)) {
// Returns audio whenever some is posted to the same audio session
doPollRequest(request, response);
return;
}
if (isForwardRequest(request)) {
// Forward audio from a particular URL to anyone polling.
doForwardRequest(request, response);
}
}
/**
* Someone, somewhere is posting some audio. Pass this streaming audio on to
* whoever is polling on the same audio session id (i.e. the applet).
*
* @param request
* @param response
*/
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) {
response.setHeader("Cache-control", "no-cache");
response.setContentType("text/xml; charset=UTF-8");
String pinyin = request.getParameter("synth_string");
System.out.println(pinyin);
AudioInputStream input;
boolean success = true;
try {
input = new AudioInputStream(request.getInputStream(), playFormat,
AudioSystem.NOT_SPECIFIED);
getRelay(request).play(input);
} catch (IOException e) {
success = false;
e.printStackTrace();
}
try {
response.getWriter().write(
"<reply success='" + success + "' session='"
+ request.getSession().getId() + "'></reply>");
} catch (IOException e) {
e.printStackTrace();
}
}
private void doForwardRequest(HttpServletRequest request,
HttpServletResponse response) {
String urlstr = request.getParameter("url");
AudioInputStream ais = getWavFromURL(urlstr);
getRelay(request).play(ais);
}
public static AudioInputStream getWavFromURL(String urlstr) {
URL url;
AudioInputStream ais = null;
try {
url = new URL(urlstr);
URLConnection c = url.openConnection();
c.connect();
InputStream stream = c.getInputStream();
ais = new AudioInputStream(stream, playFormat,
AudioSystem.NOT_SPECIFIED);
System.out.println("Getting audio from URL: " + urlstr);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return ais;
}
private boolean isForwardRequest(HttpServletRequest request) {
return request.getParameter("url") != null;
}
private boolean isPollRequest(HttpServletRequest request) {
return request.getParameter("poll") != null
&& Boolean.parseBoolean(request.getParameter("poll"));
}
private void doPollRequest(HttpServletRequest request,
HttpServletResponse response) throws IOException {
try {
String id = request.getParameter("sessionid");
if (id == null) {
// Default ID is this request's session ID.
id = request.getSession().getId();
}
WamiRelay relay = getRelay(request);
if (relay == null) {
response.sendError(1);
return;
}
ServletContext sc = request.getSession().getServletContext();
WamiConfig config = WamiConfig.getConfiguration(sc);
int playPollTimeout = config.getPlayPollTimeout(request);
InputStream in = relay.waitForAudio(playPollTimeout);
if (in != null) {
response.setContentType("audio/wav");
// InputStream in =
// AudioUtils.createInputStreamWithWaveHeader(audio);
OutputStream out = response.getOutputStream();
ServletUtils.sendStream(in, out);
} else {
// System.out
// .println("Wait for audio timeout, not sending back audio");
response.setContentType("text/xml");
response.getOutputStream().close();
// response.sendError(1);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private WamiRelay getRelay(HttpServletRequest request) {
return (WamiRelay) WamiServlet.getRelay(request);
}
}
| Java |
/* -*- Java -*-
*
* Copyright (c) 2009
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.sls.wami;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.List;
import java.util.Vector;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import edu.mit.csail.sls.wami.relay.InitializationException;
import edu.mit.csail.sls.wami.relay.ReachedCapacityException;
import edu.mit.csail.sls.wami.relay.RelayManager;
import edu.mit.csail.sls.wami.relay.WamiRelay;
import edu.mit.csail.sls.wami.util.XmlUtils;
import edu.mit.csail.sls.wami.validation.IValidator;
/**
* <p>
* WamiServlet is the HttpServlet that which "controls" the interaction between
* galaxy and the various GUI clients. There is only one WamiServlet and it
* follows the general servlet life-cycle conventions. The {@link WamiRelay} is
* maintained on a per-client basis, and manages the specifics of each
* connection. This WamiServlet servlet is the gateway that allows a client to
* perform operations within its relay.
* </p>
* <p>
* Note that we expect the clients to be "polling" where on each poll the relay
* will sit and block until we have a new message from the relay to return to
* the client. This means that the polling is not inefficient, however it does
* mean that we effectively have a connection to each client open all the time.
* </p>
*
* @author alexgru
*
*/
public class WamiServlet extends HttpServlet {
WamiConfig ac = null;
@Override
public void init() throws ServletException {
ServletContext sc = getServletContext();
ac = WamiConfig.getConfiguration(sc);
super.init();
}
@Override
public void destroy() {
System.out.println("Destroying Servlet");
ServletContext sc = getServletContext();
RelayManager manager = (RelayManager) sc.getAttribute("relayManager");
if (manager != null) {
manager.close();
}
}
/**
* Get a message from the control servlet (via polling)
*/
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
if (isValidateServletRequest(request)) {
doValidateServlet(request, response);
return;
}
boolean polling = false;
WamiRelay relay = WamiServlet.getRelay(request);
if (relay == null) {
showError(request, response, "null_relay",
"The relay to the recognizer was not found");
return;
}
// if no xml is passed in, then we try the request parameters
String pollingStr = request.getParameter("polling");
polling = pollingStr != null && !pollingStr.equals("")
&& Boolean.parseBoolean(pollingStr);
String m = null;
try {
if (polling) {
// System.out.println("polling");
// polling happens here:
m = relay.waitForMessage();
if (m != null) {
printResponse(m, request, response);
} else {
response.getWriter().close();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* XML messages are posted to the control servlet here.
*/
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
Document xmlDoc;
System.err.println(WamiConfig
.reconstructRequestURLandParams(request));
InputStream stream;
stream = request.getInputStream();
InputSource source = new InputSource(new InputStreamReader(stream,
request.getCharacterEncoding()));
xmlDoc = XmlUtils.getBuilder().parse(source);
Element root = (Element) xmlDoc.getFirstChild();
if (root == null) {
return;
}
clientUpdateMessage(request, response, root);
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void clientUpdateMessage(HttpServletRequest request,
HttpServletResponse response, Element root) throws IOException {
WamiRelay relay = WamiServlet.getRelay(request);
if (relay == null) {
// Can't really send an error when we reply to a post for x-site
printResponse("<empty />", request, response);
return;
}
String stoppollingStr = root.getAttribute("stoppolling");
boolean stopPolling = stoppollingStr != null
&& !stoppollingStr.equals("")
&& Boolean.parseBoolean(stoppollingStr);
if (stopPolling) {
relay.stopPolling();
} else {
String clientUpdateXML = XmlUtils.toXMLString(root);
System.out.println("Update: " + clientUpdateXML);
relay.handleClientUpdate(request.getSession(), clientUpdateXML);
printResponse("<empty />", request, response);
}
}
private void showError(HttpServletRequest request,
HttpServletResponse response, String type, String error) {
try {
printResponse("<reply type='error' error_type='" + type
+ "' message='" + error + "' />", request, response);
} catch (IOException e) {
e.printStackTrace();
}
}
private void doValidateServlet(HttpServletRequest request,
HttpServletResponse response) {
ServletContext sc = request.getSession().getServletContext();
WamiConfig config = WamiConfig.getConfiguration(sc);
List<String> errors = new Vector<String>();
IValidator validator = config.createValidator(sc);
List<String> relayErrors = validator.validate(request);
errors.addAll(relayErrors);
response.setContentType("text/xml; charset=UTF-8");
Document doc = XmlUtils.newXMLDocument();
doc.appendChild(doc.createElement("root"));
for (String error : errors) {
Element errorE = doc.createElement("error");
errorE.setAttribute("message", error);
doc.getFirstChild().appendChild(errorE);
}
try {
PrintWriter out = response.getWriter();
String xmlString = XmlUtils.toXMLString(doc);
out.print(xmlString);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private boolean isValidateServletRequest(HttpServletRequest request) {
return "validate".equals(request.getParameter("operation"));
}
/**
* Prints the response returned by the relay. By default, it will be encoded
* as straight xml, however with ?rtype=js it can be returned as javascript
* wrapping the xml
*/
private void printResponse(String message, HttpServletRequest request,
HttpServletResponse response) throws IOException {
// note, you must set content type before getting the writer
response.setContentType("text/xml; charset=UTF-8");
PrintWriter out = response.getWriter();
out.print(message);
out.close();
}
private static WamiRelay newRelay(ServletContext sc)
throws InitializationException {
WamiConfig ac = WamiConfig.getConfiguration(sc);
String className = ac.getRelayClass();
WamiRelay relay = null;
if (className == null) {
throw new InitializationException("No relay class name specified.");
}
try {
System.out.println("Creating new WamiRelay subclass: " + className);
relay = (WamiRelay) Class.forName(className).newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return relay;
}
/**
* The relay is lazily created for each session.
*
* @param request
* @return
*/
public static WamiRelay getRelay(HttpServletRequest request) {
String wsessionid = request.getParameter("wsessionid");
return getRelay(request, wsessionid);
}
public static WamiRelay getRelay(HttpServletRequest request,
String wsessionid) {
if (wsessionid == null || "".equals(wsessionid)) {
wsessionid = request.getSession().getId();
}
HttpSession session = request.getSession();
WamiRelay relay = null;
RelayManager manager = RelayManager.getManager(session);
synchronized (manager) {
relay = manager.getRelay(wsessionid);
if (relay == null) {
System.out.println("Relay is null, attempting to initialize");
try {
System.out.println("INITIALIZING WAMI RELAY");
relay = initializeRelay(request, wsessionid);
} catch (InitializationException e) {
if (e.getRelay() != null) {
String message = "Error initializing relay! Removing the uninitialized relay!";
System.out.println(message);
manager.remove(e.getRelay());
}
e.printStackTrace();
return null;
}
}
}
return manager.getRelay(wsessionid);
}
public static String setRelay(HttpServletRequest request, WamiRelay relay,
String wsessionid) throws ReachedCapacityException {
if (wsessionid == null) {
wsessionid = request.getSession().getId();
}
System.out.println("Placing session WAMI session: " + wsessionid);
RelayManager manager = RelayManager.getManager(request.getSession());
manager.addRelay(relay, wsessionid);
return wsessionid;
}
public static WamiRelay initializeRelay(HttpServletRequest request,
String wsessionid) throws InitializationException {
System.out.println("**********************************************");
System.out.println("Initializing Relay " + wsessionid);
System.out.println("**********************************************");
HttpSession session = request.getSession();
WamiRelay relay;
relay = newRelay(session.getServletContext());
wsessionid = setRelay(request, relay, wsessionid);
relay.initialize(request, wsessionid);
return relay;
}
} | Java |
/** -*- Java -*-
*
* Copyright (c) 2008
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.sls.wami.applet.sound;
import java.io.IOException;
import java.nio.channels.ReadableByteChannel;
import javax.sound.sampled.AudioFormat;
public interface ReadableByteChannelCreator {
AudioFormat getFormat();
ReadableByteChannel[] createReadableByteChannels(int n, int channel) throws IOException;
} | Java |
/* -*- java -*-
*
* Copyright (c) 2008
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.sls.wami.applet.sound;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.ShortBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.LinkedList;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
/** Detects the start and end of speech.
*
**/
public class AutocorrSpeechDetector implements Runnable, SpeechDetector {
static final int IDLE = 0;
static final int INIT = 1;
static final int SPEECH = 2;
static final int AWAIT_ENABLE = 3;
static final int DISABLED = 4;
static final double invlog10 = 1.0/Math.log(10.0);
volatile boolean close = false;
volatile int state = IDLE;
int sampleRate = -1;
double startPaddingDuration = 1.2; // Padding added before first voicing
double endPaddingDuration = 1.2; // Padding added after final voicing
double preSpeechSilence = 0.0; // How much unnvoiced we need before speech
//double postSpeechSilence = .5; // How much unvoiced we need to end
double postSpeechSilence = 1.0; // How much unvoiced we need to end
double voiceDuration = .060; // How much voice before we call it voice
double silenceDuration = .080; // How much silence before we call it silence
double frameDuration = .020;
double windowDuration = .080;
double clipLevel = .6; // Samples below this level are clipped
double voicingThreshold = .70;
//double energyRange = 12.0; //was the original value
double energyRange = 5.0; // dbs above min energy reqd for consideration
int minPitch = 70; // Lowest pitch we must look at
int maxPitch = 250; // Highest pitch we must look at
int autocorrRes = 30; // Pitch resolution
AudioInputStream ais;
SampleBuffer sampleBuffer;
AudioFormat format;
SampleBuffer.Reader reader;
SampleBuffer.Reader levelReader;
ByteBuffer levelBytes;
short[] levelShorts;
volatile int maxLevel;
volatile boolean resetLevel;
LinkedList<Listener> listeners = new LinkedList<Listener>();
// Samples
int frameSamples; // Samples in a frame
int windowSamples; // Samples in a window
int startPaddingSamples; // Silence before voicing enables speech
int endPaddingSamples; // Silence after voicing to end speech
int preSpeechSamples; // Padding added before first voicing
int postSpeechSamples; // Padding added after final voicing
int voiceSamples; // Minimum to trigger voicing
int silenceSamples; // Minimum to trigger silence
double[] hamming;
double[] autocorr;
int[] autocorrIdx;
int autocorrLength;
short[] windowShorts; // Before Hamming
double[] window; // Windowed points
double windowSizeBias; // Energy adjustment for window size
ByteBuffer windowBytes; // Holds a window worth of samples
long nextUttStartSample; // uttStartSample for next enable()
long uttStartSample; // Start sample for current detection
long uttEndSample; // End sample for current detection
long transitionStartSample; // Where current possible transition started
long segmentStartSample; // Start of current voiced/unnvoiced segment
boolean inSpeech; // In a voiced region
boolean inTransition; // Possible transition between voiced/unvoiced
SampleBuffer.Limit limit = null;
long limitMax = 0; // Max limitpos seen
AudioSource sampleBufferWriter;
double maxval;
double maxeng;
double mineng;
public AutocorrSpeechDetector(){
uttStartSample = Long.MAX_VALUE;
levelShorts = new short[256];
levelBytes = ByteBuffer.allocate(levelShorts.length);
new Thread(this).start();
}
synchronized void releaseSampleBuffer(){
if (sampleBuffer != null){
sampleBuffer = null;
}
uttStartSample = Long.MAX_VALUE;
}
public synchronized void listen(AudioSource audioSource,
int channel,
boolean useSpeechDetector){
releaseSampleBuffer();
sampleBufferWriter = audioSource;
format = audioSource.getFormat();
sampleBuffer =
new SampleBuffer(format.getChannels(), format.getFrameSize());
int sampleRate = (int)format.getSampleRate();
reader = sampleBuffer.reader(channel);
reader.setBlocking(false);
levelReader = sampleBuffer.reader(channel);
levelReader.setBlocking(false);
maxLevel = 0;
resetLevel = false;
if (this.sampleRate != sampleRate){
this.sampleRate = sampleRate;
initialize();
}
maxval = Double.MIN_VALUE;
maxeng = Double.MIN_VALUE;
mineng = Double.MAX_VALUE;
nextUttStartSample = sampleForByte(reader.position());
uttEndSample = Long.MAX_VALUE;
windowBytes.order(format.isBigEndian() ? ByteOrder.BIG_ENDIAN
: ByteOrder.LITTLE_ENDIAN);
levelBytes.order(format.isBigEndian() ? ByteOrder.BIG_ENDIAN
: ByteOrder.LITTLE_ENDIAN);
limit = sampleBuffer.createLimit(0);
limitMax = 0;
enable(useSpeechDetector);
}
/** Listens on the specified channel of ais, optionally detecting
* speech.
*
**/
public void listen(AudioInputStream ais,
int channel,
boolean useSpeechDetector) {
listen(new AudioInputStreamSource(ais),
channel,
useSpeechDetector);
}
public synchronized void enable(boolean useSpeechDetector){
windowBytes.clear();
if (useSpeechDetector){
state = INIT;
if (sampleBuffer == null)
return;
sampleBuffer.moveLockPosition(uttStartSample, nextUttStartSample);
uttStartSample = nextUttStartSample;
uttEndSample = Long.MAX_VALUE;
segmentStartSample = uttStartSample;
inSpeech = true;
inTransition = false;
} else {
state = DISABLED;
sampleBuffer.moveLockPosition(uttStartSample, nextUttStartSample);
uttStartSample = nextUttStartSample;
limit.limit(Long.MAX_VALUE);
limitMax = Long.MAX_VALUE;
uttEndSample = Long.MAX_VALUE;
for(Listener listener : listeners){
listener.speechStart(0);
}
sampleBuffer.unlockPosition(uttStartSample);
}
notifyAll();
}
final int samples(double duration){
return (int)Math.round(duration*sampleRate);
}
final long byteForSample(long sample){
return (sample == Long.MAX_VALUE) ? Long.MAX_VALUE : sample*2;
}
final long sampleForByte(long i){
return (i == Long.MAX_VALUE) ? Long.MAX_VALUE : i/2;
}
void initialize(){
frameSamples = samples(frameDuration);
windowSamples = samples(windowDuration);
startPaddingSamples = samples(startPaddingDuration);
endPaddingSamples = samples(endPaddingDuration);
preSpeechSamples = samples(preSpeechSilence);
postSpeechSamples = samples(postSpeechSilence);
voiceSamples = (samples(voiceDuration)/frameSamples)*frameSamples;
silenceSamples = (samples(silenceDuration)/frameSamples)*frameSamples;
autocorrIdx = new int[autocorrRes];
autocorr = new double[autocorrRes];
double interval = Math.log(maxPitch/minPitch)/autocorrRes;
int lastIndex = 0;
autocorrLength = 0;
for(int i=0; i<autocorrRes; i++){
double pitch = Math.exp(interval*i)*minPitch;
int idx = (int)Math.round(sampleRate/pitch);
//System.out.format("Pitch: %3.0f off %3d%n", pitch, idx);
if (idx != lastIndex){
autocorrIdx[autocorrLength++] = idx;
lastIndex = idx;
}
}
windowBytes = ByteBuffer.allocate((int)byteForSample(windowSamples));
hamming = new double[windowSamples];
for(int i=0; i<windowSamples; i++){
hamming[i] = 0.54-0.46*Math.cos(2.0*Math.PI*i/(windowSamples-1));
}
windowShorts = new short[windowSamples];
window = new double[windowSamples*2];
windowSizeBias = -5.0*Math.log(windowSamples)*invlog10;
}
public void run(){
while(true){
synchronized(this){
if (close)
break;
waitForWork();
}
doWork();
}
}
/** Returns true if there is work to be done
*
**/
public synchronized boolean hasWork(){
if (state == IDLE)
return false;
// If there's data to read, there's something to do
if (sampleBufferWriter != null)
return true;
return false;
}
/** Waits for the detector to have work to do
*
**/
public synchronized void waitForWork(){
while(!hasWork()){
try {
wait();
} catch(InterruptedException e){
}
}
}
/** Wait for all processing to be completed
*
**/
public synchronized void waitDone(){
while(sampleBufferWriter != null && state!=IDLE){
try {
wait();
} catch(InterruptedException e){
}
}
}
void getSamples(){
if (sampleBuffer == null || sampleBufferWriter == null)
return;
// Add samples to the sample buffer
synchronized(this){
try {
int nWritten = sampleBuffer.write(sampleBufferWriter);
if (nWritten == -1){
sampleBufferWriter = null;
sampleBuffer.close();
notifyAll();
}
} catch(IOException e){
e.printStackTrace();
state = IDLE;
sampleBufferWriter = null;
notifyAll();
return;
}
}
int levelRemaining = levelReader.remaining();
while(levelRemaining > 0){
int max = resetLevel ? 0 : maxLevel;
levelBytes.clear();
int nread = levelReader.read(levelBytes);
if (nread <= 0)
break;
levelBytes.flip();
levelRemaining -= nread;
ShortBuffer shorts = levelBytes.asShortBuffer();
int n = Math.min(shorts.limit(), levelShorts.length);
shorts.get(levelShorts, 0, n);
for(int i=0; i<n; i++){
int s = levelShorts[i];
if (s<0)
s=-s;
if (s > max)
max = s;
}
maxLevel = max;
}
}
/** Reads the current peak, and resets to 0
*
* @return current peak, in range 0.0 to 1.0
**/
public double readPeakLevel(){
double result = maxLevel/32768.0;
resetLevel = true;
return result;
}
void processWindow(long frameOffsetSample, boolean readEof){
//
reader.position(byteForSample(frameOffsetSample+frameSamples));
// Window the samples
ShortBuffer shorts = windowBytes.asShortBuffer();
int n = Math.min(shorts.limit(), windowSamples);
if (readEof){
n = 0;
uttEndSample = frameOffsetSample;
}
shorts.get(windowShorts, 0, n);
double dcOffset = 0.0;
for(int i=0; i<n; i++){
dcOffset+=window[i];
}
dcOffset = dcOffset/n;
for(int i=0; i<n; i++){
window[i] = hamming[i]*(windowShorts[i]-dcOffset);
}
for(int i=n; i<windowSamples;i++){
window[i] = 0.0;
}
/*
// Preemphasis
for(int i=n-1; i>1; i--){
window[i]-=.95*window[i-1];
}
*/
// Determine maximum value and center clip
double lmaxval = 0;
for(int i=0; i<windowSamples; i++){
double val = window[i];
lmaxval = Math.max(lmaxval, Math.abs(val));
}
maxval = Math.max(lmaxval,maxval);
double pclip = maxval*clipLevel;
double nclip = -pclip;
for(int i=0; i<windowSamples; i++){
double val = window[i];
if (-nclip < val && val < pclip)
window[i] = 0.0;
}
double a0 = 0.0;
for(int i=0; i<windowSamples; i++){
double val = window[i];
a0+=val*val;
}
// Replicate the samples so we don't need to worry about
// wrap-around
for(int i=0; i<windowSamples; i++){
window[i+windowSamples] = window[i];
}
int ires = 0;
for(int idx=0; idx<autocorrLength; idx++){
double val = 0.0;
int j = autocorrIdx[idx];
for(int i=0; i<windowSamples; i++){
val += window[i]*window[j++];
}
autocorr[ires++] = val;
}
double energy = windowSizeBias+5.0*(Math.log(a0)*invlog10);
double periodicity = 0.0;
//long pitch = 0;
boolean speech = false;
if (a0 > 0.0){
// Don't let initial zeroes cause a problem
maxeng = Math.max(energy,maxeng);
mineng = Math.min(energy,mineng);
double max = Double.MIN_VALUE;
//int maxi = 0;
for(int i=0; i<autocorrLength; i++){
if (autocorr[i] > max){
//maxi = i;
max = autocorr[i];
}
}
periodicity = max/a0;
//int maxk = autocorrIdx[maxi];
//pitch = Math.round(sampleRate/(double)maxk);
speech =
periodicity > voicingThreshold
&& energy-mineng > energyRange;
//System.out.println("periodicity: " + periodicity + "/\t" + voicingThreshold);
//System.out.println("energy: " + (energy-mineng) + "/\t" + energyRange);
//System.out.println("speech: " + speech + "\n");
}
boolean transition = false;
long lastDuration = 0;
long duration = 0;
if (inSpeech != speech){
if (!inTransition){
transitionStartSample = frameOffsetSample;
inTransition = true;
}
long transitionSamples = frameOffsetSample-transitionStartSample;
if ((speech && transitionSamples > voiceSamples)
|| (!speech && transitionSamples > silenceSamples)){
transition = true;
if (!speech)
nextUttStartSample = transitionStartSample;
lastDuration = transitionStartSample-segmentStartSample;
segmentStartSample = transitionStartSample;
inTransition = false;
inSpeech = speech;
}
} else {
inTransition = false;
}
// Last sample we can safely say is in this voiced/unvoiced
// segment. Anything beyond this could go either way
long segmentEndSample = inTransition?
transitionStartSample : frameOffsetSample;
// How many sample we know are in this segment
duration = segmentEndSample-segmentStartSample;
/*
double period = 1.0/sampleRate;
System.out.format
("%7d %3.3f p=%3d M=%5.0f [%3.2f %3.2f] e=%3.2f per=%3.0f%% d=%1.3f t=%1.3f %b %b %b%n",
frameOffsetSample,
period*frameOffsetSample,
pitch,
maxval,
mineng,
maxeng,
energy-mineng,
periodicity*100,
period*duration,
period*(frameOffsetSample-transitionStartSample),
speech,
inTransition,
inSpeech
);
*/
boolean eof = reader.eof();
switch(state){
case INIT:{
if (eof){
for(Listener listener : listeners){
listener.noSpeech(uttEndSample);
}
synchronized(this){
state = IDLE;
notifyAll();
}
break;
}
/* Wait for sp_padding_duration of silence followed by
* speech
*/
long sample =
Math.max(frameOffsetSample-startPaddingSamples,
uttStartSample);
if (speech && transition && lastDuration > preSpeechSamples){
state = SPEECH;
limit = sampleBuffer.createLimit(uttStartSample);
limitMax = sample;
for(Listener listener : listeners){
listener.speechStart(uttStartSample);
}
sampleBuffer.unlockPosition(uttStartSample);
} else {
if (sample >= uttStartSample){
sampleBuffer.moveLockPosition(uttStartSample ,sample);
uttStartSample = sample;
}
}
break;
}
case SPEECH:{
if (eof || (!inSpeech
&& !transition
&& !inTransition
&& duration > postSpeechSamples)){
// All done
long endSample =
Math.min(frameOffsetSample+windowSamples+endPaddingSamples,
uttEndSample);
limitMax = Math.max(limitMax, endSample);
limit.eofPosition(limitMax);
limit.limit(limitMax);
long remaining = limit.byteLimit()-reader.position();
while(hasWork() && reader.remaining() < remaining){
getSamples();
}
state = AWAIT_ENABLE;
for(Listener listener : listeners){
listener.speechEnd(endSample);
}
if (state == AWAIT_ENABLE){
synchronized(this){
state = IDLE;
notifyAll();
}
}
} else {
limitMax =
Math.max(limitMax,
Math.max(segmentEndSample-postSpeechSamples,
segmentStartSample));
limit.limit(limitMax);
}
break;
}
case IDLE:
break;
}
}
void doWork(){
getSamples();
if (state == DISABLED)
return;
while(true){
if (!hasWork())
return;
// Why do we get this from the reader??
long frameOffsetSample = sampleForByte(reader.position());
int nread = reader.read(windowBytes);
if (nread >= 0 && windowBytes.hasRemaining()){
// Wait for more data
return;
}
windowBytes.flip();
processWindow(frameOffsetSample, nread < 0);
windowBytes.clear();
}
}
// Reads all channels
public synchronized AudioInputStream createReader(){
return new AudioInputStream
(Channels.newInputStream(sampleBuffer.reader(limit)),
format,
AudioSystem.NOT_SPECIFIED);
}
// Reads a single channel
public synchronized AudioInputStream createReader(int channel){
return new AudioInputStream
(Channels.newInputStream(sampleBuffer.reader(limit, channel)),
new AudioFormat
(AudioFormat.Encoding.PCM_SIGNED,
format.getSampleRate(),
16,
1,
2*format.getFrameSize(),
format.getFrameRate(),
format.isBigEndian()),
AudioSystem.NOT_SPECIFIED);
}
public synchronized ReadableByteChannel createReadableByteChannel(){
return sampleBuffer.reader(limit);
}
public synchronized ReadableByteChannel
createReadableByteChannel(int channel){
return sampleBuffer.reader(limit, channel);
}
public synchronized ReadableByteChannel[]
createReadableByteChannels(int n, int channel){
ReadableByteChannel[] bcs = new ReadableByteChannel[n];
// Grab the data before we move past it
for (int i = 0; i < n; i++) {
bcs[i] = sampleBuffer.reader(limit, channel);
}
return bcs;
}
public AudioFormat getFormat(){
return format;
}
public synchronized void disable(){
state = IDLE;
reader.close();
if (sampleBufferWriter != null){
sampleBufferWriter.close();
sampleBufferWriter = null;
}
notifyAll();
}
public void addListener(Listener listener){
listeners.add(listener);
}
public void removeListener(Listener listener){
listeners.remove(listener);
}
public void setParameter(String parameter, double value) {
if(parameter.equals("energyRange")) {
energyRange = value;
} else if(parameter.equals("voicingThreshold")) {
voicingThreshold = value;
}
}
public double getParameter(String parameter) {
if(parameter.equals("energyRange")) {
return energyRange;
} else if(parameter.equals("voicingThreshold")) {
return voicingThreshold;
}
return -1;
}
public String[] getParameterNames() {
String[] params = { "energyRange", "voicingThreshold" };
return params;
}
}
| Java |
/* -*- Java -*-
*
* Copyright (c) 2008
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.sls.wami.applet.sound;
import javax.sound.sampled.*;
public class Encodings {
public static final
AudioFormat.Encoding AMR = new AudioFormat.Encoding("AMR");
}
| Java |
/* -*- java -*-
*
* Copyright (c) 2008
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.sls.wami.applet.sound;
import java.nio.channels.ReadableByteChannel;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
/** Generic speech detector API
**/
public interface SpeechDetector extends ReadableByteChannelCreator {
interface Listener {
/** Indicates that speech has been detected somewhere after
* the specified position.
*
* @param offsetSample The padded position, where speech has
* been detected, in samples
*
**/
void speechStart(long offsetSample);
/** Indicates the end of detected speech.
*
* @param offsetSample The last byte of detected speech. Note
* that if the detector is reenabled, this offset may be after
* the next speechStart position.
*
**/
void speechEnd(long offsetSample);
/** No speech was detected before the end of file marker was
* read by the detector.
*
* @param offsetSample The position of the end of file mark.
*
**/
void noSpeech(long offsetSample);
}
interface AudioSource extends SampleBuffer.DataReader {
/**
* @return The audio format of the data
*/
AudioFormat getFormat();
}
/** Listens for speech
*
* @param audioSource Audio data
*
* @param channel Which channel to use
*
* @param useSpeechDetector Whether or not the speech detector
* should be used.
*
**/
void listen(AudioSource audioSource,
int channel,
boolean useSpeechDetector);
/** Start reading samples looking for speech, calling listeners.
*
* @param useSpeechDetector If set, speech detection is used.
* Otherwise, all samples are passed through to reader.
**/
void enable(boolean useSpeechDetector);
/** Waits for the detector to finish processing all samples
*
**/
void waitDone();
/** Stop reading samples
*
**/
void disable();
/** Returns an AudioInputStream that reads the utterance
*
**/
AudioInputStream createReader();
/** Returns an AudioInputStream that reads a channel of the utterance
*
**/
AudioInputStream createReader(int channel);
/** Returns a ReadableByteChannel that reads the utterance
*
**/
ReadableByteChannel createReadableByteChannel();
/** Returns a ReadableByteChannel that reads a channel of the utterance
*
**/
ReadableByteChannel createReadableByteChannel(int channel);
/** Returns a ReadableByteChannel[] that reads a channel of the utterance
*
**/
ReadableByteChannel[] createReadableByteChannels(int n, int channel);
/** Returns the audio format
*
**/
AudioFormat getFormat();
/** Add a listener for speech events
*
* @param listener The listener to add
**/
void addListener(Listener listener);
/** Remove a listener for speech events
*
* @param listener The listener to remove
**/
void removeListener(Listener listener);
/** Read the peak level and reset to 0
*
* @return The peak level
**/
double readPeakLevel();
/**
* Get the names of parameters which can be set for this detector
*/
public String[] getParameterNames();
/**
* An interface to set parameters particular to different detectors
* @param parameter
* @param value
*/
public void setParameter(String parameter, double value);
/**
* Gets the value of a named parameter, as a string
*/
public double getParameter(String parameter);
}
| Java |
/** -*- Java -*-
*
* Copyright (c) 2008
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.sls.wami.applet.sound;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.ShortBuffer;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.sound.sampled.AudioFormat;
/**
* Sends audio data over TCP in an RTP-like format
*
* @author cyphers
*
*/
public class RtpAudioSender implements Runnable {
ByteBuffer outByteBuffer = ByteBuffer.allocate(1500);
AudioFormat dformat;
boolean littleEndian = false;
ByteBuffer inByteBuffer;
ShortBuffer inShortBuffer;
ShortBuffer outShortBuffer;
InetSocketAddress addr;
SocketChannel destinationSC = null;
int cookie;
ReadableByteChannel bc;
File file;
ByteBuffer intByteBuffer = ByteBuffer.allocate(4);
ByteBuffer headerByteBuffer;
int sequenceNumber = 0;
Charset charset = Charset.forName("UTF-8");
boolean reclog = false;
RtpAudioSender(AudioFormat dformat, ReadableByteChannel bc, File file,
InetSocketAddress addr, int cookie, boolean reclog) {
this.dformat = dformat;
this.bc = bc;
this.addr = addr;
this.cookie = cookie;
this.file = file;
this.reclog = reclog;
headerByteBuffer = ByteBuffer.allocate(12);
headerByteBuffer.order(ByteOrder.BIG_ENDIAN);
intByteBuffer.order(ByteOrder.BIG_ENDIAN);
}
void sendData(SocketChannel sc, int pt, ByteBuffer dataByteBuffer)
throws IOException {
headerByteBuffer.clear();
headerByteBuffer.putInt(2 << 30 | pt << 16 | sequenceNumber);
sequenceNumber = (sequenceNumber+1)&0xFFFF;
headerByteBuffer.putInt((int) (System.currentTimeMillis() & 0xFFFFFFFF));
headerByteBuffer.putInt(1);
headerByteBuffer.flip();
intByteBuffer.clear();
int nbytes = headerByteBuffer.limit() + dataByteBuffer.limit();
intByteBuffer.putInt(nbytes);
intByteBuffer.flip();
ByteBuffer[] bbs = new ByteBuffer[] { intByteBuffer, headerByteBuffer, dataByteBuffer };
sc.write(bbs);
}
void sendData(SocketChannel sc, AudioFormat audioFormat,
ByteBuffer dataByteBuffer) throws IOException {
int pt = Rtp.RTP_PT_PCMU;
AudioFormat.Encoding encoding = audioFormat.getEncoding();
if (encoding == AudioFormat.Encoding.ULAW)
pt = Rtp.RTP_PT_PCMU;
else if (encoding == AudioFormat.Encoding.PCM_SIGNED) {
pt = Rtp.RTP_PT_L16_8K;
} else if (encoding == Encodings.AMR) {
pt = Rtp.RTP_PT_AMR;
}
sendData(sc, pt, dataByteBuffer);
}
void sendText(SocketChannel sc, String text) throws IOException {
headerByteBuffer.clear();
ByteBuffer bytes = charset.encode(text);
sendData(sc, Rtp.RTP_PT_TXT, bytes);
}
public void run() {
try {
destinationSC = SocketChannel.open(addr);
// Send the cookie
ByteBuffer bb = ByteBuffer.allocate(4);
bb.order(ByteOrder.BIG_ENDIAN);
bb.putInt(cookie);
bb.flip();
destinationSC.write(bb);
if (reclog && file != null) {
sendText(destinationSC, "logfile:" + file.toString());
}
outByteBuffer.order(ByteOrder.BIG_ENDIAN);
if (dformat.getFrameSize() == 2 && !dformat.isBigEndian()) {
littleEndian = true;
inByteBuffer = ByteBuffer.allocate(outByteBuffer.capacity());
inByteBuffer.order(ByteOrder.LITTLE_ENDIAN);
inShortBuffer = inByteBuffer.asShortBuffer();
outShortBuffer = outByteBuffer.asShortBuffer();
} else {
inByteBuffer = outByteBuffer;
}
while (true) {
inByteBuffer.clear();
int n = bc.read(inByteBuffer);
if (n < 0)
break;
if (littleEndian) {
inShortBuffer.position(0);
inShortBuffer.limit(inByteBuffer.position() / 2);
outShortBuffer.clear();
outShortBuffer.put(inShortBuffer);
outByteBuffer.limit(outShortBuffer.position() * 2);
outByteBuffer.position(0);
} else {
outByteBuffer.flip();
}
sendData(destinationSC, dformat, outByteBuffer);
}
destinationSC.close();
destinationSC = null;
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Create senders to destinations in waveURL for data in detector
*
* @param waveURL
* Contains the destinations for the audio data
* @param file
* Log file. First destination will log if provided.
* @param detector
* The speech detector with the data
* @param channel
* The channel of the data to send
* @param reclog
* Whether the recognizer should do the logging
* @return The senders
* @throws IOException
*/
public static RtpAudioSender[] createSenders(String waveURL, File file,
ReadableByteChannelCreator channelCreator, int channel, boolean reclog)
throws IOException {
String protocolHeader = "galaxy_rtp://";
if (!waveURL.startsWith(protocolHeader))
return new RtpAudioSender[0];
AudioFormat dformat = channelCreator.getFormat();
String[] urls = waveURL.substring(protocolHeader.length()).split("//");
File sfile = file;
ReadableByteChannel[] bcs = channelCreator.createReadableByteChannels(
urls.length, channel);
RtpAudioSender[] senders = new RtpAudioSender[urls.length];
Matcher audioDestinationMatcher = Pattern.compile(
"^([^:]*):(\\d*)/([0-9a-fA-F]*)$").matcher("");
for (int i = 0; i < urls.length; i++) {
audioDestinationMatcher.reset(urls[i]);
if (!audioDestinationMatcher.matches()) {
bcs[i].close();
continue;
}
String destinationHost = audioDestinationMatcher.group(1);
int destinationPort = Integer.parseInt(audioDestinationMatcher
.group(2));
int cookie = Integer.parseInt(audioDestinationMatcher.group(3), 16);
InetSocketAddress addr = new InetSocketAddress(destinationHost,
destinationPort);
RtpAudioSender sender = new RtpAudioSender(dformat, bcs[i], sfile,
addr, cookie, reclog);
sfile = null;
senders[i] = sender;
}
return senders;
}
} | Java |
/* -*- Java -*-
*
* Copyright (c) 2008
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// FIFO implemented with a circular buffer
package edu.mit.csail.sls.wami.applet.sound;
public class ByteFifo {
private byte[] rep;
private int p = 0;
private int size = 0;
public ByteFifo() {
this.rep = new byte[8];
}
public ByteFifo(int capacity) {
this.rep = new byte[capacity];
}
public void push(byte x) {
grow(size + 1);
++size;
rep[p++] = x;
if (p == rep.length)
p = 0;
}
public void push(byte[] x) {
push(x, 0, x.length);
}
public void push(byte[] x, int offset, int length) {
grow(size + length);
size += length;
if (p + length > rep.length) {
int n = rep.length - p;
System.arraycopy(x, offset, rep, p, n);
System.arraycopy(x, offset + n, rep, 0, length - n);
} else {
System.arraycopy(x, offset, rep, p, length);
}
p += length;
if (p >= rep.length)
p -= rep.length;
}
public byte pop() {
if (size <= 0)
throw new Error("empty");
int q = p - size;
if (q < 0)
q += rep.length;
byte x = rep[q];
--size;
return x;
}
public void pop(byte[] x) {
pop(x, 0, x.length);
}
public void pop(byte[] x, int offset, int length) {
if (length <= 0)
return;
int q = p - size;
if (q < 0) {
if (length < -q) {
System.arraycopy(rep, rep.length + q, x, offset, length);
} else {
System.arraycopy(rep, rep.length + q, x, offset, -q);
System.arraycopy(rep, 0, x, offset - q, length + q);
}
} else {
System.arraycopy(rep, q, x, offset, length);
}
size -= length;
}
public int size() {
return this.size;
}
public int capacity(){
return rep.length;
}
public int bytesRemaining(){
return rep.length-this.size;
}
private void grow(int n) {
int capacity = rep.length;
while (capacity < n) {
capacity *= 2;
}
if (capacity > rep.length) {
//System.err.format("Capacity: %d/%d%n", n, capacity);
byte[] newRep = new byte[capacity];
int q = p - size;
if (q < 0) {
q += rep.length;
System.arraycopy(rep, q, newRep, 0, rep.length - q);
System.arraycopy(rep, 0, newRep, rep.length - q, p);
} else {
System.arraycopy(rep, q, newRep, 0, size);
}
p = size;
rep = newRep;
}
}
}
| Java |
/* -*- Java -*-
*
* Copyright (c) 2008
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.sls.wami.applet.sound;
public class Rtp {
// Packet types
/**
* Mulaw
*/
public static final int RTP_PT_PCMU = 0;
/**
* 16-bit signed linear at 8KHz
*/
public static final int RTP_PT_L16_8K = 96;
/**
* utf-8 text
*/
public static final int RTP_PT_TXT = 97;
/**
* AMR
*/
public static final int RTP_PT_AMR = 98;
}
| Java |
/* -*- java -*-
*
* Copyright (c) 2008
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.sls.wami.applet.sound;
import java.io.IOException;
import javax.sound.sampled.*;
/** Makes an AudioSource from an AudioInputStream.
*
**/
public class AudioInputStreamSource implements SpeechDetector.AudioSource {
AudioInputStream ais;
public AudioInputStreamSource(AudioInputStream aisin){
AudioFormat aisf = aisin.getFormat();
ais =
(aisf.getEncoding() == AudioFormat.Encoding.PCM_SIGNED
&& aisf.getSampleSizeInBits() == 16) ?
aisin :
AudioSystem
.getAudioInputStream(new AudioFormat
(AudioFormat.Encoding.PCM_SIGNED,
aisf.getSampleRate(),
16,
aisf.getChannels(),
2*aisf.getFrameSize()*aisf.getChannels(),
aisf.getFrameRate(),
aisf.isBigEndian()),
aisin);
}
public int read(byte[] dest, int off, int len) throws IOException {
return ais.read(dest, off, len);
}
public void close(){
try {
ais.close();
} catch(IOException e){
}
}
public AudioFormat getFormat(){
return ais.getFormat();
}
}
| Java |
/* -*- Java -*-
*
* Copyright (c) 2008
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.sls.wami.applet.sound;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.Line;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.Mixer;
import javax.sound.sampled.SourceDataLine;
/**
* Controls playing of audio
*
* Unless otherwise noted, methods are not thread-safe.
*
*/
class AudioPlayer implements Player {
protected volatile SourceDataLine line = null;
protected volatile boolean enabled = true; // Used for aborting play
protected volatile boolean playing = false; // Set when in play loop
protected int position = 0; // Number of bytes sent to line
protected volatile int startPosition = 0; // Start of segment
protected byte[] data = new byte[1024];
Converter currentConverter = null;
protected Mixer.Info preferredMixerInfo = null;
protected class Converter {
AudioFormat currentAudioFormat;
AudioFormat convertFormat;
AudioFormat lineFormat;
Converter(AudioFormat currentAudioFormat, AudioFormat convertFormat,
AudioFormat lineFormat) {
this.currentAudioFormat = currentAudioFormat;
this.convertFormat = convertFormat;
this.lineFormat = lineFormat;
}
boolean matches(AudioFormat desiredAudioFormat) {
return currentAudioFormat.matches(desiredAudioFormat);
}
int doSamples(AudioInputStream ais) throws IOException {
return ais.read(data);
}
}
// Converts 1-channel bytes to 2-channel bytes
protected class Converter1 extends Converter {
byte[] indata = new byte[data.length / 2];
Converter1(AudioFormat currentAudioFormat, AudioFormat convertFormat,
AudioFormat lineFormat) {
super(currentAudioFormat, convertFormat, lineFormat);
}
@Override
public int doSamples(AudioInputStream ais) throws IOException {
int n = ais.read(indata);
if (n < 0)
return n;
int j = 0;
for (int i = 0; i < n; i++) {
byte b = indata[i];
data[j++] = b;
data[j++] = b;
}
return n * 2;
}
}
// Converts 1-channel shorts to 2-channel shorts
protected class Converter2 extends Converter {
byte[] indata = new byte[data.length / 2];
Converter2(AudioFormat currentAudioFormat, AudioFormat convertFormat,
AudioFormat lineFormat) {
super(currentAudioFormat, convertFormat, lineFormat);
}
@Override
public int doSamples(AudioInputStream ais) throws IOException {
int n = ais.read(indata);
if (n < 0)
return n;
int j = 0;
for (int i = 0; i < n;) {
byte b0 = indata[i++];
byte b1 = indata[i++];
data[j++] = b0;
data[j++] = b1;
data[j++] = b0;
data[j++] = b1;
}
return n * 2;
}
}
LinkedList<Listener> listeners = new LinkedList<Listener>();
/**
* Add an event listener
*
* @param l
* The listener
*
*/
public void addListener(Listener l) {
listeners.add(l);
}
/**
* Remove an event listener
*
* @param l
* The listener
*
*/
public void removeListener(Listener l) {
listeners.remove(l);
}
void playingHasStarted() {
for (Listener listener : listeners) {
listener.playingHasStarted();
}
}
void playingHasEnded() {
for (Listener listener : listeners) {
listener.playingHasEnded();
}
}
/**
* Find the best conversion for a desired audio format
*
*/
Converter getConverter(AudioFormat desiredAudioFormat)
throws LineUnavailableException {
if (currentConverter != null
&& currentConverter.matches(desiredAudioFormat))
return currentConverter;
AudioFormat minFormat = null;
AudioFormatComparator comp = new AudioFormatComparator(
desiredAudioFormat) {
@Override
public int conversionCompare(AudioFormat f1, AudioFormat f2) {
boolean c1 = AudioSystem.isConversionSupported(f1,
desiredAudioFormat);
boolean c2 = AudioSystem.isConversionSupported(f2,
desiredAudioFormat);
if (c1) {
if (!c2) {
return -1;
}
} else if (!c2) {
return 1;
}
return 0;
}
};
// Hunt for the line that supports the format best
ArrayList<Mixer.Info> minfoList = new ArrayList<Mixer.Info>(Arrays
.asList(AudioSystem.getMixerInfo()));
if (preferredMixerInfo != null) {
minfoList.remove(preferredMixerInfo);
minfoList.add(0, preferredMixerInfo);
}
Mixer.Info[] minfo = minfoList
.toArray(new Mixer.Info[minfoList.size()]);
for (int i = 0; i < minfo.length; i++) {
Mixer mixer = AudioSystem.getMixer(minfo[i]);
Line.Info[] linfo = mixer.getSourceLineInfo();
for (int j = 0; j < linfo.length; j++) {
if (!(linfo[j] instanceof DataLine.Info)) {
// Port info doesn't tell us anything about formats
continue;
}
DataLine.Info dinfo = (DataLine.Info) linfo[j];
AudioFormat[] formats = dinfo.getFormats();
for (int k = 0; k < formats.length; k++) {
AudioFormat f = formats[k];
if (comp.compare(f, minFormat) == -1) {
minFormat = f;
}
}
}
}
AudioFormat lineFormat = minFormat;
if (lineFormat.getSampleRate() == AudioSystem.NOT_SPECIFIED) {
// A java sound feature: If all sample rates are supported,
// then AudioSystem.NOT_SPECIFIED may be returned
lineFormat = new AudioFormat(lineFormat.getEncoding(),
// +DSC
// Pretend we only have 16KHz
// 16000,
// -DSC
desiredAudioFormat.getSampleRate(), lineFormat
.getSampleSizeInBits(), lineFormat.getChannels(),
lineFormat.getFrameSize(), desiredAudioFormat
.getFrameRate(), lineFormat.isBigEndian());
}
AudioFormat clf = AudioFormatComparator.channelFormat(lineFormat,
desiredAudioFormat.getChannels());
AudioFormat convertFormat = AudioSystem.isConversionSupported(clf,
desiredAudioFormat) ? clf : desiredAudioFormat;
if (lineFormat.getChannels() == 2
&& desiredAudioFormat.getChannels() == 1) {
switch (convertFormat.getFrameSize()) {
case 1:
return new Converter1(desiredAudioFormat, convertFormat,
lineFormat);
case 2:
return new Converter2(desiredAudioFormat, convertFormat,
lineFormat);
default:
throw new LineUnavailableException("Cannot play "
+ desiredAudioFormat + " on audio device");
}
} else {
return new Converter(desiredAudioFormat, convertFormat, lineFormat);
}
}
/**
* Wait for playing to complete, and then close the line.
*
*/
public synchronized void closeLine() {
if (line == null)
return;
double padding = .3 * line.getFormat().getFrameRate()
* line.getFormat().getFrameSize();
int nbuffers = (int) ((padding + data.length - 1) / data.length);
for (int i = 0; i < nbuffers; i++) {
Arrays.fill(data, (byte) 0);
line.write(data, 0, data.length);
}
line.drain();
synchronized (this) {
line.close();
line = null;
}
}
/**
* Play the stream. This is the same as play(stream, true, true).
*
* @param stream
* The stream to play
*
*/
public void play(AudioInputStream stream) throws LineUnavailableException {
play(stream, true, true);
}
/**
* Play the stream
*
* @param stream
* The stream to play
*
* @param setStart
* If true, getFramePosition() will consider the start of
* this stream as frame 0, and playingHasStarted() will
* be called.
*
* @param last
* If true, playingHasEnded() will be called when playing
* stops.
*
*/
public void play(AudioInputStream stream, boolean setStart, boolean last)
throws LineUnavailableException {
AudioFormat desiredAudioFormat = stream.getFormat();
// Start by getting the right encoding
if (desiredAudioFormat.getEncoding() != AudioFormat.Encoding.PCM_SIGNED) {
stream = AudioSystem.getAudioInputStream(
AudioFormat.Encoding.PCM_SIGNED, stream);
desiredAudioFormat = stream.getFormat();
}
currentConverter = getConverter(desiredAudioFormat);
// Convert stream
AudioInputStream ais = desiredAudioFormat
.matches(currentConverter.convertFormat) ? stream : AudioSystem
.getAudioInputStream(currentConverter.convertFormat, stream);
// System.err.println("Request for "+desiredAudioFormat);
// System.err.println("Converted to "+ais.getFormat());
// System.err.println("Line selected "+currentConverter.lineFormat);
if (ais.getFormat().getSampleRate() != currentConverter.lineFormat
.getSampleRate()) {
// TBD: Enhance the protocol so we can tell Galaxy what
// sampling rates can be used for synthesis. For now, just
// die informatively
if (2 * ais.getFormat().getSampleRate() == currentConverter.lineFormat
.getSampleRate()) {
play(new UpSample2(ais), setStart, last);
return;
}
System.out.println("Here we go...");
throw new LineUnavailableException(
"Audio device does not support a sampling rate of "
+ ais.getFormat().getSampleRate());
}
if (line != null) {
if (!line.getFormat().matches(currentConverter.lineFormat)) {
closeLine();
}
}
// Open line
if (line == null) {
DataLine.Info info = new DataLine.Info(SourceDataLine.class,
currentConverter.lineFormat);
synchronized (this) {
try {
System.out.println("(player) preferred mixer is: "
+ preferredMixerInfo);
if (preferredMixerInfo != null) {
Mixer mixer = AudioSystem.getMixer(preferredMixerInfo);
try {
line = (SourceDataLine) mixer.getLine(info);
} catch (IllegalArgumentException e) {
// line not supported in this mixer, so try a
// different one
line = (SourceDataLine) AudioSystem.getLine(info);
}
} else {
line = (SourceDataLine) AudioSystem.getLine(info);
}
position = 0;
line.open(currentConverter.lineFormat);
line.start();
} catch (LineUnavailableException e) {
line = null;
throw e;
}
}
}
if (setStart) {
startPosition = position;
}
try {
synchronized (this) {
playing = true;
notifyAll();
}
if (setStart)
playingHasStarted();
while (true) {
synchronized (this) {
if (ais == null || line == null || !enabled)
break;
}
int n = -1;
try {
n = currentConverter.doSamples(ais);
} catch (IOException e) {
break;
}
if (n < 0) {
try {
ais.close();
} catch (IOException e) {
}
synchronized (this) {
notifyAll();
}
break;
} else {
position += n;
line.write(data, 0, n);
}
}
} finally {
synchronized (this) {
playing = false;
notifyAll();
}
if (last) {
closeLine();
playingHasEnded();
}
}
}
/**
* Returns true if in the play loop
*
*/
public synchronized boolean isPlaying() {
return playing;
}
/**
* Break out of playing
*
* Can be called from any thread
*/
public synchronized void stopPlaying() {
if (!playing)
return;
enabled = false;
while (playing) {
try {
wait();
} catch (InterruptedException e) {
}
}
enabled = true;
}
/**
* Return the frame position in the currently playing stream.
*
* Can be called from any thread
*
*/
public synchronized int getFramePosition() {
return line == null ? 0 : line.getFramePosition() - startPosition;
}
/**
* Returns the closest supported sample rate
*
*/
public int supportedSampleRate(int desiredSampleRate)
throws LineUnavailableException {
AudioFormat format = new AudioFormat((float) desiredSampleRate, 16, 2,
true, true);
Converter converter = getConverter(format);
return (int) converter.lineFormat.getSampleRate();
}
/**
* Set the preferred mixer to use to playback (note, not thread safe at
* the moment)
*/
public void setPreferredMixer(Mixer.Info mInfo) {
preferredMixerInfo = mInfo;
}
public void setPreferredMixer(String name){
for(Mixer.Info mi : AudioSystem.getMixerInfo()){
if (mi.getName().equals(name)){
setPreferredMixer(mi);
return;
}
}
}
public Mixer.Info getPreferredMixer() {
return preferredMixerInfo;
}
}
| Java |
/* -*- Java -*-
*
* Copyright (c) 2008
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.sls.wami.applet.sound;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.ShortBuffer;
import java.util.Map;
import java.util.TreeMap;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import edu.mit.csail.sls.wami.applet.sound.ByteFifo;
public class ResampleInputStream extends InputStream {
private static final int APPROXIMATION = 100;
private static final int FILTER_SCALE = 25;
private AudioFormat targetFormat;
private AudioFormat sourceFormat;
private AudioInputStream sourceStream;
private int L = 0; // interpolation factor
private int M = 0; // decimation factor
private float h[] = null; // resampling filter
private short z[] = null; // delay line
private int pZ = 0;
private int phase = 0;
private ByteFifo sourceByteFifo;
private ByteFifo targetByteFifo;
// For source byte to short conversion. Byte order set in initialize().
//
private byte[] sourceBytes = new byte[1024];
private ByteBuffer sourceByteBuffer = ByteBuffer.wrap(sourceBytes);
private ShortBuffer sourceShortBuffer = null;
// For target short to byte conversion. Byte order set in initialize().
//
private byte[] targetBytes = new byte[2];
private ByteBuffer targetByteBuffer = ByteBuffer.wrap(targetBytes);
private ShortBuffer targetShortBuffer = null;
// For caching interpolation filter.
private static Map<Integer,float[]> filterCache = new TreeMap<Integer,float[]>();
int gcd(int x, int y){
int r;
while((r=x%y)>0){
x = y;
y = r;
}
return y;
}
public ResampleInputStream(AudioFormat targetFormat,
AudioInputStream sourceStream) {
this.targetFormat = targetFormat;
this.sourceFormat = sourceStream.getFormat();
this.sourceStream = sourceStream;
int targetRate = Math.round(targetFormat.getSampleRate()/APPROXIMATION)*APPROXIMATION;
int sourceRate = Math.round(sourceFormat.getSampleRate()/APPROXIMATION)*APPROXIMATION;
int gcd = gcd(targetRate, sourceRate);
this.L = targetRate / gcd;
this.M = sourceRate / gcd;
sourceByteFifo = new ByteFifo(sourceRate/5);
targetByteFifo = new ByteFifo(targetRate/5);
initialize();
}
private void initialize() {
int f = Math.max(L, M);
int n = FILTER_SCALE*f;
int mod = n % L;
if (mod != 0)
n += L - mod;
z = new short[n / L];
boolean cached = true;
Integer cacheKey = new Integer(f);
h = filterCache.get(cacheKey);
if (h == null) {
h = InterpolationFilter.design(f, n, InterpolationFilter.HAMMING);
filterCache.put(cacheKey, h);
cached = false;
}
System.err.println("ResampleInputStream:" +
" L=" + L +
" M=" + M +
" taps=" + h.length +
" perPhase=" + z.length +
" cached=" + cached);
// Cause the delay buffer z to be fully loaded before first output.
//
phase = z.length * L;
// Finish initializing byte-swapping buffers now that we know the byte orders.
//
sourceByteBuffer.order(byteOrder(sourceFormat));
sourceShortBuffer = sourceByteBuffer.asShortBuffer();
targetByteBuffer.order(byteOrder(targetFormat));
targetShortBuffer = targetByteBuffer.asShortBuffer();
}
private ByteOrder byteOrder(AudioFormat format) {
return format.isBigEndian() ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN;
}
@Override
public int available() throws IOException {
convert(false);
return targetByteFifo.size();
}
@Override
public int read() throws IOException {
throw new Error("not supported");
}
// This must read at least one byte, blocking until something is available
@Override
public int read(byte[] b, int offset, int length) throws IOException {
if (targetByteFifo.size() == 0){
convert(true);
}
if (targetByteFifo.size() < length)
convert(false);
int m = Math.min(length, targetByteFifo.size());
if (m > 0) {
targetByteFifo.pop(b, offset, m);
}
return m;
}
@Override
public void close() {
h = null;
z = null;
sourceByteFifo = null;
targetByteFifo = null;
}
// Convert as many samples as possible without blocking.
//
private void convert(boolean wait) throws IOException {
// Return if not operational (e.g., bad sample rates during initialization).
//
if (h == null)
return;
if (wait){
int nRead = sourceStream.read(sourceBytes, 0, sourceBytes.length);
if (nRead > 0){
sourceByteFifo.push(sourceBytes, 0, nRead);
}
}
// Read some source bytes without blocking.
if (sourceStream.available() > 0){
while(true){
int nRead = sourceStream.read(sourceBytes);
if (nRead <= 0)
break;
sourceByteFifo.push(sourceBytes, 0, nRead);
}
}
// Perform conversion from sourceByteFifo to targetByteFifo.
//
int thisWhack = sourceByteFifo.size();
if (thisWhack > 1024){
//System.err.format("Backlog: %d%n", thisWhack-1024);
thisWhack = 1024;
}
while (thisWhack > 1) {
// Shift source samples into delay buffer z.
//
while (phase >= L) {
phase -= L;
sourceByteFifo.pop(sourceBytes, 0, 2);
thisWhack-=2;
short sourceSample = sourceShortBuffer.get(0);
z[pZ++] = sourceSample;
if (pZ == z.length)
pZ = 0;
if (thisWhack < 2) {
break;
}
}
// Possibly generate output samples.
//
while (phase < L) {
int pH = L - 1 - phase;
phase += M;
float sum = 0;
for (int t = pZ; t < z.length; t++) {
sum += h[pH]*z[t];
pH += L;
}
for (int t = 0; t < pZ; t++) {
sum += h[pH]*z[t];
pH += L;
}
short targetSample = (short) Math.round(L*sum);
targetShortBuffer.put(0, targetSample);
targetByteFifo.push(targetBytes);
}
}
}
}
| Java |
/* -*- Java -*-
*
* Copyright (c) 2008
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.sls.wami.applet.sound;
import edu.mit.csail.sls.wami.applet.sound.ResampleInputStream;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
public class ResampleAudioInputStream extends AudioInputStream {
public ResampleAudioInputStream(AudioFormat targetFormat, AudioInputStream sourceStream) {
super(new ResampleInputStream(targetFormat, sourceStream),
targetFormat,
AudioSystem.NOT_SPECIFIED);
}
}
| Java |
/* -*- java -*-
*
* Copyright (c) 2008
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.sls.wami.applet.sound;
import java.io.*;
public interface InputStreamWriter {
/** Copies an input stream to the output. The output is not closed.
*
* @param is The input stream.
*
**/
public void write(InputStream is) throws IOException;
/**
* Closes the stream
**/
public void close() throws IOException;
}
| Java |
/* -*- Java -*-
*
* Copyright (c) 2008
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.sls.wami.applet.sound;
import javax.sound.sampled.*;
import java.io.*;
import java.nio.*;
class UpSample2InputStream extends InputStream {
AudioInputStream in;
ByteBuffer byteBuffer;
ShortBuffer sb;
int channels;
int padding; // Number of 0s to add
boolean eof = false;
AudioFormat audioFormat;
static final int SIZE = 1024;
final float[] f;
final int fl2;
final int fl4;
final int si0;
final int si1;
final int presigSize;
float[] sigb;
int sigp;;
int presig;
UpSample2InputStream(float[] f, AudioInputStream in){
this.f = f;
this.in = in;
fl2 = f.length/2;
fl4 = f.length/4;
si0 = -((f.length-1)/2);
si1 = -((f.length-2)/2);
presigSize = fl4;
sigp = 0;
presig = presigSize;
audioFormat = in.getFormat();
channels = audioFormat.getChannels();
byteBuffer = ByteBuffer.allocate(SIZE);
byteBuffer.order(audioFormat.isBigEndian()
? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);
sb = byteBuffer.asShortBuffer();
sigb = new float[f.length*channels];
for(int i=0; i<sigb.length; i++){
sigb[i] = 0f;
}
}
boolean refill() throws IOException {
if (eof)
return false;
byteBuffer.position(sb.position()*2);
byteBuffer.compact();
// Make sure at least one n-channel sample is available
byte[] array = byteBuffer.array();
int position = byteBuffer.position();
int offset = byteBuffer.arrayOffset();
int avail = byteBuffer.capacity();
while (!eof && position < channels*2){
int n = in.read(array, offset+position, avail-position);
if (n == -1){
padding = fl2*channels;
eof = true;
} else {
position+=n;
}
}
byteBuffer.limit(position);
sb.position(0);
sb.limit(position/2);
return position > 0;
}
@Override
public int available() throws IOException {
return (in.available()+
sb.remaining()*2+
padding)*2;
}
@Override
public void close() throws IOException {
in.close();
}
@Override
public void mark(int readLimit){}
@Override
public boolean markSupported(){
return false;
}
@Override
public void reset(){}
@Override
public long skip(long n2) throws IOException {
long n = n2/2;
long result = 0;
if (padding > 0 || n < fl2+1){
while(n > 0 && padding > 0){
readSample();
result++;
}
return result;
}
long reallySkip = n - (fl2+1);
int sbbytes = sb.remaining()*2;
int sbskip = (int)Math.min((long)sbbytes, reallySkip);
result+=sbskip;
sb.position(sb.position()+sbskip/2);
reallySkip -= sbskip;
if (reallySkip > 0){
result+=in.skip(reallySkip);
}
//
presig = fl2+1;
while(presig-- > 0 && (!eof || padding > 0)){
readSample();
result++;
}
return result*2;
}
@Override
public int read() throws IOException {
throw new IOException("Attempt to read less than one frame");
}
@Override
public int read(byte[] b) throws IOException {
return read(b, 0, b.length);
}
void readSample() throws IOException {
if (sb.remaining() < channels && !eof)
refill();
if (eof && padding==0)
return;
for(int c=0; c<channels; c++){
sigb[sigp+c] = (padding-- > 0) ? 0f : sb.get();
}
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
while(presig-- > 0){
readSample();
}
ByteBuffer bout = ByteBuffer.wrap(b, off, len);
bout.order(audioFormat.isBigEndian()
? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);
ShortBuffer outShortBuffer = bout.asShortBuffer();
while(outShortBuffer.hasRemaining() && (!eof || padding > 0)){
readSample();
for(int c=0; c<channels; c++){
float o = 0.5f; // round sum
int fi = 0; // filter index
int si = sigp+si0*channels; // signal index
if (si < 0){
si+= sigb.length;
}
while(fi < f.length){
o+= f[fi]*sigb[si];
fi+=2;
si+=channels;
if (si >= sigb.length)
si -= sigb.length;
}
outShortBuffer.put((short)o);
o = 0.5f; // round sum
fi = 1; // filter index
si = sigp+si1*channels; // signal index
if (si < 0){
si+= sigb.length;
}
while(fi < f.length){
o+= f[fi]*sigb[si];
fi+=2;
si+=channels;
if (si >= sigb.length)
si -= sigb.length;
}
outShortBuffer.put((short)o);
sigp++;
}
if (sigp == sigb.length)
sigp = 0;
}
if (outShortBuffer.position() == 0)
return -1;
return outShortBuffer.position()*2;
}
}
class DownSample2InputStream extends InputStream {
AudioInputStream in;
ByteBuffer byteBuffer;
ShortBuffer sb;
int channels;
int padding; // Number of 0s to add
boolean eof = false;
AudioFormat audioFormat;
static final int SIZE = 1024;
final float[] f;
final int fl2;
final int fl4;
final int presigSize;
float[] sigb;
int sigp;;
int presig;
DownSample2InputStream(float[] f, AudioInputStream in){
this.f = f;
this.in = in;
fl2 = f.length/2;
fl4 = f.length/4;
presigSize = fl2;
sigp = 0;
presig = presigSize;
audioFormat = in.getFormat();
channels = audioFormat.getChannels();
byteBuffer = ByteBuffer.allocate(SIZE);
byteBuffer.order(audioFormat.isBigEndian()
? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);
sb = byteBuffer.asShortBuffer();
sigb = new float[f.length*channels];
for(int i=0; i<sigb.length; i++){
sigb[i] = 0f;
}
}
boolean refill() throws IOException {
if (eof)
return false;
byteBuffer.position(sb.position()*2);
byteBuffer.compact();
// Make sure at least one n-channel sample is available
byte[] array = byteBuffer.array();
int position = byteBuffer.position();
int offset = byteBuffer.arrayOffset();
int avail = byteBuffer.capacity();
while (!eof && position < channels*2){
int n = in.read(array, offset+position, avail-position);
if (n == -1){
padding = fl2*channels;
eof = true;
} else {
position+=n;
}
}
byteBuffer.limit(position);
sb.position(0);
sb.limit(position/2);
return position > 0;
}
@Override
public int available() throws IOException {
return (in.available()+
sb.remaining()*2+
padding)/2;
}
@Override
public void close() throws IOException {
in.close();
}
@Override
public void mark(int readLimit){}
@Override
public boolean markSupported(){
return false;
}
@Override
public void reset(){}
@Override
public long skip(long n2) throws IOException {
long n = n2*2;
long result = 0;
if (padding > 0 || n < fl2+1){
while(n > 0 && padding > 0){
readSample();
result++;
}
return result;
}
long reallySkip = n - (fl2+1);
int sbbytes = sb.remaining()*2;
int sbskip = (int)Math.min((long)sbbytes, reallySkip);
result+=sbskip;
sb.position(sb.position()+sbskip/2);
reallySkip -= sbskip;
if (reallySkip > 0){
result+=in.skip(reallySkip);
}
//
presig = f.length;
while(presig-- > 0 && (!eof || padding > 0)){
readSample();
result++;
}
return result/2;
}
@Override
public int read() throws IOException {
throw new IOException("Attempt to read less than one frame");
}
@Override
public int read(byte[] b) throws IOException {
return read(b, 0, b.length);
}
void readSample() throws IOException {
if (sb.remaining() < channels && !eof)
refill();
if (eof && padding==0)
return;
for(int c=0; c<channels; c++){
sigb[sigp+c] = (padding-- > 0) ? 0f : sb.get();
}
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
while(presig-- > 0){
readSample();
}
ByteBuffer bout = ByteBuffer.wrap(b, off, len);
bout.order(audioFormat.isBigEndian()
? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);
ShortBuffer outShortBuffer = bout.asShortBuffer();
while(outShortBuffer.hasRemaining() && (!eof || padding > 0)){
readSample();
for(int c=0; c<channels; c++){
float o = 0.5f; // round sum
int fi = 0; // filter index
int si = sigp-f.length*channels; // signal index
if (si < 0){
si+= sigb.length;
}
while(fi < f.length){
o+= f[fi]*sigb[si];
fi++;
si+=channels;
if (si >= sigb.length)
si -= sigb.length;
}
outShortBuffer.put((short)o);
sigp++;
}
if (sigp == sigb.length)
sigp = 0;
}
if (outShortBuffer.position() == 0)
return -1;
return outShortBuffer.position()*2;
}
}
/** Upsample a 16-bit signed stream by 2:1
*
**/
public class UpSample2 extends AudioInputStream {
static final float[] filter = new float[]{
-0.01395067863f,
-0.01254265751f,
0.005888123203f,
0.02567507422f,
0.01752509353f,
-0.0139434597f,
-0.02352647899f,
0.01344585544f,
0.04994074383f,
0.01788352979f,
-0.06279615233f,
-0.07069303465f,
0.08035806069f,
0.3083767822f,
0.4187405136f,
0.3083767822f,
0.08035806069f,
-0.07069303465f,
-0.06279615233f,
0.01788352979f,
0.04994074383f,
0.01344585544f,
-0.02352647899f,
-0.0139434597f,
0.01752509353f,
0.02567507422f,
0.005888123203f,
-0.01254265751f,
-0.01395067863f
};
static AudioFormat newFormat(AudioInputStream in){
AudioFormat inFormat = in.getFormat();
return new AudioFormat(inFormat.getEncoding(),
2*inFormat.getSampleRate(),
inFormat.getSampleSizeInBits(),
inFormat.getChannels(),
inFormat.getFrameSize(),
2*inFormat.getFrameRate(),
inFormat.isBigEndian());
}
static long newFrameLength(AudioInputStream in){
long inFrameLength = in.getFrameLength();
return inFrameLength == AudioSystem.NOT_SPECIFIED ?
AudioSystem.NOT_SPECIFIED : 2*inFrameLength;
}
public UpSample2(AudioInputStream in){
super(new UpSample2InputStream(filter, in),
newFormat(in),
newFrameLength(in));
}
}
| Java |
/* -*- Java -*-
*
* Copyright (c) 2008
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.sls.wami.applet.sound;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.Line;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.Mixer;
import javax.sound.sampled.TargetDataLine;
/**
* Controls recording of audio
*
* Unless otherwise noted, methods are not thread-safe.
*
*/
class AudioRecorder implements Recorder {
protected AudioFormat currentAudioFormat;
protected AudioFormat convertFormat;
protected AudioFormat lineFormat;
protected volatile TargetDataLine line = null;
protected volatile boolean recording = false;
LinkedList<Listener> listeners = new LinkedList<Listener>();
protected Mixer.Info preferredMixerInfo;
/**
* Add an event listener
*
* @param l
* The listener
*
*/
public void addListener(Listener l) {
listeners.add(l);
}
/**
* Remove an event listener
*
* @param l
* The listener
*
*/
public void removeListener(Listener l) {
listeners.remove(l);
}
void recordingHasStarted() {
for (Listener listener : listeners) {
listener.recordingHasStarted();
}
}
void recordingHasEnded() {
for (Listener listener : listeners) {
listener.recordingHasEnded();
}
}
/**
* Find a line for a desired format
*
*/
protected void setLine(AudioFormat desiredAudioFormat) {
if (currentAudioFormat != null
&& currentAudioFormat.matches(desiredAudioFormat))
return;
AudioFormat minFormat = null;
AudioFormatComparator comp = new AudioFormatComparator(
desiredAudioFormat) {
@Override
public int conversionCompare(AudioFormat f1, AudioFormat f2) {
boolean c1 = AudioSystem.isConversionSupported(
desiredAudioFormat, f1);
boolean c2 = AudioSystem.isConversionSupported(
desiredAudioFormat, f2);
if (c1) {
if (!c2) {
return -1;
}
} else if (!c2) {
return 1;
}
return 0;
}
};
// Hunt for the line that supports the format best
ArrayList<Mixer.Info> minfoList = new ArrayList<Mixer.Info>(Arrays
.asList(AudioSystem.getMixerInfo()));
System.out.println("(recorder) preferred mixer is: "
+ preferredMixerInfo);
if (preferredMixerInfo != null) {
minfoList.remove(preferredMixerInfo);
minfoList.add(0, preferredMixerInfo);
}
Mixer.Info[] minfo = minfoList
.toArray(new Mixer.Info[minfoList.size()]);
for (int i = 0; i < minfo.length; i++) {
Mixer mixer = AudioSystem.getMixer(minfo[i]);
System.out.format("Mixer: %s%n", minfo[i].getName());
Line.Info[] linfo = mixer.getTargetLineInfo();
for (int j = 0; j < linfo.length; j++) {
if (!(linfo[j] instanceof DataLine.Info)) {
// Port info doesn't tell us anything about formats
continue;
}
DataLine.Info dinfo = (DataLine.Info) linfo[j];
AudioFormat[] formats = dinfo.getFormats();
for (int k = 0; k < formats.length; k++) {
AudioFormat f = formats[k];
if (comp.compare(f, minFormat) == -1) {
System.out.println("set minFormat to " + f
+ " on mixer " + mixer.getMixerInfo());
minFormat = f;
}
}
}
}
currentAudioFormat = desiredAudioFormat;
if (lineFormat != null && !lineFormat.matches(minFormat)) {
// Will need to switch to a new line
closeLine();
}
lineFormat = minFormat;
if (lineFormat.getSampleRate() == AudioSystem.NOT_SPECIFIED) {
// A java sound feature: If all sample rates are supported,
// then AudioSystem.NOT_SPECIFIED may be returned
lineFormat = new AudioFormat(lineFormat.getEncoding(),
desiredAudioFormat.getSampleRate(), lineFormat
.getSampleSizeInBits(), lineFormat.getChannels(),
lineFormat.getFrameSize(), desiredAudioFormat
.getFrameRate(), lineFormat.isBigEndian());
}
AudioFormat cdf = AudioFormatComparator.channelFormat(
desiredAudioFormat, lineFormat.getChannels());
convertFormat = AudioSystem.isConversionSupported(cdf, lineFormat) ? cdf
: lineFormat;
}
/**
* Stop recording.
*
*/
public synchronized void closeLine() {
if (recording) {
line.stop();
line.drain();
line.close();
line = null;
recording = false;
notifyAll();
recordingHasEnded();
}
}
/**
* Get the recording stream
*
* @param desiredAudioFormat
* The audio format
*
*/
public AudioInputStream getAudioInputStream(AudioFormat desiredAudioFormat)
throws LineUnavailableException {
System.err.println("desired audio format: " + desiredAudioFormat);
setLine(desiredAudioFormat);
line = null;
try {
System.err.println("(recording) line format: " + lineFormat);
DataLine.Info info = new DataLine.Info(TargetDataLine.class,
lineFormat);
if (preferredMixerInfo != null) {
Mixer mixer = AudioSystem.getMixer(preferredMixerInfo);
try {
line = (TargetDataLine) mixer.getLine(info);
} catch (IllegalArgumentException e) {
// line not supported in this mixer, so try a different
// one
line = (TargetDataLine) AudioSystem.getLine(info);
}
} else {
line = (TargetDataLine) AudioSystem.getLine(info);
}
line.open(lineFormat, 8192);
synchronized (this) {
recording = true;
notifyAll();
}
//desiredAudioFormat = new AudioFormat(7000, 16, 1, true, false);
AudioInputStream lineStream = new AudioInputStream(line);
AudioInputStream ais = convertFormat.matches(lineFormat) ? lineStream
: AudioSystem
.getAudioInputStream(convertFormat, lineStream);
if (!desiredAudioFormat.matches(ais.getFormat())){
System.err.format("Resampling! Frame size %d%n", lineStream.getFormat().getFrameSize());
ais = new ResampleAudioInputStream(desiredAudioFormat, lineStream);
}
System.err.format("Converted to %s%n", ais.getFormat());
line.start();
recordingHasStarted();
return ais;
} catch (LineUnavailableException e) {
line = null;
throw e;
}
}
/**
* Returns true if recording
*
* Can be called from any thread
*
*/
public synchronized boolean isRecording() {
return recording;
}
/**
* Sets the preferred mixer to use for recording (note not thread safe
* at the moment)
*/
public void setPreferredMixer(Mixer.Info mInfo) {
preferredMixerInfo = mInfo;
}
public void setPreferredMixer(String name){
for(Mixer.Info mi : AudioSystem.getMixerInfo()){
if (mi.getName().equals(name)){
setPreferredMixer(mi);
return;
}
}
}
public Mixer.Info getPreferredMixer() {
return preferredMixerInfo;
}
}
| Java |
/* -*- Java -*-
*
* Copyright (c) 2008
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.sls.wami.applet.sound;
class InterpolationFilter {
public static final int RECTANGULAR = 1;
public static final int HANNING = 2;
public static final int HAMMING = 3;
public static final int BLACKMAN = 4;
public static float[] design(float f, int n, int windowType) {
f = 1/f;
float[] h = new float[n];
double c = 0.5*(n - 1);
for (int i = 0; i < n; ++i) {
h[i] = (float) sinc(f*(i - c));
}
window(h, windowType);
normalize(h);
return h;
}
private static double sinc(double x) {
if (x == 0.0) {
return 1.0f;
} else {
double y = Math.PI*x;
return Math.sin(y)/y;
}
}
private static void window(float[] h, int windowType) {
int n = h.length;
double s;
switch (windowType) {
default:
case RECTANGULAR:
break;
case HANNING:
s = 2*Math.PI/(n + 1);
for (int i = 0; i < n; ++i)
h[i] *= (float)(0.5*(1 - Math.cos(s*(i + 1))));
break;
case HAMMING:
s = 2*Math.PI/(n - 1);
for (int i = 0; i < n; ++i)
h[i] *= (float)(0.54 - 0.46*Math.cos(s*i));
break;
case BLACKMAN:
s = 2*Math.PI/(n - 1);
for (int i = 0; i < n; ++i)
h[i] *= (float)(0.42 - 0.5*Math.cos(s*i) + 0.08*Math.cos(2*s*i));
break;
}
}
private static void normalize(float[] h) {
float s = 0;
for (int i = 0; i < h.length; ++i)
s += h[i];
s = 1/s;
for (int i = 0; i < h.length; ++i)
h[i] *= s;
}
private static float transitionBand(int windowType) {
switch (windowType) {
default:
case RECTANGULAR:
return 1.84f;
case HANNING:
return 6.22f;
case HAMMING:
return 6.64f;
case BLACKMAN:
return 11.13f;
}
}
public static int computeN(float f, float r, int w) {
return (int) Math.round(transitionBand(w)*f/r) + 1;
}
public static void _main(String[] args) {
int a = 0;
int f = Integer.parseInt(args[a++]);
float r = Float.parseFloat(args[a++]);
int w = Integer.parseInt(args[a++]);
int n = computeN((float) f, r, w);
System.out.println("n = " + n);
float[] h = design((float) f, n, w);
for (int i = 0; i < h.length; i++) {
System.out.println(h[i]);
}
}
public static void main(String[] args) {
int a = 0;
int f = Integer.parseInt(args[a++]);
int n = Integer.parseInt(args[a++]);
int w = Integer.parseInt(args[a++]);
float[] h = design((float) f, n, w);
for (int i = 0; i < h.length; i++) {
System.out.println(f*h[i]);
}
}
}
| Java |
/* -*- java -*-
*
* Copyright (c) 2008
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.sls.wami.applet.sound;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.util.TreeMap;
/** Provides unlimited buffering with multiple readers. Readers are
* thread-safe with respect to the writer and other readers, but the
* writer and the individual readers are not themselves thread-safe.
* In other words, it is safe to have one thread for writing and one
* thread for each reader, but it is not safe to have multiple threads
* writing or multiple threads reading from a particular reader
* without additional concurrency control. It is safe for one thread
* to write and/or make use of multiple readers.
*
* Data is stored in a list of buffers. The buffer granularity
* specifies the size of each buffer.
**/
public class SampleBuffer implements WritableByteChannel, InputStreamWriter {
final int capacity; // Size of one buffer in bytes
final int nchannels; // Number of channels
final int sampleBytes; // Bytes in one sample for one channel
final int frameSize; // Bytes for one sample for all channels
volatile boolean isOpen = true;
volatile Segment tail; // Writes go here
volatile Segment head; // Reads start here
volatile Segment free = null; // Free list
volatile long position = 0; // Last readable byte position
TreeMap<Long,Segment> segments = new TreeMap<Long,Segment>();
/** Allocate a SampleBuffer with nchannels, with each channel
* consisting of sampleBytes bytes per sample. Buffers will be
* allocated in bufferGranularity-sized chunks.
*
* @param nchannels The number of channels
*
* @param frameSize The numbers of bytes in one frame
*
* @param bufferGranularity The number of bytes for one chunk of
* buffer. This will be rounded down so that the bytes for a
* channel will not cross a buffer boundary.
*
**/
public SampleBuffer(int nchannels, int frameSize, int bufferGranularity){
this.nchannels = nchannels;
this.frameSize = frameSize;
this.sampleBytes = frameSize/nchannels;
// Make a multiple of frameSize
this.capacity = (bufferGranularity/frameSize)*frameSize;
tail = getSegment(0);
tail.lock();
head = tail;
}
/** Allocate a SampleBuffer with nchannels, with each channel
* consisting of sampleBytes bytes per sample. Buffers will be
* allocated in bufferGranularity-sized chunks.
*
* @param nchannels The number of channels
*
* @param frameSize The numbers of bytes in one frame
**/
public SampleBuffer(int nchannels, int frameSize){
this(nchannels, frameSize, 1024);
}
/** Allocate a single-channel SampleBuffer of bytes with granularity 1024.
**/
public SampleBuffer(){
this(1,1);
}
/* Holds one segment of buffer
*
*/
protected class Segment {
ByteBuffer buffer = ByteBuffer.allocate(capacity);
int count = 0; // Users of segment
Segment next = null;
long position = 0; // Byte position for buffer[0]
/* Must be called with synchronization
*
* Removes the segment from the active segments and puts it on
* the free list initialized for its next use.
*/
final void release(){
segments.remove(new Long(position));
buffer.clear();
count = 0;
next = free;
free = this;
}
final void lock(){
count++;
}
final void unlock(){
if (count == 0){
throw new IllegalArgumentException
("Attempt to release a lock on position "+position
+" which is not locked");
}
count--;
while(head.count == 0){
Segment seg = head;
head = seg.next;
seg.release();
}
}
}
/* Get a segment for a segment-aligned position, either from the
* segments tree, the free list, or by allocating a new one.
* offset is a byte offset
*/
synchronized Segment getSegment(long offset){
if (head !=null && offset < head.position){
throw new IllegalArgumentException
("Position "+offset+
" is no longer available. First available byte is "
+head.position);
}
offset -= (offset % capacity);
Long key = new Long(offset);
Segment segment = (Segment)segments.get(key);
if (segment == null){
if (free == null){
segment = new Segment();
} else {
segment = free;
free = segment.next;
}
segments.put(key, segment);
}
segment.position = offset;
return segment;
}
final long byteFromSample(long sampleOffset){
return sampleOffset == Long.MAX_VALUE
? Long.MAX_VALUE : sampleOffset*frameSize;
}
final long sampleFromByte(long byteOffset){
return byteOffset == Long.MAX_VALUE
? Long.MAX_VALUE : byteOffset/frameSize;
}
/** Adds a lock to bytes starting at the indicated offset, so that
* reader stream can be positioned anywhere between this offset
* and the last written byte.
*
* @param sampleOffset The sample position to start the lock.
*
**/
public synchronized void lockPosition(long sampleOffset){
if (sampleOffset == Long.MAX_VALUE)
return;
getSegment(byteFromSample(sampleOffset)).lock();
}
/** Release a lock on a previously locked position, freeing any
* segments that are no longer needed.
*
* @param sampleOffset The position to be unlocked. The position must
* have already been locked.
*
**/
public synchronized void unlockPosition(long sampleOffset){
if (sampleOffset == Long.MAX_VALUE)
return;
getSegment(byteFromSample(sampleOffset)).unlock();
}
/** Safely move a locked position to a new position.
*
* @param oldSampleOffset The lock position to release
*
* @param newSampleOffset The lock position to take
*
**/
public synchronized void moveLockPosition(long oldSampleOffset,
long newSampleOffset){
if (oldSampleOffset != newSampleOffset){
lockPosition(newSampleOffset);
unlockPosition(oldSampleOffset);
}
}
/* Prepares the next tail segment, either by taking one from the
* free list or allocating a new one.
*/
protected synchronized void newTail(){
Segment last = tail;
tail = getSegment(tail.position+capacity);
tail.lock();
last.next = tail;
last.unlock();
}
/** True if the buffer is open.
*
**/
public synchronized boolean isOpen(){
return isOpen;
}
/** Close the buffer, preventing additional data from being
* written. Readers can continue.
*
**/
public synchronized void close(){
isOpen = false;
notifyAll();
}
/** Appends data to the samples. This is protected against
* multiple reader threads, but not against multiple writers.
*
* @param src The data to append
**/
public int write(ByteBuffer src){
int result = src.remaining();
while(true){
ByteBuffer dest = tail.buffer;
int nSrc = src.remaining();
if (nSrc == 0){
synchronized(this){
position += result;
notifyAll();
return result;
}
}
int nTail = dest.remaining();
if (nTail == 0){
newTail();
dest = tail.buffer;
nTail = dest.remaining();
}
int n = Math.min(nTail, nSrc);
int limit = src.limit();
src.limit(src.position()+n);
dest.put(src);
src.limit(limit);
}
}
/** A SampleBuffer could be filled by a channel, a stream, or a
* TargetDataLine, none of which share a common interface. A
* SampleBuffer writer can implement this interface to call the
* appropriate read method and pass the implementation to write.
**/
public interface DataReader {
/** Read data
*
* @param dest Bytes to read into
*
* @param off offset
*
* @param len length
*
* @return The number of bytes read, or -1 for end of file.
*
**/
int read(byte[] dest, int off, int len) throws IOException;
/** Cleanup any allocated resources.
*
**/
void close();
}
/** Write into the buffer via a callback that will read from a
* data source.
*
* If the reader indicates end of file, the sample buffer is not
* closed. This allows several streams to be concatenated.
*
* @param reader The reader.read method will be called with a
* byte[], position, and length to fill the next segment or
* portion of a segment of the buffer.
*
* @return The value returned by reader.read
*
**/
public int write(DataReader reader) throws IOException {
if (!tail.buffer.hasRemaining()){
newTail();
}
ByteBuffer bb = tail.buffer;
int pos = bb.position();
int len = bb.remaining();
int nread = reader.read(bb.array(), pos, len);
if (nread <= 0){
reader.close();
return -1;
}
bb.position(pos+nread);
synchronized(this){
position += nread;
notifyAll();
}
return nread;
}
public void write(final InputStream is) throws IOException {
DataReader reader = new DataReader(){
public int read(byte[] dest, int off, int len)
throws IOException {
return is.read(dest, off, len);
}
public void close(){
try {
is.close();
} catch(IOException e){
}
}
};
while(write(reader) > 0){
}
}
/** The position in the SampleBuffer of the next byte to be
* written.
*
**/
public synchronized long position(){
return position;
}
/** Returns a SampleBuffer reader
*
**/
public Reader reader(Limit limit){
return new Reader(limit);
}
public Reader reader(Limit limit, int channel){
if (channel == 0 && nchannels == 1)
return new Reader(limit);
else
return new ChannelReader(limit, channel);
}
public synchronized Reader reader(){
return reader(new Limit(sampleFromByte(head.position),
Long.MAX_VALUE,
Long.MAX_VALUE));
}
public synchronized Reader reader(int channel){
return reader(new Limit(sampleFromByte(head.position),
Long.MAX_VALUE,
Long.MAX_VALUE),
channel);
}
public class Limit {
volatile long limit = Long.MAX_VALUE; // Byte position
final long bofPosition; // Byte position
volatile long eofPosition = Long.MAX_VALUE; // Byte position
Limit(long bofSamplePosition,
long limitSample,
long eofSamplePosition){
bofPosition = byteFromSample(bofSamplePosition);
limit = byteFromSample(limitSample);
eofPosition = byteFromSample(eofSamplePosition);
}
/** Moves the reader limit forward. Readers using this limit
* will block if they try to read beyond this offset.
*
* @param sampleOffset The new sample offset
*
**/
public void limit(long sampleOffset){
long offset = byteFromSample(sampleOffset);
if (offset < limit){
throw new IllegalArgumentException
("Cannot move limit backwards from "
+sampleFromByte(limit)+" to "+sampleOffset);
}
if (offset == limit)
return;
synchronized(SampleBuffer.this){
limit = offset;
SampleBuffer.this.notifyAll();
}
}
/** The current limit in samples
*
**/
public long limit(){
return sampleFromByte(byteLimit());
}
long byteLimit(){
synchronized(SampleBuffer.this){
return limit;
}
}
/** Sets the eof position. When readers reach the eof position,
* they will see an end of file.
*
* @param sampleOffset The sample offset for the eof mark. This
* cannot be before the limit.
*
**/
public void eofPosition(long sampleOffset){
long offset = byteFromSample(sampleOffset);
synchronized(SampleBuffer.this){
if (offset < limit){
throw new IllegalArgumentException
("Cannot set eof position before limit");
}
eofPosition = offset;
SampleBuffer.this.notifyAll();
}
}
long eofBytePosition(){
synchronized(SampleBuffer.this){
return isOpen ?
eofPosition : Math.min(eofPosition, position);
}
}
/** The current eof in samples position.
*
**/
public long eofPosition(){
return sampleFromByte(eofBytePosition());
}
}
public Limit createLimit(long bofSampleOffset){
return new Limit(bofSampleOffset, bofSampleOffset, Long.MAX_VALUE);
}
/** A reader for a sample buffer. Reads can safely happen
* concurrently with writes to the buffer, but individual readers
* do not provide safe access from multiple threads.
* This reader reads all channels
**/
public class Reader implements ReadableByteChannel {
volatile Segment rhead = null; // Reader's buffer position
volatile ByteBuffer buffer; // Reader's buffer
volatile boolean eof;
volatile boolean readerIsOpen;
Limit limit;
volatile long readerPosition; // Byte offset in sample buffer
volatile boolean blocking = true;
Reader(Limit limit){
readerIsOpen = true;
synchronized(SampleBuffer.this){
this.limit = limit;
eof = false;
bufferPosition(limit.bofPosition);
}
}
/** Enable or disable blocking during reads (the default is
* for blocking reads).
*
* @param blocking Whether or not reads block
*
**/
public void setBlocking(boolean blocking){
synchronized(SampleBuffer.this){
this.blocking = blocking;
SampleBuffer.this.notifyAll();
}
}
public boolean blocking(){
synchronized(SampleBuffer.this){
return blocking;
}
}
/** Close the reader, releasing resources.
*
**/
public void close(){
synchronized(SampleBuffer.this){
if (readerIsOpen){
readerIsOpen = false;
if (rhead != null)
rhead.unlock();
SampleBuffer.this.notifyAll();
}
}
}
/** Returns true if the reader is open.
*
**/
public boolean isOpen(){
return readerIsOpen;
}
/** Returns the current byte position of this reader in the
* underlying buffer
*/
public long bufferPosition(){
synchronized(SampleBuffer.this){
return readerPosition;
}
}
/** Sets the byte position of this reader in the underlying
* buffer
*
* @param newPosition The new byte offset for the reader.
* This must within the limits specified by the associated
* limit for the reader, as well as in a locked portion of the
* buffer.
**/
public void bufferPosition(long newPosition){
synchronized(SampleBuffer.this){
if (newPosition < limit.bofPosition){
throw new IllegalArgumentException
("Position out of range for reader");
}
Segment oldseg = rhead;
readerPosition = newPosition;
rhead = getSegment(readerPosition);
if (rhead != oldseg){
rhead.lock();
if (oldseg != null){
oldseg.unlock();
}
buffer = rhead.buffer.duplicate();
}
// Expand the buffer and reposition. Read will block
// until there is something to read and then set the
// limit to the proper value
int offset = (int)(readerPosition-rhead.position);
buffer.limit(offset);
buffer.position(offset);
eof = readerPosition >= limit.eofBytePosition();
SampleBuffer.this.notifyAll();
}
}
/** Will block until there might be something to read.
*
**/
public void waitReady(){
synchronized(SampleBuffer.this){
if (eof || (readerPosition >= limit.eofPosition())){
return;
} else if (readerPosition >=
Math.min(limit.byteLimit(), position)){
// Need to wait for the data to appear
try {
SampleBuffer.this.wait();
} catch(InterruptedException e){
}
}
}
}
/** Read into dest, blocking if bytes are not available.
*
* @param dest The byte buffer to write into
*
* @return The number of bytes read, or -1 if the end of
* the sample buffer has been reached.
**/
public int read(ByteBuffer dest){
if (eof)
return -1;
synchronized(SampleBuffer.this){
int result = 0;
int destRemaining = dest.remaining();
getBytes:
while(destRemaining > 0 && !eof){
if (readerPosition >= limit.eofBytePosition()){
// Nothing more to read
eof = true;
break;
} else if (readerPosition >=
Math.min(limit.byteLimit(), position)){
// Need to wait for the data to appear
try {
if (!blocking)
break getBytes;
SampleBuffer.this.wait();
} catch(InterruptedException e){
}
} else {
// Update the buffer limit if more data has been
// written, but clip it to the limit
buffer.limit
((int)
(Math.min(rhead.buffer.position(),
limit.byteLimit()-rhead.position)));
int bufferRemaining = buffer.remaining();
if (bufferRemaining > 0){
// Copy what's in the buffer
int size = Math.min(destRemaining,bufferRemaining);
if (bufferRemaining > destRemaining){
int saveLimit = buffer.limit();
buffer.limit(buffer.position()+destRemaining);
dest.put(buffer);
buffer.limit(saveLimit);
} else {
dest.put(buffer);
}
result+=size;
destRemaining-=size;
readerPosition+=size;
} else {
// Move to the next segment
Segment oldseg = rhead;
rhead = rhead.next;
rhead.lock();
oldseg.unlock();
buffer = rhead.buffer.duplicate();
buffer.flip();
}
}
}
return result;
}
}
/** The position in the SampleBuffer of the next byte to be read,
* relative the the beginning of the limit.
*
**/
public long position(){
return bufferPosition()-limit.bofPosition;
}
/** Set the position to a new location, relative to the limit.
* This is not interlocked with read.
*
* @param newPosition
*
**/
public void position(long newPosition){
bufferPosition(newPosition+limit.bofPosition);
}
/** Returns true if an EOF mark has been passed in the input
*
**/
public boolean eof(){
return eof;
}
/** The number of bytes between the current position and the last
* readable byte.
**/
public int remaining(){
synchronized(SampleBuffer.this){
return (int)
(Math.min(position,limit.byteLimit())
-(rhead.position+buffer.position()));
}
}
}
/** Reads samples that are interleaved with others, as would be
* seen on an n-channel stream. All positioning is relative to
* the bytes in the interleaved stream, not the multi-channel
* stream
**/
public class ChannelReader extends Reader {
final int channel;
ChannelReader(Limit limit, int channel){
super(limit);
this.channel = channel;
}
/** Returns the number of interleaved bytes between the
* current reader position and the beginning of the limit.
* Bytes from other channels are not included.
*
**/
@Override
public long position(){
return super.position()/nchannels;
}
/** Sets the reader position to the nth byte of the channel's
* data, relative to the beginning of the limit.
*
* @param newPosition The byte position.
*
**/
@Override
public void position(long newPosition){
super.position(nchannels*newPosition);
}
/** The number of bytes between the current position and the last
* readable byte.
**/
@Override
public int remaining(){
return (super.remaining()/frameSize)*sampleBytes;
}
/** Read into dest, blocking if bytes are not available.
*
* @param dest The byte buffer to write into
*
* @return The number of bytes read, or -1 if the end of
* the sample buffer has been reached.
**/
@Override
public int read(ByteBuffer dest){
if (eof)
return -1;
synchronized(SampleBuffer.this){
int result = 0;
int destRemaining = dest.remaining();
getBytes:
while(destRemaining > 0 && !eof){
if (readerPosition >= limit.eofBytePosition()){
// Nothing more to read
eof = true;
break;
} else if (readerPosition >=
Math.min(limit.byteLimit(), position)){
// Need to wait for the data to appear
try {
if (!blocking)
break getBytes;
SampleBuffer.this.wait();
} catch(InterruptedException e){
}
} else {
// Update the buffer limit if more data has been
// written, but clip it to the limit
buffer.limit
((int)
(Math.min(rhead.buffer.position(),
limit.byteLimit()-rhead.position)));
// Quantize by samples
int framesRemaining = buffer.remaining()/frameSize;
int bufferRemaining = sampleBytes*framesRemaining;
int destFramesRemaining = destRemaining/sampleBytes;
// Changes start here
if (bufferRemaining > 0){
// Copy what's in the buffer
int nframes = Math.min(destFramesRemaining,
framesRemaining);
int size = nframes*sampleBytes;
int frameBytes = nframes*frameSize;
int base = buffer.position()+channel*sampleBytes;
result+=size;
destRemaining-=size;
readerPosition+=frameBytes;
while(size > 0){
for(int i=0; i<sampleBytes; i++){
dest.put(buffer.get(base++));
}
size-=sampleBytes;
base+=(frameSize-sampleBytes);
}
buffer.position(buffer.position()+frameBytes);
} else {
// Move to the next segment
Segment oldseg = rhead;
rhead = rhead.next;
rhead.lock();
oldseg.unlock();
buffer = rhead.buffer.duplicate();
buffer.flip();
}
}
}
return result;
}
}
}
}
| Java |
/* -*- Java -*-
*
* Copyright (c) 2008
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.sls.wami.applet.sound;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.Line;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.Mixer;
/**
* @author cyphers
*
* Controls half-duplex audio, switching between listening, playing, and idle as
* needed.
*
*/
public class AudioDevice implements Runnable {
static enum DeviceMode { MODE_IDLE, MODE_PLAY, MODE_RECORD };
DeviceMode mode = DeviceMode.MODE_IDLE;
LinkedList<BasicTask> tasks = new LinkedList<BasicTask>();
BasicTask task = null;
IdleTask idleTask = new IdleTask();
Thread thread;
AudioPlayer audioPlayer = new AudioPlayer();
AudioRecorder audioRecorder = new AudioRecorder();
// Event listeners
LinkedList<Listener> listeners = new LinkedList<Listener>();
/**
* @author cyphers Event listener interface for audio being controlled
*/
public interface Listener {
/**
* Audio output has been initialized, and samples are being played.
*
*/
void playingHasStarted();
/**
* The last sample has been played and the audio has been shut down
*/
void playingHasEnded();
/**
* Audio input has been initialized and samples are being received from
* the device
*/
void listeningHasStarted();
/**
* Audio input has been disabled and samples are no longer being
* received from the device
*/
void listeningHasEnded();
}
/**
* Add an event listener
*
* @param l
* The listener
*
*/
public void addListener(Listener l) {
listeners.add(l);
}
/**
* Remove an event listener
*
* @param l
* The listener
*
*/
public void removeListener(Listener l) {
listeners.remove(l);
}
void playingHasStarted() {
for (Listener listener : listeners) {
listener.playingHasStarted();
}
}
void playingHasEnded() {
for (Listener listener : listeners) {
listener.playingHasEnded();
}
}
void listeningHasStarted() {
for (Listener listener : listeners) {
listener.listeningHasStarted();
}
}
void listeningHasEnded() {
for (Listener listener : listeners) {
listener.listeningHasEnded();
}
}
/**
* @author cyphers Ensure that at most one device is active, and that is
* performing at most one activity
*/
abstract class BasicTask implements Runnable {
volatile boolean active = false; // Started
volatile boolean complete = false; // Finished
synchronized void setActive() {
active = true;
notifyAll();
}
synchronized void setComplete() {
active = false;
complete = true;
notifyAll();
}
/**
* Wait for this task to finish
*
*/
synchronized void waitComplete() {
while (!complete) {
try {
wait();
} catch (InterruptedException e) {
}
}
}
int getFramePosition() {
return 0;
}
abstract void finish();
abstract void abort();
}
/**
* @author cyphers This task "runs" when there is nothing to do. It just
* waits for another task to show up
*/
class IdleTask extends BasicTask {
public void run() {
setMode(DeviceMode.MODE_IDLE);
synchronized (AudioDevice.this) {
while (tasks.isEmpty()) {
try {
AudioDevice.this.wait();
} catch (InterruptedException e) {
}
}
}
}
@Override
void finish() {
}
@Override
void abort() {
}
}
/**
* @author cyphers Play some audio
*/
class PlayTask extends BasicTask {
AudioInputStream ais;
boolean setStart;
boolean last;
LineUnavailableException exception;
PlayTask(AudioInputStream ais, boolean setStart, boolean last) {
this.ais = ais;
this.setStart = setStart;
this.last = last;
}
public void run() {
setMode(DeviceMode.MODE_PLAY);
if (setStart)
playingHasStarted();
try {
audioPlayer.play(ais, setStart, last);
} catch (LineUnavailableException e) {
exception = e;
}
if (last) {
playingHasEnded();
}
}
@Override
int getFramePosition() {
return audioPlayer.getFramePosition();
}
@Override
synchronized void abort() {
if (active) {
audioPlayer.stopPlaying();
waitComplete();
}
}
@Override
void finish() {
waitComplete();
}
}
/**
* @author cyphers Record something
*/
class RecordTask extends BasicTask {
AudioFormat desiredAudioFormat;
AudioInputStream ais = null;
LineUnavailableException exception = null;
volatile boolean ready = false;
RecordTask(AudioFormat desiredAudioFormat) {
this.desiredAudioFormat = desiredAudioFormat;
}
public void run() {
setMode(DeviceMode.MODE_RECORD);
listeningHasStarted();
try {
ais = audioRecorder.getAudioInputStream(desiredAudioFormat);
} catch (LineUnavailableException e) {
exception = e;
}
synchronized (this) {
ready = true;
notifyAll();
}
waitComplete();
System.out.println("Waiting for record task is complete");
listeningHasEnded();
System.out.println("Fired all listening has ended stuff.");
}
synchronized AudioInputStream getAudioInputStream()
throws LineUnavailableException {
while (!ready) {
try {
wait();
} catch (InterruptedException e) {
}
}
if (ais == null)
throw exception;
else
return ais;
}
@Override
void abort() {
finish();
}
@Override
synchronized void finish() {
System.out.println("FINISH RECORDING: ");
if (active) {
System.out.println("set to idle");
setMode(DeviceMode.MODE_IDLE);
setComplete();
}
}
}
public AudioDevice() {
thread = new Thread(this);
thread.start();
}
/**
* Play an audio input stream
*
* @param ais
* The audio input stream
*
* @param setStart
* The first frame of this stream is frame 0 for
* getFramePosition()
*
* @param last
* If true, playingHasEnded() will be called when the
* stream finishes playing.
*
*/
public void play(AudioInputStream ais, boolean setStart, boolean last) {
PlayTask task = new PlayTask(ais, setStart, last);
addTask(task);
}
/**
* Play an audio input stream
*
* @param ais
* The audio input stream
*
*/
public void play(AudioInputStream ais) {
play(ais, true, true);
}
/**
* Wait for audio to become available and return an audio input stream
* close to the specified format
*
* @param format
* The desired audio format
*
*/
public AudioInputStream getAudioInputStream(AudioFormat format)
throws LineUnavailableException {
RecordTask task = new RecordTask(format);
addTask(task);
return task.getAudioInputStream();
}
synchronized void addTask(BasicTask task) {
tasks.add(task);
notifyAll();
}
public void run() {
while (true) {
synchronized (this) {
task = (tasks.isEmpty()) ? idleTask : (BasicTask) tasks
.removeFirst();
task.setActive();
notifyAll();
}
task.run();
task.setComplete();
}
}
/**
* Finish everything and return
*
*/
public void finish() {
while (true) {
synchronized (this) {
task.finish();
if (tasks.isEmpty()) {
return;
} else {
try {
wait();
} catch (InterruptedException e) {
}
}
}
}
}
/**
* Abort everything and return
*
*/
public synchronized void abort() {
tasks.clear();
task.abort();
notifyAll();
}
public int getFramePosition() {
synchronized (this) {
return task.getFramePosition();
}
}
public int supportedPlaySampleRate(int desiredSampleRate)
throws LineUnavailableException {
return audioPlayer.supportedSampleRate(desiredSampleRate);
}
// Make sure only one direction is going at once
void setMode(DeviceMode newMode) {
if (mode == newMode)
return;
switch (mode) {
case MODE_PLAY:
audioPlayer.closeLine();
break;
case MODE_RECORD:
audioRecorder.closeLine();
break;
}
mode = newMode;
}
/**
* Set the preferred target (input) mixer to use. Note, the system may
* ignore this preference if the line does not support a suitable format
*
* @param mInfo
* Description of mixer
*/
public void setPreferredTargetMixer(Mixer.Info mInfo) {
audioRecorder.setPreferredMixer(mInfo);
}
/**
* Set the preferred target (input) mixer to use. Note, the system may
* ignore this preference if the line does not support a suitable format
*
* @param mInfo
* Description of mixer
*/
public void setPreferredTargetMixer(String mInfo) {
audioRecorder.setPreferredMixer(mInfo);
}
public Mixer.Info getPreferredTargetMixer() {
return audioRecorder.getPreferredMixer();
}
/**
* Set the preferred source (output) mixer to use.
*
* @param mInfo
* Description of mixer
*/
public void setPreferredSourceMixer(Mixer.Info mInfo) {
audioPlayer.setPreferredMixer(mInfo);
}
public void setPreferredSourceMixer(String minfo){
audioPlayer.setPreferredMixer(minfo);
}
public Mixer.Info getPreferredSourceMixer() {
return audioPlayer.getPreferredMixer();
}
/**
* returns a list of target mixers (which also have data lines)
*
* @return
*/
public static Mixer.Info[] getAvailableTargetMixers() {
return getAvailableMixers(true);
}
public static Mixer.Info[] getAvailableSourceMixers() {
return getAvailableMixers(false);
}
private static Mixer.Info[] getAvailableMixers(boolean isTarget) {
ArrayList<Mixer.Info> mixers = new ArrayList<Mixer.Info>(Arrays
.asList((Mixer.Info[]) AudioSystem.getMixerInfo()));
for (Iterator<Mixer.Info> it = mixers.iterator(); it.hasNext();) {
Mixer.Info minfo = it.next();
Mixer mixer = AudioSystem.getMixer(minfo);
Line.Info[] linfo = (isTarget) ? mixer.getTargetLineInfo() : mixer
.getSourceLineInfo();
boolean hasDataLine = false;
for (int j = 0; j < linfo.length; j++) {
if (linfo[j] instanceof DataLine.Info) {
hasDataLine = true;
break;
}
}
if (!hasDataLine) {
it.remove();
}
}
return mixers.toArray(new Mixer.Info[mixers.size()]);
}
}
| Java |
/* -*- Java -*-
*
* Copyright (c) 2008
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.sls.wami.applet.sound;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.LineUnavailableException;
/**
* Interface to something that can provide an audio input stream.
*
*/
public interface Recorder {
/**
* Listener for events on the recorder
*
*/
public interface Listener {
/**
* Called when recording starts
*
*/
void recordingHasStarted();
/**
* Called when recording finishes
*
*/
void recordingHasEnded();
}
/**
* Add a listener
*
* @param listener
* The listener
*
*/
public void addListener(Listener listener);
/**
* Remove a listener
*
* @param listener
* The listener
*
*/
public void removeListener(Listener listener);
/**
* Get an AudioInputStream for the specified format (or something
* close).
*
* @param desiredAudioFormat
* The audio format desired
*
* @return An AudioInputStream.
*
*/
public AudioInputStream getAudioInputStream(AudioFormat desiredAudioFormat)
throws LineUnavailableException;
/**
* Returns true if recording is in progress
*
*/
public boolean isRecording();
/**
* Stops recording if it is in progress.
*
*/
public void closeLine();
}
| Java |
/* -*- Java -*-
*
* Copyright (c) 2008
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.sls.wami.applet.sound;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.LineUnavailableException;
/**
* @author cyphers Interface to something that can play an AudioinputStream
*/
public interface Player {
/**
* A listener for play events
*
*/
public interface Listener {
/**
* Called when playing starts
*
*/
void playingHasStarted();
/**
* Called when playing completes
*
*/
void playingHasEnded();
}
/**
* Add a listener
*
* @param listener
* The listener
*
*/
public void addListener(Listener listener);
/**
* Remove a listener
*
* @param listener
* The listener
*
*/
public void removeListener(Listener listener);
/**
* Play the stream. This is the same as play(stream, true, true).
*
* @param stream
* The stream to play
*
*/
public void play(AudioInputStream stream) throws LineUnavailableException;
/**
* Play the stream
*
* @param stream
* The stream to play
*
* @param setStart
* If true, getFramePosition() will consider the start of
* this stream as frame 0.
*
*/
void play(AudioInputStream stream, boolean setStart, boolean last)
throws LineUnavailableException;
/**
* Returns true if in the play loop
*
*/
boolean isPlaying();
/**
* Return the frame position in the currently playing stream.
*
* Can be called from any thread
*
*/
int getFramePosition();
/**
* Wait for playing to complete, and then close the line.
*
*/
void closeLine();
/**
* Break out of playing
*
* Can be called from any thread
*/
void stopPlaying();
/**
* Return the closest sample rate that can be used.
*
*/
int supportedSampleRate(int desiredSampleRate)
throws LineUnavailableException;
}
| Java |
/* -*- Java -*-
*
* Copyright (c) 2008
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.sls.wami.applet.sound;
import javax.sound.sampled.*;
import java.util.*;
/** Comparator for audio formats that uses relative distance from a
* desired format as the comparison.
**/
abstract class AudioFormatComparator implements Comparator<AudioFormat> {
AudioFormat desiredAudioFormat;
int channels;
AudioFormat.Encoding encoding;
float frameRate;
float sampleRate;
int sampleSizeInBits;
boolean isBigEndian;
public AudioFormatComparator(AudioFormat desiredAudioFormat){
this.desiredAudioFormat = desiredAudioFormat;
channels = desiredAudioFormat.getChannels();
encoding = desiredAudioFormat.getEncoding();
frameRate = desiredAudioFormat.getFrameRate();
sampleRate = desiredAudioFormat.getSampleRate();
sampleSizeInBits = desiredAudioFormat.getSampleSizeInBits();
isBigEndian = desiredAudioFormat.isBigEndian();
}
// Java doesn't provide channel conversions, so when looking for the
// nearest format, need to ignore channels
public static AudioFormat channelFormat(AudioFormat f, int n){
int channels = f.getChannels();
return new AudioFormat(f.getEncoding(),
f.getSampleRate(),
f.getSampleSizeInBits(),
n,
n*f.getFrameSize()/channels,
f.getFrameRate(),
f.isBigEndian());
}
// Compare two formats for conversions. This has to be different
// for intput and output since the conversions go in different
// directions
abstract int conversionCompare(AudioFormat f1, AudioFormat f2);
// Compare relative distance to the desiredAudioFormat
// In linux, 8-bit audio to the device is broken for record and
// play, so we need to avoid the 8-bit formats
public int compare(AudioFormat o1, AudioFormat o2){
if (o1 == o2)
return 0;
if (o1 == null)
return 1;
if (o2 == null)
return -1;
AudioFormat f1 = (AudioFormat)o1;
AudioFormat f2 = (AudioFormat)o2;
{
// 8-bit line support is broken in the vm, so push 8-bit
// formats to the bottom of the list
int b1 = f1.getSampleSizeInBits();
int b2 = f2.getSampleSizeInBits();
if (b1 != b2){
if (b1 == 8)
return 1;
if (b2 == 8)
return -1;
}
}
if (o1.equals(o2))
return 0;
if (f1.matches(f2))
return 0;
if (desiredAudioFormat.matches(f1))
return -1;
if (desiredAudioFormat.matches(f2))
return 1;
// Use the closer rate
{
float r1 = f1.getSampleRate();
float r2 = f2.getSampleRate();
if (r1 != r2){
// If a rate matches, it's closer
// Java uses AudioSystem.NOT_SPECIFIED for a rate when
// it's not going to provide any information about what's
// supports
if (r1 == sampleRate || r1 == AudioSystem.NOT_SPECIFIED)
return -1;
if (r2 == sampleRate || r2 == AudioSystem.NOT_SPECIFIED)
return 1;
boolean r1m = ((int)r1 % (int)sampleRate) == 0;
boolean r2m = ((int)r2 % (int)sampleRate) == 0;
if (r1m && r2m){
// If both rates are multiples, use the closer
// multiple, while if only one rate is a multiple,
// go with that one
float m1 = r1/sampleRate;
float m2 = r2/sampleRate;
if (m1 < m2)
return -1;
else if (m2 < m1)
return 1;
} else if (r1m){
return -1;
} else if (r2m){
return 1;
}
}
}
{
AudioFormat.Encoding e1 = f1.getEncoding();
AudioFormat.Encoding e2 = f2.getEncoding();
if (e1 != e2){
if (e1 == encoding)
return -1;
if (e2 == encoding)
return 1;
if (encoding == AudioFormat.Encoding.PCM_SIGNED
|| encoding == AudioFormat.Encoding.PCM_UNSIGNED){
// Prefer lossless encodings
if (e1 == AudioFormat.Encoding.PCM_UNSIGNED
|| e1 == AudioFormat.Encoding.PCM_SIGNED)
return -1;
if (e2 == AudioFormat.Encoding.PCM_UNSIGNED
|| e2 == AudioFormat.Encoding.PCM_SIGNED)
return 1;
} else if (encoding == AudioFormat.Encoding.ULAW ||
encoding == AudioFormat.Encoding.ALAW){
if (e1 == AudioFormat.Encoding.PCM_SIGNED)
return -1;
else if (e2 == AudioFormat.Encoding.PCM_SIGNED)
return 1;
else if (e1 == AudioFormat.Encoding.PCM_UNSIGNED)
return -1;
else if (e2 == AudioFormat.Encoding.PCM_UNSIGNED)
return 1;
else if (e1 == AudioFormat.Encoding.ULAW ||
e1 == AudioFormat.Encoding.ALAW)
return -1;
else if (e2 == AudioFormat.Encoding.ULAW ||
e2 == AudioFormat.Encoding.ALAW)
return 1;
}
}
}
// Endianness barely matters
{
boolean b1 = f1.isBigEndian();
boolean b2 = f2.isBigEndian();
if (b1 != b2){
if (b1 == isBigEndian)
return -1;
if (b2 == isBigEndian)
return 1;
}
}
// If a conversion exists for only one, then it is nearer
{
int c = conversionCompare(channelFormat(f1,1),
channelFormat(f2,1));
if (c != 0)
return c;
}
// If the channels are different, best is equal numbers of
// channels to what we want, less best is the least number
// of extra, and worst is not enough
{
int c1 = f1.getChannels();
int c2 = f2.getChannels();
if (c1 != c2){
if (c1 == channels)
return -1;
if (c2 == channels)
return 1;
if (c1 > channels){
if (c2 > channels){
if (c1 < c2)
return -1;
if (c1 > c2)
return 1;
} else return -1;
} else if (c2 > channels){
return 1;
} else if (c1 < c2){
return 1;
} else return -1;
}
}
// They are equally good/bad, so fall back to the hash code
{
int h1 = f1.hashCode();
int h2 = f2.hashCode();
if (h1 < h2)
return -1;
if (h1 > h2)
return 1;
return 0;
}
}
}
| Java |
package edu.mit.csail.sls.wami.applet;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Vector;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.Mixer;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.Box;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import edu.mit.csail.sls.wami.applet.sound.AudioDevice;
import edu.mit.csail.sls.wami.applet.sound.AudioInputStreamSource;
import edu.mit.csail.sls.wami.applet.sound.AutocorrSpeechDetector;
import edu.mit.csail.sls.wami.applet.sound.SpeechDetector;
public class WamiAudioApplet extends JApplet implements AudioDevice.Listener,
SpeechDetector.Listener {
private JButton button;
private Timer levelTimer;
private JProgressBar levelMeter;
private boolean useSpeechDetector;
private MouseListener mouseListener;
private boolean allowStopPlaying;
private boolean repollOnTimeout = true;
private volatile boolean connected = false;
private URL recordUrl;
private URL playUrl;
private boolean playRecordTone;
private AudioDevice audioDevice = new AudioDevice();
private SpeechDetector detector = new AutocorrSpeechDetector();
private AudioFormat recordFormat;
private boolean initialized = false;
private boolean isDestroyed = false;
private volatile boolean isPlaying;
private volatile boolean isRecording;
private volatile boolean isListening;
private volatile boolean audioFailure;
@Override
public void init() {
System.out.println("Initializing WAMI Audio Applet 5");
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
createGUI();
}
});
} catch (Exception e) {
System.err.println("Exception caught in applet init()");
e.printStackTrace();
}
}
@Override
public void start() {
isPlaying = false;
isRecording = false;
isListening = false;
audioFailure = false;
}
@Override
public void destroy() {
initialized = false;
isDestroyed = true;
}
/**
* Visible to javascript: starts listening / recording
*/
public void startListening() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
startAudioListening();
}
});
}
/**
* Visible to javascript: stops listening / recording
*/
public void stopRecording() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
audioDevice.finish();
isRecording = false;
isListening = false;
}
});
}
/**
* Visible to javascript: stops playing
*/
public void stopPlaying() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (isPlaying) {
audioDevice.abort();
}
}
});
}
/**
* Initializes the applet. Must be called from the swing thread
*/
private void createGUI() {
if (initialized)
return;
useSpeechDetector = getBooleanParameter("useSpeechDetector", true);
allowStopPlaying = getBooleanParameter("allowStopPlaying", true);
boolean hideButton = getBooleanParameter("hideButton", false);
recordUrl = urlParameter("recordUrl");
playUrl = urlParameter("playUrl");
recordFormat = getAudioFormatFromParams("recordAudioFormat",
"recordSampleRate", "recordIsLittleEndian");
playRecordTone = getBooleanParameter("playRecordTone", false);
mouseListener = new MouseListener();
button = new JButton("Listen");
button.setText("Initializing");
button.setEnabled(false);
button.addMouseListener(mouseListener);
Container cp = getContentPane();
cp.setBackground(Color.WHITE);
JButton settings = new JButton("...");
settings.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showSettings();
}
});
levelMeter = new JProgressBar(JProgressBar.HORIZONTAL, 0, 1024);
levelMeter.setPreferredSize(new Dimension(
levelMeter.getPreferredSize().width, settings
.getPreferredSize().height));
settings.setText("settings");
levelMeter.setStringPainted(false);
levelMeter.setIndeterminate(false);
// javax.swing.timer runs events on swing event thread, so this is safe
levelTimer = new Timer(50, new ActionListener() {
public void actionPerformed(ActionEvent e) {
double peak = detector.readPeakLevel();
levelMeter.setValue((int) (peak * 1024 + .5));
}
});
cp.setLayout(new BorderLayout());
System.out.println("Hide Button: " + hideButton);
if (!hideButton) {
cp.add(button, BorderLayout.CENTER);
}
Box box = Box.createHorizontalBox();
cp.add(box, BorderLayout.SOUTH);
box.add(settings);
box.add(Box.createHorizontalStrut(5));
box.add(levelMeter);
audioDevice.addListener(this);
detector.addListener(this);
pingURL(recordUrl);
startPollingForAudio();
showStatus();
initialized = true;
}
/**
* Audio device is listening
*/
public void listeningHasStarted() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
levelTimer.start();
showStatus();
}
});
}
/**
* Audio device has stopped listening
*/
public void listeningHasEnded() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
isRecording = false;
isListening = false;
showStatus();
levelTimer.stop();
levelMeter.setValue(0);
}
});
}
/**
* audio device is playing
*/
public void playingHasStarted() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
isPlaying = true;
showStatus();
}
});
}
/**
* audio device has finished playing
*/
public void playingHasEnded() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
isPlaying = false;
showStatus();
}
});
}
/**
* Speech detection is not sensing speech
*/
public void noSpeech(long offsetSample) {
}
/**
* Samples are ready for capture
*/
public void speechStart(long offsetSample) {
isRecording = true;
recordAudio();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
showStatus();
}
});
}
/**
* End of samples to be captured
*/
public void speechEnd(long offsetSample) {
audioDevice.finish();
}
/**
* Starts "listening" if useSpeechDetector is true, otherwise it starts
* recording immediately
*/
void startAudioListening() {
AudioInputStream audioIn;
try {
if (playRecordTone) {
playResource("start_tone.wav");
}
// The following line is necessary to fix a weird bug on the Mac
// whereby recording works once, but not a second time unless this
// method gets called in between. I have no idea why. imcgraw
AudioDevice.getAvailableTargetMixers();
audioIn = audioDevice.getAudioInputStream(recordFormat);
detector.listen(new AudioInputStreamSource(audioIn), 0,
useSpeechDetector);
System.out.println("Detector is listening");
showStatus();
} catch (LineUnavailableException e) {
e.printStackTrace();
audioFailure();
}
isListening = true;
}
private AudioFormat getAudioFormatFromParams(String formatParam,
String sampleRateParam, String isLittleEndianParam) {
String audioFormatStr = getParameter(formatParam);
int sampleRate = Integer.parseInt(getParameter(sampleRateParam));
boolean isLittleEndian = Boolean
.parseBoolean(getParameter(isLittleEndianParam));
if ("MULAW".equals(audioFormatStr)) {
return new AudioFormat(AudioFormat.Encoding.ULAW, sampleRate, 8, 1,
2, 8000, !isLittleEndian);
} else if ("LIN16".equals(audioFormatStr)) {
return new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, sampleRate,
16, 1, 2, sampleRate, !isLittleEndian);
}
throw new UnsupportedOperationException("Unsupported audio format: '"
+ audioFormatStr + "'");
}
private void pingURL(final URL recordUrl) {
if (recordUrl == null)
return;
new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 5; i++) {
HttpURLConnection c;
try {
c = (HttpURLConnection) recordUrl.openConnection();
c.setConnectTimeout(1000);
c.connect();
if (c.getResponseCode() != 200) {
System.out.println("WARNING: Ping failed for URL:"
+ recordUrl);
setConnectionStatus(false);
Thread.sleep(1000);
} else {
setConnectionStatus(true);
break;
}
} catch (IOException e) {
setConnectionStatus(false);
break;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
void setConnectionStatus(boolean value) {
connected = value;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
showStatus();
}
});
}
/**
* Must be called from the swing thread
*/
private void showStatus() {
System.out.format("Conn: %s, playing: %s, list %s, rec %s%n",
connected, isPlaying, isListening, isRecording);
if (!connected) {
setListeningStatus("Error: Connection Failure", Color.RED);
button.setEnabled(false);
} else if (audioFailure) {
setListeningStatus("Error: Audio Failure", Color.RED);
button.setEnabled(false);
} else if (isPlaying) {
if (allowStopPlaying) {
setListeningStatus("Stop playing", Color.GREEN);
button.setEnabled(true);
} else {
setListeningStatus("Playing", Color.GREEN);
button.setEnabled(false);
}
} else if (isListening) {
if (useSpeechDetector) {
button.setEnabled(true);
if (isRecording) {
setListeningStatus("Recording: Click to stop", Color.CYAN);
} else {
setListeningStatus("Listening: Click to stop", Color.CYAN);
}
} else {
button.setEnabled(true);
setListeningStatus("Recording", Color.CYAN);
}
} else {
button.setEnabled(true);
if (useSpeechDetector) {
setListeningStatus("Click to talk", Color.GREEN);
} else {
setListeningStatus("Hold to talk", Color.GREEN);
}
}
}
/**
* Must be called from the swing thread
*
* @param status
* @param color
*/
private void setListeningStatus(String status, Color color) {
button.setText(status);
button.setBackground(color);
}
private boolean getBooleanParameter(String paramName, boolean defaultValue) {
String value = getParameter(paramName);
return (value != null) ? Boolean.parseBoolean(value) : defaultValue;
}
private URL urlParameter(String paramName) {
System.out.println("Getting URL from parameter");
String urlString = getParameter(paramName);
if (urlString != null && !"".equals(urlString)
&& !"null".equals(urlString)) {
try {
URI uri = new URI(urlString);
return uri.toURL();
} catch (MalformedURLException e) {
e.printStackTrace();
System.err.println("Invalid url: " + urlString);
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
return null;
}
private class MouseListener extends MouseAdapter {
@Override
public void mousePressed(MouseEvent e) {
if (button.isEnabled()) {
if (!isPlaying) {
if (isListening && useSpeechDetector) {
audioDevice.finish();
} else if (!isRecording) {
startAudioListening();
}
}
}
}
@Override
public void mouseReleased(MouseEvent e) {
if (button.isEnabled()) {
if (!isPlaying) {
if (!useSpeechDetector) {
audioDevice.finish();
}
}
}
}
@Override
public void mouseClicked(MouseEvent e) {
if (button.isEnabled()) {
if (isPlaying) {
if (allowStopPlaying) {
audioDevice.abort();
}
} else if (isRecording) {
if (useSpeechDetector) {
audioDevice.finish();
}
}
}
}
}
/**
* shows a window where audio settings can be adjusted
*/
private void showSettings() {
Mixer.Info[] sourceMixers = AudioDevice.getAvailableSourceMixers();
Mixer.Info[] targetMixers = AudioDevice.getAvailableTargetMixers();
Mixer.Info preferredSource = audioDevice.getPreferredSourceMixer();
Mixer.Info preferredTarget = audioDevice.getPreferredTargetMixer();
Vector<Object> vSource = new Vector<Object>(Arrays.asList(sourceMixers));
Vector<Object> vTarget = new Vector<Object>(Arrays.asList(targetMixers));
vSource.add(0, "Default");
vTarget.add(0, "Default");
final JComboBox comboSource = new JComboBox(vSource);
final JComboBox comboTarget = new JComboBox(vTarget);
if (preferredSource != null) {
comboSource.setSelectedItem(preferredSource);
}
if (preferredTarget != null) {
comboTarget.setSelectedItem(preferredTarget);
}
Box audioBox = Box.createVerticalBox();
Box topBox = Box.createHorizontalBox();
Box bottomBox = Box.createHorizontalBox();
audioBox.add(topBox);
audioBox.add(bottomBox);
getContentPane().add(audioBox);
topBox.add(new JLabel("Audio Out"));
topBox.add(comboSource);
bottomBox.add(new JLabel("Audio In "));
bottomBox.add(comboTarget);
String[] empty = {};
final String[] params = useSpeechDetector ? detector
.getParameterNames() : empty;
final ArrayList<JTextField> paramFields = new ArrayList<JTextField>();
if (useSpeechDetector) {
// detector params
for (String param : params) {
Box paramBox = Box.createHorizontalBox();
final JTextField textField = new JTextField();
final JLabel label = new JLabel(param);
paramBox.add(label);
paramBox.add(textField);
paramFields.add(textField);
textField.setText("" + detector.getParameter(param));
textField.setEditable(true);
audioBox.add(paramBox);
}
}
final JFrame frame = new JFrame("Settings");
Box cp = Box.createVerticalBox();
cp.add(audioBox);
JButton okButton = new JButton("OK");
JButton cancelButton = new JButton("Cancel");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Object selected = comboSource.getSelectedItem();
audioDevice
.setPreferredSourceMixer((selected instanceof Mixer.Info) ? (Mixer.Info) selected
: null);
selected = comboTarget.getSelectedItem();
audioDevice
.setPreferredTargetMixer((selected instanceof Mixer.Info) ? (Mixer.Info) selected
: null);
if (useSpeechDetector) {
for (int i = 0; i < params.length; i++) {
String param = params[i];
try {
double value = Double.parseDouble(paramFields
.get(i).getText());
detector.setParameter(param, value);
} catch (NumberFormatException eN) {
eN.printStackTrace();
}
}
}
frame.dispose();
}
});
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.dispose();
}
});
Box buttonBox = Box.createHorizontalBox();
buttonBox.add(okButton);
buttonBox.add(cancelButton);
cp.add(buttonBox);
frame.setContentPane(cp);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
void audioFailure() {
audioFailure = true;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
showStatus();
}
});
}
/**
* records audio by sending it to the server, until the stream is closed
*/
void recordAudio() {
// must do this immediately in the same thread
final AudioInputStream in = detector.createReader(0);
new Thread(new Runnable() {
public void run() {
try {
System.out.println("Posting audio to " + recordUrl);
System.out.println("Format: " + recordFormat);
HttpURLConnection conn = (HttpURLConnection) recordUrl
.openConnection();
conn.setRequestProperty("Content-Type",
getContentType(recordFormat));
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setChunkedStreamingMode(2048);
conn.connect();
OutputStream out = conn.getOutputStream();
byte[] buffer = new byte[10240];
int totalRead = 0;
while (true) {
int numRead = in.read(buffer);
if (numRead < 0) {
break;
}
out.write(buffer, 0, numRead);
out.flush();
totalRead += numRead;
}
out.close();
in.close();
if (playRecordTone) {
playResource("end_tone.wav");
}
System.out.println("Posted total of " + totalRead
+ " audio bytes");
System.out.println("Http response line: "
+ conn.getResponseMessage());
} catch (IOException e) {
e.printStackTrace();
setConnectionStatus(false);
}
}
}).start();
}
private String getContentType(AudioFormat format) {
String encoding = null;
if (format.getEncoding() == AudioFormat.Encoding.ULAW) {
encoding = "MULAW";
} else if (format.getEncoding() == AudioFormat.Encoding.PCM_SIGNED) {
encoding = "L16";
}
return "AUDIO/" + encoding + "; CHANNELS=" + format.getChannels()
+ "; RATE=" + (int) format.getSampleRate() + "; BIG="
+ format.isBigEndian();
}
void playResource(String resourceName) {
InputStream in = (getClass().getResourceAsStream(resourceName));
if (in != null) {
try {
AudioInputStream ais = AudioSystem
.getAudioInputStream(new BufferedInputStream(in));
audioDevice.play(ais);
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.err.println("playResource(): can't find resource named: "
+ resourceName);
}
}
/**
* Polls a url for audio, plays it when it is returned
*
* @param playUrl
* The url to poll
*/
private void startPollingForAudio() {
if (playUrl == null)
return;
Thread thread = new Thread() {
@Override
public void run() {
int READ_TIMEOUT = 1000 * 60 * 5; // 5 minutes
while (!isDestroyed) {
boolean repoll = pollForAudio(READ_TIMEOUT);
if (!repoll) {
setConnectionStatus(false);
return;
}
}
}
};
thread.setDaemon(true);
thread.start();
}
boolean pollForAudio(int connectionTimeout) {
try {
HttpURLConnection c;
c = (HttpURLConnection) playUrl.openConnection();
// Spend some time polling before timing out
c.setReadTimeout(connectionTimeout);
c.connect();
System.out.println("Polling for audio on: " + playUrl);
if (c.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new IOException("Polling failed.");
}
System.out.println("Connected.");
if ("audio/wav".equals(c.getContentType())) {
InputStream stream = c.getInputStream();
AudioInputStream ais;
// assume the audio has header information in the stream
// to tell us what it is
try {
// must be a bufferedinputstream b/c mark must be
// supported to to read the header and determine the audio
// format
ais = AudioSystem
.getAudioInputStream(new BufferedInputStream(stream));
System.out.println("Playing");
audioDevice.play(ais);
System.out.println("Sleeping");
return true;
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
}
} else {
System.out
.println("Connection was OK, but there was no audio, polling again.");
}
} catch (IOException e) {
if (e instanceof SocketTimeoutException) {
System.out.println("Socket Timeout while polling for audio.");
} else {
setConnectionStatus(false);
System.out.println("WARNING: Failed to poll for audio on: "
+ playUrl);
e.printStackTrace();
return false;
}
}
return repollOnTimeout;
}
}
| Java |
package pl.polidea.treeview;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
/**
* Tree view, expandable multi-level.
*
* <pre>
* attr ref pl.polidea.treeview.R.styleable#TreeViewList_collapsible
* attr ref pl.polidea.treeview.R.styleable#TreeViewList_src_expanded
* attr ref pl.polidea.treeview.R.styleable#TreeViewList_src_collapsed
* attr ref pl.polidea.treeview.R.styleable#TreeViewList_indent_width
* attr ref pl.polidea.treeview.R.styleable#TreeViewList_handle_trackball_press
* attr ref pl.polidea.treeview.R.styleable#TreeViewList_indicator_gravity
* attr ref pl.polidea.treeview.R.styleable#TreeViewList_indicator_background
* attr ref pl.polidea.treeview.R.styleable#TreeViewList_row_background
* </pre>
*/
public class TreeViewList extends ListView {
private static final int DEFAULT_COLLAPSED_RESOURCE = R.drawable.collapsed;
private static final int DEFAULT_EXPANDED_RESOURCE = R.drawable.expanded;
private static final int DEFAULT_INDENT = 0;
private static final int DEFAULT_GRAVITY = Gravity.LEFT
| Gravity.CENTER_VERTICAL;
private Drawable expandedDrawable;
private Drawable collapsedDrawable;
private Drawable rowBackgroundDrawable;
private Drawable indicatorBackgroundDrawable;
private int indentWidth = 0;
private int indicatorGravity = 0;
private AbstractTreeViewAdapter< ? > treeAdapter;
private boolean collapsible;
private boolean handleTrackballPress;
public TreeViewList(final Context context, final AttributeSet attrs) {
this(context, attrs, R.style.treeViewListStyle);
}
public TreeViewList(final Context context) {
this(context, null);
}
public TreeViewList(final Context context, final AttributeSet attrs,
final int defStyle) {
super(context, attrs, defStyle);
parseAttributes(context, attrs);
}
private void parseAttributes(final Context context, final AttributeSet attrs) {
final TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.TreeViewList);
expandedDrawable = a.getDrawable(R.styleable.TreeViewList_src_expanded);
if (expandedDrawable == null) {
expandedDrawable = context.getResources().getDrawable(
DEFAULT_EXPANDED_RESOURCE);
}
collapsedDrawable = a
.getDrawable(R.styleable.TreeViewList_src_collapsed);
if (collapsedDrawable == null) {
collapsedDrawable = context.getResources().getDrawable(
DEFAULT_COLLAPSED_RESOURCE);
}
indentWidth = a.getDimensionPixelSize(
R.styleable.TreeViewList_indent_width, DEFAULT_INDENT);
indicatorGravity = a.getInteger(
R.styleable.TreeViewList_indicator_gravity, DEFAULT_GRAVITY);
indicatorBackgroundDrawable = a
.getDrawable(R.styleable.TreeViewList_indicator_background);
rowBackgroundDrawable = a
.getDrawable(R.styleable.TreeViewList_row_background);
collapsible = a.getBoolean(R.styleable.TreeViewList_collapsible, true);
handleTrackballPress = a.getBoolean(
R.styleable.TreeViewList_handle_trackball_press, true);
}
@Override
public void setAdapter(final ListAdapter adapter) {
if (!(adapter instanceof AbstractTreeViewAdapter)) {
throw new TreeConfigurationException(
"The adapter is not of TreeViewAdapter type");
}
treeAdapter = (AbstractTreeViewAdapter< ? >) adapter;
syncAdapter();
super.setAdapter(treeAdapter);
}
private void syncAdapter() {
treeAdapter.setCollapsedDrawable(collapsedDrawable);
treeAdapter.setExpandedDrawable(expandedDrawable);
treeAdapter.setIndicatorGravity(indicatorGravity);
treeAdapter.setIndentWidth(indentWidth);
treeAdapter.setIndicatorBackgroundDrawable(indicatorBackgroundDrawable);
treeAdapter.setRowBackgroundDrawable(rowBackgroundDrawable);
treeAdapter.setCollapsible(collapsible);
if (handleTrackballPress) {
setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(final AdapterView< ? > parent,
final View view, final int position, final long id) {
treeAdapter.handleItemClick(view, view.getTag());
}
});
} else {
setOnClickListener(null);
}
}
public void setExpandedDrawable(final Drawable expandedDrawable) {
this.expandedDrawable = expandedDrawable;
syncAdapter();
treeAdapter.refresh();
}
public void setCollapsedDrawable(final Drawable collapsedDrawable) {
this.collapsedDrawable = collapsedDrawable;
syncAdapter();
treeAdapter.refresh();
}
public void setRowBackgroundDrawable(final Drawable rowBackgroundDrawable) {
this.rowBackgroundDrawable = rowBackgroundDrawable;
syncAdapter();
treeAdapter.refresh();
}
public void setIndicatorBackgroundDrawable(
final Drawable indicatorBackgroundDrawable) {
this.indicatorBackgroundDrawable = indicatorBackgroundDrawable;
syncAdapter();
treeAdapter.refresh();
}
public void setIndentWidth(final int indentWidth) {
this.indentWidth = indentWidth;
syncAdapter();
treeAdapter.refresh();
}
public void setIndicatorGravity(final int indicatorGravity) {
this.indicatorGravity = indicatorGravity;
syncAdapter();
treeAdapter.refresh();
}
public void setCollapsible(final boolean collapsible) {
this.collapsible = collapsible;
syncAdapter();
treeAdapter.refresh();
}
public void setHandleTrackballPress(final boolean handleTrackballPress) {
this.handleTrackballPress = handleTrackballPress;
syncAdapter();
treeAdapter.refresh();
}
public Drawable getExpandedDrawable() {
return expandedDrawable;
}
public Drawable getCollapsedDrawable() {
return collapsedDrawable;
}
public Drawable getRowBackgroundDrawable() {
return rowBackgroundDrawable;
}
public Drawable getIndicatorBackgroundDrawable() {
return indicatorBackgroundDrawable;
}
public int getIndentWidth() {
return indentWidth;
}
public int getIndicatorGravity() {
return indicatorGravity;
}
public boolean isCollapsible() {
return collapsible;
}
public boolean isHandleTrackballPress() {
return handleTrackballPress;
}
}
| Java |
package pl.polidea.treeview;
import android.app.Activity;
import android.content.Context;
import android.database.DataSetObserver;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
/**
* Adapter used to feed the table view.
*
* @param <T>
* class for ID of the tree
*/
public abstract class AbstractTreeViewAdapter<T> extends BaseAdapter implements
ListAdapter {
private static final String TAG = AbstractTreeViewAdapter.class
.getSimpleName();
private final TreeStateManager<T> treeStateManager;
private final int numberOfLevels;
private final LayoutInflater layoutInflater;
private int indentWidth = 0;
private int indicatorGravity = 0;
private Drawable collapsedDrawable;
private Drawable expandedDrawable;
private Drawable indicatorBackgroundDrawable;
private Drawable rowBackgroundDrawable;
private final OnClickListener indicatorClickListener = new OnClickListener() {
@Override
public void onClick(final View v) {
@SuppressWarnings("unchecked")
final T id = (T) v.getTag();
expandCollapse(id);
}
};
private boolean collapsible;
private final Activity activity;
public Activity getActivity() {
return activity;
}
protected TreeStateManager<T> getManager() {
return treeStateManager;
}
protected void expandCollapse(final T id) {
final TreeNodeInfo<T> info = treeStateManager.getNodeInfo(id);
if (!info.isWithChildren()) {
// ignore - no default action
return;
}
if (info.isExpanded()) {
treeStateManager.collapseChildren(id);
} else {
treeStateManager.expandDirectChildren(id);
}
}
private void calculateIndentWidth() {
if (expandedDrawable != null) {
indentWidth = Math.max(getIndentWidth(),
expandedDrawable.getIntrinsicWidth());
}
if (collapsedDrawable != null) {
indentWidth = Math.max(getIndentWidth(),
collapsedDrawable.getIntrinsicWidth());
}
}
public AbstractTreeViewAdapter(final Activity activity,
final TreeStateManager<T> treeStateManager, final int numberOfLevels) {
this.activity = activity;
this.treeStateManager = treeStateManager;
this.layoutInflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.numberOfLevels = numberOfLevels;
this.collapsedDrawable = null;
this.expandedDrawable = null;
this.rowBackgroundDrawable = null;
this.indicatorBackgroundDrawable = null;
}
@Override
public void registerDataSetObserver(final DataSetObserver observer) {
treeStateManager.registerDataSetObserver(observer);
}
@Override
public void unregisterDataSetObserver(final DataSetObserver observer) {
treeStateManager.unregisterDataSetObserver(observer);
}
@Override
public int getCount() {
return treeStateManager.getVisibleCount();
}
@Override
public Object getItem(final int position) {
return getTreeId(position);
}
public T getTreeId(final int position) {
return treeStateManager.getVisibleList().get(position);
}
public TreeNodeInfo<T> getTreeNodeInfo(final int position) {
return treeStateManager.getNodeInfo(getTreeId(position));
}
@Override
public boolean hasStableIds() { // NOPMD
return true;
}
@Override
public int getItemViewType(final int position) {
return getTreeNodeInfo(position).getLevel();
}
@Override
public int getViewTypeCount() {
return numberOfLevels;
}
@Override
public boolean isEmpty() {
return getCount() == 0;
}
@Override
public boolean areAllItemsEnabled() { // NOPMD
return true;
}
@Override
public boolean isEnabled(final int position) { // NOPMD
return true;
}
protected int getTreeListItemWrapperId() {
return R.layout.tree_list_item_wrapper;
}
@Override
public final View getView(final int position, final View convertView,
final ViewGroup parent) {
Log.d(TAG, "Creating a view based on " + convertView
+ " with position " + position);
final TreeNodeInfo<T> nodeInfo = getTreeNodeInfo(position);
if (convertView == null) {
Log.d(TAG, "Creating the view a new");
final LinearLayout layout = (LinearLayout) layoutInflater.inflate(
getTreeListItemWrapperId(), null);
return populateTreeItem(layout, getNewChildView(nodeInfo),
nodeInfo, true);
} else {
Log.d(TAG, "Reusing the view");
final LinearLayout linear = (LinearLayout) convertView;
final FrameLayout frameLayout = (FrameLayout) linear
.findViewById(R.id.treeview_list_item_frame);
final View childView = frameLayout.getChildAt(0);
updateView(childView, nodeInfo);
return populateTreeItem(linear, childView, nodeInfo, false);
}
}
/**
* Called when new view is to be created.
*
* @param treeNodeInfo
* node info
* @return view that should be displayed as tree content
*/
public abstract View getNewChildView(TreeNodeInfo<T> treeNodeInfo);
/**
* Called when new view is going to be reused. You should update the view
* and fill it in with the data required to display the new information. You
* can also create a new view, which will mean that the old view will not be
* reused.
*
* @param view
* view that should be updated with the new values
* @param treeNodeInfo
* node info used to populate the view
* @return view to used as row indented content
*/
public abstract View updateView(View view, TreeNodeInfo<T> treeNodeInfo);
/**
* Retrieves background drawable for the node.
*
* @param treeNodeInfo
* node info
* @return drawable returned as background for the whole row. Might be null,
* then default background is used
*/
public Drawable getBackgroundDrawable(final TreeNodeInfo<T> treeNodeInfo) { // NOPMD
return null;
}
private Drawable getDrawableOrDefaultBackground(final Drawable r) {
if (r == null) {
return activity.getResources()
.getDrawable(R.drawable.list_selector_background).mutate();
} else {
return r;
}
}
public final LinearLayout populateTreeItem(final LinearLayout layout,
final View childView, final TreeNodeInfo<T> nodeInfo,
final boolean newChildView) {
final Drawable individualRowDrawable = getBackgroundDrawable(nodeInfo);
layout.setBackgroundDrawable(individualRowDrawable == null ? getDrawableOrDefaultBackground(rowBackgroundDrawable)
: individualRowDrawable);
final LinearLayout.LayoutParams indicatorLayoutParams = new LinearLayout.LayoutParams(
calculateIndentation(nodeInfo), LayoutParams.FILL_PARENT);
final LinearLayout indicatorLayout = (LinearLayout) layout
.findViewById(R.id.treeview_list_item_image_layout);
indicatorLayout.setGravity(indicatorGravity);
indicatorLayout.setLayoutParams(indicatorLayoutParams);
final ImageView image = (ImageView) layout
.findViewById(R.id.treeview_list_item_image);
image.setImageDrawable(getDrawable(nodeInfo));
image.setBackgroundDrawable(getDrawableOrDefaultBackground(indicatorBackgroundDrawable));
image.setScaleType(ScaleType.CENTER);
image.setTag(nodeInfo.getId());
if (nodeInfo.isWithChildren() && collapsible) {
image.setOnClickListener(indicatorClickListener);
} else {
image.setOnClickListener(null);
}
layout.setTag(nodeInfo.getId());
final FrameLayout frameLayout = (FrameLayout) layout
.findViewById(R.id.treeview_list_item_frame);
final FrameLayout.LayoutParams childParams = new FrameLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
if (newChildView) {
frameLayout.addView(childView, childParams);
}
frameLayout.setTag(nodeInfo.getId());
return layout;
}
protected int calculateIndentation(final TreeNodeInfo<T> nodeInfo) {
return getIndentWidth() * (nodeInfo.getLevel() + (collapsible ? 1 : 0));
}
protected Drawable getDrawable(final TreeNodeInfo<T> nodeInfo) {
if (!nodeInfo.isWithChildren() || !collapsible) {
return getDrawableOrDefaultBackground(indicatorBackgroundDrawable);
}
if (nodeInfo.isExpanded()) {
return expandedDrawable;
} else {
return collapsedDrawable;
}
}
public void setIndicatorGravity(final int indicatorGravity) {
this.indicatorGravity = indicatorGravity;
}
public void setCollapsedDrawable(final Drawable collapsedDrawable) {
this.collapsedDrawable = collapsedDrawable;
calculateIndentWidth();
}
public void setExpandedDrawable(final Drawable expandedDrawable) {
this.expandedDrawable = expandedDrawable;
calculateIndentWidth();
}
public void setIndentWidth(final int indentWidth) {
this.indentWidth = indentWidth;
calculateIndentWidth();
}
public void setRowBackgroundDrawable(final Drawable rowBackgroundDrawable) {
this.rowBackgroundDrawable = rowBackgroundDrawable;
}
public void setIndicatorBackgroundDrawable(
final Drawable indicatorBackgroundDrawable) {
this.indicatorBackgroundDrawable = indicatorBackgroundDrawable;
}
public void setCollapsible(final boolean collapsible) {
this.collapsible = collapsible;
}
public void refresh() {
treeStateManager.refresh();
}
private int getIndentWidth() {
return indentWidth;
}
@SuppressWarnings("unchecked")
public void handleItemClick(final View view, final Object id) {
expandCollapse((T) id);
}
}
| Java |
package pl.polidea.treeview;
/**
* This exception is thrown when the tree does not contain node requested.
*
*/
public class NodeNotInTreeException extends RuntimeException {
private static final long serialVersionUID = 1L;
public NodeNotInTreeException(final String id) {
super("The tree does not contain the node specified: " + id);
}
}
| Java |
/**
* Provides expandable Tree View implementation.
*/
package pl.polidea.treeview; | Java |
package pl.polidea.treeview;
import android.util.Log;
/**
* Allows to build tree easily in sequential mode (you have to know levels of
* all the tree elements upfront). You should rather use this class rather than
* manager if you build initial tree from some external data source.
* <p>
* Note, that all ids must be unique. IDs are used to find nodes in the whole
* tree, so they cannot repeat even if they are in different
* sub-trees.
*
* @param <T>
*/
public class TreeBuilder<T> {
private static final String TAG = TreeBuilder.class.getSimpleName();
private final TreeStateManager<T> manager;
private T lastAddedId = null;
private int lastLevel = -1;
public TreeBuilder(final TreeStateManager<T> manager) {
this.manager = manager;
}
public void clear() {
manager.clear();
lastAddedId = null;
lastLevel = -1;
}
/**
* Adds new relation to existing tree. Child is set as the last child of the
* parent node. Parent has to already exist in the tree, child cannot yet
* exist. This method is mostly useful in case you add entries layer by
* layer - i.e. first top level entries, then children for all parents, then
* grand-children and so on.
*
* @param parent
* parent id
* @param child
* child id
*/
public synchronized void addRelation(final T parent, final T child) {
Log.d(TAG, "Adding relation parent:" + parent + " -> child: " + child);
manager.addAfterChild(parent, child, null);
lastAddedId = child;
lastLevel = manager.getLevel(child);
}
/**
* Adds sequentially new node. Using this method is the simplest way of
* building tree - if you have all the elements in the sequence as they
* should be displayed in fully-expanded tree. You can combine it with add
* relation - for example you can add information about few levels using
* {@link addRelation} and then after the right level is added as parent,
* you can continue adding them using sequential operation.
*
* @param id
* id of the node
* @param level
* its level
*/
public synchronized void sequentiallyAddNextNode(final T id, final int level) {
Log.d(TAG, "Adding sequentiall node " + id + " at level " + level);
if (lastAddedId == null) {
addNodeToParentOneLevelDown(null, id, level);
} else {
if (level <= lastLevel) {
final T parent = findParentAtLevel(lastAddedId, level - 1);
addNodeToParentOneLevelDown(parent, id, level);
} else {
addNodeToParentOneLevelDown(lastAddedId, id, level);
}
}
}
/**
* Find parent of the node at the level specified.
*
* @param node
* node from which we start
* @param levelToFind
* level which we are looking for
* @return the node found (null if it is topmost node).
*/
private T findParentAtLevel(final T node, final int levelToFind) {
T parent = manager.getParent(node);
while (parent != null) {
if (manager.getLevel(parent) == levelToFind) {
break;
}
parent = manager.getParent(parent);
}
return parent;
}
/**
* Adds note to parent at the level specified. But it verifies that the
* level is one level down than the parent!
*
* @param parent
* parent parent
* @param id
* new node id
* @param level
* should always be parent's level + 1
*/
private void addNodeToParentOneLevelDown(final T parent, final T id,
final int level) {
if (parent == null && level != 0) {
throw new TreeConfigurationException("Trying to add new id " + id
+ " to top level with level != 0 (" + level + ")");
}
if (parent != null && manager.getLevel(parent) != level - 1) {
throw new TreeConfigurationException("Trying to add new id " + id
+ " <" + level + "> to " + parent + " <"
+ manager.getLevel(parent)
+ ">. The difference in levels up is bigger than 1.");
}
manager.addAfterChild(parent, id, null);
setLastAdded(id, level);
}
private void setLastAdded(final T id, final int level) {
lastAddedId = id;
lastLevel = level;
}
}
| Java |
package pl.polidea.treeview;
/**
* Exception thrown when there is a problem with configuring tree.
*
*/
public class TreeConfigurationException extends RuntimeException {
private static final long serialVersionUID = 1L;
public TreeConfigurationException(final String detailMessage) {
super(detailMessage);
}
}
| Java |
package pl.polidea.treeview;
/**
* The node being added is already in the tree.
*
*/
public class NodeAlreadyInTreeException extends RuntimeException {
private static final long serialVersionUID = 1L;
public NodeAlreadyInTreeException(final String id, final String oldNode) {
super("The node has already been added to the tree: " + id + ". Old node is:" + oldNode);
}
}
| Java |
package pl.polidea.treeview;
/**
* Information about the node.
*
* @param <T>
* type of the id for the tree
*/
public class TreeNodeInfo<T> {
private final T id;
private final int level;
private final boolean withChildren;
private final boolean visible;
private final boolean expanded;
/**
* Creates the node information.
*
* @param id
* id of the node
* @param level
* level of the node
* @param withChildren
* whether the node has children.
* @param visible
* whether the tree node is visible.
* @param expanded
* whether the tree node is expanded
*
*/
public TreeNodeInfo(final T id, final int level,
final boolean withChildren, final boolean visible,
final boolean expanded) {
super();
this.id = id;
this.level = level;
this.withChildren = withChildren;
this.visible = visible;
this.expanded = expanded;
}
public T getId() {
return id;
}
public boolean isWithChildren() {
return withChildren;
}
public boolean isVisible() {
return visible;
}
public boolean isExpanded() {
return expanded;
}
public int getLevel() {
return level;
}
@Override
public String toString() {
return "TreeNodeInfo [id=" + id + ", level=" + level
+ ", withChildren=" + withChildren + ", visible=" + visible
+ ", expanded=" + expanded + "]";
}
} | Java |
package pl.polidea.treeview;
import java.io.Serializable;
import java.util.List;
import android.database.DataSetObserver;
/**
* Manages information about state of the tree. It only keeps information about
* tree elements, not the elements themselves.
*
* @param <T>
* type of the identifier for nodes in the tree
*/
public interface TreeStateManager<T> extends Serializable {
/**
* Returns array of integers showing the location of the node in hierarchy.
* It corresponds to heading numbering. {0,0,0} in 3 level node is the first
* node {0,0,1} is second leaf (assuming that there are two leaves in first
* subnode of the first node).
*
* @param id
* id of the node
* @return textual description of the hierarchy in tree for the node.
*/
Integer[] getHierarchyDescription(T id);
/**
* Returns level of the node.
*
* @param id
* id of the node
* @return level in the tree
*/
int getLevel(T id);
/**
* Returns information about the node.
*
* @param id
* node id
* @return node info
*/
TreeNodeInfo<T> getNodeInfo(T id);
/**
* Returns children of the node.
*
* @param id
* id of the node or null if asking for top nodes
* @return children of the node
*/
List<T> getChildren(T id);
/**
* Returns parent of the node.
*
* @param id
* id of the node
* @return parent id or null if no parent
*/
T getParent(T id);
/**
* Adds the node before child or at the beginning.
*
* @param parent
* id of the parent node. If null - adds at the top level
* @param newChild
* new child to add if null - adds at the beginning.
* @param beforeChild
* child before which to add the new child
*/
void addBeforeChild(T parent, T newChild, T beforeChild);
/**
* Adds the node after child or at the end.
*
* @param parent
* id of the parent node. If null - adds at the top level.
* @param newChild
* new child to add. If null - adds at the end.
* @param afterChild
* child after which to add the new child
*/
void addAfterChild(T parent, T newChild, T afterChild);
/**
* Removes the node and all children from the tree.
*
* @param id
* id of the node to remove or null if all nodes are to be
* removed.
*/
void removeNodeRecursively(T id);
/**
* Expands all children of the node.
*
* @param id
* node which children should be expanded. cannot be null (top
* nodes are always expanded!).
*/
void expandDirectChildren(T id);
/**
* Expands everything below the node specified. Might be null - then expands
* all.
*
* @param id
* node which children should be expanded or null if all nodes
* are to be expanded.
*/
void expandEverythingBelow(T id);
/**
* Collapse children.
*
* @param id
* id collapses everything below node specified. If null,
* collapses everything but top-level nodes.
*/
void collapseChildren(T id);
/**
* Returns next sibling of the node (or null if no further sibling).
*
* @param id
* node id
* @return the sibling (or null if no next)
*/
T getNextSibling(T id);
/**
* Returns previous sibling of the node (or null if no previous sibling).
*
* @param id
* node id
* @return the sibling (or null if no previous)
*/
T getPreviousSibling(T id);
/**
* Checks if given node is already in tree.
*
* @param id
* id of the node
* @return true if node is already in tree.
*/
boolean isInTree(T id);
/**
* Count visible elements.
*
* @return number of currently visible elements.
*/
int getVisibleCount();
/**
* Returns visible node list.
*
* @return return the list of all visible nodes in the right sequence
*/
List<T> getVisibleList();
/**
* Registers observers with the manager.
*
* @param observer
* observer
*/
void registerDataSetObserver(final DataSetObserver observer);
/**
* Unregisters observers with the manager.
*
* @param observer
* observer
*/
void unregisterDataSetObserver(final DataSetObserver observer);
/**
* Cleans tree stored in manager. After this operation the tree is empty.
*
*/
void clear();
/**
* Refreshes views connected to the manager.
*/
void refresh();
}
| Java |
package pl.polidea.treeview;
import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;
/**
* Node. It is package protected so that it cannot be used outside.
*
* @param <T>
* type of the identifier used by the tree
*/
class InMemoryTreeNode<T> implements Serializable {
private static final long serialVersionUID = 1L;
private final T id;
private final T parent;
private final int level;
private boolean visible = true;
private final List<InMemoryTreeNode<T>> children = new LinkedList<InMemoryTreeNode<T>>();
private List<T> childIdListCache = null;
public InMemoryTreeNode(final T id, final T parent, final int level,
final boolean visible) {
super();
this.id = id;
this.parent = parent;
this.level = level;
this.visible = visible;
}
public int indexOf(final T id) {
return getChildIdList().indexOf(id);
}
/**
* Cache is built lasily only if needed. The cache is cleaned on any
* structure change for that node!).
*
* @return list of ids of children
*/
public synchronized List<T> getChildIdList() {
if (childIdListCache == null) {
childIdListCache = new LinkedList<T>();
for (final InMemoryTreeNode<T> n : children) {
childIdListCache.add(n.getId());
}
}
return childIdListCache;
}
public boolean isVisible() {
return visible;
}
public void setVisible(final boolean visible) {
this.visible = visible;
}
public int getChildrenListSize() {
return children.size();
}
public synchronized InMemoryTreeNode<T> add(final int index, final T child,
final boolean visible) {
childIdListCache = null;
// Note! top levell children are always visible (!)
final InMemoryTreeNode<T> newNode = new InMemoryTreeNode<T>(child,
getId(), getLevel() + 1, getId() == null ? true : visible);
children.add(index, newNode);
return newNode;
}
/**
* Note. This method should technically return unmodifiable collection, but
* for performance reason on small devices we do not do it.
*
* @return children list
*/
public List<InMemoryTreeNode<T>> getChildren() {
return children;
}
public synchronized void clearChildren() {
children.clear();
childIdListCache = null;
}
public synchronized void removeChild(final T child) {
final int childIndex = indexOf(child);
if (childIndex != -1) {
children.remove(childIndex);
childIdListCache = null;
}
}
@Override
public String toString() {
return "InMemoryTreeNode [id=" + getId() + ", parent=" + getParent()
+ ", level=" + getLevel() + ", visible=" + visible
+ ", children=" + children + ", childIdListCache="
+ childIdListCache + "]";
}
T getId() {
return id;
}
T getParent() {
return parent;
}
int getLevel() {
return level;
}
} | Java |
package pl.polidea.treeview;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import android.database.DataSetObserver;
import android.util.Log;
/**
* In-memory manager of tree state.
*
* @param <T>
* type of identifier
*/
public class InMemoryTreeStateManager<T> implements TreeStateManager<T> {
private static final String TAG = InMemoryTreeStateManager.class
.getSimpleName();
private static final long serialVersionUID = 1L;
private final Map<T, InMemoryTreeNode<T>> allNodes = new HashMap<T, InMemoryTreeNode<T>>();
private final InMemoryTreeNode<T> topSentinel = new InMemoryTreeNode<T>(
null, null, -1, true);
private transient List<T> visibleListCache = null; // lasy initialised
private transient List<T> unmodifiableVisibleList = null;
private boolean visibleByDefault = true;
private final transient Set<DataSetObserver> observers = new HashSet<DataSetObserver>();
private synchronized void internalDataSetChanged() {
visibleListCache = null;
unmodifiableVisibleList = null;
for (final DataSetObserver observer : observers) {
observer.onChanged();
}
}
/**
* If true new nodes are visible by default.
*
* @param visibleByDefault
* if true, then newly added nodes are expanded by default
*/
public void setVisibleByDefault(final boolean visibleByDefault) {
this.visibleByDefault = visibleByDefault;
}
private InMemoryTreeNode<T> getNodeFromTreeOrThrow(final T id) {
if (id == null) {
throw new NodeNotInTreeException("(null)");
}
final InMemoryTreeNode<T> node = allNodes.get(id);
if (node == null) {
throw new NodeNotInTreeException(id.toString());
}
return node;
}
private InMemoryTreeNode<T> getNodeFromTreeOrThrowAllowRoot(final T id) {
if (id == null) {
return topSentinel;
}
return getNodeFromTreeOrThrow(id);
}
private void expectNodeNotInTreeYet(final T id) {
final InMemoryTreeNode<T> node = allNodes.get(id);
if (node != null) {
throw new NodeAlreadyInTreeException(id.toString(), node.toString());
}
}
@Override
public synchronized TreeNodeInfo<T> getNodeInfo(final T id) {
final InMemoryTreeNode<T> node = getNodeFromTreeOrThrow(id);
final List<InMemoryTreeNode<T>> children = node.getChildren();
boolean expanded = false;
if (!children.isEmpty() && children.get(0).isVisible()) {
expanded = true;
}
return new TreeNodeInfo<T>(id, node.getLevel(), !children.isEmpty(),
node.isVisible(), expanded);
}
@Override
public synchronized List<T> getChildren(final T id) {
final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(id);
return node.getChildIdList();
}
@Override
public synchronized T getParent(final T id) {
final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(id);
return node.getParent();
}
private boolean getChildrenVisibility(final InMemoryTreeNode<T> node) {
boolean visibility;
final List<InMemoryTreeNode<T>> children = node.getChildren();
if (children.isEmpty()) {
visibility = visibleByDefault;
} else {
visibility = children.get(0).isVisible();
}
return visibility;
}
@Override
public synchronized void addBeforeChild(final T parent, final T newChild,
final T beforeChild) {
expectNodeNotInTreeYet(newChild);
final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(parent);
final boolean visibility = getChildrenVisibility(node);
// top nodes are always expanded.
if (beforeChild == null) {
final InMemoryTreeNode<T> added = node.add(0, newChild, visibility);
allNodes.put(newChild, added);
} else {
final int index = node.indexOf(beforeChild);
final InMemoryTreeNode<T> added = node.add(index == -1 ? 0 : index,
newChild, visibility);
allNodes.put(newChild, added);
}
if (visibility) {
internalDataSetChanged();
}
}
@Override
public synchronized void addAfterChild(final T parent, final T newChild,
final T afterChild) {
expectNodeNotInTreeYet(newChild);
final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(parent);
final boolean visibility = getChildrenVisibility(node);
if (afterChild == null) {
final InMemoryTreeNode<T> added = node.add(
node.getChildrenListSize(), newChild, visibility);
allNodes.put(newChild, added);
} else {
final int index = node.indexOf(afterChild);
final InMemoryTreeNode<T> added = node.add(
index == -1 ? node.getChildrenListSize() : index + 1, newChild,
visibility);
allNodes.put(newChild, added);
}
if (visibility) {
internalDataSetChanged();
}
}
@Override
public synchronized void removeNodeRecursively(final T id) {
final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(id);
final boolean visibleNodeChanged = removeNodeRecursively(node);
final T parent = node.getParent();
final InMemoryTreeNode<T> parentNode = getNodeFromTreeOrThrowAllowRoot(parent);
parentNode.removeChild(id);
if (visibleNodeChanged) {
internalDataSetChanged();
}
}
private boolean removeNodeRecursively(final InMemoryTreeNode<T> node) {
boolean visibleNodeChanged = false;
for (final InMemoryTreeNode<T> child : node.getChildren()) {
if (removeNodeRecursively(child)) {
visibleNodeChanged = true;
}
}
node.clearChildren();
if (node.getId() != null) {
allNodes.remove(node.getId());
if (node.isVisible()) {
visibleNodeChanged = true;
}
}
return visibleNodeChanged;
}
private void setChildrenVisibility(final InMemoryTreeNode<T> node,
final boolean visible, final boolean recursive) {
for (final InMemoryTreeNode<T> child : node.getChildren()) {
child.setVisible(visible);
if (recursive) {
setChildrenVisibility(child, visible, true);
}
}
}
@Override
public synchronized void expandDirectChildren(final T id) {
Log.d(TAG, "Expanding direct children of " + id);
final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(id);
setChildrenVisibility(node, true, false);
internalDataSetChanged();
}
@Override
public synchronized void expandEverythingBelow(final T id) {
Log.d(TAG, "Expanding all children below " + id);
final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(id);
setChildrenVisibility(node, true, true);
internalDataSetChanged();
}
@Override
public synchronized void collapseChildren(final T id) {
final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(id);
if (node == topSentinel) {
for (final InMemoryTreeNode<T> n : topSentinel.getChildren()) {
setChildrenVisibility(n, false, true);
}
} else {
setChildrenVisibility(node, false, true);
}
internalDataSetChanged();
}
@Override
public synchronized T getNextSibling(final T id) {
final T parent = getParent(id);
final InMemoryTreeNode<T> parentNode = getNodeFromTreeOrThrowAllowRoot(parent);
boolean returnNext = false;
for (final InMemoryTreeNode<T> child : parentNode.getChildren()) {
if (returnNext) {
return child.getId();
}
if (child.getId().equals(id)) {
returnNext = true;
}
}
return null;
}
@Override
public synchronized T getPreviousSibling(final T id) {
final T parent = getParent(id);
final InMemoryTreeNode<T> parentNode = getNodeFromTreeOrThrowAllowRoot(parent);
T previousSibling = null;
for (final InMemoryTreeNode<T> child : parentNode.getChildren()) {
if (child.getId().equals(id)) {
return previousSibling;
}
previousSibling = child.getId();
}
return null;
}
@Override
public synchronized boolean isInTree(final T id) {
return allNodes.containsKey(id);
}
@Override
public synchronized int getVisibleCount() {
return getVisibleList().size();
}
@Override
public synchronized List<T> getVisibleList() {
T currentId = null;
if (visibleListCache == null) {
visibleListCache = new ArrayList<T>(allNodes.size());
do {
currentId = getNextVisible(currentId);
if (currentId == null) {
break;
} else {
visibleListCache.add(currentId);
}
} while (true);
}
if (unmodifiableVisibleList == null) {
unmodifiableVisibleList = Collections
.unmodifiableList(visibleListCache);
}
return unmodifiableVisibleList;
}
public synchronized T getNextVisible(final T id) {
final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(id);
if (!node.isVisible()) {
return null;
}
final List<InMemoryTreeNode<T>> children = node.getChildren();
if (!children.isEmpty()) {
final InMemoryTreeNode<T> firstChild = children.get(0);
if (firstChild.isVisible()) {
return firstChild.getId();
}
}
final T sibl = getNextSibling(id);
if (sibl != null) {
return sibl;
}
T parent = node.getParent();
do {
if (parent == null) {
return null;
}
final T parentSibling = getNextSibling(parent);
if (parentSibling != null) {
return parentSibling;
}
parent = getNodeFromTreeOrThrow(parent).getParent();
} while (true);
}
@Override
public synchronized void registerDataSetObserver(
final DataSetObserver observer) {
observers.add(observer);
}
@Override
public synchronized void unregisterDataSetObserver(
final DataSetObserver observer) {
observers.remove(observer);
}
@Override
public int getLevel(final T id) {
return getNodeFromTreeOrThrow(id).getLevel();
}
@Override
public Integer[] getHierarchyDescription(final T id) {
final int level = getLevel(id);
final Integer[] hierarchy = new Integer[level + 1];
int currentLevel = level;
T currentId = id;
T parent = getParent(currentId);
while (currentLevel >= 0) {
hierarchy[currentLevel--] = getChildren(parent).indexOf(currentId);
currentId = parent;
parent = getParent(parent);
}
return hierarchy;
}
private void appendToSb(final StringBuilder sb, final T id) {
if (id != null) {
final TreeNodeInfo<T> node = getNodeInfo(id);
final int indent = node.getLevel() * 4;
final char[] indentString = new char[indent];
Arrays.fill(indentString, ' ');
sb.append(indentString);
sb.append(node.toString());
sb.append(Arrays.asList(getHierarchyDescription(id)).toString());
sb.append("\n");
}
final List<T> children = getChildren(id);
for (final T child : children) {
appendToSb(sb, child);
}
}
@Override
public synchronized String toString() {
final StringBuilder sb = new StringBuilder();
appendToSb(sb, null);
return sb.toString();
}
@Override
public synchronized void clear() {
allNodes.clear();
topSentinel.clearChildren();
internalDataSetChanged();
}
@Override
public void refresh() {
internalDataSetChanged();
}
}
| Java |
package pl.polidea.treeview.demo;
import java.util.Arrays;
import java.util.Set;
import pl.polidea.treeview.AbstractTreeViewAdapter;
import pl.polidea.treeview.R;
import pl.polidea.treeview.TreeNodeInfo;
import pl.polidea.treeview.TreeStateManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
* This is a very simple adapter that provides very basic tree view with a
* checkboxes and simple item description.
*
*/
class SimpleStandardAdapter extends AbstractTreeViewAdapter<Long> {
private final Set<Long> selected;
private final OnCheckedChangeListener onCheckedChange = new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(final CompoundButton buttonView,
final boolean isChecked) {
final Long id = (Long) buttonView.getTag();
changeSelected(isChecked, id);
}
};
private void changeSelected(final boolean isChecked, final Long id) {
if (isChecked) {
selected.add(id);
} else {
selected.remove(id);
}
}
public SimpleStandardAdapter(final TreeViewListDemo treeViewListDemo,
final Set<Long> selected,
final TreeStateManager<Long> treeStateManager,
final int numberOfLevels) {
super(treeViewListDemo, treeStateManager, numberOfLevels);
this.selected = selected;
}
private String getDescription(final long id) {
final Integer[] hierarchy = getManager().getHierarchyDescription(id);
return "Node " + id + Arrays.asList(hierarchy);
}
@Override
public View getNewChildView(final TreeNodeInfo<Long> treeNodeInfo) {
final LinearLayout viewLayout = (LinearLayout) getActivity()
.getLayoutInflater().inflate(R.layout.demo_list_item, null);
return updateView(viewLayout, treeNodeInfo);
}
@Override
public LinearLayout updateView(final View view,
final TreeNodeInfo<Long> treeNodeInfo) {
final LinearLayout viewLayout = (LinearLayout) view;
final TextView descriptionView = (TextView) viewLayout
.findViewById(R.id.demo_list_item_description);
final TextView levelView = (TextView) viewLayout
.findViewById(R.id.demo_list_item_level);
descriptionView.setText(getDescription(treeNodeInfo.getId()));
levelView.setText(Integer.toString(treeNodeInfo.getLevel()));
final CheckBox box = (CheckBox) viewLayout
.findViewById(R.id.demo_list_checkbox);
box.setTag(treeNodeInfo.getId());
if (treeNodeInfo.isWithChildren()) {
box.setVisibility(View.GONE);
} else {
box.setVisibility(View.VISIBLE);
box.setChecked(selected.contains(treeNodeInfo.getId()));
}
box.setOnCheckedChangeListener(onCheckedChange);
return viewLayout;
}
@Override
public void handleItemClick(final View view, final Object id) {
final Long longId = (Long) id;
final TreeNodeInfo<Long> info = getManager().getNodeInfo(longId);
if (info.isWithChildren()) {
super.handleItemClick(view, id);
} else {
final ViewGroup vg = (ViewGroup) view;
final CheckBox cb = (CheckBox) vg
.findViewById(R.id.demo_list_checkbox);
cb.performClick();
}
}
@Override
public long getItemId(final int position) {
return getTreeId(position);
}
} | Java |
package pl.polidea.treeview.demo;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import pl.polidea.treeview.InMemoryTreeStateManager;
import pl.polidea.treeview.R;
import pl.polidea.treeview.TreeBuilder;
import pl.polidea.treeview.TreeNodeInfo;
import pl.polidea.treeview.TreeStateManager;
import pl.polidea.treeview.TreeViewList;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView.AdapterContextMenuInfo;
/**
* Demo activity showing how the tree view can be used.
*
*/
public class TreeViewListDemo extends Activity {
private enum TreeType implements Serializable {
SIMPLE,
FANCY
}
private final Set<Long> selected = new HashSet<Long>();
private static final String TAG = TreeViewListDemo.class.getSimpleName();
private TreeViewList treeView;
private static final int[] DEMO_NODES = new int[] { 0, 0, 1, 1, 1, 2, 2, 1,
1, 2, 1, 0, 0, 0, 1, 2, 3, 2, 0, 0, 1, 2, 0, 1, 2, 0, 1 };
private static final int LEVEL_NUMBER = 4;
private TreeStateManager<Long> manager = null;
private FancyColouredVariousSizesAdapter fancyAdapter;
private SimpleStandardAdapter simpleAdapter;
private TreeType treeType;
private boolean collapsible;
@SuppressWarnings("unchecked")
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TreeType newTreeType = null;
boolean newCollapsible;
if (savedInstanceState == null) {
manager = new InMemoryTreeStateManager<Long>();
final TreeBuilder<Long> treeBuilder = new TreeBuilder<Long>(manager);
for (int i = 0; i < DEMO_NODES.length; i++) {
treeBuilder.sequentiallyAddNextNode((long) i, DEMO_NODES[i]);
}
Log.d(TAG, manager.toString());
newTreeType = TreeType.SIMPLE;
newCollapsible = true;
} else {
manager = (TreeStateManager<Long>) savedInstanceState
.getSerializable("treeManager");
if (manager == null) {
manager = new InMemoryTreeStateManager<Long>();
}
newTreeType = (TreeType) savedInstanceState
.getSerializable("treeType");
if (newTreeType == null) {
newTreeType = TreeType.SIMPLE;
}
newCollapsible = savedInstanceState.getBoolean("collapsible");
}
setContentView(R.layout.main_demo);
treeView = (TreeViewList) findViewById(R.id.mainTreeView);
fancyAdapter = new FancyColouredVariousSizesAdapter(this, selected,
manager, LEVEL_NUMBER);
simpleAdapter = new SimpleStandardAdapter(this, selected, manager,
LEVEL_NUMBER);
setTreeAdapter(newTreeType);
setCollapsible(newCollapsible);
registerForContextMenu(treeView);
}
@Override
protected void onSaveInstanceState(final Bundle outState) {
outState.putSerializable("treeManager", manager);
outState.putSerializable("treeType", treeType);
outState.putBoolean("collapsible", this.collapsible);
super.onSaveInstanceState(outState);
}
protected final void setTreeAdapter(final TreeType newTreeType) {
this.treeType = newTreeType;
switch (newTreeType) {
case SIMPLE:
treeView.setAdapter(simpleAdapter);
break;
case FANCY:
treeView.setAdapter(fancyAdapter);
break;
default:
treeView.setAdapter(simpleAdapter);
}
}
protected final void setCollapsible(final boolean newCollapsible) {
this.collapsible = newCollapsible;
treeView.setCollapsible(this.collapsible);
}
@Override
public boolean onCreateOptionsMenu(final Menu menu) {
final MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
@Override
public boolean onPrepareOptionsMenu(final Menu menu) {
final MenuItem collapsibleMenu = menu
.findItem(R.id.collapsible_menu_item);
if (collapsible) {
collapsibleMenu.setTitle(R.string.collapsible_menu_disable);
collapsibleMenu.setTitleCondensed(getResources().getString(
R.string.collapsible_condensed_disable));
} else {
collapsibleMenu.setTitle(R.string.collapsible_menu_enable);
collapsibleMenu.setTitleCondensed(getResources().getString(
R.string.collapsible_condensed_enable));
}
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
if (item.getItemId() == R.id.simple_menu_item) {
setTreeAdapter(TreeType.SIMPLE);
} else if (item.getItemId() == R.id.fancy_menu_item) {
setTreeAdapter(TreeType.FANCY);
} else if (item.getItemId() == R.id.collapsible_menu_item) {
setCollapsible(!this.collapsible);
} else if (item.getItemId() == R.id.expand_all_menu_item) {
manager.expandEverythingBelow(null);
} else if (item.getItemId() == R.id.collapse_all_menu_item) {
manager.collapseChildren(null);
} else {
return false;
}
return true;
}
@Override
public void onCreateContextMenu(final ContextMenu menu, final View v,
final ContextMenuInfo menuInfo) {
final AdapterContextMenuInfo adapterInfo = (AdapterContextMenuInfo) menuInfo;
final long id = adapterInfo.id;
final TreeNodeInfo<Long> info = manager.getNodeInfo(id);
final MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.context_menu, menu);
if (info.isWithChildren()) {
if (info.isExpanded()) {
menu.findItem(R.id.context_menu_expand_item).setVisible(false);
menu.findItem(R.id.context_menu_expand_all).setVisible(false);
} else {
menu.findItem(R.id.context_menu_collapse).setVisible(false);
}
} else {
menu.findItem(R.id.context_menu_expand_item).setVisible(false);
menu.findItem(R.id.context_menu_expand_all).setVisible(false);
menu.findItem(R.id.context_menu_collapse).setVisible(false);
}
super.onCreateContextMenu(menu, v, menuInfo);
}
@Override
public boolean onContextItemSelected(final MenuItem item) {
final AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
final long id = info.id;
if (item.getItemId() == R.id.context_menu_collapse) {
manager.collapseChildren(id);
return true;
} else if (item.getItemId() == R.id.context_menu_expand_all) {
manager.expandEverythingBelow(id);
return true;
} else if (item.getItemId() == R.id.context_menu_expand_item) {
manager.expandDirectChildren(id);
return true;
} else if (item.getItemId() == R.id.context_menu_delete) {
manager.removeNodeRecursively(id);
return true;
} else {
return super.onContextItemSelected(item);
}
}
} | Java |
/**
* Provides just demo of the TreeView widget.
*/
package pl.polidea.treeview.demo; | Java |
package pl.polidea.treeview.demo;
import java.util.Set;
import pl.polidea.treeview.R;
import pl.polidea.treeview.TreeNodeInfo;
import pl.polidea.treeview.TreeStateManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
final class FancyColouredVariousSizesAdapter extends SimpleStandardAdapter {
public FancyColouredVariousSizesAdapter(final TreeViewListDemo activity,
final Set<Long> selected,
final TreeStateManager<Long> treeStateManager,
final int numberOfLevels) {
super(activity, selected, treeStateManager, numberOfLevels);
}
@Override
public LinearLayout updateView(final View view,
final TreeNodeInfo<Long> treeNodeInfo) {
final LinearLayout viewLayout = super.updateView(view, treeNodeInfo);
final TextView descriptionView = (TextView) viewLayout
.findViewById(R.id.demo_list_item_description);
final TextView levelView = (TextView) viewLayout
.findViewById(R.id.demo_list_item_level);
descriptionView.setTextSize(20 - 2 * treeNodeInfo.getLevel());
levelView.setTextSize(20 - 2 * treeNodeInfo.getLevel());
return viewLayout;
}
@Override
public Drawable getBackgroundDrawable(final TreeNodeInfo<Long> treeNodeInfo) {
switch (treeNodeInfo.getLevel()) {
case 0:
return new ColorDrawable(Color.WHITE);
case 1:
return new ColorDrawable(Color.GRAY);
case 2:
return new ColorDrawable(Color.YELLOW);
default:
return null;
}
}
} | Java |
package edu.mit.csail.sls.wami;
import java.util.Map;
import javax.servlet.http.HttpSession;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import edu.mit.csail.sls.wami.app.IApplicationController;
import edu.mit.csail.sls.wami.jsapi.ClientControlledApplication;
import edu.mit.csail.sls.wami.recognition.IRecognitionResult;
/**
* NOTE:
*
* This sample code doesn't actually do anything different than the super-class.
*
* This application just provides an example of how you might override methods
* of a ClientControlledApplication to perform operations which should probably
* be performed on the server-side. For example, perhaps you need to look
* something up in a database, and do not want to force your client to make
* another request. Fortunately, Wami makes client-server communication simple
* via the app controller.
*
* @author imcgraw
*/
public class MyWamiApplication extends ClientControlledApplication {
private IApplicationController controller;
@Override
public void initialize(IApplicationController appController,
HttpSession session, Map<String, String> paramMap) {
this.controller = appController;
super.initialize(appController, session, paramMap);
};
@Override
public void onRecognitionResult(IRecognitionResult result) {
Document doc = getMessageOnlyServerCanCompute();
if (doc != null) {
controller.sendMessage(doc);
} else {
super.onRecognitionResult(result);
}
}
private Document getMessageOnlyServerCanCompute() {
// Just an example...
return null;
}
@Override
public void onClientMessage(Element xmlRoot) {
// Messages sent from the client via postXML
super.onClientMessage(xmlRoot);
}
}
| Java |
package ca.seedstuff.transdroid.preferences;
import java.util.ArrayList;
import java.util.List;
import org.transdroid.daemon.Daemon;
import org.transdroid.daemon.DaemonSettings;
import org.transdroid.daemon.OS;
import org.transdroid.daemon.util.HttpHelper;
public class SeedstuffSettings {
private static final String DEFAULT_NAME = "Seedstuff";
private static final int RTORRENT_PORT = 443;
private static final String RTORRENT_FOLDER_PART = "/user/";
private static final int FTP_PORT = 32001;
final private String name;
final private String server;
final private String username;
final private String password;
final private boolean alarmOnFinishedDownload;
final private boolean alarmOnNewTorrent;
final private String idString;
public SeedstuffSettings(String name, String server, String username, String password, boolean alarmOnFinishedDownload,
boolean alarmOnNewTorrent, String idString) {
this.name = name;
this.server = server;
this.username = username;
this.password = password;
this.alarmOnFinishedDownload = alarmOnFinishedDownload;
this.alarmOnNewTorrent = alarmOnNewTorrent;
this.idString = idString;
}
public String getName() {
return (name == null || name.equals("") ? DEFAULT_NAME : name);
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public boolean shouldAlarmOnFinishedDownload() {
return alarmOnFinishedDownload;
}
public boolean shouldAlarmOnNewTorrent() {
return alarmOnNewTorrent;
}
public String getIdString() {
return idString;
}
/**
* Builds a text that can be used by a human reader to identify this daemon settings
* @return A concatenation of username, address, port and folder, where applicable
*/
public String getHumanReadableIdentifier() {
return getServer();
}
public String getServer() {
return server;
}
@Override
public String toString() {
return getHumanReadableIdentifier();
}
public List<DaemonSettings> createDaemonSettings(int startID) {
List<DaemonSettings> daemons = new ArrayList<DaemonSettings>();
// rTorrent
daemons.add(new DaemonSettings(getName(), Daemon.rTorrent, getServer(), RTORRENT_PORT, true, true, null,
RTORRENT_FOLDER_PART + getUsername(), true, getUsername(), getPassword(), null, OS.Linux,
"/rtorrent/downloads/", "ftp://" + getName() + "@" + getServer() + FTP_PORT + "/rtorrents/downloads/",
getPassword(), HttpHelper.DEFAULT_CONNECTION_TIMEOUT, shouldAlarmOnFinishedDownload(),
shouldAlarmOnNewTorrent(), "" + startID++, true));
return daemons;
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package ca.seedstuff.transdroid.preferences;
import org.transdroid.R;
import org.transdroid.preferences.Preferences;
import org.transdroid.preferences.TransdroidCheckBoxPreference;
import org.transdroid.preferences.TransdroidEditTextPreference;
import org.transdroid.preferences.TransdroidListPreference;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.text.InputType;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.ListView;
import android.widget.Toast;
public class PreferencesSeedstuffServer extends PreferenceActivity {
public static final String PREFERENCES_SSERVER_KEY = "PREFERENCES_SSERVER_POSTFIX";
public static final String[] validAddressEnding = { ".seedstuff.ca" };
private String serverPostfix;
// These preferences are members so they can be accessed by the updateOptionAvailibility event
private TransdroidEditTextPreference name;
private TransdroidEditTextPreference server;
private TransdroidEditTextPreference user;
private TransdroidEditTextPreference pass;
private TransdroidCheckBoxPreference alarmFinished;
private TransdroidCheckBoxPreference alarmNew;
private String nameValue = null;
private String serverValue = null;
private String userValue = null;
//private String passValue = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// For which server?
serverPostfix = getIntent().getStringExtra(PREFERENCES_SSERVER_KEY);
// Create the preferences screen here: this takes care of saving/loading, but also contains the ListView adapter, etc.
setPreferenceScreen(getPreferenceManager().createPreferenceScreen(this));
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
nameValue = prefs.getString(Preferences.KEY_PREF_SNAME + serverPostfix, null);
serverValue = prefs.getString(Preferences.KEY_PREF_SSERVER + serverPostfix, null);
userValue = prefs.getString(Preferences.KEY_PREF_SUSER + serverPostfix, null);
//passValue = prefs.getString(Preferences.KEY_PREF_SPASS + serverPostfix, null);
// Create preference objects
getPreferenceScreen().setTitle(R.string.seedstuff_pref_title);
// Name
name = new TransdroidEditTextPreference(this);
name.setTitle(R.string.pref_name);
name.setKey(Preferences.KEY_PREF_SNAME + serverPostfix);
name.getEditText().setSingleLine();
name.setDialogTitle(R.string.pref_name);
name.setOnPreferenceChangeListener(updateHandler);
getPreferenceScreen().addItemFromInflater(name);
// Server
server = new TransdroidEditTextPreference(this);
server.setTitle(R.string.seedstuff_pref_server);
server.setKey(Preferences.KEY_PREF_SSERVER + serverPostfix);
server.getEditText().setSingleLine();
server.getEditText().setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_URI);
server.setDialogTitle(R.string.seedstuff_pref_server);
server.setOnPreferenceChangeListener(updateHandler);
getPreferenceScreen().addItemFromInflater(server);
// User
user = new TransdroidEditTextPreference(this);
user.setTitle(R.string.pref_user);
user.setKey(Preferences.KEY_PREF_SUSER + serverPostfix);
user.getEditText().setSingleLine();
user.getEditText().setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_FILTER);
user.setDialogTitle(R.string.pref_user);
user.setOnPreferenceChangeListener(updateHandler);
getPreferenceScreen().addItemFromInflater(user);
// Pass
pass = new TransdroidEditTextPreference(this);
pass.setTitle(R.string.pref_pass);
pass.setKey(Preferences.KEY_PREF_SPASS + serverPostfix);
pass.getEditText().setSingleLine();
pass.getEditText().setInputType(EditorInfo.TYPE_TEXT_VARIATION_PASSWORD);
pass.getEditText().setTransformationMethod(new PasswordTransformationMethod());
pass.setDialogTitle(R.string.pref_pass);
pass.setOnPreferenceChangeListener(updateHandler);
getPreferenceScreen().addItemFromInflater(pass);
// AlertFinished
alarmFinished = new TransdroidCheckBoxPreference(this);
alarmFinished.setDefaultValue(true);
alarmFinished.setTitle(R.string.pref_alarmfinished);
alarmFinished.setSummary(R.string.pref_alarmfinished_info);
alarmFinished.setKey(Preferences.KEY_PREF_SALARMFINISHED + serverPostfix);
alarmFinished.setOnPreferenceChangeListener(updateHandler);
getPreferenceScreen().addItemFromInflater(alarmFinished);
// AlertNew
alarmNew = new TransdroidCheckBoxPreference(this);
alarmNew.setTitle(R.string.pref_alarmnew);
alarmNew.setSummary(R.string.pref_alarmnew_info);
alarmNew.setKey(Preferences.KEY_PREF_SALARMNEW + serverPostfix);
alarmNew.setOnPreferenceChangeListener(updateHandler);
getPreferenceScreen().addItemFromInflater(alarmNew);
updateDescriptionTexts();
}
private OnPreferenceChangeListener updateHandler = new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (preference == name) {
nameValue = (String) newValue;
} else if (preference == server) {
String newServer = (String) newValue;
// Validate seedstuff server address
boolean valid = newServer != null && !newServer.equals("") && !(newServer.indexOf(" ") >= 0);
boolean validEnd = false;
for (int i = 0; i < validAddressEnding.length && valid; i++) {
validEnd |= newServer.endsWith(validAddressEnding[i]);
}
if (!valid || !validEnd) {
Toast.makeText(getApplicationContext(), R.string.seedstuff_error_invalid_servername, Toast.LENGTH_LONG).show();
return false;
}
serverValue = newServer;
} else if (preference == user) {
userValue = (String) newValue;
} else if (preference == pass) {
//passValue = (String) newValue;
}
updateDescriptionTexts();
// Set the value as usual
return true;
}
};
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// Perform click action, which always is a Preference
Preference item = (Preference) getListAdapter().getItem(position);
// Let the Preference open the right dialog
if (item instanceof TransdroidListPreference) {
((TransdroidListPreference)item).click();
} else if (item instanceof TransdroidCheckBoxPreference) {
((TransdroidCheckBoxPreference)item).click();
} else if (item instanceof TransdroidEditTextPreference) {
((TransdroidEditTextPreference)item).click();
}
}
private void updateDescriptionTexts() {
// Update the 'summary' labels of all preferences to show their current value
name.setSummary(nameValue == null? getText(R.string.pref_name_info): nameValue);
server.setSummary(serverValue == null? getText(R.string.seedstuff_pref_server_info): serverValue);
user.setSummary(userValue == null? "": userValue);
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.search.barcode;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.transdroid.daemon.util.HttpHelper;
import org.transdroid.util.TLog;
import android.os.AsyncTask;
public abstract class GoogleWebSearchBarcodeResolver extends AsyncTask<String, Void, String> {
private static final String LOG_NAME = "Transdroid GoogleWebSearchBarcodeResolver";
public static final String apiUrl = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=%s";
@Override
protected String doInBackground(String... params) {
if (params.length < 1) {
return null;
}
try {
// We use the Google AJAX Search API to get a JSON-formatted list of web search results
String callUrl = apiUrl.replace("%s", params[0]);
TLog.d(LOG_NAME, "Getting web results at " + callUrl);
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(callUrl);
HttpResponse response = httpclient.execute(httpget);
InputStream instream = response.getEntity().getContent();
String result = HttpHelper.ConvertStreamToString(instream);
JSONArray results = new JSONObject(result).getJSONObject("responseData").getJSONArray("results");
// We will combine and filter multiple results, if there are any
TLog.d(LOG_NAME, "Google returned " + results.length() + " results");
if (results.length() < 1) {
return null;
}
return stripGarbage(results, params[0]);
} catch (Exception e) {
TLog.d(LOG_NAME, "Error retrieving barcode: " + e.toString());
return null;
}
}
@Override
protected void onPostExecute(String result) {
onBarcodeLookupComplete(result);
}
protected abstract void onBarcodeLookupComplete(String result);
private static String stripGarbage(JSONArray results, String barcode) throws JSONException {
String good = " abcdefghijklmnopqrstuvwxyz";
final int MAX_TITLE_CONSIDER = 4;
final int MAX_MISSING = 1;
final int MIN_TITLE_CONSIDER = 2;
// First gather the titles for the first MAX_TITLE_CONSIDER results
List<String> titles = new ArrayList<String>();
for (int i = 0; i < results.length() && i < MAX_TITLE_CONSIDER; i++) {
String title = results.getJSONObject(i).getString("titleNoFormatting");
// Make string lowercase first
title = title.toLowerCase();
// Remove the barcode number if it's there
title = title.replace(barcode, "");
// Remove unwanted words and HTML special chars
for (String rem : new String[] { "dvd", "blu-ray", "bluray", "&", """, "'", "<", ">" }) {
title = title.replace(rem, "");
}
// Remove all non-alphanumeric (and space) characters
String result = "";
for ( int j = 0; j < title.length(); j++ ) {
if ( good.indexOf(title.charAt(j)) >= 0 )
result += title.charAt(j);
}
// Remove double spaces
while (result.contains(" ")) {
result = result.replace(" ", " ");
}
titles.add(result);
}
// Only retain the words that are missing in at most one of the search result titles
List<String> allWords = new ArrayList<String>();
for (String title : titles) {
for (String word : Arrays.asList(title.split(" "))) {
if (!allWords.contains(word)) {
allWords.add(word);
}
}
}
List<String> remainingWords = new ArrayList<String>();
int allowMissing = Math.min(MAX_MISSING, Math.max(titles.size() - MIN_TITLE_CONSIDER, 0));
for (String word : allWords) {
int missing = 0;
for (String title : titles) {
if (!title.contains(word)) {
// The word is not contained in this result title
missing++;
if (missing > allowMissing) {
// Already misssing more than once, no need to look further
break;
}
}
}
if (missing <= allowMissing) {
// The word was only missing at most once, so we keep it
remainingWords.add(word);
}
}
// Now the query is the concatenation of the words remaining; with spaces in between
String query = "";
for (String word : remainingWords) {
query += " " + word;
}
return query.length() > 0? query.substring(1): null;
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.search.barcode;
import java.io.IOException;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import org.ifies.android.sax.Item;
import org.ifies.android.sax.RssParser;
import org.transdroid.util.TLog;
import org.xml.sax.SAXException;
import android.os.AsyncTask;
public abstract class GoogleBaseBarcodeResolver extends AsyncTask<String, Void, String> {
private static final String LOG_NAME = "GoogleBaseBarcodeResolver";
public static final String apiUrl = "http://www.google.com/base/feeds/snippets?bq=%s&max-results=1&alt=rss";
@Override
protected String doInBackground(String... params) {
if (params.length < 1) {
return null;
}
// We use the Google Base API to get meaningful results from a barcode number
TLog.d(LOG_NAME, "Getting RSS feed at " + apiUrl.replace("%s", params[0]));
RssParser feed = new RssParser(apiUrl.replace("%s", params[0]));
try {
feed.parse();
} catch (ParserConfigurationException e) {
TLog.d(LOG_NAME, e.toString());
return null;
//throw new SearchException(R.string.error_parsingrss, e.toString());
} catch (SAXException e) {
TLog.d(LOG_NAME, e.toString());
return null;
//throw new SearchException(R.string.error_parsingrss, e.toString());
} catch (IOException e) {
TLog.d(LOG_NAME, e.toString());
return null;
//throw new SearchException(R.string.error_httperror, e.toString());
}
// For now, just return the first 5 actual words of the first item
List<Item> items = feed.getChannel().getItems();
TLog.d(LOG_NAME, "Feed contains " + items.size() + " items");
if (items.size() < 1 || items.get(0).getTitle() == null) {
return null;
}
// Remove the barcode number if it's there
String cleanup = items.get(0).getTitle().replace(params[0], "");
return stripGarbage(cleanup);
}
@Override
protected void onPostExecute(String result) {
onBarcodeLookupComplete(result);
}
protected abstract void onBarcodeLookupComplete(String result);
private static String stripGarbage(String s) {
String good = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
String result = "";
// Remove all non-alphanumeric (and space) characters
for ( int i = 0; i < s.length(); i++ ) {
if ( good.indexOf(s.charAt(i)) >= 0 )
result += s.charAt(i);
}
// Remove double spaces
while (result.contains(" ")) {
result = result.replace(" ", " ");
}
// Only retain first four words
int i, j = 0;
for ( i = 0; i < s.length(); i++ ) {
if (s.charAt(i) == ' ') {
j++;
}
if (j > 4) {
break;
}
}
return i > 0? result.substring(0, i - 1): "";
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.gui;
import org.transdroid.R;
import org.transdroid.daemon.Torrent;
import org.transdroid.daemon.TorrentStatus;
import android.content.Context;
import android.text.Html;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
* A view that shows the torrent data as a list item.
*
* @author erickok
*
*/
public class TorrentListView extends LinearLayout {
private ViewHolder views;
/**
* Constructs a view that can display torrent data (to use in a list) and sets the display data
* @param context The activity context
* @param torrent The torrent info to show the data for
*/
public TorrentListView(Context context, Torrent torrent, boolean withAvailability) {
super(context);
addView(inflate(context, R.layout.list_item_torrent, null));
setData(torrent, withAvailability);
}
/**
* Sets the actual texts and images to the visible widgets (fields)
*/
public void setData(Torrent tor, boolean withAvailability) {
LocalTorrent torrent = LocalTorrent.fromTorrent(tor);
if (views == null) {
views = new ViewHolder();
views.name = (TextView) findViewById(R.id.name);
views.progressSize = (TextView) findViewById(R.id.progress_size);
views.progressEtaRatio = (TextView) findViewById(R.id.progress_eta_ratio);
views.pb = (TorrentProgressBar) findViewById(R.id.progressbar);
views.progressPeers = (TextView) findViewById(R.id.progress_peers);
views.progressSpeed = (TextView) findViewById(R.id.progress_speed);
}
views.name.setText(tor.getName());
views.progressSize.setText(Html.fromHtml(torrent.getProgressSizeText(getResources(), false)), TextView.BufferType.SPANNABLE);
views.progressEtaRatio.setText(Html.fromHtml(torrent.getProgressEtaRatioText(getResources())), TextView.BufferType.SPANNABLE);
views.pb.setProgress((int)(tor.getDownloadedPercentage() * 100));
views.pb.setActive(tor.canPause());
views.pb.setError(tor.getStatusCode() == TorrentStatus.Error);
views.progressPeers.setText(Html.fromHtml(torrent.getProgressConnectionText(getResources())), TextView.BufferType.SPANNABLE);
views.progressSpeed.setText(Html.fromHtml(torrent.getProgressSpeedText(getResources())), TextView.BufferType.SPANNABLE);
}
/**
* Used to further optimize the getting of Views
*/
private static class ViewHolder {
TextView name;
TextView progressSize;
TextView progressEtaRatio;
TorrentProgressBar pb;
TextView progressPeers;
TextView progressSpeed;
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.gui.search;
/**
* A class that contains interface settings relating to searches
*
* @author eric
*
*/
public final class SearchSettings {
final private int numberOfResults;
final private boolean sortBySeeders;
/**
* Creates a search site settings instance, providing all result options details
* @param numberOfResults The number of results to get from the server for a single query
* @param sortBySeeders Whether to sort by number of leechers (otherwise a combined sort is used)
*/
public SearchSettings(int numberOfResults, boolean sortBySeeders) {
this.numberOfResults = numberOfResults;
this.sortBySeeders = sortBySeeders;
}
/**
* Gives how many search results to show in one screen
* @return The number of results to show
*/
public int getNumberOfResults() {
return numberOfResults;
}
/**
* Gives the sort method that should be used
* @return True if the results should be sorted by number of seeders/leechers, otherwise it should sort using the torrent site default
*/
public boolean getSortBySeeders() {
return sortBySeeders;
}
}
| Java |
package org.transdroid.gui.search;
import android.content.Intent;
/**
* Used to clean up text as received from a generic ACTION_SEND intent. This
* class is highly custom-based for known applications, i.e. the EXTRA_TEXT
* send by some known applications.
*
* @author erickok
*/
public class SendIntentHelper {
private static final String SOUNDHOUND1 = "Just used #SoundHound to find ";
private static final String SOUNDHOUND1_END = " http://";
private static final String SHAZAM = "I just used Shazam to discover ";
private static final String SHAZAM_END = ". http://";
private static final String YOUTUBE_ID= "Watch \"";
private static final String YOUTUBE_START = "\"";
private static final String YOUTUBE_END = "\"";
public static String cleanUpText(Intent intent) {
if (intent == null || !intent.hasExtra(Intent.EXTRA_TEXT)) {
return null;
}
String text = intent.getStringExtra(Intent.EXTRA_TEXT);
try {
// Soundhound song/artist share
if (text.startsWith(SOUNDHOUND1)) {
return cutOut(text, SOUNDHOUND1, SOUNDHOUND1_END).replace(" by ", " ");
}
// Shazam song share
if (text.startsWith(SHAZAM)) {
return cutOut(text, SHAZAM, SHAZAM_END).replace(" by ", " ");
}
// YouTube app share (stores title in EXTRA_SUBJECT)
if (intent.hasExtra(Intent.EXTRA_SUBJECT)) {
String subject = intent.getStringExtra(Intent.EXTRA_SUBJECT);
if (subject.startsWith(YOUTUBE_ID)) {
return cutOut(subject, YOUTUBE_START, YOUTUBE_END);
}
}
} catch (Exception e) {
// Ignore any errors in parsing; just return the raw text
}
return text;
}
private static String cutOut(String text, String start, String end) {
int startAt = text.indexOf(start) + start.length();
return text.substring(startAt, text.indexOf(end, startAt));
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.gui.search;
import java.text.DateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import org.transdroid.R;
import org.transdroid.gui.util.SelectableArrayAdapter.OnSelectedChangedListener;
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ResourceCursorAdapter;
import android.widget.TextView;
import android.widget.CompoundButton.OnCheckedChangeListener;
public class SearchListAdapter extends ResourceCursorAdapter {
private final LayoutInflater li;
private HashSet<String> selectedUrls;
private OnSelectedChangedListener listener;
public SearchListAdapter(Context context, Cursor c, OnSelectedChangedListener listener) {
super(context, R.layout.list_item_search, c);
li = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.listener = listener;
this.selectedUrls = new HashSet<String>();
}
@Override
public View newView(Context context, Cursor cur, ViewGroup parent) {
return li.inflate(R.layout.list_item_search, parent, false);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
// Set the checkbox that allow picking of multiple results at once
final CheckBox check = (CheckBox)view.findViewById(R.id.result_check);
// Store this row's URL in the check box view's tag
String tag = cursor.getString(TorrentSearchTask.CURSOR_SEARCH_TORRENTURL);
check.setTag(tag);
check.setChecked(selectedUrls.contains(tag));
check.setOnCheckedChangeListener(itemSelectionHandler);
// Bind the data values to the text views
TextView date = (TextView)view.findViewById(R.id.result_date);
((TextView)view.findViewById(R.id.result_title)).setText(cursor.getString(TorrentSearchTask.CURSOR_SEARCH_NAME));
((TextView)view.findViewById(R.id.result_size)).setText(cursor.getString(TorrentSearchTask.CURSOR_SEARCH_SIZE));
((TextView)view.findViewById(R.id.result_leechers)).setText("L: " + cursor.getInt(TorrentSearchTask.CURSOR_SEARCH_LEECHERS));
((TextView)view.findViewById(R.id.result_seeds)).setText("S: " + cursor.getInt(TorrentSearchTask.CURSOR_SEARCH_SEEDERS));
long dateAdded = cursor.getLong(TorrentSearchTask.CURSOR_SEARCH_ADDED);
if (dateAdded > 0) {
date.setText(DateFormat.getDateInstance(DateFormat.SHORT).format(new Date(dateAdded)));
date.setVisibility(View.VISIBLE);
} else {
date.setText("");
date.setVisibility(View.GONE);
}
}
private final OnCheckedChangeListener itemSelectionHandler = new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
itemChecked((String) buttonView.getTag(), isChecked);
}
};
/**
* Is called by views to indicate an item was either selected or deselected
* @param url The URL for which the selected state has changed
* @param isChecked If the item is now checked/selected
*/
public void itemChecked(String url, boolean isChecked) {
if (!isChecked && selectedUrls.contains(url)) {
selectedUrls.remove(url);
}
if (isChecked && !selectedUrls.contains(url)) {
selectedUrls.add(url);
}
if (listener != null) {
listener.onSelectedResultsChanged();
}
}
/**
* Whether an search item is currently selected
* @param url The search item URL, which should be present in the underlying list
* @return True if the search item is currently selected, false otherwise
*/
public boolean isItemChecked(String url) {
return selectedUrls.contains(url);
}
/**
* Returns the list of all checked/selected items
* @return The list of selected items
*/
public Set<String> getSelectedUrls() {
return this.selectedUrls;
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.gui.search;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.transdroid.R;
import org.transdroid.daemon.util.HttpHelper;
import org.transdroid.gui.Torrents;
import org.transdroid.gui.Transdroid;
import org.transdroid.gui.util.ActivityUtil;
import org.transdroid.gui.util.SelectableArrayAdapter.OnSelectedChangedListener;
import org.transdroid.preferences.Preferences;
import org.transdroid.util.TLog;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.OnNavigationListener;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.SearchManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.SearchRecentSuggestions;
import android.support.v4.app.FragmentActivity;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.widget.Toast;
/**
* Provides an activity that allows a search to be performed on a search engine and
* lists the results. Individual results can be browsed to using the web browser or the URL
* is forwarded to the Torrents activity. For web searches, the browser is started at
* the appropriate search URL. In-app searches are performed with the Transdroid Torrent
* Search project's public cursor adapters.
*
* @author erickok
*
*/
public class Search extends SherlockFragmentActivity implements OnTouchListener, OnSelectedChangedListener {
private static final String LOG_NAME = "Search";
private final static Uri TTS_MARKET_URI = Uri.parse("http://www.transdroid.org/latest-search");
private static final int MENU_REFRESH_ID = 1;
private static final int MENU_SEARCH_ID = 2;
private static final int MENU_SITES_ID = 3;
private static final int MENU_SAVESEARCH_ID = 4;
private static final int SEARCHMENU_ADD_ID = 10;
private static final int SEARCHMENU_DETAILS_ID = 11;
private static final int SEARCHMENU_OPENWITH_ID = 12;
private static final int SEARCHMENU_SHARELINK_ID = 13;
private static final int DIALOG_SITES = 1;
private static final int DIALOG_INSTALLSEARCH = 2;
private TextView empty;
private LinearLayout addSelected;
private Button addSelectedButton;
private SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this,
TorrentSearchHistoryProvider.AUTHORITY, TorrentSearchHistoryProvider.MODE);
private GestureDetector gestureDetector;
private List<SiteSettings> allSites;
private SiteSettings defaultSite;
private SearchSettings searchSettings;
private String query;
private boolean inProgress = false;
private boolean disableListNavigation = true;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
registerForContextMenu(findViewById(R.id.results));
getListView().setTextFilterEnabled(true);
getListView().setOnItemClickListener(onSearchResultSelected);
getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
empty = (TextView) findViewById(android.R.id.empty);
addSelected = (LinearLayout) findViewById(R.id.add_selected);
addSelectedButton = (Button) findViewById(R.id.add_selectedbutton);
addSelectedButton.setOnClickListener(addSelectedClicked);
// Swiping or flinging between server configurations
gestureDetector = new GestureDetector(new SearchScreenGestureListener());
getListView().setOnTouchListener(this);
handleIntent(getIntent());
}
private SpinnerAdapter buildProvidersAdapter() {
ArrayAdapter<String> ad = new ArrayAdapter<String>(this, R.layout.abs__simple_spinner_item, buildSiteTextsForDialog());
ad.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
return ad;
}
/** Called when a new intent is delivered */
@Override
public void onNewIntent(final Intent newIntent) {
super.onNewIntent(newIntent);
handleIntent(newIntent);
}
private void handleIntent(Intent startIntent) {
// Get the query string from the intent
String thequery = getQuery(startIntent);
// Is this actually a full HTTP URL?
if (thequery != null && (thequery.startsWith(HttpHelper.SCHEME_HTTP) ||
thequery.startsWith(HttpHelper.SCHEME_MAGNET) || thequery.startsWith(HttpHelper.SCHEME_FILE))) {
// Redirect this request to the main screen to add the URL directly
Intent i = new Intent(this, Torrents.class);
i.setData(Uri.parse(thequery));
startActivity(i);
finish();
return;
}
// Check if Transdroid Torrent Search is installed
if (!TorrentSearchTask.isTorrentSearchInstalled(this)) {
showDialog(DIALOG_INSTALLSEARCH);
empty.setText("");
return;
}
// Load preferences
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
defaultSite = Preferences.readDefaultSearchSiteSettings(prefs);
allSites = Preferences.readAllSiteSettings(prefs);
searchSettings = Preferences.readSearchSettings(prefs);
// Update selection spinner
disableListNavigation = true;
getSupportActionBar().setListNavigationCallbacks(buildProvidersAdapter(), onProviderSelected);
// Switch to a certain site?
if (startIntent.hasExtra(SearchManager.EXTRA_DATA_KEY)) {
String switchToKey = startIntent.getStringExtra(SearchManager.EXTRA_DATA_KEY);
// See if this site (key) exists
for (SiteSettings site : allSites) {
if (site.getKey().equals(switchToKey)) {
// If it is different than the last used (default) site, switch to it
if (!defaultSite.getKey().equals(switchToKey)) {
// Set the default site search to this new site
Preferences.storeLastUsedSearchSiteSettings(getApplicationContext(), switchToKey);
defaultSite = allSites.get(siteSettingsIndex(site));
}
break;
}
}
}
if (defaultSite == null) {
return;
}
// Start a web search?
if (defaultSite.isWebSearch()) {
if (thequery == null || thequery.equals("")) {
// No search term was provided: show a message and close this search activity
Toast.makeText(this, R.string.no_query, Toast.LENGTH_LONG).show();
finish();
return;
}
doWebSearch(defaultSite, thequery);
finish();
return;
}
// Select the now-selected site in the spinner
getSupportActionBar().setSelectedNavigationItem(siteSettingsIndex(defaultSite));
disableListNavigation = false;
// Normal in-app search
query = thequery;
handleQuery();
}
private void doWebSearch(SiteSettings thesite, String thequery) {
// Check for a valid url
Uri uri = Uri.parse(thesite.getSubstitutedUrl(thequery));
if (uri == null || uri.getScheme() == null || !(uri.getScheme().equals("http") || uri.getScheme().equals("https"))) {
// The url doesn't even have a http or https scheme, so the intent will fail
Toast.makeText(this, getResources().getText(R.string.error_invalid_search_url) + " " + uri.toString(), Toast.LENGTH_LONG).show();
finish();
return;
}
// Do not load this activity, but immediately start a web search via a new Intent
startActivity(new Intent(Intent.ACTION_VIEW, uri));
}
/**
* Extracts the query string from the search Intent
* @return The string that was entered by the user
*/
private String getQuery(Intent intent) {
// Extract string from Intent
String query = null;
if (intent.getAction().equals(Intent.ACTION_SEARCH)) {
query = intent.getStringExtra(SearchManager.QUERY);
} else if (intent.getAction().equals(Intent.ACTION_SEND)) {
query = SendIntentHelper.cleanUpText(intent);
}
if (query != null && query.length() > 0) {
// Remember this search query to later show as a suggestion
suggestions.saveRecentQuery(query, null);
return query;
}
return null;
}
/**
* Actually calls the search on the local preset query (if not empty)
*/
private void handleQuery() {
if (query == null || query.equals("")) {
// No search (activity was started incorrectly or query was empty)
empty.setText(R.string.no_query);
// Provide search input
onSearchRequested();
return;
}
// Execute search
doSearch(query);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, SEARCHMENU_ADD_ID, 0, R.string.searchmenu_add);
menu.add(0, SEARCHMENU_DETAILS_ID, 0, R.string.searchmenu_details);
menu.add(0, SEARCHMENU_OPENWITH_ID, 0, R.string.searchmenu_openwith);
menu.add(0, SEARCHMENU_SHARELINK_ID, 0, R.string.searchmenu_sharelink);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
boolean result = super.onCreateOptionsMenu(menu);
// Add title bar buttons
MenuItem miRefresh = menu.add(0, MENU_REFRESH_ID, 0, R.string.refresh);
miRefresh.setIcon(R.drawable.icon_refresh_title);
miRefresh.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS|MenuItem.SHOW_AS_ACTION_WITH_TEXT);
if (inProgress) {
// Show progress spinner instead of the option item
View view = getLayoutInflater().inflate(R.layout.part_actionbar_progressitem, null);
miRefresh.setActionView(view);
}
MenuItem miSearch = menu.add(0, MENU_SEARCH_ID, 0, R.string.search);
miSearch.setIcon(R.drawable.icon_search_title);
miSearch.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS|MenuItem.SHOW_AS_ACTION_WITH_TEXT);
if (TorrentSearchTask.isTorrentSearchInstalled(this)) {
// Add the switch sites button
MenuItem miSwitch = menu.add(0, MENU_SITES_ID, 0, R.string.searchmenu_switchsite);
miSwitch.setIcon(android.R.drawable.ic_menu_myplaces);
// Add the save search button
MenuItem miSave = menu.add(0, MENU_SAVESEARCH_ID, 0, R.string.searchmenu_savesearch);
miSave.setIcon(android.R.drawable.ic_menu_save);
}
return result;
}
private OnItemClickListener onSearchResultSelected = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
// If something was already selected before
Cursor item = (Cursor) getListAdapter().getItem(position);
String url = item.getString(TorrentSearchTask.CURSOR_SEARCH_TORRENTURL);
if (!getSearchListAdapter().getSelectedUrls().isEmpty()) {
// Use an item click as selection check box click
getSearchListAdapter().itemChecked(url, !getSearchListAdapter().isItemChecked(url));
getListView().invalidateViews();
} else {
// Directly return the URL of the clicked torrent file
ReturnUrlResult(url, item.getString(TorrentSearchTask.CURSOR_SEARCH_NAME));
}
}
};
private SearchListAdapter getSearchListAdapter() {
return (SearchListAdapter) getListAdapter();
}
@Override
public boolean onContextItemSelected(android.view.MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
Cursor result = (Cursor) getListAdapter().getItem((int) info.id);
switch (item.getItemId()) {
case SEARCHMENU_ADD_ID:
// Return the url of the selected list item
ReturnUrlResult(result.getString(TorrentSearchTask.CURSOR_SEARCH_TORRENTURL),
result.getString(TorrentSearchTask.CURSOR_SEARCH_NAME));
break;
case SEARCHMENU_DETAILS_ID:
// Open the browser to show the website details page
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(result.getString(TorrentSearchTask.CURSOR_SEARCH_DETAILSURL))));
break;
case SEARCHMENU_OPENWITH_ID:
// Start a VIEW (open) Intent with the .torrent url that other apps can catch
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(result.getString(TorrentSearchTask.CURSOR_SEARCH_TORRENTURL))));
break;
case SEARCHMENU_SHARELINK_ID:
// Start a SEND (share) Intent with the .torrent url so the user can send the link to someone else
startActivity(Intent.createChooser(
new Intent(Intent.ACTION_SEND)
.setType("text/plain")
.putExtra(Intent.EXTRA_TEXT, result.getString(TorrentSearchTask.CURSOR_SEARCH_TORRENTURL))
.putExtra(Intent.EXTRA_SUBJECT, result.getString(TorrentSearchTask.CURSOR_SEARCH_NAME)),
getText(R.string.searchmenu_sharelink)));
break;
}
return true;
}
private OnNavigationListener onProviderSelected = new OnNavigationListener() {
@Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
if (!disableListNavigation) {
switchProvider(itemPosition);
}
return false;
}
};
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch (item.getItemId()) {
case MENU_REFRESH_ID:
if (TorrentSearchTask.isTorrentSearchInstalled(this) && defaultSite != null) {
handleQuery();
}
break;
case MENU_SEARCH_ID:
onSearchRequested();
break;
case MENU_SITES_ID:
// Present a dialog with all available in-app sites
showDialog(DIALOG_SITES);
break;
case MENU_SAVESEARCH_ID:
// Save the current query as an RSS feed
saveSearch();
break;
}
return super.onMenuItemSelected(featureId, item);
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_SITES:
// Build a dialog with a radio box per in-app search site
AlertDialog.Builder serverDialog = new AlertDialog.Builder(this);
serverDialog.setTitle(R.string.searchmenu_switchsite);
serverDialog.setSingleChoiceItems(
buildSiteTextsForDialog(), // The strings of the available in-app search sites
siteSettingsIndex(defaultSite),
new DialogInterface.OnClickListener() {
@Override
// When the server is clicked (and it is different from the current active configuration),
// reload the daemon and update the torrent list
public void onClick(DialogInterface dialog, int which) {
switchProvider(which);
removeDialog(DIALOG_SITES);
}
});
return serverDialog.create();
case DIALOG_INSTALLSEARCH:
return ActivityUtil.buildInstallDialog(this, R.string.tts_not_found, TTS_MARKET_URI, true,
getString(R.string.tts_install));
}
return super.onCreateDialog(id);
}
private void switchProvider(int which) {
SiteSettings selected = allSites.get(which);
if (selected.getKey() != defaultSite.getKey()) {
if (selected.isWebSearch()) {
// Start a web search, but do not change the defaultSite
doWebSearch(selected, query);
} else {
// Set the default site search to this new site
Preferences.storeLastUsedSearchSiteSettings(getApplicationContext(), selected.getKey());
defaultSite = selected;
// Search again with the same query
handleQuery();
}
}
}
private int siteSettingsIndex(SiteSettings asite) {
if (asite == null ) {
return 0;
}
int i = 0;
for (SiteSettings site : allSites) {
if (site.getKey().equals(asite.getKey())) {
return i;
}
i++;
}
return -1;
}
private String[] buildSiteTextsForDialog() {
// Build a textual list of in-app search sites available
ArrayList<String> sites = new ArrayList<String>();
for (SiteSettings site : allSites) {
//if (!site.isWebSearch()) {
sites.add(site.getName());
//}
}
return sites.toArray(new String[sites.size()]);
}
private void ReturnUrlResult(String uri, String title) {
if (uri == null) {
setResult(RESULT_CANCELED);
finish();
}
try {
Uri.parse(uri);
} catch (Exception e) {
Toast.makeText(this, R.string.error_no_url_enclosure, Toast.LENGTH_LONG).show();
return;
}
// Build new intent that Transdroid can pick up again
Intent i = new Intent(this, Torrents.class);
i.setData(Uri.parse(uri));
i.putExtra(Transdroid.INTENT_TORRENT_TITLE, title);
// Create a result for the calling activity
setResult(RESULT_OK);
startActivity(i);
finish();
}
private void ReturnUrlResult(Set<String> results) {
// Build new intent with multiple result url's that Transdroid can pick up again
Intent i = new Intent(this, Torrents.class);
i.setAction(Transdroid.INTENT_ADD_MULTIPLE);
i.putExtra(Transdroid.INTENT_TORRENT_URLS, results.toArray(new String[] {}));
// Create a result for the calling activity
setResult(RESULT_OK);
startActivity(i);
finish();
}
private void doSearch(String query) {
// Show the 'loading' icon (rotating indeterminate progress bar)
setProgressBar(true);
// Show the searching text again (if search was started from within this screen itself, the results screen was populated)
empty.setText(R.string.searching);
if (getListAdapter() != null) {
setListAdapter(null);
}
// Start a new search
TLog.d(LOG_NAME, "Starting a " + defaultSite.getKey() + " search with query: " + query);
setTitle(getText(R.string.search_resultsfrom) + " " + defaultSite.getName());
new TorrentSearchTask(this) {
@Override
protected void onResultsRetrieved(Cursor cursor) {
Search.this.onResultsRetrieved(cursor);
}
@Override
protected void onError() {
Search.this.onError(getString(R.string.error_httperror));
}
}.execute(query, Preferences.getCursorKeyForPreferencesKey(defaultSite.getKey()), searchSettings.getSortBySeeders()? "BySeeders": "Combined");
}
private void setProgressBar(boolean b) {
inProgress = b;
invalidateOptionsMenu();
}
public void onResultsRetrieved(Cursor cursor) {
// Not loading any more, turn off status indicator
setProgressBar(false);
// Update the list
empty.setText(R.string.no_results);
setListAdapter(new SearchListAdapter(this, cursor, this));
getListView().requestFocus();
getListView().setOnTouchListener(this);
}
public void onError(String errorMessage) {
// Not loading any more, turn off status indicator
setProgressBar(false);
// Update the list
empty.setText(errorMessage);
setListAdapter(null);
}
private void saveSearch() {
// Find the url to match an RSS feed to the last query
String url = TorrentSearchTask.buildRssFeedFromSearch(this, defaultSite.getKey(), query);
if (url != null) {
// Build new RSS feed settings object
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
int i = 0;
String nextUrl = Preferences.KEY_PREF_RSSURL + Integer.toString(i);
while (prefs.contains(nextUrl)) {
i++;
nextUrl = Preferences.KEY_PREF_RSSURL + Integer.toString(i);
}
// Store an RSS feed setting for this feed
Editor editor = prefs.edit();
editor.putString(Preferences.KEY_PREF_RSSNAME + Integer.toString(i), query);
editor.putString(nextUrl, url);
editor.commit();
Toast.makeText(this, R.string.search_savedrssfeed, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, R.string.search_savenotsupported, Toast.LENGTH_SHORT).show();
}
}
protected ListView getListView() {
return (ListView) findViewById(R.id.results);
}
private SearchListAdapter getListAdapter() {
return (SearchListAdapter) getListView().getAdapter();
}
private View getEmptyText() {
return findViewById(android.R.id.empty);
}
private void setListAdapter(SearchListAdapter adapter) {
getListView().setAdapter(adapter);
if (adapter == null || adapter.getCount() <= 0) {
getListView().setVisibility(View.GONE);
getEmptyText().setVisibility(View.VISIBLE);
} else {
getListView().setVisibility(View.VISIBLE);
getEmptyText().setVisibility(View.GONE);
}
}
@Override
public boolean onTouchEvent(MotionEvent me) {
return gestureDetector.onTouchEvent(me);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
/**
* Internal class that handles gestures from the search screen (a 'swipe' or 'fling').
*
* More at http://stackoverflow.com/questions/937313/android-basic-gesture-detection
*/
class SearchScreenGestureListener extends SimpleOnGestureListener {
private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_MAX_OFF_PATH = 250;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
@Override
public boolean onDoubleTap (MotionEvent e) {
return false;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
if (e1 != null && e2 != null) {
if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH) {
return false;
}
// Determine to which daemon we are now switching
int newSite = siteSettingsIndex(defaultSite);
// right to left swipe
if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
newSite += 1;
if (newSite >= allSites.size() || allSites.get(newSite).isWebSearch()) {
newSite = 0;
}
} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
newSite -= 1;
if (newSite < 0) {
newSite = allSites.size() - 1;
while (allSites.get(newSite).isWebSearch()) {
// Skip the web search sites
newSite -= 1;
}
}
}
// Make the switch, if needed
SiteSettings newSiteSettings = allSites.get(newSite);
if (!newSiteSettings.getKey().equals(defaultSite.getKey())) {
// Set the default site search to this new site
Preferences.storeLastUsedSearchSiteSettings(getApplicationContext(), newSiteSettings.getKey());
defaultSite = newSiteSettings;
disableListNavigation = true;
getSupportActionBar().setSelectedNavigationItem(newSite);
disableListNavigation = false;
handleQuery();
}
}
return false;
}
}
/**
* Called by the SelectableArrayAdapter when the set of selected search results changed
*/
public void onSelectedResultsChanged() {
SearchListAdapter adapter = (SearchListAdapter) getListAdapter();
if (adapter.getSelectedUrls().size() == 0) {
// Hide the 'add selected' button
addSelected.setVisibility(View.GONE);
} else {
addSelected.setVisibility(View.VISIBLE);
}
}
private OnClickListener addSelectedClicked = new OnClickListener() {
@Override
public void onClick(View v) {
// Send the urls of all selected search result back to Transdroid
SearchListAdapter adapter = (SearchListAdapter) getListAdapter();
ReturnUrlResult(adapter.getSelectedUrls());
}
};
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.gui.search;
import org.transdroid.R;
import org.transdroid.preferences.Preferences;
import android.app.SearchManager;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.provider.BaseColumns;
/**
* Will provide a search 'suggestion' to the global Quick Search Box to search
* for torrents in every available (in-app or web) search site
*
* @author erickok
*
*/
public class GlobalTorrentSearchProvider extends ContentProvider {
public static final String AUTHORITY = "org.transdroid.GlobalTorrentSearchProvider";
@Override
public boolean onCreate() {
return true;
}
@Override
public String getType(Uri uri) {
return SearchManager.SUGGEST_MIME_TYPE;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
// Return a suggestion for every available site
return new SitesCursor(getContext(), selectionArgs[0]);
}
private class SitesCursor extends MatrixCursor {
public SitesCursor(Context context, String query) {
super(new String[] {
BaseColumns._ID,
SearchManager.SUGGEST_COLUMN_TEXT_1,
SearchManager.SUGGEST_COLUMN_TEXT_2,
SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA,
SearchManager.SUGGEST_COLUMN_QUERY,
SearchManager.SUGGEST_COLUMN_SHORTCUT_ID});
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
// Add a single item for the default search site
SiteSettings site = Preferences.readDefaultSearchSiteSettings(prefs);
RowBuilder row = newRow();
row.add(0); // ID
row.add(query); // First text line
row.add(context.getString(R.string.search_resultsfrom) + " " + site.getName()); // Second text line
row.add(site.getKey()); // Extra string (daemon key to search against)
row.add(query); // Extra string (query)
row.add(0);
}
}
@Override
public Uri insert(Uri uri, ContentValues values) {
throw new UnsupportedOperationException();
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
throw new UnsupportedOperationException();
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
throw new UnsupportedOperationException();
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.gui.search;
import android.content.Context;
import android.content.SearchRecentSuggestionsProvider;
import android.provider.SearchRecentSuggestions;
/**
* Provides a wrapper for the SearchRecentSuggestionsProvider to show the last
* torrent searches to the user
*
* @author erickok
*
*/
public class TorrentSearchHistoryProvider extends SearchRecentSuggestionsProvider {
final static String AUTHORITY = "org.transdroid.TorrentSearchHistoryProvider";
final static int MODE = DATABASE_MODE_QUERIES;
public TorrentSearchHistoryProvider() {
super();
setupSuggestions(AUTHORITY, MODE);
}
public static void clearHistory(Context context) {
SearchRecentSuggestions suggestions = new SearchRecentSuggestions(context,
TorrentSearchHistoryProvider.AUTHORITY, TorrentSearchHistoryProvider.MODE);
suggestions.clearHistory();
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.gui.search;
import java.net.URLEncoder;
import org.transdroid.R;
/**
* Represents a torrent site configuration; either in-app or web search
*
* @author erickok
*
*/
public final class SiteSettings {
final private boolean isWebSearch;
final private String key;
final private String name;
final private String url;
/**
* Instantiates an in-app search site
* @param adapterKey The unique key identifying the search adapter
* @param name The visible name of the site
*/
public SiteSettings(String adapterKey, String name) {
this.isWebSearch = false;
this.key = adapterKey;
this.name = name;
this.url = null;
}
/**
* Instantiates a web search site
* @param uniqueKey The (numeric) identifier for this web search settings (used as postfix on stored preferences)
* @param name The visible name of the site
* @param encodedUrl The raw URL to send the web search to, where %s will be replaced by the search keywords; for example http://www.google.nl/search?q=%s+ext%3Atorrent
*/
public SiteSettings(String uniqueKey, String name, String encodedUrl) {
this.isWebSearch = true;
this.key = uniqueKey;
this.name = name;
this.url = encodedUrl;
}
/**
* @return If this site performs a web search; it is an in-app search otherwise
*/
public boolean isWebSearch() {
return isWebSearch;
}
/**
* @return For in-app search sites this is the factory key; otherwise it is the unique identifier used to store it in the user preferences
*/
public String getKey() {
return key;
}
/**
* @return The visible name of the site
*/
public String getName() {
return name;
}
/**
* Returns the raw URL where web searches will be directed to; it has a %s where search keywords will be placed
* @return
*/
public String getRawurl() {
return url;
}
/**
* Returns the URL for a search based on the user query. The query will be URL-encoded.
* @param query The raw user query text
* @return The url that can be send to the browser to show the web search results
*/
public String getSubstitutedUrl(String query) {
return url.replace("%s", URLEncoder.encode(query));
}
/**
* Tells the user what type of search engine this is
* @return The resource id of the text explaining the search type
*/
public int getSearchTypeTextResource() {
if (isWebSearch()) {
return R.string.websearch;
} else {
return R.string.inappsite;
}
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.gui.search;
import org.transdroid.preferences.Preferences;
import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
/**
* Task that helps in retrieving torrent search results from the Transdroid Torrent Search content providers.
* Use getSupportedSites() to see which torrent search sites are available to query against.
*
* @author erickok
*
*/
public abstract class TorrentSearchTask extends AsyncTask<String, Void, Cursor> {
// public static final String[] SEARCH_FIELDS = new String[] { "_ID", "NAME", "TORRENTURL", "DETAILSURL",
// "SIZE", "ADDED", "SEEDERS", "LEECHERS" };
// public static final String[] SITE_FIELDS = new String[] { "_ID", "CODE", "NAME", "RSSURL" };
static final int CURSOR_SEARCH_ID = 0;
static final int CURSOR_SEARCH_NAME = 1;
static final int CURSOR_SEARCH_TORRENTURL = 2;
static final int CURSOR_SEARCH_DETAILSURL = 3;
static final int CURSOR_SEARCH_SIZE = 4;
static final int CURSOR_SEARCH_ADDED = 5;
static final int CURSOR_SEARCH_SEEDERS = 6;
static final int CURSOR_SEARCH_LEECHERS = 7;
static final int CURSOR_SITE_ID = 0;
static final int CURSOR_SITE_CODE = 1;
static final int CURSOR_SITE_NAME = 2;
static final int CURSOR_SITE_RSSURL = 3;
/**
* Returns the list of supported torrent search sites
* @param activity The displaying activity against which the query for Transdroid Torrent Search can be executed
* @return A cursor with search sites (with fields SITE_FIELDS)
*/
public static Cursor getSupportedSites(Activity activity) {
// Create the URI of the TorrentSitesProvider
String uriString = "content://org.transdroid.search.torrentsitesprovider/sites";
Uri uri = Uri.parse(uriString);
// Then query all torrent sites (no selection nor projection nor sort):
return activity.managedQuery(uri, null, null, null, null);
}
/**
* Build an RSS feed URL for some site and some user query
* @param activity The calling activity (used to connect to Transdroid Torrent Search)
* @param preferencesKey The Transdroid-preferences key, e.g. 'site_mininova'
* @param query The user query that was searched for
* @return The RSS feed URL, or null if the site isn't supporting RSS feeds (or no site with preferencesKey exists)
*/
public static String buildRssFeedFromSearch(Activity activity, String preferencesKey, String query) {
String key = Preferences.getCursorKeyForPreferencesKey(preferencesKey);
Cursor cursor = getSupportedSites(activity);
if (cursor.moveToFirst()) {
do {
if (cursor.getString(CURSOR_SITE_CODE).equals(key)) {
if (cursor.getString(CURSOR_SITE_RSSURL) == null || cursor.getString(CURSOR_SITE_RSSURL).equals("")) {
// Not supported by this site
return null;
}
return cursor.getString(CURSOR_SITE_RSSURL).replace("%s", query);
}
} while (cursor.moveToNext());
}
// Site is not supported by Transdroid Torrent Search
return null;
}
/**
* Return whether Transdroid Torrent Search is installed and available to query against
* @return True if the available sites can be retrieved from the content provider, false otherwise
*/
public static boolean isTorrentSearchInstalled(Activity activity) {
return getSupportedSites(activity) != null;
}
private Activity activity;
public TorrentSearchTask(Activity activity) {
this.activity = activity;
}
@Override
protected final Cursor doInBackground(String... params) {
// Search query, site and sort order specified?
if (params == null || params.length != 3) {
return null;
}
// Create the URI of the TorrentProvider
String uriString = "content://org.transdroid.search.torrentsearchprovider/search/" + params[0];
Uri uri = Uri.parse(uriString);
// Then query for this specific search, site and sort order
return activity.managedQuery(uri, null, "SITE = ?", new String[] { params[1] }, params[2]);
// Actual catching of run-time exceptions doesn't work cross-process
/*
* } catch (RuntimeException e) { // Hold on to the error message; onPostExecute will post it back to
* make sure it's posted on the UI thread errorMessage = e.toString(); return null; }
*/
}
@Override
protected final void onPostExecute(Cursor cursor) {
if (cursor == null)
onError();
else
onResultsRetrieved(cursor);
}
/**
* Method that needs to be implemented to handle the search results
*
* @param errorMessage
* The (technical) error message text
*/
protected abstract void onResultsRetrieved(Cursor cursor);
/**
* Method that needs to be implemented to catch error occurring during the retrieving or parsing of search
* results
*/
protected abstract void onError();
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.gui.search;
/**
* The default search activity, but extended to provide a
* separate class for the Quick Search Box expose.
*
* @author erickok
*/
public class GlobalTorrentSearch extends Search {
}
| Java |
package org.transdroid.gui;
import java.util.List;
import org.example.qberticus.quickactions.BetterPopupWindow;
import org.transdroid.R;
import org.transdroid.gui.util.ArrayAdapter;
import android.content.Context;
import android.graphics.Rect;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
public class TorrentViewSelectorWindow extends BetterPopupWindow {
private final MainViewTypeSelectionListener mainViewTypeSelectionListener;
private final LabelSelectionListener labelSelectionListener;
private ViewGroup rootView;
private ListView labelsListView;
private LayoutInflater inflater;
public TorrentViewSelectorWindow(View anchor, MainViewTypeSelectionListener mainViewTypeSelectionListener, LabelSelectionListener labelSelectionListener) {
super(anchor);
this.mainViewTypeSelectionListener = mainViewTypeSelectionListener;
this.labelSelectionListener = labelSelectionListener;
}
@Override
protected void onCreate() {
// Inflate layout
inflater = (LayoutInflater) this.anchor.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rootView = (ViewGroup) inflater.inflate(R.layout.part_quickaction, null);
// Setup button events
((ImageButton)rootView.findViewById(R.id.showall)).setOnClickListener(getOnMainViewTypeClickListener(MainViewType.ShowAll));
((ImageButton)rootView.findViewById(R.id.showdl)).setOnClickListener(getOnMainViewTypeClickListener(MainViewType.OnlyDownloading));
((ImageButton)rootView.findViewById(R.id.showup)).setOnClickListener(getOnMainViewTypeClickListener(MainViewType.OnlyUploading));
((ImageButton)rootView.findViewById(R.id.showactive)).setOnClickListener(getOnMainViewTypeClickListener(MainViewType.OnlyActive));
((ImageButton)rootView.findViewById(R.id.showinactive)).setOnClickListener(getOnMainViewTypeClickListener(MainViewType.OnlyInactive));
labelsListView = (ListView) rootView.findViewById(R.id.labelsList);
labelsListView.setOnItemClickListener(onLabelClickListener);
// set the inflated view as what we want to display
this.setContentView(rootView);
}
@Override
public void showLikePopDownMenu() {
// Place arrow
int[] location = new int[2];
anchor.getLocationOnScreen(location);
Rect anchorRect = new Rect(location[0], location[1], location[0] + anchor.getWidth(), location[1] + anchor.getHeight());
final ImageView arrow = (ImageView) rootView.findViewById(R.id.arrow_up);
ViewGroup.MarginLayoutParams param = (ViewGroup.MarginLayoutParams)arrow.getLayoutParams();
final int arrowWidth = arrow.getMeasuredWidth();
param.leftMargin = anchorRect.centerX() - arrowWidth / 2;
super.showLikePopDownMenu();
}
@SuppressWarnings("unchecked")
public void updateLabels(List<String> availableLabels) {
// Update the labels list
if (labelsListView.getAdapter() == null) {
labelsListView.setAdapter(new ArrayAdapter<String>(this.anchor.getContext(), availableLabels) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the right view, using a ViewHolder
ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_item_label, null);
holder = new ViewHolder();
holder.text1 = (TextView) convertView.findViewById(android.R.id.text1);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// Bind the data
holder.text1.setText(getItem(position));
return convertView;
}
});
} else {
((ArrayAdapter<String>)labelsListView.getAdapter()).replace(availableLabels);
}
labelsListView.setVisibility(availableLabels.size() > 0? View.VISIBLE: View.GONE);
labelsListView.setOnItemClickListener(onLabelClickListener);
}
protected static class ViewHolder {
TextView text1;
}
private OnClickListener getOnMainViewTypeClickListener(final MainViewType type) {
return new OnClickListener() {
@Override
public void onClick(View v) {
mainViewTypeSelectionListener.onMainViewTypeSelected(type);
TorrentViewSelectorWindow.this.dismiss();
}
};
}
private OnItemClickListener onLabelClickListener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
labelSelectionListener.onLabelSelected(position);
TorrentViewSelectorWindow.this.dismiss();
}
};
public static abstract class MainViewTypeSelectionListener {
public abstract void onMainViewTypeSelected(MainViewType newType);
}
public static abstract class LabelSelectionListener {
public abstract void onLabelSelected(int labelPosition);
}
}
| Java |
package org.transdroid.gui;
import java.util.ArrayList;
import org.transdroid.R;
import org.transdroid.daemon.Daemon;
import org.transdroid.daemon.Torrent;
import org.transdroid.daemon.TorrentDetails;
import org.transdroid.daemon.TorrentFile;
import org.transdroid.daemon.TorrentStatus;
import org.transdroid.daemon.util.FileSizeConverter;
import android.text.format.DateFormat;
import android.text.format.DateUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.TableRow;
import android.widget.TextView;
import com.commonsware.cwac.merge.MergeAdapter;
public class DetailsListAdapter extends MergeAdapter {
private static final String DECIMAL_FORMATTER = "%.1f";
private DetailsFragment detailsFragment;
private Torrent torrent;
private TorrentDetails fineDetails;
private TorrentFileListAdapter filesAdapter;
private View detailsfields;
private TextView dateAdded, name, state, size, downloaded, uploaded, rate, eta, peers, availability, label,
trackers, trackershint, errors, errorshint;
private TableRow dateAddedRow, availabilityRow, labelRow, trackers1Row, trackers2Row, errors1Row, errors2Row;
private ImageButton resumepause, startstop, remove, setlabel;
private boolean showingTrackers = false;
private boolean showingErrors = false;
public DetailsListAdapter(DetailsFragment detailsFragment, Torrent torrent, TorrentDetails fineDetails) {
this.detailsFragment = detailsFragment;
this.torrent = torrent;
this.fineDetails = fineDetails;
// Add the standard details fields form details_header.xml
detailsfields = detailsFragment.getActivity().getLayoutInflater().inflate(R.layout.part_details_header, null);
addView(detailsfields);
dateAdded = (TextView) findViewById(R.id.details_dateadded);
name = (TextView) findViewById(R.id.details_name);
state = (TextView) findViewById(R.id.details_state);
size = (TextView) findViewById(R.id.details_size);
downloaded = (TextView) findViewById(R.id.details_downloaded);
uploaded = (TextView) findViewById(R.id.details_uploaded);
rate = (TextView) findViewById(R.id.details_rate);
eta = (TextView) findViewById(R.id.details_eta);
peers = (TextView) findViewById(R.id.details_peers);
availability = (TextView) findViewById(R.id.details_availability);
label = (TextView) findViewById(R.id.details_label);
trackers = (TextView) findViewById(R.id.details_trackers);
trackershint = (TextView) findViewById(R.id.details_trackershint);
trackershint.setOnClickListener(onTrackersExpandClick);
errors = (TextView) findViewById(R.id.details_errors);
errorshint = (TextView) findViewById(R.id.details_errorshint);
errorshint.setOnClickListener(onErrorsExpandClick);
dateAddedRow = (TableRow) findViewById(R.id.detailsrow_dateadded);
availabilityRow = (TableRow) findViewById(R.id.detailsrow_availability);
labelRow = (TableRow) findViewById(R.id.detailsrow_label);
trackers1Row = (TableRow) findViewById(R.id.detailsrow_trackers1);
trackers2Row = (TableRow) findViewById(R.id.detailsrow_trackers2);
errors1Row = (TableRow) findViewById(R.id.detailsrow_errors1);
errors2Row = (TableRow) findViewById(R.id.detailsrow_errors2);
resumepause = (ImageButton) findViewById(R.id.resumepause);
startstop = (ImageButton) findViewById(R.id.startstop);
remove = (ImageButton) findViewById(R.id.remove);
setlabel = (ImageButton) findViewById(R.id.setlabel);
resumepause.setOnClickListener(onResumePause);
startstop.setOnClickListener(onStartStop);
remove.setOnClickListener(onRemove);
setlabel.setOnClickListener(onSetLabel);
filesAdapter = new TorrentFileListAdapter(detailsFragment, new ArrayList<TorrentFile>());
addAdapter(filesAdapter);
updateViewsAndButtonStates();
}
private View findViewById(int id) {
return detailsfields.findViewById(id);
}
public Torrent getTorrent() {
return this.torrent;
}
public TorrentFileListAdapter getTorrentFileAdapter() {
return filesAdapter;
}
public void setTorrent(Torrent torrent) {
this.torrent = torrent;
}
public void setTorrentDetails(TorrentDetails fineDetails) {
this.fineDetails = fineDetails;
}
void updateViewsAndButtonStates() {
if (name != null) {
// In case we have a name field (i.e. in tablet layouts)
name.setText(torrent.getName());
}
// Update textviews according to the torrent data
LocalTorrent local = LocalTorrent.fromTorrent(torrent);
if (torrent.getDateAdded() != null) {
dateAdded.setText(DateUtils.formatDateTime(detailsFragment.getActivity(), torrent.getDateAdded().getTime(), DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE));
dateAddedRow.setVisibility(View.VISIBLE);
} else {
dateAddedRow.setVisibility(View.GONE);
}
state.setText(torrent.getStatusCode().toString());
size.setText(FileSizeConverter.getSize(torrent.getTotalSize()));
downloaded.setText(FileSizeConverter.getSize(torrent.getDownloadedEver()) + " (" +
String.format(DECIMAL_FORMATTER, torrent.getDownloadedPercentage() * 100) + "%)");
uploaded.setText(FileSizeConverter.getSize(torrent.getUploadedEver()) + " (" +
detailsFragment.getString(R.string.status_ratio, local.getRatioString()) + ")");
rate.setText(local.getProgressSpeedText(detailsFragment.getResources()));
if (torrent.getStatusCode() == TorrentStatus.Downloading) {
eta.setText(local.getRemainingTimeString(detailsFragment.getResources(), true));
availability.setText(String.format(DECIMAL_FORMATTER, torrent.getAvailability() * 100) + "%");
availabilityRow.setVisibility(View.VISIBLE);
} else {
eta.setText("");
availability.setText("");
availabilityRow.setVisibility(View.GONE);
}
peers.setText(local.getProgressConnectionText(detailsFragment.getResources()));
label.setText((torrent.getLabelName() == null || torrent.getLabelName().equals(""))?
detailsFragment.getString(R.string.labels_unlabeled): torrent.getLabelName());
if (fineDetails == null || fineDetails.getTrackers() == null) {
trackers.setText("");
trackershint.setText("");
} else {
trackers.setText(fineDetails.getTrackersText());
if (showingTrackers) {
trackershint.setText(detailsFragment.getString(R.string.details_trackers_collapse));
} else {
trackershint.setText(detailsFragment.getString(R.string.details_trackers_expand,
fineDetails.getTrackers().size() > 0? fineDetails.getTrackers().get(0): ""));
}
}
String errorsText =
torrent.getError() != null? torrent.getError() +
(fineDetails != null && fineDetails.getErrors() != null && !fineDetails.getErrors().isEmpty()? "\n" + fineDetails.getErrorsText(): ""):
(fineDetails != null && fineDetails.getErrors() != null && !fineDetails.getErrors().isEmpty()? fineDetails.getErrorsText():
null);
if (errorsText == null || errorsText.equals("")) {
errors.setText("");
errorshint.setText("");
} else {
errors.setText(errorsText);
if (showingErrors) {
errorshint.setText(detailsFragment.getString(R.string.details_trackers_collapse));
} else {
String[] err = errorsText.split("\n");
errorshint.setText(detailsFragment.getString(R.string.details_trackers_expand,
err.length >= 0? err[0]: ""));
}
}
availabilityRow.setVisibility(Daemon.supportsAvailability(detailsFragment.getActiveDaemonType())? View.VISIBLE: View.GONE);
labelRow.setVisibility(Daemon.supportsLabels(detailsFragment.getActiveDaemonType())? View.VISIBLE: View.GONE);
trackers1Row.setVisibility(Daemon.supportsFineDetails(detailsFragment.getActiveDaemonType())? View.VISIBLE: View.GONE);
trackers2Row.setVisibility(showingTrackers? View.VISIBLE: View.GONE);
errors1Row.setVisibility(errorsText != null? View.VISIBLE: View.GONE);
errors2Row.setVisibility(showingErrors? View.VISIBLE: View.GONE);
// Update buttons
if (torrent.canPause()) {
resumepause.setImageResource(R.drawable.icon_pause);
} else {
resumepause.setImageResource(R.drawable.icon_resume);
}
if (Daemon.supportsStoppingStarting(detailsFragment.getActiveDaemonType())) {
if (torrent.canStop()) {
startstop.setImageResource(R.drawable.icon_stop);
} else {
startstop.setImageResource(R.drawable.icon_start);
}
} else {
startstop.setVisibility(View.GONE);
}
setlabel.setVisibility(Daemon.supportsSetLabel(detailsFragment.getActiveDaemonType())? View.VISIBLE: View.GONE);
}
private OnClickListener onTrackersExpandClick = new OnClickListener() {
@Override
public void onClick(View v) {
// Show (or hide) the list of full trackers (and adjust the hint text accordingly)
showingTrackers = !showingTrackers;
trackers2Row.setVisibility(showingTrackers? View.VISIBLE: View.GONE);
if (showingTrackers) {
trackershint.setText(detailsFragment.getString(R.string.details_trackers_collapse));
} else {
trackershint.setText(detailsFragment.getString(R.string.details_trackers_expand,
fineDetails != null && fineDetails.getTrackers() != null && fineDetails.getTrackers().size() > 0?
fineDetails.getTrackers().get(0): ""));
}
}
};
private OnClickListener onErrorsExpandClick = new OnClickListener() {
@Override
public void onClick(View v) {
// Show (or hide) the list of full trackers (and adjust the hint text accordingly)
showingErrors = (torrent.getError() != null || (fineDetails != null &&
fineDetails.getErrors() != null && !fineDetails.getErrors().isEmpty())) && !showingErrors;
errors2Row.setVisibility(showingErrors? View.VISIBLE: View.GONE);
if (showingErrors) {
errorshint.setText(detailsFragment.getString(R.string.details_trackers_collapse));
} else {
errorshint.setText(detailsFragment.getString(R.string.details_trackers_expand,
fineDetails != null && fineDetails.getErrors() != null && fineDetails.getErrors().size() > 0?
fineDetails.getErrors().get(0): ""));
}
}
};
private OnClickListener onResumePause = new OnClickListener() {
@Override
public void onClick(View v) {
if (torrent.canPause()) {
detailsFragment.pauseTorrent();
} else {
detailsFragment.resumeTorrent();
}
}
};
private OnClickListener onStartStop = new OnClickListener() {
@Override
public void onClick(View v) {
if (torrent.canStop()) {
detailsFragment.stopTorrent();
} else {
detailsFragment.startTorrent(false);
}
}
};
private OnClickListener onRemove = new OnClickListener() {
@Override
public void onClick(View v) {
detailsFragment.showDialog(DetailsFragment.DIALOG_ASKREMOVE);
}
};
private OnClickListener onSetLabel = new OnClickListener() {
@Override
public void onClick(View v) {
detailsFragment.showDialog(DetailsFragment.DIALOG_SETLABEL);
}
};
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.gui;
import org.transdroid.R;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;
public class TorrentProgressBar extends View {
private final float scale = getContext().getResources().getDisplayMetrics().density;
private final float ROUND_SIZE = 3.3f * scale;
private final int MINIMUM_HEIGHT = (int)(8 * scale + 0.5f);
private final int RIGHT_MARGIN = (int)(3 * scale + 0.5f);
private int progress;
private boolean isActive;
private boolean isError;
private final Paint notdonePaint = new Paint();
private final Paint inactiveDonePaint = new Paint();
private final Paint inactivePaint = new Paint();
private final Paint progressPaint = new Paint();
private final Paint donePaint = new Paint();
private final Paint errorPaint = new Paint();
public void setProgress(int progress) {
this.progress = progress;
this.invalidate();
}
public void setActive(boolean isActive) {
this.isActive = isActive;
this.invalidate();
}
public void setError(boolean isError) {
this.isError = isError;
this.invalidate();
}
public TorrentProgressBar(Context context) {
super(context);
initPaints();
}
public TorrentProgressBar(Context context, AttributeSet attrs) {
super(context, attrs);
initPaints();
// Parse any set attributes from XML
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TorrentProgressBar);
if (a.hasValue(R.styleable.TorrentProgressBar_progress)) {
this.progress = a.getIndex(R.styleable.TorrentProgressBar_progress);
this.isActive = a.getBoolean(R.styleable.TorrentProgressBar_isActive, false);
}
a.recycle();
}
private void initPaints() {
notdonePaint.setColor(0xFFEEEEEE);
inactiveDonePaint.setColor(0xFFA759D4);
inactivePaint.setColor(0xFF9E9E9E);
progressPaint.setColor(0xFF42A8FA);
donePaint.setColor(0xFF8CCF29);
errorPaint.setColor(0xFFDE3939);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int ws = MeasureSpec.getSize(widthMeasureSpec) - RIGHT_MARGIN;
int hs = Math.max(getHeight(), MINIMUM_HEIGHT);
setMeasuredDimension(ws, hs);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int height = getHeight();
int width = getWidth();
RectF fullRect = new RectF(0, 0, width, height);
// Error?
if (isError) {
canvas.drawRoundRect(fullRect, ROUND_SIZE, ROUND_SIZE, errorPaint);
} else {
// Background rounded rectangle
canvas.drawRoundRect(fullRect, ROUND_SIZE, ROUND_SIZE, notdonePaint);
// Foreground progress indicator
if (progress > 0) {
RectF progressRect = new RectF(0, 0, width * ((float)progress / 100), height);
canvas.drawRoundRect(progressRect, ROUND_SIZE, ROUND_SIZE,
(isActive? (progress == 100? donePaint: progressPaint): (progress == 100? inactiveDonePaint: inactivePaint)));
}
}
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.gui;
import org.transdroid.R;
import org.transdroid.daemon.Torrent;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import com.actionbarsherlock.app.SherlockFragmentActivity;
public class Details extends SherlockFragmentActivity {
//private static final String LOG_NAME = "Details";
public static final String STATE_DAEMON = "transdroid_state_details_daemon";
public static final String STATE_LABELS = "transdroid_state_details_labels";
public static final String STATE_TORRENT = "transdroid_state_details_torrent";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
getSupportActionBar().setDisplayShowTitleEnabled(true);
if (savedInstanceState == null) {
Intent i = getIntent();
// Get torrent and daemon form the new intent
int daemonNumber = i.getIntExtra(STATE_DAEMON, 0);
String[] existingLabels = i.getStringArrayExtra(STATE_LABELS);
Torrent torrent = i.getParcelableExtra(STATE_TORRENT);
// Start the fragment for this torrent
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.details, new DetailsFragment(null, daemonNumber, torrent, existingLabels));
if (getSupportFragmentManager().findFragmentById(R.id.details) != null) {
ft.addToBackStack(null);
}
ft.commit();
}
}
} | Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.gui;
import java.util.List;
import org.transdroid.R;
import org.transdroid.daemon.DaemonSettings;
import org.transdroid.preferences.Preferences;
import org.transdroid.preferences.PreferencesAdapter;
import android.app.ListActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.Intent.ShortcutIconResource;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.ListView;
public class ServerSelection extends ListActivity {
private SharedPreferences prefs;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_serverselection);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
// List the daemons
List<DaemonSettings> daemons = Preferences.readAllDaemonSettings(prefs);
setListAdapter(new PreferencesAdapter(this, daemons));
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// Perform click action depending on the clicked list item (note that dividers are ignored)
Object item = getListAdapter().getItem(position);
if (item instanceof DaemonSettings) {
// Get selected server
DaemonSettings daemon = (DaemonSettings) item;
Intent startIntent = new Intent(this, Torrents.class);
startIntent.putExtra(Transdroid.INTENT_OPENDAEMON, daemon.getIdString());
// Return the a shortcut intent for the selected server
Intent i = new Intent();
ShortcutIconResource icon = Intent.ShortcutIconResource.fromContext(this, R.drawable.icon);
i.putExtra(Intent.EXTRA_SHORTCUT_INTENT, startIntent);
i.putExtra(Intent.EXTRA_SHORTCUT_NAME, daemon.getName());
i.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
setResult(RESULT_OK, i);
finish();
}
}
}
| Java |
package org.transdroid.gui;
import org.transdroid.daemon.IDaemonCallback;
import org.transdroid.daemon.task.DaemonTask;
import org.transdroid.daemon.task.DaemonTaskFailureResult;
import org.transdroid.daemon.task.DaemonTaskSuccessResult;
import android.os.Handler;
import android.os.Message;
/**
* The Task result handler is a mediator between the worker and UI threads. It post
* back results from the executed tasks to itself (using the Handler class) and
* post this results (now on the UI thread) back to the original IDaemonCallback.
*
* @author erickok
*
*/
public class TaskResultHandler extends Handler implements IDaemonCallback {
private static final int QUEUE_EMPTY = 0;
private static final int TASK_FINISHED = 1;
private static final int TASK_STARTED = 2;
private static final int TASK_FAILURE = 3;
private static final int TASK_SUCCESS = 4;
private IDaemonCallback callback;
public TaskResultHandler(IDaemonCallback callback) {
this.callback = callback;
}
@Override
public void handleMessage(Message msg) {
// We are now on the UI thread again, call the original method on the IDaemonCallback
switch (msg.what) {
case QUEUE_EMPTY:
callback.onQueueEmpty();
break;
case TASK_FINISHED:
callback.onQueuedTaskFinished((DaemonTask) msg.obj);
break;
case TASK_STARTED:
callback.onQueuedTaskStarted((DaemonTask) msg.obj);
break;
case TASK_FAILURE:
callback.onTaskFailure((DaemonTaskFailureResult) msg.obj);
break;
case TASK_SUCCESS:
callback.onTaskSuccess((DaemonTaskSuccessResult) msg.obj);
break;
}
}
@Override
public void onQueueEmpty() {
Message msg = Message.obtain(this);
msg.what = QUEUE_EMPTY;
sendMessage(msg);
}
@Override
public void onQueuedTaskFinished(DaemonTask finished) {
Message msg = Message.obtain(this);
msg.what = TASK_FINISHED;
msg.obj = finished;
sendMessage(msg);
}
@Override
public void onQueuedTaskStarted(DaemonTask started) {
Message msg = Message.obtain(this);
msg.what = TASK_STARTED;
msg.obj = started;
sendMessage(msg);
}
@Override
public void onTaskFailure(DaemonTaskFailureResult result) {
Message msg = Message.obtain(this);
msg.what = TASK_FAILURE;
msg.obj = result;
sendMessage(msg);
}
@Override
public void onTaskSuccess(DaemonTaskSuccessResult result) {
Message msg = Message.obtain(this);
msg.what = TASK_SUCCESS;
msg.obj = result;
sendMessage(msg);
}
@Override
public boolean isAttached() {
return callback.isAttached();
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.gui;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
public enum MainViewType {
ShowAll (1),
OnlyDownloading (2),
OnlyUploading (3),
OnlyInactive (4),
OnlyActive (5);
private int code;
private static final Map<Integer,MainViewType> lookup = new HashMap<Integer,MainViewType>();
static {
for(MainViewType s : EnumSet.allOf(MainViewType.class))
lookup.put(s.getCode(), s);
}
MainViewType(int code) {
this.code = code;
}
public int getCode() {
return code;
}
public static MainViewType getMainViewType(int code) {
return lookup.get(code);
}
}
| Java |
package org.transdroid.gui;
import org.transdroid.R;
import android.app.Dialog;
import android.content.Context;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
/**
* A dialog that shows a list of (existing) labels to choose from as well as
* give a free text input to assign a new label. If the chosen label is
* different form the current (already assigned) label, onLabelResult is
* called with the new-to-be-assigned label.
*
* @author erickok
*/
public class SetLabelDialog extends Dialog {
private ResultListener callback;
private String currentLabel;
private ListView existingLabelsList;
private EditText newLabelText;
private Button okButton;
/**
* Callback listener for when a label is either selected or entered by the user
*/
public interface ResultListener {
/**
* Called when the label result is known and different form the current (already assigned) label
* @param label The chosen or newly entered label (to be assigned to a torrent)
*/
public void onLabelResult(String label);
}
/**
* Constructor for the labels dialog
* @param context The activity context
* @param callback The activity that will handle the dialog result (being the to be assigned label string)
* @param existingLabels The labels to list as existing
* @param currentLabel The currently assigned label to the torrent
*/
public SetLabelDialog(Context context, ResultListener callback, String[] existingLabels, String currentLabel) {
super(context);
this.callback = callback;
this.currentLabel = currentLabel;
// Custom layout
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.dialog_new_label);
existingLabelsList = (ListView) findViewById(R.id.labels);
newLabelText = (EditText) findViewById(R.id.new_label);
okButton = (Button) findViewById(R.id.set_button);
newLabelText.setText(currentLabel);
// Set content and attach listeners
existingLabelsList.setAdapter(new ArrayAdapter<String>(context, R.layout.list_item_label, existingLabels));
existingLabelsList.setOnItemClickListener(onLabelSelected);
okButton.setOnClickListener(onNewLabelClick);
}
public void resetDialog(Context context, String[] existingLabels, String currentLabel) {
// Update the available existing labels and empty the text box
this.currentLabel = currentLabel;
existingLabelsList.setAdapter(new ArrayAdapter<String>(context, R.layout.list_item_label, existingLabels));
newLabelText.setText(currentLabel);
}
private OnItemClickListener onLabelSelected = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Set the result to be the selected item in the list
returnResult((String) existingLabelsList.getItemAtPosition(position));
}
};
private View.OnClickListener onNewLabelClick = new View.OnClickListener() {
@Override
public void onClick(View v) {
// Set the result to be the current EditText input
returnResult(newLabelText.getText().toString());
}
};
private void returnResult(String label) {
// Return result (if needed) and close the dialog
if (currentLabel == null || !currentLabel.equals(label)) {
callback.onLabelResult(label);
}
dismiss();
}
}
| Java |
package org.transdroid.gui;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.transdroid.R;
import org.transdroid.daemon.Daemon;
import org.transdroid.daemon.DaemonSettings;
import org.transdroid.daemon.IDaemonAdapter;
import org.transdroid.daemon.IDaemonCallback;
import org.transdroid.daemon.Priority;
import org.transdroid.daemon.TaskQueue;
import org.transdroid.daemon.Torrent;
import org.transdroid.daemon.TorrentDetails;
import org.transdroid.daemon.TorrentFile;
import org.transdroid.daemon.TorrentFilesComparator;
import org.transdroid.daemon.TorrentFilesSortBy;
import org.transdroid.daemon.task.DaemonTask;
import org.transdroid.daemon.task.DaemonTaskFailureResult;
import org.transdroid.daemon.task.DaemonTaskSuccessResult;
import org.transdroid.daemon.task.GetFileListTask;
import org.transdroid.daemon.task.GetFileListTaskSuccessResult;
import org.transdroid.daemon.task.GetTorrentDetailsTask;
import org.transdroid.daemon.task.GetTorrentDetailsTaskSuccessResult;
import org.transdroid.daemon.task.PauseTask;
import org.transdroid.daemon.task.RemoveTask;
import org.transdroid.daemon.task.ResumeTask;
import org.transdroid.daemon.task.RetrieveTask;
import org.transdroid.daemon.task.RetrieveTaskSuccessResult;
import org.transdroid.daemon.task.SetDownloadLocationTask;
import org.transdroid.daemon.task.SetFilePriorityTask;
import org.transdroid.daemon.task.SetLabelTask;
import org.transdroid.daemon.task.SetTrackersTask;
import org.transdroid.daemon.task.StartTask;
import org.transdroid.daemon.task.StopTask;
import org.transdroid.gui.SetLabelDialog.ResultListener;
import org.transdroid.gui.util.ActivityUtil;
import org.transdroid.gui.util.DialogWrapper;
import org.transdroid.gui.util.SelectableArrayAdapter.OnSelectedChangedListener;
import org.transdroid.preferences.Preferences;
import org.transdroid.util.TLog;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentTransaction;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
@SuppressLint("ValidFragment")
public class DetailsFragment extends SherlockFragment implements IDaemonCallback, OnSelectedChangedListener {
private static final String LOG_NAME = "Details fragment";
private static final int FILEMENU_SETPRIORITY_ID = 0;
private static final int FILEMENU_SETOFF_ID = 1;
private static final int FILEMENU_SETLOW_ID = 2;
private static final int FILEMENU_SETNORMAL_ID = 3;
private static final int FILEMENU_SETHIGH_ID = 4;
private static final int FILEMENU_REMOTESTART_ID = 5;
private static final int FILEMENU_FTPDOWNLOAD_ID = 6;
private static final int MENU_FORCESTART_ID = 50;
private static final int MENU_SETLOCATION_ID = 51;
private static final int MENU_EDITTRACKERS_ID = 52;
private static final int MENU_INVERTSELECTION_ID = 53;
private static final int MENU_REFRESH_ID = 54;
static final int DIALOG_ASKREMOVE = 11;
private static final int DIALOG_INSTALLVLC = 12;
private static final int DIALOG_INSTALLFTPCLIENT = 13;
static final int DIALOG_SETLABEL = 14;
private static final int DIALOG_SETLOCATION = 15;
private static final int DIALOG_EDITTRACKERS = 16;
TorrentFilesSortBy sortSetting = TorrentFilesSortBy.Alphanumeric;
boolean sortReversed = false;
private final TorrentsFragment torrentsFragment;
private final int daemonNumber;
private Torrent torrent;
private TorrentDetails fineDetails = null;
private String[] existingLabels;
private IDaemonAdapter daemon;
private TaskQueue queue;
private LinearLayout prioBar;
private Button prioOff, prioLow, prioNormal, prioHigh;
/**
* Public empty constructor for use with fragment retainment (setRetainInstance(true);)
*/
public DetailsFragment() {
this.torrentsFragment = null;
this.daemonNumber = -1;
}
public DetailsFragment(TorrentsFragment torrentsFragment, int daemonNumber, Torrent torrent, String[] existingLabels) {
this.torrentsFragment = torrentsFragment;
this.daemonNumber = daemonNumber;
this.torrent = torrent;
this.existingLabels = existingLabels;
setHasOptionsMenu(true);
setRetainInstance(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_details, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
registerForContextMenu(getListView());
getListView().setTextFilterEnabled(true);
getListView().setOnItemClickListener(onFileClicked);
prioBar = (LinearLayout) findViewById(R.id.setprio);
prioOff = (Button) findViewById(R.id.setprio_off);
prioLow = (Button) findViewById(R.id.setprio_low);
prioNormal = (Button) findViewById(R.id.setprio_normal);
prioHigh = (Button) findViewById(R.id.setprio_high);
prioOff.setOnClickListener(setPriorityOffClicked);
prioLow.setOnClickListener(setPriorityLowClicked);
prioNormal.setOnClickListener(setPriorityNormalClicked);
prioHigh.setOnClickListener(setPriorityHighClicked);
// Set up a task queue
queue = new TaskQueue(new TaskResultHandler(this));
queue.start();
loadData(true);
}
private void loadData(boolean clearOldData) {
if (torrent == null) {
TLog.d(LOG_NAME, "No torrent was provided in either the Intent or savedInstanceState.");
return;
}
// Setup the daemon
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
DaemonSettings daemonSettings = Preferences.readAllDaemonSettings(prefs).get(daemonNumber);
daemon = daemonSettings.getType().createAdapter(daemonSettings);
// Show the torrent details
getListView().setAdapter(new DetailsListAdapter(this, torrent, fineDetails));
getSherlockActivity().setTitle(torrent.getName());
if (Daemon.supportsFileListing(daemon.getType())) {
// Remove possibly old data and start loading the new file list
if (clearOldData) {
getDetailsListAdapter().getTorrentFileAdapter().clear();
queue.enqueue(GetFileListTask.create(daemon, torrent));
}
} else {
// Show that details are not (yet) supported by this adapter
// TODO: Show this in a textview rather than as a toast pop-up
Toast.makeText(getActivity(), R.string.details_notsupported, Toast.LENGTH_LONG).show();
}
if (Daemon.supportsFineDetails(daemon.getType()) && clearOldData) {
queue.enqueue(GetTorrentDetailsTask.create(daemon, torrent));
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
TorrentFile file = getDetailsListAdapter().getTorrentFileAdapter().getItem(
(int) ((AdapterContextMenuInfo) menuInfo).id);
if (Daemon.supportsFilePrioritySetting(daemon.getType())) {
menu.add(FILEMENU_SETPRIORITY_ID, FILEMENU_SETOFF_ID, 0, R.string.file_off);
menu.add(FILEMENU_SETPRIORITY_ID, FILEMENU_SETLOW_ID, 0, R.string.file_low);
menu.add(FILEMENU_SETPRIORITY_ID, FILEMENU_SETNORMAL_ID, 0, R.string.file_normal);
menu.add(FILEMENU_SETPRIORITY_ID, FILEMENU_SETHIGH_ID, 0, R.string.file_high);
}
// Show a remote play option if the server supports file paths and a mime type for this file can be
// inferred
if (Daemon.supportsFilePaths(daemon.getType()) && torrent.getLocationDir() != null
&& file.getMimeType() != null) {
menu.add(FILEMENU_REMOTESTART_ID, FILEMENU_REMOTESTART_ID, 0, R.string.file_remotestart);
}
if (Daemon.supportsFilePaths(daemon.getType()) && daemon.getSettings().getFtpUrl() != null &&
!daemon.getSettings().getFtpUrl().equals("") && file.getRelativePath() != null) {
menu.add(FILEMENU_FTPDOWNLOAD_ID, FILEMENU_FTPDOWNLOAD_ID, 0, R.string.file_ftpdownload);
}
}
@Override
public boolean onContextItemSelected(android.view.MenuItem item) {
// Get the selected file
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
TorrentFile file = getDetailsListAdapter().getTorrentFileAdapter().getItem((int) info.id);
if (item.getItemId() >= FILEMENU_SETOFF_ID && item.getItemId() <= FILEMENU_SETHIGH_ID) {
// Update the priority for this file
Priority newPriority = file.getPriority();
switch (item.getItemId()) {
case FILEMENU_SETOFF_ID:
newPriority = Priority.Off;
break;
case FILEMENU_SETLOW_ID:
newPriority = Priority.Low;
break;
case FILEMENU_SETNORMAL_ID:
newPriority = Priority.Normal;
break;
case FILEMENU_SETHIGH_ID:
newPriority = Priority.High;
break;
}
// Schedule a task to update this file's priority
queue.enqueue(SetFilePriorityTask.create(daemon, torrent, newPriority, file));
}
if (item.getItemId() == FILEMENU_REMOTESTART_ID) {
// Set up an intent to remotely play this file (in VLC)
Intent remote = new Intent(Transdroid.REMOTEINTENT);
remote.addCategory(Intent.CATEGORY_DEFAULT);
remote.setDataAndType(Uri.parse(file.getFullPathUri()), file.getMimeType());
remote.putExtra(Transdroid.REMOTEINTENT_HOST, daemon.getSettings().getAddress());
TLog.d(LOG_NAME, "Remote start requested for " + remote.getData() + " (" + remote.getType() + ")");
if (ActivityUtil.isIntentAvailable(getActivity(), remote)) {
startActivity(remote);
} else {
showDialog(DIALOG_INSTALLVLC);
}
}
if (item.getItemId() == FILEMENU_FTPDOWNLOAD_ID) {
// Set up an intent to download this file using the partial user-specified FTP URL
Uri ftpUri = Uri.parse(daemon.getSettings().getFtpUrl() + file.getRelativePath());
// Try with an AndFTP PICK Intent
Intent dl = new Intent(Intent.ACTION_PICK);
dl.setDataAndType(Uri.parse(ftpUri.getScheme() + "://" + ftpUri.getHost()), Transdroid.ANDFTP_INTENT_TYPE);
if (!ftpUri.getScheme().equals("alias")) {
// Assume the username and password are set if the alias:// construct is used
dl.putExtra(Transdroid.ANDFTP_INTENT_USER, (ftpUri.getEncodedUserInfo() == null ? daemon.getSettings()
.getUsername() : ftpUri.getEncodedUserInfo()));
dl.putExtra(Transdroid.ANDFTP_INTENT_PASS, daemon.getSettings().getFtpPassword());
}
dl.putExtra(Transdroid.ANDFTP_INTENT_PASV, "true");
dl.putExtra(Transdroid.ANDFTP_INTENT_CMD, "download");
// If the file is directly in the root, AndFTP fails if we supply the proper path (like /file.pdf)
// Work around this bug by removing the leading / if no further directories are used in the file path
dl.putExtra(Transdroid.ANDFTP_INTENT_FILE, ftpUri.getEncodedPath().startsWith("/") &&
ftpUri.getEncodedPath().indexOf("/", 1) < 0? ftpUri.getEncodedPath().substring(1): ftpUri.getEncodedPath());
dl.putExtra(Transdroid.ANDFTP_INTENT_LOCAL, "/sdcard/download");
TLog.d(LOG_NAME, "Requesting AndFTP transfer for " + dl.getStringExtra(Transdroid.ANDFTP_INTENT_FILE)
+ " from " + dl.getDataString());
if (ActivityUtil.isIntentAvailable(getActivity(), dl)) {
startActivity(dl);
} else {
showDialog(DIALOG_INSTALLFTPCLIENT);
}
}
return true;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
if (getActivity() instanceof Details) {
// Add title bar buttons
MenuItem miRefresh = menu.add(0, MENU_REFRESH_ID, 0, R.string.refresh);
miRefresh.setIcon(R.drawable.icon_refresh_title);
miRefresh.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
}
if (Daemon.supportsForcedStarting(daemon.getType())) {
MenuItem forced = menu.add(0, MENU_FORCESTART_ID, MENU_FORCESTART_ID, R.string.menu_forcestart);
forced.setIcon(R.drawable.icon_start_menu);
}
if (Daemon.supportsSetDownloadLocation(daemon.getType())) {
MenuItem location = menu
.add(0, MENU_SETLOCATION_ID, MENU_SETLOCATION_ID, R.string.menu_setdownloadlocation);
location.setIcon(android.R.drawable.ic_menu_upload);
}
if (Daemon.supportsSetTrackers(daemon.getType()) && fineDetails != null) {
MenuItem trackers = menu.add(0, MENU_EDITTRACKERS_ID, MENU_EDITTRACKERS_ID, R.string.menu_edittrackers);
trackers.setIcon(R.drawable.icon_trackers);
}
MenuItem invert = menu.add(0, MENU_INVERTSELECTION_ID, MENU_INVERTSELECTION_ID, R.string.menu_invertselection);
invert.setIcon(R.drawable.icon_mark);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_REFRESH_ID:
refreshActivity();
break;
case MENU_FORCESTART_ID:
queue.enqueue(StartTask.create(daemon, torrent, true));
return true;
case MENU_SETLOCATION_ID:
showDialog(DIALOG_SETLOCATION);
return true;
case MENU_EDITTRACKERS_ID:
showDialog(DIALOG_EDITTRACKERS);
return true;
case MENU_INVERTSELECTION_ID:
// Invert the current file selection
getDetailsListAdapter().getTorrentFileAdapter().invertSelection();
getListView().invalidateViews();
return true;
}
return super.onOptionsItemSelected(item);
}
private void onTorrentFilesLoaded(List<TorrentFile> allFiles) {
if (allFiles != null && getView() != null) {
Collections.sort(allFiles, new TorrentFilesComparator(TorrentFilesSortBy.Alphanumeric, false));
getDetailsListAdapter().getTorrentFileAdapter().replace(allFiles);
}
}
OnClickListener onResumePause = new OnClickListener() {
@Override
public void onClick(View v) {
if (torrent.canPause()) {
queue.enqueue(PauseTask.create(daemon, torrent));
} else {
queue.enqueue(ResumeTask.create(daemon, torrent));
}
}
};
OnClickListener onStartStop = new OnClickListener() {
@Override
public void onClick(View v) {
if (torrent.canStop()) {
queue.enqueue(StopTask.create(daemon, torrent));
} else {
queue.enqueue(StartTask.create(daemon, torrent, false));
}
}
};
OnClickListener onRemove = new OnClickListener() {
@Override
public void onClick(View v) {
showDialog(DIALOG_ASKREMOVE);
}
};
OnClickListener onSetLabel = new OnClickListener() {
@Override
public void onClick(View v) {
showDialog(DIALOG_SETLABEL);
}
};
private void setNewLabel(String newLabel) {
if (!Daemon.supportsSetLabel(daemon.getType())) {
// The daemon type does not support setting the label of a torrent
Toast.makeText(getActivity(), R.string.labels_no_support, Toast.LENGTH_LONG).show();
return;
}
// Mimic that we have already set the label (for a response feel)
torrent.mimicNewLabel(newLabel);
getDetailsListAdapter().updateViewsAndButtonStates();
String saveLabel = newLabel;
if (newLabel.equals(getString(R.string.labels_unlabeled).toString())) {
// Setting a torrent to 'unlabeled' is actually setting the label to an empty string
saveLabel = "";
}
queue.enqueue(SetLabelTask.create(daemon, torrent, saveLabel));
queue.enqueue(RetrieveTask.create(daemon));
}
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_ASKREMOVE:
// Build a dialog that asks to confirm the deletions of a torrent
AlertDialog.Builder askRemoveDialog = new AlertDialog.Builder(getActivity());
askRemoveDialog.setTitle(R.string.askremove_title);
askRemoveDialog.setMessage(R.string.askremove);
askRemoveDialog.setPositiveButton(R.string.menu_remove, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
// Starts the remove task; we won't close this details dialog until its result is returned
queue.enqueue(RemoveTask.create(daemon, torrent, false));
dismissDialog(DIALOG_ASKREMOVE);
}
});
askRemoveDialog.setNeutralButton(R.string.menu_also_data, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
// Starts the remove task; we won't close this details dialog until its result is returned
queue.enqueue(RemoveTask.create(daemon, torrent, true));
dismissDialog(DIALOG_ASKREMOVE);
}
});
askRemoveDialog.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
dismissDialog(DIALOG_ASKREMOVE);
}
});
return askRemoveDialog.create();
case DIALOG_SETLABEL:
// Build a dialog that asks for a new or selected an existing label to assign to the selected
// torrent
SetLabelDialog setLabelDialog = new SetLabelDialog(getActivity(), new ResultListener() {
@Override
public void onLabelResult(String newLabel) {
if (newLabel.equals(getString(R.string.labels_unlabeled).toString())) {
// Setting a torrent to 'unlabeled' is actually setting the label to an empty string
newLabel = "";
}
setNewLabel(newLabel);
}
}, existingLabels, torrent.getLabelName());
setLabelDialog.setTitle(R.string.labels_newlabel);
return setLabelDialog;
case DIALOG_SETLOCATION:
// Build a dialog that asks for a new download location for the torrent
final View setLocationLayout = LayoutInflater.from(getActivity()).inflate(
R.layout.dialog_set_download_location, null);
final EditText newLocation = (EditText) setLocationLayout.findViewById(R.id.download_location);
newLocation.setText(torrent.getLocationDir());
AlertDialog.Builder setLocationDialog = new AlertDialog.Builder(getActivity());
setLocationDialog.setTitle(R.string.menu_setdownloadlocation);
setLocationDialog.setView(setLocationLayout);
setLocationDialog.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
queue.enqueue(SetDownloadLocationTask.create(daemon, torrent, newLocation.getText().toString()));
}
});
setLocationDialog.setNegativeButton(android.R.string.cancel, null);
return setLocationDialog.create();
case DIALOG_EDITTRACKERS:
// Build a dialog that allows for the editing of the trackers
final View editTrackersLayout = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_edittrackers,
null);
final EditText trackersText = (EditText) editTrackersLayout.findViewById(R.id.trackers);
AlertDialog.Builder editTrackersDialog = new AlertDialog.Builder(getActivity());
editTrackersDialog.setTitle(R.string.menu_edittrackers);
editTrackersDialog.setView(editTrackersLayout);
editTrackersDialog.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
queue.enqueue(SetTrackersTask.create(daemon, torrent, Arrays.asList(trackersText.getText()
.toString().split("\n"))));
}
});
editTrackersDialog.setNegativeButton(android.R.string.cancel, null);
return editTrackersDialog.create();
case DIALOG_INSTALLVLC:
return ActivityUtil.buildInstallDialog(getActivity(), R.string.vlcremote_not_found,
Transdroid.VLCREMOTE_MARKET_URI);
case DIALOG_INSTALLFTPCLIENT:
return ActivityUtil.buildInstallDialog(getActivity(), R.string.ftpclient_not_found,
Transdroid.ANDFTP_MARKET_URI);
}
return null;
}
/*
* @Override protected void onPrepareDialog(int id, Dialog dialog) { super.onPrepareDialog(id, dialog);
*
* switch (id) { case DIALOG_SETLABEL:
*
* // Re-populate the dialog adapter with the available labels SetLabelDialog setLabelDialog =
* (SetLabelDialog) dialog; setLabelDialog.resetDialog(this, existingLabels, torrent.getLabelName());
* break;
*
* case DIALOG_SETLOCATION:
*
* // Show the existing download location final EditText newLocation = (EditText)
* dialog.findViewById(R.id.download_location); newLocation.setText(torrent.getLocationDir()); break;
*
* case DIALOG_EDITTRACKERS:
*
* // Show the existing trackers final EditText trackersText = (EditText)
* dialog.findViewById(R.id.trackers); trackersText.setText(fineDetails.getTrackersText()); break;
*
* } }
*/
@Override
public boolean isAttached() {
return getActivity() != null;
}
@Override
public void onQueueEmpty() {
// No active task: turn off status indicator
// ((TransdroidListActivity)getActivity()).setProgressBar(false);
}
@Override
public void onQueuedTaskFinished(DaemonTask finished) {
}
@Override
public void onQueuedTaskStarted(DaemonTask started) {
// Started on a new task: turn on status indicator
// ((TransdroidListActivity)getActivity()).setProgressBar(true);
}
@Override
public void onTaskFailure(DaemonTaskFailureResult result) {
if (getActivity() == null) {
// No longer visible
return;
}
// Show error message
Toast.makeText(getActivity(), LocalTorrent.getResourceForDaemonException(result.getException()),
Toast.LENGTH_SHORT * 2).show();
}
@Override
public void onTaskSuccess(DaemonTaskSuccessResult result) {
if (getView() == null) {
// We are no longer visible: discard the result
return;
}
switch (result.getMethod()) {
case Retrieve:
// In the full updated list of torrents, look for the one we are showing
// (Of course ideally we would only request info on this torrent, but there is no such
// DaemonMethod for that at the moment)
List<Torrent> list = ((RetrieveTaskSuccessResult) result).getTorrents();
if (list != null) {
for (Torrent t : list) {
if (torrent.getUniqueID().equals(t.getUniqueID())) {
// This is the updated torrent data for the torrent we are showing
torrent = t;
getDetailsListAdapter().setTorrent(torrent);
getDetailsListAdapter().updateViewsAndButtonStates();
// Force a label name (use 'unlabeled' if none is provided)
if (torrent.getLabelName() == null || torrent.getLabelName().equals("")) {
torrent.mimicNewLabel(getText(R.string.labels_unlabeled).toString());
}
break;
}
}
}
break;
case GetTorrentDetails:
fineDetails = ((GetTorrentDetailsTaskSuccessResult) result).getTorrentDetails();
getDetailsListAdapter().setTorrentDetails(fineDetails);
getDetailsListAdapter().updateViewsAndButtonStates();
break;
case GetFileList:
onTorrentFilesLoaded(((GetFileListTaskSuccessResult) result).getFiles());
break;
case SetFilePriorities:
// Queue a new task to update the file listing
Toast.makeText(getActivity(), R.string.details_priorities_updated, Toast.LENGTH_SHORT).show();
queue.enqueue(GetFileListTask.create(daemon, torrent));
break;
case Pause:
torrent.mimicPause();
getDetailsListAdapter().updateViewsAndButtonStates();
// Also call back to the main torrents list to update its view
if (torrentsFragment != null) {
torrentsFragment.updateTorrentList();
}
break;
case Resume:
torrent.mimicResume();
getDetailsListAdapter().updateViewsAndButtonStates();
queue.enqueue(RetrieveTask.create(daemon));
queue.enqueue(GetFileListTask.create(daemon, torrent));
// Also call back to the main torrents list to update its view
if (torrentsFragment != null) {
torrentsFragment.updateTorrentList();
}
break;
case Stop:
torrent.mimicStop();
getDetailsListAdapter().updateViewsAndButtonStates();
// Also call back to the main torrents list to update its view
if (torrentsFragment != null) {
torrentsFragment.updateTorrentList();
}
break;
case Start:
torrent.mimicStart();
getDetailsListAdapter().updateViewsAndButtonStates();
queue.enqueue(RetrieveTask.create(daemon));
queue.enqueue(GetFileListTask.create(daemon, torrent));
// Also call back to the main torrents list to update its view
if (torrentsFragment != null) {
torrentsFragment.updateTorrentList();
}
break;
case Remove:
boolean includingData = ((RemoveTask) result.getTask()).includingData();
Toast.makeText(
getActivity(),
"'" + result.getTargetTorrent().getName() + "' "
+ getText(includingData ? R.string.torrent_removed_with_data : R.string.torrent_removed),
Toast.LENGTH_SHORT).show();
// Also call back to the main torrents list to update its view
if (torrentsFragment != null) {
torrentsFragment.updateTorrentList();
}
// Close this details fragment
if (torrentsFragment != null) {
FragmentTransaction ft = getSherlockActivity().getSupportFragmentManager().beginTransaction();
ft.remove(this);
ft.commit();
} else {
getSherlockActivity().getSupportFragmentManager().popBackStack();
}
break;
case SetDownloadLocation:
Toast.makeText(getActivity(),
getString(R.string.torrent_locationset, ((SetDownloadLocationTask) result.getTask()).getNewLocation()),
Toast.LENGTH_SHORT).show();
// TODO: Show the download location in the details
break;
case SetTrackers:
Toast.makeText(getActivity(), R.string.torrent_trackersupdated, Toast.LENGTH_SHORT).show();
break;
}
}
public void onSelectedResultsChanged() {
if (getDetailsListAdapter().getTorrentFileAdapter().getSelected().size() == 0) {
// Hide the bar with priority setting buttons
prioBar.setVisibility(View.GONE);
} else if (Daemon.supportsFilePrioritySetting(daemon.getType())) {
prioBar.setVisibility(View.VISIBLE);
}
}
private OnItemClickListener onFileClicked = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
// If something was already selected before, use an item click as selection click
if (!getDetailsListAdapter().getTorrentFileAdapter().getSelected().isEmpty()) {
TorrentFile file = getDetailsListAdapter().getTorrentFileAdapter().getItem(position - 1);
getDetailsListAdapter().getTorrentFileAdapter().itemChecked(file,
!getDetailsListAdapter().getTorrentFileAdapter().isItemChecked(file));
getListView().invalidateViews();
}
}
};
private OnClickListener setPriorityOffClicked = new OnClickListener() {
@Override
public void onClick(View v) {
// Queue a task to set the priority of all selected files
queueSetFilePrioritiesTask(Priority.Off, getDetailsListAdapter().getTorrentFileAdapter().getSelected());
}
};
private OnClickListener setPriorityLowClicked = new OnClickListener() {
@Override
public void onClick(View v) {
// Queue a task to set the priority of all selected files
queueSetFilePrioritiesTask(Priority.Low, getDetailsListAdapter().getTorrentFileAdapter().getSelected());
}
};
private OnClickListener setPriorityNormalClicked = new OnClickListener() {
@Override
public void onClick(View v) {
// Queue a task to set the priority of all selected files
queueSetFilePrioritiesTask(Priority.Normal, getDetailsListAdapter().getTorrentFileAdapter().getSelected());
}
};
private OnClickListener setPriorityHighClicked = new OnClickListener() {
@Override
public void onClick(View v) {
// Queue a task to set the priority of all selected files
queueSetFilePrioritiesTask(Priority.High, getDetailsListAdapter().getTorrentFileAdapter().getSelected());
}
};
private void queueSetFilePrioritiesTask(Priority newPriority, List<TorrentFile> selected) {
// Queue a task to set the priority of all selected files
queue.enqueue(SetFilePriorityTask.create(daemon, torrent, newPriority, (ArrayList<TorrentFile>) selected));
// Clear the selection
// TorrentFileListAdapter adapter = (TorrentFileListAdapter) fileslist.getAdapter();
// adapter.clearSelection();
}
public void pauseTorrent() {
queue.enqueue(PauseTask.create(daemon, torrent));
}
public void resumeTorrent() {
queue.enqueue(ResumeTask.create(daemon, torrent));
}
public void stopTorrent() {
queue.enqueue(StopTask.create(daemon, torrent));
}
public void startTorrent(boolean forced) {
queue.enqueue(StartTask.create(daemon, torrent, forced));
}
protected void refreshActivity() {
queue.enqueue(RetrieveTask.create(daemon));
if (Daemon.supportsFileListing(daemon.getType())) {
queue.enqueue(GetFileListTask.create(daemon, torrent));
}
if (Daemon.supportsFineDetails(daemon.getType())) {
queue.enqueue(GetTorrentDetailsTask.create(daemon, torrent));
}
}
protected View findViewById(int id) {
return getView().findViewById(id);
}
protected ListView getListView() {
return (ListView) findViewById(android.R.id.list);
}
private DetailsListAdapter getDetailsListAdapter() {
return (DetailsListAdapter) getListView().getAdapter();
}
public Daemon getActiveDaemonType() {
return daemon.getType();
}
public void showDialog(int id) {
new DialogWrapper(onCreateDialog(id)).show(getSherlockActivity().getSupportFragmentManager(), DialogWrapper.TAG
+ id);
}
protected void dismissDialog(int id) {
// Remove the dialog wrapper fragment for the dialog's ID
getSherlockActivity().getSupportFragmentManager().beginTransaction().remove(
getSherlockActivity().getSupportFragmentManager().findFragmentByTag(DialogWrapper.TAG + id)).commit();
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.gui;
import java.util.List;
import org.transdroid.daemon.TorrentFile;
import org.transdroid.gui.util.SelectableArrayAdapter;
import android.view.View;
import android.view.ViewGroup;
/**
* An adapter that can be mapped to a list of torrent files.
* @author erickok
*
*/
public class TorrentFileListAdapter extends SelectableArrayAdapter<TorrentFile> {
public TorrentFileListAdapter(DetailsFragment detailsActivity, List<TorrentFile> torrents) {
super(detailsActivity.getActivity(), torrents, detailsActivity);
}
public View getView(int position, View convertView, ViewGroup paret, boolean selected) {
// TODO: Try to reuse the convertView for better performance
return new TorrentFileListView(getContext(), this, getItem(position), selected);
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.gui;
import org.transdroid.R;
import org.transdroid.daemon.DaemonException;
import org.transdroid.daemon.Torrent;
import org.transdroid.daemon.TorrentStatus;
import org.transdroid.daemon.util.FileSizeConverter;
import org.transdroid.daemon.util.TimespanConverter;
import android.content.res.Resources;
/**
* Wrapper around Torrent to provide some addition getters that give translatable or
* otherwise formatted Strings of torrent statistics.
*
* @author erickok
*/
public class LocalTorrent {
/**
* Creates the LocalTorrent object so that the translatable/formattable
* version of a Torrent can be used.
* @param torrent The Torrent object
* @return The torrent 'casted' as LocalTorrent
*/
public static LocalTorrent fromTorrent(Torrent torrent) {
return new LocalTorrent(torrent);
}
private final Torrent t;
private LocalTorrent(Torrent torrent) {
this.t = torrent;
}
private static final String DECIMAL_FORMATTER = "%.1f";
/**
* Builds a string showing the upload/download seed ratio. If not downloading,
* it will base the ratio on the total size; so if you created the torrent yourself
* you will have downloaded 0 bytes, but the ratio will pretend you have 100%.
* @return A nicely formatted string containing the upload/download seed ratio
*/
public String getRatioString() {
long baseSize = t.getTotalSize();
if (t.getStatusCode() == TorrentStatus.Downloading) {
baseSize = t.getDownloadedEver();
}
if (baseSize <= 0) {
return String.format(DECIMAL_FORMATTER, 0d);
} else if (t.getRatio() == Double.POSITIVE_INFINITY) {
return "\u221E";
} else {
return String.format(DECIMAL_FORMATTER, t.getRatio());
}
}
public String getProgressSizeText(Resources r, boolean withAvailability) {
switch (t.getStatusCode()) {
case Waiting:
case Checking:
case Error:
// Not downloading yet
return r.getString(R.string.status_waitingtodl, FileSizeConverter.getSize(t.getTotalSize()));
case Downloading:
// Downloading
return r.getString(R.string.status_size1,
FileSizeConverter.getSize(t.getDownloadedEver()),
FileSizeConverter.getSize(t.getTotalSize()),
String.format(DECIMAL_FORMATTER, t.getDownloadedPercentage() * 100) + "%" +
(!withAvailability? "": "/" + String.format(DECIMAL_FORMATTER, t.getAvailability() * 100)+"%"));
case Seeding:
case Paused:
case Queued:
// Seeding or paused
return r.getString(R.string.status_size2, FileSizeConverter.getSize(t.getTotalSize()),
FileSizeConverter.getSize(t.getUploadedEver()));
default:
return "";
}
}
public String getProgressEtaRatioText(Resources r) {
switch (t.getStatusCode()) {
case Downloading:
// Downloading
return getRemainingTimeString(r, false);
case Seeding:
case Paused:
case Queued:
// Seeding or paused
return r.getString(R.string.status_ratio, getRatioString());
case Waiting:
case Checking:
case Error:
default:
return "";
}
}
public String getProgressConnectionText(Resources r) {
switch (t.getStatusCode()) {
case Waiting:
return r.getString(R.string.status_waiting);
case Checking:
return r.getString(R.string.status_checking);
case Downloading:
return r.getString(R.string.status_peers, t.getPeersSendingToUs(), t.getPeersConnected());
case Seeding:
return r.getString(R.string.status_peers, t.getPeersGettingFromUs(), t.getPeersConnected());
case Paused:
return r.getString(R.string.status_paused);
case Queued:
return r.getString(R.string.status_stopped);
case Error:
return r.getString(R.string.status_error);
default:
return r.getString(R.string.status_unknown);
}
}
public String getProgressSpeedText(Resources r) {
switch (t.getStatusCode()) {
case Waiting:
case Checking:
case Paused:
case Queued:
return "";
case Downloading:
return r.getString(R.string.status_speed_down,
FileSizeConverter.getSize(t.getRateDownload()) + r.getString(R.string.status_persecond)) + " " +
r.getString(R.string.status_speed_up,
FileSizeConverter.getSize(t.getRateUpload()) + r.getString(R.string.status_persecond));
case Seeding:
return r.getString(R.string.status_speed_up,
FileSizeConverter.getSize(t.getRateUpload()) + r.getString(R.string.status_persecond));
default:
return "";
}
}
public String getRemainingTimeString(Resources r, boolean inDays) {
if (t.getEta() == -1 || t.getEta() == -2) {
return r.getString(R.string.status_unknowneta);
}
return r.getString(R.string.status_eta, TimespanConverter.getTime(t.getEta(), inDays));
}
/**
* Convert a Daemon exception to a translatable human-readable error
* @param e The exception that was thrown by the daemon
* @return A string resource ID
*/
public static int getResourceForDaemonException(DaemonException e) {
switch (e.getType()) {
case MethodUnsupported:
return R.string.error_jsonrequesterror;
case ConnectionError:
return R.string.error_httperror;
case UnexpectedResponse:
return R.string.error_jsonresponseerror;
case ParsingFailed:
return R.string.error_jsonrequesterror;
case NotConnected:
return R.string.error_daemonnotconnected;
case AuthenticationFailure:
return R.string.error_401;
case FileAccessError:
return R.string.error_torrentfile;
}
return R.string.error_httperror;
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.gui;
import org.transdroid.R;
import org.transdroid.daemon.TorrentFile;
import android.content.Context;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.CompoundButton.OnCheckedChangeListener;
/**
* A view that shows a torrent file as a list item.
*
* @author erickok
*
*/
public class TorrentFileListView extends LinearLayout {
private TorrentFile file;
private TorrentFileListAdapter adapter;
/**
* Constructs a view that can display a torrent file (to use in a list)
* @param context The activity context
* @param torrent The torrent file to show the data for
*/
public TorrentFileListView(Context context, TorrentFileListAdapter adapter, TorrentFile file, boolean initialyChecked) {
super(context);
this.adapter = adapter;
addView(inflate(context, R.layout.list_item_torrentfile, null));
setData(file, initialyChecked);
}
/**
* Sets the actual texts and images to the visible widgets (fields)
*/
public void setData(TorrentFile file, boolean initialyChecked) {
this.file = file;
final CheckBox check = (CheckBox)findViewById(R.id.check);
check.setChecked(initialyChecked);
check.setOnCheckedChangeListener(itemSelection);
((TextView)findViewById(R.id.name)).setText(file.getName());
((TextView)findViewById(R.id.sizes)).setText(file.getDownloadedAndTotalSizeText());
((TextView)findViewById(R.id.progress)).setText(file.getProgressText());
ImageView priority = (ImageView) findViewById(R.id.priority);
switch (file.getPriority()) {
case Off:
priority.setImageResource(R.drawable.icon_priority_off);
break;
case Low:
priority.setImageResource(R.drawable.icon_priority_low);
break;
case Normal:
priority.setImageResource(R.drawable.icon_priority_normal);
break;
case High:
priority.setImageResource(R.drawable.icon_priority_high);
break;
}
}
private OnCheckedChangeListener itemSelection = new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
adapter.itemChecked(file, isChecked);
}
};
}
| Java |
package org.transdroid.gui.util;
import java.util.List;
import org.transdroid.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.util.Log;
import android.widget.Toast;
public class ActivityUtil {
private static final String LOG_NAME = "Activity util";
/**
* Get current version number
* @return A string with the application version number
*/
public static String getVersionNumber(Context context) {
String version = "?";
try {
PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
version = pi.versionName;
} catch (PackageManager.NameNotFoundException e) {
Log.e(LOG_NAME, "Package name not found to retrieve version number", e);
}
return version;
}
/**
* Indicates whether the specified action can be used as an intent. This
* method queries the package manager for installed packages that can
* respond to an intent with the specified action. If no suitable package is
* found, this method returns false.
* @param context The application's environment.
* @param intent The Intent to check for availability.
* @return True if an Intent with the specified action can be sent and responded to, false otherwise.
*/
public static boolean isIntentAvailable(Context context, Intent intent) {
final PackageManager packageManager = context.getPackageManager();
List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
/**
* Builds a (reusable) dialog that asks to install some application from the Android market
* @param messageResourceID The message to show to the user
* @param marketUri The application's URI on the Android Market
* @return The dialog to show
*/
public static Dialog buildInstallDialog(final Activity activity, int messageResourceID, final Uri marketUri) {
return buildInstallDialog(activity, messageResourceID, marketUri, false, activity.getString(R.string.oifm_install));
}
/**
* Builds a (reusable) dialog that asks to install some application from the Android market
* @param messageResourceID The message to show to the user
* @param marketUri The application's URI on the Android Market
* @param buttonText The text to show on the positive (install) button
* @param alternativeNegativeButtonHandler The click handler for the negative dialog button
* @return The dialog to show
*/
public static Dialog buildInstallDialog(final Activity activity, int messageResourceID, final Uri marketUri,
final boolean closeAfterInstallFailure, CharSequence buttonText) {
AlertDialog.Builder fbuilder = new AlertDialog.Builder(activity);
fbuilder.setMessage(messageResourceID);
fbuilder.setCancelable(true);
fbuilder.setPositiveButton(buttonText, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent install = new Intent(Intent.ACTION_VIEW, marketUri);
if (ActivityUtil.isIntentAvailable(activity, install)) {
activity.startActivity(install);
} else {
Toast.makeText(activity, R.string.oifm_nomarket, Toast.LENGTH_LONG).show();
if (closeAfterInstallFailure) {
activity.finish();
}
}
dialog.dismiss();
}
});
fbuilder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
if (closeAfterInstallFailure) {
activity.finish();
}
}
});
return fbuilder.create();
}
}
| Java |
package org.transdroid.gui.util;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
/**
* A wrapper used to create dialog fragments out of old-style activity dialogs
*/
public class DialogWrapper extends DialogFragment {
public static final String TAG = "DialogWrapper";
private final Dialog dialog;
public DialogWrapper(Dialog dialog) {
this.dialog = dialog;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return dialog;
}
} | Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.gui.util;
/**
* A class that contains all the user interface settings.
*
* @author erickok
*
*/
public class InterfaceSettings {
private boolean swipeLabels;
private int refreshTimerInterval;
private boolean hideRefreshMessage;
private boolean askBeforeRemove;
public InterfaceSettings(boolean swipeLabels, int refreshTimerInterval, boolean showOnlyDownloading,
boolean hideRefreshMessage, boolean askBeforeRemove, boolean enableAds) {
this.swipeLabels = swipeLabels;
this.refreshTimerInterval = refreshTimerInterval;
this.hideRefreshMessage = hideRefreshMessage;
this.askBeforeRemove = askBeforeRemove;
}
public int getRefreshTimerInterval() {
return refreshTimerInterval;
}
public boolean shouldHideRefreshMessage() {
return hideRefreshMessage;
}
public boolean getAskBeforeRemove() {
return askBeforeRemove;
}
public boolean shouldSwipeLabels() {
return swipeLabels;
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.gui.util;
import org.transdroid.R;
import org.transdroid.daemon.DaemonSettings;
import org.transdroid.daemon.IDaemonAdapter;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.widget.Toast;
public class ErrorLogSender {
public static final String LOG_COLLECTOR_PACKAGE_NAME = "com.xtralogic.android.logcollector";//$NON-NLS-1$
public static final String ACTION_SEND_LOG = "com.xtralogic.logcollector.intent.action.SEND_LOG";//$NON-NLS-1$
public static final String EXTRA_SEND_INTENT_ACTION = "com.xtralogic.logcollector.intent.extra.SEND_INTENT_ACTION";//$NON-NLS-1$
public static final String EXTRA_DATA = "com.xtralogic.logcollector.intent.extra.DATA";//$NON-NLS-1$
public static final String EXTRA_ADDITIONAL_INFO = "com.xtralogic.logcollector.intent.extra.ADDITIONAL_INFO";//$NON-NLS-1$
public static final String EXTRA_SHOW_UI = "com.xtralogic.logcollector.intent.extra.SHOW_UI";//$NON-NLS-1$
public static final String EXTRA_FILTER_SPECS = "com.xtralogic.logcollector.intent.extra.FILTER_SPECS";//$NON-NLS-1$
public static final String EXTRA_FORMAT = "com.xtralogic.logcollector.intent.extra.FORMAT";//$NON-NLS-1$
public static final String EXTRA_BUFFER = "com.xtralogic.logcollector.intent.extra.BUFFER";//$NON-NLS-1$
public static void collectAndSendLog(final Context context, final IDaemonAdapter daemon, final DaemonSettings daemonSettings){
final Intent intent = new Intent(ACTION_SEND_LOG);
final boolean isInstalled = ActivityUtil.isIntentAvailable(context, intent);
if (!isInstalled){
new AlertDialog.Builder(context)
.setTitle("Transdroid")
.setIcon(android.R.drawable.ic_dialog_info)
.setMessage(R.string.lc_install)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int whichButton){
Intent marketIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://search?q=pname:" + LOG_COLLECTOR_PACKAGE_NAME));
marketIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (ActivityUtil.isIntentAvailable(context, marketIntent)) {
context.startActivity(marketIntent);
} else {
Toast.makeText(context, R.string.oifm_nomarket, Toast.LENGTH_LONG).show();
}
}
})
.setNegativeButton(android.R.string.cancel, null)
.show();
}
else
{
new AlertDialog.Builder(context)
.setTitle("Transdroid")
.setIcon(android.R.drawable.ic_dialog_info)
.setMessage(R.string.lc_run)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int whichButton){
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(EXTRA_SEND_INTENT_ACTION, Intent.ACTION_SENDTO);
intent.putExtra(EXTRA_DATA, Uri.parse("mailto:transdroid.org@gmail.com"));
intent.putExtra(EXTRA_ADDITIONAL_INFO, "My problem:\n\n\nTransdroid version " + ActivityUtil.getVersionNumber(context) + "\n" + daemon.getType().toString() + " settings: " + daemonSettings.getHumanReadableIdentifier() + "\n");
intent.putExtra(Intent.EXTRA_SUBJECT, "Application failure report");
intent.putExtra(EXTRA_FORMAT, "time");
//The log can be filtered to contain data relevant only to your app
String[] filterSpecs = new String[4];
filterSpecs[0] = "AndroidRuntime:E";
filterSpecs[1] = "Transdroid:*";
filterSpecs[2] = "ActivityManager:*";
filterSpecs[3] = "*:S";
intent.putExtra(EXTRA_FILTER_SPECS, filterSpecs);
context.startActivity(intent);
}
})
.setNegativeButton(android.R.string.cancel, null)
.show();
}
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.