index
int64
repo_id
string
file_path
string
content
string
0
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan/model/CompleteFileUploadRequest.java
package ai.nightfall.scan.model; import java.util.UUID; /** * The container object containing all parameters required to complete a file upload. */ public class CompleteFileUploadRequest { private UUID fileUploadID; /** * Constructs a new request to complete a file upload. * * @param fileUploadID the file ID */ public CompleteFileUploadRequest(UUID fileUploadID) { this.fileUploadID = fileUploadID; } /** * Returns the file ID. * * @return the file ID */ public UUID getFileUploadID() { return fileUploadID; } /** * Sets the file ID. * * @param fileUploadID the file ID */ public void setFileUploadID(UUID fileUploadID) { this.fileUploadID = fileUploadID; } }
0
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan/model/Confidence.java
package ai.nightfall.scan.model; /** * Confidence describes the certainty that a piece of content matches a detector. */ public enum Confidence { VERY_UNLIKELY, UNLIKELY, POSSIBLE, LIKELY, VERY_LIKELY }
0
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan/model/ConfidenceAdjustment.java
package ai.nightfall.scan.model; import com.fasterxml.jackson.annotation.JsonProperty; /** * Describes how to adjust confidence on a given finding. Valid values for the adjustment are * <code>VERY_UNLIKELY</code>, <code>UNLIKELY</code>, <code>POSSIBLE</code>, <code>LIKELY</code>, * and <code>VERY_LIKELY</code>. */ public class ConfidenceAdjustment { @JsonProperty("fixedConfidence") private Confidence fixedConfidence; /** * Create a ConfidenceAdjustment object. * * @param fixedConfidence the confidence to adjust to if external criteria are met. */ public ConfidenceAdjustment(Confidence fixedConfidence) { this.fixedConfidence = fixedConfidence; } /** * Return the confidence to adjust to. * * @return the confidence to adjust to */ public Confidence getFixedConfidence() { return fixedConfidence; } }
0
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan/model/ContextRule.java
package ai.nightfall.scan.model; import com.fasterxml.jackson.annotation.JsonProperty; /** * An object that describes how a regular expression may be used to adjust the confidence of a candidate finding. * This context rule will be applied within the provided byte proximity, and if the regular expression matches, then * the confidence associated with the finding will be adjusted to the value prescribed. */ public class ContextRule { @JsonProperty("regex") private Regex regex; @JsonProperty("proximity") private Proximity proximity; @JsonProperty("confidenceAdjustment") private ConfidenceAdjustment confidenceAdjustment; /** * Create a new Context Rule. * * @param regex the regular expression configuration * @param proximity the proximity in which to evaluate the regular expression * @param confidenceAdjustment describes how to adjust the confidence of a finding if the regular expression matches */ public ContextRule(Regex regex, Proximity proximity, ConfidenceAdjustment confidenceAdjustment) { this.regex = regex; this.proximity = proximity; this.confidenceAdjustment = confidenceAdjustment; } /** * Return the regular expression. * * @return the regular expression */ public Regex getRegex() { return regex; } /** * Return the proximity. * * @return the proximity */ public Proximity getProximity() { return proximity; } /** * Return the confidence adjustment. * * @return the confidence adjustment */ public ConfidenceAdjustment getConfidenceAdjustment() { return confidenceAdjustment; } }
0
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan/model/DetectionRule.java
package ai.nightfall.scan.model; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; /** * An object that contains a set of detectors to be used when scanning content. Findings matches are * triggered according to the provided <code>logicalOp</code>logicalOp; valid values are <code>ANY</code> (logical * <code>OR</code>, i.e. a finding is emitted only if any of the provided detectors match), or <code>ALL</code> * (logical <code>AND</code>, i.e. a finding is emitted only if all provided detectors match). */ public class DetectionRule { @JsonProperty("detectors") private List<Detector> detectors; @JsonProperty("logicalOp") private LogicalOp logicalOp; @JsonProperty("name") private String name; /** * Create a detection rule with the provided detectors and logicalOp. * * @param detectors a list of detectors * @param logicalOp a logical op: ANY or ALL */ public DetectionRule(List<Detector> detectors, LogicalOp logicalOp) { this.detectors = detectors; this.logicalOp = logicalOp; } /** * Create a detection rule with the provided detectors and logicalOp. * * @param detectors a list of detectors * @param logicalOp a logical op: ANY or ALL * @param name a name for the detection rule */ public DetectionRule(List<Detector> detectors, LogicalOp logicalOp, String name) { this.detectors = detectors; this.logicalOp = logicalOp; this.name = name; } /** * Get the list of detectors. * * @return the set of detectors */ public List<Detector> getDetectors() { return detectors; } /** * Set the detectors. * * @param detectors a set of detectors */ public void setDetectors(List<Detector> detectors) { this.detectors = detectors; } /** * Get the logical op. * * @return the logical op */ public LogicalOp getLogicalOp() { return logicalOp; } /** * Set the logical op. * * @param logicalOp a logical op; valid values <code>ANY</code> or <code>ALL</code> */ public void setLogicalOp(LogicalOp logicalOp) { this.logicalOp = logicalOp; } /** * Get the name of the detection rule. * * @return the name of the detection rule */ public String getName() { return name; } /** * Set the detection rule name. * * @param name a name for the detection rule */ public void setName(String name) { this.name = name; } @Override public String toString() { return "DetectionRule{" + "detectors=" + detectors + ", logicalOp='" + logicalOp + '\'' + ", name='" + name + '\'' + '}'; } }
0
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan/model/Detector.java
package ai.nightfall.scan.model; import ai.nightfall.scan.model.redaction.RedactionConfig; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; import java.util.UUID; /** * An object that represents a data type or category of information. Detectors are used to scan content * for findings. */ public class Detector { @JsonProperty("minConfidence") private Confidence minConfidence; @JsonProperty("minNumFindings") private int minNumFindings; @JsonProperty("detectorUUID") private UUID detectorUUID; @JsonProperty("displayName") private String displayName; @JsonProperty("detectorType") private String detectorType; @JsonProperty("nightfallDetector") private String nightfallDetector; @JsonProperty("regex") private Regex regex; @JsonProperty("wordList") private WordList wordList; @JsonProperty("contextRules") private List<ContextRule> contextRules; @JsonProperty("exclusionRules") private List<ExclusionRule> exclusionRules; @JsonProperty("redactionConfig") private RedactionConfig redactionConfig; /** * Create an instance of a detector based on a pre-built Nightfall detector. * * @param nightfallDetector the name of a pre-built Nightfall detector */ public Detector(String nightfallDetector) { this.detectorType = "NIGHTFALL_DETECTOR"; this.nightfallDetector = nightfallDetector; } /** * Create an instance of a detector based on a regular expression. * * @param regex the regular expression configuration */ public Detector(Regex regex) { this.detectorType = "REGEX"; this.regex = regex; } /** * Create an instance of a detector based on a word list. * * @param wordList the word list configuration */ public Detector(WordList wordList) { this.detectorType = "WORD_LIST"; this.wordList = wordList; } /** * Create an instance of a detector by using an existing detector's UUID. * * @param detectorUUID an existing detector's UUID */ public Detector(UUID detectorUUID) { // no detector type; implicit in UUID definition this.detectorUUID = detectorUUID; } /** * Return the minimum confidence. * * @return the minimum confidence threshold required in order for a finding to be triggered */ public Confidence getMinConfidence() { return minConfidence; } /** * Set the minimum confidence. * * @param minConfidence the minimum confidence threshold. */ public void setMinConfidence(Confidence minConfidence) { this.minConfidence = minConfidence; } /** * Get the minimum number of findings. * * @return the minimum number of occurrences of the detector required to trigger a finding match */ public int getMinNumFindings() { return minNumFindings; } /** * Set the minimum number of findings. * * @param minNumFindings the minimum number of occurrences of the detector required to trigger a finding match */ public void setMinNumFindings(int minNumFindings) { this.minNumFindings = minNumFindings; } /** * Get the detector UUID. * * @return a UUID that represents a pre-built detector */ public UUID getDetectorUUID() { return detectorUUID; } /** * Get the display name. * * @return a display name for this detector */ public String getDisplayName() { return displayName; } /** * Set the display name. * * @param displayName a display name for this detector */ public void setDisplayName(String displayName) { this.displayName = displayName; } /** * Get the detector type. * * @return the type of this detector. Valid values are <code>NIGHTFALL_DETECTOR</code>, <code>REGEX</code>, * and <code>WORD_LIST</code>. */ public String getDetectorType() { return detectorType; } /** * Get the nightfall detector. * * @return the pre-built Nightfall Detector to use. This field is only used if the Detector was constructed * with a Nightfall Detector argument. */ public String getNightfallDetector() { return nightfallDetector; } /** * Get the regex. * * @return the regular expression representing this detector. This field is only used if the Detector was * constructed with a regex argument. */ public Regex getRegex() { return regex; } /** * Get the word list. * * @return the word list representing this detector. This field is only used if the Detector was constructed * with a word list argument. */ public WordList getWordList() { return wordList; } /** * Get the context rules. * * @return the context rules that will be used to customize the behavior of this detector */ public List<ContextRule> getContextRules() { return contextRules; } /** * Set the context rules. * * @param contextRules the context rules to use to customize the behavior of this detector */ public void setContextRules(List<ContextRule> contextRules) { this.contextRules = contextRules; } /** * Get the exclusion rules. * * @return the exclusion rules that will be used to customize the behavior of this detector */ public List<ExclusionRule> getExclusionRules() { return exclusionRules; } /** * Set the exclusion rules. * * @param exclusionRules the exclusion rules to use to customize the behavior of this detector */ public void setExclusionRules(List<ExclusionRule> exclusionRules) { this.exclusionRules = exclusionRules; } /** * Returns the redaction configuration to-be-applied to this detector. This configuration is currently only * supported for scanning plaintext, not for file scanning. * * @return the redaction configuration */ public RedactionConfig getRedactionConfig() { return redactionConfig; } /** * Sets the redaction configuration to-be-applied to this detector. This configuration is currently only * supported for scanning plaintext, not for file scanning. * * @param redactionConfig the redaction configuration */ public void setRedactionConfig(RedactionConfig redactionConfig) { this.redactionConfig = redactionConfig; } @Override public String toString() { return "Detector{" + "minConfidence='" + minConfidence + '\'' + ", minNumFindings=" + minNumFindings + ", detectorUUID=" + detectorUUID + ", displayName='" + displayName + '\'' + ", detectorType='" + detectorType + '\'' + ", nightfallDetector='" + nightfallDetector + '\'' + ", regex=" + regex + ", wordList=" + wordList + ", contextRules=" + contextRules + ", exclusionRules=" + exclusionRules + ", redactionConfig=" + redactionConfig + '}'; } }
0
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan/model/DetectorMetadata.java
package ai.nightfall.scan.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.UUID; /** * A container for minimal information representing a detector. A detector may be uniquely identified by its UUID; * the name field helps provide human-readability. */ @JsonIgnoreProperties(ignoreUnknown = true) public class DetectorMetadata { @JsonProperty("name") private String name; @JsonProperty("uuid") private UUID uuid; /** * Get the detector name. * * @return the name of the detector */ public String getName() { return name; } /** * Get the detector UUID. * * @return the ID that uniquely identifies this detector */ public UUID getUuid() { return uuid; } @Override public String toString() { return "DetectorMetadata{" + "name='" + name + '\'' + ", uuid=" + uuid + '}'; } }
0
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan/model/ExclusionRule.java
package ai.nightfall.scan.model; import com.fasterxml.jackson.annotation.JsonProperty; /** * An object that describes a regular expression or list of keywords that may be used to disqualify a * candidate finding from triggering a detector match. */ public class ExclusionRule { @JsonProperty("matchType") private String matchType; @JsonProperty("exclusionType") private String exclusionType; @JsonProperty("regex") private Regex regex; @JsonProperty("wordList") private WordList wordList; /** * Create an exclusion rule that uses a regular expression to make a disqualification decision. * * @param regex the regular expression * @param matchType the match type; valid values are FULL or PARTIAL */ public ExclusionRule(Regex regex, String matchType) { this.regex = regex; this.matchType = matchType; this.exclusionType = "REGEX"; } /** * Create an exclusion rule that uses a word list to make a disqualification decision. * * @param wordList the word list * @param matchType the match type; valid values are FULL or PARTIAL */ public ExclusionRule(WordList wordList, String matchType) { this.wordList = wordList; this.matchType = matchType; this.exclusionType = "WORD_LIST"; } /** * Get the match type. * * @return the match type represented by this exclusion rule. Valid values are <code>PARTIAL</code> or * <code>FULL</code>. */ public String getMatchType() { return matchType; } /** * Get the exclusion type. * * @return the type of this exclusion rule. Valid values are <code>WORD_LIST</code> or <code>REGEX</code>. * The corresponding field in this object must be set according to the value specified here. */ public String getExclusionType() { return exclusionType; } /** * Get the regex. * * @return the regular expression to use to evaluate the exclusion rule */ public Regex getRegex() { return regex; } /** * Get the word list. * * @return the word list to use to evaluate the exclusion rule */ public WordList getWordList() { return wordList; } }
0
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan/model/FileScanWebhookNotification.java
package ai.nightfall.scan.model; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Date; import java.util.List; import java.util.UUID; /** * The request payload that is sent by Nightfall to a client-configured webhook URL to report the findings from * an asynchronous file scan. The findings themselves live in an external location referred to by * <code>findingsURL</code>, and will remain accessible until the time described by the field <code>validUntil</code>. * * <p>The <code>findingsURL</code> must be considered sensitive; although the data stored at the URL is secure, the * URL itself grants a temporary lease so that anyone with the link may download the data. */ public class FileScanWebhookNotification { @JsonProperty("findingsURL") private String findingsURL; @JsonProperty("validUntil") private Date validUntil; @JsonProperty("uploadID") private UUID uploadID; @JsonProperty("findingsPresent") private boolean findingsPresent; @JsonProperty("requestMetadata") private String requestMetadata; @JsonProperty("errors") private List<NightfallErrorResponse> errors; /** * Get the findings URL. * * @return a URL referring to the location where findings may be downloaded from */ public String getFindingsURL() { return findingsURL; } /** * Get the findings URL expiry time. * * @return the point in time when the provided findings URL expires. After this date elapses, the findings * will no longer be accessible via this URL. */ public Date getValidUntil() { return validUntil; } /** * Get the file ID. * * @return the file ID associated with these scan results */ public UUID getUploadID() { return uploadID; } /** * Get whether findings are present. * * @return true if and only if any findings were detected in the file represented by <code>uploadID</code>, * otherwise false. */ public boolean isFindingsPresent() { return findingsPresent; } /** * Get the request metadata. * * @return the metadata that the client provided with the initial request, often used for correlating the file * that this scan result represents. */ public String getRequestMetadata() { return requestMetadata; } /** * Get the list of errors that occurred while processing the request. * * @return a list of errors that was encountered by the API while scanning the file. */ public List<NightfallErrorResponse> getErrors() { return errors; } }
0
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan/model/FileUpload.java
package ai.nightfall.scan.model; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.UUID; /** * An object representing a file upload. */ public class FileUpload { @JsonProperty("id") private UUID fileID; @JsonProperty("fileSizeBytes") private long fileSizeBytes; @JsonProperty("chunkSize") private long chunkSize; @JsonProperty("mimeType") private String mimeType; /** * Get the file ID. * * @return a unique ID representing this file */ public UUID getFileID() { return fileID; } /** * Get the file size. * * @return the size of the file in bytes */ public long getFileSizeBytes() { return fileSizeBytes; } /** * Get the chunk size. * * @return the number of bytes to use when uploading the file chunk-by-chunk */ public long getChunkSize() { return chunkSize; } /** * Get the mime type. * * @return the RFC-2045 media type represented by this file */ public String getMimeType() { return mimeType; } }
0
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan/model/Finding.java
package ai.nightfall.scan.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; import java.util.UUID; /** * An object representing an occurrence of a configured detector (i.e. finding) in the provided data. */ @JsonIgnoreProperties(ignoreUnknown = true) public class Finding { @JsonProperty("finding") private String finding; @JsonProperty("redactedFinding") private String redactedFinding; @JsonProperty("beforeContext") private String beforeContext; @JsonProperty("afterContext") private String afterContext; @JsonProperty("detector") private DetectorMetadata detector; @JsonProperty("confidence") private String confidence; @JsonProperty("location") private Location location; @JsonProperty("redactedLocation") private Location redactedLocation; @JsonProperty("matchedDetectionRuleUUIDs") private List<UUID> matchedDetectionRuleUUIDs; @JsonProperty("matchedDetectionRules") private List<String> matchedDetectionRules; /** * Get the finding. * * @return the data that triggered a detector match */ public String getFinding() { return finding; } /** * Returns the redacted finding. This will only be non-empty if redaction configuration was provided * as part of the request payload. * * @return the redacted finding */ public String getRedactedFinding() { return redactedFinding; } /** * Get the preceding context. * * @return the data that immediately preceded the finding */ public String getBeforeContext() { return beforeContext; } /** * Get the trailing context. * * @return the data that immediately succeeded the finding */ public String getAfterContext() { return afterContext; } /** * Get the detector. * * @return the detector that triggered the match */ public DetectorMetadata getDetector() { return detector; } /** * Get the finding confidence. * * @return the confidence that the data contained in <code>finding</code> is an instance of the matched detector */ public String getConfidence() { return confidence; } /** * Get the location of the finding. * * @return the location where the data was in the original content */ public Location getLocation() { return location; } /** * Get the location that the redacted finding would occupy in the original content if it were to replace * the finding. * * @return the location that the data occupies in its redacted form with regard to the original content */ public Location getRedactedLocation() { return redactedLocation; } /** * Get the list of matched detection rule UUIDs. * * @return the list of detection rule UUIDs that contained a detector that triggered a match */ public List<UUID> getMatchedDetectionRuleUUIDs() { return matchedDetectionRuleUUIDs; } /** * Get the list of matched detection rules. * * @return the list of inline detection rules that contained a detector that triggered a match */ public List<String> getMatchedDetectionRules() { return matchedDetectionRules; } @Override public String toString() { return "Finding{" + "finding='" + finding + '\'' + ", redactedFinding='" + redactedFinding + '\'' + ", beforeContext='" + beforeContext + '\'' + ", afterContext='" + afterContext + '\'' + ", detector=" + detector + ", confidence='" + confidence + '\'' + ", location=" + location + ", redactedLocation=" + redactedLocation + ", matchedDetectionRuleUUIDs=" + matchedDetectionRuleUUIDs + ", matchedDetectionRules=" + matchedDetectionRules + '}'; } }
0
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan/model/InitializeFileUploadRequest.java
package ai.nightfall.scan.model; import com.fasterxml.jackson.annotation.JsonProperty; /** * An object representing a request to upload a new file to Nightfall. */ public class InitializeFileUploadRequest { @JsonProperty("fileSizeBytes") private long fileSizeBytes; /** * Create a new request to upload a file to Nightfall. * * @param fileSizeBytes the size of the file in bytes */ public InitializeFileUploadRequest(long fileSizeBytes) { this.fileSizeBytes = fileSizeBytes; } /** * Get the file size. * * @return the size of the file in bytes */ public long getFileSizeBytes() { return fileSizeBytes; } }
0
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan/model/Location.java
package ai.nightfall.scan.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; /** * An object representing where a finding was discovered in content. */ @JsonIgnoreProperties(ignoreUnknown = true) public class Location { @JsonProperty("byteRange") private Range byteRange; @JsonProperty("codepointRange") private Range codepointRange; @JsonProperty("commitHash") private String commitHash; @JsonProperty("commitAuthor") private String commitAuthor; @JsonProperty("rowRange") private Range rowRange; @JsonProperty("columnRange") private Range columnRange; /** * Get the finding's byte range. * * @return the byte range in which a finding was detected */ public Range getByteRange() { return byteRange; } /** * Get the finding's codepoint range. * * @return the codepoint range in which a finding was detected. This differs from byte range since a codepoint * may contain multiple bytes. */ public Range getCodepointRange() { return codepointRange; } /** * Get the finding's row range. * * @return the row range in which a finding was detected, if it is tabular. */ public Range getRowRange() { return rowRange; } /** * Get the finding's column range. * * @return the column range in which a finding was detected, if it is tabular. */ public Range getColumnRange() { return columnRange; } /** * Get the finding's commit hash. * * @return the hash of the commit in which a finding was detected if known. */ public String getCommitHash() { return commitHash; } /** * Get the finding's commit author. * * @return the author of the commit in which a finding was detected if known. */ public String getCommitAuthor() { return commitAuthor; } @Override public String toString() { return "Location{" + "byteRange=" + byteRange + ", codepointRange=" + codepointRange + ", commitHash=" + commitHash + ", commitAuthor=" + commitAuthor + '}'; } /** * An object that contains references to the start and end of the eponymous range. */ public static class Range { @JsonProperty("start") private long start; @JsonProperty("end") private long end; /** * Get the beginning of the range. * * @return the beginning of the range */ public long getStart() { return start; } /** * Get the end of the range. * * @return the end of the range */ public long getEnd() { return end; } @Override public String toString() { return "Range{" + "start=" + start + ", end=" + end + '}'; } } }
0
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan/model/LogicalOp.java
package ai.nightfall.scan.model; /** * A modifier that is used to decide when a finding should be surfaced in the context of a detection rule. * * <p>When <code>ALL</code> is specified, all detectors in a detection rule must trigger a match in order for the * finding to be reported. This is the equivalent of a logical "AND" operator. * * <p>When <code>ANY</code> is specified, only one of the detectors in a detection rule must trigger a match in order * for the finding to be reported. This is the equivalent of a logical "OR" operator. */ public enum LogicalOp { ANY, ALL }
0
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan/model/NightfallAPIException.java
package ai.nightfall.scan.model; /** * The exception thrown when the Nightfall API returns an HTTP status code in the range [400, 599]. Embeds the * standard Nightfall error object for debugging. */ public class NightfallAPIException extends BaseNightfallException { /** * The error returned by the Nightfall API. */ private NightfallErrorResponse error; /** * The HTTP status code returned by the Nightfall API. */ private int httpStatusCode; /** * Create a new instance of the exception. * * @param message an error message */ public NightfallAPIException(String message) { super(message); } /** * Create a new instance of the exception. * * @param message an error message * @param error the standardized error object returned by the Nightfall API * @param httpStatusCode the HTTP status code */ public NightfallAPIException(String message, NightfallErrorResponse error, int httpStatusCode) { super(message); this.error = error; this.httpStatusCode = httpStatusCode; } @Override public String toString() { return "NightfallAPIException{" + "error=" + error + ", httpStatusCode=" + httpStatusCode + '}'; } /** * Get the error object returned by Nightfall. * * @return the standard error object that was returned by the Nightfall API */ public NightfallErrorResponse getError() { return error; } @Override public String getMessage() { return this.error.getMessage(); } }
0
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan/model/NightfallClientException.java
package ai.nightfall.scan.model; /** * The exception thrown when the Nightfall client is unable to process a request due to an unexpected error. */ public class NightfallClientException extends BaseNightfallException { /** * Create a new instance of this exception. * * @param message an error message */ public NightfallClientException(String message) { super(message); } }
0
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan/model/NightfallErrorResponse.java
package ai.nightfall.scan.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Map; import java.util.Objects; /** * The error model returned by Nightfall API requests that are unsuccessful. This object is generally returned * when the HTTP status code is outside the range 200-299. */ public class NightfallErrorResponse { @JsonProperty("code") private int code; @JsonProperty("message") private String message; @JsonProperty("description") private String description; @JsonProperty("additionalData") private Map<String, String> additionalData; // appease jackson serialization public NightfallErrorResponse() {} /** * Builds a new NightfallErrorResponse object. * * @param code the error code * @param message the error message * @param description further description * @param additionalData a map of key-value pairs that contain even further debugging information */ public NightfallErrorResponse(int code, String message, String description, Map<String, String> additionalData) { this.code = code; this.message = message; this.description = description; this.additionalData = additionalData; } /** * Get the error code. * * @return the error code returned by the API */ public int getCode() { return code; } /** * Get the error message. * * @return the error message returned by the API */ public String getMessage() { return message; } /** * Get the error description. * * @return additional details describing the circumstance surrounding the error */ public String getDescription() { return description; } /** * Get supplemental error data. * * @return supplemental data that may be useful in debugging the error message */ public Map<String, String> getAdditionalData() { return additionalData; } @Override public String toString() { return "Error{" + "code=" + code + ", message='" + message + '\'' + ", description='" + description + '\'' + ", additionalData=" + additionalData + '}'; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } NightfallErrorResponse that = (NightfallErrorResponse) o; return code == that.code && Objects.equals(message, that.message) && Objects.equals(description, that.description) && Objects.equals(additionalData, that.additionalData); } @Override public int hashCode() { return Objects.hash(code, message, description, additionalData); } }
0
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan/model/NightfallRequestTimeoutException.java
package ai.nightfall.scan.model; /** * An exception that indicates that a timeout was exceeded while processing a request. */ public class NightfallRequestTimeoutException extends BaseNightfallException { /** * Create a new instance of this exception. * * @param message an error message */ public NightfallRequestTimeoutException(String message) { super(message); } }
0
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan/model/Proximity.java
package ai.nightfall.scan.model; import com.fasterxml.jackson.annotation.JsonProperty; /** * An object representing a range of bytes to consider around a candidate finding. */ public class Proximity { @JsonProperty("windowBefore") private int windowBefore; @JsonProperty("windowAfter") private int windowAfter; /** * Construct a new Proximity. * * @param windowBefore The number of leading characters to consider as context * @param windowAfter The number of trailing characters to consider as context */ public Proximity(int windowBefore, int windowAfter) { this.windowBefore = windowBefore; this.windowAfter = windowAfter; } /** * Get the number of leading bytes. * * @return the number of bytes to consider leading up to a candidate finding */ public int getWindowBefore() { return windowBefore; } /** * Get the number of trailing bytes. * * @return the number of bytes to consider trailing a candidate finding */ public int getWindowAfter() { return windowAfter; } }
0
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan/model/Regex.java
package ai.nightfall.scan.model; import com.fasterxml.jackson.annotation.JsonProperty; /** * An object representing a regular expression to customize the behavior of a detector while Nightfall performs a scan. */ public class Regex { @JsonProperty("pattern") private String pattern; @JsonProperty("isCaseSensitive") private boolean isCaseSensitive; /** * Creates a new Regex object. * * @param pattern the regular expression to use as part of a detector * @param isCaseSensitive whether to consider case sensitivity when evaluating matches */ public Regex(String pattern, boolean isCaseSensitive) { this.pattern = pattern; this.isCaseSensitive = isCaseSensitive; } /** * Get the regex pattern. * * @return the regular expression to use as part of a detector */ public String getPattern() { return pattern; } /** * Get whether the regex is case-sensitive. * * @return true if the regular expression needs to consider case sensitivity when searching for * matches, false otherwise */ public boolean isCaseSensitive() { return isCaseSensitive; } }
0
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan/model/ScanFileRequest.java
package ai.nightfall.scan.model; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.UUID; /** * A container for a request to scan a file that was uploaded via the Nightfall API. Exactly one of * <code>policyUUID</code> or <code>policy</code> should be provided. */ public class ScanFileRequest { @JsonProperty("policyUUID") private UUID policyUUID; @JsonProperty("policy") private ScanPolicy policy; @JsonProperty("requestMetadata") private String requestMetadata; @JsonProperty("violation") private ViolationConfig violationConfig; /** * Create a new request to scan a file. * * @param policy the policy to use to scan the file. * @param requestMetadata arbitrary metadata to pass along with the request; maximum length 10 KB. */ public ScanFileRequest(ScanPolicy policy, String requestMetadata) { this.policy = policy; this.requestMetadata = requestMetadata; } /** * Create a new request to scan a file. * * @param policy the policy to use to scan the file. * @param requestMetadata arbitrary metadata to pass along with the request; maximum length 10 KB. * @param violationConfig the violation configuration to use on the scanned content. */ public ScanFileRequest(ScanPolicy policy, String requestMetadata, ViolationConfig violationConfig) { this.policy = policy; this.requestMetadata = requestMetadata; this.violationConfig = violationConfig; } /** * Create a new request to scan a file. * * @param policyUUID the UUID of an existing policy to use to scan the file. * @param requestMetadata arbitrary metadata to pass along with the request; maximum length 10 KB. */ public ScanFileRequest(UUID policyUUID, String requestMetadata) { this.policyUUID = policyUUID; this.requestMetadata = requestMetadata; } /** * Create a new request to scan a file. * * @param policyUUID the UUID of an existing policy to use to scan the file. * @param requestMetadata arbitrary metadata to pass along with the request; maximum length 10 KB. * @param violationConfig the violation configuration to use on the scanned content. */ public ScanFileRequest(UUID policyUUID, String requestMetadata, ViolationConfig violationConfig) { this.policyUUID = policyUUID; this.requestMetadata = requestMetadata; this.violationConfig = violationConfig; } /** * Get the policy UUID. * * @return the UUID of an existing policy to use to scan a file */ public UUID getPolicyUUID() { return policyUUID; } /** * Get the policy. * * @return the policy to use to scan the file */ public ScanPolicy getPolicy() { return policy; } /** * Get the request metadata. * * @return the request metadata. */ public String getRequestMetadata() { return requestMetadata; } /** * Set the request metadata. * * @param requestMetadata arbitrary data to be passed along with the request, maximum length 10 KB. */ public void setRequestMetadata(String requestMetadata) { this.requestMetadata = requestMetadata; } /** * Get the violation config to use when performing a scan. * * @return the violation config. */ public ViolationConfig getViolationConfig() { return violationConfig; } /** * Set the violation config to use when performing a scan. * * @param violationConfig the violation config. */ public void setViolationConfig(ViolationConfig violationConfig) { this.violationConfig = violationConfig; } }
0
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan/model/ScanFileResponse.java
package ai.nightfall.scan.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.UUID; /** * The object returned by the Nightfall API when an (asynchronous) file scan request was successfully triggered. */ @JsonIgnoreProperties(ignoreUnknown = true) public class ScanFileResponse { @JsonProperty("id") private UUID id; @JsonProperty("message") private String message; // appease jackson serialization public ScanFileResponse() {} /** * Construct a new ScanFileResponse object. * * @param id the ID of the file to-be-scanned * @param message the status message */ public ScanFileResponse(UUID id, String message) { this.id = id; this.message = message; } /** * Get the file ID. * * @return the ID of the file whose scan was triggered */ public UUID getId() { return id; } /** * Get the status message. * * @return a status message describing the file scan */ public String getMessage() { return message; } @Override public String toString() { return "ScanFileResponse{" + "id=" + id + ", message='" + message + '\'' + '}'; } }
0
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan/model/ScanPolicy.java
package ai.nightfall.scan.model; import ai.nightfall.scan.model.alert.AlertConfig; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; import java.util.UUID; /** * An object containing configuration that describes how to scan a file. Since the file is scanned asynchronously, * the results from the scan are delivered to the provided webhook URL. The scan configuration may contain both * inline detection rule definitions and UUID's referring to existing detection rules (up to 10 of each). */ public class ScanPolicy { @Deprecated @JsonProperty("webhookURL") private String webhookURL; @JsonProperty("detectionRules") private List<DetectionRule> detectionRules; @JsonProperty("detectionRuleUUIDs") private List<UUID> detectionRuleUUIDs; @JsonProperty("alertConfig") private AlertConfig alertConfig; /** * Create a scan policy with the provided detection rules. * * @param detectionRules a list of detection rules to use to scan content. maximum length 10. * @param webhookURL the URL that Nightfall will use to deliver a webhook containing scan results * @return the scan policy */ public static ScanPolicy fromDetectionRules(List<DetectionRule> detectionRules, String webhookURL) { return new ScanPolicy(webhookURL, detectionRules, null); } /** * Create a scan policy with the provided detection rules. * * @param detectionRuleUUIDs a list of detection rule UUIDs to use to scan content. maximum length 10. * @param webhookURL the URL that Nightfall will use to deliver a webhook containing scan results * @return the scan policy */ public static ScanPolicy fromDetectionRuleUUIDs(List<UUID> detectionRuleUUIDs, String webhookURL) { return new ScanPolicy(webhookURL, null, detectionRuleUUIDs); } /** * Create a scan policy with the provided detection rules and detection rule UUIDs. * * @param webhookURL the URL that Nightfall will use to deliver a webhook containing scan results * @param detectionRules a list of detection rules to use to scan content. maximum length 10. * @param detectionRuleUUIDs a list of detection rule UUIDs to use to scan content. maximum length 10. */ @Deprecated public ScanPolicy(String webhookURL, List<DetectionRule> detectionRules, List<UUID> detectionRuleUUIDs) { this.webhookURL = webhookURL; this.detectionRules = detectionRules; this.detectionRuleUUIDs = detectionRuleUUIDs; } /** * Create a scan policy with the provided detection rules and detection rule UUIDs. * * @param alertConfig the alert configuration that Nightfall will use to deliver findings to external sources. * @param detectionRules a list of detection rules to use to scan content. maximum length 10. * @param detectionRuleUUIDs a list of detection rule UUIDs to use to scan content. maximum length 10. */ public ScanPolicy(AlertConfig alertConfig, List<DetectionRule> detectionRules, List<UUID> detectionRuleUUIDs) { this.alertConfig = alertConfig; this.detectionRules = detectionRules; this.detectionRuleUUIDs = detectionRuleUUIDs; } /** * Get the webhook URL. Deprecated: use the <code>alertConfig</code> object instead. * * @return the webhook URL that Nightfall should deliver results to */ @Deprecated public String getWebhookURL() { return webhookURL; } /** * Set the webhook URL. * * @param webhookURL the webhook URL that Nightfall should deliver results to */ @Deprecated public void setWebhookURL(String webhookURL) { this.webhookURL = webhookURL; } /** * Get the list of detection rules. * * @return the list of detection rules to use to scan the files */ public List<DetectionRule> getDetectionRules() { return detectionRules; } /** * Set the detection rules. * * @param detectionRules a list of detection rules to scan against */ public void setDetectionRules(List<DetectionRule> detectionRules) { this.detectionRules = detectionRules; } /** * Get the detection rule UUIDs. * * @return the list of detection rule UUIDs to scan against */ public List<UUID> getDetectionRuleUUIDs() { return detectionRuleUUIDs; } /** * Set the detection rule UUIDs. * * @param detectionRuleUUIDs the list of detection rule UUIDs to scan against */ public void setDetectionRuleUUIDs(List<UUID> detectionRuleUUIDs) { this.detectionRuleUUIDs = detectionRuleUUIDs; } /** * Get the alert configuration that specifies where alerts should be delivered when findings are detected. * * @return the alert configuration */ public AlertConfig getAlertConfig() { return alertConfig; } /** * Sets the alert configuration that specifies where alerts should be delivered when findings are detected. * * @param alertConfig the alert configuration */ public void setAlertConfig(AlertConfig alertConfig) { this.alertConfig = alertConfig; } }
0
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan/model/ScanTextConfig.java
package ai.nightfall.scan.model; import ai.nightfall.scan.model.alert.AlertConfig; import ai.nightfall.scan.model.redaction.RedactionConfig; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; import java.util.UUID; /** * The configuration object to use when scanning inline plaintext with the Nightfall API. */ public class ScanTextConfig { @JsonProperty("detectionRuleUUIDs") private List<UUID> detectionRuleUUIDs; @JsonProperty("detectionRules") private List<DetectionRule> detectionRules; @JsonProperty("contextBytes") private int contextBytes; @JsonProperty("defaultRedactionConfig") private RedactionConfig defaultRedactionConfig; @JsonProperty("alertConfig") private AlertConfig alertConfig; /** * Create a scan configuration with the provided detection rules. * * @param detectionRuleUUIDs a list of detection rules to use to scan content (maximum length 10) * @param contextBytes the number of bytes of context (leading and trailing) to return with any matched findings * @return the scan configuration */ public static ScanTextConfig fromDetectionRuleUUIDs(List<UUID> detectionRuleUUIDs, int contextBytes) { return new ScanTextConfig(detectionRuleUUIDs, null, contextBytes); } /** * Create a scan configuration with the provided detection rules. * * @param detectionRules a list of detection rules to use to scan content (maximum length 10) * @param contextBytes the number of bytes of context (leading and trailing) to return with any matched findings * @return the scan configuration */ public static ScanTextConfig fromDetectionRules(List<DetectionRule> detectionRules, int contextBytes) { return new ScanTextConfig(null, detectionRules, contextBytes); } /** * Create a scan configuration with the provided inline detection rules and detection rule UUIDs. * * @param detectionRuleUUIDs a list of detection rules to use to scan content (maximum length 10) * @param detectionRules a list of detection rules to use to scan content (maximum length 10) * @param contextBytes the number of bytes of context (leading and trailing) to return with any matched findings */ public ScanTextConfig(List<UUID> detectionRuleUUIDs, List<DetectionRule> detectionRules, int contextBytes) { this.detectionRuleUUIDs = detectionRuleUUIDs; this.detectionRules = detectionRules; this.contextBytes = contextBytes; } /** * Create a scan configuration with the provided inline detection rules and detection rule UUIDs. * * @param detectionRuleUUIDs a list of detection rules to use to scan content (maximum length 10) * @param detectionRules a list of detection rules to use to scan content (maximum length 10) * @param contextBytes the number of bytes of context (leading and trailing) to return with any matched findings * @param defaultRedactionConfig the default redaction configuration to apply to all detection rules */ public ScanTextConfig(List<UUID> detectionRuleUUIDs, List<DetectionRule> detectionRules, int contextBytes, RedactionConfig defaultRedactionConfig) { this.detectionRuleUUIDs = detectionRuleUUIDs; this.detectionRules = detectionRules; this.contextBytes = contextBytes; this.defaultRedactionConfig = defaultRedactionConfig; } /** * Get the detection rule UUIDs. * * @return the detection rule UUIDs to use to scan the file */ public List<UUID> getDetectionRuleUUIDs() { return detectionRuleUUIDs; } /** * Set the detection rule UUIDs. * * @param detectionRuleUUIDs the detection rule UUIDs to use to scan the file */ public void setDetectionRuleUUIDs(List<UUID> detectionRuleUUIDs) { this.detectionRuleUUIDs = detectionRuleUUIDs; } /** * Get the detection rule UUIDs. * * @return the detection rules to use to scan the file */ public List<DetectionRule> getDetectionRules() { return detectionRules; } /** * Set the detection rules. * * @param detectionRules the detection rules to use to scan the file */ public void setDetectionRules(List<DetectionRule> detectionRules) { this.detectionRules = detectionRules; } /** * Get the number of context bytes. * * @return the number of bytes of context (leading and trailing) to return with any matched findings */ public int getContextBytes() { return contextBytes; } /** * Set the number of context bytes. * * @param contextBytes the number of bytes of context (leading and trailing) to return with any matched findings */ public void setContextBytes(int contextBytes) { this.contextBytes = contextBytes; } /** * Get the default redaction configuration to-be-applied to all detection rules, unless a more specific redaction * configuration is supplied at the detector level. * * @return the default redaction configuration */ public RedactionConfig getDefaultRedactionConfig() { return defaultRedactionConfig; } /** * Set the default redaction configuration to-be-applied to all detection rules, unless a more specific redaction * configuration is supplied at the detector level. * * @param defaultRedactionConfig the default redaction configuration */ public void setDefaultRedactionConfig(RedactionConfig defaultRedactionConfig) { this.defaultRedactionConfig = defaultRedactionConfig; } /** * Get the alert configuration that specifies where alerts should be delivered when findings are detected. * * @return the alert configuration */ public AlertConfig getAlertConfig() { return alertConfig; } /** * Sets the alert configuration that specifies where alerts should be delivered when findings are detected. * * @param alertConfig the alert configuration */ public void setAlertConfig(AlertConfig alertConfig) { this.alertConfig = alertConfig; } @Override public String toString() { return "ScanTextConfig{" + "detectionRuleUUIDs=" + detectionRuleUUIDs + ", detectionRules=" + detectionRules + ", contextBytes=" + contextBytes + ", defaultRedactionConfig=" + defaultRedactionConfig + ", alertConfig=" + alertConfig + '}'; } }
0
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan/model/ScanTextRequest.java
package ai.nightfall.scan.model; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; import java.util.UUID; /** * An object representing a request to scan inline plaintext with the Nightfall API. */ public class ScanTextRequest { @JsonProperty("payload") private List<String> payload; @JsonProperty("policy") private ScanTextConfig policy; @JsonProperty("policyUUIDs") private List<UUID> policyUUIDs; @JsonProperty("violation") private ViolationConfig violationConfig; /** * Create a request to scan the provided <code>payload</code> against the provided scanning * <code>policy</code>. * * @param payload the content to scan * @param policy the configuration to use to scan the content */ public ScanTextRequest(List<String> payload, ScanTextConfig policy) { this.payload = payload; this.policy = policy; } /** * Create a request to scan the provided <code>payload</code> against the provided scanning * <code>policy</code>. * * @param payload the content to scan * @param policy the configuration to use to scan the content * @param violationConfig the violation configuration to use on the scanned content */ public ScanTextRequest(List<String> payload, ScanTextConfig policy, ViolationConfig violationConfig) { this.payload = payload; this.policy = policy; this.violationConfig = violationConfig; } /** * Create a request to scan the provided <code>payload</code> against the provided * <code>policyUUIDs</code>. * * @param payload the content to scan * @param policyUUIDs a list of UUIDs referring to pre-created policies to-be-used when scanning. Maximum 1. */ public ScanTextRequest(List<String> payload, List<UUID> policyUUIDs) { this.payload = payload; this.policyUUIDs = policyUUIDs; } /** * Create a request to scan the provided <code>payload</code> against the provided * <code>policyUUIDs</code>. * * @param payload the content to scan * @param policyUUIDs a list of UUIDs referring to pre-created policies to-be-used when scanning. Maximum 1. * @param violationConfig the violation configuration to use on the scanned content */ public ScanTextRequest(List<String> payload, List<UUID> policyUUIDs, ViolationConfig violationConfig) { this.payload = payload; this.policyUUIDs = policyUUIDs; this.violationConfig = violationConfig; } /** * Get the request payload. * * @return the request data to scan */ public List<String> getPayload() { return payload; } /** * Set the request payload. * * @param payload the request data to scan */ public void setPayload(List<String> payload) { this.payload = payload; } /** * Get the request scan policy. * * @return the configuration to use to scan the <code>payload</code> data * * @deprecated alias for <code>getPolicy</code>, just provided for backwards compatibility. */ @Deprecated @JsonIgnore public ScanTextConfig getConfig() { return getPolicy(); } /** * Get the request scan policy. * * @return the configuration to use to scan the <code>payload</code> data */ public ScanTextConfig getPolicy() { return policy; } /** * Set the request scan policy. * * @param config the configuration to use to scan the <code>payload</code> data * * @deprecated alias for <code>setPolicy</code>, just provided for backwards compatibility. */ @Deprecated @JsonIgnore public void setConfig(ScanTextConfig config) { setPolicy(config); } /** * Set the request scan policy. * * @param policy the configuration to use to scan the <code>payload</code> data */ public void setPolicy(ScanTextConfig policy) { this.policy = policy; } /** * Get the policy UUIDs to use when performing a scan. * * @return the policy UUIDs. */ public List<UUID> getPolicyUUIDs() { return policyUUIDs; } /** * Set the policy UUIDs to use when performing a scan. * * @param policyUUIDs the policy UUIDs. */ public void setPolicyUUIDs(List<UUID> policyUUIDs) { this.policyUUIDs = policyUUIDs; } /** * Get the violation config to use when performing a scan. * * @return the violation config. */ public ViolationConfig getViolationConfig() { return violationConfig; } /** * Set the violation config to use when performing a scan. * * @param violationConfig the violation config. */ public void setViolationConfig(ViolationConfig violationConfig) { this.violationConfig = violationConfig; } }
0
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan/model/ScanTextResponse.java
package ai.nightfall.scan.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; /** * The response object returned by a text scan request. Each index <code>i</code> in the field <code>findings</code> * corresponds one-to-one with the input request <code>payload</code>, so all findings stored in a given sub-list * refer to matches that occurred in the <code>i</code>th index of the request payload. */ @JsonIgnoreProperties(ignoreUnknown = true) public class ScanTextResponse { @JsonProperty("findings") private List<List<Finding>> findings; @JsonProperty("redactedPayload") private List<String> redactedPayload; /** * Get the findings. * * @return the findings */ public List<List<Finding>> getFindings() { return findings; } /** * Return the original request content with the configured redactions applied. If redaction was not * applied for a given input string, the string at a given index in the array will be empty. * * @return the original content with the configured redactions applied */ public List<String> getRedactedPayload() { return redactedPayload; } @Override public String toString() { return "ScanTextResponse{" + "findings=" + findings + ", redactedPayload=" + redactedPayload + '}'; } }
0
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan/model/UploadFileChunkRequest.java
package ai.nightfall.scan.model; import java.util.UUID; /** * An object representing a request to upload a chunk of file data to the Nightfall API. */ public class UploadFileChunkRequest { private UUID fileUploadID; private long fileOffset; private byte[] content; /** * Create a new instance of a file chunk upload request. * * @param fileUploadID the ID of the file * @param fileOffset the offset at which to upload bytes */ public UploadFileChunkRequest(UUID fileUploadID, long fileOffset) { this.fileUploadID = fileUploadID; this.fileOffset = fileOffset; } /** * Create a new instance of a file chunk upload request. * * @param fileUploadID the ID of the file * @param fileOffset the offset at which to upload bytes * @param content the payload bytes to upload */ public UploadFileChunkRequest(UUID fileUploadID, long fileOffset, byte[] content) { this.fileUploadID = fileUploadID; this.fileOffset = fileOffset; this.content = content; } /** * Get the file ID. * * @return the file ID */ public UUID getFileUploadID() { return fileUploadID; } /** * Get the file offset. * * @return the offset at which to upload bytes */ public long getFileOffset() { return fileOffset; } /** * Get the request payload. * * @return the payload bytes to upload */ public byte[] getContent() { return content; } /** * Set the request payload. * * @param content the content to upload */ public void setContent(byte[] content) { this.content = content; } }
0
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan/model/UserViolation.java
package ai.nightfall.scan.model; import com.fasterxml.jackson.annotation.JsonProperty; /** * User details associated with a violation. */ public class UserViolation { @JsonProperty("id") private String id; @JsonProperty("displayName") private String displayName; /** * Creates a new UserViolation object. * * @param id the id of the user * @param displayName the display name for the user */ public UserViolation(String id, String displayName) { this.id = id; this.displayName = displayName; } /** * Get the id. * * @return the id of the user */ public String getId() { return id; } /** * Set the id. * * @param id the id of the user */ public void setId(String id) { this.id = id; } /** * Get the display name. * * @return the display name of the user */ public String getDisplayName() { return displayName; } /** * Set the display name. * * @param displayName the display name of the user */ public void setDisplayName(String displayName) { this.displayName = displayName; } }
0
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan/model/ViolationConfig.java
package ai.nightfall.scan.model; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Map; /** * Configuration that can be added to a scan request which is used to generate a Nightfall specific violation. * This class can currently only be used by Nightfall partners. */ public class ViolationConfig { /** * Value used to indicate what remediation action will be taken on violations found. */ public enum Action { UNSPECIFIED, ENCRYPT, BLOCK; } @JsonProperty("location") private String location; @JsonProperty("sublocation") private String sublocation; @JsonProperty("user") private UserViolation user; @JsonProperty("action") private Action action; @JsonProperty("actionPhrase") private String actionPhrase; @JsonProperty("properties") private Map<String, String> properties; /** * Creates a new ViolationConfig object. * * @param location the location of the content to be scanned * @param sublocation the sublocation of the content to be scanned * @param user the user associated with the content to be scanned * @param action the action to be taken on any findings from the scan request * @param actionPhrase the phrase to describe the action to be taken on any findings * @param properties a map of key value pairs containing metadata about the content to be scanned */ public ViolationConfig( String location, String sublocation, UserViolation user, Action action, String actionPhrase, Map<String, String> properties) { this.location = location; this.sublocation = sublocation; this.user = user; this.action = action; this.actionPhrase = actionPhrase; this.properties = properties; } /** * Get the location. * * @return the location associated with the created violation */ public String getLocation() { return location; } /** * Set the location. * * @param location the location associated with the created violation */ public void setLocation(String location) { this.location = location; } /** * Get the sublocation. * * @return the sublocation associated with the created violation */ public String getSublocation() { return sublocation; } /** * Set the sublocation. * * @param sublocation the sublocation associated with the created violation */ public void setSublocation(String sublocation) { this.sublocation = sublocation; } /** * Get the user. * * @return the user associated with the created violation */ public UserViolation getUser() { return user; } /** * Set the user. * * @param user the user associated with the created violation */ public void setUser(UserViolation user) { this.user = user; } /** * Get the action. * * @return the action associated with the created violation */ public Action getAction() { return action; } /** * Set the action. * * @param action the action associated with the created violation */ public void setAction(Action action) { this.action = action; } /** * Get the action phrase. * * @return the action phrase associated with the created violation */ public String getActionPhrase() { return actionPhrase; } /** * Set the action phrase. * * @param actionPhrase the action phrase associated with the created violation */ public void setActionPhrase(String actionPhrase) { this.actionPhrase = actionPhrase; } /** * Get the properties. * * @return the properties associated with the created violation */ public Map<String, String> getProperties() { return properties; } /** * Set the properties. * * @param properties the properties associated with the created violation */ public void setProperties(Map<String, String> properties) { this.properties = properties; } }
0
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan/model/WordList.java
package ai.nightfall.scan.model; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; /** * A list of words that can be used to customize the behavior of a detector while Nightfall performs a scan. */ public class WordList { @JsonProperty("values") private List<String> values; @JsonProperty("isCaseSensitive") private boolean isCaseSensitive; /** * Creates a new WordList object. * * @param values a list of words * @param isCaseSensitive whether Nightfall needs to consider case sensitivity when searching for matches */ public WordList(List<String> values, boolean isCaseSensitive) { this.values = values; this.isCaseSensitive = isCaseSensitive; } /** * Get the list of words. * * @return a list of words */ public List<String> getValues() { return values; } /** * Get whether the words in the list are case-sensitive. * * @return true if Nightfall needs to consider case sensitivity when searching for matches * in the list, false otherwise */ public boolean isCaseSensitive() { return isCaseSensitive; } }
0
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan/model
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan/model/alert/AlertConfig.java
package ai.nightfall.scan.model.alert; import com.fasterxml.jackson.annotation.JsonProperty; /** * The AlertConfig class allows clients to specify where alerts should be delivered when findings are discovered as * part of a scan. These alerts are delivered asynchronously to all destinations specified in the object instance. */ public class AlertConfig { @JsonProperty("email") private EmailAlert emailAlert; @JsonProperty("slack") private SlackAlert slackAlert; @JsonProperty("url") private WebhookAlert webhookAlert; /** * Build an instance of AlertConfig with all provided alert destinations. * * @param emailAlert the email alert destination * @param slackAlert the Slack alert destination * @param webhookAlert the webhook alert destination */ public AlertConfig(EmailAlert emailAlert, SlackAlert slackAlert, WebhookAlert webhookAlert) { this.emailAlert = emailAlert; this.slackAlert = slackAlert; this.webhookAlert = webhookAlert; } /** * Build an instance of AlertConfig that sends findings alerts via webhook. * * @param webhookAlert the webhook alert destination */ public AlertConfig(WebhookAlert webhookAlert) { this.webhookAlert = webhookAlert; } /** * Build an instance of AlertConfig that sends findings alerts via Slack. * * @param slackAlert the Slack alert destination */ public AlertConfig(SlackAlert slackAlert) { this.slackAlert = slackAlert; } /** * Build an instance of AlertConfig that sends findings alerts via email. * * @param emailAlert the email alert destination */ public AlertConfig(EmailAlert emailAlert) { this.emailAlert = emailAlert; } /** * Returns the email alert destination. * * @return the email alert destination */ public EmailAlert getEmailAlert() { return emailAlert; } /** * Sets the email alert destination. * * @param emailAlert the email alert destination */ public void setEmailAlert(EmailAlert emailAlert) { this.emailAlert = emailAlert; } /** * Returns the Slack alert destination. * * @return the Slack alert destination */ public SlackAlert getSlackAlert() { return slackAlert; } /** * Sets the Slack alert destination. * * @param slackAlert the Slack alert destination */ public void setSlackAlert(SlackAlert slackAlert) { this.slackAlert = slackAlert; } /** * Returns the webhook alert destination. * * @return the webhook alert destination */ public WebhookAlert getWebhookAlert() { return webhookAlert; } /** * Sets the webhook alert destination. * * @param webhookAlert the webhook alert destination */ public void setWebhookAlert(WebhookAlert webhookAlert) { this.webhookAlert = webhookAlert; } @Override public String toString() { return "AlertConfig{" + "emailAlert=" + emailAlert + ", slackAlert=" + slackAlert + ", webhookAlert=" + webhookAlert + '}'; } }
0
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan/model
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan/model/alert/EmailAlert.java
package ai.nightfall.scan.model.alert; import com.fasterxml.jackson.annotation.JsonProperty; /** * The EmailAlert class contains the configuration required to allow clients to send an asynchronous email message * when findings are detected. The findings themselves will be delivered as a file attachment on the email. * Alerts are only sent if findings are detected. */ public class EmailAlert { @JsonProperty("address") private String address; /** * Creates an instance of the EmailAlert class with the provided email address. * * @param address an email address */ public EmailAlert(String address) { this.address = address; } /** * Returns the email address to which alerts should be delivered. * * @return the email address */ public String getAddress() { return address; } /** * Sets the email address to which alerts should be delivered. * * @param address the email address */ public void setAddress(String address) { this.address = address; } @Override public String toString() { return "EmailAlert{" + "address='" + address + '\'' + '}'; } }
0
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan/model
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan/model/alert/SlackAlert.java
package ai.nightfall.scan.model.alert; import com.fasterxml.jackson.annotation.JsonProperty; /** * The SlackAlert class contains the configuration required to allow clients to send asynchronous alerts to a * Slack workspace when findings are detected. Note that in order for Slack alerts to be delivered to your workspace, * you must use authenticate Nightfall to your Slack workspace under the Settings menu on the * <a href="https://app.nightfall.ai/">Nightfall Dashboard</a>. Alerts are only sent if findings are detected. * * <p>Currently, Nightfall supports delivering alerts to public channels, formatted like "#general". */ public class SlackAlert { @JsonProperty("target") private String target; /** * Creates an instance of the SlackAlert class with the provided conversation name. * * @param target a Slack conversation name. */ public SlackAlert(String target) { this.target = target; } /** * Returns the target conversation to which alerts should be delivered. * * @return the name of the target conversation */ public String getTarget() { return target; } /** * Sets the target conversation to which alerts should be delivered. * * @param target the name of the target conversation */ public void setTarget(String target) { this.target = target; } @Override public String toString() { return "SlackAlert{" + "target='" + target + '\'' + '}'; } }
0
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan/model
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan/model/alert/WebhookAlert.java
package ai.nightfall.scan.model.alert; import com.fasterxml.jackson.annotation.JsonProperty; /** * The WebhookAlert class contains the configuration required to allow clients to send a webhook event to an * external URL when findings are detected. The URL provided must (1) use the HTTPS scheme, (2) have a * route defined on the HTTP POST method, and (3) return a 200 status code upon receipt of the event. * * <p>In contrast to other platforms, when using the file scanning APIs, an alert is also sent to this webhook * *even when there are no findings*. */ public class WebhookAlert { @JsonProperty("address") private String address; /** * Creates an instance of the WebhookAlert class with the provided URL. * * @param address a URL address */ public WebhookAlert(String address) { this.address = address; } /** * Returns the URL address to which alerts should be delivered. * * @return the URL address */ public String getAddress() { return address; } /** * Sets the URL address to which alerts should be delivered. * * @param address the URL address */ public void setAddress(String address) { this.address = address; } @Override public String toString() { return "WebhookAlert{" + "address='" + address + '\'' + '}'; } }
0
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan/model
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan/model/redaction/CryptoConfig.java
package ai.nightfall.scan.model.redaction; import com.fasterxml.jackson.annotation.JsonProperty; /** * An object that specifies how findings should be encrypted when returned by the API. Currently, encryption * is only supported for RSA public keys. */ public class CryptoConfig { @JsonProperty("publicKey") private String publicKey; /** * Builds a configuration object with the provided PEM-formatted RSA public key. * * @param publicKey a PEM-formatted RSA public key. */ public CryptoConfig(String publicKey) { this.publicKey = publicKey; } /** * Get the public key. * * @return the public key */ public String getPublicKey() { return publicKey; } /** * Set the public key. * * @param publicKey the public key */ public void setPublicKey(String publicKey) { this.publicKey = publicKey; } @Override public String toString() { return "CryptoConfig{" + "publicKey='" + publicKey + '\'' + '}'; } }
0
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan/model
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan/model/redaction/InfoTypeSubstitutionConfig.java
package ai.nightfall.scan.model.redaction; import com.fasterxml.jackson.databind.annotation.JsonSerialize; /** * An object that specifies that findings should be substituted with the name of the info type that matched * the request data. */ @JsonSerialize public class InfoTypeSubstitutionConfig { @Override public String toString() { return "InfoTypeSubstitutionConfig{}"; } }
0
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan/model
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan/model/redaction/MaskConfig.java
package ai.nightfall.scan.model.redaction; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Arrays; /** * An object that specifies how findings should be masked when returned by the API. */ public class MaskConfig { @JsonProperty("maskingChar") private String maskingChar; @JsonProperty("charsToIgnore") private String[] charsToIgnore; @JsonProperty("numCharsToLeaveUnmasked") private int numCharsToLeaveUnmasked; @JsonProperty("maskLeftToRight") private boolean maskLeftToRight; /** * Default constructor; when no masking char is provided, defaults to '*'. */ public MaskConfig() { this.charsToIgnore = new String[0]; this.numCharsToLeaveUnmasked = 0; this.maskLeftToRight = false; } /** * Builds a masking configuration with the provided masking character. * * @param maskingChar the masking character; this character may be a multi-byte character, but it must be * exactly one codepoint. */ public MaskConfig(String maskingChar) { this(); this.maskingChar = maskingChar; this.charsToIgnore = new String[0]; } /** * Builds a masking configuration with the provided masking character and characters to ignore. * * @param maskingChar the masking character; this character may be a multi-byte character, but it must be * exactly one codepoint. * @param charsToIgnore the set of characters to leave unmasked when the finding is returned. These characters may * be multi-byte characters, but each entry in the array must be exactly one codepoint. */ public MaskConfig(String maskingChar, String[] charsToIgnore) { this.maskingChar = maskingChar; this.charsToIgnore = charsToIgnore; } /** * Returns the masking character. * * @return the masking character */ public String getMaskingChar() { return maskingChar; } /** * Sets the masking character. * * @param maskingChar the masking character */ public void setMaskingChar(String maskingChar) { this.maskingChar = maskingChar; } /** * Returns the characters to ignore during masking. * * @return the characters to ignore during masking */ public String[] getCharsToIgnore() { return charsToIgnore; } /** * Sets the characters to ignore during masking. * * @param charsToIgnore the characters to ignore during masking */ public void setCharsToIgnore(String[] charsToIgnore) { this.charsToIgnore = charsToIgnore; } /** * Returns the number of characters to leave unmasked, defaults to 0. * * @return the number of characters to leave unmasked, defaults to 0 */ public int getNumCharsToLeaveUnmasked() { return numCharsToLeaveUnmasked; } /** * Sets the number of characters to leave unmasked. * * @param numCharsToLeaveUnmasked the number of characters to leave unmasked */ public void setNumCharsToLeaveUnmasked(int numCharsToLeaveUnmasked) { this.numCharsToLeaveUnmasked = numCharsToLeaveUnmasked; } /** * Returns true if masking should be applied left-to-right, false otherwise. Defaults to false. * * @return true if masking should be applied left-to-right, false otherwise */ public boolean isMaskLeftToRight() { return maskLeftToRight; } /** * Sets whether masking should be applied left-to-right. * * @param maskLeftToRight true if masking should be applied left-to-right, false otherwise */ public void setMaskLeftToRight(boolean maskLeftToRight) { this.maskLeftToRight = maskLeftToRight; } @Override public String toString() { return "MaskConfig{" + "maskingChar=" + maskingChar + ", charsToIgnore=" + Arrays.toString(charsToIgnore) + ", numCharsToLeaveUnmasked=" + numCharsToLeaveUnmasked + ", maskLeftToRight=" + maskLeftToRight + '}'; } }
0
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan/model
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan/model/redaction/RedactionConfig.java
package ai.nightfall.scan.model.redaction; import com.fasterxml.jackson.annotation.JsonProperty; /** * An object that configures how any detected findings should be redacted when returned to the client. When this * configuration is provided as part of a request, exactly one of the four types of redaction should be set. * * <p>Four types of redaction are supported: * <ol> * <li>Masking: replacing the characters of a finding with another character, such as '*' or '👀'</li> * <li>Info Type Substitution: replacing the finding with the name of the detector it matched, such * as CREDIT_CARD_NUMBER</li> * <li>Substitution: replacing the finding with a custom string, such as "oh no!"</li> * <li>Encryption: encrypting the finding with an RSA public key</li> * </ol> */ public class RedactionConfig { @JsonProperty("maskConfig") private MaskConfig maskConfig; @JsonProperty("infoTypeSubstitutionConfig") private InfoTypeSubstitutionConfig infoTypeSubstitutionConfig; @JsonProperty("substitutionConfig") private SubstitutionConfig substitutionConfig; @JsonProperty("cryptoConfig") private CryptoConfig cryptoConfig; @JsonProperty("removeFinding") private boolean removeFinding; /** * Build a redaction config with masking. * * @param maskConfig the masking configuration */ public RedactionConfig(MaskConfig maskConfig) { this.maskConfig = maskConfig; } /** * Build a redaction config with info type substitution. * * @param infoTypeSubstitutionConfig the info type substitution configuration */ public RedactionConfig(InfoTypeSubstitutionConfig infoTypeSubstitutionConfig) { this.infoTypeSubstitutionConfig = infoTypeSubstitutionConfig; } /** * Build a redaction config with substitution. * * @param substitutionConfig the substitution configuration */ public RedactionConfig(SubstitutionConfig substitutionConfig) { this.substitutionConfig = substitutionConfig; } /** * Build a redaction config with RSA encryption. * * @param cryptoConfig the crypto configuration */ public RedactionConfig(CryptoConfig cryptoConfig) { this.cryptoConfig = cryptoConfig; } /** * Get the masking configuration. * * @return the masking configuration */ public MaskConfig getMaskConfig() { return maskConfig; } /** * Get the info type substitution configuration. * * @return the info type substitution configuration */ public InfoTypeSubstitutionConfig getInfoTypeSubstitutionConfig() { return infoTypeSubstitutionConfig; } /** * Get the substitution configuration. * * @return the substitution configuration */ public SubstitutionConfig getSubstitutionConfig() { return substitutionConfig; } /** * Get the encryption configuration. * * @return the encryption configuration */ public CryptoConfig getCryptoConfig() { return cryptoConfig; } /** * Returns whether the original finding should be omitted in responses from the API. * * @return true if the original finding should be omitted in responses from the API, false otherwise */ public boolean isRemoveFinding() { return removeFinding; } /** * Sets whether the original finding should be omitted in responses from the API. * * @param removeFinding true if the original finding should be omitted in responses from the API, false otherwise */ public void setRemoveFinding(boolean removeFinding) { this.removeFinding = removeFinding; } @Override public String toString() { return "RedactionConfig{" + "maskConfig=" + maskConfig + ", infoTypeSubstitutionConfig=" + infoTypeSubstitutionConfig + ", substitutionConfig=" + substitutionConfig + ", cryptoConfig=" + cryptoConfig + ", removeFinding=" + removeFinding + '}'; } }
0
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan/model
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan/model/redaction/SubstitutionConfig.java
package ai.nightfall.scan.model.redaction; import com.fasterxml.jackson.annotation.JsonProperty; /** * An object that specifies how findings should be substituted when returned by the API. This is similar * to masking, but allows for a custom phrase to be used rather than simply redacting each codepoint. */ public class SubstitutionConfig { @JsonProperty("substitutionPhrase") private String substitutionPhrase; /** * Builds a substitution configuration with the provided phrase. * * @param substitutionPhrase a phrase to substitute for a finding. */ public SubstitutionConfig(String substitutionPhrase) { this.substitutionPhrase = substitutionPhrase; } /** * Returns the substitution phrase. * * @return the substitution phrase. */ public String getSubstitutionPhrase() { return substitutionPhrase; } /** * Sets the substitution phrase. * * @param substitutionPhrase the substitution phrase */ public void setSubstitutionPhrase(String substitutionPhrase) { this.substitutionPhrase = substitutionPhrase; } @Override public String toString() { return "SubstitutionConfig{" + "substitutionPhrase='" + substitutionPhrase + '\'' + '}'; } }
0
java-sources/ai/nixiesearch/llamacpp-server-java/0.0.4-b5604/ai/nixiesearch
java-sources/ai/nixiesearch/llamacpp-server-java/0.0.4-b5604/ai/nixiesearch/llamacppserver/LlamacppServer.java
package ai.nixiesearch.llamacppserver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.nio.file.Files; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; public class LlamacppServer implements AutoCloseable { public Process process; public File workdir; public CompletableFuture<Void> logStream; private static final Logger logger = LoggerFactory.getLogger(LlamacppServer.class); private static String[] CPU_LIBS = {"libggml.so", "libggml-base.so", "libggml-cpu.so", "libllama.so", "llama-server", "libmtmd.so"}; private static String[] CUDA_LIBS = {"libggml.so", "libggml-base.so", "libggml-cpu.so", "libggml-cuda.so", "libllama.so", "llama-server", "libmtmd.so"}; volatile private static boolean isStarted = false; private static LlamacppServer instance = null; private static List<File> unpackedFiles = new ArrayList<>(); public enum LLAMACPP_BACKEND { GGML_CPU, GGML_CUDA12 } LlamacppServer(Process process, File workdir, CompletableFuture<Void> logStream) { this.process = process; this.workdir = workdir; this.logStream = logStream; } public synchronized static LlamacppServer start(String[] args, LLAMACPP_BACKEND backend) throws IOException, InterruptedException { if (!isStarted) { isStarted = true; File workdir = unpack(backend); ProcessBuilder builder = new ProcessBuilder(); List<String> commandArgs = new ArrayList<>(); commandArgs.add(workdir + "/llama-server"); commandArgs.addAll(Arrays.asList(args)); builder.command(commandArgs); builder.redirectErrorStream(true); builder.directory(workdir); Process process = builder.start(); CompletableFuture<Void> logStream = CompletableFuture.runAsync(() -> { try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) { String line; while (process.isAlive() && (line = reader.readLine()) != null) { logger.info(line); } } catch (IOException e) { if (process.isAlive()) { logger.error("Log stream error: {}", e.getMessage(), e); } else { logger.debug("Log stream closed during shutdown: {}", e.getMessage()); } } catch (Exception e) { logger.error("Unexpected error in log stream: {}", e.getMessage(), e); } } ); instance = new LlamacppServer(process, workdir, logStream); return instance; } else { logger.warn("Called LlamacppServer.start for the second time - it seems like a bug"); return instance; } } @Override public synchronized void close() throws Exception { if (isStarted) { stop(); for (File unpacked: unpackedFiles) { if (unpacked.exists()) { logger.info("Deleting temp file {}", unpacked); unpacked.delete(); } } isStarted = false; instance = null; } else { logger.warn("Called LlamacppServer.close over a closed server - it seems like a bug"); } } private void stop() throws IOException, InterruptedException, ExecutionException { if (process.isAlive()) { logger.info("Waiting for running llamacpp-server to stop..."); process.destroy(); boolean exited = process.waitFor(10, java.util.concurrent.TimeUnit.SECONDS); if (!exited) { logger.warn("Process did not exit gracefully, forcing termination"); process.destroyForcibly(); process.waitFor(5, java.util.concurrent.TimeUnit.SECONDS); } try { logStream.get(2, java.util.concurrent.TimeUnit.SECONDS); } catch (java.util.concurrent.TimeoutException e) { logger.debug("Log stream did not complete within timeout, continuing shutdown"); } logger.info("llamacpp-server stopped"); } else { logger.info("llamacpp-server is already stopped"); try { logStream.get(1, java.util.concurrent.TimeUnit.SECONDS); } catch (java.util.concurrent.TimeoutException e) { logger.debug("Log stream cleanup timeout, continuing"); } } } private static synchronized File unpack(LLAMACPP_BACKEND backend) throws IOException { String tmp = System.getProperty("java.io.tmpdir"); File workdir = new File(tmp + File.separator + "llamacpp"); if (!workdir.exists() && !workdir.mkdirs()) { throw new IOException("Cannot create temp dir "+workdir); } else { String os = System.getProperty("os.name").toLowerCase(Locale.ENGLISH); String arch = System.getProperty("os.arch", "generic").toLowerCase(Locale.ENGLISH); logger.info("Unpacking llamacpp-server for os={} arch={}", os, arch); if (os.startsWith("linux")) { if (arch.startsWith("amd64") || arch.startsWith("x86_64")) { if (backend == LLAMACPP_BACKEND.GGML_CPU) { unpackResourceList(workdir, "native/linux/x86_64/cpu", CPU_LIBS); } else if (backend == LLAMACPP_BACKEND.GGML_CUDA12) { unpackResourceList(workdir, "native/linux/x86_64/cu12", CUDA_LIBS); } } else if (arch.startsWith("aarch64") || arch.startsWith("arm64")) { if (backend == LLAMACPP_BACKEND.GGML_CPU) { unpackResourceList(workdir,"native/linux/arm64/cpu", CPU_LIBS); } else if (backend == LLAMACPP_BACKEND.GGML_CUDA12) { throw new IOException("CUDA on arm64 is not supported"); } } else { throw new IOException("Only aarch64/arm64 and x86_64 are supported"); } } else { throw new IOException("Sorry, we only yet support linux builds"); } } return workdir; } private static void unpackResourceList(File workdir, String resourceDir, String[] resourcePaths) throws IOException { for (String fileName: resourcePaths) { File dest = new File(workdir.toString() + File.separator + fileName); String path = resourceDir + "/" + fileName; if (!dest.exists()) { logger.info("Extracting native lib {} to {}", path, dest); InputStream libStream = LlamacppServer.class.getClassLoader().getResourceAsStream(path); OutputStream fileStream = Files.newOutputStream(dest.toPath()); copyStream(libStream, fileStream); libStream.close(); fileStream.close(); dest.setExecutable(true); unpackedFiles.add(dest); } else { logger.info("Native lib {} already exists at {}", path, dest); } } } private static void copyStream(InputStream source, OutputStream target) throws IOException { byte[] buf = new byte[8192]; int length; int bytesCopied = 0; while ((length = source.read(buf)) > 0) { target.write(buf, 0, length); bytesCopied += length; } logger.debug("Copied {} bytes", bytesCopied); } }
0
java-sources/ai/olami/olami-android-client/2.6.0/ai/olami
java-sources/ai/olami/olami-android-client/2.6.0/ai/olami/android/AudioRecordManager.java
/* Copyright 2017, VIA Technologies, Inc. & OLAMI Team. http://olami.ai Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ai.olami.android; import android.media.AudioFormat; import android.media.AudioRecord; import android.media.MediaRecorder; import android.util.Log; import ai.olami.cloudService.SpeechRecognizer; public class AudioRecordManager { private final static String TAG = "AudioRecordManager"; private static AudioRecord mAudioRecord = null; private static AudioRecordManager mAudioRecordFactory = null; public static final int SAMPLE_RATE_44100 = 44100; public static final int SAMPLE_RATE_16000 = 16000; private void AudioRecordManager() { } /** * Create a KeepRecordingSpeechRecognizer instance by a specified speech recognizer. * * @return AudioRecordManager instance. */ public static AudioRecordManager create() throws Exception{ if (mAudioRecordFactory == null) { mAudioRecordFactory = new AudioRecordManager(); mAudioRecordFactory.initializeAudioRecord(); } return mAudioRecordFactory; } /** * Convert audio sample rate from 44100 to 16000. * * @param from - Source buffer. * @param to - Target buffer. */ public static void convert441To16(short[] from, byte[] to) { double ratio = (double) SAMPLE_RATE_44100 / (double) SAMPLE_RATE_16000; for (int i = 0; i < to.length / 2; i++) { double p = i * ratio; int m = (int) p; double delta = p - m; int n = m; if (delta != 0) { n = m + 1; } if (n >= from.length - 1) { n = from.length - 1; } short t = (short) (from[m] + (short) ((from[n] - from[m]) * delta)); to[2 * i] = (byte) (t & 0x00ff); to[2 * i + 1] = (byte) ((t >> 8) & 0x00ff); } } /** * Get AudioRecord. * * @return AudioRecord object instance. */ public AudioRecord getAudioRecord() { if (mAudioRecord != null && mAudioRecord.getState() == AudioRecord.STATE_INITIALIZED) { return mAudioRecord; } else { return null; } } /** * Enable microphone then start the voice recording. * * @throws Exception There is something wrong. */ public void startRecording() throws Exception { if (mAudioRecord == null) { initializeAudioRecord(); } mAudioRecord.startRecording(); } /** * Get the normal supported sample rate * * @return Sample rate */ public static int getSampleRateConfig() { return SAMPLE_RATE_44100; } /** * Get the normal supported audio channel setting * * @return Audio channels */ public static int getAudioChannelConfig() { switch (SpeechRecognizer.AUDIO_CHANNELS) { case 1: return AudioFormat.CHANNEL_IN_MONO; } return AudioFormat.CHANNEL_IN_MONO; } /** * Get the normal supported audio data encoding * * @return Audio data encoding */ public static int getAudioFormatConfig() { switch (SpeechRecognizer.AUDIO_CHANNELS) { case 16: return AudioFormat.ENCODING_PCM_16BIT; } return AudioFormat.ENCODING_PCM_16BIT; } private void initializeAudioRecord() throws Exception { int minBufferSize = AudioRecord.getMinBufferSize( getSampleRateConfig(), getAudioChannelConfig(), getAudioFormatConfig()); if (mAudioRecord == null) { mAudioRecord = new AudioRecord( MediaRecorder.AudioSource.MIC, getSampleRateConfig(), getAudioChannelConfig(), getAudioFormatConfig(), minBufferSize * 4); } Log.i(TAG, "AudioRecord select sample rate is : "+ mAudioRecord.getSampleRate()); // Waiting for AudioRecord initialized int retry = 0; while ((mAudioRecord.getState() != AudioRecord.STATE_INITIALIZED) && (retry < 4)) { Thread.sleep(500); retry++; } // Check AudioRecord is initialized or not if (mAudioRecord.getState() != AudioRecord.STATE_INITIALIZED) { if (mAudioRecord.getState() == AudioRecord.STATE_UNINITIALIZED) { throw new UnsupportedOperationException("Init AudioRecord failed. Permission issue?"); } else { throw new UnknownError("Failed to initialize AudioRecord."); } } } /** * Stop and release resource. * */ public void stopAndRelease() { if ((mAudioRecord != null) && (mAudioRecord.getState() != AudioRecord.STATE_UNINITIALIZED)) { try { mAudioRecord.stop(); mAudioRecord.release(); } catch (Exception e) { Log.e(TAG, "stopAndRelease() Exception: " + e.getMessage()); } } mAudioRecord = null; } }
0
java-sources/ai/olami/olami-android-client/2.6.0/ai/olami
java-sources/ai/olami/olami-android-client/2.6.0/ai/olami/android/IKeepRecordingSpeechRecognizerListener.java
/* Copyright 2017, VIA Technologies, Inc. & OLAMI Team. http://olami.ai Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ai.olami.android; import ai.olami.cloudService.APIResponse; public interface IKeepRecordingSpeechRecognizerListener { /** * Callback when the recognize state changes. * * @param state - Recognize state. */ void onRecognizeStateChange( KeepRecordingSpeechRecognizer.RecognizeState state ); /** * Callback when the results of speech recognition changes. * * @param response - API response with all kinds of results. */ void onRecognizeResultChange(APIResponse response); /** * Callback when the volume of voice input changes. * * @param volumeValue - The volume level of voice input. */ void onRecordVolumeChange(int volumeValue); /** * Callback when a server error occurs. * * @param response - API response with error message. */ void onServerError(APIResponse response); /** * Callback when a error occurs. * * @param error - Error type. */ void onError(KeepRecordingSpeechRecognizer.Error error); /** * Callback when a exception occurs. * * @param e - Exception. */ void onException(Exception e); }
0
java-sources/ai/olami/olami-android-client/2.6.0/ai/olami
java-sources/ai/olami/olami-android-client/2.6.0/ai/olami/android/IRecorderSpeechRecognizerListener.java
/* Copyright 2017, VIA Technologies, Inc. & OLAMI Team. http://olami.ai Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ai.olami.android; import ai.olami.cloudService.APIResponse; public interface IRecorderSpeechRecognizerListener { /** * Callback when the voice recording state changes. * * @param state - Recording state. */ void onRecordStateChange(RecorderSpeechRecognizer.RecordState state); /** * Callback when the recognize process state changes. * * @param state - Recognize process state. */ void onRecognizeStateChange(RecorderSpeechRecognizer.RecognizeState state); /** * Callback when the results of speech recognition changes. * * @param response - API response with all kinds of results. */ void onRecognizeResultChange(APIResponse response); /** * Callback when the volume of voice input changes. * * @param volumeValue - The volume level of voice input. */ void onRecordVolumeChange(int volumeValue); /** * Callback when a server error occurs. * * @param response - API response with error message. */ void onServerError(APIResponse response); /** * Callback when a error occurs. * * @param error - Error type. */ void onError(RecorderSpeechRecognizer.Error error); /** * Callback when a exception occurs. * * @param e - Exception. */ void onException(Exception e); }
0
java-sources/ai/olami/olami-android-client/2.6.0/ai/olami
java-sources/ai/olami/olami-android-client/2.6.0/ai/olami/android/KeepRecordingSpeechRecognizer.java
/* Copyright 2017, VIA Technologies, Inc. & OLAMI Team. http://olami.ai Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ai.olami.android; import android.media.AudioRecord; import android.os.Environment; import java.io.BufferedOutputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.LinkedList; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import ai.olami.android.jni.Codec; import ai.olami.cloudService.APIConfiguration; import ai.olami.cloudService.APIResponse; import ai.olami.cloudService.CookieSet; import ai.olami.cloudService.NLIConfig; import ai.olami.cloudService.SpeechRecognizer; import ai.olami.cloudService.SpeechResult; public class KeepRecordingSpeechRecognizer extends SpeechRecognizerBase { private final static String TAG = "KRSR"; private static KeepRecordingSpeechRecognizer mKeepRecordingSpeechRecognizer = null; private static AudioRecordManager mAudioRecordManager = null; private IKeepRecordingSpeechRecognizerListener mCallback = null; private SpeechRecognizer mRecognizer = null; private AudioRecord mAudioRecord = null; private CookieSet mCookie = null; private NLIConfig mNLIConfig = null; private BlockingQueue mRecordDataQueue = null; private boolean mSendCallback = false; private boolean mRecording = false; private boolean mRecordStopped = false; private boolean mGetting = false; private boolean mCancel = false; private boolean mIsFinal = false; private boolean mCapturedVoiceBegin = false; private boolean mSaveRecordToFile = false; private int mRecognizerTimeout = 5000; private Thread mRecorderThread = null; private Thread mSenderThread = null; private Thread mGetterThread = null; private File mRecordFile = null; private OutputStream mOutputStream = null; private BufferedOutputStream mBufferedOutputStream = null; private DataOutputStream mDataOutputStream = null; private String mRecordFilePath = Environment.getExternalStorageDirectory().getPath() +"/musicbox/"; private String mRecordFileName = "OLAMI-mic-record.pcm"; private VoiceVolume mVoiceVolume = new VoiceVolume(); private Codec mSpeexEncoder = null; private RecognizeState mRecognizeState = null; /** * Recognize process state */ public enum RecognizeState { INITIALIZING, STOPPED, PROCESSING, COMPLETED, ERROR } /** * Error type */ public enum Error { UNKNOWN } private KeepRecordingSpeechRecognizer( IKeepRecordingSpeechRecognizerListener listener, SpeechRecognizer recognizer ) { setListener(listener); setRecognizer(recognizer); setFrameSize(mRecognizer.getAudioFrameSize()); setRecordDataSize(RECORD_FRAMES * getFrameSize()); } /** * Create a KeepRecordingSpeechRecognizer instance. * * @param recognizeListener - The specified callback listener. * @param config - API configurations. * @return KeepRecordingSpeechRecognizer instance. */ public static KeepRecordingSpeechRecognizer create( IKeepRecordingSpeechRecognizerListener recognizeListener, APIConfiguration config ) throws Exception{ return create(recognizeListener, new SpeechRecognizer(config)); } /** * Create a KeepRecordingSpeechRecognizer instance by a specified speech recognizer. * * @param recognizeListener - The specified callback listener. * @param recognizer - Configured speech recognizer. * @return IotRecorderSpeechRecognizer instance. */ public static KeepRecordingSpeechRecognizer create( IKeepRecordingSpeechRecognizerListener recognizeListener, SpeechRecognizer recognizer ) throws Exception { if (mKeepRecordingSpeechRecognizer == null) { mKeepRecordingSpeechRecognizer = new KeepRecordingSpeechRecognizer(recognizeListener, recognizer); } else { mKeepRecordingSpeechRecognizer.stopRecordingAndReleaseResources(); mKeepRecordingSpeechRecognizer = new KeepRecordingSpeechRecognizer(recognizeListener, recognizer); } mKeepRecordingSpeechRecognizer.changeRecognizeState(RecognizeState.INITIALIZING); if (mAudioRecordManager == null) { mAudioRecordManager = AudioRecordManager.create(); } mKeepRecordingSpeechRecognizer.initRecognizeState(); return mKeepRecordingSpeechRecognizer; } /** * Set callback listener. * * @param listener The specified callback listener. */ public void setListener(IKeepRecordingSpeechRecognizerListener listener) { mCallback = listener; } /** * Set speech recognizer. * * @param recognizer - Configured speech recognizer. */ public void setRecognizer(SpeechRecognizer recognizer) { mRecognizer = recognizer; mRecognizer.setSdkType(SDK_TYPE); } /** * Set the identification to identify the End-user. * This is helpful in some of NLU/NLI functions, such as context support. * * @param cusId - End-user identifier. */ public void setEndUserIdentifier(String cusId) { mRecognizer.setEndUserIdentifier(cusId); } /** * Set timeout in milliseconds of each HTTP API request. * Note that each process may contain more than one request. * * @param milliseconds - Timeout in milliseconds. */ public void setApiRequestTimeout(int milliseconds) { mRecognizer.setTimeout(milliseconds); } /** * Set timeout in milliseconds of each recognize process (begin-to-end). * The recognize process will be cancelled if timeout and reset the state. * * @param milliseconds - Timeout in milliseconds. Default is 5000. */ public void setRecognizerTimeout(int milliseconds) { mRecognizerTimeout = milliseconds; } /** * Get current recognize process state. * * @return - Recognize process state. */ public RecognizeState getRecognizeState() { return mRecognizeState; } /** * Stop audio recording and release all resources. */ public void stopRecordingAndReleaseResources() { // Disable callback mSendCallback = false; // Force to cancel all processes. cancelRecognizing(); if (mAudioRecordManager != null) { mAudioRecordManager.stopAndRelease(); } mAudioRecord = null; mAudioRecordManager = null; // Force to change state for re-startRecording. initRecognizeState(); mKeepRecordingSpeechRecognizer = null; } /** * Enable microphone then start the voice recording. * * @throws Exception There is something wrong. */ public void startRecording() throws Exception { mAudioRecordManager.startRecording(); setAudioRecord(mAudioRecordManager.getAudioRecord()); } /** * Start the recognize processing. * The voice recording must be started before you use this method. * * @throws InterruptedException There is something wrong. */ public void startRecognizing() throws InterruptedException { startRecognizing(null); } /** * Start the recognize processing. * The voice recording must be started before you use this method. * * @param nliConfig - NLIConfig object. * * @throws InterruptedException There is something wrong. */ public void startRecognizing(NLIConfig nliConfig) throws InterruptedException { int wait = 0; while (mRecognizeState != RecognizeState.STOPPED) { if (wait >= 10) { changeRecognizeState(RecognizeState.ERROR); throw new InterruptedException("Threads handling state not correct."); } Thread.sleep(500); wait++; } mSendCallback = true; mCancel = false; mRecording = true; mRecordStopped = false; mGetting = false; mIsFinal = false; mCapturedVoiceBegin = false; mCookie = new CookieSet(); mNLIConfig = nliConfig; mRecordDataQueue = new LinkedBlockingQueue(); changeRecognizeState(RecognizeState.PROCESSING); // Init Recorder Thread mRecorderThread = new Thread(new Runnable() { @Override public void run() { try { doRecording(); } catch (Exception e) { changeRecognizeState(RecognizeState.ERROR); mCallback.onException(e); } } }); mRecorderThread.start(); // Init Sender Thread mSenderThread = new Thread(new Runnable() { @Override public void run() { try { doSending(); } catch (Exception e) { changeRecognizeState(RecognizeState.ERROR); mCallback.onException(e); } } }); mSenderThread.start(); // Init Getter Thread mGetterThread = new Thread(new Runnable() { @Override public void run() { try { doGetting(); } catch (Exception e) { changeRecognizeState(RecognizeState.ERROR); mCallback.onException(e); } } }); mGetterThread.start(); // Check to see if recognize process timeout. checkRecognizeTimeout(); } /** * Stop the recognize process and wait for the final recognition result. * */ public void stopRecognizing() { if (mRecording) { mRecording = false; // Waite for the recording stopped. while (!mRecordStopped) { try { Thread.sleep(1); } catch (InterruptedException e) { mCallback.onException(e); } } } } /** * Cancel all processes and give up to get recognition result. * */ public void cancelRecognizing() { mSendCallback = false; stopRecognizing(); mCancel = true; changeRecognizeState(RecognizeState.STOPPED); } /** * Get AudioRecord that used by the KeepRecordingSpeechRecognizer instance. * */ public AudioRecord getAudioRecord() { return mAudioRecord; } /** * Set AudioRecord for the KeepRecordingSpeechRecognizer instance. * */ public void setAudioRecord(AudioRecord audioRecord) { mAudioRecord = audioRecord; } /** * Enable/Disable to save the recorded audio to file. * * @param saveToFile - Set TRUE to enable, set FALSE to disable. */ public void enableSaveRecordToFIle(boolean saveToFile) { enableSaveRecordToFile(saveToFile, getDateTime() +".pcm"); } /** * Enable/Disable to save the recorded audio to file. * * @param saveToFile - Set TRUE to enable, set FALSE to disable. * @param fileName - Name of the file you want to store the audio. */ public void enableSaveRecordToFile(boolean saveToFile, String fileName) { mSaveRecordToFile = saveToFile; mRecordFileName = fileName; } private void doRecording() throws Exception { short[] audioData441 = new short[441 * RECORD_FRAMES]; byte[] audioData = null; LinkedList<byte[]> tempInputs = new LinkedList<byte[]>(); int reservedBlocks = (RESERVED_INPUT_LENGTH_MILLISECONDS / (RECORD_FRAMES * FRAME_LENGTH_MILLISECONDS)); int instantNoiseBlocks = (INSTANT_NOISE_LENGTH_MILLISECONDS / (RECORD_FRAMES * FRAME_LENGTH_MILLISECONDS)); int vadTailBlocks = (getVADEndMilliseconds() / (RECORD_FRAMES * FRAME_LENGTH_MILLISECONDS)); int inputVolume = 0; int priInputVolume = 0; int silence = 0; int instantNoise = 0; while (mRecording) { synchronized (mRecordDataQueue) { if (mAudioRecord.read(audioData441, 0, audioData441.length) == audioData441.length) { audioData = new byte[getRecordDataSize()]; AudioRecordManager.convert441To16(audioData441, audioData); saveRecordToFile(audioData, false); inputVolume = getMicInputVolume(audioData); mCallback.onRecordVolumeChange(inputVolume); if (!mCapturedVoiceBegin) { if (inputVolume == 0) { // Speech may not have started. Buffering silence audio as the head. tempInputs.add(audioData); if (tempInputs.size() > reservedBlocks) { tempInputs.removeFirst(); } } else { mCapturedVoiceBegin = true; // Insert buffered silence audio into the beginning of the real speech input. while (!tempInputs.isEmpty()) { mRecordDataQueue.put(tempInputs.poll()); } // Then append the real speech data mRecordDataQueue.put(audioData); } } else { mRecordDataQueue.put(audioData); if (inputVolume > getSilenceLevel()) { if (silence == 0) { instantNoise = 0; } if (silence > 0) { if (instantNoise == 0) { instantNoise++; } else { if ((instantNoise < instantNoiseBlocks) && (priInputVolume > inputVolume)) { instantNoise++; } else { silence = 0; } } } } else { silence++; } if (silence > vadTailBlocks) { break; } } priInputVolume = inputVolume; } } } mRecordStopped = true; saveRecordToFile(new byte[]{0}, true); stopRecognizing(); } private void doSending() throws Exception { int length = 0; mRecognizer.releaseAppendedAudio(); while (!mCancel) { if (mRecordDataQueue != null) { if (!mRecordDataQueue.isEmpty()) { byte[] audioData = (byte[]) mRecordDataQueue.take(); mIsFinal = (isRecognizerStopped() && (mRecordDataQueue.isEmpty())); length += ((audioData.length / getFrameSize()) * FRAME_LENGTH_MILLISECONDS); if (getAudioCompressLibraryType() == AUDIO_COMPRESS_LIBRARY_TYPE_CPP) { if (mSpeexEncoder == null) { mSpeexEncoder = new Codec(); mSpeexEncoder.open(1, 10); } byte[] encBuffer = new byte[audioData.length]; int encSize = mSpeexEncoder.encodeByte(audioData, 0, audioData.length, encBuffer); mRecognizer.setAudioType(SpeechRecognizer.AUDIO_TYPE_PCM_SPEEX); mRecognizer.appendSpeexAudioFramesData(encBuffer, encSize); } else { mRecognizer.setAudioType(SpeechRecognizer.AUDIO_TYPE_PCM_RAW); mRecognizer.appendAudioFramesData(audioData); } if ((length >= getUploadAudioLengthMilliseconds()) || mIsFinal) { APIResponse response = mRecognizer.flushToUploadAudio(mCookie, mIsFinal); if (response.ok()) { mGetting = true; length = 0; } else { mRecognizer.releaseAppendedAudio(); recognizeResponseError(response); } } } else { // Recorder stopped and the last audio sent at the same time, but mIsFinal = false. if (isRecognizerStopped()) { mIsFinal = true; mRecognizer.setAudioType(SpeechRecognizer.AUDIO_TYPE_PCM_RAW); byte[] audioData = new byte[getRecordDataSize()]; Arrays.fill(audioData, (byte) 0); APIResponse response = mRecognizer.uploadAudio(mCookie, audioData, mIsFinal); if (response.ok()) { mGetting = true; } else { mRecognizer.releaseAppendedAudio(); recognizeResponseError(response); } } } if (mIsFinal) { break; } } } if (mSpeexEncoder != null) { mSpeexEncoder.close(); mSpeexEncoder = null; } } private void doGetting() throws Exception { while (!mCancel) { if (mGetting) { Thread.sleep(getFrequencyToGettingResult()); APIResponse response = null; switch (getRecognizeResultType()) { case RECOGNIZE_RESULT_TYPE_ALL: response = mRecognizer.requestRecognitionWithAll(mCookie, mNLIConfig); break; case RECOGNIZE_RESULT_TYPE_STT: response = mRecognizer.requestRecognition(mCookie); break; case RECOGNIZE_RESULT_TYPE_NLI: response = mRecognizer.requestRecognitionWithNLI(mCookie, mNLIConfig); break; } if (response.ok() && response.hasData()) { SpeechResult sttResult = response.getData().getSpeechResult(); if (mSendCallback) { mCallback.onRecognizeResultChange(response); } if (sttResult.complete()) { changeRecognizeState(RecognizeState.COMPLETED); break; } } else { recognizeResponseError(response); } } } changeRecognizeState(RecognizeState.STOPPED); } private void saveRecordToFile(byte[] buff, boolean isFinal) throws IOException { if (!mSaveRecordToFile) return; if (mRecordFile == null) { mRecordFile = new File(mRecordFilePath, mRecordFileName); mRecordFile.createNewFile(); mOutputStream = new FileOutputStream(mRecordFile); mBufferedOutputStream = new BufferedOutputStream(mOutputStream); mDataOutputStream = new DataOutputStream(mBufferedOutputStream); } mDataOutputStream.write(buff); if (isFinal) { mDataOutputStream.close(); mRecordFile = null; } } private boolean isRecognizerStopped() { if (mRecording) { return false; } else { return true; } } private void changeRecognizeState(RecognizeState state) { mRecognizeState = state; if (mSendCallback || (state == RecognizeState.ERROR)) { mCallback.onRecognizeStateChange(mRecognizeState); } if (mRecognizeState == RecognizeState.ERROR) { cancelRecognizing(); } } private void recognizeResponseError(APIResponse response) { mCallback.onServerError(response); changeRecognizeState(RecognizeState.ERROR); } private void initRecognizeState() { changeRecognizeState(RecognizeState.STOPPED); } private int getMicInputVolume(byte[] data) { return (int) (mVoiceVolume.getNormalizeVolume(mVoiceVolume.getVoiceVolume(data)) * 2.5); } private void checkRecognizeTimeout() { new Thread(new Runnable() { @Override public void run() { int count = 0; while(count < (mRecognizerTimeout / 100)) { if (mRecognizeState == RecognizeState.STOPPED) { break; } if (mCapturedVoiceBegin && !mRecordStopped) { continue; } try { Thread.sleep(100); } catch (InterruptedException e) { mCallback.onException(e); } if (count >= (mRecognizerTimeout / 100) - 1) { if (mRecognizeState != RecognizeState.STOPPED) { cancelRecognizing(); mCallback.onRecognizeStateChange(RecognizeState.STOPPED); } } count++; } } }).start(); } private String getDateTime() { String ret = ""; Date date = new Date(); SimpleDateFormat dtFormat = new SimpleDateFormat("yyyyMMdd-HHmmss.SSS"); ret = dtFormat.format(date); return ret; } }
0
java-sources/ai/olami/olami-android-client/2.6.0/ai/olami
java-sources/ai/olami/olami-android-client/2.6.0/ai/olami/android/RecorderSpeechRecognizer.java
/* Copyright 2017, VIA Technologies, Inc. & OLAMI Team. http://olami.ai Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ai.olami.android; import android.media.AudioRecord; import android.os.Environment; import java.io.BufferedOutputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Arrays; import java.util.LinkedList; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import ai.olami.android.jni.Codec; import ai.olami.cloudService.APIConfiguration; import ai.olami.cloudService.APIResponse; import ai.olami.cloudService.CookieSet; import ai.olami.cloudService.SpeechRecognizer; import ai.olami.cloudService.SpeechResult; import ai.olami.cloudService.NLIConfig; public class RecorderSpeechRecognizer extends SpeechRecognizerBase{ private final static String TAG = "OLAMI_RSR"; private static RecorderSpeechRecognizer mRecorderSpeechRecognizer = null; private static AudioRecordManager mAudioRecordManager = null; private IRecorderSpeechRecognizerListener mListener = null; private CookieSet mCookie = null; private SpeechRecognizer mRecognizer = null; private AudioRecord mRecord = null; private NLIConfig mNLIConfig = null; private boolean mSendCallback = true; private boolean mGetting = false; private boolean mCancel = false; private boolean mIsFinal = false; private boolean mCapturedVoiceBegin = false; private boolean mSaveRecordToFile = false; private boolean mAutoStopRecordingFlag = true; private BlockingQueue mRecordDataQueue = null; private Thread mRecorderThread = null; private Thread mSenderThread = null; private Thread mGetterThread = null; private File mRecordFile = null; private OutputStream mOutputStream = null; private BufferedOutputStream mBufferedOutputStream = null; private DataOutputStream mDataOutputStream = null; private String mRecordFilePath = Environment.getExternalStorageDirectory().getPath(); private String mRecordFileName = "OLAMI-mic-record.pcm"; private VoiceVolume mVoiceVolume = new VoiceVolume(); private Codec mSpeexEncoder = null; private RecordState mRecordState = null; private RecognizeState mRecognizeState = null; /** * Recording state */ public enum RecordState { STOPPED, INITIALIZING, INITIALIZED, RECORDING, STOPPING, ERROR } /** * Recognize process state */ public enum RecognizeState { STOPPED, PROCESSING, COMPLETED, ERROR } /** * Error type */ public enum Error { UNKNOWN } private RecorderSpeechRecognizer( IRecorderSpeechRecognizerListener listener, SpeechRecognizer recognizer ) { setListener(listener); setRecognizer(recognizer); setFrameSize(mRecognizer.getAudioFrameSize()); setRecordDataSize(RECORD_FRAMES * getFrameSize()); initState(); } /** * Create a RecorderSpeechRecognizer instance. * * @param listener - The specified callback listener. * @param config - API configurations. * @return RecorderSpeechRecognizer instance. */ public static RecorderSpeechRecognizer create( IRecorderSpeechRecognizerListener listener, APIConfiguration config ) { return create(listener, new SpeechRecognizer(config)); } /** * Create a RecorderSpeechRecognizer instance by a specified speech recognizer. * * @param listener - The specified callback listener. * @param recognizer - Configured speech recognizer. * @return RecorderSpeechRecognizer instance. */ public static RecorderSpeechRecognizer create( IRecorderSpeechRecognizerListener listener, SpeechRecognizer recognizer ) { if (mRecorderSpeechRecognizer == null) { mRecorderSpeechRecognizer = new RecorderSpeechRecognizer(listener, recognizer); } else { mRecorderSpeechRecognizer.release(); mRecorderSpeechRecognizer.setListener(listener); mRecorderSpeechRecognizer.setRecognizer(recognizer); } if (mAudioRecordManager == null) { try { mAudioRecordManager = AudioRecordManager.create(); } catch (Exception ex) { ex.printStackTrace(); } } return mRecorderSpeechRecognizer; } /** * Set callback listener. * * @param listener The specified callback listener. */ public void setListener(IRecorderSpeechRecognizerListener listener) { mListener = listener; } /** * Set speech recognizer. * * @param recognizer - Configured speech recognizer. */ public void setRecognizer(SpeechRecognizer recognizer) { mRecognizer = recognizer; mRecognizer.setSdkType(SDK_TYPE); } /** * Set the identification to identify the End-user. * This is helpful in some of NLU/NLI functions, such as context support. * * @param cusId - End-user identifier. */ public void setEndUserIdentifier(String cusId) { mRecognizer.setEndUserIdentifier(cusId); } /** * Set timeout in milliseconds of each HTTP API request. * Note that each process may contain more than one request. * * @param milliseconds - Timeout in milliseconds. */ public void setApiRequestTimeout(int milliseconds) { mRecognizer.setTimeout(milliseconds); } /** * Enable or disable automatic stop voice recording. * * @param enable - Set FALSE to disable. */ public void enableAutoStopRecording(boolean enable) { mAutoStopRecordingFlag = enable; } /** * Check if automatic stop voice recording is enabled. * * @return - TRUE for enabled. */ public boolean isAutoStopRecordingEnabled() { return mAutoStopRecordingFlag; } /** * Get current recording state. * * @return - Recording state. */ public RecordState getRecordState() { return mRecordState; } /** * Get current recognize process state. * * @return - Recognize process state. */ public RecognizeState getRecognizeState() { return mRecognizeState; } /** * Enable microphone then start the voice recording and the recognize processing. * * @throws InterruptedException There is something wrong. * @throws IllegalStateException You are using this method in a wrong operation state. */ public void start() throws InterruptedException, IllegalStateException { start(null); } /** * Enable microphone then start the voice recording and the recognize processing. * * @param nliConfig - NLIConfig object. * * @throws InterruptedException There is something wrong. * @throws IllegalStateException You are using this method in a wrong operation state. */ public void start(NLIConfig nliConfig) throws InterruptedException, IllegalStateException { if (mRecordState != RecordState.STOPPED) { throw new IllegalStateException("The state of recording is not STOPPED."); } changeRecordState(RecordState.INITIALIZING); int wait = 0; while ((mRecognizeState != RecognizeState.STOPPED) && (mRecordDataQueue != null)) { if (wait >= 10) { changeRecordState(RecordState.ERROR); throw new InterruptedException("Threads handling state not correct."); } Thread.sleep(500); wait++; } mSendCallback = true; mCancel = false; mGetting = false; mIsFinal = false; mCapturedVoiceBegin = false; mCookie = new CookieSet(); mNLIConfig = nliConfig; mRecordDataQueue = new LinkedBlockingQueue(); if (mRecord == null) { try { mRecord = mAudioRecordManager.getAudioRecord(); } catch (Exception e) { changeRecordState(RecordState.ERROR); mListener.onException(e); } } changeRecordState(RecordState.INITIALIZED); // Init Recorder Thread mRecorderThread = new Thread(new Runnable() { @Override public void run() { try { doRecording(); } catch (Exception e) { changeRecordState(RecordState.ERROR); mListener.onException(e); } } }); mRecorderThread.start(); // Init Sender Thread mSenderThread = new Thread(new Runnable() { @Override public void run() { try { doSending(); } catch (Exception e) { changeRecognizeState(RecognizeState.ERROR); mListener.onException(e); } } }); mSenderThread.start(); // Init Getter Thread mGetterThread = new Thread(new Runnable() { @Override public void run() { try { doGetting(); } catch (Exception e) { changeRecognizeState(RecognizeState.ERROR); mListener.onException(e); } } }); mGetterThread.start(); } /** * Stop the voice recorder and wait for the final recognition result. */ public void stop() { changeRecordState(RecordState.STOPPING); } /** * Cancel all processes and give up to get recognition result. */ public void cancel() { stop(); mCancel = true; } /** * Stop or cancel all processes and then stopRecordingAndReleaseResources resources. * This will not make any callback even if you use him to terminate any process. */ public void release() { // Disable callback mSendCallback = false; // Force to cancel all processes. cancel(); // Force to change state for re-init. initState(); } private void initState() { changeRecordState(RecordState.STOPPED); changeRecognizeState(RecognizeState.STOPPED); } private void stopAndReleaseAudioRecord() { mAudioRecordManager.stopAndRelease(); mRecord = null; } /** * Enable/Disable to save the recorded audio to file. * * @param saveToFile - Set TRUE to enable, set FALSE to disable. * @param fileName - Name of the file you want to store the audio. */ public void enableSaveRecordToFile(boolean saveToFile, String fileName) { mSaveRecordToFile = saveToFile; mRecordFileName = fileName; } private void doRecording() throws Exception { mAudioRecordManager.startRecording(); mRecord = mAudioRecordManager.getAudioRecord(); changeRecordState(RecordState.RECORDING); short[] audioData441 = new short[441 * RECORD_FRAMES]; byte[] audioData = null; LinkedList<byte[]> tempInputs = new LinkedList<byte[]>(); int reservedBlocks = (RESERVED_INPUT_LENGTH_MILLISECONDS / (RECORD_FRAMES * FRAME_LENGTH_MILLISECONDS)); int instantNoiseBlocks = (INSTANT_NOISE_LENGTH_MILLISECONDS / (RECORD_FRAMES * FRAME_LENGTH_MILLISECONDS)); int vadTailBlocks = (getVADEndMilliseconds() / (RECORD_FRAMES * FRAME_LENGTH_MILLISECONDS)); int inputVolume = 0; int priInputVolume = 0; int silence = 0; int instantNoise = 0; while (mRecordState == RecordState.RECORDING) { synchronized (mRecordDataQueue) { if (mRecord.read(audioData441, 0, audioData441.length) == audioData441.length) { audioData = new byte[getRecordDataSize()]; AudioRecordManager.convert441To16(audioData441, audioData); saveRecordToFile(audioData, false); inputVolume = getMicInputVolume(audioData); mListener.onRecordVolumeChange(inputVolume); if (!mCapturedVoiceBegin) { if (inputVolume == 0) { // Speech may not have started. Buffering silence audio as the head. tempInputs.add(audioData); if (tempInputs.size() > reservedBlocks) { tempInputs.removeFirst(); } } else { mCapturedVoiceBegin = true; changeRecognizeState(RecognizeState.PROCESSING); // Insert buffered silence audio into the beginning of the real speech input. while (!tempInputs.isEmpty()) { mRecordDataQueue.put(tempInputs.poll()); } // Then append the real speech data mRecordDataQueue.put(audioData); } } else { mRecordDataQueue.put(audioData); if (inputVolume > getSilenceLevel()) { if (silence == 0) { instantNoise = 0; } if (silence > 0) { if (instantNoise == 0) { instantNoise++; } else { if ((instantNoise < instantNoiseBlocks) && (priInputVolume > inputVolume)) { instantNoise++; } else { silence = 0; } } } } else { silence++; } if (silence > vadTailBlocks) { if (mAutoStopRecordingFlag) { stop(); break; } } } priInputVolume = inputVolume; } } } stopAndReleaseAudioRecord(); saveRecordToFile(new byte[]{0}, true); } private void doSending() throws Exception { int length = 0; mRecognizer.setAudioType(SpeechRecognizer.AUDIO_TYPE_PCM_RAW); mRecognizer.releaseAppendedAudio(); while (!mCancel) { if (!mRecordDataQueue.isEmpty()) { byte[] audioData = (byte[]) mRecordDataQueue.take(); mIsFinal = (isRecodingStopped() && (mRecordDataQueue.isEmpty())); length += ((audioData.length / getFrameSize()) * FRAME_LENGTH_MILLISECONDS); if (getAudioCompressLibraryType() == AUDIO_COMPRESS_LIBRARY_TYPE_CPP) { if (mSpeexEncoder == null) { mSpeexEncoder = new Codec(); mSpeexEncoder.open(1, 10); } byte[] encBuffer = new byte[audioData.length]; int encSize = mSpeexEncoder.encodeByte(audioData, 0, audioData.length, encBuffer); mRecognizer.setAudioType(SpeechRecognizer.AUDIO_TYPE_PCM_SPEEX); mRecognizer.appendSpeexAudioFramesData(encBuffer, encSize); } else { mRecognizer.setAudioType(SpeechRecognizer.AUDIO_TYPE_PCM_RAW); mRecognizer.appendAudioFramesData(audioData); } if ((length >= getUploadAudioLengthMilliseconds()) || mIsFinal) { APIResponse response = mRecognizer.flushToUploadAudio(mCookie, mIsFinal); if (response.ok()) { mGetting = true; length = 0; } else { mRecognizer.releaseAppendedAudio(); recognizeResponseError(response); } } } else { // Recorder stopped and the last audio sent at the same time, but mIsFinal = false. if (isRecodingStopped()) { mIsFinal = true; byte[] audioData = new byte[getRecordDataSize()]; Arrays.fill(audioData, (byte) 0); APIResponse response = mRecognizer.uploadAudio(mCookie, audioData, mIsFinal); if (response.ok()) { mGetting = true; } else { mRecognizer.releaseAppendedAudio(); recognizeResponseError(response); } } } if (mIsFinal) { break; } } if (mSpeexEncoder != null) { mSpeexEncoder.close(); mSpeexEncoder = null; } synchronized (mRecordDataQueue) { mRecordDataQueue.clear(); mRecordDataQueue = null; } } private void doGetting() throws Exception { while (!mCancel) { if (mGetting) { Thread.sleep(getFrequencyToGettingResult()); APIResponse response = null; switch (getRecognizeResultType()) { case RECOGNIZE_RESULT_TYPE_ALL: response = mRecognizer.requestRecognitionWithAll(mCookie, mNLIConfig); break; case RECOGNIZE_RESULT_TYPE_STT: response = mRecognizer.requestRecognition(mCookie); break; case RECOGNIZE_RESULT_TYPE_NLI: response = mRecognizer.requestRecognitionWithNLI(mCookie, mNLIConfig); break; } if (response.ok() && response.hasData()) { SpeechResult sttResult = response.getData().getSpeechResult(); if (mSendCallback) { mListener.onRecognizeResultChange(response); } if (sttResult.complete()) { changeRecognizeState(RecognizeState.COMPLETED); break; } } else { recognizeResponseError(response); } } } changeRecognizeState(RecognizeState.STOPPED); } private void changeRecordState(RecordState state) { mRecordState = state; if (mSendCallback || (state == RecordState.ERROR)) { mListener.onRecordStateChange(mRecordState); } if (mRecordState == RecordState.ERROR) { cancel(); } } private void changeRecognizeState(RecognizeState state) { mRecognizeState = state; if (mSendCallback || (state == RecognizeState.ERROR)) { mListener.onRecognizeStateChange(mRecognizeState); } if (mRecognizeState == RecognizeState.STOPPED) { changeRecordState(RecordState.STOPPED); } else if (mRecognizeState == RecognizeState.ERROR) { cancel(); changeRecognizeState(RecognizeState.STOPPED); } } private void recognizeResponseError(APIResponse response) { mListener.onServerError(response); changeRecognizeState(RecognizeState.ERROR); } private boolean isRecodingStopped() { if (mRecordState == RecordState.STOPPING) { // AudioRecord has been released, it means recorder thread is stopped. if (mRecord == null) { return true; } else { // Check AudioRecord state if recorder thread is still running. if (mRecord.getState() != AudioRecord.RECORDSTATE_RECORDING) { return true; } } } else if (mRecordState == RecordState.STOPPED) { return true; } return false; } private void saveRecordToFile(byte[] buff, boolean isFinal) throws IOException { if (!mSaveRecordToFile) return; if (mRecordFile == null) { mRecordFile = new File(mRecordFilePath, mRecordFileName); mRecordFile.createNewFile(); mOutputStream = new FileOutputStream(mRecordFile); mBufferedOutputStream = new BufferedOutputStream(mOutputStream); mDataOutputStream = new DataOutputStream(mBufferedOutputStream); } mDataOutputStream.write(buff); if (isFinal) { mDataOutputStream.close(); mRecordFile = null; } } private int getMicInputVolume(byte[] data) { return (int) (mVoiceVolume.getNormalizeVolume(mVoiceVolume.getVoiceVolume(data)) * 2.5); } }
0
java-sources/ai/olami/olami-android-client/2.6.0/ai/olami
java-sources/ai/olami/olami-android-client/2.6.0/ai/olami/android/SpeechRecognizerBase.java
/* Copyright 2017, VIA Technologies, Inc. & OLAMI Team. http://olami.ai Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ai.olami.android; import ai.olami.cloudService.SpeechRecognizer; public class SpeechRecognizerBase { public static final int RECOGNIZE_RESULT_TYPE_STT = 0; public static final int RECOGNIZE_RESULT_TYPE_ALL = 1; public static final int RECOGNIZE_RESULT_TYPE_NLI = 2; public static final int AUDIO_COMPRESS_LIBRARY_TYPE_JAVA = 1; public static final int AUDIO_COMPRESS_LIBRARY_TYPE_CPP = 2; protected static final String SDK_TYPE = "android"; protected static final int RECORD_FRAMES = 6; protected final int FRAME_LENGTH_MILLISECONDS = SpeechRecognizer.AUDIO_LENGTH_MILLISECONDS_PER_FRAME; protected final int RESERVED_INPUT_LENGTH_MILLISECONDS = 1000; protected final int INSTANT_NOISE_LENGTH_MILLISECONDS = 1000; protected final int VAD_TAIL_SILENCE_LEVEL = 5; private int mRecognizeResultType = RECOGNIZE_RESULT_TYPE_STT; private int mAudioCompressLibraryType = AUDIO_COMPRESS_LIBRARY_TYPE_CPP; private int mFrameSize = 320; private int mRecordDataSize = RECORD_FRAMES * mFrameSize; private int mMinUploadAudioLengthMilliseconds = RECORD_FRAMES * FRAME_LENGTH_MILLISECONDS; private int mUploadAudioLengthMilliseconds = 300; private int mMinFrequencyToGettingResult = 100; private int mFrequencyToGettingResult = 100; private int mVADEndMilliseconds = 2000; private int mSilenceLevel = VAD_TAIL_SILENCE_LEVEL; public int getAudioCompressLibraryType() { return mAudioCompressLibraryType; } protected int getRecognizeResultType() { return mRecognizeResultType; } protected int getSilenceLevel() { return mSilenceLevel; } protected void setSilenceLevel(int level) { mSilenceLevel = level; } protected int getFrameSize() { return mFrameSize; } protected void setFrameSize(int size) { mFrameSize = size; } protected int getRecordDataSize() { return mRecordDataSize; } protected void setRecordDataSize(int size) { mRecordDataSize = size; } protected int getMinUploadAudioLengthMilliseconds() { return mMinUploadAudioLengthMilliseconds; } protected void setMinUploadAudioLengthMilliseconds(int milliseconds) { mMinUploadAudioLengthMilliseconds = milliseconds; } protected int getUploadAudioLengthMilliseconds() { return mUploadAudioLengthMilliseconds; } protected void setUploadAudioLengthMilliseconds(int milliseconds) { mUploadAudioLengthMilliseconds = milliseconds; } protected int getMinFrequencyToGettingResult() { return mMinFrequencyToGettingResult; } protected void setMinFrequencyToGettingResult(int frequency) { mMinFrequencyToGettingResult = frequency; } protected int getFrequencyToGettingResult() { return mFrequencyToGettingResult; } protected void setFrequencyToGettingResult(int frequency) { mFrequencyToGettingResult = frequency; } protected int getVADEndMilliseconds() { return mVADEndMilliseconds; } protected void setVADEndMilliseconds (int milliseconds) { mVADEndMilliseconds = milliseconds; } /** * Set audio length in milliseconds to upload, * then the recognizer client will upload parts of audio once every milliseconds you set. * * @param milliseconds - How long of the audio in milliseconds do you want to upload once. */ public void setSpeechUploadLength(int milliseconds) { if (getUploadAudioLengthMilliseconds() < getMinUploadAudioLengthMilliseconds()) { throw new IllegalArgumentException("The length in milliseconds cannot be less than " + getMinUploadAudioLengthMilliseconds()); } setUploadAudioLengthMilliseconds(milliseconds); } /** * Set the frequency in milliseconds of the recognition result query, * then the recognizer client will query the result once every milliseconds you set. * * @param milliseconds - How long in milliseconds do you want to query once. */ public void setResultQueryFrequency(int milliseconds) { if (getFrequencyToGettingResult() < getMinFrequencyToGettingResult()) { throw new IllegalArgumentException("The frequency in milliseconds cannot be less than " + getMinFrequencyToGettingResult()); } setFrequencyToGettingResult(milliseconds); } /** * Set length of end time of the VAD in milliseconds to stop voice recording automatically. * * @param milliseconds - length of end time in milliseconds for the speech input idle. */ public void setLengthOfVADEnd(int milliseconds) { setVADEndMilliseconds(milliseconds); } /** * Set level of silence volume of the VAD to stop voice recording automatically. * * @param level - level for the silence volume. */ public void setSilenceLevelOfVADTail(int level) { if (level < 0) { throw new IllegalArgumentException("The level cannot be less than 0"); } setSilenceLevel(level); } /** * Set type of the recognition results of the query. * * @param type - Type of the recognition results: * RECOGNIZE_RESULT_TYPE_STT to get result of Speech-To-Text. * RECOGNIZE_RESULT_TYPE_ALL to get results of the all types. * RECOGNIZE_RESULT_TYPE_NLI to get results of Speech-To-Text and NLI. */ public void setRecognizeResultType(int type) { if ((type >= 0) && (type <= 2)) { mRecognizeResultType = type; } else { throw new IllegalArgumentException("Illegal Argument [type]: " + type); } } /** * Set type of the audio compression library. * * @param type - Type of the recognition results: * RECOGNIZE_RESULT_TYPE_STT to get result of Speech-To-Text. * RECOGNIZE_RESULT_TYPE_ALL to get results of the all types. * RECOGNIZE_RESULT_TYPE_NLI to get results of Speech-To-Text and NLI. */ public void setAudioCompressLibraryType(int type) { switch (type) { case AUDIO_COMPRESS_LIBRARY_TYPE_JAVA: break; case AUDIO_COMPRESS_LIBRARY_TYPE_CPP: break; default: throw new IllegalArgumentException("Illegal library type code."); } mAudioCompressLibraryType = type; } }
0
java-sources/ai/olami/olami-android-client/2.6.0/ai/olami
java-sources/ai/olami/olami-android-client/2.6.0/ai/olami/android/VoiceVolume.java
/* Copyright 2017, VIA Technologies, Inc. & OLAMI Team. http://olami.ai Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ai.olami.android; import java.nio.ByteBuffer; import java.nio.ByteOrder; public class VoiceVolume { public static final int VOLUME_LEVEL = 12; /** * Get audio volume from audio buffer. * * @param data - Audio buffer. * @return Volume. */ public int getVoiceVolume(byte[] data){ ByteBuffer byteBuffer = ByteBuffer.wrap(data); byteBuffer.order(ByteOrder.LITTLE_ENDIAN); int v = 0; for (int i = 0 ; i < data.length ; i+=2) { if (byteBuffer.getShort(i) > v) { v = Math.abs(byteBuffer.getShort(i)); } } return v; } /** * Get normalize audio volume level. * * @param volume - Volume. * @return Volume level. */ public int getNormalizeVolume(int volume) { int nowVolumeMax = 10000; final int MIN_VOLUME = 1; final int MAX_VOLUME = 32767; if (volume > nowVolumeMax) { nowVolumeMax = (int) (volume * 1.5); } if (nowVolumeMax > MAX_VOLUME) { nowVolumeMax = MAX_VOLUME; } int v = volume - MIN_VOLUME; if(v < 0){ v = 0; } else if (v > (nowVolumeMax - MIN_VOLUME)) { v = (nowVolumeMax - MIN_VOLUME); } int normalizeVolume = (int) ((v / (float) (nowVolumeMax - MIN_VOLUME + 1)) * (VOLUME_LEVEL + 1)); return normalizeVolume; } }
0
java-sources/ai/olami/olami-android-client/2.6.0/ai/olami/android
java-sources/ai/olami/olami-android-client/2.6.0/ai/olami/android/jni/Codec.java
/* Copyright 2018, VIA Technologies, Inc. & OLAMI Team. http://olami.ai Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ai.olami.android.jni; public class Codec { static { try { System.loadLibrary("speexjni"); } catch (UnsatisfiedLinkError e) { e.printStackTrace(); } } private static void convertByte2Short( byte[] byData, int offset1, short[] sData, int offset2, int sizeFloat ) { if(byData.length - offset1 < 2 * sizeFloat) { throw new IllegalArgumentException("Insufficient Samples to convert to floats"); } else if(sData.length - offset2 < sizeFloat) { throw new IllegalArgumentException("Insufficient float buffer to convert the samples"); } else { for(int i = 0; i < sizeFloat; ++i) { sData[offset2 + i] = (short)(byData[offset1 + 2 * i] & 255 | byData[offset1 + 2 * i + 1] << 8); } } } public int encodeByte( byte lin[], int offset, int size, byte encoded[] ) { short[] sData = new short[size / 2]; convertByte2Short(lin, offset, sData, 0, size / 2); return encode(sData, 0, size / 2, encoded); } public native int open(int mode, int quality); public native int getFrameSize(); public native int decode(byte encoded[], short lin[], int size); public native int encode(short lin[], int offset, int size, byte encoded[]); public native void close(); }
0
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami/cloudService/APIConfiguration.java
/* Copyright 2017, VIA Technologies, Inc. & OLAMI Team. http://olami.ai Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ai.olami.cloudService; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.HashMap; import java.util.Map; public class APIConfiguration { public static final int LOCALIZE_OPTION_SIMPLIFIED_CHINESE = 0; public static final int LOCALIZE_OPTION_TRADITIONAL_CHINESE = 1; public static final String API_NAME_SEG = "seg"; public static final String API_NAME_NLI = "nli"; public static final String API_NAME_ASR = "asr"; protected static final String API_DOMAIN_NAME_CN = "https://cn.olami.ai"; protected static final String API_DOMAIN_NAME_TW = "https://tw.olami.ai"; protected static final String API_BASE_URL = "/cloudservice/api"; private String mAppKey = null; private String mAppSecret = null; private String mApiDomainName = null; private String mSdkType = null; private int mLocalizeOption = -1; private Map<String, String> mSignatureMap; private Map<String, Long> mTimestampMap; private static final long TIMESTAMP_RANGE = (59 * 60 * 1000); /** * Configure to issue OLAMI HTTP API requests. * * @param appKey - The 'APP KEY' you have, provided by OLAMI developer service. * @param appSecret - The 'APP SECRET' you have, provided by OLAMI developer service. * @param localizeOption - Select the location and language of the OLAMI service you want to use * (0 for Simplified Chinese in China, 1 for Traditional Chinese in Taiwan) */ public APIConfiguration( final String appKey, final String appSecret, final int localizeOption ) { if (appKey == null) { throw new IllegalArgumentException("appKey is required!"); } if (appSecret == null) { throw new IllegalArgumentException("appSecret is required!"); } initLocalization(localizeOption); mSdkType = "java"; mAppKey = appKey; mAppSecret = appSecret; mTimestampMap = new HashMap<String, Long>(); mSignatureMap = new HashMap<String, String>(); } /** * @param type - SDK type. */ public void setSdkType(String type) { mSdkType = type.toLowerCase(); } /** * Not recommended for use. * Normally this is for commercial use, so you probably don't need to use this method. * * @param domain - API server domain name */ public void setApiServerDomain(String domain) { mApiDomainName = domain; } /** * @return The given SDK type string. */ public String getSdkType() { return mSdkType; } /** * @return The given 'APP KEY'. */ public String getAppKey() { return mAppKey; } /** * @return The given 'APP SECRET'. */ public String getAppSecret() { return mAppSecret; } /** * @return The localize option you selected. */ public int getLocalizeOption() { return mLocalizeOption; } /** * Get the generated timestamp value by the given API name. * * @param apiName - API name. * @return Timestamp in milliseconds. */ public long getTimestamp(final String apiName) { return mTimestampMap.get(apiName); } /** * Get the signature by the given API name and the generated timestamp. * * @param apiName - API name. * @return MD5 signature. */ public String getSignature(final String apiName) { return mSignatureMap.get(apiName); } /** * Get the base API end point URL for the given API name. * * @param apiName - API name. * @return URL of the specified API. * @throws NoSuchAlgorithmException Filed to create signature. */ public String getBaseRequestURL(final String apiName) throws NoSuchAlgorithmException { return getBaseRequestURL(apiName, null); } /** * Get the base API end point URL for the given API name. * * @param apiName - API name. * @param queryParams - Query parameters by name-value collection. * @return URL of the specified API. * @throws NoSuchAlgorithmException Filed to create signature. */ public String getBaseRequestURL( final String apiName, final Map<String, String> queryParams ) throws NoSuchAlgorithmException { generateSignature(apiName); StringBuffer urlStringBuffer = new StringBuffer(); urlStringBuffer.append(mApiDomainName); urlStringBuffer.append(API_BASE_URL); urlStringBuffer.append("?_from="); urlStringBuffer.append(mSdkType); urlStringBuffer.append("&appkey="); urlStringBuffer.append(mAppKey); urlStringBuffer.append("&api="); urlStringBuffer.append(apiName); urlStringBuffer.append("&timestamp="); urlStringBuffer.append(getTimestamp(apiName)); urlStringBuffer.append("&sign="); urlStringBuffer.append(getSignature(apiName)); if (queryParams != null) { for (Object key : queryParams.keySet()) { urlStringBuffer.append("&"); urlStringBuffer.append(key.toString()); urlStringBuffer.append("="); urlStringBuffer.append(queryParams.get(key)); } } return urlStringBuffer.toString(); } protected void generateSignature(final String apiName) throws NoSuchAlgorithmException { long current = System.currentTimeMillis(); long expired = 0; if (!mTimestampMap.containsKey(apiName)) { mTimestampMap.put(apiName, current); } // Check the timestamp valid period. expired = mTimestampMap.get(apiName) + TIMESTAMP_RANGE; if ((current > expired) || (!mSignatureMap.containsKey(apiName))) { // Reset timestamp and signature when the old one has expired. mTimestampMap.put(apiName, current); // Prepare signature message. StringBuffer signStringBuffer = new StringBuffer(); signStringBuffer.append(mAppSecret); signStringBuffer.append("api="); signStringBuffer.append(apiName); signStringBuffer.append("appkey="); signStringBuffer.append(mAppKey); signStringBuffer.append("timestamp="); signStringBuffer.append(mTimestampMap.get(apiName)); signStringBuffer.append(mAppSecret); MessageDigest md = MessageDigest.getInstance("MD5"); md.update(signStringBuffer.toString().getBytes()); StringBuffer signature = new StringBuffer(); signature.append(new BigInteger(1, md.digest()).toString(16)); if (signature.toString().length() < 32) { signature.insert(0, "0"); } mSignatureMap.put(apiName, signature.toString()); } } protected void initLocalization(final int localizeOption) { switch (localizeOption) { case LOCALIZE_OPTION_SIMPLIFIED_CHINESE: mApiDomainName = API_DOMAIN_NAME_CN; break; case LOCALIZE_OPTION_TRADITIONAL_CHINESE: mApiDomainName = API_DOMAIN_NAME_TW; break; default: throw new IllegalArgumentException("Illegal localizeation option."); } mLocalizeOption = localizeOption; } }
0
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami/cloudService/APIRequestBase.java
/* Copyright 2017, VIA Technologies, Inc. & OLAMI Team. http://olami.ai Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ai.olami.cloudService; import java.util.UUID; public abstract class APIRequestBase { private APIConfiguration mConfiguration = null; private String mCusId = "Undefined"; private int mConnectionTimeoutMilliseconds = 5000; /** * A base class to issue OLAMI HTTP API requests. * * @param configuration - API configurations. */ public APIRequestBase(APIConfiguration configuration) { mConfiguration = configuration; mCusId = UUID.randomUUID().toString(); } /** * @param configuration - API configurations. */ public void setConfiguration(APIConfiguration configuration) { mConfiguration = configuration; } /** * @return The given API configurations */ public APIConfiguration getConfiguration() { return mConfiguration; } /** * @param type - SDK type. */ public void setSdkType(String type) { if (mConfiguration != null) { mConfiguration.setSdkType(type); } } /** * @return The given SDK type string. */ public String getSdkType() { if (mConfiguration != null) { return mConfiguration.getSdkType(); } return ""; } /** * Set the identification to identify the End-user. * This is helpful in some of NLU/NLI functions, such as context support. * * @param cusId - End-user identifier. */ public void setEndUserIdentifier(final String cusId) { mCusId = cusId; } /** * @return The given End-user identifier. */ public String getEndUserIdentifier() { return mCusId; } /** * Get the timeout setting of the HTTP API request. * * @return milliseconds. */ public int getTimeout() { return mConnectionTimeoutMilliseconds; } /** * Set timeout in milliseconds to the HTTP API request. * * @param milliseconds - Timeout in milliseconds. */ public void setTimeout(int milliseconds) { mConnectionTimeoutMilliseconds = milliseconds; } }
0
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami/cloudService/APIResponse.java
/* Copyright 2017, VIA Technologies, Inc. & OLAMI Team. http://olami.ai Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ai.olami.cloudService; import ai.olami.util.GsonFactory; import com.google.gson.Gson; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class APIResponse { public static final String STATUS_OK = "ok"; public static final String STATUS_ERROR = "error"; public static final int ERROR_CODE_INVALID_CONTENT = -1000000; @Expose(serialize = false, deserialize = false) @SerializedName("original_json_string_for_debug") private String mSourceJsonString = null; @Expose(serialize = false, deserialize = false) private Gson mGson = GsonFactory.getNormalGson(); @Expose @SerializedName("status") private String mStatus = STATUS_OK; @Expose @SerializedName("code") private int mCode; @Expose @SerializedName("msg") private String mMessage; @Expose @SerializedName("data") private APIResponseData mResponseData = null; @Override public String toString() { if (mSourceJsonString == null) { return mGson.toJson(this); } else { return mSourceJsonString; } } /** * Set the original JSON string. * This is helpful for debugging or to get other undefined members of this JSON string. * Use toString() method to get the original JSON string. * * @param jsonString - The original JSON string. */ public void setJsonStringSource(String jsonString) { mSourceJsonString = jsonString; } /** * Set as a invalid response. * * @param message - Error message to explain why this is an invalid result. */ public void setInvalid(String message) { setError(ERROR_CODE_INVALID_CONTENT, message); } /** * Set as a error response. * * @param errorCode - The error code. * @param errorMessage - Error message. */ public void setError(int errorCode, String errorMessage) { setStatus(STATUS_ERROR); setErrorCode(errorCode); setErrorMessage(errorMessage); } /** * Check whether the response status is OK (= STATUS_OK) or not. * * @return TRUE if the response status is OK. */ public boolean ok() { return getStatus().equals(STATUS_OK); } /** * Check whether the response status is OK (= STATUS_OK) or not. * * @return TRUE if something wrong, or FALSE if the response status is OK. */ public boolean hasError() { return (!ok()); } /** * @return Status */ public String getStatus() { return mStatus; } /** * Set status value. * * @param status - Status value string. */ public void setStatus(String status) { mStatus = status; } /** * @return Error code. */ public int getErrorCode() { return mCode; } /** * Set error code. * * @param errorEode - Error code. */ public void setErrorCode(int errorEode) { mCode = errorEode; } /** * @return Error message. */ public String getErrorMessage() { return mMessage; } /** * Set error message. * * @param errorMessage - Error message. */ public void setErrorMessage(String errorMessage) { mMessage = errorMessage; } /** * Get the response data. * Map to the member "data" of the JSON string. * * @return The response data object. */ public APIResponseData getData() { return mResponseData; } /** * @return TRUE if contains Data information. */ public boolean hasData() { return (mResponseData != null); } }
0
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami/cloudService/APIResponseBuilder.java
/* Copyright 2017, VIA Technologies, Inc. & OLAMI Team. http://olami.ai Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ai.olami.cloudService; import ai.olami.util.GsonFactory; public class APIResponseBuilder { /** * Create API response instance by the specified response JSON string. * * @param jsonString - API Response JSON string. * @return The instance mapped to the specified response JSON string. */ public static APIResponse create(String jsonString) { APIResponse response = null; try { response = (APIResponse) GsonFactory.getNormalGson().fromJson(jsonString, APIResponse.class); response.setJsonStringSource(jsonString); } catch (Exception e) { response.setInvalid("Invalid Response Content --> \n" + jsonString + "\n\n" + e.getMessage()); e.printStackTrace(); } return response; } }
0
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami/cloudService/APIResponseData.java
/* Copyright 2017, VIA Technologies, Inc. & OLAMI Team. http://olami.ai Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ai.olami.cloudService; import ai.olami.nli.NLIResult; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class APIResponseData { @Expose @SerializedName("seg") private String mSegResult = null; @Expose @SerializedName("nli") private NLIResult[] mNLIResults = null; @Expose @SerializedName("asr") private SpeechResult mSpeechResult = null; /** * Get word segments from the word segmentation analyzer. * * @return Word segments array. */ public String[] getWordSegmentation() { return mSegResult.split("\\s+"); } /** * @return TRUE if contains word segmentation information. */ public boolean hasWordSegmentation() { return (mSegResult != null); } /** * Get word segmentation results from the Natural Language Understanding API. * * @return Word segments string, separated by empty space. */ public String getWordSegmentationSingleString() { return mSegResult; } /** * Get NLI result from the Natural Language Understanding API. * * @return NLI result containers array. */ public NLIResult[] getNLIResults() { return mNLIResults; } /** * @return TRUE if contains NLIResult information. */ public boolean hasNLIResults() { return (mNLIResults != null); } /** * Get the Speech-To-Text results from the Cloud Speech Recognition API. * * @return Speech-To-Text container. */ public SpeechResult getSpeechResult() { return mSpeechResult; } /** * @return TRUE if contains SpeechResult information. */ public boolean hasSpeechResult() { return (mSpeechResult != null); } }
0
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami/cloudService/CookieSet.java
/* Copyright 2017, VIA Technologies, Inc. & OLAMI Team. http://olami.ai Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ai.olami.cloudService; import java.util.ArrayList; import java.util.List; import java.util.UUID; public class CookieSet { private String mUniqueId = UUID.randomUUID().toString(); private List<String> mMainCookies = null; /** * List of cookies. */ public CookieSet() { mMainCookies = new ArrayList<String>(); } /** * Get unique ID. * * @return The unique ID of this CookieSet. */ public String getUniqueID() { return mUniqueId; } /** * Set cookies * * @param contents - Cookies. */ public void setContents(List<String> contents) { mMainCookies = contents; } /** * Get cookies * * @return Cookies. */ public List<String> getContents() { return mMainCookies; } }
0
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami/cloudService/NLIConfig.java
/* Copyright 2017, VIA Technologies, Inc. & OLAMI Team. http://olami.ai Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ai.olami.cloudService; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import ai.olami.util.GsonFactory; public class NLIConfig { @Expose(serialize = false, deserialize = false) private Gson mGson = GsonFactory.getNormalGson(); // Members ------------------------------------------------------------------------------------------ @Expose @SerializedName("slotname") private String mSlotName = null; /** * Set slot name. */ public void setSlotName(String name) { mSlotName = name; } /** * @return Slot Name. */ public String getSlotName() { return mSlotName; } /** * @return TRUE if contains slot name. */ public boolean hasSlotName() { return ((mSlotName != null) && (!mSlotName.equals(""))); } // Common Methods ------------------------------------------------------------------------------------ /** * Reset all members. */ public void reset() { mSlotName = null; } /** * @return GSON Json Element. */ public JsonElement toJsonElement() { return mGson.fromJson(toString(), JsonElement.class); } @Override public String toString() { return mGson.toJson(this); } }
0
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami/cloudService/SpeechRecognizer.java
/* Copyright 2017, VIA Technologies, Inc. & OLAMI Team. http://olami.ai Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ai.olami.cloudService; import ai.olami.util.GsonFactory; import ai.olami.util.HttpClient; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import org.xiph.speex.SpeexEncoder; import com.google.gson.Gson; import com.google.gson.JsonObject; public class SpeechRecognizer extends APIRequestBase { public static final int AUDIO_TYPE_PCM_RAW = 0; public static final int AUDIO_TYPE_PCM_WAVE = 1; public static final int AUDIO_TYPE_PCM_SPEEX = 2; public static final int AUDIO_LENGTH_MILLISECONDS_PER_FRAME = 10; public static final int AUDIO_SAMPLE_RATE = 16000; public static final int AUDIO_BITS_PER_SAMPLE = 16; public static final int AUDIO_CHANNELS = 1; private static final String SEQ_TYPE_SEG = "seg"; private static final String SEQ_TYPE_NLI = "nli"; private static final String SEQ_TYPE_ALL = "nli,seg"; private static final int WAVE_HEADER_SIZE = 44; private static final int AUDIO_FRAME_SIZE = (int) ( ( AUDIO_SAMPLE_RATE * AUDIO_BITS_PER_SAMPLE * AUDIO_CHANNELS * ((float) AUDIO_LENGTH_MILLISECONDS_PER_FRAME / 1000) ) / 8 ); private static final String EXMSG_AUDIO_TYPE_NOT_SET = "Audio type has not been set! You must to specify the audio type by setAudioType(int audioType) before doing this."; private static final String EXMSG_INVALID_AUDIO_TYPE = "Invalid audio type!"; private static final String EXMSG_MUST_BE_SPECIFIED_METHOD = "Not support this audio type!"; private String mApiName = APIConfiguration.API_NAME_ASR; private String mDefaultSeqType = SEQ_TYPE_SEG; private int mAudioType = -1; private boolean mEncodeToSpeex = true; private SpeexEncoder mSpeexEncoder = null; private int mSpeexProcessFrames = 2; private int mSpeexProcessSize = 0; private int mAudioBufferListMaxSize = 0; private int mAudioBufferListMinSize = 0; private int mAudioBufferListCurrentSize = 0; private int mAudioBufferListAppendedSize = 0; private LinkedList<byte[]> mAudioBufferList = new LinkedList<byte[]>(); private Gson mGson = GsonFactory.getNormalGson(); /** * Speech Recognizer to issue Cloud Speech Recognition API requests. * * @param configuration - API configurations. */ public SpeechRecognizer(APIConfiguration configuration) { super(configuration); if (mEncodeToSpeex) { initSpeexEncoder(); } mAudioBufferListMinSize = mSpeexProcessFrames * getAudioFrameSize(); mAudioBufferListMaxSize = ( (30 * 1000) / AUDIO_LENGTH_MILLISECONDS_PER_FRAME ) * getAudioFrameSize(); } /** * Get audio frame size used by the speech recognizer. * * @return Frame size in bytes. */ public int getAudioFrameSize() { if (mEncodeToSpeex && (mSpeexEncoder != null)) { return mSpeexEncoder.getFrameSize(); } return AUDIO_FRAME_SIZE; } /** * Request to upload the specified audio for speech recognition. * You must to specify the audio type by setAudioType(int audioType) before using this method. * * @param identifier - Identifier CookieSet. * @param filePath - The path of the audio file. * Wave Header is required if it is a Wave audio. * @param isFinalAudio - TRUE if this is the last audio of a speech input. * @return API response with the audio uploading status. * @throws IOException File handling or HTTP connection failed, or other exceptions. * @throws NoSuchAlgorithmException Failed to create signature. */ public APIResponse uploadAudio( CookieSet identifier, String filePath, boolean isFinalAudio ) throws IOException, NoSuchAlgorithmException { if (mAudioType == -1) { throw new UnsupportedOperationException(EXMSG_AUDIO_TYPE_NOT_SET); } return uploadAudio(identifier, filePath, mAudioType, isFinalAudio); } /** * Request to upload the specified audio for speech recognition. * * @param identifier - Identifier CookieSet. * @param filePath - The path of the audio file. * Wave Header is required if it is a Wave audio. * @param audioType - Audio type: * AUDIO_TYPE_PCM_RAW for PCM raw data. * AUDIO_TYPE_PCM_WAVE for Wave audio. * AUDIO_TYPE_PCM_SPEEX for PCM Speex audio. * @param isFinalAudio - TRUE if this is the last audio of a speech input. * @return API response with the audio uploading status. * @throws IOException File handling or HTTP connection failed, or other exceptions. * @throws NoSuchAlgorithmException Failed to create signature. */ public APIResponse uploadAudio( CookieSet identifier, String filePath, int audioType, boolean isFinalAudio ) throws IOException, NoSuchAlgorithmException { File file = new File(filePath); if (file == null || (!file.exists())) { throw new FileNotFoundException("File not found: " + filePath); } FileInputStream fileIn = new FileInputStream(file); byte[] fileData = new byte[(int) file.length()]; fileIn.read(fileData); fileIn.close(); return uploadAudio(identifier, fileData, audioType, isFinalAudio); } /** * Request to upload the specified audio for speech recognition. * You must to specify the audio type by setAudioType(int audioType) before using this method. * * @param identifier - Identifier CookieSet. * @param audioData - The audio data. * Wave Header is required if it is a Wave audio. * @param isFinalAudio - TRUE if this is the last audio of a speech input. * @return API response with the audio uploading status. * @throws IOException HTTP connection failed, or other exceptions. * @throws NoSuchAlgorithmException Failed to create signature. */ public APIResponse uploadAudio( CookieSet identifier, byte[] audioData, boolean isFinalAudio ) throws IOException, NoSuchAlgorithmException { if (mAudioType == -1) { throw new UnsupportedOperationException(EXMSG_AUDIO_TYPE_NOT_SET); } return uploadAudio(identifier, audioData, mAudioType, isFinalAudio); } /** * Request to upload the specified audio for speech recognition. * * @param identifier - Identifier CookieSet. * @param audioData - The audio data. * Wave Header is required if it is a Wave audio. * @param audioType - Audio type: * AUDIO_TYPE_PCM_RAW for PCM raw data. * AUDIO_TYPE_PCM_WAVE for Wave audio. * AUDIO_TYPE_PCM_SPEEX for PCM Speex audio. * @param isFinalAudio - TRUE if this is the last audio of a speech input. * @return API response with the audio uploading status. * @throws IOException HTTP connection failed, or other exceptions. * @throws NoSuchAlgorithmException Failed to create signature. */ public APIResponse uploadAudio( CookieSet identifier, byte[] audioData, int audioType, boolean isFinalAudio ) throws IOException, NoSuchAlgorithmException { byte[] audioBuffer = null; int audioSize = audioData.length; switch (audioType) { case AUDIO_TYPE_PCM_RAW: if (mEncodeToSpeex) { audioBuffer = audioData; audioSize = speexEncodeRawWavePCM(audioBuffer); } else { if (!containsWaveHeader(audioData)) { audioBuffer = getWithWaveHeader(audioData, false); audioSize = audioBuffer.length; } } break; case AUDIO_TYPE_PCM_WAVE: if (mEncodeToSpeex) { if (containsWaveHeader(audioData)) { audioBuffer = getWithoutWaveHeader(audioData, false); } audioSize = speexEncodeRawWavePCM(audioBuffer); } break; case AUDIO_TYPE_PCM_SPEEX: throw new UnsupportedOperationException( EXMSG_MUST_BE_SPECIFIED_METHOD + "\nYou should use ** uploadSpeexAudio() ** method instead"); default: throw new IllegalArgumentException(EXMSG_INVALID_AUDIO_TYPE); } return uploadAudioData(identifier, audioBuffer, audioSize, isFinalAudio); } /** * Request to upload the specified audio for speech recognition. * * @param identifier - Identifier CookieSet. * @param audioData - The audio data. * @param audioDataRealSize - The real audio data size in the buffer. * @param isFinalAudio - TRUE if this is the last audio of a speech input. * @return API response with the audio uploading status. * @throws IOException HTTP connection failed, or other exceptions. * @throws NoSuchAlgorithmException Failed to create signature. */ public APIResponse uploadSpeexAudio( CookieSet identifier, byte[] audioData, int audioDataRealSize, boolean isFinalAudio ) throws IOException, NoSuchAlgorithmException { if (mAudioType != AUDIO_TYPE_PCM_SPEEX) { throw new IllegalArgumentException(EXMSG_INVALID_AUDIO_TYPE + "\nOnly supports ** SPEEX ** audio data."); } return uploadAudioData(identifier, audioData, audioDataRealSize, isFinalAudio); } /** * Set and specify the type of the speech audio. * * @param audioType - Audio type: * AUDIO_TYPE_PCM_RAW for PCM raw data. * AUDIO_TYPE_PCM_WAVE for Wave audio. * AUDIO_TYPE_PCM_SPEEX for PCM Speex audio. */ public void setAudioType(int audioType) { switch (audioType) { case AUDIO_TYPE_PCM_RAW: break; case AUDIO_TYPE_PCM_WAVE: break; case AUDIO_TYPE_PCM_SPEEX: break; default: throw new IllegalArgumentException(EXMSG_INVALID_AUDIO_TYPE); } mAudioType = audioType; } /** * Get the maximum size in bytes of the audio buffer to append audio frames data. * * @return The size in bytes. */ public int getAudioBufferMaxSize() { return mAudioBufferListMaxSize; } /** * Get the minimum size in bytes of the audio buffer to append audio frames data. * * @return The size in bytes. */ public int getAudioBufferMinSize() { return mAudioBufferListMinSize; } /** * Append audio data contains N frames to wait the upload for speech recognition. * The size of data in bytes must be a multiple of the size getAudioBufferMinSize() provides. * The total size of all of appended data must be less than or equal to the size getAudioBufferMaxSize() provides. * * @param audioFramesData - The audio frames data. (Contains N frames) * @return Total size of all of appended audio data. */ public int appendAudioFramesData(byte[] audioFramesData) { if (mAudioType == -1) { throw new UnsupportedOperationException(EXMSG_AUDIO_TYPE_NOT_SET); } else if (mAudioType == AUDIO_TYPE_PCM_SPEEX) { throw new UnsupportedOperationException( EXMSG_MUST_BE_SPECIFIED_METHOD + "\nYou should use ** appendSpeexAudioFramesData() ** method instead"); } if (mAudioBufferListAppendedSize > mAudioBufferListMaxSize) { throw new IllegalStateException( "The total size of append buffers is greater than the limited size (" + mAudioBufferListMaxSize + "). You have to flush for upload."); } synchronized (mAudioBufferList) { int audioSize = audioFramesData.length; byte[] tempData = new byte[audioSize]; System.arraycopy(audioFramesData, 0, tempData, 0, audioSize); if (mEncodeToSpeex) { if ((audioSize < mAudioBufferListMinSize) || ((audioSize % mSpeexProcessSize) != 0)) { throw new IllegalArgumentException( "The size of input data must be greater than " + mAudioBufferListMinSize + " (Bytes)," + " and it must be a multiple of " + mSpeexProcessSize + " (Bytes)."); } audioSize = speexEncodeRawWavePCM(tempData); } byte[] appendData = new byte[audioSize]; System.arraycopy(tempData, 0, appendData, 0, audioSize); Arrays.fill(tempData, (byte) 0); mAudioBufferList.offer(appendData); mAudioBufferListCurrentSize += audioSize; mAudioBufferListAppendedSize += audioFramesData.length; } return mAudioBufferListAppendedSize; } /** * Append audio data contains N frames to wait the upload for speech recognition. * The size of data in bytes must be a multiple of the size getAudioBufferMinSize() provides. * The total size of all of appended data must be less than or equal to the size getAudioBufferMaxSize() provides. * * @param audioFramesData - The audio frames data. (Contains N frames) * @param audioDataRealSize - The real audio data size in the buffer. * @return Total size of all of appended audio data. */ public int appendSpeexAudioFramesData(byte[] audioFramesData, int audioDataRealSize) { if (mAudioType != AUDIO_TYPE_PCM_SPEEX) { throw new IllegalArgumentException(EXMSG_INVALID_AUDIO_TYPE + "\nOnly supports ** SPEEX ** audio data."); } if (mAudioBufferListAppendedSize > mAudioBufferListMaxSize) { throw new IllegalStateException( "The total size of append buffers is greater than the limited size (" + mAudioBufferListMaxSize + "). You have to flush for upload."); } synchronized (mAudioBufferList) { byte[] appendData = new byte[audioDataRealSize]; System.arraycopy(audioFramesData, 0, appendData, 0, audioDataRealSize); mAudioBufferList.offer(appendData); mAudioBufferListCurrentSize += audioDataRealSize; mAudioBufferListAppendedSize += audioDataRealSize; } return mAudioBufferListAppendedSize; } /** * Flush all of appended audio data to upload and request for speech recognition. * * @param identifier - Identifier CookieSet. * @param isFinalAudio - TRUE if this is the last audio of a speech input. * @return API response with the audio uploading status. * @throws IOException HTTP connection failed, or other exceptions. * @throws NoSuchAlgorithmException Failed to create signature. */ public APIResponse flushToUploadAudio( CookieSet identifier, boolean isFinalAudio ) throws IOException, NoSuchAlgorithmException { if (mAudioType == -1) { throw new UnsupportedOperationException(EXMSG_AUDIO_TYPE_NOT_SET); } byte[] buffer = null; synchronized (mAudioBufferList) { if (mAudioBufferList.size() == 0) { throw new IllegalStateException("There are no appended buffers."); } buffer = new byte[mAudioBufferListCurrentSize]; byte[] data = null; int currentPos = 0; while ((data = mAudioBufferList.poll()) != null) { System.arraycopy(data, 0, buffer, currentPos, data.length); currentPos += data.length; } mAudioBufferListCurrentSize = 0; mAudioBufferListAppendedSize = 0; } if ((!mEncodeToSpeex) && (mAudioType != AUDIO_TYPE_PCM_SPEEX)) { // When the user uses the batch upload, we do not know whether // the user is correctly handling the cutting of the audio data. // So, we may need to remove the original wave header. if (containsWaveHeader(buffer)) { buffer = getWithoutWaveHeader(buffer, true); } // And then create a new header to ensure each batch upload // contains a wave header with the correct header information. buffer = getWithWaveHeader(buffer, true); } return uploadAudioData(identifier, buffer, buffer.length, isFinalAudio); } /** * Release all of appended audio data. */ public void releaseAppendedAudio() { synchronized (mAudioBufferList) { mAudioBufferList.clear(); mAudioBufferListCurrentSize = 0; mAudioBufferListAppendedSize = 0; } } /** * Get size of all appended audio data. * * @return Appended audio size in bytes. */ public int getAppendedAudioSize() { return mAudioBufferListAppendedSize; } /** * Get size of the buffered data from the appended audio. * * @return Size of the buffered data from the appended audio. */ public int getBufferedDataSize() { return mAudioBufferListCurrentSize; } /** * Check if there are still buffered data that has not been flushed yet. * * @return TRUE if buffered data exists. */ public boolean hasBufferedData() { return (!mAudioBufferList.isEmpty()); } /** * Request to get speech recognition results by specified task identifier. * Before you call this method, you must to upload audio by related methods first. * * @param identifier - Identifier CookieSet. * @return API response with speech recognition results. * @throws IllegalArgumentException Invalid contents of the CookieSet. * @throws IOException HTTP connection failed, or other exceptions. * @throws NoSuchAlgorithmException Failed to create signature. */ public APIResponse requestRecognition(CookieSet identifier) throws IllegalArgumentException, IOException, NoSuchAlgorithmException { return sendGetResultsRequest(identifier, SEQ_TYPE_SEG, null); } /** * Request to get speech recognition results by specified task identifier. * Before you call this method, you must to upload audio by related methods first. * * @param identifier - Identifier CookieSet. * @return API response with speech recognition results and NLI results. * @throws IllegalArgumentException Invalid contents of the CookieSet. * @throws IOException HTTP connection failed, or other exceptions. * @throws NoSuchAlgorithmException Failed to create signature. */ public APIResponse requestRecognitionWithNLI(CookieSet identifier) throws IllegalArgumentException, IOException, NoSuchAlgorithmException { return requestRecognitionWithNLI(identifier, null); } /** * Request to get speech recognition results by specified task identifier. * Before you call this method, you must to upload audio by related methods first. * * @param identifier - Identifier CookieSet. * @param nliConfig - NLIConfig object. * @return API response with speech recognition results and NLI results. * @throws IllegalArgumentException Invalid contents of the CookieSet. * @throws IOException HTTP connection failed, or other exceptions. * @throws NoSuchAlgorithmException Failed to create signature. */ public APIResponse requestRecognitionWithNLI( CookieSet identifier, NLIConfig nliConfig ) throws IllegalArgumentException, IOException, NoSuchAlgorithmException { return sendGetResultsRequest(identifier, SEQ_TYPE_NLI, nliConfig); } /** * Request to get speech recognition results by specified task identifier. * Before you call this method, you must to upload audio by related methods first. * * @param identifier - Identifier CookieSet. * @return API response with all kinds of recognition results. * @throws IllegalArgumentException Invalid contents of the CookieSet. * @throws IOException HTTP connection failed, or other exceptions. * @throws NoSuchAlgorithmException Failed to create signature. */ public APIResponse requestRecognitionWithAll(CookieSet identifier) throws IllegalArgumentException, IOException, NoSuchAlgorithmException { return requestRecognitionWithAll(identifier, null); } /** * Request to get speech recognition results by specified task identifier. * Before you call this method, you must to upload audio by related methods first. * * @param identifier - Identifier CookieSet. * @param nliConfig - NLIConfig object. * @return API response with all kinds of recognition results. * @throws IllegalArgumentException Invalid contents of the CookieSet. * @throws IOException HTTP connection failed, or other exceptions. * @throws NoSuchAlgorithmException Failed to create signature. */ public APIResponse requestRecognitionWithAll( CookieSet identifier, NLIConfig nliConfig ) throws IllegalArgumentException, IOException, NoSuchAlgorithmException { return sendGetResultsRequest(identifier, SEQ_TYPE_ALL, nliConfig); } private APIResponse uploadAudioData( CookieSet identifier, byte[] audioData, int audioSize, boolean isFinalAudio ) throws IOException, NoSuchAlgorithmException { final Map<String, String> queryParams = new HashMap<String, String>(); queryParams.put("compress", (mEncodeToSpeex ? "1" : (mAudioType == AUDIO_TYPE_PCM_SPEEX ? "1" : "0"))); queryParams.put("seq", mDefaultSeqType); queryParams.put("stop", (isFinalAudio ? "1" : "0")); String cookies = identifier.getContents().toString(); final URL url = new URL(getConfiguration().getBaseRequestURL(mApiName, queryParams)); final HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection(); httpConnection.setRequestMethod("POST"); if ((cookies != null) && (!cookies.equals(""))) { httpConnection.setRequestProperty("Cookie", cookies); } httpConnection.setRequestProperty("contentType", "utf-8"); httpConnection.setConnectTimeout(getTimeout()); HttpClient httpClient = null; String response = ""; try { httpClient = new HttpClient(httpConnection); httpClient.octetStreamConnect(audioData, audioSize); if(httpClient.getResponseCode() == HttpURLConnection.HTTP_OK) { response = httpClient.getResponseContent(); // Get cookie to setup speech task identifier. identifier.setContents(httpClient.getCookies()); if (identifier.getContents() == null) { throw new IOException("Failed to get cookie from server."); } } else { throw new IOException(httpClient.getResponseMessage()); } } finally { httpClient.close(); } return APIResponseBuilder.create(response); } private APIResponse sendGetResultsRequest( CookieSet identifier, String seqType, NLIConfig nliConfig ) throws IllegalArgumentException, IOException, NoSuchAlgorithmException { String cookies = identifier.getContents().toString(); if (cookies == null) { throw new IllegalArgumentException("Invalid contents of the CookieSet."); } final Map<String, String> queryParams = new HashMap<String, String>(); queryParams.put("compress", (mEncodeToSpeex ? "1" : "0")); queryParams.put("seq", seqType); JsonObject rq = new JsonObject(); if (seqType.contains(SEQ_TYPE_NLI)) { if (nliConfig != null) { rq.add("nli_config", nliConfig.toJsonElement()); } } queryParams.put("rq", mGson.toJson(rq)); final URL url = new URL(getConfiguration().getBaseRequestURL(mApiName, queryParams)); final HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection(); httpConnection.setRequestMethod("GET"); httpConnection.setRequestProperty("Cookie", cookies); httpConnection.setRequestProperty("contentType", "utf-8"); httpConnection.setConnectTimeout(getTimeout()); HttpClient httpClient = null; String response = null; try { httpClient = new HttpClient(httpConnection); httpClient.normalConnect(); if(httpClient.getResponseCode() == HttpURLConnection.HTTP_OK) { response = httpClient.getResponseContent(); } else { throw new IOException(httpClient.getResponseMessage()); } } finally { httpClient.close(); } return APIResponseBuilder.create(response); } private void initSpeexEncoder() { int mode = 1; int quality = 10; if (mSpeexEncoder == null) { mSpeexEncoder = new SpeexEncoder(); mSpeexEncoder.init(mode, quality, AUDIO_SAMPLE_RATE, AUDIO_CHANNELS); } mSpeexProcessSize = mSpeexProcessFrames * AUDIO_CHANNELS * mSpeexEncoder.getFrameSize(); } private int speexEncodeRawWavePCM(byte[] audioData) { initSpeexEncoder(); int blockSize = mSpeexProcessSize; byte[] data = new byte[blockSize]; int encodeSize = 0; int encodedBytes = 0; int processedOffset = 0; while ((processedOffset + blockSize) <= audioData.length) { System.arraycopy(audioData, processedOffset, data, 0, blockSize); processedOffset += blockSize; mSpeexEncoder.processData(data, 0, mSpeexProcessSize); encodeSize = mSpeexEncoder.getProcessedData(data, 0); if (encodeSize > 0) { if (encodeSize > audioData.length) { encodeSize = audioData.length; } System.arraycopy(data, 0, audioData, encodedBytes, encodeSize); encodedBytes += encodeSize; } Arrays.fill(data, (byte) 0); } if (encodedBytes < audioData.length) { Arrays.fill(audioData, encodedBytes, (audioData.length - 1), (byte) 0); } return encodedBytes; } private boolean containsWaveHeader(byte[] audioData) { return (audioData.length > WAVE_HEADER_SIZE && audioData[0] == 'R' && audioData[1] == 'I' && audioData[2] == 'F' && audioData[3] == 'F' && audioData[8] == 'W' && audioData[9] == 'A' && audioData[10] == 'V' && audioData[11] == 'E'); } private byte[] getWithoutWaveHeader( byte[] soureData, boolean cleanSourceData ) { int newSize = soureData.length - WAVE_HEADER_SIZE; byte[] newData = new byte[newSize]; System.arraycopy(soureData, WAVE_HEADER_SIZE, newData, 0, newSize); if (cleanSourceData) { Arrays.fill(soureData, (byte) 0); } return newData; } private byte[] getWithWaveHeader( byte[] soureData, boolean cleanSourceData ) { int audioDataSize = soureData.length; int totalLength = soureData.length; int byteRate = AUDIO_BITS_PER_SAMPLE * AUDIO_SAMPLE_RATE * 1 / 8; byte[] newData = new byte[audioDataSize + WAVE_HEADER_SIZE]; newData[0] = 'R'; // RIFF/WAVE header newData[1] = 'I'; newData[2] = 'F'; newData[3] = 'F'; newData[4] = (byte) (audioDataSize & 0xff); newData[5] = (byte) ((audioDataSize >> 8) & 0xff); newData[6] = (byte) ((audioDataSize >> 16) & 0xff); newData[7] = (byte) ((audioDataSize >> 24) & 0xff); newData[8] = 'W'; newData[9] = 'A'; newData[10] = 'V'; newData[11] = 'E'; newData[12] = 'f'; // 'fmt ' chunk newData[13] = 'm'; newData[14] = 't'; newData[15] = ' '; newData[16] = 16; // 4 bytes: size of 'fmt ' chunk newData[17] = 0; newData[18] = 0; newData[19] = 0; newData[20] = 1; // format = 1 newData[21] = 0; newData[22] = (byte) AUDIO_CHANNELS; newData[23] = 0; newData[24] = (byte) (AUDIO_SAMPLE_RATE & 0xff); newData[25] = (byte) ((AUDIO_SAMPLE_RATE >> 8) & 0xff); newData[26] = (byte) ((AUDIO_SAMPLE_RATE >> 16) & 0xff); newData[27] = (byte) ((AUDIO_SAMPLE_RATE >> 24) & 0xff); newData[28] = (byte) (byteRate & 0xff); newData[29] = (byte) ((byteRate >> 8) & 0xff); newData[30] = (byte) ((byteRate >> 16) & 0xff); newData[31] = (byte) ((byteRate >> 24) & 0xff); newData[32] = (byte) 2; // block align newData[33] = 0; newData[34] = AUDIO_BITS_PER_SAMPLE; newData[35] = 0; newData[36] = 'd'; newData[37] = 'a'; newData[38] = 't'; newData[39] = 'a'; newData[40] = (byte) (totalLength & 0xff); newData[41] = (byte) ((totalLength >> 8) & 0xff); newData[42] = (byte) ((totalLength >> 16) & 0xff); newData[43] = (byte) ((totalLength >> 24) & 0xff); System.arraycopy(soureData, 0, newData, WAVE_HEADER_SIZE, audioDataSize); if (cleanSourceData) { Arrays.fill(soureData, (byte) 0); } return newData; } }
0
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami/cloudService/SpeechResult.java
/* Copyright 2017, VIA Technologies, Inc. & OLAMI Team. http://olami.ai Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ai.olami.cloudService; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class SpeechResult { public static final int STATUS_RECOGNIZE_OK = 0; public static final int STATUS_RESULT_NOT_CHANGE = 1; public static final int SPEECH_STATUS_GOOD_QUALITY = 0; public static final int SPEECH_STATUS_WITH_NOISE = 1; @Expose @SerializedName("result") private String mResult = null; @Expose @SerializedName("speech_status") private int mSpeechStatus = -1; @Expose @SerializedName("final") private boolean mIsFinalResult = false; @Expose @SerializedName("status") private int mStatus = -1; /** * Get Speech-To-Text recognition result. * * @return Text result. */ public String getResult() { return (mResult == null) ? "" : mResult; } /** * Get quality and status of the speech source. * * @return 0 for good, or others for noise and issues. */ public int getSpeechStatus() { return mSpeechStatus; } /** * Check whether the recognition is completed. * * @return TRUE if recognition is completed, or FALSE means this is not final result. */ public boolean complete() { return mIsFinalResult; } /** * Get the processing status of audio uploading or recognition. * * @return 0 for the processing is fine, 1 for result not change, or others for something wrong. */ public int getStatus() { return mStatus; } }
0
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami/cloudService/TextRecognizer.java
/* Copyright 2017, VIA Technologies, Inc. & OLAMI Team. http://olami.ai Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ai.olami.cloudService; import ai.olami.util.GsonFactory; import ai.olami.util.HttpClient; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.security.NoSuchAlgorithmException; import com.google.gson.Gson; import com.google.gson.JsonObject; public class TextRecognizer extends APIRequestBase { public static final String RQ_DATA_TYPE_STT = "stt"; public static final int RQ_DATA_INPUT_TYPE_FROM_SPEECH = 0; public static final int RQ_DATA_INPUT_TYPE_FROM_TEXT = 1; private int mRqDataInputType = RQ_DATA_INPUT_TYPE_FROM_SPEECH; private Gson mGson = GsonFactory.getNormalGson(); /** * Text Recognizer to issue Natural Language Understanding API requests. * * @param configuration - API configurations. */ public TextRecognizer(APIConfiguration configuration) { super(configuration); } /** * Set NLI data input type. * * @param inputType 0 for speech source, or 1 for text source. */ public void setNLIDataInputType(int inputType) { mRqDataInputType = inputType; } /** * Request word segmentation analyze service by specified input text. * * @param text - The text to be analyzed. * @return API response with analysis results. * @throws NoSuchAlgorithmException Failed to create signature. * @throws IOException HTTP connection failed, or other exceptions. */ public APIResponse requestWordSegmentation(String text) throws NoSuchAlgorithmException, IOException { return sendRequest(APIConfiguration.API_NAME_SEG, text, null); } /** * Request Natural Language Interaction service by specified input text. * * @param text - The text to be recognized. * @return API response with Natural Language Interaction results. * @throws NoSuchAlgorithmException Failed to create signature. * @throws IOException HTTP connection failed, or other exceptions. */ public APIResponse requestNLI(String text) throws NoSuchAlgorithmException, IOException { return requestNLI(text, null); } /** * Request Natural Language Interaction service by specified input text. * * @param text - The text to be recognized. * @param nliConfig - NLIConfig object. * @return API response with Natural Language Interaction results. * @throws NoSuchAlgorithmException Failed to create signature. * @throws IOException HTTP connection failed, or other exceptions. */ public APIResponse requestNLI( String text, NLIConfig nliConfig ) throws NoSuchAlgorithmException, IOException { return sendRequest(APIConfiguration.API_NAME_NLI, text, nliConfig); } private APIResponse sendRequest( String apiName, String text, NLIConfig nliConfig ) throws NoSuchAlgorithmException, IOException { StringBuffer httpQueryStringBuffer = new StringBuffer(); if (apiName == APIConfiguration.API_NAME_SEG) { httpQueryStringBuffer.append("rq="); httpQueryStringBuffer.append(text); } else if (apiName == APIConfiguration.API_NAME_NLI) { JsonObject data = new JsonObject(); data.addProperty("input_type", mRqDataInputType); data.addProperty("text", text); JsonObject rq = new JsonObject(); rq.addProperty("data_type", "stt"); rq.add("data", data); if (nliConfig != null) { rq.add("nli_config", nliConfig.toJsonElement()); } httpQueryStringBuffer.append("rq="); httpQueryStringBuffer.append(mGson.toJson(rq)); } final URL url = new URL(getConfiguration().getBaseRequestURL(apiName)); final HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection(); httpConnection.setRequestMethod("POST"); httpConnection.setRequestProperty("contentType", "utf-8"); httpConnection.setConnectTimeout(getTimeout()); HttpClient httpClient = null; String response = null; try { httpClient = new HttpClient(httpConnection); httpClient.postQueryConnect(httpQueryStringBuffer.toString()); if(httpClient.getResponseCode() == HttpURLConnection.HTTP_OK) { response = httpClient.getResponseContent(); } else { throw new IOException(httpClient.getResponseMessage()); } } finally { httpClient.close(); } return APIResponseBuilder.create(response); } }
0
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami/ids/BaikeData.java
/* Copyright 2017, VIA Technologies, Inc. & OLAMI Team. http://olami.ai Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ai.olami.ids; import java.util.HashMap; import java.util.Map; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class BaikeData { @Expose @SerializedName("field_name") private String[] mFieldNames = null; @Expose @SerializedName("field_value") private String[] mFieldValues = null; private Map<String, String> mFieldNameValues = null; private void initFieldNameValues() { if (mFieldNameValues == null) { mFieldNameValues = new HashMap<String, String>(); for (int i = 0; i < mFieldNames.length; i++) { mFieldNameValues.put(mFieldNames[i], mFieldValues[i]); } } } /** * Get number of fields. * * @return Number of fields. */ public int getNumberOfFields() { initFieldNameValues(); return mFieldNameValues.size(); } /** * Get name-value contents of all fields. * * @return The name-value contents. */ public Map<String, String> getFieldNameValues() { initFieldNameValues(); return mFieldNameValues; } @Expose @SerializedName("photo_url") private String mPhotoURL = null; /** * @return Photo URL. */ public String getPhotoURL() { return (mPhotoURL == null) ? "" : mPhotoURL; } /** * @return TRUE if contains photo URL. */ public boolean hasPhotoURL() { return ((mPhotoURL != null) && (!mPhotoURL.equals(""))); } @Expose @SerializedName("type") private String mType = null; /** * @return Content type. */ public String getType() { return (mType == null) ? "" : mType; } /** * @return TRUE if contains type information. */ public boolean hasType() { return ((mType != null) && (!mType.equals(""))); } @Expose @SerializedName("description") private String mDescription = null; /** * @return Content description. */ public String getDescription() { return (mDescription == null) ? "" : mDescription; } /** * @return TRUE if contains description. */ public boolean hasDescription() { return ((mDescription != null) && (!mDescription.equals(""))); } @Expose @SerializedName("categorylist") private String[] mCategoryList = null; /** * @return Category list of the result. */ public String[] getCategoryList() { return (mCategoryList == null) ? new String[]{""} : mCategoryList; } /** * @return TRUE if contains category list of the result. */ public boolean hasCategoryList() { return ((mCategoryList != null) && (mCategoryList.length > 0)); } @Expose @SerializedName("highlight") private int[] mHighlights = null; /** * @return Category list of the result. */ public int[] getHighlights() { return (mHighlights == null) ? new int[]{0} : mHighlights; } /** * @return TRUE if contains category list of the result. */ public boolean hasHighlights() { return ((mHighlights != null) && (mHighlights.length > 0)); } }
0
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami/ids/CookingData.java
/* Copyright 2017, VIA Technologies, Inc. & OLAMI Team. http://olami.ai Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ai.olami.ids; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class CookingData { @Expose @SerializedName("content") private String mContent = null; /** * @return Content. */ public String getContent() { return (mContent == null) ? "" : mContent; } /** * @return TRUE if contains content information. */ public boolean hasContent() { return ((mContent != null) && (!mContent.equals(""))); } @Expose @SerializedName("name") private String mName = null; /** * @return Name. */ public String getName() { return (mName == null) ? "" : mName; } /** * @return TRUE if contains name information. */ public boolean hasName() { return ((mName != null) && (!mName.equals(""))); } }
0
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami/ids/ExchangeRateData.java
/* Copyright 2017, VIA Technologies, Inc. & OLAMI Team. http://olami.ai Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ai.olami.ids; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class ExchangeRateData { @Expose @SerializedName("target_currency") private String mTargetCurrency = null; /** * @return Target currency. */ public String getTargetCurrency() { return (mTargetCurrency == null) ? "" : mTargetCurrency; } /** * @return TRUE if contains target currency. */ public boolean hasTargetCurrency() { return ((mTargetCurrency != null) && (!mTargetCurrency.equals(""))); } }
0
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami/ids/IDSResult.java
/* Copyright 2017, VIA Technologies, Inc. & OLAMI Team. http://olami.ai Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ai.olami.ids; import java.lang.reflect.Type; import java.util.ArrayList; import com.google.gson.reflect.TypeToken; public class IDSResult { /** * IDS Modules */ public static enum Types { QUESTION ("question", null), CONFIRMATION ("confirmation", null), SELECTION ("selection", null), DATE ("date", null), NONSENSE ("nonsense", null), ZIP_CODE ("zipcode", null), MATH_24 ("math24", null), WEATHER ("weather", (new TypeToken<ArrayList<WeatherData>>() {}).getType()), BAIKE ("baike", (new TypeToken<ArrayList<BaikeData>>() {}).getType()), NEWS ("news", (new TypeToken<ArrayList<NewsData>>() {}).getType()), KKBOX ("kkbox", (new TypeToken<ArrayList<KKBOXData>>() {}).getType()), MUSIC_CONTROL ("MusicControl", (new TypeToken<ArrayList<MusicControlData>>() {}).getType()), TV_PROGRAM ("tvprogram", (new TypeToken<ArrayList<TVProgramData>>() {}).getType()), POEM ("poem", (new TypeToken<ArrayList<PoemData>>() {}).getType()), JOKE ("joke", (new TypeToken<ArrayList<JokeData>>() {}).getType()), STOCK_MARKET ("stock", (new TypeToken<ArrayList<StockMarketData>>() {}).getType()), MATH ("math", (new TypeToken<ArrayList<MathData>>() {}).getType()), UNIT_CONVERT ("unitconvert", (new TypeToken<ArrayList<UnitConvertData>>() {}).getType()), EXCHANGE_RATE ("exchangerate", (new TypeToken<ArrayList<ExchangeRateData>>() {}).getType()), COOKING ("cooking", (new TypeToken<ArrayList<CookingData>>() {}).getType()), OPEN_WEB ("openweb", (new TypeToken<ArrayList<OpenWebData>>() {}).getType()); private String name; private Type dataObjArrayListType; private Types( String name, Type dataObjArrayListType ) { this.name = name; this.dataObjArrayListType = dataObjArrayListType; } /** * @return Module name */ public String getName() { return this.name; } /** * @return Type of the DataObject ArrayList. */ public Type getDataArrayListType() { return this.dataObjArrayListType; } /** * Check if the given name exists in module type list. * * @param moduleName - Module name you want to check. * @return TRUE if the given name exists in module type list. */ public static boolean contains(String moduleName) { Object[] list = Types.class.getEnumConstants(); for (Object t : list) { if (((Types) t).getName().equals(moduleName)) { return true; } } return false; } /** * Get enum by mdoule name. * @param moduleName - Module name you want to find. * @return Module enum. */ public static Types getByName(String moduleName) { Object[] list = Types.class.getEnumConstants(); for (Object t : list) { if (((Types) t).getName().equals(moduleName)) { return ((Types) t); } } return null; } /** * Get DataObject array type by the specified module name. * * @param moduleName - Module name you want to find. * @return Type of the DataObject ArrayList. */ public static Type getDataArrayListType(String moduleName) { Object[] list = Types.class.getEnumConstants(); for (Object t : list) { if (((Types) t).getName().equals(moduleName)) { return ((Types) t).getDataArrayListType(); } } return null; } } }
0
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami/ids/JokeData.java
/* Copyright 2017, VIA Technologies, Inc. & OLAMI Team. http://olami.ai Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ai.olami.ids; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class JokeData { @Expose @SerializedName("content") private String mContent = null; /** * @return Content. */ public String getContent() { return (mContent == null) ? "" : mContent; } /** * @return TRUE if contains content. */ public boolean hasContent() { return ((mContent != null) && (!mContent.equals(""))); } }
0
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami/ids/KKBOXData.java
/* Copyright 2018, VIA Technologies, Inc. & OLAMI Team. http://olami.ai Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ai.olami.ids; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class KKBOXData { @Expose @SerializedName("id") private String mID = null; /** * @return ID. */ public String getID() { return (mID == null) ? "" : mID; } /** * @return TRUE if contains ID. */ public boolean hasID() { return ((mID != null) && (!mID.equals(""))); } @Expose @SerializedName("title") private String mTitle = null; /** * @return Title. */ public String getTitle() { return (mTitle == null) ? "" : mTitle; } /** * @return TRUE if contains title. */ public boolean hasTitle() { return ((mTitle != null) && (!mTitle.equals(""))); } @Expose @SerializedName("artist") private String mArtist = null; /** * @return Artist. */ public String getArtist() { return (mArtist == null) ? "" : mArtist; } /** * @return TRUE if contains artist. */ public boolean hasArtist() { return ((mArtist != null) && (!mArtist.equals(""))); } @Expose @SerializedName("artistId") private String mArtistID = null; /** * @return Artist ID. */ public String getArtistID() { return (mArtistID == null) ? "" : mArtistID; } /** * @return TRUE if contains artist ID. */ public boolean hasArtistID() { return ((mArtistID != null) && (!mArtistID.equals(""))); } @Expose @SerializedName("album") private String mAlbum = null; /** * @return Album. */ public String getAlbum() { return (mAlbum == null) ? "" : mAlbum; } /** * @return TRUE if contains album. */ public boolean hasAlbum() { return ((mAlbum != null) && (!mAlbum.equals(""))); } @Expose @SerializedName("albumId") private String mAlbumID = null; /** * @return Album ID. */ public String getAlbumID() { return (mAlbumID == null) ? "" : mAlbumID; } /** * @return TRUE if contains album ID. */ public boolean hasAlbumID() { return ((mAlbumID != null) && (!mAlbumID.equals(""))); } @Expose @SerializedName("time") private String mDurationTime = null; /** * @return Duration of time in milliseconds. */ public long getDuration() { return (hasDuration() ? Long.parseLong(mDurationTime) : 0); } /** * @return TRUE if contains duration. */ public boolean hasDuration() { return ((mDurationTime != null) && (!mDurationTime.equals(""))); } @Expose @SerializedName("url") private String mURL = null; /** * @return URL. */ public String getURL() { return (mURL == null) ? "" : mURL; } /** * @return TRUE if contains URL. */ public boolean hasURL() { return ((mURL != null) && (!mURL.equals(""))); } @Expose @SerializedName("photo") private KKBOXDataPhoto[] mKKBOXDataPhotos = null; /** * @return Photo information array. */ public KKBOXDataPhoto[] getPhotos() { return mKKBOXDataPhotos; } /** * @return TRUE if contains photo information. */ public boolean hasPhotos() { return ((mKKBOXDataPhotos != null) && (mKKBOXDataPhotos.length > 0)); } }
0
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami/ids/KKBOXDataPhoto.java
/* Copyright 2018, VIA Technologies, Inc. & OLAMI Team. http://olami.ai Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ai.olami.ids; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class KKBOXDataPhoto { @Expose @SerializedName("width") private int mWidth = 0; /** * @return Width. */ public int getWidth() { return mWidth; } @Expose @SerializedName("height") private int mHeight = 0; /** * @return Height. */ public int getHeight() { return mHeight; } @Expose @SerializedName("url") private String mURL = null; /** * @return URL. */ public String getURL() { return (mURL == null) ? "" : mURL; } /** * @return TRUE if contains URL. */ public boolean hasURL() { return ((mURL != null) && (!mURL.equals(""))); } }
0
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami/ids/MathData.java
/* Copyright 2017, VIA Technologies, Inc. & OLAMI Team. http://olami.ai Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ai.olami.ids; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class MathData { @Expose @SerializedName("content") private String mContent = null; /** * @return Reply content. */ public String getContent() { return (mContent == null) ? "" : mContent; } /** * @return TRUE if contains reply content information. */ public boolean hasContent() { return ((mContent != null) && (!mContent.equals(""))); } @Expose @SerializedName("result") private String mResult = null; /** * @return Result. */ public String getResult() { return (mResult == null) ? "" : mResult; } /** * @return TRUE if contains result. */ public boolean hasResult() { return ((mResult != null) && (!mResult.equals(""))); } }
0
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami/ids/MusicControlData.java
/* Copyright 2018, VIA Technologies, Inc. & OLAMI Team. http://olami.ai Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ai.olami.ids; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class MusicControlData { public static final String NEXT = "next"; public static final String PREVIOUS = "prev"; public static final String PAUSE = "pause"; public static final String PLAY = "play"; public static final String RANDOM = "random"; public static final String LOOP = "loop"; public static final String ORDER = "order"; public static final String MUTE = "mute"; public static final String VOLUME_DOWN = "volume_down"; public static final String VOLUME_UP = "volume_up"; @Expose @SerializedName("index") private String mIndex = null; /** * @return Index. */ public String getIndex() { return (mIndex == null) ? "" : mIndex; } /** * @return TRUE if contains Index. */ public boolean hasIndex() { return ((mIndex != null) && (!mIndex.equals(""))); } @Expose @SerializedName("command") private String mCommand = null; /** * @return Command. */ public String getCommand() { return (mCommand == null) ? "" : mCommand; } /** * @return TRUE if contains command. */ public boolean hasCommand() { return ((mCommand != null) && (!mCommand.equals(""))); } }
0
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami/ids/NewsData.java
/* Copyright 2017, VIA Technologies, Inc. & OLAMI Team. http://olami.ai Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ai.olami.ids; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class NewsData { @Expose @SerializedName("title") private String mTitle = null; /** * @return Title. */ public String getTitle() { return (mTitle == null) ? "" : mTitle; } /** * @return TRUE if contains title. */ public boolean hasTitle() { return ((mTitle != null) && (!mTitle.equals(""))); } @Expose @SerializedName("time") private String mTime = null; /** * @return Date-time information. */ public String getTime() { return (mTime == null) ? "" : mTime; } /** * @return TRUE if contains date-time information. */ public boolean hasTime() { return ((mTime != null) && (!mTime.equals(""))); } @Expose @SerializedName("image_url") private String mImageURL = null; /** * @return Image URL. */ public String getImageURL() { return (mImageURL == null) ? "" : mImageURL; } /** * @return TRUE if contains image URL. */ public boolean hasImageURL() { return ((mImageURL != null) && (!mImageURL.equals(""))); } @Expose @SerializedName("detail") private String mDetail = null; /** * @return News detail. */ public String getDetail() { return (mDetail == null) ? "" : mDetail; } /** * @return TRUE if contains news detail. */ public boolean hasDetail() { return ((mDetail != null) && (!mDetail.equals(""))); } @Expose @SerializedName("ref_url") private String mRefURL = null; /** * @return Source URL of the news. */ public String getSourceURL() { return (mRefURL == null) ? "" : mRefURL; } /** * @return TRUE if contains source URL. */ public boolean hasSourceURL() { return ((mRefURL != null) && (!mRefURL.equals(""))); } @Expose @SerializedName("source") private String mSource = null; /** * @return Name of the source. */ public String getSourceName() { return (mSource == null) ? "" : mSource; } /** * @return TRUE if contains name of the source. */ public boolean hasSourceName() { return ((mSource != null) && (!mSource.equals(""))); } }
0
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami/ids/OpenWebData.java
/* Copyright 2017, VIA Technologies, Inc. & OLAMI Team. http://olami.ai Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ai.olami.ids; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class OpenWebData { @Expose @SerializedName("url") private String mURL = null; /** * @return URL. */ public String getURL() { return (mURL == null) ? "" : mURL; } /** * @return TRUE if contains URL. */ public boolean hasURL() { return ((mURL != null) && (!mURL.equals(""))); } }
0
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami/ids/PoemData.java
/* Copyright 2017, VIA Technologies, Inc. & OLAMI Team. http://olami.ai Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ai.olami.ids; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class PoemData { @Expose @SerializedName("title") private String mTitle = null; /** * @return Title. */ public String getTitle() { return (mTitle == null) ? "" : mTitle; } /** * @return TRUE if contains title. */ public boolean hasTitle() { return ((mTitle != null) && (!mTitle.equals(""))); } @Expose @SerializedName("author") private String mAuthor = null; /** * @return Author. */ public String getAuthor() { return (mAuthor == null) ? "" : mAuthor; } /** * @return TRUE if contains author information. */ public boolean hasAuthor() { return ((mAuthor != null) && (!mAuthor.equals(""))); } @Expose @SerializedName("content") private String mContent = null; /** * @return Content. */ public String getContent() { return (mContent == null) ? "" : mContent; } /** * @return TRUE if contains content. */ public boolean hasContent() { return ((mContent != null) && (!mContent.equals(""))); } @Expose @SerializedName("poem_name") private String mPoemName = null; /** * @return Poem name. */ public String getPoemName() { return (mPoemName == null) ? "" : mPoemName; } /** * @return TRUE if contains poem name. */ public boolean hasPoemName() { return ((mPoemName != null) && (!mPoemName.equals(""))); } }
0
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami/ids/StockMarketData.java
/* Copyright 2017, VIA Technologies, Inc. & OLAMI Team. http://olami.ai Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ai.olami.ids; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class StockMarketData { @Expose @SerializedName("is_history") private int mIsHistory = 0; /** * @return TRUE if this is history data. */ public boolean isHistory() { return (mIsHistory == 1); } @Expose @SerializedName("id") private String mID = null; /** * @return Stock ID. */ public String getID() { return (mID == null) ? "" : mID; } /** * @return TRUE if contains stock ID. */ public boolean hasID() { return ((mID != null) && (!mID.equals(""))); } @Expose @SerializedName("name") private String mName = null; /** * @return Stock name. */ public String getName() { return (mName == null) ? "" : mName; } /** * @return TRUE if contains stock name. */ public boolean hasName() { return ((mName != null) && (!mName.equals(""))); } @Expose @SerializedName("cur_price") private String mCurrentPrice = null; /** * @return Current price. */ public String getCurrentPrice() { return (mCurrentPrice == null) ? "" : mCurrentPrice; } /** * @return TRUE if contains current price information. */ public boolean hasCurrentPrice() { return ((mCurrentPrice != null) && (!mCurrentPrice.equals(""))); } @Expose @SerializedName("price_start") private String mOpeningPrice = null; /** * @return Opening price. */ public String getOpeningPrice() { return (mOpeningPrice == null) ? "" : mOpeningPrice; } /** * @return TRUE if contains opening price information. */ public boolean hasOpeningPrice() { return ((mOpeningPrice != null) && (!mOpeningPrice.equals(""))); } @Expose @SerializedName("price_end") private String mClosingPrice = null; /** * @return Closing price. */ public String getClosingPrice() { return (mClosingPrice == null) ? "" : mClosingPrice; } /** * @return TRUE if contains closing price information. */ public boolean hasClosingPrice() { return ((mClosingPrice != null) && (!mClosingPrice.equals(""))); } @Expose @SerializedName("price_high") private String mHighestPrice = null; /** * @return The highest price. */ public String getHighestPrice() { return (mHighestPrice == null) ? "" : mHighestPrice; } /** * @return TRUE if contains the highest price information. */ public boolean hasHighestPrice() { return ((mHighestPrice != null) && (!mHighestPrice.equals(""))); } @Expose @SerializedName("price_low") private String mLowestPrice = null; /** * @return The lowest price. */ public String getLowestPrice() { return (mLowestPrice == null) ? "" : mLowestPrice; } /** * @return TRUE if contains the lowest price information. */ public boolean hasLowestPrice() { return ((mLowestPrice != null) && (!mLowestPrice.equals(""))); } @Expose @SerializedName("change_rate") private String mChangeRate = null; /** * @return The change rate. */ public String getChangeRate() { return (mChangeRate == null) ? "" : mChangeRate; } /** * @return TRUE if contains the change rate information. */ public boolean hasChangeRate() { return ((mChangeRate != null) && (!mChangeRate.equals(""))); } @Expose @SerializedName("change_amount") private String mChangeAmount = null; /** * @return The change amount. */ public String getChangeAmount() { return (mChangeAmount == null) ? "" : mChangeAmount; } /** * @return TRUE if contains the change amount information. */ public boolean hasChangeAmount() { return ((mChangeAmount != null) && (!mChangeAmount.equals(""))); } @Expose @SerializedName("volume") private String mVolume = null; /** * @return The volume. */ public String getVolume() { return (mVolume == null) ? "" : mVolume; } /** * @return TRUE if contains the volume information. */ public boolean hasVolume() { return ((mVolume != null) && (!mVolume.equals(""))); } @Expose @SerializedName("amount") private String mAmount = null; /** * @return Amount. */ public String getAmount() { return (mAmount == null) ? "" : mAmount; } /** * @return TRUE if contains amount information. */ public boolean hasAmount() { return ((mAmount != null) && (!mAmount.equals(""))); } @Expose @SerializedName("intent") private String mIntent = null; /** * @return Intent information. */ public String getIntentInfo() { return (mIntent == null) ? "" : mIntent; } /** * @return TRUE if contains intent information. */ public boolean hasIntentInfo() { return ((mIntent != null) && (!mIntent.equals(""))); } @Expose @SerializedName("time") private String mTime = null; /** * @return Date-time information. */ public String getTime() { return (mTime == null) ? "" : mTime; } /** * @return TRUE if contains date-time information. */ public boolean hasTime() { return ((mTime != null) && (!mTime.equals(""))); } @Expose @SerializedName("favorite") private String mFavorite = ""; /** * @return TRUE if it is in the favorites list. */ public boolean isFavorite() { return mFavorite.equals("1"); } }
0
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami/ids/TVProgramData.java
/* Copyright 2017, VIA Technologies, Inc. & OLAMI Team. http://olami.ai Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ai.olami.ids; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class TVProgramData { @Expose @SerializedName("name") private String mName = null; /** * @return TV program name. */ public String getName() { return (mName == null) ? "" : mName; } /** * @return TRUE if contains TV program name. */ public boolean hasName() { return ((mName != null) && (!mName.equals(""))); } @Expose @SerializedName("time") private String mTime = null; /** * @return Date-time information. */ public String getTime() { return (mTime == null) ? "" : mTime; } /** * @return TRUE if contains date-time information. */ public boolean hasTime() { return ((mTime != null) && (!mTime.equals(""))); } @Expose @SerializedName("highlight") private int mHighlight = 0; /** * @return TRUE if this content is matches the search condition. */ public boolean isHighlight() { return (mHighlight == 1); } }
0
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami/ids/UnitConvertData.java
/* Copyright 2017, VIA Technologies, Inc. & OLAMI Team. http://olami.ai Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ai.olami.ids; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class UnitConvertData { @Expose @SerializedName("content") private String mContent = null; /** * @return Reply content. */ public String getContent() { return (mContent == null) ? "" : mContent; } /** * @return TRUE if contains reply content information. */ public boolean hasContent() { return ((mContent != null) && (!mContent.equals(""))); } @Expose @SerializedName("src_value") private String mSourceValue = null; /** * @return Source value. */ public String getSourceValue() { return (mSourceValue == null) ? "" : mSourceValue; } /** * @return TRUE if contains source value. */ public boolean hasSourceValue() { return ((mSourceValue != null) && (!mSourceValue.equals(""))); } @Expose @SerializedName("src_unit") private String mSourceUnit = null; /** * @return Source unit. */ public String getSourceUnit() { return (mSourceUnit == null) ? "" : mSourceUnit; } /** * @return TRUE if contains source unit. */ public boolean hasSourceUnit() { return ((mSourceUnit != null) && (!mSourceUnit.equals(""))); } @Expose @SerializedName("dst_value") private String mDestinationValue = null; /** * @return Destination value. */ public String getDestinationValue() { return (mDestinationValue == null) ? "" : mDestinationValue; } /** * @return TRUE if contains destination value. */ public boolean hasDestinationValue() { return ((mDestinationValue != null) && (!mDestinationValue.equals(""))); } @Expose @SerializedName("dst_unit") private String mDestinationUnit = null; /** * @return Destination unit. */ public String getDestinationUnit() { return (mDestinationUnit == null) ? "" : mDestinationUnit; } /** * @return TRUE if contains destination unit. */ public boolean hasDestinationUnit() { return ((mDestinationUnit != null) && (!mDestinationUnit.equals(""))); } }
0
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami/ids/WeatherData.java
/* Copyright 2017, VIA Technologies, Inc. & OLAMI Team. http://olami.ai Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ai.olami.ids; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class WeatherData { @Expose @SerializedName("city") private String mCity = null; /** * @return City name. */ public String getCity() { return (mCity == null) ? "" : mCity; } /** * @return TRUE if contains city name. */ public boolean hasCity() { return ((mCity != null) && (!mCity.equals(""))); } @Expose @SerializedName("real_date") private long mRealDate = -1; /** * @return Date since 1970. */ public long getRealDate() { return mRealDate; } @Expose @SerializedName("date") private int mDate = -1; /** * Date description. * * @return 0 means the day, 1 means tomorrow, and so on. */ public int getDate() { return mDate; } @Expose @SerializedName("weather_start") private int mWeatherStart = -1; /** * Get the weather type code for the morning. * * @return Weather type code. */ public int getWeatherStart() { return mWeatherStart; } @Expose @SerializedName("weather_end") private int mWeatherEnd = -1; /** * Get the weather type code for the evening. * * @return Weather type code. */ public int getWeatherEnd() { return mWeatherEnd; } @Expose @SerializedName("wind") private String mWind = null; /** * @return Wind direction. */ public String getWind() { return (mWind == null) ? "" : mWind; } /** * @return TRUE if contains wind direction. */ public boolean hasWind() { return ((mWind != null) && (!mWind.equals(""))); } @Expose @SerializedName("temperature_high") private String mTemperatureHigh = null; /** * @return Maximum temperature. */ public String getMaxTemperature() { return (mTemperatureHigh == null) ? "" : mTemperatureHigh; } /** * @return TRUE if contains maximum temperature. */ public boolean hasMaxTemperature() { return ((mTemperatureHigh != null) && (!mTemperatureHigh.equals(""))); } @Expose @SerializedName("temperature_low") private String mTemperatureLow = null; /** * @return Minimum temperature. */ public String getMinTemperature() { return (mTemperatureLow == null) ? "" : mTemperatureLow; } /** * @return TRUE if contains minimum temperature. */ public boolean hasMinTemperature() { return ((mTemperatureLow != null) && (!mTemperatureLow.equals(""))); } @Expose @SerializedName("description") private String mDescription = null; /** * @return Description. */ public String getDescription() { return (mDescription == null) ? "" : mDescription; } /** * @return TRUE if contains description. */ public boolean hasDescription() { return ((mDescription != null) && (!mDescription.equals(""))); } @Expose @SerializedName("exponent_type") private String[] mExponentType = null; /** * @return Exponent type. */ public String[] getExponentType() { return (mExponentType == null) ? new String[]{""} : mExponentType; } /** * @return TRUE if contains exponent type. */ public boolean hasExponentType() { return ((mExponentType != null) && (mExponentType.length > 0)); } @Expose @SerializedName("exponent_value") private String[] mExponentValue = null; /** * @return Exponent value. */ public String[] getExponentValue() { return (mExponentValue == null) ? new String[]{""} : mExponentValue; } /** * @return TRUE if contains exponent value. */ public boolean hasExponentValue() { return ((mExponentValue != null) && (mExponentValue.length > 0)); } @Expose @SerializedName("is_querying") private int mIsQuering = 0; /** * @return TRUE if this data is for the main query target. */ public boolean isQueryTarget() { return (mIsQuering == 1); } @Expose @SerializedName("pm25") private int mPM25 = -1; /** * @return PM 2.5. */ public int getPM25() { return mPM25; } }
0
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami/nli/DescObject.java
/* Copyright 2017, VIA Technologies, Inc. & OLAMI Team. http://olami.ai Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ai.olami.nli; import ai.olami.ids.IDSResult; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class DescObject { public static final int STATUS_SUCCESS = 0; public static final int STATUS_SELECTION_OVERFLOW = 1001; public static final int STATUS_NO_MATCHED_GRAMMAR = 1003; public static final int STATUS_INPUT_LENGTH_TOO_LONG = 1005; public static final int STATUS_TIMEOUT = 3001; public static final int STATUS_SERVER_ERROR= 3003; public static final int STATUS_EXCEPTION= 3004; public static final String TYPE_WEATHER = IDSResult.Types.WEATHER.getName(); public static final String TYPE_BAIKE = IDSResult.Types.BAIKE.getName(); public static final String TYPE_NEWS = IDSResult.Types.NEWS.getName(); public static final String TYPE_TV_PROGRAM = IDSResult.Types.TV_PROGRAM.getName(); public static final String TYPE_POEM = IDSResult.Types.POEM.getName(); public static final String TYPE_JOKE = IDSResult.Types.JOKE.getName(); public static final String TYPE_STORY = "story"; public static final String TYPE_STOCK_MARKET = IDSResult.Types.STOCK_MARKET.getName(); public static final String TYPE_MATH = IDSResult.Types.MATH.getName(); public static final String TYPE_UNIT_CONVERT = IDSResult.Types.UNIT_CONVERT.getName(); public static final String TYPE_EXCHANGE_RATE = IDSResult.Types.EXCHANGE_RATE.getName(); public static final String TYPE_COOKING = IDSResult.Types.COOKING.getName(); public static final String TYPE_SEARCH = "search"; public static final String TYPE_SHOPPING = "shopping"; @Expose @SerializedName("result") protected String mResult = null; /** * Get a chat reply, the answer to the conversation text input. * If the input text not matches any grammar you configured on the NLI system, * the result will be automatically generated by OLAMI intelligent dialogue system. * * @return Chat reply text. */ public String getReplyAnswer() { return (mResult == null) ? "" : mResult; } /** * @return TRUE if contains chat reply. */ public boolean hasReplyAnswer() { return ((mResult != null) && (!mResult.equals(""))); } @Expose @SerializedName("status") protected int mStatus = 0; /** * Get the status of grammar analysis. * * @return 0 if system has understood the input statements, or others for other issues. */ public int getStatus() { return mStatus; } @Expose @SerializedName("type") protected String mType = null; /** * Get type name, it usually refers to the IDS module name. * * @return Type name. */ public String getType() { return (mType == null) ? "" : mType; } /** * @return TRUE if contains type information. */ public boolean hasType() { return ((mType != null) && (!mType.equals(""))); } @Expose @SerializedName("url") protected String mURL = null; /** * Get URL, it usually used in the IDS module. * * @return URL. */ public String getURL() { return (mURL == null) ? "" : mURL; } /** * @return TRUE if contains URL information. */ public boolean hasURL() { return ((mURL != null) && (!mURL.equals(""))); } @Expose @SerializedName("name") protected String mName = null; /** * Get Name information, it usually used in the IDS module. * * @return Name information. */ public String getName() { return (mName == null) ? "" : mName; } /** * @return TRUE if contains name information. */ public boolean hasName() { return ((mName != null) && (!mName.equals(""))); } @Expose @SerializedName("source_currency") protected String mSourceCurrency = null; /** * Get source currency information, it usually used in the IDS module. * * @return Name information. */ public String getSourceCurrency() { return (mSourceCurrency == null) ? "" : mSourceCurrency; } /** * @return TRUE if contains source currency information. */ public boolean hasSourceCurrency() { return ((mSourceCurrency != null) && (!mSourceCurrency.equals(""))); } }
0
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami/nli/NLIResult.java
/* Copyright 2017, VIA Technologies, Inc. & OLAMI Team. http://olami.ai Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ai.olami.nli; import java.util.ArrayList; import ai.olami.ids.IDSResult; import ai.olami.util.GsonFactory; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import com.google.gson.reflect.TypeToken; public class NLIResult { private Gson mGson = GsonFactory.getNormalGson(); @Expose @SerializedName("desc_obj") private DescObject mDescObject = null; /** * @return Description of the analysis results. */ public DescObject getDescObject() { return mDescObject; } /** * @return TRUE if contains description information. */ public boolean hasDescObject() { return (mDescObject != null); } @Expose @SerializedName("semantic") private Semantic[] mSemantics = null; /** * Get the semantics of input text. * * @return Semantic array */ public Semantic[] getSemantics() { return mSemantics; } /** * @return TRUE if contains semantics information. */ public boolean hasSemantics() { return ((mSemantics != null) && (mSemantics.length > 0)); } @Expose @SerializedName("type") private String mType = null; /** * @return Type information. */ public String getType() { return mType; } /** * @return TRUE if contains type information. */ public boolean hasType() { return ((mType != null) && (!mType.equals(""))); } /** * Check if this result is actually a IDS response. * * @return TRUE if this result is provided by the IDS. */ public boolean isFromIDS() { return (IDSResult.Types.contains(mType)); } @Expose @SerializedName("data_obj") private JsonElement mDataObjs = null; /** * @return List of data object * or list of JsonElement if the object type is not defined. */ public <T> ArrayList<T> getDataObjects() { if (isFromIDS()) { String typeName = mType; switch (IDSResult.Types.getByName(mType)) { case QUESTION: typeName = this.getDescObject().getType(); break; case CONFIRMATION: typeName = this.getDescObject().getType(); break; case SELECTION: typeName = this.getDescObject().getType(); break; default: break; } return mGson.fromJson(mDataObjs, IDSResult.Types.getDataArrayListType(typeName)); } else if (hasDataObjects()) { return mGson.fromJson(mDataObjs, new TypeToken<ArrayList<JsonElement>>() {}.getType()); } return null; } /** * @return TRUE if contains data contents. */ public boolean hasDataObjects() { return (mDataObjs != null); } }
0
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami/nli/Semantic.java
/* Copyright 2017, VIA Technologies, Inc. & OLAMI Team. http://olami.ai Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ai.olami.nli; import ai.olami.nli.slot.Slot; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class Semantic { @Expose @SerializedName("modifier") private String[] mGlobalModifiers = null; /** * @return Global modifiers */ public String[] getGlobalModifiers() { return mGlobalModifiers; } /** * @return TRUE if contains GlobalModifier information. */ public boolean hasGlobalModifiers() { return ((mGlobalModifiers != null) && (mGlobalModifiers.length > 0)); } @Expose @SerializedName("app") private String mAppModule = null; /** * Get the grammar module name. (Usually defined on the NLI system) * * @return Module name. */ public String getAppModule() { return mAppModule; } /** * @return TRUE if contains AppModule information. */ public boolean hasAppModule() { return ((mAppModule != null) && (!mAppModule.equals(""))); } @Expose @SerializedName("input") private String mInput = null; /** * @return The original input text. */ public String getInput() { return mInput; } /** * @return TRUE if contains Input information. */ public boolean hasInput() { return ((mInput != null) && (!mInput.equals(""))); } @Expose @SerializedName("slots") private Slot[] mSlots = null; /** * @return Slot array. */ public Slot[] getSlots() { return mSlots; } /** * @return TRUE if contains Slots information. */ public boolean hasSlots() { return ((mSlots != null) && (mSlots.length > 0)); } }
0
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami/nli
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami/nli/slot/DateTime.java
/* Copyright 2017, VIA Technologies, Inc. & OLAMI Team. http://olami.ai Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ai.olami.nli.slot; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class DateTime { public static final String TYPE_TIME_RECOMMEND = "time_recommend"; public static final String TYPE_SEMANTIC = "time_semantic"; public static final String TYPE_INVALID = "invalid"; @Expose @SerializedName("type") private String mType = null; /** * @return Date time type. */ public String getType() { return mType.toLowerCase(); } /** * @return TRUE if contains Type information. */ public boolean hasType() { return ((mType != null) && (!mType.equals(""))); } @Expose @SerializedName("data") private DateTimeData mDatetimeData = null; /** * @return Detailed information. */ public DateTimeData getData() { return mDatetimeData; } /** * @return TRUE if contains Data information. */ public boolean hasData() { return (mDatetimeData != null); } }
0
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami/nli
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami/nli/slot/DateTimeData.java
/* Copyright 2017, VIA Technologies, Inc. & OLAMI Team. http://olami.ai Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ai.olami.nli.slot; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class DateTimeData { public static final String SUB_TYPE_DURATION = "duration"; public static final String SUB_TYPE_REPEAT = "repeat"; @Expose @SerializedName("start_time") private long mStartTime = -1; /** * @return Start time. */ public long getStartTime() { return mStartTime; } @Expose @SerializedName("end_time") private long mEndTime = -1; /** * @return End time. */ public long getEndTime() { return mEndTime; } @Expose @SerializedName("sub_type") private String mSubType = null; /** * @return Sub type. */ public String getSubType() { return mSubType.toLowerCase(); } /** * @return TRUE if contains SubType information. */ public boolean hasSubType() { return ((mSubType != null) && (!mSubType.equals(""))); } @Expose @SerializedName("time_struct") private TimeStruct mTimeStruct = null; /** * @return The structure that describes the time period or the repetition. */ public TimeStruct getTimeStruct() { return mTimeStruct; } /** * @return TRUE if contains TimeStruct information. */ public boolean hasTimeStruct() { return (mTimeStruct != null); } }
0
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami/nli
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami/nli/slot/ExtendInfo.java
/* Copyright 2017, VIA Technologies, Inc. & OLAMI Team. http://olami.ai Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ai.olami.nli.slot; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class ExtendInfo { @Expose @SerializedName("Month") private int mMonth = -1; public int getMonth() { return mMonth; } @Expose @SerializedName("Day") private int mDay = -1; public int getDay() { return mDay; } @Expose @SerializedName("Hour") private int mHour = -1; public int getHour() { return mHour; } @Expose @SerializedName("Minute") private int mMinute = -1; public int getMinute() { return mMinute; } @Expose @SerializedName("Second") private int mSecond = -1; public int getSecond() { return mSecond; } @Expose @SerializedName("DayOfWeek") private int mDayOfWeek = -1; public int getDayOfWeek() { return mDayOfWeek; } @Expose @SerializedName("festival") private String mFestival = null; /** * @return Festival or holiday name. */ public String getFestival() { return mFestival; } /** * @return TRUE if contains Festival information. */ public boolean hasFestival() { return ((mFestival != null) && (!mFestival.equals(""))); } @Expose @SerializedName("jieqi") private String mJieqi = null; /** * @return Name of the Solar Terms. */ public String getJieqi() { return mJieqi; } /** * @return TRUE if contains Jieqi information. */ public boolean hasJieqi() { return ((mJieqi != null) && (!mJieqi.equals(""))); } }
0
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami/nli
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami/nli/slot/NumDetail.java
/* Copyright 2017, VIA Technologies, Inc. & OLAMI Team. http://olami.ai Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ai.olami.nli.slot; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class NumDetail { public static final String TYPE_NUMBER = "number"; public static final String TYPE_FLOAT = "float"; @Expose @SerializedName("recommend_value") private String mRecommendValue = null; /** * @return Recommend value. */ public String getRecommendValue() { return mRecommendValue; } /** * @return TRUE if contains RecommendValue information. */ public boolean hasRecommendValue() { return ((mRecommendValue != null) && (!mRecommendValue.equals(""))); } @Expose @SerializedName("type") private String mType = null; /** * @return The type of the number. */ public String getType() { return mType.toLowerCase(); } /** * @return TRUE if contains Type information. */ public boolean hasType() { return ((mType != null) && (!mType.equals(""))); } }
0
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami/nli
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami/nli/slot/RepeatRule.java
/* Copyright 2017, VIA Technologies, Inc. & OLAMI Team. http://olami.ai Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ai.olami.nli.slot; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class RepeatRule { public static final String INTERVAL_UNIT_YEAR = "Year"; public static final String INTERVAL_UNIT_MONTH = "Month"; public static final String INTERVAL_UNIT_DAY = "Day"; public static final String INTERVAL_UNIT_HOUR = "Hour"; public static final String INTERVAL_UNIT_MINUTE = "Minute"; public static final String INTERVAL_UNIT_SECOND = "Second"; public static final String INTERVAL_UNIT_WEEK = "Week"; public static final String INTERVAL_UNIT_INVALID = "Invalid"; @Expose @SerializedName("IntervalUnit") private String mIntervalUnit = null; /** * @return The unit of the repetition. */ public String getIntervalUnit() { return mIntervalUnit; } /** * @return TRUE if contains IntervalUnit information. */ public boolean hasIntervalUnit() { return ((mIntervalUnit != null) && (!mIntervalUnit.equals(""))); } @Expose @SerializedName("IntervalValue") private int mIntervalValue = -1; /** * @return The value of the repetition. */ public int getIntervalValue() { return mIntervalValue; } }
0
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami/nli
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami/nli/slot/Slot.java
/* Copyright 2017, VIA Technologies, Inc. & OLAMI Team. http://olami.ai Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ai.olami.nli.slot; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class Slot { @Expose @SerializedName("name") private String mName = null; /** * @return Slot name. */ public String getName() { return mName; } /** * @return TRUE if contains Name information. */ public boolean hasName() { return ((mName != null) && (!mName.equals(""))); } @Expose @SerializedName("value") private String mValue = null; /** * @return Slot value. */ public String getValue() { return mValue; } /** * @return TRUE if contains Value information. */ public boolean hasValue() { return ((mValue != null) && (!mValue.equals(""))); } @Expose @SerializedName("modifier") private String[] mModifiers = null; /** * @return Slot modifier. */ public String[] getModifiers() { return mModifiers; } /** * @return TRUE if contains Modifier information. */ public boolean hasModifiers() { return ((mModifiers != null) && (mModifiers.length > 0)); } @Expose @SerializedName("datetime") private DateTime mDateTime = null; /** * @return Date time analysis results. */ public DateTime getDateTime() { return mDateTime; } /** * @return TRUE if contains DateTime information. */ public boolean hasDateTime() { return (mDateTime != null); } @Expose @SerializedName("num_detail") private NumDetail mNumDetail = null; /** * @return The detailed information of the number slot. */ public NumDetail getNumDetail() { return mNumDetail; } /** * @return TRUE if contains NumDetail information. */ public boolean hasNumDetail() { return (mNumDetail != null); } }
0
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami/nli
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami/nli/slot/TimeStruct.java
/* Copyright 2017, VIA Technologies, Inc. & OLAMI Team. http://olami.ai Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ai.olami.nli.slot; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class TimeStruct { @Expose @SerializedName("Year") private int mYear = -1; public int getYear() { return mYear; } @Expose @SerializedName("Month") private int mMonth = -1; public int getMonth() { return mMonth; } @Expose @SerializedName("Day") private int mDay = -1; public int getDay() { return mDay; } @Expose @SerializedName("Hour") private int mHour = -1; public int getHour() { return mHour; } @Expose @SerializedName("Minute") private int mMinute = -1; public int getMinute() { return mMinute; } @Expose @SerializedName("Second") private int mSecond = -1; public int getSecond() { return mSecond; } @Expose @SerializedName("Week") private int mWeek = -1; public int getWeek() { return mWeek; } @Expose @SerializedName("repeat_rule") private RepeatRule mRepeatRule = null; /** * @return The structure that describes repetition rule. */ public RepeatRule getRepeatRule() { return mRepeatRule; } /** * @return TRUE if contains RepeatRule information. */ public boolean hasRepeatRule() { return (mRepeatRule != null); } @Expose @SerializedName("extend_info") private ExtendInfo mExtendInfo = null; /** * @return Extra information. */ public ExtendInfo getExtendInfo() { return mExtendInfo; } /** * @return TRUE if contains ExtendInfo information. */ public boolean hasExtendInfo() { return (mExtendInfo != null); } }
0
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami/util/GsonFactory.java
/* Copyright 2017, VIA Technologies, Inc. & OLAMI Team. http://olami.ai Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ai.olami.util; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class GsonFactory { private static Gson mDefaultGson = new GsonBuilder() .excludeFieldsWithoutExposeAnnotation().create(); private static Gson mDebugGson = new GsonBuilder() .setPrettyPrinting() .create(); private static Gson mDebugGsonWithoutEA = new GsonBuilder() .setPrettyPrinting() .excludeFieldsWithoutExposeAnnotation() .create(); /** * Create a new Gson instance with excludeFieldsWithoutExposeAnnotation(). * * @return GsonBuilder. */ public static Gson getNormalGson() { return mDefaultGson; } /** * Create a new Gson instance with PrettyPrinting. * * @param exposeAll - TRUE to create without excludeFieldsWithoutExposeAnnotation(). * @return Gson */ public static Gson getDebugGson(boolean exposeAll) { if (exposeAll) { return mDebugGson; } return mDebugGsonWithoutEA; } }
0
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami
java-sources/ai/olami/olami-java-client/1.5.0/ai/olami/util/HttpClient.java
/* Copyright 2017, VIA Technologies, Inc. & OLAMI Team. http://olami.ai Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ai.olami.util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; public class HttpClient { private final HttpURLConnection mHttpConnection; private OutputStream mOutStream = null; /** * HTTP connection utility. * * @param httpConnection - HttpURLConnection target. */ public HttpClient(final HttpURLConnection httpConnection) { if (httpConnection == null) { throw new IllegalArgumentException("HttpURLConnection is null."); } mHttpConnection = httpConnection; } /** * Connect without stream data output. * * @throws IOException HTTP connection failed. */ public void normalConnect() throws IOException { mHttpConnection.connect(); } /** * Connect with stream data output and send queries by a string. * * @param queryParams - A string that contains query parameters. * @throws IOException HTTP connection failed. */ public void postQueryConnect(final String queryParams) throws IOException { mHttpConnection.setDoOutput(true); mOutStream = mHttpConnection.getOutputStream(); if (!queryParams.startsWith("&")) { mOutStream.write("&".getBytes("utf-8")); } mOutStream.write(queryParams.getBytes("utf-8")); mOutStream.flush(); mOutStream.close(); } /** * Connect with stream data output and send queries. * * @param queryParams - Key-Value query parameters. * @throws IOException HTTP connection failed. */ public void postQueryConnect(Map<String, String> queryParams) throws IOException { StringBuffer queryParamsStringBuffer = new StringBuffer(); if (queryParams != null) { for (Object key : queryParams.keySet()) { queryParamsStringBuffer.append("&"); queryParamsStringBuffer.append(key.toString()); queryParamsStringBuffer.append("="); queryParamsStringBuffer.append(queryParams.get(key)); } } postQueryConnect(queryParamsStringBuffer.toString()); } /** * Connect and send data by "Content-Type: application/octet-stream". * * @param streamBuffer - The buffer that contains data you want to send. * @param writeBytes - How many bytes you want to send in this buffer. * @throws IOException HTTP connection failed. */ public void octetStreamConnect( final byte[] streamBuffer, final int writeBytes ) throws IOException { mHttpConnection.setDoOutput(true); mHttpConnection.setRequestProperty("Connection", "Keep-Alive"); mHttpConnection.setRequestProperty("Content-Type", "application/octet-stream"); mOutStream = mHttpConnection.getOutputStream(); mOutStream.write(streamBuffer, 0, writeBytes); mOutStream.flush(); mOutStream.close(); } /** * Get the response content after the connection. * * @return Response content. * @throws IOException - HTTP connection failed. */ public String getResponseContent() throws IOException { BufferedReader inputReader = null; StringBuffer inputStringBuffer = new StringBuffer(); try { inputReader = new BufferedReader(new InputStreamReader( mHttpConnection.getInputStream(), StandardCharsets.UTF_8)); String inputLine; while ((inputLine = inputReader.readLine()) != null) { inputStringBuffer.append(inputLine); } inputReader.close(); } finally { if (inputReader != null) { inputReader.close(); } } return inputStringBuffer.toString(); } /** * Get the response code after the connection. * * @return Response Code. * @throws IOException - HTTP connection failed. */ public int getResponseCode() throws IOException { return mHttpConnection.getResponseCode(); } /** * Get the response message after the connection. * * @return Response message. * @throws IOException - HTTP connection failed. */ public String getResponseMessage() throws IOException { return mHttpConnection.getResponseMessage(); } /** * Get the Cookies after the connection. * * @return Cookies. */ public List<String> getCookies() { return mHttpConnection.getHeaderFields().get("Set-Cookie"); } /** * Close connection and all possible resources. * * @throws IOException - HTTP connection failed. */ public void close() throws IOException { if (mOutStream != null) { mOutStream.close(); } if (mHttpConnection != null) { mHttpConnection.disconnect(); } } }
0
java-sources/ai/olami/olami-java-client/1.5.0/org/xiph
java-sources/ai/olami/olami-java-client/1.5.0/org/xiph/speex/AudioFileWriter.java
/****************************************************************************** * * * Copyright (c) 1999-2004 Wimba S.A., All Rights Reserved. * * * * COPYRIGHT: * * This software is the property of Wimba S.A. * * This software is redistributed under the Xiph.org variant of * * the BSD license. * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions * * are met: * * - Redistributions of source code must retain the above copyright * * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in the * * documentation and/or other materials provided with the distribution. * * - Neither the name of Wimba, the Xiph.org Foundation nor the names of * * its contributors may be used to endorse or promote products derived * * from this software without specific prior written permission. * * * * WARRANTIES: * * This software is made available by the authors in the hope * * that it will be useful, but without any warranty. * * Wimba S.A. is not liable for any consequence related to the * * use of the provided software. * * * * Class: RawWriter.java * * * * Author: Marc GIMPEL * * * * Date: 6th January 2004 * * * ******************************************************************************/ /* $Id: AudioFileWriter.java,v 1.2 2004/10/21 16:21:57 mgimpel Exp $ */ package org.xiph.speex; import java.io.DataOutput; import java.io.File; import java.io.IOException; import java.io.OutputStream; /** * Abstract Class that defines an Audio File Writer. * * @author Marc Gimpel, Wimba S.A. (mgimpel@horizonwimba.com) * @version $Revision: 1.2 $ */ public abstract class AudioFileWriter { /** * Closes the output file. * @exception IOException if there was an exception closing the Audio Writer. */ public abstract void close() throws IOException; /** * Open the output file. * @param file - file to open. * @exception IOException if there was an exception opening the Audio Writer. */ public abstract void open(File file) throws IOException; /** * Open the output file. * @param filename - file to open. * @exception IOException if there was an exception opening the Audio Writer. */ public abstract void open(String filename) throws IOException; /** * Writes the header pages that start the Ogg Speex file. * Prepares file for data to be written. * @param comment description to be included in the header. * @exception IOException */ public abstract void writeHeader(String comment) throws IOException; /** * Writes a packet of audio. * @param data audio data * @param offset the offset from which to start reading the data. * @param len the length of data to read. * @exception IOException */ public abstract void writePacket(byte[] data, int offset, int len) throws IOException; /** * Writes an Ogg Page Header to the given byte array. * @param buf the buffer to write to. * @param offset the from which to start writing. * @param headerType the header type flag * (0=normal, 2=bos: beginning of stream, 4=eos: end of stream). * @param granulepos the absolute granule position. * @param streamSerialNumber * @param pageCount * @param packetCount * @param packetSizes * @return the amount of data written to the buffer. */ public static int writeOggPageHeader(byte[] buf, int offset, int headerType, long granulepos, int streamSerialNumber, int pageCount, int packetCount, byte[] packetSizes) { writeString(buf, offset, "OggS"); // 0 - 3: capture_pattern buf[offset+4] = 0; // 4: stream_structure_version buf[offset+5] = (byte) headerType; // 5: header_type_flag writeLong(buf, offset+6, granulepos); // 6 - 13: absolute granule position writeInt(buf, offset+14, streamSerialNumber); // 14 - 17: stream serial number writeInt(buf, offset+18, pageCount); // 18 - 21: page sequence no writeInt(buf, offset+22, 0); // 22 - 25: page checksum buf[offset+26] = (byte) packetCount; // 26: page_segments System.arraycopy(packetSizes, 0, // 27 - x: segment_table buf, offset+27, packetCount); return packetCount+27; } /** * Builds and returns an Ogg Page Header. * @param headerType the header type flag * (0=normal, 2=bos: beginning of stream, 4=eos: end of stream). * @param granulepos the absolute granule position. * @param streamSerialNumber * @param pageCount * @param packetCount * @param packetSizes * @return an Ogg Page Header. */ public static byte[] buildOggPageHeader(int headerType, long granulepos, int streamSerialNumber, int pageCount, int packetCount, byte[] packetSizes) { byte[] data = new byte[packetCount+27]; writeOggPageHeader(data, 0, headerType, granulepos, streamSerialNumber, pageCount, packetCount, packetSizes); return data; } /** * Writes a Speex Header to the given byte array. * @param buf the buffer to write to. * @param offset the from which to start writing. * @param sampleRate * @param mode * @param channels * @param vbr * @param nframes * @return the amount of data written to the buffer. */ public static int writeSpeexHeader(byte[] buf, int offset, int sampleRate, int mode, int channels, boolean vbr, int nframes) { writeString(buf, offset, "Speex "); // 0 - 7: speex_string writeString(buf, offset+8, "speex-1.0"); // 8 - 27: speex_version System.arraycopy(new byte[11], 0, buf, offset+17, 11); // : speex_version (fill in up to 20 bytes) writeInt(buf, offset+28, 1); // 28 - 31: speex_version_id writeInt(buf, offset+32, 80); // 32 - 35: header_size writeInt(buf, offset+36, sampleRate); // 36 - 39: rate writeInt(buf, offset+40, mode); // 40 - 43: mode (0=NB, 1=WB, 2=UWB) writeInt(buf, offset+44, 4); // 44 - 47: mode_bitstream_version writeInt(buf, offset+48, channels); // 48 - 51: nb_channels writeInt(buf, offset+52, -1); // 52 - 55: bitrate writeInt(buf, offset+56, 160 << mode); // 56 - 59: frame_size (NB=160, WB=320, UWB=640) writeInt(buf, offset+60, vbr?1:0); // 60 - 63: vbr writeInt(buf, offset+64, nframes); // 64 - 67: frames_per_packet writeInt(buf, offset+68, 0); // 68 - 71: extra_headers writeInt(buf, offset+72, 0); // 72 - 75: reserved1 writeInt(buf, offset+76, 0); // 76 - 79: reserved2 return 80; } /** * Builds a Speex Header. * @param sampleRate * @param mode * @param channels * @param vbr * @param nframes * @return a Speex Header. */ public static byte[] buildSpeexHeader(int sampleRate, int mode, int channels, boolean vbr, int nframes) { byte[] data = new byte[80]; writeSpeexHeader(data, 0, sampleRate, mode, channels, vbr, nframes); return data; } /** * Writes a Speex Comment to the given byte array. * @param buf the buffer to write to. * @param offset the from which to start writing. * @param comment the comment. * @return the amount of data written to the buffer. */ public static int writeSpeexComment(byte[] buf, int offset, String comment) { int length = comment.length(); writeInt(buf, offset, length); // vendor comment size writeString(buf, offset+4, comment); // vendor comment writeInt(buf, offset+length+4, 0); // user comment list length return length+8; } /** * Builds and returns a Speex Comment. * @param comment the comment. * @return a Speex Comment. */ public static byte[] buildSpeexComment(String comment) { byte[] data = new byte[comment.length()+8]; writeSpeexComment(data, 0, comment); return data; } /** * Writes a Little-endian short. * @param out the data output to write to. * @param v value to write. * @exception IOException */ public static void writeShort(DataOutput out, short v) throws IOException { out.writeByte((0xff & v)); out.writeByte((0xff & (v >>> 8))); } /** * Writes a Little-endian int. * @param out the data output to write to. * @param v value to write. * @exception IOException */ public static void writeInt(DataOutput out, int v) throws IOException { out.writeByte(0xff & v); out.writeByte(0xff & (v >>> 8)); out.writeByte(0xff & (v >>> 16)); out.writeByte(0xff & (v >>> 24)); } /** * Writes a Little-endian short. * @param os - the output stream to write to. * @param v - the value to write. * @exception IOException */ public static void writeShort(OutputStream os, short v) throws IOException { os.write((0xff & v)); os.write((0xff & (v >>> 8))); } /** * Writes a Little-endian int. * @param os - the output stream to write to. * @param v - the value to write. * @exception IOException */ public static void writeInt(OutputStream os, int v) throws IOException { os.write(0xff & v); os.write(0xff & (v >>> 8)); os.write(0xff & (v >>> 16)); os.write(0xff & (v >>> 24)); } /** * Writes a Little-endian long. * @param os - the output stream to write to. * @param v - the value to write. * @exception IOException */ public static void writeLong(OutputStream os, long v) throws IOException { os.write((int)(0xff & v)); os.write((int)(0xff & (v >>> 8))); os.write((int)(0xff & (v >>> 16))); os.write((int)(0xff & (v >>> 24))); os.write((int)(0xff & (v >>> 32))); os.write((int)(0xff & (v >>> 40))); os.write((int)(0xff & (v >>> 48))); os.write((int)(0xff & (v >>> 56))); } /** * Writes a Little-endian short. * @param data the array into which the data should be written. * @param offset the offset from which to start writing in the array. * @param v the value to write. */ public static void writeShort(byte[] data, int offset, int v) { data[offset] = (byte) (0xff & v); data[offset+1] = (byte) (0xff & (v >>> 8)); } /** * Writes a Little-endian int. * @param data the array into which the data should be written. * @param offset the offset from which to start writing in the array. * @param v the value to write. */ public static void writeInt(byte[] data, int offset, int v) { data[offset] = (byte) (0xff & v); data[offset+1] = (byte) (0xff & (v >>> 8)); data[offset+2] = (byte) (0xff & (v >>> 16)); data[offset+3] = (byte) (0xff & (v >>> 24)); } /** * Writes a Little-endian long. * @param data the array into which the data should be written. * @param offset the offset from which to start writing in the array. * @param v the value to write. */ public static void writeLong(byte[] data, int offset, long v) { data[offset] = (byte) (0xff & v); data[offset+1] = (byte) (0xff & (v >>> 8)); data[offset+2] = (byte) (0xff & (v >>> 16)); data[offset+3] = (byte) (0xff & (v >>> 24)); data[offset+4] = (byte) (0xff & (v >>> 32)); data[offset+5] = (byte) (0xff & (v >>> 40)); data[offset+6] = (byte) (0xff & (v >>> 48)); data[offset+7] = (byte) (0xff & (v >>> 56)); } /** * Writes a String. * @param data the array into which the data should be written. * @param offset the offset from which to start writing in the array. * @param v the value to write. */ public static void writeString(byte[] data, int offset, String v) { byte[] str = v.getBytes(); System.arraycopy(str, 0, data, offset, str.length); } }
0
java-sources/ai/olami/olami-java-client/1.5.0/org/xiph
java-sources/ai/olami/olami-java-client/1.5.0/org/xiph/speex/Bits.java
/****************************************************************************** * * * Copyright (c) 1999-2003 Wimba S.A., All Rights Reserved. * * * * COPYRIGHT: * * This software is the property of Wimba S.A. * * This software is redistributed under the Xiph.org variant of * * the BSD license. * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions * * are met: * * - Redistributions of source code must retain the above copyright * * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in the * * documentation and/or other materials provided with the distribution. * * - Neither the name of Wimba, the Xiph.org Foundation nor the names of * * its contributors may be used to endorse or promote products derived * * from this software without specific prior written permission. * * * * WARRANTIES: * * This software is made available by the authors in the hope * * that it will be useful, but without any warranty. * * Wimba S.A. is not liable for any consequence related to the * * use of the provided software. * * * * Class: Bits.java * * * * Author: James LAWRENCE * * Modified by: Marc GIMPEL * * Based on code by: Jean-Marc VALIN * * * * Date: March 2003 * * * ******************************************************************************/ /* $Id: Bits.java,v 1.2 2004/10/21 16:21:57 mgimpel Exp $ */ /* Copyright (C) 2002 Jean-Marc Valin Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the Xiph.org Foundation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.xiph.speex; /** * Speex bit packing and unpacking class. * * @author Jim Lawrence, helloNetwork.com * @author Marc Gimpel, Wimba S.A. (mgimpel@horizonwimba.com) * @version $Revision: 1.2 $ */ public class Bits { /** Default buffer size */ public static final int DEFAULT_BUFFER_SIZE = 1024; /** "raw" data */ private byte[] bytes; /** Position of the byte "cursor" */ private int bytePtr; /** Position of the bit "cursor" within the current byte */ private int bitPtr; /** * Initialise the bit packing variables. */ public void init() { bytes = new byte[DEFAULT_BUFFER_SIZE]; bytePtr=0; bitPtr=0; } /** * Advance n bits. * @param n - the number of bits to advance. */ public void advance(final int n) { bytePtr += n >> 3; bitPtr += n & 7; if (bitPtr>7) { bitPtr-=8; bytePtr++; } } /** * Sets the buffer to the given value. * @param newBuffer */ protected void setBuffer(final byte[] newBuffer) { bytes = newBuffer; } /** * Take a peek at the next bit. * @return the next bit. */ public int peek() { return ((bytes[bytePtr] & 0xFF) >> (7-bitPtr)) & 1; } /** * Read the given array into the buffer. * @param newbytes * @param offset * @param len */ public void read_from(final byte[] newbytes, final int offset, final int len) { for (int i=0; i<len; i++) bytes[i]=newbytes[offset+i]; bytePtr=0; bitPtr=0; } /** * Read the next N bits from the buffer. * @param nbBits - the number of bits to read. * @return the next N bits from the buffer. */ public int unpack(int nbBits) { int d=0; while (nbBits!=0) { d<<=1; d |= ((bytes[bytePtr] & 0xFF)>>(7-bitPtr))&1; bitPtr++; if (bitPtr==8) { bitPtr=0; bytePtr++; } nbBits--; } return d; } /** * Write N bits of the given data to the buffer. * @param data - the data to write. * @param nbBits - the number of bits of the data to write. */ public void pack(int data, int nbBits) { int d=data; while (bytePtr+((nbBits+bitPtr)>>3) >= bytes.length) { // System.err.println("Buffer too small to pack bits"); /* Expand the buffer as needed. */ int size = bytes.length*2; byte[] tmp = new byte[size]; System.arraycopy(bytes, 0, tmp, 0, bytes.length); bytes = tmp; } while (nbBits>0) { int bit; bit = (d>>(nbBits-1))&1; bytes[bytePtr] |= bit<<(7-bitPtr); bitPtr++; if (bitPtr==8) { bitPtr=0; bytePtr++; } nbBits--; } } /** * Returns the current buffer array. * @return the current buffer array. */ public byte[] getBuffer() { return bytes; } /** * Returns the number of bytes used in the current buffer. * @return the number of bytes used in the current buffer. */ public int getBufferSize() { return bytePtr + (bitPtr > 0 ? 1 : 0); } }
0
java-sources/ai/olami/olami-java-client/1.5.0/org/xiph
java-sources/ai/olami/olami-java-client/1.5.0/org/xiph/speex/CbSearch.java
/****************************************************************************** * * * Copyright (c) 1999-2003 Wimba S.A., All Rights Reserved. * * * * COPYRIGHT: * * This software is the property of Wimba S.A. * * This software is redistributed under the Xiph.org variant of * * the BSD license. * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions * * are met: * * - Redistributions of source code must retain the above copyright * * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in the * * documentation and/or other materials provided with the distribution. * * - Neither the name of Wimba, the Xiph.org Foundation nor the names of * * its contributors may be used to endorse or promote products derived * * from this software without specific prior written permission. * * * * WARRANTIES: * * This software is made available by the authors in the hope * * that it will be useful, but without any warranty. * * Wimba S.A. is not liable for any consequence related to the * * use of the provided software. * * * * Class: CbSearch.java * * * * Author: James LAWRENCE * * Modified by: Marc GIMPEL * * Based on code by: Jean-Marc VALIN * * * * Date: March 2003 * * * ******************************************************************************/ /* $Id: CbSearch.java,v 1.2 2004/10/21 16:21:57 mgimpel Exp $ */ /* Copyright (C) 2002 Jean-Marc Valin Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the Xiph.org Foundation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.xiph.speex; /** * Abstract class that is the base for the various Codebook search methods. * * @author Jim Lawrence, helloNetwork.com * @author Marc Gimpel, Wimba S.A. (mgimpel@horizonwimba.com) * @version $Revision: 1.2 $ */ public abstract class CbSearch { /** * Codebook Search Quantification. * @param target target vector * @param ak LPCs for this subframe * @param awk1 Weighted LPCs for this subframe * @param awk2 Weighted LPCs for this subframe * @param p number of LPC coeffs * @param nsf number of samples in subframe * @param exc excitation array. * @param es position in excitation array. * @param r * @param bits Speex bits buffer. * @param complexity */ public abstract void quant(float[] target, float[] ak, float[] awk1, float[] awk2, int p, int nsf, float[] exc, int es, float[] r, Bits bits, int complexity); /** * Codebook Search Unquantification. * @param exc - excitation array. * @param es - position in excitation array. * @param nsf - number of samples in subframe. * @param bits - Speex bits buffer. */ public abstract void unquant(float[] exc, int es, int nsf, Bits bits); }
0
java-sources/ai/olami/olami-java-client/1.5.0/org/xiph
java-sources/ai/olami/olami-java-client/1.5.0/org/xiph/speex/Codebook.java
/****************************************************************************** * * * Copyright (c) 1999-2003 Wimba S.A., All Rights Reserved. * * * * COPYRIGHT: * * This software is the property of Wimba S.A. * * This software is redistributed under the Xiph.org variant of * * the BSD license. * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions * * are met: * * - Redistributions of source code must retain the above copyright * * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in the * * documentation and/or other materials provided with the distribution. * * - Neither the name of Wimba, the Xiph.org Foundation nor the names of * * its contributors may be used to endorse or promote products derived * * from this software without specific prior written permission. * * * * WARRANTIES: * * This software is made available by the authors in the hope * * that it will be useful, but without any warranty. * * Wimba S.A. is not liable for any consequence related to the * * use of the provided software. * * * * Class: Codebook.java * * * * Author: James LAWRENCE * * Modified by: Marc GIMPEL * * Based on code by: Jean-Marc VALIN * * * * Date: March 2003 * * * ******************************************************************************/ /* $Id: Codebook.java,v 1.2 2004/10/21 16:21:57 mgimpel Exp $ */ /* Copyright (C) 2002 Jean-Marc Valin Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the Xiph.org Foundation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.xiph.speex; /** * Codebook tables * * @author Jim Lawrence, helloNetwork.com * @author Marc Gimpel, Wimba S.A. (mgimpel@horizonwimba.com) * @version $Revision: 1.2 $ */ public interface Codebook { /** * Excitation Codebook */ public static final int[] exc_20_32_table = { 12,32,25,46,36,33,9,14,-3,6,1,-8,0,-10,-5,-7,-7,-7,-5,-5, 31,-27,24,-32,-4,10,-11,21,-3,19,23,-9,22,24,-10,-1,-10,-13,-7,-11, 42,-33,31,19,-8,0,-10,-16,1,-21,-17,10,-8,14,8,4,11,-2,5,-2, -33,11,-16,33,11,-4,9,-4,11,2,6,-5,8,-5,11,-4,-6,26,-36,-16, 0,4,-2,-8,12,6,-1,34,-46,-22,9,9,21,9,5,-66,-5,26,2,10, 13,2,19,9,12,-81,3,13,13,0,-14,22,-35,6,-7,-4,6,-6,10,-6, -31,38,-33,0,-10,-11,5,-12,12,-17,5,0,-6,13,-9,10,8,25,33,2, -12,8,-6,10,-2,21,7,17,43,5,11,-7,-9,-20,-36,-20,-23,-4,-4,-3, 27,-9,-9,-49,-39,-38,-11,-9,6,5,23,25,5,3,3,4,1,2,-3,-1, 87,39,17,-21,-9,-19,-9,-15,-13,-14,-17,-11,-10,-11,-8,-6,-1,-3,-3,-1, -54,-34,-27,-8,-11,-4,-5,0,0,4,8,6,9,7,9,7,6,5,5,5, 48,10,19,-10,12,-1,9,-3,2,5,-3,2,-2,-2,0,-2,-26,6,9,-7, -16,-9,2,7,7,-5,-43,11,22,-11,-9,34,37,-15,-13,-6,1,-1,1,1, -64,56,52,-11,-27,5,4,3,1,2,1,3,-1,-4,-4,-10,-7,-4,-4,2, -1,-7,-7,-12,-10,-15,-9,-5,-5,-11,-16,-13,6,16,4,-13,-16,-10,-4,2, -47,-13,25,47,19,-14,-20,-8,-17,0,-3,-13,1,6,-17,-14,15,1,10,6, -24,0,-10,19,-69,-8,14,49,17,-5,33,-29,3,-4,0,2,-8,5,-6,2, 120,-56,-12,-47,23,-9,6,-5,1,2,-5,1,-10,4,-1,-1,4,-1,0,-3, 30,-52,-67,30,22,11,-1,-4,3,0,7,2,0,1,-10,-4,-8,-13,5,1, 1,-1,5,13,-9,-3,-10,-62,22,48,-4,-6,2,3,5,1,1,4,1,13, 3,-20,10,-9,13,-2,-4,9,-20,44,-1,20,-32,-67,19,0,28,11,8,2, -11,15,-19,-53,31,2,34,10,6,-4,-58,8,10,13,14,1,12,2,0,0, -128,37,-8,44,-9,26,-3,18,2,6,11,-1,9,1,5,3,0,1,1,2, 12,3,-2,-3,7,25,9,18,-6,-37,3,-8,-16,3,-10,-7,17,-34,-44,11, 17,-15,-3,-16,-1,-13,11,-46,-65,-2,8,13,2,4,4,5,15,5,9,6, 8,2,8,3,10,-1,3,-3,6,-2,3,3,-5,10,-11,7,6,-2,6,-2, -9,19,-12,12,-28,38,29,-1,12,2,5,23,-10,3,4,-15,21,-4,3,3, 6,17,-9,-4,-8,-20,26,5,-10,6,1,-19,18,-15,-12,47,-6,-2,-7,-9, -1,-17,-2,-2,-14,30,-14,2,-7,-4,-1,-12,11,-25,16,-3,-12,11,-7,7, -17,1,19,-28,31,-7,-10,7,-10,3,12,5,-16,6,24,41,-29,-54,0,1, 7,-1,5,-6,13,10,-4,-8,8,-9,-27,-53,-38,-1,10,19,17,16,12,12, 0,3,-7,-4,13,12,-31,-14,6,-5,3,5,17,43,50,25,10,1,-6,-2 }; /** * Excitation Codebook */ public static final int[] exc_10_16_table = { 22,39,14,44,11,35,-2,23,-4,6, 46,-28,13,-27,-23,12,4,20,-5,9, 37,-18,-23,23,0,9,-6,-20,4,-1, -17,-5,-4,17,0,1,9,-2,1,2, 2,-12,8,-25,39,15,9,16,-55,-11, 9,11,5,10,-2,-60,8,13,-6,11, -16,27,-47,-12,11,1,16,-7,9,-3, -29,9,-14,25,-19,34,36,12,40,-10, -3,-24,-14,-37,-21,-35,-2,-36,3,-6, 67,28,6,-17,-3,-12,-16,-15,-17,-7, -59,-36,-13,1,7,1,2,10,2,11, 13,10,8,-2,7,3,5,4,2,2, -3,-8,4,-5,6,7,-42,15,35,-2, -46,38,28,-20,-9,1,7,-3,0,-2, -5,-4,-2,-4,-8,-3,-8,-5,-7,-4, -15,-28,52,32,5,-5,-17,-20,-10,-1 }; /** * Excitation Codebook */ public static final int[] exc_10_32_table = { 7,17,17,27,25,22,12,4,-3,0, 28,-36,39,-24,-15,3,-9,15,-5,10, 31,-28,11,31,-21,9,-11,-11,-2,-7, -25,14,-22,31,4,-14,19,-12,14,-5, 4,-7,4,-5,9,0,-2,42,-47,-16, 1,8,0,9,23,-57,0,28,-11,6, -31,55,-45,3,-5,4,2,-2,4,-7, -3,6,-2,7,-3,12,5,8,54,-10, 8,-7,-8,-24,-25,-27,-14,-5,8,5, 44,23,5,-9,-11,-11,-13,-9,-12,-8, -29,-8,-22,6,-15,3,-12,-1,-5,-3, 34,-1,29,-16,17,-4,12,2,1,4, -2,-4,2,-1,11,-3,-52,28,30,-9, -32,25,44,-20,-24,4,6,-1,0,0, -3,7,-4,-4,-7,-6,-9,-2,-10,-7, -25,-10,22,29,13,-13,-22,-13,-4,0, -4,-16,10,15,-36,-24,28,25,-1,-3, 66,-33,-11,-15,6,0,3,4,-2,5, 24,-20,-47,29,19,-2,-4,-1,0,-1, -2,3,1,8,-11,5,5,-57,28,28, 0,-16,4,-4,12,-6,-1,2,-20,61, -9,24,-22,-42,29,6,17,8,4,2, -65,15,8,10,5,6,5,3,2,-2, -3,5,-9,4,-5,23,13,23,-3,-63, 3,-5,-4,-6,0,-3,23,-36,-46,9, 5,5,8,4,9,-5,1,-3,10,1, -6,10,-11,24,-47,31,22,-12,14,-10, 6,11,-7,-7,7,-31,51,-12,-6,7, 6,-17,9,-11,-20,52,-19,3,-6,-6, -8,-5,23,-41,37,1,-21,10,-14,8, 7,5,-15,-15,23,39,-26,-33,7,2, -32,-30,-21,-8,4,12,17,15,14,11 }; /** * Excitation Codebook */ public static final int[] exc_5_256_table = { -8,-37,5,-43,5, 73,61,39,12,-3, -61,-32,2,42,30, -3,17,-27,9,34, 20,-1,-5,2,23, -7,-46,26,53,-47, 20,-2,-33,-89,-51, -64,27,11,15,-34, -5,-56,25,-9,-1, -29,1,40,67,-23, -16,16,33,19,7, 14,85,22,-10,-10, -12,-7,-1,52,89, 29,11,-20,-37,-46, -15,17,-24,-28,24, 2,1,0,23,-101, 23,14,-1,-23,-18, 9,5,-13,38,1, -28,-28,4,27,51, -26,34,-40,35,47, 54,38,-54,-26,-6, 42,-25,13,-30,-36, 18,41,-4,-33,23, -32,-7,-4,51,-3, 17,-52,56,-47,36, -2,-21,36,10,8, -33,31,19,9,-5, -40,10,-9,-21,19, 18,-78,-18,-5,0, -26,-36,-47,-51,-44, 18,40,27,-2,29, 49,-26,2,32,-54, 30,-73,54,3,-5, 36,22,53,10,-1, -84,-53,-29,-5,3, -44,53,-51,4,22, 71,-35,-1,33,-5, -27,-7,36,17,-23, -39,16,-9,-55,-15, -20,39,-35,6,-39, -14,18,48,-64,-17, -15,9,39,81,37, -68,37,47,-21,-6, -104,13,6,9,-2, 35,8,-23,18,42, 45,21,33,-5,-49, 9,-6,-43,-56,39, 2,-16,-25,87,1, -3,-9,17,-25,-11, -9,-1,10,2,-14, -14,4,-1,-10,28, -23,40,-32,26,-9, 26,4,-27,-23,3, 42,-60,1,49,-3, 27,10,-52,-40,-2, 18,45,-23,17,-44, 3,-3,17,-46,52, -40,-47,25,75,31, -49,53,30,-30,-32, -36,38,-6,-15,-16, 54,-27,-48,3,38, -29,-32,-22,-14,-4, -23,-13,32,-39,9, 8,-45,-13,34,-16, 49,40,32,31,28, 23,23,32,47,59, -68,8,62,44,25, -14,-24,-65,-16,36, 67,-25,-38,-21,4, -33,-2,42,5,-63, 40,11,26,-42,-23, -61,79,-31,23,-20, 10,-32,53,-25,-36, 10,-26,-5,3,0, -71,5,-10,-37,1, -24,21,-54,-17,1, -29,-25,-15,-27,32, 68,45,-16,-37,-18, -5,1,0,-77,71, -6,3,-20,71,-67, 29,-35,10,-30,19, 4,16,17,5,0, -14,19,2,28,26, 59,3,2,24,39, 55,-50,-45,-18,-17, 33,-35,14,-1,1, 8,87,-35,-29,0, -27,13,-7,23,-13, 37,-40,50,-35,14, 19,-7,-14,49,54, -5,22,-2,-29,-8, -27,38,13,27,48, 12,-41,-21,-15,28, 7,-16,-24,-19,-20, 11,-20,9,2,13, 23,-20,11,27,-27, 71,-69,8,2,-6, 22,12,16,16,9, -16,-8,-17,1,25, 1,40,-37,-33,66, 94,53,4,-22,-25, -41,-42,25,35,-16, -15,57,31,-29,-32, 21,16,-60,45,15, -1,7,57,-26,-47, -29,11,8,15,19, -105,-8,54,27,10, -17,6,-12,-1,-10, 4,0,23,-10,31, 13,11,10,12,-64, 23,-3,-8,-19,16, 52,24,-40,16,10, 40,5,9,0,-13, -7,-21,-8,-6,-7, -21,59,16,-53,18, -60,11,-47,14,-18, 25,-13,-24,4,-39, 16,-28,54,26,-67, 30,27,-20,-52,20, -12,55,12,18,-16, 39,-14,-6,-26,56, -88,-55,12,25,26, -37,6,75,0,-34, -81,54,-30,1,-7, 49,-23,-14,21,10, -62,-58,-57,-47,-34, 15,-4,34,-78,31, 25,-11,7,50,-10, 42,-63,14,-36,-4, 57,55,57,53,42, -42,-1,15,40,37, 15,25,-11,6,1, 31,-2,-6,-1,-7, -64,34,28,30,-1, 3,21,0,-88,-12, -56,25,-28,40,8, -28,-14,9,12,2, -6,-17,22,49,-6, -26,14,28,-20,4, -12,50,35,40,13, -38,-58,-29,17,30, 22,60,26,-54,-39, -12,58,-28,-63,10, -21,-8,-12,26,-62, 6,-10,-11,-22,-6, -7,4,1,18,2, -70,11,14,4,13, 19,-24,-34,24,67, 17,51,-21,13,23, 54,-30,48,1,-13, 80,26,-16,-2,13, -4,6,-30,29,-24, 73,-58,30,-27,20, -2,-21,41,45,30, -27,-3,-5,-18,-20, -49,-3,-35,10,42, -19,-67,-53,-11,9, 13,-15,-33,-51,-30, 15,7,25,-30,4, 28,-22,-34,54,-29, 39,-46,20,16,34, -4,47,75,1,-44, -55,-24,7,-1,9, -42,50,-8,-36,41, 68,0,-4,-10,-23, -15,-50,64,36,-9, -27,12,25,-38,-47, -37,32,-49,51,-36, 2,-4,69,-26,19, 7,45,67,46,13, -63,46,15,-47,4, -41,13,-6,5,-21, 37,26,-55,-7,33, -1,-28,10,-17,-64, -14,0,-36,-17,93, -3,-9,-66,44,-21, 3,-12,38,-6,-13, -12,19,13,43,-43, -10,-12,6,-5,9, -49,32,-5,2,4, 5,15,-16,10,-21, 8,-62,-8,64,8, 79,-1,-66,-49,-18, 5,40,-5,-30,-45, 1,-6,21,-32,93, -18,-30,-21,32,21, -18,22,8,5,-41, -54,80,22,-10,-7, -8,-23,-64,66,56, -14,-30,-41,-46,-14, -29,-37,27,-14,42, -2,-9,-29,34,14, 33,-14,22,4,10, 26,26,28,32,23, -72,-32,3,0,-14, 35,-42,-78,-32,6, 29,-18,-45,-5,7, -33,-45,-3,-22,-34, 8,-8,4,-51,-25, -9,59,-78,21,-5, -25,-48,66,-15,-17, -24,-49,-13,25,-23, -64,-6,40,-24,-19, -11,57,-33,-8,1, 10,-52,-54,28,39, 49,34,-11,-61,-41, -43,10,15,-15,51, 30,15,-51,32,-34, -2,-34,14,18,16, 1,1,-3,-3,1, 1,-18,6,16,48, 12,-5,-42,7,36, 48,7,-20,-10,7, 12,2,54,39,-38, 37,54,4,-11,-8, -46,-10,5,-10,-34, 46,-12,29,-37,39, 36,-11,24,56,17, 14,20,25,0,-25, -28,55,-7,-5,27, 3,9,-26,-8,6, -24,-10,-30,-31,-34, 18,4,22,21,40, -1,-29,-37,-8,-21, 92,-29,11,-3,11, 73,23,22,7,4, -44,-9,-11,21,-13, 11,9,-78,-1,47, 114,-12,-37,-19,-5, -11,-22,19,12,-30, 7,38,45,-21,-8, -9,55,-45,56,-21, 7,17,46,-57,-87, -6,27,31,31,7, -56,-12,46,21,-5, -12,36,3,3,-21, 43,19,12,-7,9, -14,0,-9,-33,-91, 7,26,3,-11,64, 83,-31,-46,25,2, 9,5,2,2,-1, 20,-17,10,-5,-27, -8,20,8,-19,16, -21,-13,-31,5,5, 42,24,9,34,-20, 28,-61,22,11,-39, 64,-20,-1,-30,-9, -20,24,-25,-24,-29, 22,-60,6,-5,41, -9,-87,14,34,15, -57,52,69,15,-3, -102,58,16,3,6, 60,-75,-32,26,7, -57,-27,-32,-24,-21, -29,-16,62,-46,31, 30,-27,-15,7,15 }; /** * Excitation Codebook */ public static final int[] exc_5_64_table = { 1,5,-15,49,-66, -48,-4,50,-44,7, 37,16,-18,25,-26, -26,-15,19,19,-27, -47,28,57,5,-17, -32,-41,68,21,-2, 64,56,8,-16,-13, -26,-9,-16,11,6, -39,25,-19,22,-31, 20,-45,55,-43,10, -16,47,-40,40,-20, -51,3,-17,-14,-15, -24,53,-20,-46,46, 27,-68,32,3,-18, -5,9,-31,16,-9, -10,-1,-23,48,95, 47,25,-41,-32,-3, 15,-25,-55,36,41, -27,20,5,13,14, -22,5,2,-23,18, 46,-15,17,-18,-34, -5,-8,27,-55,73, 16,2,-1,-17,40, -78,33,0,2,19, 4,53,-16,-15,-16, -28,-3,-13,49,8, -7,-29,27,-13,32, 20,32,-61,16,14, 41,44,40,24,20, 7,4,48,-60,-77, 17,-6,-48,65,-15, 32,-30,-71,-10,-3, -6,10,-2,-7,-29, -56,67,-30,7,-5, 86,-6,-10,0,5, -31,60,34,-38,-3, 24,10,-2,30,23, 24,-41,12,70,-43, 15,-17,6,13,16, -13,8,30,-15,-8, 5,23,-34,-98,-4, -13,13,-48,-31,70, 12,31,25,24,-24, 26,-7,33,-16,8, 5,-11,-14,-8,-65, 13,10,-2,-9,0, -3,-68,5,35,7, 0,-31,-1,-17,-9, -9,16,-37,-18,-1, 69,-48,-28,22,-21, -11,5,49,55,23, -86,-36,16,2,13, 63,-51,30,-11,13, 24,-18,-6,14,-19, 1,41,9,-5,27, -36,-44,-34,-37,-21, -26,31,-39,15,43, 5,-8,29,20,-8, -20,-52,-28,-1,13, 26,-34,-10,-9,27, -8,8,27,-66,4, 12,-22,49,10,-77, 32,-18,3,-38,12, -3,-1,2,2,0 }; /** * Excitation Codebook */ public static final int[] exc_8_128_table = { -14,9,13,-32,2,-10,31,-10, -8,-8,6,-4,-1,10,-64,23, 6,20,13,6,8,-22,16,34, 7,42,-49,-28,5,26,4,-15, 41,34,41,32,33,24,23,14, 8,40,34,4,-24,-41,-19,-15, 13,-13,33,-54,24,27,-44,33, 27,-15,-15,24,-19,14,-36,14, -9,24,-12,-4,37,-5,16,-34, 5,10,33,-15,-54,-16,12,25, 12,1,2,0,3,-1,-4,-4, 11,2,-56,54,27,-20,13,-6, -46,-41,-33,-11,-5,7,12,14, -14,-5,8,20,6,3,4,-8, -5,-42,11,8,-14,25,-2,2, 13,11,-22,39,-9,9,5,-45, -9,7,-9,12,-7,34,-17,-102, 7,2,-42,18,35,-9,-34,11, -5,-2,3,22,46,-52,-25,-9, -94,8,11,-5,-5,-5,4,-7, -35,-7,54,5,-32,3,24,-9, -22,8,65,37,-1,-12,-23,-6, -9,-28,55,-33,14,-3,2,18, -60,41,-17,8,-16,17,-11,0, -11,29,-28,37,9,-53,33,-14, -9,7,-25,-7,-11,26,-32,-8, 24,-21,22,-19,19,-10,29,-14, -10,-4,-3,-2,3,-1,-4,-4, -5,-52,10,41,6,-30,-4,16, 32,22,-27,-22,32,-3,-28,-3, 3,-35,6,17,23,21,8,2, 4,-45,-17,14,23,-4,-31,-11, -3,14,1,19,-11,2,61,-8, 9,-12,7,-10,12,-3,-24,99, -48,23,50,-37,-5,-23,0,8, -14,35,-64,-5,46,-25,13,-1, -49,-19,-15,9,34,50,25,11, -6,-9,-16,-20,-32,-33,-32,-27, 10,-8,12,-15,56,-14,-32,33, 3,-9,1,65,-9,-9,-10,-2, -6,-23,9,17,3,-28,13,-32, 4,-2,-10,4,-16,76,12,-52, 6,13,33,-6,4,-14,-9,-3, 1,-15,-16,28,1,-15,11,16, 9,4,-21,-37,-40,-6,22,12, -15,-23,-14,-17,-16,-9,-10,-9, 13,-39,41,5,-9,16,-38,25, 46,-47,4,49,-14,17,-2,6, 18,5,-6,-33,-22,44,50,-2, 1,3,-6,7,7,-3,-21,38, -18,34,-14,-41,60,-13,6,16, -24,35,19,-13,-36,24,3,-17, -14,-10,36,44,-44,-29,-3,3, -54,-8,12,55,26,4,-2,-5, 2,-11,22,-23,2,22,1,-25, -39,66,-49,21,-8,-2,10,-14, -60,25,6,10,27,-25,16,5, -2,-9,26,-13,-20,58,-2,7, 52,-9,2,5,-4,-15,23,-1, -38,23,8,27,-6,0,-27,-7, 39,-10,-14,26,11,-45,-12,9, -5,34,4,-35,10,43,-22,-11, 56,-7,20,1,10,1,-26,9, 94,11,-27,-14,-13,1,-11,0, 14,-5,-6,-10,-4,-15,-8,-41, 21,-5,1,-28,-8,22,-9,33, -23,-4,-4,-12,39,4,-7,3, -60,80,8,-17,2,-6,12,-5, 1,9,15,27,31,30,27,23, 61,47,26,10,-5,-8,-12,-13, 5,-18,25,-15,-4,-15,-11,12, -2,-2,-16,-2,-6,24,12,11, -4,9,1,-9,14,-45,57,12, 20,-35,26,11,-64,32,-10,-10, 42,-4,-9,-16,32,24,7,10, 52,-11,-57,29,0,8,0,-6, 17,-17,-56,-40,7,20,18,12, -6,16,5,7,-1,9,1,10, 29,12,16,13,-2,23,7,9, -3,-4,-5,18,-64,13,55,-25, 9,-9,24,14,-25,15,-11,-40, -30,37,1,-19,22,-5,-31,13, -2,0,7,-4,16,-67,12,66, -36,24,-8,18,-15,-23,19,0, -45,-7,4,3,-13,13,35,5, 13,33,10,27,23,0,-7,-11, 43,-74,36,-12,2,5,-8,6, -33,11,-16,-14,-5,-7,-3,17, -34,27,-16,11,-9,15,33,-31, 8,-16,7,-6,-7,63,-55,-17, 11,-1,20,-46,34,-30,6,9, 19,28,-9,5,-24,-8,-23,-2, 31,-19,-16,-5,-15,-18,0,26, 18,37,-5,-15,-2,17,5,-27, 21,-33,44,12,-27,-9,17,11, 25,-21,-31,-7,13,33,-8,-25, -7,7,-10,4,-6,-9,48,-82, -23,-8,6,11,-23,3,-3,49, -29,25,31,4,14,16,9,-4, -18,10,-26,3,5,-44,-9,9, -47,-55,15,9,28,1,4,-3, 46,6,-6,-38,-29,-31,-15,-6, 3,0,14,-6,8,-54,-50,33, -5,1,-14,33,-48,26,-4,-5, -3,-5,-3,-5,-28,-22,77,55, -1,2,10,10,-9,-14,-66,-49, 11,-36,-6,-20,10,-10,16,12, 4,-1,-16,45,-44,-50,31,-2, 25,42,23,-32,-22,0,11,20, -40,-35,-40,-36,-32,-26,-21,-13, 52,-22,6,-24,-20,17,-5,-8, 36,-25,-11,21,-26,6,34,-8, 7,20,-3,5,-25,-8,18,-5, -9,-4,1,-9,20,20,39,48, -24,9,5,-65,22,29,4,3, -43,-11,32,-6,9,19,-27,-10, -47,-14,24,10,-7,-36,-7,-1, -4,-5,-5,16,53,25,-26,-29, -4,-12,45,-58,-34,33,-5,2, -1,27,-48,31,-15,22,-5,4, 7,7,-25,-3,11,-22,16,-12, 8,-3,7,-11,45,14,-73,-19, 56,-46,24,-20,28,-12,-2,-1, -36,-3,-33,19,-6,7,2,-15, 5,-31,-45,8,35,13,20,0, -9,48,-13,-43,-3,-13,2,-5, 72,-68,-27,2,1,-2,-7,5, 36,33,-40,-12,-4,-5,23,19 }; /** * Gain Codebook (narrowband) */ public static final int[] gain_cdbk_nb = { //384 -32,-32,-32, -28,-67,-5, -42,-6,-32, -57,-10,-54, -16,27,-41, 19,-19,-40, -45,24,-21, -8,-14,-18, 1,14,-58, -18,-88,-39, -38,21,-18, -19,20,-43, 10,17,-48, -52,-58,-13, -44,-1,-11, -12,-11,-34, 14,0,-46, -37,-35,-34, -25,44,-30, 6,-4,-63, -31,43,-41, -23,30,-43, -43,26,-14, -33,1,-13, -13,18,-37, -46,-73,-45, -36,24,-25, -36,-11,-20, -25,12,-18, -36,-69,-59, -45,6,8, -22,-14,-24, -1,13,-44, -39,-48,-26, -32,31,-37, -33,15,-46, -24,30,-36, -41,31,-23, -50,22,-4, -22,2,-21, -17,30,-34, -7,-60,-28, -38,42,-28, -44,-11,21, -16,8,-44, -39,-55,-43, -11,-35,26, -9,0,-34, -8,121,-81, 7,-16,-22, -37,33,-31, -27,-7,-36, -34,70,-57, -37,-11,-48, -40,17,-1, -33,6,-6, -9,0,-20, -21,69,-33, -29,33,-31, -55,12,-1, -33,27,-22, -50,-33,-47, -50,54,51, -1,-5,-44, -4,22,-40, -39,-66,-25, -33,1,-26, -24,-23,-25, -11,21,-45, -25,-45,-19, -43,105,-16, 5,-21,1, -16,11,-33, -13,-99,-4, -37,33,-15, -25,37,-63, -36,24,-31, -53,-56,-38, -41,-4,4, -33,13,-30, 49,52,-94, -5,-30,-15, 1,38,-40, -23,12,-36, -17,40,-47, -37,-41,-39, -49,34,0, -18,-7,-4, -16,17,-27, 30,5,-62, 4,48,-68, -43,11,-11, -18,19,-15, -23,-62,-39, -42,10,-2, -21,-13,-13, -9,13,-47, -23,-62,-24, -44,60,-21, -18,-3,-52, -22,22,-36, -75,57,16, -19,3,10, -29,23,-38, -5,-62,-51, -51,40,-18, -42,13,-24, -34,14,-20, -56,-75,-26, -26,32,15, -26,17,-29, -7,28,-52, -12,-30,5, -5,-48,-5, 2,2,-43, 21,16,16, -25,-45,-32, -43,18,-10, 9,0,-1, -1,7,-30, 19,-48,-4, -28,25,-29, -22,0,-31, -32,17,-10, -64,-41,-62, -52,15,16, -30,-22,-32, -7,9,-38 }; /** * Gain Codebook (LBR) */ public static final int[] gain_cdbk_lbr = { //96 -32,-32,-32, -31,-58,-16, -41,-24,-43, -56,-22,-55, -13,33,-41, -4,-39,-9, -41,15,-12, -8,-15,-12, 1,2,-44, -22,-66,-42, -38,28,-23, -21,14,-37, 0,21,-50, -53,-71,-27, -37,-1,-19, -19,-5,-28, 6,65,-44, -33,-48,-33, -40,57,-14, -17,4,-45, -31,38,-33, -23,28,-40, -43,29,-12, -34,13,-23, -16,15,-27, -14,-82,-15, -31,25,-32, -21,5,-5, -47,-63,-51, -46,12,3, -28,-17,-29, -10,14,-40 }; /** * Excitation Codebook */ public static final int[] hexc_10_32_table = { -3, -2, -1, 0, -4, 5, 35, -40, -9, 13, -44, 5, -27, -1, -7, 6, -11, 7, -8, 7, 19, -14, 15, -4, 9, -10, 10, -8, 10, -9, -1, 1, 0, 0, 2, 5, -18, 22, -53, 50, 1, -23, 50, -36, 15, 3, -13, 14, -10, 6, 1, 5, -3, 4, -2, 5, -32, 25, 5, -2, -1, -4, 1, 11, -29, 26, -6, -15, 30, -18, 0, 15, -17, 40, -41, 3, 9, -2, -2, 3, -3, -1, -5, 2, 21, -6, -16, -21, 23, 2, 60, 15, 16, -16, -9, 14, 9, -1, 7, -9, 0, 1, 1, 0, -1, -6, 17, -28, 54, -45, -1, 1, -1, -6, -6, 2, 11, 26, -29, -2, 46, -21, 34, 12, -23, 32, -23, 16, -10, 3, 66, 19, -20, 24, 7, 11, -3, 0, -3, -1, -50, -46, 2, -18, -3, 4, -1, -2, 3, -3, -19, 41, -36, 9, 11, -24, 21, -16, 9, -3, -25, -3, 10, 18, -9, -2, -5, -1, -5, 6, -4, -3, 2, -26, 21, -19, 35, -15, 7, -13, 17, -19, 39, -43, 48, -31, 16, -9, 7, -2, -5, 3, -4, 9, -19, 27, -55, 63, -35, 10, 26, -44, -2, 9, 4, 1, -6, 8, -9, 5, -8, -1, -3, -16, 45, -42, 5, 15, -16, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -16, 24, -55, 47, -38, 27, -19, 7, -3, 1, 16, 27, 20, -19, 18, 5, -7, 1, -5, 2, -6, 8, -22, 0, -3, -3, 8, -1, 7, -8, 1, -3, 5, 0, 17, -48, 58, -52, 29, -7, -2, 3, -10, 6, -26, 58, -31, 1, -6, 3, 93, -29, 39, 3, 17, 5, 6, -1, -1, -1, 27, 13, 10, 19, -7, -34, 12, 10, -4, 9, -76, 9, 8, -28, -2, -11, 2, -1, 3, 1, -83, 38, -39, 4, -16, -6, -2, -5, 5, -2, }; /** * Excitation Codebook */ public static final int[] hexc_table = { //1024 -24, 21, -20, 5, -5, -7, 14, -10, 2, -27, 16, -20, 0, -32, 26, 19, 8, -11, -41, 31, 28, -27, -32, 34, 42, 34, -17, 22, -10, 13, -29, 18, -12, -26, -24, 11, 22, 5, -5, -5, 54, -68, -43, 57, -25, 24, 4, 4, 26, -8, -12, -17, 54, 30, -45, 1, 10, -15, 18, -41, 11, 68, -67, 37, -16, -24, -16, 38, -22, 6, -29, 30, 66, -27, 5, 7, -16, 13, 2, -12, -7, -3, -20, 36, 4, -28, 9, 3, 32, 48, 26, 39, 3, 0, 7, -21, -13, 5, -82, -7, 73, -20, 34, -9, -5, 1, -1, 10, -5, -10, -1, 9, 1, -9, 10, 0, -14, 11, -1, -2, -1, 11, 20, 96, -81, -22, -12, -9, -58, 9, 24, -30, 26, -35, 27, -12, 13, -18, 56, -59, 15, -7, 23, -15, -1, 6, -25, 14, -22, -20, 47, -11, 16, 2, 38, -23, -19, -30, -9, 40, -11, 5, 4, -6, 8, 26, -21, -11, 127, 4, 1, 6, -9, 2, -7, -2, -3, 7, -5, 10, -19, 7, -106, 91, -3, 9, -4, 21, -8, 26, -80, 8, 1, -2, -10, -17, -17, -27, 32, 71, 6, -29, 11, -23, 54, -38, 29, -22, 39, 87, -31, -12, -20, 3, -2, -2, 2, 20, 0, -1, -35, 27, 9, -6, -12, 3, -12, -6, 13, 1, 14, -22, -59, -15, -17, -25, 13, -7, 7, 3, 0, 1, -7, 6, -3, 61, -37, -23, -23, -29, 38, -31, 27, 1, -8, 2, -27, 23, -26, 36, -34, 5, 24, -24, -6, 7, 3, -59, 78, -62, 44, -16, 1, 6, 0, 17, 8, 45, 0, -110, 6, 14, -2, 32, -77, -56, 62, -3, 3, -13, 4, -16, 102, -15, -36, -1, 9, -113, 6, 23, 0, 9, 9, 5, -8, -1, -14, 5, -12, 121, -53, -27, -8, -9, 22, -13, 3, 2, -3, 1, -2, -71, 95, 38, -19, 15, -16, -5, 71, 10, 2, -32, -13, -5, 15, -1, -2, -14, -85, 30, 29, 6, 3, 2, 0, 0, 0, 0, 0, 0, 0, 0, 2, -65, -56, -9, 18, 18, 23, -14, -2, 0, 12, -29, 26, -12, 1, 2, -12, -64, 90, -6, 4, 1, 5, -5, -110, -3, -31, 22, -29, 9, 0, 8, -40, -5, 21, -5, -5, 13, 10, -18, 40, 1, 35, -20, 30, -28, 11, -6, 19, 7, 14, 18, -64, 9, -6, 16, 51, 68, 8, 16, 12, -8, 0, -9, 20, -22, 25, 7, -4, -13, 41, -35, 93, -18, -54, 11, -1, 1, -9, 4, -66, 66, -31, 20, -22, 25, -23, 11, 10, 9, 19, 15, 11, -5, -31, -10, -23, -28, -6, -6, -3, -4, 5, 3, -28, 22, -11, -42, 25, -25, -16, 41, 34, 47, -6, 2, 42, -19, -22, 5, -39, 32, 6, -35, 22, 17, -30, 8, -26, -11, -11, 3, -12, 33, 33, -37, 21, -1, 6, -4, 3, 0, -5, 5, 12, -12, 57, 27, -61, -3, 20, -17, 2, 0, 4, 0, -2, -33, -58, 81, -23, 39, -10, -5, 2, 6, -7, 5, 4, -3, -2, -13, -23, -72, 107, 15, -5, 0, -7, -3, -6, 5, -4, 15, 47, 12, -31, 25, -16, 8, 22, -25, -62, -56, -18, 14, 28, 12, 2, -11, 74, -66, 41, -20, -7, 16, -20, 16, -8, 0, -16, 4, -19, 92, 12, -59, -14, -39, 49, -25, -16, 23, -27, 19, -3, -33, 19, 85, -29, 6, -7, -10, 16, -7, -12, 1, -6, 2, 4, -2, 64, 10, -25, 41, -2, -31, 15, 0, 110, 50, 69, 35, 28, 19, -10, 2, -43, -49, -56, -15, -16, 10, 3, 12, -1, -8, 1, 26, -12, -1, 7, -11, -27, 41, 25, 1, -11, -18, 22, -7, -1, -47, -8, 23, -3, -17, -7, 18, -125, 59, -5, 3, 18, 1, 2, 3, 27, -35, 65, -53, 50, -46, 37, -21, -28, 7, 14, -37, -5, -5, 12, 5, -8, 78, -19, 21, -6, -16, 8, -7, 5, 2, 7, 2, 10, -6, 12, -60, 44, 11, -36, -32, 31, 0, 2, -2, 2, 1, -3, 7, -10, 17, -21, 10, 6, -2, 19, -2, 59, -38, -86, 38, 8, -41, -30, -45, -33, 7, 15, 28, 29, -7, 24, -40, 7, 7, 5, -2, 9, 24, -23, -18, 6, -29, 30, 2, 28, 49, -11, -46, 10, 43, -13, -9, -1, -3, -7, -7, -17, -6, 97, -33, -21, 3, 5, 1, 12, -43, -8, 28, 7, -43, -7, 17, -20, 19, -1, 2, -13, 9, 54, 34, 9, -28, -11, -9, -17, 110, -59, 44, -26, 0, 3, -12, -47, 73, -34, -43, 38, -33, 16, -5, -46, -4, -6, -2, -25, 19, -29, 28, -13, 5, 14, 27, -40, -43, 4, 32, -13, -2, -35, -4, 112, -42, 9, -12, 37, -28, 17, 14, -19, 35, -39, 23, 3, -14, -1, -57, -5, 94, -9, 3, -39, 5, 30, -10, -32, 42, -13, -14, -97, -63, 30, -9, 1, -7, 12, 5, 20, 17, -9, -36, -30, 25, 47, -9, -15, 12, -22, 98, -8, -50, 15, -27, 21, -16, -11, 2, 12, -10, 10, -3, 33, 36, -96, 0, -17, 31, -9, 9, 3, -20, 13, -11, 8, -4, 10, -10, 9, 1, 112, -70, -27, 5, -21, 2, -57, -3, -29, 10, 19, -21, 21, -10, -66, -3, 91, -35, 30, -12, 0, -7, 59, -28, 26, 2, 14, -18, 1, 1, 11, 17, 20, -54, -59, 27, 4, 29, 32, 5, 19, 12, -4, 1, 7, -10, 5, -2, 10, 0, 23, -5, 28, -104, 46, 11, 16, 3, 29, 1, -8, -14, 1, 7, -50, 88, -62, 26, 8, -17, -14, 50, 0, 32, -12, -3, -27, 18, -8, -5, 8, 3, -20, -11, 37, -12, 9, 33, 46, -101, -1, -4, 1, 6, -1, 28, -42, -15, 16, 5, -1, -2, -55, 85, 38, -9, -4, 11, -2, -9, -6, 3, -20, -10, -77, 89, 24, -3, -104, -57, -26, -31, -20, -6, -9, 14, 20, -23, 46, -15, -31, 28, 1, -15, -2, 6, -2, 31, 45, -76, 23, -25, }; /** * LSP Codebook (high) */ public static final int[] high_lsp_cdbk = { //512 39,12,-14,-20,-29,-61,-67,-76, -32,-71,-67,68,77,46,34,5, -13,-48,-46,-72,-81,-84,-60,-58, -40,-28,82,93,68,45,29,3, -19,-47,-28,-43,-35,-30,-8,-13, -39,-91,-91,-123,-96,10,10,-6, -18,-55,-60,-91,-56,-36,-27,-16, -48,-75,40,28,-10,-28,35,9, 37,19,1,-20,-31,-41,-18,-25, -35,-68,-80,45,27,-1,47,13, 0,-29,-35,-57,-50,-79,-73,-38, -19,5,35,14,-10,-23,16,-8, 5,-24,-40,-62,-23,-27,-22,-16, -18,-46,-72,-77,43,21,33,1, -80,-70,-70,-64,-56,-52,-39,-33, -31,-38,-19,-19,-15,32,33,-2, 7,-15,-15,-24,-23,-33,-41,-56, -24,-57,5,89,64,41,27,5, -9,-47,-60,-97,-97,-124,-20,-9, -44,-73,31,29,-4,64,48,7, -35,-57,0,-3,-26,-47,-3,-6, -40,-76,-79,-48,12,81,55,10, 9,-24,-43,-73,-57,-69,16,5, -28,-53,18,29,20,0,-4,-11, 6,-13,23,7,-17,-35,-37,-37, -30,-68,-63,6,24,-9,-14,3, 21,-13,-27,-57,-49,-80,-24,-41, -5,-16,-5,1,45,25,12,-7, 3,-15,-6,-16,-15,-8,6,-13, -42,-81,-80,-87,14,1,-10,-3, -43,-69,-46,-24,-28,-29,36,6, -43,-56,-12,12,54,79,43,9, 54,22,2,8,-12,-43,-46,-52, -38,-69,-89,-5,75,38,33,5, -13,-53,-62,-87,-89,-113,-99,-55, -34,-37,62,55,33,16,21,-2, -17,-46,-29,-38,-38,-48,-39,-42, -36,-75,-72,-88,-48,-30,21,2, -15,-57,-64,-98,-84,-76,25,1, -46,-80,-12,18,-7,3,34,6, 38,31,23,4,-1,20,14,-15, -43,-78,-91,-24,14,-3,54,16, 0,-27,-28,-44,-56,-83,-92,-89, -3,34,56,41,36,22,20,-8, -7,-35,-42,-62,-49,3,12,-10, -50,-87,-96,-66,92,70,38,9, -70,-71,-62,-42,-39,-43,-11,-7, -50,-79,-58,-50,-31,32,31,-6, -4,-25,7,-17,-38,-70,-58,-27, -43,-83,-28,59,36,20,31,2, -27,-71,-80,-109,-98,-75,-33,-32, -31,-2,33,15,-6,43,33,-5, 0,-22,-10,-27,-34,-49,-11,-20, -41,-91,-100,-121,-39,57,41,10, -19,-50,-38,-59,-60,-70,-18,-20, -8,-31,-8,-15,1,-14,-26,-25, 33,21,32,17,1,-19,-19,-26, -58,-81,-35,-22,45,30,11,-11, 3,-26,-48,-87,-67,-83,-58,3, -1,-26,-20,44,10,25,39,5, -9,-35,-27,-38,7,10,4,-9, -42,-85,-102,-127,52,44,28,10, -47,-61,-40,-39,-17,-1,-10,-33, -42,-74,-48,21,-4,70,52,10 }; /** * LSP Codebook (high) */ public static final int[] high_lsp_cdbk2 = { //512 -36,-62,6,-9,-10,-14,-56,23, 1,-26,23,-48,-17,12,8,-7, 23,29,-36,-28,-6,-29,-17,-5, 40,23,10,10,-46,-13,36,6, 4,-30,-29,62,32,-32,-1,22, -14,1,-4,-22,-45,2,54,4, -30,-57,-59,-12,27,-3,-31,8, -9,5,10,-14,32,66,19,9, 2,-25,-37,23,-15,18,-38,-31, 5,-9,-21,15,0,22,62,30, 15,-12,-14,-46,77,21,33,3, 34,29,-19,50,2,11,9,-38, -12,-37,62,1,-15,54,32,6, 2,-24,20,35,-21,2,19,24, -13,55,4,9,39,-19,30,-1, -21,73,54,33,8,18,3,15, 6,-19,-47,6,-3,-48,-50,1, 26,20,8,-23,-50,65,-14,-55, -17,-31,-37,-28,53,-1,-17,-53, 1,57,11,-8,-25,-30,-37,64, 5,-52,-45,15,23,31,15,14, -25,24,33,-2,-44,-56,-18,6, -21,-43,4,-12,17,-37,20,-10, 34,15,2,15,55,21,-11,-31, -6,46,25,16,-9,-25,-8,-62, 28,17,20,-32,-29,26,30,25, -19,2,-16,-17,26,-51,2,50, 42,19,-66,23,29,-2,3,19, -19,-37,32,15,6,30,-34,13, 11,-5,40,31,10,-42,4,-9, 26,-9,-70,17,-2,-23,20,-22, -55,51,-24,-31,22,-22,15,-13, 3,-10,-28,-16,56,4,-63,11, -18,-15,-18,-38,-35,16,-7,34, -1,-21,-49,-47,9,-37,7,8, 69,55,20,6,-33,-45,-10,-9, 6,-9,12,71,15,-3,-42,-7, -24,32,-35,-2,-42,-17,-5,0, -2,-33,-54,13,-12,-34,47,23, 19,55,7,-8,74,31,14,16, -23,-26,19,12,-18,-49,-28,-31, -20,2,-14,-20,-47,78,40,13, -23,-11,21,-6,18,1,47,5, 38,35,32,46,22,8,13,16, -14,18,51,19,40,39,11,-26, -1,-17,47,2,-53,-15,31,-22, 38,21,-15,-16,5,-33,53,15, -38,86,11,-3,-24,49,13,-4, -11,-18,28,20,-12,-27,-26,35, -25,-35,-3,-20,-61,30,10,-55, -12,-22,-52,-54,-14,19,-32,-12, 45,15,-8,-48,-9,11,-32,8, -16,-34,-13,51,18,38,-2,-32, -17,22,-2,-18,-28,-70,59,27, -28,-19,-10,-20,-9,-9,-8,-21, 21,-8,35,-2,45,-3,-9,12, 0,30,7,-39,43,27,-38,-91, 30,26,19,-55,-4,63,14,-17, 13,9,13,2,7,4,6,61, 72,-1,-17,29,-1,-22,-17,8, -28,-37,63,44,41,3,2,14, 9,-6,75,-8,-7,-12,-15,-12, 13,9,-4,30,-22,-65,15,0, -45,4,-4,1,5,22,11,23 }; /** */ public static final int NB_CDBK_SIZE = 64; /** */ public static final int NB_CDBK_SIZE_LOW1 = 64; /** */ public static final int NB_CDBK_SIZE_LOW2 = 64; /** */ public static final int NB_CDBK_SIZE_HIGH1 = 64; /** */ public static final int NB_CDBK_SIZE_HIGH2 = 64; /** * Codebook (narrowband) */ public static final int[] cdbk_nb = { //640 30,19,38,34,40,32,46,43,58,43, 5,-18,-25,-40,-33,-55,-52,20,34,28, -20,-63,-97,-92,61,53,47,49,53,75, -14,-53,-77,-79,0,-3,-5,19,22,26, -9,-53,-55,66,90,72,85,68,74,52, -4,-41,-58,-31,-18,-31,27,32,30,18, 24,3,8,5,-12,-3,26,28,74,63, -2,-39,-67,-77,-106,-74,59,59,73,65, 44,40,71,72,82,83,98,88,89,60, -6,-31,-47,-48,-13,-39,-9,7,2,79, -1,-39,-60,-17,87,81,65,50,45,19, -21,-67,-91,-87,-41,-50,7,18,39,74, 10,-31,-28,39,24,13,23,5,56,45, 29,10,-5,-13,-11,-35,-18,-8,-10,-8, -25,-71,-77,-21,2,16,50,63,87,87, 5,-32,-40,-51,-68,0,12,6,54,34, 5,-12,32,52,68,64,69,59,65,45, 14,-16,-31,-40,-65,-67,41,49,47,37, -11,-52,-75,-84,-4,57,48,42,42,33, -11,-51,-68,-6,13,0,8,-8,26,32, -23,-53,0,36,56,76,97,105,111,97, -1,-28,-39,-40,-43,-54,-44,-40,-18,35, 16,-20,-19,-28,-42,29,47,38,74,45, 3,-29,-48,-62,-80,-104,-33,56,59,59, 10,17,46,72,84,101,117,123,123,106, -7,-33,-49,-51,-70,-67,-27,-31,70,67, -16,-62,-85,-20,82,71,86,80,85,74, -19,-58,-75,-45,-29,-33,-18,-25,45,57, -12,-42,-5,12,28,36,52,64,81,82, 13,-9,-27,-28,22,3,2,22,26,6, -6,-44,-51,2,15,10,48,43,49,34, -19,-62,-84,-89,-102,-24,8,17,61,68, 39,24,23,19,16,-5,12,15,27,15, -8,-44,-49,-60,-18,-32,-28,52,54,62, -8,-48,-77,-70,66,101,83,63,61,37, -12,-50,-75,-64,33,17,13,25,15,77, 1,-42,-29,72,64,46,49,31,61,44, -8,-47,-54,-46,-30,19,20,-1,-16,0, 16,-12,-18,-9,-26,-27,-10,-22,53,45, -10,-47,-75,-82,-105,-109,8,25,49,77, 50,65,114,117,124,118,115,96,90,61, -9,-45,-63,-60,-75,-57,8,11,20,29, 0,-35,-49,-43,40,47,35,40,55,38, -24,-76,-103,-112,-27,3,23,34,52,75, 8,-29,-43,12,63,38,35,29,24,8, 25,11,1,-15,-18,-43,-7,37,40,21, -20,-56,-19,-19,-4,-2,11,29,51,63, -2,-44,-62,-75,-89,30,57,51,74,51, 50,46,68,64,65,52,63,55,65,43, 18,-9,-26,-35,-55,-69,3,6,8,17, -15,-61,-86,-97,1,86,93,74,78,67, -1,-38,-66,-48,48,39,29,25,17,-1, 13,13,29,39,50,51,69,82,97,98, -2,-36,-46,-27,-16,-30,-13,-4,-7,-4, 25,-5,-11,-6,-25,-21,33,12,31,29, -8,-38,-52,-63,-68,-89,-33,-1,10,74, -2,-15,59,91,105,105,101,87,84,62, -7,-33,-50,-35,-54,-47,25,17,82,81, -13,-56,-83,21,58,31,42,25,72,65, -24,-66,-91,-56,9,-2,21,10,69,75, 2,-24,11,22,25,28,38,34,48,33, 7,-29,-26,17,15,-1,14,0,-2,0, -6,-41,-67,6,-2,-9,19,2,85,74, -22,-67,-84,-71,-50,3,11,-9,2,62 }; /** * Codebook (narrowband) */ public static final int[] cdbk_nb_low1 = { //320 -34,-52,-15,45,2, 23,21,52,24,-33, -9,-1,9,-44,-41, -13,-17,44,22,-17, -6,-4,-1,22,38, 26,16,2,50,27, -35,-34,-9,-41,6, 0,-16,-34,51,8, -14,-31,-49,15,-33, 45,49,33,-11,-37, -62,-54,45,11,-5, -72,11,-1,-12,-11, 24,27,-11,-43,46, 43,33,-12,-9,-1, 1,-4,-23,-57,-71, 11,8,16,17,-8, -20,-31,-41,53,48, -16,3,65,-24,-8, -23,-32,-37,-32,-49, -10,-17,6,38,5, -9,-17,-46,8,52, 3,6,45,40,39, -7,-6,-34,-74,31, 8,1,-16,43,68, -11,-19,-31,4,6, 0,-6,-17,-16,-38, -16,-30,2,9,-39, -16,-1,43,-10,48, 3,3,-16,-31,-3, 62,68,43,13,3, -10,8,20,-56,12, 12,-2,-18,22,-15, -40,-36,1,7,41, 0,1,46,-6,-62, -4,-12,-2,-11,-83, -13,-2,91,33,-10, 0,4,-11,-16,79, 32,37,14,9,51, -21,-28,-56,-34,0, 21,9,-26,11,28, -42,-54,-23,-2,-15, 31,30,8,-39,-66, -39,-36,31,-28,-40, -46,35,40,22,24, 33,48,23,-34,14, 40,32,17,27,-3, 25,26,-13,-61,-17, 11,4,31,60,-6, -26,-41,-64,13,16, -26,54,31,-11,-23, -9,-11,-34,-71,-21, -34,-35,55,50,29, -22,-27,-50,-38,57, 33,42,57,48,26, 11,0,-49,-31,26, -4,-14,5,78,37, 17,0,-49,-12,-23, 26,14,2,2,-43, -17,-12,10,-8,-4, 8,18,12,-6,20, -12,-6,-13,-25,34, 15,40,49,7,8, 13,20,20,-19,-22, -2,-8,2,51,-51 }; /** * Codebook (narrowband) */ public static final int[] cdbk_nb_low2 = { //320 -6,53,-21,-24,4, 26,17,-4,-37,25, 17,-36,-13,31,3, -6,27,15,-10,31, 28,26,-10,-10,-40, 16,-7,15,13,41, -9,0,-4,50,-6, -7,14,38,22,0, -48,2,1,-13,-19, 32,-3,-60,11,-17, -1,-24,-34,-1,35, -5,-27,28,44,13, 25,15,42,-11,15, 51,35,-36,20,8, -4,-12,-29,19,-47, 49,-15,-4,16,-29, -39,14,-30,4,25, -9,-5,-51,-14,-3, -40,-32,38,5,-9, -8,-4,-1,-22,71, -3,14,26,-18,-22, 24,-41,-25,-24,6, 23,19,-10,39,-26, -27,65,45,2,-7, -26,-8,22,-12,16, 15,16,-35,-5,33, -21,-8,0,23,33, 34,6,21,36,6, -7,-22,8,-37,-14, 31,38,11,-4,-3, -39,-32,-8,32,-23, -6,-12,16,20,-28, -4,23,13,-52,-1, 22,6,-33,-40,-6, 4,-62,13,5,-26, 35,39,11,2,57, -11,9,-20,-28,-33, 52,-5,-6,-2,22, -14,-16,-48,35,1, -58,20,13,33,-1, -74,56,-18,-22,-31, 12,6,-14,4,-2, -9,-47,10,-3,29, -17,-5,61,14,47, -12,2,72,-39,-17, 92,64,-53,-51,-15, -30,-38,-41,-29,-28, 27,9,36,9,-35, -42,81,-21,20,25, -16,-5,-17,-35,21, 15,-28,48,2,-2, 9,-19,29,-40,30, -18,-18,18,-16,-57, 15,-20,-12,-15,-37, -15,33,-39,21,-22, -13,35,11,13,-38, -63,29,23,-27,32, 18,3,-26,42,33, -64,-66,-17,16,56, 2,36,3,31,21, -41,-39,8,-57,14, 37,-2,19,-36,-19, -23,-29,-16,1,-3, -8,-10,31,64,-65 }; /** * Codebook (narrowband) */ public static final int[] cdbk_nb_high1 = { //320 -26,-8,29,21,4, 19,-39,33,-7,-36, 56,54,48,40,29, -4,-24,-42,-66,-43, -60,19,-2,37,41, -10,-37,-60,-64,18, -22,77,73,40,25, 4,19,-19,-66,-2, 11,5,21,14,26, -25,-86,-4,18,1, 26,-37,10,37,-1, 24,-12,-59,-11,20, -6,34,-16,-16,42, 19,-28,-51,53,32, 4,10,62,21,-12, -34,27,4,-48,-48, -50,-49,31,-7,-21, -42,-25,-4,-43,-22, 59,2,27,12,-9, -6,-16,-8,-32,-58, -16,-29,-5,41,23, -30,-33,-46,-13,-10, -38,52,52,1,-17, -9,10,26,-25,-6, 33,-20,53,55,25, -32,-5,-42,23,21, 66,5,-28,20,9, 75,29,-7,-42,-39, 15,3,-23,21,6, 11,1,-29,14,63, 10,54,26,-24,-51, -49,7,-23,-51,15, -66,1,60,25,10, 0,-30,-4,-15,17, 19,59,40,4,-5, 33,6,-22,-58,-70, -5,23,-6,60,44, -29,-16,-47,-29,52, -19,50,28,16,35, 31,36,0,-21,6, 21,27,22,42,7, -66,-40,-8,7,19, 46,0,-4,60,36, 45,-7,-29,-6,-32, -39,2,6,-9,33, 20,-51,-34,18,-6, 19,6,11,5,-19, -29,-2,42,-11,-45, -21,-55,57,37,2, -14,-67,-16,-27,-38, 69,48,19,2,-17, 20,-20,-16,-34,-17, -25,-61,10,73,45, 16,-40,-64,-17,-29, -22,56,17,-39,8, -11,8,-25,-18,-13, -19,8,54,57,36, -17,-26,-4,6,-21, 40,42,-4,20,31, 53,10,-34,-53,31, -17,35,0,15,-6, -20,-63,-73,22,25, 29,17,8,-29,-39, -69,18,15,-15,-5 }; /** * Codebook (narrowband) */ public static final int[] cdbk_nb_high2 = { //320 11,47,16,-9,-46, -32,26,-64,34,-5, 38,-7,47,20,2, -73,-99,-3,-45,20, 70,-52,15,-6,-7, -82,31,21,47,51, 39,-3,9,0,-41, -7,-15,-54,2,0, 27,-31,9,-45,-22, -38,-24,-24,8,-33, 23,5,50,-36,-17, -18,-51,-2,13,19, 43,12,-15,-12,61, 38,38,7,13,0, 6,-1,3,62,9, 27,22,-33,38,-35, -9,30,-43,-9,-32, -1,4,-4,1,-5, -11,-8,38,31,11, -10,-42,-21,-37,1, 43,15,-13,-35,-19, -18,15,23,-26,59, 1,-21,53,8,-41, -50,-14,-28,4,21, 25,-28,-40,5,-40, -41,4,51,-33,-8, -8,1,17,-60,12, 25,-41,17,34,43, 19,45,7,-37,24, -15,56,-2,35,-10, 48,4,-47,-2,5, -5,-54,5,-3,-33, -10,30,-2,-44,-24, -38,9,-9,42,4, 6,-56,44,-16,9, -40,-26,18,-20,10, 28,-41,-21,-4,13, -18,32,-30,-3,37, 15,22,28,50,-40, 3,-29,-64,7,51, -19,-11,17,-27,-40, -64,24,-12,-7,-27, 3,37,48,-1,2, -9,-38,-34,46,1, 27,-6,19,-13,26, 10,34,20,25,40, 50,-6,-7,30,9, -24,0,-23,71,-61, 22,58,-34,-4,2, -49,-33,25,30,-8, -6,-16,77,2,38, -8,-35,-6,-30,56, 78,31,33,-20,13, -39,20,22,4,21, -8,4,-6,10,-83, -41,9,-25,-43,15, -7,-12,-34,-39,-37, -33,19,30,16,-33, 42,-25,25,-68,44, -15,-11,-4,23,50, 14,4,-39,-43,20, -30,60,9,-20,7, 16,19,-33,37,29, 16,-35,7,38,-27 }; /** * QMF (Quadratic Mirror Filter) table */ public static final float[] h0 = { 3.596189e-05f, -0.0001123515f, -0.0001104587f, 0.0002790277f, 0.0002298438f, -0.0005953563f, -0.0003823631f, 0.00113826f, 0.0005308539f, -0.001986177f, -0.0006243724f, 0.003235877f, 0.0005743159f, -0.004989147f, -0.0002584767f, 0.007367171f, -0.0004857935f, -0.01050689f, 0.001894714f, 0.01459396f, -0.004313674f, -0.01994365f, 0.00828756f, 0.02716055f, -0.01485397f, -0.03764973f, 0.026447f, 0.05543245f, -0.05095487f, -0.09779096f, 0.1382363f, 0.4600981f, 0.4600981f, 0.1382363f, -0.09779096f, -0.05095487f, 0.05543245f, 0.026447f, -0.03764973f, -0.01485397f, 0.02716055f, 0.00828756f, -0.01994365f, -0.004313674f, 0.01459396f, 0.001894714f, -0.01050689f, -0.0004857935f, 0.007367171f, -0.0002584767f, -0.004989147f, 0.0005743159f, 0.003235877f, -0.0006243724f, -0.001986177f, 0.0005308539f, 0.00113826f, -0.0003823631f, -0.0005953563f, 0.0002298438f, 0.0002790277f, -0.0001104587f, -0.0001123515f, 3.596189e-05f }; /** * QMF (Quadratic Mirror Filter) table */ public static final float[] h1 = { 3.596189e-05f, 0.0001123515f, -0.0001104587f, -0.0002790277f, 0.0002298438f, 0.0005953563f, -0.0003823631f, -0.00113826f, 0.0005308539f, 0.001986177f, -0.0006243724f, -0.003235877f, 0.0005743159f, 0.004989147f, -0.0002584767f, -0.007367171f, -0.0004857935f, 0.01050689f, 0.001894714f, -0.01459396f, -0.004313674f, 0.01994365f, 0.00828756f, -0.02716055f, -0.01485397f, 0.03764973f, 0.026447f, -0.05543245f, -0.05095487f, 0.09779096f, 0.1382363f, -0.4600981f, 0.4600981f, -0.1382363f, -0.09779096f, 0.05095487f, 0.05543245f, -0.026447f, -0.03764973f, 0.01485397f, 0.02716055f, -0.00828756f, -0.01994365f, 0.004313674f, 0.01459396f, -0.001894714f, -0.01050689f, 0.0004857935f, 0.007367171f, 0.0002584767f, -0.004989147f, -0.0005743159f, 0.003235877f, 0.0006243724f, -0.001986177f, -0.0005308539f, 0.00113826f, 0.0003823631f, -0.0005953563f, -0.0002298438f, 0.0002790277f, 0.0001104587f, -0.0001123515f, -3.596189e-05f }; }
0
java-sources/ai/olami/olami-java-client/1.5.0/org/xiph
java-sources/ai/olami/olami-java-client/1.5.0/org/xiph/speex/Decoder.java
/****************************************************************************** * * * Copyright (c) 1999-2003 Wimba S.A., All Rights Reserved. * * * * COPYRIGHT: * * This software is the property of Wimba S.A. * * This software is redistributed under the Xiph.org variant of * * the BSD license. * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions * * are met: * * - Redistributions of source code must retain the above copyright * * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in the * * documentation and/or other materials provided with the distribution. * * - Neither the name of Wimba, the Xiph.org Foundation nor the names of * * its contributors may be used to endorse or promote products derived * * from this software without specific prior written permission. * * * * WARRANTIES: * * This software is made available by the authors in the hope * * that it will be useful, but without any warranty. * * Wimba S.A. is not liable for any consequence related to the * * use of the provided software. * * * * Class: Decoder.java * * * * Author: James LAWRENCE * * Modified by: Marc GIMPEL * * Based on code by: Jean-Marc VALIN * * * * Date: March 2003 * * * ******************************************************************************/ /* $Id: Decoder.java,v 1.2 2004/10/21 16:21:57 mgimpel Exp $ */ /* Copyright (C) 2002 Jean-Marc Valin Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the Xiph.org Foundation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.xiph.speex; import java.io.StreamCorruptedException; /** * Speex Decoder inteface, used as a base for the Narrowband and sideband * decoders. * * @author Jim Lawrence, helloNetwork.com * @author Marc Gimpel, Wimba S.A. (mgimpel@horizonwimba.com) * @version $Revision: 1.2 $ */ public interface Decoder { /** * Decode the given input bits. * @param bits - Speex bits buffer. * @param out - the decoded mono audio frame. * @return 1 if a terminator was found, 0 if not. * @throws StreamCorruptedException If there is an error detected in the * data stream. */ public int decode(Bits bits, float[] out) throws StreamCorruptedException; /** * Decode the given bits to stereo. * @param data - float array of size 2*frameSize, that contains the mono * audio samples in the first half. When the function has completed, the * array will contain the interlaced stereo audio samples. * @param frameSize - the size of a frame of mono audio samples. */ public void decodeStereo(float[] data, int frameSize); /** * Enables or disables perceptual enhancement. * @param enhanced */ public void setPerceptualEnhancement(boolean enhanced); /** * Returns whether perceptual enhancement is enabled or disabled. * @return whether perceptual enhancement is enabled or disabled. */ public boolean getPerceptualEnhancement(); /** * Returns the size of a frame. * @return the size of a frame. */ public int getFrameSize(); /** * Returns whether or not we are using Discontinuous Transmission encoding. * @return whether or not we are using Discontinuous Transmission encoding. */ public boolean getDtx(); /** * Returns the Pitch Gain array. * @return the Pitch Gain array. */ public float[] getPiGain(); /** * Returns the excitation array. * @return the excitation array. */ public float[] getExc(); /** * Returns the innovation array. * @return the innovation array. */ public float[] getInnov(); }
0
java-sources/ai/olami/olami-java-client/1.5.0/org/xiph
java-sources/ai/olami/olami-java-client/1.5.0/org/xiph/speex/Encoder.java
/****************************************************************************** * * * Copyright (c) 1999-2003 Wimba S.A., All Rights Reserved. * * * * COPYRIGHT: * * This software is the property of Wimba S.A. * * This software is redistributed under the Xiph.org variant of * * the BSD license. * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions * * are met: * * - Redistributions of source code must retain the above copyright * * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in the * * documentation and/or other materials provided with the distribution. * * - Neither the name of Wimba, the Xiph.org Foundation nor the names of * * its contributors may be used to endorse or promote products derived * * from this software without specific prior written permission. * * * * WARRANTIES: * * This software is made available by the authors in the hope * * that it will be useful, but without any warranty. * * Wimba S.A. is not liable for any consequence related to the * * use of the provided software. * * * * Class: Encoder.java * * * * Author: Marc GIMPEL * * Based on code by: Jean-Marc VALIN * * * * Date: 9th April 2003 * * * ******************************************************************************/ /* $Id: Encoder.java,v 1.2 2004/10/21 16:21:57 mgimpel Exp $ */ /* Copyright (C) 2002 Jean-Marc Valin Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the Xiph.org Foundation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.xiph.speex; /** * Speex Encoder interface, used as a base for the Narrowband and sideband * encoders. * * @author Marc Gimpel, Wimba S.A. (mgimpel@horizonwimba.com) * @version $Revision: 1.2 $ */ public interface Encoder { /** * Encode the given input signal. * @param bits - Speex bits buffer. * @param in - the raw mono audio frame to encode. * @return 1 if successful. */ public int encode(Bits bits, float[] in); /** * Returns the size in bits of an audio frame encoded with the current mode. * @return the size in bits of an audio frame encoded with the current mode. */ public int getEncodedFrameSize(); //-------------------------------------------------------------------------- // Speex Control Functions //-------------------------------------------------------------------------- /** * Returns the size of a frame. * @return the size of a frame. */ public int getFrameSize(); /** * Sets the Quality (between 0 and 10). * @param quality - the desired Quality (between 0 and 10). */ public void setQuality(int quality); /** * Get the current Bit Rate. * @return the current Bit Rate. */ public int getBitRate(); // public void resetState(); /** * Returns the Pitch Gain array. * @return the Pitch Gain array. */ public float[] getPiGain(); /** * Returns the excitation array. * @return the excitation array. */ public float[] getExc(); /** * Returns the innovation array. * @return the innovation array. */ public float[] getInnov(); /** * Sets the encoding submode. * @param mode */ public void setMode(int mode); /** * Returns the encoding submode currently in use. * @return the encoding submode currently in use. */ public int getMode(); /** * Sets the bitrate. * @param bitrate */ public void setBitRate(int bitrate); /** * Sets whether or not to use Variable Bit Rate encoding. * @param vbr */ public void setVbr(boolean vbr); /** * Returns whether or not we are using Variable Bit Rate encoding. * @return whether or not we are using Variable Bit Rate encoding. */ public boolean getVbr(); /** * Sets whether or not to use Voice Activity Detection encoding. * @param vad */ public void setVad(boolean vad); /** * Returns whether or not we are using Voice Activity Detection encoding. * @return whether or not we are using Voice Activity Detection encoding. */ public boolean getVad(); /** * Sets whether or not to use Discontinuous Transmission encoding. * @param dtx */ public void setDtx(boolean dtx); /** * Returns whether or not we are using Discontinuous Transmission encoding. * @return whether or not we are using Discontinuous Transmission encoding. */ public boolean getDtx(); /** * Returns the Average Bit Rate used (0 if ABR is not turned on). * @return the Average Bit Rate used (0 if ABR is not turned on). */ public int getAbr(); /** * Sets the Average Bit Rate. * @param abr - the desired Average Bit Rate. */ public void setAbr(int abr); /** * Sets the Varible Bit Rate Quality. * @param quality - the desired Varible Bit Rate Quality. */ public void setVbrQuality(float quality); /** * Returns the Varible Bit Rate Quality. * @return the Varible Bit Rate Quality. */ public float getVbrQuality(); /** * Sets the algorithmic complexity. * @param complexity - the desired algorithmic complexity (between 1 and 10 - default is 3). */ public void setComplexity(int complexity); /** * Returns the algorthmic complexity. * @return the algorthmic complexity. */ public int getComplexity(); /** * Sets the sampling rate. * @param rate - the sampling rate. */ public void setSamplingRate(int rate); /** * Returns the sampling rate. * @return the sampling rate. */ public int getSamplingRate(); /** * Return LookAhead. * @return LookAhead. */ public int getLookAhead(); /** * Returns the relative quality. * @return the relative quality. */ public float getRelativeQuality(); }
0
java-sources/ai/olami/olami-java-client/1.5.0/org/xiph
java-sources/ai/olami/olami-java-client/1.5.0/org/xiph/speex/Filters.java
/****************************************************************************** * * * Copyright (c) 1999-2003 Wimba S.A., All Rights Reserved. * * * * COPYRIGHT: * * This software is the property of Wimba S.A. * * This software is redistributed under the Xiph.org variant of * * the BSD license. * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions * * are met: * * - Redistributions of source code must retain the above copyright * * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in the * * documentation and/or other materials provided with the distribution. * * - Neither the name of Wimba, the Xiph.org Foundation nor the names of * * its contributors may be used to endorse or promote products derived * * from this software without specific prior written permission. * * * * WARRANTIES: * * This software is made available by the authors in the hope * * that it will be useful, but without any warranty. * * Wimba S.A. is not liable for any consequence related to the * * use of the provided software. * * * * Class: Filters.java * * * * Author: James LAWRENCE * * Modified by: Marc GIMPEL * * Based on code by: Jean-Marc VALIN * * * * Date: March 2003 * * * ******************************************************************************/ /* $Id: Filters.java,v 1.2 2004/10/21 16:21:57 mgimpel Exp $ */ /* Copyright (C) 2002 Jean-Marc Valin Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the Xiph.org Foundation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.xiph.speex; /** * Filters * * @author Jim Lawrence, helloNetwork.com * @author Marc Gimpel, Wimba S.A. (mgimpel@horizonwimba.com) * @version $Revision: 1.2 $ */ public class Filters { private int last_pitch; private float[] last_pitch_gain; private float smooth_gain; private float[] xx; /** * Constructor */ public Filters() { last_pitch_gain = new float[3]; xx = new float[1024]; } /** * Initialisation */ public void init() { last_pitch=0; last_pitch_gain[0]=last_pitch_gain[1]=last_pitch_gain[2]=0; smooth_gain=1; } /** * bw_lpc * @param gamma * @param lpc_in * @param lpc_out * @param order */ public static final void bw_lpc(final float gamma, final float[] lpc_in, final float[] lpc_out, final int order) { float tmp=1; for (int i=0; i<order+1; i++) { lpc_out[i] = tmp * lpc_in[i]; tmp *= gamma; } } /** * filter_mem2 * @param x * @param xs * @param num * @param den * @param N * @param ord * @param mem * @param ms */ public static final void filter_mem2(final float[] x, final int xs, final float[] num, final float[] den, final int N, final int ord, final float[] mem, final int ms) { int i, j; float xi, yi; for (i=0; i<N; i++) { xi = x[xs+i]; x[xs+i] = num[0]*xi + mem[ms+0]; yi = x[xs+i]; for (j=0; j<ord-1; j++) { mem[ms+j] = mem[ms+j+1] + num[j+1]*xi - den[j+1]*yi; } mem[ms+ord-1] = num[ord]*xi - den[ord]*yi; } } /** * filter_mem2 * @param x * @param xs * @param num * @param den * @param y * @param ys * @param N * @param ord * @param mem * @param ms */ public static final void filter_mem2(final float[] x, final int xs, final float[] num, final float[] den, final float[] y, final int ys, final int N, final int ord, final float[] mem, final int ms) { int i, j; float xi, yi; for (i=0; i<N; i++) { xi = x[xs + i]; y[ys + i] = num[0]*xi + mem[0]; yi = y[ys + i]; for (j=0; j<ord-1; j++) { mem[ms+j] = mem[ms+j+1] + num[j+1]*xi - den[j+1]*yi; } mem[ms+ord-1] = num[ord]*xi - den[ord]*yi; } } /** * iir_mem2 * @param x * @param xs * @param den * @param y * @param ys * @param N * @param ord * @param mem */ public static final void iir_mem2(final float[] x, final int xs, final float[] den, final float[] y, final int ys, final int N, final int ord, final float[] mem) { int i, j; for (i=0; i<N; i++) { y[ys+i] = x[xs+i] + mem[0]; for (j=0; j<ord-1; j++) { mem[j] = mem[j+1] - den[j+1]*y[ys+i]; } mem[ord-1] = - den[ord]*y[ys+i]; } } /** * fir_mem2 * @param x * @param xs * @param num * @param y * @param ys * @param N * @param ord * @param mem */ public static final void fir_mem2(final float[] x, final int xs, final float[] num, final float[] y, final int ys, final int N, final int ord, final float[] mem) { int i,j; float xi; for (i=0; i<N; i++) { xi=x[xs+i]; y[ys+i] = num[0]*xi + mem[0]; for (j=0; j<ord-1; j++) { mem[j] = mem[j+1] + num[j+1]*xi; } mem[ord-1] = num[ord]*xi; } } /** * syn_percep_zero * @param xx * @param xxs * @param ak * @param awk1 * @param awk2 * @param y * @param N * @param ord */ public static final void syn_percep_zero(final float[] xx, final int xxs, final float[] ak, final float[] awk1, final float[] awk2, final float[] y, final int N, final int ord) { int i; float[] mem = new float[ord]; // for (i=0;i<ord;i++) // mem[i]=0; filter_mem2(xx, xxs, awk1, ak, y, 0, N, ord, mem, 0); for (i=0; i<ord; i++) mem[i]=0; iir_mem2(y, 0, awk2, y, 0, N, ord, mem); } /** * residue_percep_zero * @param xx * @param xxs * @param ak * @param awk1 * @param awk2 * @param y * @param N * @param ord */ public static final void residue_percep_zero(final float[] xx, final int xxs, final float[] ak, final float[] awk1, final float[] awk2, final float[] y, final int N, final int ord) { int i; float[] mem = new float[ord]; // for (i=0;i<ord;i++) // mem[i]=0; filter_mem2(xx, xxs, ak, awk1, y, 0, N, ord, mem, 0); for (i=0; i<ord; i++) mem[i]=0; fir_mem2(y, 0, awk2, y, 0, N, ord, mem); } /** * fir_mem_up * @param x * @param a * @param y * @param N * @param M * @param mem */ public void fir_mem_up(final float[] x, final float[] a, final float[] y, final int N, final int M, final float[] mem) { int i, j; for (i=0; i<N/2; i++) xx[2*i] = x[N/2-1-i]; for (i=0; i<M-1; i+=2) xx[N+i] = mem[i+1]; for (i=0; i<N; i+=4) { float y0, y1, y2, y3, x0; y0 = y1 = y2 = y3 = 0.f; x0 = xx[N-4-i]; for (j=0; j<M; j+=4) { float x1, a0, a1; a0 = a[j]; a1 = a[j+1]; x1 = xx[N-2+j-i]; y0 += a0 * x1; y1 += a1 * x1; y2 += a0 * x0; y3 += a1 * x0; a0 = a[j+2]; a1 = a[j+3]; x0 = xx[N+j-i]; y0 += a0 * x0; y1 += a1 * x0; y2 += a0 * x1; y3 += a1 * x1; } y[i] = y0; y[i+1] = y1; y[i+2] = y2; y[i+3] = y3; } for (i=0; i<M-1; i+=2) mem[i+1] = xx[i]; } /** * Comb Filter * @param exc - decoded excitation * @param esi * @param new_exc - enhanced excitation * @param nsi * @param nsf - sub-frame size * @param pitch - pitch period * @param pitch_gain - pitch gain (3-tap) * @param comb_gain - gain of comb filter */ public void comb_filter(final float[] exc, final int esi, final float[] new_exc, final int nsi, final int nsf, final int pitch, final float[] pitch_gain, float comb_gain) { int i, j; float exc_energy=0.0f, new_exc_energy=0.0f; float gain, step, fact, g=0.0f; /*Compute excitation energy prior to enhancement*/ for (i=esi; i<esi+nsf; i++) { exc_energy+=exc[i]*exc[i]; } /* Some gain adjustment if pitch is too high or if unvoiced */ g = .5f*Math.abs(pitch_gain[0] + pitch_gain[1] + pitch_gain[2] + last_pitch_gain[0] + last_pitch_gain[1] + last_pitch_gain[2]); if (g>1.3f) comb_gain*=1.3f/g; if (g<.5f) comb_gain*=2.0f*g; step = 1.0f/nsf; fact=0; /* Apply pitch comb-filter (filter out noise between pitch harmonics)*/ for (i=0, j=esi; i<nsf; i++, j++) { fact += step; new_exc[nsi+i] = exc[j] + comb_gain * fact * (pitch_gain[0]*exc[j-pitch+1] + pitch_gain[1]*exc[j-pitch] + pitch_gain[2]*exc[j-pitch-1]) + comb_gain * (1.0f-fact) * (last_pitch_gain[0]*exc[j-last_pitch+1] + last_pitch_gain[1]*exc[j-last_pitch] + last_pitch_gain[2]*exc[j-last_pitch-1]); } last_pitch_gain[0] = pitch_gain[0]; last_pitch_gain[1] = pitch_gain[1]; last_pitch_gain[2] = pitch_gain[2]; last_pitch = pitch; /* Gain after enhancement*/ for (i=nsi;i<nsi+nsf;i++) new_exc_energy+=new_exc[i]*new_exc[i]; /* Compute scaling factor and normalize energy*/ gain = (float) (Math.sqrt(exc_energy/(.1f+new_exc_energy))); if (gain < .5f) { gain=.5f; } if (gain>1.0f) { gain=1.0f; } for (i=nsi;i<nsi+nsf;i++) { smooth_gain = .96f*smooth_gain + .04f*gain; new_exc[i] *= smooth_gain; } } /** * Quadrature Mirror Filter to Split the band in two. * A 16kHz signal is thus divided into two 8kHz signals representing the low and high bands. * (used by wideband encoder) * @param xx * @param aa * @param y1 * @param y2 * @param N * @param M * @param mem */ public static final void qmf_decomp(final float[] xx, final float[] aa, final float[] y1, final float[] y2, final int N, final int M, final float[] mem) { int i,j,k,M2; float[] a; float[] x; int x2; a = new float[M]; x = new float[N+M-1]; x2=M-1; M2=M>>1; for (i=0; i<M; i++) a[M-i-1]=aa[i]; for (i=0; i<M-1; i++) x[i]=mem[M-i-2]; for (i=0; i<N; i++) x[i+M-1]=xx[i]; for (i=0, k=0; i<N; i+=2, k++) { y1[k]=0; y2[k]=0; for (j=0; j<M2; j++) { y1[k]+=a[j]*(x[i+j]+x[x2+i-j]); y2[k]-=a[j]*(x[i+j]-x[x2+i-j]); j++; y1[k]+=a[j]*(x[i+j]+x[x2+i-j]); y2[k]+=a[j]*(x[i+j]-x[x2+i-j]); } } for (i=0;i<M-1;i++) mem[i]=xx[N-i-1]; } }
0
java-sources/ai/olami/olami-java-client/1.5.0/org/xiph
java-sources/ai/olami/olami-java-client/1.5.0/org/xiph/speex/HighLspQuant.java
/****************************************************************************** * * * Copyright (c) 1999-2003 Wimba S.A., All Rights Reserved. * * * * COPYRIGHT: * * This software is the property of Wimba S.A. * * This software is redistributed under the Xiph.org variant of * * the BSD license. * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions * * are met: * * - Redistributions of source code must retain the above copyright * * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in the * * documentation and/or other materials provided with the distribution. * * - Neither the name of Wimba, the Xiph.org Foundation nor the names of * * its contributors may be used to endorse or promote products derived * * from this software without specific prior written permission. * * * * WARRANTIES: * * This software is made available by the authors in the hope * * that it will be useful, but without any warranty. * * Wimba S.A. is not liable for any consequence related to the * * use of the provided software. * * * * Class: HighLu.java * * * * Author: James LAWRENCE * * Modified by: Marc GIMPEL * * Based on code by: Jean-Marc VALIN * * * * Date: March 2003 * * * ******************************************************************************/ /* $Id: HighLspQuant.java,v 1.2 2004/10/21 16:21:57 mgimpel Exp $ */ /* Copyright (C) 2002 Jean-Marc Valin Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the Xiph.org Foundation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.xiph.speex; /** * LSP Quantisation and Unquantisation (high) * * @author Jim Lawrence, helloNetwork.com * @author Marc Gimpel, Wimba S.A. (mgimpel@horizonwimba.com) * @version $Revision: 1.2 $ */ public class HighLspQuant extends LspQuant { /** * Line Spectral Pair Quantification (high). * @param lsp - Line Spectral Pairs table. * @param qlsp - Quantified Line Spectral Pairs table. * @param order * @param bits - Speex bits buffer. */ public final void quant(final float[] lsp, final float[] qlsp, final int order, final Bits bits) { int i; float tmp1, tmp2; int id; float[] quant_weight = new float[MAX_LSP_SIZE]; for (i=0;i<order;i++) qlsp[i]=lsp[i]; quant_weight[0] = 1/(qlsp[1]-qlsp[0]); quant_weight[order-1] = 1/(qlsp[order-1]-qlsp[order-2]); for (i=1;i<order-1;i++) { tmp1 = 1/(qlsp[i]-qlsp[i-1]); tmp2 = 1/(qlsp[i+1]-qlsp[i]); quant_weight[i] = tmp1 > tmp2 ? tmp1 : tmp2; } for (i=0;i<order;i++) qlsp[i]-=(.3125*i+.75); for (i=0;i<order;i++) qlsp[i]*=256; id = lsp_quant(qlsp, 0, high_lsp_cdbk, 64, order); bits.pack(id, 6); for (i=0;i<order;i++) qlsp[i]*=2; id = lsp_weight_quant(qlsp, 0, quant_weight, 0, high_lsp_cdbk2, 64, order); bits.pack(id, 6); for (i=0;i<order;i++) qlsp[i]*=0.0019531; for (i=0;i<order;i++) qlsp[i]=lsp[i]-qlsp[i]; } /** * Line Spectral Pair Unquantification (high). * @param lsp - Line Spectral Pairs table. * @param order * @param bits - Speex bits buffer. */ public final void unquant(final float[] lsp, final int order, final Bits bits) { for (int i=0;i<order;i++) { lsp[i]=.3125f*i+.75f; } unpackPlus(lsp, high_lsp_cdbk, bits, 0.0039062f, order, 0); unpackPlus(lsp, high_lsp_cdbk2, bits, 0.0019531f, order, 0); } }
0
java-sources/ai/olami/olami-java-client/1.5.0/org/xiph
java-sources/ai/olami/olami-java-client/1.5.0/org/xiph/speex/Inband.java
/****************************************************************************** * * * Copyright (c) 1999-2003 Wimba S.A., All Rights Reserved. * * * * COPYRIGHT: * * This software is the property of Wimba S.A. * * This software is redistributed under the Xiph.org variant of * * the BSD license. * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions * * are met: * * - Redistributions of source code must retain the above copyright * * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in the * * documentation and/or other materials provided with the distribution. * * - Neither the name of Wimba, the Xiph.org Foundation nor the names of * * its contributors may be used to endorse or promote products derived * * from this software without specific prior written permission. * * * * WARRANTIES: * * This software is made available by the authors in the hope * * that it will be useful, but without any warranty. * * Wimba S.A. is not liable for any consequence related to the * * use of the provided software. * * * * Class: Inband.java * * * * Author: Marc GIMPEL * * * * Date: 14th July 2003 * * * ******************************************************************************/ /* $Id: Inband.java,v 1.2 2004/10/21 16:21:57 mgimpel Exp $ */ package org.xiph.speex; import java.io.StreamCorruptedException; /** * Speex in-band and User in-band controls. * * @author Marc Gimpel, Wimba S.A. (mgimpel@horizonwimba.com) * @version $Revision: 1.2 $ */ public class Inband { private Stereo stereo; /** * Constructor. * @param stereo */ public Inband (final Stereo stereo) { this.stereo = stereo; } /** * Speex in-band request (submode=14). * @param bits - Speex bits buffer. * @throws StreamCorruptedException If stream seems corrupted. */ public void speexInbandRequest(final Bits bits) throws StreamCorruptedException { int code = bits.unpack(4); switch (code) { case 0: // asks the decoder to set perceptual enhancment off (0) or on (1) bits.advance(1); break; case 1: // asks (if 1) the encoder to be less "aggressive" due to high packet loss bits.advance(1); break; case 2: // asks the encoder to switch to mode N bits.advance(4); break; case 3: // asks the encoder to switch to mode N for low-band bits.advance(4); break; case 4: // asks the encoder to switch to mode N for high-band bits.advance(4); break; case 5: // asks the encoder to switch to quality N for VBR bits.advance(4); break; case 6: // request acknowledgement (0=no, 1=all, 2=only for inband data) bits.advance(4); break; case 7: // asks the encoder to set CBR(0), VAD(1), DTX(3), VBR(5), VBR+DTX(7) bits.advance(4); break; case 8: // transmit (8-bit) character to the other end bits.advance(8); break; case 9: // intensity stereo information // setup the stereo decoder; to skip: tmp = bits.unpack(8); break; stereo.init(bits); // read 8 bits break; case 10: // announce maximum bit-rate acceptable (N in byets/second) bits.advance(16); break; case 11: // reserved bits.advance(16); break; case 12: // Acknowledge receiving packet N bits.advance(32); break; case 13: // reserved bits.advance(32); break; case 14: // reserved bits.advance(64); break; case 15: // reserved bits.advance(64); break; default: } } /** * User in-band request (submode=13). * @param bits - Speex bits buffer. * @throws StreamCorruptedException If stream seems corrupted. */ public void userInbandRequest(final Bits bits) throws StreamCorruptedException { int req_size = bits.unpack(4); bits.advance(5+8*req_size); } }
0
java-sources/ai/olami/olami-java-client/1.5.0/org/xiph
java-sources/ai/olami/olami-java-client/1.5.0/org/xiph/speex/LbrLspQuant.java
/****************************************************************************** * * * Copyright (c) 1999-2003 Wimba S.A., All Rights Reserved. * * * * COPYRIGHT: * * This software is the property of Wimba S.A. * * This software is redistributed under the Xiph.org variant of * * the BSD license. * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions * * are met: * * - Redistributions of source code must retain the above copyright * * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in the * * documentation and/or other materials provided with the distribution. * * - Neither the name of Wimba, the Xiph.org Foundation nor the names of * * its contributors may be used to endorse or promote products derived * * from this software without specific prior written permission. * * * * WARRANTIES: * * This software is made available by the authors in the hope * * that it will be useful, but without any warranty. * * Wimba S.A. is not liable for any consequence related to the * * use of the provided software. * * * * Class: LbrLU.java * * * * Author: James LAWRENCE * * Modified by: Marc GIMPEL * * Based on code by: Jean-Marc VALIN * * * * Date: March 2003 * * * ******************************************************************************/ /* $Id: LbrLspQuant.java,v 1.2 2004/10/21 16:21:57 mgimpel Exp $ */ /* Copyright (C) 2002 Jean-Marc Valin Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the Xiph.org Foundation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.xiph.speex; /** * LSP Quantisation and Unquantisation (Lbr) * * @author Jim Lawrence, helloNetwork.com * @author Marc Gimpel, Wimba S.A. (mgimpel@horizonwimba.com) * @version $Revision: 1.2 $ */ public class LbrLspQuant extends LspQuant { /** * Line Spectral Pair Quantification (Lbr). * @param lsp - Line Spectral Pairs table. * @param qlsp - Quantified Line Spectral Pairs table. * @param order * @param bits - Speex bits buffer. */ public final void quant(final float[] lsp, final float[] qlsp, final int order, final Bits bits) { int i; float tmp1, tmp2; int id; float[] quant_weight = new float[MAX_LSP_SIZE]; for (i=0;i<order;i++) qlsp[i]=lsp[i]; quant_weight[0] = 1/(qlsp[1]-qlsp[0]); quant_weight[order-1] = 1/(qlsp[order-1]-qlsp[order-2]); for (i=1;i<order-1;i++) { tmp1 = 1/((.15f+qlsp[i]-qlsp[i-1])*(.15f+qlsp[i]-qlsp[i-1])); tmp2 = 1/((.15f+qlsp[i+1]-qlsp[i])*(.15f+qlsp[i+1]-qlsp[i])); quant_weight[i] = tmp1 > tmp2 ? tmp1 : tmp2; } for (i=0;i<order;i++) qlsp[i]-=(.25*i+.25); for (i=0;i<order;i++) qlsp[i]*=256; id = lsp_quant(qlsp, 0, cdbk_nb, NB_CDBK_SIZE, order); bits.pack(id, 6); for (i=0;i<order;i++) qlsp[i]*=2; id = lsp_weight_quant(qlsp, 0, quant_weight, 0, cdbk_nb_low1, NB_CDBK_SIZE_LOW1, 5); bits.pack(id, 6); id = lsp_weight_quant(qlsp, 5, quant_weight, 5, cdbk_nb_high1, NB_CDBK_SIZE_HIGH1, 5); bits.pack(id, 6); for (i=0;i<order;i++) qlsp[i]*=0.0019531; for (i=0;i<order;i++) qlsp[i]=lsp[i]-qlsp[i]; } /** * Line Spectral Pair Unquantification (Lbr). * @param lsp - Line Spectral Pairs table. * @param order * @param bits - Speex bits buffer. */ public final void unquant(final float[] lsp, final int order, final Bits bits) { for (int i=0;i<order;i++){ lsp[i]=.25f*i+.25f; } unpackPlus(lsp, cdbk_nb, bits, 0.0039062f, 10, 0); unpackPlus(lsp, cdbk_nb_low1, bits, 0.0019531f, 5, 0); unpackPlus(lsp, cdbk_nb_high1, bits, 0.0019531f, 5, 5); } }
0
java-sources/ai/olami/olami-java-client/1.5.0/org/xiph
java-sources/ai/olami/olami-java-client/1.5.0/org/xiph/speex/Lpc.java
/****************************************************************************** * * * Copyright (c) 1999-2003 Wimba S.A., All Rights Reserved. * * * * COPYRIGHT: * * This software is the property of Wimba S.A. * * This software is redistributed under the Xiph.org variant of * * the BSD license. * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions * * are met: * * - Redistributions of source code must retain the above copyright * * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in the * * documentation and/or other materials provided with the distribution. * * - Neither the name of Wimba, the Xiph.org Foundation nor the names of * * its contributors may be used to endorse or promote products derived * * from this software without specific prior written permission. * * * * WARRANTIES: * * This software is made available by the authors in the hope * * that it will be useful, but without any warranty. * * Wimba S.A. is not liable for any consequence related to the * * use of the provided software. * * * * Class: Lpc.java * * * * Author: Marc GIMPEL * * Based on code by: Jean-Marc VALIN * * * * Date: 9th April 2003 * * * ******************************************************************************/ /* $Id: Lpc.java,v 1.2 2004/10/21 16:21:57 mgimpel Exp $ */ /* Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann, Technische Universitaet Berlin Any use of this software is permitted provided that this notice is not removed and that neither the authors nor the Technische Universitaet Berlin are deemed to have made any representations as to the suitability of this software for any purpose nor are held responsible for any defects of this software. THERE IS ABSOLUTELY NO WARRANTY FOR THIS SOFTWARE. As a matter of courtesy, the authors request to be informed about uses this software has found, about bugs in this software, and about any improvements that may be of general interest. Berlin, 28.11.1994 Jutta Degener Carsten Bormann Code slightly modified by Jean-Marc Valin Speex License: Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the Xiph.org Foundation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.xiph.speex; /** * LPC - and Reflection Coefficients. * * <p>The next two functions calculate linear prediction coefficients * and/or the related reflection coefficients from the first P_MAX+1 * values of the autocorrelation function. * * <p>Invented by N. Levinson in 1947, modified by J. Durbin in 1959. * * @author Marc Gimpel, Wimba S.A. (mgimpel@horizonwimba.com) * @version $Revision: 1.2 $ */ public class Lpc { /** * Returns minimum mean square error. * @param lpc - float[0...p-1] LPC coefficients * @param ac - in: float[0...p] autocorrelation values * @param ref - out: float[0...p-1] reflection coef's * @param p * @return minimum mean square error. */ public static float wld(final float[] lpc, final float[] ac, final float[] ref, final int p) { int i, j; float r, error = ac[0]; if (ac[0] == 0) { for (i=0; i<p; i++) ref[i] = 0; return 0; } for (i = 0; i < p; i++) { /* Sum up this iteration's reflection coefficient. */ r = -ac[i + 1]; for (j = 0; j < i; j++) r -= lpc[j] * ac[i - j]; ref[i] = r /= error; /* Update LPC coefficients and total error. */ lpc[i] = r; for (j = 0; j < i/2; j++) { float tmp = lpc[j]; lpc[j] += r * lpc[i-1-j]; lpc[i-1-j] += r * tmp; } if ((i % 2) != 0) lpc[j] += lpc[j] * r; error *= 1.0 - r * r; } return error; } /** * Compute the autocorrelation * ,--, * ac(i) = > x(n) * x(n-i) for all n * `--' * for lags between 0 and lag-1, and x == 0 outside 0...n-1 * @param x - in: float[0...n-1] samples x * @param ac - out: float[0...lag-1] ac values * @param lag * @param n */ public static void autocorr(final float[] x, final float[] ac, int lag, final int n) { float d; int i; while (lag-- > 0) { for (i=lag, d=0; i<n; i++) d += x[i] * x[i-lag]; ac[lag] = d; } } }
0
java-sources/ai/olami/olami-java-client/1.5.0/org/xiph
java-sources/ai/olami/olami-java-client/1.5.0/org/xiph/speex/Lsp.java
/****************************************************************************** * * * Copyright (c) 1999-2003 Wimba S.A., All Rights Reserved. * * * * COPYRIGHT: * * This software is the property of Wimba S.A. * * This software is redistributed under the Xiph.org variant of * * the BSD license. * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions * * are met: * * - Redistributions of source code must retain the above copyright * * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in the * * documentation and/or other materials provided with the distribution. * * - Neither the name of Wimba, the Xiph.org Foundation nor the names of * * its contributors may be used to endorse or promote products derived * * from this software without specific prior written permission. * * * * WARRANTIES: * * This software is made available by the authors in the hope * * that it will be useful, but without any warranty. * * Wimba S.A. is not liable for any consequence related to the * * use of the provided software. * * * * Class: Lsp.java * * * * Author: James LAWRENCE * * Modified by: Marc GIMPEL * * Based on code by: Jean-Marc VALIN * * * * Date: March 2003 * * * ******************************************************************************/ /* $Id: Lsp.java,v 1.2 2004/10/21 16:21:57 mgimpel Exp $ */ /* Original copyright FILE........: AKSLSPD.C TYPE........: Turbo C COMPANY.....: Voicetronix AUTHOR......: David Rowe DATE CREATED: 24/2/93 Modified by Jean-Marc Valin Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the Xiph.org Foundation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.xiph.speex; /** * Line Spectral Pair * * @author Jim Lawrence, helloNetwork.com * @author Marc Gimpel, Wimba S.A. (mgimpel@horizonwimba.com) * @version $Revision: 1.2 $ */ public class Lsp { private float[] pw; /** * Constructor */ public Lsp() { pw = new float[42]; } /*-------------------------------------------------------------------------*\ FUNCTION....: cheb_poly_eva() AUTHOR......: David Rowe DATE CREATED: 24/2/93 This function evaluates a series of Chebyshev polynomials \*-------------------------------------------------------------------------*/ /** * This function evaluates a series of Chebyshev polynomials. * @param coef - coefficients of the polynomial to be evaluated. * @param x - the point where polynomial is to be evaluated. * @param m - order of the polynomial. * @return the value of the polynomial at point x. */ public static final float cheb_poly_eva(final float[] coef, float x, final int m) { int i; float sum; float[] T; int m2 = m >> 1; /* Allocate memory for Chebyshev series formulation */ T = new float[m2+1]; /* Initialise values */ T[0] = 1; T[1] = x; /* Evaluate Chebyshev series formulation using iterative approach */ /* Evaluate polynomial and return value also free memory space */ sum = coef[m2] + coef[m2-1]*x; x *= 2; for (i=2; i<=m2; i++) { T[i] = x*T[i-1] - T[i-2]; sum += coef[m2-i] * T[i]; } return sum; } /*-------------------------------------------------------------------------*\ FUNCTION....: lpc_to_lsp() AUTHOR......: David Rowe DATE CREATED: 24/2/93 This function converts LPC coefficients to LSP coefficients. \*-------------------------------------------------------------------------*/ /** * This function converts LPC coefficients to LSP coefficients. * @param a - LPC coefficients. * @param lpcrdr - order of LPC coefficients (10). * @param freq - LSP frequencies in the x domain. * @param nb - number of sub-intervals (4). * @param delta - grid spacing interval (0.02). * @return the number of roots (the LSP coefs are returned in the array). */ public static int lpc2lsp (final float[] a, final int lpcrdr, final float[] freq, final int nb, final float delta) { float psuml, psumr, psumm, temp_xr, xl, xr, xm=0; float temp_psumr; int i, j, m, flag, k; float[] Q; // ptrs for memory allocation float[] P; int px; // ptrs of respective P'(z) & Q'(z) int qx; int p; int q; float[] pt; // ptr used for cheb_poly_eval() whether P' or Q' int roots = 0; // DR 8/2/94: number of roots found flag = 1; // program is searching for a root when, 1 else has found one m = lpcrdr/2; // order of P'(z) & Q'(z) polynomials /* Allocate memory space for polynomials */ Q = new float[m+1]; P = new float[m+1]; /* determine P'(z)'s and Q'(z)'s coefficients where P'(z) = P(z)/(1 + z^(-1)) and Q'(z) = Q(z)/(1-z^(-1)) */ px = 0; /* initialise ptrs */ qx = 0; p = px; q = qx; P[px++] = 1.0f; Q[qx++] = 1.0f; for (i=1; i<=m; i++){ P[px++] = a[i]+a[lpcrdr+1-i]-P[p++]; Q[qx++] = a[i]-a[lpcrdr+1-i]+Q[q++]; } px = 0; qx = 0; for (i=0; i<m; i++){ P[px] = 2*P[px]; Q[qx] = 2*Q[qx]; px++; qx++; } px = 0; /* re-initialise ptrs */ qx = 0; /* Search for a zero in P'(z) polynomial first and then alternate to Q'(z). Keep alternating between the two polynomials as each zero is found */ xr = 0; /* initialise xr to zero */ xl = 1.0f; /* start at point xl = 1 */ for (j=0; j<lpcrdr; j++){ if (j%2 != 0) /* determines whether P' or Q' is eval. */ pt = Q; else pt = P; psuml = cheb_poly_eva(pt, xl, lpcrdr); /* evals poly. at xl */ flag = 1; while ((flag == 1) && (xr >= -1.0)) { float dd; /* Modified by JMV to provide smaller steps around x=+-1 */ dd=(float)(delta*(1-.9*xl*xl)); if (Math.abs(psuml)<.2) dd *= .5; xr = xl - dd; /* interval spacing */ psumr = cheb_poly_eva(pt, xr, lpcrdr); /* poly(xl-delta_x) */ temp_psumr = psumr; temp_xr = xr; /* if no sign change increment xr and re-evaluate poly(xr). Repeat til sign change. if a sign change has occurred the interval is bisected and then checked again for a sign change which determines in which interval the zero lies in. If there is no sign change between poly(xm) and poly(xl) set interval between xm and xr else set interval between xl and xr and repeat till root is located within the specified limits */ if ((psumr*psuml)<0.0) { roots++; psumm = psuml; for (k=0; k<=nb; k++){ xm = (xl+xr)/2; /* bisect the interval */ psumm = cheb_poly_eva(pt, xm, lpcrdr); if (psumm*psuml>0.) { psuml = psumm; xl = xm; } else { psumr = psumm; xr = xm; } } /* once zero is found, reset initial interval to xr */ freq[j] = xm; xl = xm; flag = 0; /* reset flag for next search */ } else { psuml = temp_psumr; xl = temp_xr; } } } return roots; } /** * Line Spectral Pair to Linear Prediction Coefficients * @param freq * @param ak * @param lpcrdr */ public void lsp2lpc(final float[] freq, final float[] ak, final int lpcrdr) { int i, j; float xout1, xout2, xin1, xin2; int n1, n2 ,n3, n4=0; int m = lpcrdr/2; for (i=0; i < 4*m+2; i++) { pw[i] = 0.0f; } xin1 = 1.0f; xin2 = 1.0f; /* reconstruct P(z) and Q(z) by cascading second order polynomials in form 1 - 2xz(-1) +z(-2), where x is the LSP coefficient */ for (j=0; j<=lpcrdr; j++) { int i2=0; for (i=0; i<m; i++, i2+=2) { n1 = i*4; n2 = n1 + 1; n3 = n2 + 1; n4 = n3 + 1; xout1 = xin1 - 2*(freq[i2]) * pw[n1] + pw[n2]; xout2 = xin2 - 2*(freq[i2+1]) * pw[n3] + pw[n4]; pw[n2] = pw[n1]; pw[n4] = pw[n3]; pw[n1] = xin1; pw[n3] = xin2; xin1 = xout1; xin2 = xout2; } xout1 = xin1 + pw[n4+1]; xout2 = xin2 - pw[n4+2]; ak[j] = (xout1 + xout2)*0.5f; pw[n4+1] = xin1; pw[n4+2] = xin2; xin1 = 0.0f; xin2 = 0.0f; } } /** * Makes sure the LSPs are stable. * @param lsp * @param len * @param margin */ public static void enforce_margin(final float[] lsp, final int len, final float margin) { int i; if (lsp[0]<margin) lsp[0]=margin; if (lsp[len-1]>(float)Math.PI-margin) lsp[len-1]=(float)Math.PI-margin; for (i=1;i<len-1;i++) { if (lsp[i]<lsp[i-1]+margin) lsp[i]=lsp[i-1]+margin; if (lsp[i]>lsp[i+1]-margin) lsp[i]= .5f * (lsp[i] + lsp[i+1]-margin); } } }
0
java-sources/ai/olami/olami-java-client/1.5.0/org/xiph
java-sources/ai/olami/olami-java-client/1.5.0/org/xiph/speex/LspQuant.java
/****************************************************************************** * * * Copyright (c) 1999-2003 Wimba S.A., All Rights Reserved. * * * * COPYRIGHT: * * This software is the property of Wimba S.A. * * This software is redistributed under the Xiph.org variant of * * the BSD license. * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions * * are met: * * - Redistributions of source code must retain the above copyright * * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in the * * documentation and/or other materials provided with the distribution. * * - Neither the name of Wimba, the Xiph.org Foundation nor the names of * * its contributors may be used to endorse or promote products derived * * from this software without specific prior written permission. * * * * WARRANTIES: * * This software is made available by the authors in the hope * * that it will be useful, but without any warranty. * * Wimba S.A. is not liable for any consequence related to the * * use of the provided software. * * * * Class: LU.java * * * * Author: James LAWRENCE * * Modified by: Marc GIMPEL * * Based on code by: Jean-Marc VALIN * * * * Date: March 2003 * * * ******************************************************************************/ /* $Id: LspQuant.java,v 1.2 2004/10/21 16:21:57 mgimpel Exp $ */ /* Copyright (C) 2002 Jean-Marc Valin Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the Xiph.org Foundation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.xiph.speex; /** * Abstract class that is the base for the various LSP Quantisation and * Unquantisation methods. * * @author Jim Lawrence, helloNetwork.com * @author Marc Gimpel, Wimba S.A. (mgimpel@horizonwimba.com) * @version $Revision: 1.2 $ */ public abstract class LspQuant implements Codebook { /** */ public static final int MAX_LSP_SIZE = 20; /** * Constructor */ protected LspQuant() { } /** * Line Spectral Pair Quantification. * @param lsp - Line Spectral Pairs table. * @param qlsp - Quantified Line Spectral Pairs table. * @param order * @param bits - Speex bits buffer. */ public abstract void quant(final float[] lsp, final float[] qlsp, final int order, final Bits bits); /** * Line Spectral Pair Unquantification. * @param lsp - Line Spectral Pairs table. * @param order * @param bits - Speex bits buffer. */ public abstract void unquant(float[] lsp, int order, Bits bits); /** * Read the next 6 bits from the buffer, and using the value read and the * given codebook, rebuild LSP table. * @param lsp * @param tab * @param bits - Speex bits buffer. * @param k * @param ti * @param li */ protected void unpackPlus(final float[] lsp, final int[] tab, final Bits bits, final float k, final int ti, final int li) { int id=bits.unpack(6); for (int i=0;i<ti;i++) lsp[i+li] += k * (float)tab[id*ti+i]; } /** * LSP quantification * Note: x is modified * @param x * @param xs * @param cdbk * @param nbVec * @param nbDim * @return the index of the best match in the codebook * (NB x is also modified). */ protected static int lsp_quant(final float[] x, final int xs, final int[] cdbk, final int nbVec, final int nbDim) { int i, j; float dist, tmp; float best_dist=0; int best_id=0; int ptr=0; for (i=0; i<nbVec; i++) { dist=0; for (j=0; j<nbDim; j++) { tmp=(x[xs+j]-cdbk[ptr++]); dist+=tmp*tmp; } if (dist<best_dist || i==0) { best_dist=dist; best_id=i; } } for (j=0; j<nbDim; j++) x[xs+j] -= cdbk[best_id*nbDim+j]; return best_id; } /** * LSP weighted quantification * Note: x is modified * @param x * @param xs * @param weight * @param ws * @param cdbk * @param nbVec * @param nbDim * @return the index of the best match in the codebook * (NB x is also modified). */ protected static int lsp_weight_quant(final float[] x, final int xs, final float[] weight, final int ws, final int[] cdbk, final int nbVec, final int nbDim) { int i,j; float dist, tmp; float best_dist=0; int best_id=0; int ptr=0; for (i=0; i<nbVec; i++) { dist=0; for (j=0; j<nbDim; j++) { tmp=(x[xs+j]-cdbk[ptr++]); dist+=weight[ws+j]*tmp*tmp; } if (dist<best_dist || i==0) { best_dist=dist; best_id=i; } } for (j=0; j<nbDim; j++) x[xs+j] -= cdbk[best_id*nbDim+j]; return best_id; } }
0
java-sources/ai/olami/olami-java-client/1.5.0/org/xiph
java-sources/ai/olami/olami-java-client/1.5.0/org/xiph/speex/Ltp.java
/****************************************************************************** * * * Copyright (c) 1999-2003 Wimba S.A., All Rights Reserved. * * * * COPYRIGHT: * * This software is the property of Wimba S.A. * * This software is redistributed under the Xiph.org variant of * * the BSD license. * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions * * are met: * * - Redistributions of source code must retain the above copyright * * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in the * * documentation and/or other materials provided with the distribution. * * - Neither the name of Wimba, the Xiph.org Foundation nor the names of * * its contributors may be used to endorse or promote products derived * * from this software without specific prior written permission. * * * * WARRANTIES: * * This software is made available by the authors in the hope * * that it will be useful, but without any warranty. * * Wimba S.A. is not liable for any consequence related to the * * use of the provided software. * * * * Class: Ltp.java * * * * Author: James LAWRENCE * * Modified by: Marc GIMPEL * * Based on code by: Jean-Marc VALIN * * * * Date: March 2003 * * * ******************************************************************************/ /* $Id: Ltp.java,v 1.2 2004/10/21 16:21:57 mgimpel Exp $ */ /* Copyright (C) 2002 Jean-Marc Valin Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the Xiph.org Foundation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.xiph.speex; /** * Abstract class that is the base for the various LTP (Long Term Prediction) * Quantisation and Unquantisation methods. * * @author Jim Lawrence, helloNetwork.com * @author Marc Gimpel, Wimba S.A. (mgimpel@horizonwimba.com) * @version $Revision: 1.2 $ */ public abstract class Ltp { /** * Long Term Prediction Quantification. * @return pitch */ public abstract int quant(float[] target, float[] sw, int sws, float[] ak, float[] awk1, float[] awk2, float[] exc, int es, int start, int end, float pitch_coef, int p, int nsf, Bits bits, float[] exc2, int e2s, float[] r, int complexity); /** * Long Term Prediction Unquantification. * @param exc - Excitation * @param es - Excitation offset * @param start - Smallest pitch value allowed * @param pitch_coef - Voicing (pitch) coefficient * @param nsf - Number of samples in subframe * @param gain_val * @param bits - Speex bits buffer. * @param count_lost * @param subframe_offset * @param last_pitch_gain * @return pitch */ public abstract int unquant(float[] exc, int es, int start, float pitch_coef, int nsf, float[] gain_val, Bits bits, int count_lost, int subframe_offset, float last_pitch_gain); /** * Calculates the inner product of the given vectors. * @param x - first vector. * @param xs - offset of the first vector. * @param y - second vector. * @param ys - offset of the second vector. * @param len - length of the vectors. * @return the inner product of the given vectors. */ protected static float inner_prod(float[] x, int xs, float[] y, int ys, int len) { int i; float sum1=0,sum2=0,sum3=0,sum4=0; for (i=0;i<len;) { sum1 += x[xs+i]*y[ys+i]; sum2 += x[xs+i+1]*y[ys+i+1]; sum3 += x[xs+i+2]*y[ys+i+2]; sum4 += x[xs+i+3]*y[ys+i+3]; i+=4; } return sum1+sum2+sum3+sum4; } /** * Find the n-best pitch in Open Loop. * @param sw * @param swIdx * @param start * @param end * @param len * @param pitch * @param gain * @param N */ protected static void open_loop_nbest_pitch(final float[] sw, final int swIdx, final int start, final int end, final int len, final int[] pitch, final float[] gain, final int N) { int i, j, k; /*float corr=0;*/ /*float energy;*/ float[] best_score; float e0; float[] corr, energy, score; best_score = new float[N]; corr = new float[end-start+1]; energy = new float[end-start+2]; score = new float[end-start+1]; for (i=0; i<N; i++) { best_score[i]=-1; gain[i]=0; pitch[i]=start; } energy[0]=inner_prod(sw, swIdx-start, sw, swIdx-start, len); e0=inner_prod(sw, swIdx, sw, swIdx, len); for (i=start; i<=end; i++) { /* Update energy for next pitch*/ energy[i-start+1] = energy[i-start] + sw[swIdx-i-1]*sw[swIdx-i-1] - sw[swIdx-i+len-1]*sw[swIdx-i+len-1]; if (energy[i-start+1] < 1) energy[i-start+1]=1; } for (i=start; i<=end; i++) { corr[i-start]=0; score[i-start]=0; } for (i=start; i<=end; i++) { /* Compute correlation*/ corr[i-start]=inner_prod(sw, swIdx, sw, swIdx-i, len); score[i-start]=corr[i-start]*corr[i-start]/(energy[i-start]+1); } for (i=start; i<=end; i++) { if (score[i-start] > best_score[N-1]) { float g1, g; g1 = corr[i-start]/(energy[i-start]+10); g = (float) Math.sqrt(g1*corr[i-start]/(e0+10)); if (g>g1) g=g1; if (g<0) g=0; for (j=0; j<N; j++) { if (score[i-start] > best_score[j]) { for (k=N-1; k>j; k--) { best_score[k]=best_score[k-1]; pitch[k]=pitch[k-1]; gain[k] = gain[k-1]; } best_score[j]=score[i-start]; pitch[j]=i; gain[j]=g; break; } } } } } }