repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
self
self-master/lib/opencv/android/sdk/java/src/org/opencv/ml/LogisticRegression.java
// // This file is auto-generated. Please don't modify it! // package org.opencv.ml; import org.opencv.core.Mat; import org.opencv.core.TermCriteria; // C++: class LogisticRegression //javadoc: LogisticRegression public class LogisticRegression extends StatModel { protected LogisticRegression(long addr) { super(addr); } public static final int REG_DISABLE = -1, REG_L1 = 0, REG_L2 = 1, BATCH = 0, MINI_BATCH = 1; // // C++: Mat get_learnt_thetas() // //javadoc: LogisticRegression::get_learnt_thetas() public Mat get_learnt_thetas() { Mat retVal = new Mat(get_learnt_thetas_0(nativeObj)); return retVal; } // // C++: static Ptr_LogisticRegression create() // //javadoc: LogisticRegression::create() public static LogisticRegression create() { LogisticRegression retVal = new LogisticRegression(create_0()); return retVal; } // // C++: TermCriteria getTermCriteria() // //javadoc: LogisticRegression::getTermCriteria() public TermCriteria getTermCriteria() { TermCriteria retVal = new TermCriteria(getTermCriteria_0(nativeObj)); return retVal; } // // C++: double getLearningRate() // //javadoc: LogisticRegression::getLearningRate() public double getLearningRate() { double retVal = getLearningRate_0(nativeObj); return retVal; } // // C++: float predict(Mat samples, Mat& results = Mat(), int flags = 0) // //javadoc: LogisticRegression::predict(samples, results, flags) public float predict(Mat samples, Mat results, int flags) { float retVal = predict_0(nativeObj, samples.nativeObj, results.nativeObj, flags); return retVal; } //javadoc: LogisticRegression::predict(samples) public float predict(Mat samples) { float retVal = predict_1(nativeObj, samples.nativeObj); return retVal; } // // C++: int getIterations() // //javadoc: LogisticRegression::getIterations() public int getIterations() { int retVal = getIterations_0(nativeObj); return retVal; } // // C++: int getMiniBatchSize() // //javadoc: LogisticRegression::getMiniBatchSize() public int getMiniBatchSize() { int retVal = getMiniBatchSize_0(nativeObj); return retVal; } // // C++: int getRegularization() // //javadoc: LogisticRegression::getRegularization() public int getRegularization() { int retVal = getRegularization_0(nativeObj); return retVal; } // // C++: int getTrainMethod() // //javadoc: LogisticRegression::getTrainMethod() public int getTrainMethod() { int retVal = getTrainMethod_0(nativeObj); return retVal; } // // C++: void setIterations(int val) // //javadoc: LogisticRegression::setIterations(val) public void setIterations(int val) { setIterations_0(nativeObj, val); return; } // // C++: void setLearningRate(double val) // //javadoc: LogisticRegression::setLearningRate(val) public void setLearningRate(double val) { setLearningRate_0(nativeObj, val); return; } // // C++: void setMiniBatchSize(int val) // //javadoc: LogisticRegression::setMiniBatchSize(val) public void setMiniBatchSize(int val) { setMiniBatchSize_0(nativeObj, val); return; } // // C++: void setRegularization(int val) // //javadoc: LogisticRegression::setRegularization(val) public void setRegularization(int val) { setRegularization_0(nativeObj, val); return; } // // C++: void setTermCriteria(TermCriteria val) // //javadoc: LogisticRegression::setTermCriteria(val) public void setTermCriteria(TermCriteria val) { setTermCriteria_0(nativeObj, val.type, val.maxCount, val.epsilon); return; } // // C++: void setTrainMethod(int val) // //javadoc: LogisticRegression::setTrainMethod(val) public void setTrainMethod(int val) { setTrainMethod_0(nativeObj, val); return; } @Override protected void finalize() throws Throwable { delete(nativeObj); } // C++: Mat get_learnt_thetas() private static native long get_learnt_thetas_0(long nativeObj); // C++: static Ptr_LogisticRegression create() private static native long create_0(); // C++: TermCriteria getTermCriteria() private static native double[] getTermCriteria_0(long nativeObj); // C++: double getLearningRate() private static native double getLearningRate_0(long nativeObj); // C++: float predict(Mat samples, Mat& results = Mat(), int flags = 0) private static native float predict_0(long nativeObj, long samples_nativeObj, long results_nativeObj, int flags); private static native float predict_1(long nativeObj, long samples_nativeObj); // C++: int getIterations() private static native int getIterations_0(long nativeObj); // C++: int getMiniBatchSize() private static native int getMiniBatchSize_0(long nativeObj); // C++: int getRegularization() private static native int getRegularization_0(long nativeObj); // C++: int getTrainMethod() private static native int getTrainMethod_0(long nativeObj); // C++: void setIterations(int val) private static native void setIterations_0(long nativeObj, int val); // C++: void setLearningRate(double val) private static native void setLearningRate_0(long nativeObj, double val); // C++: void setMiniBatchSize(int val) private static native void setMiniBatchSize_0(long nativeObj, int val); // C++: void setRegularization(int val) private static native void setRegularization_0(long nativeObj, int val); // C++: void setTermCriteria(TermCriteria val) private static native void setTermCriteria_0(long nativeObj, int val_type, int val_maxCount, double val_epsilon); // C++: void setTrainMethod(int val) private static native void setTrainMethod_0(long nativeObj, int val); // native support for java finalize() private static native void delete(long nativeObj); }
6,738
21.388704
117
java
self
self-master/lib/opencv/android/sdk/java/src/org/opencv/ml/NormalBayesClassifier.java
// // This file is auto-generated. Please don't modify it! // package org.opencv.ml; import org.opencv.core.Mat; // C++: class NormalBayesClassifier //javadoc: NormalBayesClassifier public class NormalBayesClassifier extends StatModel { protected NormalBayesClassifier(long addr) { super(addr); } // // C++: static Ptr_NormalBayesClassifier create() // //javadoc: NormalBayesClassifier::create() public static NormalBayesClassifier create() { NormalBayesClassifier retVal = new NormalBayesClassifier(create_0()); return retVal; } // // C++: float predictProb(Mat inputs, Mat& outputs, Mat& outputProbs, int flags = 0) // //javadoc: NormalBayesClassifier::predictProb(inputs, outputs, outputProbs, flags) public float predictProb(Mat inputs, Mat outputs, Mat outputProbs, int flags) { float retVal = predictProb_0(nativeObj, inputs.nativeObj, outputs.nativeObj, outputProbs.nativeObj, flags); return retVal; } //javadoc: NormalBayesClassifier::predictProb(inputs, outputs, outputProbs) public float predictProb(Mat inputs, Mat outputs, Mat outputProbs) { float retVal = predictProb_1(nativeObj, inputs.nativeObj, outputs.nativeObj, outputProbs.nativeObj); return retVal; } @Override protected void finalize() throws Throwable { delete(nativeObj); } // C++: static Ptr_NormalBayesClassifier create() private static native long create_0(); // C++: float predictProb(Mat inputs, Mat& outputs, Mat& outputProbs, int flags = 0) private static native float predictProb_0(long nativeObj, long inputs_nativeObj, long outputs_nativeObj, long outputProbs_nativeObj, int flags); private static native float predictProb_1(long nativeObj, long inputs_nativeObj, long outputs_nativeObj, long outputProbs_nativeObj); // native support for java finalize() private static native void delete(long nativeObj); }
2,041
27.760563
148
java
self
self-master/lib/opencv/android/sdk/java/src/org/opencv/ml/SVM.java
// // This file is auto-generated. Please don't modify it! // package org.opencv.ml; import org.opencv.core.Mat; import org.opencv.core.TermCriteria; // C++: class SVM //javadoc: SVM public class SVM extends StatModel { protected SVM(long addr) { super(addr); } public static final int C_SVC = 100, NU_SVC = 101, ONE_CLASS = 102, EPS_SVR = 103, NU_SVR = 104, CUSTOM = -1, LINEAR = 0, POLY = 1, RBF = 2, SIGMOID = 3, CHI2 = 4, INTER = 5, C = 0, GAMMA = 1, P = 2, NU = 3, COEF = 4, DEGREE = 5; // // C++: Mat getClassWeights() // //javadoc: SVM::getClassWeights() public Mat getClassWeights() { Mat retVal = new Mat(getClassWeights_0(nativeObj)); return retVal; } // // C++: Mat getSupportVectors() // //javadoc: SVM::getSupportVectors() public Mat getSupportVectors() { Mat retVal = new Mat(getSupportVectors_0(nativeObj)); return retVal; } // // C++: Mat getUncompressedSupportVectors() // //javadoc: SVM::getUncompressedSupportVectors() public Mat getUncompressedSupportVectors() { Mat retVal = new Mat(getUncompressedSupportVectors_0(nativeObj)); return retVal; } // // C++: static Ptr_SVM create() // //javadoc: SVM::create() public static SVM create() { SVM retVal = new SVM(create_0()); return retVal; } // // C++: TermCriteria getTermCriteria() // //javadoc: SVM::getTermCriteria() public TermCriteria getTermCriteria() { TermCriteria retVal = new TermCriteria(getTermCriteria_0(nativeObj)); return retVal; } // // C++: double getC() // //javadoc: SVM::getC() public double getC() { double retVal = getC_0(nativeObj); return retVal; } // // C++: double getCoef0() // //javadoc: SVM::getCoef0() public double getCoef0() { double retVal = getCoef0_0(nativeObj); return retVal; } // // C++: double getDecisionFunction(int i, Mat& alpha, Mat& svidx) // //javadoc: SVM::getDecisionFunction(i, alpha, svidx) public double getDecisionFunction(int i, Mat alpha, Mat svidx) { double retVal = getDecisionFunction_0(nativeObj, i, alpha.nativeObj, svidx.nativeObj); return retVal; } // // C++: double getDegree() // //javadoc: SVM::getDegree() public double getDegree() { double retVal = getDegree_0(nativeObj); return retVal; } // // C++: double getGamma() // //javadoc: SVM::getGamma() public double getGamma() { double retVal = getGamma_0(nativeObj); return retVal; } // // C++: double getNu() // //javadoc: SVM::getNu() public double getNu() { double retVal = getNu_0(nativeObj); return retVal; } // // C++: double getP() // //javadoc: SVM::getP() public double getP() { double retVal = getP_0(nativeObj); return retVal; } // // C++: int getKernelType() // //javadoc: SVM::getKernelType() public int getKernelType() { int retVal = getKernelType_0(nativeObj); return retVal; } // // C++: int getType() // //javadoc: SVM::getType() public int getType() { int retVal = getType_0(nativeObj); return retVal; } // // C++: void setC(double val) // //javadoc: SVM::setC(val) public void setC(double val) { setC_0(nativeObj, val); return; } // // C++: void setClassWeights(Mat val) // //javadoc: SVM::setClassWeights(val) public void setClassWeights(Mat val) { setClassWeights_0(nativeObj, val.nativeObj); return; } // // C++: void setCoef0(double val) // //javadoc: SVM::setCoef0(val) public void setCoef0(double val) { setCoef0_0(nativeObj, val); return; } // // C++: void setDegree(double val) // //javadoc: SVM::setDegree(val) public void setDegree(double val) { setDegree_0(nativeObj, val); return; } // // C++: void setGamma(double val) // //javadoc: SVM::setGamma(val) public void setGamma(double val) { setGamma_0(nativeObj, val); return; } // // C++: void setKernel(int kernelType) // //javadoc: SVM::setKernel(kernelType) public void setKernel(int kernelType) { setKernel_0(nativeObj, kernelType); return; } // // C++: void setNu(double val) // //javadoc: SVM::setNu(val) public void setNu(double val) { setNu_0(nativeObj, val); return; } // // C++: void setP(double val) // //javadoc: SVM::setP(val) public void setP(double val) { setP_0(nativeObj, val); return; } // // C++: void setTermCriteria(TermCriteria val) // //javadoc: SVM::setTermCriteria(val) public void setTermCriteria(TermCriteria val) { setTermCriteria_0(nativeObj, val.type, val.maxCount, val.epsilon); return; } // // C++: void setType(int val) // //javadoc: SVM::setType(val) public void setType(int val) { setType_0(nativeObj, val); return; } @Override protected void finalize() throws Throwable { delete(nativeObj); } // C++: Mat getClassWeights() private static native long getClassWeights_0(long nativeObj); // C++: Mat getSupportVectors() private static native long getSupportVectors_0(long nativeObj); // C++: Mat getUncompressedSupportVectors() private static native long getUncompressedSupportVectors_0(long nativeObj); // C++: static Ptr_SVM create() private static native long create_0(); // C++: TermCriteria getTermCriteria() private static native double[] getTermCriteria_0(long nativeObj); // C++: double getC() private static native double getC_0(long nativeObj); // C++: double getCoef0() private static native double getCoef0_0(long nativeObj); // C++: double getDecisionFunction(int i, Mat& alpha, Mat& svidx) private static native double getDecisionFunction_0(long nativeObj, int i, long alpha_nativeObj, long svidx_nativeObj); // C++: double getDegree() private static native double getDegree_0(long nativeObj); // C++: double getGamma() private static native double getGamma_0(long nativeObj); // C++: double getNu() private static native double getNu_0(long nativeObj); // C++: double getP() private static native double getP_0(long nativeObj); // C++: int getKernelType() private static native int getKernelType_0(long nativeObj); // C++: int getType() private static native int getType_0(long nativeObj); // C++: void setC(double val) private static native void setC_0(long nativeObj, double val); // C++: void setClassWeights(Mat val) private static native void setClassWeights_0(long nativeObj, long val_nativeObj); // C++: void setCoef0(double val) private static native void setCoef0_0(long nativeObj, double val); // C++: void setDegree(double val) private static native void setDegree_0(long nativeObj, double val); // C++: void setGamma(double val) private static native void setGamma_0(long nativeObj, double val); // C++: void setKernel(int kernelType) private static native void setKernel_0(long nativeObj, int kernelType); // C++: void setNu(double val) private static native void setNu_0(long nativeObj, double val); // C++: void setP(double val) private static native void setP_0(long nativeObj, double val); // C++: void setTermCriteria(TermCriteria val) private static native void setTermCriteria_0(long nativeObj, int val_type, int val_maxCount, double val_epsilon); // C++: void setType(int val) private static native void setType_0(long nativeObj, int val); // native support for java finalize() private static native void delete(long nativeObj); }
8,969
18.628009
122
java
self
self-master/lib/opencv/android/sdk/java/src/org/opencv/ml/Ml.java
// // This file is auto-generated. Please don't modify it! // package org.opencv.ml; public class Ml { public static final int VAR_NUMERICAL = 0, VAR_ORDERED = 0, VAR_CATEGORICAL = 1, TEST_ERROR = 0, TRAIN_ERROR = 1, ROW_SAMPLE = 0, COL_SAMPLE = 1; }
348
13.541667
55
java
self
self-master/lib/opencv/android/sdk/java/src/org/opencv/ml/EM.java
// // This file is auto-generated. Please don't modify it! // package org.opencv.ml; import java.util.ArrayList; import java.util.List; import org.opencv.core.Mat; import org.opencv.core.TermCriteria; import org.opencv.utils.Converters; // C++: class EM //javadoc: EM public class EM extends StatModel { protected EM(long addr) { super(addr); } public static final int COV_MAT_SPHERICAL = 0, COV_MAT_DIAGONAL = 1, COV_MAT_GENERIC = 2, COV_MAT_DEFAULT = COV_MAT_DIAGONAL, DEFAULT_NCLUSTERS = 5, DEFAULT_MAX_ITERS = 100, START_E_STEP = 1, START_M_STEP = 2, START_AUTO_STEP = 0; // // C++: Mat getMeans() // //javadoc: EM::getMeans() public Mat getMeans() { Mat retVal = new Mat(getMeans_0(nativeObj)); return retVal; } // // C++: Mat getWeights() // //javadoc: EM::getWeights() public Mat getWeights() { Mat retVal = new Mat(getWeights_0(nativeObj)); return retVal; } // // C++: static Ptr_EM create() // //javadoc: EM::create() public static EM create() { EM retVal = new EM(create_0()); return retVal; } // // C++: TermCriteria getTermCriteria() // //javadoc: EM::getTermCriteria() public TermCriteria getTermCriteria() { TermCriteria retVal = new TermCriteria(getTermCriteria_0(nativeObj)); return retVal; } // // C++: Vec2d predict2(Mat sample, Mat& probs) // //javadoc: EM::predict2(sample, probs) public double[] predict2(Mat sample, Mat probs) { double[] retVal = predict2_0(nativeObj, sample.nativeObj, probs.nativeObj); return retVal; } // // C++: bool trainE(Mat samples, Mat means0, Mat covs0 = Mat(), Mat weights0 = Mat(), Mat& logLikelihoods = Mat(), Mat& labels = Mat(), Mat& probs = Mat()) // //javadoc: EM::trainE(samples, means0, covs0, weights0, logLikelihoods, labels, probs) public boolean trainE(Mat samples, Mat means0, Mat covs0, Mat weights0, Mat logLikelihoods, Mat labels, Mat probs) { boolean retVal = trainE_0(nativeObj, samples.nativeObj, means0.nativeObj, covs0.nativeObj, weights0.nativeObj, logLikelihoods.nativeObj, labels.nativeObj, probs.nativeObj); return retVal; } //javadoc: EM::trainE(samples, means0) public boolean trainE(Mat samples, Mat means0) { boolean retVal = trainE_1(nativeObj, samples.nativeObj, means0.nativeObj); return retVal; } // // C++: bool trainEM(Mat samples, Mat& logLikelihoods = Mat(), Mat& labels = Mat(), Mat& probs = Mat()) // //javadoc: EM::trainEM(samples, logLikelihoods, labels, probs) public boolean trainEM(Mat samples, Mat logLikelihoods, Mat labels, Mat probs) { boolean retVal = trainEM_0(nativeObj, samples.nativeObj, logLikelihoods.nativeObj, labels.nativeObj, probs.nativeObj); return retVal; } //javadoc: EM::trainEM(samples) public boolean trainEM(Mat samples) { boolean retVal = trainEM_1(nativeObj, samples.nativeObj); return retVal; } // // C++: bool trainM(Mat samples, Mat probs0, Mat& logLikelihoods = Mat(), Mat& labels = Mat(), Mat& probs = Mat()) // //javadoc: EM::trainM(samples, probs0, logLikelihoods, labels, probs) public boolean trainM(Mat samples, Mat probs0, Mat logLikelihoods, Mat labels, Mat probs) { boolean retVal = trainM_0(nativeObj, samples.nativeObj, probs0.nativeObj, logLikelihoods.nativeObj, labels.nativeObj, probs.nativeObj); return retVal; } //javadoc: EM::trainM(samples, probs0) public boolean trainM(Mat samples, Mat probs0) { boolean retVal = trainM_1(nativeObj, samples.nativeObj, probs0.nativeObj); return retVal; } // // C++: int getClustersNumber() // //javadoc: EM::getClustersNumber() public int getClustersNumber() { int retVal = getClustersNumber_0(nativeObj); return retVal; } // // C++: int getCovarianceMatrixType() // //javadoc: EM::getCovarianceMatrixType() public int getCovarianceMatrixType() { int retVal = getCovarianceMatrixType_0(nativeObj); return retVal; } // // C++: void getCovs(vector_Mat& covs) // //javadoc: EM::getCovs(covs) public void getCovs(List<Mat> covs) { Mat covs_mat = new Mat(); getCovs_0(nativeObj, covs_mat.nativeObj); Converters.Mat_to_vector_Mat(covs_mat, covs); covs_mat.release(); return; } // // C++: void setClustersNumber(int val) // //javadoc: EM::setClustersNumber(val) public void setClustersNumber(int val) { setClustersNumber_0(nativeObj, val); return; } // // C++: void setCovarianceMatrixType(int val) // //javadoc: EM::setCovarianceMatrixType(val) public void setCovarianceMatrixType(int val) { setCovarianceMatrixType_0(nativeObj, val); return; } // // C++: void setTermCriteria(TermCriteria val) // //javadoc: EM::setTermCriteria(val) public void setTermCriteria(TermCriteria val) { setTermCriteria_0(nativeObj, val.type, val.maxCount, val.epsilon); return; } @Override protected void finalize() throws Throwable { delete(nativeObj); } // C++: Mat getMeans() private static native long getMeans_0(long nativeObj); // C++: Mat getWeights() private static native long getWeights_0(long nativeObj); // C++: static Ptr_EM create() private static native long create_0(); // C++: TermCriteria getTermCriteria() private static native double[] getTermCriteria_0(long nativeObj); // C++: Vec2d predict2(Mat sample, Mat& probs) private static native double[] predict2_0(long nativeObj, long sample_nativeObj, long probs_nativeObj); // C++: bool trainE(Mat samples, Mat means0, Mat covs0 = Mat(), Mat weights0 = Mat(), Mat& logLikelihoods = Mat(), Mat& labels = Mat(), Mat& probs = Mat()) private static native boolean trainE_0(long nativeObj, long samples_nativeObj, long means0_nativeObj, long covs0_nativeObj, long weights0_nativeObj, long logLikelihoods_nativeObj, long labels_nativeObj, long probs_nativeObj); private static native boolean trainE_1(long nativeObj, long samples_nativeObj, long means0_nativeObj); // C++: bool trainEM(Mat samples, Mat& logLikelihoods = Mat(), Mat& labels = Mat(), Mat& probs = Mat()) private static native boolean trainEM_0(long nativeObj, long samples_nativeObj, long logLikelihoods_nativeObj, long labels_nativeObj, long probs_nativeObj); private static native boolean trainEM_1(long nativeObj, long samples_nativeObj); // C++: bool trainM(Mat samples, Mat probs0, Mat& logLikelihoods = Mat(), Mat& labels = Mat(), Mat& probs = Mat()) private static native boolean trainM_0(long nativeObj, long samples_nativeObj, long probs0_nativeObj, long logLikelihoods_nativeObj, long labels_nativeObj, long probs_nativeObj); private static native boolean trainM_1(long nativeObj, long samples_nativeObj, long probs0_nativeObj); // C++: int getClustersNumber() private static native int getClustersNumber_0(long nativeObj); // C++: int getCovarianceMatrixType() private static native int getCovarianceMatrixType_0(long nativeObj); // C++: void getCovs(vector_Mat& covs) private static native void getCovs_0(long nativeObj, long covs_mat_nativeObj); // C++: void setClustersNumber(int val) private static native void setClustersNumber_0(long nativeObj, int val); // C++: void setCovarianceMatrixType(int val) private static native void setCovarianceMatrixType_0(long nativeObj, int val); // C++: void setTermCriteria(TermCriteria val) private static native void setTermCriteria_0(long nativeObj, int val_type, int val_maxCount, double val_epsilon); // native support for java finalize() private static native void delete(long nativeObj); }
8,530
26.342949
229
java
self
self-master/lib/opencv/android/sdk/java/src/org/opencv/ml/TrainData.java
// // This file is auto-generated. Please don't modify it! // package org.opencv.ml; import org.opencv.core.Mat; // C++: class TrainData //javadoc: TrainData public class TrainData { protected final long nativeObj; protected TrainData(long addr) { nativeObj = addr; } // // C++: Mat getCatMap() // //javadoc: TrainData::getCatMap() public Mat getCatMap() { Mat retVal = new Mat(getCatMap_0(nativeObj)); return retVal; } // // C++: Mat getCatOfs() // //javadoc: TrainData::getCatOfs() public Mat getCatOfs() { Mat retVal = new Mat(getCatOfs_0(nativeObj)); return retVal; } // // C++: Mat getClassLabels() // //javadoc: TrainData::getClassLabels() public Mat getClassLabels() { Mat retVal = new Mat(getClassLabels_0(nativeObj)); return retVal; } // // C++: Mat getDefaultSubstValues() // //javadoc: TrainData::getDefaultSubstValues() public Mat getDefaultSubstValues() { Mat retVal = new Mat(getDefaultSubstValues_0(nativeObj)); return retVal; } // // C++: Mat getMissing() // //javadoc: TrainData::getMissing() public Mat getMissing() { Mat retVal = new Mat(getMissing_0(nativeObj)); return retVal; } // // C++: Mat getNormCatResponses() // //javadoc: TrainData::getNormCatResponses() public Mat getNormCatResponses() { Mat retVal = new Mat(getNormCatResponses_0(nativeObj)); return retVal; } // // C++: Mat getResponses() // //javadoc: TrainData::getResponses() public Mat getResponses() { Mat retVal = new Mat(getResponses_0(nativeObj)); return retVal; } // // C++: Mat getSampleWeights() // //javadoc: TrainData::getSampleWeights() public Mat getSampleWeights() { Mat retVal = new Mat(getSampleWeights_0(nativeObj)); return retVal; } // // C++: Mat getSamples() // //javadoc: TrainData::getSamples() public Mat getSamples() { Mat retVal = new Mat(getSamples_0(nativeObj)); return retVal; } // // C++: static Mat getSubVector(Mat vec, Mat idx) // //javadoc: TrainData::getSubVector(vec, idx) public static Mat getSubVector(Mat vec, Mat idx) { Mat retVal = new Mat(getSubVector_0(vec.nativeObj, idx.nativeObj)); return retVal; } // // C++: Mat getTestNormCatResponses() // //javadoc: TrainData::getTestNormCatResponses() public Mat getTestNormCatResponses() { Mat retVal = new Mat(getTestNormCatResponses_0(nativeObj)); return retVal; } // // C++: Mat getTestResponses() // //javadoc: TrainData::getTestResponses() public Mat getTestResponses() { Mat retVal = new Mat(getTestResponses_0(nativeObj)); return retVal; } // // C++: Mat getTestSampleIdx() // //javadoc: TrainData::getTestSampleIdx() public Mat getTestSampleIdx() { Mat retVal = new Mat(getTestSampleIdx_0(nativeObj)); return retVal; } // // C++: Mat getTestSampleWeights() // //javadoc: TrainData::getTestSampleWeights() public Mat getTestSampleWeights() { Mat retVal = new Mat(getTestSampleWeights_0(nativeObj)); return retVal; } // // C++: Mat getTrainNormCatResponses() // //javadoc: TrainData::getTrainNormCatResponses() public Mat getTrainNormCatResponses() { Mat retVal = new Mat(getTrainNormCatResponses_0(nativeObj)); return retVal; } // // C++: Mat getTrainResponses() // //javadoc: TrainData::getTrainResponses() public Mat getTrainResponses() { Mat retVal = new Mat(getTrainResponses_0(nativeObj)); return retVal; } // // C++: Mat getTrainSampleIdx() // //javadoc: TrainData::getTrainSampleIdx() public Mat getTrainSampleIdx() { Mat retVal = new Mat(getTrainSampleIdx_0(nativeObj)); return retVal; } // // C++: Mat getTrainSampleWeights() // //javadoc: TrainData::getTrainSampleWeights() public Mat getTrainSampleWeights() { Mat retVal = new Mat(getTrainSampleWeights_0(nativeObj)); return retVal; } // // C++: Mat getTrainSamples(int layout = ROW_SAMPLE, bool compressSamples = true, bool compressVars = true) // //javadoc: TrainData::getTrainSamples(layout, compressSamples, compressVars) public Mat getTrainSamples(int layout, boolean compressSamples, boolean compressVars) { Mat retVal = new Mat(getTrainSamples_0(nativeObj, layout, compressSamples, compressVars)); return retVal; } //javadoc: TrainData::getTrainSamples() public Mat getTrainSamples() { Mat retVal = new Mat(getTrainSamples_1(nativeObj)); return retVal; } // // C++: Mat getVarIdx() // //javadoc: TrainData::getVarIdx() public Mat getVarIdx() { Mat retVal = new Mat(getVarIdx_0(nativeObj)); return retVal; } // // C++: Mat getVarType() // //javadoc: TrainData::getVarType() public Mat getVarType() { Mat retVal = new Mat(getVarType_0(nativeObj)); return retVal; } // // C++: static Ptr_TrainData create(Mat samples, int layout, Mat responses, Mat varIdx = Mat(), Mat sampleIdx = Mat(), Mat sampleWeights = Mat(), Mat varType = Mat()) // // Return type 'Ptr_TrainData' is not supported, skipping the function // // C++: int getCatCount(int vi) // //javadoc: TrainData::getCatCount(vi) public int getCatCount(int vi) { int retVal = getCatCount_0(nativeObj, vi); return retVal; } // // C++: int getLayout() // //javadoc: TrainData::getLayout() public int getLayout() { int retVal = getLayout_0(nativeObj); return retVal; } // // C++: int getNAllVars() // //javadoc: TrainData::getNAllVars() public int getNAllVars() { int retVal = getNAllVars_0(nativeObj); return retVal; } // // C++: int getNSamples() // //javadoc: TrainData::getNSamples() public int getNSamples() { int retVal = getNSamples_0(nativeObj); return retVal; } // // C++: int getNTestSamples() // //javadoc: TrainData::getNTestSamples() public int getNTestSamples() { int retVal = getNTestSamples_0(nativeObj); return retVal; } // // C++: int getNTrainSamples() // //javadoc: TrainData::getNTrainSamples() public int getNTrainSamples() { int retVal = getNTrainSamples_0(nativeObj); return retVal; } // // C++: int getNVars() // //javadoc: TrainData::getNVars() public int getNVars() { int retVal = getNVars_0(nativeObj); return retVal; } // // C++: int getResponseType() // //javadoc: TrainData::getResponseType() public int getResponseType() { int retVal = getResponseType_0(nativeObj); return retVal; } // // C++: void getSample(Mat varIdx, int sidx, float* buf) // //javadoc: TrainData::getSample(varIdx, sidx, buf) public void getSample(Mat varIdx, int sidx, float buf) { getSample_0(nativeObj, varIdx.nativeObj, sidx, buf); return; } // // C++: void getValues(int vi, Mat sidx, float* values) // //javadoc: TrainData::getValues(vi, sidx, values) public void getValues(int vi, Mat sidx, float values) { getValues_0(nativeObj, vi, sidx.nativeObj, values); return; } // // C++: void setTrainTestSplit(int count, bool shuffle = true) // //javadoc: TrainData::setTrainTestSplit(count, shuffle) public void setTrainTestSplit(int count, boolean shuffle) { setTrainTestSplit_0(nativeObj, count, shuffle); return; } //javadoc: TrainData::setTrainTestSplit(count) public void setTrainTestSplit(int count) { setTrainTestSplit_1(nativeObj, count); return; } // // C++: void setTrainTestSplitRatio(double ratio, bool shuffle = true) // //javadoc: TrainData::setTrainTestSplitRatio(ratio, shuffle) public void setTrainTestSplitRatio(double ratio, boolean shuffle) { setTrainTestSplitRatio_0(nativeObj, ratio, shuffle); return; } //javadoc: TrainData::setTrainTestSplitRatio(ratio) public void setTrainTestSplitRatio(double ratio) { setTrainTestSplitRatio_1(nativeObj, ratio); return; } // // C++: void shuffleTrainTest() // //javadoc: TrainData::shuffleTrainTest() public void shuffleTrainTest() { shuffleTrainTest_0(nativeObj); return; } @Override protected void finalize() throws Throwable { delete(nativeObj); } // C++: Mat getCatMap() private static native long getCatMap_0(long nativeObj); // C++: Mat getCatOfs() private static native long getCatOfs_0(long nativeObj); // C++: Mat getClassLabels() private static native long getClassLabels_0(long nativeObj); // C++: Mat getDefaultSubstValues() private static native long getDefaultSubstValues_0(long nativeObj); // C++: Mat getMissing() private static native long getMissing_0(long nativeObj); // C++: Mat getNormCatResponses() private static native long getNormCatResponses_0(long nativeObj); // C++: Mat getResponses() private static native long getResponses_0(long nativeObj); // C++: Mat getSampleWeights() private static native long getSampleWeights_0(long nativeObj); // C++: Mat getSamples() private static native long getSamples_0(long nativeObj); // C++: static Mat getSubVector(Mat vec, Mat idx) private static native long getSubVector_0(long vec_nativeObj, long idx_nativeObj); // C++: Mat getTestNormCatResponses() private static native long getTestNormCatResponses_0(long nativeObj); // C++: Mat getTestResponses() private static native long getTestResponses_0(long nativeObj); // C++: Mat getTestSampleIdx() private static native long getTestSampleIdx_0(long nativeObj); // C++: Mat getTestSampleWeights() private static native long getTestSampleWeights_0(long nativeObj); // C++: Mat getTrainNormCatResponses() private static native long getTrainNormCatResponses_0(long nativeObj); // C++: Mat getTrainResponses() private static native long getTrainResponses_0(long nativeObj); // C++: Mat getTrainSampleIdx() private static native long getTrainSampleIdx_0(long nativeObj); // C++: Mat getTrainSampleWeights() private static native long getTrainSampleWeights_0(long nativeObj); // C++: Mat getTrainSamples(int layout = ROW_SAMPLE, bool compressSamples = true, bool compressVars = true) private static native long getTrainSamples_0(long nativeObj, int layout, boolean compressSamples, boolean compressVars); private static native long getTrainSamples_1(long nativeObj); // C++: Mat getVarIdx() private static native long getVarIdx_0(long nativeObj); // C++: Mat getVarType() private static native long getVarType_0(long nativeObj); // C++: int getCatCount(int vi) private static native int getCatCount_0(long nativeObj, int vi); // C++: int getLayout() private static native int getLayout_0(long nativeObj); // C++: int getNAllVars() private static native int getNAllVars_0(long nativeObj); // C++: int getNSamples() private static native int getNSamples_0(long nativeObj); // C++: int getNTestSamples() private static native int getNTestSamples_0(long nativeObj); // C++: int getNTrainSamples() private static native int getNTrainSamples_0(long nativeObj); // C++: int getNVars() private static native int getNVars_0(long nativeObj); // C++: int getResponseType() private static native int getResponseType_0(long nativeObj); // C++: void getSample(Mat varIdx, int sidx, float* buf) private static native void getSample_0(long nativeObj, long varIdx_nativeObj, int sidx, float buf); // C++: void getValues(int vi, Mat sidx, float* values) private static native void getValues_0(long nativeObj, int vi, long sidx_nativeObj, float values); // C++: void setTrainTestSplit(int count, bool shuffle = true) private static native void setTrainTestSplit_0(long nativeObj, int count, boolean shuffle); private static native void setTrainTestSplit_1(long nativeObj, int count); // C++: void setTrainTestSplitRatio(double ratio, bool shuffle = true) private static native void setTrainTestSplitRatio_0(long nativeObj, double ratio, boolean shuffle); private static native void setTrainTestSplitRatio_1(long nativeObj, double ratio); // C++: void shuffleTrainTest() private static native void shuffleTrainTest_0(long nativeObj); // native support for java finalize() private static native void delete(long nativeObj); }
14,123
20.965785
170
java
self
self-master/lib/opencv/android/sdk/java/src/org/opencv/ml/StatModel.java
// // This file is auto-generated. Please don't modify it! // package org.opencv.ml; import org.opencv.core.Algorithm; import org.opencv.core.Mat; // C++: class StatModel //javadoc: StatModel public class StatModel extends Algorithm { protected StatModel(long addr) { super(addr); } public static final int UPDATE_MODEL = 1, RAW_OUTPUT = 1, COMPRESSED_INPUT = 2, PREPROCESSED_INPUT = 4; // // C++: bool empty() // //javadoc: StatModel::empty() public boolean empty() { boolean retVal = empty_0(nativeObj); return retVal; } // // C++: bool isClassifier() // //javadoc: StatModel::isClassifier() public boolean isClassifier() { boolean retVal = isClassifier_0(nativeObj); return retVal; } // // C++: bool isTrained() // //javadoc: StatModel::isTrained() public boolean isTrained() { boolean retVal = isTrained_0(nativeObj); return retVal; } // // C++: bool train(Mat samples, int layout, Mat responses) // //javadoc: StatModel::train(samples, layout, responses) public boolean train(Mat samples, int layout, Mat responses) { boolean retVal = train_0(nativeObj, samples.nativeObj, layout, responses.nativeObj); return retVal; } // // C++: bool train(Ptr_TrainData trainData, int flags = 0) // // Unknown type 'Ptr_TrainData' (I), skipping the function // // C++: float calcError(Ptr_TrainData data, bool test, Mat& resp) // // Unknown type 'Ptr_TrainData' (I), skipping the function // // C++: float predict(Mat samples, Mat& results = Mat(), int flags = 0) // //javadoc: StatModel::predict(samples, results, flags) public float predict(Mat samples, Mat results, int flags) { float retVal = predict_0(nativeObj, samples.nativeObj, results.nativeObj, flags); return retVal; } //javadoc: StatModel::predict(samples) public float predict(Mat samples) { float retVal = predict_1(nativeObj, samples.nativeObj); return retVal; } // // C++: int getVarCount() // //javadoc: StatModel::getVarCount() public int getVarCount() { int retVal = getVarCount_0(nativeObj); return retVal; } @Override protected void finalize() throws Throwable { delete(nativeObj); } // C++: bool empty() private static native boolean empty_0(long nativeObj); // C++: bool isClassifier() private static native boolean isClassifier_0(long nativeObj); // C++: bool isTrained() private static native boolean isTrained_0(long nativeObj); // C++: bool train(Mat samples, int layout, Mat responses) private static native boolean train_0(long nativeObj, long samples_nativeObj, int layout, long responses_nativeObj); // C++: float predict(Mat samples, Mat& results = Mat(), int flags = 0) private static native float predict_0(long nativeObj, long samples_nativeObj, long results_nativeObj, int flags); private static native float predict_1(long nativeObj, long samples_nativeObj); // C++: int getVarCount() private static native int getVarCount_0(long nativeObj); // native support for java finalize() private static native void delete(long nativeObj); }
3,566
21.15528
120
java
self
self-master/lib/opencv/android/sdk/java/src/org/opencv/ml/KNearest.java
// // This file is auto-generated. Please don't modify it! // package org.opencv.ml; import org.opencv.core.Mat; // C++: class KNearest //javadoc: KNearest public class KNearest extends StatModel { protected KNearest(long addr) { super(addr); } public static final int BRUTE_FORCE = 1, KDTREE = 2; // // C++: static Ptr_KNearest create() // //javadoc: KNearest::create() public static KNearest create() { KNearest retVal = new KNearest(create_0()); return retVal; } // // C++: bool getIsClassifier() // //javadoc: KNearest::getIsClassifier() public boolean getIsClassifier() { boolean retVal = getIsClassifier_0(nativeObj); return retVal; } // // C++: float findNearest(Mat samples, int k, Mat& results, Mat& neighborResponses = Mat(), Mat& dist = Mat()) // //javadoc: KNearest::findNearest(samples, k, results, neighborResponses, dist) public float findNearest(Mat samples, int k, Mat results, Mat neighborResponses, Mat dist) { float retVal = findNearest_0(nativeObj, samples.nativeObj, k, results.nativeObj, neighborResponses.nativeObj, dist.nativeObj); return retVal; } //javadoc: KNearest::findNearest(samples, k, results) public float findNearest(Mat samples, int k, Mat results) { float retVal = findNearest_1(nativeObj, samples.nativeObj, k, results.nativeObj); return retVal; } // // C++: int getAlgorithmType() // //javadoc: KNearest::getAlgorithmType() public int getAlgorithmType() { int retVal = getAlgorithmType_0(nativeObj); return retVal; } // // C++: int getDefaultK() // //javadoc: KNearest::getDefaultK() public int getDefaultK() { int retVal = getDefaultK_0(nativeObj); return retVal; } // // C++: int getEmax() // //javadoc: KNearest::getEmax() public int getEmax() { int retVal = getEmax_0(nativeObj); return retVal; } // // C++: void setAlgorithmType(int val) // //javadoc: KNearest::setAlgorithmType(val) public void setAlgorithmType(int val) { setAlgorithmType_0(nativeObj, val); return; } // // C++: void setDefaultK(int val) // //javadoc: KNearest::setDefaultK(val) public void setDefaultK(int val) { setDefaultK_0(nativeObj, val); return; } // // C++: void setEmax(int val) // //javadoc: KNearest::setEmax(val) public void setEmax(int val) { setEmax_0(nativeObj, val); return; } // // C++: void setIsClassifier(bool val) // //javadoc: KNearest::setIsClassifier(val) public void setIsClassifier(boolean val) { setIsClassifier_0(nativeObj, val); return; } @Override protected void finalize() throws Throwable { delete(nativeObj); } // C++: static Ptr_KNearest create() private static native long create_0(); // C++: bool getIsClassifier() private static native boolean getIsClassifier_0(long nativeObj); // C++: float findNearest(Mat samples, int k, Mat& results, Mat& neighborResponses = Mat(), Mat& dist = Mat()) private static native float findNearest_0(long nativeObj, long samples_nativeObj, int k, long results_nativeObj, long neighborResponses_nativeObj, long dist_nativeObj); private static native float findNearest_1(long nativeObj, long samples_nativeObj, int k, long results_nativeObj); // C++: int getAlgorithmType() private static native int getAlgorithmType_0(long nativeObj); // C++: int getDefaultK() private static native int getDefaultK_0(long nativeObj); // C++: int getEmax() private static native int getEmax_0(long nativeObj); // C++: void setAlgorithmType(int val) private static native void setAlgorithmType_0(long nativeObj, int val); // C++: void setDefaultK(int val) private static native void setDefaultK_0(long nativeObj, int val); // C++: void setEmax(int val) private static native void setEmax_0(long nativeObj, int val); // C++: void setIsClassifier(bool val) private static native void setIsClassifier_0(long nativeObj, boolean val); // native support for java finalize() private static native void delete(long nativeObj); }
4,680
21.080189
172
java
self
self-master/lib/opencv/android/sdk/java/src/org/opencv/ml/ANN_MLP.java
// // This file is auto-generated. Please don't modify it! // package org.opencv.ml; import org.opencv.core.Mat; import org.opencv.core.TermCriteria; // C++: class ANN_MLP //javadoc: ANN_MLP public class ANN_MLP extends StatModel { protected ANN_MLP(long addr) { super(addr); } public static final int BACKPROP = 0, RPROP = 1, IDENTITY = 0, SIGMOID_SYM = 1, GAUSSIAN = 2, UPDATE_WEIGHTS = 1, NO_INPUT_SCALE = 2, NO_OUTPUT_SCALE = 4; // // C++: Mat getLayerSizes() // //javadoc: ANN_MLP::getLayerSizes() public Mat getLayerSizes() { Mat retVal = new Mat(getLayerSizes_0(nativeObj)); return retVal; } // // C++: Mat getWeights(int layerIdx) // //javadoc: ANN_MLP::getWeights(layerIdx) public Mat getWeights(int layerIdx) { Mat retVal = new Mat(getWeights_0(nativeObj, layerIdx)); return retVal; } // // C++: static Ptr_ANN_MLP create() // //javadoc: ANN_MLP::create() public static ANN_MLP create() { ANN_MLP retVal = new ANN_MLP(create_0()); return retVal; } // // C++: TermCriteria getTermCriteria() // //javadoc: ANN_MLP::getTermCriteria() public TermCriteria getTermCriteria() { TermCriteria retVal = new TermCriteria(getTermCriteria_0(nativeObj)); return retVal; } // // C++: double getBackpropMomentumScale() // //javadoc: ANN_MLP::getBackpropMomentumScale() public double getBackpropMomentumScale() { double retVal = getBackpropMomentumScale_0(nativeObj); return retVal; } // // C++: double getBackpropWeightScale() // //javadoc: ANN_MLP::getBackpropWeightScale() public double getBackpropWeightScale() { double retVal = getBackpropWeightScale_0(nativeObj); return retVal; } // // C++: double getRpropDW0() // //javadoc: ANN_MLP::getRpropDW0() public double getRpropDW0() { double retVal = getRpropDW0_0(nativeObj); return retVal; } // // C++: double getRpropDWMax() // //javadoc: ANN_MLP::getRpropDWMax() public double getRpropDWMax() { double retVal = getRpropDWMax_0(nativeObj); return retVal; } // // C++: double getRpropDWMin() // //javadoc: ANN_MLP::getRpropDWMin() public double getRpropDWMin() { double retVal = getRpropDWMin_0(nativeObj); return retVal; } // // C++: double getRpropDWMinus() // //javadoc: ANN_MLP::getRpropDWMinus() public double getRpropDWMinus() { double retVal = getRpropDWMinus_0(nativeObj); return retVal; } // // C++: double getRpropDWPlus() // //javadoc: ANN_MLP::getRpropDWPlus() public double getRpropDWPlus() { double retVal = getRpropDWPlus_0(nativeObj); return retVal; } // // C++: int getTrainMethod() // //javadoc: ANN_MLP::getTrainMethod() public int getTrainMethod() { int retVal = getTrainMethod_0(nativeObj); return retVal; } // // C++: void setActivationFunction(int type, double param1 = 0, double param2 = 0) // //javadoc: ANN_MLP::setActivationFunction(type, param1, param2) public void setActivationFunction(int type, double param1, double param2) { setActivationFunction_0(nativeObj, type, param1, param2); return; } //javadoc: ANN_MLP::setActivationFunction(type) public void setActivationFunction(int type) { setActivationFunction_1(nativeObj, type); return; } // // C++: void setBackpropMomentumScale(double val) // //javadoc: ANN_MLP::setBackpropMomentumScale(val) public void setBackpropMomentumScale(double val) { setBackpropMomentumScale_0(nativeObj, val); return; } // // C++: void setBackpropWeightScale(double val) // //javadoc: ANN_MLP::setBackpropWeightScale(val) public void setBackpropWeightScale(double val) { setBackpropWeightScale_0(nativeObj, val); return; } // // C++: void setLayerSizes(Mat _layer_sizes) // //javadoc: ANN_MLP::setLayerSizes(_layer_sizes) public void setLayerSizes(Mat _layer_sizes) { setLayerSizes_0(nativeObj, _layer_sizes.nativeObj); return; } // // C++: void setRpropDW0(double val) // //javadoc: ANN_MLP::setRpropDW0(val) public void setRpropDW0(double val) { setRpropDW0_0(nativeObj, val); return; } // // C++: void setRpropDWMax(double val) // //javadoc: ANN_MLP::setRpropDWMax(val) public void setRpropDWMax(double val) { setRpropDWMax_0(nativeObj, val); return; } // // C++: void setRpropDWMin(double val) // //javadoc: ANN_MLP::setRpropDWMin(val) public void setRpropDWMin(double val) { setRpropDWMin_0(nativeObj, val); return; } // // C++: void setRpropDWMinus(double val) // //javadoc: ANN_MLP::setRpropDWMinus(val) public void setRpropDWMinus(double val) { setRpropDWMinus_0(nativeObj, val); return; } // // C++: void setRpropDWPlus(double val) // //javadoc: ANN_MLP::setRpropDWPlus(val) public void setRpropDWPlus(double val) { setRpropDWPlus_0(nativeObj, val); return; } // // C++: void setTermCriteria(TermCriteria val) // //javadoc: ANN_MLP::setTermCriteria(val) public void setTermCriteria(TermCriteria val) { setTermCriteria_0(nativeObj, val.type, val.maxCount, val.epsilon); return; } // // C++: void setTrainMethod(int method, double param1 = 0, double param2 = 0) // //javadoc: ANN_MLP::setTrainMethod(method, param1, param2) public void setTrainMethod(int method, double param1, double param2) { setTrainMethod_0(nativeObj, method, param1, param2); return; } //javadoc: ANN_MLP::setTrainMethod(method) public void setTrainMethod(int method) { setTrainMethod_1(nativeObj, method); return; } @Override protected void finalize() throws Throwable { delete(nativeObj); } // C++: Mat getLayerSizes() private static native long getLayerSizes_0(long nativeObj); // C++: Mat getWeights(int layerIdx) private static native long getWeights_0(long nativeObj, int layerIdx); // C++: static Ptr_ANN_MLP create() private static native long create_0(); // C++: TermCriteria getTermCriteria() private static native double[] getTermCriteria_0(long nativeObj); // C++: double getBackpropMomentumScale() private static native double getBackpropMomentumScale_0(long nativeObj); // C++: double getBackpropWeightScale() private static native double getBackpropWeightScale_0(long nativeObj); // C++: double getRpropDW0() private static native double getRpropDW0_0(long nativeObj); // C++: double getRpropDWMax() private static native double getRpropDWMax_0(long nativeObj); // C++: double getRpropDWMin() private static native double getRpropDWMin_0(long nativeObj); // C++: double getRpropDWMinus() private static native double getRpropDWMinus_0(long nativeObj); // C++: double getRpropDWPlus() private static native double getRpropDWPlus_0(long nativeObj); // C++: int getTrainMethod() private static native int getTrainMethod_0(long nativeObj); // C++: void setActivationFunction(int type, double param1 = 0, double param2 = 0) private static native void setActivationFunction_0(long nativeObj, int type, double param1, double param2); private static native void setActivationFunction_1(long nativeObj, int type); // C++: void setBackpropMomentumScale(double val) private static native void setBackpropMomentumScale_0(long nativeObj, double val); // C++: void setBackpropWeightScale(double val) private static native void setBackpropWeightScale_0(long nativeObj, double val); // C++: void setLayerSizes(Mat _layer_sizes) private static native void setLayerSizes_0(long nativeObj, long _layer_sizes_nativeObj); // C++: void setRpropDW0(double val) private static native void setRpropDW0_0(long nativeObj, double val); // C++: void setRpropDWMax(double val) private static native void setRpropDWMax_0(long nativeObj, double val); // C++: void setRpropDWMin(double val) private static native void setRpropDWMin_0(long nativeObj, double val); // C++: void setRpropDWMinus(double val) private static native void setRpropDWMinus_0(long nativeObj, double val); // C++: void setRpropDWPlus(double val) private static native void setRpropDWPlus_0(long nativeObj, double val); // C++: void setTermCriteria(TermCriteria val) private static native void setTermCriteria_0(long nativeObj, int val_type, int val_maxCount, double val_epsilon); // C++: void setTrainMethod(int method, double param1 = 0, double param2 = 0) private static native void setTrainMethod_0(long nativeObj, int method, double param1, double param2); private static native void setTrainMethod_1(long nativeObj, int method); // native support for java finalize() private static native void delete(long nativeObj); }
10,091
21.426667
117
java
self
self-master/lib/opencv/android/sdk/java/src/org/opencv/ml/DTrees.java
// // This file is auto-generated. Please don't modify it! // package org.opencv.ml; import org.opencv.core.Mat; // C++: class DTrees //javadoc: DTrees public class DTrees extends StatModel { protected DTrees(long addr) { super(addr); } public static final int PREDICT_AUTO = 0, PREDICT_SUM = (1<<8), PREDICT_MAX_VOTE = (2<<8), PREDICT_MASK = (3<<8); // // C++: Mat getPriors() // //javadoc: DTrees::getPriors() public Mat getPriors() { Mat retVal = new Mat(getPriors_0(nativeObj)); return retVal; } // // C++: static Ptr_DTrees create() // //javadoc: DTrees::create() public static DTrees create() { DTrees retVal = new DTrees(create_0()); return retVal; } // // C++: bool getTruncatePrunedTree() // //javadoc: DTrees::getTruncatePrunedTree() public boolean getTruncatePrunedTree() { boolean retVal = getTruncatePrunedTree_0(nativeObj); return retVal; } // // C++: bool getUse1SERule() // //javadoc: DTrees::getUse1SERule() public boolean getUse1SERule() { boolean retVal = getUse1SERule_0(nativeObj); return retVal; } // // C++: bool getUseSurrogates() // //javadoc: DTrees::getUseSurrogates() public boolean getUseSurrogates() { boolean retVal = getUseSurrogates_0(nativeObj); return retVal; } // // C++: float getRegressionAccuracy() // //javadoc: DTrees::getRegressionAccuracy() public float getRegressionAccuracy() { float retVal = getRegressionAccuracy_0(nativeObj); return retVal; } // // C++: int getCVFolds() // //javadoc: DTrees::getCVFolds() public int getCVFolds() { int retVal = getCVFolds_0(nativeObj); return retVal; } // // C++: int getMaxCategories() // //javadoc: DTrees::getMaxCategories() public int getMaxCategories() { int retVal = getMaxCategories_0(nativeObj); return retVal; } // // C++: int getMaxDepth() // //javadoc: DTrees::getMaxDepth() public int getMaxDepth() { int retVal = getMaxDepth_0(nativeObj); return retVal; } // // C++: int getMinSampleCount() // //javadoc: DTrees::getMinSampleCount() public int getMinSampleCount() { int retVal = getMinSampleCount_0(nativeObj); return retVal; } // // C++: void setCVFolds(int val) // //javadoc: DTrees::setCVFolds(val) public void setCVFolds(int val) { setCVFolds_0(nativeObj, val); return; } // // C++: void setMaxCategories(int val) // //javadoc: DTrees::setMaxCategories(val) public void setMaxCategories(int val) { setMaxCategories_0(nativeObj, val); return; } // // C++: void setMaxDepth(int val) // //javadoc: DTrees::setMaxDepth(val) public void setMaxDepth(int val) { setMaxDepth_0(nativeObj, val); return; } // // C++: void setMinSampleCount(int val) // //javadoc: DTrees::setMinSampleCount(val) public void setMinSampleCount(int val) { setMinSampleCount_0(nativeObj, val); return; } // // C++: void setPriors(Mat val) // //javadoc: DTrees::setPriors(val) public void setPriors(Mat val) { setPriors_0(nativeObj, val.nativeObj); return; } // // C++: void setRegressionAccuracy(float val) // //javadoc: DTrees::setRegressionAccuracy(val) public void setRegressionAccuracy(float val) { setRegressionAccuracy_0(nativeObj, val); return; } // // C++: void setTruncatePrunedTree(bool val) // //javadoc: DTrees::setTruncatePrunedTree(val) public void setTruncatePrunedTree(boolean val) { setTruncatePrunedTree_0(nativeObj, val); return; } // // C++: void setUse1SERule(bool val) // //javadoc: DTrees::setUse1SERule(val) public void setUse1SERule(boolean val) { setUse1SERule_0(nativeObj, val); return; } // // C++: void setUseSurrogates(bool val) // //javadoc: DTrees::setUseSurrogates(val) public void setUseSurrogates(boolean val) { setUseSurrogates_0(nativeObj, val); return; } @Override protected void finalize() throws Throwable { delete(nativeObj); } // C++: Mat getPriors() private static native long getPriors_0(long nativeObj); // C++: static Ptr_DTrees create() private static native long create_0(); // C++: bool getTruncatePrunedTree() private static native boolean getTruncatePrunedTree_0(long nativeObj); // C++: bool getUse1SERule() private static native boolean getUse1SERule_0(long nativeObj); // C++: bool getUseSurrogates() private static native boolean getUseSurrogates_0(long nativeObj); // C++: float getRegressionAccuracy() private static native float getRegressionAccuracy_0(long nativeObj); // C++: int getCVFolds() private static native int getCVFolds_0(long nativeObj); // C++: int getMaxCategories() private static native int getMaxCategories_0(long nativeObj); // C++: int getMaxDepth() private static native int getMaxDepth_0(long nativeObj); // C++: int getMinSampleCount() private static native int getMinSampleCount_0(long nativeObj); // C++: void setCVFolds(int val) private static native void setCVFolds_0(long nativeObj, int val); // C++: void setMaxCategories(int val) private static native void setMaxCategories_0(long nativeObj, int val); // C++: void setMaxDepth(int val) private static native void setMaxDepth_0(long nativeObj, int val); // C++: void setMinSampleCount(int val) private static native void setMinSampleCount_0(long nativeObj, int val); // C++: void setPriors(Mat val) private static native void setPriors_0(long nativeObj, long val_nativeObj); // C++: void setRegressionAccuracy(float val) private static native void setRegressionAccuracy_0(long nativeObj, float val); // C++: void setTruncatePrunedTree(bool val) private static native void setTruncatePrunedTree_0(long nativeObj, boolean val); // C++: void setUse1SERule(bool val) private static native void setUse1SERule_0(long nativeObj, boolean val); // C++: void setUseSurrogates(bool val) private static native void setUseSurrogates_0(long nativeObj, boolean val); // native support for java finalize() private static native void delete(long nativeObj); }
7,203
19.179272
84
java
self
self-master/lib/opencv/android/sdk/java/src/org/opencv/android/CameraRenderer.java
package org.opencv.android; import java.io.IOException; import java.util.List; import android.annotation.TargetApi; import android.hardware.Camera; import android.hardware.Camera.Size; import android.os.Build; import android.util.Log; @TargetApi(15) @SuppressWarnings("deprecation") public class CameraRenderer extends CameraGLRendererBase { public static final String LOGTAG = "CameraRenderer"; private Camera mCamera; private boolean mPreviewStarted = false; CameraRenderer(CameraGLSurfaceView view) { super(view); } @Override protected synchronized void closeCamera() { Log.i(LOGTAG, "closeCamera"); if(mCamera != null) { mCamera.stopPreview(); mPreviewStarted = false; mCamera.release(); mCamera = null; } } @Override protected synchronized void openCamera(int id) { Log.i(LOGTAG, "openCamera"); closeCamera(); if (id == CameraBridgeViewBase.CAMERA_ID_ANY) { Log.d(LOGTAG, "Trying to open camera with old open()"); try { mCamera = Camera.open(); } catch (Exception e){ Log.e(LOGTAG, "Camera is not available (in use or does not exist): " + e.getLocalizedMessage()); } if(mCamera == null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { boolean connected = false; for (int camIdx = 0; camIdx < Camera.getNumberOfCameras(); ++camIdx) { Log.d(LOGTAG, "Trying to open camera with new open(" + camIdx + ")"); try { mCamera = Camera.open(camIdx); connected = true; } catch (RuntimeException e) { Log.e(LOGTAG, "Camera #" + camIdx + "failed to open: " + e.getLocalizedMessage()); } if (connected) break; } } } else { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { int localCameraIndex = mCameraIndex; if (mCameraIndex == CameraBridgeViewBase.CAMERA_ID_BACK) { Log.i(LOGTAG, "Trying to open BACK camera"); Camera.CameraInfo cameraInfo = new Camera.CameraInfo(); for (int camIdx = 0; camIdx < Camera.getNumberOfCameras(); ++camIdx) { Camera.getCameraInfo( camIdx, cameraInfo ); if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK) { localCameraIndex = camIdx; break; } } } else if (mCameraIndex == CameraBridgeViewBase.CAMERA_ID_FRONT) { Log.i(LOGTAG, "Trying to open FRONT camera"); Camera.CameraInfo cameraInfo = new Camera.CameraInfo(); for (int camIdx = 0; camIdx < Camera.getNumberOfCameras(); ++camIdx) { Camera.getCameraInfo( camIdx, cameraInfo ); if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) { localCameraIndex = camIdx; break; } } } if (localCameraIndex == CameraBridgeViewBase.CAMERA_ID_BACK) { Log.e(LOGTAG, "Back camera not found!"); } else if (localCameraIndex == CameraBridgeViewBase.CAMERA_ID_FRONT) { Log.e(LOGTAG, "Front camera not found!"); } else { Log.d(LOGTAG, "Trying to open camera with new open(" + localCameraIndex + ")"); try { mCamera = Camera.open(localCameraIndex); } catch (RuntimeException e) { Log.e(LOGTAG, "Camera #" + localCameraIndex + "failed to open: " + e.getLocalizedMessage()); } } } } if(mCamera == null) { Log.e(LOGTAG, "Error: can't open camera"); return; } Camera.Parameters params = mCamera.getParameters(); List<String> FocusModes = params.getSupportedFocusModes(); if (FocusModes != null && FocusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) { params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO); } mCamera.setParameters(params); try { mCamera.setPreviewTexture(mSTexture); } catch (IOException ioe) { Log.e(LOGTAG, "setPreviewTexture() failed: " + ioe.getMessage()); } } @Override public synchronized void setCameraPreviewSize(int width, int height) { Log.i(LOGTAG, "setCameraPreviewSize: "+width+"x"+height); if(mCamera == null) { Log.e(LOGTAG, "Camera isn't initialized!"); return; } if(mMaxCameraWidth > 0 && mMaxCameraWidth < width) width = mMaxCameraWidth; if(mMaxCameraHeight > 0 && mMaxCameraHeight < height) height = mMaxCameraHeight; Camera.Parameters param = mCamera.getParameters(); List<Size> psize = param.getSupportedPreviewSizes(); int bestWidth = 0, bestHeight = 0; if (psize.size() > 0) { float aspect = (float)width / height; for (Size size : psize) { int w = size.width, h = size.height; Log.d(LOGTAG, "checking camera preview size: "+w+"x"+h); if ( w <= width && h <= height && w >= bestWidth && h >= bestHeight && Math.abs(aspect - (float)w/h) < 0.2 ) { bestWidth = w; bestHeight = h; } } if(bestWidth <= 0 || bestHeight <= 0) { bestWidth = psize.get(0).width; bestHeight = psize.get(0).height; Log.e(LOGTAG, "Error: best size was not selected, using "+bestWidth+" x "+bestHeight); } else { Log.i(LOGTAG, "Selected best size: "+bestWidth+" x "+bestHeight); } if(mPreviewStarted) { mCamera.stopPreview(); mPreviewStarted = false; } mCameraWidth = bestWidth; mCameraHeight = bestHeight; param.setPreviewSize(bestWidth, bestHeight); } param.set("orientation", "landscape"); mCamera.setParameters(param); mCamera.startPreview(); mPreviewStarted = true; } }
6,735
39.578313
116
java
self
self-master/lib/opencv/android/sdk/java/src/org/opencv/android/OpenCVLoader.java
package org.opencv.android; import android.content.Context; /** * Helper class provides common initialization methods for OpenCV library. */ public class OpenCVLoader { /** * OpenCV Library version 2.4.2. */ public static final String OPENCV_VERSION_2_4_2 = "2.4.2"; /** * OpenCV Library version 2.4.3. */ public static final String OPENCV_VERSION_2_4_3 = "2.4.3"; /** * OpenCV Library version 2.4.4. */ public static final String OPENCV_VERSION_2_4_4 = "2.4.4"; /** * OpenCV Library version 2.4.5. */ public static final String OPENCV_VERSION_2_4_5 = "2.4.5"; /** * OpenCV Library version 2.4.6. */ public static final String OPENCV_VERSION_2_4_6 = "2.4.6"; /** * OpenCV Library version 2.4.7. */ public static final String OPENCV_VERSION_2_4_7 = "2.4.7"; /** * OpenCV Library version 2.4.8. */ public static final String OPENCV_VERSION_2_4_8 = "2.4.8"; /** * OpenCV Library version 2.4.9. */ public static final String OPENCV_VERSION_2_4_9 = "2.4.9"; /** * OpenCV Library version 2.4.10. */ public static final String OPENCV_VERSION_2_4_10 = "2.4.10"; /** * OpenCV Library version 2.4.11. */ public static final String OPENCV_VERSION_2_4_11 = "2.4.11"; /** * OpenCV Library version 3.0.0. */ public static final String OPENCV_VERSION_3_0_0 = "3.0.0"; /** * OpenCV Library version 3.1.0. */ public static final String OPENCV_VERSION_3_1_0 = "3.1.0"; /** * Loads and initializes OpenCV library from current application package. Roughly, it's an analog of system.loadLibrary("opencv_java"). * @return Returns true is initialization of OpenCV was successful. */ public static boolean initDebug() { return StaticHelper.initOpenCV(false); } /** * Loads and initializes OpenCV library from current application package. Roughly, it's an analog of system.loadLibrary("opencv_java"). * @param InitCuda load and initialize CUDA runtime libraries. * @return Returns true is initialization of OpenCV was successful. */ public static boolean initDebug(boolean InitCuda) { return StaticHelper.initOpenCV(InitCuda); } /** * Loads and initializes OpenCV library using OpenCV Engine service. * @param Version OpenCV library version. * @param AppContext application context for connecting to the service. * @param Callback object, that implements LoaderCallbackInterface for handling the connection status. * @return Returns true if initialization of OpenCV is successful. */ public static boolean initAsync(String Version, Context AppContext, LoaderCallbackInterface Callback) { return AsyncServiceHelper.initOpenCV(Version, AppContext, Callback); } }
2,920
27.359223
139
java
self
self-master/lib/opencv/android/sdk/java/src/org/opencv/android/JavaCameraView.java
package org.opencv.android; import java.util.List; import android.content.Context; import android.graphics.ImageFormat; import android.graphics.SurfaceTexture; import android.hardware.Camera; import android.hardware.Camera.PreviewCallback; import android.os.Build; import android.util.AttributeSet; import android.util.Log; import android.view.ViewGroup.LayoutParams; import org.opencv.core.CvType; import org.opencv.core.Mat; import org.opencv.core.Size; import org.opencv.imgproc.Imgproc; /** * This class is an implementation of the Bridge View between OpenCV and Java Camera. * This class relays on the functionality available in base class and only implements * required functions: * connectCamera - opens Java camera and sets the PreviewCallback to be delivered. * disconnectCamera - closes the camera and stops preview. * When frame is delivered via callback from Camera - it processed via OpenCV to be * converted to RGBA32 and then passed to the external callback for modifications if required. */ public class JavaCameraView extends CameraBridgeViewBase implements PreviewCallback { private static final int MAGIC_TEXTURE_ID = 10; private static final String TAG = "JavaCameraView"; private byte mBuffer[]; private Mat[] mFrameChain; private int mChainIdx = 0; private Thread mThread; private boolean mStopThread; protected Camera mCamera; protected JavaCameraFrame[] mCameraFrame; private SurfaceTexture mSurfaceTexture; public static class JavaCameraSizeAccessor implements ListItemAccessor { @Override public int getWidth(Object obj) { Camera.Size size = (Camera.Size) obj; return size.width; } @Override public int getHeight(Object obj) { Camera.Size size = (Camera.Size) obj; return size.height; } } public JavaCameraView(Context context, int cameraId) { super(context, cameraId); } public JavaCameraView(Context context, AttributeSet attrs) { super(context, attrs); } protected boolean initializeCamera(int width, int height) { Log.d(TAG, "Initialize java camera"); boolean result = true; synchronized (this) { mCamera = null; if (mCameraIndex == CAMERA_ID_ANY) { Log.d(TAG, "Trying to open camera with old open()"); try { mCamera = Camera.open(); } catch (Exception e){ Log.e(TAG, "Camera is not available (in use or does not exist): " + e.getLocalizedMessage()); } if(mCamera == null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { boolean connected = false; for (int camIdx = 0; camIdx < Camera.getNumberOfCameras(); ++camIdx) { Log.d(TAG, "Trying to open camera with new open(" + Integer.valueOf(camIdx) + ")"); try { mCamera = Camera.open(camIdx); connected = true; } catch (RuntimeException e) { Log.e(TAG, "Camera #" + camIdx + "failed to open: " + e.getLocalizedMessage()); } if (connected) break; } } } else { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { int localCameraIndex = mCameraIndex; if (mCameraIndex == CAMERA_ID_BACK) { Log.i(TAG, "Trying to open back camera"); Camera.CameraInfo cameraInfo = new Camera.CameraInfo(); for (int camIdx = 0; camIdx < Camera.getNumberOfCameras(); ++camIdx) { Camera.getCameraInfo( camIdx, cameraInfo ); if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK) { localCameraIndex = camIdx; break; } } } else if (mCameraIndex == CAMERA_ID_FRONT) { Log.i(TAG, "Trying to open front camera"); Camera.CameraInfo cameraInfo = new Camera.CameraInfo(); for (int camIdx = 0; camIdx < Camera.getNumberOfCameras(); ++camIdx) { Camera.getCameraInfo( camIdx, cameraInfo ); if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) { localCameraIndex = camIdx; break; } } } if (localCameraIndex == CAMERA_ID_BACK) { Log.e(TAG, "Back camera not found!"); } else if (localCameraIndex == CAMERA_ID_FRONT) { Log.e(TAG, "Front camera not found!"); } else { Log.d(TAG, "Trying to open camera with new open(" + Integer.valueOf(localCameraIndex) + ")"); try { mCamera = Camera.open(localCameraIndex); } catch (RuntimeException e) { Log.e(TAG, "Camera #" + localCameraIndex + "failed to open: " + e.getLocalizedMessage()); } } } } if (mCamera == null) return false; /* Now set camera parameters */ try { Camera.Parameters params = mCamera.getParameters(); Log.d(TAG, "getSupportedPreviewSizes()"); List<android.hardware.Camera.Size> sizes = params.getSupportedPreviewSizes(); if (sizes != null) { /* Select the size that fits surface considering maximum size allowed */ Size frameSize = calculateCameraFrameSize(sizes, new JavaCameraSizeAccessor(), width, height); params.setPreviewFormat(ImageFormat.NV21); Log.d(TAG, "Set preview size to " + Integer.valueOf((int)frameSize.width) + "x" + Integer.valueOf((int)frameSize.height)); params.setPreviewSize((int)frameSize.width, (int)frameSize.height); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH && !android.os.Build.MODEL.equals("GT-I9100")) params.setRecordingHint(true); List<String> FocusModes = params.getSupportedFocusModes(); if (FocusModes != null && FocusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) { params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO); } mCamera.setParameters(params); params = mCamera.getParameters(); mFrameWidth = params.getPreviewSize().width; mFrameHeight = params.getPreviewSize().height; if ((getLayoutParams().width == LayoutParams.MATCH_PARENT) && (getLayoutParams().height == LayoutParams.MATCH_PARENT)) mScale = Math.min(((float)height)/mFrameHeight, ((float)width)/mFrameWidth); else mScale = 0; if (mFpsMeter != null) { mFpsMeter.setResolution(mFrameWidth, mFrameHeight); } int size = mFrameWidth * mFrameHeight; size = size * ImageFormat.getBitsPerPixel(params.getPreviewFormat()) / 8; mBuffer = new byte[size]; mCamera.addCallbackBuffer(mBuffer); mCamera.setPreviewCallbackWithBuffer(this); mFrameChain = new Mat[2]; mFrameChain[0] = new Mat(mFrameHeight + (mFrameHeight/2), mFrameWidth, CvType.CV_8UC1); mFrameChain[1] = new Mat(mFrameHeight + (mFrameHeight/2), mFrameWidth, CvType.CV_8UC1); AllocateCache(); mCameraFrame = new JavaCameraFrame[2]; mCameraFrame[0] = new JavaCameraFrame(mFrameChain[0], mFrameWidth, mFrameHeight); mCameraFrame[1] = new JavaCameraFrame(mFrameChain[1], mFrameWidth, mFrameHeight); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { mSurfaceTexture = new SurfaceTexture(MAGIC_TEXTURE_ID); mCamera.setPreviewTexture(mSurfaceTexture); } else mCamera.setPreviewDisplay(null); /* Finally we are ready to start the preview */ Log.d(TAG, "startPreview"); mCamera.startPreview(); } else result = false; } catch (Exception e) { result = false; e.printStackTrace(); } } return result; } protected void releaseCamera() { synchronized (this) { if (mCamera != null) { mCamera.stopPreview(); mCamera.setPreviewCallback(null); mCamera.release(); } mCamera = null; if (mFrameChain != null) { mFrameChain[0].release(); mFrameChain[1].release(); } if (mCameraFrame != null) { mCameraFrame[0].release(); mCameraFrame[1].release(); } } } private boolean mCameraFrameReady = false; @Override protected boolean connectCamera(int width, int height) { /* 1. We need to instantiate camera * 2. We need to start thread which will be getting frames */ /* First step - initialize camera connection */ Log.d(TAG, "Connecting to camera"); if (!initializeCamera(width, height)) return false; mCameraFrameReady = false; /* now we can start update thread */ Log.d(TAG, "Starting processing thread"); mStopThread = false; mThread = new Thread(new CameraWorker()); mThread.start(); return true; } @Override protected void disconnectCamera() { /* 1. We need to stop thread which updating the frames * 2. Stop camera and release it */ Log.d(TAG, "Disconnecting from camera"); try { mStopThread = true; Log.d(TAG, "Notify thread"); synchronized (this) { this.notify(); } Log.d(TAG, "Wating for thread"); if (mThread != null) mThread.join(); } catch (InterruptedException e) { e.printStackTrace(); } finally { mThread = null; } /* Now release camera */ releaseCamera(); mCameraFrameReady = false; } @Override public void onPreviewFrame(byte[] frame, Camera arg1) { Log.d(TAG, "Preview Frame received. Frame size: " + frame.length); synchronized (this) { mFrameChain[mChainIdx].put(0, 0, frame); mCameraFrameReady = true; this.notify(); } if (mCamera != null) mCamera.addCallbackBuffer(mBuffer); } private class JavaCameraFrame implements CvCameraViewFrame { @Override public Mat gray() { return mYuvFrameData.submat(0, mHeight, 0, mWidth); } @Override public Mat rgba() { Imgproc.cvtColor(mYuvFrameData, mRgba, Imgproc.COLOR_YUV2RGBA_NV21, 4); return mRgba; } public JavaCameraFrame(Mat Yuv420sp, int width, int height) { super(); mWidth = width; mHeight = height; mYuvFrameData = Yuv420sp; mRgba = new Mat(); } public void release() { mRgba.release(); } private Mat mYuvFrameData; private Mat mRgba; private int mWidth; private int mHeight; }; private class CameraWorker implements Runnable { @Override public void run() { do { boolean hasFrame = false; synchronized (JavaCameraView.this) { try { while (!mCameraFrameReady && !mStopThread) { JavaCameraView.this.wait(); } } catch (InterruptedException e) { e.printStackTrace(); } if (mCameraFrameReady) { mChainIdx = 1 - mChainIdx; mCameraFrameReady = false; hasFrame = true; } } if (!mStopThread && hasFrame) { if (!mFrameChain[1 - mChainIdx].empty()) deliverAndDrawFrame(mCameraFrame[1 - mChainIdx]); } } while (!mStopThread); Log.d(TAG, "Finish processing thread"); } } }
13,499
36.815126
142
java
self
self-master/lib/opencv/android/sdk/java/src/org/opencv/android/CameraGLSurfaceView.java
package org.opencv.android; import org.opencv.R; import android.content.Context; import android.content.res.TypedArray; import android.opengl.GLSurfaceView; import android.util.AttributeSet; import android.util.Log; import android.view.SurfaceHolder; public class CameraGLSurfaceView extends GLSurfaceView { private static final String LOGTAG = "CameraGLSurfaceView"; public interface CameraTextureListener { /** * This method is invoked when camera preview has started. After this method is invoked * the frames will start to be delivered to client via the onCameraFrame() callback. * @param width - the width of the frames that will be delivered * @param height - the height of the frames that will be delivered */ public void onCameraViewStarted(int width, int height); /** * This method is invoked when camera preview has been stopped for some reason. * No frames will be delivered via onCameraFrame() callback after this method is called. */ public void onCameraViewStopped(); /** * This method is invoked when a new preview frame from Camera is ready. * @param texIn - the OpenGL texture ID that contains frame in RGBA format * @param texOut - the OpenGL texture ID that can be used to store modified frame image t display * @param width - the width of the frame * @param height - the height of the frame * @return `true` if `texOut` should be displayed, `false` - to show `texIn` */ public boolean onCameraTexture(int texIn, int texOut, int width, int height); }; private CameraTextureListener mTexListener; private CameraGLRendererBase mRenderer; public CameraGLSurfaceView(Context context, AttributeSet attrs) { super(context, attrs); TypedArray styledAttrs = getContext().obtainStyledAttributes(attrs, R.styleable.CameraBridgeViewBase); int cameraIndex = styledAttrs.getInt(R.styleable.CameraBridgeViewBase_camera_id, -1); styledAttrs.recycle(); if(android.os.Build.VERSION.SDK_INT >= 21) mRenderer = new Camera2Renderer(this); else mRenderer = new CameraRenderer(this); setCameraIndex(cameraIndex); setEGLContextClientVersion(2); setRenderer(mRenderer); setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY); } public void setCameraTextureListener(CameraTextureListener texListener) { mTexListener = texListener; } public CameraTextureListener getCameraTextureListener() { return mTexListener; } public void setCameraIndex(int cameraIndex) { mRenderer.setCameraIndex(cameraIndex); } public void setMaxCameraPreviewSize(int maxWidth, int maxHeight) { mRenderer.setMaxCameraPreviewSize(maxWidth, maxHeight); } @Override public void surfaceCreated(SurfaceHolder holder) { super.surfaceCreated(holder); } @Override public void surfaceDestroyed(SurfaceHolder holder) { mRenderer.mHaveSurface = false; super.surfaceDestroyed(holder); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { super.surfaceChanged(holder, format, w, h); } @Override public void onResume() { Log.i(LOGTAG, "onResume"); super.onResume(); mRenderer.onResume(); } @Override public void onPause() { Log.i(LOGTAG, "onPause"); mRenderer.onPause(); super.onPause(); } public void enableView() { mRenderer.enableView(); } public void disableView() { mRenderer.disableView(); } }
3,771
30.433333
110
java
self
self-master/lib/opencv/android/sdk/java/src/org/opencv/android/Utils.java
package org.opencv.android; import android.content.Context; import android.graphics.Bitmap; import org.opencv.core.CvException; import org.opencv.core.CvType; import org.opencv.core.Mat; import org.opencv.imgcodecs.Imgcodecs; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; public class Utils { public static String exportResource(Context context, int resourceId) { return exportResource(context, resourceId, "OpenCV_data"); } public static String exportResource(Context context, int resourceId, String dirname) { String fullname = context.getResources().getString(resourceId); String resName = fullname.substring(fullname.lastIndexOf("/") + 1); try { InputStream is = context.getResources().openRawResource(resourceId); File resDir = context.getDir(dirname, Context.MODE_PRIVATE); File resFile = new File(resDir, resName); FileOutputStream os = new FileOutputStream(resFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = is.read(buffer)) != -1) { os.write(buffer, 0, bytesRead); } is.close(); os.close(); return resFile.getAbsolutePath(); } catch (IOException e) { e.printStackTrace(); throw new CvException("Failed to export resource " + resName + ". Exception thrown: " + e); } } public static Mat loadResource(Context context, int resourceId) throws IOException { return loadResource(context, resourceId, -1); } public static Mat loadResource(Context context, int resourceId, int flags) throws IOException { InputStream is = context.getResources().openRawResource(resourceId); ByteArrayOutputStream os = new ByteArrayOutputStream(is.available()); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = is.read(buffer)) != -1) { os.write(buffer, 0, bytesRead); } is.close(); Mat encoded = new Mat(1, os.size(), CvType.CV_8U); encoded.put(0, 0, os.toByteArray()); os.close(); Mat decoded = Imgcodecs.imdecode(encoded, flags); encoded.release(); return decoded; } /** * Converts Android Bitmap to OpenCV Mat. * <p> * This function converts an Android Bitmap image to the OpenCV Mat. * <br>'ARGB_8888' and 'RGB_565' input Bitmap formats are supported. * <br>The output Mat is always created of the same size as the input Bitmap and of the 'CV_8UC4' type, * it keeps the image in RGBA format. * <br>This function throws an exception if the conversion fails. * @param bmp is a valid input Bitmap object of the type 'ARGB_8888' or 'RGB_565'. * @param mat is a valid output Mat object, it will be reallocated if needed, so it may be empty. * @param unPremultiplyAlpha is a flag, that determines, whether the bitmap needs to be converted from alpha premultiplied format (like Android keeps 'ARGB_8888' ones) to regular one; this flag is ignored for 'RGB_565' bitmaps. */ public static void bitmapToMat(Bitmap bmp, Mat mat, boolean unPremultiplyAlpha) { if (bmp == null) throw new java.lang.IllegalArgumentException("bmp == null"); if (mat == null) throw new java.lang.IllegalArgumentException("mat == null"); nBitmapToMat2(bmp, mat.nativeObj, unPremultiplyAlpha); } /** * Short form of the bitmapToMat(bmp, mat, unPremultiplyAlpha=false). * @param bmp is a valid input Bitmap object of the type 'ARGB_8888' or 'RGB_565'. * @param mat is a valid output Mat object, it will be reallocated if needed, so Mat may be empty. */ public static void bitmapToMat(Bitmap bmp, Mat mat) { bitmapToMat(bmp, mat, false); } /** * Converts OpenCV Mat to Android Bitmap. * <p> * <br>This function converts an image in the OpenCV Mat representation to the Android Bitmap. * <br>The input Mat object has to be of the types 'CV_8UC1' (gray-scale), 'CV_8UC3' (RGB) or 'CV_8UC4' (RGBA). * <br>The output Bitmap object has to be of the same size as the input Mat and of the types 'ARGB_8888' or 'RGB_565'. * <br>This function throws an exception if the conversion fails. * * @param mat is a valid input Mat object of types 'CV_8UC1', 'CV_8UC3' or 'CV_8UC4'. * @param bmp is a valid Bitmap object of the same size as the Mat and of type 'ARGB_8888' or 'RGB_565'. * @param premultiplyAlpha is a flag, that determines, whether the Mat needs to be converted to alpha premultiplied format (like Android keeps 'ARGB_8888' bitmaps); the flag is ignored for 'RGB_565' bitmaps. */ public static void matToBitmap(Mat mat, Bitmap bmp, boolean premultiplyAlpha) { if (mat == null) throw new java.lang.IllegalArgumentException("mat == null"); if (bmp == null) throw new java.lang.IllegalArgumentException("bmp == null"); nMatToBitmap2(mat.nativeObj, bmp, premultiplyAlpha); } /** * Short form of the <b>matToBitmap(mat, bmp, premultiplyAlpha=false)</b> * @param mat is a valid input Mat object of the types 'CV_8UC1', 'CV_8UC3' or 'CV_8UC4'. * @param bmp is a valid Bitmap object of the same size as the Mat and of type 'ARGB_8888' or 'RGB_565'. */ public static void matToBitmap(Mat mat, Bitmap bmp) { matToBitmap(mat, bmp, false); } private static native void nBitmapToMat2(Bitmap b, long m_addr, boolean unPremultiplyAlpha); private static native void nMatToBitmap2(long m_addr, Bitmap b, boolean premultiplyAlpha); }
5,858
40.85
231
java
self
self-master/lib/opencv/android/sdk/java/src/org/opencv/android/AsyncServiceHelper.java
package org.opencv.android; import java.io.File; import java.util.StringTokenizer; import org.opencv.core.Core; import org.opencv.engine.OpenCVEngineInterface; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.net.Uri; import android.os.IBinder; import android.os.RemoteException; import android.util.Log; class AsyncServiceHelper { public static boolean initOpenCV(String Version, final Context AppContext, final LoaderCallbackInterface Callback) { AsyncServiceHelper helper = new AsyncServiceHelper(Version, AppContext, Callback); Intent intent = new Intent("org.opencv.engine.BIND"); intent.setPackage("org.opencv.engine"); if (AppContext.bindService(intent, helper.mServiceConnection, Context.BIND_AUTO_CREATE)) { return true; } else { AppContext.unbindService(helper.mServiceConnection); InstallService(AppContext, Callback); return false; } } protected AsyncServiceHelper(String Version, Context AppContext, LoaderCallbackInterface Callback) { mOpenCVersion = Version; mUserAppCallback = Callback; mAppContext = AppContext; } protected static final String TAG = "OpenCVManager/Helper"; protected static final int MINIMUM_ENGINE_VERSION = 2; protected OpenCVEngineInterface mEngineService; protected LoaderCallbackInterface mUserAppCallback; protected String mOpenCVersion; protected Context mAppContext; protected static boolean mServiceInstallationProgress = false; protected static boolean mLibraryInstallationProgress = false; protected static boolean InstallServiceQuiet(Context context) { boolean result = true; try { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(OPEN_CV_SERVICE_URL)); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } catch(Exception e) { result = false; } return result; } protected static void InstallService(final Context AppContext, final LoaderCallbackInterface Callback) { if (!mServiceInstallationProgress) { Log.d(TAG, "Request new service installation"); InstallCallbackInterface InstallQuery = new InstallCallbackInterface() { private LoaderCallbackInterface mUserAppCallback = Callback; public String getPackageName() { return "OpenCV Manager"; } public void install() { Log.d(TAG, "Trying to install OpenCV Manager via Google Play"); boolean result = InstallServiceQuiet(AppContext); if (result) { mServiceInstallationProgress = true; Log.d(TAG, "Package installation started"); } else { Log.d(TAG, "OpenCV package was not installed!"); int Status = LoaderCallbackInterface.MARKET_ERROR; Log.d(TAG, "Init finished with status " + Status); Log.d(TAG, "Unbind from service"); Log.d(TAG, "Calling using callback"); mUserAppCallback.onManagerConnected(Status); } } public void cancel() { Log.d(TAG, "OpenCV library installation was canceled"); int Status = LoaderCallbackInterface.INSTALL_CANCELED; Log.d(TAG, "Init finished with status " + Status); Log.d(TAG, "Calling using callback"); mUserAppCallback.onManagerConnected(Status); } public void wait_install() { Log.e(TAG, "Instalation was not started! Nothing to wait!"); } }; Callback.onPackageInstall(InstallCallbackInterface.NEW_INSTALLATION, InstallQuery); } else { Log.d(TAG, "Waiting current installation process"); InstallCallbackInterface WaitQuery = new InstallCallbackInterface() { private LoaderCallbackInterface mUserAppCallback = Callback; public String getPackageName() { return "OpenCV Manager"; } public void install() { Log.e(TAG, "Nothing to install we just wait current installation"); } public void cancel() { Log.d(TAG, "Wating for OpenCV canceled by user"); mServiceInstallationProgress = false; int Status = LoaderCallbackInterface.INSTALL_CANCELED; Log.d(TAG, "Init finished with status " + Status); Log.d(TAG, "Calling using callback"); mUserAppCallback.onManagerConnected(Status); } public void wait_install() { InstallServiceQuiet(AppContext); } }; Callback.onPackageInstall(InstallCallbackInterface.INSTALLATION_PROGRESS, WaitQuery); } } /** * URL of OpenCV Manager page on Google Play Market. */ protected static final String OPEN_CV_SERVICE_URL = "market://details?id=org.opencv.engine"; protected ServiceConnection mServiceConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { Log.d(TAG, "Service connection created"); mEngineService = OpenCVEngineInterface.Stub.asInterface(service); if (null == mEngineService) { Log.d(TAG, "OpenCV Manager Service connection fails. May be service was not installed?"); InstallService(mAppContext, mUserAppCallback); } else { mServiceInstallationProgress = false; try { if (mEngineService.getEngineVersion() < MINIMUM_ENGINE_VERSION) { Log.d(TAG, "Init finished with status " + LoaderCallbackInterface.INCOMPATIBLE_MANAGER_VERSION); Log.d(TAG, "Unbind from service"); mAppContext.unbindService(mServiceConnection); Log.d(TAG, "Calling using callback"); mUserAppCallback.onManagerConnected(LoaderCallbackInterface.INCOMPATIBLE_MANAGER_VERSION); return; } Log.d(TAG, "Trying to get library path"); String path = mEngineService.getLibPathByVersion(mOpenCVersion); if ((null == path) || (path.length() == 0)) { if (!mLibraryInstallationProgress) { InstallCallbackInterface InstallQuery = new InstallCallbackInterface() { public String getPackageName() { return "OpenCV library"; } public void install() { Log.d(TAG, "Trying to install OpenCV lib via Google Play"); try { if (mEngineService.installVersion(mOpenCVersion)) { mLibraryInstallationProgress = true; Log.d(TAG, "Package installation statred"); Log.d(TAG, "Unbind from service"); mAppContext.unbindService(mServiceConnection); } else { Log.d(TAG, "OpenCV package was not installed!"); Log.d(TAG, "Init finished with status " + LoaderCallbackInterface.MARKET_ERROR); Log.d(TAG, "Unbind from service"); mAppContext.unbindService(mServiceConnection); Log.d(TAG, "Calling using callback"); mUserAppCallback.onManagerConnected(LoaderCallbackInterface.MARKET_ERROR); } } catch (RemoteException e) { e.printStackTrace();; Log.d(TAG, "Init finished with status " + LoaderCallbackInterface.INIT_FAILED); Log.d(TAG, "Unbind from service"); mAppContext.unbindService(mServiceConnection); Log.d(TAG, "Calling using callback"); mUserAppCallback.onManagerConnected(LoaderCallbackInterface.INIT_FAILED); } } public void cancel() { Log.d(TAG, "OpenCV library installation was canceled"); Log.d(TAG, "Init finished with status " + LoaderCallbackInterface.INSTALL_CANCELED); Log.d(TAG, "Unbind from service"); mAppContext.unbindService(mServiceConnection); Log.d(TAG, "Calling using callback"); mUserAppCallback.onManagerConnected(LoaderCallbackInterface.INSTALL_CANCELED); } public void wait_install() { Log.e(TAG, "Instalation was not started! Nothing to wait!"); } }; mUserAppCallback.onPackageInstall(InstallCallbackInterface.NEW_INSTALLATION, InstallQuery); } else { InstallCallbackInterface WaitQuery = new InstallCallbackInterface() { public String getPackageName() { return "OpenCV library"; } public void install() { Log.e(TAG, "Nothing to install we just wait current installation"); } public void cancel() { Log.d(TAG, "OpenCV library installation was canceled"); mLibraryInstallationProgress = false; Log.d(TAG, "Init finished with status " + LoaderCallbackInterface.INSTALL_CANCELED); Log.d(TAG, "Unbind from service"); mAppContext.unbindService(mServiceConnection); Log.d(TAG, "Calling using callback"); mUserAppCallback.onManagerConnected(LoaderCallbackInterface.INSTALL_CANCELED); } public void wait_install() { Log.d(TAG, "Waiting for current installation"); try { if (!mEngineService.installVersion(mOpenCVersion)) { Log.d(TAG, "OpenCV package was not installed!"); Log.d(TAG, "Init finished with status " + LoaderCallbackInterface.MARKET_ERROR); Log.d(TAG, "Calling using callback"); mUserAppCallback.onManagerConnected(LoaderCallbackInterface.MARKET_ERROR); } else { Log.d(TAG, "Wating for package installation"); } Log.d(TAG, "Unbind from service"); mAppContext.unbindService(mServiceConnection); } catch (RemoteException e) { e.printStackTrace(); Log.d(TAG, "Init finished with status " + LoaderCallbackInterface.INIT_FAILED); Log.d(TAG, "Unbind from service"); mAppContext.unbindService(mServiceConnection); Log.d(TAG, "Calling using callback"); mUserAppCallback.onManagerConnected(LoaderCallbackInterface.INIT_FAILED); } } }; mUserAppCallback.onPackageInstall(InstallCallbackInterface.INSTALLATION_PROGRESS, WaitQuery); } return; } else { Log.d(TAG, "Trying to get library list"); mLibraryInstallationProgress = false; String libs = mEngineService.getLibraryList(mOpenCVersion); Log.d(TAG, "Library list: \"" + libs + "\""); Log.d(TAG, "First attempt to load libs"); int status; if (initOpenCVLibs(path, libs)) { Log.d(TAG, "First attempt to load libs is OK"); String eol = System.getProperty("line.separator"); for (String str : Core.getBuildInformation().split(eol)) Log.i(TAG, str); status = LoaderCallbackInterface.SUCCESS; } else { Log.d(TAG, "First attempt to load libs fails"); status = LoaderCallbackInterface.INIT_FAILED; } Log.d(TAG, "Init finished with status " + status); Log.d(TAG, "Unbind from service"); mAppContext.unbindService(mServiceConnection); Log.d(TAG, "Calling using callback"); mUserAppCallback.onManagerConnected(status); } } catch (RemoteException e) { e.printStackTrace(); Log.d(TAG, "Init finished with status " + LoaderCallbackInterface.INIT_FAILED); Log.d(TAG, "Unbind from service"); mAppContext.unbindService(mServiceConnection); Log.d(TAG, "Calling using callback"); mUserAppCallback.onManagerConnected(LoaderCallbackInterface.INIT_FAILED); } } } public void onServiceDisconnected(ComponentName className) { mEngineService = null; } }; private boolean loadLibrary(String AbsPath) { boolean result = true; Log.d(TAG, "Trying to load library " + AbsPath); try { System.load(AbsPath); Log.d(TAG, "OpenCV libs init was ok!"); } catch(UnsatisfiedLinkError e) { Log.d(TAG, "Cannot load library \"" + AbsPath + "\""); e.printStackTrace(); result &= false; } return result; } private boolean initOpenCVLibs(String Path, String Libs) { Log.d(TAG, "Trying to init OpenCV libs"); if ((null != Path) && (Path.length() != 0)) { boolean result = true; if ((null != Libs) && (Libs.length() != 0)) { Log.d(TAG, "Trying to load libs by dependency list"); StringTokenizer splitter = new StringTokenizer(Libs, ";"); while(splitter.hasMoreTokens()) { String AbsLibraryPath = Path + File.separator + splitter.nextToken(); result &= loadLibrary(AbsLibraryPath); } } else { // If the dependencies list is not defined or empty. String AbsLibraryPath = Path + File.separator + "libopencv_java3.so"; result &= loadLibrary(AbsLibraryPath); } return result; } else { Log.d(TAG, "Library path \"" + Path + "\" is empty"); return false; } } }
17,921
44.719388
124
java
self
self-master/lib/opencv/android/sdk/java/src/org/opencv/android/CameraGLRendererBase.java
package org.opencv.android; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; import org.opencv.android.CameraGLSurfaceView.CameraTextureListener; import android.annotation.TargetApi; import android.graphics.SurfaceTexture; import android.opengl.GLES11Ext; import android.opengl.GLES20; import android.opengl.GLSurfaceView; import android.util.Log; import android.view.View; @TargetApi(15) public abstract class CameraGLRendererBase implements GLSurfaceView.Renderer, SurfaceTexture.OnFrameAvailableListener { protected final String LOGTAG = "CameraGLRendererBase"; // shaders private final String vss = "" + "attribute vec2 vPosition;\n" + "attribute vec2 vTexCoord;\n" + "varying vec2 texCoord;\n" + "void main() {\n" + " texCoord = vTexCoord;\n" + " gl_Position = vec4 ( vPosition.x, vPosition.y, 0.0, 1.0 );\n" + "}"; private final String fssOES = "" + "#extension GL_OES_EGL_image_external : require\n" + "precision mediump float;\n" + "uniform samplerExternalOES sTexture;\n" + "varying vec2 texCoord;\n" + "void main() {\n" + " gl_FragColor = texture2D(sTexture,texCoord);\n" + "}"; private final String fss2D = "" + "precision mediump float;\n" + "uniform sampler2D sTexture;\n" + "varying vec2 texCoord;\n" + "void main() {\n" + " gl_FragColor = texture2D(sTexture,texCoord);\n" + "}"; // coord-s private final float vertices[] = { -1, -1, -1, 1, 1, -1, 1, 1 }; private final float texCoordOES[] = { 0, 1, 0, 0, 1, 1, 1, 0 }; private final float texCoord2D[] = { 0, 0, 0, 1, 1, 0, 1, 1 }; private int[] texCamera = {0}, texFBO = {0}, texDraw = {0}; private int[] FBO = {0}; private int progOES = -1, prog2D = -1; private int vPosOES, vTCOES, vPos2D, vTC2D; private FloatBuffer vert, texOES, tex2D; protected int mCameraWidth = -1, mCameraHeight = -1; protected int mFBOWidth = -1, mFBOHeight = -1; protected int mMaxCameraWidth = -1, mMaxCameraHeight = -1; protected int mCameraIndex = CameraBridgeViewBase.CAMERA_ID_ANY; protected SurfaceTexture mSTexture; protected boolean mHaveSurface = false; protected boolean mHaveFBO = false; protected boolean mUpdateST = false; protected boolean mEnabled = true; protected boolean mIsStarted = false; protected CameraGLSurfaceView mView; protected abstract void openCamera(int id); protected abstract void closeCamera(); protected abstract void setCameraPreviewSize(int width, int height); // updates mCameraWidth & mCameraHeight public CameraGLRendererBase(CameraGLSurfaceView view) { mView = view; int bytes = vertices.length * Float.SIZE / Byte.SIZE; vert = ByteBuffer.allocateDirect(bytes).order(ByteOrder.nativeOrder()).asFloatBuffer(); texOES = ByteBuffer.allocateDirect(bytes).order(ByteOrder.nativeOrder()).asFloatBuffer(); tex2D = ByteBuffer.allocateDirect(bytes).order(ByteOrder.nativeOrder()).asFloatBuffer(); vert.put(vertices).position(0); texOES.put(texCoordOES).position(0); tex2D.put(texCoord2D).position(0); } @Override public synchronized void onFrameAvailable(SurfaceTexture surfaceTexture) { //Log.i(LOGTAG, "onFrameAvailable"); mUpdateST = true; mView.requestRender(); } @Override public void onDrawFrame(GL10 gl) { //Log.i(LOGTAG, "onDrawFrame start"); if (!mHaveFBO) return; synchronized(this) { if (mUpdateST) { mSTexture.updateTexImage(); mUpdateST = false; } GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT); CameraTextureListener texListener = mView.getCameraTextureListener(); if(texListener != null) { //Log.d(LOGTAG, "haveUserCallback"); // texCamera(OES) -> texFBO drawTex(texCamera[0], true, FBO[0]); // call user code (texFBO -> texDraw) boolean modified = texListener.onCameraTexture(texFBO[0], texDraw[0], mCameraWidth, mCameraHeight); if(modified) { // texDraw -> screen drawTex(texDraw[0], false, 0); } else { // texFBO -> screen drawTex(texFBO[0], false, 0); } } else { Log.d(LOGTAG, "texCamera(OES) -> screen"); // texCamera(OES) -> screen drawTex(texCamera[0], true, 0); } //Log.i(LOGTAG, "onDrawFrame end"); } } @Override public void onSurfaceChanged(GL10 gl, int surfaceWidth, int surfaceHeight) { Log.i(LOGTAG, "onSurfaceChanged("+surfaceWidth+"x"+surfaceHeight+")"); mHaveSurface = true; updateState(); setPreviewSize(surfaceWidth, surfaceHeight); } @Override public void onSurfaceCreated(GL10 gl, EGLConfig config) { Log.i(LOGTAG, "onSurfaceCreated"); initShaders(); } private void initShaders() { String strGLVersion = GLES20.glGetString(GLES20.GL_VERSION); if (strGLVersion != null) Log.i(LOGTAG, "OpenGL ES version: " + strGLVersion); GLES20.glClearColor(1.0f, 1.0f, 1.0f, 1.0f); progOES = loadShader(vss, fssOES); vPosOES = GLES20.glGetAttribLocation(progOES, "vPosition"); vTCOES = GLES20.glGetAttribLocation(progOES, "vTexCoord"); GLES20.glEnableVertexAttribArray(vPosOES); GLES20.glEnableVertexAttribArray(vTCOES); prog2D = loadShader(vss, fss2D); vPos2D = GLES20.glGetAttribLocation(prog2D, "vPosition"); vTC2D = GLES20.glGetAttribLocation(prog2D, "vTexCoord"); GLES20.glEnableVertexAttribArray(vPos2D); GLES20.glEnableVertexAttribArray(vTC2D); } private void initSurfaceTexture() { Log.d(LOGTAG, "initSurfaceTexture"); deleteSurfaceTexture(); initTexOES(texCamera); mSTexture = new SurfaceTexture(texCamera[0]); mSTexture.setOnFrameAvailableListener(this); } private void deleteSurfaceTexture() { Log.d(LOGTAG, "deleteSurfaceTexture"); if(mSTexture != null) { mSTexture.release(); mSTexture = null; deleteTex(texCamera); } } private void initTexOES(int[] tex) { if(tex.length == 1) { GLES20.glGenTextures(1, tex, 0); GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, tex[0]); GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE); GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE); GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST); GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_NEAREST); } } private static void deleteTex(int[] tex) { if(tex.length == 1) { GLES20.glDeleteTextures(1, tex, 0); } } private static int loadShader(String vss, String fss) { Log.d("CameraGLRendererBase", "loadShader"); int vshader = GLES20.glCreateShader(GLES20.GL_VERTEX_SHADER); GLES20.glShaderSource(vshader, vss); GLES20.glCompileShader(vshader); int[] status = new int[1]; GLES20.glGetShaderiv(vshader, GLES20.GL_COMPILE_STATUS, status, 0); if (status[0] == 0) { Log.e("CameraGLRendererBase", "Could not compile vertex shader: "+GLES20.glGetShaderInfoLog(vshader)); GLES20.glDeleteShader(vshader); vshader = 0; return 0; } int fshader = GLES20.glCreateShader(GLES20.GL_FRAGMENT_SHADER); GLES20.glShaderSource(fshader, fss); GLES20.glCompileShader(fshader); GLES20.glGetShaderiv(fshader, GLES20.GL_COMPILE_STATUS, status, 0); if (status[0] == 0) { Log.e("CameraGLRendererBase", "Could not compile fragment shader:"+GLES20.glGetShaderInfoLog(fshader)); GLES20.glDeleteShader(vshader); GLES20.glDeleteShader(fshader); fshader = 0; return 0; } int program = GLES20.glCreateProgram(); GLES20.glAttachShader(program, vshader); GLES20.glAttachShader(program, fshader); GLES20.glLinkProgram(program); GLES20.glDeleteShader(vshader); GLES20.glDeleteShader(fshader); GLES20.glGetProgramiv(program, GLES20.GL_LINK_STATUS, status, 0); if (status[0] == 0) { Log.e("CameraGLRendererBase", "Could not link shader program: "+GLES20.glGetProgramInfoLog(program)); program = 0; return 0; } GLES20.glValidateProgram(program); GLES20.glGetProgramiv(program, GLES20.GL_VALIDATE_STATUS, status, 0); if (status[0] == 0) { Log.e("CameraGLRendererBase", "Shader program validation error: "+GLES20.glGetProgramInfoLog(program)); GLES20.glDeleteProgram(program); program = 0; return 0; } Log.d("CameraGLRendererBase", "Shader program is built OK"); return program; } private void deleteFBO() { Log.d(LOGTAG, "deleteFBO("+mFBOWidth+"x"+mFBOHeight+")"); GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0); GLES20.glDeleteFramebuffers(1, FBO, 0); deleteTex(texFBO); deleteTex(texDraw); mFBOWidth = mFBOHeight = 0; } private void initFBO(int width, int height) { Log.d(LOGTAG, "initFBO("+width+"x"+height+")"); deleteFBO(); GLES20.glGenTextures(1, texDraw, 0); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texDraw[0]); GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGBA, width, height, 0, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, null); GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE); GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE); GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST); GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_NEAREST); GLES20.glGenTextures(1, texFBO, 0); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texFBO[0]); GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGBA, width, height, 0, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, null); GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE); GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE); GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST); GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_NEAREST); //int hFBO; GLES20.glGenFramebuffers(1, FBO, 0); GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, FBO[0]); GLES20.glFramebufferTexture2D(GLES20.GL_FRAMEBUFFER, GLES20.GL_COLOR_ATTACHMENT0, GLES20.GL_TEXTURE_2D, texFBO[0], 0); Log.d(LOGTAG, "initFBO error status: " + GLES20.glGetError()); int FBOstatus = GLES20.glCheckFramebufferStatus(GLES20.GL_FRAMEBUFFER); if (FBOstatus != GLES20.GL_FRAMEBUFFER_COMPLETE) Log.e(LOGTAG, "initFBO failed, status: " + FBOstatus); mFBOWidth = width; mFBOHeight = height; } // draw texture to FBO or to screen if fbo == 0 private void drawTex(int tex, boolean isOES, int fbo) { GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, fbo); if(fbo == 0) GLES20.glViewport(0, 0, mView.getWidth(), mView.getHeight()); else GLES20.glViewport(0, 0, mFBOWidth, mFBOHeight); GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT); if(isOES) { GLES20.glUseProgram(progOES); GLES20.glVertexAttribPointer(vPosOES, 2, GLES20.GL_FLOAT, false, 4*2, vert); GLES20.glVertexAttribPointer(vTCOES, 2, GLES20.GL_FLOAT, false, 4*2, texOES); } else { GLES20.glUseProgram(prog2D); GLES20.glVertexAttribPointer(vPos2D, 2, GLES20.GL_FLOAT, false, 4*2, vert); GLES20.glVertexAttribPointer(vTC2D, 2, GLES20.GL_FLOAT, false, 4*2, tex2D); } GLES20.glActiveTexture(GLES20.GL_TEXTURE0); if(isOES) { GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, tex); GLES20.glUniform1i(GLES20.glGetUniformLocation(progOES, "sTexture"), 0); } else { GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, tex); GLES20.glUniform1i(GLES20.glGetUniformLocation(prog2D, "sTexture"), 0); } GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4); GLES20.glFlush(); } public synchronized void enableView() { Log.d(LOGTAG, "enableView"); mEnabled = true; updateState(); } public synchronized void disableView() { Log.d(LOGTAG, "disableView"); mEnabled = false; updateState(); } protected void updateState() { Log.d(LOGTAG, "updateState"); Log.d(LOGTAG, "mEnabled="+mEnabled+", mHaveSurface="+mHaveSurface); boolean willStart = mEnabled && mHaveSurface && mView.getVisibility() == View.VISIBLE; if (willStart != mIsStarted) { if(willStart) doStart(); else doStop(); } else { Log.d(LOGTAG, "keeping State unchanged"); } Log.d(LOGTAG, "updateState end"); } protected synchronized void doStart() { Log.d(LOGTAG, "doStart"); initSurfaceTexture(); openCamera(mCameraIndex); mIsStarted = true; if(mCameraWidth>0 && mCameraHeight>0) setPreviewSize(mCameraWidth, mCameraHeight); // start preview and call listener.onCameraViewStarted() } protected void doStop() { Log.d(LOGTAG, "doStop"); synchronized(this) { mUpdateST = false; mIsStarted = false; mHaveFBO = false; closeCamera(); deleteSurfaceTexture(); } CameraTextureListener listener = mView.getCameraTextureListener(); if(listener != null) listener.onCameraViewStopped(); } protected void setPreviewSize(int width, int height) { synchronized(this) { mHaveFBO = false; mCameraWidth = width; mCameraHeight = height; setCameraPreviewSize(width, height); // can change mCameraWidth & mCameraHeight initFBO(mCameraWidth, mCameraHeight); mHaveFBO = true; } CameraTextureListener listener = mView.getCameraTextureListener(); if(listener != null) listener.onCameraViewStarted(mCameraWidth, mCameraHeight); } public void setCameraIndex(int cameraIndex) { disableView(); mCameraIndex = cameraIndex; enableView(); } public void setMaxCameraPreviewSize(int maxWidth, int maxHeight) { disableView(); mMaxCameraWidth = maxWidth; mMaxCameraHeight = maxHeight; enableView(); } public void onResume() { Log.i(LOGTAG, "onResume"); } public void onPause() { Log.i(LOGTAG, "onPause"); mHaveSurface = false; updateState(); mCameraWidth = mCameraHeight = -1; } }
16,179
35.689342
134
java
self
self-master/lib/opencv/android/sdk/java/src/org/opencv/android/FpsMeter.java
package org.opencv.android; import java.text.DecimalFormat; import org.opencv.core.Core; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.Log; public class FpsMeter { private static final String TAG = "FpsMeter"; private static final int STEP = 20; private static final DecimalFormat FPS_FORMAT = new DecimalFormat("0.00"); private int mFramesCouner; private double mFrequency; private long mprevFrameTime; private String mStrfps; Paint mPaint; boolean mIsInitialized = false; int mWidth = 0; int mHeight = 0; public void init() { mFramesCouner = 0; mFrequency = Core.getTickFrequency(); mprevFrameTime = Core.getTickCount(); mStrfps = ""; mPaint = new Paint(); mPaint.setColor(Color.BLUE); mPaint.setTextSize(20); } public void measure() { if (!mIsInitialized) { init(); mIsInitialized = true; } else { mFramesCouner++; if (mFramesCouner % STEP == 0) { long time = Core.getTickCount(); double fps = STEP * mFrequency / (time - mprevFrameTime); mprevFrameTime = time; if (mWidth != 0 && mHeight != 0) mStrfps = FPS_FORMAT.format(fps) + " FPS@" + Integer.valueOf(mWidth) + "x" + Integer.valueOf(mHeight); else mStrfps = FPS_FORMAT.format(fps) + " FPS"; Log.i(TAG, mStrfps); } } } public void setResolution(int width, int height) { mWidth = width; mHeight = height; } public void draw(Canvas canvas, float offsetx, float offsety) { Log.d(TAG, mStrfps); canvas.drawText(mStrfps, offsetx, offsety, mPaint); } }
2,044
29.522388
122
java
self
self-master/lib/opencv/android/sdk/java/src/org/opencv/android/LoaderCallbackInterface.java
package org.opencv.android; /** * Interface for callback object in case of asynchronous initialization of OpenCV. */ public interface LoaderCallbackInterface { /** * OpenCV initialization finished successfully. */ static final int SUCCESS = 0; /** * Google Play Market cannot be invoked. */ static final int MARKET_ERROR = 2; /** * OpenCV library installation has been canceled by the user. */ static final int INSTALL_CANCELED = 3; /** * This version of OpenCV Manager Service is incompatible with the app. Possibly, a service update is required. */ static final int INCOMPATIBLE_MANAGER_VERSION = 4; /** * OpenCV library initialization has failed. */ static final int INIT_FAILED = 0xff; /** * Callback method, called after OpenCV library initialization. * @param status status of initialization (see initialization status constants). */ public void onManagerConnected(int status); /** * Callback method, called in case the package installation is needed. * @param callback answer object with approve and cancel methods and the package description. */ public void onPackageInstall(final int operation, InstallCallbackInterface callback); };
1,284
30.341463
115
java
self
self-master/lib/opencv/android/sdk/java/src/org/opencv/android/Camera2Renderer.java
package org.opencv.android; import java.util.Arrays; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import android.annotation.TargetApi; import android.content.Context; import android.graphics.SurfaceTexture; import android.hardware.camera2.CameraAccessException; import android.hardware.camera2.CameraCaptureSession; import android.hardware.camera2.CameraCharacteristics; import android.hardware.camera2.CameraDevice; import android.hardware.camera2.CameraManager; import android.hardware.camera2.CaptureRequest; import android.hardware.camera2.params.StreamConfigurationMap; import android.os.Handler; import android.os.HandlerThread; import android.util.Log; import android.util.Size; import android.view.Surface; @TargetApi(21) public class Camera2Renderer extends CameraGLRendererBase { protected final String LOGTAG = "Camera2Renderer"; private CameraDevice mCameraDevice; private CameraCaptureSession mCaptureSession; private CaptureRequest.Builder mPreviewRequestBuilder; private String mCameraID; private Size mPreviewSize = new Size(-1, -1); private HandlerThread mBackgroundThread; private Handler mBackgroundHandler; private Semaphore mCameraOpenCloseLock = new Semaphore(1); Camera2Renderer(CameraGLSurfaceView view) { super(view); } @Override protected void doStart() { Log.d(LOGTAG, "doStart"); startBackgroundThread(); super.doStart(); } @Override protected void doStop() { Log.d(LOGTAG, "doStop"); super.doStop(); stopBackgroundThread(); } boolean cacPreviewSize(final int width, final int height) { Log.i(LOGTAG, "cacPreviewSize: "+width+"x"+height); if(mCameraID == null) { Log.e(LOGTAG, "Camera isn't initialized!"); return false; } CameraManager manager = (CameraManager) mView.getContext() .getSystemService(Context.CAMERA_SERVICE); try { CameraCharacteristics characteristics = manager .getCameraCharacteristics(mCameraID); StreamConfigurationMap map = characteristics .get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP); int bestWidth = 0, bestHeight = 0; float aspect = (float)width / height; for (Size psize : map.getOutputSizes(SurfaceTexture.class)) { int w = psize.getWidth(), h = psize.getHeight(); Log.d(LOGTAG, "trying size: "+w+"x"+h); if ( width >= w && height >= h && bestWidth <= w && bestHeight <= h && Math.abs(aspect - (float)w/h) < 0.2 ) { bestWidth = w; bestHeight = h; } } Log.i(LOGTAG, "best size: "+bestWidth+"x"+bestHeight); if( bestWidth == 0 || bestHeight == 0 || mPreviewSize.getWidth() == bestWidth && mPreviewSize.getHeight() == bestHeight ) return false; else { mPreviewSize = new Size(bestWidth, bestHeight); return true; } } catch (CameraAccessException e) { Log.e(LOGTAG, "cacPreviewSize - Camera Access Exception"); } catch (IllegalArgumentException e) { Log.e(LOGTAG, "cacPreviewSize - Illegal Argument Exception"); } catch (SecurityException e) { Log.e(LOGTAG, "cacPreviewSize - Security Exception"); } return false; } @Override protected void openCamera(int id) { Log.i(LOGTAG, "openCamera"); CameraManager manager = (CameraManager) mView.getContext().getSystemService(Context.CAMERA_SERVICE); try { String camList[] = manager.getCameraIdList(); if(camList.length == 0) { Log.e(LOGTAG, "Error: camera isn't detected."); return; } if(id == CameraBridgeViewBase.CAMERA_ID_ANY) { mCameraID = camList[0]; } else { for (String cameraID : camList) { CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraID); if( id == CameraBridgeViewBase.CAMERA_ID_BACK && characteristics.get(CameraCharacteristics.LENS_FACING) == CameraCharacteristics.LENS_FACING_BACK || id == CameraBridgeViewBase.CAMERA_ID_FRONT && characteristics.get(CameraCharacteristics.LENS_FACING) == CameraCharacteristics.LENS_FACING_FRONT) { mCameraID = cameraID; break; } } } if(mCameraID != null) { if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) { throw new RuntimeException( "Time out waiting to lock camera opening."); } Log.i(LOGTAG, "Opening camera: " + mCameraID); manager.openCamera(mCameraID, mStateCallback, mBackgroundHandler); } } catch (CameraAccessException e) { Log.e(LOGTAG, "OpenCamera - Camera Access Exception"); } catch (IllegalArgumentException e) { Log.e(LOGTAG, "OpenCamera - Illegal Argument Exception"); } catch (SecurityException e) { Log.e(LOGTAG, "OpenCamera - Security Exception"); } catch (InterruptedException e) { Log.e(LOGTAG, "OpenCamera - Interrupted Exception"); } } @Override protected void closeCamera() { Log.i(LOGTAG, "closeCamera"); try { mCameraOpenCloseLock.acquire(); if (null != mCaptureSession) { mCaptureSession.close(); mCaptureSession = null; } if (null != mCameraDevice) { mCameraDevice.close(); mCameraDevice = null; } } catch (InterruptedException e) { throw new RuntimeException("Interrupted while trying to lock camera closing.", e); } finally { mCameraOpenCloseLock.release(); } } private final CameraDevice.StateCallback mStateCallback = new CameraDevice.StateCallback() { @Override public void onOpened(CameraDevice cameraDevice) { mCameraDevice = cameraDevice; mCameraOpenCloseLock.release(); createCameraPreviewSession(); } @Override public void onDisconnected(CameraDevice cameraDevice) { cameraDevice.close(); mCameraDevice = null; mCameraOpenCloseLock.release(); } @Override public void onError(CameraDevice cameraDevice, int error) { cameraDevice.close(); mCameraDevice = null; mCameraOpenCloseLock.release(); } }; private void createCameraPreviewSession() { int w=mPreviewSize.getWidth(), h=mPreviewSize.getHeight(); Log.i(LOGTAG, "createCameraPreviewSession("+w+"x"+h+")"); if(w<0 || h<0) return; try { mCameraOpenCloseLock.acquire(); if (null == mCameraDevice) { mCameraOpenCloseLock.release(); Log.e(LOGTAG, "createCameraPreviewSession: camera isn't opened"); return; } if (null != mCaptureSession) { mCameraOpenCloseLock.release(); Log.e(LOGTAG, "createCameraPreviewSession: mCaptureSession is already started"); return; } if(null == mSTexture) { mCameraOpenCloseLock.release(); Log.e(LOGTAG, "createCameraPreviewSession: preview SurfaceTexture is null"); return; } mSTexture.setDefaultBufferSize(w, h); Surface surface = new Surface(mSTexture); mPreviewRequestBuilder = mCameraDevice .createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW); mPreviewRequestBuilder.addTarget(surface); mCameraDevice.createCaptureSession(Arrays.asList(surface), new CameraCaptureSession.StateCallback() { @Override public void onConfigured( CameraCaptureSession cameraCaptureSession) { mCaptureSession = cameraCaptureSession; try { mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE); mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH); mCaptureSession.setRepeatingRequest(mPreviewRequestBuilder.build(), null, mBackgroundHandler); Log.i(LOGTAG, "CameraPreviewSession has been started"); } catch (CameraAccessException e) { Log.e(LOGTAG, "createCaptureSession failed"); } mCameraOpenCloseLock.release(); } @Override public void onConfigureFailed( CameraCaptureSession cameraCaptureSession) { Log.e(LOGTAG, "createCameraPreviewSession failed"); mCameraOpenCloseLock.release(); } }, mBackgroundHandler); } catch (CameraAccessException e) { Log.e(LOGTAG, "createCameraPreviewSession"); } catch (InterruptedException e) { throw new RuntimeException( "Interrupted while createCameraPreviewSession", e); } finally { //mCameraOpenCloseLock.release(); } } private void startBackgroundThread() { Log.i(LOGTAG, "startBackgroundThread"); stopBackgroundThread(); mBackgroundThread = new HandlerThread("CameraBackground"); mBackgroundThread.start(); mBackgroundHandler = new Handler(mBackgroundThread.getLooper()); } private void stopBackgroundThread() { Log.i(LOGTAG, "stopBackgroundThread"); if(mBackgroundThread == null) return; mBackgroundThread.quitSafely(); try { mBackgroundThread.join(); mBackgroundThread = null; mBackgroundHandler = null; } catch (InterruptedException e) { Log.e(LOGTAG, "stopBackgroundThread"); } } @Override protected void setCameraPreviewSize(int width, int height) { Log.i(LOGTAG, "setCameraPreviewSize("+width+"x"+height+")"); if(mMaxCameraWidth > 0 && mMaxCameraWidth < width) width = mMaxCameraWidth; if(mMaxCameraHeight > 0 && mMaxCameraHeight < height) height = mMaxCameraHeight; try { mCameraOpenCloseLock.acquire(); boolean needReconfig = cacPreviewSize(width, height); mCameraWidth = mPreviewSize.getWidth(); mCameraHeight = mPreviewSize.getHeight(); if( !needReconfig ) { mCameraOpenCloseLock.release(); return; } if (null != mCaptureSession) { Log.d(LOGTAG, "closing existing previewSession"); mCaptureSession.close(); mCaptureSession = null; } mCameraOpenCloseLock.release(); createCameraPreviewSession(); } catch (InterruptedException e) { mCameraOpenCloseLock.release(); throw new RuntimeException("Interrupted while setCameraPreviewSize.", e); } } }
12,001
38.610561
142
java
self
self-master/lib/opencv/android/sdk/java/src/org/opencv/android/StaticHelper.java
package org.opencv.android; import org.opencv.core.Core; import java.util.StringTokenizer; import android.util.Log; class StaticHelper { public static boolean initOpenCV(boolean InitCuda) { boolean result; String libs = ""; if(InitCuda) { loadLibrary("cudart"); loadLibrary("nppc"); loadLibrary("nppi"); loadLibrary("npps"); loadLibrary("cufft"); loadLibrary("cublas"); } Log.d(TAG, "Trying to get library list"); try { System.loadLibrary("opencv_info"); libs = getLibraryList(); } catch(UnsatisfiedLinkError e) { Log.e(TAG, "OpenCV error: Cannot load info library for OpenCV"); } Log.d(TAG, "Library list: \"" + libs + "\""); Log.d(TAG, "First attempt to load libs"); if (initOpenCVLibs(libs)) { Log.d(TAG, "First attempt to load libs is OK"); String eol = System.getProperty("line.separator"); for (String str : Core.getBuildInformation().split(eol)) Log.i(TAG, str); result = true; } else { Log.d(TAG, "First attempt to load libs fails"); result = false; } return result; } private static boolean loadLibrary(String Name) { boolean result = true; Log.d(TAG, "Trying to load library " + Name); try { System.loadLibrary(Name); Log.d(TAG, "Library " + Name + " loaded"); } catch(UnsatisfiedLinkError e) { Log.d(TAG, "Cannot load library \"" + Name + "\""); e.printStackTrace(); result &= false; } return result; } private static boolean initOpenCVLibs(String Libs) { Log.d(TAG, "Trying to init OpenCV libs"); boolean result = true; if ((null != Libs) && (Libs.length() != 0)) { Log.d(TAG, "Trying to load libs by dependency list"); StringTokenizer splitter = new StringTokenizer(Libs, ";"); while(splitter.hasMoreTokens()) { result &= loadLibrary(splitter.nextToken()); } } else { // If dependencies list is not defined or empty. result &= loadLibrary("opencv_java3"); } return result; } private static final String TAG = "OpenCV/StaticHelper"; private static native String getLibraryList(); }
2,625
24.009524
76
java
self
self-master/lib/opencv/android/sdk/java/src/org/opencv/android/InstallCallbackInterface.java
package org.opencv.android; /** * Installation callback interface. */ public interface InstallCallbackInterface { /** * New package installation is required. */ static final int NEW_INSTALLATION = 0; /** * Current package installation is in progress. */ static final int INSTALLATION_PROGRESS = 1; /** * Target package name. * @return Return target package name. */ public String getPackageName(); /** * Installation is approved. */ public void install(); /** * Installation is canceled. */ public void cancel(); /** * Wait for package installation. */ public void wait_install(); };
701
19.057143
51
java
self
self-master/lib/opencv/android/sdk/java/src/org/opencv/android/BaseLoaderCallback.java
package org.opencv.android; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.util.Log; /** * Basic implementation of LoaderCallbackInterface. */ public abstract class BaseLoaderCallback implements LoaderCallbackInterface { public BaseLoaderCallback(Context AppContext) { mAppContext = AppContext; } public void onManagerConnected(int status) { switch (status) { /** OpenCV initialization was successful. **/ case LoaderCallbackInterface.SUCCESS: { /** Application must override this method to handle successful library initialization. **/ } break; /** OpenCV loader can not start Google Play Market. **/ case LoaderCallbackInterface.MARKET_ERROR: { Log.e(TAG, "Package installation failed!"); AlertDialog MarketErrorMessage = new AlertDialog.Builder(mAppContext).create(); MarketErrorMessage.setTitle("OpenCV Manager"); MarketErrorMessage.setMessage("Package installation failed!"); MarketErrorMessage.setCancelable(false); // This blocks the 'BACK' button MarketErrorMessage.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }); MarketErrorMessage.show(); } break; /** Package installation has been canceled. **/ case LoaderCallbackInterface.INSTALL_CANCELED: { Log.d(TAG, "OpenCV library instalation was canceled by user"); finish(); } break; /** Application is incompatible with this version of OpenCV Manager. Possibly, a service update is required. **/ case LoaderCallbackInterface.INCOMPATIBLE_MANAGER_VERSION: { Log.d(TAG, "OpenCV Manager Service is uncompatible with this app!"); AlertDialog IncomatibilityMessage = new AlertDialog.Builder(mAppContext).create(); IncomatibilityMessage.setTitle("OpenCV Manager"); IncomatibilityMessage.setMessage("OpenCV Manager service is incompatible with this app. Try to update it via Google Play."); IncomatibilityMessage.setCancelable(false); // This blocks the 'BACK' button IncomatibilityMessage.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }); IncomatibilityMessage.show(); } break; /** Other status, i.e. INIT_FAILED. **/ default: { Log.e(TAG, "OpenCV loading failed!"); AlertDialog InitFailedDialog = new AlertDialog.Builder(mAppContext).create(); InitFailedDialog.setTitle("OpenCV error"); InitFailedDialog.setMessage("OpenCV was not initialised correctly. Application will be shut down"); InitFailedDialog.setCancelable(false); // This blocks the 'BACK' button InitFailedDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }); InitFailedDialog.show(); } break; } } public void onPackageInstall(final int operation, final InstallCallbackInterface callback) { switch (operation) { case InstallCallbackInterface.NEW_INSTALLATION: { AlertDialog InstallMessage = new AlertDialog.Builder(mAppContext).create(); InstallMessage.setTitle("Package not found"); InstallMessage.setMessage(callback.getPackageName() + " package was not found! Try to install it?"); InstallMessage.setCancelable(false); // This blocks the 'BACK' button InstallMessage.setButton(AlertDialog.BUTTON_POSITIVE, "Yes", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { callback.install(); } }); InstallMessage.setButton(AlertDialog.BUTTON_NEGATIVE, "No", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { callback.cancel(); } }); InstallMessage.show(); } break; case InstallCallbackInterface.INSTALLATION_PROGRESS: { AlertDialog WaitMessage = new AlertDialog.Builder(mAppContext).create(); WaitMessage.setTitle("OpenCV is not ready"); WaitMessage.setMessage("Installation is in progress. Wait or exit?"); WaitMessage.setCancelable(false); // This blocks the 'BACK' button WaitMessage.setButton(AlertDialog.BUTTON_POSITIVE, "Wait", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { callback.wait_install(); } }); WaitMessage.setButton(AlertDialog.BUTTON_NEGATIVE, "Exit", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { callback.cancel(); } }); WaitMessage.show(); } break; } } void finish() { ((Activity) mAppContext).finish(); } protected Context mAppContext; private final static String TAG = "OpenCVLoader/BaseLoaderCallback"; }
6,172
42.471831
140
java
self
self-master/lib/opencv/android/sdk/java/src/org/opencv/android/CameraBridgeViewBase.java
package org.opencv.android; import java.util.List; import org.opencv.R; import org.opencv.core.Mat; import org.opencv.core.Size; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Rect; import android.util.AttributeSet; import android.util.Log; import android.view.SurfaceHolder; import android.view.SurfaceView; /** * This is a basic class, implementing the interaction with Camera and OpenCV library. * The main responsibility of it - is to control when camera can be enabled, process the frame, * call external listener to make any adjustments to the frame and then draw the resulting * frame to the screen. * The clients shall implement CvCameraViewListener. */ public abstract class CameraBridgeViewBase extends SurfaceView implements SurfaceHolder.Callback { private static final String TAG = "CameraBridge"; private static final int MAX_UNSPECIFIED = -1; private static final int STOPPED = 0; private static final int STARTED = 1; private int mState = STOPPED; private Bitmap mCacheBitmap; private CvCameraViewListener2 mListener; private boolean mSurfaceExist; private Object mSyncObject = new Object(); protected int mFrameWidth; protected int mFrameHeight; protected int mMaxHeight; protected int mMaxWidth; protected float mScale = 0; protected int mPreviewFormat = RGBA; protected int mCameraIndex = CAMERA_ID_ANY; protected boolean mEnabled; protected FpsMeter mFpsMeter = null; public static final int CAMERA_ID_ANY = -1; public static final int CAMERA_ID_BACK = 99; public static final int CAMERA_ID_FRONT = 98; public static final int RGBA = 1; public static final int GRAY = 2; public CameraBridgeViewBase(Context context, int cameraId) { super(context); mCameraIndex = cameraId; getHolder().addCallback(this); mMaxWidth = MAX_UNSPECIFIED; mMaxHeight = MAX_UNSPECIFIED; } public CameraBridgeViewBase(Context context, AttributeSet attrs) { super(context, attrs); int count = attrs.getAttributeCount(); Log.d(TAG, "Attr count: " + Integer.valueOf(count)); TypedArray styledAttrs = getContext().obtainStyledAttributes(attrs, R.styleable.CameraBridgeViewBase); if (styledAttrs.getBoolean(R.styleable.CameraBridgeViewBase_show_fps, false)) enableFpsMeter(); mCameraIndex = styledAttrs.getInt(R.styleable.CameraBridgeViewBase_camera_id, -1); getHolder().addCallback(this); mMaxWidth = MAX_UNSPECIFIED; mMaxHeight = MAX_UNSPECIFIED; styledAttrs.recycle(); } /** * Sets the camera index * @param cameraIndex new camera index */ public void setCameraIndex(int cameraIndex) { this.mCameraIndex = cameraIndex; } public interface CvCameraViewListener { /** * This method is invoked when camera preview has started. After this method is invoked * the frames will start to be delivered to client via the onCameraFrame() callback. * @param width - the width of the frames that will be delivered * @param height - the height of the frames that will be delivered */ public void onCameraViewStarted(int width, int height); /** * This method is invoked when camera preview has been stopped for some reason. * No frames will be delivered via onCameraFrame() callback after this method is called. */ public void onCameraViewStopped(); /** * This method is invoked when delivery of the frame needs to be done. * The returned values - is a modified frame which needs to be displayed on the screen. * TODO: pass the parameters specifying the format of the frame (BPP, YUV or RGB and etc) */ public Mat onCameraFrame(Mat inputFrame); } public interface CvCameraViewListener2 { /** * This method is invoked when camera preview has started. After this method is invoked * the frames will start to be delivered to client via the onCameraFrame() callback. * @param width - the width of the frames that will be delivered * @param height - the height of the frames that will be delivered */ public void onCameraViewStarted(int width, int height); /** * This method is invoked when camera preview has been stopped for some reason. * No frames will be delivered via onCameraFrame() callback after this method is called. */ public void onCameraViewStopped(); /** * This method is invoked when delivery of the frame needs to be done. * The returned values - is a modified frame which needs to be displayed on the screen. * TODO: pass the parameters specifying the format of the frame (BPP, YUV or RGB and etc) */ public Mat onCameraFrame(CvCameraViewFrame inputFrame); }; protected class CvCameraViewListenerAdapter implements CvCameraViewListener2 { public CvCameraViewListenerAdapter(CvCameraViewListener oldStypeListener) { mOldStyleListener = oldStypeListener; } public void onCameraViewStarted(int width, int height) { mOldStyleListener.onCameraViewStarted(width, height); } public void onCameraViewStopped() { mOldStyleListener.onCameraViewStopped(); } public Mat onCameraFrame(CvCameraViewFrame inputFrame) { Mat result = null; switch (mPreviewFormat) { case RGBA: result = mOldStyleListener.onCameraFrame(inputFrame.rgba()); break; case GRAY: result = mOldStyleListener.onCameraFrame(inputFrame.gray()); break; default: Log.e(TAG, "Invalid frame format! Only RGBA and Gray Scale are supported!"); }; return result; } public void setFrameFormat(int format) { mPreviewFormat = format; } private int mPreviewFormat = RGBA; private CvCameraViewListener mOldStyleListener; }; /** * This class interface is abstract representation of single frame from camera for onCameraFrame callback * Attention: Do not use objects, that represents this interface out of onCameraFrame callback! */ public interface CvCameraViewFrame { /** * This method returns RGBA Mat with frame */ public Mat rgba(); /** * This method returns single channel gray scale Mat with frame */ public Mat gray(); }; public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) { Log.d(TAG, "call surfaceChanged event"); synchronized(mSyncObject) { if (!mSurfaceExist) { mSurfaceExist = true; checkCurrentState(); } else { /** Surface changed. We need to stop camera and restart with new parameters */ /* Pretend that old surface has been destroyed */ mSurfaceExist = false; checkCurrentState(); /* Now use new surface. Say we have it now */ mSurfaceExist = true; checkCurrentState(); } } } public void surfaceCreated(SurfaceHolder holder) { /* Do nothing. Wait until surfaceChanged delivered */ } public void surfaceDestroyed(SurfaceHolder holder) { synchronized(mSyncObject) { mSurfaceExist = false; checkCurrentState(); } } /** * This method is provided for clients, so they can enable the camera connection. * The actual onCameraViewStarted callback will be delivered only after both this method is called and surface is available */ public void enableView() { synchronized(mSyncObject) { mEnabled = true; checkCurrentState(); } } /** * This method is provided for clients, so they can disable camera connection and stop * the delivery of frames even though the surface view itself is not destroyed and still stays on the scren */ public void disableView() { synchronized(mSyncObject) { mEnabled = false; checkCurrentState(); } } /** * This method enables label with fps value on the screen */ public void enableFpsMeter() { if (mFpsMeter == null) { mFpsMeter = new FpsMeter(); mFpsMeter.setResolution(mFrameWidth, mFrameHeight); } } public void disableFpsMeter() { mFpsMeter = null; } /** * * @param listener */ public void setCvCameraViewListener(CvCameraViewListener2 listener) { mListener = listener; } public void setCvCameraViewListener(CvCameraViewListener listener) { CvCameraViewListenerAdapter adapter = new CvCameraViewListenerAdapter(listener); adapter.setFrameFormat(mPreviewFormat); mListener = adapter; } /** * This method sets the maximum size that camera frame is allowed to be. When selecting * size - the biggest size which less or equal the size set will be selected. * As an example - we set setMaxFrameSize(200,200) and we have 176x152 and 320x240 sizes. The * preview frame will be selected with 176x152 size. * This method is useful when need to restrict the size of preview frame for some reason (for example for video recording) * @param maxWidth - the maximum width allowed for camera frame. * @param maxHeight - the maximum height allowed for camera frame */ public void setMaxFrameSize(int maxWidth, int maxHeight) { mMaxWidth = maxWidth; mMaxHeight = maxHeight; } public void SetCaptureFormat(int format) { mPreviewFormat = format; if (mListener instanceof CvCameraViewListenerAdapter) { CvCameraViewListenerAdapter adapter = (CvCameraViewListenerAdapter) mListener; adapter.setFrameFormat(mPreviewFormat); } } /** * Called when mSyncObject lock is held */ private void checkCurrentState() { Log.d(TAG, "call checkCurrentState"); int targetState; if (mEnabled && mSurfaceExist && getVisibility() == VISIBLE) { targetState = STARTED; } else { targetState = STOPPED; } if (targetState != mState) { /* The state change detected. Need to exit the current state and enter target state */ processExitState(mState); mState = targetState; processEnterState(mState); } } private void processEnterState(int state) { Log.d(TAG, "call processEnterState: " + state); switch(state) { case STARTED: onEnterStartedState(); if (mListener != null) { mListener.onCameraViewStarted(mFrameWidth, mFrameHeight); } break; case STOPPED: onEnterStoppedState(); if (mListener != null) { mListener.onCameraViewStopped(); } break; }; } private void processExitState(int state) { Log.d(TAG, "call processExitState: " + state); switch(state) { case STARTED: onExitStartedState(); break; case STOPPED: onExitStoppedState(); break; }; } private void onEnterStoppedState() { /* nothing to do */ } private void onExitStoppedState() { /* nothing to do */ } // NOTE: The order of bitmap constructor and camera connection is important for android 4.1.x // Bitmap must be constructed before surface private void onEnterStartedState() { Log.d(TAG, "call onEnterStartedState"); /* Connect camera */ if (!connectCamera(getWidth(), getHeight())) { AlertDialog ad = new AlertDialog.Builder(getContext()).create(); ad.setCancelable(false); // This blocks the 'BACK' button ad.setMessage("It seems that you device does not support camera (or it is locked). Application will be closed."); ad.setButton(DialogInterface.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); ((Activity) getContext()).finish(); } }); ad.show(); } } private void onExitStartedState() { disconnectCamera(); if (mCacheBitmap != null) { mCacheBitmap.recycle(); } } /** * This method shall be called by the subclasses when they have valid * object and want it to be delivered to external client (via callback) and * then displayed on the screen. * @param frame - the current frame to be delivered */ protected void deliverAndDrawFrame(CvCameraViewFrame frame) { Mat modified; if (mListener != null) { modified = mListener.onCameraFrame(frame); } else { modified = frame.rgba(); } boolean bmpValid = true; if (modified != null) { try { Utils.matToBitmap(modified, mCacheBitmap); } catch(Exception e) { Log.e(TAG, "Mat type: " + modified); Log.e(TAG, "Bitmap type: " + mCacheBitmap.getWidth() + "*" + mCacheBitmap.getHeight()); Log.e(TAG, "Utils.matToBitmap() throws an exception: " + e.getMessage()); bmpValid = false; } } if (bmpValid && mCacheBitmap != null) { Canvas canvas = getHolder().lockCanvas(); if (canvas != null) { canvas.drawColor(0, android.graphics.PorterDuff.Mode.CLEAR); Log.d(TAG, "mStretch value: " + mScale); if (mScale != 0) { canvas.drawBitmap(mCacheBitmap, new Rect(0,0,mCacheBitmap.getWidth(), mCacheBitmap.getHeight()), new Rect((int)((canvas.getWidth() - mScale*mCacheBitmap.getWidth()) / 2), (int)((canvas.getHeight() - mScale*mCacheBitmap.getHeight()) / 2), (int)((canvas.getWidth() - mScale*mCacheBitmap.getWidth()) / 2 + mScale*mCacheBitmap.getWidth()), (int)((canvas.getHeight() - mScale*mCacheBitmap.getHeight()) / 2 + mScale*mCacheBitmap.getHeight())), null); } else { canvas.drawBitmap(mCacheBitmap, new Rect(0,0,mCacheBitmap.getWidth(), mCacheBitmap.getHeight()), new Rect((canvas.getWidth() - mCacheBitmap.getWidth()) / 2, (canvas.getHeight() - mCacheBitmap.getHeight()) / 2, (canvas.getWidth() - mCacheBitmap.getWidth()) / 2 + mCacheBitmap.getWidth(), (canvas.getHeight() - mCacheBitmap.getHeight()) / 2 + mCacheBitmap.getHeight()), null); } if (mFpsMeter != null) { mFpsMeter.measure(); mFpsMeter.draw(canvas, 20, 30); } getHolder().unlockCanvasAndPost(canvas); } } } /** * This method is invoked shall perform concrete operation to initialize the camera. * CONTRACT: as a result of this method variables mFrameWidth and mFrameHeight MUST be * initialized with the size of the Camera frames that will be delivered to external processor. * @param width - the width of this SurfaceView * @param height - the height of this SurfaceView */ protected abstract boolean connectCamera(int width, int height); /** * Disconnects and release the particular camera object being connected to this surface view. * Called when syncObject lock is held */ protected abstract void disconnectCamera(); // NOTE: On Android 4.1.x the function must be called before SurfaceTexture constructor! protected void AllocateCache() { mCacheBitmap = Bitmap.createBitmap(mFrameWidth, mFrameHeight, Bitmap.Config.ARGB_8888); } public interface ListItemAccessor { public int getWidth(Object obj); public int getHeight(Object obj); }; /** * This helper method can be called by subclasses to select camera preview size. * It goes over the list of the supported preview sizes and selects the maximum one which * fits both values set via setMaxFrameSize() and surface frame allocated for this view * @param supportedSizes * @param surfaceWidth * @param surfaceHeight * @return optimal frame size */ protected Size calculateCameraFrameSize(List<?> supportedSizes, ListItemAccessor accessor, int surfaceWidth, int surfaceHeight) { int calcWidth = 0; int calcHeight = 0; int maxAllowedWidth = (mMaxWidth != MAX_UNSPECIFIED && mMaxWidth < surfaceWidth)? mMaxWidth : surfaceWidth; int maxAllowedHeight = (mMaxHeight != MAX_UNSPECIFIED && mMaxHeight < surfaceHeight)? mMaxHeight : surfaceHeight; for (Object size : supportedSizes) { int width = accessor.getWidth(size); int height = accessor.getHeight(size); if (width <= maxAllowedWidth && height <= maxAllowedHeight) { if (width >= calcWidth && height >= calcHeight) { calcWidth = (int) width; calcHeight = (int) height; } } } return new Size(calcWidth, calcHeight); } }
18,173
35.789474
133
java
self
self-master/lib/opencv/android/sdk/java/src/org/opencv/imgcodecs/Imgcodecs.java
// // This file is auto-generated. Please don't modify it! // package org.opencv.imgcodecs; import java.lang.String; import java.util.ArrayList; import java.util.List; import org.opencv.core.Mat; import org.opencv.core.MatOfByte; import org.opencv.core.MatOfInt; import org.opencv.utils.Converters; public class Imgcodecs { public static final int CV_LOAD_IMAGE_UNCHANGED = -1, CV_LOAD_IMAGE_GRAYSCALE = 0, CV_LOAD_IMAGE_COLOR = 1, CV_LOAD_IMAGE_ANYDEPTH = 2, CV_LOAD_IMAGE_ANYCOLOR = 4, CV_IMWRITE_JPEG_QUALITY = 1, CV_IMWRITE_JPEG_PROGRESSIVE = 2, CV_IMWRITE_JPEG_OPTIMIZE = 3, CV_IMWRITE_JPEG_RST_INTERVAL = 4, CV_IMWRITE_JPEG_LUMA_QUALITY = 5, CV_IMWRITE_JPEG_CHROMA_QUALITY = 6, CV_IMWRITE_PNG_COMPRESSION = 16, CV_IMWRITE_PNG_STRATEGY = 17, CV_IMWRITE_PNG_BILEVEL = 18, CV_IMWRITE_PNG_STRATEGY_DEFAULT = 0, CV_IMWRITE_PNG_STRATEGY_FILTERED = 1, CV_IMWRITE_PNG_STRATEGY_HUFFMAN_ONLY = 2, CV_IMWRITE_PNG_STRATEGY_RLE = 3, CV_IMWRITE_PNG_STRATEGY_FIXED = 4, CV_IMWRITE_PXM_BINARY = 32, CV_IMWRITE_WEBP_QUALITY = 64, CV_CVTIMG_FLIP = 1, CV_CVTIMG_SWAP_RB = 2, IMREAD_UNCHANGED = -1, IMREAD_GRAYSCALE = 0, IMREAD_COLOR = 1, IMREAD_ANYDEPTH = 2, IMREAD_ANYCOLOR = 4, IMREAD_LOAD_GDAL = 8, IMREAD_REDUCED_GRAYSCALE_2 = 16, IMREAD_REDUCED_COLOR_2 = 17, IMREAD_REDUCED_GRAYSCALE_4 = 32, IMREAD_REDUCED_COLOR_4 = 33, IMREAD_REDUCED_GRAYSCALE_8 = 64, IMREAD_REDUCED_COLOR_8 = 65, IMWRITE_JPEG_QUALITY = 1, IMWRITE_JPEG_PROGRESSIVE = 2, IMWRITE_JPEG_OPTIMIZE = 3, IMWRITE_JPEG_RST_INTERVAL = 4, IMWRITE_JPEG_LUMA_QUALITY = 5, IMWRITE_JPEG_CHROMA_QUALITY = 6, IMWRITE_PNG_COMPRESSION = 16, IMWRITE_PNG_STRATEGY = 17, IMWRITE_PNG_BILEVEL = 18, IMWRITE_PXM_BINARY = 32, IMWRITE_WEBP_QUALITY = 64, IMWRITE_PNG_STRATEGY_DEFAULT = 0, IMWRITE_PNG_STRATEGY_FILTERED = 1, IMWRITE_PNG_STRATEGY_HUFFMAN_ONLY = 2, IMWRITE_PNG_STRATEGY_RLE = 3, IMWRITE_PNG_STRATEGY_FIXED = 4; // // C++: Mat imdecode(Mat buf, int flags) // //javadoc: imdecode(buf, flags) public static Mat imdecode(Mat buf, int flags) { Mat retVal = new Mat(imdecode_0(buf.nativeObj, flags)); return retVal; } // // C++: Mat imread(String filename, int flags = IMREAD_COLOR) // //javadoc: imread(filename, flags) public static Mat imread(String filename, int flags) { Mat retVal = new Mat(imread_0(filename, flags)); return retVal; } //javadoc: imread(filename) public static Mat imread(String filename) { Mat retVal = new Mat(imread_1(filename)); return retVal; } // // C++: bool imencode(String ext, Mat img, vector_uchar& buf, vector_int params = std::vector<int>()) // //javadoc: imencode(ext, img, buf, params) public static boolean imencode(String ext, Mat img, MatOfByte buf, MatOfInt params) { Mat buf_mat = buf; Mat params_mat = params; boolean retVal = imencode_0(ext, img.nativeObj, buf_mat.nativeObj, params_mat.nativeObj); return retVal; } //javadoc: imencode(ext, img, buf) public static boolean imencode(String ext, Mat img, MatOfByte buf) { Mat buf_mat = buf; boolean retVal = imencode_1(ext, img.nativeObj, buf_mat.nativeObj); return retVal; } // // C++: bool imreadmulti(String filename, vector_Mat mats, int flags = IMREAD_ANYCOLOR) // //javadoc: imreadmulti(filename, mats, flags) public static boolean imreadmulti(String filename, List<Mat> mats, int flags) { Mat mats_mat = Converters.vector_Mat_to_Mat(mats); boolean retVal = imreadmulti_0(filename, mats_mat.nativeObj, flags); return retVal; } //javadoc: imreadmulti(filename, mats) public static boolean imreadmulti(String filename, List<Mat> mats) { Mat mats_mat = Converters.vector_Mat_to_Mat(mats); boolean retVal = imreadmulti_1(filename, mats_mat.nativeObj); return retVal; } // // C++: bool imwrite(String filename, Mat img, vector_int params = std::vector<int>()) // //javadoc: imwrite(filename, img, params) public static boolean imwrite(String filename, Mat img, MatOfInt params) { Mat params_mat = params; boolean retVal = imwrite_0(filename, img.nativeObj, params_mat.nativeObj); return retVal; } //javadoc: imwrite(filename, img) public static boolean imwrite(String filename, Mat img) { boolean retVal = imwrite_1(filename, img.nativeObj); return retVal; } // C++: Mat imdecode(Mat buf, int flags) private static native long imdecode_0(long buf_nativeObj, int flags); // C++: Mat imread(String filename, int flags = IMREAD_COLOR) private static native long imread_0(String filename, int flags); private static native long imread_1(String filename); // C++: bool imencode(String ext, Mat img, vector_uchar& buf, vector_int params = std::vector<int>()) private static native boolean imencode_0(String ext, long img_nativeObj, long buf_mat_nativeObj, long params_mat_nativeObj); private static native boolean imencode_1(String ext, long img_nativeObj, long buf_mat_nativeObj); // C++: bool imreadmulti(String filename, vector_Mat mats, int flags = IMREAD_ANYCOLOR) private static native boolean imreadmulti_0(String filename, long mats_mat_nativeObj, int flags); private static native boolean imreadmulti_1(String filename, long mats_mat_nativeObj); // C++: bool imwrite(String filename, Mat img, vector_int params = std::vector<int>()) private static native boolean imwrite_0(String filename, long img_nativeObj, long params_mat_nativeObj); private static native boolean imwrite_1(String filename, long img_nativeObj); }
6,483
31.42
128
java
self
self-master/lib/opencv/android/sdk/java/src/org/opencv/utils/Converters.java
package org.opencv.utils; import java.util.ArrayList; import java.util.List; import org.opencv.core.CvType; import org.opencv.core.Mat; import org.opencv.core.MatOfByte; import org.opencv.core.MatOfDMatch; import org.opencv.core.MatOfKeyPoint; import org.opencv.core.MatOfPoint; import org.opencv.core.MatOfPoint2f; import org.opencv.core.MatOfPoint3f; import org.opencv.core.Point; import org.opencv.core.Point3; import org.opencv.core.Rect; import org.opencv.core.DMatch; import org.opencv.core.KeyPoint; public class Converters { public static Mat vector_Point_to_Mat(List<Point> pts) { return vector_Point_to_Mat(pts, CvType.CV_32S); } public static Mat vector_Point2f_to_Mat(List<Point> pts) { return vector_Point_to_Mat(pts, CvType.CV_32F); } public static Mat vector_Point2d_to_Mat(List<Point> pts) { return vector_Point_to_Mat(pts, CvType.CV_64F); } public static Mat vector_Point_to_Mat(List<Point> pts, int typeDepth) { Mat res; int count = (pts != null) ? pts.size() : 0; if (count > 0) { switch (typeDepth) { case CvType.CV_32S: { res = new Mat(count, 1, CvType.CV_32SC2); int[] buff = new int[count * 2]; for (int i = 0; i < count; i++) { Point p = pts.get(i); buff[i * 2] = (int) p.x; buff[i * 2 + 1] = (int) p.y; } res.put(0, 0, buff); } break; case CvType.CV_32F: { res = new Mat(count, 1, CvType.CV_32FC2); float[] buff = new float[count * 2]; for (int i = 0; i < count; i++) { Point p = pts.get(i); buff[i * 2] = (float) p.x; buff[i * 2 + 1] = (float) p.y; } res.put(0, 0, buff); } break; case CvType.CV_64F: { res = new Mat(count, 1, CvType.CV_64FC2); double[] buff = new double[count * 2]; for (int i = 0; i < count; i++) { Point p = pts.get(i); buff[i * 2] = p.x; buff[i * 2 + 1] = p.y; } res.put(0, 0, buff); } break; default: throw new IllegalArgumentException("'typeDepth' can be CV_32S, CV_32F or CV_64F"); } } else { res = new Mat(); } return res; } public static Mat vector_Point3i_to_Mat(List<Point3> pts) { return vector_Point3_to_Mat(pts, CvType.CV_32S); } public static Mat vector_Point3f_to_Mat(List<Point3> pts) { return vector_Point3_to_Mat(pts, CvType.CV_32F); } public static Mat vector_Point3d_to_Mat(List<Point3> pts) { return vector_Point3_to_Mat(pts, CvType.CV_64F); } public static Mat vector_Point3_to_Mat(List<Point3> pts, int typeDepth) { Mat res; int count = (pts != null) ? pts.size() : 0; if (count > 0) { switch (typeDepth) { case CvType.CV_32S: { res = new Mat(count, 1, CvType.CV_32SC3); int[] buff = new int[count * 3]; for (int i = 0; i < count; i++) { Point3 p = pts.get(i); buff[i * 3] = (int) p.x; buff[i * 3 + 1] = (int) p.y; buff[i * 3 + 2] = (int) p.z; } res.put(0, 0, buff); } break; case CvType.CV_32F: { res = new Mat(count, 1, CvType.CV_32FC3); float[] buff = new float[count * 3]; for (int i = 0; i < count; i++) { Point3 p = pts.get(i); buff[i * 3] = (float) p.x; buff[i * 3 + 1] = (float) p.y; buff[i * 3 + 2] = (float) p.z; } res.put(0, 0, buff); } break; case CvType.CV_64F: { res = new Mat(count, 1, CvType.CV_64FC3); double[] buff = new double[count * 3]; for (int i = 0; i < count; i++) { Point3 p = pts.get(i); buff[i * 3] = p.x; buff[i * 3 + 1] = p.y; buff[i * 3 + 2] = p.z; } res.put(0, 0, buff); } break; default: throw new IllegalArgumentException("'typeDepth' can be CV_32S, CV_32F or CV_64F"); } } else { res = new Mat(); } return res; } public static void Mat_to_vector_Point2f(Mat m, List<Point> pts) { Mat_to_vector_Point(m, pts); } public static void Mat_to_vector_Point2d(Mat m, List<Point> pts) { Mat_to_vector_Point(m, pts); } public static void Mat_to_vector_Point(Mat m, List<Point> pts) { if (pts == null) throw new java.lang.IllegalArgumentException("Output List can't be null"); int count = m.rows(); int type = m.type(); if (m.cols() != 1) throw new java.lang.IllegalArgumentException("Input Mat should have one column\n" + m); pts.clear(); if (type == CvType.CV_32SC2) { int[] buff = new int[2 * count]; m.get(0, 0, buff); for (int i = 0; i < count; i++) { pts.add(new Point(buff[i * 2], buff[i * 2 + 1])); } } else if (type == CvType.CV_32FC2) { float[] buff = new float[2 * count]; m.get(0, 0, buff); for (int i = 0; i < count; i++) { pts.add(new Point(buff[i * 2], buff[i * 2 + 1])); } } else if (type == CvType.CV_64FC2) { double[] buff = new double[2 * count]; m.get(0, 0, buff); for (int i = 0; i < count; i++) { pts.add(new Point(buff[i * 2], buff[i * 2 + 1])); } } else { throw new java.lang.IllegalArgumentException( "Input Mat should be of CV_32SC2, CV_32FC2 or CV_64FC2 type\n" + m); } } public static void Mat_to_vector_Point3i(Mat m, List<Point3> pts) { Mat_to_vector_Point3(m, pts); } public static void Mat_to_vector_Point3f(Mat m, List<Point3> pts) { Mat_to_vector_Point3(m, pts); } public static void Mat_to_vector_Point3d(Mat m, List<Point3> pts) { Mat_to_vector_Point3(m, pts); } public static void Mat_to_vector_Point3(Mat m, List<Point3> pts) { if (pts == null) throw new java.lang.IllegalArgumentException("Output List can't be null"); int count = m.rows(); int type = m.type(); if (m.cols() != 1) throw new java.lang.IllegalArgumentException("Input Mat should have one column\n" + m); pts.clear(); if (type == CvType.CV_32SC3) { int[] buff = new int[3 * count]; m.get(0, 0, buff); for (int i = 0; i < count; i++) { pts.add(new Point3(buff[i * 3], buff[i * 3 + 1], buff[i * 3 + 2])); } } else if (type == CvType.CV_32FC3) { float[] buff = new float[3 * count]; m.get(0, 0, buff); for (int i = 0; i < count; i++) { pts.add(new Point3(buff[i * 3], buff[i * 3 + 1], buff[i * 3 + 2])); } } else if (type == CvType.CV_64FC3) { double[] buff = new double[3 * count]; m.get(0, 0, buff); for (int i = 0; i < count; i++) { pts.add(new Point3(buff[i * 3], buff[i * 3 + 1], buff[i * 3 + 2])); } } else { throw new java.lang.IllegalArgumentException( "Input Mat should be of CV_32SC3, CV_32FC3 or CV_64FC3 type\n" + m); } } public static Mat vector_Mat_to_Mat(List<Mat> mats) { Mat res; int count = (mats != null) ? mats.size() : 0; if (count > 0) { res = new Mat(count, 1, CvType.CV_32SC2); int[] buff = new int[count * 2]; for (int i = 0; i < count; i++) { long addr = mats.get(i).nativeObj; buff[i * 2] = (int) (addr >> 32); buff[i * 2 + 1] = (int) (addr & 0xffffffff); } res.put(0, 0, buff); } else { res = new Mat(); } return res; } public static void Mat_to_vector_Mat(Mat m, List<Mat> mats) { if (mats == null) throw new java.lang.IllegalArgumentException("mats == null"); int count = m.rows(); if (CvType.CV_32SC2 != m.type() || m.cols() != 1) throw new java.lang.IllegalArgumentException( "CvType.CV_32SC2 != m.type() || m.cols()!=1\n" + m); mats.clear(); int[] buff = new int[count * 2]; m.get(0, 0, buff); for (int i = 0; i < count; i++) { long addr = (((long) buff[i * 2]) << 32) | (((long) buff[i * 2 + 1]) & 0xffffffffL); mats.add(new Mat(addr)); } } public static Mat vector_float_to_Mat(List<Float> fs) { Mat res; int count = (fs != null) ? fs.size() : 0; if (count > 0) { res = new Mat(count, 1, CvType.CV_32FC1); float[] buff = new float[count]; for (int i = 0; i < count; i++) { float f = fs.get(i); buff[i] = f; } res.put(0, 0, buff); } else { res = new Mat(); } return res; } public static void Mat_to_vector_float(Mat m, List<Float> fs) { if (fs == null) throw new java.lang.IllegalArgumentException("fs == null"); int count = m.rows(); if (CvType.CV_32FC1 != m.type() || m.cols() != 1) throw new java.lang.IllegalArgumentException( "CvType.CV_32FC1 != m.type() || m.cols()!=1\n" + m); fs.clear(); float[] buff = new float[count]; m.get(0, 0, buff); for (int i = 0; i < count; i++) { fs.add(buff[i]); } } public static Mat vector_uchar_to_Mat(List<Byte> bs) { Mat res; int count = (bs != null) ? bs.size() : 0; if (count > 0) { res = new Mat(count, 1, CvType.CV_8UC1); byte[] buff = new byte[count]; for (int i = 0; i < count; i++) { byte b = bs.get(i); buff[i] = b; } res.put(0, 0, buff); } else { res = new Mat(); } return res; } public static void Mat_to_vector_uchar(Mat m, List<Byte> us) { if (us == null) throw new java.lang.IllegalArgumentException("Output List can't be null"); int count = m.rows(); if (CvType.CV_8UC1 != m.type() || m.cols() != 1) throw new java.lang.IllegalArgumentException( "CvType.CV_8UC1 != m.type() || m.cols()!=1\n" + m); us.clear(); byte[] buff = new byte[count]; m.get(0, 0, buff); for (int i = 0; i < count; i++) { us.add(buff[i]); } } public static Mat vector_char_to_Mat(List<Byte> bs) { Mat res; int count = (bs != null) ? bs.size() : 0; if (count > 0) { res = new Mat(count, 1, CvType.CV_8SC1); byte[] buff = new byte[count]; for (int i = 0; i < count; i++) { byte b = bs.get(i); buff[i] = b; } res.put(0, 0, buff); } else { res = new Mat(); } return res; } public static Mat vector_int_to_Mat(List<Integer> is) { Mat res; int count = (is != null) ? is.size() : 0; if (count > 0) { res = new Mat(count, 1, CvType.CV_32SC1); int[] buff = new int[count]; for (int i = 0; i < count; i++) { int v = is.get(i); buff[i] = v; } res.put(0, 0, buff); } else { res = new Mat(); } return res; } public static void Mat_to_vector_int(Mat m, List<Integer> is) { if (is == null) throw new java.lang.IllegalArgumentException("is == null"); int count = m.rows(); if (CvType.CV_32SC1 != m.type() || m.cols() != 1) throw new java.lang.IllegalArgumentException( "CvType.CV_32SC1 != m.type() || m.cols()!=1\n" + m); is.clear(); int[] buff = new int[count]; m.get(0, 0, buff); for (int i = 0; i < count; i++) { is.add(buff[i]); } } public static void Mat_to_vector_char(Mat m, List<Byte> bs) { if (bs == null) throw new java.lang.IllegalArgumentException("Output List can't be null"); int count = m.rows(); if (CvType.CV_8SC1 != m.type() || m.cols() != 1) throw new java.lang.IllegalArgumentException( "CvType.CV_8SC1 != m.type() || m.cols()!=1\n" + m); bs.clear(); byte[] buff = new byte[count]; m.get(0, 0, buff); for (int i = 0; i < count; i++) { bs.add(buff[i]); } } public static Mat vector_Rect_to_Mat(List<Rect> rs) { Mat res; int count = (rs != null) ? rs.size() : 0; if (count > 0) { res = new Mat(count, 1, CvType.CV_32SC4); int[] buff = new int[4 * count]; for (int i = 0; i < count; i++) { Rect r = rs.get(i); buff[4 * i] = r.x; buff[4 * i + 1] = r.y; buff[4 * i + 2] = r.width; buff[4 * i + 3] = r.height; } res.put(0, 0, buff); } else { res = new Mat(); } return res; } public static void Mat_to_vector_Rect(Mat m, List<Rect> rs) { if (rs == null) throw new java.lang.IllegalArgumentException("rs == null"); int count = m.rows(); if (CvType.CV_32SC4 != m.type() || m.cols() != 1) throw new java.lang.IllegalArgumentException( "CvType.CV_32SC4 != m.type() || m.rows()!=1\n" + m); rs.clear(); int[] buff = new int[4 * count]; m.get(0, 0, buff); for (int i = 0; i < count; i++) { rs.add(new Rect(buff[4 * i], buff[4 * i + 1], buff[4 * i + 2], buff[4 * i + 3])); } } public static Mat vector_KeyPoint_to_Mat(List<KeyPoint> kps) { Mat res; int count = (kps != null) ? kps.size() : 0; if (count > 0) { res = new Mat(count, 1, CvType.CV_64FC(7)); double[] buff = new double[count * 7]; for (int i = 0; i < count; i++) { KeyPoint kp = kps.get(i); buff[7 * i] = kp.pt.x; buff[7 * i + 1] = kp.pt.y; buff[7 * i + 2] = kp.size; buff[7 * i + 3] = kp.angle; buff[7 * i + 4] = kp.response; buff[7 * i + 5] = kp.octave; buff[7 * i + 6] = kp.class_id; } res.put(0, 0, buff); } else { res = new Mat(); } return res; } public static void Mat_to_vector_KeyPoint(Mat m, List<KeyPoint> kps) { if (kps == null) throw new java.lang.IllegalArgumentException("Output List can't be null"); int count = m.rows(); if (CvType.CV_64FC(7) != m.type() || m.cols() != 1) throw new java.lang.IllegalArgumentException( "CvType.CV_64FC(7) != m.type() || m.cols()!=1\n" + m); kps.clear(); double[] buff = new double[7 * count]; m.get(0, 0, buff); for (int i = 0; i < count; i++) { kps.add(new KeyPoint((float) buff[7 * i], (float) buff[7 * i + 1], (float) buff[7 * i + 2], (float) buff[7 * i + 3], (float) buff[7 * i + 4], (int) buff[7 * i + 5], (int) buff[7 * i + 6])); } } // vector_vector_Point public static Mat vector_vector_Point_to_Mat(List<MatOfPoint> pts, List<Mat> mats) { Mat res; int lCount = (pts != null) ? pts.size() : 0; if (lCount > 0) { for (MatOfPoint vpt : pts) mats.add(vpt); res = vector_Mat_to_Mat(mats); } else { res = new Mat(); } return res; } public static void Mat_to_vector_vector_Point(Mat m, List<MatOfPoint> pts) { if (pts == null) throw new java.lang.IllegalArgumentException("Output List can't be null"); if (m == null) throw new java.lang.IllegalArgumentException("Input Mat can't be null"); List<Mat> mats = new ArrayList<Mat>(m.rows()); Mat_to_vector_Mat(m, mats); for (Mat mi : mats) { MatOfPoint pt = new MatOfPoint(mi); pts.add(pt); mi.release(); } mats.clear(); } // vector_vector_Point2f public static void Mat_to_vector_vector_Point2f(Mat m, List<MatOfPoint2f> pts) { if (pts == null) throw new java.lang.IllegalArgumentException("Output List can't be null"); if (m == null) throw new java.lang.IllegalArgumentException("Input Mat can't be null"); List<Mat> mats = new ArrayList<Mat>(m.rows()); Mat_to_vector_Mat(m, mats); for (Mat mi : mats) { MatOfPoint2f pt = new MatOfPoint2f(mi); pts.add(pt); mi.release(); } mats.clear(); } // vector_vector_Point2f public static Mat vector_vector_Point2f_to_Mat(List<MatOfPoint2f> pts, List<Mat> mats) { Mat res; int lCount = (pts != null) ? pts.size() : 0; if (lCount > 0) { for (MatOfPoint2f vpt : pts) mats.add(vpt); res = vector_Mat_to_Mat(mats); } else { res = new Mat(); } return res; } // vector_vector_Point3f public static void Mat_to_vector_vector_Point3f(Mat m, List<MatOfPoint3f> pts) { if (pts == null) throw new java.lang.IllegalArgumentException("Output List can't be null"); if (m == null) throw new java.lang.IllegalArgumentException("Input Mat can't be null"); List<Mat> mats = new ArrayList<Mat>(m.rows()); Mat_to_vector_Mat(m, mats); for (Mat mi : mats) { MatOfPoint3f pt = new MatOfPoint3f(mi); pts.add(pt); mi.release(); } mats.clear(); } // vector_vector_Point3f public static Mat vector_vector_Point3f_to_Mat(List<MatOfPoint3f> pts, List<Mat> mats) { Mat res; int lCount = (pts != null) ? pts.size() : 0; if (lCount > 0) { for (MatOfPoint3f vpt : pts) mats.add(vpt); res = vector_Mat_to_Mat(mats); } else { res = new Mat(); } return res; } // vector_vector_KeyPoint public static Mat vector_vector_KeyPoint_to_Mat(List<MatOfKeyPoint> kps, List<Mat> mats) { Mat res; int lCount = (kps != null) ? kps.size() : 0; if (lCount > 0) { for (MatOfKeyPoint vkp : kps) mats.add(vkp); res = vector_Mat_to_Mat(mats); } else { res = new Mat(); } return res; } public static void Mat_to_vector_vector_KeyPoint(Mat m, List<MatOfKeyPoint> kps) { if (kps == null) throw new java.lang.IllegalArgumentException("Output List can't be null"); if (m == null) throw new java.lang.IllegalArgumentException("Input Mat can't be null"); List<Mat> mats = new ArrayList<Mat>(m.rows()); Mat_to_vector_Mat(m, mats); for (Mat mi : mats) { MatOfKeyPoint vkp = new MatOfKeyPoint(mi); kps.add(vkp); mi.release(); } mats.clear(); } public static Mat vector_double_to_Mat(List<Double> ds) { Mat res; int count = (ds != null) ? ds.size() : 0; if (count > 0) { res = new Mat(count, 1, CvType.CV_64FC1); double[] buff = new double[count]; for (int i = 0; i < count; i++) { double v = ds.get(i); buff[i] = v; } res.put(0, 0, buff); } else { res = new Mat(); } return res; } public static void Mat_to_vector_double(Mat m, List<Double> ds) { if (ds == null) throw new java.lang.IllegalArgumentException("ds == null"); int count = m.rows(); if (CvType.CV_64FC1 != m.type() || m.cols() != 1) throw new java.lang.IllegalArgumentException( "CvType.CV_64FC1 != m.type() || m.cols()!=1\n" + m); ds.clear(); double[] buff = new double[count]; m.get(0, 0, buff); for (int i = 0; i < count; i++) { ds.add(buff[i]); } } public static Mat vector_DMatch_to_Mat(List<DMatch> matches) { Mat res; int count = (matches != null) ? matches.size() : 0; if (count > 0) { res = new Mat(count, 1, CvType.CV_64FC4); double[] buff = new double[count * 4]; for (int i = 0; i < count; i++) { DMatch m = matches.get(i); buff[4 * i] = m.queryIdx; buff[4 * i + 1] = m.trainIdx; buff[4 * i + 2] = m.imgIdx; buff[4 * i + 3] = m.distance; } res.put(0, 0, buff); } else { res = new Mat(); } return res; } public static void Mat_to_vector_DMatch(Mat m, List<DMatch> matches) { if (matches == null) throw new java.lang.IllegalArgumentException("Output List can't be null"); int count = m.rows(); if (CvType.CV_64FC4 != m.type() || m.cols() != 1) throw new java.lang.IllegalArgumentException( "CvType.CV_64FC4 != m.type() || m.cols()!=1\n" + m); matches.clear(); double[] buff = new double[4 * count]; m.get(0, 0, buff); for (int i = 0; i < count; i++) { matches.add(new DMatch((int) buff[4 * i], (int) buff[4 * i + 1], (int) buff[4 * i + 2], (float) buff[4 * i + 3])); } } // vector_vector_DMatch public static Mat vector_vector_DMatch_to_Mat(List<MatOfDMatch> lvdm, List<Mat> mats) { Mat res; int lCount = (lvdm != null) ? lvdm.size() : 0; if (lCount > 0) { for (MatOfDMatch vdm : lvdm) mats.add(vdm); res = vector_Mat_to_Mat(mats); } else { res = new Mat(); } return res; } public static void Mat_to_vector_vector_DMatch(Mat m, List<MatOfDMatch> lvdm) { if (lvdm == null) throw new java.lang.IllegalArgumentException("Output List can't be null"); if (m == null) throw new java.lang.IllegalArgumentException("Input Mat can't be null"); List<Mat> mats = new ArrayList<Mat>(m.rows()); Mat_to_vector_Mat(m, mats); lvdm.clear(); for (Mat mi : mats) { MatOfDMatch vdm = new MatOfDMatch(mi); lvdm.add(vdm); mi.release(); } mats.clear(); } // vector_vector_char public static Mat vector_vector_char_to_Mat(List<MatOfByte> lvb, List<Mat> mats) { Mat res; int lCount = (lvb != null) ? lvb.size() : 0; if (lCount > 0) { for (MatOfByte vb : lvb) mats.add(vb); res = vector_Mat_to_Mat(mats); } else { res = new Mat(); } return res; } public static void Mat_to_vector_vector_char(Mat m, List<List<Byte>> llb) { if (llb == null) throw new java.lang.IllegalArgumentException("Output List can't be null"); if (m == null) throw new java.lang.IllegalArgumentException("Input Mat can't be null"); List<Mat> mats = new ArrayList<Mat>(m.rows()); Mat_to_vector_Mat(m, mats); for (Mat mi : mats) { List<Byte> lb = new ArrayList<Byte>(); Mat_to_vector_char(mi, lb); llb.add(lb); mi.release(); } mats.clear(); } }
24,826
32.686567
128
java
self
self-master/lib/opencv/android/sdk/java/src/org/opencv/calib3d/Calib3d.java
// // This file is auto-generated. Please don't modify it! // package org.opencv.calib3d; import java.util.ArrayList; import java.util.List; import org.opencv.core.Mat; import org.opencv.core.MatOfDouble; import org.opencv.core.MatOfPoint2f; import org.opencv.core.MatOfPoint3f; import org.opencv.core.Point; import org.opencv.core.Rect; import org.opencv.core.Size; import org.opencv.core.TermCriteria; import org.opencv.utils.Converters; public class Calib3d { public static final int CALIB_USE_INTRINSIC_GUESS = 1, CALIB_RECOMPUTE_EXTRINSIC = 2, CALIB_CHECK_COND = 4, CALIB_FIX_SKEW = 8, CALIB_FIX_K1 = 16, CALIB_FIX_K2 = 32, CALIB_FIX_K3 = 64, CALIB_FIX_K4 = 128, CALIB_FIX_INTRINSIC = 256, CV_ITERATIVE = 0, CV_EPNP = 1, CV_P3P = 2, CV_DLS = 3, LMEDS = 4, RANSAC = 8, RHO = 16, SOLVEPNP_ITERATIVE = 0, SOLVEPNP_EPNP = 1, SOLVEPNP_P3P = 2, SOLVEPNP_DLS = 3, SOLVEPNP_UPNP = 4, CALIB_CB_ADAPTIVE_THRESH = 1, CALIB_CB_NORMALIZE_IMAGE = 2, CALIB_CB_FILTER_QUADS = 4, CALIB_CB_FAST_CHECK = 8, CALIB_CB_SYMMETRIC_GRID = 1, CALIB_CB_ASYMMETRIC_GRID = 2, CALIB_CB_CLUSTERING = 4, CALIB_FIX_ASPECT_RATIO = 0x00002, CALIB_FIX_PRINCIPAL_POINT = 0x00004, CALIB_ZERO_TANGENT_DIST = 0x00008, CALIB_FIX_FOCAL_LENGTH = 0x00010, CALIB_FIX_K5 = 0x01000, CALIB_FIX_K6 = 0x02000, CALIB_RATIONAL_MODEL = 0x04000, CALIB_THIN_PRISM_MODEL = 0x08000, CALIB_FIX_S1_S2_S3_S4 = 0x10000, CALIB_TILTED_MODEL = 0x40000, CALIB_FIX_TAUX_TAUY = 0x80000, CALIB_SAME_FOCAL_LENGTH = 0x00200, CALIB_ZERO_DISPARITY = 0x00400, CALIB_USE_LU = (1 << 17), FM_7POINT = 1, FM_8POINT = 2, FM_LMEDS = 4, FM_RANSAC = 8; // // C++: Mat findEssentialMat(Mat points1, Mat points2, Mat cameraMatrix, int method = RANSAC, double prob = 0.999, double threshold = 1.0, Mat& mask = Mat()) // //javadoc: findEssentialMat(points1, points2, cameraMatrix, method, prob, threshold, mask) public static Mat findEssentialMat(Mat points1, Mat points2, Mat cameraMatrix, int method, double prob, double threshold, Mat mask) { Mat retVal = new Mat(findEssentialMat_0(points1.nativeObj, points2.nativeObj, cameraMatrix.nativeObj, method, prob, threshold, mask.nativeObj)); return retVal; } //javadoc: findEssentialMat(points1, points2, cameraMatrix, method, prob, threshold) public static Mat findEssentialMat(Mat points1, Mat points2, Mat cameraMatrix, int method, double prob, double threshold) { Mat retVal = new Mat(findEssentialMat_1(points1.nativeObj, points2.nativeObj, cameraMatrix.nativeObj, method, prob, threshold)); return retVal; } //javadoc: findEssentialMat(points1, points2, cameraMatrix) public static Mat findEssentialMat(Mat points1, Mat points2, Mat cameraMatrix) { Mat retVal = new Mat(findEssentialMat_2(points1.nativeObj, points2.nativeObj, cameraMatrix.nativeObj)); return retVal; } // // C++: Mat findEssentialMat(Mat points1, Mat points2, double focal = 1.0, Point2d pp = Point2d(0, 0), int method = RANSAC, double prob = 0.999, double threshold = 1.0, Mat& mask = Mat()) // //javadoc: findEssentialMat(points1, points2, focal, pp, method, prob, threshold, mask) public static Mat findEssentialMat(Mat points1, Mat points2, double focal, Point pp, int method, double prob, double threshold, Mat mask) { Mat retVal = new Mat(findEssentialMat_3(points1.nativeObj, points2.nativeObj, focal, pp.x, pp.y, method, prob, threshold, mask.nativeObj)); return retVal; } //javadoc: findEssentialMat(points1, points2, focal, pp, method, prob, threshold) public static Mat findEssentialMat(Mat points1, Mat points2, double focal, Point pp, int method, double prob, double threshold) { Mat retVal = new Mat(findEssentialMat_4(points1.nativeObj, points2.nativeObj, focal, pp.x, pp.y, method, prob, threshold)); return retVal; } //javadoc: findEssentialMat(points1, points2) public static Mat findEssentialMat(Mat points1, Mat points2) { Mat retVal = new Mat(findEssentialMat_5(points1.nativeObj, points2.nativeObj)); return retVal; } // // C++: Mat findFundamentalMat(vector_Point2f points1, vector_Point2f points2, int method = FM_RANSAC, double param1 = 3., double param2 = 0.99, Mat& mask = Mat()) // //javadoc: findFundamentalMat(points1, points2, method, param1, param2, mask) public static Mat findFundamentalMat(MatOfPoint2f points1, MatOfPoint2f points2, int method, double param1, double param2, Mat mask) { Mat points1_mat = points1; Mat points2_mat = points2; Mat retVal = new Mat(findFundamentalMat_0(points1_mat.nativeObj, points2_mat.nativeObj, method, param1, param2, mask.nativeObj)); return retVal; } //javadoc: findFundamentalMat(points1, points2, method, param1, param2) public static Mat findFundamentalMat(MatOfPoint2f points1, MatOfPoint2f points2, int method, double param1, double param2) { Mat points1_mat = points1; Mat points2_mat = points2; Mat retVal = new Mat(findFundamentalMat_1(points1_mat.nativeObj, points2_mat.nativeObj, method, param1, param2)); return retVal; } //javadoc: findFundamentalMat(points1, points2) public static Mat findFundamentalMat(MatOfPoint2f points1, MatOfPoint2f points2) { Mat points1_mat = points1; Mat points2_mat = points2; Mat retVal = new Mat(findFundamentalMat_2(points1_mat.nativeObj, points2_mat.nativeObj)); return retVal; } // // C++: Mat findHomography(vector_Point2f srcPoints, vector_Point2f dstPoints, int method = 0, double ransacReprojThreshold = 3, Mat& mask = Mat(), int maxIters = 2000, double confidence = 0.995) // //javadoc: findHomography(srcPoints, dstPoints, method, ransacReprojThreshold, mask, maxIters, confidence) public static Mat findHomography(MatOfPoint2f srcPoints, MatOfPoint2f dstPoints, int method, double ransacReprojThreshold, Mat mask, int maxIters, double confidence) { Mat srcPoints_mat = srcPoints; Mat dstPoints_mat = dstPoints; Mat retVal = new Mat(findHomography_0(srcPoints_mat.nativeObj, dstPoints_mat.nativeObj, method, ransacReprojThreshold, mask.nativeObj, maxIters, confidence)); return retVal; } //javadoc: findHomography(srcPoints, dstPoints, method, ransacReprojThreshold) public static Mat findHomography(MatOfPoint2f srcPoints, MatOfPoint2f dstPoints, int method, double ransacReprojThreshold) { Mat srcPoints_mat = srcPoints; Mat dstPoints_mat = dstPoints; Mat retVal = new Mat(findHomography_1(srcPoints_mat.nativeObj, dstPoints_mat.nativeObj, method, ransacReprojThreshold)); return retVal; } //javadoc: findHomography(srcPoints, dstPoints) public static Mat findHomography(MatOfPoint2f srcPoints, MatOfPoint2f dstPoints) { Mat srcPoints_mat = srcPoints; Mat dstPoints_mat = dstPoints; Mat retVal = new Mat(findHomography_2(srcPoints_mat.nativeObj, dstPoints_mat.nativeObj)); return retVal; } // // C++: Mat getOptimalNewCameraMatrix(Mat cameraMatrix, Mat distCoeffs, Size imageSize, double alpha, Size newImgSize = Size(), Rect* validPixROI = 0, bool centerPrincipalPoint = false) // //javadoc: getOptimalNewCameraMatrix(cameraMatrix, distCoeffs, imageSize, alpha, newImgSize, validPixROI, centerPrincipalPoint) public static Mat getOptimalNewCameraMatrix(Mat cameraMatrix, Mat distCoeffs, Size imageSize, double alpha, Size newImgSize, Rect validPixROI, boolean centerPrincipalPoint) { double[] validPixROI_out = new double[4]; Mat retVal = new Mat(getOptimalNewCameraMatrix_0(cameraMatrix.nativeObj, distCoeffs.nativeObj, imageSize.width, imageSize.height, alpha, newImgSize.width, newImgSize.height, validPixROI_out, centerPrincipalPoint)); if(validPixROI!=null){ validPixROI.x = (int)validPixROI_out[0]; validPixROI.y = (int)validPixROI_out[1]; validPixROI.width = (int)validPixROI_out[2]; validPixROI.height = (int)validPixROI_out[3]; } return retVal; } //javadoc: getOptimalNewCameraMatrix(cameraMatrix, distCoeffs, imageSize, alpha) public static Mat getOptimalNewCameraMatrix(Mat cameraMatrix, Mat distCoeffs, Size imageSize, double alpha) { Mat retVal = new Mat(getOptimalNewCameraMatrix_1(cameraMatrix.nativeObj, distCoeffs.nativeObj, imageSize.width, imageSize.height, alpha)); return retVal; } // // C++: Mat initCameraMatrix2D(vector_vector_Point3f objectPoints, vector_vector_Point2f imagePoints, Size imageSize, double aspectRatio = 1.0) // //javadoc: initCameraMatrix2D(objectPoints, imagePoints, imageSize, aspectRatio) public static Mat initCameraMatrix2D(List<MatOfPoint3f> objectPoints, List<MatOfPoint2f> imagePoints, Size imageSize, double aspectRatio) { List<Mat> objectPoints_tmplm = new ArrayList<Mat>((objectPoints != null) ? objectPoints.size() : 0); Mat objectPoints_mat = Converters.vector_vector_Point3f_to_Mat(objectPoints, objectPoints_tmplm); List<Mat> imagePoints_tmplm = new ArrayList<Mat>((imagePoints != null) ? imagePoints.size() : 0); Mat imagePoints_mat = Converters.vector_vector_Point2f_to_Mat(imagePoints, imagePoints_tmplm); Mat retVal = new Mat(initCameraMatrix2D_0(objectPoints_mat.nativeObj, imagePoints_mat.nativeObj, imageSize.width, imageSize.height, aspectRatio)); return retVal; } //javadoc: initCameraMatrix2D(objectPoints, imagePoints, imageSize) public static Mat initCameraMatrix2D(List<MatOfPoint3f> objectPoints, List<MatOfPoint2f> imagePoints, Size imageSize) { List<Mat> objectPoints_tmplm = new ArrayList<Mat>((objectPoints != null) ? objectPoints.size() : 0); Mat objectPoints_mat = Converters.vector_vector_Point3f_to_Mat(objectPoints, objectPoints_tmplm); List<Mat> imagePoints_tmplm = new ArrayList<Mat>((imagePoints != null) ? imagePoints.size() : 0); Mat imagePoints_mat = Converters.vector_vector_Point2f_to_Mat(imagePoints, imagePoints_tmplm); Mat retVal = new Mat(initCameraMatrix2D_1(objectPoints_mat.nativeObj, imagePoints_mat.nativeObj, imageSize.width, imageSize.height)); return retVal; } // // C++: Rect getValidDisparityROI(Rect roi1, Rect roi2, int minDisparity, int numberOfDisparities, int SADWindowSize) // //javadoc: getValidDisparityROI(roi1, roi2, minDisparity, numberOfDisparities, SADWindowSize) public static Rect getValidDisparityROI(Rect roi1, Rect roi2, int minDisparity, int numberOfDisparities, int SADWindowSize) { Rect retVal = new Rect(getValidDisparityROI_0(roi1.x, roi1.y, roi1.width, roi1.height, roi2.x, roi2.y, roi2.width, roi2.height, minDisparity, numberOfDisparities, SADWindowSize)); return retVal; } // // C++: Vec3d RQDecomp3x3(Mat src, Mat& mtxR, Mat& mtxQ, Mat& Qx = Mat(), Mat& Qy = Mat(), Mat& Qz = Mat()) // //javadoc: RQDecomp3x3(src, mtxR, mtxQ, Qx, Qy, Qz) public static double[] RQDecomp3x3(Mat src, Mat mtxR, Mat mtxQ, Mat Qx, Mat Qy, Mat Qz) { double[] retVal = RQDecomp3x3_0(src.nativeObj, mtxR.nativeObj, mtxQ.nativeObj, Qx.nativeObj, Qy.nativeObj, Qz.nativeObj); return retVal; } //javadoc: RQDecomp3x3(src, mtxR, mtxQ) public static double[] RQDecomp3x3(Mat src, Mat mtxR, Mat mtxQ) { double[] retVal = RQDecomp3x3_1(src.nativeObj, mtxR.nativeObj, mtxQ.nativeObj); return retVal; } // // C++: bool findChessboardCorners(Mat image, Size patternSize, vector_Point2f& corners, int flags = CALIB_CB_ADAPTIVE_THRESH + CALIB_CB_NORMALIZE_IMAGE) // //javadoc: findChessboardCorners(image, patternSize, corners, flags) public static boolean findChessboardCorners(Mat image, Size patternSize, MatOfPoint2f corners, int flags) { Mat corners_mat = corners; boolean retVal = findChessboardCorners_0(image.nativeObj, patternSize.width, patternSize.height, corners_mat.nativeObj, flags); return retVal; } //javadoc: findChessboardCorners(image, patternSize, corners) public static boolean findChessboardCorners(Mat image, Size patternSize, MatOfPoint2f corners) { Mat corners_mat = corners; boolean retVal = findChessboardCorners_1(image.nativeObj, patternSize.width, patternSize.height, corners_mat.nativeObj); return retVal; } // // C++: bool findCirclesGrid(Mat image, Size patternSize, Mat& centers, int flags = CALIB_CB_SYMMETRIC_GRID, Ptr_FeatureDetector blobDetector = SimpleBlobDetector::create()) // //javadoc: findCirclesGrid(image, patternSize, centers, flags) public static boolean findCirclesGrid(Mat image, Size patternSize, Mat centers, int flags) { boolean retVal = findCirclesGrid_0(image.nativeObj, patternSize.width, patternSize.height, centers.nativeObj, flags); return retVal; } //javadoc: findCirclesGrid(image, patternSize, centers) public static boolean findCirclesGrid(Mat image, Size patternSize, Mat centers) { boolean retVal = findCirclesGrid_1(image.nativeObj, patternSize.width, patternSize.height, centers.nativeObj); return retVal; } // // C++: bool solvePnP(vector_Point3f objectPoints, vector_Point2f imagePoints, Mat cameraMatrix, vector_double distCoeffs, Mat& rvec, Mat& tvec, bool useExtrinsicGuess = false, int flags = SOLVEPNP_ITERATIVE) // //javadoc: solvePnP(objectPoints, imagePoints, cameraMatrix, distCoeffs, rvec, tvec, useExtrinsicGuess, flags) public static boolean solvePnP(MatOfPoint3f objectPoints, MatOfPoint2f imagePoints, Mat cameraMatrix, MatOfDouble distCoeffs, Mat rvec, Mat tvec, boolean useExtrinsicGuess, int flags) { Mat objectPoints_mat = objectPoints; Mat imagePoints_mat = imagePoints; Mat distCoeffs_mat = distCoeffs; boolean retVal = solvePnP_0(objectPoints_mat.nativeObj, imagePoints_mat.nativeObj, cameraMatrix.nativeObj, distCoeffs_mat.nativeObj, rvec.nativeObj, tvec.nativeObj, useExtrinsicGuess, flags); return retVal; } //javadoc: solvePnP(objectPoints, imagePoints, cameraMatrix, distCoeffs, rvec, tvec) public static boolean solvePnP(MatOfPoint3f objectPoints, MatOfPoint2f imagePoints, Mat cameraMatrix, MatOfDouble distCoeffs, Mat rvec, Mat tvec) { Mat objectPoints_mat = objectPoints; Mat imagePoints_mat = imagePoints; Mat distCoeffs_mat = distCoeffs; boolean retVal = solvePnP_1(objectPoints_mat.nativeObj, imagePoints_mat.nativeObj, cameraMatrix.nativeObj, distCoeffs_mat.nativeObj, rvec.nativeObj, tvec.nativeObj); return retVal; } // // C++: bool solvePnPRansac(vector_Point3f objectPoints, vector_Point2f imagePoints, Mat cameraMatrix, vector_double distCoeffs, Mat& rvec, Mat& tvec, bool useExtrinsicGuess = false, int iterationsCount = 100, float reprojectionError = 8.0, double confidence = 0.99, Mat& inliers = Mat(), int flags = SOLVEPNP_ITERATIVE) // //javadoc: solvePnPRansac(objectPoints, imagePoints, cameraMatrix, distCoeffs, rvec, tvec, useExtrinsicGuess, iterationsCount, reprojectionError, confidence, inliers, flags) public static boolean solvePnPRansac(MatOfPoint3f objectPoints, MatOfPoint2f imagePoints, Mat cameraMatrix, MatOfDouble distCoeffs, Mat rvec, Mat tvec, boolean useExtrinsicGuess, int iterationsCount, float reprojectionError, double confidence, Mat inliers, int flags) { Mat objectPoints_mat = objectPoints; Mat imagePoints_mat = imagePoints; Mat distCoeffs_mat = distCoeffs; boolean retVal = solvePnPRansac_0(objectPoints_mat.nativeObj, imagePoints_mat.nativeObj, cameraMatrix.nativeObj, distCoeffs_mat.nativeObj, rvec.nativeObj, tvec.nativeObj, useExtrinsicGuess, iterationsCount, reprojectionError, confidence, inliers.nativeObj, flags); return retVal; } //javadoc: solvePnPRansac(objectPoints, imagePoints, cameraMatrix, distCoeffs, rvec, tvec) public static boolean solvePnPRansac(MatOfPoint3f objectPoints, MatOfPoint2f imagePoints, Mat cameraMatrix, MatOfDouble distCoeffs, Mat rvec, Mat tvec) { Mat objectPoints_mat = objectPoints; Mat imagePoints_mat = imagePoints; Mat distCoeffs_mat = distCoeffs; boolean retVal = solvePnPRansac_1(objectPoints_mat.nativeObj, imagePoints_mat.nativeObj, cameraMatrix.nativeObj, distCoeffs_mat.nativeObj, rvec.nativeObj, tvec.nativeObj); return retVal; } // // C++: bool stereoRectifyUncalibrated(Mat points1, Mat points2, Mat F, Size imgSize, Mat& H1, Mat& H2, double threshold = 5) // //javadoc: stereoRectifyUncalibrated(points1, points2, F, imgSize, H1, H2, threshold) public static boolean stereoRectifyUncalibrated(Mat points1, Mat points2, Mat F, Size imgSize, Mat H1, Mat H2, double threshold) { boolean retVal = stereoRectifyUncalibrated_0(points1.nativeObj, points2.nativeObj, F.nativeObj, imgSize.width, imgSize.height, H1.nativeObj, H2.nativeObj, threshold); return retVal; } //javadoc: stereoRectifyUncalibrated(points1, points2, F, imgSize, H1, H2) public static boolean stereoRectifyUncalibrated(Mat points1, Mat points2, Mat F, Size imgSize, Mat H1, Mat H2) { boolean retVal = stereoRectifyUncalibrated_1(points1.nativeObj, points2.nativeObj, F.nativeObj, imgSize.width, imgSize.height, H1.nativeObj, H2.nativeObj); return retVal; } // // C++: double calibrateCamera(vector_Mat objectPoints, vector_Mat imagePoints, Size imageSize, Mat& cameraMatrix, Mat& distCoeffs, vector_Mat& rvecs, vector_Mat& tvecs, int flags = 0, TermCriteria criteria = TermCriteria( TermCriteria::COUNT + TermCriteria::EPS, 30, DBL_EPSILON)) // //javadoc: calibrateCamera(objectPoints, imagePoints, imageSize, cameraMatrix, distCoeffs, rvecs, tvecs, flags, criteria) public static double calibrateCamera(List<Mat> objectPoints, List<Mat> imagePoints, Size imageSize, Mat cameraMatrix, Mat distCoeffs, List<Mat> rvecs, List<Mat> tvecs, int flags, TermCriteria criteria) { Mat objectPoints_mat = Converters.vector_Mat_to_Mat(objectPoints); Mat imagePoints_mat = Converters.vector_Mat_to_Mat(imagePoints); Mat rvecs_mat = new Mat(); Mat tvecs_mat = new Mat(); double retVal = calibrateCamera_0(objectPoints_mat.nativeObj, imagePoints_mat.nativeObj, imageSize.width, imageSize.height, cameraMatrix.nativeObj, distCoeffs.nativeObj, rvecs_mat.nativeObj, tvecs_mat.nativeObj, flags, criteria.type, criteria.maxCount, criteria.epsilon); Converters.Mat_to_vector_Mat(rvecs_mat, rvecs); rvecs_mat.release(); Converters.Mat_to_vector_Mat(tvecs_mat, tvecs); tvecs_mat.release(); return retVal; } //javadoc: calibrateCamera(objectPoints, imagePoints, imageSize, cameraMatrix, distCoeffs, rvecs, tvecs, flags) public static double calibrateCamera(List<Mat> objectPoints, List<Mat> imagePoints, Size imageSize, Mat cameraMatrix, Mat distCoeffs, List<Mat> rvecs, List<Mat> tvecs, int flags) { Mat objectPoints_mat = Converters.vector_Mat_to_Mat(objectPoints); Mat imagePoints_mat = Converters.vector_Mat_to_Mat(imagePoints); Mat rvecs_mat = new Mat(); Mat tvecs_mat = new Mat(); double retVal = calibrateCamera_1(objectPoints_mat.nativeObj, imagePoints_mat.nativeObj, imageSize.width, imageSize.height, cameraMatrix.nativeObj, distCoeffs.nativeObj, rvecs_mat.nativeObj, tvecs_mat.nativeObj, flags); Converters.Mat_to_vector_Mat(rvecs_mat, rvecs); rvecs_mat.release(); Converters.Mat_to_vector_Mat(tvecs_mat, tvecs); tvecs_mat.release(); return retVal; } //javadoc: calibrateCamera(objectPoints, imagePoints, imageSize, cameraMatrix, distCoeffs, rvecs, tvecs) public static double calibrateCamera(List<Mat> objectPoints, List<Mat> imagePoints, Size imageSize, Mat cameraMatrix, Mat distCoeffs, List<Mat> rvecs, List<Mat> tvecs) { Mat objectPoints_mat = Converters.vector_Mat_to_Mat(objectPoints); Mat imagePoints_mat = Converters.vector_Mat_to_Mat(imagePoints); Mat rvecs_mat = new Mat(); Mat tvecs_mat = new Mat(); double retVal = calibrateCamera_2(objectPoints_mat.nativeObj, imagePoints_mat.nativeObj, imageSize.width, imageSize.height, cameraMatrix.nativeObj, distCoeffs.nativeObj, rvecs_mat.nativeObj, tvecs_mat.nativeObj); Converters.Mat_to_vector_Mat(rvecs_mat, rvecs); rvecs_mat.release(); Converters.Mat_to_vector_Mat(tvecs_mat, tvecs); tvecs_mat.release(); return retVal; } // // C++: double sampsonDistance(Mat pt1, Mat pt2, Mat F) // //javadoc: sampsonDistance(pt1, pt2, F) public static double sampsonDistance(Mat pt1, Mat pt2, Mat F) { double retVal = sampsonDistance_0(pt1.nativeObj, pt2.nativeObj, F.nativeObj); return retVal; } // // C++: double stereoCalibrate(vector_Mat objectPoints, vector_Mat imagePoints1, vector_Mat imagePoints2, Mat& cameraMatrix1, Mat& distCoeffs1, Mat& cameraMatrix2, Mat& distCoeffs2, Size imageSize, Mat& R, Mat& T, Mat& E, Mat& F, int flags = CALIB_FIX_INTRINSIC, TermCriteria criteria = TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 1e-6)) // //javadoc: stereoCalibrate(objectPoints, imagePoints1, imagePoints2, cameraMatrix1, distCoeffs1, cameraMatrix2, distCoeffs2, imageSize, R, T, E, F, flags, criteria) public static double stereoCalibrate(List<Mat> objectPoints, List<Mat> imagePoints1, List<Mat> imagePoints2, Mat cameraMatrix1, Mat distCoeffs1, Mat cameraMatrix2, Mat distCoeffs2, Size imageSize, Mat R, Mat T, Mat E, Mat F, int flags, TermCriteria criteria) { Mat objectPoints_mat = Converters.vector_Mat_to_Mat(objectPoints); Mat imagePoints1_mat = Converters.vector_Mat_to_Mat(imagePoints1); Mat imagePoints2_mat = Converters.vector_Mat_to_Mat(imagePoints2); double retVal = stereoCalibrate_0(objectPoints_mat.nativeObj, imagePoints1_mat.nativeObj, imagePoints2_mat.nativeObj, cameraMatrix1.nativeObj, distCoeffs1.nativeObj, cameraMatrix2.nativeObj, distCoeffs2.nativeObj, imageSize.width, imageSize.height, R.nativeObj, T.nativeObj, E.nativeObj, F.nativeObj, flags, criteria.type, criteria.maxCount, criteria.epsilon); return retVal; } //javadoc: stereoCalibrate(objectPoints, imagePoints1, imagePoints2, cameraMatrix1, distCoeffs1, cameraMatrix2, distCoeffs2, imageSize, R, T, E, F, flags) public static double stereoCalibrate(List<Mat> objectPoints, List<Mat> imagePoints1, List<Mat> imagePoints2, Mat cameraMatrix1, Mat distCoeffs1, Mat cameraMatrix2, Mat distCoeffs2, Size imageSize, Mat R, Mat T, Mat E, Mat F, int flags) { Mat objectPoints_mat = Converters.vector_Mat_to_Mat(objectPoints); Mat imagePoints1_mat = Converters.vector_Mat_to_Mat(imagePoints1); Mat imagePoints2_mat = Converters.vector_Mat_to_Mat(imagePoints2); double retVal = stereoCalibrate_1(objectPoints_mat.nativeObj, imagePoints1_mat.nativeObj, imagePoints2_mat.nativeObj, cameraMatrix1.nativeObj, distCoeffs1.nativeObj, cameraMatrix2.nativeObj, distCoeffs2.nativeObj, imageSize.width, imageSize.height, R.nativeObj, T.nativeObj, E.nativeObj, F.nativeObj, flags); return retVal; } //javadoc: stereoCalibrate(objectPoints, imagePoints1, imagePoints2, cameraMatrix1, distCoeffs1, cameraMatrix2, distCoeffs2, imageSize, R, T, E, F) public static double stereoCalibrate(List<Mat> objectPoints, List<Mat> imagePoints1, List<Mat> imagePoints2, Mat cameraMatrix1, Mat distCoeffs1, Mat cameraMatrix2, Mat distCoeffs2, Size imageSize, Mat R, Mat T, Mat E, Mat F) { Mat objectPoints_mat = Converters.vector_Mat_to_Mat(objectPoints); Mat imagePoints1_mat = Converters.vector_Mat_to_Mat(imagePoints1); Mat imagePoints2_mat = Converters.vector_Mat_to_Mat(imagePoints2); double retVal = stereoCalibrate_2(objectPoints_mat.nativeObj, imagePoints1_mat.nativeObj, imagePoints2_mat.nativeObj, cameraMatrix1.nativeObj, distCoeffs1.nativeObj, cameraMatrix2.nativeObj, distCoeffs2.nativeObj, imageSize.width, imageSize.height, R.nativeObj, T.nativeObj, E.nativeObj, F.nativeObj); return retVal; } // // C++: double calibrate(vector_Mat objectPoints, vector_Mat imagePoints, Size image_size, Mat& K, Mat& D, vector_Mat& rvecs, vector_Mat& tvecs, int flags = 0, TermCriteria criteria = TermCriteria(TermCriteria::COUNT + TermCriteria::EPS, 100, DBL_EPSILON)) // //javadoc: calibrate(objectPoints, imagePoints, image_size, K, D, rvecs, tvecs, flags, criteria) public static double calibrate(List<Mat> objectPoints, List<Mat> imagePoints, Size image_size, Mat K, Mat D, List<Mat> rvecs, List<Mat> tvecs, int flags, TermCriteria criteria) { Mat objectPoints_mat = Converters.vector_Mat_to_Mat(objectPoints); Mat imagePoints_mat = Converters.vector_Mat_to_Mat(imagePoints); Mat rvecs_mat = new Mat(); Mat tvecs_mat = new Mat(); double retVal = calibrate_0(objectPoints_mat.nativeObj, imagePoints_mat.nativeObj, image_size.width, image_size.height, K.nativeObj, D.nativeObj, rvecs_mat.nativeObj, tvecs_mat.nativeObj, flags, criteria.type, criteria.maxCount, criteria.epsilon); Converters.Mat_to_vector_Mat(rvecs_mat, rvecs); rvecs_mat.release(); Converters.Mat_to_vector_Mat(tvecs_mat, tvecs); tvecs_mat.release(); return retVal; } //javadoc: calibrate(objectPoints, imagePoints, image_size, K, D, rvecs, tvecs, flags) public static double calibrate(List<Mat> objectPoints, List<Mat> imagePoints, Size image_size, Mat K, Mat D, List<Mat> rvecs, List<Mat> tvecs, int flags) { Mat objectPoints_mat = Converters.vector_Mat_to_Mat(objectPoints); Mat imagePoints_mat = Converters.vector_Mat_to_Mat(imagePoints); Mat rvecs_mat = new Mat(); Mat tvecs_mat = new Mat(); double retVal = calibrate_1(objectPoints_mat.nativeObj, imagePoints_mat.nativeObj, image_size.width, image_size.height, K.nativeObj, D.nativeObj, rvecs_mat.nativeObj, tvecs_mat.nativeObj, flags); Converters.Mat_to_vector_Mat(rvecs_mat, rvecs); rvecs_mat.release(); Converters.Mat_to_vector_Mat(tvecs_mat, tvecs); tvecs_mat.release(); return retVal; } //javadoc: calibrate(objectPoints, imagePoints, image_size, K, D, rvecs, tvecs) public static double calibrate(List<Mat> objectPoints, List<Mat> imagePoints, Size image_size, Mat K, Mat D, List<Mat> rvecs, List<Mat> tvecs) { Mat objectPoints_mat = Converters.vector_Mat_to_Mat(objectPoints); Mat imagePoints_mat = Converters.vector_Mat_to_Mat(imagePoints); Mat rvecs_mat = new Mat(); Mat tvecs_mat = new Mat(); double retVal = calibrate_2(objectPoints_mat.nativeObj, imagePoints_mat.nativeObj, image_size.width, image_size.height, K.nativeObj, D.nativeObj, rvecs_mat.nativeObj, tvecs_mat.nativeObj); Converters.Mat_to_vector_Mat(rvecs_mat, rvecs); rvecs_mat.release(); Converters.Mat_to_vector_Mat(tvecs_mat, tvecs); tvecs_mat.release(); return retVal; } // // C++: double stereoCalibrate(vector_Mat objectPoints, vector_Mat imagePoints1, vector_Mat imagePoints2, Mat& K1, Mat& D1, Mat& K2, Mat& D2, Size imageSize, Mat& R, Mat& T, int flags = fisheye::CALIB_FIX_INTRINSIC, TermCriteria criteria = TermCriteria(TermCriteria::COUNT + TermCriteria::EPS, 100, DBL_EPSILON)) // //javadoc: stereoCalibrate(objectPoints, imagePoints1, imagePoints2, K1, D1, K2, D2, imageSize, R, T, flags, criteria) public static double stereoCalibrate(List<Mat> objectPoints, List<Mat> imagePoints1, List<Mat> imagePoints2, Mat K1, Mat D1, Mat K2, Mat D2, Size imageSize, Mat R, Mat T, int flags, TermCriteria criteria) { Mat objectPoints_mat = Converters.vector_Mat_to_Mat(objectPoints); Mat imagePoints1_mat = Converters.vector_Mat_to_Mat(imagePoints1); Mat imagePoints2_mat = Converters.vector_Mat_to_Mat(imagePoints2); double retVal = stereoCalibrate_3(objectPoints_mat.nativeObj, imagePoints1_mat.nativeObj, imagePoints2_mat.nativeObj, K1.nativeObj, D1.nativeObj, K2.nativeObj, D2.nativeObj, imageSize.width, imageSize.height, R.nativeObj, T.nativeObj, flags, criteria.type, criteria.maxCount, criteria.epsilon); return retVal; } //javadoc: stereoCalibrate(objectPoints, imagePoints1, imagePoints2, K1, D1, K2, D2, imageSize, R, T, flags) public static double stereoCalibrate(List<Mat> objectPoints, List<Mat> imagePoints1, List<Mat> imagePoints2, Mat K1, Mat D1, Mat K2, Mat D2, Size imageSize, Mat R, Mat T, int flags) { Mat objectPoints_mat = Converters.vector_Mat_to_Mat(objectPoints); Mat imagePoints1_mat = Converters.vector_Mat_to_Mat(imagePoints1); Mat imagePoints2_mat = Converters.vector_Mat_to_Mat(imagePoints2); double retVal = stereoCalibrate_4(objectPoints_mat.nativeObj, imagePoints1_mat.nativeObj, imagePoints2_mat.nativeObj, K1.nativeObj, D1.nativeObj, K2.nativeObj, D2.nativeObj, imageSize.width, imageSize.height, R.nativeObj, T.nativeObj, flags); return retVal; } //javadoc: stereoCalibrate(objectPoints, imagePoints1, imagePoints2, K1, D1, K2, D2, imageSize, R, T) public static double stereoCalibrate(List<Mat> objectPoints, List<Mat> imagePoints1, List<Mat> imagePoints2, Mat K1, Mat D1, Mat K2, Mat D2, Size imageSize, Mat R, Mat T) { Mat objectPoints_mat = Converters.vector_Mat_to_Mat(objectPoints); Mat imagePoints1_mat = Converters.vector_Mat_to_Mat(imagePoints1); Mat imagePoints2_mat = Converters.vector_Mat_to_Mat(imagePoints2); double retVal = stereoCalibrate_5(objectPoints_mat.nativeObj, imagePoints1_mat.nativeObj, imagePoints2_mat.nativeObj, K1.nativeObj, D1.nativeObj, K2.nativeObj, D2.nativeObj, imageSize.width, imageSize.height, R.nativeObj, T.nativeObj); return retVal; } // // C++: float rectify3Collinear(Mat cameraMatrix1, Mat distCoeffs1, Mat cameraMatrix2, Mat distCoeffs2, Mat cameraMatrix3, Mat distCoeffs3, vector_Mat imgpt1, vector_Mat imgpt3, Size imageSize, Mat R12, Mat T12, Mat R13, Mat T13, Mat& R1, Mat& R2, Mat& R3, Mat& P1, Mat& P2, Mat& P3, Mat& Q, double alpha, Size newImgSize, Rect* roi1, Rect* roi2, int flags) // //javadoc: rectify3Collinear(cameraMatrix1, distCoeffs1, cameraMatrix2, distCoeffs2, cameraMatrix3, distCoeffs3, imgpt1, imgpt3, imageSize, R12, T12, R13, T13, R1, R2, R3, P1, P2, P3, Q, alpha, newImgSize, roi1, roi2, flags) public static float rectify3Collinear(Mat cameraMatrix1, Mat distCoeffs1, Mat cameraMatrix2, Mat distCoeffs2, Mat cameraMatrix3, Mat distCoeffs3, List<Mat> imgpt1, List<Mat> imgpt3, Size imageSize, Mat R12, Mat T12, Mat R13, Mat T13, Mat R1, Mat R2, Mat R3, Mat P1, Mat P2, Mat P3, Mat Q, double alpha, Size newImgSize, Rect roi1, Rect roi2, int flags) { Mat imgpt1_mat = Converters.vector_Mat_to_Mat(imgpt1); Mat imgpt3_mat = Converters.vector_Mat_to_Mat(imgpt3); double[] roi1_out = new double[4]; double[] roi2_out = new double[4]; float retVal = rectify3Collinear_0(cameraMatrix1.nativeObj, distCoeffs1.nativeObj, cameraMatrix2.nativeObj, distCoeffs2.nativeObj, cameraMatrix3.nativeObj, distCoeffs3.nativeObj, imgpt1_mat.nativeObj, imgpt3_mat.nativeObj, imageSize.width, imageSize.height, R12.nativeObj, T12.nativeObj, R13.nativeObj, T13.nativeObj, R1.nativeObj, R2.nativeObj, R3.nativeObj, P1.nativeObj, P2.nativeObj, P3.nativeObj, Q.nativeObj, alpha, newImgSize.width, newImgSize.height, roi1_out, roi2_out, flags); if(roi1!=null){ roi1.x = (int)roi1_out[0]; roi1.y = (int)roi1_out[1]; roi1.width = (int)roi1_out[2]; roi1.height = (int)roi1_out[3]; } if(roi2!=null){ roi2.x = (int)roi2_out[0]; roi2.y = (int)roi2_out[1]; roi2.width = (int)roi2_out[2]; roi2.height = (int)roi2_out[3]; } return retVal; } // // C++: int decomposeHomographyMat(Mat H, Mat K, vector_Mat& rotations, vector_Mat& translations, vector_Mat& normals) // //javadoc: decomposeHomographyMat(H, K, rotations, translations, normals) public static int decomposeHomographyMat(Mat H, Mat K, List<Mat> rotations, List<Mat> translations, List<Mat> normals) { Mat rotations_mat = new Mat(); Mat translations_mat = new Mat(); Mat normals_mat = new Mat(); int retVal = decomposeHomographyMat_0(H.nativeObj, K.nativeObj, rotations_mat.nativeObj, translations_mat.nativeObj, normals_mat.nativeObj); Converters.Mat_to_vector_Mat(rotations_mat, rotations); rotations_mat.release(); Converters.Mat_to_vector_Mat(translations_mat, translations); translations_mat.release(); Converters.Mat_to_vector_Mat(normals_mat, normals); normals_mat.release(); return retVal; } // // C++: int estimateAffine3D(Mat src, Mat dst, Mat& out, Mat& inliers, double ransacThreshold = 3, double confidence = 0.99) // //javadoc: estimateAffine3D(src, dst, out, inliers, ransacThreshold, confidence) public static int estimateAffine3D(Mat src, Mat dst, Mat out, Mat inliers, double ransacThreshold, double confidence) { int retVal = estimateAffine3D_0(src.nativeObj, dst.nativeObj, out.nativeObj, inliers.nativeObj, ransacThreshold, confidence); return retVal; } //javadoc: estimateAffine3D(src, dst, out, inliers) public static int estimateAffine3D(Mat src, Mat dst, Mat out, Mat inliers) { int retVal = estimateAffine3D_1(src.nativeObj, dst.nativeObj, out.nativeObj, inliers.nativeObj); return retVal; } // // C++: int recoverPose(Mat E, Mat points1, Mat points2, Mat& R, Mat& t, double focal = 1.0, Point2d pp = Point2d(0, 0), Mat& mask = Mat()) // //javadoc: recoverPose(E, points1, points2, R, t, focal, pp, mask) public static int recoverPose(Mat E, Mat points1, Mat points2, Mat R, Mat t, double focal, Point pp, Mat mask) { int retVal = recoverPose_0(E.nativeObj, points1.nativeObj, points2.nativeObj, R.nativeObj, t.nativeObj, focal, pp.x, pp.y, mask.nativeObj); return retVal; } //javadoc: recoverPose(E, points1, points2, R, t, focal, pp) public static int recoverPose(Mat E, Mat points1, Mat points2, Mat R, Mat t, double focal, Point pp) { int retVal = recoverPose_1(E.nativeObj, points1.nativeObj, points2.nativeObj, R.nativeObj, t.nativeObj, focal, pp.x, pp.y); return retVal; } //javadoc: recoverPose(E, points1, points2, R, t) public static int recoverPose(Mat E, Mat points1, Mat points2, Mat R, Mat t) { int retVal = recoverPose_2(E.nativeObj, points1.nativeObj, points2.nativeObj, R.nativeObj, t.nativeObj); return retVal; } // // C++: int recoverPose(Mat E, Mat points1, Mat points2, Mat cameraMatrix, Mat& R, Mat& t, Mat& mask = Mat()) // //javadoc: recoverPose(E, points1, points2, cameraMatrix, R, t, mask) public static int recoverPose(Mat E, Mat points1, Mat points2, Mat cameraMatrix, Mat R, Mat t, Mat mask) { int retVal = recoverPose_3(E.nativeObj, points1.nativeObj, points2.nativeObj, cameraMatrix.nativeObj, R.nativeObj, t.nativeObj, mask.nativeObj); return retVal; } //javadoc: recoverPose(E, points1, points2, cameraMatrix, R, t) public static int recoverPose(Mat E, Mat points1, Mat points2, Mat cameraMatrix, Mat R, Mat t) { int retVal = recoverPose_4(E.nativeObj, points1.nativeObj, points2.nativeObj, cameraMatrix.nativeObj, R.nativeObj, t.nativeObj); return retVal; } // // C++: void Rodrigues(Mat src, Mat& dst, Mat& jacobian = Mat()) // //javadoc: Rodrigues(src, dst, jacobian) public static void Rodrigues(Mat src, Mat dst, Mat jacobian) { Rodrigues_0(src.nativeObj, dst.nativeObj, jacobian.nativeObj); return; } //javadoc: Rodrigues(src, dst) public static void Rodrigues(Mat src, Mat dst) { Rodrigues_1(src.nativeObj, dst.nativeObj); return; } // // C++: void calibrationMatrixValues(Mat cameraMatrix, Size imageSize, double apertureWidth, double apertureHeight, double& fovx, double& fovy, double& focalLength, Point2d& principalPoint, double& aspectRatio) // //javadoc: calibrationMatrixValues(cameraMatrix, imageSize, apertureWidth, apertureHeight, fovx, fovy, focalLength, principalPoint, aspectRatio) public static void calibrationMatrixValues(Mat cameraMatrix, Size imageSize, double apertureWidth, double apertureHeight, double[] fovx, double[] fovy, double[] focalLength, Point principalPoint, double[] aspectRatio) { double[] fovx_out = new double[1]; double[] fovy_out = new double[1]; double[] focalLength_out = new double[1]; double[] principalPoint_out = new double[2]; double[] aspectRatio_out = new double[1]; calibrationMatrixValues_0(cameraMatrix.nativeObj, imageSize.width, imageSize.height, apertureWidth, apertureHeight, fovx_out, fovy_out, focalLength_out, principalPoint_out, aspectRatio_out); if(fovx!=null) fovx[0] = (double)fovx_out[0]; if(fovy!=null) fovy[0] = (double)fovy_out[0]; if(focalLength!=null) focalLength[0] = (double)focalLength_out[0]; if(principalPoint!=null){ principalPoint.x = principalPoint_out[0]; principalPoint.y = principalPoint_out[1]; } if(aspectRatio!=null) aspectRatio[0] = (double)aspectRatio_out[0]; return; } // // C++: void composeRT(Mat rvec1, Mat tvec1, Mat rvec2, Mat tvec2, Mat& rvec3, Mat& tvec3, Mat& dr3dr1 = Mat(), Mat& dr3dt1 = Mat(), Mat& dr3dr2 = Mat(), Mat& dr3dt2 = Mat(), Mat& dt3dr1 = Mat(), Mat& dt3dt1 = Mat(), Mat& dt3dr2 = Mat(), Mat& dt3dt2 = Mat()) // //javadoc: composeRT(rvec1, tvec1, rvec2, tvec2, rvec3, tvec3, dr3dr1, dr3dt1, dr3dr2, dr3dt2, dt3dr1, dt3dt1, dt3dr2, dt3dt2) public static void composeRT(Mat rvec1, Mat tvec1, Mat rvec2, Mat tvec2, Mat rvec3, Mat tvec3, Mat dr3dr1, Mat dr3dt1, Mat dr3dr2, Mat dr3dt2, Mat dt3dr1, Mat dt3dt1, Mat dt3dr2, Mat dt3dt2) { composeRT_0(rvec1.nativeObj, tvec1.nativeObj, rvec2.nativeObj, tvec2.nativeObj, rvec3.nativeObj, tvec3.nativeObj, dr3dr1.nativeObj, dr3dt1.nativeObj, dr3dr2.nativeObj, dr3dt2.nativeObj, dt3dr1.nativeObj, dt3dt1.nativeObj, dt3dr2.nativeObj, dt3dt2.nativeObj); return; } //javadoc: composeRT(rvec1, tvec1, rvec2, tvec2, rvec3, tvec3) public static void composeRT(Mat rvec1, Mat tvec1, Mat rvec2, Mat tvec2, Mat rvec3, Mat tvec3) { composeRT_1(rvec1.nativeObj, tvec1.nativeObj, rvec2.nativeObj, tvec2.nativeObj, rvec3.nativeObj, tvec3.nativeObj); return; } // // C++: void computeCorrespondEpilines(Mat points, int whichImage, Mat F, Mat& lines) // //javadoc: computeCorrespondEpilines(points, whichImage, F, lines) public static void computeCorrespondEpilines(Mat points, int whichImage, Mat F, Mat lines) { computeCorrespondEpilines_0(points.nativeObj, whichImage, F.nativeObj, lines.nativeObj); return; } // // C++: void convertPointsFromHomogeneous(Mat src, Mat& dst) // //javadoc: convertPointsFromHomogeneous(src, dst) public static void convertPointsFromHomogeneous(Mat src, Mat dst) { convertPointsFromHomogeneous_0(src.nativeObj, dst.nativeObj); return; } // // C++: void convertPointsToHomogeneous(Mat src, Mat& dst) // //javadoc: convertPointsToHomogeneous(src, dst) public static void convertPointsToHomogeneous(Mat src, Mat dst) { convertPointsToHomogeneous_0(src.nativeObj, dst.nativeObj); return; } // // C++: void correctMatches(Mat F, Mat points1, Mat points2, Mat& newPoints1, Mat& newPoints2) // //javadoc: correctMatches(F, points1, points2, newPoints1, newPoints2) public static void correctMatches(Mat F, Mat points1, Mat points2, Mat newPoints1, Mat newPoints2) { correctMatches_0(F.nativeObj, points1.nativeObj, points2.nativeObj, newPoints1.nativeObj, newPoints2.nativeObj); return; } // // C++: void decomposeEssentialMat(Mat E, Mat& R1, Mat& R2, Mat& t) // //javadoc: decomposeEssentialMat(E, R1, R2, t) public static void decomposeEssentialMat(Mat E, Mat R1, Mat R2, Mat t) { decomposeEssentialMat_0(E.nativeObj, R1.nativeObj, R2.nativeObj, t.nativeObj); return; } // // C++: void decomposeProjectionMatrix(Mat projMatrix, Mat& cameraMatrix, Mat& rotMatrix, Mat& transVect, Mat& rotMatrixX = Mat(), Mat& rotMatrixY = Mat(), Mat& rotMatrixZ = Mat(), Mat& eulerAngles = Mat()) // //javadoc: decomposeProjectionMatrix(projMatrix, cameraMatrix, rotMatrix, transVect, rotMatrixX, rotMatrixY, rotMatrixZ, eulerAngles) public static void decomposeProjectionMatrix(Mat projMatrix, Mat cameraMatrix, Mat rotMatrix, Mat transVect, Mat rotMatrixX, Mat rotMatrixY, Mat rotMatrixZ, Mat eulerAngles) { decomposeProjectionMatrix_0(projMatrix.nativeObj, cameraMatrix.nativeObj, rotMatrix.nativeObj, transVect.nativeObj, rotMatrixX.nativeObj, rotMatrixY.nativeObj, rotMatrixZ.nativeObj, eulerAngles.nativeObj); return; } //javadoc: decomposeProjectionMatrix(projMatrix, cameraMatrix, rotMatrix, transVect) public static void decomposeProjectionMatrix(Mat projMatrix, Mat cameraMatrix, Mat rotMatrix, Mat transVect) { decomposeProjectionMatrix_1(projMatrix.nativeObj, cameraMatrix.nativeObj, rotMatrix.nativeObj, transVect.nativeObj); return; } // // C++: void drawChessboardCorners(Mat& image, Size patternSize, vector_Point2f corners, bool patternWasFound) // //javadoc: drawChessboardCorners(image, patternSize, corners, patternWasFound) public static void drawChessboardCorners(Mat image, Size patternSize, MatOfPoint2f corners, boolean patternWasFound) { Mat corners_mat = corners; drawChessboardCorners_0(image.nativeObj, patternSize.width, patternSize.height, corners_mat.nativeObj, patternWasFound); return; } // // C++: void filterSpeckles(Mat& img, double newVal, int maxSpeckleSize, double maxDiff, Mat& buf = Mat()) // //javadoc: filterSpeckles(img, newVal, maxSpeckleSize, maxDiff, buf) public static void filterSpeckles(Mat img, double newVal, int maxSpeckleSize, double maxDiff, Mat buf) { filterSpeckles_0(img.nativeObj, newVal, maxSpeckleSize, maxDiff, buf.nativeObj); return; } //javadoc: filterSpeckles(img, newVal, maxSpeckleSize, maxDiff) public static void filterSpeckles(Mat img, double newVal, int maxSpeckleSize, double maxDiff) { filterSpeckles_1(img.nativeObj, newVal, maxSpeckleSize, maxDiff); return; } // // C++: void matMulDeriv(Mat A, Mat B, Mat& dABdA, Mat& dABdB) // //javadoc: matMulDeriv(A, B, dABdA, dABdB) public static void matMulDeriv(Mat A, Mat B, Mat dABdA, Mat dABdB) { matMulDeriv_0(A.nativeObj, B.nativeObj, dABdA.nativeObj, dABdB.nativeObj); return; } // // C++: void projectPoints(vector_Point3f objectPoints, Mat rvec, Mat tvec, Mat cameraMatrix, vector_double distCoeffs, vector_Point2f& imagePoints, Mat& jacobian = Mat(), double aspectRatio = 0) // //javadoc: projectPoints(objectPoints, rvec, tvec, cameraMatrix, distCoeffs, imagePoints, jacobian, aspectRatio) public static void projectPoints(MatOfPoint3f objectPoints, Mat rvec, Mat tvec, Mat cameraMatrix, MatOfDouble distCoeffs, MatOfPoint2f imagePoints, Mat jacobian, double aspectRatio) { Mat objectPoints_mat = objectPoints; Mat distCoeffs_mat = distCoeffs; Mat imagePoints_mat = imagePoints; projectPoints_0(objectPoints_mat.nativeObj, rvec.nativeObj, tvec.nativeObj, cameraMatrix.nativeObj, distCoeffs_mat.nativeObj, imagePoints_mat.nativeObj, jacobian.nativeObj, aspectRatio); return; } //javadoc: projectPoints(objectPoints, rvec, tvec, cameraMatrix, distCoeffs, imagePoints) public static void projectPoints(MatOfPoint3f objectPoints, Mat rvec, Mat tvec, Mat cameraMatrix, MatOfDouble distCoeffs, MatOfPoint2f imagePoints) { Mat objectPoints_mat = objectPoints; Mat distCoeffs_mat = distCoeffs; Mat imagePoints_mat = imagePoints; projectPoints_1(objectPoints_mat.nativeObj, rvec.nativeObj, tvec.nativeObj, cameraMatrix.nativeObj, distCoeffs_mat.nativeObj, imagePoints_mat.nativeObj); return; } // // C++: void reprojectImageTo3D(Mat disparity, Mat& _3dImage, Mat Q, bool handleMissingValues = false, int ddepth = -1) // //javadoc: reprojectImageTo3D(disparity, _3dImage, Q, handleMissingValues, ddepth) public static void reprojectImageTo3D(Mat disparity, Mat _3dImage, Mat Q, boolean handleMissingValues, int ddepth) { reprojectImageTo3D_0(disparity.nativeObj, _3dImage.nativeObj, Q.nativeObj, handleMissingValues, ddepth); return; } //javadoc: reprojectImageTo3D(disparity, _3dImage, Q, handleMissingValues) public static void reprojectImageTo3D(Mat disparity, Mat _3dImage, Mat Q, boolean handleMissingValues) { reprojectImageTo3D_1(disparity.nativeObj, _3dImage.nativeObj, Q.nativeObj, handleMissingValues); return; } //javadoc: reprojectImageTo3D(disparity, _3dImage, Q) public static void reprojectImageTo3D(Mat disparity, Mat _3dImage, Mat Q) { reprojectImageTo3D_2(disparity.nativeObj, _3dImage.nativeObj, Q.nativeObj); return; } // // C++: void stereoRectify(Mat cameraMatrix1, Mat distCoeffs1, Mat cameraMatrix2, Mat distCoeffs2, Size imageSize, Mat R, Mat T, Mat& R1, Mat& R2, Mat& P1, Mat& P2, Mat& Q, int flags = CALIB_ZERO_DISPARITY, double alpha = -1, Size newImageSize = Size(), Rect* validPixROI1 = 0, Rect* validPixROI2 = 0) // //javadoc: stereoRectify(cameraMatrix1, distCoeffs1, cameraMatrix2, distCoeffs2, imageSize, R, T, R1, R2, P1, P2, Q, flags, alpha, newImageSize, validPixROI1, validPixROI2) public static void stereoRectify(Mat cameraMatrix1, Mat distCoeffs1, Mat cameraMatrix2, Mat distCoeffs2, Size imageSize, Mat R, Mat T, Mat R1, Mat R2, Mat P1, Mat P2, Mat Q, int flags, double alpha, Size newImageSize, Rect validPixROI1, Rect validPixROI2) { double[] validPixROI1_out = new double[4]; double[] validPixROI2_out = new double[4]; stereoRectify_0(cameraMatrix1.nativeObj, distCoeffs1.nativeObj, cameraMatrix2.nativeObj, distCoeffs2.nativeObj, imageSize.width, imageSize.height, R.nativeObj, T.nativeObj, R1.nativeObj, R2.nativeObj, P1.nativeObj, P2.nativeObj, Q.nativeObj, flags, alpha, newImageSize.width, newImageSize.height, validPixROI1_out, validPixROI2_out); if(validPixROI1!=null){ validPixROI1.x = (int)validPixROI1_out[0]; validPixROI1.y = (int)validPixROI1_out[1]; validPixROI1.width = (int)validPixROI1_out[2]; validPixROI1.height = (int)validPixROI1_out[3]; } if(validPixROI2!=null){ validPixROI2.x = (int)validPixROI2_out[0]; validPixROI2.y = (int)validPixROI2_out[1]; validPixROI2.width = (int)validPixROI2_out[2]; validPixROI2.height = (int)validPixROI2_out[3]; } return; } //javadoc: stereoRectify(cameraMatrix1, distCoeffs1, cameraMatrix2, distCoeffs2, imageSize, R, T, R1, R2, P1, P2, Q) public static void stereoRectify(Mat cameraMatrix1, Mat distCoeffs1, Mat cameraMatrix2, Mat distCoeffs2, Size imageSize, Mat R, Mat T, Mat R1, Mat R2, Mat P1, Mat P2, Mat Q) { stereoRectify_1(cameraMatrix1.nativeObj, distCoeffs1.nativeObj, cameraMatrix2.nativeObj, distCoeffs2.nativeObj, imageSize.width, imageSize.height, R.nativeObj, T.nativeObj, R1.nativeObj, R2.nativeObj, P1.nativeObj, P2.nativeObj, Q.nativeObj); return; } // // C++: void triangulatePoints(Mat projMatr1, Mat projMatr2, Mat projPoints1, Mat projPoints2, Mat& points4D) // //javadoc: triangulatePoints(projMatr1, projMatr2, projPoints1, projPoints2, points4D) public static void triangulatePoints(Mat projMatr1, Mat projMatr2, Mat projPoints1, Mat projPoints2, Mat points4D) { triangulatePoints_0(projMatr1.nativeObj, projMatr2.nativeObj, projPoints1.nativeObj, projPoints2.nativeObj, points4D.nativeObj); return; } // // C++: void validateDisparity(Mat& disparity, Mat cost, int minDisparity, int numberOfDisparities, int disp12MaxDisp = 1) // //javadoc: validateDisparity(disparity, cost, minDisparity, numberOfDisparities, disp12MaxDisp) public static void validateDisparity(Mat disparity, Mat cost, int minDisparity, int numberOfDisparities, int disp12MaxDisp) { validateDisparity_0(disparity.nativeObj, cost.nativeObj, minDisparity, numberOfDisparities, disp12MaxDisp); return; } //javadoc: validateDisparity(disparity, cost, minDisparity, numberOfDisparities) public static void validateDisparity(Mat disparity, Mat cost, int minDisparity, int numberOfDisparities) { validateDisparity_1(disparity.nativeObj, cost.nativeObj, minDisparity, numberOfDisparities); return; } // // C++: void distortPoints(Mat undistorted, Mat& distorted, Mat K, Mat D, double alpha = 0) // //javadoc: distortPoints(undistorted, distorted, K, D, alpha) public static void distortPoints(Mat undistorted, Mat distorted, Mat K, Mat D, double alpha) { distortPoints_0(undistorted.nativeObj, distorted.nativeObj, K.nativeObj, D.nativeObj, alpha); return; } //javadoc: distortPoints(undistorted, distorted, K, D) public static void distortPoints(Mat undistorted, Mat distorted, Mat K, Mat D) { distortPoints_1(undistorted.nativeObj, distorted.nativeObj, K.nativeObj, D.nativeObj); return; } // // C++: void estimateNewCameraMatrixForUndistortRectify(Mat K, Mat D, Size image_size, Mat R, Mat& P, double balance = 0.0, Size new_size = Size(), double fov_scale = 1.0) // //javadoc: estimateNewCameraMatrixForUndistortRectify(K, D, image_size, R, P, balance, new_size, fov_scale) public static void estimateNewCameraMatrixForUndistortRectify(Mat K, Mat D, Size image_size, Mat R, Mat P, double balance, Size new_size, double fov_scale) { estimateNewCameraMatrixForUndistortRectify_0(K.nativeObj, D.nativeObj, image_size.width, image_size.height, R.nativeObj, P.nativeObj, balance, new_size.width, new_size.height, fov_scale); return; } //javadoc: estimateNewCameraMatrixForUndistortRectify(K, D, image_size, R, P) public static void estimateNewCameraMatrixForUndistortRectify(Mat K, Mat D, Size image_size, Mat R, Mat P) { estimateNewCameraMatrixForUndistortRectify_1(K.nativeObj, D.nativeObj, image_size.width, image_size.height, R.nativeObj, P.nativeObj); return; } // // C++: void initUndistortRectifyMap(Mat K, Mat D, Mat R, Mat P, Size size, int m1type, Mat& map1, Mat& map2) // //javadoc: initUndistortRectifyMap(K, D, R, P, size, m1type, map1, map2) public static void initUndistortRectifyMap(Mat K, Mat D, Mat R, Mat P, Size size, int m1type, Mat map1, Mat map2) { initUndistortRectifyMap_0(K.nativeObj, D.nativeObj, R.nativeObj, P.nativeObj, size.width, size.height, m1type, map1.nativeObj, map2.nativeObj); return; } // // C++: void projectPoints(vector_Point3f objectPoints, vector_Point2f& imagePoints, Mat rvec, Mat tvec, Mat K, Mat D, double alpha = 0, Mat& jacobian = Mat()) // //javadoc: projectPoints(objectPoints, imagePoints, rvec, tvec, K, D, alpha, jacobian) public static void projectPoints(MatOfPoint3f objectPoints, MatOfPoint2f imagePoints, Mat rvec, Mat tvec, Mat K, Mat D, double alpha, Mat jacobian) { Mat objectPoints_mat = objectPoints; Mat imagePoints_mat = imagePoints; projectPoints_2(objectPoints_mat.nativeObj, imagePoints_mat.nativeObj, rvec.nativeObj, tvec.nativeObj, K.nativeObj, D.nativeObj, alpha, jacobian.nativeObj); return; } //javadoc: projectPoints(objectPoints, imagePoints, rvec, tvec, K, D) public static void projectPoints(MatOfPoint3f objectPoints, MatOfPoint2f imagePoints, Mat rvec, Mat tvec, Mat K, Mat D) { Mat objectPoints_mat = objectPoints; Mat imagePoints_mat = imagePoints; projectPoints_3(objectPoints_mat.nativeObj, imagePoints_mat.nativeObj, rvec.nativeObj, tvec.nativeObj, K.nativeObj, D.nativeObj); return; } // // C++: void stereoRectify(Mat K1, Mat D1, Mat K2, Mat D2, Size imageSize, Mat R, Mat tvec, Mat& R1, Mat& R2, Mat& P1, Mat& P2, Mat& Q, int flags, Size newImageSize = Size(), double balance = 0.0, double fov_scale = 1.0) // //javadoc: stereoRectify(K1, D1, K2, D2, imageSize, R, tvec, R1, R2, P1, P2, Q, flags, newImageSize, balance, fov_scale) public static void stereoRectify(Mat K1, Mat D1, Mat K2, Mat D2, Size imageSize, Mat R, Mat tvec, Mat R1, Mat R2, Mat P1, Mat P2, Mat Q, int flags, Size newImageSize, double balance, double fov_scale) { stereoRectify_2(K1.nativeObj, D1.nativeObj, K2.nativeObj, D2.nativeObj, imageSize.width, imageSize.height, R.nativeObj, tvec.nativeObj, R1.nativeObj, R2.nativeObj, P1.nativeObj, P2.nativeObj, Q.nativeObj, flags, newImageSize.width, newImageSize.height, balance, fov_scale); return; } //javadoc: stereoRectify(K1, D1, K2, D2, imageSize, R, tvec, R1, R2, P1, P2, Q, flags) public static void stereoRectify(Mat K1, Mat D1, Mat K2, Mat D2, Size imageSize, Mat R, Mat tvec, Mat R1, Mat R2, Mat P1, Mat P2, Mat Q, int flags) { stereoRectify_3(K1.nativeObj, D1.nativeObj, K2.nativeObj, D2.nativeObj, imageSize.width, imageSize.height, R.nativeObj, tvec.nativeObj, R1.nativeObj, R2.nativeObj, P1.nativeObj, P2.nativeObj, Q.nativeObj, flags); return; } // // C++: void undistortImage(Mat distorted, Mat& undistorted, Mat K, Mat D, Mat Knew = cv::Mat(), Size new_size = Size()) // //javadoc: undistortImage(distorted, undistorted, K, D, Knew, new_size) public static void undistortImage(Mat distorted, Mat undistorted, Mat K, Mat D, Mat Knew, Size new_size) { undistortImage_0(distorted.nativeObj, undistorted.nativeObj, K.nativeObj, D.nativeObj, Knew.nativeObj, new_size.width, new_size.height); return; } //javadoc: undistortImage(distorted, undistorted, K, D) public static void undistortImage(Mat distorted, Mat undistorted, Mat K, Mat D) { undistortImage_1(distorted.nativeObj, undistorted.nativeObj, K.nativeObj, D.nativeObj); return; } // // C++: void undistortPoints(Mat distorted, Mat& undistorted, Mat K, Mat D, Mat R = Mat(), Mat P = Mat()) // //javadoc: undistortPoints(distorted, undistorted, K, D, R, P) public static void undistortPoints(Mat distorted, Mat undistorted, Mat K, Mat D, Mat R, Mat P) { undistortPoints_0(distorted.nativeObj, undistorted.nativeObj, K.nativeObj, D.nativeObj, R.nativeObj, P.nativeObj); return; } //javadoc: undistortPoints(distorted, undistorted, K, D) public static void undistortPoints(Mat distorted, Mat undistorted, Mat K, Mat D) { undistortPoints_1(distorted.nativeObj, undistorted.nativeObj, K.nativeObj, D.nativeObj); return; } // C++: Mat findEssentialMat(Mat points1, Mat points2, Mat cameraMatrix, int method = RANSAC, double prob = 0.999, double threshold = 1.0, Mat& mask = Mat()) private static native long findEssentialMat_0(long points1_nativeObj, long points2_nativeObj, long cameraMatrix_nativeObj, int method, double prob, double threshold, long mask_nativeObj); private static native long findEssentialMat_1(long points1_nativeObj, long points2_nativeObj, long cameraMatrix_nativeObj, int method, double prob, double threshold); private static native long findEssentialMat_2(long points1_nativeObj, long points2_nativeObj, long cameraMatrix_nativeObj); // C++: Mat findEssentialMat(Mat points1, Mat points2, double focal = 1.0, Point2d pp = Point2d(0, 0), int method = RANSAC, double prob = 0.999, double threshold = 1.0, Mat& mask = Mat()) private static native long findEssentialMat_3(long points1_nativeObj, long points2_nativeObj, double focal, double pp_x, double pp_y, int method, double prob, double threshold, long mask_nativeObj); private static native long findEssentialMat_4(long points1_nativeObj, long points2_nativeObj, double focal, double pp_x, double pp_y, int method, double prob, double threshold); private static native long findEssentialMat_5(long points1_nativeObj, long points2_nativeObj); // C++: Mat findFundamentalMat(vector_Point2f points1, vector_Point2f points2, int method = FM_RANSAC, double param1 = 3., double param2 = 0.99, Mat& mask = Mat()) private static native long findFundamentalMat_0(long points1_mat_nativeObj, long points2_mat_nativeObj, int method, double param1, double param2, long mask_nativeObj); private static native long findFundamentalMat_1(long points1_mat_nativeObj, long points2_mat_nativeObj, int method, double param1, double param2); private static native long findFundamentalMat_2(long points1_mat_nativeObj, long points2_mat_nativeObj); // C++: Mat findHomography(vector_Point2f srcPoints, vector_Point2f dstPoints, int method = 0, double ransacReprojThreshold = 3, Mat& mask = Mat(), int maxIters = 2000, double confidence = 0.995) private static native long findHomography_0(long srcPoints_mat_nativeObj, long dstPoints_mat_nativeObj, int method, double ransacReprojThreshold, long mask_nativeObj, int maxIters, double confidence); private static native long findHomography_1(long srcPoints_mat_nativeObj, long dstPoints_mat_nativeObj, int method, double ransacReprojThreshold); private static native long findHomography_2(long srcPoints_mat_nativeObj, long dstPoints_mat_nativeObj); // C++: Mat getOptimalNewCameraMatrix(Mat cameraMatrix, Mat distCoeffs, Size imageSize, double alpha, Size newImgSize = Size(), Rect* validPixROI = 0, bool centerPrincipalPoint = false) private static native long getOptimalNewCameraMatrix_0(long cameraMatrix_nativeObj, long distCoeffs_nativeObj, double imageSize_width, double imageSize_height, double alpha, double newImgSize_width, double newImgSize_height, double[] validPixROI_out, boolean centerPrincipalPoint); private static native long getOptimalNewCameraMatrix_1(long cameraMatrix_nativeObj, long distCoeffs_nativeObj, double imageSize_width, double imageSize_height, double alpha); // C++: Mat initCameraMatrix2D(vector_vector_Point3f objectPoints, vector_vector_Point2f imagePoints, Size imageSize, double aspectRatio = 1.0) private static native long initCameraMatrix2D_0(long objectPoints_mat_nativeObj, long imagePoints_mat_nativeObj, double imageSize_width, double imageSize_height, double aspectRatio); private static native long initCameraMatrix2D_1(long objectPoints_mat_nativeObj, long imagePoints_mat_nativeObj, double imageSize_width, double imageSize_height); // C++: Rect getValidDisparityROI(Rect roi1, Rect roi2, int minDisparity, int numberOfDisparities, int SADWindowSize) private static native double[] getValidDisparityROI_0(int roi1_x, int roi1_y, int roi1_width, int roi1_height, int roi2_x, int roi2_y, int roi2_width, int roi2_height, int minDisparity, int numberOfDisparities, int SADWindowSize); // C++: Vec3d RQDecomp3x3(Mat src, Mat& mtxR, Mat& mtxQ, Mat& Qx = Mat(), Mat& Qy = Mat(), Mat& Qz = Mat()) private static native double[] RQDecomp3x3_0(long src_nativeObj, long mtxR_nativeObj, long mtxQ_nativeObj, long Qx_nativeObj, long Qy_nativeObj, long Qz_nativeObj); private static native double[] RQDecomp3x3_1(long src_nativeObj, long mtxR_nativeObj, long mtxQ_nativeObj); // C++: bool findChessboardCorners(Mat image, Size patternSize, vector_Point2f& corners, int flags = CALIB_CB_ADAPTIVE_THRESH + CALIB_CB_NORMALIZE_IMAGE) private static native boolean findChessboardCorners_0(long image_nativeObj, double patternSize_width, double patternSize_height, long corners_mat_nativeObj, int flags); private static native boolean findChessboardCorners_1(long image_nativeObj, double patternSize_width, double patternSize_height, long corners_mat_nativeObj); // C++: bool findCirclesGrid(Mat image, Size patternSize, Mat& centers, int flags = CALIB_CB_SYMMETRIC_GRID, Ptr_FeatureDetector blobDetector = SimpleBlobDetector::create()) private static native boolean findCirclesGrid_0(long image_nativeObj, double patternSize_width, double patternSize_height, long centers_nativeObj, int flags); private static native boolean findCirclesGrid_1(long image_nativeObj, double patternSize_width, double patternSize_height, long centers_nativeObj); // C++: bool solvePnP(vector_Point3f objectPoints, vector_Point2f imagePoints, Mat cameraMatrix, vector_double distCoeffs, Mat& rvec, Mat& tvec, bool useExtrinsicGuess = false, int flags = SOLVEPNP_ITERATIVE) private static native boolean solvePnP_0(long objectPoints_mat_nativeObj, long imagePoints_mat_nativeObj, long cameraMatrix_nativeObj, long distCoeffs_mat_nativeObj, long rvec_nativeObj, long tvec_nativeObj, boolean useExtrinsicGuess, int flags); private static native boolean solvePnP_1(long objectPoints_mat_nativeObj, long imagePoints_mat_nativeObj, long cameraMatrix_nativeObj, long distCoeffs_mat_nativeObj, long rvec_nativeObj, long tvec_nativeObj); // C++: bool solvePnPRansac(vector_Point3f objectPoints, vector_Point2f imagePoints, Mat cameraMatrix, vector_double distCoeffs, Mat& rvec, Mat& tvec, bool useExtrinsicGuess = false, int iterationsCount = 100, float reprojectionError = 8.0, double confidence = 0.99, Mat& inliers = Mat(), int flags = SOLVEPNP_ITERATIVE) private static native boolean solvePnPRansac_0(long objectPoints_mat_nativeObj, long imagePoints_mat_nativeObj, long cameraMatrix_nativeObj, long distCoeffs_mat_nativeObj, long rvec_nativeObj, long tvec_nativeObj, boolean useExtrinsicGuess, int iterationsCount, float reprojectionError, double confidence, long inliers_nativeObj, int flags); private static native boolean solvePnPRansac_1(long objectPoints_mat_nativeObj, long imagePoints_mat_nativeObj, long cameraMatrix_nativeObj, long distCoeffs_mat_nativeObj, long rvec_nativeObj, long tvec_nativeObj); // C++: bool stereoRectifyUncalibrated(Mat points1, Mat points2, Mat F, Size imgSize, Mat& H1, Mat& H2, double threshold = 5) private static native boolean stereoRectifyUncalibrated_0(long points1_nativeObj, long points2_nativeObj, long F_nativeObj, double imgSize_width, double imgSize_height, long H1_nativeObj, long H2_nativeObj, double threshold); private static native boolean stereoRectifyUncalibrated_1(long points1_nativeObj, long points2_nativeObj, long F_nativeObj, double imgSize_width, double imgSize_height, long H1_nativeObj, long H2_nativeObj); // C++: double calibrateCamera(vector_Mat objectPoints, vector_Mat imagePoints, Size imageSize, Mat& cameraMatrix, Mat& distCoeffs, vector_Mat& rvecs, vector_Mat& tvecs, int flags = 0, TermCriteria criteria = TermCriteria( TermCriteria::COUNT + TermCriteria::EPS, 30, DBL_EPSILON)) private static native double calibrateCamera_0(long objectPoints_mat_nativeObj, long imagePoints_mat_nativeObj, double imageSize_width, double imageSize_height, long cameraMatrix_nativeObj, long distCoeffs_nativeObj, long rvecs_mat_nativeObj, long tvecs_mat_nativeObj, int flags, int criteria_type, int criteria_maxCount, double criteria_epsilon); private static native double calibrateCamera_1(long objectPoints_mat_nativeObj, long imagePoints_mat_nativeObj, double imageSize_width, double imageSize_height, long cameraMatrix_nativeObj, long distCoeffs_nativeObj, long rvecs_mat_nativeObj, long tvecs_mat_nativeObj, int flags); private static native double calibrateCamera_2(long objectPoints_mat_nativeObj, long imagePoints_mat_nativeObj, double imageSize_width, double imageSize_height, long cameraMatrix_nativeObj, long distCoeffs_nativeObj, long rvecs_mat_nativeObj, long tvecs_mat_nativeObj); // C++: double sampsonDistance(Mat pt1, Mat pt2, Mat F) private static native double sampsonDistance_0(long pt1_nativeObj, long pt2_nativeObj, long F_nativeObj); // C++: double stereoCalibrate(vector_Mat objectPoints, vector_Mat imagePoints1, vector_Mat imagePoints2, Mat& cameraMatrix1, Mat& distCoeffs1, Mat& cameraMatrix2, Mat& distCoeffs2, Size imageSize, Mat& R, Mat& T, Mat& E, Mat& F, int flags = CALIB_FIX_INTRINSIC, TermCriteria criteria = TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 1e-6)) private static native double stereoCalibrate_0(long objectPoints_mat_nativeObj, long imagePoints1_mat_nativeObj, long imagePoints2_mat_nativeObj, long cameraMatrix1_nativeObj, long distCoeffs1_nativeObj, long cameraMatrix2_nativeObj, long distCoeffs2_nativeObj, double imageSize_width, double imageSize_height, long R_nativeObj, long T_nativeObj, long E_nativeObj, long F_nativeObj, int flags, int criteria_type, int criteria_maxCount, double criteria_epsilon); private static native double stereoCalibrate_1(long objectPoints_mat_nativeObj, long imagePoints1_mat_nativeObj, long imagePoints2_mat_nativeObj, long cameraMatrix1_nativeObj, long distCoeffs1_nativeObj, long cameraMatrix2_nativeObj, long distCoeffs2_nativeObj, double imageSize_width, double imageSize_height, long R_nativeObj, long T_nativeObj, long E_nativeObj, long F_nativeObj, int flags); private static native double stereoCalibrate_2(long objectPoints_mat_nativeObj, long imagePoints1_mat_nativeObj, long imagePoints2_mat_nativeObj, long cameraMatrix1_nativeObj, long distCoeffs1_nativeObj, long cameraMatrix2_nativeObj, long distCoeffs2_nativeObj, double imageSize_width, double imageSize_height, long R_nativeObj, long T_nativeObj, long E_nativeObj, long F_nativeObj); // C++: double calibrate(vector_Mat objectPoints, vector_Mat imagePoints, Size image_size, Mat& K, Mat& D, vector_Mat& rvecs, vector_Mat& tvecs, int flags = 0, TermCriteria criteria = TermCriteria(TermCriteria::COUNT + TermCriteria::EPS, 100, DBL_EPSILON)) private static native double calibrate_0(long objectPoints_mat_nativeObj, long imagePoints_mat_nativeObj, double image_size_width, double image_size_height, long K_nativeObj, long D_nativeObj, long rvecs_mat_nativeObj, long tvecs_mat_nativeObj, int flags, int criteria_type, int criteria_maxCount, double criteria_epsilon); private static native double calibrate_1(long objectPoints_mat_nativeObj, long imagePoints_mat_nativeObj, double image_size_width, double image_size_height, long K_nativeObj, long D_nativeObj, long rvecs_mat_nativeObj, long tvecs_mat_nativeObj, int flags); private static native double calibrate_2(long objectPoints_mat_nativeObj, long imagePoints_mat_nativeObj, double image_size_width, double image_size_height, long K_nativeObj, long D_nativeObj, long rvecs_mat_nativeObj, long tvecs_mat_nativeObj); // C++: double stereoCalibrate(vector_Mat objectPoints, vector_Mat imagePoints1, vector_Mat imagePoints2, Mat& K1, Mat& D1, Mat& K2, Mat& D2, Size imageSize, Mat& R, Mat& T, int flags = fisheye::CALIB_FIX_INTRINSIC, TermCriteria criteria = TermCriteria(TermCriteria::COUNT + TermCriteria::EPS, 100, DBL_EPSILON)) private static native double stereoCalibrate_3(long objectPoints_mat_nativeObj, long imagePoints1_mat_nativeObj, long imagePoints2_mat_nativeObj, long K1_nativeObj, long D1_nativeObj, long K2_nativeObj, long D2_nativeObj, double imageSize_width, double imageSize_height, long R_nativeObj, long T_nativeObj, int flags, int criteria_type, int criteria_maxCount, double criteria_epsilon); private static native double stereoCalibrate_4(long objectPoints_mat_nativeObj, long imagePoints1_mat_nativeObj, long imagePoints2_mat_nativeObj, long K1_nativeObj, long D1_nativeObj, long K2_nativeObj, long D2_nativeObj, double imageSize_width, double imageSize_height, long R_nativeObj, long T_nativeObj, int flags); private static native double stereoCalibrate_5(long objectPoints_mat_nativeObj, long imagePoints1_mat_nativeObj, long imagePoints2_mat_nativeObj, long K1_nativeObj, long D1_nativeObj, long K2_nativeObj, long D2_nativeObj, double imageSize_width, double imageSize_height, long R_nativeObj, long T_nativeObj); // C++: float rectify3Collinear(Mat cameraMatrix1, Mat distCoeffs1, Mat cameraMatrix2, Mat distCoeffs2, Mat cameraMatrix3, Mat distCoeffs3, vector_Mat imgpt1, vector_Mat imgpt3, Size imageSize, Mat R12, Mat T12, Mat R13, Mat T13, Mat& R1, Mat& R2, Mat& R3, Mat& P1, Mat& P2, Mat& P3, Mat& Q, double alpha, Size newImgSize, Rect* roi1, Rect* roi2, int flags) private static native float rectify3Collinear_0(long cameraMatrix1_nativeObj, long distCoeffs1_nativeObj, long cameraMatrix2_nativeObj, long distCoeffs2_nativeObj, long cameraMatrix3_nativeObj, long distCoeffs3_nativeObj, long imgpt1_mat_nativeObj, long imgpt3_mat_nativeObj, double imageSize_width, double imageSize_height, long R12_nativeObj, long T12_nativeObj, long R13_nativeObj, long T13_nativeObj, long R1_nativeObj, long R2_nativeObj, long R3_nativeObj, long P1_nativeObj, long P2_nativeObj, long P3_nativeObj, long Q_nativeObj, double alpha, double newImgSize_width, double newImgSize_height, double[] roi1_out, double[] roi2_out, int flags); // C++: int decomposeHomographyMat(Mat H, Mat K, vector_Mat& rotations, vector_Mat& translations, vector_Mat& normals) private static native int decomposeHomographyMat_0(long H_nativeObj, long K_nativeObj, long rotations_mat_nativeObj, long translations_mat_nativeObj, long normals_mat_nativeObj); // C++: int estimateAffine3D(Mat src, Mat dst, Mat& out, Mat& inliers, double ransacThreshold = 3, double confidence = 0.99) private static native int estimateAffine3D_0(long src_nativeObj, long dst_nativeObj, long out_nativeObj, long inliers_nativeObj, double ransacThreshold, double confidence); private static native int estimateAffine3D_1(long src_nativeObj, long dst_nativeObj, long out_nativeObj, long inliers_nativeObj); // C++: int recoverPose(Mat E, Mat points1, Mat points2, Mat& R, Mat& t, double focal = 1.0, Point2d pp = Point2d(0, 0), Mat& mask = Mat()) private static native int recoverPose_0(long E_nativeObj, long points1_nativeObj, long points2_nativeObj, long R_nativeObj, long t_nativeObj, double focal, double pp_x, double pp_y, long mask_nativeObj); private static native int recoverPose_1(long E_nativeObj, long points1_nativeObj, long points2_nativeObj, long R_nativeObj, long t_nativeObj, double focal, double pp_x, double pp_y); private static native int recoverPose_2(long E_nativeObj, long points1_nativeObj, long points2_nativeObj, long R_nativeObj, long t_nativeObj); // C++: int recoverPose(Mat E, Mat points1, Mat points2, Mat cameraMatrix, Mat& R, Mat& t, Mat& mask = Mat()) private static native int recoverPose_3(long E_nativeObj, long points1_nativeObj, long points2_nativeObj, long cameraMatrix_nativeObj, long R_nativeObj, long t_nativeObj, long mask_nativeObj); private static native int recoverPose_4(long E_nativeObj, long points1_nativeObj, long points2_nativeObj, long cameraMatrix_nativeObj, long R_nativeObj, long t_nativeObj); // C++: void Rodrigues(Mat src, Mat& dst, Mat& jacobian = Mat()) private static native void Rodrigues_0(long src_nativeObj, long dst_nativeObj, long jacobian_nativeObj); private static native void Rodrigues_1(long src_nativeObj, long dst_nativeObj); // C++: void calibrationMatrixValues(Mat cameraMatrix, Size imageSize, double apertureWidth, double apertureHeight, double& fovx, double& fovy, double& focalLength, Point2d& principalPoint, double& aspectRatio) private static native void calibrationMatrixValues_0(long cameraMatrix_nativeObj, double imageSize_width, double imageSize_height, double apertureWidth, double apertureHeight, double[] fovx_out, double[] fovy_out, double[] focalLength_out, double[] principalPoint_out, double[] aspectRatio_out); // C++: void composeRT(Mat rvec1, Mat tvec1, Mat rvec2, Mat tvec2, Mat& rvec3, Mat& tvec3, Mat& dr3dr1 = Mat(), Mat& dr3dt1 = Mat(), Mat& dr3dr2 = Mat(), Mat& dr3dt2 = Mat(), Mat& dt3dr1 = Mat(), Mat& dt3dt1 = Mat(), Mat& dt3dr2 = Mat(), Mat& dt3dt2 = Mat()) private static native void composeRT_0(long rvec1_nativeObj, long tvec1_nativeObj, long rvec2_nativeObj, long tvec2_nativeObj, long rvec3_nativeObj, long tvec3_nativeObj, long dr3dr1_nativeObj, long dr3dt1_nativeObj, long dr3dr2_nativeObj, long dr3dt2_nativeObj, long dt3dr1_nativeObj, long dt3dt1_nativeObj, long dt3dr2_nativeObj, long dt3dt2_nativeObj); private static native void composeRT_1(long rvec1_nativeObj, long tvec1_nativeObj, long rvec2_nativeObj, long tvec2_nativeObj, long rvec3_nativeObj, long tvec3_nativeObj); // C++: void computeCorrespondEpilines(Mat points, int whichImage, Mat F, Mat& lines) private static native void computeCorrespondEpilines_0(long points_nativeObj, int whichImage, long F_nativeObj, long lines_nativeObj); // C++: void convertPointsFromHomogeneous(Mat src, Mat& dst) private static native void convertPointsFromHomogeneous_0(long src_nativeObj, long dst_nativeObj); // C++: void convertPointsToHomogeneous(Mat src, Mat& dst) private static native void convertPointsToHomogeneous_0(long src_nativeObj, long dst_nativeObj); // C++: void correctMatches(Mat F, Mat points1, Mat points2, Mat& newPoints1, Mat& newPoints2) private static native void correctMatches_0(long F_nativeObj, long points1_nativeObj, long points2_nativeObj, long newPoints1_nativeObj, long newPoints2_nativeObj); // C++: void decomposeEssentialMat(Mat E, Mat& R1, Mat& R2, Mat& t) private static native void decomposeEssentialMat_0(long E_nativeObj, long R1_nativeObj, long R2_nativeObj, long t_nativeObj); // C++: void decomposeProjectionMatrix(Mat projMatrix, Mat& cameraMatrix, Mat& rotMatrix, Mat& transVect, Mat& rotMatrixX = Mat(), Mat& rotMatrixY = Mat(), Mat& rotMatrixZ = Mat(), Mat& eulerAngles = Mat()) private static native void decomposeProjectionMatrix_0(long projMatrix_nativeObj, long cameraMatrix_nativeObj, long rotMatrix_nativeObj, long transVect_nativeObj, long rotMatrixX_nativeObj, long rotMatrixY_nativeObj, long rotMatrixZ_nativeObj, long eulerAngles_nativeObj); private static native void decomposeProjectionMatrix_1(long projMatrix_nativeObj, long cameraMatrix_nativeObj, long rotMatrix_nativeObj, long transVect_nativeObj); // C++: void drawChessboardCorners(Mat& image, Size patternSize, vector_Point2f corners, bool patternWasFound) private static native void drawChessboardCorners_0(long image_nativeObj, double patternSize_width, double patternSize_height, long corners_mat_nativeObj, boolean patternWasFound); // C++: void filterSpeckles(Mat& img, double newVal, int maxSpeckleSize, double maxDiff, Mat& buf = Mat()) private static native void filterSpeckles_0(long img_nativeObj, double newVal, int maxSpeckleSize, double maxDiff, long buf_nativeObj); private static native void filterSpeckles_1(long img_nativeObj, double newVal, int maxSpeckleSize, double maxDiff); // C++: void matMulDeriv(Mat A, Mat B, Mat& dABdA, Mat& dABdB) private static native void matMulDeriv_0(long A_nativeObj, long B_nativeObj, long dABdA_nativeObj, long dABdB_nativeObj); // C++: void projectPoints(vector_Point3f objectPoints, Mat rvec, Mat tvec, Mat cameraMatrix, vector_double distCoeffs, vector_Point2f& imagePoints, Mat& jacobian = Mat(), double aspectRatio = 0) private static native void projectPoints_0(long objectPoints_mat_nativeObj, long rvec_nativeObj, long tvec_nativeObj, long cameraMatrix_nativeObj, long distCoeffs_mat_nativeObj, long imagePoints_mat_nativeObj, long jacobian_nativeObj, double aspectRatio); private static native void projectPoints_1(long objectPoints_mat_nativeObj, long rvec_nativeObj, long tvec_nativeObj, long cameraMatrix_nativeObj, long distCoeffs_mat_nativeObj, long imagePoints_mat_nativeObj); // C++: void reprojectImageTo3D(Mat disparity, Mat& _3dImage, Mat Q, bool handleMissingValues = false, int ddepth = -1) private static native void reprojectImageTo3D_0(long disparity_nativeObj, long _3dImage_nativeObj, long Q_nativeObj, boolean handleMissingValues, int ddepth); private static native void reprojectImageTo3D_1(long disparity_nativeObj, long _3dImage_nativeObj, long Q_nativeObj, boolean handleMissingValues); private static native void reprojectImageTo3D_2(long disparity_nativeObj, long _3dImage_nativeObj, long Q_nativeObj); // C++: void stereoRectify(Mat cameraMatrix1, Mat distCoeffs1, Mat cameraMatrix2, Mat distCoeffs2, Size imageSize, Mat R, Mat T, Mat& R1, Mat& R2, Mat& P1, Mat& P2, Mat& Q, int flags = CALIB_ZERO_DISPARITY, double alpha = -1, Size newImageSize = Size(), Rect* validPixROI1 = 0, Rect* validPixROI2 = 0) private static native void stereoRectify_0(long cameraMatrix1_nativeObj, long distCoeffs1_nativeObj, long cameraMatrix2_nativeObj, long distCoeffs2_nativeObj, double imageSize_width, double imageSize_height, long R_nativeObj, long T_nativeObj, long R1_nativeObj, long R2_nativeObj, long P1_nativeObj, long P2_nativeObj, long Q_nativeObj, int flags, double alpha, double newImageSize_width, double newImageSize_height, double[] validPixROI1_out, double[] validPixROI2_out); private static native void stereoRectify_1(long cameraMatrix1_nativeObj, long distCoeffs1_nativeObj, long cameraMatrix2_nativeObj, long distCoeffs2_nativeObj, double imageSize_width, double imageSize_height, long R_nativeObj, long T_nativeObj, long R1_nativeObj, long R2_nativeObj, long P1_nativeObj, long P2_nativeObj, long Q_nativeObj); // C++: void triangulatePoints(Mat projMatr1, Mat projMatr2, Mat projPoints1, Mat projPoints2, Mat& points4D) private static native void triangulatePoints_0(long projMatr1_nativeObj, long projMatr2_nativeObj, long projPoints1_nativeObj, long projPoints2_nativeObj, long points4D_nativeObj); // C++: void validateDisparity(Mat& disparity, Mat cost, int minDisparity, int numberOfDisparities, int disp12MaxDisp = 1) private static native void validateDisparity_0(long disparity_nativeObj, long cost_nativeObj, int minDisparity, int numberOfDisparities, int disp12MaxDisp); private static native void validateDisparity_1(long disparity_nativeObj, long cost_nativeObj, int minDisparity, int numberOfDisparities); // C++: void distortPoints(Mat undistorted, Mat& distorted, Mat K, Mat D, double alpha = 0) private static native void distortPoints_0(long undistorted_nativeObj, long distorted_nativeObj, long K_nativeObj, long D_nativeObj, double alpha); private static native void distortPoints_1(long undistorted_nativeObj, long distorted_nativeObj, long K_nativeObj, long D_nativeObj); // C++: void estimateNewCameraMatrixForUndistortRectify(Mat K, Mat D, Size image_size, Mat R, Mat& P, double balance = 0.0, Size new_size = Size(), double fov_scale = 1.0) private static native void estimateNewCameraMatrixForUndistortRectify_0(long K_nativeObj, long D_nativeObj, double image_size_width, double image_size_height, long R_nativeObj, long P_nativeObj, double balance, double new_size_width, double new_size_height, double fov_scale); private static native void estimateNewCameraMatrixForUndistortRectify_1(long K_nativeObj, long D_nativeObj, double image_size_width, double image_size_height, long R_nativeObj, long P_nativeObj); // C++: void initUndistortRectifyMap(Mat K, Mat D, Mat R, Mat P, Size size, int m1type, Mat& map1, Mat& map2) private static native void initUndistortRectifyMap_0(long K_nativeObj, long D_nativeObj, long R_nativeObj, long P_nativeObj, double size_width, double size_height, int m1type, long map1_nativeObj, long map2_nativeObj); // C++: void projectPoints(vector_Point3f objectPoints, vector_Point2f& imagePoints, Mat rvec, Mat tvec, Mat K, Mat D, double alpha = 0, Mat& jacobian = Mat()) private static native void projectPoints_2(long objectPoints_mat_nativeObj, long imagePoints_mat_nativeObj, long rvec_nativeObj, long tvec_nativeObj, long K_nativeObj, long D_nativeObj, double alpha, long jacobian_nativeObj); private static native void projectPoints_3(long objectPoints_mat_nativeObj, long imagePoints_mat_nativeObj, long rvec_nativeObj, long tvec_nativeObj, long K_nativeObj, long D_nativeObj); // C++: void stereoRectify(Mat K1, Mat D1, Mat K2, Mat D2, Size imageSize, Mat R, Mat tvec, Mat& R1, Mat& R2, Mat& P1, Mat& P2, Mat& Q, int flags, Size newImageSize = Size(), double balance = 0.0, double fov_scale = 1.0) private static native void stereoRectify_2(long K1_nativeObj, long D1_nativeObj, long K2_nativeObj, long D2_nativeObj, double imageSize_width, double imageSize_height, long R_nativeObj, long tvec_nativeObj, long R1_nativeObj, long R2_nativeObj, long P1_nativeObj, long P2_nativeObj, long Q_nativeObj, int flags, double newImageSize_width, double newImageSize_height, double balance, double fov_scale); private static native void stereoRectify_3(long K1_nativeObj, long D1_nativeObj, long K2_nativeObj, long D2_nativeObj, double imageSize_width, double imageSize_height, long R_nativeObj, long tvec_nativeObj, long R1_nativeObj, long R2_nativeObj, long P1_nativeObj, long P2_nativeObj, long Q_nativeObj, int flags); // C++: void undistortImage(Mat distorted, Mat& undistorted, Mat K, Mat D, Mat Knew = cv::Mat(), Size new_size = Size()) private static native void undistortImage_0(long distorted_nativeObj, long undistorted_nativeObj, long K_nativeObj, long D_nativeObj, long Knew_nativeObj, double new_size_width, double new_size_height); private static native void undistortImage_1(long distorted_nativeObj, long undistorted_nativeObj, long K_nativeObj, long D_nativeObj); // C++: void undistortPoints(Mat distorted, Mat& undistorted, Mat K, Mat D, Mat R = Mat(), Mat P = Mat()) private static native void undistortPoints_0(long distorted_nativeObj, long undistorted_nativeObj, long K_nativeObj, long D_nativeObj, long R_nativeObj, long P_nativeObj); private static native void undistortPoints_1(long distorted_nativeObj, long undistorted_nativeObj, long K_nativeObj, long D_nativeObj); }
84,828
59.722262
655
java
self
self-master/lib/opencv/android/sdk/java/src/org/opencv/calib3d/StereoSGBM.java
// // This file is auto-generated. Please don't modify it! // package org.opencv.calib3d; // C++: class StereoSGBM //javadoc: StereoSGBM public class StereoSGBM extends StereoMatcher { protected StereoSGBM(long addr) { super(addr); } public static final int MODE_SGBM = 0, MODE_HH = 1, MODE_SGBM_3WAY = 2; // // C++: static Ptr_StereoSGBM create(int minDisparity, int numDisparities, int blockSize, int P1 = 0, int P2 = 0, int disp12MaxDiff = 0, int preFilterCap = 0, int uniquenessRatio = 0, int speckleWindowSize = 0, int speckleRange = 0, int mode = StereoSGBM::MODE_SGBM) // //javadoc: StereoSGBM::create(minDisparity, numDisparities, blockSize, P1, P2, disp12MaxDiff, preFilterCap, uniquenessRatio, speckleWindowSize, speckleRange, mode) public static StereoSGBM create(int minDisparity, int numDisparities, int blockSize, int P1, int P2, int disp12MaxDiff, int preFilterCap, int uniquenessRatio, int speckleWindowSize, int speckleRange, int mode) { StereoSGBM retVal = new StereoSGBM(create_0(minDisparity, numDisparities, blockSize, P1, P2, disp12MaxDiff, preFilterCap, uniquenessRatio, speckleWindowSize, speckleRange, mode)); return retVal; } //javadoc: StereoSGBM::create(minDisparity, numDisparities, blockSize) public static StereoSGBM create(int minDisparity, int numDisparities, int blockSize) { StereoSGBM retVal = new StereoSGBM(create_1(minDisparity, numDisparities, blockSize)); return retVal; } // // C++: int getMode() // //javadoc: StereoSGBM::getMode() public int getMode() { int retVal = getMode_0(nativeObj); return retVal; } // // C++: int getP1() // //javadoc: StereoSGBM::getP1() public int getP1() { int retVal = getP1_0(nativeObj); return retVal; } // // C++: int getP2() // //javadoc: StereoSGBM::getP2() public int getP2() { int retVal = getP2_0(nativeObj); return retVal; } // // C++: int getPreFilterCap() // //javadoc: StereoSGBM::getPreFilterCap() public int getPreFilterCap() { int retVal = getPreFilterCap_0(nativeObj); return retVal; } // // C++: int getUniquenessRatio() // //javadoc: StereoSGBM::getUniquenessRatio() public int getUniquenessRatio() { int retVal = getUniquenessRatio_0(nativeObj); return retVal; } // // C++: void setMode(int mode) // //javadoc: StereoSGBM::setMode(mode) public void setMode(int mode) { setMode_0(nativeObj, mode); return; } // // C++: void setP1(int P1) // //javadoc: StereoSGBM::setP1(P1) public void setP1(int P1) { setP1_0(nativeObj, P1); return; } // // C++: void setP2(int P2) // //javadoc: StereoSGBM::setP2(P2) public void setP2(int P2) { setP2_0(nativeObj, P2); return; } // // C++: void setPreFilterCap(int preFilterCap) // //javadoc: StereoSGBM::setPreFilterCap(preFilterCap) public void setPreFilterCap(int preFilterCap) { setPreFilterCap_0(nativeObj, preFilterCap); return; } // // C++: void setUniquenessRatio(int uniquenessRatio) // //javadoc: StereoSGBM::setUniquenessRatio(uniquenessRatio) public void setUniquenessRatio(int uniquenessRatio) { setUniquenessRatio_0(nativeObj, uniquenessRatio); return; } @Override protected void finalize() throws Throwable { delete(nativeObj); } // C++: static Ptr_StereoSGBM create(int minDisparity, int numDisparities, int blockSize, int P1 = 0, int P2 = 0, int disp12MaxDiff = 0, int preFilterCap = 0, int uniquenessRatio = 0, int speckleWindowSize = 0, int speckleRange = 0, int mode = StereoSGBM::MODE_SGBM) private static native long create_0(int minDisparity, int numDisparities, int blockSize, int P1, int P2, int disp12MaxDiff, int preFilterCap, int uniquenessRatio, int speckleWindowSize, int speckleRange, int mode); private static native long create_1(int minDisparity, int numDisparities, int blockSize); // C++: int getMode() private static native int getMode_0(long nativeObj); // C++: int getP1() private static native int getP1_0(long nativeObj); // C++: int getP2() private static native int getP2_0(long nativeObj); // C++: int getPreFilterCap() private static native int getPreFilterCap_0(long nativeObj); // C++: int getUniquenessRatio() private static native int getUniquenessRatio_0(long nativeObj); // C++: void setMode(int mode) private static native void setMode_0(long nativeObj, int mode); // C++: void setP1(int P1) private static native void setP1_0(long nativeObj, int P1); // C++: void setP2(int P2) private static native void setP2_0(long nativeObj, int P2); // C++: void setPreFilterCap(int preFilterCap) private static native void setPreFilterCap_0(long nativeObj, int preFilterCap); // C++: void setUniquenessRatio(int uniquenessRatio) private static native void setUniquenessRatio_0(long nativeObj, int uniquenessRatio); // native support for java finalize() private static native void delete(long nativeObj); }
5,657
23.6
270
java
self
self-master/lib/opencv/android/sdk/java/src/org/opencv/calib3d/StereoBM.java
// // This file is auto-generated. Please don't modify it! // package org.opencv.calib3d; import org.opencv.core.Rect; // C++: class StereoBM //javadoc: StereoBM public class StereoBM extends StereoMatcher { protected StereoBM(long addr) { super(addr); } public static final int PREFILTER_NORMALIZED_RESPONSE = 0, PREFILTER_XSOBEL = 1; // // C++: static Ptr_StereoBM create(int numDisparities = 0, int blockSize = 21) // //javadoc: StereoBM::create(numDisparities, blockSize) public static StereoBM create(int numDisparities, int blockSize) { StereoBM retVal = new StereoBM(create_0(numDisparities, blockSize)); return retVal; } //javadoc: StereoBM::create() public static StereoBM create() { StereoBM retVal = new StereoBM(create_1()); return retVal; } // // C++: Rect getROI1() // //javadoc: StereoBM::getROI1() public Rect getROI1() { Rect retVal = new Rect(getROI1_0(nativeObj)); return retVal; } // // C++: Rect getROI2() // //javadoc: StereoBM::getROI2() public Rect getROI2() { Rect retVal = new Rect(getROI2_0(nativeObj)); return retVal; } // // C++: int getPreFilterCap() // //javadoc: StereoBM::getPreFilterCap() public int getPreFilterCap() { int retVal = getPreFilterCap_0(nativeObj); return retVal; } // // C++: int getPreFilterSize() // //javadoc: StereoBM::getPreFilterSize() public int getPreFilterSize() { int retVal = getPreFilterSize_0(nativeObj); return retVal; } // // C++: int getPreFilterType() // //javadoc: StereoBM::getPreFilterType() public int getPreFilterType() { int retVal = getPreFilterType_0(nativeObj); return retVal; } // // C++: int getSmallerBlockSize() // //javadoc: StereoBM::getSmallerBlockSize() public int getSmallerBlockSize() { int retVal = getSmallerBlockSize_0(nativeObj); return retVal; } // // C++: int getTextureThreshold() // //javadoc: StereoBM::getTextureThreshold() public int getTextureThreshold() { int retVal = getTextureThreshold_0(nativeObj); return retVal; } // // C++: int getUniquenessRatio() // //javadoc: StereoBM::getUniquenessRatio() public int getUniquenessRatio() { int retVal = getUniquenessRatio_0(nativeObj); return retVal; } // // C++: void setPreFilterCap(int preFilterCap) // //javadoc: StereoBM::setPreFilterCap(preFilterCap) public void setPreFilterCap(int preFilterCap) { setPreFilterCap_0(nativeObj, preFilterCap); return; } // // C++: void setPreFilterSize(int preFilterSize) // //javadoc: StereoBM::setPreFilterSize(preFilterSize) public void setPreFilterSize(int preFilterSize) { setPreFilterSize_0(nativeObj, preFilterSize); return; } // // C++: void setPreFilterType(int preFilterType) // //javadoc: StereoBM::setPreFilterType(preFilterType) public void setPreFilterType(int preFilterType) { setPreFilterType_0(nativeObj, preFilterType); return; } // // C++: void setROI1(Rect roi1) // //javadoc: StereoBM::setROI1(roi1) public void setROI1(Rect roi1) { setROI1_0(nativeObj, roi1.x, roi1.y, roi1.width, roi1.height); return; } // // C++: void setROI2(Rect roi2) // //javadoc: StereoBM::setROI2(roi2) public void setROI2(Rect roi2) { setROI2_0(nativeObj, roi2.x, roi2.y, roi2.width, roi2.height); return; } // // C++: void setSmallerBlockSize(int blockSize) // //javadoc: StereoBM::setSmallerBlockSize(blockSize) public void setSmallerBlockSize(int blockSize) { setSmallerBlockSize_0(nativeObj, blockSize); return; } // // C++: void setTextureThreshold(int textureThreshold) // //javadoc: StereoBM::setTextureThreshold(textureThreshold) public void setTextureThreshold(int textureThreshold) { setTextureThreshold_0(nativeObj, textureThreshold); return; } // // C++: void setUniquenessRatio(int uniquenessRatio) // //javadoc: StereoBM::setUniquenessRatio(uniquenessRatio) public void setUniquenessRatio(int uniquenessRatio) { setUniquenessRatio_0(nativeObj, uniquenessRatio); return; } @Override protected void finalize() throws Throwable { delete(nativeObj); } // C++: static Ptr_StereoBM create(int numDisparities = 0, int blockSize = 21) private static native long create_0(int numDisparities, int blockSize); private static native long create_1(); // C++: Rect getROI1() private static native double[] getROI1_0(long nativeObj); // C++: Rect getROI2() private static native double[] getROI2_0(long nativeObj); // C++: int getPreFilterCap() private static native int getPreFilterCap_0(long nativeObj); // C++: int getPreFilterSize() private static native int getPreFilterSize_0(long nativeObj); // C++: int getPreFilterType() private static native int getPreFilterType_0(long nativeObj); // C++: int getSmallerBlockSize() private static native int getSmallerBlockSize_0(long nativeObj); // C++: int getTextureThreshold() private static native int getTextureThreshold_0(long nativeObj); // C++: int getUniquenessRatio() private static native int getUniquenessRatio_0(long nativeObj); // C++: void setPreFilterCap(int preFilterCap) private static native void setPreFilterCap_0(long nativeObj, int preFilterCap); // C++: void setPreFilterSize(int preFilterSize) private static native void setPreFilterSize_0(long nativeObj, int preFilterSize); // C++: void setPreFilterType(int preFilterType) private static native void setPreFilterType_0(long nativeObj, int preFilterType); // C++: void setROI1(Rect roi1) private static native void setROI1_0(long nativeObj, int roi1_x, int roi1_y, int roi1_width, int roi1_height); // C++: void setROI2(Rect roi2) private static native void setROI2_0(long nativeObj, int roi2_x, int roi2_y, int roi2_width, int roi2_height); // C++: void setSmallerBlockSize(int blockSize) private static native void setSmallerBlockSize_0(long nativeObj, int blockSize); // C++: void setTextureThreshold(int textureThreshold) private static native void setTextureThreshold_0(long nativeObj, int textureThreshold); // C++: void setUniquenessRatio(int uniquenessRatio) private static native void setUniquenessRatio_0(long nativeObj, int uniquenessRatio); // native support for java finalize() private static native void delete(long nativeObj); }
7,376
21.287009
114
java
self
self-master/lib/opencv/android/sdk/java/src/org/opencv/calib3d/StereoMatcher.java
// // This file is auto-generated. Please don't modify it! // package org.opencv.calib3d; import org.opencv.core.Algorithm; import org.opencv.core.Mat; // C++: class StereoMatcher //javadoc: StereoMatcher public class StereoMatcher extends Algorithm { protected StereoMatcher(long addr) { super(addr); } public static final int DISP_SHIFT = 4, DISP_SCALE = (1 << DISP_SHIFT); // // C++: int getBlockSize() // //javadoc: StereoMatcher::getBlockSize() public int getBlockSize() { int retVal = getBlockSize_0(nativeObj); return retVal; } // // C++: int getDisp12MaxDiff() // //javadoc: StereoMatcher::getDisp12MaxDiff() public int getDisp12MaxDiff() { int retVal = getDisp12MaxDiff_0(nativeObj); return retVal; } // // C++: int getMinDisparity() // //javadoc: StereoMatcher::getMinDisparity() public int getMinDisparity() { int retVal = getMinDisparity_0(nativeObj); return retVal; } // // C++: int getNumDisparities() // //javadoc: StereoMatcher::getNumDisparities() public int getNumDisparities() { int retVal = getNumDisparities_0(nativeObj); return retVal; } // // C++: int getSpeckleRange() // //javadoc: StereoMatcher::getSpeckleRange() public int getSpeckleRange() { int retVal = getSpeckleRange_0(nativeObj); return retVal; } // // C++: int getSpeckleWindowSize() // //javadoc: StereoMatcher::getSpeckleWindowSize() public int getSpeckleWindowSize() { int retVal = getSpeckleWindowSize_0(nativeObj); return retVal; } // // C++: void compute(Mat left, Mat right, Mat& disparity) // //javadoc: StereoMatcher::compute(left, right, disparity) public void compute(Mat left, Mat right, Mat disparity) { compute_0(nativeObj, left.nativeObj, right.nativeObj, disparity.nativeObj); return; } // // C++: void setBlockSize(int blockSize) // //javadoc: StereoMatcher::setBlockSize(blockSize) public void setBlockSize(int blockSize) { setBlockSize_0(nativeObj, blockSize); return; } // // C++: void setDisp12MaxDiff(int disp12MaxDiff) // //javadoc: StereoMatcher::setDisp12MaxDiff(disp12MaxDiff) public void setDisp12MaxDiff(int disp12MaxDiff) { setDisp12MaxDiff_0(nativeObj, disp12MaxDiff); return; } // // C++: void setMinDisparity(int minDisparity) // //javadoc: StereoMatcher::setMinDisparity(minDisparity) public void setMinDisparity(int minDisparity) { setMinDisparity_0(nativeObj, minDisparity); return; } // // C++: void setNumDisparities(int numDisparities) // //javadoc: StereoMatcher::setNumDisparities(numDisparities) public void setNumDisparities(int numDisparities) { setNumDisparities_0(nativeObj, numDisparities); return; } // // C++: void setSpeckleRange(int speckleRange) // //javadoc: StereoMatcher::setSpeckleRange(speckleRange) public void setSpeckleRange(int speckleRange) { setSpeckleRange_0(nativeObj, speckleRange); return; } // // C++: void setSpeckleWindowSize(int speckleWindowSize) // //javadoc: StereoMatcher::setSpeckleWindowSize(speckleWindowSize) public void setSpeckleWindowSize(int speckleWindowSize) { setSpeckleWindowSize_0(nativeObj, speckleWindowSize); return; } @Override protected void finalize() throws Throwable { delete(nativeObj); } // C++: int getBlockSize() private static native int getBlockSize_0(long nativeObj); // C++: int getDisp12MaxDiff() private static native int getDisp12MaxDiff_0(long nativeObj); // C++: int getMinDisparity() private static native int getMinDisparity_0(long nativeObj); // C++: int getNumDisparities() private static native int getNumDisparities_0(long nativeObj); // C++: int getSpeckleRange() private static native int getSpeckleRange_0(long nativeObj); // C++: int getSpeckleWindowSize() private static native int getSpeckleWindowSize_0(long nativeObj); // C++: void compute(Mat left, Mat right, Mat& disparity) private static native void compute_0(long nativeObj, long left_nativeObj, long right_nativeObj, long disparity_nativeObj); // C++: void setBlockSize(int blockSize) private static native void setBlockSize_0(long nativeObj, int blockSize); // C++: void setDisp12MaxDiff(int disp12MaxDiff) private static native void setDisp12MaxDiff_0(long nativeObj, int disp12MaxDiff); // C++: void setMinDisparity(int minDisparity) private static native void setMinDisparity_0(long nativeObj, int minDisparity); // C++: void setNumDisparities(int numDisparities) private static native void setNumDisparities_0(long nativeObj, int numDisparities); // C++: void setSpeckleRange(int speckleRange) private static native void setSpeckleRange_0(long nativeObj, int speckleRange); // C++: void setSpeckleWindowSize(int speckleWindowSize) private static native void setSpeckleWindowSize_0(long nativeObj, int speckleWindowSize); // native support for java finalize() private static native void delete(long nativeObj); }
5,753
21.653543
126
java
self
self-master/lib/opencv/android/sdk/java/src/org/opencv/videoio/VideoWriter.java
// // This file is auto-generated. Please don't modify it! // package org.opencv.videoio; import java.lang.String; import org.opencv.core.Mat; import org.opencv.core.Size; // C++: class VideoWriter //javadoc: VideoWriter public class VideoWriter { protected final long nativeObj; protected VideoWriter(long addr) { nativeObj = addr; } // // C++: VideoWriter(String filename, int fourcc, double fps, Size frameSize, bool isColor = true) // //javadoc: VideoWriter::VideoWriter(filename, fourcc, fps, frameSize, isColor) public VideoWriter(String filename, int fourcc, double fps, Size frameSize, boolean isColor) { nativeObj = VideoWriter_0(filename, fourcc, fps, frameSize.width, frameSize.height, isColor); return; } //javadoc: VideoWriter::VideoWriter(filename, fourcc, fps, frameSize) public VideoWriter(String filename, int fourcc, double fps, Size frameSize) { nativeObj = VideoWriter_1(filename, fourcc, fps, frameSize.width, frameSize.height); return; } // // C++: VideoWriter() // //javadoc: VideoWriter::VideoWriter() public VideoWriter() { nativeObj = VideoWriter_2(); return; } // // C++: bool isOpened() // //javadoc: VideoWriter::isOpened() public boolean isOpened() { boolean retVal = isOpened_0(nativeObj); return retVal; } // // C++: bool open(String filename, int fourcc, double fps, Size frameSize, bool isColor = true) // //javadoc: VideoWriter::open(filename, fourcc, fps, frameSize, isColor) public boolean open(String filename, int fourcc, double fps, Size frameSize, boolean isColor) { boolean retVal = open_0(nativeObj, filename, fourcc, fps, frameSize.width, frameSize.height, isColor); return retVal; } //javadoc: VideoWriter::open(filename, fourcc, fps, frameSize) public boolean open(String filename, int fourcc, double fps, Size frameSize) { boolean retVal = open_1(nativeObj, filename, fourcc, fps, frameSize.width, frameSize.height); return retVal; } // // C++: bool set(int propId, double value) // //javadoc: VideoWriter::set(propId, value) public boolean set(int propId, double value) { boolean retVal = set_0(nativeObj, propId, value); return retVal; } // // C++: double get(int propId) // //javadoc: VideoWriter::get(propId) public double get(int propId) { double retVal = get_0(nativeObj, propId); return retVal; } // // C++: static int fourcc(char c1, char c2, char c3, char c4) // //javadoc: VideoWriter::fourcc(c1, c2, c3, c4) public static int fourcc(char c1, char c2, char c3, char c4) { int retVal = fourcc_0(c1, c2, c3, c4); return retVal; } // // C++: void release() // //javadoc: VideoWriter::release() public void release() { release_0(nativeObj); return; } // // C++: void write(Mat image) // //javadoc: VideoWriter::write(image) public void write(Mat image) { write_0(nativeObj, image.nativeObj); return; } @Override protected void finalize() throws Throwable { delete(nativeObj); } // C++: VideoWriter(String filename, int fourcc, double fps, Size frameSize, bool isColor = true) private static native long VideoWriter_0(String filename, int fourcc, double fps, double frameSize_width, double frameSize_height, boolean isColor); private static native long VideoWriter_1(String filename, int fourcc, double fps, double frameSize_width, double frameSize_height); // C++: VideoWriter() private static native long VideoWriter_2(); // C++: bool isOpened() private static native boolean isOpened_0(long nativeObj); // C++: bool open(String filename, int fourcc, double fps, Size frameSize, bool isColor = true) private static native boolean open_0(long nativeObj, String filename, int fourcc, double fps, double frameSize_width, double frameSize_height, boolean isColor); private static native boolean open_1(long nativeObj, String filename, int fourcc, double fps, double frameSize_width, double frameSize_height); // C++: bool set(int propId, double value) private static native boolean set_0(long nativeObj, int propId, double value); // C++: double get(int propId) private static native double get_0(long nativeObj, int propId); // C++: static int fourcc(char c1, char c2, char c3, char c4) private static native int fourcc_0(char c1, char c2, char c3, char c4); // C++: void release() private static native void release_0(long nativeObj); // C++: void write(Mat image) private static native void write_0(long nativeObj, long image_nativeObj); // native support for java finalize() private static native void delete(long nativeObj); }
5,237
24.802956
164
java
self
self-master/lib/opencv/android/sdk/java/src/org/opencv/videoio/VideoCapture.java
// // This file is auto-generated. Please don't modify it! // package org.opencv.videoio; import java.lang.String; import org.opencv.core.Mat; // C++: class VideoCapture //javadoc: VideoCapture public class VideoCapture { protected final long nativeObj; protected VideoCapture(long addr) { nativeObj = addr; } // // C++: VideoCapture(String filename, int apiPreference) // //javadoc: VideoCapture::VideoCapture(filename, apiPreference) public VideoCapture(String filename, int apiPreference) { nativeObj = VideoCapture_0(filename, apiPreference); return; } // // C++: VideoCapture(String filename) // //javadoc: VideoCapture::VideoCapture(filename) public VideoCapture(String filename) { nativeObj = VideoCapture_1(filename); return; } // // C++: VideoCapture(int index) // //javadoc: VideoCapture::VideoCapture(index) public VideoCapture(int index) { nativeObj = VideoCapture_2(index); return; } // // C++: VideoCapture() // //javadoc: VideoCapture::VideoCapture() public VideoCapture() { nativeObj = VideoCapture_3(); return; } // // C++: bool grab() // //javadoc: VideoCapture::grab() public boolean grab() { boolean retVal = grab_0(nativeObj); return retVal; } // // C++: bool isOpened() // //javadoc: VideoCapture::isOpened() public boolean isOpened() { boolean retVal = isOpened_0(nativeObj); return retVal; } // // C++: bool open(String filename, int apiPreference) // //javadoc: VideoCapture::open(filename, apiPreference) public boolean open(String filename, int apiPreference) { boolean retVal = open_0(nativeObj, filename, apiPreference); return retVal; } // // C++: bool open(String filename) // //javadoc: VideoCapture::open(filename) public boolean open(String filename) { boolean retVal = open_1(nativeObj, filename); return retVal; } // // C++: bool open(int index) // //javadoc: VideoCapture::open(index) public boolean open(int index) { boolean retVal = open_2(nativeObj, index); return retVal; } // // C++: bool read(Mat& image) // //javadoc: VideoCapture::read(image) public boolean read(Mat image) { boolean retVal = read_0(nativeObj, image.nativeObj); return retVal; } // // C++: bool retrieve(Mat& image, int flag = 0) // //javadoc: VideoCapture::retrieve(image, flag) public boolean retrieve(Mat image, int flag) { boolean retVal = retrieve_0(nativeObj, image.nativeObj, flag); return retVal; } //javadoc: VideoCapture::retrieve(image) public boolean retrieve(Mat image) { boolean retVal = retrieve_1(nativeObj, image.nativeObj); return retVal; } // // C++: bool set(int propId, double value) // //javadoc: VideoCapture::set(propId, value) public boolean set(int propId, double value) { boolean retVal = set_0(nativeObj, propId, value); return retVal; } // // C++: double get(int propId) // //javadoc: VideoCapture::get(propId) public double get(int propId) { double retVal = get_0(nativeObj, propId); return retVal; } // // C++: void release() // //javadoc: VideoCapture::release() public void release() { release_0(nativeObj); return; } @Override protected void finalize() throws Throwable { delete(nativeObj); } // C++: VideoCapture(String filename, int apiPreference) private static native long VideoCapture_0(String filename, int apiPreference); // C++: VideoCapture(String filename) private static native long VideoCapture_1(String filename); // C++: VideoCapture(int index) private static native long VideoCapture_2(int index); // C++: VideoCapture() private static native long VideoCapture_3(); // C++: bool grab() private static native boolean grab_0(long nativeObj); // C++: bool isOpened() private static native boolean isOpened_0(long nativeObj); // C++: bool open(String filename, int apiPreference) private static native boolean open_0(long nativeObj, String filename, int apiPreference); // C++: bool open(String filename) private static native boolean open_1(long nativeObj, String filename); // C++: bool open(int index) private static native boolean open_2(long nativeObj, int index); // C++: bool read(Mat& image) private static native boolean read_0(long nativeObj, long image_nativeObj); // C++: bool retrieve(Mat& image, int flag = 0) private static native boolean retrieve_0(long nativeObj, long image_nativeObj, int flag); private static native boolean retrieve_1(long nativeObj, long image_nativeObj); // C++: bool set(int propId, double value) private static native boolean set_0(long nativeObj, int propId, double value); // C++: double get(int propId) private static native double get_0(long nativeObj, int propId); // C++: void release() private static native void release_0(long nativeObj); // native support for java finalize() private static native void delete(long nativeObj); }
5,828
20.043321
93
java
self
self-master/lib/opencv/android/sdk/java/src/org/opencv/videoio/Videoio.java
// // This file is auto-generated. Please don't modify it! // package org.opencv.videoio; public class Videoio { public static final int CV_CAP_MSMF = 1400, CV_CAP_ANDROID = 1000, CV_CAP_ANDROID_BACK = CV_CAP_ANDROID+99, CV_CAP_ANDROID_FRONT = CV_CAP_ANDROID+98, CV_CAP_XIAPI = 1100, CV_CAP_AVFOUNDATION = 1200, CV_CAP_GIGANETIX = 1300, CV_CAP_GPHOTO2 = 1700, CV_CAP_GSTREAMER = 1800, CV_CAP_FFMPEG = 1900, CV_CAP_IMAGES = 2000, CV_CAP_PROP_FRAME_WIDTH = 3, CV_CAP_PROP_FRAME_HEIGHT = 4, CV_CAP_PROP_ZOOM = 27, CV_CAP_PROP_FOCUS = 28, CV_CAP_PROP_GUID = 29, CV_CAP_PROP_ISO_SPEED = 30, CV_CAP_PROP_BACKLIGHT = 32, CV_CAP_PROP_PAN = 33, CV_CAP_PROP_TILT = 34, CV_CAP_PROP_ROLL = 35, CV_CAP_PROP_IRIS = 36, CV_CAP_PROP_SETTINGS = 37, CV_CAP_PROP_BUFFERSIZE = 38, CV_CAP_PROP_AUTOFOCUS = 39, CV_CAP_PROP_SAR_NUM = 40, CV_CAP_PROP_SAR_DEN = 41, CV_CAP_PROP_AUTOGRAB = 1024, CV_CAP_PROP_PREVIEW_FORMAT = 1026, CV_CAP_PROP_OPENNI2_SYNC = 110, CV_CAP_PROP_OPENNI2_MIRROR = 111, CV_CAP_PROP_PVAPI_FRAMESTARTTRIGGERMODE = 301, CV_CAP_PROP_PVAPI_DECIMATIONHORIZONTAL = 302, CV_CAP_PROP_PVAPI_DECIMATIONVERTICAL = 303, CV_CAP_PROP_PVAPI_BINNINGX = 304, CV_CAP_PROP_PVAPI_BINNINGY = 305, CV_CAP_PROP_PVAPI_PIXELFORMAT = 306, CV_CAP_PROP_XI_DOWNSAMPLING = 400, CV_CAP_PROP_XI_DATA_FORMAT = 401, CV_CAP_PROP_XI_OFFSET_X = 402, CV_CAP_PROP_XI_OFFSET_Y = 403, CV_CAP_PROP_XI_TRG_SOURCE = 404, CV_CAP_PROP_XI_TRG_SOFTWARE = 405, CV_CAP_PROP_XI_GPI_SELECTOR = 406, CV_CAP_PROP_XI_GPI_MODE = 407, CV_CAP_PROP_XI_GPI_LEVEL = 408, CV_CAP_PROP_XI_GPO_SELECTOR = 409, CV_CAP_PROP_XI_GPO_MODE = 410, CV_CAP_PROP_XI_LED_SELECTOR = 411, CV_CAP_PROP_XI_LED_MODE = 412, CV_CAP_PROP_XI_MANUAL_WB = 413, CV_CAP_PROP_XI_AUTO_WB = 414, CV_CAP_PROP_XI_AEAG = 415, CV_CAP_PROP_XI_EXP_PRIORITY = 416, CV_CAP_PROP_XI_AE_MAX_LIMIT = 417, CV_CAP_PROP_XI_AG_MAX_LIMIT = 418, CV_CAP_PROP_XI_AEAG_LEVEL = 419, CV_CAP_PROP_XI_TIMEOUT = 420, CV_CAP_PROP_XI_EXPOSURE = 421, CV_CAP_PROP_XI_EXPOSURE_BURST_COUNT = 422, CV_CAP_PROP_XI_GAIN_SELECTOR = 423, CV_CAP_PROP_XI_GAIN = 424, CV_CAP_PROP_XI_DOWNSAMPLING_TYPE = 426, CV_CAP_PROP_XI_BINNING_SELECTOR = 427, CV_CAP_PROP_XI_BINNING_VERTICAL = 428, CV_CAP_PROP_XI_BINNING_HORIZONTAL = 429, CV_CAP_PROP_XI_BINNING_PATTERN = 430, CV_CAP_PROP_XI_DECIMATION_SELECTOR = 431, CV_CAP_PROP_XI_DECIMATION_VERTICAL = 432, CV_CAP_PROP_XI_DECIMATION_HORIZONTAL = 433, CV_CAP_PROP_XI_DECIMATION_PATTERN = 434, CV_CAP_PROP_XI_IMAGE_DATA_FORMAT = 435, CV_CAP_PROP_XI_SHUTTER_TYPE = 436, CV_CAP_PROP_XI_SENSOR_TAPS = 437, CV_CAP_PROP_XI_AEAG_ROI_OFFSET_X = 439, CV_CAP_PROP_XI_AEAG_ROI_OFFSET_Y = 440, CV_CAP_PROP_XI_AEAG_ROI_WIDTH = 441, CV_CAP_PROP_XI_AEAG_ROI_HEIGHT = 442, CV_CAP_PROP_XI_BPC = 445, CV_CAP_PROP_XI_WB_KR = 448, CV_CAP_PROP_XI_WB_KG = 449, CV_CAP_PROP_XI_WB_KB = 450, CV_CAP_PROP_XI_WIDTH = 451, CV_CAP_PROP_XI_HEIGHT = 452, CV_CAP_PROP_XI_LIMIT_BANDWIDTH = 459, CV_CAP_PROP_XI_SENSOR_DATA_BIT_DEPTH = 460, CV_CAP_PROP_XI_OUTPUT_DATA_BIT_DEPTH = 461, CV_CAP_PROP_XI_IMAGE_DATA_BIT_DEPTH = 462, CV_CAP_PROP_XI_OUTPUT_DATA_PACKING = 463, CV_CAP_PROP_XI_OUTPUT_DATA_PACKING_TYPE = 464, CV_CAP_PROP_XI_IS_COOLED = 465, CV_CAP_PROP_XI_COOLING = 466, CV_CAP_PROP_XI_TARGET_TEMP = 467, CV_CAP_PROP_XI_CHIP_TEMP = 468, CV_CAP_PROP_XI_HOUS_TEMP = 469, CV_CAP_PROP_XI_CMS = 470, CV_CAP_PROP_XI_APPLY_CMS = 471, CV_CAP_PROP_XI_IMAGE_IS_COLOR = 474, CV_CAP_PROP_XI_COLOR_FILTER_ARRAY = 475, CV_CAP_PROP_XI_GAMMAY = 476, CV_CAP_PROP_XI_GAMMAC = 477, CV_CAP_PROP_XI_SHARPNESS = 478, CV_CAP_PROP_XI_CC_MATRIX_00 = 479, CV_CAP_PROP_XI_CC_MATRIX_01 = 480, CV_CAP_PROP_XI_CC_MATRIX_02 = 481, CV_CAP_PROP_XI_CC_MATRIX_03 = 482, CV_CAP_PROP_XI_CC_MATRIX_10 = 483, CV_CAP_PROP_XI_CC_MATRIX_11 = 484, CV_CAP_PROP_XI_CC_MATRIX_12 = 485, CV_CAP_PROP_XI_CC_MATRIX_13 = 486, CV_CAP_PROP_XI_CC_MATRIX_20 = 487, CV_CAP_PROP_XI_CC_MATRIX_21 = 488, CV_CAP_PROP_XI_CC_MATRIX_22 = 489, CV_CAP_PROP_XI_CC_MATRIX_23 = 490, CV_CAP_PROP_XI_CC_MATRIX_30 = 491, CV_CAP_PROP_XI_CC_MATRIX_31 = 492, CV_CAP_PROP_XI_CC_MATRIX_32 = 493, CV_CAP_PROP_XI_CC_MATRIX_33 = 494, CV_CAP_PROP_XI_DEFAULT_CC_MATRIX = 495, CV_CAP_PROP_XI_TRG_SELECTOR = 498, CV_CAP_PROP_XI_ACQ_FRAME_BURST_COUNT = 499, CV_CAP_PROP_XI_DEBOUNCE_EN = 507, CV_CAP_PROP_XI_DEBOUNCE_T0 = 508, CV_CAP_PROP_XI_DEBOUNCE_T1 = 509, CV_CAP_PROP_XI_DEBOUNCE_POL = 510, CV_CAP_PROP_XI_LENS_MODE = 511, CV_CAP_PROP_XI_LENS_APERTURE_VALUE = 512, CV_CAP_PROP_XI_LENS_FOCUS_MOVEMENT_VALUE = 513, CV_CAP_PROP_XI_LENS_FOCUS_MOVE = 514, CV_CAP_PROP_XI_LENS_FOCUS_DISTANCE = 515, CV_CAP_PROP_XI_LENS_FOCAL_LENGTH = 516, CV_CAP_PROP_XI_LENS_FEATURE_SELECTOR = 517, CV_CAP_PROP_XI_LENS_FEATURE = 518, CV_CAP_PROP_XI_DEVICE_MODEL_ID = 521, CV_CAP_PROP_XI_DEVICE_SN = 522, CV_CAP_PROP_XI_IMAGE_DATA_FORMAT_RGB32_ALPHA = 529, CV_CAP_PROP_XI_IMAGE_PAYLOAD_SIZE = 530, CV_CAP_PROP_XI_TRANSPORT_PIXEL_FORMAT = 531, CV_CAP_PROP_XI_SENSOR_CLOCK_FREQ_HZ = 532, CV_CAP_PROP_XI_SENSOR_CLOCK_FREQ_INDEX = 533, CV_CAP_PROP_XI_SENSOR_OUTPUT_CHANNEL_COUNT = 534, CV_CAP_PROP_XI_FRAMERATE = 535, CV_CAP_PROP_XI_COUNTER_SELECTOR = 536, CV_CAP_PROP_XI_COUNTER_VALUE = 537, CV_CAP_PROP_XI_ACQ_TIMING_MODE = 538, CV_CAP_PROP_XI_AVAILABLE_BANDWIDTH = 539, CV_CAP_PROP_XI_BUFFER_POLICY = 540, CV_CAP_PROP_XI_LUT_EN = 541, CV_CAP_PROP_XI_LUT_INDEX = 542, CV_CAP_PROP_XI_LUT_VALUE = 543, CV_CAP_PROP_XI_TRG_DELAY = 544, CV_CAP_PROP_XI_TS_RST_MODE = 545, CV_CAP_PROP_XI_TS_RST_SOURCE = 546, CV_CAP_PROP_XI_IS_DEVICE_EXIST = 547, CV_CAP_PROP_XI_ACQ_BUFFER_SIZE = 548, CV_CAP_PROP_XI_ACQ_BUFFER_SIZE_UNIT = 549, CV_CAP_PROP_XI_ACQ_TRANSPORT_BUFFER_SIZE = 550, CV_CAP_PROP_XI_BUFFERS_QUEUE_SIZE = 551, CV_CAP_PROP_XI_ACQ_TRANSPORT_BUFFER_COMMIT = 552, CV_CAP_PROP_XI_RECENT_FRAME = 553, CV_CAP_PROP_XI_DEVICE_RESET = 554, CV_CAP_PROP_XI_COLUMN_FPN_CORRECTION = 555, CV_CAP_PROP_XI_SENSOR_MODE = 558, CV_CAP_PROP_XI_HDR = 559, CV_CAP_PROP_XI_HDR_KNEEPOINT_COUNT = 560, CV_CAP_PROP_XI_HDR_T1 = 561, CV_CAP_PROP_XI_HDR_T2 = 562, CV_CAP_PROP_XI_KNEEPOINT1 = 563, CV_CAP_PROP_XI_KNEEPOINT2 = 564, CV_CAP_PROP_XI_IMAGE_BLACK_LEVEL = 565, CV_CAP_PROP_XI_HW_REVISION = 571, CV_CAP_PROP_XI_DEBUG_LEVEL = 572, CV_CAP_PROP_XI_AUTO_BANDWIDTH_CALCULATION = 573, CV_CAP_PROP_XI_FREE_FFS_SIZE = 581, CV_CAP_PROP_XI_USED_FFS_SIZE = 582, CV_CAP_PROP_XI_FFS_ACCESS_KEY = 583, CV_CAP_PROP_XI_SENSOR_FEATURE_SELECTOR = 585, CV_CAP_PROP_XI_SENSOR_FEATURE_VALUE = 586, CV_CAP_PROP_ANDROID_FLASH_MODE = 8001, CV_CAP_PROP_ANDROID_FOCUS_MODE = 8002, CV_CAP_PROP_ANDROID_WHITE_BALANCE = 8003, CV_CAP_PROP_ANDROID_ANTIBANDING = 8004, CV_CAP_PROP_ANDROID_FOCAL_LENGTH = 8005, CV_CAP_PROP_ANDROID_FOCUS_DISTANCE_NEAR = 8006, CV_CAP_PROP_ANDROID_FOCUS_DISTANCE_OPTIMAL = 8007, CV_CAP_PROP_ANDROID_FOCUS_DISTANCE_FAR = 8008, CV_CAP_PROP_ANDROID_EXPOSE_LOCK = 8009, CV_CAP_PROP_ANDROID_WHITEBALANCE_LOCK = 8010, CV_CAP_PROP_IOS_DEVICE_FOCUS = 9001, CV_CAP_PROP_IOS_DEVICE_EXPOSURE = 9002, CV_CAP_PROP_IOS_DEVICE_FLASH = 9003, CV_CAP_PROP_IOS_DEVICE_WHITEBALANCE = 9004, CV_CAP_PROP_IOS_DEVICE_TORCH = 9005, CV_CAP_PROP_GIGA_FRAME_OFFSET_X = 10001, CV_CAP_PROP_GIGA_FRAME_OFFSET_Y = 10002, CV_CAP_PROP_GIGA_FRAME_WIDTH_MAX = 10003, CV_CAP_PROP_GIGA_FRAME_HEIGH_MAX = 10004, CV_CAP_PROP_GIGA_FRAME_SENS_WIDTH = 10005, CV_CAP_PROP_GIGA_FRAME_SENS_HEIGH = 10006, CV_CAP_PROP_INTELPERC_PROFILE_COUNT = 11001, CV_CAP_PROP_INTELPERC_PROFILE_IDX = 11002, CV_CAP_PROP_INTELPERC_DEPTH_LOW_CONFIDENCE_VALUE = 11003, CV_CAP_PROP_INTELPERC_DEPTH_SATURATION_VALUE = 11004, CV_CAP_PROP_INTELPERC_DEPTH_CONFIDENCE_THRESHOLD = 11005, CV_CAP_PROP_INTELPERC_DEPTH_FOCAL_LENGTH_HORZ = 11006, CV_CAP_PROP_INTELPERC_DEPTH_FOCAL_LENGTH_VERT = 11007, CV_CAP_MODE_BGR = 0, CV_CAP_MODE_RGB = 1, CV_CAP_MODE_GRAY = 2, CV_CAP_MODE_YUYV = 3, CV_CAP_PROP_GPHOTO2_PREVIEW = 17001, CV_CAP_PROP_GPHOTO2_WIDGET_ENUMERATE = 17002, CV_CAP_PROP_GPHOTO2_RELOAD_CONFIG = 17003, CV_CAP_PROP_GPHOTO2_RELOAD_ON_CHANGE = 17004, CV_CAP_PROP_GPHOTO2_COLLECT_MSGS = 17005, CV_CAP_PROP_GPHOTO2_FLUSH_MSGS = 17006, CV_CAP_PROP_SPEED = 17007, CV_CAP_PROP_APERTURE = 17008, CV_CAP_PROP_VIEWFINDER = 17010, CAP_ANY = 0, CAP_VFW = 200, CAP_V4L = 200, CAP_V4L2 = CAP_V4L, CAP_FIREWARE = 300, CAP_FIREWIRE = CAP_FIREWARE, CAP_IEEE1394 = CAP_FIREWARE, CAP_DC1394 = CAP_FIREWARE, CAP_CMU1394 = CAP_FIREWARE, CAP_QT = 500, CAP_UNICAP = 600, CAP_DSHOW = 700, CAP_PVAPI = 800, CAP_OPENNI = 900, CAP_OPENNI_ASUS = 910, CAP_ANDROID = 1000, CAP_XIAPI = 1100, CAP_AVFOUNDATION = 1200, CAP_GIGANETIX = 1300, CAP_MSMF = 1400, CAP_WINRT = 1410, CAP_INTELPERC = 1500, CAP_OPENNI2 = 1600, CAP_OPENNI2_ASUS = 1610, CAP_GPHOTO2 = 1700, CAP_GSTREAMER = 1800, CAP_FFMPEG = 1900, CAP_IMAGES = 2000, CAP_PROP_POS_MSEC = 0, CAP_PROP_POS_FRAMES = 1, CAP_PROP_POS_AVI_RATIO = 2, CAP_PROP_FRAME_WIDTH = 3, CAP_PROP_FRAME_HEIGHT = 4, CAP_PROP_FPS = 5, CAP_PROP_FOURCC = 6, CAP_PROP_FRAME_COUNT = 7, CAP_PROP_FORMAT = 8, CAP_PROP_MODE = 9, CAP_PROP_BRIGHTNESS = 10, CAP_PROP_CONTRAST = 11, CAP_PROP_SATURATION = 12, CAP_PROP_HUE = 13, CAP_PROP_GAIN = 14, CAP_PROP_EXPOSURE = 15, CAP_PROP_CONVERT_RGB = 16, CAP_PROP_WHITE_BALANCE_BLUE_U = 17, CAP_PROP_RECTIFICATION = 18, CAP_PROP_MONOCHROME = 19, CAP_PROP_SHARPNESS = 20, CAP_PROP_AUTO_EXPOSURE = 21, CAP_PROP_GAMMA = 22, CAP_PROP_TEMPERATURE = 23, CAP_PROP_TRIGGER = 24, CAP_PROP_TRIGGER_DELAY = 25, CAP_PROP_WHITE_BALANCE_RED_V = 26, CAP_PROP_ZOOM = 27, CAP_PROP_FOCUS = 28, CAP_PROP_GUID = 29, CAP_PROP_ISO_SPEED = 30, CAP_PROP_BACKLIGHT = 32, CAP_PROP_PAN = 33, CAP_PROP_TILT = 34, CAP_PROP_ROLL = 35, CAP_PROP_IRIS = 36, CAP_PROP_SETTINGS = 37, CAP_PROP_BUFFERSIZE = 38, CAP_PROP_AUTOFOCUS = 39, CAP_MODE_BGR = 0, CAP_MODE_RGB = 1, CAP_MODE_GRAY = 2, CAP_MODE_YUYV = 3, CAP_PROP_DC1394_OFF = -4, CAP_PROP_DC1394_MODE_MANUAL = -3, CAP_PROP_DC1394_MODE_AUTO = -2, CAP_PROP_DC1394_MODE_ONE_PUSH_AUTO = -1, CAP_PROP_DC1394_MAX = 31, CAP_OPENNI_DEPTH_GENERATOR = 1 << 31, CAP_OPENNI_IMAGE_GENERATOR = 1 << 30, CAP_OPENNI_GENERATORS_MASK = CAP_OPENNI_DEPTH_GENERATOR + CAP_OPENNI_IMAGE_GENERATOR, CAP_PROP_OPENNI_OUTPUT_MODE = 100, CAP_PROP_OPENNI_FRAME_MAX_DEPTH = 101, CAP_PROP_OPENNI_BASELINE = 102, CAP_PROP_OPENNI_FOCAL_LENGTH = 103, CAP_PROP_OPENNI_REGISTRATION = 104, CAP_PROP_OPENNI_REGISTRATION_ON = CAP_PROP_OPENNI_REGISTRATION, CAP_PROP_OPENNI_APPROX_FRAME_SYNC = 105, CAP_PROP_OPENNI_MAX_BUFFER_SIZE = 106, CAP_PROP_OPENNI_CIRCLE_BUFFER = 107, CAP_PROP_OPENNI_MAX_TIME_DURATION = 108, CAP_PROP_OPENNI_GENERATOR_PRESENT = 109, CAP_PROP_OPENNI2_SYNC = 110, CAP_PROP_OPENNI2_MIRROR = 111, CAP_OPENNI_IMAGE_GENERATOR_PRESENT = CAP_OPENNI_IMAGE_GENERATOR + CAP_PROP_OPENNI_GENERATOR_PRESENT, CAP_OPENNI_IMAGE_GENERATOR_OUTPUT_MODE = CAP_OPENNI_IMAGE_GENERATOR + CAP_PROP_OPENNI_OUTPUT_MODE, CAP_OPENNI_DEPTH_GENERATOR_BASELINE = CAP_OPENNI_DEPTH_GENERATOR + CAP_PROP_OPENNI_BASELINE, CAP_OPENNI_DEPTH_GENERATOR_FOCAL_LENGTH = CAP_OPENNI_DEPTH_GENERATOR + CAP_PROP_OPENNI_FOCAL_LENGTH, CAP_OPENNI_DEPTH_GENERATOR_REGISTRATION = CAP_OPENNI_DEPTH_GENERATOR + CAP_PROP_OPENNI_REGISTRATION, CAP_OPENNI_DEPTH_GENERATOR_REGISTRATION_ON = CAP_OPENNI_DEPTH_GENERATOR_REGISTRATION, CAP_OPENNI_DEPTH_MAP = 0, CAP_OPENNI_POINT_CLOUD_MAP = 1, CAP_OPENNI_DISPARITY_MAP = 2, CAP_OPENNI_DISPARITY_MAP_32F = 3, CAP_OPENNI_VALID_DEPTH_MASK = 4, CAP_OPENNI_BGR_IMAGE = 5, CAP_OPENNI_GRAY_IMAGE = 6, CAP_OPENNI_VGA_30HZ = 0, CAP_OPENNI_SXGA_15HZ = 1, CAP_OPENNI_SXGA_30HZ = 2, CAP_OPENNI_QVGA_30HZ = 3, CAP_OPENNI_QVGA_60HZ = 4, CAP_PROP_GSTREAMER_QUEUE_LENGTH = 200, CAP_PROP_PVAPI_MULTICASTIP = 300, CAP_PROP_PVAPI_FRAMESTARTTRIGGERMODE = 301, CAP_PROP_PVAPI_DECIMATIONHORIZONTAL = 302, CAP_PROP_PVAPI_DECIMATIONVERTICAL = 303, CAP_PROP_PVAPI_BINNINGX = 304, CAP_PROP_PVAPI_BINNINGY = 305, CAP_PROP_PVAPI_PIXELFORMAT = 306, CAP_PVAPI_FSTRIGMODE_FREERUN = 0, CAP_PVAPI_FSTRIGMODE_SYNCIN1 = 1, CAP_PVAPI_FSTRIGMODE_SYNCIN2 = 2, CAP_PVAPI_FSTRIGMODE_FIXEDRATE = 3, CAP_PVAPI_FSTRIGMODE_SOFTWARE = 4, CAP_PVAPI_DECIMATION_OFF = 1, CAP_PVAPI_DECIMATION_2OUTOF4 = 2, CAP_PVAPI_DECIMATION_2OUTOF8 = 4, CAP_PVAPI_DECIMATION_2OUTOF16 = 8, CAP_PVAPI_PIXELFORMAT_MONO8 = 1, CAP_PVAPI_PIXELFORMAT_MONO16 = 2, CAP_PVAPI_PIXELFORMAT_BAYER8 = 3, CAP_PVAPI_PIXELFORMAT_BAYER16 = 4, CAP_PVAPI_PIXELFORMAT_RGB24 = 5, CAP_PVAPI_PIXELFORMAT_BGR24 = 6, CAP_PVAPI_PIXELFORMAT_RGBA32 = 7, CAP_PVAPI_PIXELFORMAT_BGRA32 = 8, CAP_PROP_XI_DOWNSAMPLING = 400, CAP_PROP_XI_DATA_FORMAT = 401, CAP_PROP_XI_OFFSET_X = 402, CAP_PROP_XI_OFFSET_Y = 403, CAP_PROP_XI_TRG_SOURCE = 404, CAP_PROP_XI_TRG_SOFTWARE = 405, CAP_PROP_XI_GPI_SELECTOR = 406, CAP_PROP_XI_GPI_MODE = 407, CAP_PROP_XI_GPI_LEVEL = 408, CAP_PROP_XI_GPO_SELECTOR = 409, CAP_PROP_XI_GPO_MODE = 410, CAP_PROP_XI_LED_SELECTOR = 411, CAP_PROP_XI_LED_MODE = 412, CAP_PROP_XI_MANUAL_WB = 413, CAP_PROP_XI_AUTO_WB = 414, CAP_PROP_XI_AEAG = 415, CAP_PROP_XI_EXP_PRIORITY = 416, CAP_PROP_XI_AE_MAX_LIMIT = 417, CAP_PROP_XI_AG_MAX_LIMIT = 418, CAP_PROP_XI_AEAG_LEVEL = 419, CAP_PROP_XI_TIMEOUT = 420, CAP_PROP_IOS_DEVICE_FOCUS = 9001, CAP_PROP_IOS_DEVICE_EXPOSURE = 9002, CAP_PROP_IOS_DEVICE_FLASH = 9003, CAP_PROP_IOS_DEVICE_WHITEBALANCE = 9004, CAP_PROP_IOS_DEVICE_TORCH = 9005, CAP_PROP_GIGA_FRAME_OFFSET_X = 10001, CAP_PROP_GIGA_FRAME_OFFSET_Y = 10002, CAP_PROP_GIGA_FRAME_WIDTH_MAX = 10003, CAP_PROP_GIGA_FRAME_HEIGH_MAX = 10004, CAP_PROP_GIGA_FRAME_SENS_WIDTH = 10005, CAP_PROP_GIGA_FRAME_SENS_HEIGH = 10006, CAP_PROP_INTELPERC_PROFILE_COUNT = 11001, CAP_PROP_INTELPERC_PROFILE_IDX = 11002, CAP_PROP_INTELPERC_DEPTH_LOW_CONFIDENCE_VALUE = 11003, CAP_PROP_INTELPERC_DEPTH_SATURATION_VALUE = 11004, CAP_PROP_INTELPERC_DEPTH_CONFIDENCE_THRESHOLD = 11005, CAP_PROP_INTELPERC_DEPTH_FOCAL_LENGTH_HORZ = 11006, CAP_PROP_INTELPERC_DEPTH_FOCAL_LENGTH_VERT = 11007, CAP_INTELPERC_DEPTH_GENERATOR = 1 << 29, CAP_INTELPERC_IMAGE_GENERATOR = 1 << 28, CAP_INTELPERC_GENERATORS_MASK = CAP_INTELPERC_DEPTH_GENERATOR + CAP_INTELPERC_IMAGE_GENERATOR, CAP_INTELPERC_DEPTH_MAP = 0, CAP_INTELPERC_UVDEPTH_MAP = 1, CAP_INTELPERC_IR_MAP = 2, CAP_INTELPERC_IMAGE = 3, VIDEOWRITER_PROP_QUALITY = 1, VIDEOWRITER_PROP_FRAMEBYTES = 2, VIDEOWRITER_PROP_NSTRIPES = 3, CAP_PROP_GPHOTO2_PREVIEW = 17001, CAP_PROP_GPHOTO2_WIDGET_ENUMERATE = 17002, CAP_PROP_GPHOTO2_RELOAD_CONFIG = 17003, CAP_PROP_GPHOTO2_RELOAD_ON_CHANGE = 17004, CAP_PROP_GPHOTO2_COLLECT_MSGS = 17005, CAP_PROP_GPHOTO2_FLUSH_MSGS = 17006, CAP_PROP_SPEED = 17007, CAP_PROP_APERTURE = 17008, CAP_PROP_EXPOSUREPROGRAM = 17009, CAP_PROP_VIEWFINDER = 17010; }
19,298
43.881395
112
java
uiHRDC
uiHRDC-master/uiHRDC/indexes/NOPOS/II_docs_large/ilists.imp/6.vbyteP7zip_acabadoMerge2yN[Fork]/lzmalib/lzma.sourceCode/LZMAFARI_LIB/lzma465/Java/SevenZip/CRC.java
// SevenZip/CRC.java package SevenZip; public class CRC { static public int[] Table = new int[256]; static { for (int i = 0; i < 256; i++) { int r = i; for (int j = 0; j < 8; j++) if ((r & 1) != 0) r = (r >>> 1) ^ 0xEDB88320; else r >>>= 1; Table[i] = r; } } int _value = -1; public void Init() { _value = -1; } public void Update(byte[] data, int offset, int size) { for (int i = 0; i < size; i++) _value = Table[(_value ^ data[offset + i]) & 0xFF] ^ (_value >>> 8); } public void Update(byte[] data) { int size = data.length; for (int i = 0; i < size; i++) _value = Table[(_value ^ data[i]) & 0xFF] ^ (_value >>> 8); } public void UpdateByte(int b) { _value = Table[(_value ^ b) & 0xFF] ^ (_value >>> 8); } public int GetDigest() { return _value ^ (-1); } }
847
15
71
java
uiHRDC
uiHRDC-master/uiHRDC/indexes/NOPOS/II_docs_large/ilists.imp/6.vbyteP7zip_acabadoMerge2yN[Fork]/lzmalib/lzma.sourceCode/LZMAFARI_LIB/lzma465/Java/SevenZip/ICodeProgress.java
package SevenZip; public interface ICodeProgress { public void SetProgress(long inSize, long outSize); }
107
14.428571
52
java
uiHRDC
uiHRDC-master/uiHRDC/indexes/NOPOS/II_docs_large/ilists.imp/6.vbyteP7zip_acabadoMerge2yN[Fork]/lzmalib/lzma.sourceCode/LZMAFARI_LIB/lzma465/Java/SevenZip/LzmaAlone.java
package SevenZip; public class LzmaAlone { static public class CommandLine { public static final int kEncode = 0; public static final int kDecode = 1; public static final int kBenchmak = 2; public int Command = -1; public int NumBenchmarkPasses = 10; public int DictionarySize = 1 << 23; public boolean DictionarySizeIsDefined = false; public int Lc = 3; public int Lp = 0; public int Pb = 2; public int Fb = 128; public boolean FbIsDefined = false; public boolean Eos = false; public int Algorithm = 2; public int MatchFinder = 1; public String InFile; public String OutFile; boolean ParseSwitch(String s) { if (s.startsWith("d")) { DictionarySize = 1 << Integer.parseInt(s.substring(1)); DictionarySizeIsDefined = true; } else if (s.startsWith("fb")) { Fb = Integer.parseInt(s.substring(2)); FbIsDefined = true; } else if (s.startsWith("a")) Algorithm = Integer.parseInt(s.substring(1)); else if (s.startsWith("lc")) Lc = Integer.parseInt(s.substring(2)); else if (s.startsWith("lp")) Lp = Integer.parseInt(s.substring(2)); else if (s.startsWith("pb")) Pb = Integer.parseInt(s.substring(2)); else if (s.startsWith("eos")) Eos = true; else if (s.startsWith("mf")) { String mfs = s.substring(2); if (mfs.equals("bt2")) MatchFinder = 0; else if (mfs.equals("bt4")) MatchFinder = 1; else if (mfs.equals("bt4b")) MatchFinder = 2; else return false; } else return false; return true; } public boolean Parse(String[] args) throws Exception { int pos = 0; boolean switchMode = true; for (int i = 0; i < args.length; i++) { String s = args[i]; if (s.length() == 0) return false; if (switchMode) { if (s.compareTo("--") == 0) { switchMode = false; continue; } if (s.charAt(0) == '-') { String sw = s.substring(1).toLowerCase(); if (sw.length() == 0) return false; try { if (!ParseSwitch(sw)) return false; } catch (NumberFormatException e) { return false; } continue; } } if (pos == 0) { if (s.equalsIgnoreCase("e")) Command = kEncode; else if (s.equalsIgnoreCase("d")) Command = kDecode; else if (s.equalsIgnoreCase("b")) Command = kBenchmak; else return false; } else if(pos == 1) { if (Command == kBenchmak) { try { NumBenchmarkPasses = Integer.parseInt(s); if (NumBenchmarkPasses < 1) return false; } catch (NumberFormatException e) { return false; } } else InFile = s; } else if(pos == 2) OutFile = s; else return false; pos++; continue; } return true; } } static void PrintHelp() { System.out.println( "\nUsage: LZMA <e|d> [<switches>...] inputFile outputFile\n" + " e: encode file\n" + " d: decode file\n" + " b: Benchmark\n" + "<Switches>\n" + // " -a{N}: set compression mode - [0, 1], default: 1 (max)\n" + " -d{N}: set dictionary - [0,28], default: 23 (8MB)\n" + " -fb{N}: set number of fast bytes - [5, 273], default: 128\n" + " -lc{N}: set number of literal context bits - [0, 8], default: 3\n" + " -lp{N}: set number of literal pos bits - [0, 4], default: 0\n" + " -pb{N}: set number of pos bits - [0, 4], default: 2\n" + " -mf{MF_ID}: set Match Finder: [bt2, bt4], default: bt4\n" + " -eos: write End Of Stream marker\n" ); } public static void main(String[] args) throws Exception { System.out.println("\nLZMA (Java) 4.61 2008-11-23\n"); if (args.length < 1) { PrintHelp(); return; } CommandLine params = new CommandLine(); if (!params.Parse(args)) { System.out.println("\nIncorrect command"); return; } if (params.Command == CommandLine.kBenchmak) { int dictionary = (1 << 21); if (params.DictionarySizeIsDefined) dictionary = params.DictionarySize; if (params.MatchFinder > 1) throw new Exception("Unsupported match finder"); SevenZip.LzmaBench.LzmaBenchmark(params.NumBenchmarkPasses, dictionary); } else if (params.Command == CommandLine.kEncode || params.Command == CommandLine.kDecode) { java.io.File inFile = new java.io.File(params.InFile); java.io.File outFile = new java.io.File(params.OutFile); java.io.BufferedInputStream inStream = new java.io.BufferedInputStream(new java.io.FileInputStream(inFile)); java.io.BufferedOutputStream outStream = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outFile)); boolean eos = false; if (params.Eos) eos = true; if (params.Command == CommandLine.kEncode) { SevenZip.Compression.LZMA.Encoder encoder = new SevenZip.Compression.LZMA.Encoder(); if (!encoder.SetAlgorithm(params.Algorithm)) throw new Exception("Incorrect compression mode"); if (!encoder.SetDictionarySize(params.DictionarySize)) throw new Exception("Incorrect dictionary size"); if (!encoder.SetNumFastBytes(params.Fb)) throw new Exception("Incorrect -fb value"); if (!encoder.SetMatchFinder(params.MatchFinder)) throw new Exception("Incorrect -mf value"); if (!encoder.SetLcLpPb(params.Lc, params.Lp, params.Pb)) throw new Exception("Incorrect -lc or -lp or -pb value"); encoder.SetEndMarkerMode(eos); encoder.WriteCoderProperties(outStream); long fileSize; if (eos) fileSize = -1; else fileSize = inFile.length(); for (int i = 0; i < 8; i++) outStream.write((int)(fileSize >>> (8 * i)) & 0xFF); encoder.Code(inStream, outStream, -1, -1, null); } else { int propertiesSize = 5; byte[] properties = new byte[propertiesSize]; if (inStream.read(properties, 0, propertiesSize) != propertiesSize) throw new Exception("input .lzma file is too short"); SevenZip.Compression.LZMA.Decoder decoder = new SevenZip.Compression.LZMA.Decoder(); if (!decoder.SetDecoderProperties(properties)) throw new Exception("Incorrect stream properties"); long outSize = 0; for (int i = 0; i < 8; i++) { int v = inStream.read(); if (v < 0) throw new Exception("Can't read stream size"); outSize |= ((long)v) << (8 * i); } if (!decoder.Code(inStream, outStream, outSize)) throw new Exception("Error in data stream"); } outStream.flush(); outStream.close(); inStream.close(); } else throw new Exception("Incorrect command"); return; } }
6,695
25.362205
116
java
uiHRDC
uiHRDC-master/uiHRDC/indexes/NOPOS/II_docs_large/ilists.imp/6.vbyteP7zip_acabadoMerge2yN[Fork]/lzmalib/lzma.sourceCode/LZMAFARI_LIB/lzma465/Java/SevenZip/LzmaBench.java
package SevenZip; import java.io.ByteArrayOutputStream; import java.io.ByteArrayInputStream; import java.io.IOException; public class LzmaBench { static final int kAdditionalSize = (1 << 21); static final int kCompressedAdditionalSize = (1 << 10); static class CRandomGenerator { int A1; int A2; public CRandomGenerator() { Init(); } public void Init() { A1 = 362436069; A2 = 521288629; } public int GetRnd() { return ((A1 = 36969 * (A1 & 0xffff) + (A1 >>> 16)) << 16) ^ ((A2 = 18000 * (A2 & 0xffff) + (A2 >>> 16))); } }; static class CBitRandomGenerator { CRandomGenerator RG = new CRandomGenerator(); int Value; int NumBits; public void Init() { Value = 0; NumBits = 0; } public int GetRnd(int numBits) { int result; if (NumBits > numBits) { result = Value & ((1 << numBits) - 1); Value >>>= numBits; NumBits -= numBits; return result; } numBits -= NumBits; result = (Value << numBits); Value = RG.GetRnd(); result |= Value & (((int)1 << numBits) - 1); Value >>>= numBits; NumBits = 32 - numBits; return result; } }; static class CBenchRandomGenerator { CBitRandomGenerator RG = new CBitRandomGenerator(); int Pos; int Rep0; public int BufferSize; public byte[] Buffer = null; public CBenchRandomGenerator() { } public void Set(int bufferSize) { Buffer = new byte[bufferSize]; Pos = 0; BufferSize = bufferSize; } int GetRndBit() { return RG.GetRnd(1); } int GetLogRandBits(int numBits) { int len = RG.GetRnd(numBits); return RG.GetRnd((int)len); } int GetOffset() { if (GetRndBit() == 0) return GetLogRandBits(4); return (GetLogRandBits(4) << 10) | RG.GetRnd(10); } int GetLen1() { return RG.GetRnd(1 + (int)RG.GetRnd(2)); } int GetLen2() { return RG.GetRnd(2 + (int)RG.GetRnd(2)); } public void Generate() { RG.Init(); Rep0 = 1; while (Pos < BufferSize) { if (GetRndBit() == 0 || Pos < 1) Buffer[Pos++] = (byte)(RG.GetRnd(8)); else { int len; if (RG.GetRnd(3) == 0) len = 1 + GetLen1(); else { do Rep0 = GetOffset(); while (Rep0 >= Pos); Rep0++; len = 2 + GetLen2(); } for (int i = 0; i < len && Pos < BufferSize; i++, Pos++) Buffer[Pos] = Buffer[Pos - Rep0]; } } } }; static class CrcOutStream extends java.io.OutputStream { public CRC CRC = new CRC(); public void Init() { CRC.Init(); } public int GetDigest() { return CRC.GetDigest(); } public void write(byte[] b) { CRC.Update(b); } public void write(byte[] b, int off, int len) { CRC.Update(b, off, len); } public void write(int b) { CRC.UpdateByte(b); } }; static class MyOutputStream extends java.io.OutputStream { byte[] _buffer; int _size; int _pos; public MyOutputStream(byte[] buffer) { _buffer = buffer; _size = _buffer.length; } public void reset() { _pos = 0; } public void write(int b) throws IOException { if (_pos >= _size) throw new IOException("Error"); _buffer[_pos++] = (byte)b; } public int size() { return _pos; } }; static class MyInputStream extends java.io.InputStream { byte[] _buffer; int _size; int _pos; public MyInputStream(byte[] buffer, int size) { _buffer = buffer; _size = size; } public void reset() { _pos = 0; } public int read() { if (_pos >= _size) return -1; return _buffer[_pos++] & 0xFF; } }; static class CProgressInfo implements ICodeProgress { public long ApprovedStart; public long InSize; public long Time; public void Init() { InSize = 0; } public void SetProgress(long inSize, long outSize) { if (inSize >= ApprovedStart && InSize == 0) { Time = System.currentTimeMillis(); InSize = inSize; } } } static final int kSubBits = 8; static int GetLogSize(int size) { for (int i = kSubBits; i < 32; i++) for (int j = 0; j < (1 << kSubBits); j++) if (size <= ((1) << i) + (j << (i - kSubBits))) return (i << kSubBits) + j; return (32 << kSubBits); } static long MyMultDiv64(long value, long elapsedTime) { long freq = 1000; // ms long elTime = elapsedTime; while (freq > 1000000) { freq >>>= 1; elTime >>>= 1; } if (elTime == 0) elTime = 1; return value * freq / elTime; } static long GetCompressRating(int dictionarySize, long elapsedTime, long size) { long t = GetLogSize(dictionarySize) - (18 << kSubBits); long numCommandsForOne = 1060 + ((t * t * 10) >> (2 * kSubBits)); long numCommands = (long)(size) * numCommandsForOne; return MyMultDiv64(numCommands, elapsedTime); } static long GetDecompressRating(long elapsedTime, long outSize, long inSize) { long numCommands = inSize * 220 + outSize * 20; return MyMultDiv64(numCommands, elapsedTime); } static long GetTotalRating( int dictionarySize, long elapsedTimeEn, long sizeEn, long elapsedTimeDe, long inSizeDe, long outSizeDe) { return (GetCompressRating(dictionarySize, elapsedTimeEn, sizeEn) + GetDecompressRating(elapsedTimeDe, inSizeDe, outSizeDe)) / 2; } static void PrintValue(long v) { String s = ""; s += v; for (int i = 0; i + s.length() < 6; i++) System.out.print(" "); System.out.print(s); } static void PrintRating(long rating) { PrintValue(rating / 1000000); System.out.print(" MIPS"); } static void PrintResults( int dictionarySize, long elapsedTime, long size, boolean decompressMode, long secondSize) { long speed = MyMultDiv64(size, elapsedTime); PrintValue(speed / 1024); System.out.print(" KB/s "); long rating; if (decompressMode) rating = GetDecompressRating(elapsedTime, size, secondSize); else rating = GetCompressRating(dictionarySize, elapsedTime, size); PrintRating(rating); } static public int LzmaBenchmark(int numIterations, int dictionarySize) throws Exception { if (numIterations <= 0) return 0; if (dictionarySize < (1 << 18)) { System.out.println("\nError: dictionary size for benchmark must be >= 18 (256 KB)"); return 1; } System.out.print("\n Compressing Decompressing\n\n"); SevenZip.Compression.LZMA.Encoder encoder = new SevenZip.Compression.LZMA.Encoder(); SevenZip.Compression.LZMA.Decoder decoder = new SevenZip.Compression.LZMA.Decoder(); if (!encoder.SetDictionarySize(dictionarySize)) throw new Exception("Incorrect dictionary size"); int kBufferSize = dictionarySize + kAdditionalSize; int kCompressedBufferSize = (kBufferSize / 2) + kCompressedAdditionalSize; ByteArrayOutputStream propStream = new ByteArrayOutputStream(); encoder.WriteCoderProperties(propStream); byte[] propArray = propStream.toByteArray(); decoder.SetDecoderProperties(propArray); CBenchRandomGenerator rg = new CBenchRandomGenerator(); rg.Set(kBufferSize); rg.Generate(); CRC crc = new CRC(); crc.Init(); crc.Update(rg.Buffer, 0, rg.BufferSize); CProgressInfo progressInfo = new CProgressInfo(); progressInfo.ApprovedStart = dictionarySize; long totalBenchSize = 0; long totalEncodeTime = 0; long totalDecodeTime = 0; long totalCompressedSize = 0; MyInputStream inStream = new MyInputStream(rg.Buffer, rg.BufferSize); byte[] compressedBuffer = new byte[kCompressedBufferSize]; MyOutputStream compressedStream = new MyOutputStream(compressedBuffer); CrcOutStream crcOutStream = new CrcOutStream(); MyInputStream inputCompressedStream = null; int compressedSize = 0; for (int i = 0; i < numIterations; i++) { progressInfo.Init(); inStream.reset(); compressedStream.reset(); encoder.Code(inStream, compressedStream, -1, -1, progressInfo); long encodeTime = System.currentTimeMillis() - progressInfo.Time; if (i == 0) { compressedSize = compressedStream.size(); inputCompressedStream = new MyInputStream(compressedBuffer, compressedSize); } else if (compressedSize != compressedStream.size()) throw (new Exception("Encoding error")); if (progressInfo.InSize == 0) throw (new Exception("Internal ERROR 1282")); long decodeTime = 0; for (int j = 0; j < 2; j++) { inputCompressedStream.reset(); crcOutStream.Init(); long outSize = kBufferSize; long startTime = System.currentTimeMillis(); if (!decoder.Code(inputCompressedStream, crcOutStream, outSize)) throw (new Exception("Decoding Error"));; decodeTime = System.currentTimeMillis() - startTime; if (crcOutStream.GetDigest() != crc.GetDigest()) throw (new Exception("CRC Error")); } long benchSize = kBufferSize - (long)progressInfo.InSize; PrintResults(dictionarySize, encodeTime, benchSize, false, 0); System.out.print(" "); PrintResults(dictionarySize, decodeTime, kBufferSize, true, compressedSize); System.out.println(); totalBenchSize += benchSize; totalEncodeTime += encodeTime; totalDecodeTime += decodeTime; totalCompressedSize += compressedSize; } System.out.println("---------------------------------------------------"); PrintResults(dictionarySize, totalEncodeTime, totalBenchSize, false, 0); System.out.print(" "); PrintResults(dictionarySize, totalDecodeTime, kBufferSize * (long)numIterations, true, totalCompressedSize); System.out.println(" Average"); return 0; } }
9,483
23.132316
88
java
uiHRDC
uiHRDC-master/uiHRDC/indexes/NOPOS/II_docs_large/ilists.imp/6.vbyteP7zip_acabadoMerge2yN[Fork]/lzmalib/lzma.sourceCode/LZMAFARI_LIB/lzma465/Java/SevenZip/Compression/LZ/OutWindow.java
// LZ.OutWindow package SevenZip.Compression.LZ; import java.io.IOException; public class OutWindow { byte[] _buffer; int _pos; int _windowSize = 0; int _streamPos; java.io.OutputStream _stream; public void Create(int windowSize) { if (_buffer == null || _windowSize != windowSize) _buffer = new byte[windowSize]; _windowSize = windowSize; _pos = 0; _streamPos = 0; } public void SetStream(java.io.OutputStream stream) throws IOException { ReleaseStream(); _stream = stream; } public void ReleaseStream() throws IOException { Flush(); _stream = null; } public void Init(boolean solid) { if (!solid) { _streamPos = 0; _pos = 0; } } public void Flush() throws IOException { int size = _pos - _streamPos; if (size == 0) return; _stream.write(_buffer, _streamPos, size); if (_pos >= _windowSize) _pos = 0; _streamPos = _pos; } public void CopyBlock(int distance, int len) throws IOException { int pos = _pos - distance - 1; if (pos < 0) pos += _windowSize; for (; len != 0; len--) { if (pos >= _windowSize) pos = 0; _buffer[_pos++] = _buffer[pos++]; if (_pos >= _windowSize) Flush(); } } public void PutByte(byte b) throws IOException { _buffer[_pos++] = b; if (_pos >= _windowSize) Flush(); } public byte GetByte(int distance) { int pos = _pos - distance - 1; if (pos < 0) pos += _windowSize; return _buffer[pos]; } }
1,456
15.94186
70
java
uiHRDC
uiHRDC-master/uiHRDC/indexes/NOPOS/II_docs_large/ilists.imp/6.vbyteP7zip_acabadoMerge2yN[Fork]/lzmalib/lzma.sourceCode/LZMAFARI_LIB/lzma465/Java/SevenZip/Compression/LZ/BinTree.java
// LZ.BinTree package SevenZip.Compression.LZ; import java.io.IOException; public class BinTree extends InWindow { int _cyclicBufferPos; int _cyclicBufferSize = 0; int _matchMaxLen; int[] _son; int[] _hash; int _cutValue = 0xFF; int _hashMask; int _hashSizeSum = 0; boolean HASH_ARRAY = true; static final int kHash2Size = 1 << 10; static final int kHash3Size = 1 << 16; static final int kBT2HashSize = 1 << 16; static final int kStartMaxLen = 1; static final int kHash3Offset = kHash2Size; static final int kEmptyHashValue = 0; static final int kMaxValForNormalize = (1 << 30) - 1; int kNumHashDirectBytes = 0; int kMinMatchCheck = 4; int kFixHashSize = kHash2Size + kHash3Size; public void SetType(int numHashBytes) { HASH_ARRAY = (numHashBytes > 2); if (HASH_ARRAY) { kNumHashDirectBytes = 0; kMinMatchCheck = 4; kFixHashSize = kHash2Size + kHash3Size; } else { kNumHashDirectBytes = 2; kMinMatchCheck = 2 + 1; kFixHashSize = 0; } } public void Init() throws IOException { super.Init(); for (int i = 0; i < _hashSizeSum; i++) _hash[i] = kEmptyHashValue; _cyclicBufferPos = 0; ReduceOffsets(-1); } public void MovePos() throws IOException { if (++_cyclicBufferPos >= _cyclicBufferSize) _cyclicBufferPos = 0; super.MovePos(); if (_pos == kMaxValForNormalize) Normalize(); } public boolean Create(int historySize, int keepAddBufferBefore, int matchMaxLen, int keepAddBufferAfter) { if (historySize > kMaxValForNormalize - 256) return false; _cutValue = 16 + (matchMaxLen >> 1); int windowReservSize = (historySize + keepAddBufferBefore + matchMaxLen + keepAddBufferAfter) / 2 + 256; super.Create(historySize + keepAddBufferBefore, matchMaxLen + keepAddBufferAfter, windowReservSize); _matchMaxLen = matchMaxLen; int cyclicBufferSize = historySize + 1; if (_cyclicBufferSize != cyclicBufferSize) _son = new int[(_cyclicBufferSize = cyclicBufferSize) * 2]; int hs = kBT2HashSize; if (HASH_ARRAY) { hs = historySize - 1; hs |= (hs >> 1); hs |= (hs >> 2); hs |= (hs >> 4); hs |= (hs >> 8); hs >>= 1; hs |= 0xFFFF; if (hs > (1 << 24)) hs >>= 1; _hashMask = hs; hs++; hs += kFixHashSize; } if (hs != _hashSizeSum) _hash = new int [_hashSizeSum = hs]; return true; } public int GetMatches(int[] distances) throws IOException { int lenLimit; if (_pos + _matchMaxLen <= _streamPos) lenLimit = _matchMaxLen; else { lenLimit = _streamPos - _pos; if (lenLimit < kMinMatchCheck) { MovePos(); return 0; } } int offset = 0; int matchMinPos = (_pos > _cyclicBufferSize) ? (_pos - _cyclicBufferSize) : 0; int cur = _bufferOffset + _pos; int maxLen = kStartMaxLen; // to avoid items for len < hashSize; int hashValue, hash2Value = 0, hash3Value = 0; if (HASH_ARRAY) { int temp = CrcTable[_bufferBase[cur] & 0xFF] ^ (_bufferBase[cur + 1] & 0xFF); hash2Value = temp & (kHash2Size - 1); temp ^= ((int)(_bufferBase[cur + 2] & 0xFF) << 8); hash3Value = temp & (kHash3Size - 1); hashValue = (temp ^ (CrcTable[_bufferBase[cur + 3] & 0xFF] << 5)) & _hashMask; } else hashValue = ((_bufferBase[cur] & 0xFF) ^ ((int)(_bufferBase[cur + 1] & 0xFF) << 8)); int curMatch = _hash[kFixHashSize + hashValue]; if (HASH_ARRAY) { int curMatch2 = _hash[hash2Value]; int curMatch3 = _hash[kHash3Offset + hash3Value]; _hash[hash2Value] = _pos; _hash[kHash3Offset + hash3Value] = _pos; if (curMatch2 > matchMinPos) if (_bufferBase[_bufferOffset + curMatch2] == _bufferBase[cur]) { distances[offset++] = maxLen = 2; distances[offset++] = _pos - curMatch2 - 1; } if (curMatch3 > matchMinPos) if (_bufferBase[_bufferOffset + curMatch3] == _bufferBase[cur]) { if (curMatch3 == curMatch2) offset -= 2; distances[offset++] = maxLen = 3; distances[offset++] = _pos - curMatch3 - 1; curMatch2 = curMatch3; } if (offset != 0 && curMatch2 == curMatch) { offset -= 2; maxLen = kStartMaxLen; } } _hash[kFixHashSize + hashValue] = _pos; int ptr0 = (_cyclicBufferPos << 1) + 1; int ptr1 = (_cyclicBufferPos << 1); int len0, len1; len0 = len1 = kNumHashDirectBytes; if (kNumHashDirectBytes != 0) { if (curMatch > matchMinPos) { if (_bufferBase[_bufferOffset + curMatch + kNumHashDirectBytes] != _bufferBase[cur + kNumHashDirectBytes]) { distances[offset++] = maxLen = kNumHashDirectBytes; distances[offset++] = _pos - curMatch - 1; } } } int count = _cutValue; while (true) { if (curMatch <= matchMinPos || count-- == 0) { _son[ptr0] = _son[ptr1] = kEmptyHashValue; break; } int delta = _pos - curMatch; int cyclicPos = ((delta <= _cyclicBufferPos) ? (_cyclicBufferPos - delta) : (_cyclicBufferPos - delta + _cyclicBufferSize)) << 1; int pby1 = _bufferOffset + curMatch; int len = Math.min(len0, len1); if (_bufferBase[pby1 + len] == _bufferBase[cur + len]) { while(++len != lenLimit) if (_bufferBase[pby1 + len] != _bufferBase[cur + len]) break; if (maxLen < len) { distances[offset++] = maxLen = len; distances[offset++] = delta - 1; if (len == lenLimit) { _son[ptr1] = _son[cyclicPos]; _son[ptr0] = _son[cyclicPos + 1]; break; } } } if ((_bufferBase[pby1 + len] & 0xFF) < (_bufferBase[cur + len] & 0xFF)) { _son[ptr1] = curMatch; ptr1 = cyclicPos + 1; curMatch = _son[ptr1]; len1 = len; } else { _son[ptr0] = curMatch; ptr0 = cyclicPos; curMatch = _son[ptr0]; len0 = len; } } MovePos(); return offset; } public void Skip(int num) throws IOException { do { int lenLimit; if (_pos + _matchMaxLen <= _streamPos) lenLimit = _matchMaxLen; else { lenLimit = _streamPos - _pos; if (lenLimit < kMinMatchCheck) { MovePos(); continue; } } int matchMinPos = (_pos > _cyclicBufferSize) ? (_pos - _cyclicBufferSize) : 0; int cur = _bufferOffset + _pos; int hashValue; if (HASH_ARRAY) { int temp = CrcTable[_bufferBase[cur] & 0xFF] ^ (_bufferBase[cur + 1] & 0xFF); int hash2Value = temp & (kHash2Size - 1); _hash[hash2Value] = _pos; temp ^= ((int)(_bufferBase[cur + 2] & 0xFF) << 8); int hash3Value = temp & (kHash3Size - 1); _hash[kHash3Offset + hash3Value] = _pos; hashValue = (temp ^ (CrcTable[_bufferBase[cur + 3] & 0xFF] << 5)) & _hashMask; } else hashValue = ((_bufferBase[cur] & 0xFF) ^ ((int)(_bufferBase[cur + 1] & 0xFF) << 8)); int curMatch = _hash[kFixHashSize + hashValue]; _hash[kFixHashSize + hashValue] = _pos; int ptr0 = (_cyclicBufferPos << 1) + 1; int ptr1 = (_cyclicBufferPos << 1); int len0, len1; len0 = len1 = kNumHashDirectBytes; int count = _cutValue; while (true) { if (curMatch <= matchMinPos || count-- == 0) { _son[ptr0] = _son[ptr1] = kEmptyHashValue; break; } int delta = _pos - curMatch; int cyclicPos = ((delta <= _cyclicBufferPos) ? (_cyclicBufferPos - delta) : (_cyclicBufferPos - delta + _cyclicBufferSize)) << 1; int pby1 = _bufferOffset + curMatch; int len = Math.min(len0, len1); if (_bufferBase[pby1 + len] == _bufferBase[cur + len]) { while (++len != lenLimit) if (_bufferBase[pby1 + len] != _bufferBase[cur + len]) break; if (len == lenLimit) { _son[ptr1] = _son[cyclicPos]; _son[ptr0] = _son[cyclicPos + 1]; break; } } if ((_bufferBase[pby1 + len] & 0xFF) < (_bufferBase[cur + len] & 0xFF)) { _son[ptr1] = curMatch; ptr1 = cyclicPos + 1; curMatch = _son[ptr1]; len1 = len; } else { _son[ptr0] = curMatch; ptr0 = cyclicPos; curMatch = _son[ptr0]; len0 = len; } } MovePos(); } while (--num != 0); } void NormalizeLinks(int[] items, int numItems, int subValue) { for (int i = 0; i < numItems; i++) { int value = items[i]; if (value <= subValue) value = kEmptyHashValue; else value -= subValue; items[i] = value; } } void Normalize() { int subValue = _pos - _cyclicBufferSize; NormalizeLinks(_son, _cyclicBufferSize * 2, subValue); NormalizeLinks(_hash, _hashSizeSum, subValue); ReduceOffsets(subValue); } public void SetCutValue(int cutValue) { _cutValue = cutValue; } private static final int[] CrcTable = new int[256]; static { for (int i = 0; i < 256; i++) { int r = i; for (int j = 0; j < 8; j++) if ((r & 1) != 0) r = (r >>> 1) ^ 0xEDB88320; else r >>>= 1; CrcTable[i] = r; } } }
8,800
21.979112
102
java
uiHRDC
uiHRDC-master/uiHRDC/indexes/NOPOS/II_docs_large/ilists.imp/6.vbyteP7zip_acabadoMerge2yN[Fork]/lzmalib/lzma.sourceCode/LZMAFARI_LIB/lzma465/Java/SevenZip/Compression/LZ/InWindow.java
// LZ.InWindow package SevenZip.Compression.LZ; import java.io.IOException; public class InWindow { public byte[] _bufferBase; // pointer to buffer with data java.io.InputStream _stream; int _posLimit; // offset (from _buffer) of first byte when new block reading must be done boolean _streamEndWasReached; // if (true) then _streamPos shows real end of stream int _pointerToLastSafePosition; public int _bufferOffset; public int _blockSize; // Size of Allocated memory block public int _pos; // offset (from _buffer) of curent byte int _keepSizeBefore; // how many BYTEs must be kept in buffer before _pos int _keepSizeAfter; // how many BYTEs must be kept buffer after _pos public int _streamPos; // offset (from _buffer) of first not read byte from Stream public void MoveBlock() { int offset = _bufferOffset + _pos - _keepSizeBefore; // we need one additional byte, since MovePos moves on 1 byte. if (offset > 0) offset--; int numBytes = _bufferOffset + _streamPos - offset; // check negative offset ???? for (int i = 0; i < numBytes; i++) _bufferBase[i] = _bufferBase[offset + i]; _bufferOffset -= offset; } public void ReadBlock() throws IOException { if (_streamEndWasReached) return; while (true) { int size = (0 - _bufferOffset) + _blockSize - _streamPos; if (size == 0) return; int numReadBytes = _stream.read(_bufferBase, _bufferOffset + _streamPos, size); if (numReadBytes == -1) { _posLimit = _streamPos; int pointerToPostion = _bufferOffset + _posLimit; if (pointerToPostion > _pointerToLastSafePosition) _posLimit = _pointerToLastSafePosition - _bufferOffset; _streamEndWasReached = true; return; } _streamPos += numReadBytes; if (_streamPos >= _pos + _keepSizeAfter) _posLimit = _streamPos - _keepSizeAfter; } } void Free() { _bufferBase = null; } public void Create(int keepSizeBefore, int keepSizeAfter, int keepSizeReserv) { _keepSizeBefore = keepSizeBefore; _keepSizeAfter = keepSizeAfter; int blockSize = keepSizeBefore + keepSizeAfter + keepSizeReserv; if (_bufferBase == null || _blockSize != blockSize) { Free(); _blockSize = blockSize; _bufferBase = new byte[_blockSize]; } _pointerToLastSafePosition = _blockSize - keepSizeAfter; } public void SetStream(java.io.InputStream stream) { _stream = stream; } public void ReleaseStream() { _stream = null; } public void Init() throws IOException { _bufferOffset = 0; _pos = 0; _streamPos = 0; _streamEndWasReached = false; ReadBlock(); } public void MovePos() throws IOException { _pos++; if (_pos > _posLimit) { int pointerToPostion = _bufferOffset + _pos; if (pointerToPostion > _pointerToLastSafePosition) MoveBlock(); ReadBlock(); } } public byte GetIndexByte(int index) { return _bufferBase[_bufferOffset + _pos + index]; } // index + limit have not to exceed _keepSizeAfter; public int GetMatchLen(int index, int distance, int limit) { if (_streamEndWasReached) if ((_pos + index) + limit > _streamPos) limit = _streamPos - (_pos + index); distance++; // Byte *pby = _buffer + (size_t)_pos + index; int pby = _bufferOffset + _pos + index; int i; for (i = 0; i < limit && _bufferBase[pby + i] == _bufferBase[pby + i - distance]; i++); return i; } public int GetNumAvailableBytes() { return _streamPos - _pos; } public void ReduceOffsets(int subValue) { _bufferOffset += subValue; _posLimit -= subValue; _pos -= subValue; _streamPos -= subValue; } }
3,595
26.242424
91
java
uiHRDC
uiHRDC-master/uiHRDC/indexes/NOPOS/II_docs_large/ilists.imp/6.vbyteP7zip_acabadoMerge2yN[Fork]/lzmalib/lzma.sourceCode/LZMAFARI_LIB/lzma465/Java/SevenZip/Compression/RangeCoder/BitTreeDecoder.java
package SevenZip.Compression.RangeCoder; public class BitTreeDecoder { short[] Models; int NumBitLevels; public BitTreeDecoder(int numBitLevels) { NumBitLevels = numBitLevels; Models = new short[1 << numBitLevels]; } public void Init() { Decoder.InitBitModels(Models); } public int Decode(Decoder rangeDecoder) throws java.io.IOException { int m = 1; for (int bitIndex = NumBitLevels; bitIndex != 0; bitIndex--) m = (m << 1) + rangeDecoder.DecodeBit(Models, m); return m - (1 << NumBitLevels); } public int ReverseDecode(Decoder rangeDecoder) throws java.io.IOException { int m = 1; int symbol = 0; for (int bitIndex = 0; bitIndex < NumBitLevels; bitIndex++) { int bit = rangeDecoder.DecodeBit(Models, m); m <<= 1; m += bit; symbol |= (bit << bitIndex); } return symbol; } public static int ReverseDecode(short[] Models, int startIndex, Decoder rangeDecoder, int NumBitLevels) throws java.io.IOException { int m = 1; int symbol = 0; for (int bitIndex = 0; bitIndex < NumBitLevels; bitIndex++) { int bit = rangeDecoder.DecodeBit(Models, startIndex + m); m <<= 1; m += bit; symbol |= (bit << bitIndex); } return symbol; } }
1,216
20.732143
74
java
uiHRDC
uiHRDC-master/uiHRDC/indexes/NOPOS/II_docs_large/ilists.imp/6.vbyteP7zip_acabadoMerge2yN[Fork]/lzmalib/lzma.sourceCode/LZMAFARI_LIB/lzma465/Java/SevenZip/Compression/RangeCoder/Decoder.java
package SevenZip.Compression.RangeCoder; import java.io.IOException; public class Decoder { static final int kTopMask = ~((1 << 24) - 1); static final int kNumBitModelTotalBits = 11; static final int kBitModelTotal = (1 << kNumBitModelTotalBits); static final int kNumMoveBits = 5; int Range; int Code; java.io.InputStream Stream; public final void SetStream(java.io.InputStream stream) { Stream = stream; } public final void ReleaseStream() { Stream = null; } public final void Init() throws IOException { Code = 0; Range = -1; for (int i = 0; i < 5; i++) Code = (Code << 8) | Stream.read(); } public final int DecodeDirectBits(int numTotalBits) throws IOException { int result = 0; for (int i = numTotalBits; i != 0; i--) { Range >>>= 1; int t = ((Code - Range) >>> 31); Code -= Range & (t - 1); result = (result << 1) | (1 - t); if ((Range & kTopMask) == 0) { Code = (Code << 8) | Stream.read(); Range <<= 8; } } return result; } public int DecodeBit(short []probs, int index) throws IOException { int prob = probs[index]; int newBound = (Range >>> kNumBitModelTotalBits) * prob; if ((Code ^ 0x80000000) < (newBound ^ 0x80000000)) { Range = newBound; probs[index] = (short)(prob + ((kBitModelTotal - prob) >>> kNumMoveBits)); if ((Range & kTopMask) == 0) { Code = (Code << 8) | Stream.read(); Range <<= 8; } return 0; } else { Range -= newBound; Code -= newBound; probs[index] = (short)(prob - ((prob) >>> kNumMoveBits)); if ((Range & kTopMask) == 0) { Code = (Code << 8) | Stream.read(); Range <<= 8; } return 1; } } public static void InitBitModels(short []probs) { for (int i = 0; i < probs.length; i++) probs[i] = (kBitModelTotal >>> 1); } }
1,828
19.550562
77
java
uiHRDC
uiHRDC-master/uiHRDC/indexes/NOPOS/II_docs_large/ilists.imp/6.vbyteP7zip_acabadoMerge2yN[Fork]/lzmalib/lzma.sourceCode/LZMAFARI_LIB/lzma465/Java/SevenZip/Compression/RangeCoder/BitTreeEncoder.java
package SevenZip.Compression.RangeCoder; import java.io.IOException; public class BitTreeEncoder { short[] Models; int NumBitLevels; public BitTreeEncoder(int numBitLevels) { NumBitLevels = numBitLevels; Models = new short[1 << numBitLevels]; } public void Init() { Decoder.InitBitModels(Models); } public void Encode(Encoder rangeEncoder, int symbol) throws IOException { int m = 1; for (int bitIndex = NumBitLevels; bitIndex != 0; ) { bitIndex--; int bit = (symbol >>> bitIndex) & 1; rangeEncoder.Encode(Models, m, bit); m = (m << 1) | bit; } } public void ReverseEncode(Encoder rangeEncoder, int symbol) throws IOException { int m = 1; for (int i = 0; i < NumBitLevels; i++) { int bit = symbol & 1; rangeEncoder.Encode(Models, m, bit); m = (m << 1) | bit; symbol >>= 1; } } public int GetPrice(int symbol) { int price = 0; int m = 1; for (int bitIndex = NumBitLevels; bitIndex != 0; ) { bitIndex--; int bit = (symbol >>> bitIndex) & 1; price += Encoder.GetPrice(Models[m], bit); m = (m << 1) + bit; } return price; } public int ReverseGetPrice(int symbol) { int price = 0; int m = 1; for (int i = NumBitLevels; i != 0; i--) { int bit = symbol & 1; symbol >>>= 1; price += Encoder.GetPrice(Models[m], bit); m = (m << 1) | bit; } return price; } public static int ReverseGetPrice(short[] Models, int startIndex, int NumBitLevels, int symbol) { int price = 0; int m = 1; for (int i = NumBitLevels; i != 0; i--) { int bit = symbol & 1; symbol >>>= 1; price += Encoder.GetPrice(Models[startIndex + m], bit); m = (m << 1) | bit; } return price; } public static void ReverseEncode(short[] Models, int startIndex, Encoder rangeEncoder, int NumBitLevels, int symbol) throws IOException { int m = 1; for (int i = 0; i < NumBitLevels; i++) { int bit = symbol & 1; rangeEncoder.Encode(Models, startIndex + m, bit); m = (m << 1) | bit; symbol >>= 1; } } }
2,034
19.35
79
java
uiHRDC
uiHRDC-master/uiHRDC/indexes/NOPOS/II_docs_large/ilists.imp/6.vbyteP7zip_acabadoMerge2yN[Fork]/lzmalib/lzma.sourceCode/LZMAFARI_LIB/lzma465/Java/SevenZip/Compression/RangeCoder/Encoder.java
package SevenZip.Compression.RangeCoder; import java.io.IOException; public class Encoder { static final int kTopMask = ~((1 << 24) - 1); static final int kNumBitModelTotalBits = 11; static final int kBitModelTotal = (1 << kNumBitModelTotalBits); static final int kNumMoveBits = 5; java.io.OutputStream Stream; long Low; int Range; int _cacheSize; int _cache; long _position; public void SetStream(java.io.OutputStream stream) { Stream = stream; } public void ReleaseStream() { Stream = null; } public void Init() { _position = 0; Low = 0; Range = -1; _cacheSize = 1; _cache = 0; } public void FlushData() throws IOException { for (int i = 0; i < 5; i++) ShiftLow(); } public void FlushStream() throws IOException { Stream.flush(); } public void ShiftLow() throws IOException { int LowHi = (int)(Low >>> 32); if (LowHi != 0 || Low < 0xFF000000L) { _position += _cacheSize; int temp = _cache; do { Stream.write(temp + LowHi); temp = 0xFF; } while(--_cacheSize != 0); _cache = (((int)Low) >>> 24); } _cacheSize++; Low = (Low & 0xFFFFFF) << 8; } public void EncodeDirectBits(int v, int numTotalBits) throws IOException { for (int i = numTotalBits - 1; i >= 0; i--) { Range >>>= 1; if (((v >>> i) & 1) == 1) Low += Range; if ((Range & Encoder.kTopMask) == 0) { Range <<= 8; ShiftLow(); } } } public long GetProcessedSizeAdd() { return _cacheSize + _position + 4; } static final int kNumMoveReducingBits = 2; public static final int kNumBitPriceShiftBits = 6; public static void InitBitModels(short []probs) { for (int i = 0; i < probs.length; i++) probs[i] = (kBitModelTotal >>> 1); } public void Encode(short []probs, int index, int symbol) throws IOException { int prob = probs[index]; int newBound = (Range >>> kNumBitModelTotalBits) * prob; if (symbol == 0) { Range = newBound; probs[index] = (short)(prob + ((kBitModelTotal - prob) >>> kNumMoveBits)); } else { Low += (newBound & 0xFFFFFFFFL); Range -= newBound; probs[index] = (short)(prob - ((prob) >>> kNumMoveBits)); } if ((Range & kTopMask) == 0) { Range <<= 8; ShiftLow(); } } private static int[] ProbPrices = new int[kBitModelTotal >>> kNumMoveReducingBits]; static { int kNumBits = (kNumBitModelTotalBits - kNumMoveReducingBits); for (int i = kNumBits - 1; i >= 0; i--) { int start = 1 << (kNumBits - i - 1); int end = 1 << (kNumBits - i); for (int j = start; j < end; j++) ProbPrices[j] = (i << kNumBitPriceShiftBits) + (((end - j) << kNumBitPriceShiftBits) >>> (kNumBits - i - 1)); } } static public int GetPrice(int Prob, int symbol) { return ProbPrices[(((Prob - symbol) ^ ((-symbol))) & (kBitModelTotal - 1)) >>> kNumMoveReducingBits]; } static public int GetPrice0(int Prob) { return ProbPrices[Prob >>> kNumMoveReducingBits]; } static public int GetPrice1(int Prob) { return ProbPrices[(kBitModelTotal - Prob) >>> kNumMoveReducingBits]; } }
3,087
19.315789
103
java
uiHRDC
uiHRDC-master/uiHRDC/indexes/NOPOS/II_docs_large/ilists.imp/6.vbyteP7zip_acabadoMerge2yN[Fork]/lzmalib/lzma.sourceCode/LZMAFARI_LIB/lzma465/Java/SevenZip/Compression/LZMA/Base.java
// Base.java package SevenZip.Compression.LZMA; public class Base { public static final int kNumRepDistances = 4; public static final int kNumStates = 12; public static final int StateInit() { return 0; } public static final int StateUpdateChar(int index) { if (index < 4) return 0; if (index < 10) return index - 3; return index - 6; } public static final int StateUpdateMatch(int index) { return (index < 7 ? 7 : 10); } public static final int StateUpdateRep(int index) { return (index < 7 ? 8 : 11); } public static final int StateUpdateShortRep(int index) { return (index < 7 ? 9 : 11); } public static final boolean StateIsCharState(int index) { return index < 7; } public static final int kNumPosSlotBits = 6; public static final int kDicLogSizeMin = 0; // public static final int kDicLogSizeMax = 28; // public static final int kDistTableSizeMax = kDicLogSizeMax * 2; public static final int kNumLenToPosStatesBits = 2; // it's for speed optimization public static final int kNumLenToPosStates = 1 << kNumLenToPosStatesBits; public static final int kMatchMinLen = 2; public static final int GetLenToPosState(int len) { len -= kMatchMinLen; if (len < kNumLenToPosStates) return len; return (int)(kNumLenToPosStates - 1); } public static final int kNumAlignBits = 4; public static final int kAlignTableSize = 1 << kNumAlignBits; public static final int kAlignMask = (kAlignTableSize - 1); public static final int kStartPosModelIndex = 4; public static final int kEndPosModelIndex = 14; public static final int kNumPosModels = kEndPosModelIndex - kStartPosModelIndex; public static final int kNumFullDistances = 1 << (kEndPosModelIndex / 2); public static final int kNumLitPosStatesBitsEncodingMax = 4; public static final int kNumLitContextBitsMax = 8; public static final int kNumPosStatesBitsMax = 4; public static final int kNumPosStatesMax = (1 << kNumPosStatesBitsMax); public static final int kNumPosStatesBitsEncodingMax = 4; public static final int kNumPosStatesEncodingMax = (1 << kNumPosStatesBitsEncodingMax); public static final int kNumLowLenBits = 3; public static final int kNumMidLenBits = 3; public static final int kNumHighLenBits = 8; public static final int kNumLowLenSymbols = 1 << kNumLowLenBits; public static final int kNumMidLenSymbols = 1 << kNumMidLenBits; public static final int kNumLenSymbols = kNumLowLenSymbols + kNumMidLenSymbols + (1 << kNumHighLenBits); public static final int kMatchMaxLen = kMatchMinLen + kNumLenSymbols - 1; }
2,609
28.325843
89
java
uiHRDC
uiHRDC-master/uiHRDC/indexes/NOPOS/II_docs_large/ilists.imp/6.vbyteP7zip_acabadoMerge2yN[Fork]/lzmalib/lzma.sourceCode/LZMAFARI_LIB/lzma465/Java/SevenZip/Compression/LZMA/Decoder.java
package SevenZip.Compression.LZMA; import SevenZip.Compression.RangeCoder.BitTreeDecoder; import SevenZip.Compression.LZMA.Base; import SevenZip.Compression.LZ.OutWindow; import java.io.IOException; public class Decoder { class LenDecoder { short[] m_Choice = new short[2]; BitTreeDecoder[] m_LowCoder = new BitTreeDecoder[Base.kNumPosStatesMax]; BitTreeDecoder[] m_MidCoder = new BitTreeDecoder[Base.kNumPosStatesMax]; BitTreeDecoder m_HighCoder = new BitTreeDecoder(Base.kNumHighLenBits); int m_NumPosStates = 0; public void Create(int numPosStates) { for (; m_NumPosStates < numPosStates; m_NumPosStates++) { m_LowCoder[m_NumPosStates] = new BitTreeDecoder(Base.kNumLowLenBits); m_MidCoder[m_NumPosStates] = new BitTreeDecoder(Base.kNumMidLenBits); } } public void Init() { SevenZip.Compression.RangeCoder.Decoder.InitBitModels(m_Choice); for (int posState = 0; posState < m_NumPosStates; posState++) { m_LowCoder[posState].Init(); m_MidCoder[posState].Init(); } m_HighCoder.Init(); } public int Decode(SevenZip.Compression.RangeCoder.Decoder rangeDecoder, int posState) throws IOException { if (rangeDecoder.DecodeBit(m_Choice, 0) == 0) return m_LowCoder[posState].Decode(rangeDecoder); int symbol = Base.kNumLowLenSymbols; if (rangeDecoder.DecodeBit(m_Choice, 1) == 0) symbol += m_MidCoder[posState].Decode(rangeDecoder); else symbol += Base.kNumMidLenSymbols + m_HighCoder.Decode(rangeDecoder); return symbol; } } class LiteralDecoder { class Decoder2 { short[] m_Decoders = new short[0x300]; public void Init() { SevenZip.Compression.RangeCoder.Decoder.InitBitModels(m_Decoders); } public byte DecodeNormal(SevenZip.Compression.RangeCoder.Decoder rangeDecoder) throws IOException { int symbol = 1; do symbol = (symbol << 1) | rangeDecoder.DecodeBit(m_Decoders, symbol); while (symbol < 0x100); return (byte)symbol; } public byte DecodeWithMatchByte(SevenZip.Compression.RangeCoder.Decoder rangeDecoder, byte matchByte) throws IOException { int symbol = 1; do { int matchBit = (matchByte >> 7) & 1; matchByte <<= 1; int bit = rangeDecoder.DecodeBit(m_Decoders, ((1 + matchBit) << 8) + symbol); symbol = (symbol << 1) | bit; if (matchBit != bit) { while (symbol < 0x100) symbol = (symbol << 1) | rangeDecoder.DecodeBit(m_Decoders, symbol); break; } } while (symbol < 0x100); return (byte)symbol; } } Decoder2[] m_Coders; int m_NumPrevBits; int m_NumPosBits; int m_PosMask; public void Create(int numPosBits, int numPrevBits) { if (m_Coders != null && m_NumPrevBits == numPrevBits && m_NumPosBits == numPosBits) return; m_NumPosBits = numPosBits; m_PosMask = (1 << numPosBits) - 1; m_NumPrevBits = numPrevBits; int numStates = 1 << (m_NumPrevBits + m_NumPosBits); m_Coders = new Decoder2[numStates]; for (int i = 0; i < numStates; i++) m_Coders[i] = new Decoder2(); } public void Init() { int numStates = 1 << (m_NumPrevBits + m_NumPosBits); for (int i = 0; i < numStates; i++) m_Coders[i].Init(); } Decoder2 GetDecoder(int pos, byte prevByte) { return m_Coders[((pos & m_PosMask) << m_NumPrevBits) + ((prevByte & 0xFF) >>> (8 - m_NumPrevBits))]; } } OutWindow m_OutWindow = new OutWindow(); SevenZip.Compression.RangeCoder.Decoder m_RangeDecoder = new SevenZip.Compression.RangeCoder.Decoder(); short[] m_IsMatchDecoders = new short[Base.kNumStates << Base.kNumPosStatesBitsMax]; short[] m_IsRepDecoders = new short[Base.kNumStates]; short[] m_IsRepG0Decoders = new short[Base.kNumStates]; short[] m_IsRepG1Decoders = new short[Base.kNumStates]; short[] m_IsRepG2Decoders = new short[Base.kNumStates]; short[] m_IsRep0LongDecoders = new short[Base.kNumStates << Base.kNumPosStatesBitsMax]; BitTreeDecoder[] m_PosSlotDecoder = new BitTreeDecoder[Base.kNumLenToPosStates]; short[] m_PosDecoders = new short[Base.kNumFullDistances - Base.kEndPosModelIndex]; BitTreeDecoder m_PosAlignDecoder = new BitTreeDecoder(Base.kNumAlignBits); LenDecoder m_LenDecoder = new LenDecoder(); LenDecoder m_RepLenDecoder = new LenDecoder(); LiteralDecoder m_LiteralDecoder = new LiteralDecoder(); int m_DictionarySize = -1; int m_DictionarySizeCheck = -1; int m_PosStateMask; public Decoder() { for (int i = 0; i < Base.kNumLenToPosStates; i++) m_PosSlotDecoder[i] = new BitTreeDecoder(Base.kNumPosSlotBits); } boolean SetDictionarySize(int dictionarySize) { if (dictionarySize < 0) return false; if (m_DictionarySize != dictionarySize) { m_DictionarySize = dictionarySize; m_DictionarySizeCheck = Math.max(m_DictionarySize, 1); m_OutWindow.Create(Math.max(m_DictionarySizeCheck, (1 << 12))); } return true; } boolean SetLcLpPb(int lc, int lp, int pb) { if (lc > Base.kNumLitContextBitsMax || lp > 4 || pb > Base.kNumPosStatesBitsMax) return false; m_LiteralDecoder.Create(lp, lc); int numPosStates = 1 << pb; m_LenDecoder.Create(numPosStates); m_RepLenDecoder.Create(numPosStates); m_PosStateMask = numPosStates - 1; return true; } void Init() throws IOException { m_OutWindow.Init(false); SevenZip.Compression.RangeCoder.Decoder.InitBitModels(m_IsMatchDecoders); SevenZip.Compression.RangeCoder.Decoder.InitBitModels(m_IsRep0LongDecoders); SevenZip.Compression.RangeCoder.Decoder.InitBitModels(m_IsRepDecoders); SevenZip.Compression.RangeCoder.Decoder.InitBitModels(m_IsRepG0Decoders); SevenZip.Compression.RangeCoder.Decoder.InitBitModels(m_IsRepG1Decoders); SevenZip.Compression.RangeCoder.Decoder.InitBitModels(m_IsRepG2Decoders); SevenZip.Compression.RangeCoder.Decoder.InitBitModels(m_PosDecoders); m_LiteralDecoder.Init(); int i; for (i = 0; i < Base.kNumLenToPosStates; i++) m_PosSlotDecoder[i].Init(); m_LenDecoder.Init(); m_RepLenDecoder.Init(); m_PosAlignDecoder.Init(); m_RangeDecoder.Init(); } public boolean Code(java.io.InputStream inStream, java.io.OutputStream outStream, long outSize) throws IOException { m_RangeDecoder.SetStream(inStream); m_OutWindow.SetStream(outStream); Init(); int state = Base.StateInit(); int rep0 = 0, rep1 = 0, rep2 = 0, rep3 = 0; long nowPos64 = 0; byte prevByte = 0; while (outSize < 0 || nowPos64 < outSize) { int posState = (int)nowPos64 & m_PosStateMask; if (m_RangeDecoder.DecodeBit(m_IsMatchDecoders, (state << Base.kNumPosStatesBitsMax) + posState) == 0) { LiteralDecoder.Decoder2 decoder2 = m_LiteralDecoder.GetDecoder((int)nowPos64, prevByte); if (!Base.StateIsCharState(state)) prevByte = decoder2.DecodeWithMatchByte(m_RangeDecoder, m_OutWindow.GetByte(rep0)); else prevByte = decoder2.DecodeNormal(m_RangeDecoder); m_OutWindow.PutByte(prevByte); state = Base.StateUpdateChar(state); nowPos64++; } else { int len; if (m_RangeDecoder.DecodeBit(m_IsRepDecoders, state) == 1) { len = 0; if (m_RangeDecoder.DecodeBit(m_IsRepG0Decoders, state) == 0) { if (m_RangeDecoder.DecodeBit(m_IsRep0LongDecoders, (state << Base.kNumPosStatesBitsMax) + posState) == 0) { state = Base.StateUpdateShortRep(state); len = 1; } } else { int distance; if (m_RangeDecoder.DecodeBit(m_IsRepG1Decoders, state) == 0) distance = rep1; else { if (m_RangeDecoder.DecodeBit(m_IsRepG2Decoders, state) == 0) distance = rep2; else { distance = rep3; rep3 = rep2; } rep2 = rep1; } rep1 = rep0; rep0 = distance; } if (len == 0) { len = m_RepLenDecoder.Decode(m_RangeDecoder, posState) + Base.kMatchMinLen; state = Base.StateUpdateRep(state); } } else { rep3 = rep2; rep2 = rep1; rep1 = rep0; len = Base.kMatchMinLen + m_LenDecoder.Decode(m_RangeDecoder, posState); state = Base.StateUpdateMatch(state); int posSlot = m_PosSlotDecoder[Base.GetLenToPosState(len)].Decode(m_RangeDecoder); if (posSlot >= Base.kStartPosModelIndex) { int numDirectBits = (posSlot >> 1) - 1; rep0 = ((2 | (posSlot & 1)) << numDirectBits); if (posSlot < Base.kEndPosModelIndex) rep0 += BitTreeDecoder.ReverseDecode(m_PosDecoders, rep0 - posSlot - 1, m_RangeDecoder, numDirectBits); else { rep0 += (m_RangeDecoder.DecodeDirectBits( numDirectBits - Base.kNumAlignBits) << Base.kNumAlignBits); rep0 += m_PosAlignDecoder.ReverseDecode(m_RangeDecoder); if (rep0 < 0) { if (rep0 == -1) break; return false; } } } else rep0 = posSlot; } if (rep0 >= nowPos64 || rep0 >= m_DictionarySizeCheck) { // m_OutWindow.Flush(); return false; } m_OutWindow.CopyBlock(rep0, len); nowPos64 += len; prevByte = m_OutWindow.GetByte(0); } } m_OutWindow.Flush(); m_OutWindow.ReleaseStream(); m_RangeDecoder.ReleaseStream(); return true; } public boolean SetDecoderProperties(byte[] properties) { if (properties.length < 5) return false; int val = properties[0] & 0xFF; int lc = val % 9; int remainder = val / 9; int lp = remainder % 5; int pb = remainder / 5; int dictionarySize = 0; for (int i = 0; i < 4; i++) dictionarySize += ((int)(properties[1 + i]) & 0xFF) << (i * 8); if (!SetLcLpPb(lc, lp, pb)) return false; return SetDictionarySize(dictionarySize); } }
9,677
28.327273
123
java
uiHRDC
uiHRDC-master/uiHRDC/indexes/NOPOS/II_docs_large/ilists.imp/6.vbyteP7zip_acabadoMerge2yN[Fork]/lzmalib/lzma.sourceCode/LZMAFARI_LIB/lzma465/Java/SevenZip/Compression/LZMA/Encoder.java
package SevenZip.Compression.LZMA; import SevenZip.Compression.RangeCoder.BitTreeEncoder; import SevenZip.Compression.LZMA.Base; import SevenZip.Compression.LZ.BinTree; import SevenZip.ICodeProgress; import java.io.IOException; public class Encoder { public static final int EMatchFinderTypeBT2 = 0; public static final int EMatchFinderTypeBT4 = 1; static final int kIfinityPrice = 0xFFFFFFF; static byte[] g_FastPos = new byte[1 << 11]; static { int kFastSlots = 22; int c = 2; g_FastPos[0] = 0; g_FastPos[1] = 1; for (int slotFast = 2; slotFast < kFastSlots; slotFast++) { int k = (1 << ((slotFast >> 1) - 1)); for (int j = 0; j < k; j++, c++) g_FastPos[c] = (byte)slotFast; } } static int GetPosSlot(int pos) { if (pos < (1 << 11)) return g_FastPos[pos]; if (pos < (1 << 21)) return (g_FastPos[pos >> 10] + 20); return (g_FastPos[pos >> 20] + 40); } static int GetPosSlot2(int pos) { if (pos < (1 << 17)) return (g_FastPos[pos >> 6] + 12); if (pos < (1 << 27)) return (g_FastPos[pos >> 16] + 32); return (g_FastPos[pos >> 26] + 52); } int _state = Base.StateInit(); byte _previousByte; int[] _repDistances = new int[Base.kNumRepDistances]; void BaseInit() { _state = Base.StateInit(); _previousByte = 0; for (int i = 0; i < Base.kNumRepDistances; i++) _repDistances[i] = 0; } static final int kDefaultDictionaryLogSize = 22; static final int kNumFastBytesDefault = 0x20; class LiteralEncoder { class Encoder2 { short[] m_Encoders = new short[0x300]; public void Init() { SevenZip.Compression.RangeCoder.Encoder.InitBitModels(m_Encoders); } public void Encode(SevenZip.Compression.RangeCoder.Encoder rangeEncoder, byte symbol) throws IOException { int context = 1; for (int i = 7; i >= 0; i--) { int bit = ((symbol >> i) & 1); rangeEncoder.Encode(m_Encoders, context, bit); context = (context << 1) | bit; } } public void EncodeMatched(SevenZip.Compression.RangeCoder.Encoder rangeEncoder, byte matchByte, byte symbol) throws IOException { int context = 1; boolean same = true; for (int i = 7; i >= 0; i--) { int bit = ((symbol >> i) & 1); int state = context; if (same) { int matchBit = ((matchByte >> i) & 1); state += ((1 + matchBit) << 8); same = (matchBit == bit); } rangeEncoder.Encode(m_Encoders, state, bit); context = (context << 1) | bit; } } public int GetPrice(boolean matchMode, byte matchByte, byte symbol) { int price = 0; int context = 1; int i = 7; if (matchMode) { for (; i >= 0; i--) { int matchBit = (matchByte >> i) & 1; int bit = (symbol >> i) & 1; price += SevenZip.Compression.RangeCoder.Encoder.GetPrice(m_Encoders[((1 + matchBit) << 8) + context], bit); context = (context << 1) | bit; if (matchBit != bit) { i--; break; } } } for (; i >= 0; i--) { int bit = (symbol >> i) & 1; price += SevenZip.Compression.RangeCoder.Encoder.GetPrice(m_Encoders[context], bit); context = (context << 1) | bit; } return price; } } Encoder2[] m_Coders; int m_NumPrevBits; int m_NumPosBits; int m_PosMask; public void Create(int numPosBits, int numPrevBits) { if (m_Coders != null && m_NumPrevBits == numPrevBits && m_NumPosBits == numPosBits) return; m_NumPosBits = numPosBits; m_PosMask = (1 << numPosBits) - 1; m_NumPrevBits = numPrevBits; int numStates = 1 << (m_NumPrevBits + m_NumPosBits); m_Coders = new Encoder2[numStates]; for (int i = 0; i < numStates; i++) m_Coders[i] = new Encoder2(); } public void Init() { int numStates = 1 << (m_NumPrevBits + m_NumPosBits); for (int i = 0; i < numStates; i++) m_Coders[i].Init(); } public Encoder2 GetSubCoder(int pos, byte prevByte) { return m_Coders[((pos & m_PosMask) << m_NumPrevBits) + ((prevByte & 0xFF) >>> (8 - m_NumPrevBits))]; } } class LenEncoder { short[] _choice = new short[2]; BitTreeEncoder[] _lowCoder = new BitTreeEncoder[Base.kNumPosStatesEncodingMax]; BitTreeEncoder[] _midCoder = new BitTreeEncoder[Base.kNumPosStatesEncodingMax]; BitTreeEncoder _highCoder = new BitTreeEncoder(Base.kNumHighLenBits); public LenEncoder() { for (int posState = 0; posState < Base.kNumPosStatesEncodingMax; posState++) { _lowCoder[posState] = new BitTreeEncoder(Base.kNumLowLenBits); _midCoder[posState] = new BitTreeEncoder(Base.kNumMidLenBits); } } public void Init(int numPosStates) { SevenZip.Compression.RangeCoder.Encoder.InitBitModels(_choice); for (int posState = 0; posState < numPosStates; posState++) { _lowCoder[posState].Init(); _midCoder[posState].Init(); } _highCoder.Init(); } public void Encode(SevenZip.Compression.RangeCoder.Encoder rangeEncoder, int symbol, int posState) throws IOException { if (symbol < Base.kNumLowLenSymbols) { rangeEncoder.Encode(_choice, 0, 0); _lowCoder[posState].Encode(rangeEncoder, symbol); } else { symbol -= Base.kNumLowLenSymbols; rangeEncoder.Encode(_choice, 0, 1); if (symbol < Base.kNumMidLenSymbols) { rangeEncoder.Encode(_choice, 1, 0); _midCoder[posState].Encode(rangeEncoder, symbol); } else { rangeEncoder.Encode(_choice, 1, 1); _highCoder.Encode(rangeEncoder, symbol - Base.kNumMidLenSymbols); } } } public void SetPrices(int posState, int numSymbols, int[] prices, int st) { int a0 = SevenZip.Compression.RangeCoder.Encoder.GetPrice0(_choice[0]); int a1 = SevenZip.Compression.RangeCoder.Encoder.GetPrice1(_choice[0]); int b0 = a1 + SevenZip.Compression.RangeCoder.Encoder.GetPrice0(_choice[1]); int b1 = a1 + SevenZip.Compression.RangeCoder.Encoder.GetPrice1(_choice[1]); int i = 0; for (i = 0; i < Base.kNumLowLenSymbols; i++) { if (i >= numSymbols) return; prices[st + i] = a0 + _lowCoder[posState].GetPrice(i); } for (; i < Base.kNumLowLenSymbols + Base.kNumMidLenSymbols; i++) { if (i >= numSymbols) return; prices[st + i] = b0 + _midCoder[posState].GetPrice(i - Base.kNumLowLenSymbols); } for (; i < numSymbols; i++) prices[st + i] = b1 + _highCoder.GetPrice(i - Base.kNumLowLenSymbols - Base.kNumMidLenSymbols); } }; public static final int kNumLenSpecSymbols = Base.kNumLowLenSymbols + Base.kNumMidLenSymbols; class LenPriceTableEncoder extends LenEncoder { int[] _prices = new int[Base.kNumLenSymbols<<Base.kNumPosStatesBitsEncodingMax]; int _tableSize; int[] _counters = new int[Base.kNumPosStatesEncodingMax]; public void SetTableSize(int tableSize) { _tableSize = tableSize; } public int GetPrice(int symbol, int posState) { return _prices[posState * Base.kNumLenSymbols + symbol]; } void UpdateTable(int posState) { SetPrices(posState, _tableSize, _prices, posState * Base.kNumLenSymbols); _counters[posState] = _tableSize; } public void UpdateTables(int numPosStates) { for (int posState = 0; posState < numPosStates; posState++) UpdateTable(posState); } public void Encode(SevenZip.Compression.RangeCoder.Encoder rangeEncoder, int symbol, int posState) throws IOException { super.Encode(rangeEncoder, symbol, posState); if (--_counters[posState] == 0) UpdateTable(posState); } } static final int kNumOpts = 1 << 12; class Optimal { public int State; public boolean Prev1IsChar; public boolean Prev2; public int PosPrev2; public int BackPrev2; public int Price; public int PosPrev; public int BackPrev; public int Backs0; public int Backs1; public int Backs2; public int Backs3; public void MakeAsChar() { BackPrev = -1; Prev1IsChar = false; } public void MakeAsShortRep() { BackPrev = 0; ; Prev1IsChar = false; } public boolean IsShortRep() { return (BackPrev == 0); } }; Optimal[] _optimum = new Optimal[kNumOpts]; SevenZip.Compression.LZ.BinTree _matchFinder = null; SevenZip.Compression.RangeCoder.Encoder _rangeEncoder = new SevenZip.Compression.RangeCoder.Encoder(); short[] _isMatch = new short[Base.kNumStates<<Base.kNumPosStatesBitsMax]; short[] _isRep = new short[Base.kNumStates]; short[] _isRepG0 = new short[Base.kNumStates]; short[] _isRepG1 = new short[Base.kNumStates]; short[] _isRepG2 = new short[Base.kNumStates]; short[] _isRep0Long = new short[Base.kNumStates<<Base.kNumPosStatesBitsMax]; BitTreeEncoder[] _posSlotEncoder = new BitTreeEncoder[Base.kNumLenToPosStates]; // kNumPosSlotBits short[] _posEncoders = new short[Base.kNumFullDistances-Base.kEndPosModelIndex]; BitTreeEncoder _posAlignEncoder = new BitTreeEncoder(Base.kNumAlignBits); LenPriceTableEncoder _lenEncoder = new LenPriceTableEncoder(); LenPriceTableEncoder _repMatchLenEncoder = new LenPriceTableEncoder(); LiteralEncoder _literalEncoder = new LiteralEncoder(); int[] _matchDistances = new int[Base.kMatchMaxLen*2+2]; int _numFastBytes = kNumFastBytesDefault; int _longestMatchLength; int _numDistancePairs; int _additionalOffset; int _optimumEndIndex; int _optimumCurrentIndex; boolean _longestMatchWasFound; int[] _posSlotPrices = new int[1<<(Base.kNumPosSlotBits+Base.kNumLenToPosStatesBits)]; int[] _distancesPrices = new int[Base.kNumFullDistances<<Base.kNumLenToPosStatesBits]; int[] _alignPrices = new int[Base.kAlignTableSize]; int _alignPriceCount; int _distTableSize = (kDefaultDictionaryLogSize * 2); int _posStateBits = 2; int _posStateMask = (4 - 1); int _numLiteralPosStateBits = 0; int _numLiteralContextBits = 3; int _dictionarySize = (1 << kDefaultDictionaryLogSize); int _dictionarySizePrev = -1; int _numFastBytesPrev = -1; long nowPos64; boolean _finished; java.io.InputStream _inStream; int _matchFinderType = EMatchFinderTypeBT4; boolean _writeEndMark = false; boolean _needReleaseMFStream = false; void Create() { if (_matchFinder == null) { SevenZip.Compression.LZ.BinTree bt = new SevenZip.Compression.LZ.BinTree(); int numHashBytes = 4; if (_matchFinderType == EMatchFinderTypeBT2) numHashBytes = 2; bt.SetType(numHashBytes); _matchFinder = bt; } _literalEncoder.Create(_numLiteralPosStateBits, _numLiteralContextBits); if (_dictionarySize == _dictionarySizePrev && _numFastBytesPrev == _numFastBytes) return; _matchFinder.Create(_dictionarySize, kNumOpts, _numFastBytes, Base.kMatchMaxLen + 1); _dictionarySizePrev = _dictionarySize; _numFastBytesPrev = _numFastBytes; } public Encoder() { for (int i = 0; i < kNumOpts; i++) _optimum[i] = new Optimal(); for (int i = 0; i < Base.kNumLenToPosStates; i++) _posSlotEncoder[i] = new BitTreeEncoder(Base.kNumPosSlotBits); } void SetWriteEndMarkerMode(boolean writeEndMarker) { _writeEndMark = writeEndMarker; } void Init() { BaseInit(); _rangeEncoder.Init(); SevenZip.Compression.RangeCoder.Encoder.InitBitModels(_isMatch); SevenZip.Compression.RangeCoder.Encoder.InitBitModels(_isRep0Long); SevenZip.Compression.RangeCoder.Encoder.InitBitModels(_isRep); SevenZip.Compression.RangeCoder.Encoder.InitBitModels(_isRepG0); SevenZip.Compression.RangeCoder.Encoder.InitBitModels(_isRepG1); SevenZip.Compression.RangeCoder.Encoder.InitBitModels(_isRepG2); SevenZip.Compression.RangeCoder.Encoder.InitBitModels(_posEncoders); _literalEncoder.Init(); for (int i = 0; i < Base.kNumLenToPosStates; i++) _posSlotEncoder[i].Init(); _lenEncoder.Init(1 << _posStateBits); _repMatchLenEncoder.Init(1 << _posStateBits); _posAlignEncoder.Init(); _longestMatchWasFound = false; _optimumEndIndex = 0; _optimumCurrentIndex = 0; _additionalOffset = 0; } int ReadMatchDistances() throws java.io.IOException { int lenRes = 0; _numDistancePairs = _matchFinder.GetMatches(_matchDistances); if (_numDistancePairs > 0) { lenRes = _matchDistances[_numDistancePairs - 2]; if (lenRes == _numFastBytes) lenRes += _matchFinder.GetMatchLen((int)lenRes - 1, _matchDistances[_numDistancePairs - 1], Base.kMatchMaxLen - lenRes); } _additionalOffset++; return lenRes; } void MovePos(int num) throws java.io.IOException { if (num > 0) { _matchFinder.Skip(num); _additionalOffset += num; } } int GetRepLen1Price(int state, int posState) { return SevenZip.Compression.RangeCoder.Encoder.GetPrice0(_isRepG0[state]) + SevenZip.Compression.RangeCoder.Encoder.GetPrice0(_isRep0Long[(state << Base.kNumPosStatesBitsMax) + posState]); } int GetPureRepPrice(int repIndex, int state, int posState) { int price; if (repIndex == 0) { price = SevenZip.Compression.RangeCoder.Encoder.GetPrice0(_isRepG0[state]); price += SevenZip.Compression.RangeCoder.Encoder.GetPrice1(_isRep0Long[(state << Base.kNumPosStatesBitsMax) + posState]); } else { price = SevenZip.Compression.RangeCoder.Encoder.GetPrice1(_isRepG0[state]); if (repIndex == 1) price += SevenZip.Compression.RangeCoder.Encoder.GetPrice0(_isRepG1[state]); else { price += SevenZip.Compression.RangeCoder.Encoder.GetPrice1(_isRepG1[state]); price += SevenZip.Compression.RangeCoder.Encoder.GetPrice(_isRepG2[state], repIndex - 2); } } return price; } int GetRepPrice(int repIndex, int len, int state, int posState) { int price = _repMatchLenEncoder.GetPrice(len - Base.kMatchMinLen, posState); return price + GetPureRepPrice(repIndex, state, posState); } int GetPosLenPrice(int pos, int len, int posState) { int price; int lenToPosState = Base.GetLenToPosState(len); if (pos < Base.kNumFullDistances) price = _distancesPrices[(lenToPosState * Base.kNumFullDistances) + pos]; else price = _posSlotPrices[(lenToPosState << Base.kNumPosSlotBits) + GetPosSlot2(pos)] + _alignPrices[pos & Base.kAlignMask]; return price + _lenEncoder.GetPrice(len - Base.kMatchMinLen, posState); } int Backward(int cur) { _optimumEndIndex = cur; int posMem = _optimum[cur].PosPrev; int backMem = _optimum[cur].BackPrev; do { if (_optimum[cur].Prev1IsChar) { _optimum[posMem].MakeAsChar(); _optimum[posMem].PosPrev = posMem - 1; if (_optimum[cur].Prev2) { _optimum[posMem - 1].Prev1IsChar = false; _optimum[posMem - 1].PosPrev = _optimum[cur].PosPrev2; _optimum[posMem - 1].BackPrev = _optimum[cur].BackPrev2; } } int posPrev = posMem; int backCur = backMem; backMem = _optimum[posPrev].BackPrev; posMem = _optimum[posPrev].PosPrev; _optimum[posPrev].BackPrev = backCur; _optimum[posPrev].PosPrev = cur; cur = posPrev; } while (cur > 0); backRes = _optimum[0].BackPrev; _optimumCurrentIndex = _optimum[0].PosPrev; return _optimumCurrentIndex; } int[] reps = new int[Base.kNumRepDistances]; int[] repLens = new int[Base.kNumRepDistances]; int backRes; int GetOptimum(int position) throws IOException { if (_optimumEndIndex != _optimumCurrentIndex) { int lenRes = _optimum[_optimumCurrentIndex].PosPrev - _optimumCurrentIndex; backRes = _optimum[_optimumCurrentIndex].BackPrev; _optimumCurrentIndex = _optimum[_optimumCurrentIndex].PosPrev; return lenRes; } _optimumCurrentIndex = _optimumEndIndex = 0; int lenMain, numDistancePairs; if (!_longestMatchWasFound) { lenMain = ReadMatchDistances(); } else { lenMain = _longestMatchLength; _longestMatchWasFound = false; } numDistancePairs = _numDistancePairs; int numAvailableBytes = _matchFinder.GetNumAvailableBytes() + 1; if (numAvailableBytes < 2) { backRes = -1; return 1; } if (numAvailableBytes > Base.kMatchMaxLen) numAvailableBytes = Base.kMatchMaxLen; int repMaxIndex = 0; int i; for (i = 0; i < Base.kNumRepDistances; i++) { reps[i] = _repDistances[i]; repLens[i] = _matchFinder.GetMatchLen(0 - 1, reps[i], Base.kMatchMaxLen); if (repLens[i] > repLens[repMaxIndex]) repMaxIndex = i; } if (repLens[repMaxIndex] >= _numFastBytes) { backRes = repMaxIndex; int lenRes = repLens[repMaxIndex]; MovePos(lenRes - 1); return lenRes; } if (lenMain >= _numFastBytes) { backRes = _matchDistances[numDistancePairs - 1] + Base.kNumRepDistances; MovePos(lenMain - 1); return lenMain; } byte currentByte = _matchFinder.GetIndexByte(0 - 1); byte matchByte = _matchFinder.GetIndexByte(0 - _repDistances[0] - 1 - 1); if (lenMain < 2 && currentByte != matchByte && repLens[repMaxIndex] < 2) { backRes = -1; return 1; } _optimum[0].State = _state; int posState = (position & _posStateMask); _optimum[1].Price = SevenZip.Compression.RangeCoder.Encoder.GetPrice0(_isMatch[(_state << Base.kNumPosStatesBitsMax) + posState]) + _literalEncoder.GetSubCoder(position, _previousByte).GetPrice(!Base.StateIsCharState(_state), matchByte, currentByte); _optimum[1].MakeAsChar(); int matchPrice = SevenZip.Compression.RangeCoder.Encoder.GetPrice1(_isMatch[(_state << Base.kNumPosStatesBitsMax) + posState]); int repMatchPrice = matchPrice + SevenZip.Compression.RangeCoder.Encoder.GetPrice1(_isRep[_state]); if (matchByte == currentByte) { int shortRepPrice = repMatchPrice + GetRepLen1Price(_state, posState); if (shortRepPrice < _optimum[1].Price) { _optimum[1].Price = shortRepPrice; _optimum[1].MakeAsShortRep(); } } int lenEnd = ((lenMain >= repLens[repMaxIndex]) ? lenMain : repLens[repMaxIndex]); if (lenEnd < 2) { backRes = _optimum[1].BackPrev; return 1; } _optimum[1].PosPrev = 0; _optimum[0].Backs0 = reps[0]; _optimum[0].Backs1 = reps[1]; _optimum[0].Backs2 = reps[2]; _optimum[0].Backs3 = reps[3]; int len = lenEnd; do _optimum[len--].Price = kIfinityPrice; while (len >= 2); for (i = 0; i < Base.kNumRepDistances; i++) { int repLen = repLens[i]; if (repLen < 2) continue; int price = repMatchPrice + GetPureRepPrice(i, _state, posState); do { int curAndLenPrice = price + _repMatchLenEncoder.GetPrice(repLen - 2, posState); Optimal optimum = _optimum[repLen]; if (curAndLenPrice < optimum.Price) { optimum.Price = curAndLenPrice; optimum.PosPrev = 0; optimum.BackPrev = i; optimum.Prev1IsChar = false; } } while (--repLen >= 2); } int normalMatchPrice = matchPrice + SevenZip.Compression.RangeCoder.Encoder.GetPrice0(_isRep[_state]); len = ((repLens[0] >= 2) ? repLens[0] + 1 : 2); if (len <= lenMain) { int offs = 0; while (len > _matchDistances[offs]) offs += 2; for (; ; len++) { int distance = _matchDistances[offs + 1]; int curAndLenPrice = normalMatchPrice + GetPosLenPrice(distance, len, posState); Optimal optimum = _optimum[len]; if (curAndLenPrice < optimum.Price) { optimum.Price = curAndLenPrice; optimum.PosPrev = 0; optimum.BackPrev = distance + Base.kNumRepDistances; optimum.Prev1IsChar = false; } if (len == _matchDistances[offs]) { offs += 2; if (offs == numDistancePairs) break; } } } int cur = 0; while (true) { cur++; if (cur == lenEnd) return Backward(cur); int newLen = ReadMatchDistances(); numDistancePairs = _numDistancePairs; if (newLen >= _numFastBytes) { _longestMatchLength = newLen; _longestMatchWasFound = true; return Backward(cur); } position++; int posPrev = _optimum[cur].PosPrev; int state; if (_optimum[cur].Prev1IsChar) { posPrev--; if (_optimum[cur].Prev2) { state = _optimum[_optimum[cur].PosPrev2].State; if (_optimum[cur].BackPrev2 < Base.kNumRepDistances) state = Base.StateUpdateRep(state); else state = Base.StateUpdateMatch(state); } else state = _optimum[posPrev].State; state = Base.StateUpdateChar(state); } else state = _optimum[posPrev].State; if (posPrev == cur - 1) { if (_optimum[cur].IsShortRep()) state = Base.StateUpdateShortRep(state); else state = Base.StateUpdateChar(state); } else { int pos; if (_optimum[cur].Prev1IsChar && _optimum[cur].Prev2) { posPrev = _optimum[cur].PosPrev2; pos = _optimum[cur].BackPrev2; state = Base.StateUpdateRep(state); } else { pos = _optimum[cur].BackPrev; if (pos < Base.kNumRepDistances) state = Base.StateUpdateRep(state); else state = Base.StateUpdateMatch(state); } Optimal opt = _optimum[posPrev]; if (pos < Base.kNumRepDistances) { if (pos == 0) { reps[0] = opt.Backs0; reps[1] = opt.Backs1; reps[2] = opt.Backs2; reps[3] = opt.Backs3; } else if (pos == 1) { reps[0] = opt.Backs1; reps[1] = opt.Backs0; reps[2] = opt.Backs2; reps[3] = opt.Backs3; } else if (pos == 2) { reps[0] = opt.Backs2; reps[1] = opt.Backs0; reps[2] = opt.Backs1; reps[3] = opt.Backs3; } else { reps[0] = opt.Backs3; reps[1] = opt.Backs0; reps[2] = opt.Backs1; reps[3] = opt.Backs2; } } else { reps[0] = (pos - Base.kNumRepDistances); reps[1] = opt.Backs0; reps[2] = opt.Backs1; reps[3] = opt.Backs2; } } _optimum[cur].State = state; _optimum[cur].Backs0 = reps[0]; _optimum[cur].Backs1 = reps[1]; _optimum[cur].Backs2 = reps[2]; _optimum[cur].Backs3 = reps[3]; int curPrice = _optimum[cur].Price; currentByte = _matchFinder.GetIndexByte(0 - 1); matchByte = _matchFinder.GetIndexByte(0 - reps[0] - 1 - 1); posState = (position & _posStateMask); int curAnd1Price = curPrice + SevenZip.Compression.RangeCoder.Encoder.GetPrice0(_isMatch[(state << Base.kNumPosStatesBitsMax) + posState]) + _literalEncoder.GetSubCoder(position, _matchFinder.GetIndexByte(0 - 2)). GetPrice(!Base.StateIsCharState(state), matchByte, currentByte); Optimal nextOptimum = _optimum[cur + 1]; boolean nextIsChar = false; if (curAnd1Price < nextOptimum.Price) { nextOptimum.Price = curAnd1Price; nextOptimum.PosPrev = cur; nextOptimum.MakeAsChar(); nextIsChar = true; } matchPrice = curPrice + SevenZip.Compression.RangeCoder.Encoder.GetPrice1(_isMatch[(state << Base.kNumPosStatesBitsMax) + posState]); repMatchPrice = matchPrice + SevenZip.Compression.RangeCoder.Encoder.GetPrice1(_isRep[state]); if (matchByte == currentByte && !(nextOptimum.PosPrev < cur && nextOptimum.BackPrev == 0)) { int shortRepPrice = repMatchPrice + GetRepLen1Price(state, posState); if (shortRepPrice <= nextOptimum.Price) { nextOptimum.Price = shortRepPrice; nextOptimum.PosPrev = cur; nextOptimum.MakeAsShortRep(); nextIsChar = true; } } int numAvailableBytesFull = _matchFinder.GetNumAvailableBytes() + 1; numAvailableBytesFull = Math.min(kNumOpts - 1 - cur, numAvailableBytesFull); numAvailableBytes = numAvailableBytesFull; if (numAvailableBytes < 2) continue; if (numAvailableBytes > _numFastBytes) numAvailableBytes = _numFastBytes; if (!nextIsChar && matchByte != currentByte) { // try Literal + rep0 int t = Math.min(numAvailableBytesFull - 1, _numFastBytes); int lenTest2 = _matchFinder.GetMatchLen(0, reps[0], t); if (lenTest2 >= 2) { int state2 = Base.StateUpdateChar(state); int posStateNext = (position + 1) & _posStateMask; int nextRepMatchPrice = curAnd1Price + SevenZip.Compression.RangeCoder.Encoder.GetPrice1(_isMatch[(state2 << Base.kNumPosStatesBitsMax) + posStateNext]) + SevenZip.Compression.RangeCoder.Encoder.GetPrice1(_isRep[state2]); { int offset = cur + 1 + lenTest2; while (lenEnd < offset) _optimum[++lenEnd].Price = kIfinityPrice; int curAndLenPrice = nextRepMatchPrice + GetRepPrice( 0, lenTest2, state2, posStateNext); Optimal optimum = _optimum[offset]; if (curAndLenPrice < optimum.Price) { optimum.Price = curAndLenPrice; optimum.PosPrev = cur + 1; optimum.BackPrev = 0; optimum.Prev1IsChar = true; optimum.Prev2 = false; } } } } int startLen = 2; // speed optimization for (int repIndex = 0; repIndex < Base.kNumRepDistances; repIndex++) { int lenTest = _matchFinder.GetMatchLen(0 - 1, reps[repIndex], numAvailableBytes); if (lenTest < 2) continue; int lenTestTemp = lenTest; do { while (lenEnd < cur + lenTest) _optimum[++lenEnd].Price = kIfinityPrice; int curAndLenPrice = repMatchPrice + GetRepPrice(repIndex, lenTest, state, posState); Optimal optimum = _optimum[cur + lenTest]; if (curAndLenPrice < optimum.Price) { optimum.Price = curAndLenPrice; optimum.PosPrev = cur; optimum.BackPrev = repIndex; optimum.Prev1IsChar = false; } } while (--lenTest >= 2); lenTest = lenTestTemp; if (repIndex == 0) startLen = lenTest + 1; // if (_maxMode) if (lenTest < numAvailableBytesFull) { int t = Math.min(numAvailableBytesFull - 1 - lenTest, _numFastBytes); int lenTest2 = _matchFinder.GetMatchLen(lenTest, reps[repIndex], t); if (lenTest2 >= 2) { int state2 = Base.StateUpdateRep(state); int posStateNext = (position + lenTest) & _posStateMask; int curAndLenCharPrice = repMatchPrice + GetRepPrice(repIndex, lenTest, state, posState) + SevenZip.Compression.RangeCoder.Encoder.GetPrice0(_isMatch[(state2 << Base.kNumPosStatesBitsMax) + posStateNext]) + _literalEncoder.GetSubCoder(position + lenTest, _matchFinder.GetIndexByte(lenTest - 1 - 1)).GetPrice(true, _matchFinder.GetIndexByte(lenTest - 1 - (reps[repIndex] + 1)), _matchFinder.GetIndexByte(lenTest - 1)); state2 = Base.StateUpdateChar(state2); posStateNext = (position + lenTest + 1) & _posStateMask; int nextMatchPrice = curAndLenCharPrice + SevenZip.Compression.RangeCoder.Encoder.GetPrice1(_isMatch[(state2 << Base.kNumPosStatesBitsMax) + posStateNext]); int nextRepMatchPrice = nextMatchPrice + SevenZip.Compression.RangeCoder.Encoder.GetPrice1(_isRep[state2]); // for(; lenTest2 >= 2; lenTest2--) { int offset = lenTest + 1 + lenTest2; while (lenEnd < cur + offset) _optimum[++lenEnd].Price = kIfinityPrice; int curAndLenPrice = nextRepMatchPrice + GetRepPrice(0, lenTest2, state2, posStateNext); Optimal optimum = _optimum[cur + offset]; if (curAndLenPrice < optimum.Price) { optimum.Price = curAndLenPrice; optimum.PosPrev = cur + lenTest + 1; optimum.BackPrev = 0; optimum.Prev1IsChar = true; optimum.Prev2 = true; optimum.PosPrev2 = cur; optimum.BackPrev2 = repIndex; } } } } } if (newLen > numAvailableBytes) { newLen = numAvailableBytes; for (numDistancePairs = 0; newLen > _matchDistances[numDistancePairs]; numDistancePairs += 2) ; _matchDistances[numDistancePairs] = newLen; numDistancePairs += 2; } if (newLen >= startLen) { normalMatchPrice = matchPrice + SevenZip.Compression.RangeCoder.Encoder.GetPrice0(_isRep[state]); while (lenEnd < cur + newLen) _optimum[++lenEnd].Price = kIfinityPrice; int offs = 0; while (startLen > _matchDistances[offs]) offs += 2; for (int lenTest = startLen; ; lenTest++) { int curBack = _matchDistances[offs + 1]; int curAndLenPrice = normalMatchPrice + GetPosLenPrice(curBack, lenTest, posState); Optimal optimum = _optimum[cur + lenTest]; if (curAndLenPrice < optimum.Price) { optimum.Price = curAndLenPrice; optimum.PosPrev = cur; optimum.BackPrev = curBack + Base.kNumRepDistances; optimum.Prev1IsChar = false; } if (lenTest == _matchDistances[offs]) { if (lenTest < numAvailableBytesFull) { int t = Math.min(numAvailableBytesFull - 1 - lenTest, _numFastBytes); int lenTest2 = _matchFinder.GetMatchLen(lenTest, curBack, t); if (lenTest2 >= 2) { int state2 = Base.StateUpdateMatch(state); int posStateNext = (position + lenTest) & _posStateMask; int curAndLenCharPrice = curAndLenPrice + SevenZip.Compression.RangeCoder.Encoder.GetPrice0(_isMatch[(state2 << Base.kNumPosStatesBitsMax) + posStateNext]) + _literalEncoder.GetSubCoder(position + lenTest, _matchFinder.GetIndexByte(lenTest - 1 - 1)). GetPrice(true, _matchFinder.GetIndexByte(lenTest - (curBack + 1) - 1), _matchFinder.GetIndexByte(lenTest - 1)); state2 = Base.StateUpdateChar(state2); posStateNext = (position + lenTest + 1) & _posStateMask; int nextMatchPrice = curAndLenCharPrice + SevenZip.Compression.RangeCoder.Encoder.GetPrice1(_isMatch[(state2 << Base.kNumPosStatesBitsMax) + posStateNext]); int nextRepMatchPrice = nextMatchPrice + SevenZip.Compression.RangeCoder.Encoder.GetPrice1(_isRep[state2]); int offset = lenTest + 1 + lenTest2; while (lenEnd < cur + offset) _optimum[++lenEnd].Price = kIfinityPrice; curAndLenPrice = nextRepMatchPrice + GetRepPrice(0, lenTest2, state2, posStateNext); optimum = _optimum[cur + offset]; if (curAndLenPrice < optimum.Price) { optimum.Price = curAndLenPrice; optimum.PosPrev = cur + lenTest + 1; optimum.BackPrev = 0; optimum.Prev1IsChar = true; optimum.Prev2 = true; optimum.PosPrev2 = cur; optimum.BackPrev2 = curBack + Base.kNumRepDistances; } } } offs += 2; if (offs == numDistancePairs) break; } } } } } boolean ChangePair(int smallDist, int bigDist) { int kDif = 7; return (smallDist < (1 << (32 - kDif)) && bigDist >= (smallDist << kDif)); } void WriteEndMarker(int posState) throws IOException { if (!_writeEndMark) return; _rangeEncoder.Encode(_isMatch, (_state << Base.kNumPosStatesBitsMax) + posState, 1); _rangeEncoder.Encode(_isRep, _state, 0); _state = Base.StateUpdateMatch(_state); int len = Base.kMatchMinLen; _lenEncoder.Encode(_rangeEncoder, len - Base.kMatchMinLen, posState); int posSlot = (1 << Base.kNumPosSlotBits) - 1; int lenToPosState = Base.GetLenToPosState(len); _posSlotEncoder[lenToPosState].Encode(_rangeEncoder, posSlot); int footerBits = 30; int posReduced = (1 << footerBits) - 1; _rangeEncoder.EncodeDirectBits(posReduced >> Base.kNumAlignBits, footerBits - Base.kNumAlignBits); _posAlignEncoder.ReverseEncode(_rangeEncoder, posReduced & Base.kAlignMask); } void Flush(int nowPos) throws IOException { ReleaseMFStream(); WriteEndMarker(nowPos & _posStateMask); _rangeEncoder.FlushData(); _rangeEncoder.FlushStream(); } public void CodeOneBlock(long[] inSize, long[] outSize, boolean[] finished) throws IOException { inSize[0] = 0; outSize[0] = 0; finished[0] = true; if (_inStream != null) { _matchFinder.SetStream(_inStream); _matchFinder.Init(); _needReleaseMFStream = true; _inStream = null; } if (_finished) return; _finished = true; long progressPosValuePrev = nowPos64; if (nowPos64 == 0) { if (_matchFinder.GetNumAvailableBytes() == 0) { Flush((int)nowPos64); return; } ReadMatchDistances(); int posState = (int)(nowPos64) & _posStateMask; _rangeEncoder.Encode(_isMatch, (_state << Base.kNumPosStatesBitsMax) + posState, 0); _state = Base.StateUpdateChar(_state); byte curByte = _matchFinder.GetIndexByte(0 - _additionalOffset); _literalEncoder.GetSubCoder((int)(nowPos64), _previousByte).Encode(_rangeEncoder, curByte); _previousByte = curByte; _additionalOffset--; nowPos64++; } if (_matchFinder.GetNumAvailableBytes() == 0) { Flush((int)nowPos64); return; } while (true) { int len = GetOptimum((int)nowPos64); int pos = backRes; int posState = ((int)nowPos64) & _posStateMask; int complexState = (_state << Base.kNumPosStatesBitsMax) + posState; if (len == 1 && pos == -1) { _rangeEncoder.Encode(_isMatch, complexState, 0); byte curByte = _matchFinder.GetIndexByte((int)(0 - _additionalOffset)); LiteralEncoder.Encoder2 subCoder = _literalEncoder.GetSubCoder((int)nowPos64, _previousByte); if (!Base.StateIsCharState(_state)) { byte matchByte = _matchFinder.GetIndexByte((int)(0 - _repDistances[0] - 1 - _additionalOffset)); subCoder.EncodeMatched(_rangeEncoder, matchByte, curByte); } else subCoder.Encode(_rangeEncoder, curByte); _previousByte = curByte; _state = Base.StateUpdateChar(_state); } else { _rangeEncoder.Encode(_isMatch, complexState, 1); if (pos < Base.kNumRepDistances) { _rangeEncoder.Encode(_isRep, _state, 1); if (pos == 0) { _rangeEncoder.Encode(_isRepG0, _state, 0); if (len == 1) _rangeEncoder.Encode(_isRep0Long, complexState, 0); else _rangeEncoder.Encode(_isRep0Long, complexState, 1); } else { _rangeEncoder.Encode(_isRepG0, _state, 1); if (pos == 1) _rangeEncoder.Encode(_isRepG1, _state, 0); else { _rangeEncoder.Encode(_isRepG1, _state, 1); _rangeEncoder.Encode(_isRepG2, _state, pos - 2); } } if (len == 1) _state = Base.StateUpdateShortRep(_state); else { _repMatchLenEncoder.Encode(_rangeEncoder, len - Base.kMatchMinLen, posState); _state = Base.StateUpdateRep(_state); } int distance = _repDistances[pos]; if (pos != 0) { for (int i = pos; i >= 1; i--) _repDistances[i] = _repDistances[i - 1]; _repDistances[0] = distance; } } else { _rangeEncoder.Encode(_isRep, _state, 0); _state = Base.StateUpdateMatch(_state); _lenEncoder.Encode(_rangeEncoder, len - Base.kMatchMinLen, posState); pos -= Base.kNumRepDistances; int posSlot = GetPosSlot(pos); int lenToPosState = Base.GetLenToPosState(len); _posSlotEncoder[lenToPosState].Encode(_rangeEncoder, posSlot); if (posSlot >= Base.kStartPosModelIndex) { int footerBits = (int)((posSlot >> 1) - 1); int baseVal = ((2 | (posSlot & 1)) << footerBits); int posReduced = pos - baseVal; if (posSlot < Base.kEndPosModelIndex) BitTreeEncoder.ReverseEncode(_posEncoders, baseVal - posSlot - 1, _rangeEncoder, footerBits, posReduced); else { _rangeEncoder.EncodeDirectBits(posReduced >> Base.kNumAlignBits, footerBits - Base.kNumAlignBits); _posAlignEncoder.ReverseEncode(_rangeEncoder, posReduced & Base.kAlignMask); _alignPriceCount++; } } int distance = pos; for (int i = Base.kNumRepDistances - 1; i >= 1; i--) _repDistances[i] = _repDistances[i - 1]; _repDistances[0] = distance; _matchPriceCount++; } _previousByte = _matchFinder.GetIndexByte(len - 1 - _additionalOffset); } _additionalOffset -= len; nowPos64 += len; if (_additionalOffset == 0) { // if (!_fastMode) if (_matchPriceCount >= (1 << 7)) FillDistancesPrices(); if (_alignPriceCount >= Base.kAlignTableSize) FillAlignPrices(); inSize[0] = nowPos64; outSize[0] = _rangeEncoder.GetProcessedSizeAdd(); if (_matchFinder.GetNumAvailableBytes() == 0) { Flush((int)nowPos64); return; } if (nowPos64 - progressPosValuePrev >= (1 << 12)) { _finished = false; finished[0] = false; return; } } } } void ReleaseMFStream() { if (_matchFinder != null && _needReleaseMFStream) { _matchFinder.ReleaseStream(); _needReleaseMFStream = false; } } void SetOutStream(java.io.OutputStream outStream) { _rangeEncoder.SetStream(outStream); } void ReleaseOutStream() { _rangeEncoder.ReleaseStream(); } void ReleaseStreams() { ReleaseMFStream(); ReleaseOutStream(); } void SetStreams(java.io.InputStream inStream, java.io.OutputStream outStream, long inSize, long outSize) { _inStream = inStream; _finished = false; Create(); SetOutStream(outStream); Init(); // if (!_fastMode) { FillDistancesPrices(); FillAlignPrices(); } _lenEncoder.SetTableSize(_numFastBytes + 1 - Base.kMatchMinLen); _lenEncoder.UpdateTables(1 << _posStateBits); _repMatchLenEncoder.SetTableSize(_numFastBytes + 1 - Base.kMatchMinLen); _repMatchLenEncoder.UpdateTables(1 << _posStateBits); nowPos64 = 0; } long[] processedInSize = new long[1]; long[] processedOutSize = new long[1]; boolean[] finished = new boolean[1]; public void Code(java.io.InputStream inStream, java.io.OutputStream outStream, long inSize, long outSize, ICodeProgress progress) throws IOException { _needReleaseMFStream = false; try { SetStreams(inStream, outStream, inSize, outSize); while (true) { CodeOneBlock(processedInSize, processedOutSize, finished); if (finished[0]) return; if (progress != null) { progress.SetProgress(processedInSize[0], processedOutSize[0]); } } } finally { ReleaseStreams(); } } public static final int kPropSize = 5; byte[] properties = new byte[kPropSize]; public void WriteCoderProperties(java.io.OutputStream outStream) throws IOException { properties[0] = (byte)((_posStateBits * 5 + _numLiteralPosStateBits) * 9 + _numLiteralContextBits); for (int i = 0; i < 4; i++) properties[1 + i] = (byte)(_dictionarySize >> (8 * i)); outStream.write(properties, 0, kPropSize); } int[] tempPrices = new int[Base.kNumFullDistances]; int _matchPriceCount; void FillDistancesPrices() { for (int i = Base.kStartPosModelIndex; i < Base.kNumFullDistances; i++) { int posSlot = GetPosSlot(i); int footerBits = (int)((posSlot >> 1) - 1); int baseVal = ((2 | (posSlot & 1)) << footerBits); tempPrices[i] = BitTreeEncoder.ReverseGetPrice(_posEncoders, baseVal - posSlot - 1, footerBits, i - baseVal); } for (int lenToPosState = 0; lenToPosState < Base.kNumLenToPosStates; lenToPosState++) { int posSlot; BitTreeEncoder encoder = _posSlotEncoder[lenToPosState]; int st = (lenToPosState << Base.kNumPosSlotBits); for (posSlot = 0; posSlot < _distTableSize; posSlot++) _posSlotPrices[st + posSlot] = encoder.GetPrice(posSlot); for (posSlot = Base.kEndPosModelIndex; posSlot < _distTableSize; posSlot++) _posSlotPrices[st + posSlot] += ((((posSlot >> 1) - 1) - Base.kNumAlignBits) << SevenZip.Compression.RangeCoder.Encoder.kNumBitPriceShiftBits); int st2 = lenToPosState * Base.kNumFullDistances; int i; for (i = 0; i < Base.kStartPosModelIndex; i++) _distancesPrices[st2 + i] = _posSlotPrices[st + i]; for (; i < Base.kNumFullDistances; i++) _distancesPrices[st2 + i] = _posSlotPrices[st + GetPosSlot(i)] + tempPrices[i]; } _matchPriceCount = 0; } void FillAlignPrices() { for (int i = 0; i < Base.kAlignTableSize; i++) _alignPrices[i] = _posAlignEncoder.ReverseGetPrice(i); _alignPriceCount = 0; } public boolean SetAlgorithm(int algorithm) { /* _fastMode = (algorithm == 0); _maxMode = (algorithm >= 2); */ return true; } public boolean SetDictionarySize(int dictionarySize) { int kDicLogSizeMaxCompress = 29; if (dictionarySize < (1 << Base.kDicLogSizeMin) || dictionarySize > (1 << kDicLogSizeMaxCompress)) return false; _dictionarySize = dictionarySize; int dicLogSize; for (dicLogSize = 0; dictionarySize > (1 << dicLogSize); dicLogSize++) ; _distTableSize = dicLogSize * 2; return true; } public boolean SetNumFastBytes(int numFastBytes) { if (numFastBytes < 5 || numFastBytes > Base.kMatchMaxLen) return false; _numFastBytes = numFastBytes; return true; } public boolean SetMatchFinder(int matchFinderIndex) { if (matchFinderIndex < 0 || matchFinderIndex > 2) return false; int matchFinderIndexPrev = _matchFinderType; _matchFinderType = matchFinderIndex; if (_matchFinder != null && matchFinderIndexPrev != _matchFinderType) { _dictionarySizePrev = -1; _matchFinder = null; } return true; } public boolean SetLcLpPb(int lc, int lp, int pb) { if ( lp < 0 || lp > Base.kNumLitPosStatesBitsEncodingMax || lc < 0 || lc > Base.kNumLitContextBitsMax || pb < 0 || pb > Base.kNumPosStatesBitsEncodingMax) return false; _numLiteralPosStateBits = lp; _numLiteralContextBits = lc; _posStateBits = pb; _posStateMask = ((1) << _posStateBits) - 1; return true; } public void SetEndMarkerMode(boolean endMarkerMode) { _writeEndMark = endMarkerMode; } }
40,845
27.825688
164
java
uiHRDC
uiHRDC-master/uiHRDC/indexes/NOPOS/II_docs/ilists.imp/6.vbyteP7zip_acabadoMerge2yN[Fork]/lzmalib/lzma.sourceCode/LZMAFARI_LIB/lzma465/Java/SevenZip/CRC.java
// SevenZip/CRC.java package SevenZip; public class CRC { static public int[] Table = new int[256]; static { for (int i = 0; i < 256; i++) { int r = i; for (int j = 0; j < 8; j++) if ((r & 1) != 0) r = (r >>> 1) ^ 0xEDB88320; else r >>>= 1; Table[i] = r; } } int _value = -1; public void Init() { _value = -1; } public void Update(byte[] data, int offset, int size) { for (int i = 0; i < size; i++) _value = Table[(_value ^ data[offset + i]) & 0xFF] ^ (_value >>> 8); } public void Update(byte[] data) { int size = data.length; for (int i = 0; i < size; i++) _value = Table[(_value ^ data[i]) & 0xFF] ^ (_value >>> 8); } public void UpdateByte(int b) { _value = Table[(_value ^ b) & 0xFF] ^ (_value >>> 8); } public int GetDigest() { return _value ^ (-1); } }
847
15
71
java
uiHRDC
uiHRDC-master/uiHRDC/indexes/NOPOS/II_docs/ilists.imp/6.vbyteP7zip_acabadoMerge2yN[Fork]/lzmalib/lzma.sourceCode/LZMAFARI_LIB/lzma465/Java/SevenZip/ICodeProgress.java
package SevenZip; public interface ICodeProgress { public void SetProgress(long inSize, long outSize); }
107
14.428571
52
java
uiHRDC
uiHRDC-master/uiHRDC/indexes/NOPOS/II_docs/ilists.imp/6.vbyteP7zip_acabadoMerge2yN[Fork]/lzmalib/lzma.sourceCode/LZMAFARI_LIB/lzma465/Java/SevenZip/LzmaAlone.java
package SevenZip; public class LzmaAlone { static public class CommandLine { public static final int kEncode = 0; public static final int kDecode = 1; public static final int kBenchmak = 2; public int Command = -1; public int NumBenchmarkPasses = 10; public int DictionarySize = 1 << 23; public boolean DictionarySizeIsDefined = false; public int Lc = 3; public int Lp = 0; public int Pb = 2; public int Fb = 128; public boolean FbIsDefined = false; public boolean Eos = false; public int Algorithm = 2; public int MatchFinder = 1; public String InFile; public String OutFile; boolean ParseSwitch(String s) { if (s.startsWith("d")) { DictionarySize = 1 << Integer.parseInt(s.substring(1)); DictionarySizeIsDefined = true; } else if (s.startsWith("fb")) { Fb = Integer.parseInt(s.substring(2)); FbIsDefined = true; } else if (s.startsWith("a")) Algorithm = Integer.parseInt(s.substring(1)); else if (s.startsWith("lc")) Lc = Integer.parseInt(s.substring(2)); else if (s.startsWith("lp")) Lp = Integer.parseInt(s.substring(2)); else if (s.startsWith("pb")) Pb = Integer.parseInt(s.substring(2)); else if (s.startsWith("eos")) Eos = true; else if (s.startsWith("mf")) { String mfs = s.substring(2); if (mfs.equals("bt2")) MatchFinder = 0; else if (mfs.equals("bt4")) MatchFinder = 1; else if (mfs.equals("bt4b")) MatchFinder = 2; else return false; } else return false; return true; } public boolean Parse(String[] args) throws Exception { int pos = 0; boolean switchMode = true; for (int i = 0; i < args.length; i++) { String s = args[i]; if (s.length() == 0) return false; if (switchMode) { if (s.compareTo("--") == 0) { switchMode = false; continue; } if (s.charAt(0) == '-') { String sw = s.substring(1).toLowerCase(); if (sw.length() == 0) return false; try { if (!ParseSwitch(sw)) return false; } catch (NumberFormatException e) { return false; } continue; } } if (pos == 0) { if (s.equalsIgnoreCase("e")) Command = kEncode; else if (s.equalsIgnoreCase("d")) Command = kDecode; else if (s.equalsIgnoreCase("b")) Command = kBenchmak; else return false; } else if(pos == 1) { if (Command == kBenchmak) { try { NumBenchmarkPasses = Integer.parseInt(s); if (NumBenchmarkPasses < 1) return false; } catch (NumberFormatException e) { return false; } } else InFile = s; } else if(pos == 2) OutFile = s; else return false; pos++; continue; } return true; } } static void PrintHelp() { System.out.println( "\nUsage: LZMA <e|d> [<switches>...] inputFile outputFile\n" + " e: encode file\n" + " d: decode file\n" + " b: Benchmark\n" + "<Switches>\n" + // " -a{N}: set compression mode - [0, 1], default: 1 (max)\n" + " -d{N}: set dictionary - [0,28], default: 23 (8MB)\n" + " -fb{N}: set number of fast bytes - [5, 273], default: 128\n" + " -lc{N}: set number of literal context bits - [0, 8], default: 3\n" + " -lp{N}: set number of literal pos bits - [0, 4], default: 0\n" + " -pb{N}: set number of pos bits - [0, 4], default: 2\n" + " -mf{MF_ID}: set Match Finder: [bt2, bt4], default: bt4\n" + " -eos: write End Of Stream marker\n" ); } public static void main(String[] args) throws Exception { System.out.println("\nLZMA (Java) 4.61 2008-11-23\n"); if (args.length < 1) { PrintHelp(); return; } CommandLine params = new CommandLine(); if (!params.Parse(args)) { System.out.println("\nIncorrect command"); return; } if (params.Command == CommandLine.kBenchmak) { int dictionary = (1 << 21); if (params.DictionarySizeIsDefined) dictionary = params.DictionarySize; if (params.MatchFinder > 1) throw new Exception("Unsupported match finder"); SevenZip.LzmaBench.LzmaBenchmark(params.NumBenchmarkPasses, dictionary); } else if (params.Command == CommandLine.kEncode || params.Command == CommandLine.kDecode) { java.io.File inFile = new java.io.File(params.InFile); java.io.File outFile = new java.io.File(params.OutFile); java.io.BufferedInputStream inStream = new java.io.BufferedInputStream(new java.io.FileInputStream(inFile)); java.io.BufferedOutputStream outStream = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outFile)); boolean eos = false; if (params.Eos) eos = true; if (params.Command == CommandLine.kEncode) { SevenZip.Compression.LZMA.Encoder encoder = new SevenZip.Compression.LZMA.Encoder(); if (!encoder.SetAlgorithm(params.Algorithm)) throw new Exception("Incorrect compression mode"); if (!encoder.SetDictionarySize(params.DictionarySize)) throw new Exception("Incorrect dictionary size"); if (!encoder.SetNumFastBytes(params.Fb)) throw new Exception("Incorrect -fb value"); if (!encoder.SetMatchFinder(params.MatchFinder)) throw new Exception("Incorrect -mf value"); if (!encoder.SetLcLpPb(params.Lc, params.Lp, params.Pb)) throw new Exception("Incorrect -lc or -lp or -pb value"); encoder.SetEndMarkerMode(eos); encoder.WriteCoderProperties(outStream); long fileSize; if (eos) fileSize = -1; else fileSize = inFile.length(); for (int i = 0; i < 8; i++) outStream.write((int)(fileSize >>> (8 * i)) & 0xFF); encoder.Code(inStream, outStream, -1, -1, null); } else { int propertiesSize = 5; byte[] properties = new byte[propertiesSize]; if (inStream.read(properties, 0, propertiesSize) != propertiesSize) throw new Exception("input .lzma file is too short"); SevenZip.Compression.LZMA.Decoder decoder = new SevenZip.Compression.LZMA.Decoder(); if (!decoder.SetDecoderProperties(properties)) throw new Exception("Incorrect stream properties"); long outSize = 0; for (int i = 0; i < 8; i++) { int v = inStream.read(); if (v < 0) throw new Exception("Can't read stream size"); outSize |= ((long)v) << (8 * i); } if (!decoder.Code(inStream, outStream, outSize)) throw new Exception("Error in data stream"); } outStream.flush(); outStream.close(); inStream.close(); } else throw new Exception("Incorrect command"); return; } }
6,695
25.362205
116
java
uiHRDC
uiHRDC-master/uiHRDC/indexes/NOPOS/II_docs/ilists.imp/6.vbyteP7zip_acabadoMerge2yN[Fork]/lzmalib/lzma.sourceCode/LZMAFARI_LIB/lzma465/Java/SevenZip/LzmaBench.java
package SevenZip; import java.io.ByteArrayOutputStream; import java.io.ByteArrayInputStream; import java.io.IOException; public class LzmaBench { static final int kAdditionalSize = (1 << 21); static final int kCompressedAdditionalSize = (1 << 10); static class CRandomGenerator { int A1; int A2; public CRandomGenerator() { Init(); } public void Init() { A1 = 362436069; A2 = 521288629; } public int GetRnd() { return ((A1 = 36969 * (A1 & 0xffff) + (A1 >>> 16)) << 16) ^ ((A2 = 18000 * (A2 & 0xffff) + (A2 >>> 16))); } }; static class CBitRandomGenerator { CRandomGenerator RG = new CRandomGenerator(); int Value; int NumBits; public void Init() { Value = 0; NumBits = 0; } public int GetRnd(int numBits) { int result; if (NumBits > numBits) { result = Value & ((1 << numBits) - 1); Value >>>= numBits; NumBits -= numBits; return result; } numBits -= NumBits; result = (Value << numBits); Value = RG.GetRnd(); result |= Value & (((int)1 << numBits) - 1); Value >>>= numBits; NumBits = 32 - numBits; return result; } }; static class CBenchRandomGenerator { CBitRandomGenerator RG = new CBitRandomGenerator(); int Pos; int Rep0; public int BufferSize; public byte[] Buffer = null; public CBenchRandomGenerator() { } public void Set(int bufferSize) { Buffer = new byte[bufferSize]; Pos = 0; BufferSize = bufferSize; } int GetRndBit() { return RG.GetRnd(1); } int GetLogRandBits(int numBits) { int len = RG.GetRnd(numBits); return RG.GetRnd((int)len); } int GetOffset() { if (GetRndBit() == 0) return GetLogRandBits(4); return (GetLogRandBits(4) << 10) | RG.GetRnd(10); } int GetLen1() { return RG.GetRnd(1 + (int)RG.GetRnd(2)); } int GetLen2() { return RG.GetRnd(2 + (int)RG.GetRnd(2)); } public void Generate() { RG.Init(); Rep0 = 1; while (Pos < BufferSize) { if (GetRndBit() == 0 || Pos < 1) Buffer[Pos++] = (byte)(RG.GetRnd(8)); else { int len; if (RG.GetRnd(3) == 0) len = 1 + GetLen1(); else { do Rep0 = GetOffset(); while (Rep0 >= Pos); Rep0++; len = 2 + GetLen2(); } for (int i = 0; i < len && Pos < BufferSize; i++, Pos++) Buffer[Pos] = Buffer[Pos - Rep0]; } } } }; static class CrcOutStream extends java.io.OutputStream { public CRC CRC = new CRC(); public void Init() { CRC.Init(); } public int GetDigest() { return CRC.GetDigest(); } public void write(byte[] b) { CRC.Update(b); } public void write(byte[] b, int off, int len) { CRC.Update(b, off, len); } public void write(int b) { CRC.UpdateByte(b); } }; static class MyOutputStream extends java.io.OutputStream { byte[] _buffer; int _size; int _pos; public MyOutputStream(byte[] buffer) { _buffer = buffer; _size = _buffer.length; } public void reset() { _pos = 0; } public void write(int b) throws IOException { if (_pos >= _size) throw new IOException("Error"); _buffer[_pos++] = (byte)b; } public int size() { return _pos; } }; static class MyInputStream extends java.io.InputStream { byte[] _buffer; int _size; int _pos; public MyInputStream(byte[] buffer, int size) { _buffer = buffer; _size = size; } public void reset() { _pos = 0; } public int read() { if (_pos >= _size) return -1; return _buffer[_pos++] & 0xFF; } }; static class CProgressInfo implements ICodeProgress { public long ApprovedStart; public long InSize; public long Time; public void Init() { InSize = 0; } public void SetProgress(long inSize, long outSize) { if (inSize >= ApprovedStart && InSize == 0) { Time = System.currentTimeMillis(); InSize = inSize; } } } static final int kSubBits = 8; static int GetLogSize(int size) { for (int i = kSubBits; i < 32; i++) for (int j = 0; j < (1 << kSubBits); j++) if (size <= ((1) << i) + (j << (i - kSubBits))) return (i << kSubBits) + j; return (32 << kSubBits); } static long MyMultDiv64(long value, long elapsedTime) { long freq = 1000; // ms long elTime = elapsedTime; while (freq > 1000000) { freq >>>= 1; elTime >>>= 1; } if (elTime == 0) elTime = 1; return value * freq / elTime; } static long GetCompressRating(int dictionarySize, long elapsedTime, long size) { long t = GetLogSize(dictionarySize) - (18 << kSubBits); long numCommandsForOne = 1060 + ((t * t * 10) >> (2 * kSubBits)); long numCommands = (long)(size) * numCommandsForOne; return MyMultDiv64(numCommands, elapsedTime); } static long GetDecompressRating(long elapsedTime, long outSize, long inSize) { long numCommands = inSize * 220 + outSize * 20; return MyMultDiv64(numCommands, elapsedTime); } static long GetTotalRating( int dictionarySize, long elapsedTimeEn, long sizeEn, long elapsedTimeDe, long inSizeDe, long outSizeDe) { return (GetCompressRating(dictionarySize, elapsedTimeEn, sizeEn) + GetDecompressRating(elapsedTimeDe, inSizeDe, outSizeDe)) / 2; } static void PrintValue(long v) { String s = ""; s += v; for (int i = 0; i + s.length() < 6; i++) System.out.print(" "); System.out.print(s); } static void PrintRating(long rating) { PrintValue(rating / 1000000); System.out.print(" MIPS"); } static void PrintResults( int dictionarySize, long elapsedTime, long size, boolean decompressMode, long secondSize) { long speed = MyMultDiv64(size, elapsedTime); PrintValue(speed / 1024); System.out.print(" KB/s "); long rating; if (decompressMode) rating = GetDecompressRating(elapsedTime, size, secondSize); else rating = GetCompressRating(dictionarySize, elapsedTime, size); PrintRating(rating); } static public int LzmaBenchmark(int numIterations, int dictionarySize) throws Exception { if (numIterations <= 0) return 0; if (dictionarySize < (1 << 18)) { System.out.println("\nError: dictionary size for benchmark must be >= 18 (256 KB)"); return 1; } System.out.print("\n Compressing Decompressing\n\n"); SevenZip.Compression.LZMA.Encoder encoder = new SevenZip.Compression.LZMA.Encoder(); SevenZip.Compression.LZMA.Decoder decoder = new SevenZip.Compression.LZMA.Decoder(); if (!encoder.SetDictionarySize(dictionarySize)) throw new Exception("Incorrect dictionary size"); int kBufferSize = dictionarySize + kAdditionalSize; int kCompressedBufferSize = (kBufferSize / 2) + kCompressedAdditionalSize; ByteArrayOutputStream propStream = new ByteArrayOutputStream(); encoder.WriteCoderProperties(propStream); byte[] propArray = propStream.toByteArray(); decoder.SetDecoderProperties(propArray); CBenchRandomGenerator rg = new CBenchRandomGenerator(); rg.Set(kBufferSize); rg.Generate(); CRC crc = new CRC(); crc.Init(); crc.Update(rg.Buffer, 0, rg.BufferSize); CProgressInfo progressInfo = new CProgressInfo(); progressInfo.ApprovedStart = dictionarySize; long totalBenchSize = 0; long totalEncodeTime = 0; long totalDecodeTime = 0; long totalCompressedSize = 0; MyInputStream inStream = new MyInputStream(rg.Buffer, rg.BufferSize); byte[] compressedBuffer = new byte[kCompressedBufferSize]; MyOutputStream compressedStream = new MyOutputStream(compressedBuffer); CrcOutStream crcOutStream = new CrcOutStream(); MyInputStream inputCompressedStream = null; int compressedSize = 0; for (int i = 0; i < numIterations; i++) { progressInfo.Init(); inStream.reset(); compressedStream.reset(); encoder.Code(inStream, compressedStream, -1, -1, progressInfo); long encodeTime = System.currentTimeMillis() - progressInfo.Time; if (i == 0) { compressedSize = compressedStream.size(); inputCompressedStream = new MyInputStream(compressedBuffer, compressedSize); } else if (compressedSize != compressedStream.size()) throw (new Exception("Encoding error")); if (progressInfo.InSize == 0) throw (new Exception("Internal ERROR 1282")); long decodeTime = 0; for (int j = 0; j < 2; j++) { inputCompressedStream.reset(); crcOutStream.Init(); long outSize = kBufferSize; long startTime = System.currentTimeMillis(); if (!decoder.Code(inputCompressedStream, crcOutStream, outSize)) throw (new Exception("Decoding Error"));; decodeTime = System.currentTimeMillis() - startTime; if (crcOutStream.GetDigest() != crc.GetDigest()) throw (new Exception("CRC Error")); } long benchSize = kBufferSize - (long)progressInfo.InSize; PrintResults(dictionarySize, encodeTime, benchSize, false, 0); System.out.print(" "); PrintResults(dictionarySize, decodeTime, kBufferSize, true, compressedSize); System.out.println(); totalBenchSize += benchSize; totalEncodeTime += encodeTime; totalDecodeTime += decodeTime; totalCompressedSize += compressedSize; } System.out.println("---------------------------------------------------"); PrintResults(dictionarySize, totalEncodeTime, totalBenchSize, false, 0); System.out.print(" "); PrintResults(dictionarySize, totalDecodeTime, kBufferSize * (long)numIterations, true, totalCompressedSize); System.out.println(" Average"); return 0; } }
9,483
23.132316
88
java
uiHRDC
uiHRDC-master/uiHRDC/indexes/NOPOS/II_docs/ilists.imp/6.vbyteP7zip_acabadoMerge2yN[Fork]/lzmalib/lzma.sourceCode/LZMAFARI_LIB/lzma465/Java/SevenZip/Compression/LZ/OutWindow.java
// LZ.OutWindow package SevenZip.Compression.LZ; import java.io.IOException; public class OutWindow { byte[] _buffer; int _pos; int _windowSize = 0; int _streamPos; java.io.OutputStream _stream; public void Create(int windowSize) { if (_buffer == null || _windowSize != windowSize) _buffer = new byte[windowSize]; _windowSize = windowSize; _pos = 0; _streamPos = 0; } public void SetStream(java.io.OutputStream stream) throws IOException { ReleaseStream(); _stream = stream; } public void ReleaseStream() throws IOException { Flush(); _stream = null; } public void Init(boolean solid) { if (!solid) { _streamPos = 0; _pos = 0; } } public void Flush() throws IOException { int size = _pos - _streamPos; if (size == 0) return; _stream.write(_buffer, _streamPos, size); if (_pos >= _windowSize) _pos = 0; _streamPos = _pos; } public void CopyBlock(int distance, int len) throws IOException { int pos = _pos - distance - 1; if (pos < 0) pos += _windowSize; for (; len != 0; len--) { if (pos >= _windowSize) pos = 0; _buffer[_pos++] = _buffer[pos++]; if (_pos >= _windowSize) Flush(); } } public void PutByte(byte b) throws IOException { _buffer[_pos++] = b; if (_pos >= _windowSize) Flush(); } public byte GetByte(int distance) { int pos = _pos - distance - 1; if (pos < 0) pos += _windowSize; return _buffer[pos]; } }
1,456
15.94186
70
java
uiHRDC
uiHRDC-master/uiHRDC/indexes/NOPOS/II_docs/ilists.imp/6.vbyteP7zip_acabadoMerge2yN[Fork]/lzmalib/lzma.sourceCode/LZMAFARI_LIB/lzma465/Java/SevenZip/Compression/LZ/BinTree.java
// LZ.BinTree package SevenZip.Compression.LZ; import java.io.IOException; public class BinTree extends InWindow { int _cyclicBufferPos; int _cyclicBufferSize = 0; int _matchMaxLen; int[] _son; int[] _hash; int _cutValue = 0xFF; int _hashMask; int _hashSizeSum = 0; boolean HASH_ARRAY = true; static final int kHash2Size = 1 << 10; static final int kHash3Size = 1 << 16; static final int kBT2HashSize = 1 << 16; static final int kStartMaxLen = 1; static final int kHash3Offset = kHash2Size; static final int kEmptyHashValue = 0; static final int kMaxValForNormalize = (1 << 30) - 1; int kNumHashDirectBytes = 0; int kMinMatchCheck = 4; int kFixHashSize = kHash2Size + kHash3Size; public void SetType(int numHashBytes) { HASH_ARRAY = (numHashBytes > 2); if (HASH_ARRAY) { kNumHashDirectBytes = 0; kMinMatchCheck = 4; kFixHashSize = kHash2Size + kHash3Size; } else { kNumHashDirectBytes = 2; kMinMatchCheck = 2 + 1; kFixHashSize = 0; } } public void Init() throws IOException { super.Init(); for (int i = 0; i < _hashSizeSum; i++) _hash[i] = kEmptyHashValue; _cyclicBufferPos = 0; ReduceOffsets(-1); } public void MovePos() throws IOException { if (++_cyclicBufferPos >= _cyclicBufferSize) _cyclicBufferPos = 0; super.MovePos(); if (_pos == kMaxValForNormalize) Normalize(); } public boolean Create(int historySize, int keepAddBufferBefore, int matchMaxLen, int keepAddBufferAfter) { if (historySize > kMaxValForNormalize - 256) return false; _cutValue = 16 + (matchMaxLen >> 1); int windowReservSize = (historySize + keepAddBufferBefore + matchMaxLen + keepAddBufferAfter) / 2 + 256; super.Create(historySize + keepAddBufferBefore, matchMaxLen + keepAddBufferAfter, windowReservSize); _matchMaxLen = matchMaxLen; int cyclicBufferSize = historySize + 1; if (_cyclicBufferSize != cyclicBufferSize) _son = new int[(_cyclicBufferSize = cyclicBufferSize) * 2]; int hs = kBT2HashSize; if (HASH_ARRAY) { hs = historySize - 1; hs |= (hs >> 1); hs |= (hs >> 2); hs |= (hs >> 4); hs |= (hs >> 8); hs >>= 1; hs |= 0xFFFF; if (hs > (1 << 24)) hs >>= 1; _hashMask = hs; hs++; hs += kFixHashSize; } if (hs != _hashSizeSum) _hash = new int [_hashSizeSum = hs]; return true; } public int GetMatches(int[] distances) throws IOException { int lenLimit; if (_pos + _matchMaxLen <= _streamPos) lenLimit = _matchMaxLen; else { lenLimit = _streamPos - _pos; if (lenLimit < kMinMatchCheck) { MovePos(); return 0; } } int offset = 0; int matchMinPos = (_pos > _cyclicBufferSize) ? (_pos - _cyclicBufferSize) : 0; int cur = _bufferOffset + _pos; int maxLen = kStartMaxLen; // to avoid items for len < hashSize; int hashValue, hash2Value = 0, hash3Value = 0; if (HASH_ARRAY) { int temp = CrcTable[_bufferBase[cur] & 0xFF] ^ (_bufferBase[cur + 1] & 0xFF); hash2Value = temp & (kHash2Size - 1); temp ^= ((int)(_bufferBase[cur + 2] & 0xFF) << 8); hash3Value = temp & (kHash3Size - 1); hashValue = (temp ^ (CrcTable[_bufferBase[cur + 3] & 0xFF] << 5)) & _hashMask; } else hashValue = ((_bufferBase[cur] & 0xFF) ^ ((int)(_bufferBase[cur + 1] & 0xFF) << 8)); int curMatch = _hash[kFixHashSize + hashValue]; if (HASH_ARRAY) { int curMatch2 = _hash[hash2Value]; int curMatch3 = _hash[kHash3Offset + hash3Value]; _hash[hash2Value] = _pos; _hash[kHash3Offset + hash3Value] = _pos; if (curMatch2 > matchMinPos) if (_bufferBase[_bufferOffset + curMatch2] == _bufferBase[cur]) { distances[offset++] = maxLen = 2; distances[offset++] = _pos - curMatch2 - 1; } if (curMatch3 > matchMinPos) if (_bufferBase[_bufferOffset + curMatch3] == _bufferBase[cur]) { if (curMatch3 == curMatch2) offset -= 2; distances[offset++] = maxLen = 3; distances[offset++] = _pos - curMatch3 - 1; curMatch2 = curMatch3; } if (offset != 0 && curMatch2 == curMatch) { offset -= 2; maxLen = kStartMaxLen; } } _hash[kFixHashSize + hashValue] = _pos; int ptr0 = (_cyclicBufferPos << 1) + 1; int ptr1 = (_cyclicBufferPos << 1); int len0, len1; len0 = len1 = kNumHashDirectBytes; if (kNumHashDirectBytes != 0) { if (curMatch > matchMinPos) { if (_bufferBase[_bufferOffset + curMatch + kNumHashDirectBytes] != _bufferBase[cur + kNumHashDirectBytes]) { distances[offset++] = maxLen = kNumHashDirectBytes; distances[offset++] = _pos - curMatch - 1; } } } int count = _cutValue; while (true) { if (curMatch <= matchMinPos || count-- == 0) { _son[ptr0] = _son[ptr1] = kEmptyHashValue; break; } int delta = _pos - curMatch; int cyclicPos = ((delta <= _cyclicBufferPos) ? (_cyclicBufferPos - delta) : (_cyclicBufferPos - delta + _cyclicBufferSize)) << 1; int pby1 = _bufferOffset + curMatch; int len = Math.min(len0, len1); if (_bufferBase[pby1 + len] == _bufferBase[cur + len]) { while(++len != lenLimit) if (_bufferBase[pby1 + len] != _bufferBase[cur + len]) break; if (maxLen < len) { distances[offset++] = maxLen = len; distances[offset++] = delta - 1; if (len == lenLimit) { _son[ptr1] = _son[cyclicPos]; _son[ptr0] = _son[cyclicPos + 1]; break; } } } if ((_bufferBase[pby1 + len] & 0xFF) < (_bufferBase[cur + len] & 0xFF)) { _son[ptr1] = curMatch; ptr1 = cyclicPos + 1; curMatch = _son[ptr1]; len1 = len; } else { _son[ptr0] = curMatch; ptr0 = cyclicPos; curMatch = _son[ptr0]; len0 = len; } } MovePos(); return offset; } public void Skip(int num) throws IOException { do { int lenLimit; if (_pos + _matchMaxLen <= _streamPos) lenLimit = _matchMaxLen; else { lenLimit = _streamPos - _pos; if (lenLimit < kMinMatchCheck) { MovePos(); continue; } } int matchMinPos = (_pos > _cyclicBufferSize) ? (_pos - _cyclicBufferSize) : 0; int cur = _bufferOffset + _pos; int hashValue; if (HASH_ARRAY) { int temp = CrcTable[_bufferBase[cur] & 0xFF] ^ (_bufferBase[cur + 1] & 0xFF); int hash2Value = temp & (kHash2Size - 1); _hash[hash2Value] = _pos; temp ^= ((int)(_bufferBase[cur + 2] & 0xFF) << 8); int hash3Value = temp & (kHash3Size - 1); _hash[kHash3Offset + hash3Value] = _pos; hashValue = (temp ^ (CrcTable[_bufferBase[cur + 3] & 0xFF] << 5)) & _hashMask; } else hashValue = ((_bufferBase[cur] & 0xFF) ^ ((int)(_bufferBase[cur + 1] & 0xFF) << 8)); int curMatch = _hash[kFixHashSize + hashValue]; _hash[kFixHashSize + hashValue] = _pos; int ptr0 = (_cyclicBufferPos << 1) + 1; int ptr1 = (_cyclicBufferPos << 1); int len0, len1; len0 = len1 = kNumHashDirectBytes; int count = _cutValue; while (true) { if (curMatch <= matchMinPos || count-- == 0) { _son[ptr0] = _son[ptr1] = kEmptyHashValue; break; } int delta = _pos - curMatch; int cyclicPos = ((delta <= _cyclicBufferPos) ? (_cyclicBufferPos - delta) : (_cyclicBufferPos - delta + _cyclicBufferSize)) << 1; int pby1 = _bufferOffset + curMatch; int len = Math.min(len0, len1); if (_bufferBase[pby1 + len] == _bufferBase[cur + len]) { while (++len != lenLimit) if (_bufferBase[pby1 + len] != _bufferBase[cur + len]) break; if (len == lenLimit) { _son[ptr1] = _son[cyclicPos]; _son[ptr0] = _son[cyclicPos + 1]; break; } } if ((_bufferBase[pby1 + len] & 0xFF) < (_bufferBase[cur + len] & 0xFF)) { _son[ptr1] = curMatch; ptr1 = cyclicPos + 1; curMatch = _son[ptr1]; len1 = len; } else { _son[ptr0] = curMatch; ptr0 = cyclicPos; curMatch = _son[ptr0]; len0 = len; } } MovePos(); } while (--num != 0); } void NormalizeLinks(int[] items, int numItems, int subValue) { for (int i = 0; i < numItems; i++) { int value = items[i]; if (value <= subValue) value = kEmptyHashValue; else value -= subValue; items[i] = value; } } void Normalize() { int subValue = _pos - _cyclicBufferSize; NormalizeLinks(_son, _cyclicBufferSize * 2, subValue); NormalizeLinks(_hash, _hashSizeSum, subValue); ReduceOffsets(subValue); } public void SetCutValue(int cutValue) { _cutValue = cutValue; } private static final int[] CrcTable = new int[256]; static { for (int i = 0; i < 256; i++) { int r = i; for (int j = 0; j < 8; j++) if ((r & 1) != 0) r = (r >>> 1) ^ 0xEDB88320; else r >>>= 1; CrcTable[i] = r; } } }
8,800
21.979112
102
java
uiHRDC
uiHRDC-master/uiHRDC/indexes/NOPOS/II_docs/ilists.imp/6.vbyteP7zip_acabadoMerge2yN[Fork]/lzmalib/lzma.sourceCode/LZMAFARI_LIB/lzma465/Java/SevenZip/Compression/LZ/InWindow.java
// LZ.InWindow package SevenZip.Compression.LZ; import java.io.IOException; public class InWindow { public byte[] _bufferBase; // pointer to buffer with data java.io.InputStream _stream; int _posLimit; // offset (from _buffer) of first byte when new block reading must be done boolean _streamEndWasReached; // if (true) then _streamPos shows real end of stream int _pointerToLastSafePosition; public int _bufferOffset; public int _blockSize; // Size of Allocated memory block public int _pos; // offset (from _buffer) of curent byte int _keepSizeBefore; // how many BYTEs must be kept in buffer before _pos int _keepSizeAfter; // how many BYTEs must be kept buffer after _pos public int _streamPos; // offset (from _buffer) of first not read byte from Stream public void MoveBlock() { int offset = _bufferOffset + _pos - _keepSizeBefore; // we need one additional byte, since MovePos moves on 1 byte. if (offset > 0) offset--; int numBytes = _bufferOffset + _streamPos - offset; // check negative offset ???? for (int i = 0; i < numBytes; i++) _bufferBase[i] = _bufferBase[offset + i]; _bufferOffset -= offset; } public void ReadBlock() throws IOException { if (_streamEndWasReached) return; while (true) { int size = (0 - _bufferOffset) + _blockSize - _streamPos; if (size == 0) return; int numReadBytes = _stream.read(_bufferBase, _bufferOffset + _streamPos, size); if (numReadBytes == -1) { _posLimit = _streamPos; int pointerToPostion = _bufferOffset + _posLimit; if (pointerToPostion > _pointerToLastSafePosition) _posLimit = _pointerToLastSafePosition - _bufferOffset; _streamEndWasReached = true; return; } _streamPos += numReadBytes; if (_streamPos >= _pos + _keepSizeAfter) _posLimit = _streamPos - _keepSizeAfter; } } void Free() { _bufferBase = null; } public void Create(int keepSizeBefore, int keepSizeAfter, int keepSizeReserv) { _keepSizeBefore = keepSizeBefore; _keepSizeAfter = keepSizeAfter; int blockSize = keepSizeBefore + keepSizeAfter + keepSizeReserv; if (_bufferBase == null || _blockSize != blockSize) { Free(); _blockSize = blockSize; _bufferBase = new byte[_blockSize]; } _pointerToLastSafePosition = _blockSize - keepSizeAfter; } public void SetStream(java.io.InputStream stream) { _stream = stream; } public void ReleaseStream() { _stream = null; } public void Init() throws IOException { _bufferOffset = 0; _pos = 0; _streamPos = 0; _streamEndWasReached = false; ReadBlock(); } public void MovePos() throws IOException { _pos++; if (_pos > _posLimit) { int pointerToPostion = _bufferOffset + _pos; if (pointerToPostion > _pointerToLastSafePosition) MoveBlock(); ReadBlock(); } } public byte GetIndexByte(int index) { return _bufferBase[_bufferOffset + _pos + index]; } // index + limit have not to exceed _keepSizeAfter; public int GetMatchLen(int index, int distance, int limit) { if (_streamEndWasReached) if ((_pos + index) + limit > _streamPos) limit = _streamPos - (_pos + index); distance++; // Byte *pby = _buffer + (size_t)_pos + index; int pby = _bufferOffset + _pos + index; int i; for (i = 0; i < limit && _bufferBase[pby + i] == _bufferBase[pby + i - distance]; i++); return i; } public int GetNumAvailableBytes() { return _streamPos - _pos; } public void ReduceOffsets(int subValue) { _bufferOffset += subValue; _posLimit -= subValue; _pos -= subValue; _streamPos -= subValue; } }
3,595
26.242424
91
java
uiHRDC
uiHRDC-master/uiHRDC/indexes/NOPOS/II_docs/ilists.imp/6.vbyteP7zip_acabadoMerge2yN[Fork]/lzmalib/lzma.sourceCode/LZMAFARI_LIB/lzma465/Java/SevenZip/Compression/RangeCoder/BitTreeDecoder.java
package SevenZip.Compression.RangeCoder; public class BitTreeDecoder { short[] Models; int NumBitLevels; public BitTreeDecoder(int numBitLevels) { NumBitLevels = numBitLevels; Models = new short[1 << numBitLevels]; } public void Init() { Decoder.InitBitModels(Models); } public int Decode(Decoder rangeDecoder) throws java.io.IOException { int m = 1; for (int bitIndex = NumBitLevels; bitIndex != 0; bitIndex--) m = (m << 1) + rangeDecoder.DecodeBit(Models, m); return m - (1 << NumBitLevels); } public int ReverseDecode(Decoder rangeDecoder) throws java.io.IOException { int m = 1; int symbol = 0; for (int bitIndex = 0; bitIndex < NumBitLevels; bitIndex++) { int bit = rangeDecoder.DecodeBit(Models, m); m <<= 1; m += bit; symbol |= (bit << bitIndex); } return symbol; } public static int ReverseDecode(short[] Models, int startIndex, Decoder rangeDecoder, int NumBitLevels) throws java.io.IOException { int m = 1; int symbol = 0; for (int bitIndex = 0; bitIndex < NumBitLevels; bitIndex++) { int bit = rangeDecoder.DecodeBit(Models, startIndex + m); m <<= 1; m += bit; symbol |= (bit << bitIndex); } return symbol; } }
1,216
20.732143
74
java
uiHRDC
uiHRDC-master/uiHRDC/indexes/NOPOS/II_docs/ilists.imp/6.vbyteP7zip_acabadoMerge2yN[Fork]/lzmalib/lzma.sourceCode/LZMAFARI_LIB/lzma465/Java/SevenZip/Compression/RangeCoder/Decoder.java
package SevenZip.Compression.RangeCoder; import java.io.IOException; public class Decoder { static final int kTopMask = ~((1 << 24) - 1); static final int kNumBitModelTotalBits = 11; static final int kBitModelTotal = (1 << kNumBitModelTotalBits); static final int kNumMoveBits = 5; int Range; int Code; java.io.InputStream Stream; public final void SetStream(java.io.InputStream stream) { Stream = stream; } public final void ReleaseStream() { Stream = null; } public final void Init() throws IOException { Code = 0; Range = -1; for (int i = 0; i < 5; i++) Code = (Code << 8) | Stream.read(); } public final int DecodeDirectBits(int numTotalBits) throws IOException { int result = 0; for (int i = numTotalBits; i != 0; i--) { Range >>>= 1; int t = ((Code - Range) >>> 31); Code -= Range & (t - 1); result = (result << 1) | (1 - t); if ((Range & kTopMask) == 0) { Code = (Code << 8) | Stream.read(); Range <<= 8; } } return result; } public int DecodeBit(short []probs, int index) throws IOException { int prob = probs[index]; int newBound = (Range >>> kNumBitModelTotalBits) * prob; if ((Code ^ 0x80000000) < (newBound ^ 0x80000000)) { Range = newBound; probs[index] = (short)(prob + ((kBitModelTotal - prob) >>> kNumMoveBits)); if ((Range & kTopMask) == 0) { Code = (Code << 8) | Stream.read(); Range <<= 8; } return 0; } else { Range -= newBound; Code -= newBound; probs[index] = (short)(prob - ((prob) >>> kNumMoveBits)); if ((Range & kTopMask) == 0) { Code = (Code << 8) | Stream.read(); Range <<= 8; } return 1; } } public static void InitBitModels(short []probs) { for (int i = 0; i < probs.length; i++) probs[i] = (kBitModelTotal >>> 1); } }
1,828
19.550562
77
java
uiHRDC
uiHRDC-master/uiHRDC/indexes/NOPOS/II_docs/ilists.imp/6.vbyteP7zip_acabadoMerge2yN[Fork]/lzmalib/lzma.sourceCode/LZMAFARI_LIB/lzma465/Java/SevenZip/Compression/RangeCoder/BitTreeEncoder.java
package SevenZip.Compression.RangeCoder; import java.io.IOException; public class BitTreeEncoder { short[] Models; int NumBitLevels; public BitTreeEncoder(int numBitLevels) { NumBitLevels = numBitLevels; Models = new short[1 << numBitLevels]; } public void Init() { Decoder.InitBitModels(Models); } public void Encode(Encoder rangeEncoder, int symbol) throws IOException { int m = 1; for (int bitIndex = NumBitLevels; bitIndex != 0; ) { bitIndex--; int bit = (symbol >>> bitIndex) & 1; rangeEncoder.Encode(Models, m, bit); m = (m << 1) | bit; } } public void ReverseEncode(Encoder rangeEncoder, int symbol) throws IOException { int m = 1; for (int i = 0; i < NumBitLevels; i++) { int bit = symbol & 1; rangeEncoder.Encode(Models, m, bit); m = (m << 1) | bit; symbol >>= 1; } } public int GetPrice(int symbol) { int price = 0; int m = 1; for (int bitIndex = NumBitLevels; bitIndex != 0; ) { bitIndex--; int bit = (symbol >>> bitIndex) & 1; price += Encoder.GetPrice(Models[m], bit); m = (m << 1) + bit; } return price; } public int ReverseGetPrice(int symbol) { int price = 0; int m = 1; for (int i = NumBitLevels; i != 0; i--) { int bit = symbol & 1; symbol >>>= 1; price += Encoder.GetPrice(Models[m], bit); m = (m << 1) | bit; } return price; } public static int ReverseGetPrice(short[] Models, int startIndex, int NumBitLevels, int symbol) { int price = 0; int m = 1; for (int i = NumBitLevels; i != 0; i--) { int bit = symbol & 1; symbol >>>= 1; price += Encoder.GetPrice(Models[startIndex + m], bit); m = (m << 1) | bit; } return price; } public static void ReverseEncode(short[] Models, int startIndex, Encoder rangeEncoder, int NumBitLevels, int symbol) throws IOException { int m = 1; for (int i = 0; i < NumBitLevels; i++) { int bit = symbol & 1; rangeEncoder.Encode(Models, startIndex + m, bit); m = (m << 1) | bit; symbol >>= 1; } } }
2,034
19.35
79
java
uiHRDC
uiHRDC-master/uiHRDC/indexes/NOPOS/II_docs/ilists.imp/6.vbyteP7zip_acabadoMerge2yN[Fork]/lzmalib/lzma.sourceCode/LZMAFARI_LIB/lzma465/Java/SevenZip/Compression/RangeCoder/Encoder.java
package SevenZip.Compression.RangeCoder; import java.io.IOException; public class Encoder { static final int kTopMask = ~((1 << 24) - 1); static final int kNumBitModelTotalBits = 11; static final int kBitModelTotal = (1 << kNumBitModelTotalBits); static final int kNumMoveBits = 5; java.io.OutputStream Stream; long Low; int Range; int _cacheSize; int _cache; long _position; public void SetStream(java.io.OutputStream stream) { Stream = stream; } public void ReleaseStream() { Stream = null; } public void Init() { _position = 0; Low = 0; Range = -1; _cacheSize = 1; _cache = 0; } public void FlushData() throws IOException { for (int i = 0; i < 5; i++) ShiftLow(); } public void FlushStream() throws IOException { Stream.flush(); } public void ShiftLow() throws IOException { int LowHi = (int)(Low >>> 32); if (LowHi != 0 || Low < 0xFF000000L) { _position += _cacheSize; int temp = _cache; do { Stream.write(temp + LowHi); temp = 0xFF; } while(--_cacheSize != 0); _cache = (((int)Low) >>> 24); } _cacheSize++; Low = (Low & 0xFFFFFF) << 8; } public void EncodeDirectBits(int v, int numTotalBits) throws IOException { for (int i = numTotalBits - 1; i >= 0; i--) { Range >>>= 1; if (((v >>> i) & 1) == 1) Low += Range; if ((Range & Encoder.kTopMask) == 0) { Range <<= 8; ShiftLow(); } } } public long GetProcessedSizeAdd() { return _cacheSize + _position + 4; } static final int kNumMoveReducingBits = 2; public static final int kNumBitPriceShiftBits = 6; public static void InitBitModels(short []probs) { for (int i = 0; i < probs.length; i++) probs[i] = (kBitModelTotal >>> 1); } public void Encode(short []probs, int index, int symbol) throws IOException { int prob = probs[index]; int newBound = (Range >>> kNumBitModelTotalBits) * prob; if (symbol == 0) { Range = newBound; probs[index] = (short)(prob + ((kBitModelTotal - prob) >>> kNumMoveBits)); } else { Low += (newBound & 0xFFFFFFFFL); Range -= newBound; probs[index] = (short)(prob - ((prob) >>> kNumMoveBits)); } if ((Range & kTopMask) == 0) { Range <<= 8; ShiftLow(); } } private static int[] ProbPrices = new int[kBitModelTotal >>> kNumMoveReducingBits]; static { int kNumBits = (kNumBitModelTotalBits - kNumMoveReducingBits); for (int i = kNumBits - 1; i >= 0; i--) { int start = 1 << (kNumBits - i - 1); int end = 1 << (kNumBits - i); for (int j = start; j < end; j++) ProbPrices[j] = (i << kNumBitPriceShiftBits) + (((end - j) << kNumBitPriceShiftBits) >>> (kNumBits - i - 1)); } } static public int GetPrice(int Prob, int symbol) { return ProbPrices[(((Prob - symbol) ^ ((-symbol))) & (kBitModelTotal - 1)) >>> kNumMoveReducingBits]; } static public int GetPrice0(int Prob) { return ProbPrices[Prob >>> kNumMoveReducingBits]; } static public int GetPrice1(int Prob) { return ProbPrices[(kBitModelTotal - Prob) >>> kNumMoveReducingBits]; } }
3,087
19.315789
103
java
uiHRDC
uiHRDC-master/uiHRDC/indexes/NOPOS/II_docs/ilists.imp/6.vbyteP7zip_acabadoMerge2yN[Fork]/lzmalib/lzma.sourceCode/LZMAFARI_LIB/lzma465/Java/SevenZip/Compression/LZMA/Base.java
// Base.java package SevenZip.Compression.LZMA; public class Base { public static final int kNumRepDistances = 4; public static final int kNumStates = 12; public static final int StateInit() { return 0; } public static final int StateUpdateChar(int index) { if (index < 4) return 0; if (index < 10) return index - 3; return index - 6; } public static final int StateUpdateMatch(int index) { return (index < 7 ? 7 : 10); } public static final int StateUpdateRep(int index) { return (index < 7 ? 8 : 11); } public static final int StateUpdateShortRep(int index) { return (index < 7 ? 9 : 11); } public static final boolean StateIsCharState(int index) { return index < 7; } public static final int kNumPosSlotBits = 6; public static final int kDicLogSizeMin = 0; // public static final int kDicLogSizeMax = 28; // public static final int kDistTableSizeMax = kDicLogSizeMax * 2; public static final int kNumLenToPosStatesBits = 2; // it's for speed optimization public static final int kNumLenToPosStates = 1 << kNumLenToPosStatesBits; public static final int kMatchMinLen = 2; public static final int GetLenToPosState(int len) { len -= kMatchMinLen; if (len < kNumLenToPosStates) return len; return (int)(kNumLenToPosStates - 1); } public static final int kNumAlignBits = 4; public static final int kAlignTableSize = 1 << kNumAlignBits; public static final int kAlignMask = (kAlignTableSize - 1); public static final int kStartPosModelIndex = 4; public static final int kEndPosModelIndex = 14; public static final int kNumPosModels = kEndPosModelIndex - kStartPosModelIndex; public static final int kNumFullDistances = 1 << (kEndPosModelIndex / 2); public static final int kNumLitPosStatesBitsEncodingMax = 4; public static final int kNumLitContextBitsMax = 8; public static final int kNumPosStatesBitsMax = 4; public static final int kNumPosStatesMax = (1 << kNumPosStatesBitsMax); public static final int kNumPosStatesBitsEncodingMax = 4; public static final int kNumPosStatesEncodingMax = (1 << kNumPosStatesBitsEncodingMax); public static final int kNumLowLenBits = 3; public static final int kNumMidLenBits = 3; public static final int kNumHighLenBits = 8; public static final int kNumLowLenSymbols = 1 << kNumLowLenBits; public static final int kNumMidLenSymbols = 1 << kNumMidLenBits; public static final int kNumLenSymbols = kNumLowLenSymbols + kNumMidLenSymbols + (1 << kNumHighLenBits); public static final int kMatchMaxLen = kMatchMinLen + kNumLenSymbols - 1; }
2,609
28.325843
89
java
uiHRDC
uiHRDC-master/uiHRDC/indexes/NOPOS/II_docs/ilists.imp/6.vbyteP7zip_acabadoMerge2yN[Fork]/lzmalib/lzma.sourceCode/LZMAFARI_LIB/lzma465/Java/SevenZip/Compression/LZMA/Decoder.java
package SevenZip.Compression.LZMA; import SevenZip.Compression.RangeCoder.BitTreeDecoder; import SevenZip.Compression.LZMA.Base; import SevenZip.Compression.LZ.OutWindow; import java.io.IOException; public class Decoder { class LenDecoder { short[] m_Choice = new short[2]; BitTreeDecoder[] m_LowCoder = new BitTreeDecoder[Base.kNumPosStatesMax]; BitTreeDecoder[] m_MidCoder = new BitTreeDecoder[Base.kNumPosStatesMax]; BitTreeDecoder m_HighCoder = new BitTreeDecoder(Base.kNumHighLenBits); int m_NumPosStates = 0; public void Create(int numPosStates) { for (; m_NumPosStates < numPosStates; m_NumPosStates++) { m_LowCoder[m_NumPosStates] = new BitTreeDecoder(Base.kNumLowLenBits); m_MidCoder[m_NumPosStates] = new BitTreeDecoder(Base.kNumMidLenBits); } } public void Init() { SevenZip.Compression.RangeCoder.Decoder.InitBitModels(m_Choice); for (int posState = 0; posState < m_NumPosStates; posState++) { m_LowCoder[posState].Init(); m_MidCoder[posState].Init(); } m_HighCoder.Init(); } public int Decode(SevenZip.Compression.RangeCoder.Decoder rangeDecoder, int posState) throws IOException { if (rangeDecoder.DecodeBit(m_Choice, 0) == 0) return m_LowCoder[posState].Decode(rangeDecoder); int symbol = Base.kNumLowLenSymbols; if (rangeDecoder.DecodeBit(m_Choice, 1) == 0) symbol += m_MidCoder[posState].Decode(rangeDecoder); else symbol += Base.kNumMidLenSymbols + m_HighCoder.Decode(rangeDecoder); return symbol; } } class LiteralDecoder { class Decoder2 { short[] m_Decoders = new short[0x300]; public void Init() { SevenZip.Compression.RangeCoder.Decoder.InitBitModels(m_Decoders); } public byte DecodeNormal(SevenZip.Compression.RangeCoder.Decoder rangeDecoder) throws IOException { int symbol = 1; do symbol = (symbol << 1) | rangeDecoder.DecodeBit(m_Decoders, symbol); while (symbol < 0x100); return (byte)symbol; } public byte DecodeWithMatchByte(SevenZip.Compression.RangeCoder.Decoder rangeDecoder, byte matchByte) throws IOException { int symbol = 1; do { int matchBit = (matchByte >> 7) & 1; matchByte <<= 1; int bit = rangeDecoder.DecodeBit(m_Decoders, ((1 + matchBit) << 8) + symbol); symbol = (symbol << 1) | bit; if (matchBit != bit) { while (symbol < 0x100) symbol = (symbol << 1) | rangeDecoder.DecodeBit(m_Decoders, symbol); break; } } while (symbol < 0x100); return (byte)symbol; } } Decoder2[] m_Coders; int m_NumPrevBits; int m_NumPosBits; int m_PosMask; public void Create(int numPosBits, int numPrevBits) { if (m_Coders != null && m_NumPrevBits == numPrevBits && m_NumPosBits == numPosBits) return; m_NumPosBits = numPosBits; m_PosMask = (1 << numPosBits) - 1; m_NumPrevBits = numPrevBits; int numStates = 1 << (m_NumPrevBits + m_NumPosBits); m_Coders = new Decoder2[numStates]; for (int i = 0; i < numStates; i++) m_Coders[i] = new Decoder2(); } public void Init() { int numStates = 1 << (m_NumPrevBits + m_NumPosBits); for (int i = 0; i < numStates; i++) m_Coders[i].Init(); } Decoder2 GetDecoder(int pos, byte prevByte) { return m_Coders[((pos & m_PosMask) << m_NumPrevBits) + ((prevByte & 0xFF) >>> (8 - m_NumPrevBits))]; } } OutWindow m_OutWindow = new OutWindow(); SevenZip.Compression.RangeCoder.Decoder m_RangeDecoder = new SevenZip.Compression.RangeCoder.Decoder(); short[] m_IsMatchDecoders = new short[Base.kNumStates << Base.kNumPosStatesBitsMax]; short[] m_IsRepDecoders = new short[Base.kNumStates]; short[] m_IsRepG0Decoders = new short[Base.kNumStates]; short[] m_IsRepG1Decoders = new short[Base.kNumStates]; short[] m_IsRepG2Decoders = new short[Base.kNumStates]; short[] m_IsRep0LongDecoders = new short[Base.kNumStates << Base.kNumPosStatesBitsMax]; BitTreeDecoder[] m_PosSlotDecoder = new BitTreeDecoder[Base.kNumLenToPosStates]; short[] m_PosDecoders = new short[Base.kNumFullDistances - Base.kEndPosModelIndex]; BitTreeDecoder m_PosAlignDecoder = new BitTreeDecoder(Base.kNumAlignBits); LenDecoder m_LenDecoder = new LenDecoder(); LenDecoder m_RepLenDecoder = new LenDecoder(); LiteralDecoder m_LiteralDecoder = new LiteralDecoder(); int m_DictionarySize = -1; int m_DictionarySizeCheck = -1; int m_PosStateMask; public Decoder() { for (int i = 0; i < Base.kNumLenToPosStates; i++) m_PosSlotDecoder[i] = new BitTreeDecoder(Base.kNumPosSlotBits); } boolean SetDictionarySize(int dictionarySize) { if (dictionarySize < 0) return false; if (m_DictionarySize != dictionarySize) { m_DictionarySize = dictionarySize; m_DictionarySizeCheck = Math.max(m_DictionarySize, 1); m_OutWindow.Create(Math.max(m_DictionarySizeCheck, (1 << 12))); } return true; } boolean SetLcLpPb(int lc, int lp, int pb) { if (lc > Base.kNumLitContextBitsMax || lp > 4 || pb > Base.kNumPosStatesBitsMax) return false; m_LiteralDecoder.Create(lp, lc); int numPosStates = 1 << pb; m_LenDecoder.Create(numPosStates); m_RepLenDecoder.Create(numPosStates); m_PosStateMask = numPosStates - 1; return true; } void Init() throws IOException { m_OutWindow.Init(false); SevenZip.Compression.RangeCoder.Decoder.InitBitModels(m_IsMatchDecoders); SevenZip.Compression.RangeCoder.Decoder.InitBitModels(m_IsRep0LongDecoders); SevenZip.Compression.RangeCoder.Decoder.InitBitModels(m_IsRepDecoders); SevenZip.Compression.RangeCoder.Decoder.InitBitModels(m_IsRepG0Decoders); SevenZip.Compression.RangeCoder.Decoder.InitBitModels(m_IsRepG1Decoders); SevenZip.Compression.RangeCoder.Decoder.InitBitModels(m_IsRepG2Decoders); SevenZip.Compression.RangeCoder.Decoder.InitBitModels(m_PosDecoders); m_LiteralDecoder.Init(); int i; for (i = 0; i < Base.kNumLenToPosStates; i++) m_PosSlotDecoder[i].Init(); m_LenDecoder.Init(); m_RepLenDecoder.Init(); m_PosAlignDecoder.Init(); m_RangeDecoder.Init(); } public boolean Code(java.io.InputStream inStream, java.io.OutputStream outStream, long outSize) throws IOException { m_RangeDecoder.SetStream(inStream); m_OutWindow.SetStream(outStream); Init(); int state = Base.StateInit(); int rep0 = 0, rep1 = 0, rep2 = 0, rep3 = 0; long nowPos64 = 0; byte prevByte = 0; while (outSize < 0 || nowPos64 < outSize) { int posState = (int)nowPos64 & m_PosStateMask; if (m_RangeDecoder.DecodeBit(m_IsMatchDecoders, (state << Base.kNumPosStatesBitsMax) + posState) == 0) { LiteralDecoder.Decoder2 decoder2 = m_LiteralDecoder.GetDecoder((int)nowPos64, prevByte); if (!Base.StateIsCharState(state)) prevByte = decoder2.DecodeWithMatchByte(m_RangeDecoder, m_OutWindow.GetByte(rep0)); else prevByte = decoder2.DecodeNormal(m_RangeDecoder); m_OutWindow.PutByte(prevByte); state = Base.StateUpdateChar(state); nowPos64++; } else { int len; if (m_RangeDecoder.DecodeBit(m_IsRepDecoders, state) == 1) { len = 0; if (m_RangeDecoder.DecodeBit(m_IsRepG0Decoders, state) == 0) { if (m_RangeDecoder.DecodeBit(m_IsRep0LongDecoders, (state << Base.kNumPosStatesBitsMax) + posState) == 0) { state = Base.StateUpdateShortRep(state); len = 1; } } else { int distance; if (m_RangeDecoder.DecodeBit(m_IsRepG1Decoders, state) == 0) distance = rep1; else { if (m_RangeDecoder.DecodeBit(m_IsRepG2Decoders, state) == 0) distance = rep2; else { distance = rep3; rep3 = rep2; } rep2 = rep1; } rep1 = rep0; rep0 = distance; } if (len == 0) { len = m_RepLenDecoder.Decode(m_RangeDecoder, posState) + Base.kMatchMinLen; state = Base.StateUpdateRep(state); } } else { rep3 = rep2; rep2 = rep1; rep1 = rep0; len = Base.kMatchMinLen + m_LenDecoder.Decode(m_RangeDecoder, posState); state = Base.StateUpdateMatch(state); int posSlot = m_PosSlotDecoder[Base.GetLenToPosState(len)].Decode(m_RangeDecoder); if (posSlot >= Base.kStartPosModelIndex) { int numDirectBits = (posSlot >> 1) - 1; rep0 = ((2 | (posSlot & 1)) << numDirectBits); if (posSlot < Base.kEndPosModelIndex) rep0 += BitTreeDecoder.ReverseDecode(m_PosDecoders, rep0 - posSlot - 1, m_RangeDecoder, numDirectBits); else { rep0 += (m_RangeDecoder.DecodeDirectBits( numDirectBits - Base.kNumAlignBits) << Base.kNumAlignBits); rep0 += m_PosAlignDecoder.ReverseDecode(m_RangeDecoder); if (rep0 < 0) { if (rep0 == -1) break; return false; } } } else rep0 = posSlot; } if (rep0 >= nowPos64 || rep0 >= m_DictionarySizeCheck) { // m_OutWindow.Flush(); return false; } m_OutWindow.CopyBlock(rep0, len); nowPos64 += len; prevByte = m_OutWindow.GetByte(0); } } m_OutWindow.Flush(); m_OutWindow.ReleaseStream(); m_RangeDecoder.ReleaseStream(); return true; } public boolean SetDecoderProperties(byte[] properties) { if (properties.length < 5) return false; int val = properties[0] & 0xFF; int lc = val % 9; int remainder = val / 9; int lp = remainder % 5; int pb = remainder / 5; int dictionarySize = 0; for (int i = 0; i < 4; i++) dictionarySize += ((int)(properties[1 + i]) & 0xFF) << (i * 8); if (!SetLcLpPb(lc, lp, pb)) return false; return SetDictionarySize(dictionarySize); } }
9,677
28.327273
123
java
uiHRDC
uiHRDC-master/uiHRDC/indexes/NOPOS/II_docs/ilists.imp/6.vbyteP7zip_acabadoMerge2yN[Fork]/lzmalib/lzma.sourceCode/LZMAFARI_LIB/lzma465/Java/SevenZip/Compression/LZMA/Encoder.java
package SevenZip.Compression.LZMA; import SevenZip.Compression.RangeCoder.BitTreeEncoder; import SevenZip.Compression.LZMA.Base; import SevenZip.Compression.LZ.BinTree; import SevenZip.ICodeProgress; import java.io.IOException; public class Encoder { public static final int EMatchFinderTypeBT2 = 0; public static final int EMatchFinderTypeBT4 = 1; static final int kIfinityPrice = 0xFFFFFFF; static byte[] g_FastPos = new byte[1 << 11]; static { int kFastSlots = 22; int c = 2; g_FastPos[0] = 0; g_FastPos[1] = 1; for (int slotFast = 2; slotFast < kFastSlots; slotFast++) { int k = (1 << ((slotFast >> 1) - 1)); for (int j = 0; j < k; j++, c++) g_FastPos[c] = (byte)slotFast; } } static int GetPosSlot(int pos) { if (pos < (1 << 11)) return g_FastPos[pos]; if (pos < (1 << 21)) return (g_FastPos[pos >> 10] + 20); return (g_FastPos[pos >> 20] + 40); } static int GetPosSlot2(int pos) { if (pos < (1 << 17)) return (g_FastPos[pos >> 6] + 12); if (pos < (1 << 27)) return (g_FastPos[pos >> 16] + 32); return (g_FastPos[pos >> 26] + 52); } int _state = Base.StateInit(); byte _previousByte; int[] _repDistances = new int[Base.kNumRepDistances]; void BaseInit() { _state = Base.StateInit(); _previousByte = 0; for (int i = 0; i < Base.kNumRepDistances; i++) _repDistances[i] = 0; } static final int kDefaultDictionaryLogSize = 22; static final int kNumFastBytesDefault = 0x20; class LiteralEncoder { class Encoder2 { short[] m_Encoders = new short[0x300]; public void Init() { SevenZip.Compression.RangeCoder.Encoder.InitBitModels(m_Encoders); } public void Encode(SevenZip.Compression.RangeCoder.Encoder rangeEncoder, byte symbol) throws IOException { int context = 1; for (int i = 7; i >= 0; i--) { int bit = ((symbol >> i) & 1); rangeEncoder.Encode(m_Encoders, context, bit); context = (context << 1) | bit; } } public void EncodeMatched(SevenZip.Compression.RangeCoder.Encoder rangeEncoder, byte matchByte, byte symbol) throws IOException { int context = 1; boolean same = true; for (int i = 7; i >= 0; i--) { int bit = ((symbol >> i) & 1); int state = context; if (same) { int matchBit = ((matchByte >> i) & 1); state += ((1 + matchBit) << 8); same = (matchBit == bit); } rangeEncoder.Encode(m_Encoders, state, bit); context = (context << 1) | bit; } } public int GetPrice(boolean matchMode, byte matchByte, byte symbol) { int price = 0; int context = 1; int i = 7; if (matchMode) { for (; i >= 0; i--) { int matchBit = (matchByte >> i) & 1; int bit = (symbol >> i) & 1; price += SevenZip.Compression.RangeCoder.Encoder.GetPrice(m_Encoders[((1 + matchBit) << 8) + context], bit); context = (context << 1) | bit; if (matchBit != bit) { i--; break; } } } for (; i >= 0; i--) { int bit = (symbol >> i) & 1; price += SevenZip.Compression.RangeCoder.Encoder.GetPrice(m_Encoders[context], bit); context = (context << 1) | bit; } return price; } } Encoder2[] m_Coders; int m_NumPrevBits; int m_NumPosBits; int m_PosMask; public void Create(int numPosBits, int numPrevBits) { if (m_Coders != null && m_NumPrevBits == numPrevBits && m_NumPosBits == numPosBits) return; m_NumPosBits = numPosBits; m_PosMask = (1 << numPosBits) - 1; m_NumPrevBits = numPrevBits; int numStates = 1 << (m_NumPrevBits + m_NumPosBits); m_Coders = new Encoder2[numStates]; for (int i = 0; i < numStates; i++) m_Coders[i] = new Encoder2(); } public void Init() { int numStates = 1 << (m_NumPrevBits + m_NumPosBits); for (int i = 0; i < numStates; i++) m_Coders[i].Init(); } public Encoder2 GetSubCoder(int pos, byte prevByte) { return m_Coders[((pos & m_PosMask) << m_NumPrevBits) + ((prevByte & 0xFF) >>> (8 - m_NumPrevBits))]; } } class LenEncoder { short[] _choice = new short[2]; BitTreeEncoder[] _lowCoder = new BitTreeEncoder[Base.kNumPosStatesEncodingMax]; BitTreeEncoder[] _midCoder = new BitTreeEncoder[Base.kNumPosStatesEncodingMax]; BitTreeEncoder _highCoder = new BitTreeEncoder(Base.kNumHighLenBits); public LenEncoder() { for (int posState = 0; posState < Base.kNumPosStatesEncodingMax; posState++) { _lowCoder[posState] = new BitTreeEncoder(Base.kNumLowLenBits); _midCoder[posState] = new BitTreeEncoder(Base.kNumMidLenBits); } } public void Init(int numPosStates) { SevenZip.Compression.RangeCoder.Encoder.InitBitModels(_choice); for (int posState = 0; posState < numPosStates; posState++) { _lowCoder[posState].Init(); _midCoder[posState].Init(); } _highCoder.Init(); } public void Encode(SevenZip.Compression.RangeCoder.Encoder rangeEncoder, int symbol, int posState) throws IOException { if (symbol < Base.kNumLowLenSymbols) { rangeEncoder.Encode(_choice, 0, 0); _lowCoder[posState].Encode(rangeEncoder, symbol); } else { symbol -= Base.kNumLowLenSymbols; rangeEncoder.Encode(_choice, 0, 1); if (symbol < Base.kNumMidLenSymbols) { rangeEncoder.Encode(_choice, 1, 0); _midCoder[posState].Encode(rangeEncoder, symbol); } else { rangeEncoder.Encode(_choice, 1, 1); _highCoder.Encode(rangeEncoder, symbol - Base.kNumMidLenSymbols); } } } public void SetPrices(int posState, int numSymbols, int[] prices, int st) { int a0 = SevenZip.Compression.RangeCoder.Encoder.GetPrice0(_choice[0]); int a1 = SevenZip.Compression.RangeCoder.Encoder.GetPrice1(_choice[0]); int b0 = a1 + SevenZip.Compression.RangeCoder.Encoder.GetPrice0(_choice[1]); int b1 = a1 + SevenZip.Compression.RangeCoder.Encoder.GetPrice1(_choice[1]); int i = 0; for (i = 0; i < Base.kNumLowLenSymbols; i++) { if (i >= numSymbols) return; prices[st + i] = a0 + _lowCoder[posState].GetPrice(i); } for (; i < Base.kNumLowLenSymbols + Base.kNumMidLenSymbols; i++) { if (i >= numSymbols) return; prices[st + i] = b0 + _midCoder[posState].GetPrice(i - Base.kNumLowLenSymbols); } for (; i < numSymbols; i++) prices[st + i] = b1 + _highCoder.GetPrice(i - Base.kNumLowLenSymbols - Base.kNumMidLenSymbols); } }; public static final int kNumLenSpecSymbols = Base.kNumLowLenSymbols + Base.kNumMidLenSymbols; class LenPriceTableEncoder extends LenEncoder { int[] _prices = new int[Base.kNumLenSymbols<<Base.kNumPosStatesBitsEncodingMax]; int _tableSize; int[] _counters = new int[Base.kNumPosStatesEncodingMax]; public void SetTableSize(int tableSize) { _tableSize = tableSize; } public int GetPrice(int symbol, int posState) { return _prices[posState * Base.kNumLenSymbols + symbol]; } void UpdateTable(int posState) { SetPrices(posState, _tableSize, _prices, posState * Base.kNumLenSymbols); _counters[posState] = _tableSize; } public void UpdateTables(int numPosStates) { for (int posState = 0; posState < numPosStates; posState++) UpdateTable(posState); } public void Encode(SevenZip.Compression.RangeCoder.Encoder rangeEncoder, int symbol, int posState) throws IOException { super.Encode(rangeEncoder, symbol, posState); if (--_counters[posState] == 0) UpdateTable(posState); } } static final int kNumOpts = 1 << 12; class Optimal { public int State; public boolean Prev1IsChar; public boolean Prev2; public int PosPrev2; public int BackPrev2; public int Price; public int PosPrev; public int BackPrev; public int Backs0; public int Backs1; public int Backs2; public int Backs3; public void MakeAsChar() { BackPrev = -1; Prev1IsChar = false; } public void MakeAsShortRep() { BackPrev = 0; ; Prev1IsChar = false; } public boolean IsShortRep() { return (BackPrev == 0); } }; Optimal[] _optimum = new Optimal[kNumOpts]; SevenZip.Compression.LZ.BinTree _matchFinder = null; SevenZip.Compression.RangeCoder.Encoder _rangeEncoder = new SevenZip.Compression.RangeCoder.Encoder(); short[] _isMatch = new short[Base.kNumStates<<Base.kNumPosStatesBitsMax]; short[] _isRep = new short[Base.kNumStates]; short[] _isRepG0 = new short[Base.kNumStates]; short[] _isRepG1 = new short[Base.kNumStates]; short[] _isRepG2 = new short[Base.kNumStates]; short[] _isRep0Long = new short[Base.kNumStates<<Base.kNumPosStatesBitsMax]; BitTreeEncoder[] _posSlotEncoder = new BitTreeEncoder[Base.kNumLenToPosStates]; // kNumPosSlotBits short[] _posEncoders = new short[Base.kNumFullDistances-Base.kEndPosModelIndex]; BitTreeEncoder _posAlignEncoder = new BitTreeEncoder(Base.kNumAlignBits); LenPriceTableEncoder _lenEncoder = new LenPriceTableEncoder(); LenPriceTableEncoder _repMatchLenEncoder = new LenPriceTableEncoder(); LiteralEncoder _literalEncoder = new LiteralEncoder(); int[] _matchDistances = new int[Base.kMatchMaxLen*2+2]; int _numFastBytes = kNumFastBytesDefault; int _longestMatchLength; int _numDistancePairs; int _additionalOffset; int _optimumEndIndex; int _optimumCurrentIndex; boolean _longestMatchWasFound; int[] _posSlotPrices = new int[1<<(Base.kNumPosSlotBits+Base.kNumLenToPosStatesBits)]; int[] _distancesPrices = new int[Base.kNumFullDistances<<Base.kNumLenToPosStatesBits]; int[] _alignPrices = new int[Base.kAlignTableSize]; int _alignPriceCount; int _distTableSize = (kDefaultDictionaryLogSize * 2); int _posStateBits = 2; int _posStateMask = (4 - 1); int _numLiteralPosStateBits = 0; int _numLiteralContextBits = 3; int _dictionarySize = (1 << kDefaultDictionaryLogSize); int _dictionarySizePrev = -1; int _numFastBytesPrev = -1; long nowPos64; boolean _finished; java.io.InputStream _inStream; int _matchFinderType = EMatchFinderTypeBT4; boolean _writeEndMark = false; boolean _needReleaseMFStream = false; void Create() { if (_matchFinder == null) { SevenZip.Compression.LZ.BinTree bt = new SevenZip.Compression.LZ.BinTree(); int numHashBytes = 4; if (_matchFinderType == EMatchFinderTypeBT2) numHashBytes = 2; bt.SetType(numHashBytes); _matchFinder = bt; } _literalEncoder.Create(_numLiteralPosStateBits, _numLiteralContextBits); if (_dictionarySize == _dictionarySizePrev && _numFastBytesPrev == _numFastBytes) return; _matchFinder.Create(_dictionarySize, kNumOpts, _numFastBytes, Base.kMatchMaxLen + 1); _dictionarySizePrev = _dictionarySize; _numFastBytesPrev = _numFastBytes; } public Encoder() { for (int i = 0; i < kNumOpts; i++) _optimum[i] = new Optimal(); for (int i = 0; i < Base.kNumLenToPosStates; i++) _posSlotEncoder[i] = new BitTreeEncoder(Base.kNumPosSlotBits); } void SetWriteEndMarkerMode(boolean writeEndMarker) { _writeEndMark = writeEndMarker; } void Init() { BaseInit(); _rangeEncoder.Init(); SevenZip.Compression.RangeCoder.Encoder.InitBitModels(_isMatch); SevenZip.Compression.RangeCoder.Encoder.InitBitModels(_isRep0Long); SevenZip.Compression.RangeCoder.Encoder.InitBitModels(_isRep); SevenZip.Compression.RangeCoder.Encoder.InitBitModels(_isRepG0); SevenZip.Compression.RangeCoder.Encoder.InitBitModels(_isRepG1); SevenZip.Compression.RangeCoder.Encoder.InitBitModels(_isRepG2); SevenZip.Compression.RangeCoder.Encoder.InitBitModels(_posEncoders); _literalEncoder.Init(); for (int i = 0; i < Base.kNumLenToPosStates; i++) _posSlotEncoder[i].Init(); _lenEncoder.Init(1 << _posStateBits); _repMatchLenEncoder.Init(1 << _posStateBits); _posAlignEncoder.Init(); _longestMatchWasFound = false; _optimumEndIndex = 0; _optimumCurrentIndex = 0; _additionalOffset = 0; } int ReadMatchDistances() throws java.io.IOException { int lenRes = 0; _numDistancePairs = _matchFinder.GetMatches(_matchDistances); if (_numDistancePairs > 0) { lenRes = _matchDistances[_numDistancePairs - 2]; if (lenRes == _numFastBytes) lenRes += _matchFinder.GetMatchLen((int)lenRes - 1, _matchDistances[_numDistancePairs - 1], Base.kMatchMaxLen - lenRes); } _additionalOffset++; return lenRes; } void MovePos(int num) throws java.io.IOException { if (num > 0) { _matchFinder.Skip(num); _additionalOffset += num; } } int GetRepLen1Price(int state, int posState) { return SevenZip.Compression.RangeCoder.Encoder.GetPrice0(_isRepG0[state]) + SevenZip.Compression.RangeCoder.Encoder.GetPrice0(_isRep0Long[(state << Base.kNumPosStatesBitsMax) + posState]); } int GetPureRepPrice(int repIndex, int state, int posState) { int price; if (repIndex == 0) { price = SevenZip.Compression.RangeCoder.Encoder.GetPrice0(_isRepG0[state]); price += SevenZip.Compression.RangeCoder.Encoder.GetPrice1(_isRep0Long[(state << Base.kNumPosStatesBitsMax) + posState]); } else { price = SevenZip.Compression.RangeCoder.Encoder.GetPrice1(_isRepG0[state]); if (repIndex == 1) price += SevenZip.Compression.RangeCoder.Encoder.GetPrice0(_isRepG1[state]); else { price += SevenZip.Compression.RangeCoder.Encoder.GetPrice1(_isRepG1[state]); price += SevenZip.Compression.RangeCoder.Encoder.GetPrice(_isRepG2[state], repIndex - 2); } } return price; } int GetRepPrice(int repIndex, int len, int state, int posState) { int price = _repMatchLenEncoder.GetPrice(len - Base.kMatchMinLen, posState); return price + GetPureRepPrice(repIndex, state, posState); } int GetPosLenPrice(int pos, int len, int posState) { int price; int lenToPosState = Base.GetLenToPosState(len); if (pos < Base.kNumFullDistances) price = _distancesPrices[(lenToPosState * Base.kNumFullDistances) + pos]; else price = _posSlotPrices[(lenToPosState << Base.kNumPosSlotBits) + GetPosSlot2(pos)] + _alignPrices[pos & Base.kAlignMask]; return price + _lenEncoder.GetPrice(len - Base.kMatchMinLen, posState); } int Backward(int cur) { _optimumEndIndex = cur; int posMem = _optimum[cur].PosPrev; int backMem = _optimum[cur].BackPrev; do { if (_optimum[cur].Prev1IsChar) { _optimum[posMem].MakeAsChar(); _optimum[posMem].PosPrev = posMem - 1; if (_optimum[cur].Prev2) { _optimum[posMem - 1].Prev1IsChar = false; _optimum[posMem - 1].PosPrev = _optimum[cur].PosPrev2; _optimum[posMem - 1].BackPrev = _optimum[cur].BackPrev2; } } int posPrev = posMem; int backCur = backMem; backMem = _optimum[posPrev].BackPrev; posMem = _optimum[posPrev].PosPrev; _optimum[posPrev].BackPrev = backCur; _optimum[posPrev].PosPrev = cur; cur = posPrev; } while (cur > 0); backRes = _optimum[0].BackPrev; _optimumCurrentIndex = _optimum[0].PosPrev; return _optimumCurrentIndex; } int[] reps = new int[Base.kNumRepDistances]; int[] repLens = new int[Base.kNumRepDistances]; int backRes; int GetOptimum(int position) throws IOException { if (_optimumEndIndex != _optimumCurrentIndex) { int lenRes = _optimum[_optimumCurrentIndex].PosPrev - _optimumCurrentIndex; backRes = _optimum[_optimumCurrentIndex].BackPrev; _optimumCurrentIndex = _optimum[_optimumCurrentIndex].PosPrev; return lenRes; } _optimumCurrentIndex = _optimumEndIndex = 0; int lenMain, numDistancePairs; if (!_longestMatchWasFound) { lenMain = ReadMatchDistances(); } else { lenMain = _longestMatchLength; _longestMatchWasFound = false; } numDistancePairs = _numDistancePairs; int numAvailableBytes = _matchFinder.GetNumAvailableBytes() + 1; if (numAvailableBytes < 2) { backRes = -1; return 1; } if (numAvailableBytes > Base.kMatchMaxLen) numAvailableBytes = Base.kMatchMaxLen; int repMaxIndex = 0; int i; for (i = 0; i < Base.kNumRepDistances; i++) { reps[i] = _repDistances[i]; repLens[i] = _matchFinder.GetMatchLen(0 - 1, reps[i], Base.kMatchMaxLen); if (repLens[i] > repLens[repMaxIndex]) repMaxIndex = i; } if (repLens[repMaxIndex] >= _numFastBytes) { backRes = repMaxIndex; int lenRes = repLens[repMaxIndex]; MovePos(lenRes - 1); return lenRes; } if (lenMain >= _numFastBytes) { backRes = _matchDistances[numDistancePairs - 1] + Base.kNumRepDistances; MovePos(lenMain - 1); return lenMain; } byte currentByte = _matchFinder.GetIndexByte(0 - 1); byte matchByte = _matchFinder.GetIndexByte(0 - _repDistances[0] - 1 - 1); if (lenMain < 2 && currentByte != matchByte && repLens[repMaxIndex] < 2) { backRes = -1; return 1; } _optimum[0].State = _state; int posState = (position & _posStateMask); _optimum[1].Price = SevenZip.Compression.RangeCoder.Encoder.GetPrice0(_isMatch[(_state << Base.kNumPosStatesBitsMax) + posState]) + _literalEncoder.GetSubCoder(position, _previousByte).GetPrice(!Base.StateIsCharState(_state), matchByte, currentByte); _optimum[1].MakeAsChar(); int matchPrice = SevenZip.Compression.RangeCoder.Encoder.GetPrice1(_isMatch[(_state << Base.kNumPosStatesBitsMax) + posState]); int repMatchPrice = matchPrice + SevenZip.Compression.RangeCoder.Encoder.GetPrice1(_isRep[_state]); if (matchByte == currentByte) { int shortRepPrice = repMatchPrice + GetRepLen1Price(_state, posState); if (shortRepPrice < _optimum[1].Price) { _optimum[1].Price = shortRepPrice; _optimum[1].MakeAsShortRep(); } } int lenEnd = ((lenMain >= repLens[repMaxIndex]) ? lenMain : repLens[repMaxIndex]); if (lenEnd < 2) { backRes = _optimum[1].BackPrev; return 1; } _optimum[1].PosPrev = 0; _optimum[0].Backs0 = reps[0]; _optimum[0].Backs1 = reps[1]; _optimum[0].Backs2 = reps[2]; _optimum[0].Backs3 = reps[3]; int len = lenEnd; do _optimum[len--].Price = kIfinityPrice; while (len >= 2); for (i = 0; i < Base.kNumRepDistances; i++) { int repLen = repLens[i]; if (repLen < 2) continue; int price = repMatchPrice + GetPureRepPrice(i, _state, posState); do { int curAndLenPrice = price + _repMatchLenEncoder.GetPrice(repLen - 2, posState); Optimal optimum = _optimum[repLen]; if (curAndLenPrice < optimum.Price) { optimum.Price = curAndLenPrice; optimum.PosPrev = 0; optimum.BackPrev = i; optimum.Prev1IsChar = false; } } while (--repLen >= 2); } int normalMatchPrice = matchPrice + SevenZip.Compression.RangeCoder.Encoder.GetPrice0(_isRep[_state]); len = ((repLens[0] >= 2) ? repLens[0] + 1 : 2); if (len <= lenMain) { int offs = 0; while (len > _matchDistances[offs]) offs += 2; for (; ; len++) { int distance = _matchDistances[offs + 1]; int curAndLenPrice = normalMatchPrice + GetPosLenPrice(distance, len, posState); Optimal optimum = _optimum[len]; if (curAndLenPrice < optimum.Price) { optimum.Price = curAndLenPrice; optimum.PosPrev = 0; optimum.BackPrev = distance + Base.kNumRepDistances; optimum.Prev1IsChar = false; } if (len == _matchDistances[offs]) { offs += 2; if (offs == numDistancePairs) break; } } } int cur = 0; while (true) { cur++; if (cur == lenEnd) return Backward(cur); int newLen = ReadMatchDistances(); numDistancePairs = _numDistancePairs; if (newLen >= _numFastBytes) { _longestMatchLength = newLen; _longestMatchWasFound = true; return Backward(cur); } position++; int posPrev = _optimum[cur].PosPrev; int state; if (_optimum[cur].Prev1IsChar) { posPrev--; if (_optimum[cur].Prev2) { state = _optimum[_optimum[cur].PosPrev2].State; if (_optimum[cur].BackPrev2 < Base.kNumRepDistances) state = Base.StateUpdateRep(state); else state = Base.StateUpdateMatch(state); } else state = _optimum[posPrev].State; state = Base.StateUpdateChar(state); } else state = _optimum[posPrev].State; if (posPrev == cur - 1) { if (_optimum[cur].IsShortRep()) state = Base.StateUpdateShortRep(state); else state = Base.StateUpdateChar(state); } else { int pos; if (_optimum[cur].Prev1IsChar && _optimum[cur].Prev2) { posPrev = _optimum[cur].PosPrev2; pos = _optimum[cur].BackPrev2; state = Base.StateUpdateRep(state); } else { pos = _optimum[cur].BackPrev; if (pos < Base.kNumRepDistances) state = Base.StateUpdateRep(state); else state = Base.StateUpdateMatch(state); } Optimal opt = _optimum[posPrev]; if (pos < Base.kNumRepDistances) { if (pos == 0) { reps[0] = opt.Backs0; reps[1] = opt.Backs1; reps[2] = opt.Backs2; reps[3] = opt.Backs3; } else if (pos == 1) { reps[0] = opt.Backs1; reps[1] = opt.Backs0; reps[2] = opt.Backs2; reps[3] = opt.Backs3; } else if (pos == 2) { reps[0] = opt.Backs2; reps[1] = opt.Backs0; reps[2] = opt.Backs1; reps[3] = opt.Backs3; } else { reps[0] = opt.Backs3; reps[1] = opt.Backs0; reps[2] = opt.Backs1; reps[3] = opt.Backs2; } } else { reps[0] = (pos - Base.kNumRepDistances); reps[1] = opt.Backs0; reps[2] = opt.Backs1; reps[3] = opt.Backs2; } } _optimum[cur].State = state; _optimum[cur].Backs0 = reps[0]; _optimum[cur].Backs1 = reps[1]; _optimum[cur].Backs2 = reps[2]; _optimum[cur].Backs3 = reps[3]; int curPrice = _optimum[cur].Price; currentByte = _matchFinder.GetIndexByte(0 - 1); matchByte = _matchFinder.GetIndexByte(0 - reps[0] - 1 - 1); posState = (position & _posStateMask); int curAnd1Price = curPrice + SevenZip.Compression.RangeCoder.Encoder.GetPrice0(_isMatch[(state << Base.kNumPosStatesBitsMax) + posState]) + _literalEncoder.GetSubCoder(position, _matchFinder.GetIndexByte(0 - 2)). GetPrice(!Base.StateIsCharState(state), matchByte, currentByte); Optimal nextOptimum = _optimum[cur + 1]; boolean nextIsChar = false; if (curAnd1Price < nextOptimum.Price) { nextOptimum.Price = curAnd1Price; nextOptimum.PosPrev = cur; nextOptimum.MakeAsChar(); nextIsChar = true; } matchPrice = curPrice + SevenZip.Compression.RangeCoder.Encoder.GetPrice1(_isMatch[(state << Base.kNumPosStatesBitsMax) + posState]); repMatchPrice = matchPrice + SevenZip.Compression.RangeCoder.Encoder.GetPrice1(_isRep[state]); if (matchByte == currentByte && !(nextOptimum.PosPrev < cur && nextOptimum.BackPrev == 0)) { int shortRepPrice = repMatchPrice + GetRepLen1Price(state, posState); if (shortRepPrice <= nextOptimum.Price) { nextOptimum.Price = shortRepPrice; nextOptimum.PosPrev = cur; nextOptimum.MakeAsShortRep(); nextIsChar = true; } } int numAvailableBytesFull = _matchFinder.GetNumAvailableBytes() + 1; numAvailableBytesFull = Math.min(kNumOpts - 1 - cur, numAvailableBytesFull); numAvailableBytes = numAvailableBytesFull; if (numAvailableBytes < 2) continue; if (numAvailableBytes > _numFastBytes) numAvailableBytes = _numFastBytes; if (!nextIsChar && matchByte != currentByte) { // try Literal + rep0 int t = Math.min(numAvailableBytesFull - 1, _numFastBytes); int lenTest2 = _matchFinder.GetMatchLen(0, reps[0], t); if (lenTest2 >= 2) { int state2 = Base.StateUpdateChar(state); int posStateNext = (position + 1) & _posStateMask; int nextRepMatchPrice = curAnd1Price + SevenZip.Compression.RangeCoder.Encoder.GetPrice1(_isMatch[(state2 << Base.kNumPosStatesBitsMax) + posStateNext]) + SevenZip.Compression.RangeCoder.Encoder.GetPrice1(_isRep[state2]); { int offset = cur + 1 + lenTest2; while (lenEnd < offset) _optimum[++lenEnd].Price = kIfinityPrice; int curAndLenPrice = nextRepMatchPrice + GetRepPrice( 0, lenTest2, state2, posStateNext); Optimal optimum = _optimum[offset]; if (curAndLenPrice < optimum.Price) { optimum.Price = curAndLenPrice; optimum.PosPrev = cur + 1; optimum.BackPrev = 0; optimum.Prev1IsChar = true; optimum.Prev2 = false; } } } } int startLen = 2; // speed optimization for (int repIndex = 0; repIndex < Base.kNumRepDistances; repIndex++) { int lenTest = _matchFinder.GetMatchLen(0 - 1, reps[repIndex], numAvailableBytes); if (lenTest < 2) continue; int lenTestTemp = lenTest; do { while (lenEnd < cur + lenTest) _optimum[++lenEnd].Price = kIfinityPrice; int curAndLenPrice = repMatchPrice + GetRepPrice(repIndex, lenTest, state, posState); Optimal optimum = _optimum[cur + lenTest]; if (curAndLenPrice < optimum.Price) { optimum.Price = curAndLenPrice; optimum.PosPrev = cur; optimum.BackPrev = repIndex; optimum.Prev1IsChar = false; } } while (--lenTest >= 2); lenTest = lenTestTemp; if (repIndex == 0) startLen = lenTest + 1; // if (_maxMode) if (lenTest < numAvailableBytesFull) { int t = Math.min(numAvailableBytesFull - 1 - lenTest, _numFastBytes); int lenTest2 = _matchFinder.GetMatchLen(lenTest, reps[repIndex], t); if (lenTest2 >= 2) { int state2 = Base.StateUpdateRep(state); int posStateNext = (position + lenTest) & _posStateMask; int curAndLenCharPrice = repMatchPrice + GetRepPrice(repIndex, lenTest, state, posState) + SevenZip.Compression.RangeCoder.Encoder.GetPrice0(_isMatch[(state2 << Base.kNumPosStatesBitsMax) + posStateNext]) + _literalEncoder.GetSubCoder(position + lenTest, _matchFinder.GetIndexByte(lenTest - 1 - 1)).GetPrice(true, _matchFinder.GetIndexByte(lenTest - 1 - (reps[repIndex] + 1)), _matchFinder.GetIndexByte(lenTest - 1)); state2 = Base.StateUpdateChar(state2); posStateNext = (position + lenTest + 1) & _posStateMask; int nextMatchPrice = curAndLenCharPrice + SevenZip.Compression.RangeCoder.Encoder.GetPrice1(_isMatch[(state2 << Base.kNumPosStatesBitsMax) + posStateNext]); int nextRepMatchPrice = nextMatchPrice + SevenZip.Compression.RangeCoder.Encoder.GetPrice1(_isRep[state2]); // for(; lenTest2 >= 2; lenTest2--) { int offset = lenTest + 1 + lenTest2; while (lenEnd < cur + offset) _optimum[++lenEnd].Price = kIfinityPrice; int curAndLenPrice = nextRepMatchPrice + GetRepPrice(0, lenTest2, state2, posStateNext); Optimal optimum = _optimum[cur + offset]; if (curAndLenPrice < optimum.Price) { optimum.Price = curAndLenPrice; optimum.PosPrev = cur + lenTest + 1; optimum.BackPrev = 0; optimum.Prev1IsChar = true; optimum.Prev2 = true; optimum.PosPrev2 = cur; optimum.BackPrev2 = repIndex; } } } } } if (newLen > numAvailableBytes) { newLen = numAvailableBytes; for (numDistancePairs = 0; newLen > _matchDistances[numDistancePairs]; numDistancePairs += 2) ; _matchDistances[numDistancePairs] = newLen; numDistancePairs += 2; } if (newLen >= startLen) { normalMatchPrice = matchPrice + SevenZip.Compression.RangeCoder.Encoder.GetPrice0(_isRep[state]); while (lenEnd < cur + newLen) _optimum[++lenEnd].Price = kIfinityPrice; int offs = 0; while (startLen > _matchDistances[offs]) offs += 2; for (int lenTest = startLen; ; lenTest++) { int curBack = _matchDistances[offs + 1]; int curAndLenPrice = normalMatchPrice + GetPosLenPrice(curBack, lenTest, posState); Optimal optimum = _optimum[cur + lenTest]; if (curAndLenPrice < optimum.Price) { optimum.Price = curAndLenPrice; optimum.PosPrev = cur; optimum.BackPrev = curBack + Base.kNumRepDistances; optimum.Prev1IsChar = false; } if (lenTest == _matchDistances[offs]) { if (lenTest < numAvailableBytesFull) { int t = Math.min(numAvailableBytesFull - 1 - lenTest, _numFastBytes); int lenTest2 = _matchFinder.GetMatchLen(lenTest, curBack, t); if (lenTest2 >= 2) { int state2 = Base.StateUpdateMatch(state); int posStateNext = (position + lenTest) & _posStateMask; int curAndLenCharPrice = curAndLenPrice + SevenZip.Compression.RangeCoder.Encoder.GetPrice0(_isMatch[(state2 << Base.kNumPosStatesBitsMax) + posStateNext]) + _literalEncoder.GetSubCoder(position + lenTest, _matchFinder.GetIndexByte(lenTest - 1 - 1)). GetPrice(true, _matchFinder.GetIndexByte(lenTest - (curBack + 1) - 1), _matchFinder.GetIndexByte(lenTest - 1)); state2 = Base.StateUpdateChar(state2); posStateNext = (position + lenTest + 1) & _posStateMask; int nextMatchPrice = curAndLenCharPrice + SevenZip.Compression.RangeCoder.Encoder.GetPrice1(_isMatch[(state2 << Base.kNumPosStatesBitsMax) + posStateNext]); int nextRepMatchPrice = nextMatchPrice + SevenZip.Compression.RangeCoder.Encoder.GetPrice1(_isRep[state2]); int offset = lenTest + 1 + lenTest2; while (lenEnd < cur + offset) _optimum[++lenEnd].Price = kIfinityPrice; curAndLenPrice = nextRepMatchPrice + GetRepPrice(0, lenTest2, state2, posStateNext); optimum = _optimum[cur + offset]; if (curAndLenPrice < optimum.Price) { optimum.Price = curAndLenPrice; optimum.PosPrev = cur + lenTest + 1; optimum.BackPrev = 0; optimum.Prev1IsChar = true; optimum.Prev2 = true; optimum.PosPrev2 = cur; optimum.BackPrev2 = curBack + Base.kNumRepDistances; } } } offs += 2; if (offs == numDistancePairs) break; } } } } } boolean ChangePair(int smallDist, int bigDist) { int kDif = 7; return (smallDist < (1 << (32 - kDif)) && bigDist >= (smallDist << kDif)); } void WriteEndMarker(int posState) throws IOException { if (!_writeEndMark) return; _rangeEncoder.Encode(_isMatch, (_state << Base.kNumPosStatesBitsMax) + posState, 1); _rangeEncoder.Encode(_isRep, _state, 0); _state = Base.StateUpdateMatch(_state); int len = Base.kMatchMinLen; _lenEncoder.Encode(_rangeEncoder, len - Base.kMatchMinLen, posState); int posSlot = (1 << Base.kNumPosSlotBits) - 1; int lenToPosState = Base.GetLenToPosState(len); _posSlotEncoder[lenToPosState].Encode(_rangeEncoder, posSlot); int footerBits = 30; int posReduced = (1 << footerBits) - 1; _rangeEncoder.EncodeDirectBits(posReduced >> Base.kNumAlignBits, footerBits - Base.kNumAlignBits); _posAlignEncoder.ReverseEncode(_rangeEncoder, posReduced & Base.kAlignMask); } void Flush(int nowPos) throws IOException { ReleaseMFStream(); WriteEndMarker(nowPos & _posStateMask); _rangeEncoder.FlushData(); _rangeEncoder.FlushStream(); } public void CodeOneBlock(long[] inSize, long[] outSize, boolean[] finished) throws IOException { inSize[0] = 0; outSize[0] = 0; finished[0] = true; if (_inStream != null) { _matchFinder.SetStream(_inStream); _matchFinder.Init(); _needReleaseMFStream = true; _inStream = null; } if (_finished) return; _finished = true; long progressPosValuePrev = nowPos64; if (nowPos64 == 0) { if (_matchFinder.GetNumAvailableBytes() == 0) { Flush((int)nowPos64); return; } ReadMatchDistances(); int posState = (int)(nowPos64) & _posStateMask; _rangeEncoder.Encode(_isMatch, (_state << Base.kNumPosStatesBitsMax) + posState, 0); _state = Base.StateUpdateChar(_state); byte curByte = _matchFinder.GetIndexByte(0 - _additionalOffset); _literalEncoder.GetSubCoder((int)(nowPos64), _previousByte).Encode(_rangeEncoder, curByte); _previousByte = curByte; _additionalOffset--; nowPos64++; } if (_matchFinder.GetNumAvailableBytes() == 0) { Flush((int)nowPos64); return; } while (true) { int len = GetOptimum((int)nowPos64); int pos = backRes; int posState = ((int)nowPos64) & _posStateMask; int complexState = (_state << Base.kNumPosStatesBitsMax) + posState; if (len == 1 && pos == -1) { _rangeEncoder.Encode(_isMatch, complexState, 0); byte curByte = _matchFinder.GetIndexByte((int)(0 - _additionalOffset)); LiteralEncoder.Encoder2 subCoder = _literalEncoder.GetSubCoder((int)nowPos64, _previousByte); if (!Base.StateIsCharState(_state)) { byte matchByte = _matchFinder.GetIndexByte((int)(0 - _repDistances[0] - 1 - _additionalOffset)); subCoder.EncodeMatched(_rangeEncoder, matchByte, curByte); } else subCoder.Encode(_rangeEncoder, curByte); _previousByte = curByte; _state = Base.StateUpdateChar(_state); } else { _rangeEncoder.Encode(_isMatch, complexState, 1); if (pos < Base.kNumRepDistances) { _rangeEncoder.Encode(_isRep, _state, 1); if (pos == 0) { _rangeEncoder.Encode(_isRepG0, _state, 0); if (len == 1) _rangeEncoder.Encode(_isRep0Long, complexState, 0); else _rangeEncoder.Encode(_isRep0Long, complexState, 1); } else { _rangeEncoder.Encode(_isRepG0, _state, 1); if (pos == 1) _rangeEncoder.Encode(_isRepG1, _state, 0); else { _rangeEncoder.Encode(_isRepG1, _state, 1); _rangeEncoder.Encode(_isRepG2, _state, pos - 2); } } if (len == 1) _state = Base.StateUpdateShortRep(_state); else { _repMatchLenEncoder.Encode(_rangeEncoder, len - Base.kMatchMinLen, posState); _state = Base.StateUpdateRep(_state); } int distance = _repDistances[pos]; if (pos != 0) { for (int i = pos; i >= 1; i--) _repDistances[i] = _repDistances[i - 1]; _repDistances[0] = distance; } } else { _rangeEncoder.Encode(_isRep, _state, 0); _state = Base.StateUpdateMatch(_state); _lenEncoder.Encode(_rangeEncoder, len - Base.kMatchMinLen, posState); pos -= Base.kNumRepDistances; int posSlot = GetPosSlot(pos); int lenToPosState = Base.GetLenToPosState(len); _posSlotEncoder[lenToPosState].Encode(_rangeEncoder, posSlot); if (posSlot >= Base.kStartPosModelIndex) { int footerBits = (int)((posSlot >> 1) - 1); int baseVal = ((2 | (posSlot & 1)) << footerBits); int posReduced = pos - baseVal; if (posSlot < Base.kEndPosModelIndex) BitTreeEncoder.ReverseEncode(_posEncoders, baseVal - posSlot - 1, _rangeEncoder, footerBits, posReduced); else { _rangeEncoder.EncodeDirectBits(posReduced >> Base.kNumAlignBits, footerBits - Base.kNumAlignBits); _posAlignEncoder.ReverseEncode(_rangeEncoder, posReduced & Base.kAlignMask); _alignPriceCount++; } } int distance = pos; for (int i = Base.kNumRepDistances - 1; i >= 1; i--) _repDistances[i] = _repDistances[i - 1]; _repDistances[0] = distance; _matchPriceCount++; } _previousByte = _matchFinder.GetIndexByte(len - 1 - _additionalOffset); } _additionalOffset -= len; nowPos64 += len; if (_additionalOffset == 0) { // if (!_fastMode) if (_matchPriceCount >= (1 << 7)) FillDistancesPrices(); if (_alignPriceCount >= Base.kAlignTableSize) FillAlignPrices(); inSize[0] = nowPos64; outSize[0] = _rangeEncoder.GetProcessedSizeAdd(); if (_matchFinder.GetNumAvailableBytes() == 0) { Flush((int)nowPos64); return; } if (nowPos64 - progressPosValuePrev >= (1 << 12)) { _finished = false; finished[0] = false; return; } } } } void ReleaseMFStream() { if (_matchFinder != null && _needReleaseMFStream) { _matchFinder.ReleaseStream(); _needReleaseMFStream = false; } } void SetOutStream(java.io.OutputStream outStream) { _rangeEncoder.SetStream(outStream); } void ReleaseOutStream() { _rangeEncoder.ReleaseStream(); } void ReleaseStreams() { ReleaseMFStream(); ReleaseOutStream(); } void SetStreams(java.io.InputStream inStream, java.io.OutputStream outStream, long inSize, long outSize) { _inStream = inStream; _finished = false; Create(); SetOutStream(outStream); Init(); // if (!_fastMode) { FillDistancesPrices(); FillAlignPrices(); } _lenEncoder.SetTableSize(_numFastBytes + 1 - Base.kMatchMinLen); _lenEncoder.UpdateTables(1 << _posStateBits); _repMatchLenEncoder.SetTableSize(_numFastBytes + 1 - Base.kMatchMinLen); _repMatchLenEncoder.UpdateTables(1 << _posStateBits); nowPos64 = 0; } long[] processedInSize = new long[1]; long[] processedOutSize = new long[1]; boolean[] finished = new boolean[1]; public void Code(java.io.InputStream inStream, java.io.OutputStream outStream, long inSize, long outSize, ICodeProgress progress) throws IOException { _needReleaseMFStream = false; try { SetStreams(inStream, outStream, inSize, outSize); while (true) { CodeOneBlock(processedInSize, processedOutSize, finished); if (finished[0]) return; if (progress != null) { progress.SetProgress(processedInSize[0], processedOutSize[0]); } } } finally { ReleaseStreams(); } } public static final int kPropSize = 5; byte[] properties = new byte[kPropSize]; public void WriteCoderProperties(java.io.OutputStream outStream) throws IOException { properties[0] = (byte)((_posStateBits * 5 + _numLiteralPosStateBits) * 9 + _numLiteralContextBits); for (int i = 0; i < 4; i++) properties[1 + i] = (byte)(_dictionarySize >> (8 * i)); outStream.write(properties, 0, kPropSize); } int[] tempPrices = new int[Base.kNumFullDistances]; int _matchPriceCount; void FillDistancesPrices() { for (int i = Base.kStartPosModelIndex; i < Base.kNumFullDistances; i++) { int posSlot = GetPosSlot(i); int footerBits = (int)((posSlot >> 1) - 1); int baseVal = ((2 | (posSlot & 1)) << footerBits); tempPrices[i] = BitTreeEncoder.ReverseGetPrice(_posEncoders, baseVal - posSlot - 1, footerBits, i - baseVal); } for (int lenToPosState = 0; lenToPosState < Base.kNumLenToPosStates; lenToPosState++) { int posSlot; BitTreeEncoder encoder = _posSlotEncoder[lenToPosState]; int st = (lenToPosState << Base.kNumPosSlotBits); for (posSlot = 0; posSlot < _distTableSize; posSlot++) _posSlotPrices[st + posSlot] = encoder.GetPrice(posSlot); for (posSlot = Base.kEndPosModelIndex; posSlot < _distTableSize; posSlot++) _posSlotPrices[st + posSlot] += ((((posSlot >> 1) - 1) - Base.kNumAlignBits) << SevenZip.Compression.RangeCoder.Encoder.kNumBitPriceShiftBits); int st2 = lenToPosState * Base.kNumFullDistances; int i; for (i = 0; i < Base.kStartPosModelIndex; i++) _distancesPrices[st2 + i] = _posSlotPrices[st + i]; for (; i < Base.kNumFullDistances; i++) _distancesPrices[st2 + i] = _posSlotPrices[st + GetPosSlot(i)] + tempPrices[i]; } _matchPriceCount = 0; } void FillAlignPrices() { for (int i = 0; i < Base.kAlignTableSize; i++) _alignPrices[i] = _posAlignEncoder.ReverseGetPrice(i); _alignPriceCount = 0; } public boolean SetAlgorithm(int algorithm) { /* _fastMode = (algorithm == 0); _maxMode = (algorithm >= 2); */ return true; } public boolean SetDictionarySize(int dictionarySize) { int kDicLogSizeMaxCompress = 29; if (dictionarySize < (1 << Base.kDicLogSizeMin) || dictionarySize > (1 << kDicLogSizeMaxCompress)) return false; _dictionarySize = dictionarySize; int dicLogSize; for (dicLogSize = 0; dictionarySize > (1 << dicLogSize); dicLogSize++) ; _distTableSize = dicLogSize * 2; return true; } public boolean SetNumFastBytes(int numFastBytes) { if (numFastBytes < 5 || numFastBytes > Base.kMatchMaxLen) return false; _numFastBytes = numFastBytes; return true; } public boolean SetMatchFinder(int matchFinderIndex) { if (matchFinderIndex < 0 || matchFinderIndex > 2) return false; int matchFinderIndexPrev = _matchFinderType; _matchFinderType = matchFinderIndex; if (_matchFinder != null && matchFinderIndexPrev != _matchFinderType) { _dictionarySizePrev = -1; _matchFinder = null; } return true; } public boolean SetLcLpPb(int lc, int lp, int pb) { if ( lp < 0 || lp > Base.kNumLitPosStatesBitsEncodingMax || lc < 0 || lc > Base.kNumLitContextBitsMax || pb < 0 || pb > Base.kNumPosStatesBitsEncodingMax) return false; _numLiteralPosStateBits = lp; _numLiteralContextBits = lc; _posStateBits = pb; _posStateMask = ((1) << _posStateBits) - 1; return true; } public void SetEndMarkerMode(boolean endMarkerMode) { _writeEndMark = endMarkerMode; } }
40,845
27.825688
164
java
uiHRDC
uiHRDC-master/uiHRDC/indexes/POS/II_docs/ilists.gap.imp/6.vbyteP7zip_acabadoMerge2yN[Fork.log_enabled]/lzmalib/lzma.sourceCode/LZMAFARI_LIB/lzma465/Java/SevenZip/CRC.java
// SevenZip/CRC.java package SevenZip; public class CRC { static public int[] Table = new int[256]; static { for (int i = 0; i < 256; i++) { int r = i; for (int j = 0; j < 8; j++) if ((r & 1) != 0) r = (r >>> 1) ^ 0xEDB88320; else r >>>= 1; Table[i] = r; } } int _value = -1; public void Init() { _value = -1; } public void Update(byte[] data, int offset, int size) { for (int i = 0; i < size; i++) _value = Table[(_value ^ data[offset + i]) & 0xFF] ^ (_value >>> 8); } public void Update(byte[] data) { int size = data.length; for (int i = 0; i < size; i++) _value = Table[(_value ^ data[i]) & 0xFF] ^ (_value >>> 8); } public void UpdateByte(int b) { _value = Table[(_value ^ b) & 0xFF] ^ (_value >>> 8); } public int GetDigest() { return _value ^ (-1); } }
847
15
71
java
uiHRDC
uiHRDC-master/uiHRDC/indexes/POS/II_docs/ilists.gap.imp/6.vbyteP7zip_acabadoMerge2yN[Fork.log_enabled]/lzmalib/lzma.sourceCode/LZMAFARI_LIB/lzma465/Java/SevenZip/ICodeProgress.java
package SevenZip; public interface ICodeProgress { public void SetProgress(long inSize, long outSize); }
107
14.428571
52
java
uiHRDC
uiHRDC-master/uiHRDC/indexes/POS/II_docs/ilists.gap.imp/6.vbyteP7zip_acabadoMerge2yN[Fork.log_enabled]/lzmalib/lzma.sourceCode/LZMAFARI_LIB/lzma465/Java/SevenZip/LzmaAlone.java
package SevenZip; public class LzmaAlone { static public class CommandLine { public static final int kEncode = 0; public static final int kDecode = 1; public static final int kBenchmak = 2; public int Command = -1; public int NumBenchmarkPasses = 10; public int DictionarySize = 1 << 23; public boolean DictionarySizeIsDefined = false; public int Lc = 3; public int Lp = 0; public int Pb = 2; public int Fb = 128; public boolean FbIsDefined = false; public boolean Eos = false; public int Algorithm = 2; public int MatchFinder = 1; public String InFile; public String OutFile; boolean ParseSwitch(String s) { if (s.startsWith("d")) { DictionarySize = 1 << Integer.parseInt(s.substring(1)); DictionarySizeIsDefined = true; } else if (s.startsWith("fb")) { Fb = Integer.parseInt(s.substring(2)); FbIsDefined = true; } else if (s.startsWith("a")) Algorithm = Integer.parseInt(s.substring(1)); else if (s.startsWith("lc")) Lc = Integer.parseInt(s.substring(2)); else if (s.startsWith("lp")) Lp = Integer.parseInt(s.substring(2)); else if (s.startsWith("pb")) Pb = Integer.parseInt(s.substring(2)); else if (s.startsWith("eos")) Eos = true; else if (s.startsWith("mf")) { String mfs = s.substring(2); if (mfs.equals("bt2")) MatchFinder = 0; else if (mfs.equals("bt4")) MatchFinder = 1; else if (mfs.equals("bt4b")) MatchFinder = 2; else return false; } else return false; return true; } public boolean Parse(String[] args) throws Exception { int pos = 0; boolean switchMode = true; for (int i = 0; i < args.length; i++) { String s = args[i]; if (s.length() == 0) return false; if (switchMode) { if (s.compareTo("--") == 0) { switchMode = false; continue; } if (s.charAt(0) == '-') { String sw = s.substring(1).toLowerCase(); if (sw.length() == 0) return false; try { if (!ParseSwitch(sw)) return false; } catch (NumberFormatException e) { return false; } continue; } } if (pos == 0) { if (s.equalsIgnoreCase("e")) Command = kEncode; else if (s.equalsIgnoreCase("d")) Command = kDecode; else if (s.equalsIgnoreCase("b")) Command = kBenchmak; else return false; } else if(pos == 1) { if (Command == kBenchmak) { try { NumBenchmarkPasses = Integer.parseInt(s); if (NumBenchmarkPasses < 1) return false; } catch (NumberFormatException e) { return false; } } else InFile = s; } else if(pos == 2) OutFile = s; else return false; pos++; continue; } return true; } } static void PrintHelp() { System.out.println( "\nUsage: LZMA <e|d> [<switches>...] inputFile outputFile\n" + " e: encode file\n" + " d: decode file\n" + " b: Benchmark\n" + "<Switches>\n" + // " -a{N}: set compression mode - [0, 1], default: 1 (max)\n" + " -d{N}: set dictionary - [0,28], default: 23 (8MB)\n" + " -fb{N}: set number of fast bytes - [5, 273], default: 128\n" + " -lc{N}: set number of literal context bits - [0, 8], default: 3\n" + " -lp{N}: set number of literal pos bits - [0, 4], default: 0\n" + " -pb{N}: set number of pos bits - [0, 4], default: 2\n" + " -mf{MF_ID}: set Match Finder: [bt2, bt4], default: bt4\n" + " -eos: write End Of Stream marker\n" ); } public static void main(String[] args) throws Exception { System.out.println("\nLZMA (Java) 4.61 2008-11-23\n"); if (args.length < 1) { PrintHelp(); return; } CommandLine params = new CommandLine(); if (!params.Parse(args)) { System.out.println("\nIncorrect command"); return; } if (params.Command == CommandLine.kBenchmak) { int dictionary = (1 << 21); if (params.DictionarySizeIsDefined) dictionary = params.DictionarySize; if (params.MatchFinder > 1) throw new Exception("Unsupported match finder"); SevenZip.LzmaBench.LzmaBenchmark(params.NumBenchmarkPasses, dictionary); } else if (params.Command == CommandLine.kEncode || params.Command == CommandLine.kDecode) { java.io.File inFile = new java.io.File(params.InFile); java.io.File outFile = new java.io.File(params.OutFile); java.io.BufferedInputStream inStream = new java.io.BufferedInputStream(new java.io.FileInputStream(inFile)); java.io.BufferedOutputStream outStream = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outFile)); boolean eos = false; if (params.Eos) eos = true; if (params.Command == CommandLine.kEncode) { SevenZip.Compression.LZMA.Encoder encoder = new SevenZip.Compression.LZMA.Encoder(); if (!encoder.SetAlgorithm(params.Algorithm)) throw new Exception("Incorrect compression mode"); if (!encoder.SetDictionarySize(params.DictionarySize)) throw new Exception("Incorrect dictionary size"); if (!encoder.SetNumFastBytes(params.Fb)) throw new Exception("Incorrect -fb value"); if (!encoder.SetMatchFinder(params.MatchFinder)) throw new Exception("Incorrect -mf value"); if (!encoder.SetLcLpPb(params.Lc, params.Lp, params.Pb)) throw new Exception("Incorrect -lc or -lp or -pb value"); encoder.SetEndMarkerMode(eos); encoder.WriteCoderProperties(outStream); long fileSize; if (eos) fileSize = -1; else fileSize = inFile.length(); for (int i = 0; i < 8; i++) outStream.write((int)(fileSize >>> (8 * i)) & 0xFF); encoder.Code(inStream, outStream, -1, -1, null); } else { int propertiesSize = 5; byte[] properties = new byte[propertiesSize]; if (inStream.read(properties, 0, propertiesSize) != propertiesSize) throw new Exception("input .lzma file is too short"); SevenZip.Compression.LZMA.Decoder decoder = new SevenZip.Compression.LZMA.Decoder(); if (!decoder.SetDecoderProperties(properties)) throw new Exception("Incorrect stream properties"); long outSize = 0; for (int i = 0; i < 8; i++) { int v = inStream.read(); if (v < 0) throw new Exception("Can't read stream size"); outSize |= ((long)v) << (8 * i); } if (!decoder.Code(inStream, outStream, outSize)) throw new Exception("Error in data stream"); } outStream.flush(); outStream.close(); inStream.close(); } else throw new Exception("Incorrect command"); return; } }
6,695
25.362205
116
java
uiHRDC
uiHRDC-master/uiHRDC/indexes/POS/II_docs/ilists.gap.imp/6.vbyteP7zip_acabadoMerge2yN[Fork.log_enabled]/lzmalib/lzma.sourceCode/LZMAFARI_LIB/lzma465/Java/SevenZip/LzmaBench.java
package SevenZip; import java.io.ByteArrayOutputStream; import java.io.ByteArrayInputStream; import java.io.IOException; public class LzmaBench { static final int kAdditionalSize = (1 << 21); static final int kCompressedAdditionalSize = (1 << 10); static class CRandomGenerator { int A1; int A2; public CRandomGenerator() { Init(); } public void Init() { A1 = 362436069; A2 = 521288629; } public int GetRnd() { return ((A1 = 36969 * (A1 & 0xffff) + (A1 >>> 16)) << 16) ^ ((A2 = 18000 * (A2 & 0xffff) + (A2 >>> 16))); } }; static class CBitRandomGenerator { CRandomGenerator RG = new CRandomGenerator(); int Value; int NumBits; public void Init() { Value = 0; NumBits = 0; } public int GetRnd(int numBits) { int result; if (NumBits > numBits) { result = Value & ((1 << numBits) - 1); Value >>>= numBits; NumBits -= numBits; return result; } numBits -= NumBits; result = (Value << numBits); Value = RG.GetRnd(); result |= Value & (((int)1 << numBits) - 1); Value >>>= numBits; NumBits = 32 - numBits; return result; } }; static class CBenchRandomGenerator { CBitRandomGenerator RG = new CBitRandomGenerator(); int Pos; int Rep0; public int BufferSize; public byte[] Buffer = null; public CBenchRandomGenerator() { } public void Set(int bufferSize) { Buffer = new byte[bufferSize]; Pos = 0; BufferSize = bufferSize; } int GetRndBit() { return RG.GetRnd(1); } int GetLogRandBits(int numBits) { int len = RG.GetRnd(numBits); return RG.GetRnd((int)len); } int GetOffset() { if (GetRndBit() == 0) return GetLogRandBits(4); return (GetLogRandBits(4) << 10) | RG.GetRnd(10); } int GetLen1() { return RG.GetRnd(1 + (int)RG.GetRnd(2)); } int GetLen2() { return RG.GetRnd(2 + (int)RG.GetRnd(2)); } public void Generate() { RG.Init(); Rep0 = 1; while (Pos < BufferSize) { if (GetRndBit() == 0 || Pos < 1) Buffer[Pos++] = (byte)(RG.GetRnd(8)); else { int len; if (RG.GetRnd(3) == 0) len = 1 + GetLen1(); else { do Rep0 = GetOffset(); while (Rep0 >= Pos); Rep0++; len = 2 + GetLen2(); } for (int i = 0; i < len && Pos < BufferSize; i++, Pos++) Buffer[Pos] = Buffer[Pos - Rep0]; } } } }; static class CrcOutStream extends java.io.OutputStream { public CRC CRC = new CRC(); public void Init() { CRC.Init(); } public int GetDigest() { return CRC.GetDigest(); } public void write(byte[] b) { CRC.Update(b); } public void write(byte[] b, int off, int len) { CRC.Update(b, off, len); } public void write(int b) { CRC.UpdateByte(b); } }; static class MyOutputStream extends java.io.OutputStream { byte[] _buffer; int _size; int _pos; public MyOutputStream(byte[] buffer) { _buffer = buffer; _size = _buffer.length; } public void reset() { _pos = 0; } public void write(int b) throws IOException { if (_pos >= _size) throw new IOException("Error"); _buffer[_pos++] = (byte)b; } public int size() { return _pos; } }; static class MyInputStream extends java.io.InputStream { byte[] _buffer; int _size; int _pos; public MyInputStream(byte[] buffer, int size) { _buffer = buffer; _size = size; } public void reset() { _pos = 0; } public int read() { if (_pos >= _size) return -1; return _buffer[_pos++] & 0xFF; } }; static class CProgressInfo implements ICodeProgress { public long ApprovedStart; public long InSize; public long Time; public void Init() { InSize = 0; } public void SetProgress(long inSize, long outSize) { if (inSize >= ApprovedStart && InSize == 0) { Time = System.currentTimeMillis(); InSize = inSize; } } } static final int kSubBits = 8; static int GetLogSize(int size) { for (int i = kSubBits; i < 32; i++) for (int j = 0; j < (1 << kSubBits); j++) if (size <= ((1) << i) + (j << (i - kSubBits))) return (i << kSubBits) + j; return (32 << kSubBits); } static long MyMultDiv64(long value, long elapsedTime) { long freq = 1000; // ms long elTime = elapsedTime; while (freq > 1000000) { freq >>>= 1; elTime >>>= 1; } if (elTime == 0) elTime = 1; return value * freq / elTime; } static long GetCompressRating(int dictionarySize, long elapsedTime, long size) { long t = GetLogSize(dictionarySize) - (18 << kSubBits); long numCommandsForOne = 1060 + ((t * t * 10) >> (2 * kSubBits)); long numCommands = (long)(size) * numCommandsForOne; return MyMultDiv64(numCommands, elapsedTime); } static long GetDecompressRating(long elapsedTime, long outSize, long inSize) { long numCommands = inSize * 220 + outSize * 20; return MyMultDiv64(numCommands, elapsedTime); } static long GetTotalRating( int dictionarySize, long elapsedTimeEn, long sizeEn, long elapsedTimeDe, long inSizeDe, long outSizeDe) { return (GetCompressRating(dictionarySize, elapsedTimeEn, sizeEn) + GetDecompressRating(elapsedTimeDe, inSizeDe, outSizeDe)) / 2; } static void PrintValue(long v) { String s = ""; s += v; for (int i = 0; i + s.length() < 6; i++) System.out.print(" "); System.out.print(s); } static void PrintRating(long rating) { PrintValue(rating / 1000000); System.out.print(" MIPS"); } static void PrintResults( int dictionarySize, long elapsedTime, long size, boolean decompressMode, long secondSize) { long speed = MyMultDiv64(size, elapsedTime); PrintValue(speed / 1024); System.out.print(" KB/s "); long rating; if (decompressMode) rating = GetDecompressRating(elapsedTime, size, secondSize); else rating = GetCompressRating(dictionarySize, elapsedTime, size); PrintRating(rating); } static public int LzmaBenchmark(int numIterations, int dictionarySize) throws Exception { if (numIterations <= 0) return 0; if (dictionarySize < (1 << 18)) { System.out.println("\nError: dictionary size for benchmark must be >= 18 (256 KB)"); return 1; } System.out.print("\n Compressing Decompressing\n\n"); SevenZip.Compression.LZMA.Encoder encoder = new SevenZip.Compression.LZMA.Encoder(); SevenZip.Compression.LZMA.Decoder decoder = new SevenZip.Compression.LZMA.Decoder(); if (!encoder.SetDictionarySize(dictionarySize)) throw new Exception("Incorrect dictionary size"); int kBufferSize = dictionarySize + kAdditionalSize; int kCompressedBufferSize = (kBufferSize / 2) + kCompressedAdditionalSize; ByteArrayOutputStream propStream = new ByteArrayOutputStream(); encoder.WriteCoderProperties(propStream); byte[] propArray = propStream.toByteArray(); decoder.SetDecoderProperties(propArray); CBenchRandomGenerator rg = new CBenchRandomGenerator(); rg.Set(kBufferSize); rg.Generate(); CRC crc = new CRC(); crc.Init(); crc.Update(rg.Buffer, 0, rg.BufferSize); CProgressInfo progressInfo = new CProgressInfo(); progressInfo.ApprovedStart = dictionarySize; long totalBenchSize = 0; long totalEncodeTime = 0; long totalDecodeTime = 0; long totalCompressedSize = 0; MyInputStream inStream = new MyInputStream(rg.Buffer, rg.BufferSize); byte[] compressedBuffer = new byte[kCompressedBufferSize]; MyOutputStream compressedStream = new MyOutputStream(compressedBuffer); CrcOutStream crcOutStream = new CrcOutStream(); MyInputStream inputCompressedStream = null; int compressedSize = 0; for (int i = 0; i < numIterations; i++) { progressInfo.Init(); inStream.reset(); compressedStream.reset(); encoder.Code(inStream, compressedStream, -1, -1, progressInfo); long encodeTime = System.currentTimeMillis() - progressInfo.Time; if (i == 0) { compressedSize = compressedStream.size(); inputCompressedStream = new MyInputStream(compressedBuffer, compressedSize); } else if (compressedSize != compressedStream.size()) throw (new Exception("Encoding error")); if (progressInfo.InSize == 0) throw (new Exception("Internal ERROR 1282")); long decodeTime = 0; for (int j = 0; j < 2; j++) { inputCompressedStream.reset(); crcOutStream.Init(); long outSize = kBufferSize; long startTime = System.currentTimeMillis(); if (!decoder.Code(inputCompressedStream, crcOutStream, outSize)) throw (new Exception("Decoding Error"));; decodeTime = System.currentTimeMillis() - startTime; if (crcOutStream.GetDigest() != crc.GetDigest()) throw (new Exception("CRC Error")); } long benchSize = kBufferSize - (long)progressInfo.InSize; PrintResults(dictionarySize, encodeTime, benchSize, false, 0); System.out.print(" "); PrintResults(dictionarySize, decodeTime, kBufferSize, true, compressedSize); System.out.println(); totalBenchSize += benchSize; totalEncodeTime += encodeTime; totalDecodeTime += decodeTime; totalCompressedSize += compressedSize; } System.out.println("---------------------------------------------------"); PrintResults(dictionarySize, totalEncodeTime, totalBenchSize, false, 0); System.out.print(" "); PrintResults(dictionarySize, totalDecodeTime, kBufferSize * (long)numIterations, true, totalCompressedSize); System.out.println(" Average"); return 0; } }
9,483
23.132316
88
java
uiHRDC
uiHRDC-master/uiHRDC/indexes/POS/II_docs/ilists.gap.imp/6.vbyteP7zip_acabadoMerge2yN[Fork.log_enabled]/lzmalib/lzma.sourceCode/LZMAFARI_LIB/lzma465/Java/SevenZip/Compression/LZ/OutWindow.java
// LZ.OutWindow package SevenZip.Compression.LZ; import java.io.IOException; public class OutWindow { byte[] _buffer; int _pos; int _windowSize = 0; int _streamPos; java.io.OutputStream _stream; public void Create(int windowSize) { if (_buffer == null || _windowSize != windowSize) _buffer = new byte[windowSize]; _windowSize = windowSize; _pos = 0; _streamPos = 0; } public void SetStream(java.io.OutputStream stream) throws IOException { ReleaseStream(); _stream = stream; } public void ReleaseStream() throws IOException { Flush(); _stream = null; } public void Init(boolean solid) { if (!solid) { _streamPos = 0; _pos = 0; } } public void Flush() throws IOException { int size = _pos - _streamPos; if (size == 0) return; _stream.write(_buffer, _streamPos, size); if (_pos >= _windowSize) _pos = 0; _streamPos = _pos; } public void CopyBlock(int distance, int len) throws IOException { int pos = _pos - distance - 1; if (pos < 0) pos += _windowSize; for (; len != 0; len--) { if (pos >= _windowSize) pos = 0; _buffer[_pos++] = _buffer[pos++]; if (_pos >= _windowSize) Flush(); } } public void PutByte(byte b) throws IOException { _buffer[_pos++] = b; if (_pos >= _windowSize) Flush(); } public byte GetByte(int distance) { int pos = _pos - distance - 1; if (pos < 0) pos += _windowSize; return _buffer[pos]; } }
1,456
15.94186
70
java
uiHRDC
uiHRDC-master/uiHRDC/indexes/POS/II_docs/ilists.gap.imp/6.vbyteP7zip_acabadoMerge2yN[Fork.log_enabled]/lzmalib/lzma.sourceCode/LZMAFARI_LIB/lzma465/Java/SevenZip/Compression/LZ/BinTree.java
// LZ.BinTree package SevenZip.Compression.LZ; import java.io.IOException; public class BinTree extends InWindow { int _cyclicBufferPos; int _cyclicBufferSize = 0; int _matchMaxLen; int[] _son; int[] _hash; int _cutValue = 0xFF; int _hashMask; int _hashSizeSum = 0; boolean HASH_ARRAY = true; static final int kHash2Size = 1 << 10; static final int kHash3Size = 1 << 16; static final int kBT2HashSize = 1 << 16; static final int kStartMaxLen = 1; static final int kHash3Offset = kHash2Size; static final int kEmptyHashValue = 0; static final int kMaxValForNormalize = (1 << 30) - 1; int kNumHashDirectBytes = 0; int kMinMatchCheck = 4; int kFixHashSize = kHash2Size + kHash3Size; public void SetType(int numHashBytes) { HASH_ARRAY = (numHashBytes > 2); if (HASH_ARRAY) { kNumHashDirectBytes = 0; kMinMatchCheck = 4; kFixHashSize = kHash2Size + kHash3Size; } else { kNumHashDirectBytes = 2; kMinMatchCheck = 2 + 1; kFixHashSize = 0; } } public void Init() throws IOException { super.Init(); for (int i = 0; i < _hashSizeSum; i++) _hash[i] = kEmptyHashValue; _cyclicBufferPos = 0; ReduceOffsets(-1); } public void MovePos() throws IOException { if (++_cyclicBufferPos >= _cyclicBufferSize) _cyclicBufferPos = 0; super.MovePos(); if (_pos == kMaxValForNormalize) Normalize(); } public boolean Create(int historySize, int keepAddBufferBefore, int matchMaxLen, int keepAddBufferAfter) { if (historySize > kMaxValForNormalize - 256) return false; _cutValue = 16 + (matchMaxLen >> 1); int windowReservSize = (historySize + keepAddBufferBefore + matchMaxLen + keepAddBufferAfter) / 2 + 256; super.Create(historySize + keepAddBufferBefore, matchMaxLen + keepAddBufferAfter, windowReservSize); _matchMaxLen = matchMaxLen; int cyclicBufferSize = historySize + 1; if (_cyclicBufferSize != cyclicBufferSize) _son = new int[(_cyclicBufferSize = cyclicBufferSize) * 2]; int hs = kBT2HashSize; if (HASH_ARRAY) { hs = historySize - 1; hs |= (hs >> 1); hs |= (hs >> 2); hs |= (hs >> 4); hs |= (hs >> 8); hs >>= 1; hs |= 0xFFFF; if (hs > (1 << 24)) hs >>= 1; _hashMask = hs; hs++; hs += kFixHashSize; } if (hs != _hashSizeSum) _hash = new int [_hashSizeSum = hs]; return true; } public int GetMatches(int[] distances) throws IOException { int lenLimit; if (_pos + _matchMaxLen <= _streamPos) lenLimit = _matchMaxLen; else { lenLimit = _streamPos - _pos; if (lenLimit < kMinMatchCheck) { MovePos(); return 0; } } int offset = 0; int matchMinPos = (_pos > _cyclicBufferSize) ? (_pos - _cyclicBufferSize) : 0; int cur = _bufferOffset + _pos; int maxLen = kStartMaxLen; // to avoid items for len < hashSize; int hashValue, hash2Value = 0, hash3Value = 0; if (HASH_ARRAY) { int temp = CrcTable[_bufferBase[cur] & 0xFF] ^ (_bufferBase[cur + 1] & 0xFF); hash2Value = temp & (kHash2Size - 1); temp ^= ((int)(_bufferBase[cur + 2] & 0xFF) << 8); hash3Value = temp & (kHash3Size - 1); hashValue = (temp ^ (CrcTable[_bufferBase[cur + 3] & 0xFF] << 5)) & _hashMask; } else hashValue = ((_bufferBase[cur] & 0xFF) ^ ((int)(_bufferBase[cur + 1] & 0xFF) << 8)); int curMatch = _hash[kFixHashSize + hashValue]; if (HASH_ARRAY) { int curMatch2 = _hash[hash2Value]; int curMatch3 = _hash[kHash3Offset + hash3Value]; _hash[hash2Value] = _pos; _hash[kHash3Offset + hash3Value] = _pos; if (curMatch2 > matchMinPos) if (_bufferBase[_bufferOffset + curMatch2] == _bufferBase[cur]) { distances[offset++] = maxLen = 2; distances[offset++] = _pos - curMatch2 - 1; } if (curMatch3 > matchMinPos) if (_bufferBase[_bufferOffset + curMatch3] == _bufferBase[cur]) { if (curMatch3 == curMatch2) offset -= 2; distances[offset++] = maxLen = 3; distances[offset++] = _pos - curMatch3 - 1; curMatch2 = curMatch3; } if (offset != 0 && curMatch2 == curMatch) { offset -= 2; maxLen = kStartMaxLen; } } _hash[kFixHashSize + hashValue] = _pos; int ptr0 = (_cyclicBufferPos << 1) + 1; int ptr1 = (_cyclicBufferPos << 1); int len0, len1; len0 = len1 = kNumHashDirectBytes; if (kNumHashDirectBytes != 0) { if (curMatch > matchMinPos) { if (_bufferBase[_bufferOffset + curMatch + kNumHashDirectBytes] != _bufferBase[cur + kNumHashDirectBytes]) { distances[offset++] = maxLen = kNumHashDirectBytes; distances[offset++] = _pos - curMatch - 1; } } } int count = _cutValue; while (true) { if (curMatch <= matchMinPos || count-- == 0) { _son[ptr0] = _son[ptr1] = kEmptyHashValue; break; } int delta = _pos - curMatch; int cyclicPos = ((delta <= _cyclicBufferPos) ? (_cyclicBufferPos - delta) : (_cyclicBufferPos - delta + _cyclicBufferSize)) << 1; int pby1 = _bufferOffset + curMatch; int len = Math.min(len0, len1); if (_bufferBase[pby1 + len] == _bufferBase[cur + len]) { while(++len != lenLimit) if (_bufferBase[pby1 + len] != _bufferBase[cur + len]) break; if (maxLen < len) { distances[offset++] = maxLen = len; distances[offset++] = delta - 1; if (len == lenLimit) { _son[ptr1] = _son[cyclicPos]; _son[ptr0] = _son[cyclicPos + 1]; break; } } } if ((_bufferBase[pby1 + len] & 0xFF) < (_bufferBase[cur + len] & 0xFF)) { _son[ptr1] = curMatch; ptr1 = cyclicPos + 1; curMatch = _son[ptr1]; len1 = len; } else { _son[ptr0] = curMatch; ptr0 = cyclicPos; curMatch = _son[ptr0]; len0 = len; } } MovePos(); return offset; } public void Skip(int num) throws IOException { do { int lenLimit; if (_pos + _matchMaxLen <= _streamPos) lenLimit = _matchMaxLen; else { lenLimit = _streamPos - _pos; if (lenLimit < kMinMatchCheck) { MovePos(); continue; } } int matchMinPos = (_pos > _cyclicBufferSize) ? (_pos - _cyclicBufferSize) : 0; int cur = _bufferOffset + _pos; int hashValue; if (HASH_ARRAY) { int temp = CrcTable[_bufferBase[cur] & 0xFF] ^ (_bufferBase[cur + 1] & 0xFF); int hash2Value = temp & (kHash2Size - 1); _hash[hash2Value] = _pos; temp ^= ((int)(_bufferBase[cur + 2] & 0xFF) << 8); int hash3Value = temp & (kHash3Size - 1); _hash[kHash3Offset + hash3Value] = _pos; hashValue = (temp ^ (CrcTable[_bufferBase[cur + 3] & 0xFF] << 5)) & _hashMask; } else hashValue = ((_bufferBase[cur] & 0xFF) ^ ((int)(_bufferBase[cur + 1] & 0xFF) << 8)); int curMatch = _hash[kFixHashSize + hashValue]; _hash[kFixHashSize + hashValue] = _pos; int ptr0 = (_cyclicBufferPos << 1) + 1; int ptr1 = (_cyclicBufferPos << 1); int len0, len1; len0 = len1 = kNumHashDirectBytes; int count = _cutValue; while (true) { if (curMatch <= matchMinPos || count-- == 0) { _son[ptr0] = _son[ptr1] = kEmptyHashValue; break; } int delta = _pos - curMatch; int cyclicPos = ((delta <= _cyclicBufferPos) ? (_cyclicBufferPos - delta) : (_cyclicBufferPos - delta + _cyclicBufferSize)) << 1; int pby1 = _bufferOffset + curMatch; int len = Math.min(len0, len1); if (_bufferBase[pby1 + len] == _bufferBase[cur + len]) { while (++len != lenLimit) if (_bufferBase[pby1 + len] != _bufferBase[cur + len]) break; if (len == lenLimit) { _son[ptr1] = _son[cyclicPos]; _son[ptr0] = _son[cyclicPos + 1]; break; } } if ((_bufferBase[pby1 + len] & 0xFF) < (_bufferBase[cur + len] & 0xFF)) { _son[ptr1] = curMatch; ptr1 = cyclicPos + 1; curMatch = _son[ptr1]; len1 = len; } else { _son[ptr0] = curMatch; ptr0 = cyclicPos; curMatch = _son[ptr0]; len0 = len; } } MovePos(); } while (--num != 0); } void NormalizeLinks(int[] items, int numItems, int subValue) { for (int i = 0; i < numItems; i++) { int value = items[i]; if (value <= subValue) value = kEmptyHashValue; else value -= subValue; items[i] = value; } } void Normalize() { int subValue = _pos - _cyclicBufferSize; NormalizeLinks(_son, _cyclicBufferSize * 2, subValue); NormalizeLinks(_hash, _hashSizeSum, subValue); ReduceOffsets(subValue); } public void SetCutValue(int cutValue) { _cutValue = cutValue; } private static final int[] CrcTable = new int[256]; static { for (int i = 0; i < 256; i++) { int r = i; for (int j = 0; j < 8; j++) if ((r & 1) != 0) r = (r >>> 1) ^ 0xEDB88320; else r >>>= 1; CrcTable[i] = r; } } }
8,800
21.979112
102
java
uiHRDC
uiHRDC-master/uiHRDC/indexes/POS/II_docs/ilists.gap.imp/6.vbyteP7zip_acabadoMerge2yN[Fork.log_enabled]/lzmalib/lzma.sourceCode/LZMAFARI_LIB/lzma465/Java/SevenZip/Compression/LZ/InWindow.java
// LZ.InWindow package SevenZip.Compression.LZ; import java.io.IOException; public class InWindow { public byte[] _bufferBase; // pointer to buffer with data java.io.InputStream _stream; int _posLimit; // offset (from _buffer) of first byte when new block reading must be done boolean _streamEndWasReached; // if (true) then _streamPos shows real end of stream int _pointerToLastSafePosition; public int _bufferOffset; public int _blockSize; // Size of Allocated memory block public int _pos; // offset (from _buffer) of curent byte int _keepSizeBefore; // how many BYTEs must be kept in buffer before _pos int _keepSizeAfter; // how many BYTEs must be kept buffer after _pos public int _streamPos; // offset (from _buffer) of first not read byte from Stream public void MoveBlock() { int offset = _bufferOffset + _pos - _keepSizeBefore; // we need one additional byte, since MovePos moves on 1 byte. if (offset > 0) offset--; int numBytes = _bufferOffset + _streamPos - offset; // check negative offset ???? for (int i = 0; i < numBytes; i++) _bufferBase[i] = _bufferBase[offset + i]; _bufferOffset -= offset; } public void ReadBlock() throws IOException { if (_streamEndWasReached) return; while (true) { int size = (0 - _bufferOffset) + _blockSize - _streamPos; if (size == 0) return; int numReadBytes = _stream.read(_bufferBase, _bufferOffset + _streamPos, size); if (numReadBytes == -1) { _posLimit = _streamPos; int pointerToPostion = _bufferOffset + _posLimit; if (pointerToPostion > _pointerToLastSafePosition) _posLimit = _pointerToLastSafePosition - _bufferOffset; _streamEndWasReached = true; return; } _streamPos += numReadBytes; if (_streamPos >= _pos + _keepSizeAfter) _posLimit = _streamPos - _keepSizeAfter; } } void Free() { _bufferBase = null; } public void Create(int keepSizeBefore, int keepSizeAfter, int keepSizeReserv) { _keepSizeBefore = keepSizeBefore; _keepSizeAfter = keepSizeAfter; int blockSize = keepSizeBefore + keepSizeAfter + keepSizeReserv; if (_bufferBase == null || _blockSize != blockSize) { Free(); _blockSize = blockSize; _bufferBase = new byte[_blockSize]; } _pointerToLastSafePosition = _blockSize - keepSizeAfter; } public void SetStream(java.io.InputStream stream) { _stream = stream; } public void ReleaseStream() { _stream = null; } public void Init() throws IOException { _bufferOffset = 0; _pos = 0; _streamPos = 0; _streamEndWasReached = false; ReadBlock(); } public void MovePos() throws IOException { _pos++; if (_pos > _posLimit) { int pointerToPostion = _bufferOffset + _pos; if (pointerToPostion > _pointerToLastSafePosition) MoveBlock(); ReadBlock(); } } public byte GetIndexByte(int index) { return _bufferBase[_bufferOffset + _pos + index]; } // index + limit have not to exceed _keepSizeAfter; public int GetMatchLen(int index, int distance, int limit) { if (_streamEndWasReached) if ((_pos + index) + limit > _streamPos) limit = _streamPos - (_pos + index); distance++; // Byte *pby = _buffer + (size_t)_pos + index; int pby = _bufferOffset + _pos + index; int i; for (i = 0; i < limit && _bufferBase[pby + i] == _bufferBase[pby + i - distance]; i++); return i; } public int GetNumAvailableBytes() { return _streamPos - _pos; } public void ReduceOffsets(int subValue) { _bufferOffset += subValue; _posLimit -= subValue; _pos -= subValue; _streamPos -= subValue; } }
3,595
26.242424
91
java
uiHRDC
uiHRDC-master/uiHRDC/indexes/POS/II_docs/ilists.gap.imp/6.vbyteP7zip_acabadoMerge2yN[Fork.log_enabled]/lzmalib/lzma.sourceCode/LZMAFARI_LIB/lzma465/Java/SevenZip/Compression/RangeCoder/BitTreeDecoder.java
package SevenZip.Compression.RangeCoder; public class BitTreeDecoder { short[] Models; int NumBitLevels; public BitTreeDecoder(int numBitLevels) { NumBitLevels = numBitLevels; Models = new short[1 << numBitLevels]; } public void Init() { Decoder.InitBitModels(Models); } public int Decode(Decoder rangeDecoder) throws java.io.IOException { int m = 1; for (int bitIndex = NumBitLevels; bitIndex != 0; bitIndex--) m = (m << 1) + rangeDecoder.DecodeBit(Models, m); return m - (1 << NumBitLevels); } public int ReverseDecode(Decoder rangeDecoder) throws java.io.IOException { int m = 1; int symbol = 0; for (int bitIndex = 0; bitIndex < NumBitLevels; bitIndex++) { int bit = rangeDecoder.DecodeBit(Models, m); m <<= 1; m += bit; symbol |= (bit << bitIndex); } return symbol; } public static int ReverseDecode(short[] Models, int startIndex, Decoder rangeDecoder, int NumBitLevels) throws java.io.IOException { int m = 1; int symbol = 0; for (int bitIndex = 0; bitIndex < NumBitLevels; bitIndex++) { int bit = rangeDecoder.DecodeBit(Models, startIndex + m); m <<= 1; m += bit; symbol |= (bit << bitIndex); } return symbol; } }
1,216
20.732143
74
java
uiHRDC
uiHRDC-master/uiHRDC/indexes/POS/II_docs/ilists.gap.imp/6.vbyteP7zip_acabadoMerge2yN[Fork.log_enabled]/lzmalib/lzma.sourceCode/LZMAFARI_LIB/lzma465/Java/SevenZip/Compression/RangeCoder/Decoder.java
package SevenZip.Compression.RangeCoder; import java.io.IOException; public class Decoder { static final int kTopMask = ~((1 << 24) - 1); static final int kNumBitModelTotalBits = 11; static final int kBitModelTotal = (1 << kNumBitModelTotalBits); static final int kNumMoveBits = 5; int Range; int Code; java.io.InputStream Stream; public final void SetStream(java.io.InputStream stream) { Stream = stream; } public final void ReleaseStream() { Stream = null; } public final void Init() throws IOException { Code = 0; Range = -1; for (int i = 0; i < 5; i++) Code = (Code << 8) | Stream.read(); } public final int DecodeDirectBits(int numTotalBits) throws IOException { int result = 0; for (int i = numTotalBits; i != 0; i--) { Range >>>= 1; int t = ((Code - Range) >>> 31); Code -= Range & (t - 1); result = (result << 1) | (1 - t); if ((Range & kTopMask) == 0) { Code = (Code << 8) | Stream.read(); Range <<= 8; } } return result; } public int DecodeBit(short []probs, int index) throws IOException { int prob = probs[index]; int newBound = (Range >>> kNumBitModelTotalBits) * prob; if ((Code ^ 0x80000000) < (newBound ^ 0x80000000)) { Range = newBound; probs[index] = (short)(prob + ((kBitModelTotal - prob) >>> kNumMoveBits)); if ((Range & kTopMask) == 0) { Code = (Code << 8) | Stream.read(); Range <<= 8; } return 0; } else { Range -= newBound; Code -= newBound; probs[index] = (short)(prob - ((prob) >>> kNumMoveBits)); if ((Range & kTopMask) == 0) { Code = (Code << 8) | Stream.read(); Range <<= 8; } return 1; } } public static void InitBitModels(short []probs) { for (int i = 0; i < probs.length; i++) probs[i] = (kBitModelTotal >>> 1); } }
1,828
19.550562
77
java
uiHRDC
uiHRDC-master/uiHRDC/indexes/POS/II_docs/ilists.gap.imp/6.vbyteP7zip_acabadoMerge2yN[Fork.log_enabled]/lzmalib/lzma.sourceCode/LZMAFARI_LIB/lzma465/Java/SevenZip/Compression/RangeCoder/BitTreeEncoder.java
package SevenZip.Compression.RangeCoder; import java.io.IOException; public class BitTreeEncoder { short[] Models; int NumBitLevels; public BitTreeEncoder(int numBitLevels) { NumBitLevels = numBitLevels; Models = new short[1 << numBitLevels]; } public void Init() { Decoder.InitBitModels(Models); } public void Encode(Encoder rangeEncoder, int symbol) throws IOException { int m = 1; for (int bitIndex = NumBitLevels; bitIndex != 0; ) { bitIndex--; int bit = (symbol >>> bitIndex) & 1; rangeEncoder.Encode(Models, m, bit); m = (m << 1) | bit; } } public void ReverseEncode(Encoder rangeEncoder, int symbol) throws IOException { int m = 1; for (int i = 0; i < NumBitLevels; i++) { int bit = symbol & 1; rangeEncoder.Encode(Models, m, bit); m = (m << 1) | bit; symbol >>= 1; } } public int GetPrice(int symbol) { int price = 0; int m = 1; for (int bitIndex = NumBitLevels; bitIndex != 0; ) { bitIndex--; int bit = (symbol >>> bitIndex) & 1; price += Encoder.GetPrice(Models[m], bit); m = (m << 1) + bit; } return price; } public int ReverseGetPrice(int symbol) { int price = 0; int m = 1; for (int i = NumBitLevels; i != 0; i--) { int bit = symbol & 1; symbol >>>= 1; price += Encoder.GetPrice(Models[m], bit); m = (m << 1) | bit; } return price; } public static int ReverseGetPrice(short[] Models, int startIndex, int NumBitLevels, int symbol) { int price = 0; int m = 1; for (int i = NumBitLevels; i != 0; i--) { int bit = symbol & 1; symbol >>>= 1; price += Encoder.GetPrice(Models[startIndex + m], bit); m = (m << 1) | bit; } return price; } public static void ReverseEncode(short[] Models, int startIndex, Encoder rangeEncoder, int NumBitLevels, int symbol) throws IOException { int m = 1; for (int i = 0; i < NumBitLevels; i++) { int bit = symbol & 1; rangeEncoder.Encode(Models, startIndex + m, bit); m = (m << 1) | bit; symbol >>= 1; } } }
2,034
19.35
79
java
uiHRDC
uiHRDC-master/uiHRDC/indexes/POS/II_docs/ilists.gap.imp/6.vbyteP7zip_acabadoMerge2yN[Fork.log_enabled]/lzmalib/lzma.sourceCode/LZMAFARI_LIB/lzma465/Java/SevenZip/Compression/RangeCoder/Encoder.java
package SevenZip.Compression.RangeCoder; import java.io.IOException; public class Encoder { static final int kTopMask = ~((1 << 24) - 1); static final int kNumBitModelTotalBits = 11; static final int kBitModelTotal = (1 << kNumBitModelTotalBits); static final int kNumMoveBits = 5; java.io.OutputStream Stream; long Low; int Range; int _cacheSize; int _cache; long _position; public void SetStream(java.io.OutputStream stream) { Stream = stream; } public void ReleaseStream() { Stream = null; } public void Init() { _position = 0; Low = 0; Range = -1; _cacheSize = 1; _cache = 0; } public void FlushData() throws IOException { for (int i = 0; i < 5; i++) ShiftLow(); } public void FlushStream() throws IOException { Stream.flush(); } public void ShiftLow() throws IOException { int LowHi = (int)(Low >>> 32); if (LowHi != 0 || Low < 0xFF000000L) { _position += _cacheSize; int temp = _cache; do { Stream.write(temp + LowHi); temp = 0xFF; } while(--_cacheSize != 0); _cache = (((int)Low) >>> 24); } _cacheSize++; Low = (Low & 0xFFFFFF) << 8; } public void EncodeDirectBits(int v, int numTotalBits) throws IOException { for (int i = numTotalBits - 1; i >= 0; i--) { Range >>>= 1; if (((v >>> i) & 1) == 1) Low += Range; if ((Range & Encoder.kTopMask) == 0) { Range <<= 8; ShiftLow(); } } } public long GetProcessedSizeAdd() { return _cacheSize + _position + 4; } static final int kNumMoveReducingBits = 2; public static final int kNumBitPriceShiftBits = 6; public static void InitBitModels(short []probs) { for (int i = 0; i < probs.length; i++) probs[i] = (kBitModelTotal >>> 1); } public void Encode(short []probs, int index, int symbol) throws IOException { int prob = probs[index]; int newBound = (Range >>> kNumBitModelTotalBits) * prob; if (symbol == 0) { Range = newBound; probs[index] = (short)(prob + ((kBitModelTotal - prob) >>> kNumMoveBits)); } else { Low += (newBound & 0xFFFFFFFFL); Range -= newBound; probs[index] = (short)(prob - ((prob) >>> kNumMoveBits)); } if ((Range & kTopMask) == 0) { Range <<= 8; ShiftLow(); } } private static int[] ProbPrices = new int[kBitModelTotal >>> kNumMoveReducingBits]; static { int kNumBits = (kNumBitModelTotalBits - kNumMoveReducingBits); for (int i = kNumBits - 1; i >= 0; i--) { int start = 1 << (kNumBits - i - 1); int end = 1 << (kNumBits - i); for (int j = start; j < end; j++) ProbPrices[j] = (i << kNumBitPriceShiftBits) + (((end - j) << kNumBitPriceShiftBits) >>> (kNumBits - i - 1)); } } static public int GetPrice(int Prob, int symbol) { return ProbPrices[(((Prob - symbol) ^ ((-symbol))) & (kBitModelTotal - 1)) >>> kNumMoveReducingBits]; } static public int GetPrice0(int Prob) { return ProbPrices[Prob >>> kNumMoveReducingBits]; } static public int GetPrice1(int Prob) { return ProbPrices[(kBitModelTotal - Prob) >>> kNumMoveReducingBits]; } }
3,087
19.315789
103
java
uiHRDC
uiHRDC-master/uiHRDC/indexes/POS/II_docs/ilists.gap.imp/6.vbyteP7zip_acabadoMerge2yN[Fork.log_enabled]/lzmalib/lzma.sourceCode/LZMAFARI_LIB/lzma465/Java/SevenZip/Compression/LZMA/Base.java
// Base.java package SevenZip.Compression.LZMA; public class Base { public static final int kNumRepDistances = 4; public static final int kNumStates = 12; public static final int StateInit() { return 0; } public static final int StateUpdateChar(int index) { if (index < 4) return 0; if (index < 10) return index - 3; return index - 6; } public static final int StateUpdateMatch(int index) { return (index < 7 ? 7 : 10); } public static final int StateUpdateRep(int index) { return (index < 7 ? 8 : 11); } public static final int StateUpdateShortRep(int index) { return (index < 7 ? 9 : 11); } public static final boolean StateIsCharState(int index) { return index < 7; } public static final int kNumPosSlotBits = 6; public static final int kDicLogSizeMin = 0; // public static final int kDicLogSizeMax = 28; // public static final int kDistTableSizeMax = kDicLogSizeMax * 2; public static final int kNumLenToPosStatesBits = 2; // it's for speed optimization public static final int kNumLenToPosStates = 1 << kNumLenToPosStatesBits; public static final int kMatchMinLen = 2; public static final int GetLenToPosState(int len) { len -= kMatchMinLen; if (len < kNumLenToPosStates) return len; return (int)(kNumLenToPosStates - 1); } public static final int kNumAlignBits = 4; public static final int kAlignTableSize = 1 << kNumAlignBits; public static final int kAlignMask = (kAlignTableSize - 1); public static final int kStartPosModelIndex = 4; public static final int kEndPosModelIndex = 14; public static final int kNumPosModels = kEndPosModelIndex - kStartPosModelIndex; public static final int kNumFullDistances = 1 << (kEndPosModelIndex / 2); public static final int kNumLitPosStatesBitsEncodingMax = 4; public static final int kNumLitContextBitsMax = 8; public static final int kNumPosStatesBitsMax = 4; public static final int kNumPosStatesMax = (1 << kNumPosStatesBitsMax); public static final int kNumPosStatesBitsEncodingMax = 4; public static final int kNumPosStatesEncodingMax = (1 << kNumPosStatesBitsEncodingMax); public static final int kNumLowLenBits = 3; public static final int kNumMidLenBits = 3; public static final int kNumHighLenBits = 8; public static final int kNumLowLenSymbols = 1 << kNumLowLenBits; public static final int kNumMidLenSymbols = 1 << kNumMidLenBits; public static final int kNumLenSymbols = kNumLowLenSymbols + kNumMidLenSymbols + (1 << kNumHighLenBits); public static final int kMatchMaxLen = kMatchMinLen + kNumLenSymbols - 1; }
2,609
28.325843
89
java
uiHRDC
uiHRDC-master/uiHRDC/indexes/POS/II_docs/ilists.gap.imp/6.vbyteP7zip_acabadoMerge2yN[Fork.log_enabled]/lzmalib/lzma.sourceCode/LZMAFARI_LIB/lzma465/Java/SevenZip/Compression/LZMA/Decoder.java
package SevenZip.Compression.LZMA; import SevenZip.Compression.RangeCoder.BitTreeDecoder; import SevenZip.Compression.LZMA.Base; import SevenZip.Compression.LZ.OutWindow; import java.io.IOException; public class Decoder { class LenDecoder { short[] m_Choice = new short[2]; BitTreeDecoder[] m_LowCoder = new BitTreeDecoder[Base.kNumPosStatesMax]; BitTreeDecoder[] m_MidCoder = new BitTreeDecoder[Base.kNumPosStatesMax]; BitTreeDecoder m_HighCoder = new BitTreeDecoder(Base.kNumHighLenBits); int m_NumPosStates = 0; public void Create(int numPosStates) { for (; m_NumPosStates < numPosStates; m_NumPosStates++) { m_LowCoder[m_NumPosStates] = new BitTreeDecoder(Base.kNumLowLenBits); m_MidCoder[m_NumPosStates] = new BitTreeDecoder(Base.kNumMidLenBits); } } public void Init() { SevenZip.Compression.RangeCoder.Decoder.InitBitModels(m_Choice); for (int posState = 0; posState < m_NumPosStates; posState++) { m_LowCoder[posState].Init(); m_MidCoder[posState].Init(); } m_HighCoder.Init(); } public int Decode(SevenZip.Compression.RangeCoder.Decoder rangeDecoder, int posState) throws IOException { if (rangeDecoder.DecodeBit(m_Choice, 0) == 0) return m_LowCoder[posState].Decode(rangeDecoder); int symbol = Base.kNumLowLenSymbols; if (rangeDecoder.DecodeBit(m_Choice, 1) == 0) symbol += m_MidCoder[posState].Decode(rangeDecoder); else symbol += Base.kNumMidLenSymbols + m_HighCoder.Decode(rangeDecoder); return symbol; } } class LiteralDecoder { class Decoder2 { short[] m_Decoders = new short[0x300]; public void Init() { SevenZip.Compression.RangeCoder.Decoder.InitBitModels(m_Decoders); } public byte DecodeNormal(SevenZip.Compression.RangeCoder.Decoder rangeDecoder) throws IOException { int symbol = 1; do symbol = (symbol << 1) | rangeDecoder.DecodeBit(m_Decoders, symbol); while (symbol < 0x100); return (byte)symbol; } public byte DecodeWithMatchByte(SevenZip.Compression.RangeCoder.Decoder rangeDecoder, byte matchByte) throws IOException { int symbol = 1; do { int matchBit = (matchByte >> 7) & 1; matchByte <<= 1; int bit = rangeDecoder.DecodeBit(m_Decoders, ((1 + matchBit) << 8) + symbol); symbol = (symbol << 1) | bit; if (matchBit != bit) { while (symbol < 0x100) symbol = (symbol << 1) | rangeDecoder.DecodeBit(m_Decoders, symbol); break; } } while (symbol < 0x100); return (byte)symbol; } } Decoder2[] m_Coders; int m_NumPrevBits; int m_NumPosBits; int m_PosMask; public void Create(int numPosBits, int numPrevBits) { if (m_Coders != null && m_NumPrevBits == numPrevBits && m_NumPosBits == numPosBits) return; m_NumPosBits = numPosBits; m_PosMask = (1 << numPosBits) - 1; m_NumPrevBits = numPrevBits; int numStates = 1 << (m_NumPrevBits + m_NumPosBits); m_Coders = new Decoder2[numStates]; for (int i = 0; i < numStates; i++) m_Coders[i] = new Decoder2(); } public void Init() { int numStates = 1 << (m_NumPrevBits + m_NumPosBits); for (int i = 0; i < numStates; i++) m_Coders[i].Init(); } Decoder2 GetDecoder(int pos, byte prevByte) { return m_Coders[((pos & m_PosMask) << m_NumPrevBits) + ((prevByte & 0xFF) >>> (8 - m_NumPrevBits))]; } } OutWindow m_OutWindow = new OutWindow(); SevenZip.Compression.RangeCoder.Decoder m_RangeDecoder = new SevenZip.Compression.RangeCoder.Decoder(); short[] m_IsMatchDecoders = new short[Base.kNumStates << Base.kNumPosStatesBitsMax]; short[] m_IsRepDecoders = new short[Base.kNumStates]; short[] m_IsRepG0Decoders = new short[Base.kNumStates]; short[] m_IsRepG1Decoders = new short[Base.kNumStates]; short[] m_IsRepG2Decoders = new short[Base.kNumStates]; short[] m_IsRep0LongDecoders = new short[Base.kNumStates << Base.kNumPosStatesBitsMax]; BitTreeDecoder[] m_PosSlotDecoder = new BitTreeDecoder[Base.kNumLenToPosStates]; short[] m_PosDecoders = new short[Base.kNumFullDistances - Base.kEndPosModelIndex]; BitTreeDecoder m_PosAlignDecoder = new BitTreeDecoder(Base.kNumAlignBits); LenDecoder m_LenDecoder = new LenDecoder(); LenDecoder m_RepLenDecoder = new LenDecoder(); LiteralDecoder m_LiteralDecoder = new LiteralDecoder(); int m_DictionarySize = -1; int m_DictionarySizeCheck = -1; int m_PosStateMask; public Decoder() { for (int i = 0; i < Base.kNumLenToPosStates; i++) m_PosSlotDecoder[i] = new BitTreeDecoder(Base.kNumPosSlotBits); } boolean SetDictionarySize(int dictionarySize) { if (dictionarySize < 0) return false; if (m_DictionarySize != dictionarySize) { m_DictionarySize = dictionarySize; m_DictionarySizeCheck = Math.max(m_DictionarySize, 1); m_OutWindow.Create(Math.max(m_DictionarySizeCheck, (1 << 12))); } return true; } boolean SetLcLpPb(int lc, int lp, int pb) { if (lc > Base.kNumLitContextBitsMax || lp > 4 || pb > Base.kNumPosStatesBitsMax) return false; m_LiteralDecoder.Create(lp, lc); int numPosStates = 1 << pb; m_LenDecoder.Create(numPosStates); m_RepLenDecoder.Create(numPosStates); m_PosStateMask = numPosStates - 1; return true; } void Init() throws IOException { m_OutWindow.Init(false); SevenZip.Compression.RangeCoder.Decoder.InitBitModels(m_IsMatchDecoders); SevenZip.Compression.RangeCoder.Decoder.InitBitModels(m_IsRep0LongDecoders); SevenZip.Compression.RangeCoder.Decoder.InitBitModels(m_IsRepDecoders); SevenZip.Compression.RangeCoder.Decoder.InitBitModels(m_IsRepG0Decoders); SevenZip.Compression.RangeCoder.Decoder.InitBitModels(m_IsRepG1Decoders); SevenZip.Compression.RangeCoder.Decoder.InitBitModels(m_IsRepG2Decoders); SevenZip.Compression.RangeCoder.Decoder.InitBitModels(m_PosDecoders); m_LiteralDecoder.Init(); int i; for (i = 0; i < Base.kNumLenToPosStates; i++) m_PosSlotDecoder[i].Init(); m_LenDecoder.Init(); m_RepLenDecoder.Init(); m_PosAlignDecoder.Init(); m_RangeDecoder.Init(); } public boolean Code(java.io.InputStream inStream, java.io.OutputStream outStream, long outSize) throws IOException { m_RangeDecoder.SetStream(inStream); m_OutWindow.SetStream(outStream); Init(); int state = Base.StateInit(); int rep0 = 0, rep1 = 0, rep2 = 0, rep3 = 0; long nowPos64 = 0; byte prevByte = 0; while (outSize < 0 || nowPos64 < outSize) { int posState = (int)nowPos64 & m_PosStateMask; if (m_RangeDecoder.DecodeBit(m_IsMatchDecoders, (state << Base.kNumPosStatesBitsMax) + posState) == 0) { LiteralDecoder.Decoder2 decoder2 = m_LiteralDecoder.GetDecoder((int)nowPos64, prevByte); if (!Base.StateIsCharState(state)) prevByte = decoder2.DecodeWithMatchByte(m_RangeDecoder, m_OutWindow.GetByte(rep0)); else prevByte = decoder2.DecodeNormal(m_RangeDecoder); m_OutWindow.PutByte(prevByte); state = Base.StateUpdateChar(state); nowPos64++; } else { int len; if (m_RangeDecoder.DecodeBit(m_IsRepDecoders, state) == 1) { len = 0; if (m_RangeDecoder.DecodeBit(m_IsRepG0Decoders, state) == 0) { if (m_RangeDecoder.DecodeBit(m_IsRep0LongDecoders, (state << Base.kNumPosStatesBitsMax) + posState) == 0) { state = Base.StateUpdateShortRep(state); len = 1; } } else { int distance; if (m_RangeDecoder.DecodeBit(m_IsRepG1Decoders, state) == 0) distance = rep1; else { if (m_RangeDecoder.DecodeBit(m_IsRepG2Decoders, state) == 0) distance = rep2; else { distance = rep3; rep3 = rep2; } rep2 = rep1; } rep1 = rep0; rep0 = distance; } if (len == 0) { len = m_RepLenDecoder.Decode(m_RangeDecoder, posState) + Base.kMatchMinLen; state = Base.StateUpdateRep(state); } } else { rep3 = rep2; rep2 = rep1; rep1 = rep0; len = Base.kMatchMinLen + m_LenDecoder.Decode(m_RangeDecoder, posState); state = Base.StateUpdateMatch(state); int posSlot = m_PosSlotDecoder[Base.GetLenToPosState(len)].Decode(m_RangeDecoder); if (posSlot >= Base.kStartPosModelIndex) { int numDirectBits = (posSlot >> 1) - 1; rep0 = ((2 | (posSlot & 1)) << numDirectBits); if (posSlot < Base.kEndPosModelIndex) rep0 += BitTreeDecoder.ReverseDecode(m_PosDecoders, rep0 - posSlot - 1, m_RangeDecoder, numDirectBits); else { rep0 += (m_RangeDecoder.DecodeDirectBits( numDirectBits - Base.kNumAlignBits) << Base.kNumAlignBits); rep0 += m_PosAlignDecoder.ReverseDecode(m_RangeDecoder); if (rep0 < 0) { if (rep0 == -1) break; return false; } } } else rep0 = posSlot; } if (rep0 >= nowPos64 || rep0 >= m_DictionarySizeCheck) { // m_OutWindow.Flush(); return false; } m_OutWindow.CopyBlock(rep0, len); nowPos64 += len; prevByte = m_OutWindow.GetByte(0); } } m_OutWindow.Flush(); m_OutWindow.ReleaseStream(); m_RangeDecoder.ReleaseStream(); return true; } public boolean SetDecoderProperties(byte[] properties) { if (properties.length < 5) return false; int val = properties[0] & 0xFF; int lc = val % 9; int remainder = val / 9; int lp = remainder % 5; int pb = remainder / 5; int dictionarySize = 0; for (int i = 0; i < 4; i++) dictionarySize += ((int)(properties[1 + i]) & 0xFF) << (i * 8); if (!SetLcLpPb(lc, lp, pb)) return false; return SetDictionarySize(dictionarySize); } }
9,677
28.327273
123
java
uiHRDC
uiHRDC-master/uiHRDC/indexes/POS/II_docs/ilists.gap.imp/6.vbyteP7zip_acabadoMerge2yN[Fork.log_enabled]/lzmalib/lzma.sourceCode/LZMAFARI_LIB/lzma465/Java/SevenZip/Compression/LZMA/Encoder.java
package SevenZip.Compression.LZMA; import SevenZip.Compression.RangeCoder.BitTreeEncoder; import SevenZip.Compression.LZMA.Base; import SevenZip.Compression.LZ.BinTree; import SevenZip.ICodeProgress; import java.io.IOException; public class Encoder { public static final int EMatchFinderTypeBT2 = 0; public static final int EMatchFinderTypeBT4 = 1; static final int kIfinityPrice = 0xFFFFFFF; static byte[] g_FastPos = new byte[1 << 11]; static { int kFastSlots = 22; int c = 2; g_FastPos[0] = 0; g_FastPos[1] = 1; for (int slotFast = 2; slotFast < kFastSlots; slotFast++) { int k = (1 << ((slotFast >> 1) - 1)); for (int j = 0; j < k; j++, c++) g_FastPos[c] = (byte)slotFast; } } static int GetPosSlot(int pos) { if (pos < (1 << 11)) return g_FastPos[pos]; if (pos < (1 << 21)) return (g_FastPos[pos >> 10] + 20); return (g_FastPos[pos >> 20] + 40); } static int GetPosSlot2(int pos) { if (pos < (1 << 17)) return (g_FastPos[pos >> 6] + 12); if (pos < (1 << 27)) return (g_FastPos[pos >> 16] + 32); return (g_FastPos[pos >> 26] + 52); } int _state = Base.StateInit(); byte _previousByte; int[] _repDistances = new int[Base.kNumRepDistances]; void BaseInit() { _state = Base.StateInit(); _previousByte = 0; for (int i = 0; i < Base.kNumRepDistances; i++) _repDistances[i] = 0; } static final int kDefaultDictionaryLogSize = 22; static final int kNumFastBytesDefault = 0x20; class LiteralEncoder { class Encoder2 { short[] m_Encoders = new short[0x300]; public void Init() { SevenZip.Compression.RangeCoder.Encoder.InitBitModels(m_Encoders); } public void Encode(SevenZip.Compression.RangeCoder.Encoder rangeEncoder, byte symbol) throws IOException { int context = 1; for (int i = 7; i >= 0; i--) { int bit = ((symbol >> i) & 1); rangeEncoder.Encode(m_Encoders, context, bit); context = (context << 1) | bit; } } public void EncodeMatched(SevenZip.Compression.RangeCoder.Encoder rangeEncoder, byte matchByte, byte symbol) throws IOException { int context = 1; boolean same = true; for (int i = 7; i >= 0; i--) { int bit = ((symbol >> i) & 1); int state = context; if (same) { int matchBit = ((matchByte >> i) & 1); state += ((1 + matchBit) << 8); same = (matchBit == bit); } rangeEncoder.Encode(m_Encoders, state, bit); context = (context << 1) | bit; } } public int GetPrice(boolean matchMode, byte matchByte, byte symbol) { int price = 0; int context = 1; int i = 7; if (matchMode) { for (; i >= 0; i--) { int matchBit = (matchByte >> i) & 1; int bit = (symbol >> i) & 1; price += SevenZip.Compression.RangeCoder.Encoder.GetPrice(m_Encoders[((1 + matchBit) << 8) + context], bit); context = (context << 1) | bit; if (matchBit != bit) { i--; break; } } } for (; i >= 0; i--) { int bit = (symbol >> i) & 1; price += SevenZip.Compression.RangeCoder.Encoder.GetPrice(m_Encoders[context], bit); context = (context << 1) | bit; } return price; } } Encoder2[] m_Coders; int m_NumPrevBits; int m_NumPosBits; int m_PosMask; public void Create(int numPosBits, int numPrevBits) { if (m_Coders != null && m_NumPrevBits == numPrevBits && m_NumPosBits == numPosBits) return; m_NumPosBits = numPosBits; m_PosMask = (1 << numPosBits) - 1; m_NumPrevBits = numPrevBits; int numStates = 1 << (m_NumPrevBits + m_NumPosBits); m_Coders = new Encoder2[numStates]; for (int i = 0; i < numStates; i++) m_Coders[i] = new Encoder2(); } public void Init() { int numStates = 1 << (m_NumPrevBits + m_NumPosBits); for (int i = 0; i < numStates; i++) m_Coders[i].Init(); } public Encoder2 GetSubCoder(int pos, byte prevByte) { return m_Coders[((pos & m_PosMask) << m_NumPrevBits) + ((prevByte & 0xFF) >>> (8 - m_NumPrevBits))]; } } class LenEncoder { short[] _choice = new short[2]; BitTreeEncoder[] _lowCoder = new BitTreeEncoder[Base.kNumPosStatesEncodingMax]; BitTreeEncoder[] _midCoder = new BitTreeEncoder[Base.kNumPosStatesEncodingMax]; BitTreeEncoder _highCoder = new BitTreeEncoder(Base.kNumHighLenBits); public LenEncoder() { for (int posState = 0; posState < Base.kNumPosStatesEncodingMax; posState++) { _lowCoder[posState] = new BitTreeEncoder(Base.kNumLowLenBits); _midCoder[posState] = new BitTreeEncoder(Base.kNumMidLenBits); } } public void Init(int numPosStates) { SevenZip.Compression.RangeCoder.Encoder.InitBitModels(_choice); for (int posState = 0; posState < numPosStates; posState++) { _lowCoder[posState].Init(); _midCoder[posState].Init(); } _highCoder.Init(); } public void Encode(SevenZip.Compression.RangeCoder.Encoder rangeEncoder, int symbol, int posState) throws IOException { if (symbol < Base.kNumLowLenSymbols) { rangeEncoder.Encode(_choice, 0, 0); _lowCoder[posState].Encode(rangeEncoder, symbol); } else { symbol -= Base.kNumLowLenSymbols; rangeEncoder.Encode(_choice, 0, 1); if (symbol < Base.kNumMidLenSymbols) { rangeEncoder.Encode(_choice, 1, 0); _midCoder[posState].Encode(rangeEncoder, symbol); } else { rangeEncoder.Encode(_choice, 1, 1); _highCoder.Encode(rangeEncoder, symbol - Base.kNumMidLenSymbols); } } } public void SetPrices(int posState, int numSymbols, int[] prices, int st) { int a0 = SevenZip.Compression.RangeCoder.Encoder.GetPrice0(_choice[0]); int a1 = SevenZip.Compression.RangeCoder.Encoder.GetPrice1(_choice[0]); int b0 = a1 + SevenZip.Compression.RangeCoder.Encoder.GetPrice0(_choice[1]); int b1 = a1 + SevenZip.Compression.RangeCoder.Encoder.GetPrice1(_choice[1]); int i = 0; for (i = 0; i < Base.kNumLowLenSymbols; i++) { if (i >= numSymbols) return; prices[st + i] = a0 + _lowCoder[posState].GetPrice(i); } for (; i < Base.kNumLowLenSymbols + Base.kNumMidLenSymbols; i++) { if (i >= numSymbols) return; prices[st + i] = b0 + _midCoder[posState].GetPrice(i - Base.kNumLowLenSymbols); } for (; i < numSymbols; i++) prices[st + i] = b1 + _highCoder.GetPrice(i - Base.kNumLowLenSymbols - Base.kNumMidLenSymbols); } }; public static final int kNumLenSpecSymbols = Base.kNumLowLenSymbols + Base.kNumMidLenSymbols; class LenPriceTableEncoder extends LenEncoder { int[] _prices = new int[Base.kNumLenSymbols<<Base.kNumPosStatesBitsEncodingMax]; int _tableSize; int[] _counters = new int[Base.kNumPosStatesEncodingMax]; public void SetTableSize(int tableSize) { _tableSize = tableSize; } public int GetPrice(int symbol, int posState) { return _prices[posState * Base.kNumLenSymbols + symbol]; } void UpdateTable(int posState) { SetPrices(posState, _tableSize, _prices, posState * Base.kNumLenSymbols); _counters[posState] = _tableSize; } public void UpdateTables(int numPosStates) { for (int posState = 0; posState < numPosStates; posState++) UpdateTable(posState); } public void Encode(SevenZip.Compression.RangeCoder.Encoder rangeEncoder, int symbol, int posState) throws IOException { super.Encode(rangeEncoder, symbol, posState); if (--_counters[posState] == 0) UpdateTable(posState); } } static final int kNumOpts = 1 << 12; class Optimal { public int State; public boolean Prev1IsChar; public boolean Prev2; public int PosPrev2; public int BackPrev2; public int Price; public int PosPrev; public int BackPrev; public int Backs0; public int Backs1; public int Backs2; public int Backs3; public void MakeAsChar() { BackPrev = -1; Prev1IsChar = false; } public void MakeAsShortRep() { BackPrev = 0; ; Prev1IsChar = false; } public boolean IsShortRep() { return (BackPrev == 0); } }; Optimal[] _optimum = new Optimal[kNumOpts]; SevenZip.Compression.LZ.BinTree _matchFinder = null; SevenZip.Compression.RangeCoder.Encoder _rangeEncoder = new SevenZip.Compression.RangeCoder.Encoder(); short[] _isMatch = new short[Base.kNumStates<<Base.kNumPosStatesBitsMax]; short[] _isRep = new short[Base.kNumStates]; short[] _isRepG0 = new short[Base.kNumStates]; short[] _isRepG1 = new short[Base.kNumStates]; short[] _isRepG2 = new short[Base.kNumStates]; short[] _isRep0Long = new short[Base.kNumStates<<Base.kNumPosStatesBitsMax]; BitTreeEncoder[] _posSlotEncoder = new BitTreeEncoder[Base.kNumLenToPosStates]; // kNumPosSlotBits short[] _posEncoders = new short[Base.kNumFullDistances-Base.kEndPosModelIndex]; BitTreeEncoder _posAlignEncoder = new BitTreeEncoder(Base.kNumAlignBits); LenPriceTableEncoder _lenEncoder = new LenPriceTableEncoder(); LenPriceTableEncoder _repMatchLenEncoder = new LenPriceTableEncoder(); LiteralEncoder _literalEncoder = new LiteralEncoder(); int[] _matchDistances = new int[Base.kMatchMaxLen*2+2]; int _numFastBytes = kNumFastBytesDefault; int _longestMatchLength; int _numDistancePairs; int _additionalOffset; int _optimumEndIndex; int _optimumCurrentIndex; boolean _longestMatchWasFound; int[] _posSlotPrices = new int[1<<(Base.kNumPosSlotBits+Base.kNumLenToPosStatesBits)]; int[] _distancesPrices = new int[Base.kNumFullDistances<<Base.kNumLenToPosStatesBits]; int[] _alignPrices = new int[Base.kAlignTableSize]; int _alignPriceCount; int _distTableSize = (kDefaultDictionaryLogSize * 2); int _posStateBits = 2; int _posStateMask = (4 - 1); int _numLiteralPosStateBits = 0; int _numLiteralContextBits = 3; int _dictionarySize = (1 << kDefaultDictionaryLogSize); int _dictionarySizePrev = -1; int _numFastBytesPrev = -1; long nowPos64; boolean _finished; java.io.InputStream _inStream; int _matchFinderType = EMatchFinderTypeBT4; boolean _writeEndMark = false; boolean _needReleaseMFStream = false; void Create() { if (_matchFinder == null) { SevenZip.Compression.LZ.BinTree bt = new SevenZip.Compression.LZ.BinTree(); int numHashBytes = 4; if (_matchFinderType == EMatchFinderTypeBT2) numHashBytes = 2; bt.SetType(numHashBytes); _matchFinder = bt; } _literalEncoder.Create(_numLiteralPosStateBits, _numLiteralContextBits); if (_dictionarySize == _dictionarySizePrev && _numFastBytesPrev == _numFastBytes) return; _matchFinder.Create(_dictionarySize, kNumOpts, _numFastBytes, Base.kMatchMaxLen + 1); _dictionarySizePrev = _dictionarySize; _numFastBytesPrev = _numFastBytes; } public Encoder() { for (int i = 0; i < kNumOpts; i++) _optimum[i] = new Optimal(); for (int i = 0; i < Base.kNumLenToPosStates; i++) _posSlotEncoder[i] = new BitTreeEncoder(Base.kNumPosSlotBits); } void SetWriteEndMarkerMode(boolean writeEndMarker) { _writeEndMark = writeEndMarker; } void Init() { BaseInit(); _rangeEncoder.Init(); SevenZip.Compression.RangeCoder.Encoder.InitBitModels(_isMatch); SevenZip.Compression.RangeCoder.Encoder.InitBitModels(_isRep0Long); SevenZip.Compression.RangeCoder.Encoder.InitBitModels(_isRep); SevenZip.Compression.RangeCoder.Encoder.InitBitModels(_isRepG0); SevenZip.Compression.RangeCoder.Encoder.InitBitModels(_isRepG1); SevenZip.Compression.RangeCoder.Encoder.InitBitModels(_isRepG2); SevenZip.Compression.RangeCoder.Encoder.InitBitModels(_posEncoders); _literalEncoder.Init(); for (int i = 0; i < Base.kNumLenToPosStates; i++) _posSlotEncoder[i].Init(); _lenEncoder.Init(1 << _posStateBits); _repMatchLenEncoder.Init(1 << _posStateBits); _posAlignEncoder.Init(); _longestMatchWasFound = false; _optimumEndIndex = 0; _optimumCurrentIndex = 0; _additionalOffset = 0; } int ReadMatchDistances() throws java.io.IOException { int lenRes = 0; _numDistancePairs = _matchFinder.GetMatches(_matchDistances); if (_numDistancePairs > 0) { lenRes = _matchDistances[_numDistancePairs - 2]; if (lenRes == _numFastBytes) lenRes += _matchFinder.GetMatchLen((int)lenRes - 1, _matchDistances[_numDistancePairs - 1], Base.kMatchMaxLen - lenRes); } _additionalOffset++; return lenRes; } void MovePos(int num) throws java.io.IOException { if (num > 0) { _matchFinder.Skip(num); _additionalOffset += num; } } int GetRepLen1Price(int state, int posState) { return SevenZip.Compression.RangeCoder.Encoder.GetPrice0(_isRepG0[state]) + SevenZip.Compression.RangeCoder.Encoder.GetPrice0(_isRep0Long[(state << Base.kNumPosStatesBitsMax) + posState]); } int GetPureRepPrice(int repIndex, int state, int posState) { int price; if (repIndex == 0) { price = SevenZip.Compression.RangeCoder.Encoder.GetPrice0(_isRepG0[state]); price += SevenZip.Compression.RangeCoder.Encoder.GetPrice1(_isRep0Long[(state << Base.kNumPosStatesBitsMax) + posState]); } else { price = SevenZip.Compression.RangeCoder.Encoder.GetPrice1(_isRepG0[state]); if (repIndex == 1) price += SevenZip.Compression.RangeCoder.Encoder.GetPrice0(_isRepG1[state]); else { price += SevenZip.Compression.RangeCoder.Encoder.GetPrice1(_isRepG1[state]); price += SevenZip.Compression.RangeCoder.Encoder.GetPrice(_isRepG2[state], repIndex - 2); } } return price; } int GetRepPrice(int repIndex, int len, int state, int posState) { int price = _repMatchLenEncoder.GetPrice(len - Base.kMatchMinLen, posState); return price + GetPureRepPrice(repIndex, state, posState); } int GetPosLenPrice(int pos, int len, int posState) { int price; int lenToPosState = Base.GetLenToPosState(len); if (pos < Base.kNumFullDistances) price = _distancesPrices[(lenToPosState * Base.kNumFullDistances) + pos]; else price = _posSlotPrices[(lenToPosState << Base.kNumPosSlotBits) + GetPosSlot2(pos)] + _alignPrices[pos & Base.kAlignMask]; return price + _lenEncoder.GetPrice(len - Base.kMatchMinLen, posState); } int Backward(int cur) { _optimumEndIndex = cur; int posMem = _optimum[cur].PosPrev; int backMem = _optimum[cur].BackPrev; do { if (_optimum[cur].Prev1IsChar) { _optimum[posMem].MakeAsChar(); _optimum[posMem].PosPrev = posMem - 1; if (_optimum[cur].Prev2) { _optimum[posMem - 1].Prev1IsChar = false; _optimum[posMem - 1].PosPrev = _optimum[cur].PosPrev2; _optimum[posMem - 1].BackPrev = _optimum[cur].BackPrev2; } } int posPrev = posMem; int backCur = backMem; backMem = _optimum[posPrev].BackPrev; posMem = _optimum[posPrev].PosPrev; _optimum[posPrev].BackPrev = backCur; _optimum[posPrev].PosPrev = cur; cur = posPrev; } while (cur > 0); backRes = _optimum[0].BackPrev; _optimumCurrentIndex = _optimum[0].PosPrev; return _optimumCurrentIndex; } int[] reps = new int[Base.kNumRepDistances]; int[] repLens = new int[Base.kNumRepDistances]; int backRes; int GetOptimum(int position) throws IOException { if (_optimumEndIndex != _optimumCurrentIndex) { int lenRes = _optimum[_optimumCurrentIndex].PosPrev - _optimumCurrentIndex; backRes = _optimum[_optimumCurrentIndex].BackPrev; _optimumCurrentIndex = _optimum[_optimumCurrentIndex].PosPrev; return lenRes; } _optimumCurrentIndex = _optimumEndIndex = 0; int lenMain, numDistancePairs; if (!_longestMatchWasFound) { lenMain = ReadMatchDistances(); } else { lenMain = _longestMatchLength; _longestMatchWasFound = false; } numDistancePairs = _numDistancePairs; int numAvailableBytes = _matchFinder.GetNumAvailableBytes() + 1; if (numAvailableBytes < 2) { backRes = -1; return 1; } if (numAvailableBytes > Base.kMatchMaxLen) numAvailableBytes = Base.kMatchMaxLen; int repMaxIndex = 0; int i; for (i = 0; i < Base.kNumRepDistances; i++) { reps[i] = _repDistances[i]; repLens[i] = _matchFinder.GetMatchLen(0 - 1, reps[i], Base.kMatchMaxLen); if (repLens[i] > repLens[repMaxIndex]) repMaxIndex = i; } if (repLens[repMaxIndex] >= _numFastBytes) { backRes = repMaxIndex; int lenRes = repLens[repMaxIndex]; MovePos(lenRes - 1); return lenRes; } if (lenMain >= _numFastBytes) { backRes = _matchDistances[numDistancePairs - 1] + Base.kNumRepDistances; MovePos(lenMain - 1); return lenMain; } byte currentByte = _matchFinder.GetIndexByte(0 - 1); byte matchByte = _matchFinder.GetIndexByte(0 - _repDistances[0] - 1 - 1); if (lenMain < 2 && currentByte != matchByte && repLens[repMaxIndex] < 2) { backRes = -1; return 1; } _optimum[0].State = _state; int posState = (position & _posStateMask); _optimum[1].Price = SevenZip.Compression.RangeCoder.Encoder.GetPrice0(_isMatch[(_state << Base.kNumPosStatesBitsMax) + posState]) + _literalEncoder.GetSubCoder(position, _previousByte).GetPrice(!Base.StateIsCharState(_state), matchByte, currentByte); _optimum[1].MakeAsChar(); int matchPrice = SevenZip.Compression.RangeCoder.Encoder.GetPrice1(_isMatch[(_state << Base.kNumPosStatesBitsMax) + posState]); int repMatchPrice = matchPrice + SevenZip.Compression.RangeCoder.Encoder.GetPrice1(_isRep[_state]); if (matchByte == currentByte) { int shortRepPrice = repMatchPrice + GetRepLen1Price(_state, posState); if (shortRepPrice < _optimum[1].Price) { _optimum[1].Price = shortRepPrice; _optimum[1].MakeAsShortRep(); } } int lenEnd = ((lenMain >= repLens[repMaxIndex]) ? lenMain : repLens[repMaxIndex]); if (lenEnd < 2) { backRes = _optimum[1].BackPrev; return 1; } _optimum[1].PosPrev = 0; _optimum[0].Backs0 = reps[0]; _optimum[0].Backs1 = reps[1]; _optimum[0].Backs2 = reps[2]; _optimum[0].Backs3 = reps[3]; int len = lenEnd; do _optimum[len--].Price = kIfinityPrice; while (len >= 2); for (i = 0; i < Base.kNumRepDistances; i++) { int repLen = repLens[i]; if (repLen < 2) continue; int price = repMatchPrice + GetPureRepPrice(i, _state, posState); do { int curAndLenPrice = price + _repMatchLenEncoder.GetPrice(repLen - 2, posState); Optimal optimum = _optimum[repLen]; if (curAndLenPrice < optimum.Price) { optimum.Price = curAndLenPrice; optimum.PosPrev = 0; optimum.BackPrev = i; optimum.Prev1IsChar = false; } } while (--repLen >= 2); } int normalMatchPrice = matchPrice + SevenZip.Compression.RangeCoder.Encoder.GetPrice0(_isRep[_state]); len = ((repLens[0] >= 2) ? repLens[0] + 1 : 2); if (len <= lenMain) { int offs = 0; while (len > _matchDistances[offs]) offs += 2; for (; ; len++) { int distance = _matchDistances[offs + 1]; int curAndLenPrice = normalMatchPrice + GetPosLenPrice(distance, len, posState); Optimal optimum = _optimum[len]; if (curAndLenPrice < optimum.Price) { optimum.Price = curAndLenPrice; optimum.PosPrev = 0; optimum.BackPrev = distance + Base.kNumRepDistances; optimum.Prev1IsChar = false; } if (len == _matchDistances[offs]) { offs += 2; if (offs == numDistancePairs) break; } } } int cur = 0; while (true) { cur++; if (cur == lenEnd) return Backward(cur); int newLen = ReadMatchDistances(); numDistancePairs = _numDistancePairs; if (newLen >= _numFastBytes) { _longestMatchLength = newLen; _longestMatchWasFound = true; return Backward(cur); } position++; int posPrev = _optimum[cur].PosPrev; int state; if (_optimum[cur].Prev1IsChar) { posPrev--; if (_optimum[cur].Prev2) { state = _optimum[_optimum[cur].PosPrev2].State; if (_optimum[cur].BackPrev2 < Base.kNumRepDistances) state = Base.StateUpdateRep(state); else state = Base.StateUpdateMatch(state); } else state = _optimum[posPrev].State; state = Base.StateUpdateChar(state); } else state = _optimum[posPrev].State; if (posPrev == cur - 1) { if (_optimum[cur].IsShortRep()) state = Base.StateUpdateShortRep(state); else state = Base.StateUpdateChar(state); } else { int pos; if (_optimum[cur].Prev1IsChar && _optimum[cur].Prev2) { posPrev = _optimum[cur].PosPrev2; pos = _optimum[cur].BackPrev2; state = Base.StateUpdateRep(state); } else { pos = _optimum[cur].BackPrev; if (pos < Base.kNumRepDistances) state = Base.StateUpdateRep(state); else state = Base.StateUpdateMatch(state); } Optimal opt = _optimum[posPrev]; if (pos < Base.kNumRepDistances) { if (pos == 0) { reps[0] = opt.Backs0; reps[1] = opt.Backs1; reps[2] = opt.Backs2; reps[3] = opt.Backs3; } else if (pos == 1) { reps[0] = opt.Backs1; reps[1] = opt.Backs0; reps[2] = opt.Backs2; reps[3] = opt.Backs3; } else if (pos == 2) { reps[0] = opt.Backs2; reps[1] = opt.Backs0; reps[2] = opt.Backs1; reps[3] = opt.Backs3; } else { reps[0] = opt.Backs3; reps[1] = opt.Backs0; reps[2] = opt.Backs1; reps[3] = opt.Backs2; } } else { reps[0] = (pos - Base.kNumRepDistances); reps[1] = opt.Backs0; reps[2] = opt.Backs1; reps[3] = opt.Backs2; } } _optimum[cur].State = state; _optimum[cur].Backs0 = reps[0]; _optimum[cur].Backs1 = reps[1]; _optimum[cur].Backs2 = reps[2]; _optimum[cur].Backs3 = reps[3]; int curPrice = _optimum[cur].Price; currentByte = _matchFinder.GetIndexByte(0 - 1); matchByte = _matchFinder.GetIndexByte(0 - reps[0] - 1 - 1); posState = (position & _posStateMask); int curAnd1Price = curPrice + SevenZip.Compression.RangeCoder.Encoder.GetPrice0(_isMatch[(state << Base.kNumPosStatesBitsMax) + posState]) + _literalEncoder.GetSubCoder(position, _matchFinder.GetIndexByte(0 - 2)). GetPrice(!Base.StateIsCharState(state), matchByte, currentByte); Optimal nextOptimum = _optimum[cur + 1]; boolean nextIsChar = false; if (curAnd1Price < nextOptimum.Price) { nextOptimum.Price = curAnd1Price; nextOptimum.PosPrev = cur; nextOptimum.MakeAsChar(); nextIsChar = true; } matchPrice = curPrice + SevenZip.Compression.RangeCoder.Encoder.GetPrice1(_isMatch[(state << Base.kNumPosStatesBitsMax) + posState]); repMatchPrice = matchPrice + SevenZip.Compression.RangeCoder.Encoder.GetPrice1(_isRep[state]); if (matchByte == currentByte && !(nextOptimum.PosPrev < cur && nextOptimum.BackPrev == 0)) { int shortRepPrice = repMatchPrice + GetRepLen1Price(state, posState); if (shortRepPrice <= nextOptimum.Price) { nextOptimum.Price = shortRepPrice; nextOptimum.PosPrev = cur; nextOptimum.MakeAsShortRep(); nextIsChar = true; } } int numAvailableBytesFull = _matchFinder.GetNumAvailableBytes() + 1; numAvailableBytesFull = Math.min(kNumOpts - 1 - cur, numAvailableBytesFull); numAvailableBytes = numAvailableBytesFull; if (numAvailableBytes < 2) continue; if (numAvailableBytes > _numFastBytes) numAvailableBytes = _numFastBytes; if (!nextIsChar && matchByte != currentByte) { // try Literal + rep0 int t = Math.min(numAvailableBytesFull - 1, _numFastBytes); int lenTest2 = _matchFinder.GetMatchLen(0, reps[0], t); if (lenTest2 >= 2) { int state2 = Base.StateUpdateChar(state); int posStateNext = (position + 1) & _posStateMask; int nextRepMatchPrice = curAnd1Price + SevenZip.Compression.RangeCoder.Encoder.GetPrice1(_isMatch[(state2 << Base.kNumPosStatesBitsMax) + posStateNext]) + SevenZip.Compression.RangeCoder.Encoder.GetPrice1(_isRep[state2]); { int offset = cur + 1 + lenTest2; while (lenEnd < offset) _optimum[++lenEnd].Price = kIfinityPrice; int curAndLenPrice = nextRepMatchPrice + GetRepPrice( 0, lenTest2, state2, posStateNext); Optimal optimum = _optimum[offset]; if (curAndLenPrice < optimum.Price) { optimum.Price = curAndLenPrice; optimum.PosPrev = cur + 1; optimum.BackPrev = 0; optimum.Prev1IsChar = true; optimum.Prev2 = false; } } } } int startLen = 2; // speed optimization for (int repIndex = 0; repIndex < Base.kNumRepDistances; repIndex++) { int lenTest = _matchFinder.GetMatchLen(0 - 1, reps[repIndex], numAvailableBytes); if (lenTest < 2) continue; int lenTestTemp = lenTest; do { while (lenEnd < cur + lenTest) _optimum[++lenEnd].Price = kIfinityPrice; int curAndLenPrice = repMatchPrice + GetRepPrice(repIndex, lenTest, state, posState); Optimal optimum = _optimum[cur + lenTest]; if (curAndLenPrice < optimum.Price) { optimum.Price = curAndLenPrice; optimum.PosPrev = cur; optimum.BackPrev = repIndex; optimum.Prev1IsChar = false; } } while (--lenTest >= 2); lenTest = lenTestTemp; if (repIndex == 0) startLen = lenTest + 1; // if (_maxMode) if (lenTest < numAvailableBytesFull) { int t = Math.min(numAvailableBytesFull - 1 - lenTest, _numFastBytes); int lenTest2 = _matchFinder.GetMatchLen(lenTest, reps[repIndex], t); if (lenTest2 >= 2) { int state2 = Base.StateUpdateRep(state); int posStateNext = (position + lenTest) & _posStateMask; int curAndLenCharPrice = repMatchPrice + GetRepPrice(repIndex, lenTest, state, posState) + SevenZip.Compression.RangeCoder.Encoder.GetPrice0(_isMatch[(state2 << Base.kNumPosStatesBitsMax) + posStateNext]) + _literalEncoder.GetSubCoder(position + lenTest, _matchFinder.GetIndexByte(lenTest - 1 - 1)).GetPrice(true, _matchFinder.GetIndexByte(lenTest - 1 - (reps[repIndex] + 1)), _matchFinder.GetIndexByte(lenTest - 1)); state2 = Base.StateUpdateChar(state2); posStateNext = (position + lenTest + 1) & _posStateMask; int nextMatchPrice = curAndLenCharPrice + SevenZip.Compression.RangeCoder.Encoder.GetPrice1(_isMatch[(state2 << Base.kNumPosStatesBitsMax) + posStateNext]); int nextRepMatchPrice = nextMatchPrice + SevenZip.Compression.RangeCoder.Encoder.GetPrice1(_isRep[state2]); // for(; lenTest2 >= 2; lenTest2--) { int offset = lenTest + 1 + lenTest2; while (lenEnd < cur + offset) _optimum[++lenEnd].Price = kIfinityPrice; int curAndLenPrice = nextRepMatchPrice + GetRepPrice(0, lenTest2, state2, posStateNext); Optimal optimum = _optimum[cur + offset]; if (curAndLenPrice < optimum.Price) { optimum.Price = curAndLenPrice; optimum.PosPrev = cur + lenTest + 1; optimum.BackPrev = 0; optimum.Prev1IsChar = true; optimum.Prev2 = true; optimum.PosPrev2 = cur; optimum.BackPrev2 = repIndex; } } } } } if (newLen > numAvailableBytes) { newLen = numAvailableBytes; for (numDistancePairs = 0; newLen > _matchDistances[numDistancePairs]; numDistancePairs += 2) ; _matchDistances[numDistancePairs] = newLen; numDistancePairs += 2; } if (newLen >= startLen) { normalMatchPrice = matchPrice + SevenZip.Compression.RangeCoder.Encoder.GetPrice0(_isRep[state]); while (lenEnd < cur + newLen) _optimum[++lenEnd].Price = kIfinityPrice; int offs = 0; while (startLen > _matchDistances[offs]) offs += 2; for (int lenTest = startLen; ; lenTest++) { int curBack = _matchDistances[offs + 1]; int curAndLenPrice = normalMatchPrice + GetPosLenPrice(curBack, lenTest, posState); Optimal optimum = _optimum[cur + lenTest]; if (curAndLenPrice < optimum.Price) { optimum.Price = curAndLenPrice; optimum.PosPrev = cur; optimum.BackPrev = curBack + Base.kNumRepDistances; optimum.Prev1IsChar = false; } if (lenTest == _matchDistances[offs]) { if (lenTest < numAvailableBytesFull) { int t = Math.min(numAvailableBytesFull - 1 - lenTest, _numFastBytes); int lenTest2 = _matchFinder.GetMatchLen(lenTest, curBack, t); if (lenTest2 >= 2) { int state2 = Base.StateUpdateMatch(state); int posStateNext = (position + lenTest) & _posStateMask; int curAndLenCharPrice = curAndLenPrice + SevenZip.Compression.RangeCoder.Encoder.GetPrice0(_isMatch[(state2 << Base.kNumPosStatesBitsMax) + posStateNext]) + _literalEncoder.GetSubCoder(position + lenTest, _matchFinder.GetIndexByte(lenTest - 1 - 1)). GetPrice(true, _matchFinder.GetIndexByte(lenTest - (curBack + 1) - 1), _matchFinder.GetIndexByte(lenTest - 1)); state2 = Base.StateUpdateChar(state2); posStateNext = (position + lenTest + 1) & _posStateMask; int nextMatchPrice = curAndLenCharPrice + SevenZip.Compression.RangeCoder.Encoder.GetPrice1(_isMatch[(state2 << Base.kNumPosStatesBitsMax) + posStateNext]); int nextRepMatchPrice = nextMatchPrice + SevenZip.Compression.RangeCoder.Encoder.GetPrice1(_isRep[state2]); int offset = lenTest + 1 + lenTest2; while (lenEnd < cur + offset) _optimum[++lenEnd].Price = kIfinityPrice; curAndLenPrice = nextRepMatchPrice + GetRepPrice(0, lenTest2, state2, posStateNext); optimum = _optimum[cur + offset]; if (curAndLenPrice < optimum.Price) { optimum.Price = curAndLenPrice; optimum.PosPrev = cur + lenTest + 1; optimum.BackPrev = 0; optimum.Prev1IsChar = true; optimum.Prev2 = true; optimum.PosPrev2 = cur; optimum.BackPrev2 = curBack + Base.kNumRepDistances; } } } offs += 2; if (offs == numDistancePairs) break; } } } } } boolean ChangePair(int smallDist, int bigDist) { int kDif = 7; return (smallDist < (1 << (32 - kDif)) && bigDist >= (smallDist << kDif)); } void WriteEndMarker(int posState) throws IOException { if (!_writeEndMark) return; _rangeEncoder.Encode(_isMatch, (_state << Base.kNumPosStatesBitsMax) + posState, 1); _rangeEncoder.Encode(_isRep, _state, 0); _state = Base.StateUpdateMatch(_state); int len = Base.kMatchMinLen; _lenEncoder.Encode(_rangeEncoder, len - Base.kMatchMinLen, posState); int posSlot = (1 << Base.kNumPosSlotBits) - 1; int lenToPosState = Base.GetLenToPosState(len); _posSlotEncoder[lenToPosState].Encode(_rangeEncoder, posSlot); int footerBits = 30; int posReduced = (1 << footerBits) - 1; _rangeEncoder.EncodeDirectBits(posReduced >> Base.kNumAlignBits, footerBits - Base.kNumAlignBits); _posAlignEncoder.ReverseEncode(_rangeEncoder, posReduced & Base.kAlignMask); } void Flush(int nowPos) throws IOException { ReleaseMFStream(); WriteEndMarker(nowPos & _posStateMask); _rangeEncoder.FlushData(); _rangeEncoder.FlushStream(); } public void CodeOneBlock(long[] inSize, long[] outSize, boolean[] finished) throws IOException { inSize[0] = 0; outSize[0] = 0; finished[0] = true; if (_inStream != null) { _matchFinder.SetStream(_inStream); _matchFinder.Init(); _needReleaseMFStream = true; _inStream = null; } if (_finished) return; _finished = true; long progressPosValuePrev = nowPos64; if (nowPos64 == 0) { if (_matchFinder.GetNumAvailableBytes() == 0) { Flush((int)nowPos64); return; } ReadMatchDistances(); int posState = (int)(nowPos64) & _posStateMask; _rangeEncoder.Encode(_isMatch, (_state << Base.kNumPosStatesBitsMax) + posState, 0); _state = Base.StateUpdateChar(_state); byte curByte = _matchFinder.GetIndexByte(0 - _additionalOffset); _literalEncoder.GetSubCoder((int)(nowPos64), _previousByte).Encode(_rangeEncoder, curByte); _previousByte = curByte; _additionalOffset--; nowPos64++; } if (_matchFinder.GetNumAvailableBytes() == 0) { Flush((int)nowPos64); return; } while (true) { int len = GetOptimum((int)nowPos64); int pos = backRes; int posState = ((int)nowPos64) & _posStateMask; int complexState = (_state << Base.kNumPosStatesBitsMax) + posState; if (len == 1 && pos == -1) { _rangeEncoder.Encode(_isMatch, complexState, 0); byte curByte = _matchFinder.GetIndexByte((int)(0 - _additionalOffset)); LiteralEncoder.Encoder2 subCoder = _literalEncoder.GetSubCoder((int)nowPos64, _previousByte); if (!Base.StateIsCharState(_state)) { byte matchByte = _matchFinder.GetIndexByte((int)(0 - _repDistances[0] - 1 - _additionalOffset)); subCoder.EncodeMatched(_rangeEncoder, matchByte, curByte); } else subCoder.Encode(_rangeEncoder, curByte); _previousByte = curByte; _state = Base.StateUpdateChar(_state); } else { _rangeEncoder.Encode(_isMatch, complexState, 1); if (pos < Base.kNumRepDistances) { _rangeEncoder.Encode(_isRep, _state, 1); if (pos == 0) { _rangeEncoder.Encode(_isRepG0, _state, 0); if (len == 1) _rangeEncoder.Encode(_isRep0Long, complexState, 0); else _rangeEncoder.Encode(_isRep0Long, complexState, 1); } else { _rangeEncoder.Encode(_isRepG0, _state, 1); if (pos == 1) _rangeEncoder.Encode(_isRepG1, _state, 0); else { _rangeEncoder.Encode(_isRepG1, _state, 1); _rangeEncoder.Encode(_isRepG2, _state, pos - 2); } } if (len == 1) _state = Base.StateUpdateShortRep(_state); else { _repMatchLenEncoder.Encode(_rangeEncoder, len - Base.kMatchMinLen, posState); _state = Base.StateUpdateRep(_state); } int distance = _repDistances[pos]; if (pos != 0) { for (int i = pos; i >= 1; i--) _repDistances[i] = _repDistances[i - 1]; _repDistances[0] = distance; } } else { _rangeEncoder.Encode(_isRep, _state, 0); _state = Base.StateUpdateMatch(_state); _lenEncoder.Encode(_rangeEncoder, len - Base.kMatchMinLen, posState); pos -= Base.kNumRepDistances; int posSlot = GetPosSlot(pos); int lenToPosState = Base.GetLenToPosState(len); _posSlotEncoder[lenToPosState].Encode(_rangeEncoder, posSlot); if (posSlot >= Base.kStartPosModelIndex) { int footerBits = (int)((posSlot >> 1) - 1); int baseVal = ((2 | (posSlot & 1)) << footerBits); int posReduced = pos - baseVal; if (posSlot < Base.kEndPosModelIndex) BitTreeEncoder.ReverseEncode(_posEncoders, baseVal - posSlot - 1, _rangeEncoder, footerBits, posReduced); else { _rangeEncoder.EncodeDirectBits(posReduced >> Base.kNumAlignBits, footerBits - Base.kNumAlignBits); _posAlignEncoder.ReverseEncode(_rangeEncoder, posReduced & Base.kAlignMask); _alignPriceCount++; } } int distance = pos; for (int i = Base.kNumRepDistances - 1; i >= 1; i--) _repDistances[i] = _repDistances[i - 1]; _repDistances[0] = distance; _matchPriceCount++; } _previousByte = _matchFinder.GetIndexByte(len - 1 - _additionalOffset); } _additionalOffset -= len; nowPos64 += len; if (_additionalOffset == 0) { // if (!_fastMode) if (_matchPriceCount >= (1 << 7)) FillDistancesPrices(); if (_alignPriceCount >= Base.kAlignTableSize) FillAlignPrices(); inSize[0] = nowPos64; outSize[0] = _rangeEncoder.GetProcessedSizeAdd(); if (_matchFinder.GetNumAvailableBytes() == 0) { Flush((int)nowPos64); return; } if (nowPos64 - progressPosValuePrev >= (1 << 12)) { _finished = false; finished[0] = false; return; } } } } void ReleaseMFStream() { if (_matchFinder != null && _needReleaseMFStream) { _matchFinder.ReleaseStream(); _needReleaseMFStream = false; } } void SetOutStream(java.io.OutputStream outStream) { _rangeEncoder.SetStream(outStream); } void ReleaseOutStream() { _rangeEncoder.ReleaseStream(); } void ReleaseStreams() { ReleaseMFStream(); ReleaseOutStream(); } void SetStreams(java.io.InputStream inStream, java.io.OutputStream outStream, long inSize, long outSize) { _inStream = inStream; _finished = false; Create(); SetOutStream(outStream); Init(); // if (!_fastMode) { FillDistancesPrices(); FillAlignPrices(); } _lenEncoder.SetTableSize(_numFastBytes + 1 - Base.kMatchMinLen); _lenEncoder.UpdateTables(1 << _posStateBits); _repMatchLenEncoder.SetTableSize(_numFastBytes + 1 - Base.kMatchMinLen); _repMatchLenEncoder.UpdateTables(1 << _posStateBits); nowPos64 = 0; } long[] processedInSize = new long[1]; long[] processedOutSize = new long[1]; boolean[] finished = new boolean[1]; public void Code(java.io.InputStream inStream, java.io.OutputStream outStream, long inSize, long outSize, ICodeProgress progress) throws IOException { _needReleaseMFStream = false; try { SetStreams(inStream, outStream, inSize, outSize); while (true) { CodeOneBlock(processedInSize, processedOutSize, finished); if (finished[0]) return; if (progress != null) { progress.SetProgress(processedInSize[0], processedOutSize[0]); } } } finally { ReleaseStreams(); } } public static final int kPropSize = 5; byte[] properties = new byte[kPropSize]; public void WriteCoderProperties(java.io.OutputStream outStream) throws IOException { properties[0] = (byte)((_posStateBits * 5 + _numLiteralPosStateBits) * 9 + _numLiteralContextBits); for (int i = 0; i < 4; i++) properties[1 + i] = (byte)(_dictionarySize >> (8 * i)); outStream.write(properties, 0, kPropSize); } int[] tempPrices = new int[Base.kNumFullDistances]; int _matchPriceCount; void FillDistancesPrices() { for (int i = Base.kStartPosModelIndex; i < Base.kNumFullDistances; i++) { int posSlot = GetPosSlot(i); int footerBits = (int)((posSlot >> 1) - 1); int baseVal = ((2 | (posSlot & 1)) << footerBits); tempPrices[i] = BitTreeEncoder.ReverseGetPrice(_posEncoders, baseVal - posSlot - 1, footerBits, i - baseVal); } for (int lenToPosState = 0; lenToPosState < Base.kNumLenToPosStates; lenToPosState++) { int posSlot; BitTreeEncoder encoder = _posSlotEncoder[lenToPosState]; int st = (lenToPosState << Base.kNumPosSlotBits); for (posSlot = 0; posSlot < _distTableSize; posSlot++) _posSlotPrices[st + posSlot] = encoder.GetPrice(posSlot); for (posSlot = Base.kEndPosModelIndex; posSlot < _distTableSize; posSlot++) _posSlotPrices[st + posSlot] += ((((posSlot >> 1) - 1) - Base.kNumAlignBits) << SevenZip.Compression.RangeCoder.Encoder.kNumBitPriceShiftBits); int st2 = lenToPosState * Base.kNumFullDistances; int i; for (i = 0; i < Base.kStartPosModelIndex; i++) _distancesPrices[st2 + i] = _posSlotPrices[st + i]; for (; i < Base.kNumFullDistances; i++) _distancesPrices[st2 + i] = _posSlotPrices[st + GetPosSlot(i)] + tempPrices[i]; } _matchPriceCount = 0; } void FillAlignPrices() { for (int i = 0; i < Base.kAlignTableSize; i++) _alignPrices[i] = _posAlignEncoder.ReverseGetPrice(i); _alignPriceCount = 0; } public boolean SetAlgorithm(int algorithm) { /* _fastMode = (algorithm == 0); _maxMode = (algorithm >= 2); */ return true; } public boolean SetDictionarySize(int dictionarySize) { int kDicLogSizeMaxCompress = 29; if (dictionarySize < (1 << Base.kDicLogSizeMin) || dictionarySize > (1 << kDicLogSizeMaxCompress)) return false; _dictionarySize = dictionarySize; int dicLogSize; for (dicLogSize = 0; dictionarySize > (1 << dicLogSize); dicLogSize++) ; _distTableSize = dicLogSize * 2; return true; } public boolean SetNumFastBytes(int numFastBytes) { if (numFastBytes < 5 || numFastBytes > Base.kMatchMaxLen) return false; _numFastBytes = numFastBytes; return true; } public boolean SetMatchFinder(int matchFinderIndex) { if (matchFinderIndex < 0 || matchFinderIndex > 2) return false; int matchFinderIndexPrev = _matchFinderType; _matchFinderType = matchFinderIndex; if (_matchFinder != null && matchFinderIndexPrev != _matchFinderType) { _dictionarySizePrev = -1; _matchFinder = null; } return true; } public boolean SetLcLpPb(int lc, int lp, int pb) { if ( lp < 0 || lp > Base.kNumLitPosStatesBitsEncodingMax || lc < 0 || lc > Base.kNumLitContextBitsMax || pb < 0 || pb > Base.kNumPosStatesBitsEncodingMax) return false; _numLiteralPosStateBits = lp; _numLiteralContextBits = lc; _posStateBits = pb; _posStateMask = ((1) << _posStateBits) - 1; return true; } public void SetEndMarkerMode(boolean endMarkerMode) { _writeEndMark = endMarkerMode; } }
40,845
27.825688
164
java
cobs
cobs-master/cobs/cobsScripts/RocOnBigTable.java
/** * Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu * * This code is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version, * provided that any use properly credits the author. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details at http://www.gnu.org * * */ package cobsScripts; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import utils.ConfigReader; /* Run WriteScores then AbsoluteScoreVsAverageDistance */ public class RocOnBigTable { public static void main(String[] args) throws Exception { for(String s: AbsoluteScoreVsAverageDistance.FILE_NAMES) { writeROC(s,true); writeROC(s, false); } System.out.println("All files completed."); } public static void writeROC(String fileSubString, boolean normalized) throws Exception { BufferedReader reader = new BufferedReader(new FileReader(new File( ConfigReader.getCleanroom() + File.separator + "bigSummaries" + File.separator + "big" + fileSubString + (normalized ? "normedLate" : "") + ".txt"))); File rocDir = new File(ConfigReader.getCleanroom() + File.separator + "roc" ); rocDir.mkdirs(); BufferedWriter writer = new BufferedWriter(new FileWriter( rocDir.getAbsolutePath() + File.separator + "_bigROC" + fileSubString +(normalized ? "normedLate" : "")+ "_" + ".txt")); int numBelow50=0; int numAbove50=0; writer.write("family\t" + "thisFamilyTotal\t" + "PerPFAMUnit" + fileSubString + "_prediction\t" + "PerPFAMUnit" + fileSubString + "_numBelow50\t" + "PerPFAMUnit" + fileSubString + "_numAbove50\t" + fileSubString + "_prediction\t" + fileSubString + "_numBelow50\t" + fileSubString + "_numAbove50\n"); reader.readLine(); //Looks like we need a re-usable List here List<String> theReadLines = new ArrayList<String>(); for(String s= reader.readLine(); s != null; s = reader.readLine()){ theReadLines.add(s); } //Hopefully you can do this twice with Reader! We will iterate through to get the PerPFAM counts necessary above //And create a HashMap of that Data for use later //With a HashMap of the below and a HashMap of the Above HashMap<String,Integer> pFAMtotalHits = new HashMap<String, Integer>(); HashMap<String,Integer> pFAMsubTotal = new HashMap<String, Integer>(); HashMap<String,Integer> pFAMabove = new HashMap<String, Integer>(); //This first read-through will create many "redundant" keys, but that won't be a problem, they have to be unique //for(String s : theReadLines.subList( 1, theReadLines.size() )) for(String s : theReadLines) { String[] splits = s.split("\t"); String family = (splits[0]); pFAMtotalHits.put(family, 0); pFAMsubTotal.put(family, 0); pFAMabove.put(family, 0); } //Now we will record the Total for(String s : theReadLines) { String[] splits = s.split("\t"); String family = (splits[0]); Integer currentTotal = pFAMtotalHits.get(family); currentTotal++; pFAMtotalHits.put(family, currentTotal); } for(String s : theReadLines) { String[] splits = s.split("\t"); String family = (splits[0]); //Now to track the running total Integer subTotal = pFAMsubTotal.get(family); subTotal++; pFAMsubTotal.put(family, subTotal); if( Double.parseDouble(splits[4]) < 50){ numBelow50++; } else{ numAbove50++; Integer perFamilyAbove = pFAMabove.get(family); perFamilyAbove++; pFAMabove.put(family,perFamilyAbove); } //Now to carry the family name (without proper parsing...but good enough...forward) writer.write(family + "\t"); //Now to always carry the total for the family through writer.write(pFAMtotalHits.get(family) + "\t"); //Now the three additional columns we require, one of which is "derived", which we use here as a sort of //check digit int targetPFAMhighWaterMark = pFAMsubTotal.get(family); writer.write(targetPFAMhighWaterMark + "\t"); int targetPFAMaboveCount = pFAMabove.get(family); writer.write(targetPFAMaboveCount + "\t"); int whatIsLeftForThisPFAMToAchieve = targetPFAMhighWaterMark - targetPFAMaboveCount; writer.write(whatIsLeftForThisPFAMToAchieve + "\t"); writer.write( (numBelow50 + numAbove50) + "\t" ); writer.write( numBelow50 + "\t" ); writer.write( numAbove50+ "\n" ); writer.flush(); } writer.flush(); writer.close(); reader.close(); } }
5,000
29.680982
115
java
cobs
cobs-master/cobs/cobsScripts/WriteOneDScores.java
/** * Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu * * This code is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version, * provided that any use properly credits the author. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details at http://www.gnu.org * * */ package cobsScripts; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.Date; import java.util.HashMap; import java.util.concurrent.Semaphore; import utils.ConfigReader; import covariance.algorithms.FileScoreGenerator; import covariance.algorithms.McBASCCovariance; import covariance.algorithms.ScoreGenerator; import covariance.datacontainers.Alignment; import covariance.parsers.PfamParser; import covariance.parsers.PfamToPDBBlastResults; public class WriteOneDScores { public static void main(String[] args) throws Exception { HashMap<String, PfamToPDBBlastResults> map = PfamToPDBBlastResults.getAsMap(); System.out.println(map.keySet()); Semaphore semaphore = new Semaphore(ConfigReader.getNumThreads()); PfamParser parser = new PfamParser(); for(Alignment a= parser.getNextAlignment(); a != null; a = parser.getNextAlignment()) { System.out.println("Trying " + a.getAligmentID()); PfamToPDBBlastResults toPdb = map.get(a.getAligmentID()); if( toPdb != null) { // McBASC is all we really need to cache; the other algorithms are fast enough //kickOneOffIfFileDoesNotExist(semaphore, a, new ConservationSum(a)); //kickOneOffIfFileDoesNotExist(semaphore, a, new MICovariance(a)); //kickOneOffIfFileDoesNotExist(semaphore, a, new RandomScore()); kickOneOffIfFileDoesNotExist(semaphore, a, new McBASCCovariance(a)); } } } /* * The syncrhonized is just to force all threads to the most up-to-date view of the data */ private static synchronized void kickOneOffIfFileDoesNotExist(Semaphore semaphore, Alignment a, ScoreGenerator sg) throws Exception { System.out.println("Trying " + a.getAligmentID()); File outFile = getOutputFile(a, sg); if( outFile.exists()) { FileScoreGenerator fsg = new FileScoreGenerator("foo", outFile, a); int expectedNum = a.getNumColumnsInAlignment() * (a.getNumColumnsInAlignment()-1) / 2; if( fsg.getNumScores() != expectedNum) { System.out.println(outFile.getAbsolutePath() +" truncated. Deleting"); outFile.delete(); if( outFile.exists()) throw new Exception("Could not delete " + outFile.getPath()); } } if(! outFile.exists()) { semaphore.acquire(); Worker w = new Worker(a,sg, semaphore); new Thread(w).start(); } else { Date date = new Date(); String stringDate = date.toString(); System.out.println(outFile.getAbsolutePath() + "exists. skipping at " + stringDate); } } private static File getOutputFile(Alignment a, ScoreGenerator sg) throws Exception { File resultsDir =new File( ConfigReader.getCleanroom() + File.separator + "results" + File.separator + "oneD" ); resultsDir.mkdirs(); return new File( resultsDir.getAbsolutePath() + File.separator + a.getAligmentID() + "_" + sg.getAnalysisName() + ".txt"); } private static class Worker implements Runnable { private final Alignment a; private final Semaphore semaphore; private final ScoreGenerator sg; private Worker(Alignment a, ScoreGenerator sg, Semaphore semaphore) { this.a = a; this.semaphore = semaphore; this.sg = sg; } public void run() { //So that we ALWAYS have something to close BufferedWriter writer = null; try { File outputFile = getOutputFile(a, sg); if(outputFile.exists()) throw new Exception(outputFile.getAbsolutePath() + " already exists "); writer = new BufferedWriter(new FileWriter(outputFile)); writer.write("i\tj\tscore\n"); System.out.println(a.getAligmentID()); for( int x=0; x < a.getNumColumnsInAlignment() -1; x++) for( int y=x+1; y < a.getNumColumnsInAlignment(); y++) { writer.write(x + "\t" + y + "\t" + sg.getScore(a, x, y) + "\n"); } writer.flush(); writer.close(); System.out.println("Finished " + a.getAligmentID() + "_" + sg.getAnalysisName()); semaphore.release(); } catch(Exception ex) { ex.printStackTrace(); System.exit(1); } } } }
4,767
27.380952
97
java
cobs
cobs-master/cobs/cobsScripts/AbsoluteScoreVsAverageDistance.java
/** * Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu * * This code is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version, * provided that any use properly credits the author. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details at http://www.gnu.org * * */ package cobsScripts; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import utils.ConfigReader; public class AbsoluteScoreVsAverageDistance { private static final class ListData { double medianDistance; double listSize; } //Here is what I saw from actual output // AverageAbsMcBASC_PNormalInitial // AverageAbsMcBASC // AverageConservationSum_PNormalInitial // AverageConservationSum // AverageMcBASC_PNormalInitial // AverageMcBASC // AverageMI_PNormalInitial // AverageMI // Averagerandom // COBS_UNCORRECTED public static final String[] FILE_NAMES = { "AverageAbsMcBASC", "AverageAbsMcBASC_PNormalInitial", "AverageMcBASC_PNormalInitial", "AverageMcBASC", "COBS_UNCORRECTED", "Averagerandom", "AverageConservationSum_PNormalInitial", "AverageConservationSum", "AverageMI_PNormalInitial", "AverageMI" }; public static void main(String[] args) throws Exception { for(String s : FILE_NAMES) { writeASummaryFile(s,true); writeASummaryFile(s,false); } } public static void writeASummaryFile(String fileSubString, boolean normalized) throws Exception { HashMap<String, ListData> mapOfFiles = new HashMap<String, AbsoluteScoreVsAverageDistance.ListData>(); List<ResultsFileLine> bigList = getCombinedList(mapOfFiles, fileSubString,normalized); Collections.sort(bigList, new ResultsFileLine.SortByScore()); File bigSummariesDir = new File(ConfigReader.getCleanroom() + File.separator + "bigSummaries" ); bigSummariesDir.mkdirs(); BufferedWriter writer = new BufferedWriter(new FileWriter(bigSummariesDir + File.separator + File.separator + "big" + fileSubString + (normalized ? "normedLate" : "") +".txt")); writer.write("family\tscore\tregion1\tregion2\tpercentile\tavgDistance\ttype\tlistSize\tmedianDistance\n"); for( ResultsFileLine rfl : bigList) { writer.write(rfl.getParentFileName() + "\t"); writer.write(rfl.getScore() + "\t"); writer.write(rfl.getRegion1() + "\t"); writer.write(rfl.getRegion2() + "\t"); writer.write(rfl.getPercentile() + "\t"); writer.write(rfl.getAverageDistance() + "\t"); writer.write(rfl.getCombinedType() + "\t"); //Debug only //System.out.println("Find " + rfl.getParentFileName()); ListData listData = mapOfFiles.get(rfl.getParentFileName()); writer.write(listData.listSize + "\t"); writer.write(listData.medianDistance + "\n"); writer.flush(); } writer.flush(); writer.close(); } public static List<ResultsFileLine> getCombinedList(HashMap<String, ListData> mapOfFiles, String fileSubString, boolean normalized) throws Exception { List<ResultsFileLine> bigList = new ArrayList<ResultsFileLine>(); File dataDir = new File(ConfigReader.getCleanroom() + File.separator + "results"); String[] files = dataDir.list(); int numDone =0; for(String s : files) { if(s.contains(fileSubString + ".")) { //Debug only System.out.println(s); File fileToRead = new File(dataDir.getAbsolutePath() + File.separator + s); List<ResultsFileLine> innerList= ResultsFileLine.parseResultsFile(fileToRead); if(normalized) innerList= ResultsFileLine.getNormalizedList(innerList); if( innerList.size() > 3) { ListData ld = new ListData(); ld.listSize = innerList.size(); ld.medianDistance = ResultsFileLine.getMedianAverageDistance(innerList); numDone++; // list is sorted by call to getMedianAverageDistance(...) for(int x=0;x < innerList.size(); x++) { if (x == (innerList.size() -1 )){ innerList.get(x).setPercentile(100.0); } else { innerList.get(x).setPercentile(100.0 * x / innerList.size()); } } mapOfFiles.put(s, ld); System.out.println(s + " " + innerList.get(0).getParentFileName()); bigList.addAll(innerList); } } } System.out.println("GOT " + numDone); return bigList; } }
4,767
27.722892
112
java
cobs
cobs-master/cobs/cobsScripts/WriteScores.java
/** * Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu * * This code is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version, * provided that any use properly credits the author. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details at http://www.gnu.org * * */ package cobsScripts; import gocAlgorithms.AverageScoreGenerator; import gocAlgorithms.COBS; import gocAlgorithms.GroupOfColumnsInterface; import gocAlgorithms.HelixSheetGroup; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.concurrent.Semaphore; import java.util.zip.GZIPOutputStream; import utils.ConfigReader; import utils.MapResiduesToIndex; import covariance.algorithms.AbsoluteValueFileScoreGenerator; import covariance.algorithms.ConservationSum; import covariance.algorithms.FileScoreGenerator; import covariance.algorithms.MICovariance; import covariance.algorithms.McBASCCovariance; import covariance.algorithms.PNormalize; import covariance.algorithms.RandomScore; import covariance.datacontainers.Alignment; import covariance.datacontainers.AlignmentLine; import covariance.datacontainers.PdbFileWrapper; import covariance.datacontainers.PdbResidue; import covariance.parsers.PfamParser; import covariance.parsers.PfamToPDBBlastResults; import dynamicProgramming.MaxhomSubstitutionMatrix; import dynamicProgramming.NeedlemanWunsch; import dynamicProgramming.PairedAlignment; public class WriteScores { public static final int MIN_PDB_LENGTH = 80; public static MaxhomSubstitutionMatrix substitutionMatrix; static { try { substitutionMatrix = new MaxhomSubstitutionMatrix(); } catch(Exception ex) { ex.printStackTrace(); System.exit(1); } } private static File getOneDFileName(Alignment a, String type) throws Exception { File file = new File(ConfigReader.getCleanroom() + File.separator + "results" + File.separator + "oneD" + File.separator + a.getAligmentID() + "_" + type+ ".txt"); if( ! file.exists()) { file = new File(ConfigReader.getCleanroom() + File.separator + "results" + File.separator + "oneD" + File.separator + a.getAligmentID() + "_" + type + ".txt.gz"); } return file; } private static FileScoreGenerator getOneDFileOrNull(Alignment a, String type) throws Exception { File file = getOneDFileName(a, type); if (! file.exists()) { System.out.println("Could not find " + file.getAbsolutePath()); return null; } FileScoreGenerator fsg = new FileScoreGenerator(type, file, a); if( a.getNumColumnsInAlignment() * (a.getNumColumnsInAlignment()-1) / 2 != fsg.getNumScores() ) { System.out.println("Truncated " + file.getAbsolutePath()); return null; } return fsg; } private static AbsoluteValueFileScoreGenerator getAbsoluteOneDFileOrNull( Alignment a, String type) throws Exception { File file = getOneDFileName(a, type); if (! file.exists()) { System.out.println("Could not find " + file.getAbsolutePath()); return null; } AbsoluteValueFileScoreGenerator fsg = new AbsoluteValueFileScoreGenerator(type, file, a); if( a.getNumColumnsInAlignment() * (a.getNumColumnsInAlignment()-1) / 2 != fsg.getNumScores() ) { System.out.println("Truncated " + file.getAbsolutePath()); return null; } return fsg; } public static void main(String[] args) throws Exception { HashMap<String, PfamToPDBBlastResults> pfamToPdbmap = PfamToPDBBlastResults.getAsMap(); System.out.println(pfamToPdbmap.keySet()); int numThreads = ConfigReader.getNumThreads(); Semaphore semaphore = new Semaphore(numThreads); PfamParser parser = new PfamParser(); for(Alignment a= parser.getNextAlignment(); a != null; a = parser.getNextAlignment()) { PfamToPDBBlastResults toPdb = pfamToPdbmap.get(a.getAligmentID()); System.out.println("Trying " + a.getAligmentID()); if( toPdb != null ) { FileScoreGenerator mcbascFSG = getOneDFileOrNull(a, McBASCCovariance.MCBASC_ANALYSIS); if( mcbascFSG != null) { System.out.println("Starting " + a.getAligmentID()); kickOneOffIfFileDoesNotExist(semaphore, a, toPdb, new AverageScoreGenerator(mcbascFSG)); kickOneOffIfFileDoesNotExist(semaphore, a, toPdb, new COBS()); kickOneOffIfFileDoesNotExist(semaphore, a, toPdb, new AverageScoreGenerator(new RandomScore("random",a))); kickOneOffIfFileDoesNotExist(semaphore, a, toPdb, new AverageScoreGenerator(new PNormalize(new MICovariance(a)))); kickOneOffIfFileDoesNotExist(semaphore, a, toPdb, new AverageScoreGenerator(new MICovariance(a))); kickOneOffIfFileDoesNotExist(semaphore, a, toPdb, new AverageScoreGenerator(new ConservationSum(a))); kickOneOffIfFileDoesNotExist(semaphore, a, toPdb, new AverageScoreGenerator(new PNormalize(new ConservationSum(a)))); kickOneOffIfFileDoesNotExist(semaphore, a, toPdb, new AverageScoreGenerator( new PNormalize(mcbascFSG))); // check to see if taking the absolute value of McBASC makes a difference kickOneOffIfFileDoesNotExist(semaphore, a, toPdb, new AverageScoreGenerator( getAbsoluteOneDFileOrNull(a, McBASCCovariance.MCBASC_ANALYSIS))); kickOneOffIfFileDoesNotExist(semaphore, a, toPdb, new AverageScoreGenerator( new PNormalize(getAbsoluteOneDFileOrNull(a, McBASCCovariance.MCBASC_ANALYSIS)))); } else { System.out.println("Skipping " + a.getAligmentID()); } } } while( numThreads > 0) { semaphore.acquire(); numThreads--; } System.out.println("Finished"); } /* * The syncrhonized is just to force all threads to the most up-to-date view of the data */ private static synchronized void kickOneOffIfFileDoesNotExist(Semaphore semaphore, Alignment a, PfamToPDBBlastResults toPdb, GroupOfColumnsInterface gci) throws Exception { File outFile = getOutputFile(a, gci); if(! outFile.exists()) { semaphore.acquire(); Worker w = new Worker(a,toPdb,gci, semaphore); new Thread(w).start(); } else { Date date = new Date(); String stringDate = date.toString(); System.out.println(outFile.getAbsolutePath() + "exists. skipping at " + stringDate); } } private static File getOutputFile(Alignment a, GroupOfColumnsInterface gci) throws Exception { File directory = new File( ConfigReader.getCleanroom() + File.separator + "results"); directory.mkdirs(); return new File( directory.getAbsolutePath() + File.separator + a.getAligmentID() + "__" + gci.getName() + ".txt" + (ConfigReader.writeZippedResults() ? ".gz" : "") ); } private static class Worker implements Runnable { private final Alignment a; private final PfamToPDBBlastResults toPDB; private final GroupOfColumnsInterface gci; private final Semaphore semaphore; private Worker(Alignment a, PfamToPDBBlastResults toPDB, GroupOfColumnsInterface gci, Semaphore semaphore) { this.a = a; this.toPDB = toPDB; this.gci = gci; this.semaphore = semaphore; } public void run() { try { PdbFileWrapper fileWrapper = new PdbFileWrapper( new File( ConfigReader.getPdbDir() + File.separator + toPDB.getPdbID() + ".txt")); HashMap<Integer, Integer> pdbToAlignmentNumberMap= getPdbToAlignmentNumberMap(a, toPDB, fileWrapper); File outputFile = getOutputFile(a, gci); if(outputFile.exists()) throw new Exception(outputFile.getAbsolutePath() + " already exists "); BufferedWriter writer = ConfigReader.writeZippedResults() ? new BufferedWriter(new OutputStreamWriter( new GZIPOutputStream( new FileOutputStream( outputFile )))) : new BufferedWriter(new FileWriter(outputFile)); writer.write("region1\tregion2\tcombinedType\tscore\taverageDistance\tminDistance\n"); writer.flush(); System.out.println(a.getAligmentID()); List<HelixSheetGroup> helixSheetGroup= HelixSheetGroup.getList(ConfigReader.getPdbDir() + File.separator + toPDB.getPdbID() + ".txt", toPDB.getChainId(), toPDB.getPdbStart(), toPDB.getPdbEnd()); System.out.println(helixSheetGroup); for(HelixSheetGroup hsg : helixSheetGroup) { System.out.println( hsg.getStartPos() + "-" + hsg.getEndPos() + " " + pdbToAlignmentNumberMap.get(hsg.getStartPos()) + "-" + pdbToAlignmentNumberMap.get(hsg.getEndPos())); } for(int x=0; x< helixSheetGroup.size() -1; x++) { HelixSheetGroup xHSG = helixSheetGroup.get(x); for( int y=x+1; y < helixSheetGroup.size(); y++) { HelixSheetGroup yHSG = helixSheetGroup.get(y); writer.write(xHSG.toString() + "\t"); writer.write(yHSG.toString() + "\t"); List<String> aList = new ArrayList<String>(); aList.add(xHSG.getElement()); aList.add(yHSG.getElement()); Collections.sort(aList); writer.write(aList.get(0) + "_TO_" + aList.get(1) + "\t"); double score = gci.getScore(a, pdbToAlignmentNumberMap.get(xHSG.getStartPos()), pdbToAlignmentNumberMap.get(xHSG.getEndPos()), pdbToAlignmentNumberMap.get(yHSG.getStartPos()), pdbToAlignmentNumberMap.get(yHSG.getEndPos())); writer.write(score+ "\t"); double distance = getAverageDistance(fileWrapper, xHSG, yHSG, toPDB.getChainId()); writer.write(distance + "\t"); double minDistance = getMinDistance(fileWrapper, xHSG, yHSG, toPDB.getChainId()); writer.write(minDistance + "\n"); writer.flush(); } } writer.flush(); writer.close(); Date date = new Date(); String stringDate = date.toString(); System.out.println("Finished " + a.getAligmentID() + "_" + gci.getName() + " at " + stringDate); } catch(Exception ex) { ex.printStackTrace(); // todo: Once all the bugs are out put the hard exit back in! //System.exit(1); } finally { semaphore.release(); } } } private static double getAverageDistance( PdbFileWrapper wrapper, HelixSheetGroup xGroup, HelixSheetGroup yGroup, char chain ) throws Exception { double n=0; double sum=0; for( int x=xGroup.getStartPos(); x <= xGroup.getEndPos(); x++ ) { PdbResidue xResidue = wrapper.getChain(chain).getPdbResidueByPdbPosition(x); if( xResidue == null || xResidue.getCbAtom() == null) { //Too verbose -- debug only use System.out.println("WARNING: " + wrapper.getFourCharId() + " " + chain + " " + x); } else { for( int y= yGroup.getStartPos(); y <= yGroup.getEndPos(); y++) { PdbResidue yResidue = wrapper.getChain(chain).getPdbResidueByPdbPosition(y); if( yResidue == null || yResidue.getCbAtom() == null) { //Too verbose -- debug only use //System.out.println("WARNING: NO " + wrapper.getFourCharId() + " " + chain + " " + y); } else { sum += xResidue.getCbAtom().getDistance(yResidue.getCbAtom()); n++; } } } } return sum / n; } private static double getMinDistance( PdbFileWrapper wrapper, HelixSheetGroup xGroup, HelixSheetGroup yGroup, char chain ) throws Exception { double val = Double.MAX_VALUE; for( int x=xGroup.getStartPos(); x <= xGroup.getEndPos(); x++ ) { PdbResidue xResidue = wrapper.getChain(chain).getPdbResidueByPdbPosition(x); if( xResidue == null || xResidue.getCbAtom() == null ){ //Too verbose -- debug only use //System.out.println("WARNING: No " + wrapper.getFourCharId() + " " + chain + " " + x); } else { for( int y= yGroup.getStartPos(); y <= yGroup.getEndPos(); y++) { PdbResidue yResidue = wrapper.getChain(chain).getPdbResidueByPdbPosition(y); if( yResidue == null || yResidue.getCbAtom() == null) { //Too verbose, removed //System.out.println("WARNING: NO " + wrapper.getFourCharId() + " " + chain + " " + y); } else { val = Math.min(xResidue.getCbAtom().getDistance(yResidue.getCbAtom()), val); } } } } return val; } public static double getFractionIdentity(String pdbString, String pfamString) throws Exception { double num =0; double numMatch=0; for( int x=0; x < pdbString.length(); x++) { char c = pdbString.charAt(x); if ( c != '-') { num++; if( c == pfamString.charAt(x)) numMatch++; } } return numMatch / num; } public static HashMap<Integer, Integer> getPdbToAlignmentNumberMap( Alignment a, PfamToPDBBlastResults toPDB, PdbFileWrapper fileWrapper) throws Exception { HashMap<Integer, Integer> map = new LinkedHashMap<Integer, Integer>(); AlignmentLine aLine = a.getAnAlignmentLine( toPDB.getPfamLine() ); String pFamSeq = aLine.getSequence().toUpperCase(); HashMap<Integer, Integer> ungappedPfamToGappedPfamMap = new LinkedHashMap<Integer, Integer>(); StringBuffer ungappedPfam = new StringBuffer(); int ungappedPosition =-1; for( int x=0; x< pFamSeq.length(); x++) { char c = pFamSeq.charAt(x); if( MapResiduesToIndex.isValidResidueChar(c) ) { ungappedPfam.append(c); ungappedPosition++; ungappedPfamToGappedPfamMap.put(ungappedPosition, x); } } System.out.println(toPDB.getPdbID()+ " " + toPDB.getChainId() + " " + toPDB.getPdbStart() + " "+ toPDB.getPdbEnd()); System.out.println(fileWrapper.getChain(toPDB.getChainId()).getSequence()); System.out.println(fileWrapper.getChain(toPDB.getChainId()).getSequence().length()); String pdbSeq = fileWrapper.getChain(toPDB.getChainId()).getSequence().substring(toPDB.getPdbStart()-1, toPDB.getPdbEnd()); pdbSeq = pdbSeq.toUpperCase(); PairedAlignment pa = NeedlemanWunsch.globalAlignTwoSequences( pdbSeq, ungappedPfam.toString(), substitutionMatrix, -3, 0, false); System.out.println(pa.getFirstSequence()); System.out.println(pa.getSecondSequence()); double fractionMatch = getFractionIdentity(pa.getFirstSequence(), pa.getSecondSequence()); //System.out.println("fractionMatch = " + fractionMatch); if( fractionMatch < 0.9) { throw new Exception("Alignment failure\n" + pa.getFirstSequence() + "\n" + pa.getSecondSequence() + "\n" + fractionMatch + "\n\n" ); } int x=-1; int alignmentPos =-1; int pdbNumber = toPDB.getPdbStart() -1; while(pdbNumber < toPDB.getPdbEnd()) { x++; if( pa.getSecondSequence().charAt(x) != '-') alignmentPos++; if( pa.getFirstSequence().charAt(x) != '-' ) { pdbNumber++; map.put(pdbNumber,ungappedPfamToGappedPfamMap.get(alignmentPos)); } } double num=0; double numMatch =0; StringBuffer out = new StringBuffer(); for(Integer pdbNum : map.keySet()) { num++; char pdbChar = pdbSeq.charAt(pdbNum- toPDB.getPdbStart()); char pfamChar = pFamSeq.charAt(map.get(pdbNum)); if( pdbChar == pfamChar) numMatch++; out.append(pdbNum + "\t" + pdbChar + "\t" + map.get(pdbNum) + "\t" + pfamChar + "\n"); } double postAlignmentMatch = numMatch / num; //System.out.println("Post alignment match = " + postAlignmentMatch); if( postAlignmentMatch <0.9) throw new Exception("Alignment failure\n" + postAlignmentMatch + "\n" + out + "\n\n"); return map; } }
16,229
28.296029
135
java
cobs
cobs-master/cobs/cobsScripts/ResultsFileLine.java
/** * Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu * * This code is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version, * provided that any use properly credits the author. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details at http://www.gnu.org * * */ package cobsScripts; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.StringTokenizer; import java.util.zip.GZIPInputStream; import utils.Avevar; public final class ResultsFileLine { //region1 region2 combinedType score averageDistance minDistance private final String parentFileName; private final String region1; private final String region2; private final String combinedType; private final double score; private final double averageDistance; private final double minDistance; private double percentile; public ResultsFileLine(ResultsFileLine oldLine, double newScore) { this.parentFileName = oldLine.parentFileName; this.region1 = oldLine.region1; this.region2 = oldLine.region2; this.combinedType = oldLine.combinedType; this.score = newScore; this.averageDistance = oldLine.averageDistance; this.minDistance = oldLine.minDistance; } public double getPercentile() { return percentile; } public void setPercentile(double percentile) { this.percentile = percentile; } public String getParentFileName() { return parentFileName; } public String getRegion1() { return region1; } public String getRegion2() { return region2; } public String getCombinedType() { return combinedType; } public double getScore() { return score; } public double getAverageDistance() { return averageDistance; } public double getMinDistance() { return minDistance; } private static class RegionParser { char chainStart; char chainEnd; int start; int stop; String originalString; @Override public String toString() { return originalString; } public RegionParser(String s) throws Exception { originalString = s; s= s.substring(s.indexOf(":") + 1); chainStart = s.charAt(0); s=s.substring(1); start = Integer.parseInt(new StringTokenizer(s,"-").nextToken()); s = s.substring(s.indexOf("-")+1); chainEnd = s.charAt(0); if( chainStart != chainEnd) throw new Exception("No " + chainStart + " " + chainEnd); s =s.substring(1); stop= Integer.parseInt(s); } } public static final class SortByAverageDistance implements Comparator<ResultsFileLine> { @Override public int compare(ResultsFileLine arg0, ResultsFileLine arg1) { return Double.compare(arg0.getAverageDistance(), arg1.getAverageDistance()); } } public static final class SortByScore implements Comparator<ResultsFileLine> { @Override public int compare(ResultsFileLine arg0, ResultsFileLine arg1) { return Double.compare(arg1.getScore(), arg0.getScore()); } } /* * As a side effect, sorts the list by average distance */ public static final double getMedianAverageDistance(List<ResultsFileLine> list) { Collections.sort(list, new SortByAverageDistance()); if(list.size() % 2 == 1) return list.get(list.size()/2).getAverageDistance(); return (list.get(list.size()/2 -1).getAverageDistance() + list.get(list.size()/2).getAverageDistance()) / 2.0; } public static List<ResultsFileLine> getNormalizedList(List<ResultsFileLine> inList) throws Exception { List<ResultsFileLine> returnList = new ArrayList<ResultsFileLine>(); HashMap<String, Double> colAverages = breakByColumn(inList); double sum =0; int n =0; for( ResultsFileLine rfl : inList ) { if( ! Double.isInfinite(rfl.score) && ! Double.isNaN(rfl.score) ) { sum += rfl.score; n++; } } double average = sum / n; for( ResultsFileLine rfl : inList) { double newScore = rfl.getScore() - colAverages.get(rfl.region1) * colAverages.get(rfl.region2) / average; if( ! Double.isInfinite(newScore) && ! Double.isNaN(newScore) ) returnList.add(new ResultsFileLine(rfl,newScore)); } return returnList; } /* * Made public for testing */ public static HashMap<String, Double> breakByColumn(List<ResultsFileLine> list) throws Exception { HashMap<String, List<Double>> map = new HashMap<String, List<Double>>(); for(ResultsFileLine rsf : list) { putIntoMap(rsf.region1, rsf.score , map); putIntoMap(rsf.region2, rsf.score, map); } HashMap<String, Double> returnMap = new HashMap<String, Double>(); for(String s: map.keySet()) returnMap.put(s, new Avevar(map.get(s)).getAve()); return returnMap; } private static void putIntoMap(String key, double aDoub, HashMap<String, List<Double>> map) throws Exception { List<Double> list = map.get(key); if( list == null) { list= new ArrayList<Double>(); map.put(key,list); } if( ! Double.isInfinite(aDoub) && ! Double.isNaN(aDoub) ) list.add(aDoub); } public ResultsFileLine(String s, String fileName) throws Exception { StringTokenizer sToken = new StringTokenizer(s, "\t"); //System.out.println("Now parsing file: " + fileName); this.parentFileName = fileName; this.region1 = new String( sToken.nextToken()); this.region2 = new String( sToken.nextToken()); this.combinedType = new String( sToken.nextToken()); this.score = Double.parseDouble(sToken.nextToken()); this.averageDistance = Double.parseDouble(sToken.nextToken()); this.minDistance = Double.parseDouble(sToken.nextToken()); if( sToken.hasMoreTokens()) throw new Exception("No"); } public String getRegionKey() { List<String> list = new ArrayList<String>(); list.add(this.region1); list.add(this.region2); Collections.sort(list); return list.get(0) + "@" + list.get(1); } public boolean twoRegionsAreEqual() { return this.region1.equals(region2); } /* * A region can be an exact match or not in the set. * But if it overlaps with a known region it is not ok. * * */ private static boolean isOkForRegionSet( HashSet<String> regionSet, ResultsFileLine rfl) throws Exception { if(regionSet.contains(rfl.region1) && regionSet.contains(rfl.region2)) return true; RegionParser rp1 = new RegionParser(rfl.region1); for( String r : regionSet ) if( overlaps( new RegionParser(r), rp1)) return false; regionSet.add(rfl.region1); RegionParser rp2 = new RegionParser(rfl.region2); for( String r : regionSet ) if( overlaps( new RegionParser(r), rp2)) return false; regionSet.add(rfl.region2); return true; } private static boolean overlaps(RegionParser rp1, RegionParser rp2) { if(rp1.originalString.equals(rp2.originalString)) return false; if( rp1.chainEnd != rp2.chainEnd) return false; if( rp1.chainStart != rp2.chainStart) return false; if( rp1.start >= rp2.start && rp1.start <= rp2.stop ) { System.out.println("Removing "+ rp1.toString() + " from " + rp2.toString()); System.out.println(rp1.start + " " + rp1.stop + " " + rp2.start + " " + rp2.stop); return true; } if( rp1.stop >= rp2.start && rp1.stop <= rp2.stop ) { System.out.println("Removing "+ rp1.toString() + " from " + rp2.toString()); System.out.println(rp1.start + " " + rp1.stop + " " + rp2.start + " " + rp2.stop); return true; } return false; } public static List<ResultsFileLine> parseResultsFile(String filePath) throws Exception { return parseResultsFile(new File(filePath)); } public static List<ResultsFileLine> parseResultsFile(File file) throws Exception { List<ResultsFileLine> list = new ArrayList<ResultsFileLine>(); BufferedReader reader = file.getName().toLowerCase().endsWith("gz") ? new BufferedReader(new InputStreamReader( new GZIPInputStream( new FileInputStream( file )))) : new BufferedReader(new FileReader(file)); reader.readLine(); HashSet<String> done = new HashSet<String>(); HashSet<String> regionSet = new HashSet<String>(); for(String s= reader.readLine(); s != null; s = reader.readLine()) { ResultsFileLine rfl = new ResultsFileLine(s, file.getName()); String key = rfl.getRegionKey(); if( ! rfl.twoRegionsAreEqual() && ! done.contains(key) && isOkForRegionSet(regionSet,rfl)) { done.add(key); list.add(rfl); } } reader.close(); return list; } }
9,016
23.84022
112
java
cobs
cobs-master/cobs/dynamicProgramming/PairedAlignment.java
/** * Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu * * This code is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version, * provided that any use properly credits the author. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details at http://www.gnu.org * * */ package dynamicProgramming; public interface PairedAlignment { public String getFirstSequence(); public String getSecondSequence(); public float getAlignmentScore(); }
818
34.608696
74
java
cobs
cobs-master/cobs/dynamicProgramming/SubstitutionMatrix.java
/** * Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu * * This code is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version, * provided that any use properly credits the author. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details at http://www.gnu.org * * */ package dynamicProgramming; public interface SubstitutionMatrix { public float getScore( char c1, char c2) throws Exception; public String getSubstitutionMatrixName(); }
815
36.090909
74
java
cobs
cobs-master/cobs/dynamicProgramming/MaxhomSubstitutionMatrix.java
/** * Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu * * This code is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version, * provided that any use properly credits the author. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details at http://www.gnu.org * * */ package dynamicProgramming; import utils.MapResiduesToIndex; import covariance.algorithms.McBASCCovariance; public class MaxhomSubstitutionMatrix implements SubstitutionMatrix { private final int[][] matrix; public MaxhomSubstitutionMatrix() throws Exception { this.matrix = McBASCCovariance.getMaxhomMetric(); } @Override public float getScore(char c1, char c2) throws Exception { int index1 = MapResiduesToIndex.getIndexOrNegativeOne(c1); if( index1 != -1) { int index2 = MapResiduesToIndex.getIndexOrNegativeOne(c2); if( index2 != -1) return this.matrix[index1][index2]; } return 0; } @Override public String getSubstitutionMatrixName() { return "Maxhom"; } }
1,359
25.666667
74
java
cobs
cobs-master/cobs/dynamicProgramming/NeedlemanWunsch.java
/** * Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu * * This code is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version, * provided that any use properly credits the author. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details at http://www.gnu.org * * */ package dynamicProgramming; public class NeedlemanWunsch { private static final int UP = 1; private static final int LEFT = 2; private static final int DIAG =3; private static final int START = 4; private static class AlignmentCell { int direction; float score; public AlignmentCell(float score) { this.score = score; } public AlignmentCell(int direction, float score) { this.direction = direction; this.score = score; } } /* * * * GapPenalty should be <=0 * * Set affinePenalty to positive to use linear gap penalty. * Otherwise affinePenalty should be negative * * */ public static PairedAlignment globalAlignTwoSequences(String s1, String s2, SubstitutionMatrix sm, int gapPenalty, int affinePenalty, boolean noPenaltyForBeginningOrEndingGaps ) throws Exception { if( gapPenalty > 0 ) throw new Exception("Gap penalty should be zero or negative"); AlignmentCell[][] cels = new AlignmentCell[s1.length()+1][s2.length()+1]; //System.out.println("Starting fill array step"); //long startTime = System.currentTimeMillis(); fillArray(s1, s2, sm, gapPenalty,affinePenalty, noPenaltyForBeginningOrEndingGaps, cels); //long endTime = System.currentTimeMillis(); //System.out.println("Finished array fill with " + (endTime - startTime) / 1000f); return readArray(s1, s2, cels); } /* * [0] is the first sequence * [1] is an alignment line with '|' if the first and sequence match * [2] is the second sequence */ public static String[] getPrettyPrintout( PairedAlignment pa ) { String[] s = new String[3]; s[0] = pa.getFirstSequence(); StringBuffer buff = new StringBuffer(); for( int x=0; x < pa.getFirstSequence().length(); x++) { if( pa.getFirstSequence().charAt(x) == pa.getSecondSequence().charAt(x)) { buff.append("|"); } else { buff.append(" "); } } s[1] = buff.toString(); s[2]= pa.getSecondSequence(); return s; } public static PairedAlignment readArray( String s1, String s2, AlignmentCell[][] cels ) throws Exception { int x = s1.length(); int y = s2.length(); AlignmentCell lastCel = cels[x][y]; StringBuffer topString = new StringBuffer(); StringBuffer leftString = new StringBuffer(); float score = lastCel.score; while( lastCel.direction != START ) { if( lastCel.direction == UP ) { topString.append("-"); leftString.append(s2.charAt(y-1)); y--; } else if ( lastCel.direction == LEFT) { topString.append(s1.charAt(x-1)); leftString.append("-"); x--; } else if ( lastCel.direction == DIAG) { topString.append(s1.charAt(x-1)); leftString.append(s2.charAt(y-1)); x--; y--; } else throw new Exception("Logic error"); lastCel = cels[x][y]; } return makeAPairedAlignment(topString.reverse().toString(), leftString.reverse().toString(), score); } private static PairedAlignment makeAPairedAlignment( final String s1, final String s2, final float score) { return new PairedAlignment() { public float getAlignmentScore() { return score; } public String getFirstSequence() { return s1; } public String getSecondSequence() { return s2; } }; } @SuppressWarnings("unused") private static void dumpArray( AlignmentCell[][] cels ) { for (int x=0; x < cels.length; x++) { AlignmentCell[] yArray = cels[x]; for( int y=0; y < yArray.length; y++ ) { System.out.print( cels[x][y].score + "_" + cels[x][y].direction + " " ); } System.out.println(); } } private static void fillArray( String s1, String s2, SubstitutionMatrix sm, int gapPenalty, int affinePenalty, boolean noPenaltyForBeginningOrEndingGaps, AlignmentCell[][] cels ) throws Exception { cels[0][0] = new AlignmentCell(START, 0); if( !noPenaltyForBeginningOrEndingGaps ) { for( int x=1; x <= s1.length(); x++) cels[x][0] = new AlignmentCell(LEFT, 0); for( int x=1; x <= s2.length(); x++) cels[0][x] = new AlignmentCell(UP, 0); } else if( affinePenalty > 0) // linear gap { for( int x=1; x <= s1.length(); x++) cels[x][0] = new AlignmentCell(LEFT, x * gapPenalty ); for( int x=1; x <= s2.length(); x++) cels[0][x] = new AlignmentCell(UP, x * gapPenalty); } else { cels[1][0] = new AlignmentCell(LEFT, gapPenalty); for( int x=2; x <= s1.length(); x++) cels[x][0] = new AlignmentCell(LEFT, gapPenalty + x * affinePenalty); cels[0][1] = new AlignmentCell(UP, gapPenalty); for( int x=2; x <= s2.length(); x++) cels[0][x] = new AlignmentCell(UP, gapPenalty + x * affinePenalty); } for( int y=1; y <= s2.length(); y++) for( int x=1; x <= s1.length(); x++) { float top = Float.NEGATIVE_INFINITY; float left = Float.NEGATIVE_INFINITY; if( affinePenalty >0 ) // linear gap { top = cels[x][y-1].score + gapPenalty; left = cels[x-1][y].score + gapPenalty; } else { if( cels[x][y-1].direction == UP ) top = cels[x][y-1].score + affinePenalty; else top = cels[x][y-1].score + gapPenalty; if( cels[x-1][y].direction == LEFT ) left = cels[x-1][y].score + affinePenalty; else left = cels[x-1][y].score + gapPenalty; } float diag = cels[x-1][y-1].score + sm.getScore(s1.charAt(x-1), s2.charAt(y-1)); float max = Math.max(top, Math.max(left, diag)); AlignmentCell ac = new AlignmentCell(max); if( max == top) ac.direction = UP; else if ( max == left) ac.direction = LEFT; else if ( max == diag) ac.direction = DIAG; else throw new Exception("Logic error"); cels[x][y] = ac; } } public static void main(String[] args) throws Exception { String seq1 = "ACCCCCAAAAG"; String seq2 = "ACCCGTCAAAAG"; SubstitutionMatrix sm = new DNASubstitutionMatrix(); PairedAlignment pa = globalAlignTwoSequences( seq1,seq2 , sm, -1,99, true); System.out.println(pa.getFirstSequence()); System.out.println(pa.getSecondSequence()); System.out.println(pa.getAlignmentScore()); } }
6,973
23.556338
91
java
cobs
cobs-master/cobs/dynamicProgramming/DNASubstitutionMatrix.java
/** * Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu * * This code is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version, * provided that any use properly credits the author. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details at http://www.gnu.org * * */ package dynamicProgramming; public class DNASubstitutionMatrix implements SubstitutionMatrix { public float getScore(char c1, char c2) throws Exception { if( ! isValidDnaChar(c1) || ! isValidDnaChar(c2) ) return 0; if( c1 == c2) return 1; return -3; } private static boolean isValidDnaChar(char c) { if( c== 'A' || c== 'C' || c =='G' || c == 'T' ) return true; return false; } public String getSubstitutionMatrixName() { return "DNA_Matrix"; } }
1,134
24.795455
74
java
cobs
cobs-master/cobs/test/TestSuite1.java
/** * Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu * * This code is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version, * provided that any use properly credits the author. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details at http://www.gnu.org * * */ package test; import junit.framework.Test; import junit.framework.TestSuite; public class TestSuite1 { /* * Manually synched with all test cases. These should all pass * although TestMcBasc will only pass with a certain probability * (since our implementation of McBASC covariance is approximate). */ public static Test suite() { TestSuite suite = new TestSuite("Test for covariance.test"); //$JUnit-BEGIN$ suite.addTest(new TestSuite(AlignmentFilterTest.class)); suite.addTest(new TestSuite(AlignmentLineTest.class)); suite.addTest(new TestSuite(AlignmentTest.class)); suite.addTest(new TestSuite(EntropyConservationTest.class)); suite.addTest(new TestSuite(FactorialsTest.class)); suite.addTest(new TestSuite(TestMcBasc2.class)); suite.addTest(new TestSuite(TestMi.class)); suite.addTest(new TestSuite(OmesCovarianceTest.class)); suite.addTest(new TestSuite(TestCobs.class)); suite.addTest(new TestSuite(TestConservationSum.class)); suite.addTest(new TestSuite(TestConservationSumAverage.class)); suite.addTest(new TestSuite(TestMcBasc.class)); suite.addTest(new TestSuite(TestMcBascAverage.class)); suite.addTest(new TestSuite(OmesCovarianceTest.class)); suite.addTest(new TestSuite(FactorialsTest.class)); suite.addTest(new TestSuite( TestNumberOfElements.class )); //$JUnit-END$ return suite; } }
2,000
36.754717
74
java
cobs
cobs-master/cobs/test/AlignmentFilterTest.java
/** * Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu * * This code is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version, * provided that any use properly credits the author. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details at http://www.gnu.org * * */ package test; import java.util.ArrayList; import java.util.List; import covariance.datacontainers.Alignment; import covariance.datacontainers.AlignmentLine; import junit.framework.TestCase; public class AlignmentFilterTest extends TestCase { public void testColumnRemoval() throws Exception { List alignmentLines = new ArrayList(); alignmentLines.add( new AlignmentLine( "1", "AAC")); alignmentLines.add( new AlignmentLine( "2", "A-C")); alignmentLines.add( new AlignmentLine( "3", "AHY")); alignmentLines.add( new AlignmentLine( "4", "ADF")); Alignment a = new Alignment( "1", alignmentLines ); boolean[] tossColumns = a.getTossColumns(0.7f); assertTrue( ! tossColumns[0] ); assertTrue( tossColumns[1] ); assertTrue( tossColumns[2] ); tossColumns = a.getTossColumns(0.0f); assertTrue( ! tossColumns[0] ); assertTrue( ! tossColumns[1] ); assertTrue( ! tossColumns[2] ); tossColumns = a.getTossColumns(0.4f); assertTrue( ! tossColumns[0] ); assertTrue( tossColumns[1] ); assertTrue( ! tossColumns[2] ); Alignment newA = a.getAlignmentWithRemovedUnconservedColumns(0.7f); List newLines = newA.getAlignmentLines(); for ( int x=0; x<4; x++ ) { AlignmentLine aLine = (AlignmentLine ) newLines.get(x); assertEquals(aLine.getSequence().length(), 1); assertEquals(aLine.getSequence().charAt(0), 'A'); } newA = a.getAlignmentWithRemovedUnconservedColumns(0.45f); newLines = newA.getAlignmentLines(); assertEquals( ((AlignmentLine) newLines.get(0)).getSequence(), "AC"); assertEquals( ((AlignmentLine) newLines.get(1)).getSequence(), "AC"); assertEquals( ((AlignmentLine) newLines.get(2)).getSequence(), "AY"); assertEquals( ((AlignmentLine) newLines.get(3)).getSequence(), "AF"); newA = a.getAlignmentWithRemovedUnconservedColumns(0.1f); newLines = newA.getAlignmentLines(); assertEquals( ((AlignmentLine) newLines.get(0)).getSequence(), "AAC"); assertEquals( ((AlignmentLine) newLines.get(1)).getSequence(), "A-C"); assertEquals( ((AlignmentLine) newLines.get(2)).getSequence(), "AHY"); assertEquals( ((AlignmentLine) newLines.get(3)).getSequence(), "ADF"); } public AlignmentFilterTest(String arg0) { super(arg0); } }
2,901
30.204301
74
java
cobs
cobs-master/cobs/test/AlignmentLineTest.java
/** * Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu * * This code is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version, * provided that any use properly credits the author. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details at http://www.gnu.org * * */ package test; import covariance.datacontainers.AlignmentLine; import junit.framework.TestCase; public class AlignmentLineTest extends TestCase { public AlignmentLineTest(String arg0) { super(arg0); } public void testGetUngappedSequence() throws Exception { String testSequence = TestUtils.getTestSequence(); System.out.println( TestUtils.getTestSequence() ); String prefix = "----El---vI-s------"; String id = "someId"; AlignmentLine aLine = new AlignmentLine( id, testSequence + prefix ); assertEquals(aLine.getIdentifier(), id); assertEquals( aLine.getSequence(), testSequence + prefix ); assertEquals( aLine.getUngappedSequence(), testSequence + "ELVIS" ); } public void testNumValidChars() throws Exception { AlignmentLine aLine = new AlignmentLine("1","AAA---AA"); assertEquals(aLine.getNumValidChars(), 5); aLine = new AlignmentLine("1", "abcdefg----------".toUpperCase()); assertEquals(aLine.getNumValidChars(), 6); aLine = new AlignmentLine("1", "abcdefg----------"); assertEquals(aLine.getNumValidChars(), 0); aLine = new AlignmentLine("1", "FFFFFFFFFF" ); assertEquals(aLine.getNumValidChars(), 10); } }
1,829
29
74
java
cobs
cobs-master/cobs/test/TestUtils.java
/** * Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu * * This code is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version, * provided that any use properly credits the author. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details at http://www.gnu.org * * */ package test; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import covariance.datacontainers.Alignment; import covariance.datacontainers.AlignmentLine; import utils.MapResiduesToIndex; public class TestUtils { /** Static methods only */ private TestUtils() { } /** Don't change this. Alot of the tests depend on the sequence being in this format */ public static String getTestSequence() throws Exception { StringBuffer buff = new StringBuffer(); for ( int x=0; x < MapResiduesToIndex.NUM_VALID_RESIDUES; x++ ) buff.append( "" + MapResiduesToIndex.getChararcter(x) + MapResiduesToIndex.getChararcter(x) ); return buff.toString(); } public static List getTestSequences() throws Exception { List list = new ArrayList(); String prefix = "------Evlis"; String postfix = "E--l--v--s-"; list.add( prefix + TestUtils.getTestSequence() + postfix ); list.add( postfix + TestUtils.getTestSequence() + prefix); list.add( prefix + postfix + TestUtils.getTestSequence()); list.add( TestUtils.getTestSequence() + prefix + prefix); list.add( postfix + TestUtils.getTestSequence() + postfix); list.add( prefix + prefix + TestUtils.getTestSequence() ); return list; } public static Alignment getTestAlignment( String alignmentId ) throws Exception { return getTestAlignment(alignmentId, getTestSequences()); } public static Alignment getTestAlignment(String alignmentId, List testSequences) throws Exception { List alignemntLines = new ArrayList(); int x=0; for ( Iterator i = testSequences.iterator(); i.hasNext(); ) { x++; alignemntLines.add( new AlignmentLine( "" + x, i.next().toString() )); } Alignment a= new Alignment(alignmentId, alignemntLines ); return a; } }
2,454
26.58427
98
java
cobs
cobs-master/cobs/test/TestMcBascVsAbsoluteMcBASC.java
/** * Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu * * This code is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version, * provided that any use properly credits the author. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details at http://www.gnu.org * * */ package test; import java.io.File; import utils.ConfigReader; import covariance.algorithms.AbsoluteValueFileScoreGenerator; import covariance.algorithms.FileScoreGenerator; import covariance.algorithms.McBASCCovariance; import covariance.datacontainers.Alignment; import covariance.parsers.PfamParser; import junit.framework.TestCase; public class TestMcBascVsAbsoluteMcBASC extends TestCase { /* * This assumes that cobsScripts.WriteOneDScores * has been run.. */ public void test() throws Exception { File file = new File(ConfigReader.getCleanroom() + File.separator + "results" + File.separator + "oneD" + File.separator + "3-HAO_McBASC.txt.gz"); System.out.println(file.getAbsolutePath()); Alignment a = new PfamParser().getAnAlignment("3-HAO"); FileScoreGenerator fsg = new FileScoreGenerator("mcbas", file, a); FileScoreGenerator afsg = new AbsoluteValueFileScoreGenerator("absmcbas", file, a); McBASCCovariance mcbasc =new McBASCCovariance(a); for( int i = 0; i < 354; i++) { for( int j=i+1; j < 355; j++ ) { assertEquals(fsg.getScore(a, i, j), mcbasc.getScore(a, i, j),0.00001); assertEquals(Math.abs(fsg.getScore(a, i, j)), afsg.getScore(a, i, j),0.00001); //System.out.println(i + " " + j + " " + fsg.getScore(a, i, j) + " " + mcbasc.getScore(a, i, j) ); } System.out.println(i); } System.out.println("passed"); } }
2,051
32.096774
108
java
cobs
cobs-master/cobs/test/TestAveragePDBDistance.java
/** * Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu * * This code is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version, * provided that any use properly credits the author. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details at http://www.gnu.org * * */ package test; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.StringTokenizer; import covariance.datacontainers.PdbChain; import covariance.datacontainers.PdbFileWrapper; import covariance.datacontainers.PdbResidue; import junit.framework.TestCase; import utils.ConfigReader; import cobsScripts.ResultsFileLine; public class TestAveragePDBDistance extends TestCase { /* * This assumes that writeScores has been run */ public void test() throws Exception { List<ResultsFileLine> innerList= ResultsFileLine.parseResultsFile( new File( ConfigReader.getCleanroom() + File.separator + "results" + File.separator + "2OG-FeII_Oxy_5_COBS_UNCORRECTED.txt.gz")); char chainID = 'A'; String pdbID = "3BVC"; HashMap<Integer, Point> pdbMap = getPdbAsLines(pdbID, chainID); subAgainstPdbParser(pdbMap, pdbID, chainID); for(ResultsFileLine rfl : innerList) { int leftElementStart = TestNumberOfElements.getFirstElement(rfl.getRegion1(), chainID); int leftElementEnd = TestNumberOfElements.getSecondElement(rfl.getRegion1(), chainID); int rightElementStart = TestNumberOfElements.getFirstElement(rfl.getRegion2(), chainID); int rightElementEnd = TestNumberOfElements.getSecondElement(rfl.getRegion2(), chainID); double sum =0; double n =0; System.out.println(rfl.getRegion1() + " " + rfl.getRegion2()); System.out.println(leftElementStart + " " +leftElementEnd); System.out.println(rightElementStart + " " + rightElementEnd); for( int x=leftElementStart; x <= leftElementEnd; x++) for( int y=rightElementStart; y<=rightElementEnd; y++) { sum += getDistance(pdbMap.get(x), pdbMap.get(y)); n++; } System.out.println(sum + " " + n); System.out.println("TEST " + sum/n + " " + rfl.getAverageDistance()); assertEquals(sum/n, rfl.getAverageDistance(), 0.0001); System.out.println("Passed " + rfl.getAverageDistance() ); } } private void subAgainstPdbParser(HashMap<Integer, Point> pointMap, String pdbID, char chainID ) throws Exception { PdbFileWrapper fileWrapper = new PdbFileWrapper(pdbID); PdbChain chain = fileWrapper.getChain(chainID); for( Integer i : pointMap.keySet() ) { PdbResidue residue = chain.getPdbResidueByPdbPosition(i); System.out.println(i + " "+ residue.getPdbChar()); Point point = pointMap.get(i); assertEquals(residue.getCbAtom().getX(), point.x,0.0001); assertEquals(residue.getCbAtom().getY(), point.y,0.0001); assertEquals(residue.getCbAtom().getZ(), point.z,0.0001); } } private static class Point { double x, y,z; } public double getDistance(Point p1, Point p2) { double sum =0; sum+= (p1.x - p2.x) * (p1.x - p2.x); sum+= (p1.y - p2.y) * (p1.y- p2.y); sum+= (p1.z - p2.z) * (p1.z - p2.z); return Math.sqrt(sum); } private static HashMap<Integer, Point> getPdbAsLines(String fourCharId , char chainID) throws Exception { HashMap<Integer, Point> map = new LinkedHashMap<Integer,Point>(); BufferedReader reader = new BufferedReader(new FileReader(new File(ConfigReader.getPdbDir() + File.separator + fourCharId + ".txt"))); for(String s= reader.readLine(); s != null ; s= reader.readLine()) { StringTokenizer sToken = new StringTokenizer(s); if(sToken.nextToken().equals("ATOM")) { sToken.nextToken(); String atomType = sToken.nextToken(); String residueID = sToken.nextToken(); String chainIDString = sToken.nextToken(); assertEquals(chainIDString.length(),1); char pdbChar = chainIDString.charAt(0); int position = Integer.parseInt(sToken.nextToken()); if(pdbChar == chainID) if( ( residueID.equals("GLY") && atomType.equals("CA") ) || atomType.equals("CB") ) { //System.out.println(atomType+ " " + residueID + " " + position); assertFalse(map.containsKey(position)); Point p = new Point(); p.x = Double.parseDouble(sToken.nextToken()); p.y= Double.parseDouble(sToken.nextToken()); p.z = Double.parseDouble(sToken.nextToken()); map.put(position, p); } } } reader.close(); return map; } }
4,927
30.388535
136
java
cobs
cobs-master/cobs/test/TestCobs.java
/** * Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu * * This code is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version, * provided that any use properly credits the author. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details at http://www.gnu.org * * */ package test; import gocAlgorithms.COBS; import java.util.ArrayList; import java.util.List; import java.util.Random; import utils.MapResiduesToIndex; import utils.Pearson; import covariance.algorithms.McBASCCovariance; import covariance.datacontainers.Alignment; import covariance.datacontainers.AlignmentLine; import junit.framework.TestCase; public class TestCobs extends TestCase { private static Random RANDOM = new Random(); //new Random(3432421); // seed is there for consistent results public void testCobs() throws Exception { int seqLength =100; int[][] substitutionMatrix = McBASCCovariance.getMaxhomMetric(); List<AlignmentLine> list = new ArrayList<AlignmentLine>(); String s1 = getRandomProtein(seqLength); String s2 = getRandomProtein(seqLength); for( int x=0; x < 5; x++) list.add( new AlignmentLine(">R1_", getRandomProtein(seqLength))); for(int x=0; x < 10;x++) list.add(new AlignmentLine(">S1" + x, s1)); for(int x=11; x < 20;x++) list.add(new AlignmentLine(">S2" + x, s2)); for( int x=0; x < 5; x++) list.add( new AlignmentLine(">R2_", getRandomProtein(seqLength))); Alignment a = new Alignment("A", list); double testImp = getCobs(a, 5, 21, 48, 64, substitutionMatrix); System.out.println("Test implementation of COBS = " + testImp ); COBS cobs = new COBS(); double testFromCobs = cobs.getScore(a, 5, 21, 48, 64); System.out.println("Value from previous implementation = " + testFromCobs ); assertEquals(testImp, testFromCobs,0.00001); } private double getCobs( Alignment a, int startPosLeft, int endPosLeft, int startPosRight, int endPosRight, int[][] subMatrix) throws Exception { List<Double> vectorI = new ArrayList<Double>(); List<Double> vectorJ = new ArrayList<Double>(); startPosLeft--; startPosRight--; for( int x=0; x < a.getNumSequencesInAlignment() -1; x++) { String leftTopString= a.getAlignmentLines().get(x).getSequence().substring(startPosLeft, endPosLeft); String rightTopString = a.getAlignmentLines().get(x).getSequence().substring(startPosRight, endPosRight); for( int y=x+1; y < a.getNumSequencesInAlignment(); y++) { String leftbottomString= a.getAlignmentLines().get(y).getSequence().substring(startPosLeft, endPosLeft); String rightBottomString = a.getAlignmentLines().get(y).getSequence().substring(startPosRight, endPosRight); vectorI.add( COBS.getSubstitutionMatrixSum(leftTopString, leftbottomString, subMatrix)); vectorJ.add( COBS.getSubstitutionMatrixSum(rightTopString, rightBottomString, subMatrix)); } } return Pearson.getPearsonR(vectorI, vectorJ); } static String getRandomProtein(int length) throws Exception { StringBuffer buff = new StringBuffer(); for( int x=0; x < length;x++) buff.append("" + MapResiduesToIndex.getChar(RANDOM.nextInt(20))); return buff.toString(); } }
3,563
30.821429
112
java
cobs
cobs-master/cobs/test/TestConservationSum.java
/** * Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu * * This code is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version, * provided that any use properly credits the author. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details at http://www.gnu.org * * */ package test; import java.util.ArrayList; import java.util.Collections; import java.util.List; import utils.MapResiduesToIndex; import covariance.algorithms.ConservationSum; import covariance.datacontainers.Alignment; import covariance.datacontainers.AlignmentLine; import junit.framework.TestCase; public class TestConservationSum extends TestCase { private Alignment getThreeColsEachWith20Aas() throws Exception { StringBuffer buff = new StringBuffer(); for( Character c : MapResiduesToIndex.charResidues) buff.append(c); String s = buff.toString(); System.out.println(s); for( int x=0; x< 20; x++) System.out.println( x + " "+ s.charAt(x)); String sReversed = new StringBuffer(s).reverse().toString(); List<Character> list = new ArrayList<Character>(); for( Character c : sReversed.toCharArray()) list.add(c); Collections.shuffle(list); String sShuffled = ""; for( Character c : list) sShuffled += c; List<AlignmentLine> lines= new ArrayList<AlignmentLine>(); for( int x=0; x < 20; x++) { String seq ="" + s.charAt(x) + sReversed.charAt(x) + sShuffled.charAt(x); System.out.println("Adding " + seq); lines.add( new AlignmentLine( ">" + x, seq)); } Alignment a = new Alignment( "a", lines); a.dumpAlignmentToConsole(); int index=0; for( AlignmentLine aLine : a.getAlignmentLines() ) { assertEquals(aLine.getSequence(), lines.get(index).getSequence()); System.out.println("PASSED " + aLine.getSequence() + " "+ lines.get(index).getSequence()); index++; } return a; } public void testAgainstOneKindOfEachResiude() throws Exception { double expectedVal = 0; for( int x=0; x< 20; x++) expectedVal += .05 * Math.log(0.05); expectedVal = -expectedVal; Alignment a = getThreeColsEachWith20Aas(); ConservationSum cSum= new ConservationSum( a ); assertEquals(cSum.getScore(0),expectedVal, 0.00001); assertEquals(cSum.getScore(1),expectedVal, 0.00001); assertEquals(cSum.getScore(2),expectedVal, 0.00001); assertEquals(cSum.getScore(a,0,1), expectedVal,0.00001); assertEquals(cSum.getScore(a,0,2), expectedVal,0.00001); assertEquals(cSum.getScore(a,1,2), expectedVal,0.00001); } public void testPerfectConservation() throws Exception { List<AlignmentLine> list = new ArrayList<AlignmentLine>(); list.add(new AlignmentLine("1", "AGT") ); list.add(new AlignmentLine("2", "AGT") ); list.add(new AlignmentLine("3", "AGT") ); Alignment a = new Alignment( "a", list ); ConservationSum cSum= new ConservationSum( a ); assertEquals(cSum.getScore(0),0, 0.00001); assertEquals(cSum.getScore(1),0, 0.00001); assertEquals(cSum.getScore(2),0, 0.00001); assertEquals(cSum.getScore(a,0,1), 0, 0.00001); assertEquals(cSum.getScore(a,0,2), 0, 0.00001); assertEquals(cSum.getScore(a,1,2), 0, 0.00001); } }
3,540
27.328
93
java
cobs
cobs-master/cobs/test/AlignmentTest.java
/** * Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu * * This code is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version, * provided that any use properly credits the author. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details at http://www.gnu.org * * */ package test; import java.util.ArrayList; import java.util.List; import covariance.datacontainers.Alignment; import covariance.datacontainers.AlignmentLine; import utils.MapResiduesToIndex; import junit.framework.TestCase; public class AlignmentTest extends TestCase { public AlignmentTest(String arg0) { super(arg0); } /* public void testWeights() throws Exception { List list = new ArrayList(); list.add( new AlignmentLine("0", "GYVGS")); list.add( new AlignmentLine("1", "GFDGF")); list.add( new AlignmentLine("2", "GYDGF")); list.add( new AlignmentLine("3", "GYQGG")); Alignment a= new Alignment( "1", list ); double[] weights = a.adjustFrequenciesByWeights(); assertEquals( weights.length, 4); assertEquals( weights[0], 0.267, 0.001); assertEquals( weights[1], 0.267, 0.001); assertEquals( weights[2], 0.200, 0.001); assertEquals( weights[3], 0.267, 0.001); char[] mostFrequentResidues = a.getMostFrequentResidues(a); assertEquals( mostFrequentResidues[0], 'G' ); assertEquals( mostFrequentResidues[1], 'Y' ); assertEquals( mostFrequentResidues[2], 'D'); assertEquals( mostFrequentResidues[3], 'G' ); assertEquals( mostFrequentResidues[4], 'F' ); }*/ public void testGetFilteredAlignment() throws Exception { List list = new ArrayList(); list.add( new AlignmentLine("0", "AAAAAAAA")); list.add( new AlignmentLine("1", "GGGGGGGG")); list.add( new AlignmentLine("2", "HHHHHHHH")); list.add( new AlignmentLine("3", "AAAAAAAA")); list.add( new AlignmentLine("4", "---A----")); list.add( new AlignmentLine("5", "AAAAGGGG")); list.add( new AlignmentLine("6", "FFFFFAAA")); assertEquals( Alignment.getPairwiseIdentity( (AlignmentLine)list.get(0), (AlignmentLine) list.get(4)) , 100.0, 0.01 ); assertEquals( Alignment.getPairwiseIdentity( (AlignmentLine)list.get(0), (AlignmentLine) list.get(1)) , 0.0, 0.01 ); assertEquals( Alignment.getPairwiseIdentity( (AlignmentLine)list.get(0), (AlignmentLine) list.get(5)) , 50.0, 0.01 ); Alignment a = new Alignment("a", list ); assertEquals(a.getNumSequencesInAlignment(), 7); char[] mostFrequentResidues = a.getMostFrequentResidues(a); assertEquals( mostFrequentResidues[0], 'A' ); assertEquals( mostFrequentResidues[1], 'A' ); assertEquals( mostFrequentResidues[6], 'A'); a = a.getFilteredAlignment(50); assertEquals(a.getNumSequencesInAlignment(), 4); assertEquals( ((AlignmentLine)(a.getAlignmentLines().get(0))).getSequence(), "AAAAAAAA" ); assertEquals( ((AlignmentLine)(a.getAlignmentLines().get(3))).getSequence(), "FFFFFAAA" ); a = a.getFilteredAlignment(10); assertEquals(a.getNumSequencesInAlignment(), 3); assertEquals( ((AlignmentLine)(a.getAlignmentLines().get(0))).getSequence(), "AAAAAAAA" ); assertEquals( ((AlignmentLine)(a.getAlignmentLines().get(2))).getSequence(), "HHHHHHHH" ); /* very slooooow!! a= PfamParser.getOneAlignment("ACT"); a = a.getFilteredAlignment(20); for ( int x=0; x< a.getAlignmentLines().size(); x++) { AlignmentLine xLine = (AlignmentLine) a.getAlignmentLines().get(x); for ( int y=x+1; y < a.getAlignmentLines().size(); y++ ) { AlignmentLine yLine = (AlignmentLine) a.getAlignmentLines().get(y); assertTrue( a.getPairwiseIdentity(xLine, yLine) < 20 ); } } a = a.getFilteredAlignment(0.00001f); assertEquals(a.getNumSequencesInAlignment(), 1); */ } public void testGetRatioValid() throws Exception { List list = new ArrayList(); list.add( new AlignmentLine("1","AAA---G")); list.add( new AlignmentLine("2","AAAaaaG")); list.add( new AlignmentLine("3", "Cc----G")); list.add( new AlignmentLine("4", "F------")); Alignment a = new Alignment("", list); assertEquals( a.getRatioValid(0), 1.0, 0.1 ); assertEquals( a.getRatioValid(1), .5, 0.1); assertEquals( a.getRatioValid(5), 0, 0.1); assertEquals( a.getRatioValid(6), 0, 0.75f); } public void testAlignmentConstructor() throws Exception { String someString = "AString"; String someOtherString = "SomeOtherStringOFDifferentSize"; List list = new ArrayList(); list.add( new AlignmentLine("1", someString )); list.add( new AlignmentLine("2", someOtherString )); boolean threw = false; try { // should throw due to unequal alignment lengths Alignment a = new Alignment("1", list); } catch(Exception e) { threw = true; } assertTrue( threw ); String id = "The Name of this Alignment"; list = TestUtils.getTestSequences(); Alignment a = TestUtils.getTestAlignment( id, list ); assertEquals( a.getAligmentID(), id); assertEquals( list.size(), a.getAlignmentLines().size()); int length = list.iterator().next().toString().length(); assertEquals( a.getNumColumnsInAlignment(), length); } public void testGetTotalNumValidResidues() throws Exception { String aString = TestUtils.getTestSequence(); List list = new ArrayList(); for ( int x=1; x <=20; x++ ) list.add( new AlignmentLine( "" + x, aString )); StringBuffer nonValid = new StringBuffer(); for ( int x=0; x< aString.length(); x++ ) nonValid.append('-'); String nonValidString = nonValid.toString(); for ( int x=0; x< 14; x++ ) list.add( new AlignmentLine( "" + (20+x), nonValidString )); Alignment a= new Alignment("1", list); int[] totalValid = a.getTotalNumValidResidues(); assertEquals(totalValid.length, aString.length()); for ( int x=0; x < MapResiduesToIndex.NUM_VALID_RESIDUES; x++ ) { assertEquals(20 , totalValid[x]); } } public void testGetCounts() throws Exception { StringBuffer buff = new StringBuffer(); for ( int x=0; x < MapResiduesToIndex.NUM_VALID_RESIDUES; x++ ) buff.append( "" + MapResiduesToIndex.getChararcter(x) ); String aSeq = buff.toString(); List alignmentList = new ArrayList(); for ( int x=0; x <= 99; x++ ) alignmentList.add( new AlignmentLine( ""+ x, aSeq + "-----" )); Alignment a= new Alignment("1", alignmentList); int count[][] = a.getCounts(); for (int x=0; x< count.length; x++ ) for ( int y=0; y< MapResiduesToIndex.NUM_VALID_RESIDUES; y++ ) { if ( x==y ) assertEquals(count[x][y], 100); else assertEquals(count[x][y], 0); } } public void testGetFrequencies() throws Exception { List alignmentList = new ArrayList(); alignmentList.add( new AlignmentLine( "1", "----AAAAA---G" )); alignmentList.add( new AlignmentLine( "2", "----CCCCC---G" )); alignmentList.add( new AlignmentLine( "1", "----AAAAA---G" )); alignmentList.add( new AlignmentLine( "2", "----CCCCC----" )); alignmentList.add( new AlignmentLine( "1", "----AAAAA---G" )); alignmentList.add( new AlignmentLine( "2", "----CCCCC---G" )); alignmentList.add( new AlignmentLine( "1", "----AAAAA---G" )); alignmentList.add( new AlignmentLine( "2", "----CCCCC----" )); Alignment a= new Alignment("1", alignmentList); float[] frequencies = a.getFrequencies(); for (int x=0; x< frequencies.length; x++ ) { char c = MapResiduesToIndex.getChar(x); if ( c == 'A' || c == 'C' ) assertEquals( frequencies[x], (20f) / 46, 0.0001); else if ( c == 'G' ) assertEquals(frequencies[x], 6f/46, 0.0001 ); else assertEquals( frequencies[x], 0, 0.00001); } a = TestUtils.getTestAlignment("1", TestUtils.getTestSequences()); float sum = 0; frequencies = a.getFrequencies(); for ( int x=0; x < frequencies.length; x++ ) sum += frequencies[x]; assertEquals( 1, sum, 0.0005); } }
8,332
28.44523
106
java
cobs
cobs-master/cobs/test/TestMi.java
/** * Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu * * This code is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version, * provided that any use properly credits the author. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details at http://www.gnu.org * * */ package test; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import covariance.algorithms.MICovariance; import covariance.datacontainers.Alignment; import covariance.datacontainers.AlignmentLine; import utils.MapResiduesToIndex; import junit.framework.TestCase; public class TestMi extends TestCase { public void testDistro1() throws Exception { List alignmentLines = new ArrayList(); for ( int x=0; x < MapResiduesToIndex.NUM_VALID_RESIDUES; x++ ) alignmentLines.add( new AlignmentLine("" + x, "" + MapResiduesToIndex.getChararcter(x) + MapResiduesToIndex.getChararcter(x) )); for ( int x=0; x< 10; x++) alignmentLines.add( new AlignmentLine("1", "-A")); for ( int x=0; x< 10; x++) alignmentLines.add( new AlignmentLine("1", "G-")); Alignment a = new Alignment("1", alignmentLines ); MICovariance mi = new MICovariance(a); double expectedScore = 20 * 0.05 * Math.log(0.05/ (0.05*0.05)); assertEquals( expectedScore, mi.getScore(a,0,1), 0.01); assertEquals( expectedScore, mi.getScore(a,1,0), 0.01); } public void testOneConserved() throws Exception { List alignmentLines = new ArrayList(); for ( int x=0; x < MapResiduesToIndex.NUM_VALID_RESIDUES; x++ ) alignmentLines.add( new AlignmentLine("" + x, "Y" + MapResiduesToIndex.getRandomChar() )); Alignment a = new Alignment("1", alignmentLines ); MICovariance mi= new MICovariance(a); assertEquals( mi.getScore(a,0,1), 0, 0.01); } public void testRandom() throws Exception { List alignmentLines = new ArrayList(); for ( int x=0; x < MapResiduesToIndex.NUM_VALID_RESIDUES; x++ ) alignmentLines.add( new AlignmentLine("" + x, "" + MapResiduesToIndex.getRandomChar() + MapResiduesToIndex.getRandomChar() )); Alignment a = new Alignment("1", alignmentLines ); MICovariance mi = new MICovariance(a); String iString = a.getColumnAsString(0); String jString= a.getColumnAsString(1); if ( iString.length() != jString.length() ) throw new Exception("Logic error"); StringBuffer iStringNew = new StringBuffer(); StringBuffer jStringNew= new StringBuffer(); for ( int x=0; x< iString.length(); x++ ) { char iListChar = iString.charAt(x);; char jListChar = jString.charAt(x); if ( MapResiduesToIndex.isValidResidueChar( iListChar ) && MapResiduesToIndex.isValidResidueChar( jListChar ) ) { iStringNew.append( iListChar ); jStringNew.append( jListChar ); } } iString = iStringNew.toString(); jString = jStringNew.toString(); int[] iFrequencies = mi.getFrequencies( iString ); int[] jFrequencies = mi.getFrequencies( jString); for ( int x=0; x<MapResiduesToIndex.NUM_VALID_RESIDUES; x++ ) { // no gaps so this should work assertEquals( iFrequencies[x],a.getCounts()[0][x]); assertEquals( jFrequencies[x],a.getCounts()[1][x]); } HashMap pairs = mi.getPairs( iString, jString, iFrequencies, jFrequencies ); for ( Iterator i = pairs.keySet().iterator(); i.hasNext(); ) { String pairString = i.next().toString(); MICovariance.PairsClass pClass = (MICovariance.PairsClass) pairs.get( pairString ); assertEquals( pClass.pair, pairString ); int count =0; for (int x =0; x< a.getNumSequencesInAlignment(); x++ ) { String alignmentSequence = ((AlignmentLine) a.getAlignmentLines().get(x)).getSequence(); if ( alignmentSequence.charAt(0) == pairString.charAt(0) && alignmentSequence.charAt(1) == pairString.charAt(1) ) count++; } assertEquals( pClass.num, count ); } } public void testAnAlignment() throws Exception { List alignmentLines = new ArrayList(); alignmentLines.add( new AlignmentLine( "1", "YH")); alignmentLines.add( new AlignmentLine( "1", "YH")); alignmentLines.add( new AlignmentLine( "1", "YH")); alignmentLines.add( new AlignmentLine( "1", "YH")); alignmentLines.add( new AlignmentLine( "1", "SF")); alignmentLines.add( new AlignmentLine( "1", "SM")); alignmentLines.add( new AlignmentLine( "1", "SM")); Alignment a = new Alignment("1", alignmentLines); MICovariance mi = new MICovariance(a); assertEquals(mi.getScore(a, 0,1), 0.682908105, 0.00001); assertEquals(mi.getScore(a, 1,0), 0.682908105, 0.00001); } public void testAnotherAlignment() throws Exception { List alignmentLines = new ArrayList(); alignmentLines.add( new AlignmentLine( "1", "AC")); alignmentLines.add( new AlignmentLine( "1", "AC")); alignmentLines.add( new AlignmentLine( "1", "AC")); alignmentLines.add( new AlignmentLine( "1", "AC")); alignmentLines.add( new AlignmentLine( "1", "-C")); alignmentLines.add( new AlignmentLine( "1", "AC")); alignmentLines.add( new AlignmentLine( "1", "A-")); Alignment a = new Alignment("1", alignmentLines); MICovariance mi = new MICovariance(a); assertEquals(mi.getScore(a, 0,1), 0.0, 0.001); assertEquals(mi.getScore(a, 1,0), 0.0, 0.001); } public void testYetAnotherOne() throws Exception { List alignmentLines = new ArrayList(); alignmentLines.add( new AlignmentLine( "1", "GCA")); alignmentLines.add( new AlignmentLine( "1", "ACA")); alignmentLines.add( new AlignmentLine( "1", "ACG")); alignmentLines.add( new AlignmentLine( "1", "GGG")); alignmentLines.add( new AlignmentLine( "1", "AGT")); alignmentLines.add( new AlignmentLine( "1", "GTT")); alignmentLines.add( new AlignmentLine( "1", "ATT")); alignmentLines.add( new AlignmentLine( "1", "ATT")); alignmentLines.add( new AlignmentLine( "1", "ATT")); alignmentLines.add( new AlignmentLine( "1", "ATT")); Alignment a = new Alignment("1", alignmentLines); MICovariance mi = new MICovariance(a); assertEquals(mi.getScore(a, 1,2),0.620686859, 0.001); assertEquals(mi.getScore(a, 2,1), 0.620686859, 0.001); } public TestMi(String arg0) { super(arg0); } }
6,710
30.507042
92
java
cobs
cobs-master/cobs/test/OmesCovarianceTest.java
/** * Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu * * This code is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version, * provided that any use properly credits the author. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details at http://www.gnu.org * * */ package test; import java.util.ArrayList; import java.util.Collection; import java.util.List; import covariance.algorithms.OmesCovariance; import covariance.datacontainers.Alignment; import covariance.datacontainers.AlignmentLine; import covariance.datacontainers.AlignmentSubScore; import utils.MapResiduesToIndex; import junit.framework.TestCase; public class OmesCovarianceTest extends TestCase { public void testAnotherAlignment() throws Exception { List alignmentLines = new ArrayList(); alignmentLines.add( new AlignmentLine( "1", "YH")); alignmentLines.add( new AlignmentLine( "1", "YH")); alignmentLines.add( new AlignmentLine( "1", "YH")); alignmentLines.add( new AlignmentLine( "1", "YH")); alignmentLines.add( new AlignmentLine( "1", "TA")); alignmentLines.add( new AlignmentLine( "1", "TA")); alignmentLines.add( new AlignmentLine( "1", "TA")); alignmentLines.add( new AlignmentLine( "1", "TA")); alignmentLines.add( new AlignmentLine( "1", "TA")); alignmentLines.add( new AlignmentLine( "1", "TL")); Alignment a = new Alignment("1", alignmentLines); OmesCovariance oc= new OmesCovariance(a); assertEquals( oc.getScore(a,0,1), 1.98, 0.01); Collection subScores= oc.getSubScores(a, 0,1); AlignmentSubScore subScore = AlignmentSubScore.getASubScore(subScores, 'Y', 'H'); assertEquals(subScore.getNumExpected(), 1.6, 0.001 ); assertEquals(subScore.getNumObserved(), 4); assertEquals(subScore.getScore(), 5.76, 0.01); subScore = AlignmentSubScore.getASubScore(subScores, 'T', 'L'); assertEquals( subScore.getNumExpected(), 0.6, 0.01 ); assertEquals( subScore.getNumObserved(), 1); assertEquals( subScore.getScore(), 0.16, 0.01 ); } public void testYetAnotherAlignment() throws Exception { List alignmentLines = new ArrayList(); alignmentLines.add( new AlignmentLine( "1", "YH")); alignmentLines.add( new AlignmentLine( "1", "YH")); alignmentLines.add( new AlignmentLine( "1", "YH")); alignmentLines.add( new AlignmentLine( "1", "YH")); alignmentLines.add( new AlignmentLine( "1", "SF")); alignmentLines.add( new AlignmentLine( "1", "SM")); alignmentLines.add( new AlignmentLine( "1", "SM")); Alignment a = new Alignment("1", alignmentLines); OmesCovariance oc = new OmesCovariance(a); assertEquals(oc.getScore(a, 0,1), 1.306, 0.01); assertEquals(oc.getScore(a, 1,0), 1.306, 0.01); Collection subScores = oc.getSubScores(a, 0, 1); AlignmentSubScore subScore = AlignmentSubScore.getASubScore(subScores, 'Y', 'H'); assertEquals(subScore.getNumExpected(), 2.29, 0.01 ); assertEquals(subScore.getNumObserved(), 4); assertEquals(subScore.getScore(), 2.94, 0.01); subScore = AlignmentSubScore.getASubScore(subScores, 'Y', 'F'); assertEquals(subScore.getNumExpected(), 0.57, 0.01 ); assertEquals(subScore.getNumObserved(), 0); assertEquals(subScore.getScore(), 0.33, 0.01); subScore = AlignmentSubScore.getASubScore(subScores, 'Y', 'M'); assertEquals(subScore.getNumExpected(), 1.14, 0.01 ); assertEquals(subScore.getNumObserved(), 0); assertEquals(subScore.getScore(), 1.31, 0.01); subScore = AlignmentSubScore.getASubScore(subScores, 'S', 'H'); assertEquals(subScore.getNumExpected(), 1.71, 0.01 ); assertEquals(subScore.getNumObserved(), 0); assertEquals(subScore.getScore(), 2.94, 0.01); subScore = AlignmentSubScore.getASubScore(subScores, 'S', 'F'); assertEquals(subScore.getNumExpected(), 0.43, 0.01 ); assertEquals(subScore.getNumObserved(), 1); assertEquals(subScore.getScore(), 0.33, 0.01); } public void testKass() throws Exception { List alignmentLines = new ArrayList(); alignmentLines.add( new AlignmentLine( "1", "AHA")); alignmentLines.add( new AlignmentLine( "1", "AHA")); alignmentLines.add( new AlignmentLine( "1", "AHA")); alignmentLines.add( new AlignmentLine( "1", "AHA")); alignmentLines.add( new AlignmentLine( "1", "CFA")); alignmentLines.add( new AlignmentLine( "2", "CGA")); alignmentLines.add( new AlignmentLine( "2", "CGA")); alignmentLines.add( new AlignmentLine( "3", "--A" )); alignmentLines.add( new AlignmentLine( "1", "--A" )); alignmentLines.add( new AlignmentLine( "1", "--A" )); alignmentLines.add( new AlignmentLine( "5", "-L-" )); alignmentLines.add( new AlignmentLine( "6", "af-")); Alignment a = new Alignment("1", alignmentLines); OmesCovariance oc = new OmesCovariance(a); assertEquals( oc.getScore(a,0,1), 1.31, 0.1); assertEquals( oc.getScore(a,0,2), oc.getScore(a, 2,0), 0.01); alignmentLines = new ArrayList(); for ( int x=0; x< MapResiduesToIndex.NUM_VALID_RESIDUES; x++ ) { alignmentLines.add( new AlignmentLine(""+x, "" + MapResiduesToIndex.getChar(x) + MapResiduesToIndex.getChar(x))); } a = new Alignment("2", alignmentLines ); assertEquals( new OmesCovariance(a).getScore(a,0,1), .95, 0.001); } public OmesCovarianceTest(String arg0) { super(arg0); } }
5,640
35.869281
83
java
cobs
cobs-master/cobs/test/TestPNormalize.java
/** * Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu * * This code is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version, * provided that any use properly credits the author. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details at http://www.gnu.org * * */ package test; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import covariance.algorithms.FileScoreGenerator; import covariance.algorithms.PNormalize; import covariance.datacontainers.Alignment; import covariance.parsers.PfamParser; import utils.ConfigReader; import junit.framework.TestCase; public class TestPNormalize extends TestCase { /* * This assumes WriteScripts has been run */ public void testPNormalize() throws Exception { double sum =0; int n=0; HashMap<Integer, List<Double>> map = new HashMap<Integer,List<Double>>(); PfamParser pfamParser = new PfamParser(); Alignment a = pfamParser.getAnAlignment("2OG-FeII_Oxy_5"); int numCols = a.getNumColumnsInAlignment(); FileScoreGenerator fsg = new FileScoreGenerator("blah", ConfigReader.getCleanroom() + File.separator + "results" + File.separator + "oneD" + File.separator +"2OG-FeII_Oxy_5_McBASC.txt.gz", a); for( int i =0; i <=numCols-1; i++) for( int j=i+1; j<numCols; j++) { double score = fsg.getScore(a, i, j); sum += score ; addOne(map, i, score); addOne(map, j,score); n++; } double globalAverage = sum / n; System.out.println("GLOBAL AVERAGE = " +globalAverage); HashMap<Integer, Double> avMap = getAverageMap(map); PNormalize pnormal = new PNormalize(fsg); for( int i =0; i <=numCols -1; i++) for( int j=i+1; j<numCols; j++) { double expectedNormedScore = fsg.getScore(a, i, j) - avMap.get(i) * avMap.get(j)/ globalAverage; System.out.println(expectedNormedScore + " " + pnormal.getScore(a, i, j)); assertEquals(expectedNormedScore ,pnormal.getScore(a, i, j),0.0001); } } private static HashMap<Integer, Double> getAverageMap( HashMap<Integer, List<Double>> map ) { HashMap<Integer, Double> averageMap = new HashMap<Integer,Double>(); for( Integer key : map.keySet() ) { List<Double> list = map.get(key); double sum =0; for(Double d : list) sum+=d; averageMap.put(key, sum / list.size()); } return averageMap; } private static void addOne( HashMap<Integer, List<Double>> map, Integer key, double score ) { List<Double> list = map.get(key); if( list == null) { list = new ArrayList<Double>(); map.put(key,list); } list.add(score); } }
3,010
25.646018
116
java
cobs
cobs-master/cobs/test/EntropyConservationTest.java
/** * Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu * * This code is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version, * provided that any use properly credits the author. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details at http://www.gnu.org * * */ package test; import java.util.ArrayList; import java.util.List; import covariance.algorithms.ConservationSum; import covariance.datacontainers.Alignment; import covariance.datacontainers.AlignmentLine; import utils.MapResiduesToIndex; import junit.framework.TestCase; public class EntropyConservationTest extends TestCase { public void testEntropySomeMore() throws Exception { List list = new ArrayList(); list.add( new AlignmentLine( "1", "AH" )); list.add( new AlignmentLine( "1", "AH" )); list.add( new AlignmentLine( "1", "CH" )); list.add( new AlignmentLine( "1", "CH" )); list.add( new AlignmentLine( "1", "GH" )); list.add( new AlignmentLine( "1", "GH" )); list.add( new AlignmentLine( "1", "YH" )); list.add( new AlignmentLine( "1", "YH" )); list.add( new AlignmentLine( "1", "YH" )); Alignment a = new Alignment("1", list); double score = (2f / 9f ) * Math.log(2f/9f); score = 3* score; score += ( 3f/ 9f ) * Math.log(3f/9f); score = -score; ConservationSum cSum = new ConservationSum(a); assertEquals(cSum.getScore(0), score, 0.01); assertEquals(cSum.getScore(1), 0, 0.001); assertEquals(cSum.getScore(a, 0,1), score /2, 0.01); assertEquals(cSum.getScore(a, 1,0), score /2, 0.01); } public void testEntropy() throws Exception { List alignmentLines = new ArrayList(); for ( int x=0; x<=10; x++ ) { alignmentLines.add(new AlignmentLine("" + x, TestUtils.getTestSequence())); } Alignment a = new Alignment("1", alignmentLines ); int length = TestUtils.getTestSequence().length(); ConservationSum cSum = new ConservationSum(a); for ( int x=0; x< length; x++ ) for ( int y=0; y < length; y++ ) { assertEquals( cSum.getScore(a, x,y), 0.0, .0001); assertEquals( cSum.getScore(x), 0.0, .0001); assertEquals( cSum.getScore(y), 0.0, .0001); } alignmentLines = new ArrayList(); for ( int x=0; x< MapResiduesToIndex.NUM_VALID_RESIDUES; x++ ) { StringBuffer buff = new StringBuffer(); for ( int y=0; y< MapResiduesToIndex.NUM_VALID_RESIDUES; y++ ) buff.append( MapResiduesToIndex.getChar(x) ); alignmentLines.add( new AlignmentLine("" + x, buff.toString())); } alignmentLines.add( new AlignmentLine("1", "aaaaaaaaaaaaaaaaaaaa")); alignmentLines.add( new AlignmentLine("1", "--------------------")); a = new Alignment("2", alignmentLines); cSum = new ConservationSum(a); double expectedScore = -20 * .05 * Math.log(.05); for ( int x=0; x < MapResiduesToIndex.NUM_VALID_RESIDUES; x++ ) for ( int y=0; y < MapResiduesToIndex.NUM_VALID_RESIDUES; y++ ) { if ( x != y ) assertEquals( cSum.getScore(a, x,y), expectedScore, 0.01 ); } } public EntropyConservationTest(String arg0) { super(arg0); } }
3,440
29.451327
78
java
cobs
cobs-master/cobs/test/TestAbsoluteScoreVsAverageDistance.java
/** * Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu * * This code is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version, * provided that any use properly credits the author. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details at http://www.gnu.org * * */ package test; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.Comparator; import java.util.HashMap; import java.util.List; import cobsScripts.ResultsFileLine; import utils.ConfigReader; import junit.framework.TestCase; public class TestAbsoluteScoreVsAverageDistance extends TestCase { /* * This assumes that AbsoluteScoreVsAverageDistance has been run and the results * in COBS_CLEANROOM/bigSummaries reflects the files in COBS_CLEANROOM results */ public void test() throws Exception { BufferedReader reader = new BufferedReader(new FileReader(new File(ConfigReader.getCleanroom() + File.separator + "bigSummaries" + File.separator + "bigAverageMI.txt" ))); reader.readLine(); HashMap<String, List<ResultsFileLine>> cache = new HashMap<String, List<ResultsFileLine>>(); for(String s = reader.readLine(); s != null; s = reader.readLine()) { String[] splits = s.split("\t"); List<ResultsFileLine> list = getResults(splits[0], cache); assertEquals(list.size(), (int) Double.parseDouble(splits[7])); ResultsFileLine rfl = getExactlyOne(list, splits[2], splits[3]); assertEquals(rfl.getAverageDistance(), Double.parseDouble(splits[5]), 0.0001); int index = getExactlyOneIndex(list, splits[2], splits[3]); double percentile =100; if( index < list.size() -1 ) percentile = 100.0 * ((double)index) / list.size(); System.out.println("Expected percentile " + percentile); assertEquals(percentile, Double.parseDouble(splits[4]),0.0001); System.out.println(splits[1] + " " + splits[2]); } reader.close(); } private static class SortByAverageDistance implements Comparator<ResultsFileLine> { @Override public int compare(ResultsFileLine arg0, ResultsFileLine arg1) { return Double.compare(arg0.getAverageDistance(), arg1.getAverageDistance()); } } private static ResultsFileLine getExactlyOne(List<ResultsFileLine> list, String region1,String region2) { ResultsFileLine returnVal =null; for(ResultsFileLine rfl : list) { if(rfl.getRegion1().equals(region1) && rfl.getRegion2().equals(region2)) { assertTrue(returnVal == null); returnVal = rfl; } } assertTrue(returnVal != null); return returnVal; } private static int getExactlyOneIndex(List<ResultsFileLine> list, String region1,String region2) { Integer returnVal =null; for(int x=0; x < list.size(); x++) { ResultsFileLine rfl = list.get(x); if(rfl.getRegion1().equals(region1) && rfl.getRegion2().equals(region2)) { assertTrue(returnVal == null); returnVal = x; } } assertTrue(returnVal != null); return returnVal; } private static List<ResultsFileLine> getResults( String filename, HashMap<String, List<ResultsFileLine>> cache ) throws Exception { List<ResultsFileLine> list= cache.get(filename); if(list == null) { list = ResultsFileLine.parseResultsFile(new File(ConfigReader.getCleanroom() + File.separator + "results" + File.separator + filename)); java.util.Collections.sort(list, new SortByAverageDistance()); double init =-1; for( ResultsFileLine rfl : list ) { assertTrue(rfl.getAverageDistance() >= init); init = rfl.getAverageDistance(); } cache.put(filename, list); } return list; } }
4,018
27.302817
131
java
cobs
cobs-master/cobs/test/TestMcBasc2.java
/** * Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu * * This code is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version, * provided that any use properly credits the author. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details at http://www.gnu.org * * */ package test; import java.util.ArrayList; import java.util.List; import covariance.algorithms.McBASCCovariance; import covariance.datacontainers.Alignment; import covariance.datacontainers.AlignmentLine; import utils.MapResiduesToIndex; import utils.TTest; import junit.framework.TestCase; public class TestMcBasc2 extends TestCase { public TestMcBasc2(String arg0) { super(arg0); } public void test1() throws Exception { List list = new ArrayList(); list.add(new AlignmentLine("1", "AA") ); list.add(new AlignmentLine("2", "GG") ); list.add(new AlignmentLine("3", "HH") ); int[][] metric = McBASCCovariance.getMaxhomMetric(); List sumList = new ArrayList(); sumList.add( new Double (metric[ MapResiduesToIndex.getIndex('A')][MapResiduesToIndex.getIndex('A')])); sumList.add( new Double (metric[ MapResiduesToIndex.getIndex('A')][MapResiduesToIndex.getIndex('G')])); sumList.add( new Double (metric[ MapResiduesToIndex.getIndex('A')][MapResiduesToIndex.getIndex('H')])); sumList.add( new Double (metric[ MapResiduesToIndex.getIndex('G')][MapResiduesToIndex.getIndex('A')])); sumList.add( new Double (metric[ MapResiduesToIndex.getIndex('G')][MapResiduesToIndex.getIndex('G')])); sumList.add( new Double (metric[ MapResiduesToIndex.getIndex('G')][MapResiduesToIndex.getIndex('H')])); sumList.add( new Double (metric[ MapResiduesToIndex.getIndex('H')][MapResiduesToIndex.getIndex('A')])); sumList.add( new Double (metric[ MapResiduesToIndex.getIndex('H')][MapResiduesToIndex.getIndex('G')])); sumList.add( new Double (metric[ MapResiduesToIndex.getIndex('H')][MapResiduesToIndex.getIndex('H')])); Alignment a = new Alignment( "a", list ); McBASCCovariance mcBasc = new McBASCCovariance( a ); System.out.println( new Double (metric[ MapResiduesToIndex.getIndex('A')][MapResiduesToIndex.getIndex('G')])); System.out.println( mcBasc.getAverages()[0] ); System.out.println( mcBasc.getSds()[0] ); assertEquals( mcBasc.getAverages()[0], TTest.getAverage(sumList), 0.001); assertEquals( mcBasc.getAverages()[1], TTest.getAverage(sumList), 0.001); assertEquals( mcBasc.getSds()[0], TTest.getStDev(sumList), 0.001); assertEquals( mcBasc.getSds()[1], TTest.getStDev(sumList), 0.001); } }
2,908
38.310811
112
java